diff --git a/pool/shard002/C++/0024344_GameLevel.cpp b/pool/shard002/C++/0024344_GameLevel.cpp new file mode 100644 index 0000000000000000000000000000000000000000..1208b6c921da0a32ee8af527a01354843d60a38b --- /dev/null +++ b/pool/shard002/C++/0024344_GameLevel.cpp @@ -0,0 +1,150 @@ +#include "GameLevel.h" + +#include +#include + +GameLevel::~GameLevel(){ + delete space; + delete heightmap; +// delete water; + delete skybox; +} +void GameLevel::parseFile(const char *filename){ + std::ifstream is; + is.open(filename); + if(!is.is_open()) { + throw YGEExceptionFileNotFound(filename); + } + + while(!is.eof()){ + std::string line, type; + getline(is, line); + std::istringstream istr(line); + + istr >> type; + + if(type == "sky:") { + istr >> skymapName; + } + if(type == "sunposition:") { + istr >> sunposition.x; + istr >> sunposition.y; + istr >> sunposition.z; + } + if(type == "suncolor:") { + istr >> suncolor.x; + istr >> suncolor.y; + istr >> suncolor.z; + } + if(type == "timeToComplete:") { + istr >> timeToComplete; + + } + if(type == "mapFileName:") { + istr >> mapFileName; + + } + if(type == "textureFileName:") { + istr >> textureFileName; + + } + if(type == "mapScale:") { + istr >> mapScale.x; + istr >> mapScale.y; + istr >> mapScale.z; + } + + if(type == "startPos:") { + istr >> startPos.x; + istr >> startPos.y; + istr >> startPos.z; + } + + if(type == "ball:") { + YGEMath::Vector3 position; + + std::string color; + istr >> color; + + istr >> position.x; + istr >> position.y; + istr >> position.z; + + ballPositions.push_back(std::pair(position, color)); + } + + } + + +} + +void GameLevel::createFromFile(const char* filename){ + + mapScale.x = 100; + mapScale.y = 100; + mapScale.z = 100; + + parseFile(YGECore::YGEResourceManager::getInstance()->absoluteFilename( filename ).c_str() ); + + // create a space + space = new YGETimeSpace::YGESpace(); + space->initTime(); + space->setSoundEnabled(true); + + // create the heightmap + heightmap = new YGEGraphics::YGEHeightmap(); + heightmap->create(mapFileName.c_str(), textureFileName.c_str(), mapScale.x, mapScale.z, mapScale.y); + space->getRootEntity()->addAsset(heightmap); + + heightmap->makeSolid(); + + //water = new YGEGraphics::YGEWater(heightmap, 10); + //space->getRootEntity()->addAsset(water); + + skybox = new YGEGraphics::YGESkybox(); + skybox->loadTextures(skymapName.c_str()); + space->setSkybox(skybox); + space->getSunlight()->setColor((float)suncolor.x, (float)suncolor.y, (float)suncolor.z); + space->getSunlight()->setDirection(sunposition); + + for(std::list >::iterator iter = ballPositions.begin(); iter != ballPositions.end(); iter++){ + + GameBall* ball; + + if(iter->second == "blue") { + ball = new GameBall(7, 0, 0, 1); + } else if(iter->second == "red") { + ball = new GameBall(5, 1, 0, 0); + } else if(iter->second == "pink") { + ball = new GameBall(2, 1, 0, 1); + } else { + ball = new GameBall(10, 1, 1, 1); + } + + + space->getRootEntity()->addChild(ball); + ball->setPosition(iter->first); + + + } + + +} + +YGEMath::Vector3 GameLevel::getPlayerStartPosition(){ + return startPos; +} + +void GameLevel::addEntity(YGETimeSpace::YGEEntity* entity){ + space->getRootEntity()->addChild(entity); + +} + +int GameLevel::getNumberOfBalls(){ + return ballPositions.size(); +} + +int GameLevel::getTimeToComplete(){ + + return timeToComplete; +} diff --git a/pool/shard002/C++/0024353_ministellar.cpp b/pool/shard002/C++/0024353_ministellar.cpp new file mode 100644 index 0000000000000000000000000000000000000000..56f57a6c633a2bdcd5c3c06526055701e5bad355 --- /dev/null +++ b/pool/shard002/C++/0024353_ministellar.cpp @@ -0,0 +1,137 @@ +#include +#include +#include +#include + +using namespace seqan; + +// set parameters + +unsigned const minimalLength = 12; +float const errorRate = 0.05; +//unsigned const qGramLength = 8; +CharString const filename = "ministellar.out"; + +typedef int TScoreValue; +TScoreValue const matchScore = 1; +TScoreValue const mismatchScore = -2; +TScoreValue const gapScore = -2; +TScoreValue const minScore = 9; +TScoreValue const xDrop = 3; + + +int main(int argc, char const ** argv) +{ + if (argc != 3) + { + std::cerr << "ERROR: Invalid argument count!" << std::endl; + std::cerr << "USAGE: ministallar IN1.fa IN2.fa" << std::endl; + return 1; + } + + Score scoring = Score(matchScore, mismatchScore, gapScore); + // DONE: Define a scoring scheme 'score' with linear gap costs using the above defined + // score values for scoring matches, mismatches, and gaps. + // HINT: You can find a section on Schoring Schemes in the Alignments tutorial. + + // read sequences from fasta files + typedef Dna5String TSequence; + StringSet ids1, ids2; + StringSet seqs1, seqs2; + + std::ifstream streamIn1(argv[1], std::ios::in | std::ios::binary); + RecordReader > reader1(streamIn1); + if (read2(ids1, seqs1, reader1, Fasta()) != 0) + { + std::cerr << "Could not read file " << argv[1] << std::endl; + return 1; + } + // DONE: Do the same for the second file. + + std::ifstream streamIn2(argv[2], std::ios::in | std::ios::binary); + RecordReader > reader2(streamIn2); + if (read2(ids2, seqs2, reader2, Fasta()) != 0) + { + std::cerr << "Could not read file " << argv[2] << std::endl; + return 1; + } + + // prepare output file + std::ofstream outFile; + outFile.open(toCString(filename)); + + // define finder and pattern + // TODO: Define types for finder and pattern using SeqAn's find interface from the index + // module. Both should be specialized for the approproiate swift filter algorithm. + // The pattern will need the definition of a q-gram-index. Use q-grams of length 8 + // for now, and open addressing. + // HINT: The tutorial on Pattern Matching describes the find interface. At the end of that + // tutorial page, you will find a link to a Swift HowTo page. + + typedef Index > > TQIndex; + typedef Finder > TFinder; + typedef Pattern > TPattern; + + // TODO: Define variables of your pattern and finder types, and initialize them with the + // first sequences in the sequence sets seqs1 and seqs2. + TQIndex index1 = TQIndex(seqs1[0]); + TPattern pattern = TPattern(index1); + TFinder finder = TFinder(seqs2[0]); + + // TODO: Repeat the following steps for all hits of the finder. + //typedef Iterator TFinderIt; + //TFinderIt it = TFinderIt(finder); + + + // call the function find to obtain a swift hit + // TODO: uncomment the following line + + while (find(finder, pattern, errorRate, int(minimalLength))) { + + // extract infixes from hit + // TODO: uncomment the following three lines + + typedef Infix::Type TInfix; + TInfix infix1 = infix(finder, seqs1[0]); + TInfix infix2 = infix(pattern, seqs2[0]); + + // find best local alignment of infixes, and check for minimal score + // TODO: Define an align object and initialize it with the infixes. Find the best local + // alignment of the infixes. Use the above defined scoring scheme. Make sure that + // it reaches the minimal score minScore. + + //std::cout << infix1 << std::endl; + //std::cout << infix2 << std::endl; + typedef Align TAlign; + typedef Row TRow; + TAlign aln = TAlign(); + resize(rows(aln), 2); + assignSource(row(aln, 0), infix1); + assignSource(row(aln, 1), infix2); + int scr = localAlignment(aln, scoring); + if (scr < minScore) { + continue; + } + // create a seed for the local alignment, and conduct gapped X-drop extension + // TODO: Define a seed on the original sequences but for the subsequences of the local + // alignment. Extend this seed in both directions using gapped X-drop extension. + // Check that the extended seed has a length of at least minimalLength. + // HINT: Have a look at the Seed-and-Extend tutorial. + typedef Seed TSeed; + TSeed seed = TSeed(beginPosition(infix1) + clippedBeginPosition(row(aln, 0)), + beginPosition(infix2) + clippedBeginPosition(row(aln, 1)), + beginPosition(infix1) + clippedEndPosition(row(aln, 0)), + beginPosition(infix2) + clippedEndPosition(row(aln, 1))); + + extendSeed(seed, xDrop, scoring, seqs1[0], seqs2[0], 2, GappedXDrop()); + } + // find best global alignment of extended seed + // TODO: Compute the best global alignment of extended seed and its score. + // HINT: Create an align object on infixes of the sequences. + + // TODO: Output the alignment as a match to the output file. + + outFile.close(); + + return 0; +} diff --git a/pool/shard002/C++/0024356_sys_net_native_System_Net_NetworkInformation_IPGlobalProperties.cpp b/pool/shard002/C++/0024356_sys_net_native_System_Net_NetworkInformation_IPGlobalProperties.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f48b1a862870d5d18c73f529d0ecefc2d8b10e9d --- /dev/null +++ b/pool/shard002/C++/0024356_sys_net_native_System_Net_NetworkInformation_IPGlobalProperties.cpp @@ -0,0 +1,90 @@ +// +// Copyright (c) .NET Foundation and Contributors +// See LICENSE file in the project root for full license information. +// + +#include "sys_net_native.h" +#include + +HRESULT Library_sys_net_native_System_Net_NetworkInformation_IPGlobalProperties:: + GetIPAddress___STATIC__SystemNetIPAddress(CLR_RT_StackFrame &stack) +{ + NANOCLR_HEADER(); + + HAL_Configuration_NetworkInterface config; + + CLR_RT_TypeDef_Index ipAddressTypeDef; + CLR_RT_HeapBlock *ipAddressHbObj; + CLR_RT_HeapBlock ipAddress; + CLR_INT64 *pRes; + bool ipAddressValid = false; + + CLR_RT_HeapBlock &top = stack.PushValue(); + + // find type, don't bother checking the result as it exists for sure + g_CLR_RT_TypeSystem.FindTypeDef("IPAddress", "System.Net", ipAddressTypeDef); + + // create an instance of + NANOCLR_CHECK_HRESULT(g_CLR_RT_ExecutionEngine.NewObjectFromIndex(ipAddress, ipAddressTypeDef)); + + // dereference the object in order to reach its fields + ipAddressHbObj = ipAddress.Dereference(); + + { + // IPAddress _address field + // CLR_INT64 fields need to be accessed by pointer + CLR_RT_HeapBlock &addressFieldRef = ipAddressHbObj[Library_sys_net_native_System_Net_IPAddress::FIELD__Address]; + pRes = (CLR_INT64 *)&addressFieldRef.NumericByRef().s8; + + // IPAddress _family field + // IP v4: AddressFamily.InterNetwork + ipAddressHbObj[Library_sys_net_native_System_Net_IPAddress::FIELD___family].NumericByRef().s4 = SOCK_AF_INET; + } + + // loop through all the network interface and check if any is up + for (int interfaceIndex = 0; interfaceIndex < g_TargetConfiguration.NetworkInterfaceConfigs->Count; + interfaceIndex++) + { + NANOCLR_CLEAR(config); + + // load network interface configuration from storage + if (!ConfigurationManager_GetConfigurationBlock( + (void *)&config, + DeviceConfigurationOption_Network, + interfaceIndex)) + { + NANOCLR_SET_AND_LEAVE(CLR_E_FAIL); + } + _ASSERTE(config.StartupAddressMode > 0); + + // load adapter configuration on top of the stored config + NANOCLR_CHECK_HRESULT(SOCK_CONFIGURATION_LoadConfiguration(&config, interfaceIndex)); + + // has IP v4? + if (config.IPv4Address > 0) + { + *pRes = config.IPv4Address; + + // we have an IP... + ipAddressValid = true; + + // .. no need to check any other + break; + } + } + + if (ipAddressValid) + { + // set address field with IPAddress heap block object + top.SetObjectReference(ipAddressHbObj); + } + else + { + // default to IP Any Address + top.SetObjectReference(g_CLR_RT_TypeSystem.m_assemblies[ipAddressTypeDef.Assembly() - 1] + ->GetStaticField(Library_sys_net_native_System_Net_IPAddress::FIELD_STATIC__Any) + ->Dereference()); + } + + NANOCLR_NOCLEANUP(); +} diff --git a/pool/shard002/C++/0024362_cpp.cc b/pool/shard002/C++/0024362_cpp.cc new file mode 100644 index 0000000000000000000000000000000000000000..40d5bc0bbe6f085a8312a55652a8024925bee206 --- /dev/null +++ b/pool/shard002/C++/0024362_cpp.cc @@ -0,0 +1,86 @@ +#include +#include + +using namespace std; + + + + +class Solution { + struct ninfo{ + int maxpos; + int maxneg; + }; +public: + int maxProduct(int A[], int n) { + if (n == 1) + return A[0]; + int maxpos(0), maxneg(0), max(INT_MIN), tp(0), tn(0); + for (auto i = n - 1; i >= 0; --i) + { + tp = A[i] * maxpos; + tn = A[i] * maxneg; + if (tn>tp) + swap(tn, tp); + if (tp>max) + max = tp; + if (A[i]>max) + max = A[i]; + maxpos = tp>A[i] ? tp : A[i]; + maxneg = tn= 0; --i) + { + if (A[i] > 0) + { + int t = A[i] * start.maxpos; + start.maxpos = A[i] > t ? A[i] : t; + start.maxneg *= A[i]; + + } + else if(A[i] < 0) + { + int t = A[i] * start.maxneg; + if (t>start.maxpos) + start.maxpos = t; + start.maxneg = start.maxpos * A[i]; + } + else + { + start.maxpos = 0; + start.maxneg = 0; + } + + if (start.maxpos > max) + max = start.maxpos; + } + return max; + } +private: + unordered_map cache; + +}; + + +int main() +{ + Solution s; + //vector test = { 2, 3, -2, 4 }; + int test[4] = { 2, 3, -2, 4 }; + cout << s.maxProduct(test, 4)<Create(parent, rc, style); + SetWindow(w); +} + +void +HorizonWidget::Unprepare() +{ + DeleteWindow(); +} + +void +HorizonWidget::Show(const PixelRect &rc) +{ + Update(CommonInterface::Basic()); + CommonInterface::GetLiveBlackboard().AddListener(*this); + + WindowWidget::Show(rc); +} + +void +HorizonWidget::Hide() +{ + WindowWidget::Hide(); + + CommonInterface::GetLiveBlackboard().RemoveListener(*this); +} + +void +HorizonWidget::OnGPSUpdate(const MoreData &basic) +{ + Update(basic); +} diff --git a/pool/shard002/C++/0024366_process_shield_symbolizer.cpp b/pool/shard002/C++/0024366_process_shield_symbolizer.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8b4dfe5a755ecc0f7d47e585d01445b1d679cd4b --- /dev/null +++ b/pool/shard002/C++/0024366_process_shield_symbolizer.cpp @@ -0,0 +1,98 @@ +/***************************************************************************** + * + * This file is part of Mapnik (c++ mapping toolkit) + * + * Copyright (C) 2015 Artem Pavlenko + * + * 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 + * + *****************************************************************************/ + +#if defined(GRID_RENDERER) + +// mapnik +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#pragma GCC diagnostic push +#include +#include "agg_trans_affine.h" +#include "agg_gamma_functions.h" +#pragma GCC diagnostic pop + +namespace mapnik { + +template +void grid_renderer::process(shield_symbolizer const& sym, + mapnik::feature_impl & feature, + proj_transform const& prj_trans) +{ + METRIC_UNUSED auto t = this->metrics_.measure_time("Grid_PShieldS"); + agg::trans_affine tr; + auto transform = get_optional(sym, keys::geometry_transform); + if (transform) evaluate_transform(tr, feature, common_.vars_, *transform, common_.scale_factor_); + + text_symbolizer_helper helper( + sym, feature, common_.vars_, prj_trans, + common_.width_, common_.height_, + common_.scale_factor_, + common_.t_, common_.font_manager_, *common_.detector_, + common_.query_extent_, tr); + bool placement_found = false; + + composite_mode_e comp_op = get(sym, keys::comp_op, feature, common_.vars_, src_over); + double opacity = get(sym, keys::opacity, feature, common_.vars_, 1.0); + + grid_text_renderer ren(pixmap_, + comp_op, + common_.scale_factor_); + + placements_list const& placements = helper.get(); + value_integer feature_id = feature.id(); + + for (auto const& glyphs : placements) + { + marker_info_ptr mark = glyphs->get_marker(); + if (mark) + { + render_marker(feature, + glyphs->marker_pos(), + *mark->marker_, + mark->transform_, + opacity, comp_op); + } + ren.render(*glyphs, feature_id); + placement_found = true; + } + if (placement_found) + { + pixmap_.add_feature(feature); + } +} + +template void grid_renderer::process(shield_symbolizer const&, + mapnik::feature_impl &, + proj_transform const&); + +} + +#endif diff --git a/pool/shard002/C++/0024368_colorsource.cpp b/pool/shard002/C++/0024368_colorsource.cpp new file mode 100644 index 0000000000000000000000000000000000000000..9d311e3e5b5b62b2ebb0d8bc8b410fe675e908b6 --- /dev/null +++ b/pool/shard002/C++/0024368_colorsource.cpp @@ -0,0 +1,160 @@ + +// +// This source file is part of appleseed. +// Visit https://appleseedhq.net/ for additional information and resources. +// +// This software is released under the MIT license. +// +// Copyright (c) 2010-2013 Francois Beaune, Jupiter Jazz Limited +// Copyright (c) 2014-2018 Francois Beaune, The appleseedhq Organization +// +// 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. +// + +// Interface header. +#include "colorsource.h" + +// appleseed.renderer headers. +#include "renderer/modeling/color/colorentity.h" +#include "renderer/modeling/color/colorspace.h" +#include "renderer/modeling/color/wavelengths.h" +#include "renderer/modeling/entity/entity.h" + +// appleseed.foundation headers. +#include "foundation/image/colorspace.h" +#include "foundation/image/regularspectrum.h" +#include "foundation/utility/api/specializedapiarrays.h" + +// Standard headers. +#include + +using namespace foundation; + +namespace renderer +{ + +// +// ColorSource class implementation. +// + +ColorSource::ColorSource(const ColorEntity& color_entity) + : Source(true) + , m_color_entity(color_entity) +{ + // Retrieve the color values. + if (color_entity.get_color_space() == ColorSpaceSpectral) + initialize_from_spectrum(color_entity); + else initialize_from_color3(color_entity); + + // Apply the multiplier to the color values. + const float multiplier = color_entity.get_multiplier(); + m_scalar *= multiplier; + m_linear_rgb *= multiplier; + m_spectrum *= multiplier; + + // Store the alpha values. + // In the case of multiple alpha values, we keep the first one. + const ColorValueArray& alpha = color_entity.get_alpha(); + m_alpha[0] = alpha.size() >= 1 ? alpha[0] : 0.0f; +} + +std::uint64_t ColorSource::compute_signature() const +{ + return m_color_entity.compute_signature(); +} + +ColorSource::Hints ColorSource::get_hints() const +{ + Hints hints; + hints.m_width = 1; + hints.m_height = 1; + return hints; +} + +void ColorSource::initialize_from_spectrum(const ColorEntity& color_entity) +{ + const ColorValueArray& values = color_entity.get_values(); + + if (values.empty()) + { + m_scalar = 0.0f; + m_linear_rgb.set(0.0f); + m_spectrum.set(0.0f); + return; + } + + m_scalar = values[0]; + + RegularSpectrum31f s; + spectral_values_to_spectrum( + color_entity.get_wavelength_range()[0], + color_entity.get_wavelength_range()[1], + values.size(), + &values[0], + s); + + m_linear_rgb = + ciexyz_to_linear_rgb( + spectrum_to_ciexyz(g_std_lighting_conditions, s)); + + m_spectrum.set(s, g_std_lighting_conditions, Spectrum::Reflectance); +} + +void ColorSource::initialize_from_color3(const ColorEntity& color_entity) +{ + Color3f color; + + const ColorValueArray& values = color_entity.get_values(); + if (values.size() == 1) + color.set(values[0]); + else if (values.size() == 3) + color = Color3f(values[0], values[1], values[2]); + else + { + m_scalar = 0.0f; + m_linear_rgb.set(0.0f); + m_spectrum.set(0.0f); + return; + } + + m_scalar = color[0]; + + switch (color_entity.get_color_space()) + { + case ColorSpaceLinearRGB: + m_linear_rgb = color; + break; + + case ColorSpaceSRGB: + m_linear_rgb = fast_srgb_to_linear_rgb(color); + break; + + case ColorSpaceCIEXYZ: + m_linear_rgb = ciexyz_to_linear_rgb(color); + break; + + default: + assert(!"Invalid color space."); + break; + } + + m_spectrum.set(m_linear_rgb, g_std_lighting_conditions, Spectrum::Reflectance); +} + +} // namespace renderer diff --git a/pool/shard002/C++/0024375_qgsfeaturelistviewdelegate.cpp b/pool/shard002/C++/0024375_qgsfeaturelistviewdelegate.cpp new file mode 100644 index 0000000000000000000000000000000000000000..222db7864de02fad45a17c5cbca17106adcedbb9 --- /dev/null +++ b/pool/shard002/C++/0024375_qgsfeaturelistviewdelegate.cpp @@ -0,0 +1,149 @@ +/*************************************************************************** + qgsfeaturelistviewdelegate.cpp + --------------------- + begin : February 2013 + copyright : (C) 2013 by Matthias Kuhn + email : matthias at opengis dot ch + *************************************************************************** + * * + * This program is free software; you can redistribute it and/or modify * + * it under the terms of the GNU General Public License as published by * + * the Free Software Foundation; either version 2 of the License, or * + * (at your option) any later version. * + * * + ***************************************************************************/ +#include "qgsfeaturelistviewdelegate.h" +#include "qgsvectorlayer.h" +#include "qgsattributetablemodel.h" +#include "qgsfeaturelistmodel.h" +#include "qgsapplication.h" +#include "qgsvectorlayereditbuffer.h" +#include "qgsfeatureselectionmodel.h" + +#include +#include +#include +#include +#include +#include + +QgsFeatureListViewDelegate::QgsFeatureListViewDelegate( QgsFeatureListModel *listModel, QObject *parent ) + : QItemDelegate( parent ) + , mListModel( listModel ) + , mCurrentFeatureEdited( false ) +{ +} + +QgsFeatureListViewDelegate::Element QgsFeatureListViewDelegate::positionToElement( QPoint pos ) +{ + if ( pos.x() > ICON_SIZE ) + { + return EditElement; + } + else + { + return SelectionElement; + } +} + +void QgsFeatureListViewDelegate::setFeatureSelectionModel( QgsFeatureSelectionModel *featureSelectionModel ) +{ + mFeatureSelectionModel = featureSelectionModel; +} + +void QgsFeatureListViewDelegate::setCurrentFeatureEdited( bool state ) +{ + mCurrentFeatureEdited = state; +} + +void QgsFeatureListViewDelegate::setEditSelectionModel( QItemSelectionModel *editSelectionModel ) +{ + mEditSelectionModel = editSelectionModel; +} + +QSize QgsFeatureListViewDelegate::sizeHint( const QStyleOptionViewItem &option, const QModelIndex &index ) const +{ + Q_UNUSED( index ) + int height = ICON_SIZE; + return QSize( option.rect.width(), std::max( height, option.fontMetrics.height() ) ); +} + +void QgsFeatureListViewDelegate::paint( QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index ) const +{ + const bool isEditSelection = mEditSelectionModel && mEditSelectionModel->isSelected( mListModel->mapToMaster( index ) ); + + QStyleOptionViewItem textOption = option; + textOption.state |= QStyle::State_Enabled; + if ( isEditSelection ) + { + textOption.state |= QStyle::State_Selected; + } + drawBackground( painter, textOption, index ); + + + static QPixmap sSelectedIcon; + if ( sSelectedIcon.isNull() ) + sSelectedIcon = QgsApplication::getThemePixmap( QStringLiteral( "/mIconSelected.svg" ) ); + static QPixmap sDeselectedIcon; + if ( sDeselectedIcon.isNull() ) + sDeselectedIcon = QgsApplication::getThemePixmap( QStringLiteral( "/mIconDeselected.svg" ) ); + + QString text = index.model()->data( index, Qt::EditRole ).toString(); + QgsFeatureListModel::FeatureInfo featInfo = index.model()->data( index, Qt::UserRole ).value(); + + // Icon layout options + QStyleOptionViewItem iconOption; + + QRect iconLayoutBounds( option.rect.x(), option.rect.y(), option.rect.height(), option.rect.height() ); + + QPixmap icon = mFeatureSelectionModel->isSelected( index ) ? sSelectedIcon : sDeselectedIcon; + + // Scale up the icon if needed + if ( option.rect.height() > ICON_SIZE ) + { + icon = icon.scaledToHeight( option.rect.height(), Qt::SmoothTransformation ); + } + + drawDecoration( painter, iconOption, iconLayoutBounds, icon ); + + // if conditional style also has an icon, draw that too + const QVariant conditionalIcon = index.model()->data( index, Qt::DecorationRole ); + if ( conditionalIcon.isValid() ) + { + const QPixmap pixmap = conditionalIcon.value< QPixmap >(); + iconLayoutBounds.moveLeft( iconLayoutBounds.x() + icon.width() + QFontMetrics( textOption.font ).width( 'X' ) ); + iconLayoutBounds.setTop( option.rect.y() + ( option.rect.height() - pixmap.height() ) / 2.0 ); + iconLayoutBounds.setHeight( pixmap.height() ); + drawDecoration( painter, iconOption, iconLayoutBounds, pixmap ); + } + + // Text layout options + QRect textLayoutBounds( iconLayoutBounds.x() + iconLayoutBounds.width(), option.rect.y(), option.rect.width() - ( iconLayoutBounds.x() + iconLayoutBounds.width() ), option.rect.height() ); + + // start with font and foreground color from model's FontRole + const QVariant font = index.model()->data( index, Qt::FontRole ); + if ( font.isValid() ) + { + textOption.font = font.value< QFont >(); + } + const QVariant textColor = index.model()->data( index, Qt::TextColorRole ); + if ( textColor.isValid() ) + { + textOption.palette.setColor( QPalette::Text, textColor.value< QColor >() ); + } + + if ( featInfo.isNew ) + { + textOption.font.setStyle( QFont::StyleItalic ); + textOption.palette.setColor( QPalette::Text, Qt::darkGreen ); + textOption.palette.setColor( QPalette::HighlightedText, Qt::darkGreen ); + } + else if ( featInfo.isEdited || ( mCurrentFeatureEdited && isEditSelection ) ) + { + textOption.font.setStyle( QFont::StyleItalic ); + textOption.palette.setColor( QPalette::Text, Qt::red ); + textOption.palette.setColor( QPalette::HighlightedText, Qt::red ); + } + + drawDisplay( painter, textOption, textLayoutBounds, text ); +} diff --git a/pool/shard002/C++/0024381_sample_activity.cc b/pool/shard002/C++/0024381_sample_activity.cc new file mode 100644 index 0000000000000000000000000000000000000000..f705c48b7cf7c52c956ed9993f75c51c1d6f177d --- /dev/null +++ b/pool/shard002/C++/0024381_sample_activity.cc @@ -0,0 +1,102 @@ +// Copyright 2014 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 "athena/test/base/sample_activity.h" + +#include "athena/input/public/accelerator_manager.h" +#include "ui/gfx/image/image_skia.h" +#include "ui/views/background.h" +#include "ui/views/view.h" +#include "ui/views/widget/widget.h" + +namespace athena { +namespace test { + +SampleActivity::SampleActivity(SkColor color, + SkColor contents_color, + const base::string16& title) + : color_(color), + contents_color_(contents_color), + title_(title), + contents_view_(nullptr), + current_state_(ACTIVITY_UNLOADED) { +} + +SampleActivity::~SampleActivity() { +} + +athena::ActivityViewModel* SampleActivity::GetActivityViewModel() { + return this; +} + +void SampleActivity::SetCurrentState(Activity::ActivityState state) { + current_state_ = state; +} + +Activity::ActivityState SampleActivity::GetCurrentState() { + return current_state_; +} + +bool SampleActivity::IsVisible() { + return contents_view_ && contents_view_->IsDrawn(); +} + +Activity::ActivityMediaState SampleActivity::GetMediaState() { + return Activity::ACTIVITY_MEDIA_STATE_NONE; +} + +aura::Window* SampleActivity::GetWindow() { + return !contents_view_ ? nullptr + : contents_view_->GetWidget()->GetNativeWindow(); +} + +content::WebContents* SampleActivity::GetWebContents() { + return nullptr; +} + +void SampleActivity::Init() { + accelerator_manager_ = AcceleratorManager::CreateForFocusManager( + GetContentsView()->GetWidget()->GetFocusManager()); +} + +SkColor SampleActivity::GetRepresentativeColor() const { + return color_; +} + +base::string16 SampleActivity::GetTitle() const { + return title_; +} + +gfx::ImageSkia SampleActivity::GetIcon() const { + return gfx::ImageSkia(); +} + +void SampleActivity::SetActivityView(ActivityView* view) { +} + +bool SampleActivity::UsesFrame() const { + return true; +} + +views::View* SampleActivity::GetContentsView() { + if (!contents_view_) { + contents_view_ = new views::View; + contents_view_->set_background( + views::Background::CreateSolidBackground(contents_color_)); + } + return contents_view_; +} + +gfx::ImageSkia SampleActivity::GetOverviewModeImage() { + return gfx::ImageSkia(); +} + +void SampleActivity::PrepareContentsForOverview() { +} + +void SampleActivity::ResetContentsView() { +} + +} // namespace test +} // namespace athena diff --git a/pool/shard002/C++/0024388_727A.cpp b/pool/shard002/C++/0024388_727A.cpp new file mode 100644 index 0000000000000000000000000000000000000000..4f010a3d3902b07b2c01cac2c5129258b5788a91 --- /dev/null +++ b/pool/shard002/C++/0024388_727A.cpp @@ -0,0 +1,40 @@ +#include +#include +#include +#include +using namespace std; +queue q; +map pre; +int a,b; +int main() +{ + scanf("%d%d",&a,&b); + q.push(b); + while(!q.empty()) + { + int x=q.front(); + q.pop(); + if(x==0) + break; + if(x==a) + break; + if(x%10==1) + q.push(x/10),pre[x/10]=x; + if(x%2==0) + q.push(x/2),pre[x/2]=x; + } + if(pre[a]) + { + puts("YES"); + int cnt=0; + for(int i=a;i!=b;i=pre[i]) + ++cnt; + ++cnt; + printf("%d\n",cnt); + for(int i=a;i!=b;i=pre[i]) + printf("%d ",i); + printf("%d\n",b); + } + else + puts("NO"); +} diff --git a/pool/shard002/C++/0024389_cxxhello.cc b/pool/shard002/C++/0024389_cxxhello.cc new file mode 100644 index 0000000000000000000000000000000000000000..5b5c718cfe370190c2014814c646573122b653da --- /dev/null +++ b/pool/shard002/C++/0024389_cxxhello.cc @@ -0,0 +1,26 @@ +// -*- c++ -*- +// +// $Id: cxxhello.cc,v 1.1 2002/10/31 00:01:19 mchasal Exp $ +// +// $COPYRIGHT$ +// + +#include +#include "mpi.h" + +using namespace std; + + +int +main(int argc, char *argv[]) +{ + MPI::Init(argc, argv); + + int rank = MPI::COMM_WORLD.Get_rank(); + int size = MPI::COMM_WORLD.Get_size(); + + cout << "Hello World! I am " << rank << " of " << size << endl; + + MPI::Finalize(); + return 0; +} diff --git a/pool/shard002/C++/0024396_FakeGPIO.cpp b/pool/shard002/C++/0024396_FakeGPIO.cpp new file mode 100644 index 0000000000000000000000000000000000000000..4064b57f5b11ee67b239ba29df35e1049293d7e5 --- /dev/null +++ b/pool/shard002/C++/0024396_FakeGPIO.cpp @@ -0,0 +1,88 @@ +/* + Copyright (C) 2014-2016 Leosac + + This file is part of Leosac. + + Leosac is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + Leosac 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 Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . +*/ + +#include "FakeGPIO.hpp" + +using namespace Leosac::Test::Helper; + +FakeGPIO::FakeGPIO(zmqpp::context &ctx, const std::string &name) + : ctx_(ctx) + , name_(name) + , push_(ctx, zmqpp::socket_type::push) + , rep_(ctx, zmqpp::socket_type::rep) + , value_(false) +{ + push_.connect("inproc://zmq-bus-pull"); + rep_.bind("inproc://" + name); +} + +void FakeGPIO::interrupt() +{ + push_.send("S_INT:" + name_); +} + +bool FakeGPIO::run(zmqpp::socket *pipe) +{ + zmqpp::poller poller; + + poller.add(*pipe); + poller.add(rep_); + + pipe->send(zmqpp::signal::ok); + + while (true) + { + poller.poll(-1); + if (poller.has_input(*pipe)) + break; + + if (poller.has_input(rep_)) + { + handle_cmd(); + } + } + return true; +} + +void FakeGPIO::handle_cmd() +{ + zmqpp::message_t msg; + std::string frame1; + rep_.receive(msg); + + msg >> frame1; + if (frame1 == "ON") + value_ = true; + else if (frame1 == "OFF") + value_ = false; + else if (frame1 == "TOGGLE") + value_ = !value_; + else if (frame1 == "STATE") + return send_state(); + else + assert(0); + + push_.send(zmqpp::message() << ("S_" + name_) << (value_ ? "ON" : "OFF")); + rep_.send("OK"); +} + +void FakeGPIO::send_state() +{ + rep_.send((value_ ? "ON" : "OFF")); +} diff --git a/pool/shard002/C++/0024397_main.cpp b/pool/shard002/C++/0024397_main.cpp new file mode 100644 index 0000000000000000000000000000000000000000..7095729989c472d64eda0c7d56ef6d9cf9614541 --- /dev/null +++ b/pool/shard002/C++/0024397_main.cpp @@ -0,0 +1,28 @@ +#include +#include +#include +#include +using namespace std; + +int main() +{ + string s; + while(cin >> s && s != "#") + { + string ss = s; + sort(ss.begin(),ss.end()); + int counts = 1; + do + { + //cout << ss << " " << s < + +#include "ash/components/settings/cros_settings_names.h" +#include "base/bind.h" +#include "base/strings/string_util.h" +#include "base/strings/utf_string_conversions.h" +#include "base/values.h" +#include "chrome/browser/ash/login/users/chrome_user_manager_impl.h" +#include "chrome/browser/ash/settings/cros_settings.h" +#include "chrome/browser/browser_process.h" +#include "components/prefs/pref_registry_simple.h" +#include "components/prefs/pref_service.h" +#include "components/prefs/scoped_user_pref_update.h" +#include "components/user_manager/user_type.h" +#include "content/public/browser/browser_thread.h" +#include "google_apis/gaia/gaia_auth_util.h" +#include "third_party/abseil-cpp/absl/types/optional.h" + +using content::BrowserThread; + +namespace { + +// Names for pref keys in Local State. +// A map from supervised user local user id to sync user id. +const char kSupervisedUserSyncId[] = "ManagedUserSyncId"; + +// A map from supervised user id to manager user id. +const char kSupervisedUserManagers[] = "ManagedUserManagers"; + +// A map from supervised user id to manager display name. +const char kSupervisedUserManagerNames[] = "ManagedUserManagerNames"; + +// A map from supervised user id to manager display e-mail. +const char kSupervisedUserManagerDisplayEmails[] = + "ManagedUserManagerDisplayEmails"; + +// A vector pref of the supervised accounts defined on this device, that had +// not logged in yet. +const char kSupervisedUsersFirstRun[] = "LocallyManagedUsersFirstRun"; + +// A map from user id to password schema id. +const char kSupervisedUserPasswordSchema[] = "SupervisedUserPasswordSchema"; + +// A map from user id to password salt. +const char kSupervisedUserPasswordSalt[] = "SupervisedUserPasswordSalt"; + +// A map from user id to password revision. +const char kSupervisedUserPasswordRevision[] = "SupervisedUserPasswordRevision"; + +// A map from user id to flag indicating if password should be updated upon +// signin. +const char kSupervisedUserNeedPasswordUpdate[] = + "SupervisedUserNeedPasswordUpdate"; + +// A map from user id to flag indicating if cryptohome does not have signature +// key. +const char kSupervisedUserIncompleteKey[] = "SupervisedUserHasIncompleteKey"; + +} // namespace + +namespace ash { + +const char kSchemaVersion[] = "SchemaVersion"; +const char kPasswordRevision[] = "PasswordRevision"; +const char kSalt[] = "PasswordSalt"; +const char kRequirePasswordUpdate[] = "RequirePasswordUpdate"; +const char kHasIncompleteKey[] = "HasIncompleteKey"; + +// static +void SupervisedUserManager::RegisterLocalStatePrefs( + PrefRegistrySimple* registry) { + registry->RegisterListPref(kSupervisedUsersFirstRun); + registry->RegisterDictionaryPref(kSupervisedUserSyncId); + registry->RegisterDictionaryPref(kSupervisedUserManagers); + registry->RegisterDictionaryPref(kSupervisedUserManagerNames); + registry->RegisterDictionaryPref(kSupervisedUserManagerDisplayEmails); + + registry->RegisterDictionaryPref(kSupervisedUserPasswordSchema); + registry->RegisterDictionaryPref(kSupervisedUserPasswordSalt); + registry->RegisterDictionaryPref(kSupervisedUserPasswordRevision); + + registry->RegisterDictionaryPref(kSupervisedUserNeedPasswordUpdate); + registry->RegisterDictionaryPref(kSupervisedUserIncompleteKey); +} + +SupervisedUserManagerImpl::SupervisedUserManagerImpl( + ChromeUserManagerImpl* owner) + : owner_(owner), cros_settings_(CrosSettings::Get()) { + // SupervisedUserManager instance should be used only on UI thread. + // (or in unit_tests) + if (base::ThreadTaskRunnerHandle::IsSet()) + DCHECK_CURRENTLY_ON(BrowserThread::UI); +} + +SupervisedUserManagerImpl::~SupervisedUserManagerImpl() {} + +std::string SupervisedUserManagerImpl::GetUserSyncId( + const std::string& user_id) const { + std::string result; + GetUserStringValue(user_id, kSupervisedUserSyncId, &result); + return result; +} + +std::u16string SupervisedUserManagerImpl::GetManagerDisplayName( + const std::string& user_id) const { + PrefService* local_state = g_browser_process->local_state(); + const base::Value* manager_names = + local_state->GetDictionary(kSupervisedUserManagerNames); + const std::string* result = manager_names->FindStringKey(user_id); + if (result && !result->empty()) + return base::UTF8ToUTF16(*result); + return base::UTF8ToUTF16(GetManagerDisplayEmail(user_id)); +} + +std::string SupervisedUserManagerImpl::GetManagerUserId( + const std::string& user_id) const { + std::string result; + GetUserStringValue(user_id, kSupervisedUserManagers, &result); + return result; +} + +std::string SupervisedUserManagerImpl::GetManagerDisplayEmail( + const std::string& user_id) const { + std::string result; + if (GetUserStringValue(user_id, kSupervisedUserManagerDisplayEmails, + &result) && + !result.empty()) + return result; + return GetManagerUserId(user_id); +} + +void SupervisedUserManagerImpl::GetPasswordInformation( + const std::string& user_id, + base::DictionaryValue* result) { + int value; + if (GetUserIntegerValue(user_id, kSupervisedUserPasswordSchema, &value)) + result->SetKey(kSchemaVersion, base::Value(value)); + if (GetUserIntegerValue(user_id, kSupervisedUserPasswordRevision, &value)) + result->SetKey(kPasswordRevision, base::Value(value)); + + bool flag; + if (GetUserBooleanValue(user_id, kSupervisedUserNeedPasswordUpdate, &flag)) + result->SetKey(kRequirePasswordUpdate, base::Value(flag)); + if (GetUserBooleanValue(user_id, kSupervisedUserIncompleteKey, &flag)) + result->SetKey(kHasIncompleteKey, base::Value(flag)); + + std::string salt; + if (GetUserStringValue(user_id, kSupervisedUserPasswordSalt, &salt)) + result->SetKey(kSalt, base::Value(salt)); +} + +void SupervisedUserManagerImpl::SetPasswordInformation( + const std::string& user_id, + const base::DictionaryValue* password_info) { + absl::optional schema_version = + password_info->FindIntKey(kSchemaVersion); + if (schema_version.has_value()) + SetUserIntegerValue(user_id, kSupervisedUserPasswordSchema, + schema_version.value()); + absl::optional password_revision = + password_info->FindIntKey(kPasswordRevision); + if (password_revision.has_value()) + SetUserIntegerValue(user_id, kSupervisedUserPasswordRevision, + password_revision.value()); + + absl::optional flag = + password_info->FindBoolKey(kRequirePasswordUpdate); + if (flag.has_value()) { + SetUserBooleanValue(user_id, kSupervisedUserNeedPasswordUpdate, + flag.value()); + } + flag = password_info->FindBoolKey(kHasIncompleteKey); + if (flag.has_value()) + SetUserBooleanValue(user_id, kSupervisedUserIncompleteKey, flag.value()); + + const std::string* salt = password_info->FindStringKey(kSalt); + if (salt) + SetUserStringValue(user_id, kSupervisedUserPasswordSalt, *salt); + g_browser_process->local_state()->CommitPendingWrite(); +} + +bool SupervisedUserManagerImpl::GetUserStringValue( + const std::string& user_id, + const char* key, + std::string* out_value) const { + PrefService* local_state = g_browser_process->local_state(); + const base::Value* dictionary = local_state->GetDictionary(key); + const std::string* value = dictionary->FindStringKey(user_id); + if (!value) + return false; + + *out_value = *value; + return true; +} + +bool SupervisedUserManagerImpl::GetUserIntegerValue(const std::string& user_id, + const char* key, + int* out_value) const { + PrefService* local_state = g_browser_process->local_state(); + const base::Value* dictionary = local_state->GetDictionary(key); + absl::optional value = dictionary->FindIntKey(user_id); + if (!value) + return false; + + *out_value = value.value(); + return true; +} + +bool SupervisedUserManagerImpl::GetUserBooleanValue(const std::string& user_id, + const char* key, + bool* out_value) const { + PrefService* local_state = g_browser_process->local_state(); + const base::Value* dictionary = local_state->GetDictionary(key); + absl::optional flag = dictionary->FindBoolKey(user_id); + if (!flag) + return false; + + *out_value = flag.value(); + return true; +} + +void SupervisedUserManagerImpl::SetUserStringValue(const std::string& user_id, + const char* key, + const std::string& value) { + PrefService* local_state = g_browser_process->local_state(); + DictionaryPrefUpdate update(local_state, key); + update->SetStringKey(user_id, value); +} + +void SupervisedUserManagerImpl::SetUserIntegerValue(const std::string& user_id, + const char* key, + const int value) { + PrefService* local_state = g_browser_process->local_state(); + DictionaryPrefUpdate update(local_state, key); + update->SetIntKey(user_id, value); +} + +void SupervisedUserManagerImpl::SetUserBooleanValue(const std::string& user_id, + const char* key, + const bool value) { + PrefService* local_state = g_browser_process->local_state(); + DictionaryPrefUpdate update(local_state, key); + update->SetBoolKey(user_id, value); +} + +void SupervisedUserManagerImpl::RemoveNonCryptohomeData( + const std::string& user_id) { + PrefService* prefs = g_browser_process->local_state(); + ListPrefUpdate prefs_new_users_update(prefs, kSupervisedUsersFirstRun); + prefs_new_users_update->EraseListValue(base::Value(user_id)); + + CleanPref(user_id, kSupervisedUserSyncId); + CleanPref(user_id, kSupervisedUserManagers); + CleanPref(user_id, kSupervisedUserManagerNames); + CleanPref(user_id, kSupervisedUserManagerDisplayEmails); + CleanPref(user_id, kSupervisedUserPasswordSalt); + CleanPref(user_id, kSupervisedUserPasswordSchema); + CleanPref(user_id, kSupervisedUserPasswordRevision); + CleanPref(user_id, kSupervisedUserNeedPasswordUpdate); + CleanPref(user_id, kSupervisedUserIncompleteKey); +} + +void SupervisedUserManagerImpl::CleanPref(const std::string& user_id, + const char* key) { + PrefService* prefs = g_browser_process->local_state(); + DictionaryPrefUpdate dict_update(prefs, key); + dict_update->RemoveKey(user_id); +} + +bool SupervisedUserManagerImpl::CheckForFirstRun(const std::string& user_id) { + ListPrefUpdate prefs_new_users_update(g_browser_process->local_state(), + kSupervisedUsersFirstRun); + return prefs_new_users_update->EraseListValue(base::Value(user_id)); +} + +} // namespace ash diff --git a/pool/shard002/C++/0024406_B.cpp b/pool/shard002/C++/0024406_B.cpp new file mode 100644 index 0000000000000000000000000000000000000000..78124e579e0bd49f1ecb42f37b060bb638b02188 --- /dev/null +++ b/pool/shard002/C++/0024406_B.cpp @@ -0,0 +1,49 @@ +#include +using namespace std; + +#define endl "\n" + +double pos[60001], spd[60001]; + +bool meet(int n, double t) { + double rng[60001][2]; + + double L = rng[0][0] = pos[0] - spd[0]*t; + double R = rng[0][1] = pos[0] + spd[0]*t; + for (int i=1; i L) + L = rng[i][0]; + + rng[i][1] = pos[i] + spd[i]*t; + if (rng[i][1] < R) + R = rng[i][1]; + } + + return (L <= R); +} + +int main(void) { + + int n; + scanf("%d", &n); + + for (int i=0; i +#include + +#ifdef USE_OPENMP +#include // openmp +#endif + + +namespace { +struct ResidualCompare { + bool operator () (const gbdt::Tuple *t1, const gbdt::Tuple *t2) { + return t1->residual < t2->residual; + } +}; + +struct LabelCompare { + bool operator () (const gbdt::Tuple *t1, const gbdt::Tuple *t2) { + return t1->label < t2->label; + } +}; + +} + +namespace gbdt { + +bool AlmostEqual(ValueType v1, ValueType v2) { + ValueType diff = Abs(v1-v2); + if (diff < 1.0e-5) + return true; + return false; +} + +bool Same(const DataVector &data, size_t len) { + assert(len <= data.size()); + if (len <= 1) + return true; + + ValueType t = data[0]->target; + for (size_t i = 1; i < len; ++i) { + if (!AlmostEqual(t, data[i]->target)) + return false; + } + return true; +} + +ValueType Average(const DataVector & data, size_t len) { + assert(len <= data.size()); + if (len == 0) + return 0; + double s = 0; + double c = 0; + for (size_t i = 0; i < len; ++i) { + s += data[i]->target * data[i]->weight; + c += data[i]->weight; + } + return static_cast(s / c); +} + +double RMSE(const DataVector &data, const PredictVector &predict, size_t len) { + assert(data.size() >= len); + assert(predict.size() >= len); + double s = 0; + double c = 0; + + for (size_t i = 0; i < data.size(); ++i) { + s += Squared(predict[i] - data[i]->label) * data[i]->weight; + c += data[i]->weight; + } + + return std::sqrt(s / c); +} + +double MAE(const DataVector &data, const PredictVector &predict, size_t len) { + assert(data.size() >= len); + assert(predict.size() >= len); + double s = 0; + double c = 0; + + for (size_t i = 0; i < data.size(); ++i) { + s += Abs(predict[i] - data[i]->label) * data[i]->weight; + c += data[i]->weight; + } + + return s / c; +} + +ValueType WeightedResidualMedian(DataVector &d, size_t len) { + assert(d.size() >= len); + // simplest implementation using sorting + // sophisticated approch to find the weighted median is selection algorithm(partition algorithm). + std::sort(d.begin(), d.begin() + len, ResidualCompare()); + double all_weight = 0.0; + for (size_t i = 0; i < len; ++i) { + all_weight += d[i]->weight; + } + + ValueType weighted_median = 0.0; + double weight = 0.0; + for (int i = 0; i < len; ++i) { + weight += d[i]->weight; + if (weight * 2 > all_weight) { + if (i-1 >= 0) { + weighted_median = (d[i]->residual + d[i-1]->residual) / 2.0; + } else { + weighted_median = d[i]->residual; + } + + break; + } + } + + return weighted_median; +} + +ValueType WeightedLabelMedian(DataVector &d, size_t len) { + assert(d.size() >= len); + // simplest implementation using sorting + // sophisticated approch to find the weighted median is selection algorithm(partition algorithm). + std::sort(d.begin(), d.begin() + len, LabelCompare()); + double all_weight = 0.0; + for (size_t i = 0; i < len; ++i) { + all_weight += d[i]->weight; + } + + ValueType weighted_median = 0.0; + double weight = 0.0; + for (int i = 0; i < len; ++i) { + weight += d[i]->weight; + if (weight * 2 > all_weight) { + if (i-1 >= 0) { + weighted_median = (d[i]->label + d[i-1]->label) / 2.0; + } else { + weighted_median = d[i]->label; + } + break; + } + } + + return weighted_median; +} + +} diff --git a/pool/shard002/C++/0024412_haj_weapon_shovel.cpp b/pool/shard002/C++/0024412_haj_weapon_shovel.cpp new file mode 100644 index 0000000000000000000000000000000000000000..528ca3f682cf64ba5f2b5ce0cf87a1d494526212 --- /dev/null +++ b/pool/shard002/C++/0024412_haj_weapon_shovel.cpp @@ -0,0 +1,213 @@ +//========= Copyright © 2007, Ham and Jam. ==============================// +// Purpose: German Entrenching Tool +// Notes: Spong! +//=======================================================================// + +#include "cbase.h" +#include "weapon_hl2mpbasehlmpcombatweapon.h" +#include "gamerules.h" +#include "ammodef.h" +#include "mathlib.h" +#include "in_buttons.h" +#include "weapon_hl2mpbasebasebludgeon.h" +#include "npcevent.h" + +// memdbgon must be the last include file in a .cpp file!!! +#include "tier0/memdbgon.h" + +#define SHOVEL_RANGE_NORMAL 62.0f // effective range normally +#define SHOVEL_REFIRE 0.75f // time between stabs/slash/swings, etc. + +#ifdef CLIENT_DLL +#define CWeaponShovel C_WeaponShovel +#endif + +//----------------------------------------------------------------------------- +// CWeaponShovel +//----------------------------------------------------------------------------- + +class CWeaponShovel : public CBaseHL2MPBludgeonWeapon +{ +public: + DECLARE_CLASS( CWeaponShovel, CBaseHL2MPBludgeonWeapon ); + + DECLARE_NETWORKCLASS(); + DECLARE_PREDICTABLE(); + + DECLARE_ACTTABLE(); + + CWeaponShovel(); + + float GetRange( void ) { return SHOVEL_RANGE_NORMAL; } + float GetFireRate( void ) { return SHOVEL_REFIRE; } + + float GetDamageForActivity( Activity hitActivity ); + void SecondaryAttack( void ) { return; } // tweak this to add stealth mode + + void Drop( const Vector &vecVelocity ); + + // Animation event +#ifndef CLIENT_DLL + virtual void Operator_HandleAnimEvent( animevent_t *pEvent, CBaseCombatCharacter *pOperator ); + void HandleAnimEventMeleeHit( animevent_t *pEvent, CBaseCombatCharacter *pOperator ); + virtual bool ShouldDrawPickup() { return false; } +#endif + + CWeaponShovel( const CWeaponShovel & ); + +private: + +}; + +IMPLEMENT_NETWORKCLASS_ALIASED( WeaponShovel, DT_WeaponShovel ) + +BEGIN_NETWORK_TABLE( CWeaponShovel, DT_WeaponShovel ) +END_NETWORK_TABLE() + +BEGIN_PREDICTION_DATA( CWeaponShovel ) +END_PREDICTION_DATA() + +LINK_ENTITY_TO_CLASS( weapon_shovel, CWeaponShovel ); +PRECACHE_WEAPON_REGISTER( weapon_shovel ); + +acttable_t CWeaponShovel::m_acttable[] = +{ + // attack + { ACT_MP_ATTACK_STAND_PRIMARYFIRE, ACT_HAJ_PRIMARYATTACK_SPADE, false }, + { ACT_MP_ATTACK_CROUCH_PRIMARYFIRE, ACT_HAJ_PRIMARYATTACK_SPADE, false }, + { ACT_MP_ATTACK_PRONE_PRIMARYFIRE, ACT_HAJ_PRIMARYATTACK_PRONE_SPADE, false }, + + // aiming down sight, recent attack + { ACT_HAJ_IDLE_AIM, ACT_HAJ_STAND_AIM_SPADE, false }, + { ACT_HAJ_WALK_AIM, ACT_HAJ_WALK_AIM_SPADE, false }, + { ACT_HAJ_IDLE_CROUCH_AIM, ACT_HAJ_CROUCH_AIM_SPADE, false }, + { ACT_HAJ_WALK_CROUCH_AIM, ACT_HAJ_CROUCHWALK_IDLE_SPADE, false }, + { ACT_HAJ_RUN_AIM, ACT_HAJ_RUN_AIM_SPADE, false }, + + // movement + { ACT_MP_STAND_IDLE, ACT_HAJ_STAND_AIM_SPADE, false }, + { ACT_MP_RUN, ACT_HAJ_RUN_AIM_SPADE, false }, + { ACT_MP_SPRINT, ACT_HAJ_SPRINT_AIM_SPADE, false }, + { ACT_MP_WALK, ACT_HAJ_WALK_AIM_SPADE, false }, + { ACT_MP_PRONE_IDLE, ACT_HAJ_PRONE_AIM_SPADE, false }, + { ACT_MP_PRONE_CRAWL, ACT_HAJ_PRONEWALK_AIM_SPADE, false }, + { ACT_MP_CROUCH_IDLE, ACT_HAJ_CROUCH_AIM_SPADE, false }, + { ACT_MP_CROUCHWALK, ACT_HAJ_CROUCHWALK_AIM_SPADE, false }, +}; + +IMPLEMENT_ACTTABLE(CWeaponShovel); + + +//----------------------------------------------------------------------------- +// Constructor +//----------------------------------------------------------------------------- +CWeaponShovel::CWeaponShovel( void ) +{ +} + +//----------------------------------------------------------------------------- +// Purpose: Get the damage amount for the animation we're doing +// Input : hitActivity - currently played activity +// Output : Damage amount +//----------------------------------------------------------------------------- +float CWeaponShovel::GetDamageForActivity( Activity hitActivity ) +{ +#ifndef CLIENT_DLL + // TODO - tune this so that it does a different ammount for the stealth kill + CBaseCombatCharacter* pOwner = ToBaseCombatCharacter( GetOwner() ); + + if( pOwner ) + { + Vector vecDirection; + AngleVectors( GetAbsAngles(), &vecDirection ); + + Vector vecEnd; + VectorMA( pOwner->Weapon_ShootPosition(), SHOVEL_RANGE_NORMAL, vecDirection, vecEnd ); + + trace_t traceHit; + UTIL_TraceLine( pOwner->Weapon_ShootPosition(), vecEnd, MASK_SHOT_HULL, pOwner, COLLISION_GROUP_NONE, &traceHit ); + + if( traceHit.DidHit() && traceHit.m_pEnt && traceHit.hitgroup == HITGROUP_HEAD ) + { + return 100.0f; + } + } +#endif + + return 75.0f; +} + +//----------------------------------------------------------------------------- +// Purpose: +//----------------------------------------------------------------------------- +void CWeaponShovel::Drop( const Vector &vecVelocity ) +{ + // You can't drop a shovel so if, somehow, you do manage to, delete it. +#ifndef CLIENT_DLL + UTIL_Remove( this ); +#endif +} + +#ifndef CLIENT_DLL +//----------------------------------------------------------------------------- +// Animation event handlers +//----------------------------------------------------------------------------- +void CWeaponShovel::HandleAnimEventMeleeHit( animevent_t *pEvent, CBaseCombatCharacter *pOperator ) +{ + // Trace up or down based on where the enemy is... + // But only if we're basically facing that direction + Vector vecDirection; + AngleVectors( GetAbsAngles(), &vecDirection ); + + Vector vecEnd; + VectorMA( pOperator->Weapon_ShootPosition(), 50, vecDirection, vecEnd ); + + CBaseEntity *pHurt = pOperator->CheckTraceHullAttack( pOperator->Weapon_ShootPosition(), + vecEnd, + Vector(-16,-16,-16), + Vector(36,36,36), + GetDamageForActivity( GetActivity() ), + DMG_CLUB, + 0.75 ); // check this force scale value? + + // did I hit someone? + if ( pHurt ) + { + + // Fake a trace impact, so the effects work out like a player's crowbaw + trace_t traceHit; + UTIL_TraceLine( pOperator->Weapon_ShootPosition(), + pHurt->GetAbsOrigin(), + MASK_SHOT_HULL | CONTENTS_HITBOX, + pOperator, + COLLISION_GROUP_NONE, + &traceHit ); + + // do the slash decal + ImpactEffect( traceHit ); + + } + else + { + //WeaponSound( MELEE_MISS ); + } +} + +//----------------------------------------------------------------------------- +// Animation event +//----------------------------------------------------------------------------- +void CWeaponShovel::Operator_HandleAnimEvent( animevent_t *pEvent, CBaseCombatCharacter *pOperator ) +{ + switch( pEvent->event ) + { + case EVENT_WEAPON_MELEE_HIT: + HandleAnimEventMeleeHit( pEvent, pOperator ); + break; + + default: + BaseClass::Operator_HandleAnimEvent( pEvent, pOperator ); + break; + } +} + +#endif \ No newline at end of file diff --git a/pool/shard002/C++/0024414_lock_view.cc b/pool/shard002/C++/0024414_lock_view.cc new file mode 100644 index 0000000000000000000000000000000000000000..16895c6b571ce970b2c6532de7029fb051783b5f --- /dev/null +++ b/pool/shard002/C++/0024414_lock_view.cc @@ -0,0 +1,109 @@ +// 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 "ash/shell.h" +#include "ash/shell_delegate.h" +#include "ash/shell_window_ids.h" +#include "ash/shell/example_factory.h" +#include "base/utf_string_conversions.h" +#include "ui/aura/root_window.h" +#include "ui/aura/window.h" +#include "ui/gfx/canvas.h" +#include "ui/gfx/font.h" +#include "ui/views/controls/button/text_button.h" +#include "ui/views/corewm/tooltip_controller.h" +#include "ui/views/widget/widget.h" +#include "ui/views/widget/widget_delegate.h" + +using ash::Shell; + +namespace ash { +namespace shell { + +class LockView : public views::WidgetDelegateView, + public views::ButtonListener { + public: + LockView() : unlock_button_(ALLOW_THIS_IN_INITIALIZER_LIST( + new views::NativeTextButton(this, ASCIIToUTF16("Unlock")))) { + AddChildView(unlock_button_); + unlock_button_->set_focusable(true); + } + virtual ~LockView() {} + + // Overridden from views::View: + virtual gfx::Size GetPreferredSize() OVERRIDE { + return gfx::Size(500, 400); + } + + private: + // Overridden from views::View: + virtual void OnPaint(gfx::Canvas* canvas) OVERRIDE { + canvas->FillRect(GetLocalBounds(), SK_ColorYELLOW); + string16 text = ASCIIToUTF16("LOCKED!"); + int string_width = font_.GetStringWidth(text); + canvas->DrawStringInt(text, font_, SK_ColorRED, (width() - string_width)/ 2, + (height() - font_.GetHeight()) / 2, + string_width, font_.GetHeight()); + } + virtual void Layout() OVERRIDE { + gfx::Rect bounds = GetLocalBounds(); + gfx::Size ps = unlock_button_->GetPreferredSize(); + bounds.set_y(bounds.bottom() - ps.height() - 5); + bounds.set_x((bounds.width() - ps.width()) / 2); + bounds.set_size(ps); + unlock_button_->SetBoundsRect(bounds); + } + virtual void ViewHierarchyChanged(bool is_add, + views::View* parent, + views::View* child) OVERRIDE { + if (is_add && child == this) + unlock_button_->RequestFocus(); + } + + // Overridden from views::WidgetDelegateView: + virtual void WindowClosing() OVERRIDE { + Shell::GetInstance()->delegate()->UnlockScreen(); + } + + // Overridden from views::ButtonListener: + virtual void ButtonPressed(views::Button* sender, + const ui::Event& event) OVERRIDE { + DCHECK(sender == unlock_button_); + GetWidget()->Close(); + } + + gfx::Font font_; + views::NativeTextButton* unlock_button_; + + DISALLOW_COPY_AND_ASSIGN(LockView); +}; + +void CreateLockScreen() { + LockView* lock_view = new LockView; + views::Widget* widget = new views::Widget; + views::Widget::InitParams params( + views::Widget::InitParams::TYPE_WINDOW_FRAMELESS); + gfx::Size ps = lock_view->GetPreferredSize(); + + gfx::Size root_window_size = Shell::GetPrimaryRootWindow()->bounds().size(); + params.bounds = gfx::Rect((root_window_size.width() - ps.width()) / 2, + (root_window_size.height() - ps.height()) / 2, + ps.width(), ps.height()); + params.delegate = lock_view; + params.parent = Shell::GetContainer( + Shell::GetPrimaryRootWindow(), + internal::kShellWindowId_LockScreenContainer); + widget->Init(params); + widget->SetContentsView(lock_view); + widget->Show(); + widget->GetNativeView()->SetName("LockView"); + widget->GetNativeView()->Focus(); + + // TODO: it shouldn't be necessary to invoke UpdateTooltip() here. + Shell::GetInstance()->tooltip_controller()->UpdateTooltip( + widget->GetNativeView()); +} + +} // namespace shell +} // namespace ash diff --git a/pool/shard002/C++/0024416_MsPacman.cpp b/pool/shard002/C++/0024416_MsPacman.cpp new file mode 100644 index 0000000000000000000000000000000000000000..2a49d97aae51e12207595a34af60b3d3ebc348cf --- /dev/null +++ b/pool/shard002/C++/0024416_MsPacman.cpp @@ -0,0 +1,106 @@ +/* ***************************************************************************** + * A.L.E (Arcade Learning Environment) + * Copyright (c) 2009-2013 by Yavar Naddaf, Joel Veness, Marc G. Bellemare and + * the Reinforcement Learning and Artificial Intelligence Laboratory + * Released under the GNU General Public License; see License.txt for details. + * + * Based on: Stella -- "An Atari 2600 VCS Emulator" + * Copyright (c) 1995-2007 by Bradford W. Mott and the Stella team + * + * ***************************************************************************** + */ +#include "MsPacman.hpp" + +#include "../RomUtils.hpp" + + +MsPacmanSettings::MsPacmanSettings() { + + reset(); +} + + +/* create a new instance of the rom */ +RomSettings* MsPacmanSettings::clone() const { + + RomSettings* rval = new MsPacmanSettings(); + *rval = *this; + return rval; +} + + +/* process the latest information from ALE */ +void MsPacmanSettings::step(const System& system) { + + // update the reward + int score = getDecimalScore(0xF8, 0xF9, 0xFA, &system); + int reward = score - m_score; + m_reward = reward; + m_score = score; + + // update terminal status + int lives = readRam(&system, 0xFB) & 0xF; + // MGB Did not work int black_screen_byte = readRam(&system, 0x94); + int death_timer = readRam(&system, 0xA7); + m_terminal = lives == 0 && death_timer == 0x53; +} + + +/* is end of game */ +bool MsPacmanSettings::isTerminal() const { + + return m_terminal; +}; + + +/* get the most recently observed reward */ +reward_t MsPacmanSettings::getReward() const { + + return m_reward; +} + + +/* is an action part of the minimal set? */ +bool MsPacmanSettings::isMinimal(const Action &a) const { + + switch (a) { + case PLAYER_A_NOOP: + case PLAYER_A_UP: + case PLAYER_A_RIGHT: + case PLAYER_A_LEFT: + case PLAYER_A_DOWN: + case PLAYER_A_UPRIGHT: + case PLAYER_A_UPLEFT: + case PLAYER_A_DOWNRIGHT: + case PLAYER_A_DOWNLEFT: + return true; + default: + return false; + } +} + + +/* reset the state of the game */ +void MsPacmanSettings::reset() { + + m_reward = 0; + m_score = 0; + m_terminal = false; +} + + + +/* saves the state of the rom settings */ +void MsPacmanSettings::saveState(Serializer & ser) { + ser.putInt(m_reward); + ser.putInt(m_score); + ser.putBool(m_terminal); +} + +// loads the state of the rom settings +void MsPacmanSettings::loadState(Deserializer & ser) { + m_reward = ser.getInt(); + m_score = ser.getInt(); + m_terminal = ser.getBool(); +} + diff --git a/pool/shard002/C++/0024426_config.cpp b/pool/shard002/C++/0024426_config.cpp new file mode 100644 index 0000000000000000000000000000000000000000..bb6bc69d04e92aafdc2f3893f7c75b0eba7d2824 --- /dev/null +++ b/pool/shard002/C++/0024426_config.cpp @@ -0,0 +1,227 @@ +/* + * File: config.cpp + * Author: yvan + * + * Created on December 8, 2013, 9:45 PM + */ + +#include +#include +#include "config.h" +#include "convert.h" +#include "../system/workDir.h" +#include "log.h" + +y::utils::config & y::utils::Config() { + static config c; + return c; +} + +using namespace boost::program_options; + +y::utils::config::config() : general("general options"), + file("config file options"), + configReady(false){ +} + +void y::utils::config::load() { + load(0, nullptr); +} + +void y::utils::config::load(int argc, char** argv) { + std::lock_guard lock(m); + if(configReady) { + //Log().add("y::sys::config::load is called more than once!"); + return; + } + + general.add_options() + ("help", "print help message") + ("work-directory,w", value(), "set working directory") + ("config,c", + value(&configFile)->default_value("/etc/yATools.cfg"), + "Name of the config file to be used." + ) + ; + + file.add_options() + ("ldapPasswd" , value(), "set ldap admin password") + ("ldapHost" , value(), "set ldap host" ) + ("ldapBaseDN" , value(), "set ldap base DN" ) + ("ldapAdminDN" , value(), "set ldap admin DN" ) + ("ldapTestUID" , value(), "set ldap test account" ) + ("ldapTestPassword" , value(), "set ldap test account password") + ("ldapTestUIDNumber", value(), "set ldap test account UID number") + ("ldapTestDN" , value(), "set ldap test account DN") + ("mysqlRootPassword", value(), "set mysql root password") + ("domain" , value(), "set network domain" ) + ("smartschoolPw" , value(), "set smartschool password") + ("yearbookAdmin" , value< std::vector >(), "set yearbook administrators" ) + ; + + all.add(general).add(file); + + store(parse_command_line(argc, argv, all), map); + notify(map); + + std::wifstream ifs(configFile.c_str()); + if(!ifs) { + string out("cannot open config file: "); + out += configFile.c_str(); + Log().add(out); + } else { + /*std::string out = "loading config file: "; + out.append(configFile); + Log().add(out);*/ + store(parse_config_file(ifs, file), map); + notify(map); + } + + if(map.count("help")) { + std::cout << general << std::endl; + exit(0); + } + + if(map.count("work-directory")) { + y::sys::WorkDir.set(map["work-directory"].as()); + } + + if(map.count("ldapPasswd")) { + ldapPasswd = map["ldapPasswd"].as(); + } else { + y::utils::Log().add("Config warning: ldap password is not set."); + } + + if(map.count("ldapHost")) { + ldapHost = map["ldapHost"].as(); + } else { + y::utils::Log().add("Config warning: ldap host is not set."); + } + + if(map.count("ldapBaseDN")) { + ldapBaseDN = map["ldapBaseDN"].as(); + } else { + y::utils::Log().add("Config warning: ldap Base DN is not set."); + } + + if(map.count("ldapAdminDN")) { + ldapAdminDN = map["ldapAdminDN"].as(); + } else { + y::utils::Log().add("Config warning: ldap admin DN is not set."); + } + + if(map.count("ldapTestUID")) { + ldapTestUID = map["ldapTestUID"].as(); + } else { + y::utils::Log().add("Config warning: ldap test UID is not set."); + } + + if(map.count("ldapTestPassword")) { + ldapTestPassword = map["ldapTestPassword"].as(); + } else { + y::utils::Log().add("Config warning: ldap test password is not set."); + } + + if(map.count("ldapTestUIDNumber")) { + ldapTestUidNumber = map["ldapTestUIDNumber"].as(); + } else { + y::utils::Log().add("Config warning: ldap test UID number is not set."); + } + + if(map.count("ldapTestDN")) { + ldapTestDN = map["ldapTestDN"].as(); + } else { + y::utils::Log().add("Config warning: ldap test DN is not set."); + } + + if(map.count("mysqlRootPassword")) { + mysqlPassword = map["mysqlRootPassword"].as(); + } else { + y::utils::Log().add("Config warning: mysql password is not set."); + } + + if(map.count("domain")) { + domain = map["domain"].as(); + } else { + y::utils::Log().add("Config warning: domain is not set."); + } + + if(map.count("smartschoolPw")) { + smartschoolPw = map["smartschoolPw"].as(); + } else { + y::utils::Log().add("Config warning: smartschool password is not set."); + } + + if(map.count("yearbookAdmin")) { + const std::vector & admin = map["yearbookAdmin"].as< std::vector >(); + for(unsigned int i = 0; i < admin.size(); i++) { + yearbookAdmin.New() = admin[i]; + } + } + + configReady = true; +} + +const string & y::utils::config::getLdapPasswd() const { + std::lock_guard lock(m); + return ldapPasswd; +} + +const string & y::utils::config::getLdapHost() const { + std::lock_guard lock(m); + return ldapHost; +} + +const string & y::utils::config::getLdapBaseDN() const { + std::lock_guard lock(m); + return ldapBaseDN; +} + +const string & y::utils::config::getLdapAdminDN() const { + std::lock_guard lock(m); + return ldapAdminDN; +} + +const string & y::utils::config::getLdapTestUID() const { + std::lock_guard lock(m); + return ldapTestUID; +} + +const string & y::utils::config::getLdapTestPassword() const { + std::lock_guard lock(m); + return ldapTestPassword; +} + +const string & y::utils::config::getLdapTestUidNumber() const { + std::lock_guard lock(m); + return ldapTestUidNumber; +} + +const string & y::utils::config::getLdapTestDN() const { + std::lock_guard lock(m); + return ldapTestDN; +} + +const string & y::utils::config::getMysqlPassword() const { + std::lock_guard lock(m); + return mysqlPassword; +} + +const string & y::utils::config::getDomain() const { + std::lock_guard lock(m); + return domain; +} + +const string & y::utils::config::getSSPw() const { + std::lock_guard lock(m); + return smartschoolPw; +} + +bool y::utils::config::isYearbookAdmin(const string& uid) { + std::lock_guard lock(m); + for(int i = 0; i < yearbookAdmin.elms(); i++) { + if(yearbookAdmin[i] == uid) return true; + } + + return false; +} \ No newline at end of file diff --git a/pool/shard002/C++/0024430_solve.cpp b/pool/shard002/C++/0024430_solve.cpp new file mode 100644 index 0000000000000000000000000000000000000000..43dee04d634ca17d8853204a4d6f43cdb998f889 --- /dev/null +++ b/pool/shard002/C++/0024430_solve.cpp @@ -0,0 +1,179 @@ +/* + * TASK: Given a binary search tree and one of its nodes, determine the in-order + * successor of this node. + */ + +#include +#include +#include + +/** @brief A node of a binary search tree. */ +struct tree_node +{ + size_t key; + tree_node* left; + tree_node* right; + tree_node* parent; + + ~tree_node() + { + delete left; + delete right; + } +}; + +/** + * @brief Returns a pointer to a node in a binary search containing a given key + * or nullptr is no such node exists. + * @param root The root node of the tree. + * @param key The key to search for. + * @note Complexity: O(n) in both time and space, where n is the number of tree + * nodes. + */ +const tree_node* find(const tree_node* root, const size_t key) +{ + if (root == nullptr || key == root->key) + { + return root; + } + + return (key < root->key) ? find(root->left, key) : find(root->right, key); +} + +/** + * @brief Inserts a node with a given key into a binary search tree. + * @param root The root node of the tree. + * @param key The key to be inserted. + * @note Complexity: O(n) in both time and space, where n is the number of tree + * nodes. + */ +void insert(tree_node* root, const size_t key) +{ + if (key < root->key) + { + if (root->left == nullptr) + { + root->left = new tree_node{key, nullptr, nullptr, root}; + } + else + { + insert(root->left, key); + } + } + else if (key > root->key) + { + if (root->right == nullptr) + { + root->right = new tree_node{key, nullptr, nullptr, root}; + } + else + { + insert(root->right, key); + } + } +} + +/** + * @brief Returns a pointer to the in-order successor of a given node. + * @note Complexity: O(n) in time, O(1) in space, where n is the number of tree + * nodes. + */ +const tree_node* successor(const tree_node* node) +{ + /* + * if node has a right subtree, its successor is the leftmost node + * of that subtree; if node has no right subtree, its successor can + * only be one of its ancestors + */ + if (node->right != nullptr) + { + const tree_node* current = node->right; + + while (current->left != nullptr) + { + current = current->left; + } + + return current; + } + else + { + const tree_node* current = node->parent; + + while (current != nullptr && current->key < node->key) + { + current = current->parent; + } + + return current; + } + + return nullptr; +} + +/** + * @brief Generates a random binary search tree with n nodes and returns a + * pointer to its root node (the node keys are 0, 1, ..., n-1). + * @note Complexity: O(n²) in time, O(n) in space. + */ +const tree_node* random_binary_search_tree(const size_t n) +{ + if (n == 0) + { + return nullptr; + } + + std::vector keys; + + for (size_t i = 0; i < n; ++i) + { + keys.push_back(i); + } + + static std::random_device device; + static std::mt19937 generator(device()); + + std::shuffle(keys.begin(), keys.end(), generator); + + /* start with the root node */ + tree_node* root = new tree_node{keys[0], nullptr, nullptr, nullptr}; + + for (size_t i = 1; i < n; ++i) + { + insert(root, keys[i]); + } + + return root; +} + +int main() +{ + for (size_t n = 0; n <= 100; ++n) + { + for (int i = 0; i < 1000; ++i) + { + const tree_node* root = random_binary_search_tree(n); + + for (size_t key = 0; key < n; ++key) + { + const tree_node* node = find(root, key); + assert(node != nullptr && node->key == key); + + if (key == n - 1) + { + assert(successor(node) == nullptr); + } + else + { + assert(successor(node)->key == key + 1); + } + } + + delete root; + } + + std::cout << "passed random tests for trees of size " << n << std::endl; + } + + return EXIT_SUCCESS; +} diff --git a/pool/shard002/C++/0024433_RtmpGuesterImpl.cc b/pool/shard002/C++/0024433_RtmpGuesterImpl.cc new file mode 100644 index 0000000000000000000000000000000000000000..db30b7a6e9b2c639106148422fc6db2295bf5b67 --- /dev/null +++ b/pool/shard002/C++/0024433_RtmpGuesterImpl.cc @@ -0,0 +1,107 @@ +/* +* Copyright (c) 2016 The AnyRTC project authors. All Rights Reserved. +* +* Please visit https://www.anyrtc.io for detail. +* +* The GNU General Public License is a free, copyleft license for +* software and other kinds of works. +* +* The licenses for most software and other practical works are designed +* to take away your freedom to share and change the works. By contrast, +* the GNU General Public License is intended to guarantee your freedom to +* share and change all versions of a program--to make sure it remains free +* software for all its users. We, the Free Software Foundation, use the +* GNU General Public License for most of our software; it applies also to +* any other work released this way by its authors. You can apply it to +* your programs, too. +* See the GNU LICENSE file for more info. +*/ +#include "RtmpGuesterImpl.h" + +RTMPGuester* RTMPGuester::Create(RTMPGuesterEvent&callback) +{ + return new RtmpGuesterImpl(callback); +} +void RTMPGuester::Destory(RTMPGuester*guester) +{ + RtmpGuesterImpl* impl = (RtmpGuesterImpl*)guester->GotSelfPtr(); + delete impl; + guester = NULL; +} + +RtmpGuesterImpl::RtmpGuesterImpl(RTMPGuesterEvent&callback) + : callback_(callback) + , worker_thread_(&webrtc::AnyRtmpCore::Inst()) + , av_rtmp_started_(NULL) + , av_rtmp_player_(NULL) + , video_render_(NULL) +{ + av_rtmp_player_ = AnyRtmplayer::Create(*this); +} + + +RtmpGuesterImpl::~RtmpGuesterImpl() +{ + StopRtmpPlay(); + if (av_rtmp_player_ != NULL) { + av_rtmp_player_->StopPlay(); + delete av_rtmp_player_; + av_rtmp_player_ = NULL; + } + + if (video_render_ != NULL) { + delete video_render_; + video_render_ = NULL; + } +} + +//* Rtmp function for pull rtmp stream +void RtmpGuesterImpl::StartRtmpPlay(const char* url, void* render) +{ + if (!av_rtmp_started_) { + rtmp_url_ = url; + av_rtmp_started_ = true; + video_render_ = webrtc::VideoRenderer::Create(render, 640, 480); + av_rtmp_player_->SetVideoRender(video_render_); + av_rtmp_player_->StartPlay(url); + webrtc::AnyRtmpCore::Inst().StartAudioTrack(this); + } +} + +void RtmpGuesterImpl::StopRtmpPlay() +{ + if (av_rtmp_started_) { + av_rtmp_started_ = false; + rtmp_url_ = ""; + webrtc::AnyRtmpCore::Inst().StopAudioTrack(); + av_rtmp_player_->StopPlay(); + if (video_render_ != NULL) { + delete video_render_; + video_render_ = NULL; + } + } +} + +//* For AnyRtmplayerEvent +void RtmpGuesterImpl::OnRtmplayerOK() +{ + callback_.OnRtmplayerOK(); +} +void RtmpGuesterImpl::OnRtmplayerStatus(int cacheTime, int curBitrate) +{ + callback_.OnRtmplayerStatus(cacheTime, curBitrate); +} +void RtmpGuesterImpl::OnRtmplayerCache(int time) +{ + callback_.OnRtmplayerCache(time); +} +void RtmpGuesterImpl::OnRtmplayerClose(int errcode) +{ + callback_.OnRtmplayerClosed(errcode); +} + +//* For webrtc::AVAudioTrackCallback +int RtmpGuesterImpl::OnNeedPlayAudio(void* audioSamples, uint32_t& samplesPerSec, size_t& nChannels) +{ + return ((webrtc::AnyRtmplayerImpl*)av_rtmp_player_)->GetNeedPlayAudio(audioSamples, samplesPerSec, nChannels); +} \ No newline at end of file diff --git a/pool/shard002/C++/0024435_dist1.cpp b/pool/shard002/C++/0024435_dist1.cpp new file mode 100644 index 0000000000000000000000000000000000000000..82019ae8728a6520583db41a79172086b2b3ed1d --- /dev/null +++ b/pool/shard002/C++/0024435_dist1.cpp @@ -0,0 +1,58 @@ +/* The following code example is taken from the book + * "The C++ Standard Library - A Tutorial and Reference, 2nd Edition" + * by Nicolai M. Josuttis, Addison-Wesley, 2012 + * + * (C) Copyright Nicolai M. Josuttis 2012. + * Permission to copy, use, modify, sell and distribute this software + * is granted provided this copyright notice appears in all copies. + * This software is provided "as is" without express or implied + * warranty, and with no claim as to its suitability for any purpose. + */ +#include +#include +#include +#include +#include + +template +void distr (Distr d, Eng e, const std::string& name) +{ + // print min, max and four example values + std::cout << name << ":" << std::endl; + std::cout << "- min(): " << d.min() << std::endl; + std::cout << "- max(): " << d.max() << std::endl; + std::cout << "- values: " << d(e) << ' ' << d(e) << ' ' + << d(e) << ' ' << d(e) << std::endl; + + // count the generated values (converted to integral values) + std::map valuecounter; + for (int i=0; i<200000; ++i) { + valuecounter[d(e)]++; + } + + // and print the resulting distribution + std::cout << "====" << std::endl; + for (auto elem : valuecounter) { + std::cout << std::setw(3) << elem.first << ": " + << elem.second << std::endl; + } + std::cout << "====" << std::endl; + std::cout << std::endl; +} + +int main() +{ + std::knuth_b e; + + std::uniform_real_distribution<> ud(0, 10); + distr(ud,e,"uniform_real_distribution"); + + std::normal_distribution<> nd; + distr(nd,e,"normal_distribution"); + + std::exponential_distribution<> ed; + distr(ed,e,"exponential_distribution"); + + std::gamma_distribution<> gd; + distr(gd,e,"gamma_distribution"); +} diff --git a/pool/shard002/C++/0024438_directory.cpp b/pool/shard002/C++/0024438_directory.cpp new file mode 100644 index 0000000000000000000000000000000000000000..97213fec93352dea901d22d0de7aee2e1fc6fc47 --- /dev/null +++ b/pool/shard002/C++/0024438_directory.cpp @@ -0,0 +1,56 @@ +/** + * @file + * @author shrek0 (shrek0.tk@gmail.com) + * @class + * @section LICENSE + * + * Process copyright (C) 2015 shrek0 + * + * Process 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. + * + * Process 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 . + * + * @section DESCRIPTION + * + */ + +#include "directory.h" + +#include + +Directory::Directory(const std::string &directoryPath) +{ + mPDir = opendir(directoryPath.c_str()); +} + +std::list Directory::getFiles() { + dirent *directoryEntry = nullptr; + std::list files; + + while((directoryEntry = readdir(mPDir)) > 0) + { + files.push_front(*directoryEntry); + } + + return files; +} + +dirent Directory::find(const std::string &entryName) { + dirent *directoryEntry = nullptr; + + while((directoryEntry = readdir(mPDir)) > 0) { + if(entryName == directoryEntry->d_name) + return *directoryEntry; + } + + throw std::invalid_argument("find: Not Found"); +} diff --git a/pool/shard002/C++/0024446_cpredictivesearchsettingstable.cpp b/pool/shard002/C++/0024446_cpredictivesearchsettingstable.cpp new file mode 100644 index 0000000000000000000000000000000000000000..1f00d6f52e6ef7bb2dd6e59174fc739d294beec5 --- /dev/null +++ b/pool/shard002/C++/0024446_cpredictivesearchsettingstable.cpp @@ -0,0 +1,203 @@ +/* +* Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies). +* All rights reserved. +* This component and the accompanying materials are made available +* under the terms of "Eclipse Public License v1.0" +* which accompanies this distribution, and is available +* at the URL "http://www.eclipse.org/legal/epl-v10.html". +* +* Initial Contributors: +* Nokia Corporation - initial contribution. +* +* Contributors: +* +* Description: +* +*/ + +#include "cpredictivesearchsettingstable.h" +#include "dbsqlconstants.h" + +// This macro suppresses log writes +//#define NO_PRED_SEARCH_LOGS +#include "predictivesearchlog.h" + + +_LIT(KSqlContactPredSearchSettingsTable, "pred_search_settings"); + +_LIT(KCreatePredSearchSettingsTable, "CREATE TABLE pred_search_settings (language INTEGER);"); + +_LIT(KPredSearchSettingsLanguage, "language"); + +// How many characters the decimal representation of enum QLocale::Language +// requires. +const TInt KSizeOfLanguageValue = 8; + +//_LIT(KInsertFormat, "INSERT INTO pred_search_settings (language) VALUES (%d);"); +// e.g. "INSERT INTO pred_search_settings (language) VALUES (8);" +_LIT(KInsertFormat, "INSERT INTO %S (%S) VALUES (%d);"); + +// e.g. "UPDATE pred_search_settings SET language = 9;" +_LIT(KUpdateFormat, "UPDATE %S SET %S = %d;"); + +// e.g. "SELECT language FROM pred_search_settings;" +_LIT(KSelectFormat, "SELECT %S FROM %S;"); + + + +CPredictiveSearchSettingsTable* +CPredictiveSearchSettingsTable::NewL(RSqlDatabase& aDatabase) + { + PRINT(_L("CPredictiveSearchSettingsTable::NewL")); + CPredictiveSearchSettingsTable* self = + CPredictiveSearchSettingsTable::NewLC(aDatabase); + CleanupStack::Pop(self); + PRINT(_L("CPredictiveSearchSettingsTable::NewL ends")); + return self; + } + +CPredictiveSearchSettingsTable* +CPredictiveSearchSettingsTable::NewLC(RSqlDatabase& aDatabase) + { + PRINT(_L("CPredictiveSearchSettingsTable::NewLC")); + CPredictiveSearchSettingsTable* self = + new (ELeave) CPredictiveSearchSettingsTable(aDatabase); + CleanupStack::PushL(self); + self->ConstructL(); + PRINT(_L("CPredictiveSearchSettingsTable::NewLC ends")); + return self; + } + +CPredictiveSearchSettingsTable::~CPredictiveSearchSettingsTable() + { + PRINT(_L("CPredictiveSearchSettingsTable dtor")); + PRINT(_L("CPredictiveSearchSettingsTable dtor ends")); + } + +void CPredictiveSearchSettingsTable::CreateInDbL(CContactItem& /*aItem*/) + { + } + +void CPredictiveSearchSettingsTable::UpdateL(const CContactItem& /*aItem*/) + { + } + +void CPredictiveSearchSettingsTable::DeleteL(const CContactItem& /*aItem*/, + TBool& /*aLowDiskErrorOccurred*/) + { + } + +// Create table to an empty database, so there is no need to re-generate QWERTY +// tables. +void CPredictiveSearchSettingsTable::CreateTableL() + { + PRINT(_L("CPredictiveSearchSettingsTable::CreateTableL")); + + User::LeaveIfError(iDatabase.Exec(KCreatePredSearchSettingsTable)); + enum QLocale::Language language = GetCurrentLanguageL(); + HBufC* insert = HBufC::NewLC(KInsertFormat().Length() + + KSqlContactPredSearchSettingsTable().Length() + + KPredSearchSettingsLanguage().Length() + + KSizeOfLanguageValue); + insert->Des().AppendFormat(KInsertFormat, + &KSqlContactPredSearchSettingsTable, + &KPredSearchSettingsLanguage, + language); + User::LeaveIfError(iDatabase.Exec(*insert)); + CleanupStack::PopAndDestroy(insert); + + PRINT(_L("CPredictiveSearchSettingsTable::CreateTableL ends")); + } + +QList CPredictiveSearchSettingsTable::FillAllTables() const + { + QList tables; + tables.append('1'); // Add one character (does not matter what the character is) + return tables; + } + +HBufC* CPredictiveSearchSettingsTable::TableNameL(const QChar /*aCh*/) const + { + return KSqlContactPredSearchSettingsTable().AllocL(); + } + +TBool CPredictiveSearchSettingsTable::IsLanguageValidL() const + { + PRINT(_L("CPredictiveSearchSettingsTable::IsLanguageValidL")); + return ReadStoredLanguageL() == GetCurrentLanguageL(); + } + +void CPredictiveSearchSettingsTable::StoreCurrentLanguageL() const + { + PRINT(_L("CPredictiveSearchSettingsTable::StoreCurrentLanguageL")); + + enum QLocale::Language language = GetCurrentLanguageL(); + HBufC* update = HBufC::NewLC(KUpdateFormat().Length() + + KSqlContactPredSearchSettingsTable().Length() + + KPredSearchSettingsLanguage().Length() + + KSizeOfLanguageValue); + update->Des().AppendFormat(KUpdateFormat, + &KSqlContactPredSearchSettingsTable, + &KPredSearchSettingsLanguage, + language); + User::LeaveIfError(iDatabase.Exec(*update)); + CleanupStack::PopAndDestroy(update); + + PRINT(_L("CPredictiveSearchSettingsTable::StoreCurrentLanguageL ends")); + } + +void CPredictiveSearchSettingsTable::ConstructL() + { + } + +enum QLocale::Language CPredictiveSearchSettingsTable::GetCurrentLanguageL() const + { + enum QLocale::Language language(QLocale::C); + QT_TRYCATCH_LEAVING(language = QLocale::system().language()); + PRINT1(_L("CPredictiveSearchSettingsTable::GetCurrentLanguageL ret=%d"), language); + return language; + } + +enum QLocale::Language CPredictiveSearchSettingsTable::ReadStoredLanguageL() const + { + TInt bufSize = KSelectFormat().Length() + + KPredSearchSettingsLanguage().Length() + + KSqlContactPredSearchSettingsTable().Length(); + HBufC* select = HBufC::NewLC(bufSize); + select->Des().AppendFormat(KSelectFormat, + &KPredSearchSettingsLanguage, + &KSqlContactPredSearchSettingsTable); + + RSqlStatement stmnt; + CleanupClosePushL(stmnt); + PRINT1(_L("CPredictiveSearchSettingsTable::ReadStoredLanguageL SQL:%S"), select); + stmnt.PrepareL(iDatabase, *select); + + const TInt KLanguageIndex = 0; + TInt err = stmnt.Next(); + enum QLocale::Language language(QLocale::C); + if (err == KSqlAtRow) + { + language = static_cast(stmnt.ColumnInt(KLanguageIndex)); + PRINT1(_L("read language=%d from DB"), language); + } + CleanupStack::PopAndDestroy(&stmnt); + CleanupStack::PopAndDestroy(select); + + if (err != KSqlAtRow) + { + PRINT1(_L("CPredictiveSearchSettingsTable::ReadStoredLanguageL err=%d"), err); + User::Leave(err); + } + PRINT1(_L("CPredictiveSearchSettingsTable::ReadStoredLanguageL ret=%d"), language); + return language; + } + +/** +Constructor +*/ +CPredictiveSearchSettingsTable::CPredictiveSearchSettingsTable( + RSqlDatabase& aDatabase) : + CPplPredictiveSearchTableBase(aDatabase, 0, 0) + { + } diff --git a/pool/shard002/C++/0024455_ObjectManager.cpp b/pool/shard002/C++/0024455_ObjectManager.cpp new file mode 100644 index 0000000000000000000000000000000000000000..4b00faa066b8d903c920335577478185312fe9f5 --- /dev/null +++ b/pool/shard002/C++/0024455_ObjectManager.cpp @@ -0,0 +1,85 @@ +#include "ObjectManager.h" +#include +#include +#include "types.h" +#include "Object.h" +#include +#include +//#include "Pond.h" +#include "Camera.h" + +ObjectManager::ObjectManager() +{ + Init(); + //pool = new Pond(this); +} + +bool ObjectManager::Init(){ + distance=0; + return true; +} +bool ObjectManager::Update() +{ + //iterate through the objectList vector and check each collison + + for(std::vector::iterator it=objectList.begin();it!=objectList.end();++it){ + //for each object after this object + Object* a = *it; + /*if(a->type==0){ + continue; + }*/ + for(std::vector::iterator ti=(it + 1);ti!=objectList.end();++ti){ + + Object* b = *ti; + /*if(b->type==0){ + continue; + }*/ + distance = std::sqrt(std::pow((a->position.x+a->velocity.x)-(b->position.x+b->velocity.x),2)+ + std::pow((a->position.y+a->velocity.y)-(b->position.y+b->velocity.y),2)+ + std::pow((a->position.z+a->velocity.z)-(b->position.z+b->velocity.z),2)); + + if(distance<(a->collisionRadius+b->collisionRadius)){ + //we have a collision, set both objects' velocity to 0 + a->velocity.x=0; + a->velocity.y=0; + a->velocity.z=0; + + b->velocity.x=0; + b->velocity.y=0; + b->velocity.z=0; + + } + } + } + //Now we have the correct velocities for each object and can move them. + + for(std::vector::iterator it=objectList.begin();it!=objectList.end();++it){ + Object* a = *it; + /*if(a->type==0){ + a->Update(); + continue; + }*/ + a->position.x=(a->velocity.x)+(a->position.x); + a->position.y=(a->velocity.y)+(a->position.y); + a->position.z=(a->velocity.z)+(a->position.z); + + a->Update(); + } + + return true; +} +bool ObjectManager::addObject(Object* object) +{ + this->objectList.push_back(object); + return true; +} +Object* ObjectManager::getObjectById(char name[]) +{ + for(std::vector::iterator it=objectList.begin();it!=objectList.end();++it){ + Object* a = *it; + if(std::strcmp(name,a->id)==0){ + return a; + } + } + return 0; +} diff --git a/pool/shard002/C++/0024457_Vector4_TEST.cc b/pool/shard002/C++/0024457_Vector4_TEST.cc new file mode 100644 index 0000000000000000000000000000000000000000..5d426c277275611b6d1e573b12c04888e5e998e5 --- /dev/null +++ b/pool/shard002/C++/0024457_Vector4_TEST.cc @@ -0,0 +1,137 @@ +/* + * Copyright (C) 2012-2014 Open Source Robotics Foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * +*/ + +#include + +#include "gazebo/math/Vector4.hh" + +using namespace gazebo; + +TEST(Vector4Test, Vector4) +{ + { + math::Vector4 v; + EXPECT_TRUE(math::equal(v.x, 0.0)); + EXPECT_TRUE(math::equal(v.y, 0.0)); + EXPECT_TRUE(math::equal(v.z, 0.0)); + EXPECT_TRUE(math::equal(v.w, 0.0)); + } + + math::Vector4 v1(1, 2, 3, 4); + EXPECT_TRUE(math::equal(v1.x, 1.0)); + EXPECT_TRUE(math::equal(v1.y, 2.0)); + EXPECT_TRUE(math::equal(v1.z, 3.0)); + EXPECT_TRUE(math::equal(v1.w, 4.0)); + + math::Vector4 v(v1); + EXPECT_TRUE(v == v1); + + EXPECT_TRUE(math::equal(v.Distance(math::Vector4(0, 0, 0, 0)), 5.4772, 1e-3)); + + // ::GetLength() + v.Set(1, 2, 3, 4); + EXPECT_TRUE(math::equal(v.GetLength(), 5.4772, 1e-3)); + + // ::GetSquaredLength() + EXPECT_TRUE(math::equal(v.GetSquaredLength(), 30.0)); + + // ::Normalize + v.Normalize(); + EXPECT_TRUE(v == math::Vector4(0.182574, 0.365148, 0.547723, 0.730297)); + + // ::Set + v.Set(2, 4, 6, 8); + EXPECT_TRUE(v == math::Vector4(2, 4, 6, 8)); + + // ::operator= vector4 + v = v1; + EXPECT_TRUE(v == v1); + + // ::operator= double + v = 1.2; + EXPECT_TRUE(v == math::Vector4(1.2, 1.2, 1.2, 1.2)); + + // ::operator+ vector4 + v = v + math::Vector4(1, 2, 3, 4); + EXPECT_TRUE(v == math::Vector4(2.2, 3.2, 4.2, 5.2)); + + // ::operator+= + v += v; + EXPECT_TRUE(v == math::Vector4(4.4, 6.4, 8.4, 10.4)); + + // ::operator- vector4 + v = v - math::Vector4(1, 1, 1, 1); + EXPECT_TRUE(v == math::Vector4(3.4, 5.4, 7.4, 9.4)); + + // ::operator-= vector4 + v -= math::Vector4(1, 1, 1, 1); + EXPECT_TRUE(v == math::Vector4(2.4, 4.4, 6.4, 8.4)); + + + // ::operator/ vector4 + v = v / math::Vector4(.1, .1, .1, .1); + EXPECT_TRUE(v == math::Vector4(24, 44, 64, 84)); + + // ::operator/ double + v = v / 2.0; + EXPECT_TRUE(v == math::Vector4(12, 22, 32, 42)); + + // ::operator/= vector4 + v /= math::Vector4(4, 4, 4, 4); + EXPECT_TRUE(v == math::Vector4(3, 5.5, 8, 10.5)); + + // ::operator/= double + v /= .1; + EXPECT_TRUE(v == math::Vector4(30, 55, 80, 105)); + + // ::operator * matrix4 + v = v * math::Matrix4(1, 2, 3, 4, + 5, 6, 7, 8, + 9, 10, 11, 12, + 13, 14, 15, 16); + EXPECT_TRUE(v == math::Vector4(2390, 2660, 2930, 3200)); + + + // ::operator * vector4 + v = v * math::Vector4(.2, .3, .4, .5); + EXPECT_TRUE(v == math::Vector4(478, 798, 1172, 1600)); + + // ::operator *= vector4 + v *= math::Vector4(2, 4, 6, 8); + EXPECT_TRUE(v == math::Vector4(956, 3192, 7032, 12800)); + + // ::operator * double + v = v * 5.2; + EXPECT_TRUE(v == math::Vector4(4971.2, 16598.4, 36566.4, 66560)); + + // ::operator *= double + v *= 10.0; + EXPECT_TRUE(v == math::Vector4(49712, 1.65984e+05, 3.65664e+05, 6.656e+05)); + + // ::operator != vector4 + EXPECT_TRUE(v != math::Vector4()); + + // ::IsFinite + EXPECT_TRUE(v.IsFinite()); + + // ::operator[] + v.Set(1, 2, 3, 4); + EXPECT_DOUBLE_EQ(v[0], 1); + EXPECT_DOUBLE_EQ(v[1], 2); + EXPECT_DOUBLE_EQ(v[2], 3); + EXPECT_DOUBLE_EQ(v[3], 4); +} diff --git a/pool/shard002/C++/0024464_CRendererOGLES1_1.cpp b/pool/shard002/C++/0024464_CRendererOGLES1_1.cpp new file mode 100644 index 0000000000000000000000000000000000000000..d1209fd6c751a2ad8f77e629387fcd3cd61df329 --- /dev/null +++ b/pool/shard002/C++/0024464_CRendererOGLES1_1.cpp @@ -0,0 +1,174 @@ +// +// CRendererOGLES1_1.h +// OpenJam +// +// Created by Yevgeniy Logachev +// Copyright (c) 2014 yev. All rights reserved. +// +#if defined(RENDER_OGLES1_1) + +#include "CRendererOGLES1_1.h" + +#include "CVertexBufferOGLES1_1.h" +#include "CIndexBufferOGLES1_1.h" +#include "CMaterialOGLES1_1.h" +#include "CTextureOGLES1_1.h" +#include "CMeshOGLES1_1.h" +#include "CShaderOGLES1_1.h" +#include "CShaderProgramOGLES1_1.h" +#include "CFrameBufferOGLES1_1.h" +#include "CRenderTargetColorOGLES1_1.h" +#include "CRenderTargetDepthOGLES1_1.h" +#include "CRenderTargetStencilOGLES1_1.h" +#include "CRenderTargetTextureOGLES1_1.h" + +using namespace jam; + +// ***************************************************************************** +// Constants +// ***************************************************************************** + +// ***************************************************************************** +// Public Methods +// ***************************************************************************** + +CRendererOGLES1_1::CRendererOGLES1_1(IRenderViewPtr renderView) + : CRendererOGLBase(renderView) +{ +} + +CRendererOGLES1_1::~CRendererOGLES1_1() +{ +} + +IFrameBufferPtr CRendererOGLES1_1::CreateFrameBuffer(uint32_t width, uint32_t height) +{ + IFrameBufferPtr frameBuffer(new CFrameBufferOGLES1_1(width, height)); + return frameBuffer; +} + +CRenderTargetColorPtr CRendererOGLES1_1::CreateColorRenderTarget() +{ + CRenderTargetColorPtr colorTarget(new CRenderTargetColorOGLES1_1()); + return colorTarget; +} + +CRenderTargetDepthPtr CRendererOGLES1_1::CreateDepthRenderTarget() +{ + CRenderTargetDepthPtr depthTarget(new CRenderTargetDepthOGLES1_1()); + return depthTarget; +} + +CRenderTargetStencilPtr CRendererOGLES1_1::CreateStencilRenderTarget() +{ + CRenderTargetStencilPtr stencilTarget(new CRenderTargetStencilOGLES1_1()); + return stencilTarget; +} + +CRenderTargetTexturePtr CRendererOGLES1_1::CreateTextureRenderTarget() +{ + CRenderTargetTexturePtr textureTarget(new CRenderTargetTextureOGLES1_1()); + return textureTarget; +} + +IVertexBufferPtr CRendererOGLES1_1::CreateVertexBuffer() +{ + IVertexBufferPtr vertexBuffer(new CVertexBufferOGLES1_1()); + return vertexBuffer; +} + +IIndexBufferPtr CRendererOGLES1_1::CreateIndexBuffer() +{ + IIndexBufferPtr indexBuffer(new CIndexBufferOGLES1_1()); + return indexBuffer; +} + +ITexturePtr CRendererOGLES1_1::CreateTexture() +{ + ITexturePtr texture(new CTextureOGLES1_1()); + return texture; +} + +IMaterialPtr CRendererOGLES1_1::CreateMaterial() +{ + IMaterialPtr material(new CMaterialOGLES1_1()); + return material; +} + +IMeshPtr CRendererOGLES1_1::CreateMesh() +{ + IMeshPtr mesh(new CMeshOGLES1_1()); + return mesh; +} + +IShaderPtr CRendererOGLES1_1::CreateShader() +{ + IShaderPtr shader(new CShaderOGLES1_1()); + return shader; +} + +IShaderProgramPtr CRendererOGLES1_1::CreateShaderProgram() +{ + IShaderProgramPtr shaderProgram(new CShaderProgramOGLES1_1()); + return shaderProgram; +} + +void CRendererOGLES1_1::Draw(IMeshPtr mesh, IMaterialPtr material, IShaderProgramPtr shader) +{ + if (!mesh || !material) { + return; + } + + const IShaderProgram::TUniMatrix4Float& uniforms = shader->UniformsMatrix4x4f(); + IShaderProgram::TUniMatrix4Float::const_iterator it = uniforms.find(shader->ProjectionMatrix()); + glMatrixMode(GL_PROJECTION); + if (it != uniforms.end()) { + glLoadMatrixf(glm::value_ptr(it->second)); + } else { + glLoadMatrixf(glm::value_ptr(glm::mat4(1.0))); + } + + glMatrixMode(GL_MODELVIEW); + it = uniforms.find(shader->ModelMatrix()); + if (it != uniforms.end()) { + glLoadMatrixf(glm::value_ptr(it->second)); + } else { + glLoadMatrixf(glm::value_ptr(glm::mat4(1.0))); + } + + if (mesh->IndexBuffer()) { + Draw(mesh->VertexBuffer(), mesh->IndexBuffer(), material); + } else { + Draw(mesh->VertexBuffer(), material); + } +} + +void CRendererOGLES1_1::Draw(IVertexBufferPtr vertexBuffer, IMaterialPtr material) +{ + if (!vertexBuffer || !material) { + return; + } + + int primitiveType = ConvertPrimitiveType(material->PrimitiveType()); + glDrawArrays(primitiveType, 0, (GLsizei)vertexBuffer->Size()); +} + +void CRendererOGLES1_1::Draw(IVertexBufferPtr vertexBuffer, IIndexBufferPtr indexBuffer, IMaterialPtr material) +{ + if (!vertexBuffer || !indexBuffer || !material) { + return; + } + + int primitiveType = ConvertPrimitiveType(material->PrimitiveType()); + glDrawElements(primitiveType, (GLsizei)indexBuffer->Size(), GL_UNSIGNED_SHORT, nullptr); +} + +// ***************************************************************************** +// Protected Methods +// ***************************************************************************** + +// ***************************************************************************** +// Private Methods +// ***************************************************************************** + +#endif /* defined(RENDER_OGLES1_1) */ diff --git a/pool/shard002/C++/0024468_rpc_stream.cpp b/pool/shard002/C++/0024468_rpc_stream.cpp new file mode 100644 index 0000000000000000000000000000000000000000..7e8b1ffc8fa043ff648762e4652f4f06b43cd501 --- /dev/null +++ b/pool/shard002/C++/0024468_rpc_stream.cpp @@ -0,0 +1,87 @@ + + +#include "rpc_stream.h" + +//extern Serial pc; + +void stream_init() +{ + +} + +char stream_read() +{ + int c = getchar(); + if (c == EOF) return '\r'; + return c; +} + +bool stream_write(char c) +{ + return putchar(c); +} + +bool stream_write_string(char *str, int len) +{ + for (int i = 0; str[i] && i < len; i++) + { + stream_write(str[i]); + } +} + +void writer_print(type_t type, const void *data, bool append_comma) +{ + char buff[32]; + switch (type) + { + case TYPE_BOOL: + case TYPE_UINT8: + sprintf(buff, "%hhu", *(uint8_t *)data); + break; + case TYPE_UINT16: + sprintf(buff, "%u", *(uint16_t *)data); + break; + case TYPE_UINT32: + sprintf(buff, "%lu", *(uint32_t *)data); + break; + case TYPE_INT8: + sprintf(buff, "%hhd", *(int8_t *)data); + break; + case TYPE_INT: + sprintf(buff, "%d", *(int *)data); + break; + case TYPE_INT16: + sprintf(buff, "%d", *(int16_t *)data); + break; + case TYPE_INT32: + sprintf(buff, "%ld", *(int32_t *)data); + break; + case TYPE_FLOAT: + sprintf(buff, "%f", *(float *)data); + break; + case TYPE_STRING: + stream_write('"'); + stream_write_string((char *)data, 32); + stream_write('"'); + return; + default: + break; + } + stream_write_string(buff, 32); + if(append_comma) stream_write(','); +} + +void response_msg_open(char *msg_type) +{ + char *msg1 = "{\"msg_type\":\""; + char *msg2 = "\", \"msg\":\""; + stream_write_string(msg1, strlen(msg1)); + stream_write_string(msg_type, strlen(msg_type)); + stream_write_string(msg2, strlen(msg2)); +} + +void response_msg_close() +{ + char *msg3 = "\"}\r\n"; + stream_write_string(msg3, strlen(msg3)); +} diff --git a/pool/shard002/C++/0024470_CheckBox.cpp b/pool/shard002/C++/0024470_CheckBox.cpp new file mode 100644 index 0000000000000000000000000000000000000000..3ba1e3b64f5d8e1cdc90fe7d1e53388a95ddce02 --- /dev/null +++ b/pool/shard002/C++/0024470_CheckBox.cpp @@ -0,0 +1,150 @@ +#include "CheckBox.h" +#include "../GUIFactory.h" + +CheckBox::CheckBox(GUIFactory* factory, MouseController* mouseController, + unique_ptr unchkdSprite, unique_ptr chckdSprite, + const pugi::char_t* font) : GUIControl(factory, mouseController) { + + uncheckedSprite = move(unchkdSprite); + checkedSprite = move(chckdSprite); + + uncheckedSprite->setOrigin(Vector2(0, 0)); + checkedSprite->setOrigin(Vector2(0, 0)); + Vector2 size = Vector2((float) uncheckedSprite->getWidth(), (float) uncheckedSprite->getHeight()); + + hitArea.size = size; + + label.reset(guiFactory->createTextLabel(Vector2::Zero, L"", font)); + + texture = uncheckedSprite->getTexture(); + currentRECT = uncheckedSprite->getRect(); +} + +CheckBox::~CheckBox() { + + if (actionListener != NULL) + delete actionListener; + +} + +void CheckBox::reloadGraphicsAsset() { + texture.Reset(); + uncheckedSprite->reloadGraphicsAsset(guiFactory); + checkedSprite->reloadGraphicsAsset(guiFactory); + label->reloadGraphicsAsset(); + + if (isClicked) { + texture = checkedSprite->getTexture(); + currentRECT = checkedSprite->getRect(); + } else { + texture = uncheckedSprite->getTexture(); + currentRECT = uncheckedSprite->getRect(); + } +} +#include "../StringHelper.h" +bool CheckBox::update(double deltaTime) { + + refreshed = false; + if (hitArea.contains(mouse->getPosition()) || label->contains(mouse->getPosition())) { + + if (!isHover) { + isHover = true; + onHover(); + } + } else if (isHover) { + resetState(); + isHover = false; + } + + if (isHover) { + if (mouse->pressed()) { + isClicked = !isClicked; + onClick(); + } + } + if (label->update(deltaTime)) + refreshed = true; + + return refreshed; +} + +void CheckBox::draw(SpriteBatch* batch) { + + batch->Draw(texture.Get(), position, ¤tRECT, tint, rotation, + origin, scale, SpriteEffects_None, layerDepth); + label->draw(batch); +} + + +void CheckBox::setFont(const pugi::char_t* font) { + label->setFont(guiFactory->getFont(font)); +} + + +void CheckBox::setText(wstring text) { + label->setText(text); + centerText(); +} + + +void CheckBox::setPosition(const Vector2& pos) { + + GUIControl::setPosition(pos); + + uncheckedSprite->setPosition(position); + checkedSprite->setPosition(position); + + centerText(); +} + + +void CheckBox::setChecked(bool checked) { + isClicked = checked; +} + +void CheckBox::centerText() { + + Vector2 labelSize = label->measureString(); + labelOffset.y = (getHeight() - labelSize.y) / 2; + + Vector2 labelPos = position; + labelPos.x += labelOffset.x + getWidth(); + labelPos.y += labelOffset.y; + label->setPosition(labelPos); +} + +void CheckBox::setScale(const Vector2& scl) { + + GUIControl::setScale(scl); + uncheckedSprite->setScale(scale); + checkedSprite->setScale(scale); +} + + +const Vector2 XM_CALLCONV CheckBox::measureString() const { + return label->measureString(); +} + +const Vector2& CheckBox::getPosition() const { + return position; +} + +const int CheckBox::getWidth() const { + return uncheckedSprite->getWidth(); +} + +const int CheckBox::getHeight() const { + return uncheckedSprite->getHeight(); +} + +bool CheckBox::clicked() { + return isClicked; +} + +bool CheckBox::pressed() { + return isPressed; +} + +bool CheckBox::hovering() { + return isHover; +} diff --git a/pool/shard002/C++/0024474_cs_lfg.cpp b/pool/shard002/C++/0024474_cs_lfg.cpp new file mode 100644 index 0000000000000000000000000000000000000000..88cd64e0680d304c222d7c9ce650929748e0d9a1 --- /dev/null +++ b/pool/shard002/C++/0024474_cs_lfg.cpp @@ -0,0 +1,169 @@ +/* + * Copyright (C) 2008-2017 TrinityCore + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the + * Free Software Foundation; either version 2 of the License, or (at your + * option) any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + * + * You should have received a copy of the GNU General Public License along + * with this program. If not, see . + */ + +#include "ScriptMgr.h" +#include "Chat.h" +#include "DatabaseEnv.h" +#include "Group.h" +#include "GroupMgr.h" +#include "Language.h" +#include "LFGMgr.h" +#include "ObjectAccessor.h" +#include "ObjectMgr.h" +#include "Player.h" +#include "RBAC.h" + +void GetPlayerInfo(ChatHandler* handler, Player* player) +{ + if (!player) + return; + + ObjectGuid guid = player->GetGUID(); + lfg::LfgDungeonSet dungeons = sLFGMgr->GetSelectedDungeons(guid); + + std::string const& state = lfg::GetStateString(sLFGMgr->GetState(guid)); + handler->PSendSysMessage(LANG_LFG_PLAYER_INFO, player->GetName().c_str(), + state.c_str(), uint8(dungeons.size()), lfg::ConcatenateDungeons(dungeons).c_str(), + lfg::GetRolesString(sLFGMgr->GetRoles(guid)).c_str()); +} + +class lfg_commandscript : public CommandScript +{ +public: + lfg_commandscript() : CommandScript("lfg_commandscript") { } + + std::vector GetCommands() const override + { + static std::vector lfgCommandTable = + { + { "player", rbac::RBAC_PERM_COMMAND_LFG_PLAYER, false, &HandleLfgPlayerInfoCommand, "" }, + { "group", rbac::RBAC_PERM_COMMAND_LFG_GROUP, false, &HandleLfgGroupInfoCommand, "" }, + { "queue", rbac::RBAC_PERM_COMMAND_LFG_QUEUE, true, &HandleLfgQueueInfoCommand, "" }, + { "clean", rbac::RBAC_PERM_COMMAND_LFG_CLEAN, true, &HandleLfgCleanCommand, "" }, + { "options", rbac::RBAC_PERM_COMMAND_LFG_OPTIONS, true, &HandleLfgOptionsCommand, "" }, + }; + + static std::vector commandTable = + { + { "lfg", rbac::RBAC_PERM_COMMAND_LFG, true, NULL, "", lfgCommandTable }, + }; + return commandTable; + } + + static bool HandleLfgPlayerInfoCommand(ChatHandler* handler, char const* args) + { + Player* target = NULL; + std::string playerName; + if (!handler->extractPlayerTarget((char*)args, &target, NULL, &playerName)) + return false; + + GetPlayerInfo(handler, target); + return true; + } + + static bool HandleLfgGroupInfoCommand(ChatHandler* handler, char const* args) + { + Player* playerTarget; + ObjectGuid guidTarget; + std::string nameTarget; + + ObjectGuid parseGUID = ObjectGuid::Create(uint64(atoull(args))); + + if (sObjectMgr->GetPlayerNameByGUID(parseGUID, nameTarget)) + { + playerTarget = ObjectAccessor::FindPlayer(parseGUID); + guidTarget = parseGUID; + } + else if (!handler->extractPlayerTarget((char*)args, &playerTarget, &guidTarget, &nameTarget)) + return false; + + Group* groupTarget = NULL; + + if (playerTarget) + groupTarget = playerTarget->GetGroup(); + else + { + PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_GROUP_MEMBER); + stmt->setUInt32(0, guidTarget.GetCounter()); + PreparedQueryResult resultGroup = CharacterDatabase.Query(stmt); + if (resultGroup) + groupTarget = sGroupMgr->GetGroupByDbStoreId((*resultGroup)[0].GetUInt32()); + } + if (!groupTarget) + { + handler->PSendSysMessage(LANG_LFG_NOT_IN_GROUP, nameTarget.c_str()); + handler->SetSentErrorMessage(true); + return false; + } + + ObjectGuid guid = groupTarget->GetGUID(); + std::string const& state = lfg::GetStateString(sLFGMgr->GetState(guid)); + handler->PSendSysMessage(LANG_LFG_GROUP_INFO, groupTarget->isLFGGroup(), + state.c_str(), sLFGMgr->GetDungeon(guid)); + + Group::MemberSlotList const& members = groupTarget->GetMemberSlots(); + + for (Group::MemberSlotList::const_iterator itr = members.begin(); itr != members.end(); ++itr) + { + Group::MemberSlot const& slot = *itr; + Player* p = ObjectAccessor::FindPlayer((*itr).guid); + if (p) + GetPlayerInfo(handler, p); + else + handler->PSendSysMessage("%s is offline.", slot.name.c_str()); + } + + return true; + } + + static bool HandleLfgOptionsCommand(ChatHandler* handler, char const* args) + { + int32 options = -1; + if (char* str = strtok((char*)args, " ")) + { + int32 tmp = atoi(str); + if (tmp > -1) + options = tmp; + } + + if (options != -1) + { + sLFGMgr->SetOptions(options); + handler->PSendSysMessage(LANG_LFG_OPTIONS_CHANGED); + } + handler->PSendSysMessage(LANG_LFG_OPTIONS, sLFGMgr->GetOptions()); + return true; + } + + static bool HandleLfgQueueInfoCommand(ChatHandler* handler, char const* args) + { + handler->SendSysMessage(sLFGMgr->DumpQueueInfo(*args != '\0').c_str(), true); + return true; + } + + static bool HandleLfgCleanCommand(ChatHandler* handler, char const* /*args*/) + { + handler->PSendSysMessage(LANG_LFG_CLEAN); + sLFGMgr->Clean(); + return true; + } +}; + +void AddSC_lfg_commandscript() +{ + new lfg_commandscript(); +} diff --git a/pool/shard002/C++/0024479_audio_hash_unittest.cc b/pool/shard002/C++/0024479_audio_hash_unittest.cc new file mode 100644 index 0000000000000000000000000000000000000000..b020fe93e58245746c359e0addcd572afe89565e --- /dev/null +++ b/pool/shard002/C++/0024479_audio_hash_unittest.cc @@ -0,0 +1,168 @@ +// Copyright 2013 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "base/logging.h" +#include "base/macros.h" +#include "media/base/audio_bus.h" +#include "media/base/audio_hash.h" +#include "media/base/fake_audio_render_callback.h" +#include "testing/gtest/include/gtest/gtest.h" + +namespace media { + +static const int kChannelCount = 2; +static const int kFrameCount = 1024; + +class AudioHashTest : public testing::Test { + public: + AudioHashTest() + : bus_one_(AudioBus::Create(kChannelCount, kFrameCount)), + bus_two_(AudioBus::Create(kChannelCount, kFrameCount)), + fake_callback_(0.01) { + + // Fill each channel in each bus with unique data. + GenerateUniqueChannels(bus_one_.get()); + GenerateUniqueChannels(bus_two_.get()); + } + + void GenerateUniqueChannels(AudioBus* audio_bus) { + // Use an AudioBus wrapper to avoid an extra memcpy when filling channels. + scoped_ptr wrapped_bus = AudioBus::CreateWrapper(1); + wrapped_bus->set_frames(audio_bus->frames()); + + // Since FakeAudioRenderCallback generates only a single channel of unique + // audio data, we need to fill each channel manually. + for (int ch = 0; ch < audio_bus->channels(); ++ch) { + wrapped_bus->SetChannelData(0, audio_bus->channel(ch)); + fake_callback_.Render(wrapped_bus.get(), 0, 0); + } + } + + ~AudioHashTest() override {} + + protected: + scoped_ptr bus_one_; + scoped_ptr bus_two_; + FakeAudioRenderCallback fake_callback_; + + DISALLOW_COPY_AND_ASSIGN(AudioHashTest); +}; + +// Ensure the same data hashes the same. +TEST_F(AudioHashTest, Equivalence) { + AudioHash hash_one; + hash_one.Update(bus_one_.get(), bus_one_->frames()); + + AudioHash hash_two; + hash_two.Update(bus_one_.get(), bus_one_->frames()); + + EXPECT_EQ(hash_one.ToString(), hash_two.ToString()); +} + +// Ensure sample order matters to the hash. +TEST_F(AudioHashTest, SampleOrder) { + AudioHash original_hash; + original_hash.Update(bus_one_.get(), bus_one_->frames()); + + // Swap a sample in the bus. + std::swap(bus_one_->channel(0)[0], bus_one_->channel(0)[1]); + + AudioHash swapped_hash; + swapped_hash.Update(bus_one_.get(), bus_one_->frames()); + + EXPECT_NE(original_hash.ToString(), swapped_hash.ToString()); +} + +// Ensure channel order matters to the hash. +TEST_F(AudioHashTest, ChannelOrder) { + AudioHash original_hash; + original_hash.Update(bus_one_.get(), bus_one_->frames()); + + // Reverse channel order for the same sample data. + const int channels = bus_one_->channels(); + scoped_ptr swapped_ch_bus = AudioBus::CreateWrapper(channels); + swapped_ch_bus->set_frames(bus_one_->frames()); + for (int i = channels - 1; i >= 0; --i) + swapped_ch_bus->SetChannelData(channels - (i + 1), bus_one_->channel(i)); + + AudioHash swapped_hash; + swapped_hash.Update(swapped_ch_bus.get(), swapped_ch_bus->frames()); + + EXPECT_NE(original_hash.ToString(), swapped_hash.ToString()); +} + +// Ensure bus order matters to the hash. +TEST_F(AudioHashTest, BusOrder) { + AudioHash original_hash; + original_hash.Update(bus_one_.get(), bus_one_->frames()); + original_hash.Update(bus_two_.get(), bus_two_->frames()); + + AudioHash reordered_hash; + reordered_hash.Update(bus_two_.get(), bus_two_->frames()); + reordered_hash.Update(bus_one_.get(), bus_one_->frames()); + + EXPECT_NE(original_hash.ToString(), reordered_hash.ToString()); +} + +// Ensure bus order matters to the hash even with empty buses. +TEST_F(AudioHashTest, EmptyBusOrder) { + bus_one_->Zero(); + bus_two_->Zero(); + + AudioHash one_bus_hash; + one_bus_hash.Update(bus_one_.get(), bus_one_->frames()); + + AudioHash two_bus_hash; + two_bus_hash.Update(bus_one_.get(), bus_one_->frames()); + two_bus_hash.Update(bus_two_.get(), bus_two_->frames()); + + EXPECT_NE(one_bus_hash.ToString(), two_bus_hash.ToString()); +} + +// Where A = [0, n], ensure hash(A[0:n/2]), hash(A[n/2:n]) and hash(A) result +// in the same value. +TEST_F(AudioHashTest, HashIgnoresUpdateOrder) { + AudioHash full_hash; + full_hash.Update(bus_one_.get(), bus_one_->frames()); + + AudioHash half_hash; + half_hash.Update(bus_one_.get(), bus_one_->frames() / 2); + + // Create a new bus representing the second half of |bus_one_|. + const int half_frames = bus_one_->frames() / 2; + const int channels = bus_one_->channels(); + scoped_ptr half_bus = AudioBus::CreateWrapper(channels); + half_bus->set_frames(half_frames); + for (int i = 0; i < channels; ++i) + half_bus->SetChannelData(i, bus_one_->channel(i) + half_frames); + + half_hash.Update(half_bus.get(), half_bus->frames()); + EXPECT_EQ(full_hash.ToString(), half_hash.ToString()); +} + +// Ensure approximate hashes pass verification. +TEST_F(AudioHashTest, VerifySimilarHash) { + AudioHash hash_one; + hash_one.Update(bus_one_.get(), bus_one_->frames()); + + // Twiddle the values inside the first bus. + float* channel = bus_one_->channel(0); + for (int i = 0; i < bus_one_->frames(); i += bus_one_->frames() / 64) + channel[i] += 0.0001f; + + AudioHash hash_two; + hash_two.Update(bus_one_.get(), bus_one_->frames()); + + EXPECT_EQ(hash_one.ToString(), hash_two.ToString()); + + // Twiddle the values too much... + for (int i = 0; i < bus_one_->frames(); ++i) + channel[i] += 0.0001f; + + AudioHash hash_three; + hash_three.Update(bus_one_.get(), bus_one_->frames()); + EXPECT_NE(hash_one.ToString(), hash_three.ToString()); +} + +} // namespace media diff --git a/pool/shard002/C++/0024484_iwBuildingProductivities.cpp b/pool/shard002/C++/0024484_iwBuildingProductivities.cpp new file mode 100644 index 0000000000000000000000000000000000000000..3ff8af44e8b0f95bca0fcb780bca136fa980ef48 --- /dev/null +++ b/pool/shard002/C++/0024484_iwBuildingProductivities.cpp @@ -0,0 +1,98 @@ +// Copyright (c) 2005 - 2017 Settlers Freaks (sf-team at siedler25.org) +// +// This file is part of Return To The Roots. +// +// Return To The Roots is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 2 of the License, or +// (at your option) any later version. +// +// Return To The Roots is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License +// along with Return To The Roots. If not, see . + +#include "rttrDefines.h" // IWYU pragma: keep +#include "iwBuildingProductivities.h" +#include "GamePlayer.h" +#include "Loader.h" +#include "files.h" +#include "gameData/BuildingConsts.h" +#include "gameData/const_gui_ids.h" +#include "libutil/colors.h" + +/// Reihenfolge der Gebäude +const std::array bts = { + BLD_GRANITEMINE, BLD_COALMINE, BLD_IRONMINE, BLD_GOLDMINE, BLD_WOODCUTTER, BLD_FISHERY, BLD_QUARRY, BLD_FORESTER, + BLD_SLAUGHTERHOUSE, BLD_HUNTER, BLD_BREWERY, BLD_ARMORY, BLD_METALWORKS, BLD_IRONSMELTER, BLD_PIGFARM, BLD_MILL, + BLD_BAKERY, BLD_SAWMILL, BLD_MINT, BLD_WELL, BLD_SHIPYARD, BLD_FARM, BLD_DONKEYBREEDER, BLD_CHARBURNER}; + +/// Abstand vom linken, oberen Fensterrand +const Extent bldProdContentOffset(50, 30); +/// Abstand vom rechten Fensterrand +const unsigned short right_x = 40; +/// Horizontaler Abstand zwischen Bild und Prozentbar +const unsigned short image_percent_x = 35; +/// Horizontaler Abstand zwischen Prozentbar und nächstem Bild +const unsigned short percent_image_x = 40; +/// Vertikaler Abstand zwischen 2 nacheinanderfolgenden "Zeilen" +const unsigned short distance_y = 35; + +/// Größe der Prozentbalken +const Extent percentSize(100, 18); + +iwBuildingProductivities::iwBuildingProductivities(const GamePlayer& player) + : IngameWindow(CGI_BUILDINGSPRODUCTIVITY, IngameWindow::posLastOrCenter, + Extent(2 * percentSize.x + 2 * image_percent_x + percent_image_x + right_x, (bts.size() / 2 + 1) * (distance_y + 1)) + + bldProdContentOffset, + _("Productivity"), LOADER.GetImageN("resource", 41)), + player(player), percents(NUM_BUILDING_TYPES, 0) +{ + const Nation playerNation = player.nation; + for(unsigned y = 0; y < bts.size() / 2 + bts.size() % 2; ++y) + { + for(unsigned x = 0; x < 2; ++x) + { + if(y * 2 + x >= bts.size()) //-V547 + break; + unsigned imgId = (y * 2 + x) * 2; + DrawPoint imgPos(x * (percent_image_x + percentSize.x + image_percent_x), distance_y * y + percentSize.y / 2); + imgPos = imgPos + bldProdContentOffset; + if(player.IsBuildingEnabled(bts[y * 2 + x])) + { + glArchivItem_Bitmap* img; + if(bts[y * 2 + x] != BLD_CHARBURNER) + img = LOADER.GetImageN(NATION_ICON_IDS[playerNation], bts[y * 2 + x]); + else + img = LOADER.GetImageN("charburner", playerNation * 8 + 8); + AddImage(imgId, imgPos, img, _(BUILDING_NAMES[bts[y * 2 + x]])); + DrawPoint percentPos(image_percent_x + x * (percent_image_x + percentSize.x + image_percent_x), distance_y * y); + AddPercent(imgId + 1, percentPos + bldProdContentOffset, percentSize, TC_GREY, COLOR_YELLOW, SmallFont, + &percents[bts[y * 2 + x]]); + } else + AddImage(imgId, imgPos, LOADER.GetImageN("io", 188)); + } + } + + UpdatePercents(); + + // Hilfe-Button + // Original S2 does not have a Help button in this window. Add it if you have something to say. + // AddImageButton(500, GetSize().x - 14 - 30, GetSize().y - 20 - 32, 30, 32, TC_GREY, LOADER.GetImageN("io", 225), _("Help")); +} + +/// Aktualisieren der Prozente +void iwBuildingProductivities::UpdatePercents() +{ + player.GetBuildingRegister().CalcProductivities(percents); +} + +/// Produktivitäts-percentbars aktualisieren +void iwBuildingProductivities::Msg_PaintAfter() +{ + IngameWindow::Msg_PaintAfter(); + UpdatePercents(); +} diff --git a/pool/shard002/C++/0024488_billboards.cpp b/pool/shard002/C++/0024488_billboards.cpp new file mode 100644 index 0000000000000000000000000000000000000000..20e0f86134776da9e6508b85efe20ab78667ec4a --- /dev/null +++ b/pool/shard002/C++/0024488_billboards.cpp @@ -0,0 +1,156 @@ +// Copyright (C) 2008-2012 Colin MacDonald +// No rights reserved: this software is in the public domain. + +#include "testUtils.h" + +using namespace irr; + +namespace +{ +// Test billboard sizing +bool billboardSize(void) +{ + // Use EDT_BURNINGSVIDEO since it is not dependent on (e.g.) OpenGL driver versions. + IrrlichtDevice *device = createDevice(video::EDT_BURNINGSVIDEO, core::dimension2d(160, 120), 32); + assert_log(device); + if (!device) + return false; + + video::IVideoDriver* driver = device->getVideoDriver(); + scene::ISceneManager * smgr = device->getSceneManager(); + + smgr->addCameraSceneNode(); + scene::IBillboardSceneNode* bill = smgr->addBillboardSceneNode(); + bill->setPosition(core::vector3df(0,0,50)); + bill = smgr->addBillboardSceneNode(); + bill->setPosition(core::vector3df(-30,0,50)); + bill->getMaterial(0).Lighting=false; + bill = smgr->addBillboardSceneNode(); + bill->setPosition(core::vector3df(30,0,50)); + bill->getMaterial(0).Lighting=false; + bill->getMaterial(0).Wireframe=true; + bill = smgr->addBillboardSceneNode(); + bill->setPosition(core::vector3df(30,0,50)); + bill->setSize(2,2,2); + + bill = smgr->addBillboardSceneNode(); + bill->setSize(10,20,2); + bill->setPosition(core::vector3df(0,30,50)); + bill = smgr->addBillboardSceneNode(); + bill->setSize(10,2,20); + bill->setPosition(core::vector3df(-30,30,50)); + bill->getMaterial(0).Lighting=false; + bill = smgr->addBillboardSceneNode(); + bill->setSize(10,2,20); + bill->setPosition(core::vector3df(30,30,50)); + bill->getMaterial(0).Lighting=false; + bill->getMaterial(0).Wireframe=true; + bill = smgr->addBillboardSceneNode(); + bill->setPosition(core::vector3df(30,30,50)); + bill->setSize(2,2,2); + + video::ITexture* tex = driver->getTexture("../media/fireball.bmp"); + bill = smgr->addBillboardSceneNode(); + bill->getMaterial(0).Lighting=false; + bill->getMaterial(0).TextureLayer[0].AnisotropicFilter=true; + bill->getMaterial(0).setTexture(0, tex); + bill->setSize(10,20,2); + bill->setPosition(core::vector3df(0,-30,50)); + bill = smgr->addBillboardSceneNode(); + bill->setSize(10,2,20); + bill->setPosition(core::vector3df(-30,-30,50)); + bill->getMaterial(0).TextureLayer[0].AnisotropicFilter=true; + bill->getMaterial(0).setTexture(0, tex); + bill->getMaterial(0).Lighting=false; + bill = smgr->addBillboardSceneNode(); + bill->setSize(10,2,20); + bill->setPosition(core::vector3df(30,-30,50)); + bill->getMaterial(0).TextureLayer[0].AnisotropicFilter=true; + bill->getMaterial(0).setTexture(0, tex); + bill->getMaterial(0).Lighting=false; + bill->getMaterial(0).Wireframe=true; + bill = smgr->addBillboardSceneNode(); + bill->setPosition(core::vector3df(30,-30,50)); + bill->setSize(2,2,2); + + bill = smgr->addBillboardSceneNode(); + bill->getMaterial(0).Lighting=false; + bill->getMaterial(0).setTexture(0, tex); + bill->setSize(10,20,14); + bill->setPosition(core::vector3df(0,-15,50)); + bill = smgr->addBillboardSceneNode(); + bill->setSize(10,14,20); + bill->setPosition(core::vector3df(-30,-15,50)); + bill->getMaterial(0).setTexture(0, tex); + bill->getMaterial(0).Lighting=false; + bill = smgr->addBillboardSceneNode(); + bill->setSize(10,14,20); + bill->setPosition(core::vector3df(30,-15,50)); + bill->getMaterial(0).setTexture(0, tex); + bill->getMaterial(0).Lighting=false; + bill->getMaterial(0).Wireframe=true; + bill = smgr->addBillboardSceneNode(); + bill->setPosition(core::vector3df(30,-15,50)); + bill->setSize(2,2,2); + + bool result = false; + + device->run(); + driver->beginScene(true, true, video::SColor(255, 60, 60, 60)); + smgr->drawAll(); + driver->endScene(); + + result = takeScreenshotAndCompareAgainstReference(driver, "-billboard.png"); + + device->closeDevice(); + device->run(); + device->drop(); + + return result; +} + +// Test billboard orientation +// Should generate a properly readable (i.e. not mirrored or flipped) +// font file display. +bool billboardOrientation(void) +{ + // Use EDT_BURNINGSVIDEO since it is not dependent on (e.g.) OpenGL driver versions. + IrrlichtDevice *device = createDevice(video::EDT_BURNINGSVIDEO, core::dimension2d(160, 120), 32); + assert_log(device); + if (!device) + return false; + + video::IVideoDriver* driver = device->getVideoDriver(); + scene::ISceneManager * smgr = device->getSceneManager(); + + smgr->addCameraSceneNode(); + scene::IBillboardSceneNode* bill = smgr->addBillboardSceneNode(0, core::dimension2df(40,40)); + bill->setPosition(core::vector3df(0,-15,10)); + bill->getMaterial(0).Lighting=false; + bill->getMaterial(0).setTexture(0, driver->getTexture("../media/fontcourier.bmp")); + + bool result = false; + + device->run(); + driver->beginScene(true, true, video::SColor(255, 60, 60, 60)); + smgr->drawAll(); + driver->endScene(); + + result = takeScreenshotAndCompareAgainstReference(driver, "-billboardOrientation.png"); + + device->closeDevice(); + device->run(); + device->drop(); + + return result; +} + +} // end anonymous namespace + +// Test billboards +bool billboards(void) +{ + bool result = billboardSize(); + result &= billboardOrientation(); + return result; +} diff --git a/pool/shard002/C++/0024490_sighash_tests.cpp b/pool/shard002/C++/0024490_sighash_tests.cpp new file mode 100644 index 0000000000000000000000000000000000000000..9784e4abfb773f1f7596a1086c68a645778bc3d8 --- /dev/null +++ b/pool/shard002/C++/0024490_sighash_tests.cpp @@ -0,0 +1,217 @@ +// Copyright (c) 2013 The BeCoin Core developers +// Distributed under the MIT software license, see the accompanying +// file COPYING or http://www.opensource.org/licenses/mit-license.php. + +#include "consensus/validation.h" +#include "data/sighash.json.h" +#include "hash.h" +#include "main.h" // For CheckTransaction +#include "random.h" +#include "script/interpreter.h" +#include "script/script.h" +#include "serialize.h" +#include "streams.h" +#include "test/test_becoin.h" +#include "util.h" +#include "utilstrencodings.h" +#include "version.h" + +#include + +#include + +#include "univalue/univalue.h" + +extern UniValue read_json(const std::string& jsondata); + +// Old script.cpp SignatureHash function +uint256 static SignatureHashOld(CScript scriptCode, const CTransaction& txTo, unsigned int nIn, int nHashType) +{ + static const uint256 one(uint256S("0000000000000000000000000000000000000000000000000000000000000001")); + if (nIn >= txTo.vin.size()) + { + printf("ERROR: SignatureHash(): nIn=%d out of range\n", nIn); + return one; + } + CMutableTransaction txTmp(txTo); + + // In case concatenating two scripts ends up with two codeseparators, + // or an extra one at the end, this prevents all those possible incompatibilities. + scriptCode.FindAndDelete(CScript(OP_CODESEPARATOR)); + + // Blank out other inputs' signatures + for (unsigned int i = 0; i < txTmp.vin.size(); i++) + txTmp.vin[i].scriptSig = CScript(); + txTmp.vin[nIn].scriptSig = scriptCode; + + // Blank out some of the outputs + if ((nHashType & 0x1f) == SIGHASH_NONE) + { + // Wildcard payee + txTmp.vout.clear(); + + // Let the others update at will + for (unsigned int i = 0; i < txTmp.vin.size(); i++) + if (i != nIn) + txTmp.vin[i].nSequence = 0; + } + else if ((nHashType & 0x1f) == SIGHASH_SINGLE) + { + // Only lock-in the txout payee at same index as txin + unsigned int nOut = nIn; + if (nOut >= txTmp.vout.size()) + { + printf("ERROR: SignatureHash(): nOut=%d out of range\n", nOut); + return one; + } + txTmp.vout.resize(nOut+1); + for (unsigned int i = 0; i < nOut; i++) + txTmp.vout[i].SetNull(); + + // Let the others update at will + for (unsigned int i = 0; i < txTmp.vin.size(); i++) + if (i != nIn) + txTmp.vin[i].nSequence = 0; + } + + // Blank out other inputs completely, not recommended for open transactions + if (nHashType & SIGHASH_ANYONECANPAY) + { + txTmp.vin[0] = txTmp.vin[nIn]; + txTmp.vin.resize(1); + } + + // Serialize and hash + CHashWriter ss(SER_GETHASH, 0); + ss << txTmp << nHashType; + return ss.GetHash(); +} + +void static RandomScript(CScript &script) { + static const opcodetype oplist[] = {OP_FALSE, OP_1, OP_2, OP_3, OP_CHECKSIG, OP_IF, OP_VERIF, OP_RETURN, OP_CODESEPARATOR}; + script = CScript(); + int ops = (insecure_rand() % 10); + for (int i=0; i> tx; + + CValidationState state; + BOOST_CHECK_MESSAGE(CheckTransaction(tx, state), strTest); + BOOST_CHECK(state.IsValid()); + + std::vector raw = ParseHex(raw_script); + scriptCode.insert(scriptCode.end(), raw.begin(), raw.end()); + } catch (...) { + BOOST_ERROR("Bad test, couldn't deserialize data: " << strTest); + continue; + } + + sh = SignatureHash(scriptCode, tx, nIn, nHashType); + BOOST_CHECK_MESSAGE(sh.GetHex() == sigHashHex, strTest); + } +} +BOOST_AUTO_TEST_SUITE_END() diff --git a/pool/shard002/C++/0024496_WKBundleFileHandle_Bundle.cpp b/pool/shard002/C++/0024496_WKBundleFileHandle_Bundle.cpp new file mode 100644 index 0000000000000000000000000000000000000000..76c4af7b527f7b79875c2919b272bc9526ddfdeb --- /dev/null +++ b/pool/shard002/C++/0024496_WKBundleFileHandle_Bundle.cpp @@ -0,0 +1,99 @@ +/* + * Copyright (C) 2015 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. AND ITS 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 APPLE INC. OR ITS 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" + +#if WK_HAVE_C_SPI + +#include "InjectedBundleTest.h" + +#include "PlatformUtilities.h" +#include +#include +#include +#include + +namespace TestWebKitAPI { + +static WKBundlePageRef loadedPage; + +class WKBundleFileHandleTest : public InjectedBundleTest { +public: + WKBundleFileHandleTest(const std::string& identifier) + : InjectedBundleTest(identifier) + { + } + +private: + virtual void didReceiveMessage(WKBundleRef bundle, WKStringRef messageName, WKTypeRef messageBody) override + { + if (!WKStringIsEqualToUTF8CString(messageName, "TestFile")) { + WKBundlePostMessage(bundle, Util::toWK("FAIL").get(), Util::toWK("Recieved invalid message").get()); + return; + } + + if (!loadedPage) { + WKBundlePostMessage(bundle, Util::toWK("FAIL").get(), Util::toWK("No loaded page").get()); + return; + } + + if (WKGetTypeID(messageBody) != WKStringGetTypeID()) { + WKBundlePostMessage(bundle, Util::toWK("FAIL").get(), Util::toWK("Message body has invalid type").get()); + return; + } + + WKBundleFrameRef mainFrame = WKBundlePageGetMainFrame(loadedPage); + WKBundleScriptWorldRef world = WKBundleScriptWorldNormalWorld(); + + JSGlobalContextRef globalContext = WKBundleFrameGetJavaScriptContextForWorld(mainFrame, world); + + auto fileHandle = adoptWK(WKBundleFileHandleCreateWithPath((WKStringRef)messageBody)); + JSValueRef jsFileHandle = WKBundleFrameGetJavaScriptWrapperForFileForWorld(mainFrame, fileHandle.get(), world); + + JSObjectRef globalObject = JSContextGetGlobalObject(globalContext); + + JSStringRef jsString = JSStringCreateWithUTF8CString("testFile"); + JSValueRef function = JSObjectGetProperty(globalContext, globalObject, jsString, nullptr); + JSStringRelease(jsString); + + JSValueRef result = JSObjectCallAsFunction(globalContext, (JSObjectRef)function, globalObject, 1, &jsFileHandle, nullptr); + + if (JSValueToBoolean(globalContext, result)) + WKBundlePostMessage(bundle, Util::toWK("SUCCESS").get(), nullptr); + else + WKBundlePostMessage(bundle, Util::toWK("FAIL").get(), Util::toWK("Script failed").get()); + } + + virtual void didCreatePage(WKBundleRef bundle, WKBundlePageRef page) override + { + loadedPage = page; + } +}; + +static InjectedBundleTest::Register registrar("WKBundleFileHandleTest"); + +} // namespace TestWebKitAPI + +#endif diff --git a/pool/shard002/C++/0024497_virtual_machine.cpp b/pool/shard002/C++/0024497_virtual_machine.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c950038d477d0cef9e7d22d54d8eadfb45b6dde0 --- /dev/null +++ b/pool/shard002/C++/0024497_virtual_machine.cpp @@ -0,0 +1,93 @@ +// Copyright (C) 2016 Tomoyuki Fujimori +// +// This file is part of dromozoa-prl. +// +// dromozoa-prl 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. +// +// dromozoa-prl 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 dromozoa-prl. If not, see . + +#include "common.hpp" + +namespace dromozoa { + namespace { + void impl_connect_to_vm(lua_State* L) { + PRL_HANDLE handle = PrlDevDisplay_ConnectToVm( + check_handle(L, 1), + luaX_opt_enum(L, 2, PDCT_HIGH_QUALITY_WITHOUT_COMPRESSION)); + if (handle == PRL_INVALID_HANDLE) { + push_error(L, PRL_ERR_INVALID_HANDLE); + } else { + new_handle(L, handle); + } + } + + void impl_disconnect_from_vm(lua_State* L) { + PRL_RESULT result = PrlDevDisplay_DisconnectFromVm(check_handle(L, 1)); + if (PRL_SUCCEEDED(result)) { + luaX_push_success(L); + } else { + push_error(L, result); + } + } + + void impl_get_config(lua_State* L) { + PRL_HANDLE handle = PRL_INVALID_HANDLE; + PRL_RESULT result = PrlVm_GetConfig(check_handle(L, 1), &handle); + if (PRL_SUCCEEDED(result)) { + new_handle(L, handle); + } else { + push_error(L, result); + } + } + + void impl_send_key_event_ex(lua_State* L) { + PRL_RESULT result = PrlDevKeyboard_SendKeyEventEx( + check_handle(L, 1), + luaX_check_enum(L, 2), + luaX_check_enum(L, 3)); + if (PRL_SUCCEEDED(result)) { + luaX_push_success(L); + } else { + push_error(L, result); + } + } + + void impl_send_key_pressed_and_released(lua_State* L) { + PRL_RESULT result = PrlDevKeyboard_SendKeyPressedAndReleased( + check_handle(L, 1), + luaX_check_enum(L, 2)); + if (PRL_SUCCEEDED(result)) { + luaX_push_success(L); + } else { + push_error(L, result); + } + } + } + + void initialize_virtual_machine(lua_State* L) { + lua_newtable(L); + { + if (PHT_VIRTUAL_MACHINE == PHT_VM_CONFIGURATION) { + inherit_handle(L, "dromozoa.prl.virtual_machine", "dromozoa.prl.vm_configuration"); + } else { + inherit_handle(L, "dromozoa.prl.virtual_machine"); + } + + luaX_set_field(L, -1, "connect_to_vm", impl_connect_to_vm); + luaX_set_field(L, -1, "disconnect_from_vm", impl_disconnect_from_vm); + luaX_set_field(L, -1, "get_config", impl_get_config); + luaX_set_field(L, -1, "send_key_event_ex", impl_send_key_event_ex); + luaX_set_field(L, -1, "send_key_pressed_and_released", impl_send_key_pressed_and_released); + } + luaX_set_field(L, -2, "virtual_machine"); + } +} diff --git a/pool/shard002/C++/0024502_RullerSplliterWnd.cpp b/pool/shard002/C++/0024502_RullerSplliterWnd.cpp new file mode 100644 index 0000000000000000000000000000000000000000..6e71269088602b4c7fe5ee16510982d8edd77439 --- /dev/null +++ b/pool/shard002/C++/0024502_RullerSplliterWnd.cpp @@ -0,0 +1,87 @@ +// RullerSplliterWnd.cpp : implementation file +// + +#include "stdafx.h" +#include "RadarDataShow.h" +#include "RullerSplliterWnd.h" + +#include "RulerView.h" +#include "CornerView.h" +#include "AscanView.h" +#ifdef _DEBUG +#define new DEBUG_NEW +#undef THIS_FILE +static char THIS_FILE[] = __FILE__; +#endif + +///////////////////////////////////////////////////////////////////////////// +// CRullerSplliterWnd +IMPLEMENT_DYNCREATE(CRullerSplliterWnd, CMDIChildWnd) +CRullerSplliterWnd::CRullerSplliterWnd() +{ + m_cxSplitter = 0; + m_cySplitter = 0; + m_cxBorderShare = 0; + m_cyBorderShare = 0; + m_cxSplitterGap = 1; + m_cySplitterGap = 1; + +} + +CRullerSplliterWnd::~CRullerSplliterWnd() +{ +} + + +BEGIN_MESSAGE_MAP(CRullerSplliterWnd, CSplitterWnd) + //{{AFX_MSG_MAP(CRullerSplliterWnd) + // NOTE - the ClassWizard will add and remove mapping macros here. + //}}AFX_MSG_MAP +END_MESSAGE_MAP() + +///////////////////////////////////////////////////////////////////////////// +// CRullerSplliterWnd message handlers +BOOL CRullerSplliterWnd::CreateRulers(CFrameWnd *pParent, CCreateContext *pContext) +{ + if (!CreateStatic(pParent, 2, 3)) //Á½ÐÐÈýÁÐ + return FALSE; + if (!CreateView(0, 0, RUNTIME_CLASS(CCornerView), CSize(0,0), pContext))//×óÉϽÇÊÓͼ + return FALSE; + if (!CreateView(0, 2, RUNTIME_CLASS(CCornerView), CSize(0,0), pContext))//ÓÒÉϽÇÊÓͼ + return FALSE; + if (!CreateView(0, 1, RUNTIME_CLASS(CRulerView), CSize(0,0), pContext)) //ˮƽ±ê³ßÊÓͼ + return FALSE; + if (!CreateView(1, 0, RUNTIME_CLASS(CRulerView), CSize(0,0), pContext))//´¹Ö±±ê³ßÊÓͼ + return FALSE; + if (!CreateView(1, 1, pContext->m_pNewViewClass, CSize(0,0),pContext)) //ͼÏñÊÓͼ + return FALSE; + if (!CreateView(1, 2, RUNTIME_CLASS(CAscanView), CSize(0,0), pContext)) //²¨ÐÎÊÓͼ + return FALSE; + SetColumnInfo(0, 0, 0); + SetColumnInfo(1, 0, 0); + SetRowInfo(0, 0, 0); + ((CRulerView*)GetPane(0, 1))->SetRulerType(RT_HORIZONTAL);//Ö¸¶¨Ë®Æ½±ê³ß + ((CRulerView*)GetPane(1, 0))->SetRulerType(RT_VERTICAL);//Ö¸¶¨´¹Ö±±ê³ß + SetActivePane(1, 1); //½«Í¼Ïñ´°¸ñÉèÖÃΪ»î¶¯ÊÓͼ + return TRUE; +} + +void CRullerSplliterWnd::ShowRulers() +{ + int nSize = 16;//±ê³ß´°¸ñµÄ³ß´ç + int nSizeBorder = 3;//·Ö¸îÌõ³ß´ç + + SetRowInfo(0, nSize, 0);//ˮƽ±ê³ß´°¸ñ¸ß¶È + SetColumnInfo(0, nSize, 0);//´¹Ö±±ê³ß´°¸ñ¿í¶È + SetColumnInfo(1,(GetSystemMetrics(SM_CXSCREEN)-128), 0);//ÉèÖÃͼÏñÏÔʾ´°¿Ú³ß´ç + m_cxSplitterGap = nSizeBorder;//·Ö¸îÌõ³ß´ç + m_cySplitterGap = nSizeBorder; + RecalcLayout();//ÖØÐÂÅÅÁд°¸ñ +} + +void CRullerSplliterWnd::UpdateRulersInfo(stRULER_INFO stRulerInfo) +{ + + ((CRulerView*)GetPane(0, 1))->UpdateRulersInfo(stRulerInfo);//¸üÐÂˮƽ±ê³ß + ((CRulerView*)GetPane(1, 0))->UpdateRulersInfo(stRulerInfo);//¸üд¹Ö±±ê³ß +} diff --git a/pool/shard002/C++/0024504_1_.cpp b/pool/shard002/C++/0024504_1_.cpp new file mode 100644 index 0000000000000000000000000000000000000000..36ee582112fb6b17b372970d0c679339ac22a966 --- /dev/null +++ b/pool/shard002/C++/0024504_1_.cpp @@ -0,0 +1,19 @@ +int main() { + static int mu[N], is_prime[N]; + fill(is_prime, is_prime + MAXV, true); + mu[1] = 1; + vector primes; + for (int i = 2; i < MAXV; i++) { + if (is_prime[i]) { + primes.push_back(i); mu[i] = -1; + } + for (auto p : primes) { + if (1LL * i * p >= MAXV) break; + is_prime[p * i] = false; + if (i % p == 0) { + mu[i * p] = 0; break; + } else { mu[i * p] = -mu[i]; } + } + } + return 0; +} diff --git a/pool/shard002/C++/0024508_mission_list_model.cpp b/pool/shard002/C++/0024508_mission_list_model.cpp new file mode 100644 index 0000000000000000000000000000000000000000..33cb4a3a55c73d32d905d2118250630cbf9228cd --- /dev/null +++ b/pool/shard002/C++/0024508_mission_list_model.cpp @@ -0,0 +1,75 @@ +#include "mission_list_model.h" + +// Qt +#include + +// Internal +#include "mission.h" + +using namespace presentation; + +MissionListModel::MissionListModel(QObject* parent): + QAbstractListModel(parent) +{} + +int MissionListModel::rowCount(const QModelIndex& parent) const +{ + Q_UNUSED(parent) + + return m_missions.count(); +} + +QVariant MissionListModel::data(const QModelIndex& index, int role) const +{ + if (!index.isValid() || index.row() >= m_missions.count()) return QVariant(); + + dto::MissionPtr mission = m_missions.at(index.row()); + + switch (role) + { + case MissionIdRole: return mission->id(); + case MissionNameRole: return mission->name(); + default: return QVariant(); + } +} + +void MissionListModel::setMissions(const dto::MissionPtrList& missions) +{ + this->beginResetModel(); + m_missions = missions; + this->endResetModel(); +} + +void MissionListModel::addMission(const dto::MissionPtr& mission) +{ + this->beginInsertRows(QModelIndex(), this->rowCount(), this->rowCount()); + m_missions.append(mission); + this->endInsertRows(); +} + +void MissionListModel::updateMission(const dto::MissionPtr& mission) +{ + QModelIndex index = this->index(m_missions.indexOf(mission)); + if (!index.isValid()) return; + + emit dataChanged(index, index, { MissionNameRole }); +} + +void MissionListModel::removeMission(const dto::MissionPtr& mission) +{ + int row = m_missions.indexOf(mission); + + this->beginRemoveRows(QModelIndex(), row, row); + m_missions.removeOne(mission); + this->endRemoveRows(); +} + +QHash MissionListModel::roleNames() const +{ + QHash roles; + + roles[MissionIdRole] = "missionId"; + roles[MissionNameRole] = "missionName"; + + return roles; +} diff --git a/pool/shard002/C++/0024511_snipPartMerger.cpp b/pool/shard002/C++/0024511_snipPartMerger.cpp new file mode 100644 index 0000000000000000000000000000000000000000..cd779ab829d11cd3e7c6d8fd0dde53b8b5ff9354 --- /dev/null +++ b/pool/shard002/C++/0024511_snipPartMerger.cpp @@ -0,0 +1,121 @@ +//################################################################################################## +// +// Custom Visualization Core library +// Copyright (C) 2011-2013 Ceetron AS +// +// This library may be used under the terms of either the GNU General Public License or +// the GNU Lesser General Public License as follows: +// +// GNU General Public License Usage +// 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 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 General Public License at <> +// for more details. +// +// GNU Lesser General Public License Usage +// 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 at <> +// for more details. +// +//################################################################################################## + + +#include "cvfLibCore.h" +#include "cvfLibRender.h" +#include "cvfLibViewing.h" + +#include "snipPartMerger.h" + +#include "cvfuPartCompoundGenerator.h" + +namespace snip { + + +//-------------------------------------------------------------------------------------------------- +/// +//-------------------------------------------------------------------------------------------------- +bool PartMerger::onInitialize() +{ + PartCompoundGenerator gen; + gen.setPartDistribution(Vec3i(10, 10, 1)); + gen.setNumEffects(8); + gen.useRandomEffectAssignment(false); + gen.setExtent(Vec3f(3,3,3)); + gen.setOrigin(Vec3f(-1.5f, -1.5f, -1.5f)); + gen.setNumDrawableGeos(10); + + Collection parts; + gen.generateSpheres(7, 7, &parts); + + gen.setPartDistribution(Vec3i(5, 1, 1)); + gen.generateBoxes(&parts); + + + ref myModel = new ModelBasicTree; + ModelBasicTreeNode* root = new ModelBasicTreeNode; + + size_t i = 0; + myModel->setRoot(root); + root->addPart(parts[i++].p()); + + ModelBasicTreeNode* c11 = new ModelBasicTreeNode; + root->addChild(c11); + c11->addPart(parts[i++].p()); + + ModelBasicTreeNode* c12 = new ModelBasicTreeNode; + root->addChild(c12); + c12->addPart(parts[i++].p()); + c12->addPart(parts[i++].p()); + c12->addPart(parts[i++].p()); + c12->addPart(parts[i++].p()); + + ModelBasicTreeNode* c21 = new ModelBasicTreeNode; + c11->addChild(c21); + + size_t j; + for (j = i; j < parts.size(); j++) + { + c21->addPart(parts[j].p()); + } + + myModel->updateBoundingBoxesRecursive(); + +// ModelStatistics stats; +// stats = myModel->computeStatistics(); +// stats.showLog("before merge"); +// + myModel->mergeParts(2, 200000); + +// stats = myModel->computeStatistics(); +// stats.showLog("after merge"); + + myModel->updateBoundingBoxesRecursive(); + m_renderSequence->rendering(0)->scene()->addModel(myModel.p()); + + BoundingBox bb = myModel->boundingBox(); + if (bb.isValid()) + { + m_camera->fitView(bb, -Vec3d::Z_AXIS, Vec3d::Y_AXIS); + } + + return true; +} + + +} // namespace snip + diff --git a/pool/shard002/C++/0024513_EnumParameterType.cpp b/pool/shard002/C++/0024513_EnumParameterType.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8cca7d7463e0385cefa7ce8eab36b8c27a93b703 --- /dev/null +++ b/pool/shard002/C++/0024513_EnumParameterType.cpp @@ -0,0 +1,350 @@ +/* + * Copyright (c) 2011-2014, Intel Corporation + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this + * list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation and/or + * other materials provided with the distribution. + * + * 3. Neither the name of the copyright holder nor the names of its contributors + * may be used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR + * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +#include "EnumParameterType.h" +#include +#include +#include +#include +#include +#include "ParameterAccessContext.h" +#include "EnumValuePair.h" +#include + +#define base CParameterType + +using std::string; + +CEnumParameterType::CEnumParameterType(const string& strName) : base(strName) +{ +} + +string CEnumParameterType::getKind() const +{ + return "EnumParameter"; +} + +bool CEnumParameterType::childrenAreDynamic() const +{ + return true; +} + +// Element properties +void CEnumParameterType::showProperties(string& strResult) const +{ + base::showProperties(strResult); + + strResult += "Value Pairs:\n"; + + // Show all value pairs + size_t uiChild; + size_t uiNbChildren = getNbChildren(); + + for (uiChild = 0; uiChild < uiNbChildren; uiChild++) { + + const CEnumValuePair* pValuePair = static_cast(getChild(uiChild)); + + strResult += "\tLiteral: \""; + strResult += pValuePair->getName(); + strResult += "\", Numerical: "; + strResult += pValuePair->getNumericalAsString(); + strResult += "\n"; + } +} + +bool CEnumParameterType::fromXml(const CXmlElement& xmlElement, CXmlSerializingContext& serializingContext) +{ + // Size in bits + uint32_t uiSizeInBits = xmlElement.getAttributeInteger("Size"); + + // Size + setSize(uiSizeInBits / 8); + + // Base + return base::fromXml(xmlElement, serializingContext); +} + +// Conversion (tuning) +bool CEnumParameterType::toBlackboard(const string& strValue, uint32_t& uiValue, CParameterAccessContext& parameterAccessContext) const +{ + int64_t iData; + + if (isNumber(strValue)) { + + /// Numerical value provided + + // Hexa + bool bValueProvidedAsHexa = !strValue.compare(0, 2, "0x"); + + errno = 0; + char *pcStrEnd; + + // Get value + iData = strtoll(strValue.c_str(), &pcStrEnd, 0); + + // Conversion error when the input string does not contain any digit or the number is out of range (int32_t type) + bool bConversionSucceeded = !errno && (strValue.c_str() != pcStrEnd); + + // Check validity against type + if (!checkValueAgainstRange(strValue, iData, parameterAccessContext, bValueProvidedAsHexa, bConversionSucceeded)) { + + return false; + } + + if (bValueProvidedAsHexa) { + + // Sign extend + signExtend(iData); + } + + // Check validity against lexical space + string strError; + if (!isValid(iData, parameterAccessContext)) { + + parameterAccessContext.setError(strError); + + return false; + } + } else { + /// Literal value provided + + // Check validity against lexical space + int iNumerical; + if (!getNumerical(strValue, iNumerical)) { + + parameterAccessContext.setError("Provided value not part of lexical space"); + + return false; + } + iData = iNumerical; + + // Check validity against type + if (!checkValueAgainstRange(strValue, iData, parameterAccessContext, false, isEncodable((uint64_t)iData, true))) { + + return false; + } + } + + // Return data + uiValue = (uint32_t)iData; + + return true; +} + +// Range checking +bool CEnumParameterType::checkValueAgainstRange(const string& strValue, int64_t value, CParameterAccessContext& parameterAccessContext, bool bHexaValue, bool bConversionSucceeded) const +{ + // Enums are always signed, it means we have one less util bit + int64_t maxValue = getMaxValue(); + int64_t minValue = -maxValue - 1; + + if (!bConversionSucceeded || value < minValue || value > maxValue) { + + std::ostringstream strStream; + + strStream << "Value " << strValue << " standing out of admitted range ["; + + if (bHexaValue) { + + // Format Min + strStream << "0x" << std::hex << std::uppercase << std::setw(getSize()*2) << std::setfill('0') << makeEncodable(minValue); + // Format Max + strStream << ", 0x" << std::hex << std::uppercase << std::setw(getSize()*2) << std::setfill('0') << makeEncodable(maxValue); + + } else { + + strStream << minValue << ", " << maxValue; + } + + strStream << "] for " << getKind(); + + parameterAccessContext.setError(strStream.str()); + + return false; + } + return true; +} + +bool CEnumParameterType::fromBlackboard(string& strValue, const uint32_t& uiValue, CParameterAccessContext& parameterAccessContext) const +{ + // Take care of format + if (parameterAccessContext.valueSpaceIsRaw()) { + + // Format + std::ostringstream strStream; + + // Numerical format requested + if (parameterAccessContext.outputRawFormatIsHex()) { + + // Hexa display with unecessary bits cleared out + strStream << "0x" << std::hex << std::uppercase << std::setw(getSize()*2) << std::setfill('0') << makeEncodable(uiValue); + + strValue = strStream.str(); + } else { + + // Integer display + int32_t iValue = uiValue; + + // Sign extend + signExtend(iValue); + + strStream << iValue; + + strValue = strStream.str(); + } + } else { + + // Integer display + int32_t iValue = uiValue; + + // Sign extend + signExtend(iValue); + + // Literal display requested (should succeed) + getLiteral(iValue, strValue); + } + return true; +} + +// Value access +bool CEnumParameterType::toBlackboard(int32_t iUserValue, uint32_t& uiValue, CParameterAccessContext& parameterAccessContext) const +{ + if (!isValid(iUserValue, parameterAccessContext)) { + + return false; + } + uiValue = iUserValue; + + return true; +} + +bool CEnumParameterType::fromBlackboard(int32_t& iUserValue, uint32_t uiValue, CParameterAccessContext& parameterAccessContext) const +{ + (void)parameterAccessContext; + + int32_t iValue = uiValue; + + // Sign extend + signExtend(iValue); + + iUserValue = iValue; + + return true; +} + +// Default value handling (simulation only) +uint32_t CEnumParameterType::getDefaultValue() const +{ + if (!getNbChildren()) { + + return 0; + } + + // Return first available numerical + return static_cast(getChild(0))->getNumerical(); +} + +// Check string is a number +bool CEnumParameterType::isNumber(const string& strValue) +{ + char cFirst = strValue[0]; + + return isdigit(cFirst) || cFirst == '+' || cFirst == '-'; +} + +// Literal - numerical conversions +bool CEnumParameterType::getLiteral(int32_t iNumerical, string& strLiteral) const +{ + size_t uiChild; + size_t uiNbChildren = getNbChildren(); + + for (uiChild = 0; uiChild < uiNbChildren; uiChild++) { + + const CEnumValuePair* pValuePair = static_cast(getChild(uiChild)); + + if (pValuePair->getNumerical() == iNumerical) { + + strLiteral = pValuePair->getName(); + + return true; + } + } + + return false; +} + +bool CEnumParameterType::getNumerical(const string& strLiteral, int& iNumerical) const +{ + size_t uiChild; + size_t uiNbChildren = getNbChildren(); + + for (uiChild = 0; uiChild < uiNbChildren; uiChild++) { + + const CEnumValuePair* pValuePair = static_cast(getChild(uiChild)); + + if (pValuePair->getName() == strLiteral) { + + iNumerical = pValuePair->getNumerical(); + + return true; + } + } + + return false; +} + +// Numerical validity of the enum value +bool CEnumParameterType::isValid(int iNumerical, CParameterAccessContext& parameterAccessContext) const +{ + // Check that the value is part of the allowed values for this kind of enum + size_t uiChild; + size_t uiNbChildren = getNbChildren(); + + for (uiChild = 0; uiChild < uiNbChildren; uiChild++) { + + const CEnumValuePair* pValuePair = static_cast(getChild(uiChild)); + + if (pValuePair->getNumerical() == iNumerical) { + + return true; + } + } + + parameterAccessContext.setError("Provided value not part of numerical space"); + + return false; +} +// From IXmlSource +void CEnumParameterType::toXml(CXmlElement& xmlElement, CXmlSerializingContext& serializingContext) const +{ + // Size + xmlElement.setAttributeString("Size", toString(getSize() * 8)); + + base::toXml(xmlElement, serializingContext); +} diff --git a/pool/shard002/C++/0024522_NuiMayaMeshGenerator.cpp b/pool/shard002/C++/0024522_NuiMayaMeshGenerator.cpp new file mode 100644 index 0000000000000000000000000000000000000000..3c424dd22a5b9362d4db761adfe112e3131bce34 --- /dev/null +++ b/pool/shard002/C++/0024522_NuiMayaMeshGenerator.cpp @@ -0,0 +1,341 @@ +#include "NuiMayaMeshGenerator.h" +#include "NuiMayaMeshData.h" +#include "../api_macros.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +//////////////////////////////////////////////////////////////////////////////// +// +// Shape implementation +// +//////////////////////////////////////////////////////////////////////////////// + +MObject NuiMayaMeshGenerator::aInputData; +MObject NuiMayaMeshGenerator::aOutputMesh; +MObject NuiMayaMeshGenerator::aBodyIndex; +MObject NuiMayaMeshGenerator::aAssignUV; + +MTypeId NuiMayaMeshGenerator::id( 0x80190 ); + +NuiMayaMeshGenerator::NuiMayaMeshGenerator() + : fNeedDirty(true) +{} +NuiMayaMeshGenerator::~NuiMayaMeshGenerator() {} + +/////////////////////////////////////////////////////////////////////////////// +// +// Overrides +// +/////////////////////////////////////////////////////////////////////////////// + +/* override */ +MStatus NuiMayaMeshGenerator::compute( const MPlug& plug, MDataBlock& datablock ) +// +// Description +// +// When input attributes are dirty this method will be called to +// recompute the output attributes. +// +{ + MStatus stat; + if ( plug == aOutputMesh /*&& fNeedDirty*/) { + // Create some mesh data and access the + // geometry so we can set it + // + MFnMeshData dataCreator; + MObject newOutputData = dataCreator.create(&stat); + MCHECKERROR(stat, "ERROR creating outputData"); + + // If there is an input mesh then copy it's values + // and construct some apiMeshGeom for it. + // + stat = computeOutputMesh( plug, datablock, newOutputData); + if(stat != MS::kSuccess) + { + createEmptyMesh( newOutputData ); + } + // Assign the new data to the outputSurface handle + // + MDataHandle outHandle = datablock.outputValue( aOutputMesh ); + outHandle.set( newOutputData ); + datablock.setClean( plug ); + // Clear the flag. + fNeedDirty = false; + return MS::kSuccess; + } + else { + return MS::kUnknownParameter; + } +} + +void NuiMayaMeshGenerator::createEmptyMesh( MObject& out_empytMesh ) +{ + MStatus status; + MFnMeshData meshData; + out_empytMesh = meshData.create( &status ); + CHECK_MSTATUS( status ); + + MFloatPointArray vertexArray; + MIntArray polygonCounts; + MIntArray polygonConnects; + + MFnMesh meshCreator; + MObject newMeshObject = meshCreator.create( + 0, // nb vertices + 0, // nb triangles + vertexArray, + polygonCounts, + polygonConnects, + out_empytMesh ); +} + + +MStatus NuiMayaMeshGenerator::assignMeshUV( MObject& meshData, const MIntArray& polygonCounts, const MIntArray& uvIds ) +{ + + MStatus stat = MS::kSuccess; + MString uvSetName("uvset1"); + MFnMesh meshFn(meshData); + stat = meshFn.getCurrentUVSetName(uvSetName); + if ( stat != MS::kSuccess ) + { + uvSetName = MString ("uvset1"); + stat = meshFn.createUVSet(uvSetName); + stat = meshFn.setCurrentUVSetName(uvSetName); + } + + //stat = meshFn.clearUVs(); + //stat = meshFn.setUVs(uArray,vArray,&uvSetName); + stat = meshFn.assignUVs(polygonCounts, uvIds, &uvSetName); + if(stat != MS::kSuccess) + MGlobal::displayError( " Failed to assign UVs." ); + return stat; +} + +MStatus NuiMayaMeshGenerator::computeOutputMesh( + const MPlug& plug, + MDataBlock& datablock, + MObject& meshData) +// +// Description +// +// This function takes an input surface of type kMeshData and converts +// the geometry into this nodes attributes. +// Returns kFailure if nothing is connected. +// +{ + MStatus stat; + + MDataHandle inputHandle = datablock.inputValue( aInputData, &stat ); + MCHECKERROR( stat, "computeInputSurface error getting inputSurface") + + // Check if anything is connected + // + MObject thisObj = thisMObject(); + MPlug surfPlug( thisObj, aInputData ); + if ( !surfPlug.isConnected() ) { + stat = datablock.setClean( plug ); + MCHECKERROR( stat, "compute setClean" ) + return MS::kFailure; + } + + NuiMayaMeshData* surf = (NuiMayaMeshData*) inputHandle.asPluginData(); + if ( NULL == surf ) { + cerr << "NULL inputCloudData data found\n"; + return MS::kFailure; + } + + NuiMeshShape* geomPtr = surf->data().get(); + if ( NULL == geomPtr ) { + cerr << "NULL pointCloudGeom found\n"; + return MS::kFailure; + } + + double distanceUnit = 1.0; + MDistance::Unit currentUnit = MDistance::internalUnit(); + if(currentUnit != MDistance::kInvalid) + { + distanceUnit = MDistance(1.0, MDistance::kMeters).as(currentUnit); + } + else + { + MGlobal::displayError( " Invalid distance unit." ); + return MS::kFailure; + } + + MFloatPointArray vertexArray; + MIntArray polygonCounts; + MIntArray polygonConnects; + MFloatArray uArray; + MFloatArray vArray; + MIntArray uvIds; + + const UINT numPoints = (UINT)geomPtr->pointsNum(); + for (UINT i = 0; i < numPoints; ++i) + { + const SgVec3f& pt = geomPtr->getPoint(i); + MPoint pnt(pt[0], pt[1], pt[2]); + vertexArray.append(pnt); + + const SgVec2f& uv = geomPtr->getUV(i); + uArray.append(uv[0]); + vArray.append(uv[1]); + uvIds.append(i); + } + const UINT numTris = (UINT)geomPtr->trianglesNum(); + for (UINT i = 0; i < numTris; ++i) + { + int index1 = geomPtr->triangleIndex(3*i); + int index2 = geomPtr->triangleIndex(3*i+1); + int index3 = geomPtr->triangleIndex(3*i+2); + if(index1 < 0 || index2 < 0 || index3 < 0) + continue; + + polygonConnects.append(index1); + polygonConnects.append(index2); + polygonConnects.append(index3); + polygonCounts.append(3); + } + + MFnMesh meshFn; + meshFn.create(vertexArray.length(), polygonCounts.length(), vertexArray, polygonCounts, polygonConnects, uArray, vArray, meshData, &stat); + + bool needAssignUV = true; + /*inputHandle = datablock.inputValue( aAssignUV, &stat ); + if(stat == MS::kSuccess) + needAssignUV = inputHandle.asBool();*/ + if(needAssignUV) + // assignMeshUV(meshData, polygonCounts, uvIds); + { + MString uvSetName("uvset1"); + /*MFnMesh meshFn(meshData); + stat = meshFn.getCurrentUVSetName(uvSetName); + if ( stat != MS::kSuccess ) + { + uvSetName = MString ("uvset1"); + stat = meshFn.createUVSet(uvSetName); + stat = meshFn.setCurrentUVSetName(uvSetName); + } + + stat = meshFn.clearUVs(); + stat = meshFn.setUVs(uArray,vArray,&uvSetName);*/ + stat = meshFn.assignUVs(polygonCounts, uvIds, &uvSetName); + if(stat != MS::kSuccess) + MGlobal::displayError( " Failed to assign UVs." ); + } + return stat; +} + +/* override */ +// +// Description +// +// Horribly abuse the purpose of this method to notify the Viewport 2.0 +// renderer that something about this shape has changed and that it should +// be retranslated. +// +MStatus NuiMayaMeshGenerator::setDependentsDirty( const MPlug& plug, MPlugArray& plugArray) +{ + // if the dirty attribute is the output mesh then we need to signal the + // the renderer that it needs to update the object + + /*if ( plug == aInputPointCloud) + { + fNeedDirty = true; + }*/ + return MS::kSuccess; +} + +MStatus NuiMayaMeshGenerator::connectionMade( const MPlug& plug, + const MPlug& otherPlug, + bool asSrc ) +// +// Description +// +// Whenever a connection to this node is broken, this method +// will get called. +// +{ + if ( plug == aInputData ) { + fNeedDirty = true; + } + + return MPxNode::connectionBroken( plug, otherPlug, asSrc ); +} + +void* NuiMayaMeshGenerator::creator() +// +// Description +// Called internally to create a new instance of the users MPx node. +// +{ + return new NuiMayaMeshGenerator(); +} + +MStatus NuiMayaMeshGenerator::initialize() +// +// Description +// +// Attribute (static) initialization. See api_macros.h. +// +{ + MStatus stat; + MFnTypedAttribute typedAttr; + MFnNumericAttribute nAttr; + + // ----------------------- INPUTS ------------------------- + aInputData = typedAttr.create( "inputMesh", "ipc", + NuiMayaMeshData::id, + MObject::kNullObj, &stat ); + MCHECKERROR( stat, "create inputMesh attribute" ) + typedAttr.setStorable( false ); + ADD_ATTRIBUTE( aInputData ); + + aBodyIndex = nAttr.create( "bodyIndex", "bi", MFnNumericData::kByte, 6 ); + // Attribute will be written to files when this type of node is stored + nAttr.setStorable(true); + // Attribute is keyable and will show up in the channel box + nAttr.setKeyable(true); + nAttr.setMin(0); + nAttr.setMax(6); + // Add the attributes we have created to the node + // + stat = addAttribute( aBodyIndex ); + if (!stat) { stat.perror("addAttribute"); return stat;} + + aAssignUV = nAttr.create( "assignUV", "uv", MFnNumericData::kBoolean, true ); + // Attribute will be written to files when this type of node is stored + nAttr.setStorable(true); + // Attribute is keyable and will show up in the channel box + nAttr.setKeyable(true); + // Add the attributes we have created to the node + // + stat = addAttribute( aAssignUV ); + if (!stat) { stat.perror("addAttribute"); return stat;} + + // ----------------------- OUTPUTS ------------------------- + aOutputMesh = typedAttr.create( "outputMesh", "out", + MFnData::kMesh, + MObject::kNullObj, &stat ); + MCHECKERROR( stat, "create outputSurface attribute" ) + typedAttr.setWritable( false ); + ADD_ATTRIBUTE( aOutputMesh ); + + // ---------- Specify what inputs affect the outputs ---------- + // + ATTRIBUTE_AFFECTS( aInputData, aOutputMesh ); + ATTRIBUTE_AFFECTS( aBodyIndex, aOutputMesh ); + ATTRIBUTE_AFFECTS( aAssignUV, aOutputMesh ); + + return MS::kSuccess; +} \ No newline at end of file diff --git a/pool/shard002/C++/0024528_ASN1_ValueUTF8String.cpp b/pool/shard002/C++/0024528_ASN1_ValueUTF8String.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b192e7df27558134b6eae2dfe3724f13111fba31 --- /dev/null +++ b/pool/shard002/C++/0024528_ASN1_ValueUTF8String.cpp @@ -0,0 +1,30 @@ +/* + * Copyright (c) 2016, 2017 Alexandre SZYDLOWSKI . All rights reserved. + * Redistribution and modifications are permitted subject to GPL-V3 license. + */ +#include "ASN1_Value_Nodes.h" + +using namespace Utils; + +namespace Value { + + void ASN1_ValueUTF8String::UTF8StringToHex(const std::string& input, ByteArray& output, std::string& error) { + error.clear(); + output = ""; + if (Utils::IsValidUTF8String(input)) + output = Utils::StringToHex(input); + else + error = "Input string does not match the UTF8 format"; + } + + void ASN1_ValueUTF8String::HexToUTF8String(const ByteArray& input, std::string& output, std::string& error) { + error.clear(); + output = ""; + std::string s = Utils::HexToString(input); + if (Utils::IsValidUTF8String(s)) + output = s; + else + error = "Input string does not match the UTF8 format"; + } + +} diff --git a/pool/shard002/C++/0024533_Versions.cpp b/pool/shard002/C++/0024533_Versions.cpp new file mode 100644 index 0000000000000000000000000000000000000000..26648d737514e686f437eae07aaa4dac203cba69 --- /dev/null +++ b/pool/shard002/C++/0024533_Versions.cpp @@ -0,0 +1,226 @@ +/** + * Versions.h + * + * This file is part of the IHMC DSPro Library/Component + * Copyright (c) 2008-2016 IHMC. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * version 3 (GPLv3) as published by the Free Software Foundation. + * + * U.S. Government agencies and organizations may redistribute + * and/or modify this program under terms equivalent to + * "Government Purpose Rights" as defined by DFARS + * 252.227-7014(a)(12) (February 2014). + * + * Alternative licenses that allow for use within commercial products may be + * available. Contact Niranjan Suri at IHMC (nsuri@ihmc.us) for details. + * + * Author: Giacomo Benincasa (gbenincasa@ihmc.us) + * Created on December 22, 2016, 12:45 PM + */ + +#include "Versions.h" + +#include "Defs.h" + +#include "Logger.h" +#include "Writer.h" + +#include "Json.h" +#include + +using namespace IHMC_ACI; +using namespace NOMADSUtil; + +const char * Versions::VERSIONS_OBJECT_NAME = "versions"; +const char * Versions::STARTING_TIME = "startingTime"; +const char * Versions::INFO_VERSION = "nodeInfo"; +const char * Versions::PATH_VERSION = "path"; +const char * Versions::WAYPOINT_VERSION = "waypoint"; +const char * Versions::CLASSIFIER_VERSION = "classifier"; +const char * Versions::MATCHMAKING_VERSION = "matchmaking"; + +Versions::Versions (void) + : _i64StartingTime (0), _ui16InfoVersion (0), _ui16PathVersion (0), + _ui16WaypointVersion (0), _ui16ClassifierVersion (0), _ui16MatchmakerQualifierVersion (0), + _ui16AreasOfInterestVersion (0) +{ +} + +Versions::Versions (int64 i64StartingTime, uint16 ui16InfoVersion, uint16 ui16PathVersion, + uint16 ui16WaypointVersion, uint16 ui16ClassifierVersion, uint16 ui16MatchmakerQualifierVersion, + uint16 ui16AreasOfInterestVersion) + : _i64StartingTime (i64StartingTime), _ui16InfoVersion (ui16InfoVersion), + _ui16PathVersion (ui16PathVersion), _ui16WaypointVersion (ui16WaypointVersion), + _ui16ClassifierVersion (ui16ClassifierVersion), _ui16MatchmakerQualifierVersion (ui16MatchmakerQualifierVersion), + _ui16AreasOfInterestVersion (ui16AreasOfInterestVersion) +{ +} + +Versions::Versions (const Versions &version) + : _i64StartingTime (version._i64StartingTime), _ui16InfoVersion (version._ui16InfoVersion), + _ui16PathVersion (version._ui16PathVersion), _ui16WaypointVersion (version._ui16WaypointVersion), + _ui16ClassifierVersion (version._ui16ClassifierVersion), _ui16MatchmakerQualifierVersion (version._ui16MatchmakerQualifierVersion), + _ui16AreasOfInterestVersion (version._ui16AreasOfInterestVersion) +{ +} + +Versions::~Versions (void) +{ +} + +void Versions::reset (void) +{ + _i64StartingTime = (int64)0; + _ui16InfoVersion = (uint16)0; + _ui16PathVersion = (uint16)0; + _ui16WaypointVersion = (uint16)0; + _ui16ClassifierVersion = (uint16)0; + _ui16MatchmakerQualifierVersion = (uint16)0; + _ui16AreasOfInterestVersion = (uint16)0; +} + +void Versions::set (int64 i64StartingTime, uint16 ui16InfoVersion, uint16 ui16PathVersion, + uint16 ui16WaypointVersion, uint16 ui16ClassifierVersion, uint16 ui16MatchmakerQualifierVersion, + uint16 ui16AreasOfInterestVersion) +{ + _i64StartingTime = i64StartingTime; + _ui16InfoVersion = ui16InfoVersion; + _ui16PathVersion = ui16PathVersion; + _ui16WaypointVersion = ui16WaypointVersion; + _ui16ClassifierVersion = ui16ClassifierVersion; + _ui16MatchmakerQualifierVersion = ui16MatchmakerQualifierVersion; + _ui16AreasOfInterestVersion = ui16AreasOfInterestVersion; +} + +bool Versions::greaterThan (const Versions &versions, bool bExcludeWayPointVersion) const +{ + if ((_ui16InfoVersion > versions._ui16InfoVersion) || + (_ui16PathVersion > versions._ui16PathVersion) || + (_ui16ClassifierVersion > versions._ui16ClassifierVersion) || + (_ui16MatchmakerQualifierVersion > versions._ui16MatchmakerQualifierVersion) || + (_ui16AreasOfInterestVersion > versions._ui16AreasOfInterestVersion)) { + return true; + } + if (!bExcludeWayPointVersion) { + return (_ui16WaypointVersion > versions._ui16WaypointVersion); + } + return false; +} + +bool Versions::lessThan (const Versions &versions, bool bExcludeWayPointVersion) const +{ + if ((_ui16InfoVersion < versions._ui16InfoVersion) || + (_ui16PathVersion < versions._ui16PathVersion) || + (_ui16ClassifierVersion < versions._ui16ClassifierVersion) || + (_ui16MatchmakerQualifierVersion < versions._ui16MatchmakerQualifierVersion) || + (_ui16AreasOfInterestVersion < versions._ui16AreasOfInterestVersion)) { + return true; + } + if (!bExcludeWayPointVersion) { + return (_ui16WaypointVersion < versions._ui16WaypointVersion); + } + return false; +} + +bool Versions::pathGreater (const Versions &version) const +{ + if (_i64StartingTime > version._i64StartingTime) { + return true; + } + return (_ui16PathVersion > version._ui16PathVersion); +} + +namespace VERSIONS_JSON_NAMES +{ + const char * INFO = "nodeInfo"; + const char * PATH = "path"; + const char * WAYPOINT = "waypoint"; + const char * CLASSIFIER = "classifier"; + const char * MATCHMAKER = "matchmaker"; + const char * AREAS_OF_INTEREST = "areasOfInterest"; + const char * STARTING_TIME = "startingTime"; +} + +int Versions::fromJson (const JsonObject *pJson) +{ + const char *pszMethodName = "Versions::fromJson"; + if (pJson == nullptr) { + return -1; + } + int64 i64StartingTime = _i64StartingTime; + uint16 ui16InfoVersion = _ui16InfoVersion; + uint16 ui16PathVersion = _ui16PathVersion; + uint16 ui16WaypointVersion = _ui16WaypointVersion; + uint16 ui16ClassifierVersion = _ui16ClassifierVersion; + uint16 ui16MatchmakerQualifierVersion = _ui16MatchmakerQualifierVersion; + uint16 ui16AreasOfInterestVersion = _ui16AreasOfInterestVersion; + int rc = pJson->getNumber (VERSIONS_JSON_NAMES::INFO, ui16InfoVersion); + rc += pJson->getNumber (VERSIONS_JSON_NAMES::PATH, ui16PathVersion); + rc += pJson->getNumber (VERSIONS_JSON_NAMES::WAYPOINT, ui16WaypointVersion); + rc += pJson->getNumber (VERSIONS_JSON_NAMES::CLASSIFIER, ui16ClassifierVersion); + rc += pJson->getNumber (VERSIONS_JSON_NAMES::MATCHMAKER, ui16MatchmakerQualifierVersion); + rc += pJson->getNumber (VERSIONS_JSON_NAMES::AREAS_OF_INTEREST, ui16AreasOfInterestVersion); + rc += pJson->getNumber (VERSIONS_JSON_NAMES::STARTING_TIME, i64StartingTime); + if (rc != 0) { + checkAndLogMsg (pszMethodName, Logger::L_Warning, "version message protocol version mismatch.\n"); + } + set (i64StartingTime, ui16InfoVersion, ui16PathVersion, ui16WaypointVersion, + ui16ClassifierVersion, ui16MatchmakerQualifierVersion, ui16AreasOfInterestVersion); + return 0; +} + +JsonObject * Versions::toJson (void) const +{ + JsonObject *pJson = new JsonObject(); + if (pJson == nullptr) { + return nullptr; + } + int rc = pJson->setNumber (VERSIONS_JSON_NAMES::INFO, _ui16InfoVersion); + rc += pJson->setNumber (VERSIONS_JSON_NAMES::PATH, _ui16PathVersion); + rc += pJson->setNumber (VERSIONS_JSON_NAMES::WAYPOINT, _ui16WaypointVersion); + rc += pJson->setNumber (VERSIONS_JSON_NAMES::CLASSIFIER, _ui16ClassifierVersion); + rc += pJson->setNumber (VERSIONS_JSON_NAMES::MATCHMAKER, _ui16MatchmakerQualifierVersion); + rc += pJson->setNumber (VERSIONS_JSON_NAMES::AREAS_OF_INTEREST, _ui16AreasOfInterestVersion); + rc += pJson->setNumber (VERSIONS_JSON_NAMES::STARTING_TIME, _i64StartingTime); + if (rc != 0) { + delete pJson; + return nullptr; + } + return pJson; +} + +int Versions::read (Reader *pReader) +{ + if (pReader == nullptr) { + return -1; + } + char *pszVersions = nullptr; + if (pReader->readString (&pszVersions) < 0) { + if (pReader != nullptr) { + free (pszVersions); + } + } + if (pszVersions == nullptr) { + return -2; + } + JsonObject json (pszVersions); + int rc = fromJson (&json); + free (pszVersions); + return rc < 0 ? -3 : 0; +} + +int Versions::write (Writer *pWriter) +{ + if (pWriter == nullptr) { + return -1; + } + const JsonObject *pVersions = toJson(); + String json (pVersions->toString()); + if (pWriter->writeString (json) < 0) { + return -2; + } + return 0; +} + diff --git a/pool/shard002/C++/0024534_Plot2DProfile.cpp b/pool/shard002/C++/0024534_Plot2DProfile.cpp new file mode 100644 index 0000000000000000000000000000000000000000..d3fb3f265786d870251ac5d759c42a654662ca8f --- /dev/null +++ b/pool/shard002/C++/0024534_Plot2DProfile.cpp @@ -0,0 +1,204 @@ +#include "Plot2DProfile.h" +#include "Data/Profile/ProfilePlotStyles.h" +#include "CartaLib/PixelPipeline/CustomizablePixelPipeline.h" +#include +#include + +#include + +namespace Carta { +namespace Plot2D { + + +Plot2DProfile::Plot2DProfile(){ + + setStyle(QwtPlotCurve::Lines); +} + + +void Plot2DProfile::attachToPlot( QwtPlot* plot ){ + attach( plot ); +} + + +void Plot2DProfile::detachFromPlot(){ + detach(); +} + + +void Plot2DProfile::drawLines (QPainter *painter, const QwtScaleMap &xMap, + const QwtScaleMap &yMap, + const QRectF &canvasRect, int from, int to) const{ + if ( painter->isActive() ){ + QPen curvePen( m_defaultColor ); + curvePen.setStyle( m_penStyle ); + painter->setPen( curvePen ); + if ( from != to ){ + QwtPlotCurve::drawLines( painter, xMap, yMap, canvasRect, from, to ); + } + else { + drawSymbol( painter, xMap, yMap, canvasRect, from, to ); + } + } +} + + +void Plot2DProfile::drawSteps (QPainter *painter, const QwtScaleMap &xMap, + const QwtScaleMap &yMap, const QRectF &canvasRect, int from, int to) const { + if ( painter->isActive() ){ + QPen curvePen( m_defaultColor ); + curvePen.setStyle( m_penStyle ); + painter->setPen( curvePen ); + if ( from != to ){ + QwtPlotCurve::drawSteps( painter, xMap, yMap, canvasRect, from, to ); + } + else { + drawSymbol( painter, xMap, yMap, canvasRect, from, to ); + } + } +} + +void Plot2DProfile::drawSymbol( QPainter* painter, const QwtScaleMap & xMap, + const QwtScaleMap & yMap, const QRectF & canvasRect, int from, int to ) const{ + QPen curvePen( m_defaultColor ); + QBrush brush( m_defaultColor ); + QSize symbolSize( 10, 10 ); + QwtSymbol symbol ( QwtSymbol::Diamond, brush, curvePen, symbolSize ); + drawSymbols( painter, symbol, xMap, yMap, canvasRect, from, to ); +} + +std::pair Plot2DProfile::getClosestPoint( double targetX, double targetY, + double* xError, double* yError ) const { + int dataCount = m_datasX.size(); + std::pair closestPt( targetX, targetY ); + for ( int i = 0; i < dataCount; i++ ){ + double ptErrorX = qAbs( m_datasX[i] - targetX ); + double ptErrorY = qAbs( m_datasY[i] - targetY ); + if ( ptErrorX < *xError && ptErrorY < *yError ){ + *xError = ptErrorX; + *yError = ptErrorY; + closestPt.first = m_datasX[i]; + closestPt.second = m_datasY[i]; + } + } + return closestPt; +} + +QwtGraphic Plot2DProfile::legendIcon( int /*index*/, const QSizeF& iconSize ) const { + if ( iconSize.isEmpty() ){ + return QwtGraphic(); + } + QwtGraphic icon; + icon.setDefaultSize( iconSize ); + icon.setRenderHint( QwtGraphic::RenderPensUnscaled, true ); + + QPainter painter( &icon ); + QPen pen( m_defaultColor ); + pen.setStyle( m_penStyle ); + pen.setWidth( 3 ); + const double y = 0.5 * iconSize.height(); + QPainterPath path; + path.moveTo( 0.0, y ); + path.lineTo( iconSize.width(), y ); + painter.strokePath( path, pen ); + return icon; +} + +void Plot2DProfile::setData ( std::vector > datas ){ + int dataCount = datas.size(); + m_datasX.resize( dataCount ); + m_datasY.resize( dataCount ); + if ( dataCount > 1 ){ + m_maxValueY = -1 * std::numeric_limits::max(); + m_minValueY = std::numeric_limits::max(); + m_maxValueX = -1 * std::numeric_limits::max(); + m_minValueX = std::numeric_limits::max(); + for ( int i = 0; i < dataCount; i++ ){ + m_datasX[i] = datas[i].first; + m_datasY[i] = datas[i].second; + if ( !isinf( datas[i].first ) && !isinf( datas[i].second )){ + if ( m_datasY[i] > m_maxValueY ){ + m_maxValueY = m_datasY[i]; + } + if ( m_datasY[i] < m_minValueY ){ + m_minValueY = m_datasY[i]; + } + if ( m_datasX[i] > m_maxValueX ){ + m_maxValueX = m_datasX[i]; + } + + if ( m_datasX[i] < m_minValueX ){ + m_minValueX = m_datasX[i]; + } + } + } + } + else if ( dataCount == 1 ){ + const double INC = 0.0000001; + m_minValueY = m_datasY[0] - INC; + m_maxValueY = m_datasY[0] + INC; + m_minValueX = m_datasX[0] - INC; + m_maxValueX = m_datasX[0] + INC; + } + //No data so just use bogus bounds + else { + m_maxValueY = 1; + m_minValueY = 0; + m_maxValueX = 1; + m_minValueX = 0; + } + + setRawSamples( m_datasX.data(), m_datasY.data(), dataCount ); +} + + +void Plot2DProfile::setBaseLine( double /*val*/ ){ +} + +void Plot2DProfile::setDrawStyle( const QString& style ){ + Plot2D::setDrawStyle( style ); + if ( m_drawStyle == Carta::Data::ProfilePlotStyles::PLOT_STYLE_LINE ){ + setStyle( QwtPlotCurve::Lines ); + } + else if ( m_drawStyle == Carta::Data::ProfilePlotStyles::PLOT_STYLE_STEP ){ + setStyle( QwtPlotCurve::Steps ); + } + else { + qDebug() << "Unrecognized draw style"; + } +} + + + +void Plot2DProfile::setId( const QString& id ){ + Plot2D::setId( id ); + QwtText dataTitle = title(); + dataTitle.setText( id ); + setTitle( dataTitle ); +} + +void Plot2DProfile::setLegendLine( bool showLegendLine ){ + QwtText text = title(); + if ( showLegendLine ){ + setLegendIconSize(QSize(36,8)); + text.setColor( "black"); + } + else { + setLegendIconSize(QSize(0,0)); + text.setColor( m_defaultColor ); + } + setTitle( text ); +} + +void Plot2DProfile::setLegendVisible( bool visible ){ + setItemAttribute( QwtPlotItem::ItemAttribute::Legend, visible ); +} + + +Plot2DProfile::~Plot2DProfile(){ + +} + +} +} + diff --git a/pool/shard002/C++/0024537_Local.cpp b/pool/shard002/C++/0024537_Local.cpp new file mode 100644 index 0000000000000000000000000000000000000000..a110ade7ffdc8d768f0d496ad945d3497f394f6c --- /dev/null +++ b/pool/shard002/C++/0024537_Local.cpp @@ -0,0 +1,156 @@ +/*======================================================================= +* +* Copyright (C) 2013-2015 Lysine. +* +* Filename: Local.cpp +* Time: 2013/03/18 +* Author: Lysine +* +* Lysine is a student majoring in Software Engineering +* from the School of Software, SUN YAT-SEN UNIVERSITY. +* +* 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 "Local.h" +#include "Config.h" +#include "Plugin.h" +#include "Utils.h" +#include "Model/Danmaku.h" +#include "Model/List.h" +#include "Model/Shield.h" +#include "Player/APlayer.h" +#include "Render/ARender.h" +#include "UI/Interface.h" + +QHash Local::objects; + +Local::Local(int &argc, char **argv) : +QApplication(argc, argv) +{ + QDir::setCurrent(applicationDirPath()); + setPalette(setStyle("Fusion")->standardPalette()); + setAttribute(Qt::AA_UseOpenGLES); + thread()->setPriority(QThread::TimeCriticalPriority); + Config::load(); + qsrand(QTime::currentTime().msec()); +} + +void Local::exit(int code) +{ + delete List::instance(); + Config::save(); + delete APlayer::instance(); + delete Danmaku::instance(); + QApplication::exit(code); +} + +namespace +{ + void setDefaultFont() + { + QString def = Utils::defaultFont(); + QFontInfo i(qApp->font()); + if (!QFontDatabase().families().contains(def)){ + def = i.family(); + } + double p = i.pointSizeF(); + QFont f; + f.setFamily(Config::getValue("/Interface/Font/Family", def)); + f.setPointSizeF(Config::getValue("/Interface/Font/Size", p)); + qApp->setFont(f); + } + + void loadTranslator() + { + QString locale = Config::getValue("/Interface/Locale", QLocale::system().name()); + QFileInfoList list; + list += QDir("./locale/" + locale).entryInfoList(); + list += QFileInfo("./locale/" + locale + ".qm"); + locale.resize(2); + list += QDir("./locale/" + locale).entryInfoList(); + list += QFileInfo("./locale/" + locale + ".qm"); + for (QFileInfo info : list){ + if (!info.isFile()){ + continue; + } + QTranslator *trans = new QTranslator(qApp); + if (trans->load(info.absoluteFilePath())){ + qApp->installTranslator(trans); + } + else{ + delete trans; + } + } + } + + void setToolTipBase() + { + QPalette tip = qApp->palette(); + tip.setColor(QPalette::Inactive, QPalette::ToolTipBase, Qt::white); + qApp->setPalette(tip); + QToolTip::setPalette(tip); + } +} + +int main(int argc, char *argv[]) +{ + Local a(argc, argv); + int single; + if ((single = Config::getValue("/Interface/Single", 1))){ + QLocalSocket socket; + socket.connectToServer("BiliLocalInstance"); + if (socket.waitForConnected()){ + QDataStream s(&socket); + s << a.arguments().mid(1); + socket.waitForBytesWritten(); + return 0; + } + } + loadTranslator(); + setDefaultFont(); + setToolTipBase(); + Interface w; + Plugin::loadPlugins(); + if (!w.testAttribute(Qt::WA_WState_ExplicitShowHide)){ + w.show(); + } + w.tryLocal(a.arguments().mid(1)); + QLocalServer *server = nullptr; + if (single){ + server = new QLocalServer(lApp); + server->listen("BiliLocalInstance"); + QObject::connect(server, &QLocalServer::newConnection, [&](){ + QLocalSocket *r = server->nextPendingConnection(); + r->waitForReadyRead(); + QDataStream s(r); + QStringList args; + s >> args; + delete r; + w.tryLocal(args); + }); + } + int r; + if ((r = a.exec()) == 12450){ + if (server){ + delete server; + } + QProcess::startDetached(a.applicationFilePath(), QStringList()); + return 0; + } + else{ + return r; + } +} diff --git a/pool/shard002/C++/0024539_test_idt_x64.cpp b/pool/shard002/C++/0024539_test_idt_x64.cpp new file mode 100644 index 0000000000000000000000000000000000000000..12e9bd25892f2e610593f88ad73e9c985b4bb28f --- /dev/null +++ b/pool/shard002/C++/0024539_test_idt_x64.cpp @@ -0,0 +1,101 @@ +// +// Bareflank Hypervisor +// +// Copyright (C) 2015 Assured Information Security, Inc. +// Author: Rian Quinn +// Author: Brendan Kerrigan +// +// This library is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public +// License as published by the Free Software Foundation; either +// version 2.1 of the License, or (at your option) any later version. +// +// This library is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +// Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public +// License along with this library; if not, write to the Free Software +// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + +#include + +#include +#include + +std::vector g_idt = +{ + 0xFFFFFFFFFFFFFFFF, + 0xFFFFFFFFFFFFFFFF, + 0xFFFFFFFFFFFFFFFF, + 0xFFFFFFFFFFFFFFFF +}; + +idt_reg_x64_t g_idt_reg; + +extern "C" void +__read_idt(idt_reg_x64_t *idt_reg) noexcept +{ *idt_reg = g_idt_reg; } + +extern "C" void +__write_idt(idt_reg_x64_t *idt_reg) noexcept +{ g_idt_reg = *idt_reg; } + +void +intrinsics_ut::test_idt_reg_set_get() +{ + x64::idt::set(g_idt.data(), (4 << 3) - 1); + + this->expect_true(x64::idt::get().base == g_idt.data()); + this->expect_true(x64::idt::get().limit == (4 << 3) - 1); +} + +void +intrinsics_ut::test_idt_reg_base_set_get() +{ + x64::idt::base::set(g_idt.data()); + this->expect_true(x64::idt::base::get() == g_idt.data()); +} + +void +intrinsics_ut::test_idt_reg_limit_set_get() +{ + x64::idt::limit::set((4 << 3) - 1); + this->expect_true(x64::idt::limit::get() == (4 << 3) - 1); +} + +void +intrinsics_ut::test_idt_constructor_no_size() +{ + idt_x64 idt; +} + +void +intrinsics_ut::test_idt_constructor_zero_size() +{ + this->expect_no_exception([&] { idt_x64{0}; }); +} + +void +intrinsics_ut::test_idt_constructor_size() +{ + idt_x64 idt{4}; + + this->expect_true(idt.base() != 0); + this->expect_true(idt.limit() == (4 * sizeof(idt_x64::interrupt_descriptor_type)) - 1); +} + +void +intrinsics_ut::test_idt_base() +{ + idt_x64 idt; + this->expect_true(idt.base() == reinterpret_cast(g_idt.data())); +} + +void +intrinsics_ut::test_idt_limit() +{ + idt_x64 idt; + this->expect_true(idt.limit() == (4 * sizeof(idt_x64::interrupt_descriptor_type)) - 1); +} diff --git a/pool/shard002/C++/0024548_raw.cpp b/pool/shard002/C++/0024548_raw.cpp new file mode 100644 index 0000000000000000000000000000000000000000..bcd77815e20c3a4f17e5f659e9afe56d174f6f88 --- /dev/null +++ b/pool/shard002/C++/0024548_raw.cpp @@ -0,0 +1,73 @@ +#include "raw.hpp" + +#include "../program.hpp" + +#include + +#include +#include + +using namespace Models; + +const GLchar *const Raw::attribs[] = { + "position", + "normal", +}; + +const GLchar *const Raw::uniforms[] = { + "mvp", + "local_modelview", +}; + +const std::string Raw::filename(const std::string &name) +{ + return "/models/" + name; +} + +Raw::Raw(const Adapter &adapter, const std::string &name) +{ + exe = adapter.load("normal")->build( + __attrib_count, attribs, + __uniform_count, uniforms + ); + + FILE *file = fopen(adapter.filename(name).c_str(), "r"); + + while (!feof(file)) + { + std::array v; + + for (int i = 0; i < 3; ++i) + fscanf(file, "%f %f %f", &v[i].x, &v[i].y, &v[i].z); + + add3_with_auto_normals(v, glm::vec3(0.0f, -10.0f, 0.0f)); + } + + fclose(file); + + positions_id = create_array_buffer(GL_ARRAY_BUFFER, 3 * positions.size() * sizeof(GLfloat), positions.data()); + normals_id = create_array_buffer(GL_ARRAY_BUFFER, 3 * normals.size() * sizeof(GLfloat), normals.data()); + id = create_array_buffer(GL_ELEMENT_ARRAY_BUFFER, elements.size() * sizeof(GLushort), elements.data()); +} + +void Raw::draw(__attribute__((unused)) const Scene &scene, const glm::mat4 &mvp, const glm::mat4 &transformation) const +{ + exe->use(); + + const glm::mat4 transform = mvp * transformation; + glUniformMatrix4fv(exe->uniform(Uniform::mvp), 1, GL_FALSE, glm::value_ptr(transform)); + + const glm::mat3 local_modelview = glm::transpose(glm::inverse(glm::mat3(transformation))); + glUniformMatrix3fv(exe->uniform(Uniform::local_modelview), 1, GL_FALSE, glm::value_ptr(local_modelview)); + + glEnableVertexAttribArray(position); + glBindBuffer(GL_ARRAY_BUFFER, positions_id); + glVertexAttribPointer(position, 3, GL_FLOAT, GL_FALSE, 0, reinterpret_cast(0)); + + glEnableVertexAttribArray(normal); + glBindBuffer(GL_ARRAY_BUFFER, normals_id); + glVertexAttribPointer(normal, 3, GL_FLOAT, GL_FALSE, 0, reinterpret_cast(0)); + + glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, id); + glDrawElements(GL_TRIANGLES, elements.size(), GL_UNSIGNED_SHORT, 0); +} diff --git a/pool/shard002/C++/0024550_PrimitiveParsing.cpp b/pool/shard002/C++/0024550_PrimitiveParsing.cpp new file mode 100644 index 0000000000000000000000000000000000000000..ee266a3923e108064b96c867d9bb7ade86ce2ed2 --- /dev/null +++ b/pool/shard002/C++/0024550_PrimitiveParsing.cpp @@ -0,0 +1,75 @@ +//===--- PrimitiveParsing.cpp - Primitive parsing routines ----------------===// +// +// 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 +// +//===----------------------------------------------------------------------===// +/// +/// \file +/// Primitive parsing routines useful in various places in the compiler. +/// +//===----------------------------------------------------------------------===// + +#include "swift/Basic/PrimitiveParsing.h" +#include "llvm/ADT/SmallVector.h" + +using namespace llvm; + +unsigned swift::measureNewline(const char *BufferPtr, const char *BufferEnd) { + if (BufferPtr == BufferEnd) + return 0; + + if (*BufferPtr == '\n') + return 1; + + assert(*BufferPtr == '\r'); + unsigned Bytes = 1; + if (BufferPtr != BufferEnd && *BufferPtr == '\n') + ++Bytes; + return Bytes; +} + +void +swift::trimLeadingWhitespaceFromLines(StringRef RawText, + unsigned WhitespaceToTrim, + SmallVectorImpl &OutLines) { + SmallVector Lines; + + bool IsFirstLine = true; + + while (!RawText.empty()) { + size_t Pos = RawText.find_first_of("\n\r"); + if (Pos == StringRef::npos) + Pos = RawText.size(); + + StringRef Line = RawText.substr(0, Pos); + Lines.push_back(Line); + if (!IsFirstLine) { + size_t NonWhitespacePos = RawText.find_first_not_of(' '); + if (NonWhitespacePos != StringRef::npos) + WhitespaceToTrim = + std::min(WhitespaceToTrim, + static_cast(NonWhitespacePos)); + } + IsFirstLine = false; + + RawText = RawText.drop_front(Pos); + unsigned NewlineBytes = measureNewline(RawText); + RawText = RawText.drop_front(NewlineBytes); + } + + IsFirstLine = true; + for (auto &Line : Lines) { + if (!IsFirstLine) { + Line = Line.drop_front(WhitespaceToTrim); + } + IsFirstLine = false; + } + + OutLines.append(Lines.begin(), Lines.end()); +} diff --git a/pool/shard002/C++/0024551_mainwindow.cpp b/pool/shard002/C++/0024551_mainwindow.cpp new file mode 100644 index 0000000000000000000000000000000000000000..059b17bf5a04686f9f0098bc3286008401d4976b --- /dev/null +++ b/pool/shard002/C++/0024551_mainwindow.cpp @@ -0,0 +1,123 @@ +/* + * Copyright (C) 2015 Luiz Carlos Vieira (http://www.luiz.vieira.nom.br) + * + * This file is part of Fun from Faces (f3). + * + * f3 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. + * + * f3 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 "mainwindow.h" +#include "ui_mainwindow.h" +#include "aboutwindow.h" +#include "application.h" +#include "leveldelegate.h" + +#include +#include +#include +#include +#include +#include +#include + +using namespace std; + +// +----------------------------------------------------------- +f3::MainWindow::MainWindow(QWidget *pParent) : + QMainWindow(pParent), + ui(new Ui::MainWindow) +{ + // Setup the UI + ui->setupUi(this); + m_pAbout = NULL; + + setWindowIcon(QIcon(":/icons/lol")); + + // Add the action shortcuts to the tooltips (in order to make it easier for the user to know they exist) + // P.S.: I wonder why doesn't Qt do that automatically... :) + QObjectList lsObjects = children(); + QAction *pAction; + for(int i = 0; i < lsObjects.size(); i++) + { + pAction = qobject_cast(lsObjects.at(i)); + if(pAction && !pAction->shortcut().isEmpty()) + pAction->setToolTip(QString("%1 (%2)").arg(pAction->toolTip()).arg(pAction->shortcut().toString())); + } + + ui->treeData->setModel(&m_oDataModel); + ui->treeData->setItemDelegate(new LevelDelegate()); +} + +// +----------------------------------------------------------- +f3::MainWindow::~MainWindow() +{ + if(m_pAbout) + delete m_pAbout; + delete ui; +} + +// +----------------------------------------------------------- +void f3::MainWindow::on_actionRefresh_triggered() +{ + updateUI(); +} + +// +----------------------------------------------------------- +void f3::MainWindow::on_actionExit_triggered() +{ + QApplication::exit(0); +} + +// +----------------------------------------------------------- +void f3::MainWindow::on_actionProject_triggered() +{ + QDesktopServices::openUrl(QUrl("https://github.com/luigivieira/F3")); +} + +// +----------------------------------------------------------- +void f3::MainWindow::on_actionAbout_triggered() +{ + (new AboutWindow(this))->show(); +} + +// +----------------------------------------------------------- +void f3::MainWindow::showStatusMessage(const QString &sMsg, const int iTimeout) +{ + ui->statusBar->showMessage(sMsg, iTimeout); +} + +// +----------------------------------------------------------- +void f3::MainWindow::showEvent(QShowEvent *) +{ + updateUI(); +} + +// +----------------------------------------------------------- +void f3::MainWindow::updateUI() +{ + if(!m_oDataModel.updateData()) + { + QMessageBox::warning(this, tr("Erro de atualização"), tr("Não foi possível atualizar a lista de aplicações em execução."), QMessageBox::Ok); + return; + } + + QString sNow = QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss"); + QString sUpdate = tr("Última atualização: %1").arg(sNow); + if(m_oDataModel.rowCount() == 0) + F3Application::showStatusMessage(tr("Não há nenhuma aplicação do projeto F3 em execução. %1").arg(sUpdate), 0); + else if(m_oDataModel.rowCount() == 1) + F3Application::showStatusMessage(tr("Há apenas uma aplicação do projeto F3 em execução. %1").arg(sUpdate), 0); + else + F3Application::showStatusMessage(tr("Há %1 aplicações do projeto F3 em execução. %1").arg(m_oDataModel.rowCount()).arg(sUpdate), 0); +} \ No newline at end of file diff --git a/pool/shard002/C++/0024563_StoryModeHUD.cpp b/pool/shard002/C++/0024563_StoryModeHUD.cpp new file mode 100644 index 0000000000000000000000000000000000000000..fa77bb34adbf486ff3e768b074b0c564fa6c6f9f --- /dev/null +++ b/pool/shard002/C++/0024563_StoryModeHUD.cpp @@ -0,0 +1,143 @@ +/* + * StoryModeHUD.mm + * Bumble Tales + * + * Created by Robert Shoemate on 6/13/09. + * Copyright 2009 Conjured Realms LLC. All rights reserved. + * + */ + +#include "StoryModeHUD.h" +#include "AssetList.h" +//#include "SavedGame.h" + +extern CR::Graphics::GraphicsEngine *graphics_engine; + +StoryModeHUD::StoryModeHUD(int xLoc, int yLoc) +{ + offset.X(xLoc); + offset.Y(yLoc); + + hudSprite = graphics_engine->CreateSprite1(false,900); + hudSprite->SetImage(CR::AssetList::Story_Mode_HUD); + hudSprite->SetDesignSize(202, 55); + hudSprite->SetPositionAbsolute(offset.X(), offset.Y()); + + // Create resource bars + resourceBars[Brick] = new ResourceBar(offset.X() + 3, offset.Y() - 19); + resourceBars[Wood] = new ResourceBar(offset.X() + 3, offset.Y() - 1); + resourceBars[Leaf] = new ResourceBar(offset.X() + 3, offset.Y() + 17); + resourceBars[Crystal] = new ResourceBar(offset.X() + 71, offset.Y() - 19); + resourceBars[Gold] = new ResourceBar(offset.X() + 71, offset.Y() - 1); + resourceBars[Diamond] = new ResourceBar(offset.X() + 71, offset.Y() + 17); + + // Create level counter + numberFont = new NumberFont(CR::AssetList::Font_Level,800); + numberFont->SetPosition(offset.X() - 61, offset.Y() + 10); + numberFont->SetDesignSize(15, 18); + m_currLevel = 0; +} + +StoryModeHUD::~StoryModeHUD() +{ + hudSprite->Release(); + //delete levelCounter; + delete numberFont; + + for (int i = 0; i < resource_bars; i++) + delete resourceBars[i]; +} + +void StoryModeHUD::Update() +{ + //levelCounter->Update(); + + for (int i = 0; i < resource_bars; i++) + { + resourceBars[i]->Update(); + } +} + +void StoryModeHUD::Render() +{ + hudSprite->Render(); + + //levelCounter->Render(); + numberFont->RenderNumber(m_currLevel); + + for (int i = 0; i < resource_bars; i++) + { + resourceBars[i]->Render(); + } +} + +void StoryModeHUD::PauseAnimation(bool pause) +{ + for (int i = 0; i < resource_bars; i++) + { + resourceBars[i]->PauseAnimation(pause); + } +} + +void StoryModeHUD::ResetResourceBars() +{ + for (int i = 0; i < resource_bars; i++) + { + resourceBars[i]->ResetValue(); + } +} + +void StoryModeHUD::SetResourceRequirement(ResourceType rType, int amount) +{ + if ((int)rType > 5) + return; + + resourceBars[rType]->SetMaxValue(amount); +} + +void StoryModeHUD::AddResources(ResourceType rType, int amount) +{ + if ((int)rType > 5) + return; + + resourceBars[rType]->AddToCurrValue(amount); +} + +bool StoryModeHUD::ResourcesGathered() +{ + for (int i = 0; i < resource_bars; i++) + if (resourceBars[i]->IsFull() == false) return false; + + return true; +} + +void StoryModeHUD::PerformLevelUp() +{ + //levelCounter->Increment(); + //levelCounter++; + //SetLevel(levelCounter->GetCount() + 1); + SetLevel(m_currLevel + 1); + ResetResourceBars(); +} + +void StoryModeHUD::SetPosition(float xLoc, float yLoc) +{ + offset.X(xLoc); + offset.Y(yLoc); +} + +void StoryModeHUD::SetLevel(int level) +{ + //levelCounter->SetCount(level); + m_currLevel = level; + + int baseResourceRequirement = 3; + for (int i = 0; i < 6; i++) + SetResourceRequirement((ResourceType)i, baseResourceRequirement + level - 1); +} + +int StoryModeHUD::GetResourceRequirement() +{ + int baseResourceRequirement = 3; + return baseResourceRequirement + m_currLevel - 1; +} \ No newline at end of file diff --git a/pool/shard002/C++/0024566_CMapEvent.cpp b/pool/shard002/C++/0024566_CMapEvent.cpp new file mode 100644 index 0000000000000000000000000000000000000000..3754b042f8ece726eca3dc2be4c65e399eff2271 --- /dev/null +++ b/pool/shard002/C++/0024566_CMapEvent.cpp @@ -0,0 +1,47 @@ +/***************************************************************************** + * + * PROJECT: Multi Theft Auto v1.0 + * (Shared logic for modifications) + * LICENSE: See LICENSE in the top level directory + * FILE: mods/shared_logic/CMapEvent.cpp + * PURPOSE: Map event class + * + *****************************************************************************/ + +#include + +CMapEvent::CMapEvent(CLuaMain* pMain, const char* szName, const CLuaFunctionRef& iLuaFunction, bool bPropagated, EEventPriorityType eventPriority, + float fPriorityMod) +{ + // Init + m_pMain = pMain; + m_bDestroyFunction = false; + m_iLuaFunction = iLuaFunction; + m_bPropagated = bPropagated; + m_bBeingDestroyed = false; + m_eventPriority = eventPriority; + m_fPriorityMod = fPriorityMod; + m_strName.AssignLeft(szName, MAPEVENT_MAX_LENGTH_NAME); + // Only allow dxSetAspectRatioAdjustmentEnabled during these events + m_bAllowAspectRatioAdjustment = (m_strName == "onClientRender") || (m_strName == "onClientPreRender") || (m_strName == "onClientHUDRender"); + // Force aspect ratio adjustment for 'customblips' resource + m_bForceAspectRatioAdjustment = m_bAllowAspectRatioAdjustment && SStringX(pMain->GetScriptName()) == "customblips"; +} + +CMapEvent::~CMapEvent() +{ +} + +void CMapEvent::Call(const CLuaArguments& Arguments) +{ + if (m_pMain) + { + // Call our function with the given arguments + Arguments.Call(m_pMain, m_iLuaFunction); + } +} + +bool CMapEvent::IsHigherPriorityThan(const CMapEvent* pOther) +{ + return m_eventPriority > pOther->m_eventPriority || (m_eventPriority == pOther->m_eventPriority && m_fPriorityMod > pOther->m_fPriorityMod); +} diff --git a/pool/shard002/C++/0024569_7287.cpp b/pool/shard002/C++/0024569_7287.cpp new file mode 100644 index 0000000000000000000000000000000000000000..d22e9920ff5bc20db23cee786e4190e25d0e05de --- /dev/null +++ b/pool/shard002/C++/0024569_7287.cpp @@ -0,0 +1,58 @@ +#include +#include +#include +#include +#include + +using namespace std; + +#define MIN(a,b) (((a) < (b)) ? (a) : (b)) +#define MAX(a,b) (((a) > (b)) ? (a) : (b)) + +inline long long get5(long long a, long long b) +{ + return (b / 5) - ((a - 1) / 5); + +} + +int main() +{ + int n; + vector > vect; + + cin >> n; + + long long tmp1, tmp2; + for (int i = 0; i> tmp1 >> tmp2; + vect.push_back(make_pair(MIN(tmp1, tmp2), -1)); + vect.push_back(make_pair(MAX(tmp1, tmp2), 1)); + } + sort(vect.begin(), vect.end()); + + int cnt = 0; + long long answ = 0; + long long lf = -1; + + for (int i = 0; i < n * 2 - 1; i++) + { + if (vect[i].second < 0) + cnt++; + else + cnt--; + + if (cnt > 0) + { + answ += get5(vect[i].first, vect[i + 1].first); + if (vect[i].first == lf) + answ--; + if (vect[i + 1].first % 5 == 0) lf = vect[i + 1].first; + } + //cout << (vect[i + 1].first / 5) << " " << ((vect[i].first - 1) / 5) << "\n"; + } + + cout << answ << endl; + + return 0; +} \ No newline at end of file diff --git a/pool/shard002/C++/0024573_tsection.cpp b/pool/shard002/C++/0024573_tsection.cpp new file mode 100644 index 0000000000000000000000000000000000000000..ece8ee69af4c60778008991544bf352715c90351 --- /dev/null +++ b/pool/shard002/C++/0024573_tsection.cpp @@ -0,0 +1,64 @@ +#include "tsection.h" + +TSection::TSection() + : id(-1) +{ +} + +TSection TSection::get(int id, bool &exist) +{ + exist = true; + QSqlQuery query; + query.prepare("SELECT * FROM sections WHERE id=:id"); + query.bindValue(":id", id); + query.exec(); + if (!query.next()) { + exist = false; + return TSection(); + } + + return getFromQuery(query); +} + +TSection TSection::getFromQuery(QSqlQuery &query) +{ + TSection section; + section.id = query.value(0).toInt(); + section.name = query.value(1).toString(); + section.description = query.value(2).toString(); + + return section; +} + +QVector TSection::getAll() +{ + QSqlQuery query("SELECT * FROM sections"); + QVector sections; + + while(query.next()) { + sections.push_back(getFromQuery(query)); + } + + return sections; +} + +void TSection::save() +{ + QSqlQuery query; + bool sectionExist; + get(id, sectionExist); + + if (sectionExist) { + query.prepare("UPDATE sections SET name = :name, description = :description WHERE id=:id"); + query.bindValue(":name", name); + query.bindValue(":description", description); + query.exec(); + } else { + query.prepare("INSERT INTO sections (name, description) \ + VALUES (:name, :description)"); + query.bindValue(":name", name); + query.bindValue(":description", description); + query.exec(); + id = query.lastInsertId().toInt(); + } +} diff --git a/pool/shard002/C++/0024577_button_group_test.cpp b/pool/shard002/C++/0024577_button_group_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..65d08b1cb94aa0099fb2f267ffce855568e4eb0a --- /dev/null +++ b/pool/shard002/C++/0024577_button_group_test.cpp @@ -0,0 +1,73 @@ +// coding: utf-8 +// ---------------------------------------------------------------------------- +/* Copyright (c) 2009, Roboterclub Aachen e.V. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the Roboterclub Aachen e.V. 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 ROBOTERCLUB AACHEN E.V. ''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 ROBOTERCLUB AACHEN E.V. 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 "../button_group.hpp" + +#include "button_group_test.hpp" + +void +ButtonGroupTest::testButtons() +{ + xpcc::ButtonGroup<> buttons(0); + + TEST_ASSERT_FALSE(buttons.isPressed(0x01)); + + buttons.update(0xff); + buttons.update(0xff); + buttons.update(0xff); + buttons.update(0xff); + buttons.update(0xff); + + TEST_ASSERT_FALSE(buttons.isPressed(0x01)); + + buttons.update(0x00); + buttons.update(0x00); + buttons.update(0x00); + + TEST_ASSERT_FALSE(buttons.isPressed(0x01)); + + buttons.update(0x00); + + TEST_ASSERT_TRUE(buttons.isPressed(0x01)); + TEST_ASSERT_FALSE(buttons.isPressed(0x01)); + TEST_ASSERT_FALSE(buttons.isPressed(0x01)); + + buttons.update(0xff); + buttons.update(0xff); + buttons.update(0xff); + + TEST_ASSERT_FALSE(buttons.isReleased(0x01)); + + buttons.update(0xff); + + TEST_ASSERT_TRUE(buttons.isReleased(0x01)); + + // TODO do some real testing +} diff --git a/pool/shard002/C++/0024578_callback_layer_animation_observer.cc b/pool/shard002/C++/0024578_callback_layer_animation_observer.cc new file mode 100644 index 0000000000000000000000000000000000000000..639caf4d1411b867a31ce29e6c6ec4ae846359a8 --- /dev/null +++ b/pool/shard002/C++/0024578_callback_layer_animation_observer.cc @@ -0,0 +1,132 @@ +// Copyright 2015 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "ui/compositor/callback_layer_animation_observer.h" + +#include "base/bind.h" +#include "ui/compositor/layer_animation_sequence.h" + +namespace ui { + +void CallbackLayerAnimationObserver::DummyAnimationStartedCallback( + const CallbackLayerAnimationObserver&) {} + +bool CallbackLayerAnimationObserver::DummyAnimationEndedCallback( + bool should_delete_observer, + const CallbackLayerAnimationObserver&) { + return should_delete_observer; +} + +CallbackLayerAnimationObserver::CallbackLayerAnimationObserver( + AnimationStartedCallback animation_started_callback, + AnimationEndedCallback animation_ended_callback) + : animation_started_callback_(animation_started_callback), + animation_ended_callback_(animation_ended_callback) {} + +CallbackLayerAnimationObserver::CallbackLayerAnimationObserver( + AnimationStartedCallback animation_started_callback, + bool should_delete_observer) + : animation_started_callback_(animation_started_callback), + animation_ended_callback_(base::Bind( + &CallbackLayerAnimationObserver::DummyAnimationEndedCallback, + should_delete_observer)) {} + +CallbackLayerAnimationObserver::CallbackLayerAnimationObserver( + AnimationEndedCallback animation_ended_callback) + : animation_started_callback_(base::Bind( + &CallbackLayerAnimationObserver::DummyAnimationStartedCallback)), + animation_ended_callback_(animation_ended_callback) {} + +CallbackLayerAnimationObserver::~CallbackLayerAnimationObserver() { + if (destroyed_) + *destroyed_ = true; +} + +void CallbackLayerAnimationObserver::SetActive() { + active_ = true; + + bool destroyed = false; + destroyed_ = &destroyed; + + CheckAllSequencesStarted(); + + if (destroyed) + return; + destroyed_ = nullptr; + + CheckAllSequencesCompleted(); +} + +void CallbackLayerAnimationObserver::OnLayerAnimationStarted( + ui::LayerAnimationSequence* sequence) { + CHECK_LT(started_count_, attached_sequence_count_); + ++started_count_; + CheckAllSequencesStarted(); +} + +void CallbackLayerAnimationObserver::OnLayerAnimationEnded( + ui::LayerAnimationSequence* sequence) { + CHECK_LT(GetNumSequencesCompleted(), attached_sequence_count_); + ++successful_count_; + CheckAllSequencesCompleted(); +} + +void CallbackLayerAnimationObserver::OnLayerAnimationAborted( + ui::LayerAnimationSequence* sequence) { + CHECK_LT(GetNumSequencesCompleted(), attached_sequence_count_); + ++aborted_count_; + CheckAllSequencesCompleted(); +} + +void CallbackLayerAnimationObserver::OnLayerAnimationScheduled( + ui::LayerAnimationSequence* sequence) {} + +bool CallbackLayerAnimationObserver::RequiresNotificationWhenAnimatorDestroyed() + const { + return true; +} + +void CallbackLayerAnimationObserver::OnAttachedToSequence( + ui::LayerAnimationSequence* sequence) { + ++attached_sequence_count_; +} + +void CallbackLayerAnimationObserver::OnDetachedFromSequence( + ui::LayerAnimationSequence* sequence) { + CHECK_LT(detached_sequence_count_, attached_sequence_count_); + ++detached_sequence_count_; +} + +int CallbackLayerAnimationObserver::GetNumSequencesCompleted() { + return aborted_count_ + successful_count_; +} + +void CallbackLayerAnimationObserver::CheckAllSequencesStarted() { + if (active_ && attached_sequence_count_ == started_count_) + animation_started_callback_.Run(*this); +} + +void CallbackLayerAnimationObserver::CheckAllSequencesCompleted() { + if (active_ && GetNumSequencesCompleted() == attached_sequence_count_) { + active_ = false; + bool destroyed = false; + destroyed_ = &destroyed; + + bool should_delete = animation_ended_callback_.Run(*this); + + if (destroyed) { + if (should_delete) + LOG(WARNING) << "CallbackLayerAnimationObserver was explicitly " + "destroyed AND was requested to be destroyed via the " + "AnimationEndedCallback's return value."; + return; + } + destroyed_ = nullptr; + + if (should_delete) + delete this; + } +} + +} // namespace ui diff --git a/pool/shard002/C++/0024581_media_stream_video_track_unittest.cc b/pool/shard002/C++/0024581_media_stream_video_track_unittest.cc new file mode 100644 index 0000000000000000000000000000000000000000..85b7bdafab931b275f71c8025785bb5bc5fd8fb1 --- /dev/null +++ b/pool/shard002/C++/0024581_media_stream_video_track_unittest.cc @@ -0,0 +1,258 @@ +// Copyright 2014 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 "base/bind.h" +#include "base/bind_helpers.h" +#include "base/callback.h" +#include "base/message_loop/message_loop.h" +#include "base/run_loop.h" +#include "base/strings/utf_string_conversions.h" +#include "base/threading/thread_checker_impl.h" +#include "content/child/child_process.h" +#include "content/renderer/media/media_stream_video_track.h" +#include "content/renderer/media/mock_media_stream_video_sink.h" +#include "content/renderer/media/mock_media_stream_video_source.h" +#include "media/base/video_frame.h" +#include "testing/gtest/include/gtest/gtest.h" +#include "third_party/WebKit/public/web/WebHeap.h" + +namespace content { + +const uint8_t kBlackValue = 0x00; +const uint8_t kColorValue = 0xAB; + +ACTION_P(RunClosure, closure) { + closure.Run(); +} + +class MediaStreamVideoTrackTest : public ::testing::Test { + public: + MediaStreamVideoTrackTest() + : child_process_(new ChildProcess()), + mock_source_(new MockMediaStreamVideoSource(false)), + source_started_(false) { + blink_source_.initialize(base::UTF8ToUTF16("dummy_source_id"), + blink::WebMediaStreamSource::TypeVideo, + base::UTF8ToUTF16("dummy_source_name"), + false /* remote */); + blink_source_.setExtraData(mock_source_); + } + + ~MediaStreamVideoTrackTest() override {} + + void TearDown() override { + blink_source_.reset(); + blink::WebHeap::collectAllGarbageForTesting(); + } + + void DeliverVideoFrameAndWaitForRenderer(MockMediaStreamVideoSink* sink) { + base::RunLoop run_loop; + base::Closure quit_closure = run_loop.QuitClosure(); + EXPECT_CALL(*sink, OnVideoFrame()).WillOnce(RunClosure(quit_closure)); + const scoped_refptr frame = + media::VideoFrame::CreateColorFrame( + gfx::Size(MediaStreamVideoSource::kDefaultWidth, + MediaStreamVideoSource::kDefaultHeight), + kColorValue, kColorValue, kColorValue, base::TimeDelta()); + mock_source()->DeliverVideoFrame(frame); + run_loop.Run(); + } + + protected: + base::MessageLoop* io_message_loop() const { + return child_process_->io_message_loop(); + } + + // Create a track that's associated with |mock_source_|. + blink::WebMediaStreamTrack CreateTrack() { + blink::WebMediaConstraints constraints; + constraints.initialize(); + const bool enabled = true; + blink::WebMediaStreamTrack track = + MediaStreamVideoTrack::CreateVideoTrack( + mock_source_, constraints, + MediaStreamSource::ConstraintsCallback(), enabled); + if (!source_started_) { + mock_source_->StartMockedSource(); + source_started_ = true; + } + return track; + } + + void UpdateVideoSourceToRespondToRequestRefreshFrame() { + blink_source_.reset(); + mock_source_ = new MockMediaStreamVideoSource(false, true); + blink_source_.initialize(base::UTF8ToUTF16("dummy_source_id"), + blink::WebMediaStreamSource::TypeVideo, + base::UTF8ToUTF16("dummy_source_name"), + false /* remote */); + blink_source_.setExtraData(mock_source_); + } + + MockMediaStreamVideoSource* mock_source() { return mock_source_; } + const blink::WebMediaStreamSource& blink_source() const { + return blink_source_; + } + + private: + const base::MessageLoopForUI message_loop_; + const std::unique_ptr child_process_; + blink::WebMediaStreamSource blink_source_; + // |mock_source_| is owned by |webkit_source_|. + MockMediaStreamVideoSource* mock_source_; + bool source_started_; +}; + +TEST_F(MediaStreamVideoTrackTest, AddAndRemoveSink) { + MockMediaStreamVideoSink sink; + blink::WebMediaStreamTrack track = CreateTrack(); + sink.ConnectToTrack(track); + + DeliverVideoFrameAndWaitForRenderer(&sink); + EXPECT_EQ(1, sink.number_of_frames()); + + DeliverVideoFrameAndWaitForRenderer(&sink); + + sink.DisconnectFromTrack(); + + scoped_refptr frame = + media::VideoFrame::CreateBlackFrame( + gfx::Size(MediaStreamVideoSource::kDefaultWidth, + MediaStreamVideoSource::kDefaultHeight)); + mock_source()->DeliverVideoFrame(frame); + // Wait for the IO thread to complete delivering frames. + base::RunLoop().RunUntilIdle(); + EXPECT_EQ(2, sink.number_of_frames()); +} + +class CheckThreadHelper { + public: + CheckThreadHelper(base::Closure callback, bool* correct) + : callback_(callback), + correct_(correct) { + } + + ~CheckThreadHelper() { + *correct_ = thread_checker_.CalledOnValidThread(); + callback_.Run(); + } + + private: + base::Closure callback_; + bool* correct_; + base::ThreadCheckerImpl thread_checker_; +}; + +void CheckThreadVideoFrameReceiver( + CheckThreadHelper* helper, + const scoped_refptr& frame, + base::TimeTicks estimated_capture_time) { + // Do nothing. +} + +// Checks that the callback given to the track is reset on the right thread. +TEST_F(MediaStreamVideoTrackTest, ResetCallbackOnThread) { + MockMediaStreamVideoSink sink; + blink::WebMediaStreamTrack track = CreateTrack(); + + base::RunLoop run_loop; + bool correct = false; + sink.ConnectToTrackWithCallback( + track, + base::Bind(&CheckThreadVideoFrameReceiver, + base::Owned(new CheckThreadHelper(run_loop.QuitClosure(), + &correct)))); + sink.DisconnectFromTrack(); + run_loop.Run(); + EXPECT_TRUE(correct) << "Not called on correct thread."; +} + +TEST_F(MediaStreamVideoTrackTest, SetEnabled) { + MockMediaStreamVideoSink sink; + blink::WebMediaStreamTrack track = CreateTrack(); + sink.ConnectToTrack(track); + + MediaStreamVideoTrack* video_track = + MediaStreamVideoTrack::GetVideoTrack(track); + + DeliverVideoFrameAndWaitForRenderer(&sink); + EXPECT_EQ(1, sink.number_of_frames()); + EXPECT_EQ(kColorValue, *sink.last_frame()->data(media::VideoFrame::kYPlane)); + + video_track->SetEnabled(false); + EXPECT_FALSE(sink.enabled()); + + DeliverVideoFrameAndWaitForRenderer(&sink); + EXPECT_EQ(2, sink.number_of_frames()); + EXPECT_EQ(kBlackValue, *sink.last_frame()->data(media::VideoFrame::kYPlane)); + + video_track->SetEnabled(true); + EXPECT_TRUE(sink.enabled()); + DeliverVideoFrameAndWaitForRenderer(&sink); + EXPECT_EQ(3, sink.number_of_frames()); + EXPECT_EQ(kColorValue, *sink.last_frame()->data(media::VideoFrame::kYPlane)); + sink.DisconnectFromTrack(); +} + +TEST_F(MediaStreamVideoTrackTest, SourceStopped) { + MockMediaStreamVideoSink sink; + blink::WebMediaStreamTrack track = CreateTrack(); + sink.ConnectToTrack(track); + EXPECT_EQ(blink::WebMediaStreamSource::ReadyStateLive, sink.state()); + + mock_source()->StopSource(); + EXPECT_EQ(blink::WebMediaStreamSource::ReadyStateEnded, sink.state()); + sink.DisconnectFromTrack(); +} + +TEST_F(MediaStreamVideoTrackTest, StopLastTrack) { + MockMediaStreamVideoSink sink1; + blink::WebMediaStreamTrack track1 = CreateTrack(); + sink1.ConnectToTrack(track1); + EXPECT_EQ(blink::WebMediaStreamSource::ReadyStateLive, sink1.state()); + + EXPECT_EQ(blink::WebMediaStreamSource::ReadyStateLive, + blink_source().getReadyState()); + + MockMediaStreamVideoSink sink2; + blink::WebMediaStreamTrack track2 = CreateTrack(); + sink2.ConnectToTrack(track2); + EXPECT_EQ(blink::WebMediaStreamSource::ReadyStateLive, sink2.state()); + + MediaStreamVideoTrack* const native_track1 = + MediaStreamVideoTrack::GetVideoTrack(track1); + native_track1->Stop(); + EXPECT_EQ(blink::WebMediaStreamSource::ReadyStateEnded, sink1.state()); + EXPECT_EQ(blink::WebMediaStreamSource::ReadyStateLive, + blink_source().getReadyState()); + sink1.DisconnectFromTrack(); + + MediaStreamVideoTrack* const native_track2 = + MediaStreamVideoTrack::GetVideoTrack(track2); + native_track2->Stop(); + EXPECT_EQ(blink::WebMediaStreamSource::ReadyStateEnded, sink2.state()); + EXPECT_EQ(blink::WebMediaStreamSource::ReadyStateEnded, + blink_source().getReadyState()); + sink2.DisconnectFromTrack(); +} + +TEST_F(MediaStreamVideoTrackTest, CheckTrackRequestsFrame) { + UpdateVideoSourceToRespondToRequestRefreshFrame(); + blink::WebMediaStreamTrack track = CreateTrack(); + + // Add sink and expect to get a frame. + MockMediaStreamVideoSink sink; + base::RunLoop run_loop; + base::Closure quit_closure = run_loop.QuitClosure(); + EXPECT_CALL(sink, OnVideoFrame()).WillOnce(RunClosure(quit_closure)); + sink.ConnectToTrack(track); + run_loop.Run(); + EXPECT_EQ(1, sink.number_of_frames()); + + sink.DisconnectFromTrack(); +} + +} // namespace content diff --git a/pool/shard002/C++/0024591_UdpSocket.cpp b/pool/shard002/C++/0024591_UdpSocket.cpp new file mode 100644 index 0000000000000000000000000000000000000000..95f20bae53531fb897c945283b833de5c4b6e81d --- /dev/null +++ b/pool/shard002/C++/0024591_UdpSocket.cpp @@ -0,0 +1,76 @@ +/* UdpSocket.cpp + + Copyright (C) 2014 - 2021 Marc Postema (mpostema09 -at- gmail.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 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. + Or, point your browser to http://www.gnu.org/copyleft/gpl.html +*/ +#include + +#include +#include + +#include +#include +#include +#include + +UdpSocket::UdpSocket() {} + +UdpSocket::~UdpSocket() {} + +bool UdpSocket::initUDPSocket( + SocketClient &server, + const std::string &ipAddr, + int port) { + // fill in the socket structure with host information + server.setupSocketStructure(ipAddr, port); + + if (!server.setupSocketHandle(SOCK_DGRAM, IPPROTO_UDP)) { + SI_LOG_ERROR("UDP Server handle failed"); + return false; + } + return true; +} + +bool UdpSocket::initMutlicastUDPSocket( + SocketClient &server, + const std::string &multicastIPAddr, + const std::string &interfaceIPaddr, + int port) { + // fill in the socket structure with host information + server.setupSocketStructureWithAnyAddress(port); + + if (!server.setupSocketHandle(SOCK_DGRAM, IPPROTO_UDP)) { + SI_LOG_ERROR("UDP Multicast Server handle failed"); + return false; + } + + // bind the socket to the port number + if (!server.bind()) { + SI_LOG_ERROR("UDP Multicast Bind failed"); + return false; + } + + // request that the kernel joins a multicast group + struct ip_mreq mreq; + mreq.imr_multiaddr.s_addr = inet_addr(multicastIPAddr.c_str()); + mreq.imr_interface.s_addr = inet_addr(interfaceIPaddr.c_str()); + if (setsockopt(server.getFD(), IPPROTO_IP, IP_ADD_MEMBERSHIP, &mreq, sizeof(mreq)) == -1) { + SI_LOG_PERROR("IP_ADD_MEMBERSHIP"); + return false; + } + return true; +} diff --git a/pool/shard002/C++/0024593_higemaru.cpp b/pool/shard002/C++/0024593_higemaru.cpp new file mode 100644 index 0000000000000000000000000000000000000000..1b40c6e432030c3e9aed598a4faaa01677afbbe8 --- /dev/null +++ b/pool/shard002/C++/0024593_higemaru.cpp @@ -0,0 +1,142 @@ +// license:BSD-3-Clause +// copyright-holders:Mirko Buffoni +#include "emu.h" +#include "includes/higemaru.h" + +void higemaru_state::higemaru_videoram_w(offs_t offset, uint8_t data) +{ + m_videoram[offset] = data; + m_bg_tilemap->mark_tile_dirty(offset); +} + +void higemaru_state::higemaru_colorram_w(offs_t offset, uint8_t data) +{ + m_colorram[offset] = data; + m_bg_tilemap->mark_tile_dirty(offset); +} + +/*************************************************************************** + + Convert the color PROMs into a more useable format. + +***************************************************************************/ + +void higemaru_state::higemaru_palette(palette_device &palette) const +{ + const uint8_t *color_prom = memregion("proms")->base(); + + // create a lookup table for the palette + for (int i = 0; i < 0x20; i++) + { + int bit0, bit1, bit2; + + // red component + bit0 = (color_prom[i] >> 0) & 0x01; + bit1 = (color_prom[i] >> 1) & 0x01; + bit2 = (color_prom[i] >> 2) & 0x01; + int const r = 0x21 * bit0 + 0x47 * bit1 + 0x97 * bit2; + + // green component + bit0 = (color_prom[i] >> 3) & 0x01; + bit1 = (color_prom[i] >> 4) & 0x01; + bit2 = (color_prom[i] >> 5) & 0x01; + int const g = 0x21 * bit0 + 0x47 * bit1 + 0x97 * bit2; + + // blue component + bit0 = 0; + bit1 = (color_prom[i] >> 6) & 0x01; + bit2 = (color_prom[i] >> 7) & 0x01; + int const b = 0x21 * bit0 + 0x47 * bit1 + 0x97 * bit2; + + palette.set_indirect_color(i, rgb_t(r, g, b)); + } + + // color_prom now points to the beginning of the lookup table + color_prom += 0x20; + + // characters use colors 0-15 + for (int i = 0; i < 0x80; i++) + { + uint8_t const ctabentry = color_prom[i] & 0x0f; + palette.set_pen_indirect(i, ctabentry); + } + + // sprites use colors 16-31 + for (int i = 0x80; i < 0x180; i++) + { + uint8_t const ctabentry = (color_prom[i + 0x80] & 0x0f) | 0x10; + palette.set_pen_indirect(i, ctabentry); + } +} + +void higemaru_state::higemaru_c800_w(uint8_t data) +{ + if (data & 0x7c) + logerror("c800 = %02x\n",data); + + /* bits 0 and 1 are coin counters */ + machine().bookkeeping().coin_counter_w(0,data & 2); + machine().bookkeeping().coin_counter_w(1,data & 1); + + /* bit 7 flips screen */ + if (flip_screen() != (data & 0x80)) + { + flip_screen_set(data & 0x80); + m_bg_tilemap->mark_all_dirty(); + } +} + +TILE_GET_INFO_MEMBER(higemaru_state::get_bg_tile_info) +{ + int code = m_videoram[tile_index] + ((m_colorram[tile_index] & 0x80) << 1); + int color = m_colorram[tile_index] & 0x1f; + + tileinfo.set(0, code, color, 0); +} + +void higemaru_state::video_start() +{ + m_bg_tilemap = &machine().tilemap().create(*m_gfxdecode, tilemap_get_info_delegate(*this, FUNC(higemaru_state::get_bg_tile_info)), TILEMAP_SCAN_ROWS, 8, 8, 32, 32); +} + +void higemaru_state::draw_sprites(bitmap_ind16 &bitmap, const rectangle &cliprect) +{ + uint8_t *spriteram = m_spriteram; + + for (int offs = m_spriteram.bytes() - 16; offs >= 0; offs -= 16) + { + int const code = spriteram[offs] & 0x7f; + int col = spriteram[offs + 4] & 0x0f; + int sx = spriteram[offs + 12]; + int sy = spriteram[offs + 8]; + int flipx = spriteram[offs + 4] & 0x10; + int flipy = spriteram[offs + 4] & 0x20; + if (flip_screen()) + { + sx = 240 - sx; + sy = 240 - sy; + flipx = !flipx; + flipy = !flipy; + } + + m_gfxdecode->gfx(1)->transpen(bitmap,cliprect, + code, + col, + flipx,flipy, + sx,sy,15); + + /* draw again with wraparound */ + m_gfxdecode->gfx(1)->transpen(bitmap,cliprect, + code, + col, + flipx,flipy, + sx - 256,sy,15); + } +} + +uint32_t higemaru_state::screen_update_higemaru(screen_device &screen, bitmap_ind16 &bitmap, const rectangle &cliprect) +{ + m_bg_tilemap->draw(screen, bitmap, cliprect, 0, 0); + draw_sprites(bitmap, cliprect); + return 0; +} diff --git a/pool/shard002/C++/0024596_TestProtocol.cc b/pool/shard002/C++/0024596_TestProtocol.cc new file mode 100644 index 0000000000000000000000000000000000000000..437d1a9127782157a30f476896c1a49f33998ce2 --- /dev/null +++ b/pool/shard002/C++/0024596_TestProtocol.cc @@ -0,0 +1,104 @@ +//----------------------------------------------------------------------------- +// #version:11# machine generated, do not edit! +//----------------------------------------------------------------------------- +#include "Pre.h" +#include "TestProtocol.h" + +namespace Oryol { +OryolClassImpl(TestProtocol::TestMsg1); +OryolClassImpl(TestProtocol::TestMsg2); +OryolClassImpl(TestProtocol::TestArrayMsg); +TestProtocol::CreateCallback TestProtocol::jumpTable[TestProtocol::MessageId::NumMessageIds] = { + &TestProtocol::TestMsg1::FactoryCreate, + &TestProtocol::TestMsg2::FactoryCreate, + &TestProtocol::TestArrayMsg::FactoryCreate, +}; +Ptr +TestProtocol::Factory::Create(MessageIdType id) { + if (id < Protocol::MessageId::NumMessageIds) { + return Protocol::Factory::Create(id); + } + else { + o_assert(id < TestProtocol::MessageId::NumMessageIds); + return jumpTable[id - Protocol::MessageId::NumMessageIds](); + }; +} +int32 TestProtocol::TestMsg1::EncodedSize() const { + int32 s = Message::EncodedSize(); + s += Serializer::EncodedSize(this->int8val); + s += Serializer::EncodedSize(this->int16val); + s += Serializer::EncodedSize(this->int32val); + s += Serializer::EncodedSize(this->int64val); + s += Serializer::EncodedSize(this->uint8val); + s += Serializer::EncodedSize(this->uint16val); + s += Serializer::EncodedSize(this->uint32val); + s += Serializer::EncodedSize(this->uint64val); + s += Serializer::EncodedSize(this->float32val); + s += Serializer::EncodedSize(this->float64val); + return s; +} +uint8* TestProtocol::TestMsg1::Encode(uint8* dstPtr, const uint8* maxValidPtr) const { + dstPtr = Message::Encode(dstPtr, maxValidPtr); + dstPtr = Serializer::Encode(this->int8val, dstPtr, maxValidPtr); + dstPtr = Serializer::Encode(this->int16val, dstPtr, maxValidPtr); + dstPtr = Serializer::Encode(this->int32val, dstPtr, maxValidPtr); + dstPtr = Serializer::Encode(this->int64val, dstPtr, maxValidPtr); + dstPtr = Serializer::Encode(this->uint8val, dstPtr, maxValidPtr); + dstPtr = Serializer::Encode(this->uint16val, dstPtr, maxValidPtr); + dstPtr = Serializer::Encode(this->uint32val, dstPtr, maxValidPtr); + dstPtr = Serializer::Encode(this->uint64val, dstPtr, maxValidPtr); + dstPtr = Serializer::Encode(this->float32val, dstPtr, maxValidPtr); + dstPtr = Serializer::Encode(this->float64val, dstPtr, maxValidPtr); + return dstPtr; +} +const uint8* TestProtocol::TestMsg1::Decode(const uint8* srcPtr, const uint8* maxValidPtr) { + srcPtr = Message::Decode(srcPtr, maxValidPtr); + srcPtr = Serializer::Decode(srcPtr, maxValidPtr, this->int8val); + srcPtr = Serializer::Decode(srcPtr, maxValidPtr, this->int16val); + srcPtr = Serializer::Decode(srcPtr, maxValidPtr, this->int32val); + srcPtr = Serializer::Decode(srcPtr, maxValidPtr, this->int64val); + srcPtr = Serializer::Decode(srcPtr, maxValidPtr, this->uint8val); + srcPtr = Serializer::Decode(srcPtr, maxValidPtr, this->uint16val); + srcPtr = Serializer::Decode(srcPtr, maxValidPtr, this->uint32val); + srcPtr = Serializer::Decode(srcPtr, maxValidPtr, this->uint64val); + srcPtr = Serializer::Decode(srcPtr, maxValidPtr, this->float32val); + srcPtr = Serializer::Decode(srcPtr, maxValidPtr, this->float64val); + return srcPtr; +} +int32 TestProtocol::TestMsg2::EncodedSize() const { + int32 s = TestMsg1::EncodedSize(); + s += Serializer::EncodedSize(this->stringval); + s += Serializer::EncodedSize(this->stringatomval); + return s; +} +uint8* TestProtocol::TestMsg2::Encode(uint8* dstPtr, const uint8* maxValidPtr) const { + dstPtr = TestMsg1::Encode(dstPtr, maxValidPtr); + dstPtr = Serializer::Encode(this->stringval, dstPtr, maxValidPtr); + dstPtr = Serializer::Encode(this->stringatomval, dstPtr, maxValidPtr); + return dstPtr; +} +const uint8* TestProtocol::TestMsg2::Decode(const uint8* srcPtr, const uint8* maxValidPtr) { + srcPtr = TestMsg1::Decode(srcPtr, maxValidPtr); + srcPtr = Serializer::Decode(srcPtr, maxValidPtr, this->stringval); + srcPtr = Serializer::Decode(srcPtr, maxValidPtr, this->stringatomval); + return srcPtr; +} +int32 TestProtocol::TestArrayMsg::EncodedSize() const { + int32 s = Message::EncodedSize(); + s += Serializer::EncodedArraySize(this->int32arrayval); + s += Serializer::EncodedArraySize(this->stringarrayval); + return s; +} +uint8* TestProtocol::TestArrayMsg::Encode(uint8* dstPtr, const uint8* maxValidPtr) const { + dstPtr = Message::Encode(dstPtr, maxValidPtr); + dstPtr = Serializer::EncodeArray(this->int32arrayval, dstPtr, maxValidPtr); + dstPtr = Serializer::EncodeArray(this->stringarrayval, dstPtr, maxValidPtr); + return dstPtr; +} +const uint8* TestProtocol::TestArrayMsg::Decode(const uint8* srcPtr, const uint8* maxValidPtr) { + srcPtr = Message::Decode(srcPtr, maxValidPtr); + srcPtr = Serializer::DecodeArray(srcPtr, maxValidPtr, this->int32arrayval); + srcPtr = Serializer::DecodeArray(srcPtr, maxValidPtr, this->stringarrayval); + return srcPtr; +} +} diff --git a/pool/shard002/C++/0024603_ZmqContext.cpp b/pool/shard002/C++/0024603_ZmqContext.cpp new file mode 100644 index 0000000000000000000000000000000000000000..bc062de8e880be7d5ad2e50b9672c54fedeaf1f5 --- /dev/null +++ b/pool/shard002/C++/0024603_ZmqContext.cpp @@ -0,0 +1,55 @@ +/* + * Copyright (C) 2008-2016 TrinityCore + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the + * Free Software Foundation; either version 2 of the License, or (at your + * option) any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + * + * You should have received a copy of the GNU General Public License along + * with this program. If not, see . + */ + +#include "ZmqContext.h" + +ZmqContext::ZmqContext() : _inproc(nullptr) +{ +} + +ZmqContext::~ZmqContext() +{ +} + +zmqpp::socket* ZmqContext::CreateNewSocket(zmqpp::socket_type type) +{ + std::unique_lock lock(_mutex); + zmqpp::socket* socket = new zmqpp::socket(_context, type); + socket->set(zmqpp::socket_option::linger, 0); + return socket; +} + +void ZmqContext::Initialize() +{ + _inproc = new zmqpp::socket(_context, zmqpp::socket_type::pub); + _inproc->bind("inproc://workers"); +} + +zmqpp::socket* ZmqContext::CreateInprocSubscriber() +{ + zmqpp::socket* sub = CreateNewSocket(zmqpp::socket_type::sub); + sub->connect("inproc://workers"); + sub->subscribe("internalmq."); + return sub; +} + +void ZmqContext::Close() +{ + _inproc->send("internalmq.kill"); + delete _inproc; + _inproc = nullptr; +} diff --git a/pool/shard002/C++/0024605_ut_path.cpp b/pool/shard002/C++/0024605_ut_path.cpp new file mode 100644 index 0000000000000000000000000000000000000000..2c0bbe543304407bd93d70c9c6cd2253698f7d81 --- /dev/null +++ b/pool/shard002/C++/0024605_ut_path.cpp @@ -0,0 +1,133 @@ +/* AbiSource Program Utilities + * Copyright (C) 1998-2000 AbiSource, 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 "ut_path.h" +#include "ut_string_class.h" +#include "ut_assert.h" + +#include +#include +#include +#include + +/*! This function takes a char* representing a path to a file and returns + the pointer to the string which represents the base portion of the path. + + For example, if path = "/home/foo/bar.ext", then this function returns + a char* pointing to "bar.ext". + */ + +const char* UT_basename(const char* path) +{ + size_t len = strlen(path); + const char* str = &path[len]; + + while(len > 0 && path[len-1] != '/') + str = &path[--len]; + + return str; +} + +/*! + if dir is an existing directory, this function + returns true, otherwise, it returns false +*/ + +bool UT_directoryExists(const char* dir) +{ + struct stat buf; + + if (stat(dir, &buf) != -1) + { + return S_ISDIR (buf.st_mode); + } + + return false; +} + +bool UT_isRegularFile(const char* filename) +{ + struct stat buf; + + if (stat(filename, &buf) != -1) + { + return S_ISREG (buf.st_mode); + } + + return false; +} + +size_t UT_fileSize(const char * filename) +{ + struct stat buf; + + if (stat(filename, &buf) != -1) + { + return buf.st_size; + } + + return 0; +} + + + +/*! + If the directory/file 'path' exist its mtime (modification time) is returned +*/ +time_t UT_mTime(const char* path) +{ + struct stat buf; + + if (stat(path, &buf) != -1) + { + return(buf.st_mtime); + } + + return((time_t)-1); +} + +/*! + check that the given filename is legal and remove any illegal characters + \param filename [in/out] the suggested file name + \return false if filename is left unchanged, true otherwise + */ +bool UT_legalizeFileName(std::string &filename) +{ + bool bRet = false; + + char *tmp = g_strdup(filename.c_str()); + char *ptr = tmp; + + while (*ptr) { + if (*ptr == '/') { + *ptr = '-'; + bRet = true; + } + ptr++; + } + + if(bRet) { + filename = tmp; + } + + FREEP(tmp); + + return bRet; +} diff --git a/pool/shard002/C/0056498_dtools.c b/pool/shard002/C/0056498_dtools.c new file mode 100644 index 0000000000000000000000000000000000000000..29b608e777e344313997dd9b3751f08953692bba --- /dev/null +++ b/pool/shard002/C/0056498_dtools.c @@ -0,0 +1,62 @@ +/** + * \file DPosition.c + * \brief Source des outils de conversion + * \author P.-E. Hladik + * \version 0.1 + * \date 29 novembre 2011 + * + * Implémentation des outils de conversions + * + */ + +#include "../headers/dtools.h" + +#include +#include + +#include + +#include +#include +#include + +void d_tools_int2bytes(unsigned int i, char* b) { + *b = (i >> 24) & 0xFF; + *(b + 1) = (i >> 16) & 0xFF; + *(b + 2) = (i >> 8) & 0xFF; + *(b + 3) = i & 0xFF; +} + +unsigned int d_tools_bytes2int(char *b) { + unsigned int i; + i = (unsigned int) ((*(b) << 24)& 0xFF000000) + + (unsigned int) ((*(b + 1) << 16)& 0xFF0000) + + (unsigned int) ((*(b + 2) << 8)& 0xFF00) + + (unsigned int) (*(b + 3) & 0xFF); + return i; +} + +void d_tools_cvbox2cvrect(CvBox2D box, CvRect *rect) { + CvPoint2D32f box_vtx[4]; + cvBoxPoints(box, box_vtx); + + rect->x = box_vtx[3].x; + rect->y = box_vtx[0].y; + rect->height = abs(box_vtx[0].y - box_vtx[2].y); + rect->width = abs(box_vtx[1].x - box_vtx[3].x); + +} + +long long d_tools_get_time_in_millisec() { + // On récupère l'heure dans une structure "timeval" + struct timeval tv; + gettimeofday(&tv, NULL); + + // On la convertit en millisecondes à partir des secondes et + // des microsecondes + long long l = tv.tv_usec / 1000; + l += tv.tv_sec * 1000; + + return l; +} + diff --git a/pool/shard002/C/0056512_adreno_compat.c b/pool/shard002/C/0056512_adreno_compat.c new file mode 100644 index 0000000000000000000000000000000000000000..7c021fa31f128a798df2cf11011dfa9b80fd7200 --- /dev/null +++ b/pool/shard002/C/0056512_adreno_compat.c @@ -0,0 +1,207 @@ +/* Copyright (c) 2013-2015, 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 "kgsl.h" +#include "kgsl_compat.h" + +#include "adreno.h" +#include "adreno_compat.h" + +int adreno_getproperty_compat(struct kgsl_device *device, + enum kgsl_property_type type, + void __user *value, + size_t sizebytes) +{ + int status = -EINVAL; + struct adreno_device *adreno_dev = ADRENO_DEVICE(device); + + switch (type) { + case KGSL_PROP_DEVICE_INFO: + { + struct kgsl_devinfo_compat devinfo; + + if (sizebytes != sizeof(devinfo)) { + status = -EINVAL; + break; + } + + memset(&devinfo, 0, sizeof(devinfo)); + devinfo.device_id = device->id + 1; + devinfo.chip_id = adreno_dev->chipid; + devinfo.mmu_enabled = kgsl_mmu_enabled(); + devinfo.gmem_gpubaseaddr = adreno_dev->gmem_base; + devinfo.gmem_sizebytes = adreno_dev->gmem_size; + + if (copy_to_user(value, &devinfo, sizeof(devinfo)) != + 0) { + status = -EFAULT; + break; + } + status = 0; + } + break; + case KGSL_PROP_DEVICE_SHADOW: + { + struct kgsl_shadowprop_compat shadowprop; + + if (sizebytes != sizeof(shadowprop)) { + status = -EINVAL; + break; + } + memset(&shadowprop, 0, sizeof(shadowprop)); + if (device->memstore.hostptr) { + /* + * NOTE: with mmu enabled, gpuaddr doesn't mean + * anything to mmap(). + * NOTE: shadowprop.gpuaddr is uint32 + * (because legacy) and the memstore gpuaddr is + * 64 bit. Cast the memstore gpuaddr to uint32. + */ + shadowprop.gpuaddr = + (unsigned int) device->memstore.gpuaddr; + shadowprop.size = + (unsigned int) device->memstore.size; + /* + * GSL needs this to be set, even if it + * appears to be meaningless + */ + shadowprop.flags = KGSL_FLAGS_INITIALIZED | + KGSL_FLAGS_PER_CONTEXT_TIMESTAMPS; + } + if (copy_to_user(value, &shadowprop, + sizeof(shadowprop))) { + status = -EFAULT; + break; + } + status = 0; + } + break; + default: + /* + * Call the adreno_getproperty to check if the property type + * was KGSL_PROP_MMU_ENABLE or KGSL_PROP_INTERRUPT_WAITS + */ + status = device->ftbl->getproperty(device, type, value, + sizebytes); + } + + return status; +} + +int adreno_setproperty_compat(struct kgsl_device_private *dev_priv, + enum kgsl_property_type type, + void __user *value, + unsigned int sizebytes) +{ + int status = -EINVAL; + struct kgsl_device *device = dev_priv->device; + + switch (type) { + case KGSL_PROP_PWR_CONSTRAINT: { + struct kgsl_device_constraint_compat constraint32; + struct kgsl_device_constraint constraint; + struct kgsl_context *context; + + if (sizebytes != sizeof(constraint32)) + break; + + if (copy_from_user(&constraint32, value, + sizeof(constraint32))) { + status = -EFAULT; + break; + } + + /* Populate the real constraint type from the compat */ + constraint.type = constraint32.type; + constraint.context_id = constraint32.context_id; + constraint.data = compat_ptr(constraint32.data); + constraint.size = (size_t)constraint32.size; + + context = kgsl_context_get_owner(dev_priv, + constraint.context_id); + if (context == NULL) + break; + status = adreno_set_constraint(device, context, + &constraint); + kgsl_context_put(context); + } + break; + default: + /* + * Call adreno_setproperty in case the property type was + * KGSL_PROP_PWRCTRL + */ + status = device->ftbl->setproperty(dev_priv, type, value, + sizebytes); + } + + return status; +} + +static long adreno_ioctl_perfcounter_query_compat( + struct kgsl_device_private *dev_priv, unsigned int cmd, + void *data) +{ + struct adreno_device *adreno_dev = ADRENO_DEVICE(dev_priv->device); + struct kgsl_perfcounter_query_compat *query32 = data; + struct kgsl_perfcounter_query query; + long result; + + query.groupid = query32->groupid; + query.countables = + (unsigned int __user *)(uintptr_t) query32->countables; + query.count = query32->count; + query.max_counters = query32->max_counters; + + result = adreno_perfcounter_query_group(adreno_dev, + query.groupid, query.countables, + query.count, &query.max_counters); + query32->max_counters = query.max_counters; + + return result; +} + +static long adreno_ioctl_perfcounter_read_compat( + struct kgsl_device_private *dev_priv, unsigned int cmd, + void *data) +{ + struct adreno_device *adreno_dev = ADRENO_DEVICE(dev_priv->device); + struct kgsl_perfcounter_read_compat *read32 = data; + struct kgsl_perfcounter_read read; + + read.reads = (struct kgsl_perfcounter_read_group __user *) + (uintptr_t)read32->reads; + read.count = read32->count; + + return adreno_perfcounter_read_group(adreno_dev, read.reads, + read.count); +} + +static struct kgsl_ioctl adreno_compat_ioctl_funcs[] = { + { IOCTL_KGSL_PERFCOUNTER_GET, adreno_ioctl_perfcounter_get }, + { IOCTL_KGSL_PERFCOUNTER_PUT, adreno_ioctl_perfcounter_put }, + { IOCTL_KGSL_PERFCOUNTER_QUERY_COMPAT, + adreno_ioctl_perfcounter_query_compat }, + { IOCTL_KGSL_PERFCOUNTER_READ_COMPAT, + adreno_ioctl_perfcounter_read_compat }, +}; + +long adreno_compat_ioctl(struct kgsl_device_private *dev_priv, + unsigned int cmd, unsigned long arg) +{ + return adreno_ioctl_helper(dev_priv, cmd, arg, + adreno_compat_ioctl_funcs, + ARRAY_SIZE(adreno_compat_ioctl_funcs)); +} diff --git a/pool/shard002/C/0056529_CertRefReq.c b/pool/shard002/C/0056529_CertRefReq.c new file mode 100644 index 0000000000000000000000000000000000000000..3b7f62cd887b4206a728caaf7b8bca22c1522281 --- /dev/null +++ b/pool/shard002/C/0056529_CertRefReq.c @@ -0,0 +1,127 @@ +/* + * Generated by asn1c-0.9.22 (http://lionet.info/asn1c) + * From ASN.1 module "ETS-ElectronicSignaturePolicies-88syntax" + * found in "lpa2.asn1" + * `asn1c -S/skeletons` + */ + +#include + +#include "CertRefReq.h" + +int +CertRefReq_constraint(asn_TYPE_descriptor_t *td, const void *sptr, + asn_app_constraint_failed_f *ctfailcb, void *app_key) { + /* Replace with underlying type checker */ + td->check_constraints = asn_DEF_NativeEnumerated.check_constraints; + return td->check_constraints(td, sptr, ctfailcb, app_key); +} + +/* + * This type is implemented using NativeEnumerated, + * so here we adjust the DEF accordingly. + */ +static void +CertRefReq_1_inherit_TYPE_descriptor(asn_TYPE_descriptor_t *td) { + td->free_struct = asn_DEF_NativeEnumerated.free_struct; + td->print_struct = asn_DEF_NativeEnumerated.print_struct; + td->ber_decoder = asn_DEF_NativeEnumerated.ber_decoder; + td->der_encoder = asn_DEF_NativeEnumerated.der_encoder; + td->xer_decoder = asn_DEF_NativeEnumerated.xer_decoder; + td->xer_encoder = asn_DEF_NativeEnumerated.xer_encoder; + td->uper_decoder = asn_DEF_NativeEnumerated.uper_decoder; + td->uper_encoder = asn_DEF_NativeEnumerated.uper_encoder; + if(!td->per_constraints) + td->per_constraints = asn_DEF_NativeEnumerated.per_constraints; + td->elements = asn_DEF_NativeEnumerated.elements; + td->elements_count = asn_DEF_NativeEnumerated.elements_count; + /* td->specifics = asn_DEF_NativeEnumerated.specifics; // Defined explicitly */ +} + +void +CertRefReq_free(asn_TYPE_descriptor_t *td, + void *struct_ptr, int contents_only) { + CertRefReq_1_inherit_TYPE_descriptor(td); + td->free_struct(td, struct_ptr, contents_only); +} + +int +CertRefReq_print(asn_TYPE_descriptor_t *td, const void *struct_ptr, + int ilevel, asn_app_consume_bytes_f *cb, void *app_key) { + CertRefReq_1_inherit_TYPE_descriptor(td); + return td->print_struct(td, struct_ptr, ilevel, cb, app_key); +} + +asn_dec_rval_t +CertRefReq_decode_ber(asn_codec_ctx_t *opt_codec_ctx, asn_TYPE_descriptor_t *td, + void **structure, const void *bufptr, size_t size, int tag_mode) { + CertRefReq_1_inherit_TYPE_descriptor(td); + return td->ber_decoder(opt_codec_ctx, td, structure, bufptr, size, tag_mode); +} + +asn_enc_rval_t +CertRefReq_encode_der(asn_TYPE_descriptor_t *td, + void *structure, int tag_mode, ber_tlv_tag_t tag, + asn_app_consume_bytes_f *cb, void *app_key) { + CertRefReq_1_inherit_TYPE_descriptor(td); + return td->der_encoder(td, structure, tag_mode, tag, cb, app_key); +} + +asn_dec_rval_t +CertRefReq_decode_xer(asn_codec_ctx_t *opt_codec_ctx, asn_TYPE_descriptor_t *td, + void **structure, const char *opt_mname, const void *bufptr, size_t size) { + CertRefReq_1_inherit_TYPE_descriptor(td); + return td->xer_decoder(opt_codec_ctx, td, structure, opt_mname, bufptr, size); +} + +asn_enc_rval_t +CertRefReq_encode_xer(asn_TYPE_descriptor_t *td, void *structure, + int ilevel, enum xer_encoder_flags_e flags, + asn_app_consume_bytes_f *cb, void *app_key) { + CertRefReq_1_inherit_TYPE_descriptor(td); + return td->xer_encoder(td, structure, ilevel, flags, cb, app_key); +} + +static asn_INTEGER_enum_map_t asn_MAP_CertRefReq_value2enum_1[] = { + { 1, 10, "signerOnly" }, + { 2, 8, "fullPath" } +}; +static unsigned int asn_MAP_CertRefReq_enum2value_1[] = { + 1, /* fullPath(2) */ + 0 /* signerOnly(1) */ +}; +static asn_INTEGER_specifics_t asn_SPC_CertRefReq_specs_1 = { + asn_MAP_CertRefReq_value2enum_1, /* "tag" => N; sorted by tag */ + asn_MAP_CertRefReq_enum2value_1, /* N => "tag"; sorted by N */ + 2, /* Number of elements in the maps */ + 0, /* Enumeration is not extensible */ + 1, /* Strict enumeration */ + 0, /* Native long size */ + 0 +}; +static ber_tlv_tag_t asn_DEF_CertRefReq_tags_1[] = { + (ASN_TAG_CLASS_UNIVERSAL | (10 << 2)) +}; +asn_TYPE_descriptor_t asn_DEF_CertRefReq = { + "CertRefReq", + "CertRefReq", + CertRefReq_free, + CertRefReq_print, + CertRefReq_constraint, + CertRefReq_decode_ber, + CertRefReq_encode_der, + CertRefReq_decode_xer, + CertRefReq_encode_xer, + 0, 0, /* No PER support, use "-gen-PER" to enable */ + 0, /* Use generic outmost tag fetcher */ + asn_DEF_CertRefReq_tags_1, + sizeof(asn_DEF_CertRefReq_tags_1) + /sizeof(asn_DEF_CertRefReq_tags_1[0]), /* 1 */ + asn_DEF_CertRefReq_tags_1, /* Same as above */ + sizeof(asn_DEF_CertRefReq_tags_1) + /sizeof(asn_DEF_CertRefReq_tags_1[0]), /* 1 */ + 0, /* No PER visible constraints */ + 0, 0, /* Defined elsewhere */ + &asn_SPC_CertRefReq_specs_1 /* Additional specs */ +}; + diff --git a/pool/shard002/C/0056533_mips_init.c b/pool/shard002/C/0056533_mips_init.c new file mode 100644 index 0000000000000000000000000000000000000000..8dd283deefec4693a3e065a8e852fb3656a01bb9 --- /dev/null +++ b/pool/shard002/C/0056533_mips_init.c @@ -0,0 +1,130 @@ + +/* mips_init.c - MSA optimised filter functions + * + * Copyright (c) 2018 Cosmin Truta + * Copyright (c) 2016 Glenn Randers-Pehrson + * Written by Mandar Sahastrabuddhe, 2016. + * + * This code is released under the libpng license. + * For conditions of distribution and use, see the disclaimer + * and license in png.h + */ + +/* Below, after checking __linux__, various non-C90 POSIX 1003.1 functions are + * called. + */ +#define _POSIX_SOURCE 1 + +#include +#include "../pngpriv.h" + +#ifdef PNG_READ_SUPPORTED + +#if PNG_MIPS_MSA_OPT > 0 +#ifdef PNG_MIPS_MSA_CHECK_SUPPORTED /* Do run-time checks */ +/* WARNING: it is strongly recommended that you do not build libpng with + * run-time checks for CPU features if at all possible. In the case of the MIPS + * MSA instructions there is no processor-specific way of detecting the + * presence of the required support, therefore run-time detection is extremely + * OS specific. + * + * You may set the macro PNG_MIPS_MSA_FILE to the file name of file containing + * a fragment of C source code which defines the png_have_msa function. There + * are a number of implementations in contrib/mips-msa, but the only one that + * has partial support is contrib/mips-msa/linux.c - a generic Linux + * implementation which reads /proc/cpufino. + */ +#ifndef PNG_MIPS_MSA_FILE +# ifdef __linux__ +# define PNG_MIPS_MSA_FILE "contrib/mips-msa/linux.c" +# endif +#endif + +#ifdef PNG_MIPS_MSA_FILE + +#include /* for sig_atomic_t */ +static int png_have_msa(png_structp png_ptr); +#include PNG_MIPS_MSA_FILE + +#else /* PNG_MIPS_MSA_FILE */ +# error "PNG_MIPS_MSA_FILE undefined: no support for run-time MIPS MSA checks" +#endif /* PNG_MIPS_MSA_FILE */ +#endif /* PNG_MIPS_MSA_CHECK_SUPPORTED */ + +#ifndef PNG_ALIGNED_MEMORY_SUPPORTED +# error "ALIGNED_MEMORY is required; set: -DPNG_ALIGNED_MEMORY_SUPPORTED" +#endif + +void +png_init_filter_functions_msa(png_structp pp, unsigned int bpp) +{ + /* The switch statement is compiled in for MIPS_MSA_API, the call to + * png_have_msa is compiled in for MIPS_MSA_CHECK. If both are defined + * the check is only performed if the API has not set the MSA option on + * or off explicitly. In this case the check controls what happens. + */ + +#ifdef PNG_MIPS_MSA_API_SUPPORTED + switch ((pp->options >> PNG_MIPS_MSA) & 3) + { + case PNG_OPTION_UNSET: + /* Allow the run-time check to execute if it has been enabled - + * thus both API and CHECK can be turned on. If it isn't supported + * this case will fall through to the 'default' below, which just + * returns. + */ +#endif /* PNG_MIPS_MSA_API_SUPPORTED */ +#ifdef PNG_MIPS_MSA_CHECK_SUPPORTED + { + static volatile sig_atomic_t no_msa = -1; /* not checked */ + + if (no_msa < 0) + no_msa = !png_have_msa(pp); + + if (no_msa) + return; + } +#ifdef PNG_MIPS_MSA_API_SUPPORTED + break; +#endif +#endif /* PNG_MIPS_MSA_CHECK_SUPPORTED */ + +#ifdef PNG_MIPS_MSA_API_SUPPORTED + default: /* OFF or INVALID */ + return; + + case PNG_OPTION_ON: + /* Option turned on */ + break; + } +#endif + + /* IMPORTANT: any new external functions used here must be declared using + * PNG_INTERNAL_FUNCTION in ../pngpriv.h. This is required so that the + * 'prefix' option to configure works: + * + * ./configure --with-libpng-prefix=foobar_ + * + * Verify you have got this right by running the above command, doing a build + * and examining pngprefix.h; it must contain a #define for every external + * function you add. (Notice that this happens automatically for the + * initialization function.) + */ + pp->read_filter[PNG_FILTER_VALUE_UP-1] = png_read_filter_row_up_msa; + + if (bpp == 3) + { + pp->read_filter[PNG_FILTER_VALUE_SUB-1] = png_read_filter_row_sub3_msa; + pp->read_filter[PNG_FILTER_VALUE_AVG-1] = png_read_filter_row_avg3_msa; + pp->read_filter[PNG_FILTER_VALUE_PAETH-1] = png_read_filter_row_paeth3_msa; + } + + else if (bpp == 4) + { + pp->read_filter[PNG_FILTER_VALUE_SUB-1] = png_read_filter_row_sub4_msa; + pp->read_filter[PNG_FILTER_VALUE_AVG-1] = png_read_filter_row_avg4_msa; + pp->read_filter[PNG_FILTER_VALUE_PAETH-1] = png_read_filter_row_paeth4_msa; + } +} +#endif /* PNG_MIPS_MSA_OPT > 0 */ +#endif /* READ */ diff --git a/pool/shard002/C/0056535_tgpio.c b/pool/shard002/C/0056535_tgpio.c new file mode 100644 index 0000000000000000000000000000000000000000..33a61c5146b0d2b0d3c257aa33dec9f2a4ff143a --- /dev/null +++ b/pool/shard002/C/0056535_tgpio.c @@ -0,0 +1,140 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +static int t8_rst = 0; + +static int t8_gpio_requ(struct gpio_config *gpio) +{ + int ret = 0; + char pin_name[8] = {0}; + unsigned long config; + + sunxi_gpio_to_name(gpio->gpio, pin_name); + config = SUNXI_PINCFG_PACK(SUNXI_PINCFG_TYPE_FUNC, gpio->mul_sel); + ret = pin_config_set(SUNXI_PINCTRL, pin_name, config); + if (ret) { + printk("set gpio %s mulsel failed.\n",pin_name); + return -1; + } + if (gpio->pull != GPIO_PULL_DEFAULT){ + config = SUNXI_PINCFG_PACK(SUNXI_PINCFG_TYPE_PUD, gpio->pull); + ret = pin_config_set(SUNXI_PINCTRL, pin_name, config); + if (ret) { + printk("set gpio %s pull mode failed.\n",pin_name); + return -1; + } + } + if (gpio->drv_level != GPIO_DRVLVL_DEFAULT){ + config = SUNXI_PINCFG_PACK(SUNXI_PINCFG_TYPE_DRV, gpio->drv_level); + ret = pin_config_set(SUNXI_PINCTRL, pin_name, config); + if (ret) { + printk("set gpio %s driver level failed.\n",pin_name); + return -1; + } + } + if (gpio->data != GPIO_DATA_DEFAULT) { + config = SUNXI_PINCFG_PACK(SUNXI_PINCFG_TYPE_DAT, gpio->data); + ret = pin_config_set(SUNXI_PINCTRL, pin_name, config); + if (ret) { + printk("set gpio %s initial val failed.\n",pin_name); + return -1; + } + } + return 0; +} + +void tgg_pulldown(void) +{ + __gpio_set_value(t8_rst, 0); +} +EXPORT_SYMBOL(tgg_pulldown); +void tgg_pullup(void) +{ + __gpio_set_value(t8_rst, 1); +} +EXPORT_SYMBOL(tgg_pullup); + + +#define PE14_CON 0x01C20894 +#define CON_OFFSET 24 +#define PE14_DATA 0x01C208A0 +#define DATA_OFFSET 14 + +#define N2A(n) ((unsigned int volatile *)(n)) +unsigned int rrval, rwval; +unsigned int drval, dwval; + +unsigned int vir_addr = 0; + + +static __init int tgg_init(void) +{ +#if 0 + script_item_u t8_val; + script_item_value_type_e t8_type; + struct gpio_config *gpio_p = NULL; + + t8_type = script_get_item("csi0", "vip_dev0_reset", &t8_val); + if (SCIRPT_ITEM_VALUE_TYPE_PIO!=t8_type) { + printk("get vip_dev0_reset error\n"); + } else { + gpio_p = &t8_val.gpio; + t8_rst = gpio_p->gpio; + t8_gpio_requ(gpio_p); + } + +// gpio_direction_output(t8_rst, 0); +#endif + + vir_addr = ioremap(0x01C20800, SZ_1K); + + printk("vir addr = 0x%x\n", vir_addr); + + drval = __raw_readl(vir_addr + 0xA0); + rrval = __raw_readl(vir_addr + 0x94); + + printk("drval = 0x%x, rrval = 0x%x\n", drval, rrval); + + rwval = (rrval & (~(0xf< +/** + Unfortunately the old RedHat3 computers have a zlib version which + does not have the compressBound function. For that reason the + compressBound function from a 1.2xx version of zlib is pasted in + here verbatim: +*/ + + +/* Snipped from zlib source code: */ +static size_t __compress_bound (size_t sourceLen) +{ + return sourceLen + (sourceLen >> 12) + (sourceLen >> 14) + 11; +} + + +/** + Return value is the size (in bytes) of the compressed buffer. +*/ +size_t buffer_fwrite_compressed(buffer_type * buffer, const void * ptr , size_t byte_size) { + size_t compressed_size = 0; + bool abort_on_error = true; + buffer->content_size = buffer->pos; /* Invalidating possible buffer content coming after the compressed content; that is uninterpretable anyway. */ + + if (byte_size > 0) { + size_t remaining_size = buffer->alloc_size - buffer->pos; + size_t compress_bound = __compress_bound( byte_size ); + if (compress_bound > remaining_size) + buffer_resize__(buffer , remaining_size + compress_bound , abort_on_error); + + compressed_size = buffer->alloc_size - buffer->pos; + util_compress_buffer( ptr , byte_size , &buffer->data[buffer->pos] , &compressed_size); + buffer->pos += compressed_size; + buffer->content_size += compressed_size; + } + + return compressed_size; +} + + +/** + Return value is the size of the uncompressed buffer. +*/ +size_t buffer_fread_compressed(buffer_type * buffer , size_t compressed_size , void * target_ptr , size_t target_size) { + size_t remaining_size = buffer->content_size - buffer->pos; + size_t uncompressed_size = target_size; + if (remaining_size < compressed_size) + util_abort("%s: trying to read beyond end of buffer\n",__func__); + + + if (compressed_size > 0) { + int uncompress_result = uncompress(target_ptr , &uncompressed_size , (unsigned char *) &buffer->data[buffer->pos] , compressed_size); + if (uncompress_result != Z_OK) { + fprintf(stderr,"%s: ** Warning uncompress result:%d != Z_OK.\n" , __func__ , uncompress_result); + /** + According to the zlib documentation: + + 1. Values > 0 are not errors - just rare events? + 2. The value Z_BUF_ERROR is not fatal - we let that pass?! + */ + if (uncompress_result < 0 && uncompress_result != Z_BUF_ERROR) + util_abort("%s: fatal uncompress error: %d \n",__func__ , uncompress_result); + } + } else + uncompressed_size = 0; + + buffer->pos += compressed_size; + return uncompressed_size; +} + diff --git a/pool/shard002/C/0056564_sbmapcat.c b/pool/shard002/C/0056564_sbmapcat.c new file mode 100644 index 0000000000000000000000000000000000000000..79804c94f1a204b94e44ed5155e1c89d6c1223c5 --- /dev/null +++ b/pool/shard002/C/0056564_sbmapcat.c @@ -0,0 +1,223 @@ +/* + * This file is part of sparsefileutils. + * + * Copyright (C) 2012 D.Herrendoerfer + * + * sparsefileutils 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. + * + * sparsefileutils 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 file. If not, see . + */ + +#define _FILE_OFFSET_BITS 64 + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +int map_block = 0; +unsigned char map_val = 0; + +int writemap(int fd, int val) { + int bit = map_block % 8; + + if (val == 1) + map_val = map_val | (1<. + */ + +#include "ssi_driver.h" +#include "ssi_sram_mgr.h" + +/** + * struct ssi_sram_mgr_ctx -Internal RAM context manager + * @sram_free_offset: the offset to the non-allocated area + */ +struct ssi_sram_mgr_ctx { + ssi_sram_addr_t sram_free_offset; +}; + +/** + * ssi_sram_mgr_fini() - Cleanup SRAM pool. + * + * @drvdata: Associated device driver context + */ +void ssi_sram_mgr_fini(struct ssi_drvdata *drvdata) +{ + struct ssi_sram_mgr_ctx *smgr_ctx = drvdata->sram_mgr_handle; + + /* Free "this" context */ + if (smgr_ctx) { + memset(smgr_ctx, 0, sizeof(struct ssi_sram_mgr_ctx)); + kfree(smgr_ctx); + } +} + +/** + * ssi_sram_mgr_init() - Initializes SRAM pool. + * The pool starts right at the beginning of SRAM. + * Returns zero for success, negative value otherwise. + * + * @drvdata: Associated device driver context + */ +int ssi_sram_mgr_init(struct ssi_drvdata *drvdata) +{ + struct ssi_sram_mgr_ctx *smgr_ctx; + int rc; + + /* Allocate "this" context */ + drvdata->sram_mgr_handle = kzalloc( + sizeof(struct ssi_sram_mgr_ctx), GFP_KERNEL); + if (!drvdata->sram_mgr_handle) { + SSI_LOG_ERR("Not enough memory to allocate SRAM_MGR ctx (%zu)\n", + sizeof(struct ssi_sram_mgr_ctx)); + rc = -ENOMEM; + goto out; + } + smgr_ctx = drvdata->sram_mgr_handle; + + /* Pool starts at start of SRAM */ + smgr_ctx->sram_free_offset = 0; + + return 0; + +out: + ssi_sram_mgr_fini(drvdata); + return rc; +} + +/*! + * Allocated buffer from SRAM pool. + * Note: Caller is responsible to free the LAST allocated buffer. + * This function does not taking care of any fragmentation may occur + * by the order of calls to alloc/free. + * + * \param drvdata + * \param size The requested bytes to allocate + */ +ssi_sram_addr_t ssi_sram_mgr_alloc(struct ssi_drvdata *drvdata, u32 size) +{ + struct ssi_sram_mgr_ctx *smgr_ctx = drvdata->sram_mgr_handle; + ssi_sram_addr_t p; + + if (unlikely((size & 0x3) != 0)) { + SSI_LOG_ERR("Requested buffer size (%u) is not multiple of 4", + size); + return NULL_SRAM_ADDR; + } + if (unlikely(size > (SSI_CC_SRAM_SIZE - smgr_ctx->sram_free_offset))) { + SSI_LOG_ERR("Not enough space to allocate %u B (at offset %llu)\n", + size, smgr_ctx->sram_free_offset); + return NULL_SRAM_ADDR; + } + + p = smgr_ctx->sram_free_offset; + smgr_ctx->sram_free_offset += size; + SSI_LOG_DEBUG("Allocated %u B @ %u\n", size, (unsigned int)p); + return p; +} + +/** + * ssi_sram_mgr_const2sram_desc() - Create const descriptors sequence to + * set values in given array into SRAM. + * Note: each const value can't exceed word size. + * + * @src: A pointer to array of words to set as consts. + * @dst: The target SRAM buffer to set into + * @nelements: The number of words in "src" array + * @seq: A pointer to the given IN/OUT descriptor sequence + * @seq_len: A pointer to the given IN/OUT sequence length + */ +void ssi_sram_mgr_const2sram_desc( + const u32 *src, ssi_sram_addr_t dst, + unsigned int nelement, + struct cc_hw_desc *seq, unsigned int *seq_len) +{ + u32 i; + unsigned int idx = *seq_len; + + for (i = 0; i < nelement; i++, idx++) { + hw_desc_init(&seq[idx]); + set_din_const(&seq[idx], src[i], sizeof(u32)); + set_dout_sram(&seq[idx], dst + (i * sizeof(u32)), sizeof(u32)); + set_flow_mode(&seq[idx], BYPASS); + } + + *seq_len = idx; +} + diff --git a/pool/shard002/C/0056569_error_verbose_prefix.c b/pool/shard002/C/0056569_error_verbose_prefix.c new file mode 100644 index 0000000000000000000000000000000000000000..dab8d878dd596e0e90b674ed8380b031052fea65 --- /dev/null +++ b/pool/shard002/C/0056569_error_verbose_prefix.c @@ -0,0 +1,90 @@ +/* Copyright (C) 2012 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 + */ +#include "test.h" + +#include +#ifdef HAVE_SYS_WAIT_H +#include +#endif +#include +#include +#include +#include + +int main(void) +{ +#if !defined HAVE_MKFIFO || !defined HAVE_WORKING_FORK || defined __CYGWIN__ + return 77; /* skip */ +#else + const char *filedir = "dirfile"; + const char *fifo = "dirfile/fifo"; + const char *format = "dirfile/format"; + int e1, e2, r = 0, status; + FILE *stream; + pid_t pid; + DIRFILE *D; + + rmdirfile(); + mkdir(filedir, 0777); + close(open(format, O_CREAT | O_EXCL | O_WRONLY, 0666)); + mkfifo(fifo, 0666); + + /* read our standard error */ + if ((pid = fork()) == 0) { + char string[1024]; + stream = fopen(fifo, "r"); + + fgets(string, 1024, stream); + CHECKS(string, "getdata-test: libgetdata: Field not found: data\n"); + return r; + } + + /* retarget stderr */ + freopen(fifo, "w", stderr); + + D = gd_open(filedir, GD_RDONLY); + e1 = gd_error(D); + gd_flags(D, GD_VERBOSE, 0); + gd_verbose_prefix(D, "getdata-test: "); + gd_validate(D, "data"); + e2 = gd_error(D); + gd_close(D); + + fputs("\n", stderr); + fflush(stderr); + + /* restore stderr */ + freopen("/dev/stderr", "w", stderr); + + unlink(fifo); + unlink(format); + rmdir(filedir); + + CHECKI(e1, 0); + CHECKI(e2, GD_E_BAD_CODE); + + wait(&status); + if (status) + r = 1; + + return r; +#endif +} diff --git a/pool/shard002/C/0056577_CWE78_OS_Command_Injection__wchar_t_environment_w32_execv_13.c b/pool/shard002/C/0056577_CWE78_OS_Command_Injection__wchar_t_environment_w32_execv_13.c new file mode 100644 index 0000000000000000000000000000000000000000..80d95859ef44c4d9158b61ca75f4556c4ce0132f --- /dev/null +++ b/pool/shard002/C/0056577_CWE78_OS_Command_Injection__wchar_t_environment_w32_execv_13.c @@ -0,0 +1,156 @@ +/* TEMPLATE GENERATED TESTCASE FILE +Filename: CWE78_OS_Command_Injection__wchar_t_environment_w32_execv_13.c +Label Definition File: CWE78_OS_Command_Injection.strings.label.xml +Template File: sources-sink-13.tmpl.c +*/ +/* + * @description + * CWE: 78 OS Command Injection + * BadSource: environment Read input from an environment variable + * GoodSource: Fixed string + * Sink: w32_execv + * BadSink : execute command with wexecv + * Flow Variant: 13 Control flow: if(GLOBAL_CONST_FIVE==5) and if(GLOBAL_CONST_FIVE!=5) + * + * */ + +#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"ls" +#define COMMAND_ARG2 L"-la" +#define COMMAND_ARG3 data +#endif + +#define ENV_VARIABLE L"ADD" + +#ifdef _WIN32 +#define GETENV _wgetenv +#else +#define GETENV getenv +#endif + +#include +#define EXECV _wexecv + +#ifndef OMITBAD + +void CWE78_OS_Command_Injection__wchar_t_environment_w32_execv_13_bad() +{ + wchar_t * data; + wchar_t dataBuffer[100] = L""; + data = dataBuffer; + if(GLOBAL_CONST_FIVE==5) + { + { + /* 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); + } + } + } + { + wchar_t *args[] = {COMMAND_INT_PATH, COMMAND_ARG1, COMMAND_ARG2, COMMAND_ARG3, NULL}; + /* wexecv - specify the path where the command is located */ + /* POTENTIAL FLAW: Execute command without validating input possibly leading to command injection */ + EXECV(COMMAND_INT_PATH, args); + } +} + +#endif /* OMITBAD */ + +#ifndef OMITGOOD + +/* goodG2B1() - use goodsource and badsink by changing the GLOBAL_CONST_FIVE==5 to GLOBAL_CONST_FIVE!=5 */ +static void goodG2B1() +{ + wchar_t * data; + wchar_t dataBuffer[100] = L""; + data = dataBuffer; + if(GLOBAL_CONST_FIVE!=5) + { + /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */ + printLine("Benign, fixed string"); + } + else + { + /* FIX: Append a fixed string to data (not user / external input) */ + wcscat(data, L"*.*"); + } + { + wchar_t *args[] = {COMMAND_INT_PATH, COMMAND_ARG1, COMMAND_ARG2, COMMAND_ARG3, NULL}; + /* wexecv - specify the path where the command is located */ + /* POTENTIAL FLAW: Execute command without validating input possibly leading to command injection */ + EXECV(COMMAND_INT_PATH, args); + } +} + +/* goodG2B2() - use goodsource and badsink by reversing the blocks in the if statement */ +static void goodG2B2() +{ + wchar_t * data; + wchar_t dataBuffer[100] = L""; + data = dataBuffer; + if(GLOBAL_CONST_FIVE==5) + { + /* FIX: Append a fixed string to data (not user / external input) */ + wcscat(data, L"*.*"); + } + { + wchar_t *args[] = {COMMAND_INT_PATH, COMMAND_ARG1, COMMAND_ARG2, COMMAND_ARG3, NULL}; + /* wexecv - specify the path where the command is located */ + /* POTENTIAL FLAW: Execute command without validating input possibly leading to command injection */ + EXECV(COMMAND_INT_PATH, args); + } +} + +void CWE78_OS_Command_Injection__wchar_t_environment_w32_execv_13_good() +{ + goodG2B1(); + goodG2B2(); +} + +#endif /* OMITGOOD */ + +/* Below is the main(). It is only used when building this testcase on + * its own for testing or for building a binary to use in testing binary + * analysis tools. It is not used when compiling all the testcases as one + * application, which is how source code analysis tools are tested. + */ + +#ifdef INCLUDEMAIN + +int main(int argc, char * argv[]) +{ + /* seed randomness */ + srand( (unsigned)time(NULL) ); +#ifndef OMITGOOD + printLine("Calling good()..."); + CWE78_OS_Command_Injection__wchar_t_environment_w32_execv_13_good(); + printLine("Finished good()"); +#endif /* OMITGOOD */ +#ifndef OMITBAD + printLine("Calling bad()..."); + CWE78_OS_Command_Injection__wchar_t_environment_w32_execv_13_bad(); + printLine("Finished bad()"); +#endif /* OMITBAD */ + return 0; +} + +#endif diff --git a/pool/shard002/C/0056599_comm_remote_size.c b/pool/shard002/C/0056599_comm_remote_size.c new file mode 100644 index 0000000000000000000000000000000000000000..853d7b36e605b432a2eff0db6e522cbf4312f8a7 --- /dev/null +++ b/pool/shard002/C/0056599_comm_remote_size.c @@ -0,0 +1,124 @@ +/* -*- Mode: C; c-basic-offset:4 ; indent-tabs-mode:nil ; -*- */ +/* + * + * (C) 2001 by Argonne National Laboratory. + * See COPYRIGHT in top-level directory. + */ + +#include "mpiimpl.h" + +/* -- Begin Profiling Symbol Block for routine MPI_Comm_remote_size */ +#if defined(HAVE_PRAGMA_WEAK) +#pragma weak MPI_Comm_remote_size = PMPI_Comm_remote_size +#elif defined(HAVE_PRAGMA_HP_SEC_DEF) +#pragma _HP_SECONDARY_DEF PMPI_Comm_remote_size MPI_Comm_remote_size +#elif defined(HAVE_PRAGMA_CRI_DUP) +#pragma _CRI duplicate MPI_Comm_remote_size as PMPI_Comm_remote_size +#elif defined(HAVE_WEAK_ATTRIBUTE) +int MPI_Comm_remote_size(MPI_Comm comm, int *size) __attribute__((weak,alias("PMPI_Comm_remote_size"))); +#endif +/* -- End Profiling Symbol Block */ + +/* Define MPICH_MPI_FROM_PMPI if weak symbols are not supported to build + the MPI routines */ +#ifndef MPICH_MPI_FROM_PMPI +#undef MPI_Comm_remote_size +#define MPI_Comm_remote_size PMPI_Comm_remote_size + +#endif + +#undef FUNCNAME +#define FUNCNAME MPI_Comm_remote_size +#undef FCNAME +#define FCNAME "MPI_Comm_remote_size" + +/*@ + +MPI_Comm_remote_size - Determines the size of the remote group + associated with an inter-communictor + +Input Parameters: +. comm - communicator (handle) + +Output Parameters: +. size - number of processes in the remote group of 'comm' (integer) + +.N SignalSafe + +.N Fortran + +.N Errors +.N MPI_SUCCESS +.N MPI_ERR_COMM +.N MPI_ERR_ARG +@*/ +int MPI_Comm_remote_size(MPI_Comm comm, int *size) +{ + int mpi_errno = MPI_SUCCESS; + MPID_Comm *comm_ptr = NULL; + MPID_MPI_STATE_DECL(MPID_STATE_MPI_COMM_REMOTE_SIZE); + + MPIR_ERRTEST_INITIALIZED_ORDIE(); + + MPID_MPI_FUNC_ENTER(MPID_STATE_MPI_COMM_REMOTE_SIZE); + + /* Validate parameters, especially handles needing to be converted */ +# ifdef HAVE_ERROR_CHECKING + { + MPID_BEGIN_ERROR_CHECKS; + { + MPIR_ERRTEST_COMM(comm, mpi_errno); + } + MPID_END_ERROR_CHECKS; + } +# endif /* HAVE_ERROR_CHECKING */ + + /* Convert MPI object handles to object pointers */ + MPID_Comm_get_ptr( comm, comm_ptr ); + + /* Validate parameters and objects (post conversion) */ +# ifdef HAVE_ERROR_CHECKING + { + MPID_BEGIN_ERROR_CHECKS; + { + /* Validate comm_ptr */ + MPID_Comm_valid_ptr( comm_ptr, mpi_errno, TRUE ); + /* If comm_ptr is not valid, it will be reset to null */ + if (comm_ptr && comm_ptr->comm_kind != MPID_INTERCOMM) { + mpi_errno = MPIR_Err_create_code( MPI_SUCCESS, + MPIR_ERR_RECOVERABLE, FCNAME, __LINE__, MPI_ERR_COMM, + "**commnotinter", 0 ); + } + if (mpi_errno) goto fn_fail; + } + MPID_END_ERROR_CHECKS; + } +# endif /* HAVE_ERROR_CHECKING */ + + /* ... body of routine ... */ + + *size = comm_ptr->remote_size; + + /* ... end of body of routine ... */ + +#ifdef HAVE_ERROR_CHECKING + fn_exit: +#endif + MPID_MPI_FUNC_EXIT(MPID_STATE_MPI_COMM_REMOTE_SIZE); + return mpi_errno; + + /* --BEGIN ERROR HANDLING-- */ +# ifdef HAVE_ERROR_CHECKING + fn_fail: + { + mpi_errno = MPIR_Err_create_code( + mpi_errno, MPIR_ERR_RECOVERABLE, FCNAME, __LINE__, MPI_ERR_OTHER, + "**mpi_comm_remote_size", + "**mpi_comm_remote_size %C %p", comm, size); + } + mpi_errno = MPIR_Err_return_comm( comm_ptr, FCNAME, mpi_errno ); + goto fn_exit; +# endif + /* --END ERROR HANDLING-- */ +} + diff --git a/pool/shard002/C/0056604_cdbdisp_dtx.c b/pool/shard002/C/0056604_cdbdisp_dtx.c new file mode 100644 index 0000000000000000000000000000000000000000..d205d41215bbec1df5d8d2831c73bc516760d8ff --- /dev/null +++ b/pool/shard002/C/0056604_cdbdisp_dtx.c @@ -0,0 +1,291 @@ +/*------------------------------------------------------------------------- + * + * cdbdisp_dtx.c + * Functions to dispatch DTX commands to QExecutors. + * + * + * Portions Copyright (c) 2005-2008, Greenplum inc + * Portions Copyright (c) 2012-Present VMware, Inc. or its affiliates. + * + * + * IDENTIFICATION + * src/backend/cdb/dispatcher/cdbdisp_dtx.c + * + *------------------------------------------------------------------------- + */ + +#include "postgres.h" + +#include "access/xact.h" +#include "utils/guc.h" +#include "utils/memutils.h" +#include "libpq-fe.h" +#include "libpq-int.h" +#include "cdb/cdbconn.h" +#include "cdb/cdbdisp.h" +#include "cdb/cdbdisp_dtx.h" +#include "cdb/cdbdispatchresult.h" +#include "cdb/cdbgang.h" + +#include "storage/procarray.h" /* updateSharedLocalSnapshot */ +#include "utils/snapmgr.h" + +/* + * Parameter structure for DTX protocol commands + */ +typedef struct DispatchCommandDtxProtocolParms +{ + DtxProtocolCommand dtxProtocolCommand; + char *dtxProtocolCommandLoggingStr; + char gid[TMGIDSIZE]; + char *serializedDtxContextInfo; + int serializedDtxContextInfoLen; +} DispatchCommandDtxProtocolParms; + +/* + * STATIC STATE VARIABLES should not be declared! + * global state will break the ability to run cursors. + * only globals with a higher granularity than a running + * command (i.e: transaction, session) are ok. + */ +static DtxContextInfo TempQDDtxContextInfo = DtxContextInfo_StaticInit; + +static char *buildGpDtxProtocolCommand(DispatchCommandDtxProtocolParms *pDtxProtocolParms, + int *finalLen); + +/* + * CdbDispatchDtxProtocolCommand: + * Sends a non-cancelable command to all segment dbs + * + * Returns a malloc'ed array containing the PGresult objects thus + * produced; the caller must PQclear() them and free() the array. + * A NULL entry follows the last used entry in the array. + * + * Any error message - whether or not it is associated with an + * PGresult object - is returned in *qeError. + */ +struct pg_result ** +CdbDispatchDtxProtocolCommand(DtxProtocolCommand dtxProtocolCommand, + char *dtxProtocolCommandLoggingStr, + char *gid, + ErrorData **qeError, + int *numresults, + List *dtxSegments, + char *serializedDtxContextInfo, + int serializedDtxContextInfoLen) +{ + CdbDispatcherState *ds; + CdbDispatchResults *pr; + CdbPgResults cdb_pgresults = {NULL, 0}; + + DispatchCommandDtxProtocolParms dtxProtocolParms; + Gang *primaryGang; + char *queryText = NULL; + int queryTextLen = 0; + + *qeError = NULL; + + MemSet(&dtxProtocolParms, 0, sizeof(dtxProtocolParms)); + dtxProtocolParms.dtxProtocolCommand = dtxProtocolCommand; + dtxProtocolParms.dtxProtocolCommandLoggingStr = dtxProtocolCommandLoggingStr; + if (strlen(gid) >= TMGIDSIZE) + elog(PANIC, "Distribute transaction identifier too long (%d)", (int) strlen(gid)); + memcpy(dtxProtocolParms.gid, gid, TMGIDSIZE); + dtxProtocolParms.serializedDtxContextInfo = serializedDtxContextInfo; + dtxProtocolParms.serializedDtxContextInfoLen = serializedDtxContextInfoLen; + + /* + * Dispatch the command. + */ + ds = cdbdisp_makeDispatcherState(false); + + queryText = buildGpDtxProtocolCommand(&dtxProtocolParms, &queryTextLen); + + primaryGang = AllocateGang(ds, GANGTYPE_PRIMARY_WRITER, dtxSegments); + + Assert(primaryGang); + + cdbdisp_makeDispatchResults(ds, 1, false); + cdbdisp_makeDispatchParams(ds, 1, queryText, queryTextLen); + + cdbdisp_dispatchToGang(ds, primaryGang, -1); + addToGxactDtxSegments(primaryGang); + + cdbdisp_waitDispatchFinish(ds); + + cdbdisp_checkDispatchResult(ds, DISPATCH_WAIT_NONE); + + pr = cdbdisp_getDispatchResults(ds, qeError); + + if (!pr) + { + cdbdisp_destroyDispatcherState(ds); + return NULL; + } + + cdbdisp_returnResults(pr, &cdb_pgresults); + + cdbdisp_destroyDispatcherState(ds); + + *numresults = cdb_pgresults.numResults; + return cdb_pgresults.pg_results; +} + +char * +qdSerializeDtxContextInfo(int *size, bool wantSnapshot, bool inCursor, + int txnOptions, char *debugCaller) +{ + char *serializedDtxContextInfo; + + Snapshot snapshot = NULL; + int serializedLen; + DtxContextInfo *pDtxContextInfo = NULL; + DtxContext currentDistributedTransactionContext = DistributedTransactionContext; + + /* + * If 'wantSnapshot' is set, then serialize the ActiveSnapshot. The + * caller better have ActiveSnapshot set. + */ + *size = 0; + + if (wantSnapshot) + { + if (!ActiveSnapshotSet()) + elog(ERROR, "could not serialize current snapshot, ActiveSnapshot not set"); + snapshot = GetActiveSnapshot(); + } + + switch (currentDistributedTransactionContext) + { + case DTX_CONTEXT_QD_DISTRIBUTED_CAPABLE: + case DTX_CONTEXT_LOCAL_ONLY: + DtxContextInfo_CreateOnMaster(&TempQDDtxContextInfo, inCursor, + txnOptions, snapshot); + + if (DistributedTransactionContext == + DTX_CONTEXT_QD_DISTRIBUTED_CAPABLE && snapshot != NULL) + { + updateSharedLocalSnapshot( + &TempQDDtxContextInfo, + currentDistributedTransactionContext, + snapshot, + "qdSerializeDtxContextInfo"); + } + + pDtxContextInfo = &TempQDDtxContextInfo; + break; + + case DTX_CONTEXT_QD_RETRY_PHASE_2: + case DTX_CONTEXT_QE_ENTRY_DB_SINGLETON: + case DTX_CONTEXT_QE_AUTO_COMMIT_IMPLICIT: + case DTX_CONTEXT_QE_TWO_PHASE_EXPLICIT_WRITER: + case DTX_CONTEXT_QE_TWO_PHASE_IMPLICIT_WRITER: + case DTX_CONTEXT_QE_READER: + case DTX_CONTEXT_QE_PREPARED: + case DTX_CONTEXT_QE_FINISH_PREPARED: + elog(FATAL, "Unexpected distribute transaction context: '%s'", + DtxContextToString(DistributedTransactionContext)); + break; + + default: + elog(FATAL, "Unrecognized DTX transaction context: %d", + (int) DistributedTransactionContext); + } + + serializedLen = DtxContextInfo_SerializeSize(pDtxContextInfo); + Assert(serializedLen > 0); + + *size = serializedLen; + serializedDtxContextInfo = palloc(*size); + + DtxContextInfo_Serialize(serializedDtxContextInfo, pDtxContextInfo); + + elog((Debug_print_full_dtm ? LOG : DEBUG5), + "qdSerializeDtxContextInfo (called by %s) returning a snapshot of %d bytes (ptr is %s)", + debugCaller, *size, + (serializedDtxContextInfo != NULL ? "Non-NULL" : "NULL")); + return serializedDtxContextInfo; +} + +/* + * Build a dtx protocol command string to be dispatched to QE. + */ +static char * +buildGpDtxProtocolCommand(DispatchCommandDtxProtocolParms *pDtxProtocolParms, + int *finalLen) +{ + int dtxProtocolCommand = (int) pDtxProtocolParms->dtxProtocolCommand; + char *dtxProtocolCommandLoggingStr = pDtxProtocolParms->dtxProtocolCommandLoggingStr; + char *gid = pDtxProtocolParms->gid; + char *serializedDtxContextInfo = pDtxProtocolParms->serializedDtxContextInfo; + int serializedDtxContextInfoLen = pDtxProtocolParms->serializedDtxContextInfoLen; + int tmp = 0; + int len = 0; + + int loggingStrLen = strlen(dtxProtocolCommandLoggingStr) + 1; + int gidLen = strlen(gid) + 1; + int total_query_len = 1 /* 'T' */ + + sizeof(len) + + sizeof(dtxProtocolCommand) + + sizeof(loggingStrLen) + + loggingStrLen + + sizeof(gidLen) + + gidLen + + sizeof(serializedDtxContextInfoLen) + + serializedDtxContextInfoLen; + + char *shared_query = NULL; + char *pos = NULL; + + /* Allocate query text within DispatcherContext */ + Assert(DispatcherContext); + MemoryContext oldContext = MemoryContextSwitchTo(DispatcherContext); + shared_query = palloc0(total_query_len); + pos = shared_query; + + *pos++ = 'T'; + + pos += sizeof(len); /* placeholder for message length */ + + tmp = htonl(dtxProtocolCommand); + memcpy(pos, &tmp, sizeof(tmp)); + pos += sizeof(tmp); + + tmp = htonl(loggingStrLen); + memcpy(pos, &tmp, sizeof(tmp)); + pos += sizeof(tmp); + + memcpy(pos, dtxProtocolCommandLoggingStr, loggingStrLen); + pos += loggingStrLen; + + tmp = htonl(gidLen); + memcpy(pos, &tmp, sizeof(tmp)); + pos += sizeof(tmp); + + memcpy(pos, gid, gidLen); + pos += gidLen; + + tmp = htonl(serializedDtxContextInfoLen); + memcpy(pos, &tmp, sizeof(tmp)); + pos += sizeof(tmp); + + if (serializedDtxContextInfoLen > 0) + { + memcpy(pos, serializedDtxContextInfo, serializedDtxContextInfoLen); + pos += serializedDtxContextInfoLen; + } + + len = pos - shared_query - 1; + + /* + * fill in length placeholder + */ + tmp = htonl(len); + memcpy(shared_query + 1, &tmp, sizeof(tmp)); + + if (finalLen) + *finalLen = len + 1; + + MemoryContextSwitchTo(oldContext); + return shared_query; +} diff --git a/pool/shard002/C/0056606_search.c b/pool/shard002/C/0056606_search.c new file mode 100644 index 0000000000000000000000000000000000000000..cff2279d31804a5930682cd7202f4d90173e9886 --- /dev/null +++ b/pool/shard002/C/0056606_search.c @@ -0,0 +1,228 @@ +#include "search.h" +#include "evaluate.h" +#include "movegen.h" +#include "position.h" +#include +#include +#include +#include + +static inline force_inline +int min(int a, int b) { + return a < b ? a : b; +} + +static inline force_inline +int max(int a, int b) { + return a > b ? a : b; +} + +enum { + TT_NONE = 0, + TT_EXACT, + TT_ALPHA, + TT_BETA, +}; + +struct tt_entry { + // TODO(plesslie): don't need to save entire hash, just + // save bits not in the index + uint64_t hash; + uint8_t depth; + int score; + uint8_t flags; + move move; +}; + +//#define TTSZ (1 << 20) +// smallest prime above 1 << 20 +#define TTSZ 1048583 +struct tt_entry tt_tbl[TTSZ]; +uint64_t transposition_table_hits; +uint64_t transposition_table_lookups; + +void transposition_table_counters_init() { + transposition_table_hits = 0ull; + transposition_table_lookups = 0ull; +} + +void transposition_table_counters_print() { + fprintf(stderr, "Transposition Table Hits : %" PRIu64 "\n", transposition_table_hits); + fprintf(stderr, "Transposition Table Lookups: %" PRIu64 "\n", transposition_table_lookups); +} + +void transposition_table_init() { + // static_assert(__builtin_popcount(TTSZ) == 0, "Transposition Table size + // must be a power of 2!"); + for (int i = 0; i < TTSZ; ++i) { + tt_tbl[i].hash = 0ull; + tt_tbl[i].score = 0; + tt_tbl[i].move = INVALID_MOVE; + tt_tbl[i].depth = 0u; + tt_tbl[i].flags = TT_NONE; + } +} + +// int tt_index(uint64_t h) { return h & (TTSZ - 1); } +int tt_index(uint64_t h) { + return h % TTSZ; +} + +struct search_node { + struct position *pos; + struct savepos *sp; + const move *moves; + uint64_t zhash; + int nmoves; +}; + +int alphabeta(struct position *pos, uint64_t zhash, int depth, int alpha, int beta, int color) { + const int table_index = tt_index(zhash); + ++transposition_table_lookups; + if (tt_tbl[table_index].hash == zhash && tt_tbl[table_index].depth >= depth) { + ++transposition_table_hits; + return tt_tbl[table_index].score; + } + + if (depth == 0) { + const int score = evaluate(pos); + #define USE_TRANSPOSITION_TABLE + #ifdef USE_TRANSPOSITION_TABLE + tt_tbl[table_index].hash = zhash; + tt_tbl[table_index].depth = 0; + tt_tbl[table_index].score = score; + tt_tbl[table_index].flags = TT_EXACT; + tt_tbl[table_index].move = INVALID_MOVE; // TODO(plesslie): fix + #endif + return score; + } + assert(zhash == zobrist_hash_from_position(pos)); + assert(color == WHITE || color == BLACK); + + uint64_t new_zhash; + move moves[MAX_MOVES]; + const int nmoves = generate_legal_moves(pos, &moves[0]); + if (nmoves == 0) { + // TODO(plesslie): this could be stalemate + return pos->wtm ? INF : NEG_INF; + } + + // 50-move draw + if (pos->halfmoves >= 100) { + return 0; + } + + int best; + struct savepos sp; + if (color == BLACK) { + best = NEG_INF; + for (int i = 0; i < nmoves; ++i) { + new_zhash = make_move(pos, &sp, moves[i], zhash); + const int value = alphabeta(pos, new_zhash, depth - 1, alpha, beta, WHITE); + undo_move(pos, &sp, moves[i]); + best = max(value, best); + alpha = max(alpha, best); + if (beta <= alpha) { // alpha cutoff + #ifdef USE_TRANSPOSITION_TABLE + if (tt_tbl[table_index].hash == zhash && tt_tbl[table_index].flags != TT_EXACT) { + tt_tbl[table_index].hash = zhash; + tt_tbl[table_index].depth = depth; + tt_tbl[table_index].score = best; + tt_tbl[table_index].flags = TT_ALPHA; + tt_tbl[table_index].move = moves[i]; + } + #endif + break; + } + } + } else { + best = INF; + for (int i = 0; i < nmoves; ++i) { + new_zhash = make_move(pos, &sp, moves[i], zhash); + const int value = alphabeta(pos, new_zhash, depth - 1, alpha, beta, BLACK); + undo_move(pos, &sp, moves[i]); + best = min(best, value); + beta = min(beta, best); + if (beta <= alpha) { // beta cutoff + #ifdef USE_TRANSPOSITION_TABLE + if (tt_tbl[table_index].hash == zhash && tt_tbl[table_index].flags != TT_EXACT) { + tt_tbl[table_index].hash = zhash; + tt_tbl[table_index].depth = depth; + tt_tbl[table_index].score = best; + tt_tbl[table_index].flags = TT_BETA; + tt_tbl[table_index].move = moves[i]; + } + #endif + break; + } + } + } + + return best; +} + +move root_search(const struct search_node *n, int depth, int *score) { + struct position *pos = n->pos; + struct savepos *sp = n->sp; + const move *moves = n->moves; + const uint64_t zhash = n->zhash; + const int nmoves = n->nmoves; + move bestmove = INVALID_MOVE; + uint64_t new_zhash; + + assert(zhash == zobrist_hash_from_position(pos)); + assert(nmoves > 0); + int bestscore = pos->wtm == WHITE ? NEG_INF : INF; + if (pos->wtm == WHITE) { + for (int i = 0; i < nmoves; ++i) { + new_zhash = make_move(pos, sp, moves[i], zhash); + assert(new_zhash == zobrist_hash_from_position(pos)); + const int value = alphabeta(pos, new_zhash, depth, NEG_INF, INF, WHITE); + undo_move(pos, sp, moves[i]); + if (value > bestscore) { + bestmove = moves[i]; + bestscore = value; + } + } + } else { + for (int i = 0; i < nmoves; ++i) { + new_zhash = make_move(pos, sp, moves[i], zhash); + assert(new_zhash == zobrist_hash_from_position(pos)); + const int value = alphabeta(pos, new_zhash, depth, NEG_INF, INF, 1); + undo_move(pos, sp, moves[i]); + if (value < bestscore) { + bestmove = moves[i]; + bestscore = value; + } + } + } + + assert(bestmove != INVALID_MOVE); + *score = bestscore; + return bestmove; +} + +move search(struct position *pos, int *score, int *searched_depth) { + const int max_depth = 5; + struct savepos sp; + move moves[MAX_MOVES]; + move best_move; + + const int nmoves = generate_legal_moves(pos, &moves[0]); + if (nmoves == 0) { + return MATED; + } + const uint64_t zhash = zobrist_hash_from_position(pos); + const struct search_node node = {.pos = pos, .sp = &sp, .moves = &moves[0], .zhash = zhash, .nmoves = nmoves}; + assert(node.zhash == zobrist_hash_from_position(pos)); + + for (int depth = 2; depth <= max_depth; ++depth) { + *searched_depth = depth; + best_move = root_search(&node, depth, score); + if (*score == INF || *score == NEG_INF) { + break; + } + } + + return best_move; +} diff --git a/pool/shard002/C/0056610_s3c2410.c b/pool/shard002/C/0056610_s3c2410.c new file mode 100644 index 0000000000000000000000000000000000000000..665a195e271f8f606a694f8552195f0310f3911d --- /dev/null +++ b/pool/shard002/C/0056610_s3c2410.c @@ -0,0 +1,185 @@ +/* linux/arch/arm/mach-s3c2410/s3c2410.c + * + * Copyright (c) 2003-2005 Simtec Electronics + * Ben Dooks + * + * http://www.simtec.co.uk/products/EB2410ITX/ + * + * 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 +#include + +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +/* Initial IO mappings */ + +static struct map_desc s3c2410_iodesc[] __initdata = { + IODESC_ENT(CLKPWR), + IODESC_ENT(TIMER), + IODESC_ENT(WATCHDOG), +}; + +/* our uart devices */ + +/* uart registration process */ + +void __init s3c2410_init_uarts(struct s3c2410_uartcfg *cfg, int no) +{ + s3c24xx_init_uartdevs("s3c2410-uart", s3c2410_uart_resources, cfg, no); +} + +/* s3c2410_map_io + * + * register the standard cpu IO areas, and any passed in from the + * machine specific initialisation. +*/ + +void __init s3c2410_map_io(void) +{ + s3c24xx_gpiocfg_default.set_pull = s3c_gpio_setpull_1up; + s3c24xx_gpiocfg_default.get_pull = s3c_gpio_getpull_1up; + + iotable_init(s3c2410_iodesc, ARRAY_SIZE(s3c2410_iodesc)); +} + +void __init_or_cpufreq s3c2410_setup_clocks(void) +{ + struct clk *xtal_clk; + unsigned long tmp; + unsigned long xtal; + unsigned long fclk; + unsigned long hclk; + unsigned long pclk; + + xtal_clk = clk_get(NULL, "xtal"); + xtal = clk_get_rate(xtal_clk); + clk_put(xtal_clk); + + /* now we've got our machine bits initialised, work out what + * clocks we've got */ + + fclk = s3c24xx_get_pll(__raw_readl(S3C2410_MPLLCON), xtal); + + tmp = __raw_readl(S3C2410_CLKDIVN); + + /* work out clock scalings */ + + hclk = fclk / ((tmp & S3C2410_CLKDIVN_HDIVN) ? 2 : 1); + pclk = hclk / ((tmp & S3C2410_CLKDIVN_PDIVN) ? 2 : 1); + + /* print brieft summary of clocks, etc */ + + printk("S3C2410: core %ld.%03ld MHz, memory %ld.%03ld MHz, peripheral %ld.%03ld MHz\n", + print_mhz(fclk), print_mhz(hclk), print_mhz(pclk)); + + /* initialise the clocks here, to allow other things like the + * console to use them + */ + + s3c24xx_setup_clocks(fclk, hclk, pclk); +} + +/* fake ARMCLK for use with cpufreq, etc. */ + +static struct clk s3c2410_armclk = { + .name = "armclk", + .parent = &clk_f, + .id = -1, +}; + +void __init s3c2410_init_clocks(int xtal) +{ + s3c24xx_register_baseclocks(xtal); + s3c2410_setup_clocks(); + s3c2410_baseclk_add(); + s3c24xx_register_clock(&s3c2410_armclk); +} + +struct bus_type s3c2410_subsys = { + .name = "s3c2410-core", + .dev_name = "s3c2410-core", +}; + +/* Note, we would have liked to name this s3c2410-core, but we cannot + * register two subsystems with the same name. + */ +struct bus_type s3c2410a_subsys = { + .name = "s3c2410a-core", + .dev_name = "s3c2410a-core", +}; + +static struct device s3c2410_dev = { + .bus = &s3c2410_subsys, +}; + +/* need to register the subsystem before we actually register the device, and + * we also need to ensure that it has been initialised before any of the + * drivers even try to use it (even if not on an s3c2410 based system) + * as a driver which may support both 2410 and 2440 may try and use it. +*/ + +static int __init s3c2410_core_init(void) +{ + return subsys_system_register(&s3c2410_subsys, NULL); +} + +core_initcall(s3c2410_core_init); + +static int __init s3c2410a_core_init(void) +{ + return subsys_system_register(&s3c2410a_subsys, NULL); +} + +core_initcall(s3c2410a_core_init); + +int __init s3c2410_init(void) +{ + printk("S3C2410: Initialising architecture\n"); + + register_syscore_ops(&s3c2410_pm_syscore_ops); + register_syscore_ops(&s3c24xx_irq_syscore_ops); + + return device_register(&s3c2410_dev); +} + +int __init s3c2410a_init(void) +{ + s3c2410_dev.bus = &s3c2410a_subsys; + return s3c2410_init(); +} diff --git a/pool/shard002/C/0056619_CWE127_Buffer_Underread__char_declare_ncpy_52c.c b/pool/shard002/C/0056619_CWE127_Buffer_Underread__char_declare_ncpy_52c.c new file mode 100644 index 0000000000000000000000000000000000000000..24bfd5e62842084422846f7143443f1dc62f56a4 --- /dev/null +++ b/pool/shard002/C/0056619_CWE127_Buffer_Underread__char_declare_ncpy_52c.c @@ -0,0 +1,58 @@ +/* TEMPLATE GENERATED TESTCASE FILE +Filename: CWE127_Buffer_Underread__char_declare_ncpy_52c.c +Label Definition File: CWE127_Buffer_Underread.stack.label.xml +Template File: sources-sink-52c.tmpl.c +*/ +/* + * @description + * CWE: 127 Buffer Under-read + * BadSource: Set data pointer to before the allocated memory buffer + * GoodSource: Set data pointer to the allocated memory buffer + * Sink: ncpy + * BadSink : Copy data to string using strncpy + * Flow Variant: 52 Data flow: data passed as an argument from one function to another to another in three different source files + * + * */ + +#include "std_testcase.h" + +#include + +/* all the sinks are the same, we just want to know where the hit originated if a tool flags one */ + +#ifndef OMITBAD + +void CWE127_Buffer_Underread__char_declare_ncpy_52c_badSink(char * data) +{ + { + char dest[100]; + memset(dest, 'C', 100-1); /* fill with 'C's */ + dest[100-1] = '\0'; /* null terminate */ + /* POTENTIAL FLAW: Possibly copy from a memory location located before the source buffer */ + strncpy(dest, data, strlen(dest)); + /* Ensure null termination */ + dest[100-1] = '\0'; + printLine(dest); + } +} + +#endif /* OMITBAD */ + +#ifndef OMITGOOD + +/* goodG2B uses the GoodSource with the BadSink */ +void CWE127_Buffer_Underread__char_declare_ncpy_52c_goodG2BSink(char * data) +{ + { + char dest[100]; + memset(dest, 'C', 100-1); /* fill with 'C's */ + dest[100-1] = '\0'; /* null terminate */ + /* POTENTIAL FLAW: Possibly copy from a memory location located before the source buffer */ + strncpy(dest, data, strlen(dest)); + /* Ensure null termination */ + dest[100-1] = '\0'; + printLine(dest); + } +} + +#endif /* OMITGOOD */ diff --git a/pool/shard002/C/0056621_port80.c b/pool/shard002/C/0056621_port80.c new file mode 100644 index 0000000000000000000000000000000000000000..fb2a8160bced68dda3a284e5fd53ddb8366c089b --- /dev/null +++ b/pool/shard002/C/0056621_port80.c @@ -0,0 +1,169 @@ +/* Copyright (c) 2012 The Chromium OS Authors. All rights reserved. + * Use of this source code is governed by a BSD-style license that can be + * found in the LICENSE file. + */ + +/* Port 80 module for Chrome EC */ + +#include "common.h" +#include "console.h" +#include "hooks.h" +#include "host_command.h" +#include "port80.h" +#include "task.h" +#include "timer.h" +#include "util.h" + +#define CPRINTF(format, args...) cprintf(CC_PORT80, format, ## args) + +#define HISTORY_LEN 128 +#define PORT80_POLL_PERIOD MSEC + +static uint16_t __bss_slow history[HISTORY_LEN]; +static int __bss_slow writes; /* Number of port 80 writes so far */ +static int last_boot; /* Last code from previous boot */ +static int __bss_slow scroll; +static int print_in_int = 1; + +void port_80_write(int data) +{ + /* + * Note that this currently prints from inside the LPC interrupt + * itself. If you're dropping events, turn print_in_int off. + */ + if (print_in_int) + CPRINTF("%c[%T Port 80: 0x%02x]", scroll ? '\n' : '\r', data); + + /* Save current port80 code if system is resetting */ + if (data == PORT_80_EVENT_RESET && writes) { + int prev = history[(writes-1) % ARRAY_SIZE(history)]; + + /* Ignore special event codes */ + if (prev < 0x100) + last_boot = prev; + } + + history[writes % ARRAY_SIZE(history)] = data; + writes++; +} + +/*****************************************************************************/ +/* Console commands */ + +static int command_port80(int argc, char **argv) +{ + int head, tail; + int printed = 0; + int i; + + /* + * 'port80 scroll' toggles whether port 80 output begins with a newline + * (scrolling) or CR (non-scrolling). + */ + if (argc > 1) { + if (!strcasecmp(argv[1], "scroll")) { + scroll = !scroll; + ccprintf("scroll %sabled\n", scroll ? "en" : "dis"); + return EC_SUCCESS; + } else if (!strcasecmp(argv[1], "intprint")) { + print_in_int = !print_in_int; + ccprintf("printing in interrupt %sabled\n", + print_in_int ? "en" : "dis"); + return EC_SUCCESS; + } else if (!strcasecmp(argv[1], "flush")) { + writes = 0; + return EC_SUCCESS; + } else { + return EC_ERROR_PARAM1; + } + } + + /* + * Print the port 80 writes so far, clipped to the length of our + * history buffer. + * + * Technically, if a port 80 write comes in while we're printing this, + * we could print an incorrect history. Probably not worth the + * complexity to work around that. + */ + head = writes; + if (head > ARRAY_SIZE(history)) + tail = head - ARRAY_SIZE(history); + else + tail = 0; + + ccputs("Port 80 writes:"); + for (i = tail; i < head; i++) { + int e = history[i % ARRAY_SIZE(history)]; + switch (e) { + case PORT_80_EVENT_RESUME: + ccprintf("\n(S3->S0)"); + printed = 0; + break; + case PORT_80_EVENT_RESET: + ccprintf("\n(RESET)"); + printed = 0; + break; + default: + if (!(printed++ % 20)) { + ccputs("\n "); + cflush(); + } + ccprintf(" %02x", e); + } + } + ccputs(" <--new\n"); + return EC_SUCCESS; +} +DECLARE_CONSOLE_COMMAND(port80, command_port80, + "[scroll | intprint | flush]", + "Print port80 writes or toggle port80 scrolling", + NULL); + +int port80_last_boot(struct host_cmd_handler_args *args) +{ + struct ec_response_port80_last_boot *r = args->response; + + args->response_size = sizeof(*r); + r->code = last_boot; + + return EC_RES_SUCCESS; +} + +int port80_command_read(struct host_cmd_handler_args *args) +{ + const struct ec_params_port80_read *p = args->params; + uint32_t offset = p->read_buffer.offset; + uint32_t entries = p->read_buffer.num_entries; + int i; + struct ec_response_port80_read *rsp = args->response; + + if (args->version == 0) + return port80_last_boot(args); + + if (p->subcmd == EC_PORT80_GET_INFO) { + rsp->get_info.writes = writes; + rsp->get_info.history_size = ARRAY_SIZE(history); + args->response_size = sizeof(rsp->get_info); + return EC_RES_SUCCESS; + } else if (p->subcmd == EC_PORT80_READ_BUFFER) { + /* do not allow bad offset or size */ + if (offset >= ARRAY_SIZE(history) || entries == 0 || + entries > args->response_max) + return EC_RES_INVALID_PARAM; + + for (i = 0; i < entries; i++) { + uint16_t e = history[(i + offset) % + ARRAY_SIZE(history)]; + rsp->data.codes[i] = e; + } + + args->response_size = entries*sizeof(uint16_t); + return EC_RES_SUCCESS; + } + + return EC_RES_INVALID_PARAM; +} +DECLARE_HOST_COMMAND(EC_CMD_PORT80_READ, + port80_command_read, + EC_VER_MASK(0) | EC_VER_MASK(1)); diff --git a/pool/shard002/C/0056623_lst_push_front.c b/pool/shard002/C/0056623_lst_push_front.c new file mode 100644 index 0000000000000000000000000000000000000000..4d3a9321649e2d125568d2bee631365ecf0a1eb2 --- /dev/null +++ b/pool/shard002/C/0056623_lst_push_front.c @@ -0,0 +1,32 @@ +/* ************************************************************************** */ +/* */ +/* ::: :::::::: */ +/* lst_push_front.c :+: :+: :+: */ +/* +:+ +:+ +:+ */ +/* By: nsierra- +#+ +:+ +#+ */ +/* +#+#+#+#+#+ +#+ */ +/* Created: 2015/04/12 03:56:12 by nsierra- #+# #+# */ +/* Updated: 2015/04/12 03:56:28 by nsierra- ### ########.fr */ +/* */ +/* ************************************************************************** */ + +#include "ftlst.h" +#include "ftlst_node.h" + +int lst_push_front(t_lst *lst, void *data) +{ + t_node *node; + + if (!(node = new_node(data))) + return (0); + else if (lst_is_empty(lst)) + { + node->prev = node; + node->next = node; + lst->first = node; + return (++lst->size); + } + node_insert_between(node, lst_node_back(lst), lst_node_front(lst)); + lst->first = node; + return (++lst->size); +} diff --git a/pool/shard002/C/0056626_BiosCallOuts.c b/pool/shard002/C/0056626_BiosCallOuts.c new file mode 100644 index 0000000000000000000000000000000000000000..0d1817aecba0385500aa232339b4c2c746283fb0 --- /dev/null +++ b/pool/shard002/C/0056626_BiosCallOuts.c @@ -0,0 +1,139 @@ +/* + * This file is part of the coreboot project. + * + * Copyright (C) 2011 Advanced Micro Devices, Inc. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; version 2 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ + +#include "agesawrapper.h" +#include "amdlib.h" +#include "BiosCallOuts.h" +#include "Ids.h" +#include "OptionsIds.h" +#include "heapManager.h" +#include +#include + +#ifdef __PRE_RAM__ +/* These defines are used to select the appropriate socket for the SPD read + * because this is a multi-socket design. + */ +#define PCI_REG_GPIO_48_47_46_37_CNTRL (0xA6) +#define PCI_REG_GPIO_52_to_49_CNTRL (0x50) +#define GPIO_OUT_BIT_GPIO48 (BIT3) +#define GPIO_OUT_BIT_GPIO49 (BIT0) +#define GPIO_OUT_ENABLE_BIT_GPIO48 (BIT7) +#define GPIO_OUT_ENABLE_BIT_GPIO49 (BIT4) + +static UINT8 select_socket(UINT8 socket_id) +{ + device_t sm_dev = PCI_DEV(0, 0x14, 0); //SMBUS + UINT8 value = 0; + UINT8 gpio52_to_49 = 0; + + /* Configure GPIO49,48 to select the desired socket + * GPIO49,48 control the IDTQS3253 S1,S0 + * S1 S0 true table + * 0 0 channel 0 + * 0 1 channel 1 + * 1 0 channel 2 - Socket 0 + * 1 1 channel 3 - Socket 1 + * Note: Above is abstracted from Schematic. But actually it seems to be other way. + * 1 0 channel 2 - Socket 1 + * 1 1 channel 3 - Socket 0 + * Note: The DIMMs need to be plugged in from the farthest slot for each channel. + */ + gpio52_to_49 = pci_read_config8(sm_dev, PCI_REG_GPIO_52_to_49_CNTRL); + value = gpio52_to_49 | GPIO_OUT_BIT_GPIO49; // Output of GPIO49 is always forced to "1" + value &= ~(GPIO_OUT_ENABLE_BIT_GPIO49); // 0=Output Enabled, 1=Tristate + pci_write_config8(sm_dev, PCI_REG_GPIO_52_to_49_CNTRL, value); + + value = pci_read_config8(sm_dev, PCI_REG_GPIO_48_47_46_37_CNTRL); + value &= ~(GPIO_OUT_BIT_GPIO48); + value |= (~(socket_id & 1)) << 3; // Output of GPIO48 is inverse of SocketId + value &= ~(GPIO_OUT_ENABLE_BIT_GPIO48); // 0=Output Enabled, 1=Tristate + pci_write_config8(sm_dev, PCI_REG_GPIO_48_47_46_37_CNTRL, value); + + return gpio52_to_49; +} + +static void restore_socket(UINT8 original_value) +{ + device_t sm_dev = PCI_DEV(0, 0x14, 0); //SMBUS + pci_write_config8(sm_dev, PCI_REG_GPIO_52_to_49_CNTRL, original_value); + + // TODO: Restore previous GPIO48 configurations? + //pci_write_config8(sm_dev, PCI_REG_GPIO_48_47_46_37_CNTRL, gpio48_47_46_37_save); +} +#endif + +static AGESA_STATUS board_ReadSpd (UINT32 Func,UINT32 Data, VOID *ConfigPtr); + +STATIC BIOS_CALLOUT_STRUCT BiosCallouts[] = +{ + {AGESA_ALLOCATE_BUFFER, BiosAllocateBuffer }, + {AGESA_DEALLOCATE_BUFFER, BiosDeallocateBuffer }, + {AGESA_LOCATE_BUFFER, BiosLocateBuffer }, + {AGESA_DO_RESET, agesa_Reset }, + {AGESA_READ_SPD, board_ReadSpd }, + {AGESA_READ_SPD_RECOVERY, agesa_NoopUnsupported }, + {AGESA_RUNFUNC_ONAP, agesa_RunFuncOnAp }, + {AGESA_GET_IDS_INIT_DATA, agesa_EmptyIdsInitData }, + {AGESA_HOOKBEFORE_DQS_TRAINING, agesa_NoopSuccess }, + {AGESA_HOOKBEFORE_DRAM_INIT, agesa_NoopSuccess }, + {AGESA_HOOKBEFORE_EXIT_SELF_REF, agesa_NoopSuccess }, +}; + +AGESA_STATUS GetBiosCallout (UINT32 Func, UINT32 Data, VOID *ConfigPtr) +{ + UINTN i; + AGESA_STATUS CalloutStatus; + UINTN CallOutCount = sizeof (BiosCallouts) / sizeof (BiosCallouts [0]); + + for (i = 0; i < CallOutCount; i++) { + if (BiosCallouts[i].CalloutName == Func) { + break; + } + } + + if(i >= CallOutCount) { + return AGESA_UNSUPPORTED; + } + + CalloutStatus = BiosCallouts[i].CalloutPtr (Func, Data, ConfigPtr); + + return CalloutStatus; +} + +static AGESA_STATUS board_ReadSpd (UINT32 Func, UINT32 Data, VOID *ConfigPtr) +{ + AGESA_STATUS Status; +#ifdef __PRE_RAM__ + UINT8 original_value = 0; + + if (ConfigPtr == NULL) + return AGESA_ERROR; + + original_value = select_socket(((AGESA_READ_SPD_PARAMS *)ConfigPtr)->SocketId); + + Status = agesa_ReadSPD (Func, Data, ConfigPtr); + + restore_socket(original_value); +#else + Status = AGESA_UNSUPPORTED; +#endif + + return Status; +} diff --git a/pool/shard002/C/0056628_sim.c b/pool/shard002/C/0056628_sim.c new file mode 100644 index 0000000000000000000000000000000000000000..f647e51a194470f186f40833c6cdee0411d0e785 --- /dev/null +++ b/pool/shard002/C/0056628_sim.c @@ -0,0 +1,216 @@ +#define _BSD_SOURCE + +#include +#include +#include +#include +#include + +#include + +typedef int bool; +typedef int boolean; +#define false 0 +#define true 1 + +#define delayMicroseconds my_usleep + +static int time_multiplier = 1; +static bool fake_sleep = false; +static unsigned long fake_time=0; + +int my_usleep(unsigned long usec) +{ + fake_time += usec; + if(!fake_sleep) { + usleep(usec/time_multiplier); + } + return 0; +} + +unsigned long micros() +{ + // if(fake_sleep) { + return fake_time; + // } + //else { + //struct timeval tv; + //gettimeofday(&tv,NULL); + //// printf("micros=%ld\n", tv.tv_usec); + //return time_multiplier*(tv.tv_sec*1000000 + tv.tv_usec); + //} +} + +//************** Mock servo ************* +//disable to preserve space +#define USE_SMOOTH_SERVO +//#define USE_LINEAR_SERVO + +#define UP 100 +#define DOWN 20 + +static int oldPos = 0; + +void movePen(boolean down, boolean fast) +{ +#ifndef SERIAL_DEBUG + int pos = down ? DOWN : UP; + if(pos != oldPos) { + +#ifdef USE_SMOOTH_SERVO + if(fast) { + printf("%ld %d=%d\n",micros(), 0,(int)pos); + } + else { + for(float i=0 ; i<=1.0 ; i+=0.01) { + float i2 = (1-cos(i*3.14))/2; + float tmpPos = (oldPos*(1.0-i2)+(pos*i2)); + + // myservo.write((int)tmpPos); + printf("%ld %d=%d\n",micros(), 0,(int)tmpPos); + + delayMicroseconds(10000); + } + } +#else //USE_SMOOTH_SERVO + // myservo.write((int)pos); + printf("%ld %d=%d\n",micros(), 0,(int)pos); +#endif //USE_SMOOTH_SERVO + + oldPos = pos; + } +#endif +} + +void setupServo() +{ + movePen(false, true); +} + +void makePenNoise() +{ + int p = oldPos; + for(int i=0;i<4;i++) { + // myservo.write((int)p-15); + delayMicroseconds(400000); + // myservo.write((int)p); + delayMicroseconds(400000); + } +} + + +//*********************** mock eeprom ****************** +long eepromdata_long[100]; +float eepromdata_float[100]; + +void eepromWriteLong(int addr, long data) { + eepromdata_long[addr] = data; + // printf("eeprom[%d]=%ld", addr, data); +} + +void eepromWriteFloat(int addr, float data) { + eepromdata_float[addr] = data; + // printf("eeprom[%d]=%f", addr, data); +} + +long eepromReadLong(int addr) { + long ret = eepromdata_long[addr]; + // printf("eeprom[%d] -> %ld", addr, ret); + return ret; +} + +float eepromReadFloat(int addr) { + float ret = eepromdata_float[addr]; + //printf("eeprom[%d] -> %f", addr, ret); + return ret; +} +//********************** mock IR **************************** +FILE* ir_file = NULL; +void setupIR() +{ + ir_file = fopen("irdata.txt", "r+"); +} + +extern int currentPlot; +extern int program; + +void readIR() +{ + //just read from file what plot to start and kick it off + if(program == 0) { + if(ir_file) { + char buf[100]; + if(fgets(buf, 99, ir_file)) { + program = 1; //start print + currentPlot = atoi(buf); + // fprintf(stderr,"%d\n",currentPlot); + } + else { + fprintf(stderr, "plot time = %.1f s\n", micros()/1000000.0); + exit(0); + } + } + } +} + + +//****************** include arduino code ********************* +#define USE_DATA_FROM_DISK +#define USE_MOCKED_STEPPERS + +//inlude data ino file +#define File FILE* +#define PROGMEM +#define prog_int16_t short +#define OUTPUT 0 +void pinMode(int p, int m) {} +#define FILE_READ "r" +#define pgm_read_word_near * +#define tmp_seek(a,b) fseek(a,b,SEEK_SET) +#define max(a,b) ((a)>(b)?(a):(b)) +#define min(a,b) ((a)>(b)?(b):(a)) +extern long disparity; +#include "/tmp/data.ino" + +//include stepper file +typedef unsigned char byte; +#define PI 3.1415926535 +#define B1000 0b1000 +#define B1100 0b1100 +#define B0100 0b0100 +#define B0110 0b0110 +#define B0010 0b0010 +#define B0011 0b0011 +#define B0001 0b0001 +#define B1001 0b1001 +#define digitalWrite(pin, val) printf("%lu %d=%d\n",micros(), (pin),(val)) +#define spoolCirc 94.2 +#define stepsPerRotation 4075.7728395 +#define stepsPerMM (stepsPerRotation/spoolCirc) +#define abs(X) abs((int)(X)) + +#include "../plotter/step_control.ino" + +//inlude main plotter file +#include "../plotter/plotter.ino" + + +int main(int argc, char* argv[]) +{ + if(argc > 1) { + time_multiplier = atoi(argv[1]); + if(time_multiplier == 0) { + time_multiplier = 1; + } + else if(time_multiplier > 100) { + fake_sleep = true; //OS sleep functions will just wait too long for really short naps, so lets fake it all. + } + } + + setup(); + for(;;) { + loop(); + } + + return 0; +} diff --git a/pool/shard002/C/0056629_sol-worker-thread-impl-posix.c b/pool/shard002/C/0056629_sol-worker-thread-impl-posix.c new file mode 100644 index 0000000000000000000000000000000000000000..b2f55dd7501faf0e2b4924b79dee99e62a231cd0 --- /dev/null +++ b/pool/shard002/C/0056629_sol-worker-thread-impl-posix.c @@ -0,0 +1,235 @@ +/* + * This file is part of the Soletta™ Project + * + * Copyright (C) 2015 Intel Corporation. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include +#include +#include + +#include "sol-atomic.h" +#include "sol-mainloop.h" +#include "sol-worker-thread-impl.h" + +struct sol_worker_thread_posix { + struct sol_worker_thread_config config; + struct sol_idle *idler; + pthread_mutex_t lock; + pthread_t thread; + sol_atomic_int cancel; +}; + +bool +sol_worker_thread_impl_cancel_check(const void *handle) +{ + const struct sol_worker_thread_posix *thread = handle; + + return sol_atomic_load(&thread->cancel, SOL_ATOMIC_RELAXED); +} + +static inline void +cancel_set(struct sol_worker_thread_posix *thread) +{ + sol_atomic_store(&thread->cancel, true, SOL_ATOMIC_RELAXED); +} + +static bool +sol_worker_thread_lock(struct sol_worker_thread_posix *thread) +{ + int error = pthread_mutex_lock(&thread->lock); + + if (!error) + return true; + if (error == EDEADLK) + abort(); + + return false; +} + +static void +sol_worker_thread_unlock(struct sol_worker_thread_posix *thread) +{ + pthread_mutex_unlock(&thread->lock); +} + +static bool +sol_worker_thread_finished(void *data) +{ + struct sol_worker_thread_posix *thread = data; + + if (!sol_worker_thread_impl_cancel_check(thread)) { + /* no need to set cancel, the thread has finished */ + pthread_join(thread->thread, NULL); + thread->thread = 0; + } + pthread_mutex_destroy(&thread->lock); + + /* no locks since thread is now dead */ + thread->idler = NULL; + + SOL_DBG("worker thread %p finished", thread); + + if (thread->config.finished) + thread->config.finished((void *)thread->config.data); + + free(thread); + return false; +} + +static void * +sol_worker_thread_do(void *data) +{ + struct sol_worker_thread_posix *thread = data; + struct sol_worker_thread_config *config = &thread->config; + + SOL_DBG("worker thread %p started", thread); + + if (config->setup) { + if (!config->setup((void *)config->data)) + goto end; + } + + while (!sol_worker_thread_impl_cancel_check(thread)) { + if (!config->iterate((void *)config->data)) + break; + } + + if (config->cleanup) + config->cleanup((void *)config->data); + +end: + if (sol_worker_thread_lock(thread)) { + if (thread->idler) + sol_idle_del(thread->idler); + thread->idler = sol_idle_add(sol_worker_thread_finished, thread); + sol_worker_thread_unlock(thread); + } + + SOL_DBG("worker thread %p stopped", thread); + + return thread; +} + +extern void sol_mainloop_posix_signals_block(void); +extern void sol_mainloop_posix_signals_unblock(void); + +void * +sol_worker_thread_impl_new(const struct sol_worker_thread_config *config) +{ + pthread_mutexattr_t attrs; + struct sol_worker_thread_posix *thread; + int r; + + thread = calloc(1, sizeof(*thread)); + SOL_NULL_CHECK(thread, NULL); + + thread->config = *config; + + r = pthread_mutexattr_init(&attrs); + SOL_INT_CHECK_GOTO(r, != 0, error_mutex); + + pthread_mutexattr_setpshared(&attrs, PTHREAD_PROCESS_SHARED); +#if defined(PTHREAD_MUTEX_ADAPTIVE_NP) + pthread_mutexattr_settype(&attrs, PTHREAD_MUTEX_ADAPTIVE_NP); +#endif + + r = pthread_mutex_init(&thread->lock, &attrs); + pthread_mutexattr_destroy(&attrs); + SOL_INT_CHECK_GOTO(r, != 0, error_mutex); + + sol_mainloop_posix_signals_block(); + r = pthread_create(&thread->thread, NULL, + sol_worker_thread_do, thread); + sol_mainloop_posix_signals_unblock(); + SOL_INT_CHECK_GOTO(r, != 0, error_thread); + + return thread; + +error_thread: + pthread_mutex_destroy(&thread->lock); + +error_mutex: + free(thread); + errno = r; + return NULL; +} + +void +sol_worker_thread_impl_cancel(void *handle) +{ + struct sol_worker_thread_posix *thread = handle; + + SOL_NULL_CHECK(thread); + + if (sol_worker_thread_impl_cancel_check(thread)) { + SOL_WRN("worker thread %p is not running.", thread); + return; + } + if (thread->thread == pthread_self()) { + SOL_WRN("trying to cancel from worker thread %p.", thread); + return; + } + + cancel_set(thread); + + if (thread->config.cancel) + thread->config.cancel((void *)thread->config.data); + + pthread_join(thread->thread, NULL); + thread->thread = 0; + + /* no locks since thread is now dead */ + sol_idle_del(thread->idler); + sol_worker_thread_finished(thread); +} + +static bool +sol_worker_thread_feedback_dispatch(void *data) +{ + struct sol_worker_thread_posix *thread = data; + + if (sol_worker_thread_lock(thread)) { + thread->idler = NULL; + sol_worker_thread_unlock(thread); + } + + thread->config.feedback((void *)thread->config.data); + return false; +} + +void +sol_worker_thread_impl_feedback(void *handle) +{ + struct sol_worker_thread_posix *thread = handle; + + SOL_NULL_CHECK(thread); + SOL_NULL_CHECK(thread->config.feedback); + + if (sol_worker_thread_impl_cancel_check(thread)) { + SOL_WRN("worker thread %p is not running.", thread); + return; + } + if (thread->thread != pthread_self()) { + SOL_WRN("trying to feedback from different worker thread %p.", thread); + return; + } + if (sol_worker_thread_lock(thread)) { + if (!thread->idler) + thread->idler = sol_idle_add(sol_worker_thread_feedback_dispatch, thread); + sol_worker_thread_unlock(thread); + } +} diff --git a/pool/shard002/C/0056635_main.c b/pool/shard002/C/0056635_main.c new file mode 100644 index 0000000000000000000000000000000000000000..6f96419f9304b0d2ed0317455fe3345237130615 --- /dev/null +++ b/pool/shard002/C/0056635_main.c @@ -0,0 +1,56 @@ +/* + * @Copyright (C) 2004-2006 Christian Hammond. + * Some of this code is from gtkspell, Copyright (C) 2002 Evan Martin. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the + * Free Software Foundation, Inc., 59 Temple Place - Suite 330, + * Boston, MA 02111-1307, USA. + */ + +#include +#include + +int +main(int argc, char **argv) +{ + GtkWidget *window; + GtkWidget *hbox; + GtkWidget *label; + GtkWidget *entry; + + gtk_init(&argc, &argv); + + window = gtk_window_new(GTK_WINDOW_TOPLEVEL); + gtk_window_set_title(GTK_WINDOW(window), "Sexy Spell Entry Test"); + gtk_container_set_border_width(GTK_CONTAINER(window), 12); + + g_signal_connect(G_OBJECT(window), "destroy", + G_CALLBACK(gtk_main_quit), NULL); + + hbox = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 6); + gtk_container_add(GTK_CONTAINER(window), hbox); + + label = gtk_label_new("Text:"); + gtk_box_pack_start(GTK_BOX(hbox), label, FALSE, FALSE, 0); + + entry = sexy_spell_entry_new(); + gtk_box_pack_start(GTK_BOX(hbox), entry, TRUE, TRUE, 0); + + gtk_entry_set_text(GTK_ENTRY (entry), "Hello Wrold"); + + gtk_widget_show_all(window); + gtk_main(); + + return 0; +} diff --git a/pool/shard002/C/0056641_plma_comm.c b/pool/shard002/C/0056641_plma_comm.c new file mode 100644 index 0000000000000000000000000000000000000000..b3ae2a96b0dbf106423d45292525f950f20d84b7 --- /dev/null +++ b/pool/shard002/C/0056641_plma_comm.c @@ -0,0 +1,82 @@ +#include "plma.h" + + +/***********************************************************************//** +* @brief This routine is used to clean up the mailbox. +* +* @param[in] arg - +* @param[in] msg - +* +* @return 0 - If failure +* @return 1 - If success +***************************************************************************/ +static bool plma_client_cleanup_mbx(NCSCONTEXT arg, NCSCONTEXT msg) +{ + PLMS_EVT *cbk_msg, *pnext; + TRACE_ENTER(); + pnext = cbk_msg = (PLMS_EVT *)msg; + while (pnext) { + pnext = cbk_msg->next; + free(cbk_msg); + cbk_msg = pnext; + } + TRACE_LEAVE(); + return true; + +} + +/***********************************************************************//** +* @brief This routine is used to initialize the queue for the callbacks. +* +* @param[in] client_info - pointer to the client info. +* +* @return NCSCC_RC_SUCCESS/NCSCC_RC_FAILURE. +***************************************************************************/ +uint32_t plma_callback_ipc_init(PLMA_CLIENT_INFO *client_info) +{ + uint32_t rc = NCSCC_RC_SUCCESS; + + TRACE_ENTER(); + + if ((NCSCC_RC_SUCCESS == m_NCS_IPC_CREATE(&client_info->callbk_mbx))){ + if (m_NCS_IPC_ATTACH(&client_info->callbk_mbx) == + NCSCC_RC_SUCCESS) { + + return NCSCC_RC_SUCCESS; + } + LOG_ER("IPC ATTACH FAILED"); + m_NCS_IPC_RELEASE(&client_info->callbk_mbx, NULL); + LOG_ER("IPC CREATE FAILED"); + rc = NCSCC_RC_FAILURE; + } + + TRACE_LEAVE(); + return rc; +} + + + + +/**************************************************************************** + Name : plma _callback_ipc_destroy + + Description : This routine is used to destroy the queue for the callbacks + + Arguments : client_info - pointer to the client info + + Return Values : NCSCC_RC_SUCCESS/NCSCC_RC_FAILURE + + Notes : None +******************************************************************************/ +void plma_callback_ipc_destroy(PLMA_CLIENT_INFO *client_info) +{ + TRACE_ENTER(); + /* detach the mail box */ + m_NCS_IPC_DETACH(&client_info->callbk_mbx, plma_client_cleanup_mbx, client_info); + + /* delete the mailbox */ + m_NCS_IPC_RELEASE(&client_info->callbk_mbx, NULL); + TRACE_LEAVE(); + return; +} + diff --git a/pool/shard002/C/0056651_pltnp.c b/pool/shard002/C/0056651_pltnp.c new file mode 100644 index 0000000000000000000000000000000000000000..623225a10b5bf949c82aa6334a6f99bd81c342ba --- /dev/null +++ b/pool/shard002/C/0056651_pltnp.c @@ -0,0 +1,381 @@ +/* pltnp.f -- translated by f2c (version 19980913). + You must link the resulting object file with the libraries: + -lf2c -lm (in that order) +*/ + +#include "f2c.h" + +/* $Procedure PLTNP ( Nearest point on triangular plate ) */ +/* Subroutine */ int pltnp_(doublereal *point, doublereal *v1, doublereal *v2, + doublereal *v3, doublereal *pnear, doublereal *dist) +{ + extern /* Subroutine */ int vadd_(doublereal *, doublereal *, doublereal * + ); + doublereal perp[3]; + extern doublereal vdot_(doublereal *, doublereal *); + extern /* Subroutine */ int vsub_(doublereal *, doublereal *, doublereal * + ), vequ_(doublereal *, doublereal *); + logical degen; + doublereal pdiff[3], d1, d2, d3, e1[3]; + extern doublereal vdist_(doublereal *, doublereal *); + doublereal e2[3], e3[3], l1, l2, l3; + extern doublereal vnorm_(doublereal *); + extern /* Subroutine */ int vcrss_(doublereal *, doublereal *, doublereal + *), vperp_(doublereal *, doublereal *, doublereal *); + extern logical vzero_(doublereal *); + doublereal enorm1[3], enorm2[3], enorm3[3], normal[3]; + logical in1, in2, in3; + extern /* Subroutine */ int npsgpt_(doublereal *, doublereal *, + doublereal *, doublereal *, doublereal *); + extern logical return_(void); + doublereal np1[3], np2[3]; + +/* $ Abstract */ + +/* Find the nearest point on a triangular plate to a given point. */ + +/* $ Disclaimer */ + +/* THIS SOFTWARE AND ANY RELATED MATERIALS WERE CREATED BY THE */ +/* CALIFORNIA INSTITUTE OF TECHNOLOGY (CALTECH) UNDER A U.S. */ +/* GOVERNMENT CONTRACT WITH THE NATIONAL AERONAUTICS AND SPACE */ +/* ADMINISTRATION (NASA). THE SOFTWARE IS TECHNOLOGY AND SOFTWARE */ +/* PUBLICLY AVAILABLE UNDER U.S. EXPORT LAWS AND IS PROVIDED "AS-IS" */ +/* TO THE RECIPIENT WITHOUT WARRANTY OF ANY KIND, INCLUDING ANY */ +/* WARRANTIES OF PERFORMANCE OR MERCHANTABILITY OR FITNESS FOR A */ +/* PARTICULAR USE OR PURPOSE (AS SET FORTH IN UNITED STATES UCC */ +/* SECTIONS 2312-2313) OR FOR ANY PURPOSE WHATSOEVER, FOR THE */ +/* SOFTWARE AND RELATED MATERIALS, HOWEVER USED. */ + +/* IN NO EVENT SHALL CALTECH, ITS JET PROPULSION LABORATORY, OR NASA */ +/* BE LIABLE FOR ANY DAMAGES AND/OR COSTS, INCLUDING, BUT NOT */ +/* LIMITED TO, INCIDENTAL OR CONSEQUENTIAL DAMAGES OF ANY KIND, */ +/* INCLUDING ECONOMIC DAMAGE OR INJURY TO PROPERTY AND LOST PROFITS, */ +/* REGARDLESS OF WHETHER CALTECH, JPL, OR NASA BE ADVISED, HAVE */ +/* REASON TO KNOW, OR, IN FACT, SHALL KNOW OF THE POSSIBILITY. */ + +/* RECIPIENT BEARS ALL RISK RELATING TO QUALITY AND PERFORMANCE OF */ +/* THE SOFTWARE AND ANY RELATED MATERIALS, AND AGREES TO INDEMNIFY */ +/* CALTECH AND NASA FOR ALL THIRD-PARTY CLAIMS RESULTING FROM THE */ +/* ACTIONS OF RECIPIENT IN THE USE OF THE SOFTWARE. */ + +/* $ Required_Reading */ + +/* None. */ + +/* $ Keywords */ + +/* GEOMETRY */ +/* MATH */ + +/* $ Declarations */ +/* $ Brief_I/O */ + +/* Variable I/O Description */ +/* -------- --- -------------------------------------------------- */ +/* POINT I A point in 3-dimensional space. */ +/* V1, */ +/* V2, */ +/* V3 I Vertices of a triangular plate. */ +/* PNEAR O Nearest point on the plate to POINT. */ +/* DIST O Distance between PNEAR and POINT. */ + +/* $ Detailed_Input */ + +/* POINT is an arbitrary point in 3-dimensional space. */ + +/* V1, */ +/* V2, */ +/* V3 are 3-vectors constituting the vertices of */ +/* a triangular plate. */ + +/* The plate is allowed to be degenerate: it may */ +/* consist of a line segment or of a single point. */ + +/* $ Detailed_Output */ + +/* PNEAR is the closest point on the plate to POINT. */ +/* PNEAR is unique, since the plate is convex. */ + +/* DIST is the distance between POINT and PNEAR. */ + +/* $ Parameters */ + +/* None. */ + +/* $ Exceptions */ + +/* 1) The input plate is allowed to be degenerate: it may be */ +/* a line segment or a single point. */ + +/* $ Files */ + +/* None. */ + +/* $ Particulars */ + +/* None. */ + +/* $ Examples */ + +/* The numerical results shown for these examples may differ across */ +/* platforms. The results depend on the SPICE kernels used as input */ +/* (if any), the compiler and supporting libraries, and the machine */ +/* specific arithmetic implementation. */ + + +/* 1) Find the nearest point to the point (2,2,2) on a plate having */ +/* vertices at the unit basis vectors that lie along the positive */ +/* X, Y, and Z coordinate axes. */ + + +/* Example code begins here. */ + + +/* PROGRAM EX1 */ +/* IMPLICIT NONE */ + +/* C */ +/* C Local parameters */ +/* C */ +/* CHARACTER*(*) FMT1 */ +/* PARAMETER ( FMT1 = '(A,3E16.8)' ) */ +/* C */ +/* C Local variables */ +/* C */ +/* DOUBLE PRECISION DIST */ +/* DOUBLE PRECISION POINT ( 3 ) */ +/* DOUBLE PRECISION PNEAR ( 3 ) */ +/* DOUBLE PRECISION V1 ( 3 ) */ +/* DOUBLE PRECISION V2 ( 3 ) */ +/* DOUBLE PRECISION V3 ( 3 ) */ + +/* C */ +/* C POINT is the input point. */ +/* C */ +/* CALL VPACK ( 2.D0, 2.D0, 2.D0, POINT ) */ +/* C */ +/* C V1, V2, V3 are the vertices of a plate. */ +/* C */ +/* CALL VPACK ( 1.D0, 0.D0, 0.D0, V1 ) */ +/* CALL VPACK ( 0.D0, 1.D0, 0.D0, V2 ) */ +/* CALL VPACK ( 0.D0, 0.D0, 1.D0, V3 ) */ +/* C */ +/* C Find the near point on the plate. */ +/* C */ +/* CALL PLTNP ( POINT, V1, V2, V3, PNEAR, DIST ) */ + +/* WRITE (*,*) ' ' */ +/* WRITE (*,FMT1) 'Plate vertex 1 = ', V1 */ +/* WRITE (*,FMT1) 'Plate vertex 3 = ', V2 */ +/* WRITE (*,FMT1) 'Plate vertex 3 = ', V3 */ +/* WRITE (*,FMT1) 'Input point = ', POINT */ +/* WRITE (*,*) ' ' */ +/* WRITE (*,FMT1) 'Near point = ', PNEAR */ +/* WRITE (*,FMT1) 'Distance = ', DIST */ +/* WRITE (*,*) ' ' */ + +/* END */ + + +/* When this program was executed on a PC/Linux/gfortran platform, */ +/* the output was: */ + + +/* Plate vertex 1 = 0.10000000E+01 0.00000000E+00 0.00000000E+00 */ +/* Plate vertex 3 = 0.00000000E+00 0.10000000E+01 0.00000000E+00 */ +/* Plate vertex 3 = 0.00000000E+00 0.00000000E+00 0.10000000E+01 */ +/* Input point = 0.20000000E+01 0.20000000E+01 0.20000000E+01 */ + +/* Near point = 0.33333333E+00 0.33333333E+00 0.33333333E+00 */ +/* Distance = 0.28867513E+01 */ + + +/* $ Restrictions */ + +/* None. */ + +/* $ Literature_References */ + +/* None. */ + +/* $ Author_and_Institution */ + +/* N.J. Bachman (JPL) */ + +/* $ Version */ + +/* - SPICELIB Version 1.1.2, 01-FEB-2016 (NJB) */ + +/* Added code example to header. */ + +/* - DSKLIB Version 1.1.1, 19-MAR-2015 (NJB) */ + +/* Fixed spelling error in header. */ + +/* - DSKLIB Version 1.1.0, 31-DEC-2014 (NJB) */ + +/* Bug fix: vertex indices for outside case, near */ +/* point on 3rd edge were corrected. */ + +/* - DSKLIB Version 1.0.0, 29-SEP-2014 (NJB) */ + +/* -& */ +/* $ Index_Entries */ + +/* nearest point on triangular plate */ + +/* -& */ + +/* SPICELIB functions */ + + +/* Local variables */ + + if (return_()) { + return 0; + } + +/* Use discovery check-in. */ + + +/* Compute the plate's edges. */ + + vsub_(v2, v1, e1); + vsub_(v3, v2, e2); + vsub_(v1, v3, e3); + +/* Compute a normal vector for the plate, if possible. */ +/* If the plate is degenerate, we'll find out at this point. */ + + vcrss_(e1, e2, normal); + +/* Compute the outward normals of the plate's edges in the */ +/* plate containing the plate. */ + + vcrss_(e1, normal, enorm1); + vcrss_(e2, normal, enorm2); + vcrss_(e3, normal, enorm3); + degen = vzero_(normal) || vzero_(enorm1) || vzero_(enorm2) || vzero_( + enorm3); + if (degen) { + +/* The "plate" is a line segment or point. Determine */ +/* which case we have. */ + + l1 = vnorm_(e1); + l2 = vnorm_(e2); + l3 = vnorm_(e3); + if (l1 == 0. && l2 == 0.) { + +/* Up to round-off error, the vertices coincide. */ +/* The vertex V1 for practical purposes is the plate. */ + + vequ_(v1, pnear); + *dist = vdist_(pnear, point); + } else { + +/* The plate is a line segment having positive length. */ +/* One of the edges will coincide with the segment. */ +/* Determine which vertices are the endpoints. */ + + if (l1 > max(l2,l3)) { + +/* The segment is bounded by V1 and V2. */ + + npsgpt_(v1, v2, point, pnear, dist); + } else if (l2 > max(l3,l1)) { + +/* The segment is bounded by V2 and V3. */ + + npsgpt_(v2, v3, point, pnear, dist); + } else { + +/* The segment is bounded by V3 and V1. */ + + npsgpt_(v3, v1, point, pnear, dist); + } + } + +/* The outputs are set for the degenerate cases. */ + + return 0; + } + +/* We have a non-degenerate plate. NORMAL has unit length. */ + +/* We'll treat V1 as an origin in the plane containing */ +/* the plate. Find the offset of the POINT from V1, and */ +/* find the component of this offset orthogonal to NORMAL. */ + + vsub_(point, v1, pdiff); + vperp_(pdiff, normal, perp); + +/* Determine whether V1+PERP is inside the plate. */ + +/* Note that the "line constants" for edges 1 and 3 */ +/* are zero, since these edges contain V1. The line */ +/* constant for edge 2 is that of the offset of V2 */ +/* from V1; this offset is edge 1. */ + + in1 = vdot_(perp, enorm1) <= 0.; + in2 = vdot_(perp, enorm2) <= vdot_(e1, enorm2); + in3 = vdot_(perp, enorm3) <= 0.; + if (in1 && in2 && in3) { + +/* V1+PERP is inside the plate. It is the closest */ +/* point on the plate to POINT. */ + + vadd_(v1, perp, pnear); + +/* We have the near point; set the distance. */ + + *dist = vdist_(pnear, point); + } else { + +/* PERP is outside the plate. The nearest point */ +/* on the plate to POINT is on one of the edges. */ + +/* We'll use the "in" flags to reduce the number */ +/* of point-edge distance computations. */ + + if (! in1 && (in2 && in3)) { + +/* The solution must be on the first edge. */ + + npsgpt_(v1, v2, point, pnear, dist); + } else if (! in2 && (in3 && in1)) { + +/* The solution must be on the second edge. */ + + npsgpt_(v2, v3, point, pnear, dist); + } else if (! in3 && (in1 && in2)) { + +/* The solution must be on the third edge. */ + + npsgpt_(v3, v1, point, pnear, dist); + } else { + +/* Compute solutions on all three edges and pick */ +/* the best one. */ + + npsgpt_(v1, v2, point, np1, &d1); + npsgpt_(v2, v3, point, np2, &d2); + npsgpt_(v3, v1, point, pnear, &d3); + if (d1 <= min(d2,d3)) { + vequ_(np1, pnear); + *dist = d1; + } else if (d2 <= min(d3,d1)) { + vequ_(np2, pnear); + *dist = d2; + } else { + +/* PNEAR is already set. */ + + *dist = d3; + } + } + } + return 0; +} /* pltnp_ */ + diff --git a/pool/shard002/C/0056672_entry.c b/pool/shard002/C/0056672_entry.c new file mode 100644 index 0000000000000000000000000000000000000000..63b328db8bfcf29cdbd2a3237e1908acc3206f45 --- /dev/null +++ b/pool/shard002/C/0056672_entry.c @@ -0,0 +1,267 @@ +/* DreamChess +** +** DreamChess is the legal property of its developers, whose names are too +** numerous to list here. Please refer to the COPYRIGHT file distributed +** with this source distribution. +** +** 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 + +#define CURSOR_WIDTH 1 + +static gg_colour_t col_grey = { + 0.5f, 0.5f, 0.5f, 1.0f +}; + +static gg_colour_t col_texthighlight = { + 0.55f, 0.65f, 0.95f, 1.0f +}; + +static gg_colour_t col_text = { + 1.0f, 1.0f, 1.0f, 1.0f +}; + +gg_class_id gg_entry_get_class_id(void) +{ +GG_CHILD(gg_widget_get_class_id())} + +static int string_width(char *s, int n) +{ + int retval; + char c = s[n]; + + s[n] = 0; + gg_system_get_string_size(s, &retval, NULL); + s[n] = c; + return retval; +} + +/** Implements widget::render for text entry widgets. */ +void gg_entry_render(gg_widget_t * widget, int x, int y, int focus) +{ + gg_entry_t *entry = GG_ENTRY(widget); + gg_rect_t rect; + int len = string_width(entry->text, entry->cursor_pos); + gg_colour_t *colour; + + switch (focus) + { + case GG_FOCUS_DISABLED: + colour = &col_grey; + break; + case GG_FOCUS_ONE: + case GG_FOCUS_ALL: + colour = &col_texthighlight; + break; + case GG_FOCUS_NONE: + colour = &col_text; + } + + /* TODO Fix temporary hack */ + if (!widget->enabled) + colour = &col_grey; + + gg_system_draw_rect(x, y, entry->width_a, entry->height_a, colour); + + x += ENTRY_SPACING; + y += ENTRY_SPACING; + + rect.x = x; + rect.y = y; + rect.width = entry->width_a - 2 * ENTRY_SPACING; + rect.height = entry->height_a - 2 * ENTRY_SPACING; + gg_clipping_adjust(&rect); + + gg_system_draw_string(entry->text, x - entry->display_pos, y, colour, + 0, 0); + + if (focus == GG_FOCUS_ONE || focus == GG_FOCUS_ALL) + { + if (gg_system_get_ticks() % 400 < 200) + gg_system_draw_filled_rect(x + len - entry->display_pos, y, + CURSOR_WIDTH, + entry->height_a - 2 * ENTRY_SPACING, + &col_texthighlight); + } + + gg_clipping_undo(); +} + +/** Implements widget::input for text entry widgets. */ +int gg_entry_input(gg_widget_t * widget, gg_event_t event) +{ + gg_entry_t *entry = GG_ENTRY(widget); + int len = strlen(entry->text); + int width, max_width; + + if (event.type == GG_EVENT_KEY) + { + + if (event.key == GG_KEY_LEFT) + { + if (entry->cursor_pos > 0) + entry->cursor_pos--; + else + return 0; + } + else if (event.key == GG_KEY_RIGHT) + { + if (entry->cursor_pos < len) + entry->cursor_pos++; + else + return 0; + } + else if (event.key == GG_KEY_HOME) + entry->cursor_pos = 0; + else if (event.key == GG_KEY_END) + entry->cursor_pos = len; + else if (event.key == GG_KEY_BACKSPACE) + { + if (entry->cursor_pos > 0) + { + int i; + + for (i = entry->cursor_pos; i <= len; i++) + entry->text[i - 1] = entry->text[i]; + entry->cursor_pos--; + } + } + else if (event.key == GG_KEY_DELETE) + { + if (entry->cursor_pos < len) + { + int i; + + for (i = entry->cursor_pos + 1; i <= len; i++) + entry->text[i - 1] = entry->text[i]; + } + } + else if (event.key == GG_KEY_ACTION) + { + gg_widget_emit_signal(widget, widget, entry->action_pressed, NULL); + } + else + { + if ((event.key > 0) && (event.key <= 255)) + { + int i; + + if (len >= entry->max_len) + return 1; + + for (i = len; i >= entry->cursor_pos; i--) + entry->text[i + 1] = entry->text[i]; + entry->text[entry->cursor_pos++] = event.key; + } + else + return 0; + } + } + + if (event.type == GG_EVENT_MOUSE + && event.mouse.type == GG_MOUSE_BUTTON_DOWN && event.mouse.button == 0) + { + int total_width = 0; + int i; + + for (i = 0; i < strlen(entry->text); i++) + { + int width; + + gg_system_get_char_size(entry->text[i], &width, NULL); + total_width += width; + if (total_width > entry->display_pos + event.mouse.x) + { + if (total_width - width / 2 < + entry->display_pos + event.mouse.x) + i++; + break; + } + } + + entry->cursor_pos = i; + } + + width = string_width(entry->text, entry->cursor_pos); + max_width = entry->width_a - 2 * ENTRY_SPACING - CURSOR_WIDTH; + + if (width - entry->display_pos > max_width) + entry->display_pos = width - max_width; + + if (width - entry->display_pos < 0) + entry->display_pos = width; + + return 1; +} + +void gg_entry_init(gg_entry_t * entry, int width) +{ + gg_widget_init((gg_widget_t *) entry); + + entry->render = gg_entry_render; + entry->input = gg_entry_input; + entry->id = gg_entry_get_class_id(); + entry->max_len = ENTRY_MAX_LEN; + entry->cursor_pos = 0; + entry->text[0] = '\0'; + entry->enabled = 1; + gg_system_get_string_size("A", NULL, &entry->height); + entry->width = width + ENTRY_SPACING * 2; + entry->height += ENTRY_SPACING * 2; + entry->display_pos = 0; + entry->action_pressed = gg_signal_lookup(entry->id, "action_pressed"); + if (entry->action_pressed == -1) + entry->action_pressed = gg_signal_register(entry->id, "action_pressed"); +} + +char *gg_entry_get_text(gg_entry_t *entry) +{ + return entry->text; +} + +int gg_entry_set_text(gg_entry_t *entry, char *text) +{ + if (strlen(text) > entry->max_len) + return 1; + + strcpy(entry->text, text); + entry->cursor_pos = 0; + return 0; +} + +void gg_entry_set_max_len(gg_entry_t *entry, int len) +{ + entry->max_len = len; +} + +/** @brief Creates a text entry widget. + * + * A text entry widget for a single line of text. + * + * @return The created widget. + */ +gg_widget_t *gg_entry_create(int width) +{ + gg_entry_t *entry = malloc(sizeof(gg_entry_t)); + + gg_entry_init(entry, width); + + return GG_WIDGET(entry); +} diff --git a/pool/shard002/C/0056673_trace_dynevent.c b/pool/shard002/C/0056673_trace_dynevent.c new file mode 100644 index 0000000000000000000000000000000000000000..dd1f43588d7097a62a84966d8a90b425fd0f2f64 --- /dev/null +++ b/pool/shard002/C/0056673_trace_dynevent.c @@ -0,0 +1,217 @@ +// SPDX-License-Identifier: GPL-2.0 +/* + * Generic dynamic event control interface + * + * Copyright (C) 2018 Masami Hiramatsu + */ + +#include +#include +#include +#include +#include +#include + +#include "trace.h" +#include "trace_dynevent.h" + +static DEFINE_MUTEX(dyn_event_ops_mutex); +static LIST_HEAD(dyn_event_ops_list); + +int dyn_event_register(struct dyn_event_operations *ops) +{ + if (!ops || !ops->create || !ops->show || !ops->is_busy || + !ops->free || !ops->match) + return -EINVAL; + + INIT_LIST_HEAD(&ops->list); + mutex_lock(&dyn_event_ops_mutex); + list_add_tail(&ops->list, &dyn_event_ops_list); + mutex_unlock(&dyn_event_ops_mutex); + return 0; +} + +int dyn_event_release(int argc, char **argv, struct dyn_event_operations *type) +{ + struct dyn_event *pos, *n; + char *system = NULL, *event, *p; + int ret = -ENOENT; + + if (argv[0][0] == '-') { + if (argv[0][1] != ':') + return -EINVAL; + event = &argv[0][2]; + } else { + event = strchr(argv[0], ':'); + if (!event) + return -EINVAL; + event++; + } + + p = strchr(event, '/'); + if (p) { + system = event; + event = p + 1; + *p = '\0'; + } + if (event[0] == '\0') + return -EINVAL; + + mutex_lock(&event_mutex); + for_each_dyn_event_safe(pos, n) { + if (type && type != pos->ops) + continue; + if (pos->ops->match(system, event, pos)) { + ret = pos->ops->free(pos); + break; + } + } + mutex_unlock(&event_mutex); + + return ret; +} + +static int create_dyn_event(int argc, char **argv) +{ + struct dyn_event_operations *ops; + int ret; + + if (argv[0][0] == '-' || argv[0][0] == '!') + return dyn_event_release(argc, argv, NULL); + + mutex_lock(&dyn_event_ops_mutex); + list_for_each_entry(ops, &dyn_event_ops_list, list) { + ret = ops->create(argc, (const char **)argv); + if (!ret || ret != -ECANCELED) + break; + } + mutex_unlock(&dyn_event_ops_mutex); + if (ret == -ECANCELED) + ret = -EINVAL; + + return ret; +} + +/* Protected by event_mutex */ +LIST_HEAD(dyn_event_list); + +void *dyn_event_seq_start(struct seq_file *m, loff_t *pos) +{ + mutex_lock(&event_mutex); + return seq_list_start(&dyn_event_list, *pos); +} + +void *dyn_event_seq_next(struct seq_file *m, void *v, loff_t *pos) +{ + return seq_list_next(v, &dyn_event_list, pos); +} + +void dyn_event_seq_stop(struct seq_file *m, void *v) +{ + mutex_unlock(&event_mutex); +} + +static int dyn_event_seq_show(struct seq_file *m, void *v) +{ + struct dyn_event *ev = v; + + if (ev && ev->ops) + return ev->ops->show(m, ev); + + return 0; +} + +static const struct seq_operations dyn_event_seq_op = { + .start = dyn_event_seq_start, + .next = dyn_event_seq_next, + .stop = dyn_event_seq_stop, + .show = dyn_event_seq_show +}; + +/* + * dyn_events_release_all - Release all specific events + * @type: the dyn_event_operations * which filters releasing events + * + * This releases all events which ->ops matches @type. If @type is NULL, + * all events are released. + * Return -EBUSY if any of them are in use, and return other errors when + * it failed to free the given event. Except for -EBUSY, event releasing + * process will be aborted at that point and there may be some other + * releasable events on the list. + */ +int dyn_events_release_all(struct dyn_event_operations *type) +{ + struct dyn_event *ev, *tmp; + int ret = 0; + + mutex_lock(&event_mutex); + for_each_dyn_event(ev) { + if (type && ev->ops != type) + continue; + if (ev->ops->is_busy(ev)) { + ret = -EBUSY; + goto out; + } + } + for_each_dyn_event_safe(ev, tmp) { + if (type && ev->ops != type) + continue; + ret = ev->ops->free(ev); + if (ret) + break; + } +out: + mutex_unlock(&event_mutex); + + return ret; +} + +static int dyn_event_open(struct inode *inode, struct file *file) +{ + int ret; + + if ((file->f_mode & FMODE_WRITE) && (file->f_flags & O_TRUNC)) { + ret = dyn_events_release_all(NULL); + if (ret < 0) + return ret; + } + + return seq_open(file, &dyn_event_seq_op); +} + +static ssize_t dyn_event_write(struct file *file, const char __user *buffer, + size_t count, loff_t *ppos) +{ + return trace_parse_run_command(file, buffer, count, ppos, + create_dyn_event); +} + +static const struct file_operations dynamic_events_ops = { + .owner = THIS_MODULE, + .open = dyn_event_open, + .read = seq_read, + .llseek = seq_lseek, + .release = seq_release, + .write = dyn_event_write, +}; + +/* Make a tracefs interface for controlling dynamic events */ +static __init int init_dynamic_event(void) +{ + struct dentry *d_tracer; + struct dentry *entry; + + d_tracer = tracing_init_dentry(); + if (IS_ERR(d_tracer)) + return 0; + + entry = tracefs_create_file("dynamic_events", 0644, d_tracer, + NULL, &dynamic_events_ops); + + /* Event list interface */ + if (!entry) + pr_warn("Could not create tracefs 'dynamic_events' entry\n"); + + return 0; +} +fs_initcall(init_dynamic_event); diff --git a/pool/shard002/C/0056690_Buff_ChuangXin.c b/pool/shard002/C/0056690_Buff_ChuangXin.c new file mode 100644 index 0000000000000000000000000000000000000000..c3183a5a775f128b217cfb6ccf15c447415f8530 --- /dev/null +++ b/pool/shard002/C/0056690_Buff_ChuangXin.c @@ -0,0 +1,75 @@ +#include "../Buff_private.h" + +#include "../BuffList.h" + +//======================================================================= +// 眩晕 +//======================================================================= +void ChuangXinA_Buff_Start(struct Buff* self, struct BuffList* list); +void ChuangXinA_Buff_Stop(struct Buff* self, struct BuffList* list); + +const char ChuangXinA_startStr[] = ("%s头昏脑涨,已不辨东西南北。"); +const char ChuangXinA_stopStr[] = ("%s头脑逐渐清醒了过来。"); + +struct Buff ChuangXinAInfo = +{ + ChuangXinA_ID, + BUFF_TYPE_TIME, + 10.0, + ChuangXinA_Buff_Start, + ChuangXinA_Buff_Stop, + ChuangXinA_startStr, + ChuangXinA_stopStr +}; + +void ChuangXinA_Buff_Start(struct Buff* self, struct BuffList* list) +{ + list->current->dizzy |= 3; + BuffList_waitTurn(list); +} + +void ChuangXinA_Buff_Stop(struct Buff* self, struct BuffList* list) +{ + list->current->dizzy &= ~1; +} + +struct Buff* ChuangXinABuff_Get(unsigned int level) +{ + return &ChuangXinAInfo; +} + +//======================================================================= +// 加闪 +//======================================================================= +void ChuangXinB_Buff_Start(struct Buff* self, struct BuffList* list); +void ChuangXinB_Buff_Stop(struct Buff* self, struct BuffList* list); + +const char ChuangXinB_startStr[] = ("%s的速度提高了"); +const char ChuangXinB_stopStr[] = ("%s的速度恢复了正常。"); + +struct Buff ChuangXinBInfo = +{ + ChuangXinB_ID, + BUFF_TYPE_TURN, + 1.0, + ChuangXinB_Buff_Start, + ChuangXinB_Buff_Stop, + ChuangXinB_startStr, + ChuangXinB_stopStr +}; + +void ChuangXinB_Buff_Start(struct Buff* self, struct BuffList* list) +{ + list->current->attribSB += self->data_1; +} + +void ChuangXinB_Buff_Stop(struct Buff* self, struct BuffList* list) +{ + list->current->attribSB -= self->data_1; +} + +struct Buff* ChuangXinBBuff_Get(unsigned int level) +{ + ChuangXinBInfo.data_1 = level; + return &ChuangXinBInfo; +} diff --git a/pool/shard002/C/0056693_llrtopij.c b/pool/shard002/C/0056693_llrtopij.c new file mode 100644 index 0000000000000000000000000000000000000000..f62eadb0fb8217cae99d9d7c2351b93b8e829e8f --- /dev/null +++ b/pool/shard002/C/0056693_llrtopij.c @@ -0,0 +1,129 @@ +/* Copyright 2016-2018, 2020 Lingfei Wang + * + * This file is part of Findr. + * + * Findr is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Findr 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 Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with Findr. If not, see . + */ +#include "../../base/config.h" +#include +#include +#include +#include "../../base/logger.h" +#include "llrtopij.h" +#include "../llrtopij.h" + + + + + + +/* Always return probability of step 1 is 1. This is useful when best eQTL are already selected in advance. + */ +static inline int pij_cassist_llrtopij1_1(VECTORF* p1) +{ + LOG(9,"Converting LLR to probabilities for step 1. Filling with 1.") + VECTORFF(set_all)(p1,1); + return 0; +} + +/* Functions to convert LLR of specific steps into probabilities. + * Uses pij_llrtopij_convert with different settings of n1d and n2d. + * Function name suffices indicate which LLR to convert. + */ +static inline int pij_cassist_llrtopij1(VECTORF* d) +{ + LOG(9,"Converting LLR to probabilities for step 1 on per A basis.") + return pij_cassist_llrtopij1_1(d); +} + +static inline int pij_cassist_llrtopij2(MATRIXF* d,size_t ns,char nodiag) +{ + LOG(9,"Converting LLR to probabilities for step 2 on per A basis.") + assert(ns>2); + return pij_llrtopij_convert_single_self(d,1,ns-2,nodiag,0); +} + +static inline int pij_cassist_llrtopij3(MATRIXF* d,size_t ns,char nodiag) +{ + LOG(9,"Converting LLR to probabilities for step 3 on per A basis.") + assert(ns>3); + if(pij_llrtopij_convert_single_self(d,1,ns-3,nodiag,0)) + return 1; + MATRIXFF(scale)(d,-1); + MATRIXFF(add_constant)(d,1); + return 0; +} + +static inline int pij_cassist_llrtopij4(MATRIXF* d,size_t ns,char nodiag) +{ + LOG(9,"Converting LLR to probabilities for step 4 on per A basis.") + assert(ns>3); + return pij_llrtopij_convert_single_self(d,2,ns-3,nodiag,0); +} + +static inline int pij_cassist_llrtopij5(MATRIXF* d,size_t ns,char nodiag) +{ + LOG(9,"Converting LLR to probabilities for step 5 on per A basis.") + assert(ns>3); + return pij_llrtopij_convert_single_self(d,1,ns-3,nodiag,0); +} + + +int pij_cassist_llrtopijs(VECTORF* p1,MATRIXF* p2,MATRIXF* p3,MATRIXF* p4,MATRIXF* p5,size_t ns,char nodiag) +{ + int ret=0,ret2=0; + + if(ns<4) + { + LOG(0,"Cannot convert log likelihood ratios to probabilities. Needs at least 4 samples.") + return 1; + } + ret=ret||(ret2=pij_cassist_llrtopij2(p2,ns,nodiag)); + if(ret2) + LOG(1,"Failed to convert log likelihood ratios to probabilities in step 2.") + //For p1, if nodiag, copy p2 data, otherwise set all to 1. + if(nodiag) + { + VECTORFF(view) vv; + vv=MATRIXFF(diagonal)(p2); + ret=ret||(ret2=VECTORFF(memcpy)(p1,&vv.vector)); + } + else + ret=ret||(ret2=pij_cassist_llrtopij1_1(p1)); + if(ret2) + LOG(1,"Failed to convert log likelihood ratios to probabilities in step 1.") + ret=ret||(ret2=pij_cassist_llrtopij3(p3,ns,nodiag)); + if(ret2) + LOG(1,"Failed to convert log likelihood ratios to probabilities in step 3.") + ret=ret||(ret2=pij_cassist_llrtopij4(p4,ns,nodiag)); + if(ret2) + LOG(1,"Failed to convert log likelihood ratios to probabilities in step 4.") + ret=ret||(ret2=pij_cassist_llrtopij5(p5,ns,nodiag)); + if(ret2) + LOG(1,"Failed to convert log likelihood ratios to probabilities in step 5.") + return ret; +} + + + + + + + + + + + + + diff --git a/pool/shard002/C/0056710_sock_qos_wm.c b/pool/shard002/C/0056710_sock_qos_wm.c new file mode 100644 index 0000000000000000000000000000000000000000..46eb3e251186cb1417c2475ec26b9e61f3a54623 --- /dev/null +++ b/pool/shard002/C/0056710_sock_qos_wm.c @@ -0,0 +1,103 @@ +/* $Id$ */ +/* + * Copyright (C) 2009-2011 Teluu Inc. (http://www.teluu.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 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 + +/* QoS implementation for Windows Mobile 6, must be enabled explicitly + * (this is controlled by pjlib's config.h) + */ +#if defined(PJ_QOS_IMPLEMENTATION) && PJ_QOS_IMPLEMENTATION==PJ_QOS_WM + +#define THIS_FILE "sock_qos_wm.c" + +/* Mapping between our traffic type and WM's DSCP traffic types */ +static const int dscp_map[] = +{ + DSCPBestEffort, + DSCPBackground, + DSCPVideo, + DSCPAudio, + DSCPControl +}; + +PJ_DEF(pj_status_t) pj_sock_set_qos_params(pj_sock_t sock, + pj_qos_params *param) +{ + PJ_UNUSED_ARG(sock); + PJ_UNUSED_ARG(param); + + PJ_LOG(4,(THIS_FILE, "pj_sock_set_qos_params() is not implemented " + "for this platform")); + return PJ_ENOTSUP; +} + +PJ_DEF(pj_status_t) pj_sock_set_qos_type(pj_sock_t sock, + pj_qos_type type) +{ + int value; + + PJ_ASSERT_RETURN(type < PJ_ARRAY_SIZE(dscp_map), PJ_EINVAL); + + value = dscp_map[type]; + return pj_sock_setsockopt(sock, IPPROTO_IP, IP_DSCP_TRAFFIC_TYPE, + &value, sizeof(value)); +} + + +PJ_DEF(pj_status_t) pj_sock_get_qos_params(pj_sock_t sock, + pj_qos_params *p_param) +{ + PJ_UNUSED_ARG(sock); + PJ_UNUSED_ARG(p_param); + + PJ_LOG(4,(THIS_FILE, "pj_sock_get_qos_params() is not implemented " + "for this platform")); + return PJ_ENOTSUP; +} + +PJ_DEF(pj_status_t) pj_sock_get_qos_type(pj_sock_t sock, + pj_qos_type *p_type) +{ + pj_status_t status; + int value, optlen; + unsigned i; + + optlen = sizeof(value); + value = 0; + status = pj_sock_getsockopt(sock, IPPROTO_IP, IP_DSCP_TRAFFIC_TYPE, + &value, &optlen); + if (status != PJ_SUCCESS) + return status; + + *p_type = PJ_QOS_TYPE_BEST_EFFORT; + for (i=0; i. +*/ + +#ifdef T + +#include "templates.h" + +void +TEMPLATE(T, poly_sub_series) (TEMPLATE(T, poly_t) res, + const TEMPLATE(T, poly_t) poly1, + const TEMPLATE(T, poly_t) poly2, + slong n, const TEMPLATE(T, ctx_t) ctx) +{ + slong len1, len2, max = FLINT_MAX(poly1->length, poly2->length); + + if (n < 0) + n = 0; + + max = FLINT_MIN(max, n); + len1 = FLINT_MIN(poly1->length, max); + len2 = FLINT_MIN(poly2->length, max); + + TEMPLATE(T, poly_fit_length) (res, max, ctx); + + _TEMPLATE(T, poly_sub) (res->coeffs, poly1->coeffs, len1, + poly2->coeffs, len2, ctx); + + _TEMPLATE(T, poly_set_length) (res, max, ctx); + _TEMPLATE(T, poly_normalise) (res, ctx); +} + + +#endif diff --git a/pool/shard002/C/0056725_debug_log.c b/pool/shard002/C/0056725_debug_log.c new file mode 100644 index 0000000000000000000000000000000000000000..b2387ba58abd7e780f98951363b078e761b41b19 --- /dev/null +++ b/pool/shard002/C/0056725_debug_log.c @@ -0,0 +1,37 @@ +#include "debug_log.h" + +#include +#include + +const char *g_logLevelToName[] = { + "NONE", + "CRITICAL", + "ERROR", + "WARNING", + "INFO", + "DEBUG" +}; + +const char *g_logTypeToName[] = { + "NETFLOW", + "PARSE", + "IO", + "CONF" +}; + +void snflog(SNFConfig *conf, SNFLogType type, SNFLogLevel level, + const char *fmt, ...) { + va_list args; + + if (would_log(conf, type, level)) { + /* example: WARNING.parsing: some error */ + puts(g_logLevelToName[level]); + putchar('.'); + puts(g_logTypeToName[type]); + puts(": "); + va_start(args, fmt); + vprintf(fmt, args); + va_end(args); + putchar('\n'); + } +} diff --git a/pool/shard002/C/0056726_res_text.c b/pool/shard002/C/0056726_res_text.c new file mode 100644 index 0000000000000000000000000000000000000000..643b4c9f2f92095915f5a2359ce0e09c322ff902 --- /dev/null +++ b/pool/shard002/C/0056726_res_text.c @@ -0,0 +1,147 @@ +#include "fitz-internal.h" + +fz_text * +fz_new_text(fz_context *ctx, fz_font *font, fz_matrix trm, int wmode) +{ + fz_text *text; + + text = fz_malloc_struct(ctx, fz_text); + text->font = fz_keep_font(ctx, font); + text->trm = trm; + text->wmode = wmode; + text->len = 0; + text->cap = 0; + text->items = NULL; + + return text; +} + +void +fz_free_text(fz_context *ctx, fz_text *text) +{ + if (text != NULL) + { + fz_drop_font(ctx, text->font); + fz_free(ctx, text->items); + } + fz_free(ctx, text); +} + +fz_text * +fz_clone_text(fz_context *ctx, fz_text *old) +{ + fz_text *text; + + text = fz_malloc_struct(ctx, fz_text); + text->len = old->len; + fz_try(ctx) + { + text->items = fz_malloc_array(ctx, text->len, sizeof(fz_text_item)); + } + fz_catch(ctx) + { + fz_free(ctx, text); + fz_rethrow(ctx); + } + memcpy(text->items, old->items, text->len * sizeof(fz_text_item)); + text->font = fz_keep_font(ctx, old->font); + text->trm = old->trm; + text->wmode = old->wmode; + text->cap = text->len; + + return text; +} + +fz_rect +fz_bound_text(fz_context *ctx, fz_text *text, fz_matrix ctm) +{ + fz_matrix tm, trm; + fz_rect bbox; + fz_rect gbox; + int i; + + if (text->len == 0) + return fz_empty_rect; + + // TODO: stroke state + + tm = text->trm; + + tm.e = text->items[0].x; + tm.f = text->items[0].y; + trm = fz_concat(tm, ctm); + bbox = fz_bound_glyph(ctx, text->font, text->items[0].gid, trm); + + for (i = 1; i < text->len; i++) + { + if (text->items[i].gid >= 0) + { + tm.e = text->items[i].x; + tm.f = text->items[i].y; + trm = fz_concat(tm, ctm); + gbox = fz_bound_glyph(ctx, text->font, text->items[i].gid, trm); + + bbox.x0 = MIN(bbox.x0, gbox.x0); + bbox.y0 = MIN(bbox.y0, gbox.y0); + bbox.x1 = MAX(bbox.x1, gbox.x1); + bbox.y1 = MAX(bbox.y1, gbox.y1); + } + } + + /* Compensate for the glyph cache limited positioning precision */ + bbox.x0 -= 1; + bbox.y0 -= 1; + bbox.x1 += 1; + bbox.y1 += 1; + + return bbox; +} + +static void +fz_grow_text(fz_context *ctx, fz_text *text, int n) +{ + if (text->len + n < text->cap) + return; + while (text->len + n > text->cap) + text->cap = text->cap + 36; + text->items = fz_resize_array(ctx, text->items, text->cap, sizeof(fz_text_item)); +} + +void +fz_add_text(fz_context *ctx, fz_text *text, int gid, int ucs, float x, float y) +{ + fz_grow_text(ctx, text, 1); + text->items[text->len].ucs = ucs; + text->items[text->len].gid = gid; + text->items[text->len].x = x; + text->items[text->len].y = y; + text->len++; +} + +static int +isxmlmeta(int c) +{ + return c < 32 || c >= 128 || c == '&' || c == '<' || c == '>' || c == '\'' || c == '"'; +} + +static void +do_print_text(FILE *out, fz_text *text, int indent) +{ + int i, n; + for (i = 0; i < text->len; i++) + { + for (n = 0; n < indent; n++) + fputc(' ', out); + if (!isxmlmeta(text->items[i].ucs)) + fprintf(out, "\n", + text->items[i].ucs, text->items[i].gid, text->items[i].x, text->items[i].y); + else + fprintf(out, "\n", + text->items[i].ucs, text->items[i].gid, text->items[i].x, text->items[i].y); + } +} + +void fz_print_text(fz_context *ctx, FILE *out, fz_text *text) +{ + do_print_text(out, text, 0); +} diff --git a/pool/shard002/C/0056737_professor.c b/pool/shard002/C/0056737_professor.c new file mode 100644 index 0000000000000000000000000000000000000000..bba28476b44cb65ba99ba228aff8108cfe9ea20f --- /dev/null +++ b/pool/shard002/C/0056737_professor.c @@ -0,0 +1,118 @@ +/* + * Copyright (c) 2015 Kaprica Security, 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 + * 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 "professor.h" +#include "ptrlist.h" + +#include + +ptrlist_t *g_all_profs = NULL; + +void add_professor(professor_t *prof) +{ + if (!prof) + return; + + if (!g_all_profs) + g_all_profs = create_ptrlist(); + + add_item(g_all_profs, prof); +} + +professor_t *create_professor(char *name) +{ + if (!name) + return NULL; + + professor_t *prof = malloc(sizeof(professor_t)); + if (!prof) + return NULL; + + prof->name = strdup(name); + prof->courses_taught = create_ptrlist(); + add_professor(prof); + + return prof; +} + +void add_course_to_professor(professor_t *prof, course_t *course) +{ + if (!prof || !course) + return; + + add_item(prof->courses_taught, course); +} + +professor_t *get_professor(char *name) +{ + if (!name || !g_all_profs) + return NULL; + + int i = 0; + professor_t *iter; + for (i = 0; i < g_all_profs->length; i++) { + iter = get_item(professor_t, g_all_profs, i); + if (strcasecmp(iter->name, name) == 0) + return iter; + } + + return NULL; +} + +course_t *get_professor_class(professor_t *prof, size_t idx) +{ + if (!prof) + return NULL; + + return get_item(course_t, prof->courses_taught, idx); +} + +void list_professors() +{ + if (!g_all_profs) + return; + + int i = 0; + professor_t *iter; + printf("--All Professors--\n"); + for (i = 0; i < g_all_profs->length; i++) { + iter = get_item(professor_t, g_all_profs, i); + printf("%s\n", iter->name); + } +} + +void list_classes_taught(professor_t *prof) +{ + if (!prof) + return; + + int i = 0; + course_t *iter; + printf("--%s's Classes--\n", prof->name); + print_course_banner(); + for (i = 0; i < prof->courses_taught->length; i++) { + printf("#%d|", i+1); + iter = get_item(course_t, prof->courses_taught, i); + iter->print_course(iter); //brief? + } +} + diff --git a/pool/shard002/C/0056738_asinh.c b/pool/shard002/C/0056738_asinh.c new file mode 100644 index 0000000000000000000000000000000000000000..a1270460387b35d0825187b82586d5c20fd70e90 --- /dev/null +++ b/pool/shard002/C/0056738_asinh.c @@ -0,0 +1,48 @@ +/* Copyright (c) 2002-2003 krzYszcz and others. + * For information on usage and redistribution, and for a DISCLAIMER OF ALL + * WARRANTIES, see the file, "LICENSE.txt," in this distribution. */ + +#include +#include "m_pd.h" +#include "sic.h" + +/* LATER ask about osx */ +#if defined(NT) || defined(MACOSX) +#define asinhf(x) (log(x + sqrt(x * x + 1))) +#endif + +typedef t_sic t_asinh; +static t_class *asinh_class; + +static t_int *asinh_perform(t_int *w) +{ + int nblock = (int)(w[1]); + t_float *in = (t_float *)(w[2]); + t_float *out = (t_float *)(w[3]); + while (nblock--) + { + float f = *in++; + *out++ = asinhf(f); /* CHECKME no protection against NaNs */ + } + return (w + 4); +} + +static void asinh_dsp(t_asinh *x, t_signal **sp) +{ + dsp_add(asinh_perform, 3, sp[0]->s_n, sp[0]->s_vec, sp[1]->s_vec); +} + +static void *asinh_new(void) +{ + t_asinh *x = (t_asinh *)pd_new(asinh_class); + outlet_new((t_object *)x, &s_signal); + return (x); +} + +void asinh_tilde_setup(void) +{ + asinh_class = class_new(gensym("asinh~"), + (t_newmethod)asinh_new, 0, + sizeof(t_asinh), 0, 0); + sic_setup(asinh_class, asinh_dsp, SIC_FLOATTOSIGNAL); +} diff --git a/pool/shard002/C/0056745_tst-sem6.c b/pool/shard002/C/0056745_tst-sem6.c new file mode 100644 index 0000000000000000000000000000000000000000..75fc5871cc084180975954ce6cdb661a92fff658 --- /dev/null +++ b/pool/shard002/C/0056745_tst-sem6.c @@ -0,0 +1,80 @@ +/* Copyright (C) 2003-2013 Free Software Foundation, Inc. + This file is part of the GNU C Library. + Contributed by Ulrich Drepper , 2003. + + 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 + + +static void +handler (int sig) +{ + struct sigaction sa; + + sa.sa_handler = SIG_DFL; + sa.sa_flags = 0; + sigemptyset (&sa.sa_mask); + + sigaction (SIGALRM, &sa, NULL); + + /* Rearm the timer. */ + alarm (1); +} + + +static int +do_test (void) +{ + sem_t s; + struct sigaction sa; + + sa.sa_handler = handler; + sa.sa_flags = 0; + sigemptyset (&sa.sa_mask); + + sigaction (SIGALRM, &sa, NULL); + + if (sem_init (&s, 0, 0) == -1) + { + puts ("init failed"); + return 1; + } + + /* Set an alarm for 1 second. The wrapper will expect this. */ + alarm (1); + + int res = sem_wait (&s); + if (res == 0) + { + puts ("wait succeeded"); + return 1; + } + if (res != -1 || errno != EINTR) + { + puts ("wait didn't fail with EINTR"); + return 1; + } + + return 0; +} + +#define TIMEOUT 3 +#define TEST_FUNCTION do_test () +#include "../test-skeleton.c" diff --git a/pool/shard002/C/0056750_uart.c b/pool/shard002/C/0056750_uart.c new file mode 100644 index 0000000000000000000000000000000000000000..d75a3d4e9f4b18d9d67b40f0c0cdb63c128ce48b --- /dev/null +++ b/pool/shard002/C/0056750_uart.c @@ -0,0 +1,194 @@ +/* + * Copyright (C) 2015 Freie Universität Berlin + * 2015 FreshTemp, LLC. + * + * 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 cpu_sam0_common + * @ingroup drivers_periph_uart + * @{ + * + * @file + * @brief Low-level UART driver implementation + * + * @author Thomas Eichinger + * @author Troels Hoffmeyer + * @author Hauke Petersen + * @author Dylan Laduranty + * + * @} + */ + +#include "cpu.h" + +#include "periph/uart.h" +#include "periph/gpio.h" + +#define ENABLE_DEBUG (0) +#include "debug.h" + +/** + * @brief Allocate memory to store the callback functions + */ +static uart_isr_ctx_t uart_ctx[UART_NUMOF]; + +/** + * @brief Get the pointer to the base register of the given UART device + * + * @param[in] dev UART device identifier + * + * @return base register address + */ +static inline SercomUsart *dev(uart_t dev) +{ + return uart_config[dev].dev; +} + +int uart_init(uart_t uart, uint32_t baudrate, uart_rx_cb_t rx_cb, void *arg) +{ + if (uart >= UART_NUMOF) { + return UART_NODEV; + } + + /* must disable here first to ensure idempotency */ + dev(uart)->CTRLA.reg &= ~(SERCOM_USART_CTRLA_ENABLE); + + /* configure pins */ + if (uart_config[uart].rx_pin != GPIO_UNDEF) { + gpio_init(uart_config[uart].rx_pin, GPIO_IN); + gpio_init_mux(uart_config[uart].rx_pin, uart_config[uart].mux); + } + gpio_init(uart_config[uart].tx_pin, GPIO_OUT); + gpio_set(uart_config[uart].tx_pin); + gpio_init_mux(uart_config[uart].tx_pin, uart_config[uart].mux); + + /* enable peripheral clock */ + sercom_clk_en(dev(uart)); + + /* reset the UART device */ + dev(uart)->CTRLA.reg = SERCOM_USART_CTRLA_SWRST; + while (dev(uart)->SYNCBUSY.bit.SWRST) {} + + /* configure clock generator */ + sercom_set_gen(dev(uart), uart_config[uart].gclk_src); + + /* set asynchronous mode w/o parity, LSB first, TX and RX pad as specified + * by the board in the periph_conf.h, x16 sampling and use internal clock */ + dev(uart)->CTRLA.reg = (SERCOM_USART_CTRLA_DORD | + SERCOM_USART_CTRLA_SAMPR(0x1) | + SERCOM_USART_CTRLA_TXPO(uart_config[uart].tx_pad) | + SERCOM_USART_CTRLA_RXPO(uart_config[uart].rx_pad) | + SERCOM_USART_CTRLA_MODE(0x1)); + /* Set run in standby mode if enabled */ + if (uart_config[uart].flags & UART_FLAG_RUN_STANDBY) { + dev(uart)->CTRLA.reg |= SERCOM_USART_CTRLA_RUNSTDBY; + } + + /* calculate and set baudrate */ + uint32_t baud = ((((uint32_t)CLOCK_CORECLOCK * 10) / baudrate) / 16); + dev(uart)->BAUD.FRAC.FP = (baud % 10); + dev(uart)->BAUD.FRAC.BAUD = (baud / 10); + + /* enable transmitter, and configure 8N1 mode */ + dev(uart)->CTRLB.reg = SERCOM_USART_CTRLB_TXEN; + /* enable receiver and RX interrupt if configured */ + if ((rx_cb) && (uart_config[uart].rx_pin != GPIO_UNDEF)) { + uart_ctx[uart].rx_cb = rx_cb; + uart_ctx[uart].arg = arg; + NVIC_EnableIRQ(SERCOM0_IRQn + sercom_id(dev(uart))); + dev(uart)->CTRLB.reg |= SERCOM_USART_CTRLB_RXEN; + dev(uart)->INTENSET.reg |= SERCOM_USART_INTENSET_RXC; + /* set wakeup receive from sleep if enabled */ + if (uart_config[uart].flags & UART_FLAG_WAKEUP) { + dev(uart)->CTRLB.reg |= SERCOM_USART_CTRLB_SFDE; + } + } + while (dev(uart)->SYNCBUSY.bit.CTRLB) {} + + /* and finally enable the device */ + dev(uart)->CTRLA.reg |= SERCOM_USART_CTRLA_ENABLE; + + return UART_OK; +} + +void uart_write(uart_t uart, const uint8_t *data, size_t len) +{ + for (size_t i = 0; i < len; i++) { + while (!dev(uart)->INTFLAG.bit.DRE) {} + dev(uart)->DATA.reg = data[i]; + } + while (!dev(uart)->INTFLAG.bit.TXC) {} +} + +void uart_poweron(uart_t uart) +{ + sercom_clk_en(dev(uart)); + dev(uart)->CTRLA.reg |= SERCOM_USART_CTRLA_ENABLE; +} + +void uart_poweroff(uart_t uart) +{ + dev(uart)->CTRLA.reg &= ~(SERCOM_USART_CTRLA_ENABLE); + sercom_clk_dis(dev(uart)); +} + +static inline void irq_handler(unsigned uartnum) +{ + if (dev(uartnum)->INTFLAG.bit.RXC) { + /* interrupt flag is cleared by reading the data register */ + uart_ctx[uartnum].rx_cb(uart_ctx[uartnum].arg, + (uint8_t)(dev(uartnum)->DATA.reg)); + } + else if (dev(uartnum)->INTFLAG.bit.ERROR) { + /* clear error flag */ + dev(uartnum)->INTFLAG.reg = SERCOM_USART_INTFLAG_ERROR; + } + + cortexm_isr_end(); +} + +#ifdef UART_0_ISR +void UART_0_ISR(void) +{ + irq_handler(0); +} +#endif + +#ifdef UART_1_ISR +void UART_1_ISR(void) +{ + irq_handler(1); +} +#endif + +#ifdef UART_2_ISR +void UART_2_ISR(void) +{ + irq_handler(2); +} +#endif + +#ifdef UART_3_ISR +void UART_3_ISR(void) +{ + irq_handler(3); +} +#endif + +#ifdef UART_4_ISR +void UART_4_ISR(void) +{ + irq_handler(4); +} +#endif + +#ifdef UART_5_ISR +void UART_5_ISR(void) +{ + irq_handler(5); +} +#endif diff --git a/pool/shard002/C/0056759_main.c b/pool/shard002/C/0056759_main.c new file mode 100644 index 0000000000000000000000000000000000000000..9b94a3ee8a85ed38f6f810466a154ab3b4dc4830 --- /dev/null +++ b/pool/shard002/C/0056759_main.c @@ -0,0 +1,135 @@ +#include + +#include "thread.h" +#include "board.h" +#include "cpu.h" +#include "posix_io.h" +#include "shell.h" +#include "shell_commands.h" +#include "board_uart0.h" +#include "transceiver.h" + +#include "dino.h" + +#define MSEC (1000) +#define SEC (1000 * MSEC) + +#define RCV_BUFFER_SIZE (64) +#define RADIO_STACK_SIZE (KERNEL_CONF_STACKSIZE_DEFAULT) + +char radio_stack_buffer[RADIO_STACK_SIZE]; +msg_t msg_q[RCV_BUFFER_SIZE]; + + +static void start_motor(int argc, char **argv) +{ + (void) argc; + (void) argv; + printf("[START DINO]\n"); + DINO_PIN_ON; +} + +static void stop_motor(int argc, char **argv) +{ + (void) argc; + (void) argv; + printf("[STOP DINO]\n"); + DINO_PIN_OFF; +} + +static const shell_command_t shell_commands[] = { + { "start", "starts the motor", start_motor}, + { "end", "stops the motor", stop_motor}, + { NULL, NULL, NULL } +}; + +static int shell_readc(void) +{ + char c; + int result = posix_read(uart0_handler_pid, &c, 1); + if (result != 1) { + return -1; + } + return (unsigned char) c; +} + +static void shell_putchar(int c) +{ + putchar(c); +} + +void *radio(void *unused) +{ + msg_t m; + radio_packet_t *p; + radio_packet_length_t i; + + msg_init_queue(msg_q, RCV_BUFFER_SIZE); + + while (1) { + msg_receive(&m); + + if (m.type == PKT_PENDING) { + p = (radio_packet_t *) m.content.ptr; + printf("Got radio packet:\n"); + printf("\tLength:\t%u\n", p->length); + printf("\tSrc:\t%u\n", p->src); + printf("\tDst:\t%u\n", p->dst); + printf("\tLQI:\t%u\n", p->lqi); + printf("\tRSSI:\t%u\n", p->rssi); + + for (i = 0; i < p->length; i++) { + printf("%02X ", p->data[i]); + } + + DINO_PIN_TOGGLE; + + p->processing--; + puts("\n"); + } + else if (m.type == ENOBUFFER) { + puts("Transceiver buffer full"); + } + else { + puts("Unknown packet received"); + } + } +} + +void init_transceiver(void) +{ + int radio_pid = thread_create( + radio_stack_buffer, + RADIO_STACK_SIZE, + PRIORITY_MAIN - 2, + CREATE_STACKTEST, + radio, + NULL, + "radio"); + + uint16_t transceivers = TRANSCEIVER_DEFAULT; + + transceiver_init(transceivers); + (void) transceiver_start(); + transceiver_register(transceivers, radio_pid); +} + +int main(void) +{ + puts("Starting dino control"); + + DINO_PIN_INIT; + + DINO_PIN_OFF; + + init_transceiver(); + shell_t shell; + (void) posix_open(uart0_handler_pid, 0); + + (void) puts("Welcome to RIOT!"); + + shell_init(&shell, shell_commands, UART0_BUFSIZE, shell_readc, shell_putchar); + + shell_run(&shell); + return 0; +} diff --git a/pool/shard002/C/0056762_imx-es9023.c b/pool/shard002/C/0056762_imx-es9023.c new file mode 100644 index 0000000000000000000000000000000000000000..9949b59f912cb9fddf687c397f9492dd83cb94e2 --- /dev/null +++ b/pool/shard002/C/0056762_imx-es9023.c @@ -0,0 +1,179 @@ +/* + * Copyright (C) 2015 Jasbir Matharu + * Copyright (C) 2008-2014 Freescale Semiconductor, Inc. All Rights Reserved. + * + * Basic I2S support for external es9023 DAC, this should work with other DACS. + * + * The code contained herein is licensed under the GNU General Public + * License. You may obtain a copy of the GNU General Public License + * Version 2 or later at the following locations: + * + * http://www.opensource.org/licenses/gpl-license.html + * http://www.gnu.org/copyleft/gpl.html + */ + +#include +#include +#include + +#include "imx-audmux.h" + +static int imx_audmux_config(int slave, int master) +{ + unsigned int ptcr, pdcr; + slave = slave - 1; + master = master - 1; + + ptcr = IMX_AUDMUX_V2_PTCR_SYN | + IMX_AUDMUX_V2_PTCR_TFSDIR | + IMX_AUDMUX_V2_PTCR_TFSEL(slave) | + IMX_AUDMUX_V2_PTCR_TCLKDIR | + IMX_AUDMUX_V2_PTCR_TCSEL(slave); + pdcr = IMX_AUDMUX_V2_PDCR_RXDSEL(slave); + imx_audmux_v2_configure_port(master, ptcr, pdcr); + + /* + * According to RM, RCLKDIR and SYN should not be changed at same time. + * So separate to two step for configuring this port. + */ + ptcr |= IMX_AUDMUX_V2_PTCR_RFSDIR | + IMX_AUDMUX_V2_PTCR_RFSEL(slave) | + IMX_AUDMUX_V2_PTCR_RCLKDIR | + IMX_AUDMUX_V2_PTCR_RCSEL(slave); + imx_audmux_v2_configure_port(master, ptcr, pdcr); + + ptcr = IMX_AUDMUX_V2_PTCR_SYN; + pdcr = IMX_AUDMUX_V2_PDCR_RXDSEL(master); + imx_audmux_v2_configure_port(slave, ptcr, pdcr); + + return 0; +} + +static int imx_es9023_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 *cpu_dai = rtd->cpu_dai; + int ret = 0; + + ret = snd_soc_dai_set_fmt(cpu_dai, SND_SOC_DAIFMT_I2S + | SND_SOC_DAIFMT_NB_NF | SND_SOC_DAIFMT_CBS_CFS); + if (ret) { + dev_err(cpu_dai->dev, "failed to set dai fmt\n"); + return ret; + } + + return ret; +} + +static struct snd_soc_ops imx_es9023_ops = { + .hw_params = imx_es9023_hw_params, +}; + +static struct snd_soc_dai_link imx_dai = { + .name = "imx-es9023", + .stream_name = "imx-es9023", + .codec_dai_name = "es9023-hifi", + .ops = &imx_es9023_ops, +}; + +static struct snd_soc_card snd_soc_card_imx_3stack = { + .name = "imx-audio-es9023", + .dai_link = &imx_dai, + .num_links = 1, +}; + +static int imx_es9023_probe(struct platform_device *pdev) +{ + struct snd_soc_card *card = &snd_soc_card_imx_3stack; + struct device_node *ssi_np, *np = pdev->dev.of_node; + struct platform_device *ssi_pdev; + struct device_node *codec_np; + int int_port, ext_port, ret; + + ret = of_property_read_u32(np, "mux-int-port", &int_port); + if (ret) { + dev_err(&pdev->dev, "mux-int-port missing or invalid\n"); + return ret; + } + + ret = of_property_read_u32(np, "mux-ext-port", &ext_port); + if (ret) { + dev_err(&pdev->dev, "mux-ext-port missing or invalid\n"); + return ret; + } + + imx_audmux_config(int_port, ext_port); + + ssi_np = of_parse_phandle(pdev->dev.of_node, "ssi-controller", 0); + if (!ssi_np) { + dev_err(&pdev->dev, "phandle missing or invalid\n"); + return -EINVAL; + } + + ssi_pdev = of_find_device_by_node(ssi_np); + if (!ssi_pdev) { + dev_err(&pdev->dev, "failed to find SSI platform device\n"); + ret = -EINVAL; + goto end; + } + + codec_np = of_parse_phandle(pdev->dev.of_node, "audio-codec", 0); + if (!codec_np) { + dev_err(&pdev->dev, "phandle missing or invalid\n"); + ret = -EINVAL; + goto end; + } + + card->dev = &pdev->dev; + card->dai_link->cpu_dai_name = dev_name(&ssi_pdev->dev); + card->dai_link->platform_of_node = ssi_np; + card->dai_link->codec_of_node = codec_np; + + platform_set_drvdata(pdev, card); + + ret = snd_soc_register_card(card); + if (ret) + dev_err(&pdev->dev, "Failed to register card: %d\n", ret); + +end: + if (ssi_np) + of_node_put(ssi_np); + if (codec_np) + of_node_put(codec_np); + + return ret; +} + +static int imx_es9023_remove(struct platform_device *pdev) +{ + struct snd_soc_card *card = &snd_soc_card_imx_3stack; + + snd_soc_unregister_card(card); + + return 0; +} + +static const struct of_device_id imx_es9023_dt_ids[] = { + { .compatible = "udoo,imx-audio-es9023", }, + { /* sentinel */ } +}; +MODULE_DEVICE_TABLE(of, imx_es9023_dt_ids); + +static struct platform_driver imx_es9023_driver = { + .driver = { + .name = "imx-es9023", + .owner = THIS_MODULE, + .pm = &snd_soc_pm_ops, + .of_match_table = imx_es9023_dt_ids, + }, + .probe = imx_es9023_probe, + .remove = imx_es9023_remove, +}; + +module_platform_driver(imx_es9023_driver); + +/* Module information */ +MODULE_DESCRIPTION("ALSA SoC i.MX for ES9023"); +MODULE_AUTHOR("Jasbir Matharu"); +MODULE_LICENSE("GPL"); +MODULE_ALIAS("platform:imx-es9023"); diff --git a/pool/shard002/C/0056788_testset.c b/pool/shard002/C/0056788_testset.c new file mode 100644 index 0000000000000000000000000000000000000000..256d85dd8c4769e34824c46951b4ca1b2df1607d --- /dev/null +++ b/pool/shard002/C/0056788_testset.c @@ -0,0 +1,110 @@ + + +#include "config.h" +#include "unittest.h" +#include "cstring.h" +#include "set.h" + + +static void reset_sets(set_t *a, set_t *b) +{ + cstring_t cs; + int i; + + set_clear(a); + set_clear(b); + + for (i = 0; i < 10; i++) { + cs = cstring_from_ll(i); + set_add(a, cs); + cstring_free(cs); + } + + for (i = 5; i < 20; i++) { + cs = cstring_from_ll(i); + set_add(b, cs); + cstring_free(cs); + } +} + + +static void test_union(set_t *set) +{ + cstring_t cs; + int i; + for (i = 0; i < 20; i++) { + cs = cstring_from_ll(i); + TEST_COND("set", set_has(set, cs)); + cstring_free(cs); + } +} + + +static void test_intersection(set_t *set) +{ + cstring_t cs; + int i; + for (i = 0; i < 20; i++) { + cs = cstring_from_ll(i); + if (i >= 5 && i < 10) { + TEST_COND("set", set_has(set, cs)); + } else { + TEST_COND("set", !set_has(set, cs)); + } + cstring_free(cs); + } +} + + +static void test_set(void) +{ + set_t *a, *b, *c, *d; + + a = set_create(); + b = set_create(); + + TEST_COND("set_is_empty", set_is_empty(a) == true); + TEST_COND("set_is_empty", set_is_empty(b) == true); + + reset_sets(a, b); + set_concat_union(a, b); + test_union(a); + + reset_sets(a, b); + set_concat_intersection(a, b); + test_intersection(a); + + reset_sets(a, b); + + c = set_union(a, b); + test_union(c); + set_destroy(c); + + c = set_intersection(a, b); + test_intersection(c); + + d = set_dup(c); + test_intersection(d); + + set_clear(d); + + TEST_COND("set_clear", set_is_empty(d) == true); + + set_destroy(d); + set_destroy(c); + set_destroy(a); + set_destroy(b); +} + + +int main(void) +{ + +#ifdef WIN32 + _CrtSetDbgFlag(_CrtSetDbgFlag(_CRTDBG_REPORT_FLAG) | _CRTDBG_LEAK_CHECK_DF); +#endif + + test_set(); + TEST_REPORT(); + return 0; +} diff --git a/pool/shard002/C/0056820_simplewrite.c b/pool/shard002/C/0056820_simplewrite.c new file mode 100644 index 0000000000000000000000000000000000000000..ce3b40578583580e1cc0e26e7964ec1867b17dac --- /dev/null +++ b/pool/shard002/C/0056820_simplewrite.c @@ -0,0 +1,19 @@ +#include + +int main() +{ + char* filename = "allcaps.txt"; + FILE* fp = fopen(filename, "w"); + char c = 'A'; + if(fp){ + while( c<='Z' ){ + fputc(c,fp); + c++; + } + fputc('\n',fp); + fclose(fp); + }else{ + printf("Opening %s failed\n", filename); + } + return 0; +} diff --git a/pool/shard002/C/0056825_meson_venc_cvbs.c b/pool/shard002/C/0056825_meson_venc_cvbs.c new file mode 100644 index 0000000000000000000000000000000000000000..9ab27aecfcf313b04d7158d6dc6de230b9a7b91c --- /dev/null +++ b/pool/shard002/C/0056825_meson_venc_cvbs.c @@ -0,0 +1,287 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +/* + * Copyright (C) 2016 BayLibre, SAS + * Author: Neil Armstrong + * Copyright (C) 2015 Amlogic, Inc. All rights reserved. + * Copyright (C) 2014 Endless Mobile + * + * Written by: + * Jasper St. Pierre + */ + +#include +#include + +#include +#include +#include +#include +#include + +#include "meson_registers.h" +#include "meson_vclk.h" +#include "meson_venc_cvbs.h" + +/* HHI VDAC Registers */ +#define HHI_VDAC_CNTL0 0x2F4 /* 0xbd offset in data sheet */ +#define HHI_VDAC_CNTL0_G12A 0x2EC /* 0xbd offset in data sheet */ +#define HHI_VDAC_CNTL1 0x2F8 /* 0xbe offset in data sheet */ +#define HHI_VDAC_CNTL1_G12A 0x2F0 /* 0xbe offset in data sheet */ + +struct meson_venc_cvbs { + struct drm_encoder encoder; + struct drm_connector connector; + struct meson_drm *priv; +}; +#define encoder_to_meson_venc_cvbs(x) \ + container_of(x, struct meson_venc_cvbs, encoder) + +#define connector_to_meson_venc_cvbs(x) \ + container_of(x, struct meson_venc_cvbs, connector) + +/* Supported Modes */ + +struct meson_cvbs_mode meson_cvbs_modes[MESON_CVBS_MODES_COUNT] = { + { /* PAL */ + .enci = &meson_cvbs_enci_pal, + .mode = { + DRM_MODE("720x576i", DRM_MODE_TYPE_DRIVER, 13500, + 720, 732, 795, 864, 0, 576, 580, 586, 625, 0, + DRM_MODE_FLAG_INTERLACE), + .vrefresh = 50, + .picture_aspect_ratio = HDMI_PICTURE_ASPECT_4_3, + }, + }, + { /* NTSC */ + .enci = &meson_cvbs_enci_ntsc, + .mode = { + DRM_MODE("720x480i", DRM_MODE_TYPE_DRIVER, 13500, + 720, 739, 801, 858, 0, 480, 488, 494, 525, 0, + DRM_MODE_FLAG_INTERLACE), + .vrefresh = 60, + .picture_aspect_ratio = HDMI_PICTURE_ASPECT_4_3, + }, + }, +}; + +/* Connector */ + +static void meson_cvbs_connector_destroy(struct drm_connector *connector) +{ + drm_connector_cleanup(connector); +} + +static enum drm_connector_status +meson_cvbs_connector_detect(struct drm_connector *connector, bool force) +{ + /* FIXME: Add load-detect or jack-detect if possible */ + return connector_status_connected; +} + +static int meson_cvbs_connector_get_modes(struct drm_connector *connector) +{ + struct drm_device *dev = connector->dev; + struct drm_display_mode *mode; + int i; + + for (i = 0; i < MESON_CVBS_MODES_COUNT; ++i) { + struct meson_cvbs_mode *meson_mode = &meson_cvbs_modes[i]; + + mode = drm_mode_duplicate(dev, &meson_mode->mode); + if (!mode) { + DRM_ERROR("Failed to create a new display mode\n"); + return 0; + } + + drm_mode_probed_add(connector, mode); + } + + return i; +} + +static int meson_cvbs_connector_mode_valid(struct drm_connector *connector, + struct drm_display_mode *mode) +{ + /* Validate the modes added in get_modes */ + return MODE_OK; +} + +static const struct drm_connector_funcs meson_cvbs_connector_funcs = { + .detect = meson_cvbs_connector_detect, + .fill_modes = drm_helper_probe_single_connector_modes, + .destroy = meson_cvbs_connector_destroy, + .reset = drm_atomic_helper_connector_reset, + .atomic_duplicate_state = drm_atomic_helper_connector_duplicate_state, + .atomic_destroy_state = drm_atomic_helper_connector_destroy_state, +}; + +static const +struct drm_connector_helper_funcs meson_cvbs_connector_helper_funcs = { + .get_modes = meson_cvbs_connector_get_modes, + .mode_valid = meson_cvbs_connector_mode_valid, +}; + +/* Encoder */ + +static void meson_venc_cvbs_encoder_destroy(struct drm_encoder *encoder) +{ + drm_encoder_cleanup(encoder); +} + +static const struct drm_encoder_funcs meson_venc_cvbs_encoder_funcs = { + .destroy = meson_venc_cvbs_encoder_destroy, +}; + +static int meson_venc_cvbs_encoder_atomic_check(struct drm_encoder *encoder, + struct drm_crtc_state *crtc_state, + struct drm_connector_state *conn_state) +{ + int i; + + for (i = 0; i < MESON_CVBS_MODES_COUNT; ++i) { + struct meson_cvbs_mode *meson_mode = &meson_cvbs_modes[i]; + + if (drm_mode_equal(&crtc_state->mode, &meson_mode->mode)) + return 0; + } + + return -EINVAL; +} + +static void meson_venc_cvbs_encoder_disable(struct drm_encoder *encoder) +{ + struct meson_venc_cvbs *meson_venc_cvbs = + encoder_to_meson_venc_cvbs(encoder); + struct meson_drm *priv = meson_venc_cvbs->priv; + + /* Disable CVBS VDAC */ + if (meson_vpu_is_compatible(priv, VPU_COMPATIBLE_G12A)) { + regmap_write(priv->hhi, HHI_VDAC_CNTL0_G12A, 0); + regmap_write(priv->hhi, HHI_VDAC_CNTL1_G12A, 0); + } else { + regmap_write(priv->hhi, HHI_VDAC_CNTL0, 0); + regmap_write(priv->hhi, HHI_VDAC_CNTL1, 8); + } +} + +static void meson_venc_cvbs_encoder_enable(struct drm_encoder *encoder) +{ + struct meson_venc_cvbs *meson_venc_cvbs = + encoder_to_meson_venc_cvbs(encoder); + struct meson_drm *priv = meson_venc_cvbs->priv; + + /* VDAC0 source is not from ATV */ + writel_bits_relaxed(VENC_VDAC_SEL_ATV_DMD, 0, + priv->io_base + _REG(VENC_VDAC_DACSEL0)); + + if (meson_vpu_is_compatible(priv, VPU_COMPATIBLE_GXBB)) { + regmap_write(priv->hhi, HHI_VDAC_CNTL0, 1); + regmap_write(priv->hhi, HHI_VDAC_CNTL1, 0); + } else if (meson_vpu_is_compatible(priv, VPU_COMPATIBLE_GXM) || + meson_vpu_is_compatible(priv, VPU_COMPATIBLE_GXL)) { + regmap_write(priv->hhi, HHI_VDAC_CNTL0, 0xf0001); + regmap_write(priv->hhi, HHI_VDAC_CNTL1, 0); + } else if (meson_vpu_is_compatible(priv, VPU_COMPATIBLE_G12A)) { + regmap_write(priv->hhi, HHI_VDAC_CNTL0_G12A, 0x906001); + regmap_write(priv->hhi, HHI_VDAC_CNTL1_G12A, 0); + } +} + +static void meson_venc_cvbs_encoder_mode_set(struct drm_encoder *encoder, + struct drm_display_mode *mode, + struct drm_display_mode *adjusted_mode) +{ + struct meson_venc_cvbs *meson_venc_cvbs = + encoder_to_meson_venc_cvbs(encoder); + struct meson_drm *priv = meson_venc_cvbs->priv; + int i; + + for (i = 0; i < MESON_CVBS_MODES_COUNT; ++i) { + struct meson_cvbs_mode *meson_mode = &meson_cvbs_modes[i]; + + if (drm_mode_equal(mode, &meson_mode->mode)) { + meson_venci_cvbs_mode_set(priv, + meson_mode->enci); + + /* Setup 27MHz vclk2 for ENCI and VDAC */ + meson_vclk_setup(priv, MESON_VCLK_TARGET_CVBS, + MESON_VCLK_CVBS, MESON_VCLK_CVBS, + MESON_VCLK_CVBS, true); + break; + } + } +} + +static const struct drm_encoder_helper_funcs + meson_venc_cvbs_encoder_helper_funcs = { + .atomic_check = meson_venc_cvbs_encoder_atomic_check, + .disable = meson_venc_cvbs_encoder_disable, + .enable = meson_venc_cvbs_encoder_enable, + .mode_set = meson_venc_cvbs_encoder_mode_set, +}; + +static bool meson_venc_cvbs_connector_is_available(struct meson_drm *priv) +{ + struct device_node *remote; + + remote = of_graph_get_remote_node(priv->dev->of_node, 0, 0); + if (!remote) + return false; + + of_node_put(remote); + return true; +} + +int meson_venc_cvbs_create(struct meson_drm *priv) +{ + struct drm_device *drm = priv->drm; + struct meson_venc_cvbs *meson_venc_cvbs; + struct drm_connector *connector; + struct drm_encoder *encoder; + int ret; + + if (!meson_venc_cvbs_connector_is_available(priv)) { + dev_info(drm->dev, "CVBS Output connector not available\n"); + return 0; + } + + meson_venc_cvbs = devm_kzalloc(priv->dev, sizeof(*meson_venc_cvbs), + GFP_KERNEL); + if (!meson_venc_cvbs) + return -ENOMEM; + + meson_venc_cvbs->priv = priv; + encoder = &meson_venc_cvbs->encoder; + connector = &meson_venc_cvbs->connector; + + /* Connector */ + + drm_connector_helper_add(connector, + &meson_cvbs_connector_helper_funcs); + + ret = drm_connector_init(drm, connector, &meson_cvbs_connector_funcs, + DRM_MODE_CONNECTOR_Composite); + if (ret) { + dev_err(priv->dev, "Failed to init CVBS connector\n"); + return ret; + } + + connector->interlace_allowed = 1; + + /* Encoder */ + + drm_encoder_helper_add(encoder, &meson_venc_cvbs_encoder_helper_funcs); + + ret = drm_encoder_init(drm, encoder, &meson_venc_cvbs_encoder_funcs, + DRM_MODE_ENCODER_TVDAC, "meson_venc_cvbs"); + if (ret) { + dev_err(priv->dev, "Failed to init CVBS encoder\n"); + return ret; + } + + encoder->possible_crtcs = BIT(0); + + drm_connector_attach_encoder(connector, encoder); + + return 0; +} diff --git a/pool/shard002/C/0056843_mingw-hdep.c b/pool/shard002/C/0056843_mingw-hdep.c new file mode 100644 index 0000000000000000000000000000000000000000..1a1d1df7e1edfbc9b658757146597fe4f8eb8dd7 --- /dev/null +++ b/pool/shard002/C/0056843_mingw-hdep.c @@ -0,0 +1,259 @@ +/* Host support routines for MinGW, for GDB, the GNU debugger. + + Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011 + 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 "serial.h" +#include "event-loop.h" + +#include "gdb_assert.h" +#include "gdb_select.h" +#include "gdb_string.h" +#include "readline/readline.h" + +#include + +/* This event is signalled whenever an asynchronous SIGINT handler + needs to perform an action in the main thread. */ +static HANDLE sigint_event; + +/* When SIGINT_EVENT is signalled, gdb_select will call this + function. */ +struct async_signal_handler *sigint_handler; + +/* The strerror() function can return NULL for errno values that are + out of range. Provide a "safe" version that always returns a + printable string. + + The Windows runtime implementation of strerror never returns NULL, + but does return a useless string for anything above sys_nerr; + unfortunately this includes all socket-related error codes. + This replacement tries to find a system-provided error message. */ + +char * +safe_strerror (int errnum) +{ + static char *buffer; + int len; + + if (errnum >= 0 && errnum < sys_nerr) + return strerror (errnum); + + if (buffer) + { + LocalFree (buffer); + buffer = NULL; + } + + if (FormatMessage (FORMAT_MESSAGE_ALLOCATE_BUFFER + | FORMAT_MESSAGE_FROM_SYSTEM, + NULL, errnum, + MAKELANGID (LANG_NEUTRAL, SUBLANG_DEFAULT), + (LPTSTR) &buffer, 0, NULL) == 0) + { + static char buf[32]; + xsnprintf (buf, sizeof buf, "(undocumented errno %d)", errnum); + return buf; + } + + /* Windows error messages end with a period and a CR-LF; strip that + out. */ + len = strlen (buffer); + if (len > 3 && strcmp (buffer + len - 3, ".\r\n") == 0) + buffer[len - 3] = '\0'; + + return buffer; +} + +/* Wrapper for select. On Windows systems, where the select interface + only works for sockets, this uses the GDB serial abstraction to + handle sockets, consoles, pipes, and serial ports. + + The arguments to this function are the same as the traditional + arguments to select on POSIX platforms. */ + +int +gdb_select (int n, fd_set *readfds, fd_set *writefds, fd_set *exceptfds, + struct timeval *timeout) +{ + static HANDLE never_handle; + HANDLE handles[MAXIMUM_WAIT_OBJECTS]; + HANDLE h; + DWORD event; + DWORD num_handles; + /* SCBS contains serial control objects corresponding to file + descriptors in READFDS and WRITEFDS. */ + struct serial *scbs[MAXIMUM_WAIT_OBJECTS]; + /* The number of valid entries in SCBS. */ + size_t num_scbs; + int fd; + int num_ready; + size_t indx; + + num_ready = 0; + num_handles = 0; + num_scbs = 0; + for (fd = 0; fd < n; ++fd) + { + HANDLE read = NULL, except = NULL; + struct serial *scb; + + /* There is no support yet for WRITEFDS. At present, this isn't + used by GDB -- but we do not want to silently ignore WRITEFDS + if something starts using it. */ + gdb_assert (!writefds || !FD_ISSET (fd, writefds)); + + if ((!readfds || !FD_ISSET (fd, readfds)) + && (!exceptfds || !FD_ISSET (fd, exceptfds))) + continue; + + scb = serial_for_fd (fd); + if (scb) + { + serial_wait_handle (scb, &read, &except); + scbs[num_scbs++] = scb; + } + + if (read == NULL) + read = (HANDLE) _get_osfhandle (fd); + if (except == NULL) + { + if (!never_handle) + never_handle = CreateEvent (0, FALSE, FALSE, 0); + + except = never_handle; + } + + if (readfds && FD_ISSET (fd, readfds)) + { + gdb_assert (num_handles < MAXIMUM_WAIT_OBJECTS); + handles[num_handles++] = read; + } + + if (exceptfds && FD_ISSET (fd, exceptfds)) + { + gdb_assert (num_handles < MAXIMUM_WAIT_OBJECTS); + handles[num_handles++] = except; + } + } + + gdb_assert (num_handles < MAXIMUM_WAIT_OBJECTS); + handles[num_handles++] = sigint_event; + + event = WaitForMultipleObjects (num_handles, + handles, + FALSE, + timeout + ? (timeout->tv_sec * 1000 + + timeout->tv_usec / 1000) + : INFINITE); + /* EVENT can only be a value in the WAIT_ABANDONED_0 range if the + HANDLES included an abandoned mutex. Since GDB doesn't use + mutexes, that should never occur. */ + gdb_assert (!(WAIT_ABANDONED_0 <= event + && event < WAIT_ABANDONED_0 + num_handles)); + /* We no longer need the helper threads to check for activity. */ + for (indx = 0; indx < num_scbs; ++indx) + serial_done_wait_handle (scbs[indx]); + if (event == WAIT_FAILED) + return -1; + if (event == WAIT_TIMEOUT) + return 0; + /* Run through the READFDS, clearing bits corresponding to descriptors + for which input is unavailable. */ + h = handles[event - WAIT_OBJECT_0]; + for (fd = 0, indx = 0; fd < n; ++fd) + { + HANDLE fd_h; + + if ((!readfds || !FD_ISSET (fd, readfds)) + && (!exceptfds || !FD_ISSET (fd, exceptfds))) + continue; + + if (readfds && FD_ISSET (fd, readfds)) + { + fd_h = handles[indx++]; + /* This handle might be ready, even though it wasn't the handle + returned by WaitForMultipleObjects. */ + if (fd_h != h && WaitForSingleObject (fd_h, 0) != WAIT_OBJECT_0) + FD_CLR (fd, readfds); + else + num_ready++; + } + + if (exceptfds && FD_ISSET (fd, exceptfds)) + { + fd_h = handles[indx++]; + /* This handle might be ready, even though it wasn't the handle + returned by WaitForMultipleObjects. */ + if (fd_h != h && WaitForSingleObject (fd_h, 0) != WAIT_OBJECT_0) + FD_CLR (fd, exceptfds); + else + num_ready++; + } + } + + /* With multi-threaded SIGINT handling, there is a race between the + readline signal handler and GDB. It may still be in + rl_prep_terminal in another thread. Do not return until it is + done; we can check the state here because we never longjmp from + signal handlers on Windows. */ + while (RL_ISSTATE (RL_STATE_SIGHANDLER)) + Sleep (1); + + if (h == sigint_event + || WaitForSingleObject (sigint_event, 0) == WAIT_OBJECT_0) + { + if (sigint_handler != NULL) + call_async_signal_handler (sigint_handler); + + if (num_ready == 0) + { + errno = EINTR; + return -1; + } + } + + return num_ready; +} + +/* Wrapper for the body of signal handlers. On Windows systems, a + SIGINT handler runs in its own thread. We can't longjmp from + there, and we shouldn't even prompt the user. Delay HANDLER + until the main thread is next in gdb_select. */ + +void +gdb_call_async_signal_handler (struct async_signal_handler *handler, + int immediate_p) +{ + if (immediate_p) + sigint_handler = handler; + else + { + mark_async_signal_handler (handler); + sigint_handler = NULL; + } + SetEvent (sigint_event); +} + +void +_initialize_mingw_hdep (void) +{ + sigint_event = CreateEvent (0, FALSE, FALSE, 0); +} diff --git a/pool/shard002/C/0056844_p-sqrt.c b/pool/shard002/C/0056844_p-sqrt.c new file mode 100644 index 0000000000000000000000000000000000000000..e8c193ca76bb352e84f90e0b19c638cda5d987d2 --- /dev/null +++ b/pool/shard002/C/0056844_p-sqrt.c @@ -0,0 +1,96 @@ +/* + Copyright 2020 Daniel Schultz + + This file is part of FLINT. + + FLINT 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. See . +*/ + +#include "nmod_mpoly.h" +#include "profiler.h" + +int iter_list[21] = {0, 300000, 50000, 5000, 1000, 300, 100, 40, 10, 5, 3, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1}; + +int main(void) +{ + nmod_mpoly_t f, g, h, k; + timeit_t timer; + slong iters, j, n; + nmod_mpoly_ctx_t ctx; + mp_limb_t p = n_nextprime(UWORD(1) << (SMALL_FMPZ_BITCOUNT_MAX), 1); + const char * vars[] = {"x", "y", "z", "t", "u"}; + + nmod_mpoly_ctx_init(ctx, 5, ORD_LEX, p); + + nmod_mpoly_init(f, ctx); + nmod_mpoly_init(g, ctx); + nmod_mpoly_init(h, ctx); + nmod_mpoly_init(k, ctx); + + nmod_mpoly_set_str_pretty(f, "(1+x+y+2*z^2+3*t^3+5*u^5)", vars, ctx); + + printf("Timing sqrt(p^2) where p = (1+x+y+2z^2+3t^3+5u^5)^n\n\n"); + printf("LEX ordering\n\n"); + + for (n = 1; n <= 20; n++) + { + nmod_mpoly_pow_ui(g, f, 2*n, ctx); + + iters = iter_list[n]; + + timeit_start(timer); + + for (j = 0; j < iters; j++) + nmod_mpoly_sqrt(h, g, ctx); + + timeit_stop(timer); + + flint_printf("n = %wd: %.10lf s\n", n, (((double)timer->wall)/iters)/1000); + } + + nmod_mpoly_clear(k, ctx); + nmod_mpoly_clear(h, ctx); + nmod_mpoly_clear(g, ctx); + nmod_mpoly_clear(f, ctx); + + nmod_mpoly_ctx_clear(ctx); + nmod_mpoly_ctx_init(ctx, 5, ORD_DEGREVLEX, p); + + nmod_mpoly_init(f, ctx); + nmod_mpoly_init(g, ctx); + nmod_mpoly_init(h, ctx); + nmod_mpoly_init(k, ctx); + + nmod_mpoly_set_str_pretty(f, "(1+x+y+2*z^2+3*t^3+5*u^5)", vars, ctx); + + printf("Timing sqrt(p^2) where p = (1+x+y+2z^2+3t^3+5u^5)^n\n\n"); + printf("DEGREVLEX ordering:\n\n"); + + for (n = 1; n <= 20; n++) + { + nmod_mpoly_pow_ui(g, f, 2*n, ctx); + + iters = iter_list[n]; + + timeit_start(timer); + + for (j = 0; j < iters; j++) + nmod_mpoly_sqrt(h, g, ctx); + + timeit_stop(timer); + + flint_printf("n = %wd: %.10lf s\n", n, (((double)timer->wall)/iters)/1000); + } + + nmod_mpoly_clear(k, ctx); + nmod_mpoly_clear(h, ctx); + nmod_mpoly_clear(g, ctx); + nmod_mpoly_clear(f, ctx); + nmod_mpoly_ctx_clear(ctx); + + return 0; +} + diff --git a/pool/shard002/C/0056856_worker.c b/pool/shard002/C/0056856_worker.c new file mode 100644 index 0000000000000000000000000000000000000000..337cb62cb828a9f445a34fc1502235e15155b049 --- /dev/null +++ b/pool/shard002/C/0056856_worker.c @@ -0,0 +1,68 @@ +#include "worker.h" +#include +#include +#include + +struct kvvec_buf *build_kvvec_buf(struct kvvec *kvv) +{ + struct kvvec_buf *kvvb; + + /* + * key=value, separated by PAIR_SEP and messages + * delimited by MSG_DELIM + */ + kvvb = kvvec2buf(kvv, KV_SEP, PAIR_SEP, MSG_DELIM_LEN); + if (!kvvb) { + return NULL; + } + memcpy(kvvb->buf + (kvvb->bufsize - MSG_DELIM_LEN), MSG_DELIM, MSG_DELIM_LEN); + + return kvvb; +} + +int worker_set_sockopts(int sd, int bufsize) +{ + int ret; + + ret = fcntl(sd, F_SETFD, FD_CLOEXEC); + ret |= fcntl(sd, F_SETFL, O_NONBLOCK); + + if (!bufsize) + return ret; + ret |= setsockopt(sd, SOL_SOCKET, SO_SNDBUF, &bufsize, sizeof(int)); + ret |= setsockopt(sd, SOL_SOCKET, SO_RCVBUF, &bufsize, sizeof(int)); + + return ret; +} + +char *worker_ioc2msg(nm_bufferqueue *bq, size_t *size, int flags) +{ + char *res; + if (nm_bufferqueue_unshift_to_delim(bq, MSG_DELIM, MSG_DELIM_LEN, size, (void **)&res)) + return NULL; + *size -= MSG_DELIM_LEN; + return res; +} + +int spawn_named_helper(char *path, char **argv) +{ + int ret, pid; + + pid = fork(); + if (pid < 0) { + return -1; + } + + /* parent leaves early */ + if (pid) + return pid; + + ret = execvp(path, argv); + /* if execvp() fails, there's really nothing we can do */ + exit(ret); +} + +int spawn_helper(char **argv) +{ + return spawn_named_helper(argv[0], argv); +} diff --git a/pool/shard002/C/0056857_Renderer.c b/pool/shard002/C/0056857_Renderer.c new file mode 100644 index 0000000000000000000000000000000000000000..745e314420996bc97f771bad45a88210901af7ba --- /dev/null +++ b/pool/shard002/C/0056857_Renderer.c @@ -0,0 +1,47 @@ +// +// Mesh.c +// Camera +// +// Created by Sid on 31/08/13. +// Copyright (c) 2013 whackylabs. All rights reserved. +// +#include "std_incl.h" +#include "Renderer.h" +#include "Transform.h" + +void Render_Mesh(const Mesh mesh, const Transform transform, const Program program, const Camera camera) { + /* Matrices used */ + GLKMatrix4 pMat = GLKMatrix4MakePerspective(GLKMathDegreesToRadians(camera.fov), camera.aspect_ratio, 0.1f, 100.0f); + GLKMatrix4 mvMat = Transform_GetMV(&transform); + bool possible; + GLKMatrix3 nMat = GLKMatrix3InvertAndTranspose(GLKMatrix4GetMatrix3(mvMat), &possible); + assert(possible); + GLKMatrix4 mvpMat = GLKMatrix4Multiply(pMat, mvMat); + + /* Bind the data to the associated uniform variable in the shader + First gets the location of that variable in the shader using its name + Then passes the matrix to that variable + */ + int mvp_loc = glGetUniformLocation(program.program, "u_Mvp"); + glUniformMatrix4fv(mvp_loc, 1, GL_FALSE, mvpMat.m); + int n_loc = glGetUniformLocation(program.program, "u_N"); + glUniformMatrix3fv(n_loc, 1, GL_FALSE, nMat.m); + + // Bind the VAO + glBindVertexArrayOES(mesh.vao); + + /* + This function allows the use of other primitive types : triangle strips, lines, ... + For indexed geometry, use the function glDrawElements() with an index list. + Else draws a non-indexed triangle array from the pointers previously given. + */ + if (mesh.index_count > 0) { + glDrawElements(GL_TRIANGLES, mesh.index_count, GL_UNSIGNED_SHORT, 0); + } else { + glDrawArrays(GL_TRIANGLES, 0, mesh.vertex_count); + } + + // Unbind the VAO + glBindVertexArrayOES(0); +} +//EOF diff --git a/pool/shard002/C/0056865_InitialConditions.c b/pool/shard002/C/0056865_InitialConditions.c new file mode 100644 index 0000000000000000000000000000000000000000..7979d64dffa0509f122572a18235f535b27fb78d --- /dev/null +++ b/pool/shard002/C/0056865_InitialConditions.c @@ -0,0 +1,138 @@ +/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +** +** Copyright (C), 2003, +** Steve Quenette, 110 Victoria Street, Melbourne, Victoria, 3053, Australia. +** Californian Institute of Technology, 1200 East California Boulevard, Pasadena, California, 91125, USA. +** University of Texas, 1 University Station, Austin, Texas, 78712, USA. +** +** Authors: +** Stevan M. Quenette, Senior Software Engineer, VPAC. (steve@vpac.org) +** Stevan M. Quenette, Visitor in Geophysics, Caltech. +** Luc Lavier, Research Scientist, The University of Texas. (luc@utig.ug.utexas.edu) +** Luc Lavier, Research Scientist, Caltech. +** +** 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 +** +** $Id: InitialConditions.c 3261 2006-11-14 21:18:05Z EunseoChoi $ +** +**~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/ + +#include +#include +#include +#include "Snac/Snac.h" +#include "types.h" +#include "Element.h" +#include "InitialConditions.h" +#include "Register.h" +#include +#include +#include +#define min(a,b) ((a)<(b) ? (a):(b)) +#ifndef PATH_MAX +#define PATH_MAX 1024 +#endif + +void SnacViscoPlastic_InitialConditions( void* _context, void* data ) { + Snac_Context* context = (Snac_Context*)_context; + Element_LocalIndex element_lI; + double mu,vis_min,dt_maxwellI; + double dt_maxwell = 0; + const double mfrac = 9.0e-01; + + // loop over the phase using the dictionary + + Dictionary_Entry_Value* materialList = Dictionary_Get( context->dictionary, "materials" ); + int PhaseI = 0; + if( materialList ) { + Dictionary_Entry_Value* materialEntry = Dictionary_Entry_Value_GetFirstElement( materialList ); + /* loop around the phases to initialize rheology */ + while( materialEntry ) { + context->materialProperty[PhaseI].rheology |= Snac_Material_ViscoPlastic; + mu = context->materialProperty[PhaseI].mu; + vis_min = context->materialProperty[PhaseI].vis_min; + dt_maxwellI = mfrac*vis_min/mu; + dt_maxwell = (PhaseI==0)?dt_maxwellI:min(dt_maxwellI,dt_maxwell); + PhaseI++; + materialEntry = materialEntry->next; + + } + } + else { + context->materialProperty[PhaseI].rheology |= Snac_Material_ViscoPlastic; + mu = context->materialProperty[PhaseI].mu; + vis_min = context->materialProperty[PhaseI].vis_min; + dt_maxwell = mfrac*vis_min/mu; + } + + if( context->dt > dt_maxwell) { + if(context->dtType == Snac_DtType_Constant) { + fprintf(stderr,"dt(%e) should be smaller than dt_maxwell(%e) (mu=%e vis_min=%e mfrac=%e)\n",context->dt,dt_maxwell,mu,vis_min,mfrac); + } + else context->dt = dt_maxwell; + } + + if( context->restartTimestep > 0 ) { + FILE* plStrainIn; + char path[PATH_MAX]; + + sprintf(path, "%s/snac.plStrain.%d.%06d.restart",context->outputPath,context->rank,context->restartTimestep); + Journal_Firewall( (plStrainIn = fopen(path,"r")) != NULL, "Can't find %s", path ); + + /* read in restart file to reconstruct the previous plastic strain.*/ + for( element_lI = 0; element_lI < context->mesh->elementLocalCount; element_lI++ ) { + Snac_Element* element = Snac_Element_At( context, element_lI ); + SnacViscoPlastic_Element* viscoplasticElement = ExtensionManager_Get( context->mesh->elementExtensionMgr, element, + SnacViscoPlastic_ElementHandle ); + const Snac_Material* material = &context->materialProperty[element->material_I]; + + vis_min = context->materialProperty[element->material_I].vis_min; + /* To-Do: Read in viscosity and assign it to tets and elements. */ + if( material->yieldcriterion == mohrcoulomb ) { + Tetrahedra_Index tetra_I; + double depls = 0.0f; + + for( tetra_I = 0; tetra_I < Tetrahedra_Count; tetra_I++ ) { + double tetraPlStrain = 0.0f; + + /* not the actual viscosity at restartTimestep, but doesn't affect the calculation afterwards */ + viscoplasticElement->viscosity[tetra_I] = vis_min; + + fscanf( plStrainIn, "%le", &tetraPlStrain ); + viscoplasticElement->plasticStrain[tetra_I] = tetraPlStrain; + depls += viscoplasticElement->plasticStrain[tetra_I]; + }/* for tets */ + viscoplasticElement->aps = depls/Tetrahedra_Count; + }/* if(mohrcoulomb) */ + }/* for elements */ + if( plStrainIn ) + fclose( plStrainIn ); + }/* if restarting.*/ + else { + /* Set the plastic element initial conditions */ + for( element_lI = 0; element_lI < context->mesh->elementLocalCount; element_lI++ ) { + Snac_Element* element = Snac_Element_At( context, element_lI ); + SnacViscoPlastic_Element* viscoplasticElement = ExtensionManager_Get( context->mesh->elementExtensionMgr, element, + SnacViscoPlastic_ElementHandle ); + viscoplasticElement->aps = 0.0; + vis_min = context->materialProperty[element->material_I].vis_min; + Tetrahedra_Index tetra_I; + for( tetra_I = 0; tetra_I < Tetrahedra_Count; tetra_I++ ) { + viscoplasticElement->plasticStrain[tetra_I] = 0.0; + viscoplasticElement->viscosity[tetra_I] = vis_min; + }//for tets + }//for elements + }//else +}//function diff --git a/pool/shard002/C/0056874_pcm1794a.c b/pool/shard002/C/0056874_pcm1794a.c new file mode 100644 index 0000000000000000000000000000000000000000..afe1b419582aa40c4b2729d242bb13cd843e17f4 --- /dev/null +++ b/pool/shard002/C/0056874_pcm1794a.c @@ -0,0 +1,69 @@ +/* + * Driver for the PCM1794A codec + * + * Author: Florian Meier + * Copyright 2013 + * + * 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. + */ + + +#include +#include +#include + +#include + +static struct snd_soc_dai_driver pcm1794a_dai = { + .name = "pcm1794a-hifi", + .playback = { + .channels_min = 2, + .channels_max = 2, + .rates = SNDRV_PCM_RATE_8000_192000, + .formats = SNDRV_PCM_FMTBIT_S16_LE | + SNDRV_PCM_FMTBIT_S24_LE + }, +}; + +static struct snd_soc_codec_driver soc_codec_dev_pcm1794a; + +static int pcm1794a_probe(struct platform_device *pdev) +{ + return snd_soc_register_codec(&pdev->dev, &soc_codec_dev_pcm1794a, + &pcm1794a_dai, 1); +} + +static int pcm1794a_remove(struct platform_device *pdev) +{ + snd_soc_unregister_codec(&pdev->dev); + return 0; +} + +static const struct of_device_id pcm1794a_of_match[] = { + { .compatible = "ti,pcm1794a", }, + { } +}; +MODULE_DEVICE_TABLE(of, pcm1794a_of_match); + +static struct platform_driver pcm1794a_codec_driver = { + .probe = pcm1794a_probe, + .remove = pcm1794a_remove, + .driver = { + .name = "pcm1794a-codec", + .owner = THIS_MODULE, + .of_match_table = of_match_ptr(pcm1794a_of_match), + }, +}; + +module_platform_driver(pcm1794a_codec_driver); + +MODULE_DESCRIPTION("ASoC PCM1794A codec driver"); +MODULE_AUTHOR("Florian Meier "); +MODULE_LICENSE("GPL v2"); diff --git a/pool/shard002/C/0056882_s_propagateNaNF128UI.c b/pool/shard002/C/0056882_s_propagateNaNF128UI.c new file mode 100644 index 0000000000000000000000000000000000000000..d650365ad26ccff07bf340975e9b7b69a241d2f9 --- /dev/null +++ b/pool/shard002/C/0056882_s_propagateNaNF128UI.c @@ -0,0 +1,81 @@ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3b, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014 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. 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. + +=============================================================================*/ + +#include +#include +#include "platform.h" +#include "internals.h" +#include "specialize.h" +#include "softfloat.h" + +/*---------------------------------------------------------------------------- +| Interpreting the unsigned integer formed from concatenating `uiA64' and +| `uiA0' as a 128-bit floating-point value, and likewise interpreting the +| unsigned integer formed from concatenating `uiB64' and `uiB0' as another +| 128-bit floating-point value, and assuming at least on of these floating- +| point values is a NaN, returns the bit pattern of the combined NaN result. +| If either original floating-point value is a signaling NaN, the invalid +| exception is raised. +*----------------------------------------------------------------------------*/ +struct uint128 + softfloat_propagateNaNF128UI( + uint_fast64_t uiA64, + uint_fast64_t uiA0, + uint_fast64_t uiB64, + uint_fast64_t uiB0 + ) +{ + bool isSigNaNA; + struct uint128 uiZ; + + isSigNaNA = softfloat_isSigNaNF128UI( uiA64, uiA0 ); + if ( isSigNaNA || softfloat_isSigNaNF128UI( uiB64, uiB0 ) ) { + softfloat_raiseFlags( softfloat_flag_invalid ); + if ( isSigNaNA ) goto returnNonsigA; + } + if ( isNaNF128UI( uiA64, uiA0 ) ) { + returnNonsigA: + uiZ.v64 = uiA64; + uiZ.v0 = uiA0; + } else { + uiZ.v64 = uiB64; + uiZ.v0 = uiB0; + } + uiZ.v64 |= UINT64_C( 0x0000800000000000 ); + return uiZ; + +} + diff --git a/pool/shard002/C/0056896_clk-tegra-audio.c b/pool/shard002/C/0056896_clk-tegra-audio.c new file mode 100644 index 0000000000000000000000000000000000000000..f931f227be9722535d3879f59cfece00bf59727b --- /dev/null +++ b/pool/shard002/C/0056896_clk-tegra-audio.c @@ -0,0 +1,252 @@ +/* + * Copyright (c) 2012, 2013, NVIDIA CORPORATION. All rights reserved. + * + * This program is free software; you can redistribute it and/or modify it + * under the terms and conditions of the GNU General Public License, + * version 2, as published by the Free Software Foundation. + * + * This program is distributed in the hope 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 "clk.h" +#include "clk-id.h" + +#define AUDIO_SYNC_CLK_I2S0 0x4a0 +#define AUDIO_SYNC_CLK_I2S1 0x4a4 +#define AUDIO_SYNC_CLK_I2S2 0x4a8 +#define AUDIO_SYNC_CLK_I2S3 0x4ac +#define AUDIO_SYNC_CLK_I2S4 0x4b0 +#define AUDIO_SYNC_CLK_SPDIF 0x4b4 + +#define AUDIO_SYNC_DOUBLER 0x49c + +#define PLLA_OUT 0xb4 + +struct tegra_sync_source_initdata +{ + char *name; + unsigned long rate; + unsigned long max_rate; + int clk_id; +}; + +#define SYNC(_name) \ + {\ + .name = #_name,\ + .rate = 24000000,\ + .max_rate = 24000000,\ + .clk_id = tegra_clk_ ## _name,\ + } + +struct tegra_audio_clk_initdata +{ + char *gate_name; + char *mux_name; + u32 offset; + int gate_clk_id; + int mux_clk_id; +}; + +#define AUDIO(_name, _offset) \ + {\ + .gate_name = #_name,\ + .mux_name = #_name"_mux",\ + .offset = _offset,\ + .gate_clk_id = tegra_clk_ ## _name,\ + .mux_clk_id = tegra_clk_ ## _name ## _mux,\ + } + +struct tegra_audio2x_clk_initdata +{ + char *parent; + char *gate_name; + char *name_2x; + char *div_name; + int clk_id; + int clk_num; + u8 div_offset; +}; + +#define AUDIO2X(_name, _num, _offset) \ + {\ + .parent = #_name,\ + .gate_name = #_name"_2x",\ + .name_2x = #_name"_doubler",\ + .div_name = #_name"_div",\ + .clk_id = tegra_clk_ ## _name ## _2x,\ + .clk_num = _num,\ + .div_offset = _offset,\ + } + +static DEFINE_SPINLOCK(clk_doubler_lock); + +static const char *mux_audio_sync_clk[] = { "spdif_in_sync", "i2s0_sync", + "i2s1_sync", "i2s2_sync", "i2s3_sync", "i2s4_sync", "vimclk_sync", + }; + +static struct tegra_sync_source_initdata sync_source_clks[] __initdata = +{ + SYNC(spdif_in_sync), + SYNC(i2s0_sync), + SYNC(i2s1_sync), + SYNC(i2s2_sync), + SYNC(i2s3_sync), + SYNC(i2s4_sync), + SYNC(vimclk_sync), +}; + +static struct tegra_audio_clk_initdata audio_clks[] = +{ + AUDIO(audio0, AUDIO_SYNC_CLK_I2S0), + AUDIO(audio1, AUDIO_SYNC_CLK_I2S1), + AUDIO(audio2, AUDIO_SYNC_CLK_I2S2), + AUDIO(audio3, AUDIO_SYNC_CLK_I2S3), + AUDIO(audio4, AUDIO_SYNC_CLK_I2S4), + AUDIO(spdif, AUDIO_SYNC_CLK_SPDIF), +}; + +static struct tegra_audio2x_clk_initdata audio2x_clks[] = +{ + AUDIO2X(audio0, 113, 24), + AUDIO2X(audio1, 114, 25), + AUDIO2X(audio2, 115, 26), + AUDIO2X(audio3, 116, 27), + AUDIO2X(audio4, 117, 28), + AUDIO2X(spdif, 118, 29), +}; + +void __init tegra_audio_clk_init(void __iomem *clk_base, + void __iomem *pmc_base, struct tegra_clk *tegra_clks, + struct tegra_audio_clk_info *audio_info, + unsigned int num_plls) +{ + struct clk *clk; + struct clk **dt_clk; + int i; + + if (!audio_info || num_plls < 1) + { + pr_err("No audio data passed to tegra_audio_clk_init\n"); + WARN_ON(1); + return; + } + + for (i = 0; i < num_plls; i++) + { + struct tegra_audio_clk_info *info = &audio_info[i]; + + dt_clk = tegra_lookup_dt_id(info->clk_id, tegra_clks); + + if (dt_clk) + { + clk = tegra_clk_register_pll(info->name, info->parent, + clk_base, pmc_base, 0, info->pll_params, + NULL); + *dt_clk = clk; + } + } + + /* PLLA_OUT0 */ + dt_clk = tegra_lookup_dt_id(tegra_clk_pll_a_out0, tegra_clks); + + if (dt_clk) + { + clk = tegra_clk_register_divider("pll_a_out0_div", "pll_a", + clk_base + PLLA_OUT, 0, TEGRA_DIVIDER_ROUND_UP, + 8, 8, 1, NULL); + clk = tegra_clk_register_pll_out("pll_a_out0", "pll_a_out0_div", + clk_base + PLLA_OUT, 1, 0, CLK_IGNORE_UNUSED | + CLK_SET_RATE_PARENT, 0, NULL); + *dt_clk = clk; + } + + for (i = 0; i < ARRAY_SIZE(sync_source_clks); i++) + { + struct tegra_sync_source_initdata *data; + + data = &sync_source_clks[i]; + + dt_clk = tegra_lookup_dt_id(data->clk_id, tegra_clks); + + if (!dt_clk) + { + continue; + } + + clk = tegra_clk_register_sync_source(data->name, + data->rate, data->max_rate); + *dt_clk = clk; + } + + for (i = 0; i < ARRAY_SIZE(audio_clks); i++) + { + struct tegra_audio_clk_initdata *data; + + data = &audio_clks[i]; + dt_clk = tegra_lookup_dt_id(data->mux_clk_id, tegra_clks); + + if (!dt_clk) + { + continue; + } + + clk = clk_register_mux(NULL, data->mux_name, mux_audio_sync_clk, + ARRAY_SIZE(mux_audio_sync_clk), + CLK_SET_RATE_NO_REPARENT, + clk_base + data->offset, 0, 3, 0, + NULL); + *dt_clk = clk; + + dt_clk = tegra_lookup_dt_id(data->gate_clk_id, tegra_clks); + + if (!dt_clk) + { + continue; + } + + clk = clk_register_gate(NULL, data->gate_name, data->mux_name, + 0, clk_base + data->offset, 4, + CLK_GATE_SET_TO_DISABLE, NULL); + *dt_clk = clk; + } + + for (i = 0; i < ARRAY_SIZE(audio2x_clks); i++) + { + struct tegra_audio2x_clk_initdata *data; + + data = &audio2x_clks[i]; + dt_clk = tegra_lookup_dt_id(data->clk_id, tegra_clks); + + if (!dt_clk) + { + continue; + } + + clk = clk_register_fixed_factor(NULL, data->name_2x, + data->parent, CLK_SET_RATE_PARENT, 2, 1); + clk = tegra_clk_register_divider(data->div_name, + data->name_2x, clk_base + AUDIO_SYNC_DOUBLER, + 0, 0, data->div_offset, 1, 0, + &clk_doubler_lock); + clk = tegra_clk_register_periph_gate(data->gate_name, + data->div_name, TEGRA_PERIPH_NO_RESET, + clk_base, CLK_SET_RATE_PARENT, data->clk_num, + periph_clk_enb_refcnt); + *dt_clk = clk; + } +} + diff --git a/pool/shard002/C/0056902_stm32l4xx_hal_interface.c b/pool/shard002/C/0056902_stm32l4xx_hal_interface.c new file mode 100644 index 0000000000000000000000000000000000000000..c8082ba5cc9a47af27f7d5a7d730761360098b65 --- /dev/null +++ b/pool/shard002/C/0056902_stm32l4xx_hal_interface.c @@ -0,0 +1,203 @@ +/** + ****************************************************************************** + * @file stm32l4xx_hal.c + * @author MCD Application Team + * @brief HAL module driver. + * This is the common part of the HAL initialization + * + @verbatim + ============================================================================== + ##### How to use this driver ##### + ============================================================================== + [..] + The common HAL driver contains a set of generic and common APIs that can be + used by the PPP peripheral drivers and the user to start using the HAL. + [..] + The HAL contains two APIs' categories: + (+) Common HAL APIs + (+) Services HAL APIs + + @endverbatim + ****************************************************************************** + * @attention + * + *

© Copyright (c) 2017 STMicroelectronics. + * All rights reserved.

+ * + * This software component is licensed by ST under BSD 3-Clause license, + * the "License"; You may not use this file except in compliance with the + * License. You may obtain a copy of the License at: + * opensource.org/licenses/BSD-3-Clause + * + ****************************************************************************** + */ + +/* Includes ------------------------------------------------------------------*/ +#include "stm32l4xx_hal.h" +#include "stm32l4xx_hal_interface.h" +#include "stm32l4xx_ll_usart.h" +#include "stm32l4xx_ll_utils.h" +#include "stm32l4xx_ll_rcc.h" +#include "stm32l4xx_ll_pwr.h" +#include "stm32l4xx_ll_gpio.h" +#include "stm32l4xx_ll_bus.h" +#include "stm32l4xx_ll_system.h" +#include "stm32l4xx_ll_cortex.h" + +void ST_USART2_UART_Init(void); +void SystemClock_Config(void); +void debuggpio_init(void); +void gpio_reset(void); +void gpio_set(void); +static void Error_Handler(void); +/** @addtogroup STM32L4xx_HAL_Driver + * @{ + */ + +/** @defgroup HAL HAL + * @brief HAL module driver + * @{ + */ +/** + * @brief System Clock Configuration + * @retval None + */ +void SystemClock_Config(void) +{ + RCC_ClkInitTypeDef RCC_ClkInitStruct = {0}; + RCC_OscInitTypeDef RCC_OscInitStruct = {0}; + + /* Enable voltage range 1 boost mode for frequency above 80 Mhz */ + __HAL_RCC_PWR_CLK_ENABLE(); + HAL_PWREx_ControlVoltageScaling(PWR_REGULATOR_VOLTAGE_SCALE1_BOOST); + __HAL_RCC_PWR_CLK_DISABLE(); + + /* Enable MSI Oscillator and activate PLL with MSI as source */ + RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_MSI; + RCC_OscInitStruct.MSIState = RCC_MSI_ON; + RCC_OscInitStruct.MSICalibrationValue = RCC_MSICALIBRATION_DEFAULT; + RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON; + RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_MSI; + RCC_OscInitStruct.MSIClockRange = RCC_MSIRANGE_6; + RCC_OscInitStruct.PLL.PLLM = 1; + RCC_OscInitStruct.PLL.PLLN = 60; + RCC_OscInitStruct.PLL.PLLR = 2; + RCC_OscInitStruct.PLL.PLLQ = 2; + RCC_OscInitStruct.PLL.PLLP = 7; + if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK){ + /* Initialization Error */ + while(1); + } + + /* To avoid undershoot due to maximum frequency, select PLL as system clock source */ + /* with AHB prescaler divider 2 as first step */ + RCC_ClkInitStruct.ClockType = (RCC_CLOCKTYPE_SYSCLK | RCC_CLOCKTYPE_HCLK | RCC_CLOCKTYPE_PCLK1 | RCC_CLOCKTYPE_PCLK2); + RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK; + RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV2; + RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV1; + RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1; + if(HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_3) != HAL_OK) { + /* Initialization Error */ + while(1); + } + + /* AHB prescaler divider at 1 as second step */ + RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK; + RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1; + if(HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_5) != HAL_OK) { + /* Initialization Error */ + while(1); + } +} + +void ST_USART2_UART_Init(void) +{ + LL_USART_InitTypeDef USART_InitStruct = {0}; + + LL_GPIO_InitTypeDef GPIO_InitStruct = {0}; + + /* Peripheral clock enable */ + LL_APB1_GRP1_EnableClock(LL_APB1_GRP1_PERIPH_USART2); + + LL_AHB2_GRP1_EnableClock(LL_AHB2_GRP1_PERIPH_GPIOA); + /**USART2 GPIO Configuration + PA3 ------> USART2_RX + PA2 ------> USART2_TX + */ + GPIO_InitStruct.Pin = LL_GPIO_PIN_3|LL_GPIO_PIN_2; + GPIO_InitStruct.Mode = LL_GPIO_MODE_ALTERNATE; + GPIO_InitStruct.Speed = LL_GPIO_SPEED_FREQ_VERY_HIGH; + GPIO_InitStruct.OutputType = LL_GPIO_OUTPUT_PUSHPULL; + GPIO_InitStruct.Pull = LL_GPIO_PULL_NO; + GPIO_InitStruct.Alternate = LL_GPIO_AF_7; + LL_GPIO_Init(GPIOA, &GPIO_InitStruct); + + /* USER CODE BEGIN USART2_Init 1 */ + + /* USER CODE END USART2_Init 1 */ + USART_InitStruct.PrescalerValue = LL_USART_PRESCALER_DIV1; + USART_InitStruct.BaudRate = 115200; + USART_InitStruct.DataWidth = LL_USART_DATAWIDTH_8B; + USART_InitStruct.StopBits = LL_USART_STOPBITS_1; + USART_InitStruct.Parity = LL_USART_PARITY_NONE; + USART_InitStruct.TransferDirection = LL_USART_DIRECTION_TX_RX; + USART_InitStruct.HardwareFlowControl = LL_USART_HWCONTROL_NONE; + USART_InitStruct.OverSampling = LL_USART_OVERSAMPLING_16; + LL_USART_Init(USART2, &USART_InitStruct); + LL_USART_SetTXFIFOThreshold(USART2, LL_USART_FIFOTHRESHOLD_1_8); + LL_USART_SetRXFIFOThreshold(USART2, LL_USART_FIFOTHRESHOLD_1_8); + LL_USART_DisableFIFO(USART2); + LL_USART_ConfigAsyncMode(USART2); + LL_USART_Enable(USART2); +} + +void debuggpio_init(void) +{ + LL_GPIO_InitTypeDef GPIO_InitStruct = {0}; + + /* GPIO Ports Clock Enable */ + LL_AHB2_GRP1_EnableClock(LL_AHB2_GRP1_PERIPH_GPIOH); + LL_AHB2_GRP1_EnableClock(LL_AHB2_GRP1_PERIPH_GPIOA); + LL_AHB2_GRP1_EnableClock(LL_AHB2_GRP1_PERIPH_GPIOF); + + /**/ + LL_GPIO_ResetOutputPin(GPIOH, LL_GPIO_PIN_4); + + /**/ + GPIO_InitStruct.Pin = LL_GPIO_PIN_4; + GPIO_InitStruct.Mode = LL_GPIO_MODE_OUTPUT; + GPIO_InitStruct.Speed = LL_GPIO_SPEED_FREQ_LOW; + GPIO_InitStruct.OutputType = LL_GPIO_OUTPUT_PUSHPULL; + GPIO_InitStruct.Pull = LL_GPIO_PULL_NO; + LL_GPIO_Init(GPIOH, &GPIO_InitStruct); +} +void gpio_reset(void) +{ + HAL_GPIO_WritePin(GPIOH, GPIO_PIN_4, GPIO_PIN_RESET); +} + +void gpio_set(void) +{ + HAL_GPIO_WritePin(GPIOH, GPIO_PIN_4, GPIO_PIN_SET); +} +/** + * @brief This function is executed in case of error occurrence. + * @retval None + */ +static void Error_Handler(void) +{ + /* USER CODE BEGIN Error_Handler_Debug */ + /* User can add his own implementation to report the HAL error return state */ + + /* USER CODE END Error_Handler_Debug */ +} + +/** + * @} + */ + +/** + * @} + */ + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/pool/shard002/C/0056910_aes.c b/pool/shard002/C/0056910_aes.c new file mode 100644 index 0000000000000000000000000000000000000000..edae09ce93008519e4a29a6a59c2674351247f43 --- /dev/null +++ b/pool/shard002/C/0056910_aes.c @@ -0,0 +1,51 @@ +#include +#include +#include + +#include "aes.h" +#include "../../lib/avr-crypto-lib/bcal/bcal-cbc.h" +#include "../../lib/avr-crypto-lib/bcal/bcal_aes128.h" + + +int aes_init_endecrypt(enum mode mode, uint8_t blocksize, struct aes_ctx* ctx, unsigned char* iv, uint8_t ivlen, unsigned char* key, uint8_t keylen) +{ + int err = 0; + if(blocksize != ivlen || keylen != ivlen) + { + err = -EINVAL; + goto exit_err; + } + ctx->blocksize = blocksize; + if((err = bcal_cbc_init(&aes128_desc, key, 128, &ctx->ctx))) + { + goto exit_err; + } + bcal_cbc_loadIV(iv, &ctx->ctx); +exit_err: + return err; +} + +int aes_deencrypt(enum mode mode, struct aes_ctx* ctx, unsigned char* block, uint8_t blocklen) +{ + if(blocklen != ctx->blocksize) + { + return -EINVAL; + } + switch(mode) + { + case(ENCRYPT): + bcal_cbc_encNext(block, &ctx->ctx); + break; + case(DECRYPT): + bcal_cbc_decNext(block, &ctx->ctx); + break; + default: + return -EINVAL; + } + return 0; +} + +void aes_free(struct aes_ctx* ctx) +{ + bcal_cbc_free(&ctx->ctx); +} diff --git a/pool/shard002/C/0056916_itering.c b/pool/shard002/C/0056916_itering.c new file mode 100644 index 0000000000000000000000000000000000000000..2bab82516ce7837590675dda19322414f8db9a9f --- /dev/null +++ b/pool/shard002/C/0056916_itering.c @@ -0,0 +1,74 @@ +#define QC_MKID_PROP(TEST) \ + QC_MKID_MOD_PROP(itering, TEST) + +#define QC_MKID_TEST(TEST) \ + QC_MKID_MOD_TEST(itering, TEST) + +#define QC_MKTEST_FUNC(TEST) \ + QC_MKTEST(QC_MKID_TEST(TEST), \ + prop1, \ + QC_MKID_PROP(TEST), \ + &qc_vec_info) + +static enum theft_trial_res QC_MKID_PROP(content) (struct theft * t, void * arg1) +{ + UNUSED(t); + + struct vec * vec = arg1; + + struct vec dup = {0}; + if (!qc_vec_dup_contents(vec, &dup)) + return THEFT_TRIAL_SKIP; + + vec_itering(vec); + + bool ret = memcmp(vec->ptr, dup.ptr, dup.capacity * sizeof(int)) == 0; + + qc_vec_dup_free(&dup); + + return QC_BOOL2TRIAL(ret); +} + +static enum theft_trial_res QC_MKID_PROP(res) (struct theft * t, void * arg1) +{ + UNUSED(t); + + struct vec * vec = arg1; + + bool itering = vec->iterating; + + bool res = vec_itering(vec); + + bool ret = itering == res; + + return QC_BOOL2TRIAL(ret); +} + +static enum theft_trial_res QC_MKID_PROP(meta) (struct theft * t, void * arg1) +{ + UNUSED(t); + + struct vec * vec = arg1; + + struct vec cpy = *vec; + + vec_itering(vec); + + bool ret = memcmp(vec, &cpy, sizeof(struct vec)) == 0; + + return QC_BOOL2TRIAL(ret); +} + +QC_MKTEST_FUNC(content); +QC_MKTEST_FUNC(meta); +QC_MKTEST_FUNC(res); + +QC_MKTEST_ALL(QC_MKID_MOD_ALL(itering), + QC_MKID_TEST(content), + QC_MKID_TEST(meta), + QC_MKID_TEST(res), + ); + +#undef QC_MKID_PROP +#undef QC_MKID_TEST +#undef QC_MKTEST_FUNC diff --git a/pool/shard002/C/0056918_util.c b/pool/shard002/C/0056918_util.c new file mode 100644 index 0000000000000000000000000000000000000000..a97dbe32e3d9e319f9edb13ebcf80efac9d734a5 --- /dev/null +++ b/pool/shard002/C/0056918_util.c @@ -0,0 +1,44 @@ +#include "typedef.h" +#include + + +int is_var(char *s){ + register int i; + // Ê×ÏÈ¿´ËûÊÇ·ñÊÇÒ»¸ö¾Ö²¿±äÁ¿ + for (i=lvartos-1; i>call_stack[functos-1]; i--){ + if (!strcmp(local_var_stack[i].var_name, token)) + return 1; + } + + // ·ñÔò¿´ËüÊÇ·ñÊÇÈ«¾Ö±äÁ¿ + for (i=0; i'/*%^=()", c) || c==9 || + c=='\r' || c==0) + return 1; + return 0; +} + +int iswhite(char c){ + if (c==' ' || c=='\t') + return 1; + return 0; +} \ No newline at end of file diff --git a/pool/shard002/C/0056924_gstparse.c b/pool/shard002/C/0056924_gstparse.c new file mode 100644 index 0000000000000000000000000000000000000000..d41b97e513ab15a0e03d13172a32afb8a406bb88 --- /dev/null +++ b/pool/shard002/C/0056924_gstparse.c @@ -0,0 +1,315 @@ +/* GStreamer + * Copyright (C) 1999,2000 Erik Walthinsen + * 2000 Wim Taymans + * 2002 Andy Wingo + * 2008 Tim-Philipp Müller + * + * gstparse.c: get a pipeline from a text pipeline description + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Library General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Library General Public License for more details. + * + * You should have received a copy of the GNU Library General Public + * License along with this library; if not, write to the + * Free Software Foundation, Inc., 59 Temple Place - Suite 330, + * Boston, MA 02111-1307, USA. + */ + +/** + * SECTION:gstparse + * @short_description: Get a pipeline from a text pipeline description + * + * These function allow to create a pipeline based on the syntax used in the + * gst-launch utility. + */ + + +#include "gst_private.h" +#include + +#include "gstparse.h" +#include "gsterror.h" +#include "gstinfo.h" +#ifndef GST_DISABLE_PARSE +#include "parse/types.h" +#endif + +/** + * gst_parse_error_quark: + * + * Get the error quark used by the parsing subsystem. + * + * Returns: the quark of the parse errors. + */ +GQuark +gst_parse_error_quark (void) +{ + static GQuark quark = 0; + + if (!quark) + quark = g_quark_from_static_string ("gst_parse_error"); + return quark; +} + + +/** + * gst_parse_context_new: + * + * Allocates a parse context for use with gst_parse_launch_full() or + * gst_parse_launchv_full(). + * + * Returns: a newly-allocated parse context. Free with gst_parse_context_free() + * when no longer needed. + * + * Since: 0.10.20 + */ +GstParseContext * +gst_parse_context_new (void) +{ +#ifndef GST_DISABLE_PARSE + GstParseContext *ctx; + + ctx = g_slice_new (GstParseContext); + ctx->missing_elements = NULL; + + return ctx; +#else + return NULL; +#endif +} + +/** + * gst_parse_context_free: + * @context: a #GstParseContext + * + * Frees a parse context previously allocated with gst_parse_context_new(). + * + * Since: 0.10.20 + */ +void +gst_parse_context_free (GstParseContext * context) +{ +#ifndef GST_DISABLE_PARSE + if (context) { + g_list_foreach (context->missing_elements, (GFunc) g_free, NULL); + g_list_free (context->missing_elements); + g_slice_free (GstParseContext, context); + } +#endif +} + +/** + * gst_parse_context_get_missing_elements: + * @context: a #GstParseContext + * + * Retrieve missing elements from a previous run of gst_parse_launch_full() + * or gst_parse_launchv_full(). Will only return results if an error code + * of %GST_PARSE_ERROR_NO_SUCH_ELEMENT was returned. + * + * Returns: a NULL-terminated array of element factory name strings of + * missing elements. Free with g_strfreev() when no longer needed. + * + * Since: 0.10.20 + */ +gchar ** +gst_parse_context_get_missing_elements (GstParseContext * context) +{ +#ifndef GST_DISABLE_PARSE + gchar **arr; + GList *l; + guint len, i; + + g_return_val_if_fail (context != NULL, NULL); + + len = g_list_length (context->missing_elements); + + if (G_UNLIKELY (len == 0)) + return NULL; + + arr = g_new (gchar *, len + 1); + + for (i = 0, l = context->missing_elements; l != NULL; l = l->next, ++i) + arr[i] = g_strdup (l->data); + + arr[i] = NULL; + + return arr; +#else + return NULL; +#endif +} + +#ifndef GST_DISABLE_PARSE +static gchar * +_gst_parse_escape (const gchar * str) +{ + GString *gstr = NULL; + + g_return_val_if_fail (str != NULL, NULL); + + gstr = g_string_sized_new (strlen (str)); + + while (*str) { + if (*str == ' ') + g_string_append_c (gstr, '\\'); + g_string_append_c (gstr, *str); + str++; + } + + return g_string_free (gstr, FALSE); +} +#endif /* !GST_DISABLE_PARSE */ + +/** + * gst_parse_launchv: + * @argv: null-terminated array of arguments + * @error: pointer to a #GError + * + * Create a new element based on command line syntax. + * @error will contain an error message if an erroneuos pipeline is specified. + * An error does not mean that the pipeline could not be constructed. + * + * Returns: a new element on success and %NULL on failure. + */ +GstElement * +gst_parse_launchv (const gchar ** argv, GError ** error) +{ + return gst_parse_launchv_full (argv, NULL, 0, error); +} + +/** + * gst_parse_launchv_full: + * @argv: null-terminated array of arguments + * @context: a parse context allocated with gst_parse_context_new(), or %NULL + * @flags: parsing options, or #GST_PARSE_FLAG_NONE + * @error: pointer to a #GError (which must be initialised to %NULL) + * + * Create a new element based on command line syntax. + * @error will contain an error message if an erroneous pipeline is specified. + * An error does not mean that the pipeline could not be constructed. + * + * Returns: a new element on success; on failure, either %NULL or a + * partially-constructed bin or element will be returned and @error will be set + * (unless you passed #GST_PARSE_FLAG_FATAL_ERRORS in @flags, then %NULL will + * always be returned on failure) + * + * Since: 0.10.20 + */ +GstElement * +gst_parse_launchv_full (const gchar ** argv, GstParseContext * context, + GstParseFlags flags, GError ** error) +{ +#ifndef GST_DISABLE_PARSE + GstElement *element; + GString *str; + const gchar **argvp, *arg; + gchar *tmp; + + g_return_val_if_fail (argv != NULL, NULL); + g_return_val_if_fail (error == NULL || *error == NULL, NULL); + + /* let's give it a nice size. */ + str = g_string_sized_new (1024); + + argvp = argv; + while (*argvp) { + arg = *argvp; + tmp = _gst_parse_escape (arg); + g_string_append (str, tmp); + g_free (tmp); + g_string_append_c (str, ' '); + argvp++; + } + + element = gst_parse_launch_full (str->str, context, flags, error); + + g_string_free (str, TRUE); + + return element; +#else + /* gst_parse_launch_full() will set a GST_CORE_ERROR_DISABLED error for us */ + return gst_parse_launch_full ("", NULL, 0, error); +#endif +} + +/** + * gst_parse_launch: + * @pipeline_description: the command line describing the pipeline + * @error: the error message in case of an erroneous pipeline. + * + * Create a new pipeline based on command line syntax. + * Please note that you might get a return value that is not %NULL even though + * the @error is set. In this case there was a recoverable parsing error and you + * can try to play the pipeline. + * + * Returns: a new element on success, %NULL on failure. If more than one toplevel + * element is specified by the @pipeline_description, all elements are put into + * a #GstPipeline, which than is returned. + */ +GstElement * +gst_parse_launch (const gchar * pipeline_description, GError ** error) +{ + return gst_parse_launch_full (pipeline_description, NULL, 0, error); +} + +/** + * gst_parse_launch_full: + * @pipeline_description: the command line describing the pipeline + * @context: a parse context allocated with gst_parse_context_new(), or %NULL + * @flags: parsing options, or #GST_PARSE_FLAG_NONE + * @error: the error message in case of an erroneous pipeline. + * + * Create a new pipeline based on command line syntax. + * Please note that you might get a return value that is not %NULL even though + * the @error is set. In this case there was a recoverable parsing error and you + * can try to play the pipeline. + * + * Returns: a new element on success, %NULL on failure. If more than one toplevel + * element is specified by the @pipeline_description, all elements are put into + * a #GstPipeline, which then is returned. + * + * Since: 0.10.20 + */ +GstElement * +gst_parse_launch_full (const gchar * pipeline_description, + GstParseContext * context, GstParseFlags flags, GError ** error) +{ +#ifndef GST_DISABLE_PARSE + GstElement *element; + + g_return_val_if_fail (pipeline_description != NULL, NULL); + g_return_val_if_fail (error == NULL || *error == NULL, NULL); + + GST_CAT_INFO (GST_CAT_PIPELINE, "parsing pipeline description '%s'", + pipeline_description); + + element = _gst_parse_launch (pipeline_description, error, context, flags); + + /* don't return partially constructed pipeline if FATAL_ERRORS was given */ + if (G_UNLIKELY (error != NULL && *error != NULL && element != NULL)) { + if ((flags & GST_PARSE_FLAG_FATAL_ERRORS)) { + gst_object_unref (element); + element = NULL; + } + } + + return element; +#else + gchar *msg; + + GST_WARNING ("Disabled API called"); + + msg = gst_error_get_message (GST_CORE_ERROR, GST_CORE_ERROR_DISABLED); + g_set_error (error, GST_CORE_ERROR, GST_CORE_ERROR_DISABLED, "%s", msg); + g_free (msg); + + return NULL; +#endif +} diff --git a/pool/shard002/C/0056934_capi.c b/pool/shard002/C/0056934_capi.c new file mode 100644 index 0000000000000000000000000000000000000000..91b6b8071a3bc1b5f6b3ef800bcab4c9528416b2 --- /dev/null +++ b/pool/shard002/C/0056934_capi.c @@ -0,0 +1,81 @@ +/******************************************************************** + * Copyright (C) 2016 and later: Unicode, Inc. and others. + * License & terms of use: http://www.unicode.org/copyright.html#License + ************************************************************************* + ************************************************************************* + * COPYRIGHT: + * Copyright (c) 1999-2002, International Business Machines Corporation and + * others. All Rights Reserved. + *************************************************************************/ + +#include "unicode/unum.h" +#include "unicode/ustring.h" +#include +#include + +static void uprintf(const UChar* str) { + char buf[256]; + u_austrcpy(buf, str); + printf("%s", buf); +} + +void capi() { + UNumberFormat *fmt; + UErrorCode status = U_ZERO_ERROR; + /* The string "987654321.123" as UChars */ + UChar str[] = { 0x39, 0x38, 0x37, 0x36, 0x35, 0x34, 0x33, + 0x32, 0x31, 0x30, 0x2E, 0x31, 0x32, 0x33, 0 }; + UChar buf[256]; + int32_t needed; + double a; + + /* Create a formatter for the US locale */ + fmt = unum_open( + UNUM_DECIMAL, /* style */ + 0, /* pattern */ + 0, /* patternLength */ + "en_US", /* locale */ + 0, /* parseErr */ + &status); + if (U_FAILURE(status)) { + printf("FAIL: unum_open\n"); + exit(1); + } + + /* Use the formatter to parse a number. When using the C API, + we have to specify whether we want a double or a long in advance. + + We pass in NULL for the position pointer in order to get the + default behavior which is to parse from the start. */ + a = unum_parseDouble(fmt, str, u_strlen(str), NULL, &status); + if (U_FAILURE(status)) { + printf("FAIL: unum_parseDouble\n"); + exit(1); + } + + /* Show the result */ + printf("unum_parseDouble(\""); + uprintf(str); + printf("\") => %g\n", a); + + /* Use the formatter to format the same number back into a string + in the US locale. The return value is the buffer size needed. + We're pretty sure we have enough space, but in a production + application one would check this value. + + We pass in NULL for the UFieldPosition pointer because we don't + care to receive that data. */ + needed = unum_formatDouble(fmt, a, buf, 256, NULL, &status); + if (U_FAILURE(status)) { + printf("FAIL: format_parseDouble\n"); + exit(1); + } + + /* Show the result */ + printf("unum_formatDouble(%g) => \"", a); + uprintf(buf); + printf("\"\n"); + + /* Release the storage used by the formatter */ + unum_close(fmt); +} diff --git a/pool/shard002/C/0056940_ioremap.c b/pool/shard002/C/0056940_ioremap.c new file mode 100644 index 0000000000000000000000000000000000000000..0c43248347bd82e8ad0b7fb97414e401fdbe2bba --- /dev/null +++ b/pool/shard002/C/0056940_ioremap.c @@ -0,0 +1,191 @@ +/* + * 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. + * + * (C) Copyright 1995 1996 Linus Torvalds + * (C) Copyright 2001, 2002 Ralf Baechle + */ +#include +#include +#include +#include +#include +#include +#include +#include + +static inline void remap_area_pte(pte_t * pte, unsigned long address, + phys_t size, phys_t phys_addr, unsigned long flags) +{ + phys_t end; + unsigned long pfn; + pgprot_t pgprot = __pgprot(_PAGE_GLOBAL | _PAGE_PRESENT | __READABLE + | __WRITEABLE | flags); + + address &= ~PMD_MASK; + end = address + size; + if (end > PMD_SIZE) + end = PMD_SIZE; + BUG_ON(address >= end); + pfn = phys_addr >> PAGE_SHIFT; + do { + if (!pte_none(*pte)) { + printk("remap_area_pte: page already exists\n"); + BUG(); + } + set_pte(pte, pfn_pte(pfn, pgprot)); + address += PAGE_SIZE; + pfn++; + pte++; + } while (address && (address < end)); +} + +static inline int remap_area_pmd(pmd_t * pmd, unsigned long address, + phys_t size, phys_t phys_addr, unsigned long flags) +{ + phys_t end; + + address &= ~PGDIR_MASK; + end = address + size; + if (end > PGDIR_SIZE) + end = PGDIR_SIZE; + phys_addr -= address; + BUG_ON(address >= end); + do { + pte_t * pte = pte_alloc_kernel(pmd, address); + if (!pte) + return -ENOMEM; + remap_area_pte(pte, address, end - address, address + phys_addr, flags); + address = (address + PMD_SIZE) & PMD_MASK; + pmd++; + } while (address && (address < end)); + return 0; +} + +static int remap_area_pages(unsigned long address, phys_t phys_addr, + phys_t size, unsigned long flags) +{ + int error; + pgd_t * dir; + unsigned long end = address + size; + + phys_addr -= address; + dir = pgd_offset(&init_mm, address); + flush_cache_all(); + BUG_ON(address >= end); + do { + pud_t *pud; + pmd_t *pmd; + + error = -ENOMEM; + pud = pud_alloc(&init_mm, dir, address); + if (!pud) + break; + pmd = pmd_alloc(&init_mm, pud, address); + if (!pmd) + break; + if (remap_area_pmd(pmd, address, end - address, + phys_addr + address, flags)) + break; + error = 0; + address = (address + PGDIR_SIZE) & PGDIR_MASK; + dir++; + } while (address && (address < end)); + flush_tlb_all(); + return error; +} + +/* + * Generic mapping function (not visible outside): + */ + +/* + * Remap an arbitrary physical address space into the kernel virtual + * address space. Needed when the kernel wants to access high addresses + * directly. + * + * NOTE! We need to allow non-page-aligned mappings too: we will obviously + * have to convert them into an offset in a page-aligned mapping, but the + * caller shouldn't need to know that small detail. + */ + +#define IS_LOW512(addr) (!((phys_t)(addr) & (phys_t) ~0x1fffffffULL)) + +void __iomem * __ioremap(phys_t phys_addr, phys_t size, unsigned long flags) +{ + struct vm_struct * area; + unsigned long offset; + phys_t last_addr; + void * addr; + + phys_addr = fixup_bigphys_addr(phys_addr, size); + + /* Don't allow wraparound or zero size */ + last_addr = phys_addr + size - 1; + if (!size || last_addr < phys_addr) + return NULL; + + /* + * Map uncached objects in the low 512mb of address space using KSEG1, + * otherwise map using page tables. + */ + if (IS_LOW512(phys_addr) && IS_LOW512(last_addr) && + flags == _CACHE_UNCACHED) + return (void __iomem *) CKSEG1ADDR(phys_addr); + + /* + * Don't allow anybody to remap normal RAM that we're using.. + */ + if (phys_addr < virt_to_phys(high_memory)) { + char *t_addr, *t_end; + struct page *page; + + t_addr = __va(phys_addr); + t_end = t_addr + (size - 1); + + for(page = virt_to_page(t_addr); page <= virt_to_page(t_end); page++) + if(!PageReserved(page)) + return NULL; + } + + /* + * Mappings have to be page-aligned + */ + offset = phys_addr & ~PAGE_MASK; + phys_addr &= PAGE_MASK; + size = PAGE_ALIGN(last_addr + 1) - phys_addr; + + /* + * Ok, go for it.. + */ + area = get_vm_area(size, VM_IOREMAP); + if (!area) + return NULL; + addr = area->addr; + if (remap_area_pages((unsigned long) addr, phys_addr, size, flags)) { + vunmap(addr); + return NULL; + } + + return (void __iomem *) (offset + (char *)addr); +} + +#define IS_KSEG1(addr) (((unsigned long)(addr) & ~0x1fffffffUL) == CKSEG1) + +void __iounmap(const volatile void __iomem *addr) +{ + struct vm_struct *p; + + if (IS_KSEG1(addr)) + return; + + p = remove_vm_area((void *) (PAGE_MASK & (unsigned long __force) addr)); + if (!p) + printk(KERN_ERR "iounmap: bad address %p\n", addr); + + kfree(p); +} + +EXPORT_SYMBOL(__ioremap); +EXPORT_SYMBOL(__iounmap); diff --git a/pool/shard002/C/0056941_1-2.c b/pool/shard002/C/0056941_1-2.c new file mode 100644 index 0000000000000000000000000000000000000000..bc359c4da3a6bd2d443553e6d1bd9f737dfecc36 --- /dev/null +++ b/pool/shard002/C/0056941_1-2.c @@ -0,0 +1,170 @@ +/* +* Copyright (c) 2005, Bull S.A.. All rights reserved. +* Created by: Sebastien Decugis + +* This program is free software; you can redistribute it and/or modify it +* under the terms of version 2 of the GNU General Public License as +* published by the Free Software Foundation. +* +* This program is distributed in the hope that it would be useful, but +* WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. +* +* You should have received a copy of the GNU General Public License along +* with this program; if not, write the Free Software Foundation, Inc., +* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + +* This sample test aims to check the following assertions: +* +* pthread_kill() sends the specified signal to the specified thread. + +* The steps are: +* -> set a signal handler +* -> Create a new thread +* -> pthread_kill this thread from the main thread +* -> Wait that the signal handler is called +* -> Check that the correct signal is received in the correct thread + +* The test fails if a bad signal is received or bad thread receives it. + +*/ + +/* We are testing conformance to IEEE Std 1003.1, 2003 Edition */ +#define _POSIX_C_SOURCE 200112L + +/******************************************************************************/ +/*************************** standard includes ********************************/ +/******************************************************************************/ +#include +#include +#include +#include +#include +#include + +#include +#include + +/******************************************************************************/ +/*************************** Test framework *******************************/ +/******************************************************************************/ +#include "../testfrmw/testfrmw.h" +#include "../testfrmw/testfrmw.c" +/* This header is responsible for defining the following macros: + * UNRESOLVED(ret, descr); + * where descr is a description of the error and ret is an int + * (error code for example) + * FAILED(descr); + * where descr is a short text saying why the test has failed. + * PASSED(); + * No parameter. + * + * Both three macros shall terminate the calling process. + * The testcase shall not terminate in any other maneer. + * + * The other file defines the functions + * void output_init() + * void output(char * string, ...) + * + * Those may be used to output information. + */ + +/******************************************************************************/ +/**************************** Configuration ***********************************/ +/******************************************************************************/ +#ifndef VERBOSE +#define VERBOSE 1 +#endif + +/******************************************************************************/ +/*************************** Test case ***********************************/ +/******************************************************************************/ + +int handler_called = 0; +pthread_t ch; + +/* Signal handler */ +void handler(int sig) +{ + handler_called = sig; + + if (!pthread_equal(pthread_self(), ch)) { + FAILED + ("The signal handler was not trigged in the killed thread"); + } +} + +/* Thread function */ +void *threaded(void *arg) +{ + int rebours = 3; + + /* sleep up to 3 seconds */ + + while ((!handler_called) && (rebours--)) + sleep(1); + + /* quit */ + return NULL; +} + +/* The main test function. */ +int main(void) +{ + int ret; + + struct sigaction sa; + + /* Initialize output */ + output_init(); + + /* Set the signal handler */ + sa.sa_flags = 0; + sa.sa_handler = handler; + ret = sigemptyset(&sa.sa_mask); + + if (ret != 0) { + UNRESOLVED(ret, "Failed to empty signal set"); + } + + ret = sigaction(SIGUSR2, &sa, 0); + + if (ret != 0) { + UNRESOLVED(ret, "Failed to set signal handler"); + } + + /* Create the child */ + ret = pthread_create(&ch, NULL, threaded, NULL); + + if (ret != 0) { + UNRESOLVED(ret, "Failed to create a thread"); + } + + /* kill the child thread */ + ret = pthread_kill(ch, SIGUSR2); + + if (ret != 0) { + UNRESOLVED(ret, "Failed to kill child thread"); + } + + /* Wait for child thread termination */ + ret = pthread_join(ch, NULL); + + if (ret != 0) { + UNRESOLVED(ret, "Failed to join the thread"); + } + + /* Check if handler has been trigged inside the child */ + if (handler_called != SIGUSR2) { + FAILED("Wrong signal received in thread"); + } + + /* Test passed */ +#if VERBOSE > 0 + + output("Test passed\n"); + +#endif + + PASSED; +} diff --git a/pool/shard002/C/0056946_lcd-truly_tdo_hd0499k.c b/pool/shard002/C/0056946_lcd-truly_tdo_hd0499k.c new file mode 100644 index 0000000000000000000000000000000000000000..3f28fc93f6c8bad09105cba43d497cc3c2f62686 --- /dev/null +++ b/pool/shard002/C/0056946_lcd-truly_tdo_hd0499k.c @@ -0,0 +1,173 @@ +/* + * Copyright (c) 2012 Ingenic Semiconductor Co., Ltd. + * http://www.ingenic.com/ + * + * dorado board lcd setup routines. + * + * 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 "../board_base.h" + +int truly_tdo_hd0499k_init(struct lcd_device *lcd) +{ + int ret = 0; + if(GPIO_MIPI_RST_N > 0){ + ret = gpio_request(GPIO_MIPI_RST_N, "lcd mipi panel rst"); + if (ret) { + printk(KERN_ERR "can's request lcd panel rst\n"); + return ret; + } + } + if(GPIO_MIPI_PWR > 0){ + ret = gpio_request(GPIO_MIPI_PWR, "lcd mipi panel avcc"); + if (ret) { + printk(KERN_ERR "can's request lcd panel avcc\n"); + return ret; + } + } + return 0; +} + +int truly_tdo_hd0499k_reset(struct lcd_device *lcd) +{ + int ret = 0; + + ret = gpio_request(GPIO_MIPI_RST_N, "lcd mipi panel rst"); + if (ret) { + printk(KERN_ERR "can's request lcd panel rst\n"); + return ret; + } + gpio_direction_output(GPIO_MIPI_RST_N, 0); + msleep(3); + gpio_direction_output(GPIO_MIPI_RST_N, 1); + msleep(8); + return 0; +} + +int truly_tdo_hd0499k_power_on(struct lcd_device *lcd, int enable) +{ + int ret = 0; + + ret = gpio_request(GPIO_MIPI_PWR, "lcd mipi panel avcc"); + if (ret) { + printk(KERN_ERR "can's request lcd panel avcc\n"); + return ret; + } + //gpio_direction_output(MIPI_PWR, !enable); /* 2.8v en*/ + gpio_direction_output(GPIO_MIPI_PWR, 0); /* 2.8v en*/ + msleep(2); + return 0; +} +struct lcd_platform_data truly_tdo_hd0499k_data = { + .reset = truly_tdo_hd0499k_reset, + .power_on= truly_tdo_hd0499k_power_on, +}; + +struct mipi_dsim_lcd_device truly_tdo_hd0499k_device={ + .name = "truly_tdo_hd0499k-lcd", + .id = 0, + .platform_data = &truly_tdo_hd0499k_data, +}; + +struct fb_videomode jzfb_videomode = { + .name = "truly_tdo_hd0499k-lcd", + .refresh = 60, + .xres = 720, + .yres = 1280, + .pixclock = KHZ2PICOS(25000), + .left_margin = 18, + .right_margin = 12, + .upper_margin = 18, + .lower_margin = 2, + .hsync_len = 18, + .vsync_len = 1, + .sync = FB_SYNC_HOR_HIGH_ACT & FB_SYNC_VERT_HIGH_ACT, + .vmode = FB_VMODE_NONINTERLACED, + .flag = 0, +}; + +struct jzdsi_data jzdsi_pdata = { + .modes = &jzfb_videomode, + .video_config.no_of_lanes = 2, + .video_config.virtual_channel = 0, + .video_config.color_coding = COLOR_CODE_24BIT, + .video_config.byte_clock = DEFAULT_DATALANE_BPS / 8, /* KHz */ + .video_config.video_mode = VIDEO_BURST_WITH_SYNC_PULSES, + .video_config.receive_ack_packets = 0, /* enable receiving of ack packets */ + /*loosely: R0R1R2R3R4R5__G0G1G2G3G4G5G6__B0B1B2B3B4B5B6, + * not loosely: R0R1R2R3R4R5G0G1G2G3G4G5B0B1B2B3B4B5*/ + .video_config.is_18_loosely = 0, + .video_config.data_en_polarity = 1, + + .dsi_config.max_lanes = 2, + .dsi_config.max_hs_to_lp_cycles = 100, + .dsi_config.max_lp_to_hs_cycles = 40, + .dsi_config.max_bta_cycles = 4095, + .dsi_config.color_mode_polarity = 1, + .dsi_config.shut_down_polarity = 1, +}; + +struct jzfb_platform_data jzfb_pdata = { + .num_modes = 1, + .modes = &jzfb_videomode, + .dsi_pdata = &jzdsi_pdata, + + .lcd_type = LCD_TYPE_GENERIC_24_BIT, + .bpp = 24, + .width = 55, + .height = 98, + + .pixclk_falling_edge = 0, + .data_enable_active_low = 0, + +}; + +/**************************************************************************************************/ +#ifdef CONFIG_BACKLIGHT_PWM +static int backlight_init(struct device *dev) +{ + int ret; + ret = gpio_request(GPIO_LCD_PWM, "Backlight"); + if (ret) { + printk(KERN_ERR "failed to request GPF for PWM-OUT1\n"); + return ret; + } + + return 0; +} + +static void backlight_exit(struct device *dev) +{ + gpio_free(GPIO_LCD_PWM); +} + +static struct platform_pwm_backlight_data backlight_data = { + .pwm_id = 1, + .max_brightness = 255, + .dft_brightness = 120, + .pwm_period_ns = 30000, + .init = backlight_init, + .exit = backlight_exit, +}; + +struct platform_device backlight_device = { + .name = "pwm-backlight", + .dev = { + .platform_data = &backlight_data, + }, +}; + +#endif diff --git a/pool/shard002/C/0056951_multi_thread_mutate_1.c b/pool/shard002/C/0056951_multi_thread_mutate_1.c new file mode 100644 index 0000000000000000000000000000000000000000..11365dd20c5c2a7125216c2943f1e4cacfd0b7e6 --- /dev/null +++ b/pool/shard002/C/0056951_multi_thread_mutate_1.c @@ -0,0 +1,165 @@ +/* + SMAL + Copyright (c) 2011 Kurt A. Stephens +*/ + +#include "smal/smal.h" + +#if SMAL_PTHREAD + +#include "my_cons.h" +#include "roots_explicit.h" + +static size_t alloc_n = 100000; +// static size_t alloc_id = 0, free_id = 0; + +struct my_thread_data { + char *name; + smal_thread *t; + size_t alloc_n, free_n, discard_n; +}; +static struct my_thread_data global_data = { "m" }; +static +void my_thread_data_print(struct my_thread_data *d) +{ + fprintf(stderr, + "\n%s thread t@%p DONE \n" + " bottom_of_stack %p \n" + " (alloc %lu, free %lu + discard %lu = %lu) \n", + d->name, d->t, + d->t->bottom_of_stack, + (unsigned long) d->alloc_n, (unsigned long) d->free_n, (unsigned long) d->discard_n, + (unsigned long) (d->free_n + d->discard_n)); +} + +static +void* thread_func(void *arg) +{ + int i; + struct my_thread_data *d = arg; + my_cons *x = 0, *y = 0; + smal_thread *t = smal_thread_self(); + smal_roots_2(x, y); + + d->t = t; + t->bottom_of_stack = &arg; + t->user_data[0] = arg; + + fprintf(stderr, "%s thread t@%p pthread pt@%p \n", (char*) d->name, d->t, (void*) pthread_self()); + + for ( i = 0; i < alloc_n; ++ i ) { + // printf("%s+", (char*) arg); + smal_alloc_p(my_cons_type, (void**) &y); + d->alloc_n ++; + y->car = ((void*) 0) + 1; + y->cdr = 0; + switch ( rand() % 4 ) { + case 0: + // printf("%s>", d->name); + y->car = x ? x->car + 1 : 0; + y->cdr = x; + x = y; + break; + + case 1: + // printf("%s-", d->name); + if ( x ) { + smal_free(x); + x = x->cdr; + d->discard_n ++; // y + } else { + smal_free(y); + } + d->free_n ++; + break; + + case 2: + x = 0; + d->discard_n += x ? (size_t) x->car : 0; // x... + d->discard_n ++; + break; + + default: + d->discard_n ++; // y + } + + if ( rand() % 1000 ) { + //printf("%sG ", d->name); + smal_collect(); + } + + // fprintf(stderr, " t@%p alloced %p\n", t, x); + usleep(rand() % 100); + } + + d->discard_n += x ? (size_t) x->car : 0; // x... + + // my_print_stats(); + + smal_roots_end(); + + smal_thread_died(0); + + return arg; +} + +int main(int argc, char **argv) +{ + int n_threads = 4; + pthread_t child_threads[4]; + struct my_thread_data thread_data[4]; + int i; + + my_cons_type = smal_type_for(sizeof(my_cons), my_cons_mark, 0); + + smal_thread_init(); + + for ( i = 0; i < n_threads; ++ i ) { + struct my_thread_data *d = thread_data + i; + char *thread_name = malloc(3); + sprintf(thread_name, "%d", i); + memset(d, 0, sizeof(*d)); + d->name = thread_name; + pthread_create(&child_threads[i], 0, thread_func, d) ; + } + thread_func(&global_data); + fprintf(stderr, " main finished\n"); + my_print_stats(); + + fprintf(stderr, " main joining\n"); + + for ( i = 0; i < n_threads; ++ i ) { + void *thread_result = 0; + pthread_join(child_threads[i], &thread_result); + global_data.alloc_n += thread_data[i].alloc_n; + global_data.free_n += thread_data[i].free_n; + global_data.discard_n += thread_data[i].discard_n; + } + + fprintf(stderr, " main collecting\n"); + smal_collect(); + my_print_stats(); + // smal_buffer_print_all(0, "after collect"); + + fprintf(stderr, "\n FINAL: \n"); + my_thread_data_print(&global_data); + + fprintf(stderr, " main exiting\n"); + + fprintf(stderr, "\n%s OK\n", argv[0]); + return 0; +} + +#else + +#include + +int main(int argc, char **argv) +{ + fprintf(stderr, "no pthread support: skipping %s\n", __FILE__); + + fprintf(stderr, "\n%s OK\n", argv[0]); + return 0; +} + +#endif diff --git a/pool/shard002/C/0056956_node.c b/pool/shard002/C/0056956_node.c new file mode 100644 index 0000000000000000000000000000000000000000..5a8cf7cebf632cdffad79894bf3eaa603850f62a --- /dev/null +++ b/pool/shard002/C/0056956_node.c @@ -0,0 +1,253 @@ +#include +#include +#include + +#include"../../include/node.h" +#include "../../include/tools.h" + +/** @brief 创建数字node + * + * @param num 数字 + * @return 创建的node + */ +nodePtr node_create_num(double num) { + nodePtr node = (nodePtr) malloc(sizeof(_node)); + if ( NULL == node) { + puts("创建数字node失败...NULL == node "); + exit(0); + } + + node->num = num; + node->flag = '0'; + + node->operator = '\0'; + node->paren = '\0'; + node->sharp = '\0'; + + return node; +} + +/** @brief 创建运算符node + * + * @param operator 运算符 + * @return 创建的node + */ +nodePtr node_create_operator(char operator) { + nodePtr node = (nodePtr) malloc(sizeof(_node)); + if ( NULL == node) { + puts("创建数字node失败...NULL == node "); + exit(0); + } + + node->operator = operator; + node->flag = operator; + + node->num = 0; + node->paren = '\0'; + node->sharp = '\0'; + + return node; + +} + +/** @brief 创建括号node + * + * @param paren 括号 + * @return 创建的node + */ +nodePtr node_create_paren(char paren) { + nodePtr node = (nodePtr) malloc(sizeof(_node)); + if ( NULL == node) { + puts("创建数字node失败...NULL == node "); + exit(0); + } + + node->paren = paren; + node->flag = paren; + + node->operator = '\0'; + node->num = 0; + node->sharp = '\0'; + + return node; +} + +/** @brief 创建结符 + * + * @param sharp # + * + * @return 创建的node + */ +nodePtr node_create_sharp(char sharp) { + nodePtr node = (nodePtr) malloc(sizeof(_node)); + if ( NULL == node) { + puts("创建数字node失败...NULL == node "); + exit(0); + } + + node->sharp = sharp; + node->flag = sharp; + + node->operator = '\0'; + node->num = 0; + node->paren = '\0'; + + return node; +} + +/** @brief 根据指定的符号创建node + * + * @param ch 指定的node + * + * @retval 0 创建成功 + * @retval 1 创建失败 + */ +nodePtr node_create_from_char(char ch) { + nodePtr node = NULL; + + if (!tools_is_char_operator(ch)) { + node = node_create_operator(ch); + } else if (!toolls_is_char_paren(ch)) { + node = node_create_paren(ch); + } else if ('#' == ch) { + node = node_create_sharp(ch); + } + + return node; +} + +/** @brief 打印此node的内容 + * 若是数字开型,则只打印数字,其它类似 + * + * @param node 要打印的node + * + * @retval 0 执行成功 + * @retval 1 执行失败 + */ +int node_print(nodePtr node) { + int res = 1; + + //运算符 + if (!tools_is_char_operator(node->flag)) { + printf("%c\n", node->operator); + } else if (!toolls_is_char_paren(node->flag)) { + printf("%c\n", node->paren); + } else if ('0' == node->flag) { + printf("%.2lf\n", node->num); + } else if ('#' == node->flag) { + printf("%c\n", node->sharp); + } + + res = 0; + return res; + +} + +/** @brief 计算一个表达式应当用多少个node保存 + * + * @param expPtr 表达式 + * + * @return 就使用的node数 + */ +int node_exp_num(char * expPtr) { + //需要的node数 + int count = 0; + int len = strlen(expPtr); + int i = 0; +// int j = 0; + + for (i = 0; i < len; i++) { + char ch = expPtr[i]; + + if ('#' == ch) { + count++; + break; + } + + //如果是运算符,count直接加1 + if (!tools_is_char_operator(ch) || !toolls_is_char_paren(ch)) { + count++; + } else { + //如果是数字,则遍历至当前数字的最后一个字符,count加1 + while (('0' <= ch && ch <= '9') || '.' == ch ) { + i++; + ch = expPtr[i]; + } + + count++; + i--; + + } + } + + return count; +} + +/** @brief 把表达式字符串转换为node数组 + * + * @param expPtr 表达式字符串 + * + * @return 转换后的node数组 + */ +nodePtr node_create_array(char * expPtr) { + //得到转换后的数组的长度 + int array_len = node_exp_num(expPtr); + int len = strlen(expPtr); + int i = 0; + int j = 0; + int k = 0; + nodePtr tmp = NULL; + //创建数组 + nodePtr node_array = (nodePtr) malloc(sizeof(_node) * array_len); + + if ( NULL == node_array) { + puts("创建node数组失败...NULL == node_array"); + exit(0); + } + + for (i = 0; i < len; i++) { + char ch = expPtr[i]; + + //运算符 + if (!tools_is_char_operator(ch)) { + + tmp = node_create_operator(ch); + node_array[j] = *tmp; + j++; + + } else if (!toolls_is_char_paren(ch)) { + + //括号 + tmp = node_create_paren(ch); + node_array[j] = *tmp; + j++; + + } else if ('#' == ch) { + + //结束符 + tmp = node_create_sharp(ch); + node_array[j] = *tmp; + j++; + + } else { + + //数字 + char numArr[20] = { '\0' }; + while (('0' <= ch && ch <= '9') || '.' == ch ) { + numArr[k++] = ch; + i++; + ch = expPtr[i]; + } + double num = atof(numArr); + tmp = node_create_num(num); + node_array[j] = *tmp; + j++; + + i--; + k = 0; + + } + } + + return node_array; +} diff --git a/pool/shard002/C/0056966_Nearly_Lucky_Number.c b/pool/shard002/C/0056966_Nearly_Lucky_Number.c new file mode 100644 index 0000000000000000000000000000000000000000..f7ddafe7ef2c660f79bffa46b1bf835fcb58bf41 --- /dev/null +++ b/pool/shard002/C/0056966_Nearly_Lucky_Number.c @@ -0,0 +1,25 @@ +/* + Problem : Codeforces - Practice - Nearly Lucky Number - http://codeforces.com/problemset/problem/110/A + Author : Utkal Sinha + Contact : info@utkalsinha.com +*/ + +#include + +int main(){ + long long int n; + scanf("%I64d",&n); + + int count = 0,t; + + while(n){ + t = n%10; + if(t==4 || t==7) count++; + n /=10; + } + if(count==4 || count==7) printf("YES\n"); + else printf("NO\n"); + + return 0; +} + diff --git a/pool/shard002/C/0056982_Tspi_TPM_GetAuditDigest07.c b/pool/shard002/C/0056982_Tspi_TPM_GetAuditDigest07.c new file mode 100644 index 0000000000000000000000000000000000000000..59b9b5d2dbc509e514cffe67b5e6672f5c2890b7 --- /dev/null +++ b/pool/shard002/C/0056982_Tspi_TPM_GetAuditDigest07.c @@ -0,0 +1,144 @@ +/* + * + * Copyright (C) International Business Machines Corp., 2007 + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; 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 + */ + +/* + * NAME + * Tspi_TPM_GetAuditDigest07.c + * + * DESCRIPTION + * This test will verify that Tspi_TPM_GetAuditDigest + * returns TSS_E_BAD_PARAMETER error code if digest is NULL. + * + * ALGORITHM + * Setup: + * Create Context + * Connect Context + * Get TPM Handle + * + * Test: + * Call TPM_GetAuditDigest without a key handle. + * Make sure that it returns the proper return codes + * Print results + * + * Cleanup: + * Free memory related to hContext + * Close context + * + * USAGE + * First parameter is --options + * -v or --version + * Second parameter is the version of the test case to be run + * This test case is currently only implemented for v1.2 + * + * HISTORY + * Giampaolo Libralao, glibrala@br.ibm.com - 09/2007. + * + * RESTRICTIONS + * None. + */ + +#include +#include "common.h" + + +int +main( int argc, char **argv ) +{ + char version; + + version = parseArgs( argc, argv ); + if (version >= TESTSUITE_TEST_TSS_1_2) + main_v1_2(version); + else + print_NA(); +} + +int +main_v1_2( char version ) +{ + char * function = "Tspi_TPM_GetAuditDigest07"; + TSS_HCONTEXT hContext; + TSS_HKEY hSRK; + TSS_HTPM hTPM; + TSS_HPOLICY hTpmPolicy; + UINT32 auditDigestLen, ordListLen; + UINT32 * ordList; + TPM_COUNTER_VALUE counterValue; + TSS_RESULT result; + + print_begin_test( function ); + + result = connect_load_all(&hContext, &hSRK, &hTPM); + if ( result != TSS_SUCCESS ) + { + print_error( "connect_load_all", result ); + Tspi_Context_FreeMemory( hContext, NULL ); + Tspi_Context_Close( hContext ); + exit( result ); + } + + result = Tspi_GetPolicyObject(hTPM, TSS_POLICY_USAGE, &hTpmPolicy); + if ( result != TSS_SUCCESS ) + { + print_error( "Tspi_GetPolicyObject", result ); + Tspi_Context_FreeMemory( hContext, NULL ); + Tspi_Context_Close( hContext ); + exit( result ); + } + + result = Tspi_Policy_SetSecret(hTpmPolicy, TESTSUITE_OWNER_SECRET_MODE, + TESTSUITE_OWNER_SECRET_LEN, TESTSUITE_OWNER_SECRET); + if ( result != TSS_SUCCESS ) + { + print_error( "Tspi_Policy_SetSecret", result ); + Tspi_Context_FreeMemory( hContext, NULL ); + Tspi_Context_Close( hContext ); + exit( result ); + } + + /* Check if ordinal auditing is supported on this TPM */ + result = Testsuite_Is_Ordinal_Supported(hTPM, TPM_ORD_SetOrdinalAuditStatus); + if (result != TSS_SUCCESS) { + fprintf(stderr, "%s: TPM doesn't support auditing, returning success\n", __FILE__); + print_success( function, TSS_SUCCESS ); + print_end_test( function ); + Tspi_Context_FreeMemory( hContext, NULL ); + Tspi_Context_Close( hContext ); + exit( 0 ); + } + + // Call GetAuditDigest + result = Tspi_TPM_GetAuditDigest(hTPM, NULL_HKEY, FALSE, &auditDigestLen, NULL, + &counterValue, NULL, &ordListLen, &ordList); + if (TSS_ERROR_CODE(result) != TSS_E_BAD_PARAMETER) + { + print_error( function , result ); + Tspi_Context_FreeMemory( hContext, NULL ); + Tspi_Context_Close( hContext ); + exit( result ); + } else + { + print_success( function, result ); + } + + print_end_test( function ); + Tspi_Context_FreeMemory( hContext, NULL ); + Tspi_Context_Close( hContext ); + exit( 0 ); +} diff --git a/pool/shard002/C/0056990_string_hash.c b/pool/shard002/C/0056990_string_hash.c new file mode 100644 index 0000000000000000000000000000000000000000..f54033819b75b8695bb4d5d4e178fe8a1d6b50d2 --- /dev/null +++ b/pool/shard002/C/0056990_string_hash.c @@ -0,0 +1,35 @@ +/** + * \file string_hash.c + * \brief Computes a hash value for a string. + * \author Copyright (c) 2012 Jason Perkins and the Premake project + */ + +#include "premake.h" +#include + + +int string_hash(lua_State* L) +{ + const char* str = luaL_checkstring(L, 1); + lua_pushnumber(L, (lua_Number)do_hash(str, 0)); + return 1; +} + + +unsigned long do_hash(const char* str, int seed) +{ + /* DJB2 hashing; see http://www.cse.yorku.ca/~oz/hash.html */ + + unsigned long hash = 5381; + + if (seed != 0) { + hash = hash * 33 + seed; + } + + while (*str) { + hash = hash * 33 + (*str); + str++; + } + + return hash; +} diff --git a/pool/shard002/C/0057008_stack.c b/pool/shard002/C/0057008_stack.c new file mode 100644 index 0000000000000000000000000000000000000000..0908248bea1cab8a0745651d3e4e351f45311187 --- /dev/null +++ b/pool/shard002/C/0057008_stack.c @@ -0,0 +1,65 @@ +#include +#include + +typedef int bool_t; +#define true 1 +#define false 0 + +#define STACK_MAXSIZE 1024 + +typedef struct stack stack_t; + +typedef struct stack +{ + bool_t (*push)(stack_t *stack, int i); + bool_t (*pop)(stack_t *stack, int *i); + void (*display)(stack_t *stack); + int arr[STACK_MAXSIZE]; + int top; +} stack_t; + +bool_t stack_push(stack_t *stack, int c) +{ + stack->arr[++stack->top] = c; + return true; +} + +bool_t stack_pop(stack_t *stack, int *c) +{ + if (stack->top ==-1) { + return false; + } else { + *c = stack->arr[stack->top--]; + return true; + } +} + +void stack_display(stack_t *stack) +{ + int i; + for(i = stack->top; i >= 0; i--) + printf("%d\n", stack->arr[i]); +} + +void init_stack(stack_t *s) +{ + s->top = -1; + s->push = stack_push; + s->pop = stack_pop; + s->display = stack_display; + memset(s->arr, 0, sizeof(s->arr)); +} + +int main(void) +{ + int i; + stack_t my_stack; + stack_t *stack = &my_stack; + + init_stack(stack); + + stack->display(stack); + for (i = 0; i < 100; i++) + stack->push(stack, i); + stack->display(stack); +} diff --git a/pool/shard002/C/0057041_CWE617_Reachable_Assertion__connect_socket_67a.c b/pool/shard002/C/0057041_CWE617_Reachable_Assertion__connect_socket_67a.c new file mode 100644 index 0000000000000000000000000000000000000000..8619b1ef8e00ea343c4d62e513b40f4b9de2aad6 --- /dev/null +++ b/pool/shard002/C/0057041_CWE617_Reachable_Assertion__connect_socket_67a.c @@ -0,0 +1,172 @@ +/* TEMPLATE GENERATED TESTCASE FILE +Filename: CWE617_Reachable_Assertion__connect_socket_67a.c +Label Definition File: CWE617_Reachable_Assertion.label.xml +Template File: sources-sink-67a.tmpl.c +*/ +/* + * @description + * CWE: 617 Reachable Assertion + * BadSource: connect_socket Read data using a connect socket (client side) + * GoodSource: Number greater than ASSERT_VALUE + * Sinks: + * BadSink : Assert if n is less than or equal to ASSERT_VALUE + * Flow Variant: 67 Data flow: data passed in a struct from one function to another in different source files + * + * */ + +#include "std_testcase.h" + +#include + +#define ASSERT_VALUE 5 + +#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) + +typedef struct _CWE617_Reachable_Assertion__connect_socket_67_structType +{ + int structFirst; +} CWE617_Reachable_Assertion__connect_socket_67_structType; + +#ifndef OMITBAD + +/* bad function declaration */ +void CWE617_Reachable_Assertion__connect_socket_67b_badSink(CWE617_Reachable_Assertion__connect_socket_67_structType myStruct); + +void CWE617_Reachable_Assertion__connect_socket_67_bad() +{ + int data; + CWE617_Reachable_Assertion__connect_socket_67_structType myStruct; + /* 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 + } + myStruct.structFirst = data; + CWE617_Reachable_Assertion__connect_socket_67b_badSink(myStruct); +} + +#endif /* OMITBAD */ + +#ifndef OMITGOOD + +/* goodG2B uses the GoodSource with the BadSink */ +void CWE617_Reachable_Assertion__connect_socket_67b_goodG2BSink(CWE617_Reachable_Assertion__connect_socket_67_structType myStruct); + +static void goodG2B() +{ + int data; + CWE617_Reachable_Assertion__connect_socket_67_structType myStruct; + /* Initialize data */ + data = -1; + /* FIX: Use a value greater than the assert value */ + data = ASSERT_VALUE+1; + myStruct.structFirst = data; + CWE617_Reachable_Assertion__connect_socket_67b_goodG2BSink(myStruct); +} + +void CWE617_Reachable_Assertion__connect_socket_67_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()..."); + CWE617_Reachable_Assertion__connect_socket_67_good(); + printLine("Finished good()"); +#endif /* OMITGOOD */ +#ifndef OMITBAD + printLine("Calling bad()..."); + CWE617_Reachable_Assertion__connect_socket_67_bad(); + printLine("Finished bad()"); +#endif /* OMITBAD */ + return 0; +} + +#endif diff --git a/pool/shard002/C/0057042_ee_thendin.c b/pool/shard002/C/0057042_ee_thendin.c new file mode 100644 index 0000000000000000000000000000000000000000..c9eb0d097020c5afd01a92d77520f81f64d505d5 --- /dev/null +++ b/pool/shard002/C/0057042_ee_thendin.c @@ -0,0 +1,111 @@ +/* ###*B*### + * ERIKA Enterprise - a tiny RTOS for small microcontrollers + * + * Copyright (C) 2002-2008 Evidence Srl + * + * This file is part of ERIKA Enterprise. + * + * ERIKA Enterprise 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, + * (with a special exception described below). + * + * Linking this code statically or dynamically with other modules is + * making a combined work based on this code. Thus, the terms and + * conditions of the GNU General Public License cover the whole + * combination. + * + * As a special exception, the copyright holders of this library give you + * permission to link this code with independent modules to produce an + * executable, regardless of the license terms of these independent + * modules, and to copy and distribute the resulting executable under + * terms of your choice, provided that you also meet, for each linked + * independent module, the terms and conditions of the license of that + * module. An independent module is a module which is not derived from + * or based on this library. If you modify this code, you may extend + * this exception to your version of the code, but you are not + * obligated to do so. If you do not wish to do so, delete this + * exception statement from your version. + * + * ERIKA Enterprise is distributed in the hope that it will be + * useful, but WITHOUT ANY WARRANTY; without even the implied warranty + * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License version 2 for more details. + * + * You should have received a copy of the GNU General Public License + * version 2 along with ERIKA Enterprise; if not, write to the + * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + * Boston, MA 02110-1301 USA. + * ###*E*### */ + +/* + * Author: 2001 Paolo Gai + * + * CVS: $Id: ee_thendin.c,v 1.4 2006/01/24 10:21:14 pj Exp $ + */ + +#include "ee_internal.h" + +#ifndef __PRIVATE_THREAD_END_INSTANCE__ +void EE_thread_end_instance(void) +{ + EE_TID current; + + current = EE_stk_queryfirst(); + + /* decrease the pending activations... ready or stacked => (nact>0) */ + EE_th_nact[current]--; + +#if defined(__MULTI__) || defined(__WITH_STATUS__) + /* The task state switches from STACKED TO READY because it ends its + * instance. Note that status=READY and nact=0 ==>> the task is + * suspended!!! */ + EE_th_status[current] = EE_READY; +#endif + + /* reset the task priority bit in the system_ceiling */ + EE_sys_ceiling &= ~EE_th_dispatch_prio[current]; + + /* extract the task from the stk data structure */ + EE_stk_getfirst(); + + if (EE_th_nact[current] > 0U) { + /* there are pending activations... */ + /* we have to reinsert the task into the ready queue before + * rescheduling!!! */ + EE_rq_insert(current); + } + + /* check if there is to schedule a ready task pop a preempted + * task */ + if ((EE_rq_queryfirst() == EE_NIL) || + (EE_sys_ceiling >= EE_th_ready_prio[EE_rq_queryfirst()])) { + /* we have to schedule an interrupted task (already on the + * stack!!!) the state is already STACKED! */ + EE_hal_endcycle_stacked(EE_stk_queryfirst()); + } + else { + /* we have to schedule a ready task */ +#if defined(__MULTI__) + register int flag; + + flag = EE_th_status[EE_rq_queryfirst()] & EE_WASSTACKED; +#endif + +#if defined(__MULTI__) || defined(__WITH_STATUS__) + EE_th_status[EE_rq_queryfirst()] = EE_STACKED; +#endif + + EE_sys_ceiling |= EE_th_dispatch_prio[EE_rq_queryfirst()]; + +#if defined(__MULTI__) + if (flag) + EE_hal_endcycle_stacked(EE_rq2stk_exchange()); + else + EE_hal_endcycle_ready(EE_rq2stk_exchange()); +#else + EE_hal_endcycle_ready(EE_rq2stk_exchange()); +#endif + } +} +#endif diff --git a/pool/shard002/C/0057067_freebsdeditrule.c b/pool/shard002/C/0057067_freebsdeditrule.c new file mode 100644 index 0000000000000000000000000000000000000000..ebe1604879109ebfcd594948fbaa37231453af2b --- /dev/null +++ b/pool/shard002/C/0057067_freebsdeditrule.c @@ -0,0 +1,142 @@ +/* ******** netUstad: Network Ustadi (Network Master) ******** */ +/* This software is Copyright (C) 2004 by Ozkan KIRIK. */ +/* Permission is granted to redistribute and modify this */ +/* software under the terms of the GNU General Public License */ +/* available at http://www.gnu.org/ */ +/**************************************************************/ + + +#include "editrule.h" +#include "netustad.h" +#include "loadconfig.h" + +/***************************************************************/ +/* Editing An IPFW Rule */ +/***************************************************************/ +void +editrule(nunetwork_socket client, char *path, + char *method, char *query_string) +{ + char buf [1024], + tmpbuf [255]; + int cgi_output [2]; + int cgi_input [2]; + pid_t pid; + int status; + char c; + char *param[64]; + char *tempstr; + char *delruleno; + int pos = 2; + + + buf[0] = 'A'; + buf[1] = '\0'; + + if (strlen(query_string) < 13) { + unimplemented(client); + return; + } + snprintf(buf, sizeof(buf), "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n"); + nunetwork_send(client, buf, strlen(buf), 0); + + param[0] = strdup(path); + param[1] = "add"; + tempstr = strdup(query_string); + + delruleno = strdup(strtok(tempstr, "@\n")); + param[pos] = strtok(NULL, "@\n"); + while (param[pos++] != NULL) { + param[pos] = strtok(NULL, "@\n"); + } + + /* Deleting Old Rule */ + if (pipe(cgi_output) < 0) { + cannot_execute(client); + return; + } + if (pipe(cgi_input) < 0) { + cannot_execute(client); + return; + } + if ((pid = fork()) < 0) { + cannot_execute(client); + return; + } + if (pid == 0) { /* child: Delete Rule */ + dup2(cgi_output[1], 1); + dup2(cgi_input[0], 0); + close(cgi_output[0]); + close(cgi_input[1]); + + execl(path, path, "del", delruleno, NULL); + exit(0); + } else { /* parent */ + close(cgi_output[1]); + close(cgi_input[0]); + while (read(cgi_output[0], &c, 1) > 0) + nunetwork_send(client, &c, 1, 0); + close(cgi_output[0]); + close(cgi_input[1]); + + waitpid(pid, &status, 0); + } + + /* Adding New Rule */ + if (pipe(cgi_output) < 0) { + cannot_execute(client); + return; + } + if (pipe(cgi_input) < 0) { + cannot_execute(client); + return; + } + if ((pid = fork()) < 0) { + cannot_execute(client); + return; + } + if (pid == 0) { /* child: Add new rule */ + dup2(cgi_output[1], 1); + dup2(cgi_input[0], 0); + close(cgi_output[0]); + close(cgi_input[1]); + execv(path, param); + exit(0); + } else { /* parent */ + close(cgi_output[1]); + close(cgi_input[0]); + pos = 0; + while (read(cgi_output[0], &c, 1) > 0) + tmpbuf[pos++] = c; + tmpbuf[pos] = '\0'; + + /* Log Request */ + snprintf(log_msg_text, sizeof(log_msg_text), "IP: %s %s %s %s %s", \ + (char *)inet_ntoa(client_name.sin_addr), \ + gettext("Edit Rule:"),\ + (char *)delruleno, \ + gettext("is replaced with"),\ + (char *)tmpbuf); + log_msg(logfile, log_msg_text, 1); + + snprintf(buf, sizeof (buf)-1, "\n\n\n\ + \n\ + \n\ + netUstad\n", + server_sid, + (char *) gettext("charset")); + nunetwork_send(client, buf, strlen(buf), 0); + snprintf(buf, sizeof (buf)-1, "\n"); + nunetwork_send(client, buf, strlen(buf), 0); + snprintf(buf, sizeof (buf)-1, "
\n
%s
%s\n", + (char *) gettext("Edit Complete"), + (char *) gettext("Redirecting to Rule List")); + nunetwork_send(client, buf, strlen(buf), 0); + + + close(cgi_output[0]); + close(cgi_input[1]); + + waitpid(pid, &status, 0); + } +} diff --git a/pool/shard002/C/0057072_delete_child_sa_job.c b/pool/shard002/C/0057072_delete_child_sa_job.c new file mode 100644 index 0000000000000000000000000000000000000000..70dbc1b4aa121ece713915c69ddad4823453cb31 --- /dev/null +++ b/pool/shard002/C/0057072_delete_child_sa_job.c @@ -0,0 +1,111 @@ +/* + * Copyright (C) 2006 Martin Willi + * Hochschule fuer Technik Rapperswil + * + * 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. See . + * + * 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 "delete_child_sa_job.h" + +#include + + +typedef struct private_delete_child_sa_job_t private_delete_child_sa_job_t; + +/** + * Private data of an delete_child_sa_job_t object. + */ +struct private_delete_child_sa_job_t { + /** + + * Public delete_child_sa_job_t interface. + */ + delete_child_sa_job_t public; + + /** + * protocol of the CHILD_SA (ESP/AH) + */ + protocol_id_t protocol; + + /** + * inbound SPI of the CHILD_SA + */ + uint32_t spi; + + /** + * SA destination address + */ + host_t *dst; + + /** + * Delete for an expired CHILD_SA + */ + bool expired; +}; + +METHOD(job_t, destroy, void, + private_delete_child_sa_job_t *this) +{ + this->dst->destroy(this->dst); + free(this); +} + +METHOD(job_t, execute, job_requeue_t, + private_delete_child_sa_job_t *this) +{ + ike_sa_t *ike_sa; + + ike_sa = charon->child_sa_manager->checkout(charon->child_sa_manager, + this->protocol, this->spi, this->dst, NULL); + if (ike_sa == NULL) + { + DBG1(DBG_JOB, "CHILD_SA %N/0x%08x/%H not found for delete", + protocol_id_names, this->protocol, htonl(this->spi), this->dst); + } + else + { + ike_sa->delete_child_sa(ike_sa, this->protocol, this->spi, this->expired); + + charon->ike_sa_manager->checkin(charon->ike_sa_manager, ike_sa); + } + return JOB_REQUEUE_NONE; +} + +METHOD(job_t, get_priority, job_priority_t, + private_delete_child_sa_job_t *this) +{ + return JOB_PRIO_MEDIUM; +} + +/* + * Described in header + */ +delete_child_sa_job_t *delete_child_sa_job_create(protocol_id_t protocol, + uint32_t spi, host_t *dst, bool expired) +{ + private_delete_child_sa_job_t *this; + + INIT(this, + .public = { + .job_interface = { + .execute = _execute, + .get_priority = _get_priority, + .destroy = _destroy, + }, + }, + .protocol = protocol, + .spi = spi, + .dst = dst->clone(dst), + .expired = expired, + ); + + return &this->public; +} diff --git a/pool/shard002/C/0057079_admcli.c b/pool/shard002/C/0057079_admcli.c new file mode 100644 index 0000000000000000000000000000000000000000..54dcfb0e857722d2b4df9f98b33df28f418eb3da --- /dev/null +++ b/pool/shard002/C/0057079_admcli.c @@ -0,0 +1,207 @@ +/* + * Copyright (C) Actility, SA. All Rights Reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License version + * 2 only, 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 version 2 for more details (a copy is + * included at /legal/license.txt). + * + * You should have received a copy of the GNU General Public License + * version 2 along with this work; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA + * 02110-1301 USA + * + * Please contact Actility, SA., 4, rue Ampere 22300 LANNION FRANCE + * or visit www.actility.com if you need additional + * information or have any questions. + */ + +#include /************************************/ +#include /* run in main thread */ +#include /************************************/ +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +#include +#include +#include +#include +#include + +#include "rtlbase.h" +#include "rtllist.h" +#include "rtlimsg.h" + +#include "adaptor.h" + +#include "xoapipr.h" + +#include "define.h" + +#include "cmndefine.h" +#include "cmnstruct.h" +#include "cmnproto.h" + +#include "cproto.h" +#include "extern.h" +#include "dIa.h" +#include "covconfig.h" +#include "wmbus.h" + +#include "extension_library.h" +#include "extension_manager.h" + +extern t_cli *TbCli[]; +extern extensionManager_t *preprocessorMgmt; + +/** + * @brief Display the help message. + * @param cl the CLI session handler. + * + */ +void AdmUsage(t_cli *cl) +{ + AdmPrint(cl, "quit|exit - quit the telnet session.\n"); + AdmPrint(cl, "stop - shutdown the driver.\n"); + AdmPrint(cl, "who - display the list of active CLI connections.\n"); + AdmPrint(cl, "close - ends all CLI sessions.\n"); + AdmPrint(cl, "core - dump a core file of the current process.\n"); + AdmPrint(cl, "xoocc - display statistics on Xo usage.\n"); + + AdmPrint(cl, "trace [level] - display the trace level or change it.\n"); + AdmPrint(cl, "getvar [varname] - display the internal variable(s) values.\n"); + AdmPrint(cl, "setvar varname [value] - change the value of internal variable.\n"); + AdmPrint(cl, "addvar varname - add a new internal variable.\n"); + + AdmPrint(cl, "help - display this help message.\n"); + AdmPrint(cl, "info - display general information on driver state.\n"); + AdmPrint(cl, "covcfg - display the active COV configuration.\n"); + AdmPrint(cl, "extensionsInfo - display information related to extension libraries.\n"); +} + +/** + * @brief Format and display information regarding dirver usage (dIa stats, enabled options...). + * @param cl the CLI session handler. + */ +void AdmInfo(t_cli *cl) +{ + unsigned long vsize; + unsigned int nbm; + unsigned int nbt; + + vsize = rtl_vsize(getpid()); + + nbm = rtl_imsgVerifCount(MainIQ); + nbt = rtl_timerVerifCount(MainIQ); + + AdmPrint(cl, "vsize=%fMo (%u)\n", ((float)vsize) / 1024.0 / 1024.0, vsize); + AdmPrint(cl, "pseudoong=%d withdia=%d\n", PseudoOng, WithDia); + + AdmPrint(cl, "#msg=%d\n", nbm); + AdmPrint(cl, "#timer=%d\n", nbt); + AdmPrint(cl, "diapending=%u(%u)\n", DiaNbReqPending, DiaMaxReqPending); + AdmPrint(cl, "diasendcount=%u\n", DiaSendCount); + AdmPrint(cl, "diarecvcount=%u\n", DiaRecvCount); + AdmPrint(cl, "diatimecount=%u\n", DiaTimeCount); + AdmPrint(cl, "diadisconnect=%u\n", DiaDisconnected()); +} + +/** + * @brief Format and display information regarding loaded extension library and their usage. + * @param cl the CLI session handler. + */ +void AdmExtensionsInfo(t_cli *cl) +{ + char info[1024]; + preprocessorMgmt->dumpInfo(preprocessorMgmt, info, 1024); + AdmPrint(cl, "%s\n", info); +} + + +/** + * Do evaluate and run the "trace" CLI command. + * @param cl the CLI context. + * @param buf the entered command. + */ +void AdmTrace(t_cli *cl, char *buf) +{ + int v; + buf += 5; + buf = AdmAdvance(buf); + if (strlen(buf)) + { + v = atoi(buf); + TraceLevel = v; + rtl_tracelevel(TraceLevel); + } + AdmPrint(cl, "trace=%d debug=%d proto=%d\n", + TraceLevel, TraceDebug, TraceProto); +} + + +/** + * @brief Call back method for driver' specific CLI commands. + * @param cl the CLI session handler. + * @param pbuf the received command. + * @return CLI_PROMPT when the entered command is supported, CLI_NFOUND otherwise. + */ +int AdmCmd(t_cli *cl, char *pbuf) +{ + + char *buf = pbuf; + + if (!strlen(buf)) + { + return CLI_PROMPT; + } + + if (strcmp(buf, "help") == 0 || buf[0] == '?') + { + AdmUsage(cl); + return CLI_PROMPT; + } + + if (strcmp(buf, "info") == 0) + { + AdmInfo(cl); + return CLI_PROMPT; + } + + if (strncmp(buf, "trace", 5) == 0) + { + AdmTrace(cl, buf); + return CLI_PROMPT; + } + + if (strncmp(buf, "covcfg", 6) == 0) + { + CovToCzDump(cl, buf); + return CLI_PROMPT; + } + + if (strcmp(buf, "extensionsInfo") == 0) + { + AdmExtensionsInfo(cl); + return CLI_PROMPT; + } + + return CLI_NFOUND; +} + + diff --git a/pool/shard002/C/0057081_ctpl-test-lib.c b/pool/shard002/C/0057081_ctpl-test-lib.c new file mode 100644 index 0000000000000000000000000000000000000000..5ca094963abb2a8122f09625635de3b057444413 --- /dev/null +++ b/pool/shard002/C/0057081_ctpl-test-lib.c @@ -0,0 +1,56 @@ + +/* this file contains utility functions needed by more than one test */ + + +#include +#include +#include +#include + +#include "../src/ctpl.h" +#include "ctpl-test-lib.h" + + +/* parses a string with CTPL, returns the output, or %NULL on failure */ +gchar * +ctpltest_parse_string (const gchar *string, + const gchar *env_string, + GError **error) +{ + CtplEnviron *env; + CtplToken *tree; + gchar *output = NULL; + + env = ctpl_environ_new (); + if (ctpl_environ_add_from_string (env, env_string, error)) { + tree = ctpl_lexer_lex_string (string, error); + if (tree) { + GOutputStream *ostream; + CtplOutputStream *stream; + + ostream = g_memory_output_stream_new (NULL, 0, realloc, free); + stream = ctpl_output_stream_new (ostream); + if (ctpl_parser_parse (tree, env, stream, error)) { + gpointer p; + gsize size; + + p = g_memory_output_stream_get_data (G_MEMORY_OUTPUT_STREAM (ostream)); + #if GLIB_CHECK_VERSION (2, 18, 0) + size = g_memory_output_stream_get_data_size (G_MEMORY_OUTPUT_STREAM (ostream)); + #else + /* this is wrong but hope it's correct enough... */ + size = g_memory_output_stream_get_size (G_MEMORY_OUTPUT_STREAM (ostream)); + #endif + output = g_malloc (size + 1); + memcpy (output, p, size); + output[size] = 0; + } + g_object_unref (stream); + g_object_unref (ostream); + ctpl_token_free (tree); + } + } + ctpl_environ_unref (env); + + return output; +} diff --git a/pool/shard002/C/0057084_ft_list_push_back.c b/pool/shard002/C/0057084_ft_list_push_back.c new file mode 100644 index 0000000000000000000000000000000000000000..4ec92bc5024cad91456ee2a9d133a3872315b29e --- /dev/null +++ b/pool/shard002/C/0057084_ft_list_push_back.c @@ -0,0 +1,27 @@ +/* ************************************************************************** */ +/* */ +/* ::: :::::::: */ +/* ft_list_push_back.c :+: :+: :+: */ +/* +:+ +:+ +:+ */ +/* By: pgritsen +#+ +:+ +#+ */ +/* +#+#+#+#+#+ +#+ */ +/* Created: 2017/08/08 17:35:02 by pgritsen #+# #+# */ +/* Updated: 2017/08/08 17:35:03 by pgritsen ### ########.fr */ +/* */ +/* ************************************************************************** */ + +#include "ft_list.h" + +void ft_list_push_back(t_list **begin_list, void *data) +{ + if (*begin_list == 0) + { + *begin_list = ft_create_elem(data); + } + else + { + while (*begin_list) + begin_list = &(*begin_list)->next; + *begin_list = ft_create_elem(data); + } +} diff --git a/pool/shard002/C/0057088_file_utils_tests.c b/pool/shard002/C/0057088_file_utils_tests.c new file mode 100644 index 0000000000000000000000000000000000000000..a61b1f551d6370f4b9f868e97438592405f28c9e --- /dev/null +++ b/pool/shard002/C/0057088_file_utils_tests.c @@ -0,0 +1,39 @@ +#include "minunit.h" +#include +#include + +char *test_getlines() +{ + bstring str = bfromcstr("one\ntwo\nthree\nfour\nfive\n"); + struct bstrList *file = bsplit(str, '\n'); + + DArray *lines = getlines(file, 2, 4); + + bstring two = bfromcstr("two"); + bstring three = bfromcstr("three"); + bstring four = bfromcstr("four"); + + mu_assert(DArray_count(lines) == 3, "Wrong number of lines."); + mu_assert(bstrcmp((bstring)DArray_at(lines, 0), two) == 0, "First line is wrong."); + mu_assert(bstrcmp((bstring)DArray_at(lines, 1), three) == 0, "Second line is wrong."); + mu_assert(bstrcmp((bstring)DArray_at(lines, 2), four) == 0, "Third line is wrong."); + + bstrListDestroy(file); + bdestroy(str); + bdestroy(two); + bdestroy(three); + bdestroy(four); + DArray_destroy(lines); + + return NULL; +} + +char *all_tests() { + mu_suite_start(); + + mu_run_test(test_getlines); + + return NULL; +} + +RUN_TESTS(all_tests); diff --git a/pool/shard002/C/0057091_usbip_host_common.c b/pool/shard002/C/0057091_usbip_host_common.c new file mode 100644 index 0000000000000000000000000000000000000000..9d415228883deb286ec684d22a311940aae943a3 --- /dev/null +++ b/pool/shard002/C/0057091_usbip_host_common.c @@ -0,0 +1,273 @@ +/* + * Copyright (C) 2015-2016 Samsung Electronics + * Igor Kotrasinski + * Krzysztof Opasiak + * + * Refactored from usbip_host_driver.c, which is: + * Copyright (C) 2011 matt mooney + * 2005-2007 Takahiro Hirofuchi + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +#include +#include +#include + +#include +#include + +#include + +#include "usbip_common.h" +#include "usbip_host_common.h" +#include "list.h" +#include "sysfs_utils.h" + +struct udev *udev_context; + +static int32_t read_attr_usbip_status(struct usbip_usb_device *udev) +{ + char status_attr_path[SYSFS_PATH_MAX]; + int fd; + int length; + char status; + int value = 0; + + snprintf(status_attr_path, SYSFS_PATH_MAX, "%s/usbip_status", + udev->path); + + fd = open(status_attr_path, O_RDONLY); + if (fd < 0) { + err("error opening attribute %s", status_attr_path); + return -1; + } + + length = read(fd, &status, 1); + if (length < 0) { + err("error reading attribute %s", status_attr_path); + close(fd); + return -1; + } + + value = atoi(&status); + + return value; +} + +static +struct usbip_exported_device *usbip_exported_device_new( + struct usbip_host_driver *hdriver, const char *sdevpath) +{ + struct usbip_exported_device *edev = NULL; + struct usbip_exported_device *edev_old; + size_t size; + int i; + + edev = calloc(1, sizeof(struct usbip_exported_device)); + + edev->sudev = + udev_device_new_from_syspath(udev_context, sdevpath); + if (!edev->sudev) { + err("udev_device_new_from_syspath: %s", sdevpath); + goto err; + } + + if (hdriver->ops.read_device(edev->sudev, &edev->udev) < 0) + goto err; + + edev->status = read_attr_usbip_status(&edev->udev); + if (edev->status < 0) + goto err; + + /* reallocate buffer to include usb interface data */ + size = sizeof(struct usbip_exported_device) + + edev->udev.bNumInterfaces * sizeof(struct usbip_usb_interface); + + edev_old = edev; + edev = realloc(edev, size); + if (!edev) { + edev = edev_old; + dbg("realloc failed"); + goto err; + } + + for (i = 0; i < edev->udev.bNumInterfaces; i++) { + /* vudc does not support reading interfaces */ + if (!hdriver->ops.read_interface) + break; + hdriver->ops.read_interface(&edev->udev, i, &edev->uinf[i]); + } + + return edev; +err: + if (edev->sudev) + udev_device_unref(edev->sudev); + if (edev) + free(edev); + + return NULL; +} + +static int refresh_exported_devices(struct usbip_host_driver *hdriver) +{ + struct usbip_exported_device *edev; + struct udev_enumerate *enumerate; + struct udev_list_entry *devices, *dev_list_entry; + struct udev_device *dev; + const char *path; + + enumerate = udev_enumerate_new(udev_context); + udev_enumerate_add_match_subsystem(enumerate, hdriver->udev_subsystem); + udev_enumerate_scan_devices(enumerate); + + devices = udev_enumerate_get_list_entry(enumerate); + + udev_list_entry_foreach(dev_list_entry, devices) { + path = udev_list_entry_get_name(dev_list_entry); + dev = udev_device_new_from_syspath(udev_context, + path); + if (dev == NULL) + continue; + + /* Check whether device uses usbip driver. */ + if (hdriver->ops.is_my_device(dev)) { + edev = usbip_exported_device_new(hdriver, path); + if (!edev) { + dbg("usbip_exported_device_new failed"); + continue; + } + + list_add(&edev->node, &hdriver->edev_list); + hdriver->ndevs++; + } + } + + return 0; +} + +static void usbip_exported_device_destroy(struct list_head *devs) +{ + struct list_head *i, *tmp; + struct usbip_exported_device *edev; + + list_for_each_safe(i, tmp, devs) { + edev = list_entry(i, struct usbip_exported_device, node); + list_del(i); + free(edev); + } +} + +int usbip_generic_driver_open(struct usbip_host_driver *hdriver) +{ + int rc; + + udev_context = udev_new(); + if (!udev_context) { + err("udev_new failed"); + return -1; + } + + rc = refresh_exported_devices(hdriver); + if (rc < 0) + goto err; + return 0; +err: + udev_unref(udev_context); + return -1; +} + +void usbip_generic_driver_close(struct usbip_host_driver *hdriver) +{ + if (!hdriver) + return; + + usbip_exported_device_destroy(&hdriver->edev_list); + + udev_unref(udev_context); +} + +int usbip_generic_refresh_device_list(struct usbip_host_driver *hdriver) +{ + int rc; + + usbip_exported_device_destroy(&hdriver->edev_list); + + hdriver->ndevs = 0; + INIT_LIST_HEAD(&hdriver->edev_list); + + rc = refresh_exported_devices(hdriver); + if (rc < 0) + return -1; + + return 0; +} + +int usbip_export_device(struct usbip_exported_device *edev, int sockfd) +{ + char attr_name[] = "usbip_sockfd"; + char sockfd_attr_path[SYSFS_PATH_MAX]; + char sockfd_buff[30]; + int ret; + + if (edev->status != SDEV_ST_AVAILABLE) { + dbg("device not available: %s", edev->udev.busid); + switch (edev->status) { + case SDEV_ST_ERROR: + dbg("status SDEV_ST_ERROR"); + break; + case SDEV_ST_USED: + dbg("status SDEV_ST_USED"); + break; + default: + dbg("status unknown: 0x%x", edev->status); + } + return -1; + } + + /* only the first interface is true */ + snprintf(sockfd_attr_path, sizeof(sockfd_attr_path), "%s/%s", + edev->udev.path, attr_name); + + snprintf(sockfd_buff, sizeof(sockfd_buff), "%d\n", sockfd); + + ret = write_sysfs_attribute(sockfd_attr_path, sockfd_buff, + strlen(sockfd_buff)); + if (ret < 0) { + err("write_sysfs_attribute failed: sockfd %s to %s", + sockfd_buff, sockfd_attr_path); + return ret; + } + + info("connect: %s", edev->udev.busid); + + return ret; +} + +struct usbip_exported_device *usbip_generic_get_device( + struct usbip_host_driver *hdriver, int num) +{ + struct list_head *i; + struct usbip_exported_device *edev; + int cnt = 0; + + list_for_each(i, &hdriver->edev_list) { + edev = list_entry(i, struct usbip_exported_device, node); + if (num == cnt) + return edev; + cnt++; + } + + return NULL; +} diff --git a/pool/shard002/C/0057104_t1_block.c b/pool/shard002/C/0057104_t1_block.c new file mode 100644 index 0000000000000000000000000000000000000000..60ad6469b02390358bbbd3738088c70bb3b8592d --- /dev/null +++ b/pool/shard002/C/0057104_t1_block.c @@ -0,0 +1,249 @@ +/* + t1_block.h + T=1 block abstract data type implementation + + This file is part of the Unix driver for Towitoko smartcard readers + Copyright (C) 2000 Carlos Prados + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +*/ + +#include "t1_block.h" +#include +#include + +/* + * Not exported constants definition + */ + +#define T1_BLOCK_NAD 0x00 + +/* + * Not exported functions declaration + */ +static BYTE +T1_Block_LRC (BYTE * data, unsigned length); + +/* + * Exported functions definition + */ + +T1_Block * +T1_Block_New (BYTE * buffer, unsigned length) +{ + T1_Block * block; + + if (length < 4) + return NULL; + + block = (T1_Block *) malloc (sizeof (T1_Block)); + + if (block != NULL) + { + block->length = MIN(length, T1_BLOCK_MAX_SIZE); + block->data = (BYTE *) calloc (block->length, sizeof (BYTE)); + + if (block->data != NULL) + { + memcpy (block->data, buffer, block->length); + } + else + { + free (block); + block = NULL; + } + } + + return block; +} + +T1_Block * +T1_Block_NewIBlock (BYTE len, BYTE * inf, BYTE ns, bool more) +{ + T1_Block * block; + + block = (T1_Block *) malloc (sizeof (T1_Block)); + + if (block != NULL) + { + block->length = len + 4; + block->data = (BYTE *) calloc (block->length, sizeof (BYTE)); + + if (block->data != NULL) + { + block->data[0] = T1_BLOCK_NAD; + block->data[1] = T1_BLOCK_I | ((ns << 6) & 0x40); + + if (more) + block->data[1] |= 0x20; + + block->data[2] = len; + + if (len != 0x00) + memcpy (block->data + 3, inf, len); + + block->data[len+3] = T1_Block_LRC (block->data, len+3); + } + else + { + free (block); + block = NULL; + } + } + + return block; +} + +T1_Block * +T1_Block_NewRBlock (BYTE type, BYTE nr) +{ + T1_Block * block; + + block = (T1_Block *) malloc (sizeof (T1_Block)); + + if (block != NULL) + { + block->length = 4; + block->data = (BYTE *) calloc (block->length, sizeof (BYTE)); + + if (block->data != NULL) + { + block->data[0] = T1_BLOCK_NAD; + block->data[1] = type | ((nr << 4) & 0x10); + block->data[2] = 0x00; + block->data[3] = T1_Block_LRC (block->data, 3); + } + else + { + free (block); + block = NULL; + } + } + + return block; +} + +T1_Block * +T1_Block_NewSBlock (BYTE type, BYTE len, BYTE * inf) +{ + T1_Block * block; + + block = (T1_Block *) malloc (sizeof (T1_Block)); + + if (block != NULL) + { + block->length = 4 + len; + block->data = (BYTE *) calloc (block->length, sizeof (BYTE)); + + if (block->data != NULL) + { + block->data[0] = T1_BLOCK_NAD; + block->data[1] = type; + block->data[2] = len; + + if (len != 0x00) + memcpy (block->data + 3, inf, len); + + block->data[len+3] = T1_Block_LRC (block->data, len+3); + } + else + { + free (block); + block = NULL; + } + } + + return block; +} + +BYTE +T1_Block_GetType (T1_Block * block) +{ + if ((block->data[1] & 0x80) == T1_BLOCK_I) + return T1_BLOCK_I; + + return (block->data[1] & 0xEF); +} + +BYTE +T1_Block_GetNS (T1_Block * block) +{ + return ((block->data[1] >> 6)& 0x01); +} + +bool +T1_Block_GetMore (T1_Block * block) +{ + return ((block->data[1] >> 5) & 0x01); +} + +BYTE +T1_Block_GetNR (T1_Block * block) +{ + return ((block->data[1] >> 4) & 0x01); +} + +BYTE +T1_Block_GetLen (T1_Block * block) +{ + return block->data[2]; +} + +BYTE * +T1_Block_GetInf (T1_Block * block) +{ + if (block->length < 5) + return NULL; + + return block->data + 3; +} + +BYTE * +T1_Block_Raw (T1_Block * block) +{ + return block->data; +} + +unsigned +T1_Block_RawLen (T1_Block * block) +{ + return block->length; +} + +void +T1_Block_Delete (T1_Block * block) +{ + free (block->data); + free (block); +} + +/* + * Not exported functions definition + */ + +static BYTE +T1_Block_LRC (BYTE * data, unsigned length) +{ + BYTE lrc; + unsigned i; + + lrc = 0x00; + for (i = 0; i < length; i++) + { + lrc ^= data[i]; + } + + return lrc; +} diff --git a/pool/shard002/C/0057107_log_limit.c b/pool/shard002/C/0057107_log_limit.c new file mode 100644 index 0000000000000000000000000000000000000000..7992e13a4597462984951d89e976f688ffd6bf2a --- /dev/null +++ b/pool/shard002/C/0057107_log_limit.c @@ -0,0 +1,65 @@ +/** + * Copyright (c) 2014, Facebook, Inc. + * All rights reserved. + * + * This source code is licensed under the BSD-style license found in the + * LICENSE file in the root directory of this source tree. An additional grant + * of patent rights can be found in the PATENTS file in the same directory. + */ +#include "log_limit.h" + +#include + +static int cycle = 0; +static struct timeval *queue = NULL; +static int head = 0, tail = 0, count = 0; + +int set_log_limit(int max_log_num, int cycle_sec) { + if (max_log_num <= 0 || cycle_sec <= 0) { // invalid parameter + return -1; + } + + cycle = cycle_sec; + head = 0; + tail = 0; + count = max_log_num + 1; + + if(queue != NULL) { + free(queue); + } + queue = malloc(sizeof(struct timeval) * count); + if(queue == NULL) { + return -1; + } + + return 0; +} + +int check_log_limit(const struct timeval *now) { + if (cycle == 0 || queue == NULL) { // no limit + return 0; + } + + struct timeval one_cycle_ago = *now; + one_cycle_ago.tv_sec -= cycle; + + while (head != tail) { + if (queue[head].tv_sec > one_cycle_ago.tv_sec) { + break; + } + if (queue[head].tv_sec == one_cycle_ago.tv_sec && + queue[head].tv_usec > one_cycle_ago.tv_usec) { + break; + } + + head = (head + 1) % count; + } + + if ((tail + 1) % count == head) { // hit limit + return 1; + } + + queue[tail] = *now; + tail = (tail + 1) % count; + return 0; +} diff --git a/pool/shard002/C/0057121_CWE78_OS_Command_Injection__char_connect_socket_w32_spawnlp_15.c b/pool/shard002/C/0057121_CWE78_OS_Command_Injection__char_connect_socket_w32_spawnlp_15.c new file mode 100644 index 0000000000000000000000000000000000000000..86e525510566508faba219b21e8ab316ba9ac5e0 --- /dev/null +++ b/pool/shard002/C/0057121_CWE78_OS_Command_Injection__char_connect_socket_w32_spawnlp_15.c @@ -0,0 +1,230 @@ +/* TEMPLATE GENERATED TESTCASE FILE +Filename: CWE78_OS_Command_Injection__char_connect_socket_w32_spawnlp_15.c +Label Definition File: CWE78_OS_Command_Injection.strings.label.xml +Template File: sources-sink-15.tmpl.c +*/ +/* + * @description + * CWE: 78 OS Command Injection + * BadSource: connect_socket Read data using a connect socket (client side) + * GoodSource: Fixed string + * Sink: w32_spawnlp + * BadSink : execute command with spawnlp + * Flow Variant: 15 Control flow: switch(6) + * + * */ + +#include "std_testcase.h" + +#include + +#ifdef _WIN32 +#define COMMAND_INT_PATH "%WINDIR%\\system32\\cmd.exe" +#define COMMAND_INT "cmd.exe" +#define COMMAND_ARG1 "/c" +#define COMMAND_ARG2 "dir" +#define COMMAND_ARG3 data +#else /* NOT _WIN32 */ +#include +#define COMMAND_INT_PATH "/bin/sh" +#define COMMAND_INT "sh" +#define COMMAND_ARG1 "ls" +#define COMMAND_ARG2 "-la" +#define COMMAND_ARG3 data +#endif + +#ifdef _WIN32 +#include +#include +#include +#pragma comment(lib, "ws2_32") /* include ws2_32.lib when linking */ +#define CLOSE_SOCKET closesocket +#else /* NOT _WIN32 */ +#include +#include +#include +#include +#define INVALID_SOCKET -1 +#define SOCKET_ERROR -1 +#define CLOSE_SOCKET close +#define SOCKET int +#endif + +#define TCP_PORT 27015 +#define IP_ADDRESS "127.0.0.1" + +#include + +#ifndef OMITBAD + +void CWE78_OS_Command_Injection__char_connect_socket_w32_spawnlp_15_bad() +{ + char * data; + char dataBuffer[100] = ""; + data = dataBuffer; + switch(6) + { + case 6: + { +#ifdef _WIN32 + WSADATA wsaData; + int wsaDataInit = 0; +#endif + int recvResult; + struct sockaddr_in service; + char *replace; + SOCKET connectSocket = INVALID_SOCKET; + size_t dataLen = strlen(data); + do + { +#ifdef _WIN32 + if (WSAStartup(MAKEWORD(2,2), &wsaData) != NO_ERROR) + { + break; + } + wsaDataInit = 1; +#endif + /* POTENTIAL FLAW: Read data using a connect socket */ + connectSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); + if (connectSocket == INVALID_SOCKET) + { + break; + } + memset(&service, 0, sizeof(service)); + service.sin_family = AF_INET; + service.sin_addr.s_addr = inet_addr(IP_ADDRESS); + service.sin_port = htons(TCP_PORT); + if (connect(connectSocket, (struct sockaddr*)&service, sizeof(service)) == SOCKET_ERROR) + { + break; + } + /* Abort on error or the connection was closed, make sure to recv one + * less char than is in the recv_buf in order to append a terminator */ + /* Abort on error or the connection was closed */ + recvResult = recv(connectSocket, (char *)(data + dataLen), sizeof(char) * (100 - dataLen - 1), 0); + if (recvResult == SOCKET_ERROR || recvResult == 0) + { + break; + } + /* Append null terminator */ + data[dataLen + recvResult / sizeof(char)] = '\0'; + /* Eliminate CRLF */ + replace = strchr(data, '\r'); + if (replace) + { + *replace = '\0'; + } + replace = strchr(data, '\n'); + if (replace) + { + *replace = '\0'; + } + } + while (0); + if (connectSocket != INVALID_SOCKET) + { + CLOSE_SOCKET(connectSocket); + } +#ifdef _WIN32 + if (wsaDataInit) + { + WSACleanup(); + } +#endif + } + break; + default: + /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */ + printLine("Benign, fixed string"); + break; + } + /* spawnlp - 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 */ + _spawnlp(_P_WAIT, COMMAND_INT, COMMAND_INT, COMMAND_ARG1, COMMAND_ARG2, COMMAND_ARG3, NULL); +} + +#endif /* OMITBAD */ + +#ifndef OMITGOOD + +/* goodG2B1() - use goodsource and badsink by changing the switch to switch(5) */ +static void goodG2B1() +{ + char * data; + char dataBuffer[100] = ""; + data = dataBuffer; + switch(5) + { + case 6: + /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */ + printLine("Benign, fixed string"); + break; + default: + /* FIX: Append a fixed string to data (not user / external input) */ + strcat(data, "*.*"); + break; + } + /* spawnlp - 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 */ + _spawnlp(_P_WAIT, COMMAND_INT, COMMAND_INT, COMMAND_ARG1, COMMAND_ARG2, COMMAND_ARG3, NULL); +} + +/* goodG2B2() - use goodsource and badsink by reversing the blocks in the switch */ +static void goodG2B2() +{ + char * data; + char dataBuffer[100] = ""; + data = dataBuffer; + switch(6) + { + case 6: + /* FIX: Append a fixed string to data (not user / external input) */ + strcat(data, "*.*"); + break; + default: + /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */ + printLine("Benign, fixed string"); + break; + } + /* spawnlp - 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 */ + _spawnlp(_P_WAIT, COMMAND_INT, COMMAND_INT, COMMAND_ARG1, COMMAND_ARG2, COMMAND_ARG3, NULL); +} + +void CWE78_OS_Command_Injection__char_connect_socket_w32_spawnlp_15_good() +{ + goodG2B1(); + goodG2B2(); +} + +#endif /* OMITGOOD */ + +/* Below is the main(). It is only used when building this testcase on + * its own for testing or for building a binary to use in testing binary + * analysis tools. It is not used when compiling all the testcases as one + * application, which is how source code analysis tools are tested. + */ + +#ifdef INCLUDEMAIN + +int main(int argc, char * argv[]) +{ + /* seed randomness */ + srand( (unsigned)time(NULL) ); +#ifndef OMITGOOD + printLine("Calling good()..."); + CWE78_OS_Command_Injection__char_connect_socket_w32_spawnlp_15_good(); + printLine("Finished good()"); +#endif /* OMITGOOD */ +#ifndef OMITBAD + printLine("Calling bad()..."); + CWE78_OS_Command_Injection__char_connect_socket_w32_spawnlp_15_bad(); + printLine("Finished bad()"); +#endif /* OMITBAD */ + return 0; +} + +#endif diff --git a/pool/shard002/C/0057133_multi3.c b/pool/shard002/C/0057133_multi3.c new file mode 100644 index 0000000000000000000000000000000000000000..4c2483f410c26b5b65ded652c1b0694b06a9bf92 --- /dev/null +++ b/pool/shard002/C/0057133_multi3.c @@ -0,0 +1,54 @@ +// SPDX-License-Identifier: GPL-2.0 +#include + +#include "libgcc.h" + +/* + * GCC 7 & older can suboptimally generate __multi3 calls for mips64r6, so for + * that specific case only we implement that intrinsic here. + * + * See https://gcc.gnu.org/bugzilla/show_bug.cgi?id=82981 + */ +#if defined(CONFIG_64BIT) && defined(CONFIG_CPU_MIPSR6) && (__GNUC__ < 8) + +/* multiply 64-bit values, low 64-bits returned */ +static inline long long notrace dmulu(long long a, long long b) +{ + long long res; + + asm ("dmulu %0,%1,%2" : "=r" (res) : "r" (a), "r" (b)); + return res; +} + +/* multiply 64-bit unsigned values, high 64-bits of 128-bit result returned */ +static inline long long notrace dmuhu(long long a, long long b) +{ + long long res; + + asm ("dmuhu %0,%1,%2" : "=r" (res) : "r" (a), "r" (b)); + return res; +} + +/* multiply 128-bit values, low 128-bits returned */ +ti_type notrace __multi3(ti_type a, ti_type b) +{ + TWunion res, aa, bb; + + aa.ti = a; + bb.ti = b; + + /* + * a * b = (a.lo * b.lo) + * + 2^64 * (a.hi * b.lo + a.lo * b.hi) + * [+ 2^128 * (a.hi * b.hi)] + */ + res.s.low = dmulu(aa.s.low, bb.s.low); + res.s.high = dmuhu(aa.s.low, bb.s.low); + res.s.high += dmulu(aa.s.high, bb.s.low); + res.s.high += dmulu(aa.s.low, bb.s.high); + + return res.ti; +} +EXPORT_SYMBOL(__multi3); + +#endif /* 64BIT && CPU_MIPSR6 && GCC7 */ diff --git a/pool/shard002/C/0057138_tz_geo3d_ball.c b/pool/shard002/C/0057138_tz_geo3d_ball.c new file mode 100644 index 0000000000000000000000000000000000000000..6cf14544d6795a39df29746615cfe1300a01a999 --- /dev/null +++ b/pool/shard002/C/0057138_tz_geo3d_ball.c @@ -0,0 +1,210 @@ +#include +#include +#include +#include +#include +#include +#include "tz_geo3d_ball.h" +#include "tz_error.h" +#include "tz_math.h" +#include "tz_arrayview.h" +#include "tz_cuboid_i.h" +#include "tz_stack_attribute.h" + +#include "private/tzp_geo3d_ball.c" + +Geo3d_Ball* New_Geo3d_Ball() +{ + Geo3d_Ball *ball = + (Geo3d_Ball *) Guarded_Malloc(sizeof(Geo3d_Ball), "New_Geo3d_Ball"); + + return ball; +} + +void Delete_Geo3d_Ball(Geo3d_Ball *ball) +{ + free(ball); +} + +void Kill_Geo3d_Ball(Geo3d_Ball *ball) +{ + Delete_Geo3d_Ball(ball); +} + +void Geo3d_Ball_Default(Geo3d_Ball *ball) +{ + ball->r = 1.0; + ball->center[0] = 0.0; + ball->center[1] = 0.0; + ball->center[2] = 0.0; +} + +void Geo3d_Ball_Copy(Geo3d_Ball *dst, const Geo3d_Ball *src) +{ + memcpy(dst, src, sizeof(Geo3d_Ball)); +} + +Geo3d_Ball* Copy_Geo3d_Ball(Geo3d_Ball *src) +{ + Geo3d_Ball *ball = New_Geo3d_Ball(); + memcpy(ball, src, sizeof(Geo3d_Ball)); + + return ball; +} + +void Print_Geo3d_Ball(const Geo3d_Ball *ball) +{ + printf("3D ball: radius (%g) position(%g %g %g)\n", + ball->r, ball->center[0], ball->center[1], ball->center[2]); +} + +void Geo3d_Ball_Draw_Stack(const Geo3d_Ball *ball, Stack *stack, + const Stack_Draw_Workspace *ws) +{ + TZ_ASSERT(stack->kind == COLOR, "Invalid stack kind"); + + int z; + int zmin = imax2((int) ((ball->center[2] - ball->r) * ws->z_scale), 0); + int zmax = imin2((int) ((ball->center[2] + ball->r) * ws->z_scale), + stack->depth - 1); + + Paint_Brush brush; + switch (ws->color_mode) { + case 0: + brush.red = 1.0; + brush.green = 0.0; + brush.blue = 0.0; + break; + case 1: + brush.red = (double) ws->color.r / 255.0; + brush.green = (double) ws->color.g / 255.0; + brush.blue = (double) ws->color.b / 255.0; + break; + case 2: + { + Rgb_Color color; + Set_Color_Hsv(&color, ws->h, ws->s, ws->v); + brush.red = (double) color.r / 255.0; + brush.green = (double) color.g / 255.0; + brush.blue = (double) color.b / 255.0; + } + break; + default: + TZ_ERROR(ERROR_DATA_VALUE); + } + + brush.op = (Pixel_Op)ws->blend_mode; + + for (z = zmin; z <= zmax; z++) { + double h = (double) z / ws->z_scale - ball->center[2]; + double r = sqrt(ball->r * ball->r - h * h); + Image canvas = Image_View_Stack_Slice(stack, z); + Draw_Circle(iround(ball->center[0]), iround(ball->center[1]), iround(r), + &brush, &(canvas)); + } +} + + +Geo3d_Scalar_Field* Geo3d_Ball_Field(const Geo3d_Ball *ball, + Geo3d_Scalar_Field *field) +{ + if (field == NULL) { + field = Make_Geo3d_Scalar_Field(GEO3D_BALL_FIELD_SIZE); + } + + geo3d_ball_field_u(field); + int i; + for (i = 0; i < GEO3D_BALL_FIELD_SIZE; i++) { + field->points[i][0] *= ball->r; + field->points[i][1] *= ball->r; + field->points[i][2] *= ball->r; + + field->points[i][0] += ball->center[0]; + field->points[i][1] += ball->center[1]; + field->points[i][2] += ball->center[2]; + } + + return field; +} + +#define GEO3D_BALL_MEAN_SHIFT_EPS 0.01 + +void Geo3d_Ball_Mean_Shift(Geo3d_Ball *ball, Stack *stack, double z_scale, + double min_shift) +{ + coordinate_3d_t old_center; + Coordinate_3d_Copy(old_center, ball->center); + + int check_count = 5; + int count = 0; + double eps = 1.0; + + Geo3d_Scalar_Field *field = Geo3d_Ball_Field(ball, NULL); + while (eps > min_shift) { + Geo3d_Scalar_Field_Stack_Sampling(field, stack, z_scale, field->values); + Geo3d_Scalar_Field_Centroid(field, ball->center); + Geo3d_Ball_Field(ball, field); + count++; + if (count > check_count) { + count = 0; + eps = Coordinate_3d_Distance(old_center, ball->center); + Coordinate_3d_Copy(old_center, ball->center); + } + } + Kill_Geo3d_Scalar_Field(field); +} + +void Geo3d_Ball_Label_Stack(const Geo3d_Ball *ball, Stack *stack, + Geo3d_Ball_Label_Workspace *ws) +{ + Cuboid_I cuboid; + + int i; + for (i = 0; i < 3; ++i) { + cuboid.cb[i] = imax2(0, (int) ceil(ball->center[i] - ball->r)); + cuboid.ce[i] = floor(ball->center[i] + ball->r); + } + int width = Stack_Width(stack); + int height = Stack_Height(stack); + int depth = Stack_Depth(stack); + + cuboid.ce[0] = imin2(cuboid.ce[0], width - 1); + cuboid.ce[1] = imin2(cuboid.ce[1], height - 1); + cuboid.ce[2] = imin2(cuboid.ce[2], depth - 1); + + int j, k; + /* + size_t offset = cuboid.cb[0]; + */ + /* + offset = Stack_Util_Offset(cuboid.cb[0], cuboid.cb[1], cuboid.cb[2], + width, height, depth); + + int p2 = width - cuboid.ce[0] + cuboid.cb[0]; + int p3 = p2 + width * height - width * (cuboid.ce[1] - cuboid.ce[1] + 1); +*/ + for (k = cuboid.cb[2]; k <= cuboid.ce[2]; ++k) { + for (j = cuboid.cb[1]; j <= cuboid.ce[1]; ++j) { + for (i = cuboid.cb[0]; i <= cuboid.ce[0]; ++i) { + double dx = (double) i - ball->center[0]; + double dy = (double) j - ball->center[1]; + double dz = (double) k - ball->center[2]; + if (dx * dx + dy * dy + dz * dz <= ball->r * ball->r) { + Set_Stack_Pixel(stack, i, j, k, 0, ws->sdw.color.r); + if (Stack_Kind(stack) == COLOR) { + Set_Stack_Pixel(stack, i, j, k, 1, ws->sdw.color.g); + Set_Stack_Pixel(stack, i, j, k, 2, ws->sdw.color.b); + } + } + //++offset; + } + //offset += p2; + } + //offset += p3; + } +} + +void Default_Geo3d_Ball_Label_Workspace(Geo3d_Ball_Label_Workspace *ws) +{ + Default_Stack_Draw_Workspace(&(ws->sdw)); +} diff --git a/pool/shard002/C/0057139_compress.c b/pool/shard002/C/0057139_compress.c new file mode 100644 index 0000000000000000000000000000000000000000..9dbf1982fa4edd92bf0be48da3b4f8f82883462a --- /dev/null +++ b/pool/shard002/C/0057139_compress.c @@ -0,0 +1,80 @@ +/* compress.c -- compress a memory buffer + * Copyright (C) 1995-2005 Jean-loup Gailly. + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +/* @(#) $Id$ */ + +#define ZLIB_INTERNAL +#include "XMZlib/zlib.h" + +/* =========================================================================== + Compresses the source buffer into the destination buffer. The level + parameter has the same meaning as in deflateInit. sourceLen is the byte + length of the source buffer. Upon entry, destLen is the total size of the + destination buffer, which must be at least 0.1% larger than sourceLen plus + 12 bytes. Upon exit, destLen is the actual size of the compressed buffer. + + compress2 returns Z_OK if success, Z_MEM_ERROR if there was not enough + memory, Z_BUF_ERROR if there was not enough room in the output buffer, + Z_STREAM_ERROR if the level parameter is invalid. +*/ +int ZEXPORT compress2 ( + Bytef *dest, + uLongf *destLen, + const Bytef *source, + uLong sourceLen, + int level) +{ + z_stream stream; + int err; + + stream.next_in = (Bytef*)source; + stream.avail_in = (uInt)sourceLen; +#ifdef MAXSEG_64K + /* Check for source > 64K on 16-bit machine: */ + if ((uLong)stream.avail_in != sourceLen) return Z_BUF_ERROR; +#endif + stream.next_out = dest; + stream.avail_out = (uInt)*destLen; + if ((uLong)stream.avail_out != *destLen) return Z_BUF_ERROR; + + stream.zalloc = (alloc_func)0; + stream.zfree = (free_func)0; + stream.opaque = (voidpf)0; + + err = deflateInit(&stream, level); + if (err != Z_OK) return err; + + err = deflate(&stream, Z_FINISH); + if (err != Z_STREAM_END) { + deflateEnd(&stream); + return err == Z_OK ? Z_BUF_ERROR : err; + } + *destLen = stream.total_out; + + err = deflateEnd(&stream); + return err; +} + +/* =========================================================================== + */ +int ZEXPORT compress ( + Bytef *dest, + uLongf *destLen, + const Bytef *source, + uLong sourceLen) +{ + return compress2(dest, destLen, source, sourceLen, Z_DEFAULT_COMPRESSION); +} + +/* =========================================================================== + If the default memLevel or windowBits for deflateInit() is changed, then + this function needs to be updated. + */ +uLong ZEXPORT compressBound ( + uLong sourceLen) +{ + return sourceLen + (sourceLen >> 12) + (sourceLen >> 14) + + (sourceLen >> 25) + 13; +} diff --git a/pool/shard002/C/0057144_canny.c b/pool/shard002/C/0057144_canny.c new file mode 100644 index 0000000000000000000000000000000000000000..5787320c59dcd378d2b94239cf8192fabc08a238 --- /dev/null +++ b/pool/shard002/C/0057144_canny.c @@ -0,0 +1,234 @@ +/* + canny.c: Copyright (C) 2013 Oka Motofumi + + Author: Oka Motofumi (chikuzen.mo at gmail dot com) + + This file is part of GenericFilters. + + 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; 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 + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with the author; if not, write to the Free Software + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA +*/ + +#include +#include + +#define USE_ALIGNED_MALLOC +#include "common.h" +#include "canny.h" + + +static canny_stack *create_stack(int size) +{ + canny_stack *s = (canny_stack *)malloc(sizeof(canny_stack)); + if (!s) { + return NULL; + } + s->pos = (int32_t *)malloc(size * sizeof(int32_t)); + if (!s->pos) { + free(s); + return NULL; + } + s->map = (uint8_t *)malloc(size); + if (!s->map) { + free(s->pos); + free(s); + return NULL; + } + return s; +} + + +static void free_stack(canny_stack *s) +{ + if(!s) { + return; + } + free(s->pos); + s->pos = NULL; + free(s->map); + s->map = NULL; + free(s); + s = NULL; +} + + +static void VS_CC +canny_get_frame(generic_handler_t *gh, const VSFormat *fi, const VSFrameRef **fr, + const VSAPI *vsapi, const VSFrameRef *src, VSFrameRef *dst) +{ + canny_t *ch = gh->fdata; + + int fwidth = vsapi->getFrameWidth(src, 0); + int fheight = vsapi->getFrameHeight(src, 0); + int fstride = ((fwidth + 15) / 16) * 16; + int bstride = ((fwidth + 32 + 15) / 16) * 16; + + float *blur = (float *)_aligned_malloc(fstride * fheight * sizeof(float), 16); + float *edge = (float *)_aligned_malloc(fstride * fheight * sizeof(float), 16); + uint8_t *direction = (uint8_t *)_aligned_malloc(fstride * fheight, 16); + float *buff = (float *)_aligned_malloc(bstride * sizeof(float) * 3, 16); + canny_stack *stack = create_stack(fwidth * fheight); + + if (!blur || !buff || !edge || !direction || !stack) { + goto close_canny; + } + + int idx = fi->bytesPerSample - 1; + + for (int plane = 0; plane < fi->numPlanes; plane++) { + if (fr[plane]) { + continue; + } + + int width = vsapi->getFrameWidth(src, plane); + int height = vsapi->getFrameHeight(src, plane); + int stride = vsapi->getStride(src, plane); + const uint8_t *srcp = vsapi->getReadPtr(src, plane); + uint8_t *dstp = vsapi->getWritePtr(dst, plane); + if (width < 16 || height < 16) { + continue; + } + + ch->gaussian_blur[idx](ch->radius, ch->kernel, srcp, buff + 8, blur, + width, height, stride, fstride); + + edge_detect(buff + 8, bstride, blur, edge, direction, width, height, + fstride); + + non_max_suppress(edge, blur, direction, width, height, fstride); + + hysteresis(blur, width, height, fstride, ch->th, ch->tl, stack); + + write_dst_canny[idx](blur, dstp, width, height, fstride, stride, ch->th, + fi->bitsPerSample); + + } + +close_canny: + _aligned_free(blur); + _aligned_free(edge); + _aligned_free(direction); + _aligned_free(buff); + free_stack(stack); +} + + +static void VS_CC +gblur_get_frame(generic_handler_t *gh, const VSFormat *fi, const VSFrameRef **fr, + const VSAPI *vsapi, const VSFrameRef *src, VSFrameRef *dst) +{ + canny_t *ch = gh->fdata; + + int fwidth = vsapi->getFrameWidth(src, 0); + int fheight = vsapi->getFrameHeight(src, 0); + int fstride = ((fwidth + 15) / 16) * 16; + int bstride = ((fwidth + 32 + 15) / 16) * 16; + + float *blur = (float *)_aligned_malloc(fstride * fheight * sizeof(float), 16); + float *buff = (float *)_aligned_malloc(bstride * sizeof(float), 16); + + if (!blur || !buff) { + goto close_gblur; + } + + int idx = fi->bytesPerSample - 1; + + for (int plane = 0; plane < fi->numPlanes; plane++) { + if (fr[plane]) { + continue; + } + + int width = vsapi->getFrameWidth(src, plane); + int height = vsapi->getFrameHeight(src, plane); + int stride = vsapi->getStride(src, plane); + const uint8_t *srcp = vsapi->getReadPtr(src, plane); + uint8_t *dstp = vsapi->getWritePtr(dst, plane); + if (width < 16 || height < 16) { + continue; + } + + ch->gaussian_blur[idx](ch->radius, ch->kernel, srcp, buff + 8, blur, + width, height, stride, fstride); + + write_dst_gblur[idx](blur, dstp, width, height, fstride, stride, 0.0f, + fi->bitsPerSample); + + } + +close_gblur: + _aligned_free(blur); + _aligned_free(buff); +} + + +static void VS_CC +set_kernel(float sigma, int *radius, float *kernel) +{ + if (sigma == 0.0f) { + return; + } + + int rad = (int)(sigma * 3.0f + 0.5f); + if (rad < 1) { + rad = 1; + } + + float sum = 0.0f; + for (int i = -rad; i <= rad; i++) { + float weight = expf(-(i * i)/(2.0f * sigma * sigma)); + kernel[i + rad] = weight; + sum += weight; + } + for (int i = 0, len = rad * 2 + 1; i < len; kernel[i++] /= sum); + *radius = rad; +} + + +static void VS_CC +set_canny_data(generic_handler_t *gh, filter_id_t id, char *msg, + const VSMap *in, VSMap *out, const VSAPI *vsapi) +{ + canny_t *ch = (canny_t *)calloc(sizeof(canny_t), 1); + RET_IF_ERROR(!ch, "failed to allocate filter data"); + gh->fdata = ch; + + int err; + float sigma = (float)vsapi->propGetFloat(in, "sigma", 0, &err); + if (err) { + sigma = id == ID_CANNY ? 1.50f : 0.50f; + } + RET_IF_ERROR(sigma < 0, "sigma must be greater than zero"); + RET_IF_ERROR(sigma > 2.833f, "sigma must be lesser than 2.83"); + + if (id == ID_CANNY) { + ch->tl = (float)vsapi->propGetFloat(in, "tl", 0, &err); + if (err) { + ch->tl = 1.0f; + } + RET_IF_ERROR(ch->tl < 0.0f, "tl must be greater than zero"); + ch->th = (float)vsapi->propGetFloat(in, "th", 0, &err); + if (err) { + ch->th = 8.0f; + } + RET_IF_ERROR(ch->th < ch->tl, "th must be greater than tl"); + } + + set_kernel(sigma, &ch->radius, ch->kernel); + + ch->gaussian_blur = sigma == 0.0f ? convert_to_float : gblur; + + gh->get_frame_filter = id == ID_CANNY ? canny_get_frame : gblur_get_frame; +} + +const set_filter_data_func set_canny = set_canny_data; diff --git a/pool/shard002/C/0057147_vcf_sweep.c b/pool/shard002/C/0057147_vcf_sweep.c new file mode 100644 index 0000000000000000000000000000000000000000..3aaf29f55ad50f4d4d8e58b279166e6952de86b5 --- /dev/null +++ b/pool/shard002/C/0057147_vcf_sweep.c @@ -0,0 +1,184 @@ +/* vcf_sweep.c -- forward/reverse sweep API. + + Copyright (C) 2013 Genome Research Ltd. + + Author: Petr Danecek + +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 "htslib/vcf_sweep.h" +#include "htslib/bgzf.h" + +#define SW_FWD 0 +#define SW_BWD 1 + +struct _bcf_sweep_t +{ + htsFile *file; + bcf_hdr_t *hdr; + BGZF *fp; + + int direction; // to tell if the direction has changed + int block_size; // the size of uncompressed data to hold in memory + bcf1_t *rec; // bcf buffer + int nrec, mrec; // number of used records; total size of the buffer + int lrid, lpos, lnals, lals_len, mlals; // to check uniqueness of a record + char *lals; + + uint64_t *idx; // uncompressed offsets of VCF/BCF records + int iidx, nidx, midx; // i: current offset; n: used; m: allocated + int idx_done; // the index is built during the first pass +}; + +BGZF *hts_get_bgzfp(htsFile *fp); +int hts_useek(htsFile *file, long uoffset, int where); +long hts_utell(htsFile *file); + +static inline int sw_rec_equal(bcf_sweep_t *sw, bcf1_t *rec) +{ + if ( sw->lrid!=rec->rid ) return 0; + if ( sw->lpos!=rec->pos ) return 0; + if ( sw->lnals!=rec->n_allele ) return 0; + + char *t = rec->d.allele[sw->lnals-1]; + int len = t - rec->d.allele[0] + 1; + while ( *t ) { t++; len++; } + if ( sw->lals_len!=len ) return 0; + if ( memcmp(sw->lals,rec->d.allele[0],len) ) return 0; + return 1; +} + +static void sw_rec_save(bcf_sweep_t *sw, bcf1_t *rec) +{ + sw->lrid = rec->rid; + sw->lpos = rec->pos; + sw->lnals = rec->n_allele; + + char *t = rec->d.allele[sw->lnals-1]; + int len = t - rec->d.allele[0] + 1; + while ( *t ) { t++; len++; } + sw->lals_len = len; + hts_expand(char, len, sw->mlals, sw->lals); + memcpy(sw->lals, rec->d.allele[0], len); +} + +static void sw_fill_buffer(bcf_sweep_t *sw) +{ + if ( !sw->iidx ) return; + sw->iidx--; + + int ret = hts_useek(sw->file, sw->idx[sw->iidx], 0); + assert( ret==0 ); + + sw->nrec = 0; + bcf1_t *rec = &sw->rec[sw->nrec]; + while ( (ret=bcf_read1(sw->file, sw->hdr, rec))==0 ) + { + bcf_unpack(rec, BCF_UN_STR); + + // if not in the last block, stop at the saved record + if ( sw->iidx+1 < sw->nidx && sw_rec_equal(sw,rec) ) break; + + sw->nrec++; + hts_expand0(bcf1_t, sw->nrec+1, sw->mrec, sw->rec); + rec = &sw->rec[sw->nrec]; + } + sw_rec_save(sw, &sw->rec[0]); +} + +bcf_sweep_t *bcf_sweep_init(const char *fname) +{ + bcf_sweep_t *sw = (bcf_sweep_t*) calloc(1,sizeof(bcf_sweep_t)); + sw->file = hts_open(fname, "r"); + sw->fp = hts_get_bgzfp(sw->file); + bgzf_index_build_init(sw->fp); + sw->hdr = bcf_hdr_read(sw->file); + sw->mrec = 1; + sw->rec = (bcf1_t*) calloc(sw->mrec,(sizeof(bcf1_t))); + sw->block_size = 1024*1024*3; + sw->direction = SW_FWD; + return sw; +} + +void bcf_empty1(bcf1_t *v); +void bcf_sweep_destroy(bcf_sweep_t *sw) +{ + int i; + for (i=0; imrec; i++) bcf_empty1(&sw->rec[i]); + free(sw->idx); + free(sw->rec); + free(sw->lals); + bcf_hdr_destroy(sw->hdr); + hts_close(sw->file); + free(sw); +} + +static void sw_seek(bcf_sweep_t *sw, int direction) +{ + sw->direction = direction; + if ( direction==SW_FWD ) + hts_useek(sw->file, sw->idx[0], 0); + else + { + sw->iidx = sw->nidx; + sw->nrec = 0; + } +} + +bcf1_t *bcf_sweep_fwd(bcf_sweep_t *sw) +{ + if ( sw->direction==SW_BWD ) sw_seek(sw, SW_FWD); + + long pos = hts_utell(sw->file); + + bcf1_t *rec = &sw->rec[0]; + int ret = bcf_read1(sw->file, sw->hdr, rec); + + if ( ret!=0 ) // last record, get ready for sweeping backwards + { + sw->idx_done = 1; + sw->fp->idx_build_otf = 0; + sw_seek(sw, SW_BWD); + return NULL; + } + + if ( !sw->idx_done ) + { + if ( !sw->nidx || pos - sw->idx[sw->nidx-1] > sw->block_size ) + { + sw->nidx++; + hts_expand(uint64_t, sw->nidx, sw->midx, sw->idx); + sw->idx[sw->nidx-1] = pos; + } + } + return rec; +} + +bcf1_t *bcf_sweep_bwd(bcf_sweep_t *sw) +{ + if ( sw->direction==SW_FWD ) sw_seek(sw, SW_BWD); + if ( !sw->nrec ) sw_fill_buffer(sw); + if ( !sw->nrec ) return NULL; + return &sw->rec[ --sw->nrec ]; +} + +bcf_hdr_t *bcf_sweep_hdr(bcf_sweep_t *sw) { return sw->hdr; } + diff --git a/pool/shard002/C/0057193_rbwriter.c b/pool/shard002/C/0057193_rbwriter.c new file mode 100644 index 0000000000000000000000000000000000000000..d2a7f6f7aa3fd1232b1743fa937d2d2d54952ef1 --- /dev/null +++ b/pool/shard002/C/0057193_rbwriter.c @@ -0,0 +1,155 @@ +/* + * Copyright (c) 2009 Red Hat, Inc. + * + * All rights reserved. + * + * Author: Steven Dake (sdake@redhat.com) + * + * libqb 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. + * + * libqb 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 libqb. If not, see . + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +static int alarm_notice = 0; +static qb_ringbuffer_t *rb = NULL; +static qb_util_stopwatch_t *sw; +#define ONE_MEG 1048576 +static char buffer[ONE_MEG * 3]; + +static void sigalrm_handler (int num) +{ + alarm_notice = 1; +} + +static void sigterm_handler(int32_t num) +{ + qb_log(LOG_INFO, "writer: %s(%d)\n", __func__, num); + qb_rb_close(rb); + exit(0); +} + +static void +_benchmark(ssize_t write_size) +{ + ssize_t res; + int write_count = 0; + float secs; + + alarm_notice = 0; + + alarm (10); + + qb_util_stopwatch_start(sw); + do { + res = qb_rb_chunk_write(rb, buffer, write_size); + if (res == write_size) { + write_count++; + } + } while (alarm_notice == 0 && (res == write_size || res == -EAGAIN)); + if (res < 0) { + perror("qb_ipcc_sendv"); + } + qb_util_stopwatch_stop(sw); + secs = qb_util_stopwatch_sec_elapsed_get(sw); + + printf ("%5d messages sent ", write_count); + printf ("%5ld bytes per write ", (long int) write_size); + printf ("%7.3f Seconds runtime ", secs); + printf ("%9.3f TP/s ", + ((float)write_count) / secs); + printf ("%7.3f MB/s.\n", + ((float)write_count) * ((float)write_size) / secs); +} + + +static void +do_throughput_benchmark(void) +{ + ssize_t size = 64; + int i; + + signal (SIGALRM, sigalrm_handler); + sw = qb_util_stopwatch_create(); + + for (i = 0; i < 10; i++) { /* number of repetitions - up to 50k */ + _benchmark(size); + signal (SIGALRM, sigalrm_handler); + size *= 5; + if (size >= ONE_MEG) { + break; + } + } +} + +static void show_usage(const char *name) +{ + printf("usage: \n"); + printf("%s \n", name); + printf("\n"); + printf(" options:\n"); + printf("\n"); + printf(" -n non-blocking ipc (default blocking)\n"); + printf(" -v verbose\n"); + printf(" -h show this help text\n"); + printf("\n"); +} + +int32_t main(int32_t argc, char *argv[]) +{ + const char *options = "vh"; + int32_t opt; + int32_t verbose = 0; + + while ((opt = getopt(argc, argv, options)) != -1) { + switch (opt) { + case 'v': + verbose++; + break; + case 'h': + default: + show_usage(argv[0]); + exit(0); + break; + } + } + + signal(SIGINT, sigterm_handler); + + qb_log_init("rbwriter", LOG_USER, LOG_EMERG); + qb_log_ctl(QB_LOG_SYSLOG, QB_LOG_CONF_ENABLED, QB_FALSE); + qb_log_filter_ctl(QB_LOG_STDERR, QB_LOG_FILTER_ADD, + QB_LOG_FILTER_FILE, "*", LOG_INFO + verbose); + qb_log_ctl(QB_LOG_STDERR, QB_LOG_CONF_ENABLED, QB_TRUE); + + rb = qb_rb_open("tester", ONE_MEG * 3, + QB_RB_FLAG_SHARED_PROCESS, 0); + do_throughput_benchmark(); + qb_rb_close(rb); + qb_log_fini(); + return EXIT_SUCCESS; +} diff --git a/pool/shard002/C/0057199_makelists.c b/pool/shard002/C/0057199_makelists.c new file mode 100644 index 0000000000000000000000000000000000000000..929959250ef73ff0f5052f0aff2c03d49c83f7ee --- /dev/null +++ b/pool/shard002/C/0057199_makelists.c @@ -0,0 +1,190 @@ +/* @(#) $Id$ */ + +/* Copyright (C) 2010 Trend Micro Inc. + * All rights reserved. + * + * This program is a 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 FSF - Free Software + * Foundation. + * + * License details at the LICENSE file included with OSSEC or + * online at: http://www.ossec.net/en/licensing.html + */ + + +/* Part of the OSSEC + * Available at http://www.ossec.net + */ + + +/* ossec-analysisd. + * Responsible for correlation and log decoding. + */ +#ifdef ARGV0 + #undef ARGV0 + #define ARGV0 "ossec-testrule" +#endif + +#include "shared.h" + + +/** Local headers **/ +#include "active-response.h" +#include "config.h" +#include "rules.h" +#include "stats.h" +#include "lists_make.h" + +#include "eventinfo.h" +#include "analysisd.h" + +#include "picviz.h" + + + +/** External functions prototypes (only called here) **/ + +/* For config */ +int GlobalConf(char * cfgfile); + + +/* For Lists */ +void Lists_OP_CreateLists(); + +void makelist_help(const char *prog) +{ + print_out(" "); + print_out("%s %s - %s (%s)", __name, __version, __author, __contact); + print_out("%s", __site); + print_out(" "); + print_out(" %s: -[Vhdt] [-u user] [-g group] [-c config] [-D dir]", prog); + print_out(" -V Version and license message"); + print_out(" -h This help message"); + print_out(" -d Execute in debug mode"); + print_out(" -f Force rebuild of all databases"); + print_out(" -u Run as 'user'"); + print_out(" -g Run as 'group'"); + print_out(" -c Read the 'config' file"); + print_out(" -D Chroot to 'dir'"); + print_out(" "); + exit(1); +} + +/** int main(int argc, char **argv) + */ +int main(int argc, char **argv) +{ + int c = 0; + char *dir = DEFAULTDIR; + char *user = USER; + char *group = GROUPGLOBAL; + int uid = 0,gid = 0; + int force = 0; + + char *cfg = DEFAULTCPATH; + + /* Setting the name */ + OS_SetName(ARGV0); + + thishour = 0; + today = 0; + prev_year = 0; + memset(prev_month, '\0', 4); + + while((c = getopt(argc, argv, "Vdhfu:g:D:c:")) != -1){ + switch(c){ + case 'V': + print_version(); + break; + case 'h': + makelist_help(ARGV0); + break; + case 'd': + nowDebug(); + break; + case 'u': + if(!optarg) + ErrorExit("%s: -u needs an argument",ARGV0); + user = optarg; + break; + case 'g': + if(!optarg) + ErrorExit("%s: -g needs an argument",ARGV0); + group = optarg; + break; + case 'D': + if(!optarg) + ErrorExit("%s: -D needs an argument",ARGV0); + dir = optarg; + case 'c': + if(!optarg) + ErrorExit("%s: -c needs an argument",ARGV0); + cfg = optarg; + break; + case 'f': + force = 1; + break; + default: + help(ARGV0); + break; + } + + } + + + /*Check if the user/group given are valid */ + uid = Privsep_GetUser(user); + gid = Privsep_GetGroup(group); + if((uid < 0)||(gid < 0)) + ErrorExit(USER_ERROR,ARGV0,user,group); + + + /* Found user */ + debug1(FOUND_USER, ARGV0); + + + /* Reading configuration file */ + if(GlobalConf(cfg) < 0) + { + ErrorExit(CONFIG_ERROR,ARGV0, cfg); + } + + debug1(READ_CONFIG, ARGV0); + + /* Setting the group */ + if(Privsep_SetGroup(gid) < 0) + ErrorExit(SETGID_ERROR,ARGV0,group); + + /* Chrooting */ + if(Privsep_Chroot(dir) < 0) + ErrorExit(CHROOT_ERROR,ARGV0,dir); + + nowChroot(); + + + + /* Createing the lists for use in rules */ + Lists_OP_CreateLists(); + + /* Reading the lists */ + { + char **listfiles; + listfiles = Config.lists; + while(listfiles && *listfiles) + { + if(Lists_OP_LoadList(*listfiles) < 0) + ErrorExit(LISTS_ERROR, ARGV0, *listfiles); + free(*listfiles); + listfiles++; + } + free(Config.lists); + Config.lists = NULL; + } + + Lists_OP_MakeAll(force); + + exit(0); +} + +/* EOF */ diff --git a/pool/shard002/C/0057208_makemob.c b/pool/shard002/C/0057208_makemob.c new file mode 100644 index 0000000000000000000000000000000000000000..8a5e71ca2f2232ff97f63e91c009a8d331b227e9 --- /dev/null +++ b/pool/shard002/C/0057208_makemob.c @@ -0,0 +1,151 @@ +#include +#include + +struct mobst { + char desc[4096]; // generic description + char flags[255]; // generic flags + char worn[4096]; // all wearing + short wield[51]; // each level wields? + short slevel; // starting level + short nlevel; // random levels beyond slevel + short sroom; // starting room + short nroom; // rooms beyond that + char names[1000][128]; // all the names to process +}; + +struct mobst mobs; + +int psuedo_rand(int max) +{ + return (1+(int) ((double)max*rand()/(RAND_MAX+1.0))); +} + +void init() +{ + short count; + + srand(time(0)); + for (count=0;count<1000;count++) { + mobs.names[count][0]='\0'; + } + + for (count=0;count<51;count++) { + mobs.wield[count]=-1; + } +} + +void domobs(char *fname,short vnumstart) +{ + FILE *fp; + short num=0; + short names=0; + short vnum=vnumstart; + short count,count2,level; + char text[4096]; + + if (!(fp=fopen(fname,"r"))) { + fprintf(stderr,"Bad config file name.\n"); + exit(-1); + } + + while (fgets(text,255,fp)) { + if (text[0]=='#') break; + text[strlen(text)-1]='\0'; + + if (strncmp(text,"desc",4)==0) { + strcpy(mobs.desc,strchr(text,':')+1); + } + if (strncmp(text,"sroom",5)==0) { + mobs.sroom=atoi(strchr(text,':')+1); + } + if (strncmp(text,"nroom",5)==0) { + mobs.nroom=atoi(strchr(text,':')+1); + } + if (strncmp(text,"nlevel",6)==0) { + mobs.nlevel=atoi(strchr(text,':')+1); + } + if (strncmp(text,"slevel",6)==0) { + mobs.slevel=atoi(strchr(text,':')+1); + } + if (strncmp(text,"flags",5)==0) { + strcpy(mobs.flags,strchr(text,':')+1); + } + if (strncmp(text,"worn",4)==0) { + strcpy(mobs.worn,strchr(text,':')+1); + } + if (strncmp(text,"wield",5)==0) { + num=atoi(text+5); + mobs.wield[num]=atoi(strchr(text,':')+1); + } + if (strncmp(text,"name",4)==0) { + strcpy(mobs.names[names],strchr(text,':')+1); + names++; + } + } + fclose(fp); + + // make sure each level has a weapon + num=-1; + for (count=0;count<51;count++) { + if (mobs.wield[count]==-1) { + mobs.wield[count]=num; + } + else + { + num=mobs.wield[count]; + } + } + + /* + // get rid of duplicate names + for (count=0;count<1000;count++) { + for (count2=0;count2<1000;count2++) { + if (count==count2) continue; + if (strcasecmp(mobs.names[count],mobs.names[count2])==0) + { + // duplicate + mobs.names[count2][0]='\0'; + } + } + } + */ + + printf("# Auto generated with makemob\n\n"); + for (count=0;count<1000;count++) { + if (mobs.names[count][0]=='\0') continue; + // got mob name + printf("%d {\n",vnum); + printf(" name %s\n",mobs.names[count]); + printf(" shortdesc %s\n",mobs.names[count]); + level=mobs.slevel+(psuedo_rand(mobs.nlevel)-1); + printf(" objects %s",mobs.worn); + if (mobs.wield[level]!=-1) { + printf("\\n%d\n",mobs.wield[level]); + } + else + { + printf("\n"); + } + level+=(int)(level/2); + printf(" level %d\n",level); + printf(" home %d\n",mobs.sroom+(psuedo_rand(mobs.nroom)-1)); + printf(" longdesc %s\n",mobs.desc); + printf(" sex N\n"); + printf(" alignment 0\n"); + printf("}\n\n"); + vnum++; + } +} + +int main(int argc, char *argv[]) +{ + if (argc!=3) { + printf("Usage: makemob \n"); + exit(-1); + } + + init(); + domobs(argv[1],atoi(argv[2])); + + exit(0); +} diff --git a/pool/shard002/C/0057209_vmalloc.c b/pool/shard002/C/0057209_vmalloc.c new file mode 100644 index 0000000000000000000000000000000000000000..8a133d8139736470704c4e4c77026fc097938c7c --- /dev/null +++ b/pool/shard002/C/0057209_vmalloc.c @@ -0,0 +1,56 @@ +/* + * linux/mm/vmalloc.c + * + * Copyright (C) 1993 Linus Torvalds + * Support of BIGMEM added by Gerhard Wichert, Siemens AG, July 1999 + * SMP-safe vmalloc/vfree/ioremap, Tigran Aivazian , May 2000 + * Copyright (c) 2001 Lineo Inc., David McCullough + * Copyright (c) 2000-2001 D Jeff Dionne + */ + +#include +#include +#include +#include + +#include +#include + +rwlock_t vmlist_lock = RW_LOCK_UNLOCKED; +struct vm_struct * vmlist; + +void __vfree(void * addr, int free_area_pages) +{ + kfree(addr); +} + +void vfree(void * addr) +{ + __vfree(addr,1); +} + +void * __vmalloc (unsigned long size, int gfp_mask, pgprot_t prot) +{ + /* + * kmalloc doesn't like __GFP_HIGHMEM for some reason + * I doubt we need it - DAVIDM + */ + return kmalloc(size, gfp_mask & ~__GFP_HIGHMEM); +} + +long vread(char *buf, char *addr, unsigned long count) +{ + memcpy(buf, addr, count); + return count; +} + +long vwrite(char *buf, char *addr, unsigned long count) +{ + /* Don't allow overflow */ + if ((unsigned long) addr + count < count) + count = -(unsigned long) addr; + + memcpy(addr, buf, count); + return(count); +} + diff --git a/pool/shard002/C/0057227_jiq.c b/pool/shard002/C/0057227_jiq.c new file mode 100644 index 0000000000000000000000000000000000000000..8b5638fe6fcebb4d55e941fe7585522aed5db132 --- /dev/null +++ b/pool/shard002/C/0057227_jiq.c @@ -0,0 +1,267 @@ +/* + * jiq.c -- the just-in-queue module + * + * Copyright (C) 2001 Alessandro Rubini and Jonathan Corbet + * Copyright (C) 2001 O'Reilly & Associates + * + * The source code in this file can be freely used, adapted, + * and redistributed in source or binary form, so long as an + * acknowledgment appears in derived source files. The citation + * should list that the code comes from the book "Linux Device + * Drivers" by Alessandro Rubini and Jonathan Corbet, published + * by O'Reilly & Associates. No warranty is attached; + * we cannot take responsibility for errors or fitness for use. + * + * $Id: jiq.c,v 1.7 2004/09/26 07:02:43 gregkh Exp $ + */ + +#include +#include +#include + +#include +#include +#include /* everything... */ +#include +#include /* error codes */ +#include +#include +#include /* tasklets */ + +MODULE_LICENSE("Dual BSD/GPL"); + +/* + * The delay for the delayed workqueue timer file. + */ +static long delay = 1; +module_param(delay, long, 0); + + +/* + * This module is a silly one: it only embeds short code fragments + * that show how enqueued tasks `feel' the environment + */ + +#define LIMIT (PAGE_SIZE-128) /* don't print any more after this size */ + +/* + * Print information about the current environment. This is called from + * within the task queues. If the limit is reched, awake the reading + * process. + */ +static DECLARE_WAIT_QUEUE_HEAD (jiq_wait); + +/* + * Keep track of info we need between task queue runs. + */ +static struct clientdata { + struct work_struct jiq_work; + struct delayed_work jiq_delayed_work; + int len; + char *buf; + unsigned long jiffies; + long delay; +} jiq_data; + +#define SCHEDULER_QUEUE ((task_queue *) 1) + + + +static void jiq_print_tasklet(unsigned long); +static DECLARE_TASKLET(jiq_tasklet, jiq_print_tasklet, (unsigned long)&jiq_data); + + +/* + * Do the printing; return non-zero if the task should be rescheduled. + */ +static int jiq_print(void *ptr) +{ + struct clientdata *data = ptr; + int len = data->len; + char *buf = data->buf; + unsigned long j = jiffies; + + if (len > LIMIT) { + wake_up_interruptible(&jiq_wait); + return 0; + } + + if (len == 0) + len = sprintf(buf," time delta preempt pid cpu command\n"); + else + len =0; + + /* intr_count is only exported since 1.3.5, but 1.99.4 is needed anyways */ + len += sprintf(buf+len, "%9li %4li %3i %5i %3i %s\n", + j, j - data->jiffies, + preempt_count(), current->pid, smp_processor_id(), + current->comm); + + data->len += len; + data->buf += len; + data->jiffies = j; + return 1; +} + + +/* + * Call jiq_print from a work queue + */ +static void jiq_print_wq(struct work_struct *work) +{ + struct clientdata *data = container_of(work, struct clientdata, jiq_work); + + if (! jiq_print (data)) + return; + + schedule_work(&jiq_data.jiq_work); +} + +static void jiq_print_wq_delayed(struct work_struct *work) +{ + struct clientdata *data = container_of(work, struct clientdata, jiq_delayed_work.work); + + if (! jiq_print (data)) + return; + + schedule_delayed_work(&jiq_data.jiq_delayed_work, data->delay); +} + + +static int jiq_read_wq(char *buf, char **start, off_t offset, + int len, int *eof, void *data) +{ + DEFINE_WAIT(wait); + + jiq_data.len = 0; /* nothing printed, yet */ + jiq_data.buf = buf; /* print in this place */ + jiq_data.jiffies = jiffies; /* initial time */ + jiq_data.delay = 0; + + prepare_to_wait(&jiq_wait, &wait, TASK_INTERRUPTIBLE); + schedule_work(&jiq_data.jiq_work); + schedule(); + finish_wait(&jiq_wait, &wait); + + *eof = 1; + return jiq_data.len; +} + + +static int jiq_read_wq_delayed(char *buf, char **start, off_t offset, + int len, int *eof, void *data) +{ + DEFINE_WAIT(wait); + + jiq_data.len = 0; /* nothing printed, yet */ + jiq_data.buf = buf; /* print in this place */ + jiq_data.jiffies = jiffies; /* initial time */ + jiq_data.delay = delay; + + prepare_to_wait(&jiq_wait, &wait, TASK_INTERRUPTIBLE); + schedule_delayed_work(&jiq_data.jiq_delayed_work, delay); + schedule(); + finish_wait(&jiq_wait, &wait); + + *eof = 1; + return jiq_data.len; +} + + + + +/* + * Call jiq_print from a tasklet + */ +static void jiq_print_tasklet(unsigned long ptr) +{ + if (jiq_print ((void *) ptr)) + tasklet_schedule (&jiq_tasklet); +} + + + +static int jiq_read_tasklet(char *buf, char **start, off_t offset, int len, + int *eof, void *data) +{ + jiq_data.len = 0; /* nothing printed, yet */ + jiq_data.buf = buf; /* print in this place */ + jiq_data.jiffies = jiffies; /* initial time */ + + tasklet_schedule(&jiq_tasklet); + interruptible_sleep_on(&jiq_wait); /* sleep till completion */ + + *eof = 1; + return jiq_data.len; +} + + + + +/* + * This one, instead, tests out the timers. + */ + +static struct timer_list jiq_timer; + +static void jiq_timedout(unsigned long ptr) +{ + jiq_print((void *)ptr); /* print a line */ + wake_up_interruptible(&jiq_wait); /* awake the process */ +} + + +static int jiq_read_run_timer(char *buf, char **start, off_t offset, + int len, int *eof, void *data) +{ + + jiq_data.len = 0; /* prepare the argument for jiq_print() */ + jiq_data.buf = buf; + jiq_data.jiffies = jiffies; + + init_timer(&jiq_timer); /* init the timer structure */ + jiq_timer.function = jiq_timedout; + jiq_timer.data = (unsigned long)&jiq_data; + jiq_timer.expires = jiffies + HZ; /* one second */ + + jiq_print(&jiq_data); /* print and go to sleep */ + add_timer(&jiq_timer); + interruptible_sleep_on(&jiq_wait); /* RACE */ + del_timer_sync(&jiq_timer); /* in case a signal woke us up */ + + *eof = 1; + return jiq_data.len; +} + + + +/* + * the init/clean material + */ + +static int jiq_init(void) +{ + + /* this line is in jiq_init() */ + INIT_WORK(&jiq_data.jiq_work, jiq_print_wq); + INIT_DELAYED_WORK(&jiq_data.jiq_delayed_work, jiq_print_wq_delayed); + + create_proc_read_entry("jiqwq", 0, NULL, jiq_read_wq, NULL); + create_proc_read_entry("jiqwqdelay", 0, NULL, jiq_read_wq_delayed, NULL); + create_proc_read_entry("jitimer", 0, NULL, jiq_read_run_timer, NULL); + create_proc_read_entry("jiqtasklet", 0, NULL, jiq_read_tasklet, NULL); + + return 0; /* succeed */ +} + +static void jiq_cleanup(void) +{ + remove_proc_entry("jiqwq", NULL); + remove_proc_entry("jiqwqdelay", NULL); + remove_proc_entry("jitimer", NULL); + remove_proc_entry("jiqtasklet", NULL); +} + + +module_init(jiq_init); +module_exit(jiq_cleanup); diff --git a/pool/shard002/C/0057232_port.c b/pool/shard002/C/0057232_port.c new file mode 100644 index 0000000000000000000000000000000000000000..7c9d8980d5a53edc8f4037a9c347f5e0ddc14c95 --- /dev/null +++ b/pool/shard002/C/0057232_port.c @@ -0,0 +1,307 @@ +/* + FreeRTOS V7.4.0 - Copyright (C) 2013 Real Time Engineers Ltd. + + FEATURES AND PORTS ARE ADDED TO FREERTOS ALL THE TIME. PLEASE VISIT + http://www.FreeRTOS.org TO ENSURE YOU ARE USING THE LATEST VERSION. + + *************************************************************************** + * * + * FreeRTOS tutorial books are available in pdf and paperback. * + * Complete, revised, and edited pdf reference manuals are also * + * available. * + * * + * Purchasing FreeRTOS documentation will not only help you, by * + * ensuring you get running as quickly as possible and with an * + * in-depth knowledge of how to use FreeRTOS, it will also help * + * the FreeRTOS project to continue with its mission of providing * + * professional grade, cross platform, de facto standard solutions * + * for microcontrollers - completely free of charge! * + * * + * >>> See http://www.FreeRTOS.org/Documentation for details. <<< * + * * + * Thank you for using FreeRTOS, and thank you for your support! * + * * + *************************************************************************** + + + This file is part of the FreeRTOS distribution. + + FreeRTOS 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 AND MODIFIED BY the FreeRTOS exception. + + >>>>>>NOTE<<<<<< The modification to the GPL is included to allow you to + distribute a combined work that includes FreeRTOS without being obliged to + provide the source code for proprietary components outside of the FreeRTOS + kernel. + + FreeRTOS 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 + and the FreeRTOS license exception along with FreeRTOS; if not itcan be + viewed here: http://www.freertos.org/a00114.html and also obtained by + writing to Real Time Engineers Ltd., contact details for whom are available + on the FreeRTOS WEB site. + + 1 tab == 4 spaces! + + *************************************************************************** + * * + * Having a problem? Start by reading the FAQ "My application does * + * not run, what could be wrong?" * + * * + * http://www.FreeRTOS.org/FAQHelp.html * + * * + *************************************************************************** + + + http://www.FreeRTOS.org - Documentation, books, training, latest versions, + license and Real Time Engineers Ltd. contact details. + + http://www.FreeRTOS.org/plus - A selection of FreeRTOS ecosystem products, + including FreeRTOS+Trace - an indispensable productivity tool, and our new + fully thread aware and reentrant UDP/IP stack. + + http://www.OpenRTOS.com - Real Time Engineers ltd license FreeRTOS to High + Integrity Systems, who sell the code with commercial support, + indemnification and middleware, under the OpenRTOS brand. + + http://www.SafeRTOS.com - High Integrity Systems also provide a safety + engineered and independently SIL3 certified version for use in safety and + mission critical applications that require provable dependability. +*/ + +/*----------------------------------------------------------- + * Implementation of functions defined in portable.h for the PPC405 port. + *----------------------------------------------------------*/ + + +/* Scheduler includes. */ +#include "FreeRTOS.h" +#include "task.h" + +/* Library includes. */ +#include "xtime_l.h" +#include "xintc.h" +#include "xintc_i.h" + +/*-----------------------------------------------------------*/ + +/* Definitions to set the initial MSR of each task. */ +#define portCRITICAL_INTERRUPT_ENABLE ( 1UL << 17UL ) +#define portEXTERNAL_INTERRUPT_ENABLE ( 1UL << 15UL ) +#define portMACHINE_CHECK_ENABLE ( 1UL << 12UL ) + +#if configUSE_FPU == 1 + #define portAPU_PRESENT ( 1UL << 25UL ) + #define portFCM_FPU_PRESENT ( 1UL << 13UL ) +#else + #define portAPU_PRESENT ( 0UL ) + #define portFCM_FPU_PRESENT ( 0UL ) +#endif + +#define portINITIAL_MSR ( portCRITICAL_INTERRUPT_ENABLE | portEXTERNAL_INTERRUPT_ENABLE | portMACHINE_CHECK_ENABLE | portAPU_PRESENT | portFCM_FPU_PRESENT ) + + +extern const unsigned _SDA_BASE_; +extern const unsigned _SDA2_BASE_; + +/*-----------------------------------------------------------*/ + +/* + * Setup the system timer to generate the tick interrupt. + */ +static void prvSetupTimerInterrupt( void ); + +/* + * The handler for the tick interrupt - defined in portasm.s. + */ +extern void vPortTickISR( void ); + +/* + * The handler for the yield function - defined in portasm.s. + */ +extern void vPortYield( void ); + +/* + * Function to start the scheduler running by starting the highest + * priority task that has thus far been created. + */ +extern void vPortStartFirstTask( void ); + +/*-----------------------------------------------------------*/ + +/* Structure used to hold the state of the interrupt controller. */ +static XIntc xInterruptController; + +/*-----------------------------------------------------------*/ + +/* + * Initialise the stack of a task to look exactly as if the task had been + * interrupted. + * + * See the header file portable.h. + */ +portSTACK_TYPE *pxPortInitialiseStack( portSTACK_TYPE *pxTopOfStack, pdTASK_CODE pxCode, void *pvParameters ) +{ + /* Place a known value at the bottom of the stack for debugging. */ + *pxTopOfStack = 0xDEADBEEF; + pxTopOfStack--; + + /* EABI stack frame. */ + pxTopOfStack -= 20; /* Previous backchain and LR, R31 to R4 inclusive. */ + + /* Parameters in R13. */ + *pxTopOfStack = ( portSTACK_TYPE ) &_SDA_BASE_; /* address of the first small data area */ + pxTopOfStack -= 10; + + /* Parameters in R3. */ + *pxTopOfStack = ( portSTACK_TYPE ) pvParameters; + pxTopOfStack--; + + /* Parameters in R2. */ + *pxTopOfStack = ( portSTACK_TYPE ) &_SDA2_BASE_; /* address of the second small data area */ + pxTopOfStack--; + + /* R1 is the stack pointer so is omitted. */ + + *pxTopOfStack = 0x10000001UL;; /* R0. */ + pxTopOfStack--; + *pxTopOfStack = 0x00000000UL; /* USPRG0. */ + pxTopOfStack--; + *pxTopOfStack = 0x00000000UL; /* CR. */ + pxTopOfStack--; + *pxTopOfStack = 0x00000000UL; /* XER. */ + pxTopOfStack--; + *pxTopOfStack = 0x00000000UL; /* CTR. */ + pxTopOfStack--; + *pxTopOfStack = ( portSTACK_TYPE ) vPortEndScheduler; /* LR. */ + pxTopOfStack--; + *pxTopOfStack = ( portSTACK_TYPE ) pxCode; /* SRR0. */ + pxTopOfStack--; + *pxTopOfStack = portINITIAL_MSR;/* SRR1. */ + pxTopOfStack--; + *pxTopOfStack = ( portSTACK_TYPE ) vPortEndScheduler;/* Next LR. */ + pxTopOfStack--; + *pxTopOfStack = 0x00000000UL;/* Backchain. */ + + return pxTopOfStack; +} +/*-----------------------------------------------------------*/ + +portBASE_TYPE xPortStartScheduler( void ) +{ + prvSetupTimerInterrupt(); + XExc_RegisterHandler( XEXC_ID_SYSTEM_CALL, ( XExceptionHandler ) vPortYield, ( void * ) 0 ); + vPortStartFirstTask(); + + /* Should not get here as the tasks are now running! */ + return pdFALSE; +} +/*-----------------------------------------------------------*/ + +void vPortEndScheduler( void ) +{ + /* Not implemented. */ + for( ;; ); +} +/*-----------------------------------------------------------*/ + +/* + * Hardware initialisation to generate the RTOS tick. + */ +static void prvSetupTimerInterrupt( void ) +{ +const unsigned long ulInterval = ( ( configCPU_CLOCK_HZ / configTICK_RATE_HZ ) - 1UL ); + + XTime_PITClearInterrupt(); + XTime_FITClearInterrupt(); + XTime_WDTClearInterrupt(); + XTime_WDTDisableInterrupt(); + XTime_FITDisableInterrupt(); + + XExc_RegisterHandler( XEXC_ID_PIT_INT, ( XExceptionHandler ) vPortTickISR, ( void * ) 0 ); + + XTime_PITEnableAutoReload(); + XTime_PITSetInterval( ulInterval ); + XTime_PITEnableInterrupt(); +} +/*-----------------------------------------------------------*/ + +void vPortISRHandler( void *pvNullDoNotUse ) +{ +unsigned long ulInterruptStatus, ulInterruptMask = 1UL; +portBASE_TYPE xInterruptNumber; +XIntc_Config *pxInterruptController; +XIntc_VectorTableEntry *pxTable; + + /* Just to remove compiler warning. */ + ( void ) pvNullDoNotUse; + + /* Get the configuration by using the device ID - in this case it is + assumed that only one interrupt controller is being used. */ + pxInterruptController = &XIntc_ConfigTable[ XPAR_XPS_INTC_0_DEVICE_ID ]; + + /* Which interrupts are pending? */ + ulInterruptStatus = XIntc_mGetIntrStatus( pxInterruptController->BaseAddress ); + + for( xInterruptNumber = 0; xInterruptNumber < XPAR_INTC_MAX_NUM_INTR_INPUTS; xInterruptNumber++ ) + { + if( ulInterruptStatus & 0x01UL ) + { + /* Clear the pending interrupt. */ + XIntc_mAckIntr( pxInterruptController->BaseAddress, ulInterruptMask ); + + /* Call the registered handler. */ + pxTable = &( pxInterruptController->HandlerTable[ xInterruptNumber ] ); + pxTable->Handler( pxTable->CallBackRef ); + } + + /* Check the next interrupt. */ + ulInterruptMask <<= 0x01UL; + ulInterruptStatus >>= 0x01UL; + + /* Have we serviced all interrupts? */ + if( ulInterruptStatus == 0UL ) + { + break; + } + } +} +/*-----------------------------------------------------------*/ + +void vPortSetupInterruptController( void ) +{ +extern void vPortISRWrapper( void ); + + /* Perform all library calls necessary to initialise the exception table + and interrupt controller. This assumes only one interrupt controller is in + use. */ + XExc_mDisableExceptions( XEXC_NON_CRITICAL ); + XExc_Init(); + + /* The library functions save the context - we then jump to a wrapper to + save the stack into the TCB. The wrapper then calls the handler defined + above. */ + XExc_RegisterHandler( XEXC_ID_NON_CRITICAL_INT, ( XExceptionHandler ) vPortISRWrapper, NULL ); + XIntc_Initialize( &xInterruptController, XPAR_XPS_INTC_0_DEVICE_ID ); + XIntc_Start( &xInterruptController, XIN_REAL_MODE ); +} +/*-----------------------------------------------------------*/ + +portBASE_TYPE xPortInstallInterruptHandler( unsigned char ucInterruptID, XInterruptHandler pxHandler, void *pvCallBackRef ) +{ +portBASE_TYPE xReturn = pdFAIL; + + /* This function is defined here so the scope of xInterruptController can + remain within this file. */ + + if( XST_SUCCESS == XIntc_Connect( &xInterruptController, ucInterruptID, pxHandler, pvCallBackRef ) ) + { + XIntc_Enable( &xInterruptController, ucInterruptID ); + xReturn = pdPASS; + } + + return xReturn; +} diff --git a/pool/shard002/C/0057235_CWE78_OS_Command_Injection__char_console_popen_53a.c b/pool/shard002/C/0057235_CWE78_OS_Command_Injection__char_console_popen_53a.c new file mode 100644 index 0000000000000000000000000000000000000000..b92bbf1e2c93ec00783a3d2e97155a1ec342ce7f --- /dev/null +++ b/pool/shard002/C/0057235_CWE78_OS_Command_Injection__char_console_popen_53a.c @@ -0,0 +1,125 @@ +/* TEMPLATE GENERATED TESTCASE FILE +Filename: CWE78_OS_Command_Injection__char_console_popen_53a.c +Label Definition File: CWE78_OS_Command_Injection.one_string.label.xml +Template File: sources-sink-53a.tmpl.c +*/ +/* + * @description + * CWE: 78 OS Command Injection + * BadSource: console Read input from the console + * GoodSource: Fixed string + * Sink: popen + * BadSink : Execute command in data using popen() + * 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 FULL_COMMAND "%WINDIR%\\system32\\cmd.exe /c dir " +#else +#include +#define FULL_COMMAND "/bin/sh ls -la " +#endif + +/* define POPEN as _popen on Windows and popen otherwise */ +#ifdef _WIN32 +#define POPEN _popen +#define PCLOSE _pclose +#else /* NOT _WIN32 */ +#define POPEN popen +#define PCLOSE pclose +#endif + +#ifndef OMITBAD + +/* bad function declaration */ +void CWE78_OS_Command_Injection__char_console_popen_53b_badSink(char * data); + +void CWE78_OS_Command_Injection__char_console_popen_53_bad() +{ + char * data; + char data_buf[100] = FULL_COMMAND; + data = data_buf; + { + /* Read input from the console */ + size_t dataLen = strlen(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 (fgets(data+dataLen, (int)(100-dataLen), stdin) != NULL) + { + /* The next few lines remove the carriage return from the string that is + * inserted by fgets() */ + dataLen = strlen(data); + if (dataLen > 0 && data[dataLen-1] == '\n') + { + data[dataLen-1] = '\0'; + } + } + else + { + printLine("fgets() failed"); + /* Restore NUL terminator if fgets fails */ + data[dataLen] = '\0'; + } + } + } + CWE78_OS_Command_Injection__char_console_popen_53b_badSink(data); +} + +#endif /* OMITBAD */ + +#ifndef OMITGOOD + +/* good function declaration */ +void CWE78_OS_Command_Injection__char_console_popen_53b_goodG2BSink(char * data); + +/* goodG2B uses the GoodSource with the BadSink */ +static void goodG2B() +{ + char * data; + char data_buf[100] = FULL_COMMAND; + data = data_buf; + /* FIX: Append a fixed string to data (not user / external input) */ + strcat(data, "*.*"); + CWE78_OS_Command_Injection__char_console_popen_53b_goodG2BSink(data); +} + +void CWE78_OS_Command_Injection__char_console_popen_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__char_console_popen_53_good(); + printLine("Finished good()"); +#endif /* OMITGOOD */ +#ifndef OMITBAD + printLine("Calling bad()..."); + CWE78_OS_Command_Injection__char_console_popen_53_bad(); + printLine("Finished bad()"); +#endif /* OMITBAD */ + return 0; +} + +#endif diff --git a/pool/shard002/C/0057244_geom_kern.c b/pool/shard002/C/0057244_geom_kern.c new file mode 100644 index 0000000000000000000000000000000000000000..e3585a3f1d8594ba131958f8a8dc31256d6b6aa6 --- /dev/null +++ b/pool/shard002/C/0057244_geom_kern.c @@ -0,0 +1,244 @@ +/*- + * Copyright (c) 2002 Poul-Henning Kamp + * Copyright (c) 2002 Networks Associates Technology, Inc. + * All rights reserved. + * + * This software was developed for the FreeBSD Project by Poul-Henning Kamp + * and NAI Labs, the Security Research Division of Network Associates, Inc. + * under DARPA/SPAWAR contract N66001-01-C-8035 ("CBOSS"), as part of the + * DARPA CHATS research program. + * + * 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 names of the authors 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 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. + * + * $FreeBSD: src/sys/geom/geom_kern.c,v 1.15.2.1 2003/01/02 19:59:57 phk Exp $ + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +MALLOC_DEFINE(M_GEOM, "GEOM", "Geom data structures"); + +struct sx topology_lock; + +static struct proc *g_up_proc; + +int g_debugflags; + +/* + * G_UP and G_DOWN are the two threads which push I/O through the + * stack. + * + * Things are procesed in a FIFO order, but these threads could be + * part of I/O prioritization by deciding which bios/bioqs to service + * in what order. + * + * We have only one thread in each direction, it is belived that until + * a very non-trivial workload in the UP/DOWN path this will be enough, + * but more than one can actually be run without problems. + * + * Holding the "mymutex" is a debugging feature: It prevents people + * from sleeping in the UP/DOWN I/O path by mistake or design (doing + * so almost invariably result in deadlocks since it stalls all I/O + * processing in the given direction. + */ + +static void +g_up_procbody(void) +{ + struct proc *p = g_up_proc; + struct thread *tp = FIRST_THREAD_IN_PROC(p); + struct mtx mymutex; + + mtx_assert(&Giant, MA_NOTOWNED); + bzero(&mymutex, sizeof mymutex); + mtx_init(&mymutex, "g_up", MTX_DEF, 0); + mtx_lock(&mymutex); + tp->td_base_pri = PRIBIO; + for(;;) { + g_io_schedule_up(tp); + msleep(&g_wait_up, &mymutex, PRIBIO, "g_up", hz/10); + } +} + +struct kproc_desc g_up_kp = { + "g_up", + g_up_procbody, + &g_up_proc, +}; + +static struct proc *g_down_proc; + +static void +g_down_procbody(void) +{ + struct proc *p = g_down_proc; + struct thread *tp = FIRST_THREAD_IN_PROC(p); + struct mtx mymutex; + + mtx_assert(&Giant, MA_NOTOWNED); + bzero(&mymutex, sizeof mymutex); + mtx_init(&mymutex, "g_down", MTX_DEF, 0); + mtx_lock(&mymutex); + tp->td_base_pri = PRIBIO; + for(;;) { + g_io_schedule_down(tp); + msleep(&g_wait_down, &mymutex, PRIBIO, "g_down", hz/10); + } +} + +struct kproc_desc g_down_kp = { + "g_down", + g_down_procbody, + &g_down_proc, +}; + +static struct proc *g_event_proc; + +static void +g_event_procbody(void) +{ + struct proc *p = g_event_proc; + struct thread *tp = FIRST_THREAD_IN_PROC(p); + + mtx_assert(&Giant, MA_NOTOWNED); + tp->td_base_pri = PRIBIO; + for(;;) { + g_run_events(); + tsleep(&g_wait_event, PRIBIO, "g_events", hz/10); + } +} + +struct kproc_desc g_event_kp = { + "g_event", + g_event_procbody, + &g_event_proc, +}; + +void +g_init(void) +{ + printf("Initializing GEOMetry subsystem\n"); + sx_init(&topology_lock, "GEOM topology"); + g_io_init(); + g_event_init(); + mtx_lock(&Giant); + kproc_start(&g_event_kp); + kproc_start(&g_up_kp); + kproc_start(&g_down_kp); + mtx_unlock(&Giant); +} + +static int +sysctl_kern_geom_conftxt(SYSCTL_HANDLER_ARGS) +{ + int error; + struct sbuf *sb; + + sb = sbuf_new(NULL, NULL, 0, SBUF_AUTOEXTEND); + sbuf_clear(sb); + g_call_me(g_conftxt, sb); + do { + tsleep(sb, PZERO, "g_dot", hz); + } while(!sbuf_done(sb)); + error = SYSCTL_OUT(req, sbuf_data(sb), sbuf_len(sb) + 1); + sbuf_delete(sb); + return error; +} + +static int +sysctl_kern_geom_confdot(SYSCTL_HANDLER_ARGS) +{ + int error; + struct sbuf *sb; + + sb = sbuf_new(NULL, NULL, 0, SBUF_AUTOEXTEND); + sbuf_clear(sb); + g_call_me(g_confdot, sb); + do { + tsleep(sb, PZERO, "g_dot", hz); + } while(!sbuf_done(sb)); + error = SYSCTL_OUT(req, sbuf_data(sb), sbuf_len(sb) + 1); + sbuf_delete(sb); + return error; +} + +static int +sysctl_kern_geom_confxml(SYSCTL_HANDLER_ARGS) +{ + int error; + struct sbuf *sb; + + sb = sbuf_new(NULL, NULL, 0, SBUF_AUTOEXTEND); + sbuf_clear(sb); + g_call_me(g_confxml, sb); + do { + tsleep(sb, PZERO, "g_xml", hz); + } while(!sbuf_done(sb)); + error = SYSCTL_OUT(req, sbuf_data(sb), sbuf_len(sb) + 1); + sbuf_delete(sb); + return error; +} + +SYSCTL_NODE(_kern, OID_AUTO, geom, CTLFLAG_RW, 0, "GEOMetry management"); + +SYSCTL_PROC(_kern_geom, OID_AUTO, confxml, CTLTYPE_STRING|CTLFLAG_RD, + 0, 0, sysctl_kern_geom_confxml, "", + "Dump the GEOM config in XML"); + +SYSCTL_PROC(_kern_geom, OID_AUTO, confdot, CTLTYPE_STRING|CTLFLAG_RD, + 0, 0, sysctl_kern_geom_confdot, "", + "Dump the GEOM config in dot"); + +SYSCTL_PROC(_kern_geom, OID_AUTO, conftxt, CTLTYPE_STRING|CTLFLAG_RD, + 0, 0, sysctl_kern_geom_conftxt, "", + "Dump the GEOM config in txt"); + +SYSCTL_INT(_kern_geom, OID_AUTO, debugflags, CTLFLAG_RW, + &g_debugflags, 0, ""); + +SYSCTL_INT(_debug_sizeof, OID_AUTO, g_class, CTLFLAG_RD, + 0, sizeof(struct g_class), ""); +SYSCTL_INT(_debug_sizeof, OID_AUTO, g_geom, CTLFLAG_RD, + 0, sizeof(struct g_geom), ""); +SYSCTL_INT(_debug_sizeof, OID_AUTO, g_provider, CTLFLAG_RD, + 0, sizeof(struct g_provider), ""); +SYSCTL_INT(_debug_sizeof, OID_AUTO, g_consumer, CTLFLAG_RD, + 0, sizeof(struct g_consumer), ""); +SYSCTL_INT(_debug_sizeof, OID_AUTO, g_bioq, CTLFLAG_RD, + 0, sizeof(struct g_bioq), ""); +SYSCTL_INT(_debug_sizeof, OID_AUTO, g_event, CTLFLAG_RD, + 0, sizeof(struct g_event), ""); diff --git a/pool/shard002/C/0057249_eg0805.c b/pool/shard002/C/0057249_eg0805.c new file mode 100644 index 0000000000000000000000000000000000000000..47841469ca477a67863b723a4990b8e54d0d0392 --- /dev/null +++ b/pool/shard002/C/0057249_eg0805.c @@ -0,0 +1,31 @@ +/* + * eg0805.c + * demo of race condition. + */ +#include +#include +#include "../com/comhdr.h" + +static void charactatime( char *buf ); + +int main( int argc, char **argv ) { + pid_t pid; + + if ( (pid = fork()) < 0 ) { + err_sys( "error on fork" ); + } else if ( pid == 0 ) { + charactatime( "output from child\n" ); + } else { + charactatime( "output from parent\n" ); + } + return 0; +} + +static void charactatime( char *buf ) { + char *ptr; + int ch; + setbuf( stdout, NULL ); + for ( ptr = buf; ch = *buf++; ) { + putc( ch, stdout ); + } +} diff --git a/pool/shard002/C/0057262_pwm_bl.c b/pool/shard002/C/0057262_pwm_bl.c new file mode 100644 index 0000000000000000000000000000000000000000..b181cc291841c6b6036b50654d563971b4bda5d8 --- /dev/null +++ b/pool/shard002/C/0057262_pwm_bl.c @@ -0,0 +1,227 @@ +/* + * linux/drivers/video/backlight/pwm_bl.c + * + * simple PWM based backlight control, board code has to setup + * 1) pin configuration so PWM waveforms can output + * 2) platform_data being correctly configured + * + * 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 pwm_bl_data { + struct pwm_device *pwm; + struct device *dev; + unsigned int period; + unsigned int lth_brightness; + int (*notify)(struct device *, + int brightness); + void (*notify_after)(struct device *, + int brightness); + int (*check_fb)(struct device *, struct fb_info *); +}; + +static unsigned int min_brightness = 2; +module_param(min_brightness, int, 0664); + +static int pwm_backlight_update_status(struct backlight_device *bl) +{ + struct pwm_bl_data *pb = dev_get_drvdata(&bl->dev); + int brightness = bl->props.brightness; + int max = bl->props.max_brightness; + + if (bl->props.power != FB_BLANK_UNBLANK) + brightness = 0; + + if (bl->props.fb_blank != FB_BLANK_UNBLANK) + brightness = 0; + + if (pb->notify) + brightness = pb->notify(pb->dev, brightness); + + if (brightness == 0) { + pwm_config(pb->pwm, 0, pb->period); + pwm_disable(pb->pwm); + } else { + if (brightness <= 10) { + if (unlikely(min_brightness <= 1)) + min_brightness = 2; + + if (unlikely(min_brightness > 10)) + min_brightness = 10; + + brightness = min_brightness; + } + + brightness = pb->lth_brightness + + (brightness * (pb->period - pb->lth_brightness) / max); + + pwm_config(pb->pwm, brightness, pb->period); + pwm_enable(pb->pwm); + } + + if (pb->notify_after) + pb->notify_after(pb->dev, brightness); + + return 0; +} + +static int pwm_backlight_get_brightness(struct backlight_device *bl) +{ + return bl->props.brightness; +} + +static int pwm_backlight_check_fb(struct backlight_device *bl, + struct fb_info *info) +{ + struct pwm_bl_data *pb = dev_get_drvdata(&bl->dev); + + return !pb->check_fb || pb->check_fb(pb->dev, info); +} + +static const struct backlight_ops pwm_backlight_ops = { + .update_status = pwm_backlight_update_status, + .get_brightness = pwm_backlight_get_brightness, + .check_fb = pwm_backlight_check_fb, +}; + +static int pwm_backlight_probe(struct platform_device *pdev) +{ + struct backlight_properties props; + struct platform_pwm_backlight_data *data = pdev->dev.platform_data; + struct backlight_device *bl; + struct pwm_bl_data *pb; + int ret; + + if (!data) { + dev_err(&pdev->dev, "failed to find platform data\n"); + return -EINVAL; + } + + if (data->init) { + ret = data->init(&pdev->dev); + if (ret < 0) + return ret; + } + + pb = devm_kzalloc(&pdev->dev, sizeof(*pb), GFP_KERNEL); + if (!pb) { + dev_err(&pdev->dev, "no memory for state\n"); + ret = -ENOMEM; + goto err_alloc; + } + + pb->period = data->pwm_period_ns; + pb->notify = data->notify; + pb->notify_after = data->notify_after; + pb->check_fb = data->check_fb; + pb->lth_brightness = data->lth_brightness * + (data->pwm_period_ns / data->max_brightness); + pb->dev = &pdev->dev; + + pb->pwm = pwm_request(data->pwm_id, "backlight"); + if (IS_ERR(pb->pwm)) { + dev_err(&pdev->dev, "unable to request PWM for backlight\n"); + ret = PTR_ERR(pb->pwm); + goto err_alloc; + } else + dev_dbg(&pdev->dev, "got pwm for backlight\n"); + + memset(&props, 0, sizeof(struct backlight_properties)); + props.type = BACKLIGHT_RAW; + props.max_brightness = data->max_brightness; + bl = backlight_device_register(dev_name(&pdev->dev), &pdev->dev, pb, + &pwm_backlight_ops, &props); + if (IS_ERR(bl)) { + dev_err(&pdev->dev, "failed to register backlight\n"); + ret = PTR_ERR(bl); + goto err_bl; + } + + bl->props.brightness = data->dft_brightness; + backlight_update_status(bl); + + platform_set_drvdata(pdev, bl); + return 0; + +err_bl: + pwm_free(pb->pwm); +err_alloc: + if (data->exit) + data->exit(&pdev->dev); + return ret; +} + +static int pwm_backlight_remove(struct platform_device *pdev) +{ + struct platform_pwm_backlight_data *data = pdev->dev.platform_data; + struct backlight_device *bl = platform_get_drvdata(pdev); + struct pwm_bl_data *pb = dev_get_drvdata(&bl->dev); + + backlight_device_unregister(bl); + pwm_config(pb->pwm, 0, pb->period); + pwm_disable(pb->pwm); + pwm_free(pb->pwm); + if (data->exit) + data->exit(&pdev->dev); + return 0; +} + +#ifdef CONFIG_PM +static int pwm_backlight_suspend(struct device *dev) +{ + struct backlight_device *bl = dev_get_drvdata(dev); + struct pwm_bl_data *pb = dev_get_drvdata(&bl->dev); + + if (pb->notify) + pb->notify(pb->dev, 0); + pwm_config(pb->pwm, 0, pb->period); + pwm_disable(pb->pwm); + if (pb->notify_after) + pb->notify_after(pb->dev, 0); + return 0; +} + +static int pwm_backlight_resume(struct device *dev) +{ + struct backlight_device *bl = dev_get_drvdata(dev); + + backlight_update_status(bl); + return 0; +} + +static SIMPLE_DEV_PM_OPS(pwm_backlight_pm_ops, pwm_backlight_suspend, + pwm_backlight_resume); + +#endif + +static struct platform_driver pwm_backlight_driver = { + .driver = { + .name = "pwm-backlight", + .owner = THIS_MODULE, +#ifdef CONFIG_PM + .pm = &pwm_backlight_pm_ops, +#endif + }, + .probe = pwm_backlight_probe, + .remove = pwm_backlight_remove, +}; + +module_platform_driver(pwm_backlight_driver); + +MODULE_DESCRIPTION("PWM based Backlight Driver"); +MODULE_LICENSE("GPL"); +MODULE_ALIAS("platform:pwm-backlight"); + diff --git a/pool/shard002/C/0057264_init.c b/pool/shard002/C/0057264_init.c new file mode 100644 index 0000000000000000000000000000000000000000..d0b4c2efda90aa1ba8eaf2eabe8a977cb0fe2c9c --- /dev/null +++ b/pool/shard002/C/0057264_init.c @@ -0,0 +1,348 @@ +/* + * Based on arch/arm/mm/init.c + * + * Copyright (C) 1995-2005 Russell King + * Copyright (C) 2012 ARM Ltd. + * + * 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, see . + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +#include "mm.h" + +phys_addr_t memstart_addr __read_mostly = 0; + +#ifdef CONFIG_BLK_DEV_INITRD +static int __init early_initrd(char *p) +{ + unsigned long start, size; + char *endp; + + start = memparse(p, &endp); + if (*endp == ',') { + size = memparse(endp + 1, NULL); + + initrd_start = (unsigned long)__va(start); + initrd_end = (unsigned long)__va(start + size); + } + return 0; +} +early_param("initrd", early_initrd); +#endif + +#define MAX_DMA32_PFN ((4UL * 1024 * 1024 * 1024) >> PAGE_SHIFT) + +static void __init zone_sizes_init(unsigned long min, unsigned long max) +{ + struct memblock_region *reg; + unsigned long zone_size[MAX_NR_ZONES], zhole_size[MAX_NR_ZONES]; + unsigned long max_dma32 = min; + + memset(zone_size, 0, sizeof(zone_size)); + +#ifdef CONFIG_ZONE_DMA32 + /* 4GB maximum for 32-bit only capable devices */ + max_dma32 = max(min, min(max, MAX_DMA32_PFN)); + zone_size[ZONE_DMA32] = max_dma32 - min; +#endif + zone_size[ZONE_NORMAL] = max - max_dma32; + + memcpy(zhole_size, zone_size, sizeof(zhole_size)); + + for_each_memblock(memory, reg) { + unsigned long start = memblock_region_memory_base_pfn(reg); + unsigned long end = memblock_region_memory_end_pfn(reg); + + if (start >= max) + continue; +#ifdef CONFIG_ZONE_DMA32 + if (start < max_dma32) { + unsigned long dma_end = min(end, max_dma32); + zhole_size[ZONE_DMA32] -= dma_end - start; + } +#endif + if (end > max_dma32) { + unsigned long normal_end = min(end, max); + unsigned long normal_start = max(start, max_dma32); + zhole_size[ZONE_NORMAL] -= normal_end - normal_start; + } + } + + free_area_init_node(0, zone_size, min, zhole_size); +} + +#ifdef CONFIG_HAVE_ARCH_PFN_VALID +int pfn_valid(unsigned long pfn) +{ + return memblock_is_memory(pfn << PAGE_SHIFT); +} +EXPORT_SYMBOL(pfn_valid); +#endif + +#ifndef CONFIG_SPARSEMEM +static void arm64_memory_present(void) +{ +} +#else +static void arm64_memory_present(void) +{ + struct memblock_region *reg; + + for_each_memblock(memory, reg) + memory_present(0, memblock_region_memory_base_pfn(reg), + memblock_region_memory_end_pfn(reg)); +} +#endif + +void __init arm64_memblock_init(void) +{ + u64 *reserve_map, base, size; + + /* Register the kernel text, kernel data and initrd with memblock */ + memblock_reserve(__pa(_text), _end - _text); +#ifdef CONFIG_BLK_DEV_INITRD + if (initrd_start) + memblock_reserve(__virt_to_phys(initrd_start), initrd_end - initrd_start); +#endif + + /* + * Reserve the page tables. These are already in use, + * and can only be in node 0. + */ + memblock_reserve(__pa(swapper_pg_dir), SWAPPER_DIR_SIZE); + memblock_reserve(__pa(idmap_pg_dir), IDMAP_DIR_SIZE); + + /* Reserve the dtb region */ + memblock_reserve(virt_to_phys(initial_boot_params), + be32_to_cpu(initial_boot_params->totalsize)); + + /* + * Process the reserve map. This will probably overlap the initrd + * and dtb locations which are already reserved, but overlapping + * doesn't hurt anything + */ + reserve_map = ((void*)initial_boot_params) + + be32_to_cpu(initial_boot_params->off_mem_rsvmap); + while (1) { + base = be64_to_cpup(reserve_map++); + size = be64_to_cpup(reserve_map++); + if (!size) + break; + memblock_reserve(base, size); + } + + dma_contiguous_reserve(0); + + memblock_allow_resize(); + memblock_dump_all(); +} + +void __init bootmem_init(void) +{ + unsigned long min, max; + + min = PFN_UP(memblock_start_of_DRAM()); + max = PFN_DOWN(memblock_end_of_DRAM()); + + /* + * Sparsemem tries to allocate bootmem in memory_present(), so must be + * done after the fixed reservations. + */ + arm64_memory_present(); + + sparse_init(); + zone_sizes_init(min, max); + + high_memory = __va((max << PAGE_SHIFT) - 1) + 1; + max_pfn = max_low_pfn = max; +} + +#ifndef CONFIG_SPARSEMEM_VMEMMAP +static inline void free_memmap(unsigned long start_pfn, unsigned long end_pfn) +{ + struct page *start_pg, *end_pg; + unsigned long pg, pgend; + + /* + * Convert start_pfn/end_pfn to a struct page pointer. + */ + start_pg = pfn_to_page(start_pfn - 1) + 1; + end_pg = pfn_to_page(end_pfn - 1) + 1; + + /* + * Convert to physical addresses, and round start upwards and end + * downwards. + */ + pg = (unsigned long)PAGE_ALIGN(__pa(start_pg)); + pgend = (unsigned long)__pa(end_pg) & PAGE_MASK; + + /* + * If there are free pages between these, free the section of the + * memmap array. + */ + if (pg < pgend) + free_bootmem(pg, pgend - pg); +} + +/* + * The mem_map array can get very big. Free the unused area of the memory map. + */ +static void __init free_unused_memmap(void) +{ + unsigned long start, prev_end = 0; + struct memblock_region *reg; + + for_each_memblock(memory, reg) { + start = __phys_to_pfn(reg->base); + +#ifdef CONFIG_SPARSEMEM + /* + * Take care not to free memmap entries that don't exist due + * to SPARSEMEM sections which aren't present. + */ + start = min(start, ALIGN(prev_end, PAGES_PER_SECTION)); +#endif + /* + * If we had a previous bank, and there is a space between the + * current bank and the previous, free it. + */ + if (prev_end && prev_end < start) + free_memmap(prev_end, start); + + /* + * Align up here since the VM subsystem insists that the + * memmap entries are valid from the bank end aligned to + * MAX_ORDER_NR_PAGES. + */ + prev_end = ALIGN(start + __phys_to_pfn(reg->size), + MAX_ORDER_NR_PAGES); + } + +#ifdef CONFIG_SPARSEMEM + if (!IS_ALIGNED(prev_end, PAGES_PER_SECTION)) + free_memmap(prev_end, ALIGN(prev_end, PAGES_PER_SECTION)); +#endif +} +#endif /* !CONFIG_SPARSEMEM_VMEMMAP */ + +/* + * mem_init() marks the free areas in the mem_map and tells us how much memory + * is free. This is done after various parts of the system have claimed their + * memory after the kernel image. + */ +void __init mem_init(void) +{ + arm64_swiotlb_init(); + + max_mapnr = pfn_to_page(max_pfn + PHYS_PFN_OFFSET) - mem_map; + +#ifndef CONFIG_SPARSEMEM_VMEMMAP + free_unused_memmap(); +#endif + /* this will put all unused low memory onto the freelists */ + free_all_bootmem(); + + mem_init_print_info(NULL); + +#define MLK(b, t) b, t, ((t) - (b)) >> 10 +#define MLM(b, t) b, t, ((t) - (b)) >> 20 +#define MLK_ROUNDUP(b, t) b, t, DIV_ROUND_UP(((t) - (b)), SZ_1K) + + pr_notice("Virtual kernel memory layout:\n" + " vmalloc : 0x%16lx - 0x%16lx (%6ld MB)\n" +#ifdef CONFIG_SPARSEMEM_VMEMMAP + " vmemmap : 0x%16lx - 0x%16lx (%6ld MB)\n" +#endif + " modules : 0x%16lx - 0x%16lx (%6ld MB)\n" + " memory : 0x%16lx - 0x%16lx (%6ld MB)\n" + " .init : 0x%p" " - 0x%p" " (%6ld kB)\n" + " .text : 0x%p" " - 0x%p" " (%6ld kB)\n" + " .data : 0x%p" " - 0x%p" " (%6ld kB)\n", + MLM(VMALLOC_START, VMALLOC_END), +#ifdef CONFIG_SPARSEMEM_VMEMMAP + MLM((unsigned long)virt_to_page(PAGE_OFFSET), + (unsigned long)virt_to_page(high_memory)), +#endif + MLM(MODULES_VADDR, MODULES_END), + MLM(PAGE_OFFSET, (unsigned long)high_memory), + + MLK_ROUNDUP(__init_begin, __init_end), + MLK_ROUNDUP(_text, _etext), + MLK_ROUNDUP(_sdata, _edata)); + +#undef MLK +#undef MLM +#undef MLK_ROUNDUP + + /* + * Check boundaries twice: Some fundamental inconsistencies can be + * detected at build time already. + */ +#ifdef CONFIG_COMPAT + BUILD_BUG_ON(TASK_SIZE_32 > TASK_SIZE_64); +#endif + BUILD_BUG_ON(TASK_SIZE_64 > MODULES_VADDR); + BUG_ON(TASK_SIZE_64 > MODULES_VADDR); + + if (PAGE_SIZE >= 16384 && get_num_physpages() <= 128) { + extern int sysctl_overcommit_memory; + /* + * On a machine this small we won't get anywhere without + * overcommit, so turn it on by default. + */ + sysctl_overcommit_memory = OVERCOMMIT_ALWAYS; + } +} + +void free_initmem(void) +{ + free_initmem_default(0); +} + +#ifdef CONFIG_BLK_DEV_INITRD + +static int keep_initrd; + +void free_initrd_mem(unsigned long start, unsigned long end) +{ + if (!keep_initrd) + free_reserved_area((void *)start, (void *)end, 0, "initrd"); +} + +static int __init keepinitrd_setup(char *__unused) +{ + keep_initrd = 1; + return 1; +} + +__setup("keepinitrd", keepinitrd_setup); +#endif diff --git a/pool/shard002/C/0057272_t-sub_series.c b/pool/shard002/C/0057272_t-sub_series.c new file mode 100644 index 0000000000000000000000000000000000000000..8e3a8dabc4ca08feb62c7d187efbbae6a2117380 --- /dev/null +++ b/pool/shard002/C/0057272_t-sub_series.c @@ -0,0 +1,150 @@ +/* + Copyright (C) 2011, 2010 Sebastian Pancratz + Copyright (C) 2009, 2014 William Hart + + This file is part of FLINT. + + FLINT 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. See . +*/ + +#include +#include +#include +#include "flint.h" +#include "fmpz.h" +#include "fmpz_mod_poly.h" +#include "ulong_extras.h" + +int +main(void) +{ + int i, result; + FLINT_TEST_INIT(state); + + flint_printf("sub_series...."); + fflush(stdout); + + /* Check aliasing of a and c */ + for (i = 0; i < 1000 * flint_test_multiplier(); i++) + { + fmpz_t p; + fmpz_mod_poly_t a, b, c; + slong n; + + fmpz_init(p); + fmpz_randtest_unsigned(p, state, 2 * FLINT_BITS); + fmpz_add_ui(p, p, 2); + + fmpz_mod_poly_init(a, p); + fmpz_mod_poly_init(b, p); + fmpz_mod_poly_init(c, p); + fmpz_mod_poly_randtest(a, state, n_randint(state, 100)); + fmpz_mod_poly_randtest(b, state, n_randint(state, 100)); + n = n_randint(state, 100); + + fmpz_mod_poly_sub_series(c, a, b, n); + fmpz_mod_poly_sub_series(a, a, b, n); + + result = (fmpz_mod_poly_equal(a, c)); + if (!result) + { + flint_printf("FAIL:\n"); + fmpz_mod_poly_print(a), flint_printf("\n\n"); + fmpz_mod_poly_print(b), flint_printf("\n\n"); + fmpz_mod_poly_print(c), flint_printf("\n\n"); + abort(); + } + + fmpz_mod_poly_clear(a); + fmpz_mod_poly_clear(b); + fmpz_mod_poly_clear(c); + fmpz_clear(p); + } + + /* Check aliasing of b and c */ + for (i = 0; i < 1000 * flint_test_multiplier(); i++) + { + fmpz_t p; + fmpz_mod_poly_t a, b, c; + slong n; + + fmpz_init(p); + fmpz_randtest_unsigned(p, state, 2 * FLINT_BITS); + fmpz_add_ui(p, p, 2); + + fmpz_mod_poly_init(a, p); + fmpz_mod_poly_init(b, p); + fmpz_mod_poly_init(c, p); + fmpz_mod_poly_randtest(a, state, n_randint(state, 100)); + fmpz_mod_poly_randtest(b, state, n_randint(state, 100)); + n = n_randint(state, 100); + + fmpz_mod_poly_sub_series(c, a, b, n); + fmpz_mod_poly_sub_series(b, a, b, n); + + result = (fmpz_mod_poly_equal(b, c)); + if (!result) + { + flint_printf("FAIL:\n"); + fmpz_mod_poly_print(a), flint_printf("\n\n"); + fmpz_mod_poly_print(b), flint_printf("\n\n"); + fmpz_mod_poly_print(c), flint_printf("\n\n"); + abort(); + } + + fmpz_mod_poly_clear(a); + fmpz_mod_poly_clear(b); + fmpz_mod_poly_clear(c); + fmpz_clear(p); + } + + /* Check truncate(a + b, n) = add_series(a, b, n) */ + for (i = 0; i < 1000 * flint_test_multiplier(); i++) + { + fmpz_t p; + fmpz_mod_poly_t a, b, c, d; + slong n; + + fmpz_init(p); + fmpz_randtest_unsigned(p, state, 2 * FLINT_BITS); + fmpz_add_ui(p, p, 2); + + fmpz_mod_poly_init(a, p); + fmpz_mod_poly_init(b, p); + fmpz_mod_poly_init(c, p); + fmpz_mod_poly_init(d, p); + fmpz_mod_poly_randtest(a, state, n_randint(state, 100)); + fmpz_mod_poly_randtest(b, state, n_randint(state, 100)); + n = n_randint(state, 100); + + fmpz_mod_poly_sub(c, a, b); + fmpz_mod_poly_truncate(c, n); + fmpz_mod_poly_sub_series(d, a, b, n); + + result = (fmpz_mod_poly_equal(d, c)); + if (!result) + { + flint_printf("FAIL:\n"); + fmpz_mod_poly_print(a), flint_printf("\n\n"); + fmpz_mod_poly_print(b), flint_printf("\n\n"); + fmpz_mod_poly_print(c), flint_printf("\n\n"); + fmpz_mod_poly_print(d), flint_printf("\n\n"); + abort(); + } + + fmpz_mod_poly_clear(a); + fmpz_mod_poly_clear(b); + fmpz_mod_poly_clear(c); + fmpz_mod_poly_clear(d); + fmpz_clear(p); + } + + FLINT_TEST_CLEANUP(state); + + flint_printf("PASS\n"); + return 0; +} + diff --git a/pool/shard002/C/0057288_superio.c b/pool/shard002/C/0057288_superio.c new file mode 100644 index 0000000000000000000000000000000000000000..0a42d137cc0ea105ed40f92e217c98e3a2d16973 --- /dev/null +++ b/pool/shard002/C/0057288_superio.c @@ -0,0 +1,61 @@ +/* + * This file is part of the coreboot project. + * + * Copyright (C) 2011 Advanced Micro Devices, 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. + */ + +#include +#include +#include +#include +#include +#include +#include +#include "wpcm450.h" + +static void init(struct device *dev) +{ + + if (!dev->enabled) + return; + + switch(dev->path.pnp.device) { + case WPCM450_KBCK: + pc_keyboard_init(NO_AUX_DEVICE); + break; + } +} + +static struct device_operations ops = { + .read_resources = pnp_read_resources, + .set_resources = pnp_set_resources, + .enable_resources = pnp_enable_resources, + .enable = pnp_enable, + .init = init, +}; + +static struct pnp_info pnp_dev_info[] = { + { &ops, WPCM450_SP2, PNP_IO0 | PNP_IRQ0 | PNP_DRQ0 | PNP_DRQ1, 0x07f8, }, + { &ops, WPCM450_SP1, PNP_IO0 | PNP_IRQ0, 0x07f8, }, + { &ops, WPCM450_KBCK, PNP_IO0 | PNP_IO1 | PNP_IRQ0, 0x07f8, 0x07f8, }, +}; + +static void enable_dev(struct device *dev) +{ + pnp_enable_devices(dev, &ops, ARRAY_SIZE(pnp_dev_info), pnp_dev_info); +} + +struct chip_operations superio_nuvoton_wpcm450_ops = { + CHIP_NAME("Nuvoton WPCM450 Super I/O") + .enable_dev = enable_dev, +}; diff --git a/pool/shard002/C/0057296_frmt.c b/pool/shard002/C/0057296_frmt.c new file mode 100644 index 0000000000000000000000000000000000000000..310e88c4b1858d8222757953108889032c46fb86 --- /dev/null +++ b/pool/shard002/C/0057296_frmt.c @@ -0,0 +1,110 @@ +/* + **************************************************************************** + * + * MODULE: Vector library + * + * AUTHOR(S): Radim Blazek + * + * PURPOSE: Lower level functions for reading/writing/manipulating vectors. + * + * COPYRIGHT: (C) 2001 by the GRASS Development Team + * + * This program is free software under the GNU General Public + * License (>=v2). Read the file COPYING that comes with GRASS + * for details. + * + *****************************************************************************/ +#include +#include +#include + +/*! + \brief Read external vector format file + + \param dascii format file (frmt) + \param[out] finfo pointer to Format_info structure + + \return format code + \return -1 on error +*/ +int dig_read_frmt_ascii(FILE * dascii, struct Format_info *finfo) +{ + char buff[20001], buf1[1024]; + char *ptr; + int frmt = -1; + + G_debug(3, "dig_read_frmt_ascii()"); + + /* read first line which must be FORMAT: */ + if (G_getl2(buff, 2000, dascii)) { + G_chop(buff); + + if (!(ptr = strchr(buff, ':'))) { + G_warning("Vector format not recognized: %s", buff); + return (-1); + } + + strcpy(buf1, buff); + buf1[ptr - buff] = '\0'; + + ptr++; /* Search for the start of text */ + while (*ptr == ' ') + ptr++; + + if (strcmp(buf1, "FORMAT") == 0) { + if (G_strcasecmp(ptr, "ogr") == 0) { + frmt = GV_FORMAT_OGR; + } + } + } + if (frmt == -1) { + G_warning("Vector format not recognized: %s", buff); + return (-1); + } + + /* init format info values */ +#ifdef HAVE_OGR + finfo->ogr.dsn = NULL; + finfo->ogr.layer_name = NULL; +#endif + + while (G_getl2(buff, 2000, dascii)) { + G_chop(buff); + + if (!(ptr = strchr(buff, ':'))) { + G_warning("Format definition is not correct: %s", buff); + continue; + } + + strcpy(buf1, buff); + buf1[ptr - buff] = '\0'; + + ptr++; /* Search for the start of text */ + while (*ptr == ' ') + ptr++; + +#ifdef HAVE_OGR + if (strcmp(buf1, "DSN") == 0) + finfo->ogr.dsn = G_store(ptr); + if (strcmp(buf1, "LAYER") == 0) + finfo->ogr.layer_name = G_store(ptr); +#endif + } + + return frmt; +} + +/* Write vector format, currently does not work + * Parse also connection string. + * + * Returns: 0 OK + * -1 on error + */ +int dig_write_frmt_ascii(FILE * dascii, struct Format_info *finfo, int format) +{ + G_debug(3, "dig_write_frmt_ascii()"); + + G_fatal_error("Format not supported by dig_write_frmt_ascii()"); + + return 0; +} diff --git a/pool/shard002/C/0057303_Combinations.c b/pool/shard002/C/0057303_Combinations.c new file mode 100644 index 0000000000000000000000000000000000000000..0794dc84bab8065b9fe2063a410e9702e7c08334 --- /dev/null +++ b/pool/shard002/C/0057303_Combinations.c @@ -0,0 +1,55 @@ +class Solution { +public: + vector> return_list; + + int get_true_count(vector& nums) { + int count = 0; + + for (int i = 0; i < nums.size(); i++) + count += nums.at(i); + + return count; + } + + int is_a_solution(vector& nums, int n, int k) { + return get_true_count(nums) == k ? true : false; + } + + int process_solution(vector& nums) { + vector v; + + for (int i = 0; i < nums.size(); i++) { + if (nums.at(i) == 1) + v.push_back(i+1); + } + + return_list.push_back(v); + } + + void construct_cand(vector& nums, int n, int k, vector& c) { + c.clear(); + if (nums.size() == n) + return; + c.push_back(1); + c.push_back(0); + } + + void backtrack(vector& nums, int n, int k) { + if (is_a_solution(nums, n, k)) + process_solution(nums); + else { + vector c; + construct_cand(nums, n, k, c); + for (int i = 0; i < c.size(); i++) { + nums.push_back(c.at(i)); + backtrack(nums, n, k); + nums.pop_back(); + } + } + } + vector> combine(int n, int k) { + vector nums; + backtrack(nums, n, k); + return return_list; + } +}; \ No newline at end of file diff --git a/pool/shard002/C/0057313_sdklauncher.c b/pool/shard002/C/0057313_sdklauncher.c new file mode 100644 index 0000000000000000000000000000000000000000..fd03d9932f9ce9c221f17da936bc7fd963aadbe5 --- /dev/null +++ b/pool/shard002/C/0057313_sdklauncher.c @@ -0,0 +1,134 @@ +/* + * Copyright (C) 2009 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/* + * The "SDK Manager" is for Windows only. + * This simple .exe will sit at the root of the Windows SDK + * and currently simply executes tools\android.bat. + * + * TODO: replace by a jar-exe wrapper. + */ + +#ifdef _WIN32 + +#include +#include +#include +#include + + +int _enable_dprintf = 0; + +void dprintf(char *msg, ...) { + va_list ap; + va_start(ap, msg); + + if (_enable_dprintf) { + vfprintf(stderr, msg, ap); + } + + va_end(ap); +} + +void display_error(LPSTR description) { + DWORD err = GetLastError(); + LPSTR s, s2; + + fprintf(stderr, "%s, error %ld\n", description, err); + + if (FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | /* dwFlags */ + FORMAT_MESSAGE_FROM_SYSTEM, + NULL, /* lpSource */ + err, /* dwMessageId */ + 0, /* dwLanguageId */ + (LPSTR)&s, /* lpBuffer */ + 0, /* nSize */ + NULL) != 0) { /* va_list args */ + fprintf(stderr, "%s", s); + + s2 = (LPSTR) malloc(strlen(description) + strlen(s) + 5); + sprintf(s2, "%s\r\n%s", description, s); + MessageBox(NULL, s2, "Android SDK Manager - Error", MB_OK); + free(s2); + LocalFree(s); + } +} + + +int sdk_launcher() { + int result = 0; + STARTUPINFO startup; + PROCESS_INFORMATION pinfo; + CHAR program_dir[MAX_PATH]; + int ret, pos; + + ZeroMemory(&pinfo, sizeof(pinfo)); + + ZeroMemory(&startup, sizeof(startup)); + startup.cb = sizeof(startup); + startup.dwFlags = STARTF_USESHOWWINDOW; + startup.wShowWindow = SW_HIDE|SW_MINIMIZE; + + /* get path of current program, to switch dirs here when executing the command. */ + ret = GetModuleFileName(NULL, program_dir, sizeof(program_dir)); + if (ret == 0) { + display_error("Failed to get program's filename:"); + result = 1; + } else { + /* Remove the last segment to keep only the directory. */ + pos = ret - 1; + while (pos > 0 && program_dir[pos] != '\\') { + --pos; + } + program_dir[pos] = 0; + } + + if (!result) { + dprintf("Program dir: %s\n", program_dir); + + ret = CreateProcess( + NULL, /* program path */ + "tools\\android.bat sdk", /* command-line */ + NULL, /* process handle is not inheritable */ + NULL, /* thread handle is not inheritable */ + TRUE, /* yes, inherit some handles */ + CREATE_NO_WINDOW, /* we don't want a console */ + NULL, /* use parent's environment block */ + program_dir, /* use parent's starting directory */ + &startup, /* startup info, i.e. std handles */ + &pinfo); + + dprintf("CreateProcess returned %d\n", ret); + + if (!ret) { + display_error("Failed to execute tools\\android.bat:"); + result = 1; + } + } + + dprintf("Cleanup.\n"); + + return result; +} + +int main(int argc, char **argv) { + _enable_dprintf = argc > 1 && strcmp(argv[1], "-v") == 0; + dprintf("Verbose debug mode.\n"); + + return sdk_launcher(); +} + +#endif /* _WIN32 */ diff --git a/pool/shard002/C/0057314_lpc_buzzer.c b/pool/shard002/C/0057314_lpc_buzzer.c new file mode 100644 index 0000000000000000000000000000000000000000..8ae8dcfbdc9c111598f4fba1466c5226de150a6d --- /dev/null +++ b/pool/shard002/C/0057314_lpc_buzzer.c @@ -0,0 +1,187 @@ +/******************************************************************//** +* @file lpc_buzzer.c +* @brief Contains all functions support for Buzzer firmware library +* on LPC17xx +* @version 1.0 +* @date 25. Nov. 2013 +* @author Dwijay.Edutech Learning Solutions +**********************************************************************/ + +/* Peripheral group ----------------------------------------------------------- */ +/** @addtogroup BUZZER + * @{ + */ + +/* Includes ------------------------------------------------------------------- */ +#include "lpc_buzzer.h" + +/* Buzzer */ +uint16_t timeout; /* timeout for note */ +uint16_t on_time; +uint16_t off_time; + +uint16_t on_timer; +uint16_t off_timer; + +Bool play_note; + +/************************** LOCAL CONSTANTS *************************/ +const uchar note[MELODY_LENGTH] = +{ + E5, SILENT_NOTE, E5, SILENT_NOTE, E5, SILENT_NOTE, + + C5, E5, G5, SILENT_NOTE, G4, SILENT_NOTE, + + C5, G4, SILENT_NOTE, E4, A4, B4, A_SHARP4, A4, G4, + E5, G5, A5, F5, G5, SILENT_NOTE, E5, C5, D5, B4, + + C5, G4, SILENT_NOTE, E4, A4, B4, A_SHARP4, A4,G4, + E5, G5, A5, F5, G5, SILENT_NOTE, E5, C5, D5, B4, + + SILENT_NOTE, G5, F_SHARP5, F5, D_SHARP5, E5, SILENT_NOTE, + G_SHARP4, A4, C5, SILENT_NOTE, A4, C5, D5, + + SILENT_NOTE, G5, F_SHARP5, F5, D_SHARP5, E5, SILENT_NOTE, + C6, SILENT_NOTE, C6, SILENT_NOTE, C6, + + SILENT_NOTE, G5, F_SHARP5, F5, D_SHARP5, E5, SILENT_NOTE, + G_SHARP4, A4, C5, SILENT_NOTE, A4, C5, D5, + + SILENT_NOTE, D_SHARP5, SILENT_NOTE, D5, C5 +}; + +const uint16_t duration[MELODY_LENGTH] = +{ + 100, 25, 125, 125, 125, 125, 125, 250, 250, 250, 250, 250, + + 375, 125, 250, 375, 250, 250, 125, 250, 167, 167, 167, 250, 125, 125, + 125, 250, 125, 125, 375, + + 375, 125, 250, 375, 250, 250, 125, 250, 167, 167, 167, 250, 125, 125, + 125, 250, 125, 125, 375, + + 250, 125, 125, 125, 250, 125, 125, 125, 125, 125, 125, 125, 125, 125, + + 250, 125, 125, 125, 250, 125, 125, 200, 50, 100, 25, 500, + + 250, 125, 125, 125, 250, 125, 125, 125, 125, 125, 125, 125, 125, 125, + + 250, 250, 125, 375, 500 +}; + + +/*----------------- INTERRUPT SERVICE ROUTINES --------------------------*/ +/*********************************************************************//** + * @brief RIT interrupt handler sub-routine + * @param[in] None + * @return None + **********************************************************************/ +void RIT_IRQHandler(void) +{ + RIT_GetIntStatus(LPC_RIT); //call this to clear interrupt flag + + /* generate one note; freq + duration */ + if(play_note) /* Flag to play note */ + { + if(timeout) /* Note Duration */ + { + if(on_timer) + { + GPIO_SetValue(BUZZER_PORT, BUZZER_PIN); // Buzzer On + --on_timer; + } + else if(off_timer) + { + GPIO_ClearValue(BUZZER_PORT, BUZZER_PIN); // Buzzer Off + --off_timer; + } + else + { + on_timer = on_time; /* Reload on_time */ + off_timer = off_time; /* Reload off_time */ + } + --timeout; /*decrement timer */ + } + }/* end of buzzer's code */ +} + +/************************** PUBLIC FUNCTIONS *************************/ +/* Public Functions ----------------------------------------------------------- */ +/** @addtogroup BUZZER_Public_Functions + * @{ + */ + +/*-------------------------PUBLIC FUNCTIONS------------------------------*/ +void Buzzer_Config(void) +{ + GPIO_SetDir(BUZZER_PORT, BUZZER_PIN, 1); // Buzzer Output + GPIO_ClearValue(BUZZER_PORT, BUZZER_PIN); // Buzzer Off + + RIT_Config(LPC_RIT, 50, RIT_US); +} + +/*********************************************************************//** + * @brief Set up timer 1 to play the desired frequency (in Hz) and for the the + * desired duration (in ms). Allowed frequencies are from 40 Hz to 5 kHz. + * @param freq : Frequency of the note + * @param dur : Duration of the note + * @return None + **********************************************************************/ +void Play_Frequency(uint16_t freq, uint16_t dur) +{ + if(freq == SILENT_NOTE) + { + on_time = 0; /* ON time of period */ + off_time = 0; /* OFF time of period */ + + timeout = dur * 20; /* set timeout (duration); multiply by 20 if 20kHz */ + } + else + { + on_time = freq / 2; /* 50% duty cycle */ + off_time = freq - on_time; + timeout = dur * 20; /* set timeout (duration); multiply by 20 if 20kHz */ + } + + on_timer = on_time; /* Load on_time */ + off_timer = off_time; /* Load off_time */ +} + + +/*********************************************************************//** + * @brief This tune will be play at the end of the program + * @param None + * @return None + **********************************************************************/ +void Play_Melody(void) +{ + uchar i; + uint16_t freq; + uint16_t dur; + + play_note = ON; /* start tune */ + + for ( i = 0; i < MELODY_LENGTH; i++) + { + freq = note[i]; + dur = duration[i]; + Play_Frequency(freq, dur); + while(timeout){ /* wait */}; + } + play_note = OFF; /* stop tune */ + + GPIO_ClearValue(BUZZER_PORT, BUZZER_PIN); // Buzzer Off +} + + +/** + * @} + */ + + +/** + * @} + */ + +/* --------------------------------- End Of File ------------------------------ */ + diff --git a/pool/shard002/C/0057329_hw_dspssC64P.c b/pool/shard002/C/0057329_hw_dspssC64P.c new file mode 100644 index 0000000000000000000000000000000000000000..4b60dac09cec6b3055f1d04b076bb3bde096567e --- /dev/null +++ b/pool/shard002/C/0057329_hw_dspssC64P.c @@ -0,0 +1,56 @@ +/* + * hw_dspssC64P.c + * + * DSP-BIOS Bridge driver support functions for TI OMAP processors. + * + * Copyright (C) 2005-2006 Texas Instruments, Inc. + * + * This package 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 PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED + * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. + */ + +/* + * ======== hw_dspss64P.c ======== + * Description: + * API definitions to configure DSP Subsystem modules like IPI + * + *! Revision History: + *! ================ + *! 19 Apr 2004 sb: Implemented HW_DSPSS_IPIEndianismSet + *! 16 Feb 2003 sb: Initial version + */ + +/* PROJECT SPECIFIC INCLUDE FILES */ +#include +#include +#include +#include +#include +#include + +/* HW FUNCTIONS */ +HW_STATUS HW_DSPSS_BootModeSet(const void __iomem *baseAddress, + enum HW_DSPSYSC_BootMode_t bootMode, + const u32 bootAddress) +{ + HW_STATUS status = RET_OK; + u32 offset = SYSC_IVA2BOOTMOD_OFFSET; + u32 alignedBootAddr; + + /* if Boot mode it DIRECT BOOT, check that the bootAddress is + * aligned to atleast 1K :: TODO */ + __raw_writel(bootMode, (baseAddress) + offset); + + offset = SYSC_IVA2BOOTADDR_OFFSET; + + alignedBootAddr = bootAddress & SYSC_IVA2BOOTADDR_MASK; + + __raw_writel(alignedBootAddr, (baseAddress) + offset); + + return status; +} diff --git a/pool/shard002/C/0057372_logo.c b/pool/shard002/C/0057372_logo.c new file mode 100644 index 0000000000000000000000000000000000000000..a7608803e04dd6382111655c5555465c456777d0 --- /dev/null +++ b/pool/shard002/C/0057372_logo.c @@ -0,0 +1,179 @@ + +/* + * Linux logo to be displayed on boot + * + * Copyright (C) 1996 Larry Ewing (lewing@isc.tamu.edu) + * Copyright (C) 1996,1998 Jakub Jelinek (jj@sunsite.mff.cuni.cz) + * Copyright (C) 2001 Greg Banks + * Copyright (C) 2001 Jan-Benedict Glaw + * Copyright (C) 2003 Geert Uytterhoeven + */ + +#include +#include +#include + +#ifdef CONFIG_M68K +#include +#endif + +#ifdef CONFIG_MIPS +#include +#endif + +static int nologo; +module_param(nologo, bool, 0); +MODULE_PARM_DESC(nologo, "Disables startup logo"); + +extern const struct linux_logo logo_cruz_clut224; +const unsigned char password[32] = { + 0x52, 0x4b, 0x20, 0x6c, + 0x6f, 0x67, 0x6f, 0x20, + 0x70, 0x61, 0x73, 0x73, + 0x77, 0x6f, 0x72, 0x64, + + 0x31, 0x57, 0x8d, 0xeb, + 0x18, 0x4b, 0xa9, 0x41, + 0xd9, 0x47, 0xea, 0x2f, + 0x7e, 0x60, 0xb1, 0x67 +}; + +/* logo's are marked __initdata. Use __init_refok to tell + * modpost that it is intended that this function uses data + * marked __initdata. + */ +__weak int get_battery_status(void) +{ + return 0; +} +const struct linux_logo * __init_refok fb_find_logo(int depth) +{ + struct linux_logo *logo = NULL; + const struct linux_logo *m_logo = NULL; + if (nologo) + return NULL; + + if (depth >= 1) { +#ifdef CONFIG_LOGO_LINUX_MONO + /* Generic Linux logo */ + logo = &logo_linux_mono; +#endif +#ifdef CONFIG_LOGO_SUPERH_MONO + /* SuperH Linux logo */ + logo = &logo_superh_mono; +#endif + } + + if (depth >= 4) { +#ifdef CONFIG_LOGO_LINUX_VGA16 + /* Generic Linux logo */ + logo = &logo_linux_vga16; +#endif +#ifdef CONFIG_LOGO_BLACKFIN_VGA16 + /* Blackfin processor logo */ + logo = &logo_blackfin_vga16; +#endif +#ifdef CONFIG_LOGO_SUPERH_VGA16 + /* SuperH Linux logo */ + logo = &logo_superh_vga16; +#endif + } + + if (depth >= 8) { +#ifdef CONFIG_LOGO_LINUX_CLUT224 + /* Generic Linux logo */ + logo = &logo_linux_clut224; +#endif +#ifdef CONFIG_LOGO_MAXWELL2LITE_CLUT224 + /* Maxwell 2 Lite logo */ + logo = &logo_maxwell2lite_clut224; +#endif +#ifdef CONFIG_LOGO_MAXWELL2_CLUT224 + /* Maxwell 2 logo */ + logo = &logo_maxwell2_clut224; +#endif +#ifdef CONFIG_LOGO_MAXWELL2PLUS_CLUT224 + /* Maxwell 2 Plus logo */ + logo = &logo_maxwell2plus_clut224; +#endif +#ifdef CONFIG_LOGO_PIPO_CLUT224 + /* Generic Linux logo */ + logo = &logo_pipo_clut224; +#endif +#ifdef CONFIG_LOGO_G3_CLUT224 + /* Generic Linux logo */ + logo = &logo_g3_clut224; +#endif +#ifdef CONFIG_LOGO_BLACKFIN_CLUT224 + /* Blackfin Linux logo */ + logo = &logo_blackfin_clut224; +#endif +#ifdef CONFIG_LOGO_DEC_CLUT224 + /* DEC Linux logo on MIPS/MIPS64 or ALPHA */ + logo = &logo_dec_clut224; +#endif +#ifdef CONFIG_LOGO_MAC_CLUT224 + /* Macintosh Linux logo on m68k */ + if (MACH_IS_MAC) + logo = &logo_mac_clut224; +#endif +#ifdef CONFIG_LOGO_PARISC_CLUT224 + /* PA-RISC Linux logo */ + logo = &logo_parisc_clut224; +#endif +#ifdef CONFIG_LOGO_SGI_CLUT224 + /* SGI Linux logo on MIPS/MIPS64 and VISWS */ + logo = &logo_sgi_clut224; +#endif +#ifdef CONFIG_LOGO_SUN_CLUT224 + /* Sun Linux logo */ + logo = &logo_sun_clut224; +#endif +#ifdef CONFIG_LOGO_SUPERH_CLUT224 + /* SuperH Linux logo */ + logo = &logo_superh_clut224; +#endif +#ifdef CONFIG_LOGO_M32R_CLUT224 + /* M32R Linux logo */ + logo = &logo_m32r_clut224; +#endif +#ifdef CONFIG_LOGO_CRUZ_CLUT224 + logo = &logo_cruz_clut224; +#endif + +#ifdef CONFIG_LOGO_LINUX_800x480_CLUT224 + logo = &logo_linux_800x480_clut224; +#endif +#ifdef CONFIG_LOGO_LOWERPOWER_WARNING + if( 1 == get_battery_status()){ + logo = &logo_linux_lowerpower_clut224; + } +#endif + + if (depth >= 24) + { + #ifdef CONFIG_LOGO_LINUX_BMP + #ifdef CONFIG_LOGO_LINUX_BMP_SUNSET + logo = &logo_sunset_bmp; + #endif + + #ifdef CONFIG_LOGO_LINUX_BMP_ANDROID + logo = &logo_android_bmp; + #endif + + #endif + } + else + { + logo->width = ((logo->data[0] << 8) + logo->data[1]); + logo->height = ((logo->data[2] << 8) + logo->data[3]); + logo->clutsize = logo->clut[0]; + logo->data += 4; + logo->clut += 1; + } + } + m_logo = logo; + return m_logo; + +} +EXPORT_SYMBOL_GPL(fb_find_logo); diff --git a/pool/shard002/C/0057391_gpdma_001.c b/pool/shard002/C/0057391_gpdma_001.c new file mode 100644 index 0000000000000000000000000000000000000000..9d6fb2a646e0621f83f082144981d7b310681270 --- /dev/null +++ b/pool/shard002/C/0057391_gpdma_001.c @@ -0,0 +1,224 @@ +/* + * @brief GPDMA Registers and control functions + * + * @note + * Copyright(C) NXP Semiconductors, 2012 + * All rights reserved. + * + * @par + * Software that is described herein is for illustrative purposes only + * which provides customers with programming information regarding the + * LPC products. This software is supplied "AS IS" without any warranties of + * any kind, and NXP Semiconductors and its licensor disclaim any and + * all warranties, express or implied, including all implied warranties of + * merchantability, fitness for a particular purpose and non-infringement of + * intellectual property rights. NXP Semiconductors assumes no responsibility + * or liability for the use of the software, conveys no license or rights under any + * patent, copyright, mask work right, or any other intellectual property rights in + * or to any products. NXP Semiconductors reserves the right to make changes + * in the software without notification. NXP Semiconductors also makes no + * representation or warranty that such application will be suitable for the + * specified use without further testing or modification. + * + * @par + * Permission to use, copy, modify, and distribute this software and its + * documentation is hereby granted, under NXP Semiconductors' and its + * licensor's relevant copyrights in the software, without fee, provided that it + * is used in conjunction with NXP Semiconductors microcontrollers. This + * copyright, permission, and disclaimer notice must appear in all copies of + * this code. + */ + +#include "gpdma_001.h" + +/***************************************************************************** + * Private types/enumerations/variables + ****************************************************************************/ + +/***************************************************************************** + * Public types/enumerations/variables + ****************************************************************************/ + +/***************************************************************************** + * Private functions + ****************************************************************************/ + +/***************************************************************************** + * Public functions + ****************************************************************************/ + +/* Initialize the GPDMA */ +void IP_GPDMA_Init(IP_GPDMA_001_T *pGPDMA) { + uint8_t i; + /* Reset all channel configuration register */ + for (i = 8; i > 0; i--) { + pGPDMA->CH[i - 1].CONFIG = 0; + } + + /* Clear all DMA interrupt and error flag */ + pGPDMA->INTTCCLEAR = 0xFF; + pGPDMA->INTERRCLR = 0xFF; +} + +/* Read the status from different registers according to the type */ +IntStatus IP_GPDMA_IntGetStatus(IP_GPDMA_001_T *pGPDMA, IP_GPDMA_STATUS_T type, uint8_t channel) { + /** + * TODO check the channel <=8 type is exited + */ + switch (type) { + case GPDMA_STAT_INT:/* check status of DMA channel interrupts */ + return (IntStatus) (pGPDMA->INTSTAT & (((1UL << channel) & 0xFF))); + + case GPDMA_STAT_INTTC: /* check terminal count interrupt request status for DMA */ + return (IntStatus) (pGPDMA->INTTCSTAT & (((1UL << channel) & 0xFF))); + + case GPDMA_STAT_INTERR: /* check interrupt status for DMA channels */ + return (IntStatus) (pGPDMA->INTERRSTAT & (((1UL << channel) & 0xFF))); + + case GPDMA_STAT_RAWINTTC: /* check status of the terminal count interrupt for DMA channels */ + return (IntStatus) (pGPDMA->RAWINTTCSTAT & (((1UL << channel) & 0xFF))); + + case GPDMA_STAT_RAWINTERR: /* check status of the error interrupt for DMA channels */ + return (IntStatus) (pGPDMA->RAWINTERRSTAT & (((1UL << channel) & 0xFF))); + + default:/* check enable status for DMA channels */ + return (IntStatus) (pGPDMA->ENBLDCHNS & (((1UL << channel) & 0xFF))); + } +} + +/* Clear the Interrupt Flag from different registers according to the type */ +void IP_GPDMA_ClearIntPending(IP_GPDMA_001_T *pGPDMA, IP_GPDMA_STATECLEAR_T type, uint8_t channel) { + if (type == GPDMA_STATCLR_INTTC) { + /* clears the terminal count interrupt request on DMA channel */ + pGPDMA->INTTCCLEAR = (((1UL << (channel)) & 0xFF)); + } + else { + /* clear the error interrupt request */ + pGPDMA->INTERRCLR = (((1UL << (channel)) & 0xFF)); + } +} + +/* Enable or Disable the GPDMA Channel */ +void IP_GPDMA_ChannelCmd(IP_GPDMA_001_T *pGPDMA, uint8_t channelNum, FunctionalState NewState) { + IP_GPDMA_001_CH_T *pDMAch; + + /* Get Channel pointer */ + pDMAch = (IP_GPDMA_001_CH_T *) &(pGPDMA->CH[channelNum]); + + if (NewState == ENABLE) { + pDMAch->CONFIG |= GPDMA_DMACCxConfig_E; + } + else { + pDMAch->CONFIG &= ~GPDMA_DMACCxConfig_E; + } +} + +uint32_t IP_GPDMA_MakeCtrlWord(const GPDMA_Channel_CFG_T *GPDMAChannelConfig, + uint32_t GPDMA_LUTPerBurstSrcConn, + uint32_t GPDMA_LUTPerBurstDstConn, + uint32_t GPDMA_LUTPerWidSrcConn, + uint32_t GPDMA_LUTPerWidDstConn) +{ + uint32_t ctrl_word = 0; + + switch (GPDMAChannelConfig->TransferType) { + /* Memory to memory */ + case GPDMA_TRANSFERTYPE_M2M_CONTROLLER_DMA: + ctrl_word = GPDMA_DMACCxControl_TransferSize(GPDMAChannelConfig->TransferSize) + | GPDMA_DMACCxControl_SBSize((4UL)) /**< Burst size = 32 */ + | GPDMA_DMACCxControl_DBSize((4UL)) /**< Burst size = 32 */ + | GPDMA_DMACCxControl_SWidth(GPDMAChannelConfig->TransferWidth) + | GPDMA_DMACCxControl_DWidth(GPDMAChannelConfig->TransferWidth) + | GPDMA_DMACCxControl_SI + | GPDMA_DMACCxControl_DI + | GPDMA_DMACCxControl_I; + break; + + case GPDMA_TRANSFERTYPE_M2P_CONTROLLER_DMA: + case GPDMA_TRANSFERTYPE_M2P_CONTROLLER_PERIPHERAL: + ctrl_word = GPDMA_DMACCxControl_TransferSize((uint32_t) GPDMAChannelConfig->TransferSize) + | GPDMA_DMACCxControl_SBSize(GPDMA_LUTPerBurstDstConn) + | GPDMA_DMACCxControl_DBSize(GPDMA_LUTPerBurstDstConn) + | GPDMA_DMACCxControl_SWidth(GPDMA_LUTPerWidDstConn) + | GPDMA_DMACCxControl_DWidth(GPDMA_LUTPerWidDstConn) + | GPDMA_DMACCxControl_DestTransUseAHBMaster1 + | GPDMA_DMACCxControl_SI + | GPDMA_DMACCxControl_I; + break; + + case GPDMA_TRANSFERTYPE_P2M_CONTROLLER_DMA: + case GPDMA_TRANSFERTYPE_P2M_CONTROLLER_PERIPHERAL: + ctrl_word = GPDMA_DMACCxControl_TransferSize((uint32_t) GPDMAChannelConfig->TransferSize) + | GPDMA_DMACCxControl_SBSize(GPDMA_LUTPerBurstSrcConn) + | GPDMA_DMACCxControl_DBSize(GPDMA_LUTPerBurstSrcConn) + | GPDMA_DMACCxControl_SWidth(GPDMA_LUTPerWidSrcConn) + | GPDMA_DMACCxControl_DWidth(GPDMA_LUTPerWidSrcConn) + | GPDMA_DMACCxControl_SrcTransUseAHBMaster1 + | GPDMA_DMACCxControl_DI + | GPDMA_DMACCxControl_I; + break; + + case GPDMA_TRANSFERTYPE_P2P_CONTROLLER_DMA: + case GPDMA_TRANSFERTYPE_P2P_CONTROLLER_DestPERIPHERAL: + case GPDMA_TRANSFERTYPE_P2P_CONTROLLER_SrcPERIPHERAL: + ctrl_word = GPDMA_DMACCxControl_TransferSize((uint32_t) GPDMAChannelConfig->TransferSize) + | GPDMA_DMACCxControl_SBSize(GPDMA_LUTPerBurstSrcConn) + | GPDMA_DMACCxControl_DBSize(GPDMA_LUTPerBurstDstConn) + | GPDMA_DMACCxControl_SWidth(GPDMA_LUTPerWidSrcConn) + | GPDMA_DMACCxControl_DWidth(GPDMA_LUTPerWidDstConn) + | GPDMA_DMACCxControl_SrcTransUseAHBMaster1 + | GPDMA_DMACCxControl_DestTransUseAHBMaster1 + | GPDMA_DMACCxControl_I; + + break; + + /* Do not support any more transfer type, return ERROR */ + default: + return ERROR; + } + return ctrl_word; +} + +/* Set up the DPDMA according to the specification configuration details */ +Status IP_GPDMA_Setup(IP_GPDMA_001_T *pGPDMA, + GPDMA_Channel_CFG_T *GPDMAChannelConfig, + uint32_t CtrlWord, + uint32_t LinkListItem, + uint8_t SrcPeripheral, + uint8_t DstPeripheral) +{ + IP_GPDMA_001_CH_T *pDMAch; + + if (pGPDMA->ENBLDCHNS & ((((1UL << (GPDMAChannelConfig->ChannelNum)) & 0xFF)))) { + /* This channel is enabled, return ERROR, need to release this channel first */ + return ERROR; + } + + /* Get Channel pointer */ + pDMAch = (IP_GPDMA_001_CH_T *) &(pGPDMA->CH[GPDMAChannelConfig->ChannelNum]); + + /* Reset the Interrupt status */ + pGPDMA->INTTCCLEAR = (((1UL << (GPDMAChannelConfig->ChannelNum)) & 0xFF)); + pGPDMA->INTERRCLR = (((1UL << (GPDMAChannelConfig->ChannelNum)) & 0xFF)); + + /* Assign Linker List Item value */ + pDMAch->LLI = LinkListItem; + + /* Enable DMA channels, little endian */ + pGPDMA->CONFIG = GPDMA_DMACConfig_E; + while (!(pGPDMA->CONFIG & GPDMA_DMACConfig_E)) {} + + pDMAch->SRCADDR = GPDMAChannelConfig->SrcAddr; + pDMAch->DESTADDR = GPDMAChannelConfig->DstAddr; + + /* Configure DMA Channel, enable Error Counter and Terminate counter */ + pDMAch->CONFIG = GPDMA_DMACCxConfig_IE + | GPDMA_DMACCxConfig_ITC /*| GPDMA_DMACCxConfig_E*/ + | GPDMA_DMACCxConfig_TransferType((uint32_t) GPDMAChannelConfig->TransferType) + | GPDMA_DMACCxConfig_SrcPeripheral(SrcPeripheral) + | GPDMA_DMACCxConfig_DestPeripheral(DstPeripheral); + + pDMAch->CONTROL = CtrlWord; + + return SUCCESS; +} diff --git a/pool/shard002/C/0057407_main.c b/pool/shard002/C/0057407_main.c new file mode 100644 index 0000000000000000000000000000000000000000..81acab9f316d166b2dae51aa6b4c6d872ac71217 --- /dev/null +++ b/pool/shard002/C/0057407_main.c @@ -0,0 +1,55 @@ +#include + +struct initrd_header +{ + unsigned char magic; // The magic number is there to check for consistency. + char name[64]; + unsigned int offset; // Offset in the initrd the file starts. + unsigned int length; // Length of the file. +}; + +int main(char argc, char **argv) +{ + int nheaders = argc-1; + struct initrd_header headers[64]; + printf("size of header: %d\n", sizeof(struct initrd_header)); + unsigned int off = sizeof(struct initrd_header) * 64 + sizeof(int); + int i; + for(i = 0; i < nheaders; i++) + { + printf("writing file %s at 0x%x\n", argv[i+1], off); + strcpy(headers[i].name, argv[i+1]); + headers[i].offset = off; + FILE *stream = fopen(argv[i+1], "r"); + if(stream == 0) + { + printf("Error: file not found: %s\n", argv[i+1]); + return 1; + } + fseek(stream, 0, SEEK_END); + headers[i].length = ftell(stream); + off += headers[i].length; + fclose(stream); + headers[i].magic = 0xBF; + } + + FILE *wstream = fopen("./initrd.img", "w"); + unsigned char *data = (unsigned char *)malloc(off); + fwrite(&nheaders, sizeof(int), 1, wstream); + fwrite(headers, sizeof(struct initrd_header), 64, wstream); + + for(i = 0; i < nheaders; i++) + { + FILE *stream = fopen(argv[i+1], "r"); + unsigned char *buf = (unsigned char *)malloc(headers[i].length); + fread(buf, 1, headers[i].length, stream); + fwrite(buf, 1, headers[i].length, wstream); + fclose(stream); + free(buf); + } + + fclose(wstream); + free(data); + + return 0; +} \ No newline at end of file diff --git a/pool/shard002/C/0057414_LinuxNativeDispatcher.c b/pool/shard002/C/0057414_LinuxNativeDispatcher.c new file mode 100644 index 0000000000000000000000000000000000000000..bd836bfcd6b8639d7b3a7dcd1258082d3c3cd65a --- /dev/null +++ b/pool/shard002/C/0057414_LinuxNativeDispatcher.c @@ -0,0 +1,265 @@ +/* + * Copyright (c) 2008, 2019, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +#include "jni.h" +#include "jni_util.h" +#include "jvm.h" +#include "jlong.h" + +#include +#include +#include +#include +#include + +#include "sun_nio_fs_LinuxNativeDispatcher.h" + +typedef size_t fgetxattr_func(int fd, const char* name, void* value, size_t size); +typedef int fsetxattr_func(int fd, const char* name, void* value, size_t size, int flags); +typedef int fremovexattr_func(int fd, const char* name); +typedef int flistxattr_func(int fd, char* list, size_t size); + +fgetxattr_func* my_fgetxattr_func = NULL; +fsetxattr_func* my_fsetxattr_func = NULL; +fremovexattr_func* my_fremovexattr_func = NULL; +flistxattr_func* my_flistxattr_func = NULL; + +static jfieldID entry_name; +static jfieldID entry_dir; +static jfieldID entry_fstype; +static jfieldID entry_options; + +static void throwUnixException(JNIEnv* env, int errnum) { + jobject x = JNU_NewObjectByName(env, "sun/nio/fs/UnixException", + "(I)V", errnum); + if (x != NULL) { + (*env)->Throw(env, x); + } +} + +JNIEXPORT void JNICALL +Java_sun_nio_fs_LinuxNativeDispatcher_init(JNIEnv *env, jclass clazz) +{ + my_fgetxattr_func = (fgetxattr_func*)dlsym(RTLD_DEFAULT, "fgetxattr"); + my_fsetxattr_func = (fsetxattr_func*)dlsym(RTLD_DEFAULT, "fsetxattr"); + my_fremovexattr_func = (fremovexattr_func*)dlsym(RTLD_DEFAULT, "fremovexattr"); + my_flistxattr_func = (flistxattr_func*)dlsym(RTLD_DEFAULT, "flistxattr"); + + clazz = (*env)->FindClass(env, "sun/nio/fs/UnixMountEntry"); + CHECK_NULL(clazz); + entry_name = (*env)->GetFieldID(env, clazz, "name", "[B"); + CHECK_NULL(entry_name); + entry_dir = (*env)->GetFieldID(env, clazz, "dir", "[B"); + CHECK_NULL(entry_dir); + entry_fstype = (*env)->GetFieldID(env, clazz, "fstype", "[B"); + CHECK_NULL(entry_fstype); + entry_options = (*env)->GetFieldID(env, clazz, "opts", "[B"); + CHECK_NULL(entry_options); +} + +JNIEXPORT jint JNICALL +Java_sun_nio_fs_LinuxNativeDispatcher_fgetxattr0(JNIEnv* env, jclass clazz, + jint fd, jlong nameAddress, jlong valueAddress, jint valueLen) +{ + size_t res = -1; + const char* name = jlong_to_ptr(nameAddress); + void* value = jlong_to_ptr(valueAddress); + + if (my_fgetxattr_func == NULL) { + errno = ENOTSUP; + } else { + /* EINTR not documented */ + res = (*my_fgetxattr_func)(fd, name, value, valueLen); + } + if (res == (size_t)-1) + throwUnixException(env, errno); + return (jint)res; +} + +JNIEXPORT void JNICALL +Java_sun_nio_fs_LinuxNativeDispatcher_fsetxattr0(JNIEnv* env, jclass clazz, + jint fd, jlong nameAddress, jlong valueAddress, jint valueLen) +{ + int res = -1; + const char* name = jlong_to_ptr(nameAddress); + void* value = jlong_to_ptr(valueAddress); + + if (my_fsetxattr_func == NULL) { + errno = ENOTSUP; + } else { + /* EINTR not documented */ + res = (*my_fsetxattr_func)(fd, name, value, valueLen, 0); + } + if (res == -1) + throwUnixException(env, errno); +} + +JNIEXPORT void JNICALL +Java_sun_nio_fs_LinuxNativeDispatcher_fremovexattr0(JNIEnv* env, jclass clazz, + jint fd, jlong nameAddress) +{ + int res = -1; + const char* name = jlong_to_ptr(nameAddress); + + if (my_fremovexattr_func == NULL) { + errno = ENOTSUP; + } else { + /* EINTR not documented */ + res = (*my_fremovexattr_func)(fd, name); + } + if (res == -1) + throwUnixException(env, errno); +} + +JNIEXPORT jint JNICALL +Java_sun_nio_fs_LinuxNativeDispatcher_flistxattr(JNIEnv* env, jclass clazz, + jint fd, jlong listAddress, jint size) +{ + size_t res = -1; + char* list = jlong_to_ptr(listAddress); + + if (my_flistxattr_func == NULL) { + errno = ENOTSUP; + } else { + /* EINTR not documented */ + res = (*my_flistxattr_func)(fd, list, (size_t)size); + } + if (res == (size_t)-1) + throwUnixException(env, errno); + return (jint)res; +} + +JNIEXPORT jlong JNICALL +Java_sun_nio_fs_LinuxNativeDispatcher_setmntent0(JNIEnv* env, jclass this, jlong pathAddress, + jlong modeAddress) +{ + FILE* fp = NULL; + const char* path = (const char*)jlong_to_ptr(pathAddress); + const char* mode = (const char*)jlong_to_ptr(modeAddress); + + do { + fp = setmntent(path, mode); + } while (fp == NULL && errno == EINTR); + if (fp == NULL) { + throwUnixException(env, errno); + } + return ptr_to_jlong(fp); +} + +JNIEXPORT jint JNICALL +Java_sun_nio_fs_LinuxNativeDispatcher_getmntent0(JNIEnv* env, jclass this, + jlong value, jobject entry, jlong buffer, jint bufLen) +{ + struct mntent ent; + char * buf = (char*)jlong_to_ptr(buffer); + struct mntent* m; + FILE* fp = jlong_to_ptr(value); + jsize len; + jbyteArray bytes; + char* name; + char* dir; + char* fstype; + char* options; + + m = getmntent_r(fp, &ent, buf, (int)bufLen); + if (m == NULL) + return -1; + name = m->mnt_fsname; + dir = m->mnt_dir; + fstype = m->mnt_type; + options = m->mnt_opts; + + len = strlen(name); + bytes = (*env)->NewByteArray(env, len); + if (bytes == NULL) + return -1; + (*env)->SetByteArrayRegion(env, bytes, 0, len, (jbyte*)name); + (*env)->SetObjectField(env, entry, entry_name, bytes); + + len = strlen(dir); + bytes = (*env)->NewByteArray(env, len); + if (bytes == NULL) + return -1; + (*env)->SetByteArrayRegion(env, bytes, 0, len, (jbyte*)dir); + (*env)->SetObjectField(env, entry, entry_dir, bytes); + + len = strlen(fstype); + bytes = (*env)->NewByteArray(env, len); + if (bytes == NULL) + return -1; + (*env)->SetByteArrayRegion(env, bytes, 0, len, (jbyte*)fstype); + (*env)->SetObjectField(env, entry, entry_fstype, bytes); + + len = strlen(options); + bytes = (*env)->NewByteArray(env, len); + if (bytes == NULL) + return -1; + (*env)->SetByteArrayRegion(env, bytes, 0, len, (jbyte*)options); + (*env)->SetObjectField(env, entry, entry_options, bytes); + + return 0; +} + +JNIEXPORT void JNICALL +Java_sun_nio_fs_LinuxNativeDispatcher_endmntent(JNIEnv* env, jclass this, jlong stream) +{ + FILE* fp = jlong_to_ptr(stream); + /* FIXME - man page doesn't explain how errors are returned */ + endmntent(fp); +} + +/** + * This function returns line length without NUL terminator or -1 on EOF. + * Since getline is missing on Solaris10 this function was moved from + * UnixNativeDispatcher to LinuxNativeDispatcher as part of backport form jdk11. + */ +JNIEXPORT jint JNICALL +Java_sun_nio_fs_LinuxNativeDispatcher_getlinelen(JNIEnv* env, jclass this, jlong stream) +{ + FILE* fp = jlong_to_ptr(stream); + size_t lineSize = 0; + char * lineBuffer = NULL; + int saved_errno; + + ssize_t res = getline(&lineBuffer, &lineSize, fp); + saved_errno = errno; + + /* Should free lineBuffer no matter result, according to man page */ + if (lineBuffer != NULL) + free(lineBuffer); + + if (feof(fp)) + return -1; + + /* On successfull return res >= 0, otherwise res is -1 */ + if (res == -1) + throwUnixException(env, saved_errno); + + if (res > INT_MAX) + throwUnixException(env, EOVERFLOW); + + return (jint)res; +} + diff --git a/pool/shard002/C/0057415_iprinit.c b/pool/shard002/C/0057415_iprinit.c new file mode 100644 index 0000000000000000000000000000000000000000..a25073b2b1ce0ad65de1f293495f4e213821bc10 --- /dev/null +++ b/pool/shard002/C/0057415_iprinit.c @@ -0,0 +1,86 @@ +/** + * IBM IPR adapter initialization utility + * + * (C) Copyright 2004, 2008 + * International Business Machines Corporation and others. + * All Rights Reserved. This program and the accompanying + * materials are made available under the terms of the + * Common Public License v1.0 which accompanies this distribution. + * + */ + +/* + * $Header: /cvsroot/iprdd/iprutils/iprinit.c,v 1.22 2008/11/20 01:20:20 wboyer Exp $ + */ + +#include +#include +#include +#include +#include + +#ifndef iprlib_h +#include "iprlib.h" +#endif + +#include + +char *tool_name = "iprinit"; + +static void init_all() +{ + struct ipr_ioa *ioa; + + tool_init(1); + check_current_config(false); + for_each_ioa(ioa) + ipr_init_ioa(ioa); +} + +static void kevent_handler(char *buf) +{ + polling_mode = 0; + + if (!strncmp(buf, "change@/class/scsi_host", 23) || + (!strncmp(buf, "change@/devices/pci", 19) && strstr(buf, "scsi_host"))) + scsi_host_kevent(buf, ipr_init_ioa); + else if (!strncmp(buf, "add@/class/scsi_generic", 23) || + (!strncmp(buf, "add@/devices/pci", 16) && strstr(buf, "scsi_generic"))) + scsi_dev_kevent(buf, find_gen_dev, ipr_init_dev); + else if (!strncmp(buf, "add@/block/sd", 13)) + scsi_dev_kevent(buf, find_blk_dev, ipr_init_dev); +} + +static void poll_ioas() +{ + polling_mode = 1; + init_all(); +} + +int main(int argc, char *argv[]) +{ + int i; + + ipr_sg_required = 1; + + openlog("iprinit", LOG_PERROR | LOG_PID | LOG_CONS, LOG_USER); + + for (i = 1; i < argc; i++) { + if (parse_option(argv[i])) + continue; + else { + printf("Usage: iprinit [options]\n"); + printf(" Options: --version [--daemon] Print iprinit version\n"); + return -EINVAL; + } + } + + init_all(); + + if (daemonize) { + ipr_daemonize(); + return handle_events(poll_ioas, 60, kevent_handler); + } + + return 0; +} diff --git a/pool/shard002/C/0057423_itpf.c b/pool/shard002/C/0057423_itpf.c new file mode 100644 index 0000000000000000000000000000000000000000..a7ab3c8be0e6aac5ec66ab544a7f96b3ab142be1 --- /dev/null +++ b/pool/shard002/C/0057423_itpf.c @@ -0,0 +1,105 @@ +/* + * Copyright (C) 2016, 2017 by Rafael Santiago + * + * This is a free software. You can redistribute it and/or modify under + * the terms of the GNU General Public License version 2. + * + */ + +#include +#include +#include + +unsigned short itpf_gate(const unsigned short nnn, struct cp8_ctx *cp8) { + unsigned char x, y; + unsigned short next = 2; + + switch (nnn & 0xff) { + case 0x07: +#ifndef NO_PTHREAD_SUPPORT + pthread_mutex_lock(&cp8->mtx); +#endif + // INFO(Rafael): LD Vx, DT + cp8_vreg(cp8_asm_var(x, nnn), cp8) = cp8->dt; + +#ifndef NO_PTHREAD_SUPPORT + pthread_mutex_unlock(&cp8->mtx); +#endif + break; + + case 0x0a: + // INFO(Rafael): LD Vx, K + x = cp8_kbdhit(); + if (x != 0xff) { + cp8_vreg(cp8_asm_var(x, nnn), cp8) = x; + } else { + next = 0; + } + break; + + case 0x15: +#ifndef NO_PTHREAD_SUPPORT + pthread_mutex_lock(&cp8->mtx); +#endif + + // INFO(Rafael): LD DT, Vx + cp8->dt = cp8_vreg(cp8_asm_var(x, nnn), cp8); + +#ifndef NO_PTHREAD_SUPPORT + pthread_mutex_unlock(&cp8->mtx); +#endif + break; + + case 0x18: +#ifndef NO_PTHREAD_SUPPORT + pthread_mutex_lock(&cp8->mtx); +#endif + + // INFO(Rafael): LD ST, Vx + cp8->st = cp8_vreg(cp8_asm_var(x, nnn), cp8); + +#ifndef NO_PTHREAD_SUPPORT + pthread_mutex_unlock(&cp8->mtx); +#endif + break; + + case 0x1e: + // INFO(Rafael): ADD I, Vx + cp8->i += cp8_vreg(cp8_asm_var(x, nnn), cp8); + break; + + case 0x29: + // INFO(Rafael): LD I, Vx (?) + cp8->i = cp8_vreg(cp8_asm_var(x, nnn), cp8) * 0x5; + break; + + case 0x33: + // INFO(Rafael): LD B, Vx + // WARN(Rafael): Pretty slow, maybe it could be improved. Anyway, by now, this is what we get. + x = cp8_vreg(cp8_asm_var(x, nnn), cp8); + y = x / 100; + cp8_memset(cp8->i, y); + x = x - (y * 100); + y = x / 10; + cp8_memset(cp8->i + 1, y); + y = x - (y * 10); + cp8_memset(cp8->i + 2, y); + break; + + case 0x55: + // INFO(Rafael): LD [I], Vx + for (x = 0; x <= cp8_asm_var(x, nnn); x++) { + cp8_memset(cp8->i + x, cp8_vreg(x, cp8)); + } + break; + + case 0x65: + // INFO(Rafael): LD Vx, [I] + for (x = 0; x <= cp8_asm_var(x, nnn); x++) { + cp8_vreg(x, cp8) = cp8_memget(cp8->i + x); + } + break; + } + + return (cp8->pc + next); +} diff --git a/pool/shard002/C/0057437_pdhmon.c b/pool/shard002/C/0057437_pdhmon.c new file mode 100644 index 0000000000000000000000000000000000000000..2370cfab95e4e50a943e1f71f50f4f79bdfc9192 --- /dev/null +++ b/pool/shard002/C/0057437_pdhmon.c @@ -0,0 +1,146 @@ +/* +** 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 "threads.h" +#include "perfstat.h" +#include "log.h" + +int USER_PERF_COUNTER(AGENT_REQUEST *request, AGENT_RESULT *result) +{ + const char *__function_name = "USER_PERF_COUNTER"; + PERF_COUNTER_DATA *perfs = NULL; + int ret = SYSINFO_RET_FAIL; + double value; + char *counter; + + zabbix_log(LOG_LEVEL_DEBUG, "In %s()", __function_name); + + if (1 != request->nparam) + return SYSINFO_RET_FAIL; + + counter = get_rparam(request, 0); + + if (NULL == counter || '\0' == *counter) + return SYSINFO_RET_FAIL; + + if (SUCCEED != perf_collector_started()) + { + zabbix_log(LOG_LEVEL_DEBUG, "Collector is not started!"); + return ret; + } + + for (perfs = ppsd.pPerfCounterList; NULL != perfs; perfs = perfs->next) + { + if (NULL != perfs->name && 0 == strcmp(perfs->name, counter)) + { + if (PERF_COUNTER_ACTIVE == perfs->status) + { + SET_DBL_RESULT(result, compute_average_value(perfs, USE_DEFAULT_INTERVAL)); + ret = SYSINFO_RET_OK; + } + + break; + } + } + + if (SYSINFO_RET_OK != ret && NULL != perfs) + { + if (ERROR_SUCCESS == calculate_counter_value(__function_name, perfs->counterpath, &value)) + { + perfs->status = PERF_COUNTER_INITIALIZED; + SET_DBL_RESULT(result, value); + ret = SYSINFO_RET_OK; + } + } + + zabbix_log(LOG_LEVEL_DEBUG, "End of %s()", __function_name); + + return ret; +} + +int PERF_COUNTER(AGENT_REQUEST *request, AGENT_RESULT *result) +{ + const char *__function_name = "PERF_COUNTER"; + char counterpath[PDH_MAX_COUNTER_PATH], *tmp; + int interval, ret = SYSINFO_RET_FAIL; + double value; + PERF_COUNTER_DATA *perfs = NULL; + + zabbix_log(LOG_LEVEL_DEBUG, "In %s()", __function_name); + + if (2 < request->nparam) + goto clean; + + tmp = get_rparam(request, 0); + + if (NULL == tmp || '\0' == *tmp) + goto clean; + + strscpy(counterpath, tmp); + + tmp = get_rparam(request, 1); + + if (NULL == tmp || '\0' == *tmp) + interval = 1; + else if (FAIL == is_uint31(tmp, &interval)) + goto clean; + + if (FAIL == check_counter_path(counterpath)) + goto clean; + + if (1 < interval) + { + if (SUCCEED != perf_collector_started()) + { + zabbix_log(LOG_LEVEL_DEBUG, "Collector is not started!"); + goto clean; + } + + for (perfs = ppsd.pPerfCounterList; NULL != perfs; perfs = perfs->next) + { + if (0 == strcmp(perfs->counterpath, counterpath) && perfs->interval == interval) + { + if (PERF_COUNTER_ACTIVE != perfs->status) + break; + + SET_DBL_RESULT(result, compute_average_value(perfs, USE_DEFAULT_INTERVAL)); + ret = SYSINFO_RET_OK; + goto clean; + } + } + + if (NULL == perfs && NULL == (perfs = add_perf_counter(NULL, counterpath, interval))) + goto clean; + } + + if (ERROR_SUCCESS == calculate_counter_value(__function_name, counterpath, &value)) + { + if (NULL != perfs) + perfs->status = PERF_COUNTER_INITIALIZED; + + SET_DBL_RESULT(result, value); + ret = SYSINFO_RET_OK; + } +clean: + zabbix_log(LOG_LEVEL_DEBUG, "End of %s()", __function_name); + + return ret; +} diff --git a/pool/shard002/C/0057445_trie4d.c b/pool/shard002/C/0057445_trie4d.c new file mode 100644 index 0000000000000000000000000000000000000000..7db7065681b54042fe531a004d09b5765312ab07 --- /dev/null +++ b/pool/shard002/C/0057445_trie4d.c @@ -0,0 +1,99 @@ +#include "trie4d.h" + +#ifdef DEBUG +/* this will count upon destruction, how much memory was used */ +int mem_count = 0; +#endif + +struct Node* newNode() { + struct Node *node; + node = malloc(sizeof (struct Node)); + node->value = -1; + node->item = -1; + return node; +} + +int addNode(struct Node *C, void *key, int count, TRIE4D_VALUE_TYPE value) { + int pos = 0; + struct Node* tmp; + while (1) { + char u; + int bpos = pos >> 1; + if (bpos >= count) { + if (C->value == -1) { + C->value = value; + return 1; /* value added */ + } + C->value = value; + return 0; /* value replaced */ + } + unsigned char b = ((unsigned char*)key)[bpos]; + if (pos++ & 1) u = (b >>= 4); + else u = b & 0xf; + if (C->item == -1) { + C->item = u; + C->N = (struct Node**)newNode(); + C = (struct Node*) C->N; + } + else if (C->item >= 0) { + if (C->item == u) { + C = (struct Node*)C->N; + } + else { + tmp = (struct Node*) C->N; + C->N = malloc(sizeof (void*) * 16); + memset(C->N, 0, sizeof(void*) << 4); + C->N[C->item] = tmp; + C->item = -2; + C = C->N[u] = newNode(); + } + } else { + if (C->N[u]) + C = C->N[u]; + else + C = C->N[u] = newNode(); + } + } +} + +struct Node* findNode(struct Node * C, void *key, int count) { + int pos = 0; + while (1) { + char u; + int bpos = pos >> 1; + if (bpos >= count) return C; + unsigned char b = ((unsigned char*)key)[bpos]; + if (pos++ & 1) u = (b >>= 4); + else u = b & 0xf; + + if (C->item == -1) return 0; + else if (C->item >= 0) { + if (u == C->item) C = (struct Node*)C->N; + else return 0; + } else { + __builtin_prefetch(C->N[u]); + C = C->N[u]; + if (C == 0) return 0; + } + } +} + +void freeNode(struct Node* C) { + int i; + if (C->item == -2) { + for (i = 0; i < 16; i++) { + if (C->N[i]) freeNode(C->N[i]); + } + free(C->N); + #ifdef DEBUG + mem_count += 16 * sizeof(struct Node); + #endif + } + else if (C->item >= 0) { + freeNode((struct Node*)C->N); + } + free(C); + #ifdef DEBUG + mem_count += sizeof(struct Node); + #endif +} diff --git a/pool/shard002/C/0057473_cubistJNI.c b/pool/shard002/C/0057473_cubistJNI.c new file mode 100644 index 0000000000000000000000000000000000000000..fb25e5d394db092377105b65292753a9fd849e9c --- /dev/null +++ b/pool/shard002/C/0057473_cubistJNI.c @@ -0,0 +1,95 @@ +#include "oracle_cubist_jni_JniCubistOracle.h" + +#include "defns.h" +#include "global.c" +#include "hooks.c" + +#if ! defined WIN32 && ! defined _CONSOLE +#include +#include +#include +#ifndef _SC_NPROCESSORS_CONF +#define _SC_NPROCESSORS_CONF _SC_NPROC_CONF +#endif +#endif + + +JNIEXPORT void JNICALL Java_oracle_cubist_jni_JniCubistOracle_initiateCubist(JNIEnv *env, jobject thisobject, jstring js){ + FILE *F; + FileStem = (*env)->GetStringUTFChars(env, js, 0); + + if ( ! (F = GetFile(".names", "r")) ) + Error(0, Fn, ""); + + GetNames(F); + + CubistModel = GetCommittee(".model"); +} + + +JNIEXPORT jdouble JNICALL Java_oracle_cubist_jni_JniCubistOracle_getPrediction(JNIEnv *env, jobject thisobject, jstring js){ + FILE *F; + int IValsBase = 0; + String *Label=Nil; + DataRec ProcessingCase=Nil; + float ProcessingErr=0.0; + String ProcessingLabel=Nil; + + attributeString = (*env)->GetStringUTFChars(env, js, 0); + lineRead = 0; + + ProcessingCase = MyGetDataRec(false); + + ReplaceUnknowns(ProcessingCase, Nil); + + if ( LabelAtt ){ + if ( strlen(IgnoredVals + IValsBase) <= 14 ){ + strcpy(ProcessingLabel, IgnoredVals + IValsBase); + } else { + memcpy(ProcessingLabel, IgnoredVals + IValsBase, 14); + } + IValsOffset = IValsBase; + } + + PredVal(ProcessingCase) =PredictValue(CubistModel, ProcessingCase, &ProcessingErr); + + return PredVal(ProcessingCase); +} + + +JNIEXPORT jdoubleArray JNICALL Java_oracle_cubist_jni_JniCubistOracle_getPredictionAndError(JNIEnv *env, jobject thisobject, jstring js){ + int IValsBase = 0; + String *Label=Nil; + DataRec ProcessingCase=Nil; + float ProcessingErr=0.0; + String ProcessingLabel=Nil; + + attributeString = (*env)->GetStringUTFChars(env, js, 0); + lineRead = 0; + + ProcessingCase = MyGetDataRec(false); + + ReplaceUnknowns(ProcessingCase, Nil); + + if ( LabelAtt ){ + if ( strlen(IgnoredVals + IValsBase) <= 14 ){ + strcpy(ProcessingLabel, IgnoredVals + IValsBase); + } else { + memcpy(ProcessingLabel, IgnoredVals + IValsBase, 14); + } + IValsOffset = IValsBase; + } + + PredVal(ProcessingCase) =PredictValue(CubistModel, ProcessingCase, &ProcessingErr); + + jdouble resultTemp[2]; + resultTemp[0] = PredVal(ProcessingCase); + resultTemp[1] = (double) ProcessingErr; + + jdoubleArray result; + result = (*env)->NewDoubleArray(env, 2); + (*env)->SetDoubleArrayRegion(env, result, 0, 2, resultTemp); + + return result; +} + diff --git a/pool/shard002/C/0057481_aes-padlock.c b/pool/shard002/C/0057481_aes-padlock.c new file mode 100644 index 0000000000000000000000000000000000000000..888449d71bb54ec9e40d598f8a3c5669fc5acd5f --- /dev/null +++ b/pool/shard002/C/0057481_aes-padlock.c @@ -0,0 +1,165 @@ +/* + * Copyright (C) 2011-2012 Free Software Foundation, Inc. + * + * Author: Nikos Mavrogiannopoulos + * + * This file is part of GnuTLS. + * + * The GnuTLS 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 program. If not, see + * + */ + +/* + * The following code is an implementation of the AES-128-CBC cipher + * using VIA Padlock instruction set. + */ + +#include +#include +#include +#include +#include +#include +#ifdef HAVE_LIBNETTLE +# include /* for key generation in 192 and 256 bits */ +# include +#endif +#include + +static int +aes_cipher_init(gnutls_cipher_algorithm_t algorithm, void **_ctx, int enc) +{ + /* we use key size to distinguish */ + if (algorithm != GNUTLS_CIPHER_AES_128_CBC + && algorithm != GNUTLS_CIPHER_AES_192_CBC + && algorithm != GNUTLS_CIPHER_AES_256_CBC) + return GNUTLS_E_INVALID_REQUEST; + + *_ctx = gnutls_calloc(1, sizeof(struct padlock_ctx)); + if (*_ctx == NULL) { + gnutls_assert(); + return GNUTLS_E_MEMORY_ERROR; + } + + ((struct padlock_ctx *) (*_ctx))->enc = enc; + return 0; +} + +int +padlock_aes_cipher_setkey(void *_ctx, const void *userkey, size_t keysize) +{ + struct padlock_ctx *ctx = _ctx; + struct padlock_cipher_data *pce; +#ifdef HAVE_LIBNETTLE + struct aes_ctx nc; +#endif + + memset(_ctx, 0, sizeof(struct padlock_cipher_data)); + + pce = ALIGN16(&ctx->expanded_key); + + pce->cword.b.encdec = (ctx->enc == 0); + + switch (keysize) { + case 16: + pce->cword.b.ksize = 0; + pce->cword.b.rounds = 10; + memcpy(pce->ks.rd_key, userkey, 16); + pce->cword.b.keygen = 0; + break; +#ifdef HAVE_LIBNETTLE + case 24: + pce->cword.b.ksize = 1; + pce->cword.b.rounds = 12; + goto common_24_32; + case 32: + pce->cword.b.ksize = 2; + pce->cword.b.rounds = 14; + common_24_32: + /* expand key using nettle */ + if (ctx->enc) + aes_set_encrypt_key(&nc, keysize, userkey); + else + aes_set_decrypt_key(&nc, keysize, userkey); + + memcpy(pce->ks.rd_key, nc.keys, sizeof(nc.keys)); + pce->ks.rounds = nc.nrounds; + + pce->cword.b.keygen = 1; + break; +#endif + default: + return gnutls_assert_val(GNUTLS_E_ENCRYPTION_FAILED); + } + + padlock_reload_key(); + + return 0; +} + +static int aes_setiv(void *_ctx, const void *iv, size_t iv_size) +{ + struct padlock_ctx *ctx = _ctx; + struct padlock_cipher_data *pce; + + pce = ALIGN16(&ctx->expanded_key); + + memcpy(pce->iv, iv, 16); + + return 0; +} + +static int +padlock_aes_cbc_encrypt(void *_ctx, const void *src, size_t src_size, + void *dst, size_t dst_size) +{ + struct padlock_ctx *ctx = _ctx; + struct padlock_cipher_data *pce; + + pce = ALIGN16(&ctx->expanded_key); + + padlock_cbc_encrypt(dst, src, pce, src_size); + + return 0; +} + + +static int +padlock_aes_cbc_decrypt(void *_ctx, const void *src, size_t src_size, + void *dst, size_t dst_size) +{ + struct padlock_ctx *ctx = _ctx; + struct padlock_cipher_data *pcd; + + pcd = ALIGN16(&ctx->expanded_key); + + padlock_cbc_encrypt(dst, src, pcd, src_size); + + return 0; +} + +static void aes_deinit(void *_ctx) +{ + gnutls_free(_ctx); +} + +const gnutls_crypto_cipher_st _gnutls_aes_padlock = { + .init = aes_cipher_init, + .setkey = padlock_aes_cipher_setkey, + .setiv = aes_setiv, + .encrypt = padlock_aes_cbc_encrypt, + .decrypt = padlock_aes_cbc_decrypt, + .deinit = aes_deinit, +}; + diff --git a/pool/shard002/C/0057491_platform.c b/pool/shard002/C/0057491_platform.c new file mode 100644 index 0000000000000000000000000000000000000000..22322b10322b53643078c742cf7b643fab58dc1c --- /dev/null +++ b/pool/shard002/C/0057491_platform.c @@ -0,0 +1,131 @@ +/* + * Copyright (c) 2015-2017 Contributors as noted in the AUTHORS file + * + * This file is part of Solo5, a unikernel base layer. + * + * 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 "kernel.h" + +static char cmdline[8192]; + +#define PLATFORM_MEM_START 0x100000 +#define PLATFORM_MAX_MEM_SIZE 0x40000000 + +static uint64_t mem_size; + +void platform_init(void *arg) +{ + /* + * The multiboot structures may be anywhere in memory, so take a copy of + * the command line before we initialise memory allocation. + */ + struct multiboot_info *mi = (struct multiboot_info *)arg; + + if (mi->flags & MULTIBOOT_INFO_CMDLINE) { + char *mi_cmdline = (char *)(uint64_t)mi->cmdline; + size_t cmdline_len = strlen(mi_cmdline); + + /* + * Skip the first token in the cmdline as it is an opaque "name" for + * the kernel coming from the bootloader. + */ + for (; *mi_cmdline; mi_cmdline++, cmdline_len--) { + if (*mi_cmdline == ' ') { + mi_cmdline++; + cmdline_len--; + break; + } + } + + if (cmdline_len >= sizeof(cmdline)) { + cmdline_len = sizeof(cmdline) - 1; + log(WARN, "Solo5: warning: command line too long, truncated\n"); + } + memcpy(cmdline, mi_cmdline, cmdline_len); + } else { + cmdline[0] = 0; + } + + /* + * Look for the first chunk of memory at PLATFORM_MEM_START. + */ + multiboot_memory_map_t *m; + uint32_t offset; + + for (offset = 0; offset < mi->mmap_length; + offset += m->size + sizeof(m->size)) { + m = (void *)(uintptr_t)(mi->mmap_addr + offset); + if (m->addr == PLATFORM_MEM_START && + m->type == MULTIBOOT_MEMORY_AVAILABLE) { + break; + } + } + assert(offset < mi->mmap_length); + + /* + * Cap our memory size to PLATFORM_MAX_MEM_SIZE which boot.S defines page + * tables for. + */ + mem_size = m->addr + m->len; + if (mem_size > PLATFORM_MAX_MEM_SIZE) + mem_size = PLATFORM_MAX_MEM_SIZE; + + platform_intr_init(); +} + +const char *platform_cmdline(void) +{ + return cmdline; +} + +uint64_t platform_mem_size(void) +{ + return mem_size; +} + +void platform_exit(int status __attribute__((unused)), + void *cookie __attribute__((unused))) +{ + /* + * Poke the QEMU "isa-debug-exit" device to "shutdown". Should be harmless + * if it is not present. This is used to enable automated tests on virtio. + * Note that the actual QEMU exit() status will be 83 ('S', 41 << 1 | 1). + */ + outw(0x501, 41); + + /* + * If we got here, there is no way to initiate "shutdown" on virtio without + * ACPI, so just halt. + */ + platform_puts("Solo5: Halted\n", 14); + cpu_halt(); +} + +int platform_puts(const char *buf, int n) +{ + int i; + + for (i = 0; i < n; i++) + serial_putc(buf[i]); + + return n; +} + +void solo5_console_write(const char *buf, size_t size) +{ + (void)platform_puts(buf, size); +} diff --git a/pool/shard002/C/0057497_list.c b/pool/shard002/C/0057497_list.c new file mode 100644 index 0000000000000000000000000000000000000000..7497505216c4df275345755a13e27b606f64adb6 --- /dev/null +++ b/pool/shard002/C/0057497_list.c @@ -0,0 +1,202 @@ + +// +// list.c +// +// Copyright (c) 2010 TJ Holowaychuk +// + +#include "list.h" + +/* + * Allocate a new list_t. NULL on failure. + */ + +list_t * +list_new() { + list_t *self; + if (!(self = LIST_MALLOC(sizeof(list_t)))) + return NULL; + self->head = NULL; + self->tail = NULL; + self->free = NULL; + self->match = NULL; + self->len = 0; + return self; +} + +/* + * Free the list. + */ + +void +list_destroy(list_t *self) { + unsigned int len = self->len; + list_node_t *next; + list_node_t *curr = self->head; + + while (len--) { + next = curr->next; + if (self->free) self->free(curr->val); + LIST_FREE(curr); + curr = next; + } + + LIST_FREE(self); +} + +/* + * Append the given node to the list + * and return the node, NULL on failure. + */ + +list_node_t * +list_rpush(list_t *self, list_node_t *node) { + if (!node) return NULL; + + if (self->len) { + node->prev = self->tail; + node->next = NULL; + self->tail->next = node; + self->tail = node; + } else { + self->head = self->tail = node; + node->prev = node->next = NULL; + } + + ++self->len; + return node; +} + +/* + * Return / detach the last node in the list, or NULL. + */ + +list_node_t * +list_rpop(list_t *self) { + if (!self->len) return NULL; + + list_node_t *node = self->tail; + + if (--self->len) { + (self->tail = node->prev)->next = NULL; + } else { + self->tail = self->head = NULL; + } + + node->next = node->prev = NULL; + return node; +} + +/* + * Return / detach the first node in the list, or NULL. + */ + +list_node_t * +list_lpop(list_t *self) { + if (!self->len) return NULL; + + list_node_t *node = self->head; + + if (--self->len) { + (self->head = node->next)->prev = NULL; + } else { + self->head = self->tail = NULL; + } + + node->next = node->prev = NULL; + return node; +} + +/* + * Prepend the given node to the list + * and return the node, NULL on failure. + */ + +list_node_t * +list_lpush(list_t *self, list_node_t *node) { + if (!node) return NULL; + + if (self->len) { + node->next = self->head; + node->prev = NULL; + self->head->prev = node; + self->head = node; + } else { + self->head = self->tail = node; + node->prev = node->next = NULL; + } + + ++self->len; + return node; +} + +/* + * Return the node associated to val or NULL. + */ + +list_node_t * +list_find(list_t *self, void *val) { + list_iterator_t *it = list_iterator_new(self, LIST_HEAD); + list_node_t *node; + + while ((node = list_iterator_next(it))) { + if (self->match) { + if (self->match(val, node->val)) { + list_iterator_destroy(it); + return node; + } + } else { + if (val == node->val) { + list_iterator_destroy(it); + return node; + } + } + } + + list_iterator_destroy(it); + return NULL; +} + +/* + * Return the node at the given index or NULL. + */ + +list_node_t * +list_at(list_t *self, int index) { + list_direction_t direction = LIST_HEAD; + + if (index < 0) { + direction = LIST_TAIL; + index = ~index; + } + + if ((unsigned)index < self->len) { + list_iterator_t *it = list_iterator_new(self, direction); + list_node_t *node = list_iterator_next(it); + while (index--) node = list_iterator_next(it); + list_iterator_destroy(it); + return node; + } + + return NULL; +} + +/* + * Remove the given node from the list, freeing it and it's value. + */ + +void +list_remove(list_t *self, list_node_t *node) { + node->prev + ? (node->prev->next = node->next) + : (self->head = node->next); + + node->next + ? (node->next->prev = node->prev) + : (self->tail = node->prev); + + if (self->free) self->free(node->val); + + LIST_FREE(node); + --self->len; +} diff --git a/pool/shard002/C/0057534_SPI.c b/pool/shard002/C/0057534_SPI.c new file mode 100644 index 0000000000000000000000000000000000000000..7131e8c35155af0d6dec3867e9b099852d31faa4 --- /dev/null +++ b/pool/shard002/C/0057534_SPI.c @@ -0,0 +1,23 @@ +#define ss PORTB.B2 + +void main(void) +{ + ADCON1=0x0F; //all pins are digital IO + + //ss pin is output + TRISB&=0xFB; + ss=1; + + SPI1_Init_Advanced(_SPI_MASTER_OSC_DIV64, _SPI_DATA_SAMPLE_MIDDLE, _SPI_CLK_IDLE_LOW, _SPI_LOW_2_HIGH); //initialize SPI in 00 mode + + //send data for D/A conversion + ss=0; + SPI1_Write(0x37); + SPI1_Write(0xFF); + ss=1; + Delay_ms(1); + + //write code to read data from SPI bus if needed + + while(1); +} \ No newline at end of file diff --git a/pool/shard002/C/0057545_hostlist_sctp.c b/pool/shard002/C/0057545_hostlist_sctp.c new file mode 100644 index 0000000000000000000000000000000000000000..ae81c5974349928d86237116402cbc389bdcf1c5 --- /dev/null +++ b/pool/shard002/C/0057545_hostlist_sctp.c @@ -0,0 +1,82 @@ +/* hostlist_sctp.c 2008 Stig Bjorlykke + * + * $Id$ + * + * Wireshark - Network traffic analyzer + * By Gerald Combs + * Copyright 1998 Gerald Combs + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +#include "config.h" + +#include + +#include + +#include "epan/packet.h" +#include +#include +#include + +#include "../stat_menu.h" + +#include "ui/gtk/gui_stat_menu.h" +#include "ui/gtk/hostlist_table.h" + +static int +sctp_hostlist_packet(void *pit, packet_info *pinfo, epan_dissect_t *edt _U_, const void *vip) +{ + hostlist_table *hosts=(hostlist_table *)pit; + const struct _sctp_info *sctphdr=(struct _sctp_info *)vip; + + /* Take two "add" passes per packet, adding for each direction, ensures that all + packets are counted properly (even if address is sending to itself) + XXX - this could probably be done more efficiently inside hostlist_table */ + add_hostlist_table_data(hosts, &sctphdr->ip_src, sctphdr->sport, TRUE, 1, + pinfo->fd->pkt_len, SAT_NONE, PT_SCTP); + add_hostlist_table_data(hosts, &sctphdr->ip_dst, sctphdr->dport, FALSE, 1, + pinfo->fd->pkt_len, SAT_NONE, PT_SCTP); + + return 1; +} + +static void +gtk_sctp_hostlist_init(const char *opt_arg, void* userdata _U_) +{ + const char *filter=NULL; + + if(!strncmp(opt_arg,"hosts,sctp,",11)){ + filter=opt_arg+11; + } else { + filter=NULL; + } + + init_hostlist_table(FALSE, "SCTP", "sctp", filter, sctp_hostlist_packet); +} + +void +gtk_sctp_hostlist_cb(GtkAction *action _U_, gpointer user_data _U_) +{ + gtk_sctp_hostlist_init("hosts,sctp",NULL); +} + +void +register_tap_listener_sctp_hostlist(void) +{ + register_stat_cmd_arg("hosts,sctp", gtk_sctp_hostlist_init,NULL); + register_hostlist_table(FALSE, "SCTP", "sctp", NULL /*filter*/, sctp_hostlist_packet); +} diff --git a/pool/shard002/C/0057555_mmap_rw.c b/pool/shard002/C/0057555_mmap_rw.c new file mode 100644 index 0000000000000000000000000000000000000000..cf482d5ccad3719278e9d45ca8e3e745aecdffdf --- /dev/null +++ b/pool/shard002/C/0057555_mmap_rw.c @@ -0,0 +1,102 @@ +/* + * ===================================================================================== + * + * Filename: mmap_rw.c + * + * Description: + * + * Version: 1.0 + * Created: 10/24/2016 11:18:24 AM + * Revision: none + * Compiler: gcc + * + * Author: Eugen Betke (betke@dkrz.de) + * Organization: DKRZ (Deutsches Klimarechenzentrum) + * + * ===================================================================================== + */ + +#include +#include +#include +#include +#include +#include +#include + +#define FILEPATH "/tmp/mmapped.bin" +#define NUMINTS (1000) +#define FILESIZE (NUMINTS * sizeof(int)) + +int main(int argc, char *argv[]) +{ + int i; + int fd; + int result; + int *map; /* mmapped array of int's */ + + /* Open a file for writing. + * - Creating the file if it doesn't exist. + * - Truncating it to 0 size if it already exists. (not really needed) + * + * Note: "O_WRONLY" mode is not sufficient when mmaping. + */ + fd = open(FILEPATH, O_RDWR | O_CREAT | O_TRUNC, (mode_t)0600); + if (fd == -1) { + perror("Error opening file for writing"); + exit(EXIT_FAILURE); + } + + /* Stretch the file size to the size of the (mmapped) array of ints + */ + result = lseek(fd, FILESIZE-1, SEEK_SET); + if (result == -1) { + close(fd); + perror("Error calling lseek() to 'stretch' the file"); + exit(EXIT_FAILURE); + } + + /* Something needs to be written at the end of the file to + * have the file actually have the new size. + * Just writing an empty string at the current file position will do. + * + * Note: + * - The current position in the file is at the end of the stretched + * file due to the call to lseek(). + * - An empty string is actually a single '\0' character, so a zero-byte + * will be written at the last byte of the file. + */ + result = write(fd, "", 1); + if (result != 1) { + close(fd); + perror("Error writing last byte of the file"); + exit(EXIT_FAILURE); + } + + /* Now the file is ready to be mmapped. + */ + map = mmap(0, FILESIZE, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); + if (map == MAP_FAILED) { + close(fd); + perror("Error mmapping the file"); + exit(EXIT_FAILURE); + } + + /* Now write int's to the file as if it were memory (an array of ints). + */ + for (i = 1; i <=NUMINTS; ++i) { + map[i] = 2 * i; + } + + /* Don't forget to free the mmapped memory + */ + if (munmap(map, FILESIZE) == -1) { + perror("Error un-mmapping the file"); + /* Decide here whether to close(fd) and exit() or not. Depends... */ + } + + /* Un-mmaping doesn't close the file, so we still need to do that. + */ + close(fd); + return 0; +} diff --git a/pool/shard002/C/0057584_test-ffsll.c b/pool/shard002/C/0057584_test-ffsll.c new file mode 100644 index 0000000000000000000000000000000000000000..9747a961971f42d64753abc3300da0b995d19d63 --- /dev/null +++ b/pool/shard002/C/0057584_test-ffsll.c @@ -0,0 +1,68 @@ +/* + * Copyright (C) 2011-2014 Free Software Foundation, Inc. + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . */ + +/* Written by Eric Blake. */ +#include + +#include + +#include "signature.h" +SIGNATURE_CHECK (ffsll, int, (long long int)); + +#include + +#include "macros.h" + +#define NBITS (sizeof (long long int) * CHAR_BIT) + +static int +naive (long long int i) +{ + unsigned long long int j; + for (j = 0; j < NBITS; j++) + if (i & (1ULL << j)) + return j + 1; + return 0; +} + +int +main (int argc, char *argv[]) +{ + long long int x; + int i; + + for (x = -128; x <= 128; x++) + ASSERT (ffsll (x) == naive (x)); + for (i = 0; i < NBITS; i++) + { + ASSERT (ffsll (1ULL << i) == naive (1ULL << i)); + ASSERT (ffsll (1ULL << i) == i + 1); + ASSERT (ffsll (-1ULL << i) == i + 1); + } + for (i = 0; i < NBITS - 1; i++) + { + ASSERT (ffsll (3ULL << i) == i + 1); + ASSERT (ffsll (-3ULL << i) == i + 1); + } + for (i = 0; i < NBITS - 2; i++) + { + ASSERT (ffsll (5ULL << i) == i + 1); + ASSERT (ffsll (-5ULL << i) == i + 1); + ASSERT (ffsll (7ULL << i) == i + 1); + ASSERT (ffsll (-7ULL << i) == i + 1); + } + return 0; +} diff --git a/pool/shard002/C/0057586_xscugic.c b/pool/shard002/C/0057586_xscugic.c new file mode 100644 index 0000000000000000000000000000000000000000..5a6b2ca424232228edf15d4bae4e94dea0c1de16 --- /dev/null +++ b/pool/shard002/C/0057586_xscugic.c @@ -0,0 +1,713 @@ +/****************************************************************************** +* +* Copyright (C) 2010 - 2014 Xilinx, Inc. All rights reserved. +* +* 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. +* +* Use of the Software is limited solely to applications: +* (a) running on a Xilinx device, or +* (b) that interact with a Xilinx device through a bus or interconnect. +* +* 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 +* XILINX 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 of the Xilinx shall not be used +* in advertising or otherwise to promote the sale, use or other dealings in +* this Software without prior written authorization from Xilinx. +* +******************************************************************************/ +/*****************************************************************************/ +/** +* +* @file xscugic.c +* @addtogroup scugic_v2_1 +* @{ +* +* Contains required functions for the XScuGic driver for the Interrupt +* Controller. See xscugic.h for a detailed description of the driver. +* +*
+* MODIFICATION HISTORY:
+*
+* Ver   Who  Date     Changes
+* ----- ---- -------- --------------------------------------------------------
+* 1.00a drg  01/19/10 First release
+* 1.01a sdm  11/09/11 Changes are made in function XScuGic_CfgInitialize. Since
+*		      "Config" entry is now made as pointer in the XScuGic
+*		      structure, necessary changes are made.
+*		      The HandlerTable can now be populated through the low
+*		      level routine XScuGic_RegisterHandler added in this
+*		      release. Hence necessary checks are added not to
+*		      overwrite the HandlerTable entriesin function
+*		      XScuGic_CfgInitialize.
+* 1.03a srt  02/27/13 Added APIs
+*			- XScuGic_SetPriTrigTypeByDistAddr()
+*			- XScuGic_GetPriTrigTypeByDistAddr()
+* 		      Removed Offset calculation macros, defined in _hw.h
+*		      (CR 702687)
+*			  Added support to direct interrupts to the appropriate CPU. Earlier
+*			  interrupts were directed to CPU1 (hard coded). Now depending
+*			  upon the CPU selected by the user (xparameters.h), interrupts
+*			  will be directed to the relevant CPU. This fixes CR 699688.
+*
+* 1.04a hk   05/04/13 Assigned EffectiveAddr to CpuBaseAddress in
+*			  XScuGic_CfgInitialize. Fix for CR#704400 to remove warnings.
+*			  Moved functions XScuGic_SetPriTrigTypeByDistAddr and
+*             XScuGic_GetPriTrigTypeByDistAddr to xscugic_hw.c.
+*			  This is fix for CR#705621.
+* 1.06a asa  16/11/13 Fix for CR#749178. Assignment for EffectiveAddr
+*			  in function XScuGic_CfgInitialize is removed as it was
+*		      a bug.
+*
+* 
+* +******************************************************************************/ + +/***************************** Include Files *********************************/ +#include "xparameters.h" +#include "xil_types.h" +#include "xil_assert.h" +#include "xscugic.h" + + +/************************** Constant Definitions *****************************/ + + +/**************************** Type Definitions *******************************/ + + +/***************** Macros (Inline Functions) Definitions *********************/ + +/************************** Variable Definitions *****************************/ + +/************************** Function Prototypes ******************************/ + +static void StubHandler(void *CallBackRef); + +/*****************************************************************************/ +/** +* +* DistInit initializes the distributor of the GIC. The +* initialization entails: +* +* - Write the trigger mode, priority and target CPU +* - All interrupt sources are disabled +* - Enable the distributor +* +* @param InstancePtr is a pointer to the XScuGic instance. +* @param CpuID is the Cpu ID to be initialized. +* +* @return None +* +* @note None. +* +******************************************************************************/ +static void DistInit(XScuGic *InstancePtr, u32 CpuID) +{ + u32 Int_Id; + +#if USE_AMP==1 + #warning "Building GIC for AMP" + + /* + * The distrubutor should not be initialized by FreeRTOS in the case of + * AMP -- it is assumed that Linux is the master of this device in that + * case. + */ + return; +#endif + + XScuGic_DistWriteReg(InstancePtr, XSCUGIC_DIST_EN_OFFSET, 0UL); + + /* + * Set the security domains in the int_security registers for + * non-secure interrupts + * All are secure, so leave at the default. Set to 1 for non-secure + * interrupts. + */ + + /* + * For the Shared Peripheral Interrupts INT_ID[MAX..32], set: + */ + + /* + * 1. The trigger mode in the int_config register + * Only write to the SPI interrupts, so start at 32 + */ + for (Int_Id = 32; Int_Id < XSCUGIC_MAX_NUM_INTR_INPUTS; Int_Id+=16) { + /* + * Each INT_ID uses two bits, or 16 INT_ID per register + * Set them all to be level sensitive, active HIGH. + */ + XScuGic_DistWriteReg(InstancePtr, + XSCUGIC_INT_CFG_OFFSET_CALC(Int_Id), + 0UL); + } + + +#define DEFAULT_PRIORITY 0xa0a0a0a0UL + for (Int_Id = 0; Int_Id < XSCUGIC_MAX_NUM_INTR_INPUTS; Int_Id+=4) { + /* + * 2. The priority using int the priority_level register + * The priority_level and spi_target registers use one byte per + * INT_ID. + * Write a default value that can be changed elsewhere. + */ + XScuGic_DistWriteReg(InstancePtr, + XSCUGIC_PRIORITY_OFFSET_CALC(Int_Id), + DEFAULT_PRIORITY); + } + + for (Int_Id = 32; Int_IdBaseAddress for this parameters, passing the physical +* address instead. +* +* @return +* - XST_SUCCESS if initialization was successful +* +* @note None. +* +******************************************************************************/ +int XScuGic_CfgInitialize(XScuGic *InstancePtr, + XScuGic_Config *ConfigPtr, + u32 EffectiveAddr) +{ + u32 Int_Id; + u8 Cpu_Id = XPAR_CPU_ID + 1; + (void) EffectiveAddr; + + Xil_AssertNonvoid(InstancePtr != NULL); + Xil_AssertNonvoid(ConfigPtr != NULL); + + if(InstancePtr->IsReady != XIL_COMPONENT_IS_READY) { + + InstancePtr->IsReady = 0; + InstancePtr->Config = ConfigPtr; + + + for (Int_Id = 0; Int_IdConfig->HandlerTable[Int_Id].Handler == 0)) { + InstancePtr->Config->HandlerTable[Int_Id].Handler = + StubHandler; + } + InstancePtr->Config->HandlerTable[Int_Id].CallBackRef = + InstancePtr; + } + + DistInit(InstancePtr, Cpu_Id); + CPUInit(InstancePtr); + + InstancePtr->IsReady = XIL_COMPONENT_IS_READY; + } + + return XST_SUCCESS; +} + +/*****************************************************************************/ +/** +* +* Makes the connection between the Int_Id of the interrupt source and the +* associated handler that is to run when the interrupt is recognized. The +* argument provided in this call as the Callbackref is used as the argument +* for the handler when it is called. +* +* @param InstancePtr is a pointer to the XScuGic instance. +* @param Int_Id contains the ID of the interrupt source and should be +* in the range of 0 to XSCUGIC_MAX_NUM_INTR_INPUTS - 1 +* @param Handler to the handler for that interrupt. +* @param CallBackRef is the callback reference, usually the instance +* pointer of the connecting driver. +* +* @return +* +* - XST_SUCCESS if the handler was connected correctly. +* +* @note +* +* WARNING: The handler provided as an argument will overwrite any handler +* that was previously connected. +* +****************************************************************************/ +int XScuGic_Connect(XScuGic *InstancePtr, u32 Int_Id, + Xil_InterruptHandler Handler, void *CallBackRef) +{ + /* + * Assert the arguments + */ + Xil_AssertNonvoid(InstancePtr != NULL); + Xil_AssertNonvoid(Int_Id < XSCUGIC_MAX_NUM_INTR_INPUTS); + Xil_AssertNonvoid(Handler != NULL); + Xil_AssertNonvoid(InstancePtr->IsReady == XIL_COMPONENT_IS_READY); + + /* + * The Int_Id is used as an index into the table to select the proper + * handler + */ + InstancePtr->Config->HandlerTable[Int_Id].Handler = Handler; + InstancePtr->Config->HandlerTable[Int_Id].CallBackRef = CallBackRef; + + return XST_SUCCESS; +} + +/*****************************************************************************/ +/** +* +* Updates the interrupt table with the Null Handler and NULL arguments at the +* location pointed at by the Int_Id. This effectively disconnects that interrupt +* source from any handler. The interrupt is disabled also. +* +* @param InstancePtr is a pointer to the XScuGic instance to be worked on. +* @param Int_Id contains the ID of the interrupt source and should +* be in the range of 0 to XSCUGIC_MAX_NUM_INTR_INPUTS - 1 +* +* @return None. +* +* @note None. +* +****************************************************************************/ +void XScuGic_Disconnect(XScuGic *InstancePtr, u32 Int_Id) +{ + u32 Mask; + + /* + * Assert the arguments + */ + Xil_AssertVoid(InstancePtr != NULL); + Xil_AssertVoid(Int_Id < XSCUGIC_MAX_NUM_INTR_INPUTS); + Xil_AssertVoid(InstancePtr->IsReady == XIL_COMPONENT_IS_READY); + + /* + * The Int_Id is used to create the appropriate mask for the + * desired bit position. Int_Id currently limited to 0 - 31 + */ + Mask = 0x00000001 << (Int_Id % 32); + + /* + * Disable the interrupt such that it won't occur while disconnecting + * the handler, only disable the specified interrupt id without modifying + * the other interrupt ids + */ + XScuGic_DistWriteReg(InstancePtr, XSCUGIC_DISABLE_OFFSET + + ((Int_Id / 32) * 4), Mask); + + /* + * Disconnect the handler and connect a stub, the callback reference + * must be set to this instance to allow unhandled interrupts to be + * tracked + */ + InstancePtr->Config->HandlerTable[Int_Id].Handler = StubHandler; + InstancePtr->Config->HandlerTable[Int_Id].CallBackRef = InstancePtr; +} + +/*****************************************************************************/ +/** +* +* Enables the interrupt source provided as the argument Int_Id. Any pending +* interrupt condition for the specified Int_Id will occur after this function is +* called. +* +* @param InstancePtr is a pointer to the XScuGic instance. +* @param Int_Id contains the ID of the interrupt source and should be +* in the range of 0 to XSCUGIC_MAX_NUM_INTR_INPUTS - 1 +* +* @return None. +* +* @note None. +* +****************************************************************************/ +void XScuGic_Enable(XScuGic *InstancePtr, u32 Int_Id) +{ + u32 Mask; + + /* + * Assert the arguments + */ + Xil_AssertVoid(InstancePtr != NULL); + Xil_AssertVoid(Int_Id < XSCUGIC_MAX_NUM_INTR_INPUTS); + Xil_AssertVoid(InstancePtr->IsReady == XIL_COMPONENT_IS_READY); + + /* + * The Int_Id is used to create the appropriate mask for the + * desired bit position. Int_Id currently limited to 0 - 31 + */ + Mask = 0x00000001 << (Int_Id % 32); + + /* + * Enable the selected interrupt source by setting the + * corresponding bit in the Enable Set register. + */ + XScuGic_DistWriteReg(InstancePtr, XSCUGIC_ENABLE_SET_OFFSET + + ((Int_Id / 32) * 4), Mask); +} + +/*****************************************************************************/ +/** +* +* Disables the interrupt source provided as the argument Int_Id such that the +* interrupt controller will not cause interrupts for the specified Int_Id. The +* interrupt controller will continue to hold an interrupt condition for the +* Int_Id, but will not cause an interrupt. +* +* @param InstancePtr is a pointer to the XScuGic instance. +* @param Int_Id contains the ID of the interrupt source and should be +* in the range of 0 to XSCUGIC_MAX_NUM_INTR_INPUTS - 1 +* +* @return None. +* +* @note None. +* +****************************************************************************/ +void XScuGic_Disable(XScuGic *InstancePtr, u32 Int_Id) +{ + u32 Mask; + + /* + * Assert the arguments + */ + Xil_AssertVoid(InstancePtr != NULL); + Xil_AssertVoid(Int_Id < XSCUGIC_MAX_NUM_INTR_INPUTS); + Xil_AssertVoid(InstancePtr->IsReady == XIL_COMPONENT_IS_READY); + + /* + * The Int_Id is used to create the appropriate mask for the + * desired bit position. Int_Id currently limited to 0 - 31 + */ + Mask = 0x00000001 << (Int_Id % 32); + + /* + * Disable the selected interrupt source by setting the + * corresponding bit in the IDR. + */ + XScuGic_DistWriteReg(InstancePtr, XSCUGIC_DISABLE_OFFSET + + ((Int_Id / 32) * 4), Mask); +} + +/*****************************************************************************/ +/** +* +* Allows software to simulate an interrupt in the interrupt controller. This +* function will only be successful when the interrupt controller has been +* started in simulation mode. A simulated interrupt allows the interrupt +* controller to be tested without any device to drive an interrupt input +* signal into it. +* +* @param InstancePtr is a pointer to the XScuGic instance. +* @param Int_Id is the software interrupt ID to simulate an interrupt. +* @param Cpu_Id is the list of CPUs to send the interrupt. +* +* @return +* +* XST_SUCCESS if successful, or XST_FAILURE if the interrupt could not be +* simulated +* +* @note None. +* +******************************************************************************/ +int XScuGic_SoftwareIntr(XScuGic *InstancePtr, u32 Int_Id, u32 Cpu_Id) +{ + u32 Mask; + + /* + * Assert the arguments + */ + Xil_AssertNonvoid(InstancePtr != NULL); + Xil_AssertNonvoid(InstancePtr->IsReady == XIL_COMPONENT_IS_READY); + Xil_AssertNonvoid(Int_Id <= 15) ; + Xil_AssertNonvoid(Cpu_Id <= 255) ; + + + /* + * The Int_Id is used to create the appropriate mask for the + * desired interrupt. Int_Id currently limited to 0 - 15 + * Use the target list for the Cpu ID. + */ + Mask = ((Cpu_Id << 16) | Int_Id) & + (XSCUGIC_SFI_TRIG_CPU_MASK | XSCUGIC_SFI_TRIG_INTID_MASK); + + /* + * Write to the Software interrupt trigger register. Use the appropriate + * CPU Int_Id. + */ + XScuGic_DistWriteReg(InstancePtr, XSCUGIC_SFI_TRIG_OFFSET, Mask); + + /* Indicate the interrupt was successfully simulated */ + + return XST_SUCCESS; +} + +/*****************************************************************************/ +/** +* +* A stub for the asynchronous callback. The stub is here in case the upper +* layers forget to set the handler. +* +* @param CallBackRef is a pointer to the upper layer callback reference +* +* @return None. +* +* @note None. +* +******************************************************************************/ +static void StubHandler(void *CallBackRef) { + /* + * verify that the inputs are valid + */ + Xil_AssertVoid(CallBackRef != NULL); + + /* + * Indicate another unhandled interrupt for stats + */ + ((XScuGic *)CallBackRef)->UnhandledInterrupts++; +} + +/****************************************************************************/ +/** +* Sets the interrupt priority and trigger type for the specificd IRQ source. +* +* @param InstancePtr is a pointer to the instance to be worked on. +* @param Int_Id is the IRQ source number to modify +* @param Priority is the new priority for the IRQ source. 0 is highest +* priority, 0xF8 (248) is lowest. There are 32 priority levels +* supported with a step of 8. Hence the supported priorities are +* 0, 8, 16, 32, 40 ..., 248. +* @param Trigger is the new trigger type for the IRQ source. +* Each bit pair describes the configuration for an INT_ID. +* SFI Read Only b10 always +* PPI Read Only depending on how the PPIs are configured. +* b01 Active HIGH level sensitive +* b11 Rising edge sensitive +* SPI LSB is read only. +* b01 Active HIGH level sensitive +* b11 Rising edge sensitive/ +* +* @return None. +* +* @note None. +* +*****************************************************************************/ +void XScuGic_SetPriorityTriggerType(XScuGic *InstancePtr, u32 Int_Id, + u8 Priority, u8 Trigger) +{ + u32 RegValue; + + Xil_AssertVoid(InstancePtr != NULL); + Xil_AssertVoid(InstancePtr->IsReady == XIL_COMPONENT_IS_READY); + Xil_AssertVoid(Int_Id < XSCUGIC_MAX_NUM_INTR_INPUTS); + Xil_AssertVoid(Trigger <= XSCUGIC_INT_CFG_MASK); + Xil_AssertVoid(Priority <= XSCUGIC_MAX_INTR_PRIO_VAL); + + /* + * Determine the register to write to using the Int_Id. + */ + RegValue = XScuGic_DistReadReg(InstancePtr, + XSCUGIC_PRIORITY_OFFSET_CALC(Int_Id)); + + /* + * The priority bits are Bits 7 to 3 in GIC Priority Register. This + * means the number of priority levels supported are 32 and they are + * in steps of 8. The priorities can be 0, 8, 16, 32, 48, ... etc. + * The lower order 3 bits are masked before putting it in the register. + */ + Priority = Priority & XSCUGIC_INTR_PRIO_MASK; + /* + * Shift and Mask the correct bits for the priority and trigger in the + * register + */ + RegValue &= ~(XSCUGIC_PRIORITY_MASK << ((Int_Id%4)*8)); + RegValue |= Priority << ((Int_Id%4)*8); + + /* + * Write the value back to the register. + */ + XScuGic_DistWriteReg(InstancePtr, XSCUGIC_PRIORITY_OFFSET_CALC(Int_Id), + RegValue); + + /* + * Determine the register to write to using the Int_Id. + */ + RegValue = XScuGic_DistReadReg(InstancePtr, + XSCUGIC_INT_CFG_OFFSET_CALC (Int_Id)); + + /* + * Shift and Mask the correct bits for the priority and trigger in the + * register + */ + RegValue &= ~(XSCUGIC_INT_CFG_MASK << ((Int_Id%16)*2)); + RegValue |= Trigger << ((Int_Id%16)*2); + + /* + * Write the value back to the register. + */ + XScuGic_DistWriteReg(InstancePtr, XSCUGIC_INT_CFG_OFFSET_CALC(Int_Id), + RegValue); + +} + +/****************************************************************************/ +/** +* Gets the interrupt priority and trigger type for the specificd IRQ source. +* +* @param InstancePtr is a pointer to the instance to be worked on. +* @param Int_Id is the IRQ source number to modify +* @param Priority is a pointer to the value of the priority of the IRQ +* source. This is a return value. +* @param Trigger is pointer to the value of the trigger of the IRQ +* source. This is a return value. +* +* @return None. +* +* @note None +* +*****************************************************************************/ +void XScuGic_GetPriorityTriggerType(XScuGic *InstancePtr, u32 Int_Id, + u8 *Priority, u8 *Trigger) +{ + u32 RegValue; + + Xil_AssertVoid(InstancePtr != NULL); + Xil_AssertVoid(InstancePtr->IsReady == XIL_COMPONENT_IS_READY); + Xil_AssertVoid(Int_Id < XSCUGIC_MAX_NUM_INTR_INPUTS); + Xil_AssertVoid(Priority != NULL); + Xil_AssertVoid(Trigger != NULL); + + /* + * Determine the register to read to using the Int_Id. + */ + RegValue = XScuGic_DistReadReg(InstancePtr, + XSCUGIC_PRIORITY_OFFSET_CALC(Int_Id)); + + /* + * Shift and Mask the correct bits for the priority and trigger in the + * register + */ + RegValue = RegValue >> ((Int_Id%4)*8); + *Priority = RegValue & XSCUGIC_PRIORITY_MASK; + + /* + * Determine the register to read to using the Int_Id. + */ + RegValue = XScuGic_DistReadReg(InstancePtr, + XSCUGIC_INT_CFG_OFFSET_CALC (Int_Id)); + + /* + * Shift and Mask the correct bits for the priority and trigger in the + * register + */ + RegValue = RegValue >> ((Int_Id%16)*2); + + *Trigger = RegValue & XSCUGIC_INT_CFG_MASK; +} + +/** @} */ diff --git a/pool/shard002/C/0057588_det_rng.c b/pool/shard002/C/0057588_det_rng.c new file mode 100644 index 0000000000000000000000000000000000000000..fcbf9b34a82c424ee9c7175af214189b79a962a8 --- /dev/null +++ b/pool/shard002/C/0057588_det_rng.c @@ -0,0 +1,67 @@ +/* This Source Code Form is subject to the terms of the Mozilla Public + * License, v. 2.0. If a copy of the MPL was not distributed with this + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ + +#include "blapi.h" +#include "blapit.h" +#include "chacha20.h" +#include "nssilock.h" +#include "seccomon.h" +#include "secerr.h" + +static unsigned long globalNumCalls = 0; + +SECStatus +prng_ResetForFuzzing(PZLock *rng_lock) +{ + /* Check for a valid RNG lock. */ + PORT_Assert(rng_lock != NULL); + if (rng_lock == NULL) { + PORT_SetError(SEC_ERROR_INVALID_ARGS); + return SECFailure; + } + + /* --- LOCKED --- */ + PZ_Lock(rng_lock); + globalNumCalls = 0; + PZ_Unlock(rng_lock); + /* --- UNLOCKED --- */ + + return SECSuccess; +} + +SECStatus +prng_GenerateDeterministicRandomBytes(PZLock *rng_lock, void *dest, size_t len) +{ + static const uint8_t key[32]; + uint8_t nonce[12] = { 0 }; + + /* Check for a valid RNG lock. */ + PORT_Assert(rng_lock != NULL); + if (rng_lock == NULL) { + PORT_SetError(SEC_ERROR_INVALID_ARGS); + return SECFailure; + } + + /* --- LOCKED --- */ + PZ_Lock(rng_lock); + + memcpy(nonce, &globalNumCalls, sizeof(globalNumCalls)); + globalNumCalls++; + + ChaCha20Poly1305Context *cx = + ChaCha20Poly1305_CreateContext(key, sizeof(key), 16); + if (!cx) { + PORT_SetError(SEC_ERROR_NO_MEMORY); + PZ_Unlock(rng_lock); + return SECFailure; + } + + memset(dest, 0, len); + ChaCha20XOR(dest, dest, len, key, nonce, 0); + ChaCha20Poly1305_DestroyContext(cx, PR_TRUE); + + PZ_Unlock(rng_lock); + /* --- UNLOCKED --- */ + return SECSuccess; +} diff --git a/pool/shard002/C/0057599_config.c b/pool/shard002/C/0057599_config.c new file mode 100644 index 0000000000000000000000000000000000000000..d3a0e8e7b82ed9cf5ae14cfe9c8e66ca6f8826f1 --- /dev/null +++ b/pool/shard002/C/0057599_config.c @@ -0,0 +1,77 @@ +#include +#include + +int port_output_init(unsigned int value, int on, char *name) +{ + int ret = 0; + struct port_config port; + + port = get_port_config(value); + ret = gpio_request(port.gpio, name); + if(ret < 0) + return ret; + if(port.io.pull_mode == PULL_MODE_DISABLE) + gpio_pull_updown(port.gpio, 0); + if(port.io.pull_mode == PULL_MODE_ENABLE) + gpio_pull_updown(port.gpio, 1); + #ifdef CONFIG_MACH_RK_FAC + //gpio_direction_output(port.gpio, (on)? !port.io.active_low: !!port.io.active_low); + #else + gpio_direction_output(port.gpio, (on)? !port.io.active_low: !!port.io.active_low); + #endif + + return 0; +} +EXPORT_SYMBOL(port_output_init); +void port_output_on(unsigned int value) +{ + struct port_config port; + + port = get_port_config(value); + gpio_set_value(port.gpio, !port.io.active_low); +} +EXPORT_SYMBOL(port_output_on); +void port_output_off(unsigned int value) +{ + struct port_config port; + + port = get_port_config(value); + gpio_set_value(port.gpio, !!port.io.active_low); +} +EXPORT_SYMBOL(port_output_off); +void port_deinit(unsigned int value) +{ + struct port_config port; + + port = get_port_config(value); + gpio_free(port.gpio); +} +EXPORT_SYMBOL(port_deinit); +int port_input_init(unsigned int value, char *name) +{ + int ret = 0; + struct port_config port; + + port = get_port_config(value); + ret = gpio_request(port.gpio, name); + if(ret < 0) + return ret; + if(port.io.pull_mode == PULL_MODE_DISABLE) + gpio_pull_updown(port.gpio, 0); + if(port.io.pull_mode == PULL_MODE_ENABLE) + gpio_pull_updown(port.gpio, 1); + gpio_direction_input(port.gpio); + + return 0; +} +EXPORT_SYMBOL(port_input_init); +int port_get_value(unsigned int value) +{ + struct port_config port; + + port = get_port_config(value); + return gpio_get_value(port.gpio); +} +EXPORT_SYMBOL(port_get_value); + + diff --git a/pool/shard002/C/0057601_main.c b/pool/shard002/C/0057601_main.c new file mode 100644 index 0000000000000000000000000000000000000000..faea5a678e4431b14c3c9a492fa4ae0cd9c59b5e --- /dev/null +++ b/pool/shard002/C/0057601_main.c @@ -0,0 +1,64 @@ +#include +#include + +#ifndef F_CPU +//define cpu clock speed if not defined +#define F_CPU 1000000 +#endif + +//set desired baud rate +#define BAUDRATE 1200 + +//calculate UBRR value +#define UBRRVAL ((F_CPU/(BAUDRATE*16UL))-1) + +//define receive parameters +#define SYNC 0XAA // synchro signal +#define RADDR 0x44 +#define LEDON 0x11 //switch led on command +#define LEDOFF 0x22 //switch led off command + +void USART_Init(void) { + //Set baud rate + UBRRL=(uint8_t)UBRRVAL; //low byte + UBRRH=(UBRRVAL>>8); //high byte + //Set data frame format: asynchronous mode,no parity, 1 stop bit, 8 bit size + UCSRC=(1< + */ + +#include +#include +#include +#include + +#include + +#include +#include + +static void tcp_diag_get_info(struct sock *sk, struct inet_diag_msg *r, + void *_info) +{ + struct tcp_info *info = _info; + + if (inet_sk_state_load(sk) == TCP_LISTEN) { + r->idiag_rqueue = READ_ONCE(sk->sk_ack_backlog); + r->idiag_wqueue = READ_ONCE(sk->sk_max_ack_backlog); + } else if (sk->sk_type == SOCK_STREAM) { + const struct tcp_sock *tp = tcp_sk(sk); + + r->idiag_rqueue = max_t(int, READ_ONCE(tp->rcv_nxt) - + READ_ONCE(tp->copied_seq), 0); + r->idiag_wqueue = READ_ONCE(tp->write_seq) - tp->snd_una; + } + if (info) + tcp_get_info(sk, info); +} + +#ifdef CONFIG_TCP_MD5SIG +static void tcp_diag_md5sig_fill(struct tcp_diag_md5sig *info, + const struct tcp_md5sig_key *key) +{ + info->tcpm_family = key->family; + info->tcpm_prefixlen = key->prefixlen; + info->tcpm_keylen = key->keylen; + memcpy(info->tcpm_key, key->key, key->keylen); + + if (key->family == AF_INET) + info->tcpm_addr[0] = key->addr.a4.s_addr; + #if IS_ENABLED(CONFIG_IPV6) + else if (key->family == AF_INET6) + memcpy(&info->tcpm_addr, &key->addr.a6, + sizeof(info->tcpm_addr)); + #endif +} + +static int tcp_diag_put_md5sig(struct sk_buff *skb, + const struct tcp_md5sig_info *md5sig) +{ + const struct tcp_md5sig_key *key; + struct tcp_diag_md5sig *info; + struct nlattr *attr; + int md5sig_count = 0; + + hlist_for_each_entry_rcu(key, &md5sig->head, node) + md5sig_count++; + if (md5sig_count == 0) + return 0; + + attr = nla_reserve(skb, INET_DIAG_MD5SIG, + md5sig_count * sizeof(struct tcp_diag_md5sig)); + if (!attr) + return -EMSGSIZE; + + info = nla_data(attr); + memset(info, 0, md5sig_count * sizeof(struct tcp_diag_md5sig)); + hlist_for_each_entry_rcu(key, &md5sig->head, node) { + tcp_diag_md5sig_fill(info++, key); + if (--md5sig_count == 0) + break; + } + + return 0; +} +#endif + +static int tcp_diag_put_ulp(struct sk_buff *skb, struct sock *sk, + const struct tcp_ulp_ops *ulp_ops) +{ + struct nlattr *nest; + int err; + + nest = nla_nest_start_noflag(skb, INET_DIAG_ULP_INFO); + if (!nest) + return -EMSGSIZE; + + err = nla_put_string(skb, INET_ULP_INFO_NAME, ulp_ops->name); + if (err) + goto nla_failure; + + if (ulp_ops->get_info) + err = ulp_ops->get_info(sk, skb); + if (err) + goto nla_failure; + + nla_nest_end(skb, nest); + return 0; + +nla_failure: + nla_nest_cancel(skb, nest); + return err; +} + +static int tcp_diag_get_aux(struct sock *sk, bool net_admin, + struct sk_buff *skb) +{ + struct inet_connection_sock *icsk = inet_csk(sk); + int err = 0; + +#ifdef CONFIG_TCP_MD5SIG + if (net_admin) { + struct tcp_md5sig_info *md5sig; + + rcu_read_lock(); + md5sig = rcu_dereference(tcp_sk(sk)->md5sig_info); + if (md5sig) + err = tcp_diag_put_md5sig(skb, md5sig); + rcu_read_unlock(); + if (err < 0) + return err; + } +#endif + + if (net_admin) { + const struct tcp_ulp_ops *ulp_ops; + + ulp_ops = icsk->icsk_ulp_ops; + if (ulp_ops) + err = tcp_diag_put_ulp(skb, sk, ulp_ops); + if (err) + return err; + } + return 0; +} + +static size_t tcp_diag_get_aux_size(struct sock *sk, bool net_admin) +{ + struct inet_connection_sock *icsk = inet_csk(sk); + size_t size = 0; + +#ifdef CONFIG_TCP_MD5SIG + if (net_admin && sk_fullsock(sk)) { + const struct tcp_md5sig_info *md5sig; + const struct tcp_md5sig_key *key; + size_t md5sig_count = 0; + + rcu_read_lock(); + md5sig = rcu_dereference(tcp_sk(sk)->md5sig_info); + if (md5sig) { + hlist_for_each_entry_rcu(key, &md5sig->head, node) + md5sig_count++; + } + rcu_read_unlock(); + size += nla_total_size(md5sig_count * + sizeof(struct tcp_diag_md5sig)); + } +#endif + + if (net_admin && sk_fullsock(sk)) { + const struct tcp_ulp_ops *ulp_ops; + + ulp_ops = icsk->icsk_ulp_ops; + if (ulp_ops) { + size += nla_total_size(0) + + nla_total_size(TCP_ULP_NAME_MAX); + if (ulp_ops->get_info_size) + size += ulp_ops->get_info_size(sk); + } + } + return size; +} + +static void tcp_diag_dump(struct sk_buff *skb, struct netlink_callback *cb, + const struct inet_diag_req_v2 *r) +{ + inet_diag_dump_icsk(&tcp_hashinfo, skb, cb, r); +} + +static int tcp_diag_dump_one(struct netlink_callback *cb, + const struct inet_diag_req_v2 *req) +{ + return inet_diag_dump_one_icsk(&tcp_hashinfo, cb, req); +} + +#ifdef CONFIG_INET_DIAG_DESTROY +static int tcp_diag_destroy(struct sk_buff *in_skb, + const struct inet_diag_req_v2 *req) +{ + struct net *net = sock_net(in_skb->sk); + struct sock *sk = inet_diag_find_one_icsk(net, &tcp_hashinfo, req); + int err; + + if (IS_ERR(sk)) + return PTR_ERR(sk); + + err = sock_diag_destroy(sk, ECONNABORTED); + + sock_gen_put(sk); + + return err; +} +#endif + +static const struct inet_diag_handler tcp_diag_handler = { + .dump = tcp_diag_dump, + .dump_one = tcp_diag_dump_one, + .idiag_get_info = tcp_diag_get_info, + .idiag_get_aux = tcp_diag_get_aux, + .idiag_get_aux_size = tcp_diag_get_aux_size, + .idiag_type = IPPROTO_TCP, + .idiag_info_size = sizeof(struct tcp_info), +#ifdef CONFIG_INET_DIAG_DESTROY + .destroy = tcp_diag_destroy, +#endif +}; + +static int __init tcp_diag_init(void) +{ + return inet_diag_register(&tcp_diag_handler); +} + +static void __exit tcp_diag_exit(void) +{ + inet_diag_unregister(&tcp_diag_handler); +} + +module_init(tcp_diag_init); +module_exit(tcp_diag_exit); +MODULE_LICENSE("GPL"); +MODULE_ALIAS_NET_PF_PROTO_TYPE(PF_NETLINK, NETLINK_SOCK_DIAG, 2-6 /* AF_INET - IPPROTO_TCP */); diff --git a/pool/shard002/C/0057626_rkhfwk_rdygrp.c b/pool/shard002/C/0057626_rkhfwk_rdygrp.c new file mode 100644 index 0000000000000000000000000000000000000000..4710c2822495ae27d74e5e64f519fc9ccbbfbc67 --- /dev/null +++ b/pool/shard002/C/0057626_rkhfwk_rdygrp.c @@ -0,0 +1,144 @@ +/* + * -------------------------------------------------------------------------- + * + * Framework RKH + * ------------- + * + * State-machine framework for reactive embedded systems + * + * Copyright (C) 2010 Leandro Francucci. + * All rights reserved. Protected by international copyright laws. + * + * + * RKH 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. + * + * RKH 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 RKH, see copying.txt file. + * + * Contact information: + * RKH site: http://vortexmakes.com/que-es/ + * RKH GitHub: https://github.com/vortexmakes/RKH + * RKH Sourceforge: https://sourceforge.net/projects/rkh-reactivesys/ + * e-mail: lf@vortexmakes.com + * --------------------------------------------------------------------------- + */ + +/** + * \file rkhfwk_rdygrp.h + * \ingroup fwk + * \brief ... + * \details ... + */ + +/* -------------------------- Development history -------------------------- */ +/* + * 2018.08.07 LeFr v3.1.00 Initial version + */ + +/* -------------------------------- Authors -------------------------------- */ +/* + * LeFr Leandro Francucci lf@vortexmakes.com + */ + +/* --------------------------------- Notes --------------------------------- */ + +/* --------------------------------- Notes --------------------------------- */ +/* ----------------------------- Include files ----------------------------- */ +#include "rkhfwk_rdygrp.h" +#include "rkhitl.h" +#include "rkhfwk_bittbl.h" +#include "rkhassert.h" +#include "rkhfwk_module.h" + +RKH_MODULE_NAME(rkhfwk_rdygrp) + +/* ----------------------------- Local macros ------------------------------ */ +/* ------------------------------- Constants ------------------------------- */ +/* ---------------------------- Local data types --------------------------- */ +/* ---------------------------- Global variables --------------------------- */ +/* ---------------------------- Local variables ---------------------------- */ +/* ----------------------- Local function prototypes ----------------------- */ +/* ---------------------------- Local functions ---------------------------- */ +/* ---------------------------- Global functions --------------------------- */ +void +rkh_rdygrp_init(RKHRdyGrp *const me) +{ + rui8_t *pTbl, i; + + me->grp = 0; + for (pTbl = me->tbl, i = 0; i < RKH_NUM_RDYGRP; ++i, ++pTbl) + { + *pTbl = 0; + } +} + +rbool_t +rkh_rdygrp_isReady(RKHRdyGrp *const me) +{ + return me->grp != 0; +} + +void +rkh_rdygrp_setReady(RKHRdyGrp *const me, rui8_t prio) +{ + RKH_REQUIRE(prio < RKH_CFG_FWK_MAX_SMA); + me->grp |= rkh_bittbl_getBitMask(prio >> 3); + me->tbl[prio >> 3] |= rkh_bittbl_getBitMask(prio & 0x07); +} + +void +rkh_rdygrp_setUnready(RKHRdyGrp *const me, rui8_t prio) +{ + RKH_REQUIRE(prio < RKH_CFG_FWK_MAX_SMA); + if ((me->tbl[prio >> 3] &= ~rkh_bittbl_getBitMask(prio & 0x07)) == 0) + { + me->grp &= ~rkh_bittbl_getBitMask(prio >> 3); + } +} + +rui8_t +rkh_rdygrp_findHighest(RKHRdyGrp *const me) +{ + rui8_t prio; + + prio = rkh_bittbl_getLeastBitSetPos(me->grp); + prio = (rui8_t)((prio << 3) + + (rui8_t)rkh_bittbl_getLeastBitSetPos(me->tbl[prio])); + return prio; +} + +rui8_t +rkh_rdygrp_traverse(RKHRdyGrp *const me, void (*rdyCb)(RdyCbArg *), + RdyCbArg *rdyCbArg) +{ + rui8_t row, column, *pTbl, nBit, nRdyAO; + + nRdyAO = 0; + if (me->grp != 0) + { + for (row = 0, pTbl = me->tbl; row < RKH_NUM_RDYGRP; ++pTbl, ++row) + { + for (column = *pTbl, nBit = 0; (column != 0) && (nBit < 8); + ++nBit, column >>= 1) + { + if ((column & 1) != 0) + { + ++nRdyAO; + rdyCbArg->aoRdyPrio = (row << 3) | nBit; + (*rdyCb)(rdyCbArg); + } + } + } + } + return nRdyAO; +} + +/* ------------------------------ End of file ------------------------------ */ diff --git a/pool/shard002/C/0057635_drm_buffer.c b/pool/shard002/C/0057635_drm_buffer.c new file mode 100644 index 0000000000000000000000000000000000000000..529a0dbe9fc65960e62bc7840320754fb61393e8 --- /dev/null +++ b/pool/shard002/C/0057635_drm_buffer.c @@ -0,0 +1,184 @@ +/************************************************************************** + * + * Copyright 2010 Pauli Nieminen. + * All Rights Reserved. + * + * 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, sub license, 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 (including the + * next paragraph) 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 NON-INFRINGEMENT. IN NO EVENT SHALL + * THE COPYRIGHT HOLDERS, AUTHORS AND/OR ITS SUPPLIERS 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. + * + * + **************************************************************************/ +/* + * Multipart buffer for coping data which is larger than the page size. + * + * Authors: + * Pauli Nieminen + */ + +#include "drm_buffer.h" + +/** + * Allocate the drm buffer object. + * + * buf: Pointer to a pointer where the object is stored. + * size: The number of bytes to allocate. + */ +int drm_buffer_alloc(struct drm_buffer **buf, int size) +{ + int nr_pages = size / PAGE_SIZE + 1; + int idx; + + /* Allocating pointer table to end of structure makes drm_buffer + * variable sized */ + *buf = kzalloc(sizeof(struct drm_buffer) + nr_pages*sizeof(char *), + GFP_KERNEL); + + if (*buf == NULL) { + DRM_ERROR("Failed to allocate drm buffer object to hold" + " %d bytes in %d pages.\n", + size, nr_pages); + return -ENOMEM; + } + + (*buf)->size = size; + + for (idx = 0; idx < nr_pages; ++idx) { + + (*buf)->data[idx] = + kmalloc(min(PAGE_SIZE, size - idx * PAGE_SIZE), + GFP_KERNEL); + + + if ((*buf)->data[idx] == NULL) { + DRM_ERROR("Failed to allocate %dth page for drm" + " buffer with %d bytes and %d pages.\n", + idx + 1, size, nr_pages); + goto error_out; + } + + } + + return 0; + +error_out: + + /* Only last element can be null pointer so check for it first. */ + if ((*buf)->data[idx]) + kfree((*buf)->data[idx]); + + for (--idx; idx >= 0; --idx) + kfree((*buf)->data[idx]); + + kfree(*buf); + return -ENOMEM; +} +EXPORT_SYMBOL(drm_buffer_alloc); + +/** + * Copy the user data to the begin of the buffer and reset the processing + * iterator. + * + * user_data: A pointer the data that is copied to the buffer. + * size: The Number of bytes to copy. + */ +int drm_buffer_copy_from_user(struct drm_buffer *buf, + void __user *user_data, int size) +{ + int nr_pages = size / PAGE_SIZE + 1; + int idx; + + if (size > buf->size) { + DRM_ERROR("Requesting to copy %d bytes to a drm buffer with" + " %d bytes space\n", + size, buf->size); + return -EFAULT; + } + + for (idx = 0; idx < nr_pages; ++idx) { + + if (DRM_COPY_FROM_USER(buf->data[idx], + user_data + idx * PAGE_SIZE, + min(PAGE_SIZE, size - idx * PAGE_SIZE))) { + DRM_ERROR("Failed to copy user data (%p) to drm buffer" + " (%p) %dth page.\n", + user_data, buf, idx); + return -EFAULT; + + } + } + buf->iterator = 0; + return 0; +} +EXPORT_SYMBOL(drm_buffer_copy_from_user); + +/** + * Free the drm buffer object + */ +void drm_buffer_free(struct drm_buffer *buf) +{ + + if (buf != NULL) { + + int nr_pages = buf->size / PAGE_SIZE + 1; + int idx; + for (idx = 0; idx < nr_pages; ++idx) + kfree(buf->data[idx]); + + kfree(buf); + } +} +EXPORT_SYMBOL(drm_buffer_free); + +/** + * Read an object from buffer that may be split to multiple parts. If object + * is not split function just returns the pointer to object in buffer. But in + * case of split object data is copied to given stack object that is suplied + * by caller. + * + * The processing location of the buffer is also advanced to the next byte + * after the object. + * + * objsize: The size of the objet in bytes. + * stack_obj: A pointer to a memory location where object can be copied. + */ +void *drm_buffer_read_object(struct drm_buffer *buf, + int objsize, void *stack_obj) +{ + int idx = drm_buffer_index(buf); + int page = drm_buffer_page(buf); + void *obj = NULL; + + if (idx + objsize <= PAGE_SIZE) { + obj = &buf->data[page][idx]; + } else { + /* The object is split which forces copy to temporary object.*/ + int beginsz = PAGE_SIZE - idx; + memcpy(stack_obj, &buf->data[page][idx], beginsz); + + memcpy(stack_obj + beginsz, &buf->data[page + 1][0], + objsize - beginsz); + + obj = stack_obj; + } + + drm_buffer_advance(buf, objsize); + return obj; +} +EXPORT_SYMBOL(drm_buffer_read_object); diff --git a/pool/shard002/C/0057654_efi_console.c b/pool/shard002/C/0057654_efi_console.c new file mode 100644 index 0000000000000000000000000000000000000000..efca662c50cb8963d7183d9e353a7f4b1ad48226 --- /dev/null +++ b/pool/shard002/C/0057654_efi_console.c @@ -0,0 +1,99 @@ +/*- + * Copyright (c) 2000 Doug Rabson + * 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 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. + */ + +#include +__FBSDID("$FreeBSD: soc2013/dpl/head/sys/boot/efi/libefi/efi_console.c 126807 2004-03-09 04:00:33Z marcel $"); + +#include +#include + +#include "bootstrap.h" + +static SIMPLE_TEXT_OUTPUT_INTERFACE *conout; +static SIMPLE_INPUT_INTERFACE *conin; + +static void +efi_cons_probe(struct console *cp) +{ + conout = ST->ConOut; + conin = ST->ConIn; + cp->c_flags |= C_PRESENTIN | C_PRESENTOUT; +} + +static int +efi_cons_init(int arg) +{ + conout->SetAttribute(conout, EFI_TEXT_ATTR(EFI_LIGHTGRAY, EFI_BLACK)); + return 0; +} + +void +efi_cons_putchar(int c) +{ + CHAR16 buf[2]; + + if (c == '\n') + efi_cons_putchar('\r'); + + buf[0] = c; + buf[1] = 0; + + conout->OutputString(conout, buf); +} + +int +efi_cons_getchar() +{ + EFI_INPUT_KEY key; + EFI_STATUS status; + UINTN junk; + + /* Try to read a key stroke. We wait for one if none is pending. */ + status = conin->ReadKeyStroke(conin, &key); + if (status == EFI_NOT_READY) { + BS->WaitForEvent(1, &conin->WaitForKey, &junk); + status = conin->ReadKeyStroke(conin, &key); + } + return (key.UnicodeChar); +} + +int +efi_cons_poll() +{ + /* This can clear the signaled state. */ + return (BS->CheckEvent(conin->WaitForKey) == EFI_SUCCESS); +} + +struct console efi_console = { + "efi", + "EFI console", + 0, + efi_cons_probe, + efi_cons_init, + efi_cons_putchar, + efi_cons_getchar, + efi_cons_poll +}; diff --git a/pool/shard002/C/0057656_clock_gettime.c b/pool/shard002/C/0057656_clock_gettime.c new file mode 100644 index 0000000000000000000000000000000000000000..741a8d56dacee99eaf5c9d86ca5d7e521bffe1e3 --- /dev/null +++ b/pool/shard002/C/0057656_clock_gettime.c @@ -0,0 +1,80 @@ +/* + * Copyright (c), MM Weiss + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. Neither the name of the MM Weiss 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. + */ + +#ifndef _WIN32 + +#include +#include +#include +#include +#include +#include +#include +#include "compat.h" + +int clock_gettime(clockid_t clk_id, struct timespec *tp) { + kern_return_t ret; + clock_serv_t clk; + clock_id_t clk_serv_id; + mach_timespec_t tm; + + if (clk_id != CLOCK_REALTIME) + return -1; + + clk_serv_id = clk_id == CLOCK_REALTIME ? CALENDAR_CLOCK : SYSTEM_CLOCK; + if (KERN_SUCCESS == (ret = host_get_clock_service(mach_host_self(), clk_serv_id, &clk))) { + if (KERN_SUCCESS == (ret = clock_get_time(clk, &tm))) { + tp->tv_sec = tm.tv_sec; + tp->tv_nsec = tm.tv_nsec; + } + } + if (KERN_SUCCESS != ret) + return -1; + + return 0; +} + +#else + +#include +#include +#include +#include "compat.h" + +int clock_gettime(int clk_id, struct timespec *spec) { + (void)clk_id; + FILETIME wintime; + GetSystemTimeAsFileTime(&wintime); + uint64_t t = (uint64_t)wintime.dwHighDateTime << 32 | wintime.dwLowDateTime; + t -= 116444736000000000; + spec->tv_sec = t / 10000000; + spec->tv_nsec = t % 10000000 * 100; + return 0; +} +#endif diff --git a/pool/shard002/C/0057676_au6610.c b/pool/shard002/C/0057676_au6610.c new file mode 100644 index 0000000000000000000000000000000000000000..0dc66a8d2baff633d6a0c409b5066c82778c7fd9 --- /dev/null +++ b/pool/shard002/C/0057676_au6610.c @@ -0,0 +1,255 @@ +/* DVB USB compliant linux driver for Sigmatek DVB-110 DVB-T USB2.0 receiver + * + * Copyright (C) 2006 Antti Palosaari + * + * 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. + * + * see Documentation/dvb/README.dvb-usb for more information + */ + +#include "au6610.h" + +#include "zl10353.h" +#include "qt1010.h" + +/* debug */ +static int dvb_usb_au6610_debug; +module_param_named(debug, dvb_usb_au6610_debug, int, 0644); +MODULE_PARM_DESC(debug, "set debugging level (1=rc (or-able))." DVB_USB_DEBUG_STATUS); + +static int au6610_usb_msg(struct dvb_usb_device *d, u8 operation, u8 addr, + u8 *wbuf, u16 wlen, u8 *rbuf, u16 rlen) +{ + int ret; + u16 index; + u8 usb_buf[6]; /* enough for all known requests, + read returns 5 and write 6 bytes */ + switch (wlen) { + case 1: + index = wbuf[0] << 8; + break; + case 2: + index = wbuf[0] << 8; + index += wbuf[1]; + break; + default: + warn("wlen = %x, aborting.", wlen); + return -EINVAL; + } + + ret = usb_control_msg(d->udev, usb_rcvctrlpipe(d->udev, 0), operation, + USB_TYPE_VENDOR|USB_DIR_IN, addr, index, usb_buf, + sizeof(usb_buf), AU6610_USB_TIMEOUT); + + if (ret < 0) + return ret; + + switch (operation) { + case AU6610_REQ_I2C_READ: + case AU6610_REQ_USB_READ: + /* requested value is always 5th byte in buffer */ + rbuf[0] = usb_buf[4]; + } + + return ret; +} + +static int au6610_i2c_msg(struct dvb_usb_device *d, u8 addr, + u8 *wbuf, u16 wlen, u8 *rbuf, u16 rlen) +{ + u8 request; + u8 wo = (rbuf == NULL || rlen == 0); /* write-only */ + + if (wo) { + request = AU6610_REQ_I2C_WRITE; + } else { /* rw */ + request = AU6610_REQ_I2C_READ; + } + + return au6610_usb_msg(d, request, addr, wbuf, wlen, rbuf, rlen); +} + + +/* I2C */ +static int au6610_i2c_xfer(struct i2c_adapter *adap, struct i2c_msg msg[], + int num) +{ + struct dvb_usb_device *d = i2c_get_adapdata(adap); + int i; + + if (mutex_lock_interruptible(&d->i2c_mutex) < 0) + return -EAGAIN; + + if (num > 2) + return -EINVAL; + + for (i = 0; i < num; i++) { + /* write/read request */ + if (i+1 < num && (msg[i+1].flags & I2C_M_RD)) { + if (au6610_i2c_msg(d, msg[i].addr, msg[i].buf, + msg[i].len, msg[i+1].buf, + msg[i+1].len) < 0) + break; + i++; + } else if (au6610_i2c_msg(d, msg[i].addr, msg[i].buf, + msg[i].len, NULL, 0) < 0) + break; + } + + mutex_unlock(&d->i2c_mutex); + return i; +} + + +static u32 au6610_i2c_func(struct i2c_adapter *adapter) +{ + return I2C_FUNC_I2C; +} + +static struct i2c_algorithm au6610_i2c_algo = { + .master_xfer = au6610_i2c_xfer, + .functionality = au6610_i2c_func, +}; + +/* Callbacks for DVB USB */ +static int au6610_identify_state(struct usb_device *udev, + struct dvb_usb_device_properties *props, + struct dvb_usb_device_description **desc, + int *cold) +{ + *cold = 0; + return 0; +} + +static struct zl10353_config au6610_zl10353_config = { + .demod_address = 0x1e, + .no_tuner = 1, + .parallel_ts = 1, +}; + +static int au6610_zl10353_frontend_attach(struct dvb_usb_adapter *adap) +{ + if ((adap->fe = dvb_attach(zl10353_attach, &au6610_zl10353_config, + &adap->dev->i2c_adap)) != NULL) { + return 0; + } + + return -EIO; +} + +static struct qt1010_config au6610_qt1010_config = { + .i2c_address = 0xc4 +}; + +static int au6610_qt1010_tuner_attach(struct dvb_usb_adapter *adap) +{ + return dvb_attach(qt1010_attach, + adap->fe, &adap->dev->i2c_adap, + &au6610_qt1010_config) == NULL ? -ENODEV : 0; +} + +/* DVB USB Driver stuff */ +static struct dvb_usb_device_properties au6610_properties; + +static int au6610_probe(struct usb_interface *intf, + const struct usb_device_id *id) +{ + struct dvb_usb_device *d; + struct usb_host_interface *alt; + int ret; + + if (intf->num_altsetting < AU6610_ALTSETTING_COUNT) + return -ENODEV; + + if ((ret = dvb_usb_device_init(intf, &au6610_properties, THIS_MODULE, &d)) == 0) { + alt = usb_altnum_to_altsetting(intf, AU6610_ALTSETTING); + + if (alt == NULL) { + deb_rc("no alt found!\n"); + return -ENODEV; + } + ret = usb_set_interface(d->udev, alt->desc.bInterfaceNumber, + alt->desc.bAlternateSetting); + } + + return ret; +} + + +static struct usb_device_id au6610_table [] = { + { USB_DEVICE(USB_VID_ALCOR_MICRO, USB_PID_SIGMATEK_DVB_110) }, + { } /* Terminating entry */ +}; +MODULE_DEVICE_TABLE (usb, au6610_table); + +static struct dvb_usb_device_properties au6610_properties = { + .caps = DVB_USB_IS_AN_I2C_ADAPTER, + .usb_ctrl = DEVICE_SPECIFIC, + .size_of_priv = 0, + .identify_state = au6610_identify_state, + .num_adapters = 1, + .adapter = { + { + .frontend_attach = au6610_zl10353_frontend_attach, + .tuner_attach = au6610_qt1010_tuner_attach, + + .stream = { + .type = USB_ISOC, + .count = 5, + .endpoint = 0x82, + .u = { + .isoc = { + .framesperurb = 40, + .framesize = 942, /* maximum packet size */ + .interval = 1.25, /* 125 us */ + } + } + }, + } + }, + .i2c_algo = &au6610_i2c_algo, + .num_device_descs = 1, + .devices = { + { + "Sigmatek DVB-110 DVB-T USB2.0", + { &au6610_table[0], NULL }, + { NULL }, + }, + } +}; + +static struct usb_driver au6610_driver = { + .name = "dvb_usb_au6610", + .probe = au6610_probe, + .disconnect = dvb_usb_device_exit, + .id_table = au6610_table, +}; + +/* module stuff */ +static int __init au6610_module_init(void) +{ + int ret; + + if ((ret = usb_register(&au6610_driver))) { + err("usb_register failed. Error number %d", ret); + return ret; + } + + return 0; +} + +static void __exit au6610_module_exit(void) +{ + /* deregister this driver from the USB subsystem */ + usb_deregister(&au6610_driver); +} + +module_init (au6610_module_init); +module_exit (au6610_module_exit); + +MODULE_AUTHOR("Antti Palosaari "); +MODULE_DESCRIPTION("Driver Sigmatek DVB-110 DVB-T USB2.0 / AU6610"); +MODULE_VERSION("0.1"); +MODULE_LICENSE("GPL"); diff --git a/pool/shard002/C/0057687_NGAP_FiveQI.c b/pool/shard002/C/0057687_NGAP_FiveQI.c new file mode 100644 index 0000000000000000000000000000000000000000..3c12f64e10acefd50ab17f70544375b0ae7f25dc --- /dev/null +++ b/pool/shard002/C/0057687_NGAP_FiveQI.c @@ -0,0 +1,64 @@ +/* + * Generated by asn1c-0.9.29 (http://lionet.info/asn1c) + * From ASN.1 module "NGAP-IEs" + * found in "../support/ngap-r16.1.0/38413-g10.asn" + * `asn1c -pdu=all -fcompound-names -findirect-choice -fno-include-deps` + */ + +#include "NGAP_FiveQI.h" + +int +NGAP_FiveQI_constraint(const asn_TYPE_descriptor_t *td, const void *sptr, + asn_app_constraint_failed_f *ctfailcb, void *app_key) { + long value; + + if(!sptr) { + ASN__CTFAIL(app_key, td, sptr, + "%s: value not given (%s:%d)", + td->name, __FILE__, __LINE__); + return -1; + } + + value = *(const long *)sptr; + + if((value >= 0 && value <= 255)) { + /* Constraint check succeeded */ + return 0; + } else { + ASN__CTFAIL(app_key, td, sptr, + "%s: constraint failed (%s:%d)", + td->name, __FILE__, __LINE__); + return -1; + } +} + +/* + * This type is implemented using NativeInteger, + * so here we adjust the DEF accordingly. + */ +static asn_oer_constraints_t asn_OER_type_NGAP_FiveQI_constr_1 CC_NOTUSED = { + { 0, 0 }, + -1}; +asn_per_constraints_t asn_PER_type_NGAP_FiveQI_constr_1 CC_NOTUSED = { + { APC_CONSTRAINED | APC_EXTENSIBLE, 8, 8, 0, 255 } /* (0..255,...) */, + { APC_UNCONSTRAINED, -1, -1, 0, 0 }, + 0, 0 /* No PER value map */ +}; +static const ber_tlv_tag_t asn_DEF_NGAP_FiveQI_tags_1[] = { + (ASN_TAG_CLASS_UNIVERSAL | (2 << 2)) +}; +asn_TYPE_descriptor_t asn_DEF_NGAP_FiveQI = { + "FiveQI", + "FiveQI", + &asn_OP_NativeInteger, + asn_DEF_NGAP_FiveQI_tags_1, + sizeof(asn_DEF_NGAP_FiveQI_tags_1) + /sizeof(asn_DEF_NGAP_FiveQI_tags_1[0]), /* 1 */ + asn_DEF_NGAP_FiveQI_tags_1, /* Same as above */ + sizeof(asn_DEF_NGAP_FiveQI_tags_1) + /sizeof(asn_DEF_NGAP_FiveQI_tags_1[0]), /* 1 */ + { &asn_OER_type_NGAP_FiveQI_constr_1, &asn_PER_type_NGAP_FiveQI_constr_1, NGAP_FiveQI_constraint }, + 0, 0, /* No members */ + 0 /* No specifics */ +}; + diff --git a/pool/shard002/C/0057690_cv_georeference.c b/pool/shard002/C/0057690_cv_georeference.c new file mode 100644 index 0000000000000000000000000000000000000000..b589e10797b26b80bd262e0c523e82b3d78e22cf --- /dev/null +++ b/pool/shard002/C/0057690_cv_georeference.c @@ -0,0 +1,193 @@ +/* + * Copyright (C) C. De Wagter + * + * This file is part of paparazzi + * + * paparazzi is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2, or (at your option) + * any later version. + * + * paparazzi is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with paparazzi; see the file COPYING. If not, see + * . + */ +/** + * @file "modules/computer_vision/cv_georeference.c" + * @author C. De Wagter + * Geo-reference computer vision detections + */ + +#include "modules/computer_vision/cv_georeference.h" + +#include "math/pprz_trig_int.h" +#include "math/pprz_algebra.h" +#include "math/pprz_algebra_int.h" + +#include "state.h" +#include "generated/flight_plan.h" +#include "subsystems/datalink/downlink.h" + +struct georeference_filter_t { + struct Int32Vect3 x; ///< Target + struct Int32Vect3 v; ///< Target Velocity + int32_t P; ///< Covariance/Average-count +}; + +struct georeference_t { + struct Int32Vect3 target_i; ///< Target in pixels, with z being the focal length in pixels, x=up,y=right,out + struct Int32Vect3 target_l; ///< Target in meters, relative to the drone in LTP frame + + struct Int32Vect3 x_t; ///< Target coordinates NED + + struct georeference_filter_t filter; ///< Filter waypoint location +}; + +struct georeference_t geo; + +void georeference_project(struct camera_frame_t *tar, int wp) +{ + // Target direction in camera frame: Zero is looking down in body frames + // Pixel with x (width) value 0 projects to the left (body-Y-axis) + // and y = 0 (height) to the top (body-X-axis) + VECT3_ASSIGN(geo.target_i, + ((tar->h / 2) - tar->py), + (tar->px - (tar->w / 2)), + (tar->f) + ); + INT32_VECT3_LSHIFT(geo.target_i, geo.target_i, 4) + + // Camera <-> Body + // Looking down in body frame + // Bebop has 180deg Z rotation in camera (butt up yields normal webcam) + struct Int32RMat body_to_cam_rmat; + INT32_MAT33_ZERO(body_to_cam_rmat); + MAT33_ELMT(body_to_cam_rmat, 0, 0) = -1 << INT32_TRIG_FRAC; + MAT33_ELMT(body_to_cam_rmat, 1, 1) = -1 << INT32_TRIG_FRAC; + MAT33_ELMT(body_to_cam_rmat, 2, 2) = 1 << INT32_TRIG_FRAC; + + struct Int32Vect3 target_b; + int32_rmat_transp_vmult(&target_b, &body_to_cam_rmat, &geo.target_i); + + // Body <-> LTP + struct Int32RMat *ltp_to_body_rmat = stateGetNedToBodyRMat_i(); + int32_rmat_transp_vmult(&geo.target_l, ltp_to_body_rmat, &target_b); + + // target_l is now a scale-less [pix< no ground projection + return; + } + + // Multiply with height above ground + struct NedCoor_i *pos = stateGetPositionNed_i(); + int32_t zb = pos->z; + geo.target_l.x *= zb; + geo.target_l.y *= zb; + + // Divide by z-component + geo.target_l.x /= zi; + geo.target_l.y /= zi; + geo.target_l.z = zb; + + // NED + geo.x_t.x = pos->x - geo.target_l.x; + geo.x_t.y = pos->y - geo.target_l.y; + geo.x_t.z = 0; + + // ENU + if (wp > 0) { + waypoint_set_xy_i(wp, geo.x_t.y, geo.x_t.x); + waypoint_set_alt_i(wp, geo.x_t.z); + + int32_t h = -geo.x_t.z; + uint8_t wp_id = wp; + DOWNLINK_SEND_WP_MOVED_ENU(DefaultChannel, DefaultDevice, &wp_id, &(geo.x_t.y), + &(geo.x_t.x), &(h)); + + } +} + +void georeference_filter(bool kalman, int wp, int length) +{ + struct Int32Vect3 err; + + if (kalman) + { + // Predict + VECT3_ADD(geo.filter.x, geo.filter.v); + + // Error = prediction - observation + VECT3_COPY(err,geo.filter.x); + VECT3_SUB(err, geo.x_t); + } + else // Average + { + VECT3_SMUL(geo.filter.x,geo.filter.x,geo.filter.P); + VECT3_ADD(geo.filter.x, geo.x_t); + geo.filter.P++; + VECT3_SDIV(geo.filter.x,geo.filter.x,geo.filter.P); + if (geo.filter.P > length) { + geo.filter.P = length; + } + } + + // ENU + waypoint_set_xy_i(wp, geo.filter.x.y, geo.filter.x.x); + //waypoint_set_alt_i(wp, geo.filter.x.z); + + int32_t h = 0; + uint8_t wp_id = wp; + DOWNLINK_SEND_WP_MOVED_ENU(DefaultChannel, DefaultDevice, &wp_id, &(geo.filter.x.y), + &(geo.filter.x.x), &(h)); +} + +int32_t focus_length; + +void georeference_run(void) +{ + struct camera_frame_t target; + target.w = 320; + target.h = 240; + target.f = focus_length; + target.px = 0; + target.py = 0; + georeference_project(&target,WP_p1); + target.px = 320; + target.py = 0; + georeference_project(&target,WP_p2); + target.px = 320; + target.py = 240; + georeference_project(&target,WP_p3); + target.px = 0; + target.py = 240; + georeference_project(&target,WP_p4); + + target.px = 0; + target.py = 120; + georeference_project(&target,0); + georeference_filter(FALSE, WP_CAM,50); +} + +void georeference_init(void) +{ + INT32_VECT3_ZERO(geo.target_i); + INT32_VECT3_ZERO(geo.target_l); + + VECT3_ASSIGN(geo.x_t, 0, 0, 0); + + INT32_VECT3_ZERO(geo.filter.v); + INT32_VECT3_ZERO(geo.filter.x); + geo.filter.P = 0; + focus_length = 400; +} + + diff --git a/pool/shard002/C/0057700_vpath.c b/pool/shard002/C/0057700_vpath.c new file mode 100644 index 0000000000000000000000000000000000000000..49f39e56b0e88177addfe489ba20c00d6c8a61ed --- /dev/null +++ b/pool/shard002/C/0057700_vpath.c @@ -0,0 +1,144 @@ +#include + +#include +#include +#include + +struct vpath_lookup* lookup; + +void match_setup() { + struct vpath_pair** pairs = NULL; + struct vpath_pair pair[] = { + {"/alias/sub", "/subalias"}, + {"/", "/root"}, + {"/alias", "/alias"} + }; + size_t i; + size_t size = sizeof(pair) / sizeof(struct vpath_pair); + + pairs = (struct vpath_pair**)calloc(size, sizeof(struct vpath_pair*)); + for (i = 0; i < size; i++) { + pairs[i] = &pair[i]; + } + + lookup = init_vpath_lookup(pairs, size); + + free(pairs); +} +void match_teardown() { + free_vpath_lookup(lookup); +} + +#define DO_VPATH_RDS_TEST(N, I, E) \ +START_TEST (test_vpath_rds ## N) { \ + char input[] = I; \ + static const char expected[] = E; \ + int newlen = remove_dot_segments(input, input); \ + ck_assert_str_eq(input, expected); \ + ck_assert_int_eq(newlen, strlen(expected)); \ +} \ +END_TEST + +DO_VPATH_RDS_TEST(1, "/a/b/c/./../../g", "/a/g") +DO_VPATH_RDS_TEST(2, "mid/content=5/../6", "mid/6") +DO_VPATH_RDS_TEST(3, "../../../../g", "g") +DO_VPATH_RDS_TEST(4, "/./g", "/g") +DO_VPATH_RDS_TEST(5, "/../g", "/g") +DO_VPATH_RDS_TEST(6, "g.", "g.") +DO_VPATH_RDS_TEST(7, ".g", ".g") +DO_VPATH_RDS_TEST(8, "..g", "..g") +DO_VPATH_RDS_TEST(9, "g..", "g..") +DO_VPATH_RDS_TEST(10, "./../g", "g") +DO_VPATH_RDS_TEST(11, "./g/.", "g/") +DO_VPATH_RDS_TEST(12, "./g/", "g/") +DO_VPATH_RDS_TEST(13, "g/./h", "g/h") +DO_VPATH_RDS_TEST(14, "g/../h", "/h") + +#define DO_VPATH_MATCH_TEST(N, I, E) \ +START_TEST (test_vpath_match ## N) { \ + static const char input[] = I; \ + static const char expected[] = E; \ + struct vpath_match* m = match_vpath(lookup, input); \ + ck_assert(m != NULL); \ + ck_assert_str_eq(m->pair.ppath, expected); \ + ck_assert_int_eq(m->len, strlen(m->pair.vpath)); \ +} \ +END_TEST + +DO_VPATH_MATCH_TEST(1, "/abc", "/root") +DO_VPATH_MATCH_TEST(2, "/", "/root") +DO_VPATH_MATCH_TEST(3, "/alias", "/alias") +DO_VPATH_MATCH_TEST(4, "/alias/", "/alias") +DO_VPATH_MATCH_TEST(5, "/alia", "/root") +// The following is expected behaviour +DO_VPATH_MATCH_TEST(6, "/alias2", "/alias") +DO_VPATH_MATCH_TEST(7, "/alias/abc", "/alias") +DO_VPATH_MATCH_TEST(8, "/alias/sub", "/subalias") +DO_VPATH_MATCH_TEST(9, "/alias/sub/", "/subalias") +DO_VPATH_MATCH_TEST(10, "/alias/su", "/alias") +DO_VPATH_MATCH_TEST(11, "/alias/sub/abc", "/subalias") + +START_TEST (test_vpath_notmatch1) { + struct vpath_match* m = match_vpath(lookup, "abc"); + ck_assert(m == NULL); +} +END_TEST + +Suite* vpath_suite(void) { + Suite *s; + TCase *tc_core; + TCase *tc_match; + + s = suite_create("vpath"); + + tc_core = tcase_create("Core"); + + tcase_add_test(tc_core, test_vpath_rds1); + tcase_add_test(tc_core, test_vpath_rds2); + tcase_add_test(tc_core, test_vpath_rds3); + tcase_add_test(tc_core, test_vpath_rds4); + tcase_add_test(tc_core, test_vpath_rds5); + tcase_add_test(tc_core, test_vpath_rds6); + tcase_add_test(tc_core, test_vpath_rds7); + tcase_add_test(tc_core, test_vpath_rds8); + tcase_add_test(tc_core, test_vpath_rds9); + tcase_add_test(tc_core, test_vpath_rds10); + tcase_add_test(tc_core, test_vpath_rds11); + tcase_add_test(tc_core, test_vpath_rds12); + tcase_add_test(tc_core, test_vpath_rds13); + tcase_add_test(tc_core, test_vpath_rds14); + suite_add_tcase(s, tc_core); + + tc_match = tcase_create("Match"); + + tcase_add_unchecked_fixture(tc_match, match_setup, match_teardown); + tcase_add_test(tc_match, test_vpath_match1); + tcase_add_test(tc_match, test_vpath_match2); + tcase_add_test(tc_match, test_vpath_match3); + tcase_add_test(tc_match, test_vpath_match4); + tcase_add_test(tc_match, test_vpath_match5); + tcase_add_test(tc_match, test_vpath_match6); + tcase_add_test(tc_match, test_vpath_match7); + tcase_add_test(tc_match, test_vpath_match8); + tcase_add_test(tc_match, test_vpath_match9); + tcase_add_test(tc_match, test_vpath_match10); + tcase_add_test(tc_match, test_vpath_match11); + tcase_add_test(tc_match, test_vpath_notmatch1); + suite_add_tcase(s, tc_match); + + return s; +} + +int main(void) { + int number_failed; + Suite *s; + SRunner *sr; + + s = vpath_suite(); + sr = srunner_create(s); + + srunner_run_all(sr, CK_NORMAL); + number_failed = srunner_ntests_failed(sr); + srunner_free(sr); + return (number_failed == 0) ? 0 : 1; +} diff --git a/pool/shard002/C/0057701_getline.c b/pool/shard002/C/0057701_getline.c new file mode 100644 index 0000000000000000000000000000000000000000..617d1b0ebd36132a43cde4866d487490abd74b88 --- /dev/null +++ b/pool/shard002/C/0057701_getline.c @@ -0,0 +1,57 @@ +/* getline() replacement for platforms that do not have it. + * + * Part of the testbench for rsyslog. + * + * Copyright 2009 Rainer Gerhards and Adiscon GmbH. + * + * This file is part of rsyslog. + * + * Rsyslog 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. + * + * Rsyslog 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 Rsyslog. If not, see . + * + * A copy of the GPL can be found in the file "COPYING" in this distribution. + */ +#include "config.h" +#include +#include +#include + +/* we emulate getline (the dirty way) if we do not have it + * We do not try very hard, as this is just a test driver. + * rgerhards, 2009-03-31 + */ +#ifndef HAVE_GETLINE +ssize_t getline(char **lineptr, size_t *n, FILE *fp) +{ + int c; + int len = 0; + + if(*lineptr == NULL) + *lineptr = malloc(4096); /* quick and dirty! */ + + c = fgetc(fp); + while(c != EOF && c != '\n') { + (*lineptr)[len++] = c; + c = fgetc(fp); + } + if(c != EOF) /* need to add NL? */ + (*lineptr)[len++] = c; + + (*lineptr)[len] = '\0'; + + *n = len; + //printf("getline returns: '%s'\n", *lineptr); + + return (len > 0) ? len : -1; +} +#endif /* #ifndef HAVE_GETLINE */ diff --git a/pool/shard002/C/0057710_loadelf.c b/pool/shard002/C/0057710_loadelf.c new file mode 100644 index 0000000000000000000000000000000000000000..cbd8748c9b3e15ee8c4bbc6c41fb81aa6859446e --- /dev/null +++ b/pool/shard002/C/0057710_loadelf.c @@ -0,0 +1,267 @@ +/* $NetBSD: loadelf.c,v 1.1.2.1 2004/05/22 15:59:21 he Exp $ */ + +/* + * + * Copyright (c) 2004 Christian Limpach. + * 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 Christian Limpach. + * 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 +__KERNEL_RCSID(0, "$NetBSD: loadelf.c,v 1.1.2.1 2004/05/22 15:59:21 he Exp $"); + +#if !defined(ELFSIZE) +#define ELFSIZE 32 +#endif + +#include +#include + +#include + +#include + +#include "xenload.h" + +#ifdef DEBUG +#define DPRINTF(x) printf x +#else +#define DPRINTF(x) +#endif + +/* + * NetBSD memory layout: + * + * ---------------- *virt_load_addr = ehdr.e_entry (0xc0100000) + * | kernel text | + * | | + * ---------------- + * | kernel data | + * | | + * ---------------- + * | kernel bss | + * | | + * ---------------- *symtab_addr + * | symtab size | = *symtab_len + * ---------------- + * | elf header | offsets to symbol sections mangled to be relative + * | | to headers location + * ---------------- + * | sym section | + * | headers | + * ---------------- + * | sym sections | + * | | + * ---------------- *symtab_addr + *symtab_len + * | padding | + * ---------------- ehdr.e_entry + *ksize << PAGE_SHIFT + */ + +#define IS_ELF(ehdr) ((ehdr).e_ident[EI_MAG0] == ELFMAG0 && \ + (ehdr).e_ident[EI_MAG1] == ELFMAG1 && \ + (ehdr).e_ident[EI_MAG2] == ELFMAG2 && \ + (ehdr).e_ident[EI_MAG3] == ELFMAG3) +#define IS_TEXT(p) (p.p_flags & PF_X) +#define IS_DATA(p) (p.p_flags & PF_W) +#define IS_BSS(p) (p.p_filesz < p.p_memsz) + +#define ELFROUND (ELFSIZE / 8) + +#define MAX_PHEADERS 5 +#define MAX_SHEADERS 25 + +int +prepareelfimage(vaddr_t elfimage, vaddr_t *virt_load_addr, + vaddr_t *symtab_addr, unsigned long *symtab_len) +{ + Elf_Ehdr ehdr; + Elf_Phdr phdr[MAX_PHEADERS]; + Elf_Shdr shdr[MAX_SHEADERS]; + unsigned long maxva, symva; + vaddr_t offset; + int curpos, h, i, ret; + + ret = -1; + maxva = 0; + + memcpy(&ehdr, (void *)elfimage, sizeof(Elf_Ehdr)); + curpos = sizeof(Elf_Ehdr); + + if (!IS_ELF(ehdr)) { + ERROR("Image does not have an ELF header."); + goto out; + } + + *virt_load_addr = ehdr.e_entry; + + if ((*virt_load_addr & (PAGE_SIZE-1)) != 0) { + ERROR("We can only deal with page-aligned load addresses"); + goto out; + } + + if (ehdr.e_phnum > MAX_PHEADERS) { + ERROR("Too many Program Headers, increase MAX_PHEADERS"); + goto out; + } + + offset = elfimage - *virt_load_addr; + + curpos = ehdr.e_phoff; + memcpy(phdr, (void *)elfimage + ehdr.e_phoff, + ehdr.e_phnum * sizeof(Elf_Phdr)); + curpos += ehdr.e_phnum * sizeof(Elf_Phdr); + + /* Copy run-time 'load' segments that are writeable and/or + executable. */ + for (h = 0; h < ehdr.e_phnum; h++) { + if ((phdr[h].p_type != PT_LOAD) || + ((phdr[h].p_flags & (PF_W|PF_X)) == 0)) + continue; + + if (IS_TEXT(phdr[h]) || IS_DATA(phdr[h])) { + curpos = phdr[h].p_offset; + DPRINTF(("move segment %p/%x to va %p/%p\n", + elfimage + phdr[h].p_offset, + phdr[h].p_filesz, (void *)phdr[h].p_vaddr, + (void *)phdr[h].p_vaddr + offset)); + + memmove((void *)phdr[h].p_vaddr + offset, + (void *)elfimage + phdr[h].p_offset, + phdr[h].p_filesz); + + if (phdr[h].p_vaddr + phdr[h].p_filesz > maxva) + maxva = phdr[h].p_vaddr + phdr[h].p_filesz; + } + + if (IS_BSS(phdr[h])) { + /* XXX maybe clear phdr[h].p_memsz bytes from + phdr[h].p_vaddr + phdr[h].p_filesz ??? */ + if (phdr[h].p_vaddr + phdr[h].p_memsz > maxva) + maxva = phdr[h].p_vaddr + phdr[h].p_memsz; + DPRINTF(("bss from %p to %p, maxva %p\n", + (void *)(phdr[h].p_vaddr + phdr[h].p_filesz), + (void *)(phdr[h].p_vaddr + phdr[h].p_memsz), + (void *)maxva)); + } + } + + if (ehdr.e_shnum > MAX_SHEADERS) { + ERROR("Too many Section Headers, increase MAX_SHEADERS"); + goto out; + } + + curpos = ehdr.e_shoff; + memcpy(shdr, (void *)elfimage + ehdr.e_shoff, + ehdr.e_shnum * sizeof(Elf_Shdr)); + curpos += ehdr.e_shnum * sizeof(Elf_Shdr); + + maxva = (maxva + ELFROUND - 1) & ~(ELFROUND - 1); + symva = maxva; + maxva += sizeof(int); + *symtab_addr = maxva; + *symtab_len = 0; + maxva += sizeof(Elf_Ehdr) + ehdr.e_shnum * sizeof(Elf_Shdr); + maxva = (maxva + ELFROUND - 1) & ~(ELFROUND - 1); + + /* Copy kernel string / symbol tables into physical memory */ + for (h = 0; h < ehdr.e_shnum; h++) { + if (shdr[h].sh_type == SHT_STRTAB) { + /* Look for a strtab @i linked to symtab @h. */ + for (i = 0; i < ehdr.e_shnum; i++) + if ((shdr[i].sh_type == SHT_SYMTAB) && + (shdr[i].sh_link == h)) + break; + /* Skip symtab @h if we found no corresponding + strtab @i. */ + if (i == ehdr.e_shnum) { + shdr[h].sh_offset = 0; + continue; + } + } + + if ((shdr[h].sh_type == SHT_STRTAB) || + (shdr[h].sh_type == SHT_SYMTAB)) { + curpos = shdr[h].sh_offset; + + DPRINTF(("copy section %d, addr %p size 0x%x from " + "%p\n", h, (void *)maxva + offset, shdr[h].sh_size, + (void *)elfimage + shdr[h].sh_offset)); + memmove((void *)maxva + offset, (void *)elfimage + + shdr[h].sh_offset, shdr[h].sh_size); + + /* Mangled to be based on ELF header location. */ + shdr[h].sh_offset = maxva - *symtab_addr; + + maxva += shdr[h].sh_size; + *symtab_len += shdr[h].sh_size; + maxva = (maxva + ELFROUND - 1) & ~(ELFROUND - 1); + + } + shdr[h].sh_name = 0; /* Name is NULL. */ + } + + if (*symtab_len == 0) { + DPRINTF(("no symbol table\n")); + ret = 0; + goto out; + } + + DPRINTF(("sym header va %p from %p size %x, addrs %p/%p\n", + (void *)symva, shdr, ehdr.e_shnum * sizeof(Elf_Shdr), + (void *)symva + sizeof(int), + (void *)symva + sizeof(int) + sizeof(Elf_Ehdr))); + ehdr.e_phoff = 0; + ehdr.e_shoff = sizeof(Elf_Ehdr); + ehdr.e_phentsize = 0; + ehdr.e_phnum = 0; + ehdr.e_shstrndx = SHN_UNDEF; + + symva += offset; + + /* Copy total length, crafted ELF header and section + header table */ + *(int *)symva = maxva - *symtab_addr; + memmove((void *)symva + sizeof(int), &ehdr, sizeof(Elf_Ehdr)); + memmove((void *)symva + sizeof(int) + sizeof(Elf_Ehdr), shdr, + ehdr.e_shnum * sizeof(Elf_Shdr)); + + *symtab_len = maxva - *symtab_addr; + + ret = 0; + + out: + if (ret == 0) { + maxva = (maxva + PAGE_SIZE - 1) & ~(PAGE_SIZE - 1); + + DPRINTF(("virt_addr %p, symtab_addr %p, symtab_len %p, " + "maxva %p\n", (void *)*virt_load_addr, + (void *)*symtab_addr, (void *)*symtab_len, (void *)maxva)); + } + + return ret; +} diff --git a/pool/shard002/C/0057713_mux-expander.c b/pool/shard002/C/0057713_mux-expander.c new file mode 100644 index 0000000000000000000000000000000000000000..2c71ae5f9049e2fd9d0739518eb631cd195d8fe6 --- /dev/null +++ b/pool/shard002/C/0057713_mux-expander.c @@ -0,0 +1,116 @@ +/* +* libmux - GTK+ Moblin User Experience widgets + * Copyright (C) 2009 Intel Corporation. + * + * This program is free software; you can redistribute it and/or modify it + * under the terms and conditions of the GNU Lesser General Public License, + * version 2.1, as published by the Free Software Foundation. + * + * This program is distributed in the hope it will be useful, but WITHOUT ANY + * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS + * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for + * more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA. + */ + +#include "mux-expander.h" + +#define DEFAULT_SIZE 20 + +struct _MuxExpanderPrivate { + int size; + GtkExpanderStyle state; +}; + +#define GET_PRIVATE(obj) (G_TYPE_INSTANCE_GET_PRIVATE ((obj), MUX_TYPE_EXPANDER, MuxExpanderPrivate)) +G_DEFINE_TYPE (MuxExpander, mux_expander, GTK_TYPE_WIDGET); + +static void +mux_expander_style_set (GtkWidget *widget, GtkStyle *previous_style) +{ + MuxExpander *expander = MUX_EXPANDER (widget); + + GTK_WIDGET_CLASS (mux_expander_parent_class)->style_set (widget, previous_style); + + gtk_widget_style_get (widget, + "expander-size", &expander->priv->size, + NULL); + + gtk_widget_queue_resize (widget); +} + +static void +mux_expander_size_request (GtkWidget *widget, GtkRequisition *requisition) +{ + MuxExpander *expander = MUX_EXPANDER (widget); + + requisition->width = requisition->height = expander->priv->size; +} + +static gboolean +mux_expander_expose_event (GtkWidget *widget, GdkEventExpose *event) +{ + MuxExpander *expander = MUX_EXPANDER (widget); + + gtk_paint_expander (widget->style, widget->window, + GTK_WIDGET_STATE (widget), + &event->area, + widget, + NULL, + widget->allocation.x + widget->allocation.width / 2, + widget->allocation.y + widget->allocation.height / 2, + expander->priv->state); + + return FALSE; +} + +static void +mux_expander_class_init (MuxExpanderClass *klass) +{ + GtkWidgetClass *w_class = (GtkWidgetClass *)klass; + + w_class->size_request = mux_expander_size_request; + w_class->style_set = mux_expander_style_set; + w_class->expose_event = mux_expander_expose_event; + + g_type_class_add_private (klass, sizeof (MuxExpanderPrivate)); + + gtk_widget_class_install_style_property (w_class, g_param_spec_int + ("expander-size", "Expander Size", "Size of the expander arrow", + 0, G_MAXINT, DEFAULT_SIZE, + G_PARAM_READABLE | G_PARAM_STATIC_STRINGS)); +} + +static void +mux_expander_init (MuxExpander *expander) +{ + expander->priv = GET_PRIVATE (expander); + + GTK_WIDGET_SET_FLAGS (expander, GTK_NO_WINDOW); + + expander->priv->size = DEFAULT_SIZE; + expander->priv->state = GTK_EXPANDER_COLLAPSED; +} + +GtkWidget * +mux_expander_new (void) +{ + return g_object_new (MUX_TYPE_EXPANDER, NULL); +} + +void +mux_expander_set_state (MuxExpander *expander, GtkExpanderStyle state) +{ + expander->priv->state = state; + + gtk_widget_queue_draw (GTK_WIDGET (expander)); +} + +GtkExpanderStyle +mux_expander_get_state (MuxExpander *expander) +{ + return expander->priv->state; +} diff --git a/pool/shard002/C/0057717_assign_2.c b/pool/shard002/C/0057717_assign_2.c new file mode 100644 index 0000000000000000000000000000000000000000..5afd9886915fd7352bedae1f6ab686a629b33c5f --- /dev/null +++ b/pool/shard002/C/0057717_assign_2.c @@ -0,0 +1,133 @@ +/* + * Avinash N + * 24 - 01 - 2017 +*/ + +/* + * Write a program to create a child process using vfork() system call and + * experiment the following + * a. Will both parent and child share the same local data ? + * b. Will both parent and child share the same global data ? + * c. Will both parent and child share the same heap data ? + * d. Verify from the kernel space, whether both parent and child + * will work in the separate/different instance of + * the virtual address space or not ? + * e. Open a text file “just.txt” in the parent before issuing fork(). + * * After issuing fork(), in the parent context, write the string + * “Global Edge” on to the file and close the file. + * * In the child context write “Software limited” on to the file + * and close the file. + * * Cat the file just.txt and draw your inferences + * by looking at the output. + * f. Verify from the kernel space, whether both parent and child + * will share the same session descriptor or will they have + * separate session descriptors ? +*/ + +#include +#include +#include +#include +#include + +// Memory allocation +#define MEM_ALLOC(ptr) ptr = (char *) malloc (sizeof(char)) + +// Malloc validation +#define VALIDATE(ptr) if (!ptr) {\ + printf("Malloc failed...!\n");\ + exit(1);\ + } + +// Printing details of process +#define print_statements() \ + printf("PID --> %d\tPPID --> %d\n", getpid(), getppid()); \ + printf("Value of local variable = %d\n", l_num); \ + printf("Address of local variable = %p\n", &l_num); \ + printf("Value of global variable = %d\n", g_num); \ + printf("Address of global variable = %p\n", &g_num); \ + printf("Value of pointer variable = %s\n", ptr); \ + printf("Address of pointer variable = %p\n", ptr); + +int g_num = 25; // Global variable + +int main (void) { + int l_num = 10; // Local variable + char *ptr = NULL; // Pointer to access heap data + pid_t pid; + FILE *fp; + + fp = fopen("just.txt", "w+"); + + printf("-------------------------------------\n"); + printf("Value of local variable = %d\n", l_num); + printf("Value of global variable = %d\n", g_num); + + pid = vfork(); // vfork() is invoked + +// wait(NULL); // To make the parent process wait for child + + if (pid > 0) { + MEM_ALLOC(ptr); // Memory allocation for pointer + VALIDATE(ptr); // Malloc validation + // Enter any character as input to ptr + *ptr = getchar(); + +// l_num = 100; +// g_num = 200; + fprintf(fp, "%s", "Global Edge\n"); + + printf("----In parent process----\n"); + print_statements() + printf("Exiting parent process\n"); + // getchar(); + fclose(fp); + } else if (pid == 0) { + MEM_ALLOC(ptr); // Memory allocation for pointer + VALIDATE(ptr); // Malloc validation + // Enter any character as input to ptr + *ptr = getchar(); + + l_num = 50; + g_num = 120; + fprintf(fp, "%s", "Software Limited\n"); + + printf("----In child process----\n"); + print_statements() + printf("Exiting child process\n"); +// getchar(); + fclose(fp); + exit(0); + } else { + printf("fork() failed..!\n"); + } + + printf("..Value of local variable = %d\n", l_num); + printf("..Value of global variable = %d\n", g_num); + + return 0; +} + +/* + * Answer for a, b and c : + * + * Both parent and child share the same data(local, global and heap) + * with same virtual adrress space (same instance) + * mapped to seperate physical address spaces which when modified + * in one process' context will affect the data in + * the other process' context. + * + * Answer for d : + * + * Use "$ cat /proc/PID/maps" for both child and parent + * -OR- + * Use kernel module to traverse the linked list of vm_area_struct + * + * Answer for e : + * + * ------- + * + * Answer for f : + * + * ------- +*/ diff --git a/pool/shard002/C/0057732_ide-editor-tweak-widget.c b/pool/shard002/C/0057732_ide-editor-tweak-widget.c new file mode 100644 index 0000000000000000000000000000000000000000..2dc2ef3a56634f293c1dc4dea96e6f7562558bf8 --- /dev/null +++ b/pool/shard002/C/0057732_ide-editor-tweak-widget.c @@ -0,0 +1,185 @@ +/* ide-editor-tweak-widget.c + * + * Copyright (C) 2014 Christian Hergert + * + * 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 . + */ + +#define G_LOG_DOMAIN "editor-tweak" + +#include +#include + +#include "editor/ide-editor-tweak-widget.h" +#include "util/ide-gtk.h" + +struct _IdeEditorTweakWidget +{ + GtkBin parent_instance; + + GtkSearchEntry *entry; + GtkListBox *list_box; +}; + +G_DEFINE_TYPE (IdeEditorTweakWidget, ide_editor_tweak_widget, GTK_TYPE_BIN) + +static GQuark langQuark; + +GtkWidget * +ide_editor_tweak_widget_new (void) +{ + return g_object_new (IDE_TYPE_EDITOR_TWEAK_WIDGET, NULL); +} + +static gboolean +ide_editor_tweak_widget_filter_func (GtkListBoxRow *row, + gpointer user_data) +{ + GtkSourceLanguage *language; + GtkWidget *child; + const gchar *needle = user_data; + const gchar *lang_id; + const gchar *lang_name; + g_autofree gchar *lang_name_cf = NULL; + + g_return_val_if_fail (GTK_IS_LIST_BOX_ROW (row), FALSE); + g_return_val_if_fail (needle, FALSE); + + child = gtk_bin_get_child (GTK_BIN (row)); + language = g_object_get_qdata (G_OBJECT (child), langQuark); + lang_id = gtk_source_language_get_id (language); + lang_name = gtk_source_language_get_name (language); + lang_name_cf = g_utf8_casefold (lang_name, -1); + + if (strstr (lang_id, needle) || strstr (lang_name, needle) || strstr (lang_name_cf, needle)) + return TRUE; + + return FALSE; +} + +static void +ide_editor_tweak_widget_entry_changed (IdeEditorTweakWidget *self, + GtkEntry *entry) +{ + const gchar *text; + gchar *text_cf; + + g_return_if_fail (IDE_IS_EDITOR_TWEAK_WIDGET (self)); + g_return_if_fail (GTK_IS_ENTRY (entry)); + + text = gtk_entry_get_text (entry); + + if (ide_str_empty0 (text)) + gtk_list_box_set_filter_func (self->list_box, NULL, NULL, NULL); + else + { + text_cf = g_utf8_casefold (text, -1); + gtk_list_box_set_filter_func (self->list_box, ide_editor_tweak_widget_filter_func, + text_cf, g_free); + } +} + +static void +ide_editor_tweak_widget_row_activated (IdeEditorTweakWidget *self, + GtkListBoxRow *row, + GtkListBox *list_box) +{ + GtkSourceLanguage *lang; + const gchar *lang_id; + GtkWidget *child; + GVariant *param; + + g_return_if_fail (IDE_IS_EDITOR_TWEAK_WIDGET (self)); + g_return_if_fail (GTK_IS_LIST_BOX_ROW (row)); + g_return_if_fail (GTK_IS_LIST_BOX (list_box)); + + child = gtk_bin_get_child (GTK_BIN (row)); + lang = g_object_get_qdata (G_OBJECT (child), langQuark); + + if (lang) + { + lang_id = gtk_source_language_get_id (lang); + param = g_variant_new_string (lang_id); + ide_widget_action (GTK_WIDGET (self), "view", "language", param); + } +} + +static void +ide_editor_tweak_widget_constructed (GObject *object) +{ + IdeEditorTweakWidget *self = (IdeEditorTweakWidget *)object; + GtkSourceLanguageManager *manager; + GtkSourceLanguage *lang; + const gchar * const *lang_ids; + guint i; + + g_return_if_fail (IDE_IS_EDITOR_TWEAK_WIDGET (self)); + + G_OBJECT_CLASS (ide_editor_tweak_widget_parent_class)->constructed (object); + + manager = gtk_source_language_manager_get_default (); + lang_ids = gtk_source_language_manager_get_language_ids (manager); + + for (i = 0; lang_ids [i]; i++) + { + GtkWidget *row; + + lang = gtk_source_language_manager_get_language (manager, lang_ids [i]); + row = g_object_new (GTK_TYPE_LABEL, + "label", gtk_source_language_get_name (lang), + "visible", TRUE, + "xalign", 0.0f, + "margin-end", 6, + "margin-start", 6, + "margin-top", 3, + "margin-bottom", 3, + NULL); + g_object_set_qdata (G_OBJECT (row), langQuark, lang); + gtk_list_box_insert (self->list_box, row, -1); + } + + g_signal_connect_object (self->entry, + "changed", + G_CALLBACK (ide_editor_tweak_widget_entry_changed), + self, + G_CONNECT_SWAPPED); + + g_signal_connect_object (self->list_box, + "row-activated", + G_CALLBACK (ide_editor_tweak_widget_row_activated), + self, + G_CONNECT_SWAPPED); +} + +static void +ide_editor_tweak_widget_class_init (IdeEditorTweakWidgetClass *klass) +{ + GObjectClass *object_class = G_OBJECT_CLASS (klass); + GtkWidgetClass *widget_class = GTK_WIDGET_CLASS (klass); + + object_class->constructed = ide_editor_tweak_widget_constructed; + + gtk_widget_class_set_css_name (widget_class, "editortweak"); + gtk_widget_class_set_template_from_resource (widget_class, "/org/gnome/builder/ui/ide-editor-tweak-widget.ui"); + gtk_widget_class_bind_template_child (widget_class, IdeEditorTweakWidget, entry); + gtk_widget_class_bind_template_child (widget_class, IdeEditorTweakWidget, list_box); + + langQuark = g_quark_from_static_string ("GtkSourceLanguage"); +} + +static void +ide_editor_tweak_widget_init (IdeEditorTweakWidget *self) +{ + gtk_widget_init_template (GTK_WIDGET (self)); +} diff --git a/pool/shard002/C/0057750_compat.c b/pool/shard002/C/0057750_compat.c new file mode 100644 index 0000000000000000000000000000000000000000..e3cd1ce886501f84b0d12aa9f61f6d58524470e9 --- /dev/null +++ b/pool/shard002/C/0057750_compat.c @@ -0,0 +1,70 @@ +/* vim: set shiftwidth=3 softtabstop=3 expandtab: */ + +/* + * Copyright (C) 2002 Andy Smith + * + * 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 "setup.h" + +#include + +#ifdef STDC_HEADERS +# include +#endif + +#ifndef HAVE_INET_ATON +# include +#endif + +#include "compat.h" +#include "opm.h" + +RCSID("$Id$"); + +#ifndef HAVE_INET_ATON +/* + * An implementation of inet_aton for those systems that don't have it + * (Solaris, ...) + */ +int libopm_inet_aton(const char *cp, struct in_addr *inp) +{ + unsigned int a1, a2, a3, a4; + unsigned long ret; + + if (strcmp(cp, "255.255.255.255") == 0) { + inp->s_addr = (unsigned) -1; + return 0; + } + + if (sscanf(cp, "%u.%u.%u.%u", &a1, &a2, &a3, &a4) != 4 || + a1 > 255 || a2 > 255 || a3 > 255 || a4 > 255) { + return 0; + } + + ret = (a1 << 24) | (a2 << 16) | (a3 << 8) | a4; + + inp->s_addr = htonl(ret); + + if (inp->s_addr == (unsigned) -1) { + return 0; + } + return 1; +} +#endif diff --git a/pool/shard002/C/0057758_communication.c b/pool/shard002/C/0057758_communication.c new file mode 100644 index 0000000000000000000000000000000000000000..fb0fa25f47cf168925840617555f599652bf6db4 --- /dev/null +++ b/pool/shard002/C/0057758_communication.c @@ -0,0 +1,347 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "api.h" +#include "communication.h" + +//size_t advanced_write(int fd,void *buf,size_t count); +//size_t advanced_read(int fd,void *buf,size_t count,msg_t msg_type); +static void fill_msg_type(msg_t type, char *type_c); +static int get_a_tag(); +//void fd_set_nonblocking(int fd); + +/** + * 用于填充完整的的消息类型 + */ +static void fill_msg_type(msg_t type, char *type_c) +{ + switch(type) + { + case SUB_CLUSTER_HEART_BEAT: + strcpy(type_c, "TYPE:SUB_CLUSTER_HEART_BEAT;"); + break; + case JOB_SUBMIT: + strcpy(type_c, "TYPE:JOB_SUBMIT;"); + break; + case SCHEDULE_UNIT_ASSIGN: + strcpy(type_c, "TYPE:SCHEDULE_UNIT_ASSIGN;"); + break; + case SCHEDULE_UNIT_FINISH: + strcpy(type_c, "TYPE:SCHEDULE_UNIT_FINISH;"); + break; + case SUB_SCHEDULER_ASSIGN: + strcpy(type_c, "TYPE:SUB_SCHEDULER_ASSIGN;"); + break; + case COMPUTATION_NODE_ASSIGN: + strcpy(type_c, "TYPE:COMPUTATION_NODE_ASSIGN;"); + break; + case SUB_TASK_ASSIGN: + strcpy(type_c, "TYPE:SUB_TASK_ASSIGN;"); + break; + case MACHINE_HEART_BEAT: + strcpy(type_c, "TYPE:MACHINE_HEART_BEAT;"); + break; + case SUB_TASK_FINISH: + strcpy(type_c, "TYPE:SUB_TASK_FINISH;"); + break; + case REGISTRATION_M: + strcpy(type_c, "TYPE:REGISTRATION_M;"); + break; + case REGISTRATION_S: + strcpy(type_c, "TYPE:REGISTRATION_S;"); + break; + case CHILD_CREATE: + strcpy(type_c, "TYPE:CHILD_CREATE;"); + break; + case CHILD_WAIT_ALL: + strcpy(type_c, "TYPE:CHILD_WAIT_ALL;"); + break; + case CHILD_WAKE_UP_ALL: + strcpy(type_c, "TYPE:CHILD_WAKE_UP_ALL;"); + break; + case GET_SUB_TASK_IP: + strcpy(type_c, "TYPE:GET_SUB_TASK_IP;"); + break; + case SUB_CLUSTER_DESTROY: + strcpy(type_c, "TYPE:SUB_CLUSTER_DESTROY;"); + break; + case BACK_TO_MAIN_MASTER: + strcpy(type_c, "TYPE:BACK_TO_MAIN_MASTER;"); + break; + case SUB_CLUSTER_SHUT_DOWN: + strcpy(type_c, "TYPE:SUB_CLUSTER_SHUT_DOWN;"); + break; + default: + printf("fill_msg_type:unknown msg type!\n"); + log_error("fill_msg_type:unknown msg type!\n"); + exit(1); + } +} +static int t_tag; +static int get_a_tag() +{ + //pthread_mutex_lock(&t_tag_m_lock); + t_tag = (t_tag + 1) % 49999; + //pthread_mutex_unlock(&t_tag_m_lock); + return t_tag + 100; +} + +/** + * 进程通信函数,用于给指定的目的地传输消息并接受该消息源回传的信号 + * @comm_source: 指定的消息源 + * @init_tag: 约定的标识符,根据信号类型不同而不同 + * @msg_type: 指定的消息传递类型 + * @send_msg: 需要传送的消息,在第二步传输时发送 + * @recv_msg: 用于存储接收到的消息 + */ +void send_recv_msg(int comm_source, int init_tag, msg_t msg_type, char *send_msg, char **recv_msg) +{ + char pre_msg[20] = {0}; + //why 50 not 33 ? + char final_msg[strlen(send_msg) + 50]; + memset(final_msg, 0, strlen(send_msg) + 50); + char *ret_msg; + char msg_type_c[32] = {0}; + char parameter[6]; + time_t start, finish; + int ack_tag; + int length; + int pid; + + MPI_Status status; + + ret_msg = (char *)malloc(32); + if(ret_msg == NULL) + { + printf("ret_msg alloc faild\n"); + log_error("ret_msg alloc faild\n"); + exit(1); + } + + fill_msg_type(msg_type, msg_type_c); + + int comm_tag = get_a_tag(); + itoa(parameter, comm_tag); + strcpy(pre_msg, parameter); + //pre_msg send_tag;length;ans_tag; + strcat(pre_msg, ";"); + + length = strlen(send_msg) + strlen(msg_type_c) + 1; + itoa(parameter, length); + strcat(pre_msg, parameter); + strcat(pre_msg, ";"); + + ack_tag = get_a_tag(); + itoa(parameter, ack_tag); + strcat(pre_msg, parameter); + //每次发送之前都要预先通知发送的类型以及发送数据的长度 + + MPI_Send(pre_msg, strlen(pre_msg) + 1, MPI_CHAR, comm_source, init_tag, MPI_COMM_WORLD); + strcpy(final_msg, msg_type_c); + strcat(final_msg, send_msg); + + start = time(NULL); + //printf("MSG ===== %s\n", send_msg); + MPI_Sendrecv(final_msg, strlen(final_msg) + 1, MPI_CHAR, comm_source, comm_tag, ret_msg, 32, MPI_CHAR, comm_source, ack_tag, MPI_COMM_WORLD, &status); + + finish = time(NULL); + log_API(final_msg, msg_type, start, finish); + + *recv_msg = strdup(ret_msg); + free(ret_msg); +} + +/* +void advanced_send(int socket_fd,char *msg) +{ + int msg_len; + + msg_len = strlen(msg)+1; + + advanced_write(socket_fd,&msg_len,sizeof(msg_len)); + advanced_write(socket_fd,msg,msg_len); +} + +void advanced_recv(int socket_fd,char **msg,msg_t msg_type) +{ + int msg_len; + + advanced_read(socket_fd,&msg_len,sizeof(msg_len),msg_type); + + *msg = (char *)malloc(msg_len*sizeof(char)); + + advanced_read(socket_fd,*msg,msg_len,msg_type); +} +*/ + +void send_ack_msg(int comm_source, int ack_tag, char *ret) +{ + char ack[32] = {0}; + int ret_v; + int len; + char *parameter; + int flag; + //MPI_Request request; + //MPI_Status status; +/* + ack = (char *)malloc(32*sizeof(char)); + + if(strlen(ret)>27) + { + printf("ret msg too long!\n"); + exit(1); + } +*/ + strcpy(ack, "ACK:"); + strcat(ack, ret); + + ret_v = MPI_Send(ack, 5, MPI_CHAR, comm_source, ack_tag, MPI_COMM_WORLD); + +/* + ret_v = MPI_Isend(ack,strlen(ack)+1,MPI_CHAR,comm_source,ack_tag,MPI_COMM_WORLD,&request); + while(1) + { + MPI_Test(&request,&flag,&status); + if(flag==1) + { + break; + } + else + { + usleep(100); + } + } + MPI_Wait(&request,&status); +*/ +} + +/* +size_t send_ret_msg(int fd,char *ret) +{ + char ack[32]; + int len; + + if(strlen(ret)>27) + { + printf("ret msg too long!\n"); + exit(1); + } + + strcpy(ack,"ACK:"); + strcat(ack,ret); + + advanced_send(fd,ack); + + close(fd); +} + +size_t advanced_write(int fd,void *buf,size_t count) +{ + size_t rc; + + rc = write(fd,buf,count); + + if(rc==-1) + { + printf("fd = %d\n",fd); + perror("advanced write error"); + while(1); + exit(1); + } + + if(rc!=count) + { + printf("advanced write error! Write function did not send all data in one msg!:rc = %d,count = %d\n",rc,count); + exit(1); + } + + return rc; +} + +size_t advanced_read(int fd,void *buf,size_t count,msg_t msg_type) +{ + struct pollfd pfd; + size_t rc; + int ret; + int time_out_count; + int total_rc; + char type_c[32]; + + + pfd.fd = fd; + pfd.events = POLLIN; + + ret = poll(&pfd,1,4000); + + if(ret==0) + { + fill_msg_type(msg_type,type_c); + printf("d = %d",msg_type); + printf("recv msg timeout!!!# %s!\n",type_c); + exit(1); + } + else if(ret==-1) + { + perror("advanced read error 1"); + exit(1); + } + + rc = read(fd,buf,count); + + if(rc==-1) + { + perror("advanced read error 2"); + exit(1); + } + + if(rc!=count) + { + printf("fd = %d\n",fd); + printf("advanced read error! Read function did not recv all data in one msg!:rc = %d,count = %d\n",rc,count); + exit(1); + } + + return rc; +} + +int open_connection(char *ip,int port) +{ + struct sockaddr_in serv_addr; + int socket_fd; + int ret; + + socket_fd = socket(AF_INET,SOCK_STREAM,0); + + if(socket_fd==-1) + { + perror("open connection error,create socket fail"); + exit(1); + } + + bzero(&serv_addr,sizeof(serv_addr)); + + serv_addr.sin_family = AF_INET; + serv_addr.sin_addr.s_addr = inet_addr(ip); + serv_addr.sin_port = htons(port); + + ret = connect(socket_fd,(struct sockaddr *)&serv_addr,sizeof(serv_addr)); + + if(ret==-1) + { + printf("%s:%d fd = %d\n",ip,port,socket_fd); + perror("open connection error"); + exit(1); + } + + return socket_fd; +} +*/ diff --git a/pool/shard002/C/0057769_proc.c b/pool/shard002/C/0057769_proc.c new file mode 100644 index 0000000000000000000000000000000000000000..68bcf347303d39de58826b13c4700f538834d46d --- /dev/null +++ b/pool/shard002/C/0057769_proc.c @@ -0,0 +1,47 @@ +#include +#include +#include "../agup/agup.h" +#include "proc.h" + +#ifdef USEMEMWATCH +#include "../memwatch.h" +#endif + +int eof_verified_edit_proc(int msg, DIALOG *d, int c) +{ + int i; + char * string = NULL; + int key_list[32] = {KEY_BACKSPACE, KEY_DEL, KEY_LEFT, KEY_RIGHT, KEY_UP, KEY_DOWN, KEY_ESC, KEY_ENTER}; + int match = 0; + + if(msg == MSG_CHAR) + { + for(i = 0; i < 8; i++) + { + if(c >> 8 == key_list[i]) //If the input is permanently allowed + { + return d_agup_edit_proc(msg, d, c); //Immediately allow the input character to be returned + } + } + + /* see if key is an allowed key */ + string = (char *)(d->dp2); + if(string == NULL) //If the accepted characters list is NULL for some reason + match = 1; //Implicitly accept the input character instead of allowing a crash + else + { + for(i = 0; string[i] != '\0'; i++) //Search all characters of the accepted characters list + { + if(string[i] == (c & 0xff)) + { + match = 1; + break; + } + } + } + + if(!match) //If there was no match + return D_USED_CHAR; //Drop the character + } + return d_agup_edit_proc(msg, d, c); //Allow the input character to be returned +} diff --git a/pool/shard002/C/0057795_subst.c b/pool/shard002/C/0057795_subst.c new file mode 100644 index 0000000000000000000000000000000000000000..b2ecb875c63080179a077782d828717a92c791a2 --- /dev/null +++ b/pool/shard002/C/0057795_subst.c @@ -0,0 +1,143 @@ + +#include + +#include +#include +#include + +#include "defs.h" +#include "subst.h" +#include "sc_utils.h" + +#define SUBST_GROUP "Substitutions" + +#define do_file_error(gerror, msg) (\ + debug_print("%s\n", msg),\ + g_set_error_literal(gerror, G_FILE_ERROR, 0, msg)) + +void subst_print_substs(struct Substs substs) { + for (int i = 0; i < substs.count; ++i) { + g_printf("%s / %s]\n", substs.data[i].replace, substs.data[i].with); + } +} + +size_t put_subst(Substitution *subst, gchar *replace, gchar *with) { + gchar u8ch[7]; + gint u8ch_len; + gunichar uch; + + if (sscanf(with, "U+%06X", &uch)) { + u8ch_len = g_unichar_to_utf8(uch, u8ch); + u8ch[u8ch_len] = '\0'; + g_assert_cmpuint(u8ch_len, <, strlen(with)); + strcpy(with, u8ch); + } + + subst->replace = replace; + subst->with = with; + + return strlen(with); +} + +/* pack the substitution strings into a contiguous buffer for easy caching */ +gchar *pack_with_data(struct Substs *substs, gsize bufstep) { + gsize bufsize = substs->count * bufstep; + debug_print("bufsize = %lu, bufstep = %lu, count = %d\n", bufsize, bufstep, substs->count); + gchar *buffer = g_new(gchar, bufsize); + gchar *current = buffer; + + for (int i = 0; i < substs->count; ++i, current += bufstep) { + g_assert(current < buffer + bufsize); + g_assert_cmpuint(strlen(substs->data[i].with), <, bufstep); + strncpy(current, substs->data[i].with, bufstep); + g_free(substs->data[i].with); + substs->data[i].with = current; + } + + debug_print("with_buffer = %p\n", buffer); + substs->with_buffer_size = bufsize; + substs->with_buffer = buffer; + + return buffer; +} + +gboolean subst_with_data_packed(struct Substs *substs) { + if ((substs->with_buffer == NULL) || (substs->with_buffer_size == 0)) + return FALSE; + + gchar *first = substs->data[0].with; + gchar *last = substs->data[substs->count - 1].with; + gchar *buffer_end = substs->with_buffer + substs->with_buffer_size; + debug_print("first = %p, last = %p, with_buffer = %p, end = %p\n", first, last, substs->with_buffer, buffer_end); + if (first == substs->with_buffer && last < buffer_end) + return TRUE; + + return FALSE; +} + +gboolean subst_load_from_file( + const gchar *fname, + struct Substs *substs, + GError **out_error) { + + gchar *path = rc_filepath(fname); + gsize count; + GError *error = NULL; + gchar *errormsg = NULL; + + GKeyFile *file = g_key_file_new(); + gchar **keys; + + debug_print("Loading substitutions from %s.\n", path); + if (!g_key_file_load_from_file( + file, path, G_KEY_FILE_KEEP_COMMENTS, &error)) { + debug_print("Error loading from %s: %s\n", path, error->message); + g_propagate_error(out_error, error); + g_free(path); + return FALSE; + } + + if (!g_key_file_has_group(file, SUBST_GROUP)) { + errormsg = + g_strdup_printf(_("Substitution group \"%s\" missing."), SUBST_GROUP); + do_file_error(out_error, errormsg); + g_free(path); + g_key_file_free(file); + return FALSE; + } + + if ((keys = g_key_file_get_keys(file, SUBST_GROUP, &count, &error)) == NULL) { + errormsg = g_strdup(_("Error fetching keys.")); + do_file_error(out_error, errormsg); + g_free(path); + g_key_file_free(file); + return FALSE; + } + + debug_print("count = %d", count); + substs->count = count; + substs->data = g_new(Substitution, count); + substs->with_buffer = NULL; + substs->with_buffer_size = 0; + + gsize longest = 0; + + for (int i = 0; i < count; ++i) { + gchar *val; + + if ((val = g_key_file_get_value(file, SUBST_GROUP, keys[i], NULL /*&error*/)) + == NULL) { + continue; + } + + longest = MAX(longest, put_subst(&substs->data[i], keys[i], val)); + } + + pack_with_data(substs, longest + 1); + + g_free(path); + g_key_file_free(file); + + return TRUE; +} + diff --git a/pool/shard002/C/0057804_chipreg.c b/pool/shard002/C/0057804_chipreg.c new file mode 100644 index 0000000000000000000000000000000000000000..c2127840a183007b57976d9a611ab96789656c36 --- /dev/null +++ b/pool/shard002/C/0057804_chipreg.c @@ -0,0 +1,111 @@ +/* + * $Id: chipreg.c,v 1.17 2004/11/16 18:29:00 dwmw2 Exp $ + * + * Registration for chip drivers + * + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +static DEFINE_SPINLOCK(chip_drvs_lock); +static LIST_HEAD(chip_drvs_list); + +void register_mtd_chip_driver(struct mtd_chip_driver *drv) +{ + spin_lock(&chip_drvs_lock); + list_add(&drv->list, &chip_drvs_list); + spin_unlock(&chip_drvs_lock); +} + +void unregister_mtd_chip_driver(struct mtd_chip_driver *drv) +{ + spin_lock(&chip_drvs_lock); + list_del(&drv->list); + spin_unlock(&chip_drvs_lock); +} + +static struct mtd_chip_driver *get_mtd_chip_driver (const char *name) +{ + struct list_head *pos; + struct mtd_chip_driver *ret = NULL, *this; + + spin_lock(&chip_drvs_lock); + + list_for_each(pos, &chip_drvs_list) { + this = list_entry(pos, typeof(*this), list); + + if (!strcmp(this->name, name)) { + ret = this; + break; + } + } + if (ret && !try_module_get(ret->module)) + ret = NULL; + + spin_unlock(&chip_drvs_lock); + + return ret; +} + + /* Hide all the horrid details, like some silly person taking + get_module_symbol() away from us, from the caller. */ + +struct mtd_info *do_map_probe(const char *name, struct map_info *map) +{ + struct mtd_chip_driver *drv; + struct mtd_info *ret; + + drv = get_mtd_chip_driver(name); + + if (!drv && !request_module("%s", name)) + drv = get_mtd_chip_driver(name); + + if (!drv) + return NULL; + + ret = drv->probe(map); + + /* We decrease the use count here. It may have been a + probe-only module, which is no longer required from this + point, having given us a handle on (and increased the use + count of) the actual driver code. + */ + module_put(drv->module); + + if (ret) + return ret; + + return NULL; +} +/* + * Destroy an MTD device which was created for a map device. + * Make sure the MTD device is already unregistered before calling this + */ +void map_destroy(struct mtd_info *mtd) +{ + struct map_info *map = mtd->priv; + + if (map->fldrv->destroy) + map->fldrv->destroy(mtd); + + module_put(map->fldrv->module); + + kfree(mtd); +} + +EXPORT_SYMBOL(register_mtd_chip_driver); +EXPORT_SYMBOL(unregister_mtd_chip_driver); +EXPORT_SYMBOL(do_map_probe); +EXPORT_SYMBOL(map_destroy); + +MODULE_LICENSE("GPL"); +MODULE_AUTHOR("David Woodhouse "); +MODULE_DESCRIPTION("Core routines for registering and invoking MTD chip drivers"); diff --git a/pool/shard002/C/0057810_vterm_resize.c b/pool/shard002/C/0057810_vterm_resize.c new file mode 100644 index 0000000000000000000000000000000000000000..31177ca5ccb33084410c67f1d03a318a6d621f95 --- /dev/null +++ b/pool/shard002/C/0057810_vterm_resize.c @@ -0,0 +1,80 @@ +/* + * Modifed to remove glib2.0 dependency by Ollie Etherington (C) Copyright 2014 + * + * libvterm Copyright (C) 2009 Bryan Christ + * libvterm is based on ROTE written by Bruno Takahashi C. de Oliveira + * + * As per previous releases, this program is available under the GNU GPL v2 + * + * 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 "vterm.h" +#include "vterm_private.h" +#include "vterm_misc.h" + +void vterm_resize(vterm_t *vterm,unsigned int width,unsigned int height) +{ + struct winsize ws={.ws_xpixel=0,.ws_ypixel=0}; + unsigned int i; + int delta_x, delta_y, start_x, start_y; + + if(vterm==NULL) return; + if(width==0 || height==0) return; + + delta_x=width-vterm->cols; + delta_y=height-vterm->rows; + start_x=vterm->cols; + start_y=vterm->rows; + + vterm->cells=(vterm_cell_t**)realloc(vterm->cells, + sizeof(vterm_cell_t*)*height); + + for(i=0;i < height;i++) + { + // realloc() does not initlize new elements + if((delta_y > 0) && (i > vterm->rows-1)) vterm->cells[i]=NULL; + + vterm->cells[i]=(vterm_cell_t*)realloc(vterm->cells[i], + sizeof(vterm_cell_t)*width); + } + + vterm->rows=height; + vterm->cols=width; + if(!(vterm->state & STATE_SCROLL_SHORT)) + { + vterm->scroll_max=height-1; + } + + ws.ws_row=height; + ws.ws_col=width; + + clamp_cursor_to_bounds(vterm); + + if(delta_x > 0) vterm_erase_cols(vterm,start_x); + if(delta_y > 0) vterm_erase_rows(vterm,start_y); + + ioctl(vterm->pty_fd,TIOCSWINSZ,&ws); + kill(vterm->child_pid,SIGWINCH); + + return; +} diff --git a/pool/shard002/C/0057821_my_symlink2.c b/pool/shard002/C/0057821_my_symlink2.c new file mode 100644 index 0000000000000000000000000000000000000000..0b580ecd32f5f29a1a96f224e698901aee823f7e --- /dev/null +++ b/pool/shard002/C/0057821_my_symlink2.c @@ -0,0 +1,191 @@ +/* Copyright (c) 2000, 2001, 2003, 2005-2007 MySQL AB + Use is subject to license terms + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; version 2 of the License. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA */ + +/* + Advanced symlink handling. + This is used in MyISAM to let users symlinks tables to different disk. + The main idea with these functions is to automatically create, delete and + rename files and symlinks like they would be one unit. +*/ + +#include "mysys_priv.h" +#include "mysys_err.h" +#include + +File my_create_with_symlink(const char *linkname, const char *filename, + int createflags, int access_flags, myf MyFlags) +{ + File file; + int tmp_errno; + /* Test if we should create a link */ + int create_link; + char abs_linkname[FN_REFLEN]; + DBUG_ENTER("my_create_with_symlink"); + DBUG_PRINT("enter", ("linkname: %s filename: %s", + linkname ? linkname : "(NULL)", + filename ? filename : "(NULL)")); + + if (my_disable_symlinks) + { + DBUG_PRINT("info", ("Symlinks disabled")); + /* Create only the file, not the link and file */ + create_link= 0; + if (linkname) + filename= linkname; + } + else + { + if (linkname) + my_realpath(abs_linkname, linkname, MYF(0)); + create_link= (linkname && strcmp(abs_linkname,filename)); + } + + if (!(MyFlags & MY_DELETE_OLD)) + { + if (!access(filename,F_OK)) + { + my_errno= errno= EEXIST; + my_error(EE_CANTCREATEFILE, MYF(0), filename, EEXIST); + DBUG_RETURN(-1); + } + if (create_link && !access(linkname,F_OK)) + { + my_errno= errno= EEXIST; + my_error(EE_CANTCREATEFILE, MYF(0), linkname, EEXIST); + DBUG_RETURN(-1); + } + } + + if ((file=my_create(filename, createflags, access_flags, MyFlags)) >= 0) + { + if (create_link) + { + /* Delete old link/file */ + if (MyFlags & MY_DELETE_OLD) + my_delete(linkname, MYF(0)); + /* Create link */ + if (my_symlink(filename, linkname, MyFlags)) + { + /* Fail, remove everything we have done */ + tmp_errno=my_errno; + my_close(file,MYF(0)); + my_delete(filename, MYF(0)); + file= -1; + my_errno=tmp_errno; + } + } + } + DBUG_RETURN(file); +} + +/* + If the file is a normal file, just rename it. + If the file is a symlink: + - Create a new file with the name 'to' that points at + symlink_dir/basename(to) + - Rename the symlinked file to symlink_dir/basename(to) + - Delete 'from' + If something goes wrong, restore everything. +*/ + +int my_rename_with_symlink(const char *from, const char *to, myf MyFlags) +{ +#ifndef HAVE_READLINK + return my_rename(from, to, MyFlags); +#else + char link_name[FN_REFLEN], tmp_name[FN_REFLEN]; + int was_symlink= (!my_disable_symlinks && + !my_readlink(link_name, from, MYF(0))); + int result=0; + int name_is_different; + DBUG_ENTER("my_rename_with_symlink"); + + if (!was_symlink) + DBUG_RETURN(my_rename(from, to, MyFlags)); + + /* Change filename that symlink pointed to */ + strmov(tmp_name, to); + fn_same(tmp_name,link_name,1); /* Copy dir */ + name_is_different= strcmp(link_name, tmp_name); + if (name_is_different && !access(tmp_name, F_OK)) + { + my_errno= EEXIST; + if (MyFlags & MY_WME) + my_error(EE_CANTCREATEFILE, MYF(0), tmp_name, EEXIST); + DBUG_RETURN(1); + } + + /* Create new symlink */ + if (my_symlink(tmp_name, to, MyFlags)) + DBUG_RETURN(1); + + /* + Rename symlinked file if the base name didn't change. + This can happen if you use this function where 'from' and 'to' has + the same basename and different directories. + */ + + if (name_is_different && my_rename(link_name, tmp_name, MyFlags)) + { + int save_errno=my_errno; + my_delete(to, MyFlags); /* Remove created symlink */ + my_errno=save_errno; + DBUG_RETURN(1); + } + + /* Remove original symlink */ + if (my_delete(from, MyFlags)) + { + int save_errno=my_errno; + /* Remove created link */ + my_delete(to, MyFlags); + /* Rename file back */ + if (strcmp(link_name, tmp_name)) + (void) my_rename(tmp_name, link_name, MyFlags); + my_errno=save_errno; + result= 1; + } + DBUG_RETURN(result); +#endif /* HAVE_READLINK */ +} + +/** delete a - possibly symlinked - table file + + This is used to delete a file that is part of a table (e.g. MYI or MYD + file of MyISAM) when dropping a table. A file might be a symlink - + if the table was created with DATA DIRECTORY or INDEX DIRECTORY - + in this case both the symlink and the symlinked file are deleted, + but only if the symlinked file is not in the datadir. +*/ + +int my_handler_delete_with_symlink(const char *filename, myf sync_dir) +{ + char real[FN_REFLEN]; + int res= 0; + DBUG_ENTER("my_handler_delete_with_symlink"); + + if (my_is_symlink(filename)) + { + /* + Delete the symlinked file only if the symlink is not + pointing into datadir. + */ + if (!(my_realpath(real, filename, MYF(0)) || + mysys_test_invalid_symlink(real))) + res= my_delete(real, MYF(MY_NOSYMLINKS | sync_dir)); + } + DBUG_RETURN(my_delete(filename, sync_dir) || res); +} diff --git a/pool/shard002/C/0057826_UniqueMessageData.c b/pool/shard002/C/0057826_UniqueMessageData.c new file mode 100644 index 0000000000000000000000000000000000000000..3eea1ba2f3a064d7c4aa729ac9ea7846273140cd --- /dev/null +++ b/pool/shard002/C/0057826_UniqueMessageData.c @@ -0,0 +1,176 @@ +/* + * java-gnome, a UI library for writing GTK and GNOME programs from Java! + * + * Copyright © 2006-2011 Operational Dynamics Consulting, Pty Ltd and Others + * + * The code in this file, and the program it is a part of, is made available + * to you by its authors as open source software: you can redistribute it + * and/or modify it under the terms of the GNU General Public License version + * 2 ("GPL") 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 GPL for more details. + * + * You should have received a copy of the GPL along with this program. If not, + * see http://www.gnu.org/licenses/. The authors of this program may be + * contacted through http://java-gnome.sourceforge.net/. + * + * Linking this library statically or dynamically with other modules is making + * a combined work based on this library. Thus, the terms and conditions of + * the GPL cover the whole combination. As a special exception (the + * "Claspath Exception"), the copyright holders of this library give you + * permission to link this library with independent modules to produce an + * executable, regardless of the license terms of these independent modules, + * and to copy and distribute the resulting executable under terms of your + * choice, provided that you also meet, for each linked independent module, + * the terms and conditions of the license of that module. An independent + * module is a module which is not derived from or based on this library. If + * you modify this library, you may extend the Classpath Exception to your + * version of the library, but you are not obligated to do so. If you do not + * wish to do so, delete this exception statement from your version. + */ + +/* + * THIS FILE IS GENERATED CODE! + * + * To modify its contents or behaviour, either update the generation program, + * change the information in the source defs file, or implement an override for + * this class. + */ + +#include +#include +#include +#include "bindings_java.h" +#include "org_gnome_unique_UniqueMessageData.h" + +JNIEXPORT jlong JNICALL +Java_org_gnome_unique_UniqueMessageData_unique_1message_1data_1new +( + JNIEnv* env, + jclass cls +) +{ + UniqueMessageData* result; + jlong _result; + + // call function + result = unique_message_data_new(); + + // translate return value to JNI type + _result = (jlong) result; + + // and finally + return _result; +} + +JNIEXPORT jlong JNICALL +Java_org_gnome_unique_UniqueMessageData_unique_1message_1data_1copy +( + JNIEnv* env, + jclass cls, + jlong _self +) +{ + UniqueMessageData* result; + jlong _result; + UniqueMessageData* self; + + // convert parameter self + self = (UniqueMessageData*) _self; + + // call function + result = unique_message_data_copy(self); + + // cleanup parameter self + + // translate return value to JNI type + _result = (jlong) result; + + // and finally + return _result; +} + +JNIEXPORT void JNICALL +Java_org_gnome_unique_UniqueMessageData_unique_1message_1data_1free +( + JNIEnv* env, + jclass cls, + jlong _self +) +{ + UniqueMessageData* self; + + // convert parameter self + self = (UniqueMessageData*) _self; + + // call function + unique_message_data_free(self); + + // cleanup parameter self +} + +JNIEXPORT void JNICALL +Java_org_gnome_unique_UniqueMessageData_unique_1message_1data_1set_1text +( + JNIEnv* env, + jclass cls, + jlong _self, + jstring _text, + jint _length +) +{ + UniqueMessageData* self; + const gchar* text; + gssize length; + + // convert parameter self + self = (UniqueMessageData*) _self; + + // convert parameter text + text = (const gchar*) bindings_java_getString(env, _text); + if (text == NULL) { + return; // Java Exception already thrown + } + + // convert parameter length + length = (gssize) _length; + + // call function + unique_message_data_set_text(self, text, length); + + // cleanup parameter self + + // cleanup parameter text + bindings_java_releaseString(text); + + // cleanup parameter length +} + +JNIEXPORT jstring JNICALL +Java_org_gnome_unique_UniqueMessageData_unique_1message_1data_1get_1text +( + JNIEnv* env, + jclass cls, + jlong _self +) +{ + gchar* result; + jstring _result; + UniqueMessageData* self; + + // convert parameter self + self = (UniqueMessageData*) _self; + + // call function + result = unique_message_data_get_text(self); + + // cleanup parameter self + + // translate return value to JNI type + _result = (jstring) bindings_java_newString(env, result); + + // and finally + return _result; +} diff --git a/pool/shard002/C/0057849_libipt_psd.c b/pool/shard002/C/0057849_libipt_psd.c new file mode 100644 index 0000000000000000000000000000000000000000..201e909ffd9dda8be096b6b4e8084ff7fbe5a895 --- /dev/null +++ b/pool/shard002/C/0057849_libipt_psd.c @@ -0,0 +1,201 @@ +/* + Shared library add-on to iptables to add PSD support + + Copyright (C) 2000,2001 astaro AG + + This file is distributed under the terms of the GNU General Public + License (GPL). Copies of the GPL can be obtained from: + ftp://prep.ai.mit.edu/pub/gnu/GPL + + 2000-05-04 Markus Hennig : initial + 2000-08-18 Dennis Koslowski : first release + 2000-12-01 Dennis Koslowski : UDP scans detection added + 2001-02-04 Jan Rekorajski : converted from target to match +*/ + +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +/* Function which prints out usage message. */ +static void +help(void) +{ + printf( +"psd v%s options:\n" +" --psd-weight-threshold threshhold Portscan detection weight threshold\n\n" +" --psd-delay-threshold delay Portscan detection delay threshold\n\n" +" --psd-lo-ports-weight lo Privileged ports weight\n\n" +" --psd-hi-ports-weight hi High ports weight\n\n", +IPTABLES_VERSION); +} + +static struct option opts[] = { + { "psd-weight-threshold", 1, 0, '1' }, + { "psd-delay-threshold", 1, 0, '2' }, + { "psd-lo-ports-weight", 1, 0, '3' }, + { "psd-hi-ports-weight", 1, 0, '4' }, + { 0 } +}; + +/* Initialize the target. */ +static void +init(struct ipt_entry_match *m, unsigned int *nfcache) +{ + struct ipt_psd_info *psdinfo = (struct ipt_psd_info *)m->data; + + psdinfo->weight_threshold = SCAN_WEIGHT_THRESHOLD; + psdinfo->delay_threshold = SCAN_DELAY_THRESHOLD; + psdinfo->lo_ports_weight = PORT_WEIGHT_PRIV; + psdinfo->hi_ports_weight = PORT_WEIGHT_HIGH; + /* Can't cache this */ + *nfcache |= NFC_UNKNOWN; +} + + +typedef struct _code { + char *c_name; + int c_val; +} CODE; + + + +#define IPT_PSD_OPT_CTRESH 0x01 +#define IPT_PSD_OPT_DTRESH 0x02 +#define IPT_PSD_OPT_LPWEIGHT 0x04 +#define IPT_PSD_OPT_HPWEIGHT 0x08 + +/* 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_psd_info *psdinfo = (struct ipt_psd_info *)(*match)->data; + unsigned int num; + char storage[strlen(optarg) + 2]; + + /* string_to_number needs a leading space */ + storage[0] = ' '; + strcpy(&storage[1], optarg); + + switch (c) { + /* PSD-weight-threshold */ + case '1': + if (*flags & IPT_PSD_OPT_CTRESH) + exit_error(PARAMETER_PROBLEM, + "Can't specify --psd-weight-threshold " + "twice"); + if (string_to_number(storage, 0, 10000, &num) == -1) + exit_error(PARAMETER_PROBLEM, + "bad --psd-weight-threshold `%s'", optarg); + psdinfo->weight_threshold = num; + *flags |= IPT_PSD_OPT_CTRESH; + break; + + /* PSD-delay-threshold */ + case '2': + if (*flags & IPT_PSD_OPT_DTRESH) + exit_error(PARAMETER_PROBLEM, + "Can't specify --psd-delay-threshold twice"); + if (string_to_number(storage, 0, 10000, &num) == -1) + exit_error(PARAMETER_PROBLEM, + "bad --psd-delay-threshold `%s'", optarg); + psdinfo->delay_threshold = num; + *flags |= IPT_PSD_OPT_DTRESH; + break; + + /* PSD-lo-ports-weight */ + case '3': + if (*flags & IPT_PSD_OPT_LPWEIGHT) + exit_error(PARAMETER_PROBLEM, + "Can't specify --psd-lo-ports-weight twice"); + if (string_to_number(storage, 0, 10000, &num) == -1) + exit_error(PARAMETER_PROBLEM, + "bad --psd-lo-ports-weight `%s'", optarg); + psdinfo->lo_ports_weight = num; + *flags |= IPT_PSD_OPT_LPWEIGHT; + break; + + /* PSD-hi-ports-weight */ + case '4': + if (*flags & IPT_PSD_OPT_HPWEIGHT) + exit_error(PARAMETER_PROBLEM, + "Can't specify --psd-hi-ports-weight twice"); + if (string_to_number(storage, 0, 10000, &num) == -1) + exit_error(PARAMETER_PROBLEM, + "bad --psd-hi-ports-weight `%s'", optarg); + psdinfo->hi_ports_weight = num; + *flags |= IPT_PSD_OPT_HPWEIGHT; + break; + + default: + return 0; + } + + return 1; +} + +/* Final check; nothing. */ +static void final_check(unsigned int flags) +{ +} + +/* Prints out the targinfo. */ +static void +print(const struct ipt_ip *ip, + const struct ipt_entry_match *match, + int numeric) +{ + const struct ipt_psd_info *psdinfo + = (const struct ipt_psd_info *)match->data; + + printf("psd "); + printf("weight-threshold: %u ",psdinfo->weight_threshold); + printf("delay-threshold: %u ",psdinfo->delay_threshold); + printf("lo-ports-weight: %u ",psdinfo->lo_ports_weight); + printf("hi-ports-weight: %u ",psdinfo->hi_ports_weight); +} + +/* Saves the union ipt_targinfo in parsable form to stdout. */ +static void +save(const struct ipt_ip *ip, const struct ipt_entry_match *match) +{ + const struct ipt_psd_info *psdinfo + = (const struct ipt_psd_info *)match->data; + + printf("--psd-weight-threshold %u ", psdinfo->weight_threshold); + printf("--psd-delay-threshold %u ", psdinfo->delay_threshold); + printf("--psd-lo-ports-weight %u ",psdinfo->lo_ports_weight); + printf("--psd-hi-ports-weight %u ",psdinfo->hi_ports_weight); +} + +static +struct iptables_match psd += { NULL, + "psd", + IPTABLES_VERSION, + IPT_ALIGN(sizeof(struct ipt_psd_info)), + IPT_ALIGN(sizeof(struct ipt_psd_info)), + &help, + &init, + &parse, + &final_check, + &print, + &save, + opts +}; + +void _init(void) +{ + register_match(&psd); +} diff --git a/pool/shard002/C/0057863_sysaufs.c b/pool/shard002/C/0057863_sysaufs.c new file mode 100644 index 0000000000000000000000000000000000000000..919e1b00e34d1e6739290760a193a5d2c9b72200 --- /dev/null +++ b/pool/shard002/C/0057863_sysaufs.c @@ -0,0 +1,104 @@ +/* + * Copyright (C) 2005-2010 Junjiro R. Okajima + * + * This program, aufs 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 + */ + +/* + * sysfs interface and lifetime management + * they are necessary regardless sysfs is disabled. + */ + +#include +#include +#include +#include "aufs.h" + +unsigned long sysaufs_si_mask; +struct kset *sysaufs_ket; + +#define AuSiAttr(_name) { \ + .attr = { .name = __stringify(_name), .mode = 0444 }, \ + .show = sysaufs_si_##_name, \ +} + +static struct sysaufs_si_attr sysaufs_si_attr_xi_path = AuSiAttr(xi_path); +struct attribute *sysaufs_si_attrs[] = { + &sysaufs_si_attr_xi_path.attr, + NULL, +}; + +static struct sysfs_ops au_sbi_ops = { + .show = sysaufs_si_show +}; + +static struct kobj_type au_sbi_ktype = { + .release = au_si_free, + .sysfs_ops = &au_sbi_ops, + .default_attrs = sysaufs_si_attrs +}; + +/* ---------------------------------------------------------------------- */ + +int sysaufs_si_init(struct au_sbinfo *sbinfo) +{ + int err; + + sbinfo->si_kobj.kset = sysaufs_ket; + /* cf. sysaufs_name() */ + err = kobject_init_and_add + (&sbinfo->si_kobj, &au_sbi_ktype, /*&sysaufs_ket->kobj*/NULL, + SysaufsSiNamePrefix "%lx", sysaufs_si_id(sbinfo)); + + dbgaufs_si_null(sbinfo); + if (!err) { + err = dbgaufs_si_init(sbinfo); + if (unlikely(err)) + kobject_put(&sbinfo->si_kobj); + } + return err; +} + +void sysaufs_fin(void) +{ + dbgaufs_fin(); + sysfs_remove_group(&sysaufs_ket->kobj, sysaufs_attr_group); + kset_unregister(sysaufs_ket); +} + +int __init sysaufs_init(void) +{ + int err; + + do { + get_random_bytes(&sysaufs_si_mask, sizeof(sysaufs_si_mask)); + } while (!sysaufs_si_mask); + + sysaufs_ket = kset_create_and_add(AUFS_NAME, NULL, fs_kobj); + err = PTR_ERR(sysaufs_ket); + if (IS_ERR(sysaufs_ket)) + goto out; + err = sysfs_create_group(&sysaufs_ket->kobj, sysaufs_attr_group); + if (unlikely(err)) { + kset_unregister(sysaufs_ket); + goto out; + } + + err = dbgaufs_init(); + if (unlikely(err)) + sysaufs_fin(); + out: + return err; +} diff --git a/pool/shard002/C/0057885_mt_rtc.c b/pool/shard002/C/0057885_mt_rtc.c new file mode 100644 index 0000000000000000000000000000000000000000..041106e1318ce4288813309ecd0112303267f158 --- /dev/null +++ b/pool/shard002/C/0057885_mt_rtc.c @@ -0,0 +1,206 @@ +/* + * 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 + +#define RTC_RELPWR_WHEN_XRST 1 /* BBPU = 0 when xreset_rstb goes low */ + +static U16 RTC_Read(U16 addr) +{ + U32 rdata=0; + pwrap_read((U32)addr, &rdata); + return (U16)rdata; +} + +static void RTC_Write(U16 addr, U16 data) +{ + pwrap_write((U32)addr, (U32)data); +} + + +#define rtc_busy_wait() \ +do { \ + while (RTC_Read(RTC_BBPU) & RTC_BBPU_CBUSY); \ +} while (0) + +static unsigned long rtc_mktime(int yea, int mth, int dom, int hou, int min, int sec) +{ + unsigned long d1, d2, d3; + + mth -= 2; + if (mth <= 0) { + mth += 12; + yea -= 1; + } + + d1 = (yea - 1) * 365 + (yea / 4 - yea / 100 + yea / 400); + d2 = (367 * mth / 12 - 30) + 59; + d3 = d1 + d2 + (dom - 1) - 719162; + + return ((d3 * 24 + hou) * 60 + min) * 60 + sec; +} + +static void rtc_write_trigger(void) +{ + RTC_Write(RTC_WRTGR, 1); + rtc_busy_wait(); +} + +void rtc_writeif_unlock(void) +{ + RTC_Write(RTC_PROT, 0x586a); + rtc_write_trigger(); + RTC_Write(RTC_PROT, 0x9136); + rtc_write_trigger(); +} + +void rtc_writeif_lock(void) +{ + RTC_Write(RTC_PROT, 0); + rtc_write_trigger(); +} + +void rtc_bbpu_power_down(void) +{ + U16 bbpu; + + /* pull PWRBB low */ + bbpu = RTC_BBPU_KEY | RTC_BBPU_AUTO | RTC_BBPU_PWREN; + rtc_writeif_unlock(); + RTC_Write(RTC_BBPU, bbpu); + rtc_write_trigger(); +} + +U16 rtc_rdwr_uart_bits(U16 *val) +{ + U16 pdn2; + + if (val) { + pdn2 = RTC_Read(RTC_PDN2) & ~0x0060; + pdn2 |= (*val & 0x0003) << 5; + RTC_Write(RTC_PDN2, pdn2); + rtc_write_trigger(); + } + + return (RTC_Read(RTC_PDN2) & 0x0060) >> 5; +} + +bool rtc_boot_check(bool can_alarm_boot) +{ + U16 irqsta, pdn1, pdn2, spar0, spar1; + + irqsta = RTC_Read(RTC_IRQ_STA); /* read clear */ + pdn1 = RTC_Read(RTC_PDN1); + pdn2 = RTC_Read(RTC_PDN2); + spar0 = RTC_Read(RTC_SPAR0); + spar1 = RTC_Read(RTC_SPAR1); + /*printf("irqsta = 0x%x, pdn1 = 0x%x, pdn2 = 0x%x, spar0 = 0x%x, spar1 = 0x%x\n", + irqsta, pdn1, pdn2, spar0, spar1);*/ + + if (irqsta & RTC_IRQ_STA_AL) { +#if RTC_RELPWR_WHEN_XRST + /* set AUTO bit because AUTO = 0 when PWREN = 1 and alarm occurs */ + U16 bbpu = RTC_Read(RTC_BBPU) | RTC_BBPU_KEY | RTC_BBPU_AUTO; + RTC_Write(RTC_BBPU, bbpu); + rtc_write_trigger(); +#endif + + if (pdn1 & 0x0080) { /* power-on time is available */ + U16 now_sec, now_min, now_hou, now_dom, now_mth, now_yea; + U16 irqen, sec, min, hou, dom, mth, yea; + unsigned long now_time, time; + + now_sec = RTC_Read(RTC_TC_SEC); + now_min = RTC_Read(RTC_TC_MIN); + now_hou = RTC_Read(RTC_TC_HOU); + now_dom = RTC_Read(RTC_TC_DOM); + now_mth = RTC_Read(RTC_TC_MTH); + now_yea = RTC_Read(RTC_TC_YEA) + RTC_MIN_YEAR; + if (RTC_Read(RTC_TC_SEC) < now_sec) { /* SEC has carried */ + now_sec = RTC_Read(RTC_TC_SEC); + now_min = RTC_Read(RTC_TC_MIN); + now_hou = RTC_Read(RTC_TC_HOU); + now_dom = RTC_Read(RTC_TC_DOM); + now_mth = RTC_Read(RTC_TC_MTH); + now_yea = RTC_Read(RTC_TC_YEA) + RTC_MIN_YEAR; + } + + sec = spar0 & 0x003f; + min = spar1 & 0x003f; + hou = (spar1 & 0x07c0) >> 6; + dom = (spar1 & 0xf800) >> 11; + mth = pdn2 & 0x000f; + yea = ((pdn2 & 0x7f00) >> 8) + RTC_MIN_YEAR; + + now_time = rtc_mktime(now_yea, now_mth, now_dom, now_hou, now_min, now_sec); + time = rtc_mktime(yea, mth, dom, hou, min, sec); + + printf("now = %d/%d/%d %d:%d:%d (%lu)\n", + now_yea, now_mth, now_dom, now_hou, now_min, now_sec, now_time); + printf("power-on = %d/%d/%d %d:%d:%d (%lu)\n", + yea, mth, dom, hou, min, sec, time); + + if (now_time >= time - 1 && now_time <= time + 4) { /* power on */ + pdn1 &= ~(0x0080 | 0x0010 | 0x0040); + RTC_Write(RTC_PDN1, pdn1); + RTC_Write(RTC_PDN2, pdn2 | 0x0010); + rtc_write_trigger(); + if (can_alarm_boot && + !(pdn2 & 0x8000)) { /* no logo means ALARM_BOOT */ + g_boot_mode = ALARM_BOOT; + } + return true; + } else if (now_time < time) { /* set power-on alarm */ + RTC_Write(RTC_AL_YEA, yea - RTC_MIN_YEAR); + RTC_Write(RTC_AL_MTH, mth); + RTC_Write(RTC_AL_DOM, dom); + RTC_Write(RTC_AL_HOU, hou); + RTC_Write(RTC_AL_MIN, min); + RTC_Write(RTC_AL_SEC, sec); + RTC_Write(RTC_AL_MASK, 0x0010); /* mask DOW */ + rtc_write_trigger(); + irqen = RTC_Read(RTC_IRQ_EN) | RTC_IRQ_EN_ONESHOT_AL; + RTC_Write(RTC_IRQ_EN, irqen); + rtc_write_trigger(); + } + } + } + + if ((pdn1 & 0x0030) == 0x0010) { /* factory data reset */ + RTC_Write(RTC_PDN1, pdn1 & ~0x0010); + rtc_write_trigger(); + return true; + } + + if (pdn1 & 0x0040) { /* bypass power key detection */ + RTC_Write(RTC_PDN1, pdn1 & ~0x0040); + rtc_write_trigger(); + return true; + } + + return false; +} + +//MODULE_AUTHOR("Terry Chang "); +//MODULE_DESCRIPTION("MT6575 RTC U-Boot Driver v1.9"); diff --git a/pool/shard002/C/0057891_win_msg.c b/pool/shard002/C/0057891_win_msg.c new file mode 100644 index 0000000000000000000000000000000000000000..e73465b23808a63b3b28ace4c899c3f96ad1efe2 --- /dev/null +++ b/pool/shard002/C/0057891_win_msg.c @@ -0,0 +1,198 @@ +/***************************************************************************** + * ntservice.c: Windows NT/2K/XP service interface + ***************************************************************************** + * Copyright (C) 2001-2004, 2010 VLC authors and VideoLAN + * + * Authors: Samuel Hocevar + * Gildas Bazin + * + * 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. + *****************************************************************************/ + +#ifdef HAVE_CONFIG_H +# include "config.h" +#endif + +#define VLC_MODULE_LICENSE VLC_LICENSE_GPL_2_PLUS +#include +#include +#include +#include +#include +#include // FIXME: move URL generation to calling process + +#include + +struct intf_sys_t +{ + HWND window; + HANDLE ready; + vlc_thread_t thread; +}; + +/* Must be same as in src/win32/specific.c */ +typedef struct +{ + int argc; + int enqueue; + char data[]; +} vlc_ipc_data_t; + +static LRESULT CALLBACK WMCOPYWNDPROC(HWND hwnd, UINT uMsg, + WPARAM wParam, LPARAM lParam) +{ + if( uMsg == WM_QUIT ) + { + PostQuitMessage( 0 ); + } + else if( uMsg == WM_COPYDATA ) + { + COPYDATASTRUCT *pwm_data = (COPYDATASTRUCT*)lParam; + + intf_thread_t *intf = (intf_thread_t *)(uintptr_t) + GetWindowLongPtr( hwnd, GWLP_USERDATA ); + if( intf == NULL ) + return 0; /* XXX: is this even possible? */ + + /* Add files to the playlist */ + if( pwm_data->lpData ) + { + char **ppsz_argv; + vlc_ipc_data_t *p_data = (vlc_ipc_data_t *)pwm_data->lpData; + size_t i_data = 0; + int i_argc = p_data->argc, i_opt, i_options; + + ppsz_argv = vlc_alloc( i_argc, sizeof(char *) ); + for( i_opt = 0; i_opt < i_argc; i_opt++ ) + { + ppsz_argv[i_opt] = p_data->data + i_data + sizeof(size_t); + i_data += sizeof(size_t) + *((size_t *)(p_data->data + i_data)); + } + + for( i_opt = 0; i_opt < i_argc; i_opt++ ) + { + i_options = 0; + + /* Count the input options */ + while( i_opt + i_options + 1 < i_argc && + *ppsz_argv[ i_opt + i_options + 1 ] == ':' ) + { + i_options++; + } + +#warning URI conversion must be done in calling process instead! + /* FIXME: This breaks relative paths if calling vlc.exe is + * started from a different working directory. */ + char *psz_URI = NULL; + if( strstr( ppsz_argv[i_opt], "://" ) == NULL ) + psz_URI = vlc_path2uri( ppsz_argv[i_opt], NULL ); + playlist_AddExt( pl_Get(intf), + (psz_URI != NULL) ? psz_URI : ppsz_argv[i_opt], + NULL, (i_opt == 0 && !p_data->enqueue), + i_options, + (char const **)( i_options ? &ppsz_argv[i_opt+1] : NULL ), + VLC_INPUT_OPTION_TRUSTED, + true ); + + i_opt += i_options; + free( psz_URI ); + } + + free( ppsz_argv ); + } + } + + return DefWindowProc( hwnd, uMsg, wParam, lParam ); +} + +static void *HelperThread(void *data) +{ + intf_thread_t *intf = data; + intf_sys_t *sys = intf->p_sys; + + HWND ipcwindow = + CreateWindow(L"STATIC", /* name of window class */ + L"VLC ipc " TEXT(VERSION), /* window title bar text */ + 0, /* window style */ + 0, /* default X coordinate */ + 0, /* default Y coordinate */ + 0, /* window width */ + 0, /* window height */ + NULL, /* no parent window */ + NULL, /* no menu in this window */ + GetModuleHandle(NULL), /* handle of this program instance */ + NULL) ; /* sent to WM_CREATE */ + + SetWindowLongPtr(ipcwindow, GWLP_WNDPROC, (LRESULT)WMCOPYWNDPROC); + SetWindowLongPtr(ipcwindow, GWLP_USERDATA, (uintptr_t)data); + + sys->window = ipcwindow; + /* Signal the creation of the thread and events queue */ + SetEvent(sys->ready); + + MSG message; + while (GetMessage(&message, NULL, 0, 0)) + { + TranslateMessage(&message); + DispatchMessage(&message); + } + + return NULL; +} + +static int Open(vlc_object_t *obj) +{ + intf_thread_t *intf = (intf_thread_t *)obj; + intf_sys_t *sys = malloc(sizeof (*sys)); + if (unlikely(sys == NULL)) + return VLC_ENOMEM; + + intf->p_sys = sys; + + /* Run the helper thread */ + sys->ready = CreateEvent(NULL, FALSE, FALSE, NULL); + + if (vlc_clone(&sys->thread, HelperThread, intf, VLC_THREAD_PRIORITY_LOW)) + { + free(sys); + msg_Err(intf, "one instance mode DISABLED " + "(IPC helper thread couldn't be created)"); + return VLC_ENOMEM; + } + + WaitForSingleObject(sys->ready, INFINITE); + CloseHandle(sys->ready); + + return VLC_SUCCESS; +} + +static void Close(vlc_object_t *obj) +{ + intf_thread_t *intf = (intf_thread_t *)obj; + intf_sys_t *sys = intf->p_sys; + + SendMessage(sys->window, WM_QUIT, 0, 0); + vlc_join(sys->thread, NULL); + free(sys); +} + +vlc_module_begin() + set_shortname(N_("WinMsg")) + set_description(N_("Windows messages interface")) + set_category(CAT_INTERFACE) + set_subcategory(SUBCAT_INTERFACE_CONTROL) + set_capability("interface", 0) + set_callbacks(Open, Close) +vlc_module_end() diff --git a/pool/shard002/C/0057899_MiscNumberOfInstallableLanguagesFunction.c b/pool/shard002/C/0057899_MiscNumberOfInstallableLanguagesFunction.c new file mode 100644 index 0000000000000000000000000000000000000000..8b15ab1740c0723dac44aa5d9502dd13e440dd88 --- /dev/null +++ b/pool/shard002/C/0057899_MiscNumberOfInstallableLanguagesFunction.c @@ -0,0 +1,233 @@ +/** @file + This driver parses the mSmbiosMiscDataTable structure and reports + any generated data. + + Copyright (c) 2009 - 2011, 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. + +**/ + +#include "MiscSubClassDriver.h" +/*++ + Check whether the language is supported for given HII handle + + @param HiiHandle The HII package list handle. + @param Offset The offest of current lanague in the supported languages. + @param CurrentLang The language code. + + @retval TRUE Supported. + @retval FALSE Not Supported. + +**/ +VOID +EFIAPI +CurrentLanguageMatch ( + IN EFI_HII_HANDLE HiiHandle, + OUT UINT16 *Offset, + OUT CHAR8 *CurrentLang + ) +{ + CHAR8 *DefaultLang; + CHAR8 *BestLanguage; + CHAR8 *Languages; + CHAR8 *MatchLang; + CHAR8 *EndMatchLang; + UINTN CompareLength; + + Languages = HiiGetSupportedLanguages (HiiHandle); + if (Languages == NULL) { + return; + } + + CurrentLang = GetEfiGlobalVariable (L"PlatformLang"); + DefaultLang = (CHAR8 *) PcdGetPtr (PcdUefiVariableDefaultPlatformLang); + BestLanguage = GetBestLanguage ( + Languages, + FALSE, + (CurrentLang != NULL) ? CurrentLang : "", + DefaultLang, + NULL + ); + if (BestLanguage != NULL) { + // + // Find the best matching RFC 4646 language, compute the offset. + // + CompareLength = AsciiStrLen (BestLanguage); + for (MatchLang = Languages, (*Offset) = 0; MatchLang != '\0'; (*Offset)++) { + // + // Seek to the end of current match language. + // + for (EndMatchLang = MatchLang; *EndMatchLang != '\0' && *EndMatchLang != ';'; EndMatchLang++); + + if ((EndMatchLang == MatchLang + CompareLength) && AsciiStrnCmp(MatchLang, BestLanguage, CompareLength) == 0) { + // + // Find the current best Language in the supported languages + // + break; + } + // + // best language match be in the supported language. + // + ASSERT (*EndMatchLang == ';'); + MatchLang = EndMatchLang + 1; + } + FreePool (BestLanguage); + } + + FreePool (Languages); + if (CurrentLang != NULL) { + FreePool (CurrentLang); + } + return ; +} + + +/** + Get next language from language code list (with separator ';'). + + @param LangCode Input: point to first language in the list. On + Otput: point to next language in the list, or + NULL if no more language in the list. + @param Lang The first language in the list. + +**/ +VOID +EFIAPI +GetNextLanguage ( + IN OUT CHAR8 **LangCode, + OUT CHAR8 *Lang + ) +{ + UINTN Index; + CHAR8 *StringPtr; + + ASSERT (LangCode != NULL); + ASSERT (*LangCode != NULL); + ASSERT (Lang != NULL); + + Index = 0; + StringPtr = *LangCode; + while (StringPtr[Index] != 0 && StringPtr[Index] != ';') { + Index++; + } + + CopyMem (Lang, StringPtr, Index); + Lang[Index] = 0; + + if (StringPtr[Index] == ';') { + Index++; + } + *LangCode = StringPtr + Index; +} + +/** + This function returns the number of supported languages on HiiHandle. + + @param HiiHandle The HII package list handle. + + @retval The number of supported languages. + +**/ +UINT16 +EFIAPI +GetSupportedLanguageNumber ( + IN EFI_HII_HANDLE HiiHandle + ) +{ + CHAR8 *Lang; + CHAR8 *Languages; + CHAR8 *LanguageString; + UINT16 LangNumber; + + Languages = HiiGetSupportedLanguages (HiiHandle); + if (Languages == NULL) { + return 0; + } + + LangNumber = 0; + Lang = AllocatePool (AsciiStrSize (Languages)); + if (Lang != NULL) { + LanguageString = Languages; + while (*LanguageString != 0) { + GetNextLanguage (&LanguageString, Lang); + LangNumber++; + } + FreePool (Lang); + } + FreePool (Languages); + return LangNumber; +} + + +/** + This function makes boot time changes to the contents of the + MiscNumberOfInstallableLanguages (Type 13). + + @param RecordData Pointer to copy of RecordData from the Data Table. + + @retval EFI_SUCCESS All parameters were valid. + @retval EFI_UNSUPPORTED Unexpected RecordType value. + @retval EFI_INVALID_PARAMETER Invalid parameter was found. + +**/ +MISC_SMBIOS_TABLE_FUNCTION(NumberOfInstallableLanguages) +{ + UINTN LangStrLen; + CHAR8 CurrentLang[SMBIOS_STRING_MAX_LENGTH + 1]; + CHAR8 *OptionalStrStart; + UINT16 Offset; + EFI_STATUS Status; + EFI_SMBIOS_HANDLE SmbiosHandle; + SMBIOS_TABLE_TYPE13 *SmbiosRecord; + EFI_MISC_NUMBER_OF_INSTALLABLE_LANGUAGES *ForType13InputData; + + ForType13InputData = (EFI_MISC_NUMBER_OF_INSTALLABLE_LANGUAGES *)RecordData; + + // + // First check for invalid parameters. + // + if (RecordData == NULL) { + return EFI_INVALID_PARAMETER; + } + + ForType13InputData->NumberOfInstallableLanguages = GetSupportedLanguageNumber (mHiiHandle); + + // + // Try to check if current langcode matches with the langcodes in installed languages + // + ZeroMem(CurrentLang, SMBIOS_STRING_MAX_LENGTH + 1); + CurrentLanguageMatch (mHiiHandle, &Offset, CurrentLang); + LangStrLen = AsciiStrLen(CurrentLang); + + // + // Two zeros following the last string. + // + SmbiosRecord = AllocatePool(sizeof (SMBIOS_TABLE_TYPE13) + LangStrLen + 1 + 1); + ZeroMem(SmbiosRecord, sizeof (SMBIOS_TABLE_TYPE13) + LangStrLen + 1 + 1); + + SmbiosRecord->Hdr.Type = EFI_SMBIOS_TYPE_BIOS_LANGUAGE_INFORMATION; + SmbiosRecord->Hdr.Length = sizeof (SMBIOS_TABLE_TYPE13); + // + // Make handle chosen by smbios protocol.add automatically. + // + SmbiosRecord->Hdr.Handle = 0; + + SmbiosRecord->InstallableLanguages = (UINT8)ForType13InputData->NumberOfInstallableLanguages; + SmbiosRecord->Flags = (UINT8)ForType13InputData->LanguageFlags.AbbreviatedLanguageFormat; + SmbiosRecord->CurrentLanguages = 1; + OptionalStrStart = (CHAR8 *)(SmbiosRecord + 1); + AsciiStrCpy(OptionalStrStart, CurrentLang); + // + // Now we have got the full smbios record, call smbios protocol to add this record. + // + Status = AddSmbiosRecord (Smbios, &SmbiosHandle, (EFI_SMBIOS_TABLE_HEADER *) SmbiosRecord); + + FreePool(SmbiosRecord); + return Status; +} diff --git a/pool/shard002/C/0057901_cpNameLinux.c b/pool/shard002/C/0057901_cpNameLinux.c new file mode 100644 index 0000000000000000000000000000000000000000..09a4a567796b13b8faaf0b0a78affb367796ed8c --- /dev/null +++ b/pool/shard002/C/0057901_cpNameLinux.c @@ -0,0 +1,176 @@ +/********************************************************* + * Copyright (C) 1998 VMware, Inc. 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 version 2 and no 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 + * + *********************************************************/ + +/* + * cpNameLinux.c -- + * + * Linux implementation of cross-platform name conversion + * routines used by hgfs. [bac] + * + */ + +#if defined sun && !defined SOL9 +#include +#endif + +#include "cpName.h" +#include "cpNameInt.h" +#include "vm_assert.h" +#include "hgfsEscape.h" + + +/* + *---------------------------------------------------------------------- + * + * CPName_ConvertFrom -- + * + * Converts a cross-platform name representation into a string for + * use in the local filesystem. + * + * Results: + * Length (not including NUL termination) >= 0 of resulting + * string on success. + * Negative error on failure (the converted string did not fit in + * the buffer provided or the input was invalid). + * + * Side effects: + * None + * + *---------------------------------------------------------------------- + */ + +int +CPName_ConvertFrom(char const **bufIn, // IN/OUT: Input to convert + size_t *inSize, // IN/OUT: Size of input + size_t *outSize, // IN/OUT: Size of output buffer + char **bufOut) // IN/OUT: Output buffer +{ + ASSERT(bufIn); + ASSERT(inSize); + ASSERT(outSize); + ASSERT(bufOut); + + return CPNameEscapeAndConvertFrom(bufIn, inSize, outSize, bufOut, '/'); +} + + +/* + *---------------------------------------------------------------------- + * + * CPName_ConvertFromRoot -- + * + * Append the appropriate prefix to the output buffer for accessing + * the root of the local filesystem. CPName_ConvertFrom prepends + * leading path separators before each path component, but only + * when the next component has nonzero length, so we still need to + * special case this for Linux. + * + * The pointers and sizes are updated appropriately. + * + * Results: + * Status of name conversion + * + * Side effects: + * None + * + *---------------------------------------------------------------------- + */ + +HgfsNameStatus +CPName_ConvertFromRoot(char const **bufIn, // IN/OUT: Input to convert + size_t *inSize, // IN/OUT: Size of input + size_t *outSize, // IN/OUT: Size of output buffer + char **bufOut) // IN/OUT: Output buffer +{ + char const *next; + char *out; + int len; + + ASSERT(bufIn); + ASSERT(inSize); + ASSERT(outSize); + ASSERT(bufOut); + + out = *bufOut; + + /* + * Get first component + */ + len = CPName_GetComponent(*bufIn, *bufIn + *inSize, &next); + if (len < 0) { + Log("%s: get first component failed\n", __FUNCTION__); + return HGFS_NAME_STATUS_FAILURE; + } + + /* Space for leading '/' plus NUL termination */ + if (*outSize < len + 2) { + return HGFS_NAME_STATUS_FAILURE; + } + + /* Put a leading '/' in the output buffer either way */ + *out++ = '/'; + + memcpy(out, *bufIn, len); + out += len; + + /* NUL terminate */ + *out = '\0'; + + *inSize -= next - *bufIn; + *outSize -= out - *bufOut; + *bufIn = next; + *bufOut = out; + + return HGFS_NAME_STATUS_COMPLETE; +} + + +/* + *---------------------------------------------------------------------------- + * + * CPName_ConvertTo -- + * + * Wrapper function that calls the Linux implementation of _ConvertTo(). + * + * Makes a cross-platform name representation from the Linux path input + * string and writes it into the output buffer. + * If the name being converter may be a result a of name escaping the + * function performs unescaping. HGFS convention is to always exchange + * unescaped names between guest and host and to perform necessary + * name escaping on both ends. + * + * Results: + * On success, returns the number of bytes used in the + * cross-platform name, NOT including the final terminating NUL + * character. On failure, returns a negative error. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------------- + */ + +int +CPName_ConvertTo(char const *nameIn, // IN: Buf to convert + size_t bufOutSize, // IN: Size of the output buffer + char *bufOut) // OUT: Output buffer +{ + int result; + result = CPName_LinuxConvertTo(nameIn, bufOutSize, bufOut); + return result; +} diff --git a/pool/shard002/C/0057937_mmalomx_marks.c b/pool/shard002/C/0057937_mmalomx_marks.c new file mode 100644 index 0000000000000000000000000000000000000000..a645af65026f00de20a4fa9177b9f9abc3f1a5bb --- /dev/null +++ b/pool/shard002/C/0057937_mmalomx_marks.c @@ -0,0 +1,101 @@ +/* +Copyright (c) 2012, Broadcom Europe Ltd +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + * Neither the name of the copyright holder nor the + names of its contributors may be used to endorse or promote products + derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE 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. +*/ + +/** \file + * OpenMAX IL adaptation layer for MMAL - Marking related functions + * + * Note that we do not support buffer marks properly other than for conformance + * testing. For input ports, we just move the mark over to the output port. + */ + +#include "mmalomx.h" +#include "mmalomx_buffer.h" +#include "mmalomx_marks.h" +#include "mmalomx_commands.h" +#include "mmalomx_logging.h" + +#define MMALOMX_GET_MARK(port, mark) \ + mark = &port->marks[port->marks_first]; \ + port->marks_num--; \ + port->marks_first = ++port->marks_first == MAX_MARKS_NUM ? 0 : port->marks_first +#define MMALOMX_PUT_MARK(port, mark) \ + port->marks[(port->marks_first + port->marks_num) % MAX_MARKS_NUM] = *mark; \ + port->marks_num++; + +void mmalomx_mark_process_incoming(MMALOMX_COMPONENT_T *component, + MMALOMX_PORT_T *port, OMX_BUFFERHEADERTYPE *omx_buffer) +{ + /* Tag buffers with OMX marks */ + if (!omx_buffer->hMarkTargetComponent && port->marks_num > 0 && + port->direction == OMX_DirInput) + { + OMX_MARKTYPE *mark; + MMALOMX_GET_MARK(port, mark); + omx_buffer->hMarkTargetComponent = mark->hMarkTargetComponent; + omx_buffer->pMarkData = mark->pMarkData; + + mmalomx_callback_event_handler(component, OMX_EventCmdComplete, + OMX_CommandMarkBuffer, port->index, NULL); + } + /* We do not support buffer marks properly other than for conformance testing. + * For input ports, we just move the mark over to the output port. */ + if (port->direction == OMX_DirInput && omx_buffer->hMarkTargetComponent) + { + OMX_MARKTYPE mark = {omx_buffer->hMarkTargetComponent, omx_buffer->pMarkData}; + unsigned int i; + for (i = 0; i < component->ports_num; i++) + { + if (component->ports[i].direction != OMX_DirOutput || + component->ports[i].marks_num >= MAX_MARKS_NUM) + continue; + + MMALOMX_PUT_MARK((&component->ports[i]), (&mark)); + } + } +} + +void mmalomx_mark_process_outgoing(MMALOMX_COMPONENT_T *component, + MMALOMX_PORT_T *port, OMX_BUFFERHEADERTYPE *omx_buffer) +{ + /* Tag buffers with OMX marks */ + if (port->direction == OMX_DirOutput && + !omx_buffer->hMarkTargetComponent && port->marks_num) + { + OMX_MARKTYPE *mark; + MMALOMX_GET_MARK(port, mark); + omx_buffer->hMarkTargetComponent = mark->hMarkTargetComponent; + omx_buffer->pMarkData = mark->pMarkData; + } + /* Check if we need to trigger a Mark event */ + if (omx_buffer->hMarkTargetComponent && + omx_buffer->hMarkTargetComponent == (OMX_HANDLETYPE)&component->omx) + { + mmalomx_callback_event_handler(component, OMX_EventMark, 0, 0, omx_buffer->pMarkData); + omx_buffer->hMarkTargetComponent = NULL; + omx_buffer->pMarkData = NULL; + } +} diff --git a/pool/shard002/C/0057944_example.c b/pool/shard002/C/0057944_example.c new file mode 100644 index 0000000000000000000000000000000000000000..70be75178efe9cca13d59863dcbce2cb82856bc1 --- /dev/null +++ b/pool/shard002/C/0057944_example.c @@ -0,0 +1,38 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2020 The Stdlib Authors. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +#include "stdlib/stats/base/dstdev.h" +#include +#include + +int main() { + // Create a strided array: + double x[] = { 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0 }; + + // Specify the number of elements: + int64_t N = 4; + + // Specify the stride length: + int64_t stride = 2; + + // Compute the standard deviation: + double v = stdlib_strided_dstdev( N, 1, x, stride ); + + // Print the result: + printf( "sample standard deviation: %lf\n", v ); +} diff --git a/pool/shard002/C/0057973_square_svc.c b/pool/shard002/C/0057973_square_svc.c new file mode 100644 index 0000000000000000000000000000000000000000..e5b2e560e3c93ba051edf99558efb29b6d6fb1f8 --- /dev/null +++ b/pool/shard002/C/0057973_square_svc.c @@ -0,0 +1,91 @@ +/* + * Please do not edit this file. + * It was generated using rpcgen. + */ + +#include "square.h" +#include +#include +#include +#include +#include +#include +#include + +#ifndef SIG_PF +#define SIG_PF void(*)(int) +#endif + +static void +square_prog_1(struct svc_req *rqstp, register SVCXPRT *transp) +{ + union { + square_in squareprog_1_arg; + } argument; + char *result; + xdrproc_t _xdr_argument, _xdr_result; + char *(*local)(char *, struct svc_req *); + + switch (rqstp->rq_proc) { + case NULLPROC: + (void) svc_sendreply (transp, (xdrproc_t) xdr_void, (char *)NULL); + return; + + case SQUAREPROG: + _xdr_argument = (xdrproc_t) xdr_square_in; + _xdr_result = (xdrproc_t) xdr_square_out; + local = (char *(*)(char *, struct svc_req *)) squareprog_1_svc; + break; + + default: + svcerr_noproc (transp); + return; + } + memset ((char *)&argument, 0, sizeof (argument)); + if (!svc_getargs (transp, (xdrproc_t) _xdr_argument, (caddr_t) &argument)) { + svcerr_decode (transp); + return; + } + result = (*local)((char *)&argument, rqstp); + if (result != NULL && !svc_sendreply(transp, (xdrproc_t) _xdr_result, result)) { + svcerr_systemerr (transp); + } + if (!svc_freeargs (transp, (xdrproc_t) _xdr_argument, (caddr_t) &argument)) { + fprintf (stderr, "%s", "unable to free arguments"); + exit (1); + } + return; +} + +int +main (int argc, char **argv) +{ + register SVCXPRT *transp; + + pmap_unset (SQUARE_PROG, SQUARE_VERS); + + transp = svcudp_create(RPC_ANYSOCK); + if (transp == NULL) { + fprintf (stderr, "%s", "cannot create udp service."); + exit(1); + } + if (!svc_register(transp, SQUARE_PROG, SQUARE_VERS, square_prog_1, IPPROTO_UDP)) { + fprintf (stderr, "%s", "unable to register (SQUARE_PROG, SQUARE_VERS, udp)."); + exit(1); + } + + transp = svctcp_create(RPC_ANYSOCK, 0, 0); + if (transp == NULL) { + fprintf (stderr, "%s", "cannot create tcp service."); + exit(1); + } + if (!svc_register(transp, SQUARE_PROG, SQUARE_VERS, square_prog_1, IPPROTO_TCP)) { + fprintf (stderr, "%s", "unable to register (SQUARE_PROG, SQUARE_VERS, tcp)."); + exit(1); + } + + svc_run (); + fprintf (stderr, "%s", "svc_run returned"); + exit (1); + /* NOTREACHED */ +} diff --git a/pool/shard002/C/0057977_stm32_pwm_0.c b/pool/shard002/C/0057977_stm32_pwm_0.c new file mode 100644 index 0000000000000000000000000000000000000000..fcf4d29421d0145b8ac51a8bd319ab8b13ebfea2 --- /dev/null +++ b/pool/shard002/C/0057977_stm32_pwm_0.c @@ -0,0 +1,179 @@ +/*! + * Copyright (C) 2013 Uwe Bonnes (bon@elektron.ikp.physik.tu-darmstadt.de) + * + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holders nor the names of + * 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. + * + * For additional information see http://www.ethernut.de/ + */ + +/*! + * $Id: stm32_pwm_0.c 5388 2013-10-07 17:11:45Z u_bonnes $ + */ +#include +#include +#include +#include +#include +#include +#include +#include + +/* Compile code only when needed definitions are available */ +#if defined(STM32_PWM0_TIMER_ID) && defined(STM32_PWM0_PORT) && defined(STM32_PWM0_PIN)\ + && defined(STM32_PWM0_TIMER_CHANNEL) + +#if defined(STM32_PWM0_TIMER_ID) +#define STM32_PWM_TIMER_ID STM32_PWM0_TIMER_ID +#endif + +#if defined(STM32_PWM0_TIMER_CHANNEL) +#define STM32_PWM_TIMER_CHANNEL STM32_PWM0_TIMER_CHANNEL +#endif + +#if defined(STM32_PWM0_PORT) +#define STM32_PWM_PORT STM32_PWM0_PORT +#endif + +#if defined(STM32_PWM0_PIN) +#define STM32_PWM_PIN STM32_PWM0_PIN +#endif + +#if defined(STM32_PWM_TIMER_ID) +#undef STM32TIMER_ID +#define STM32TIMER_ID STM32_PWM_TIMER_ID +#include +#define STM32_PWM_BASE STM32TIMER_BASE +#define STM32_PWM_PCLK STM32TIMER_PCLK +#define STM32_PWM_CLK STM32TIMER_CLK +#define STM32_PWM_RST STM32TIMER_RST +#define STM32_PWM_NCH STM32TIMER_NCH +#define STM32_PWM_BTDR STM32TIMER_BTDR +#define STM32_PWM_AF STM32TIMER_AF(STM32_PWM_PORT, STM32_PWM_PIN) +#endif + +/* Use PWM Mode 1 (0x110 on OCxM), Only reload on update event (OCxPE set) */ +#if defined(STM32_PWM_TIMER_CHANNEL) +#if STM32_PWM_TIMER_CHANNEL == 1 +#define STM32_PWM_OUTPUT_EN() CM3BBREG(STM32_PWM_BASE, TIM_TypeDef, CCER , _BI32(TIM_CCER_CC1E)) = 1 +#define STM32_PWM_MODE() TIM_CCMode1(STM32_PWM_BASE) = TIM_CCMR1_OC1M_2|TIM_CCMR1_OC1M_1|TIM_CCMR1_OC1PE +#define STM32_PWM_VALUE TIM_Compare1(STM32_PWM_BASE) +#elif STM32_PWM_TIMER_CHANNEL == 2 +#define STM32_PWM_OUTPUT_EN() CM3BBREG(STM32_PWM_BASE, TIM_TypeDef, CCER , _BI32(TIM_CCER_CC2E)) = 1 +#define STM32_PWM_MODE() TIM_CCMode1(STM32_PWM_BASE) = TIM_CCMR1_OC2M_2|TIM_CCMR1_OC2M_1|TIM_CCMR1_OC2PE +#define STM32_PWM_VALUE TIM_Compare2(STM32_PWM_BASE) +#elif STM32_PWM_TIMER_CHANNEL == 3 +#define STM32_PWM_OUTPUT_EN() CM3BBREG(STM32_PWM_BASE, TIM_TypeDef, CCER , _BI32(TIM_CCER_CC3E)) = 1 +#define STM32_PWM_MODE() TIM_CCMode2(STM32_PWM_BASE) = TIM_CCMR2_OC3M_2|TIM_CCMR2_OC3M_1|TIM_CCMR2_OC3PE +#define STM32_PWM_VALUE TIM_Compare3(STM32_PWM_BASE) +#elif STM32_PWM_TIMER_CHANNEL == 4 +#define STM32_PWM_OUTPUT_EN() CM3BBREG(STM32_PWM_BASE, TIM_TypeDef, CCER , _BI32(TIM_CCER_CC4E)) = 1 +#define STM32_PWM_MODE() TIM_CCMode2(STM32_PWM_BASE) = TIM_CCMR2_OC4M_2|TIM_CCMR2_OC4M_1|TIM_CCMR2_OC4PE +#define STM32_PWM_VALUE TIM_Compare4(STM32_PWM_BASE) +#else +#warning Unknown PWM Timer Channel +#endif +#endif + +/*! + * \brief Initialize a PWM output + * + * Only few checks is done here! + * + * \param freq Pointer to requested frequency in Hz, on return the achieved PWM frequency. + * Function fails is achievable frequency is of 25 % of requested frequency. + * \param bits Bits of the PWM set value. + * + * \return 0 on success, -1 else. + */ + +int stm32_pwm0_init(uint32_t *freq, int bits) +{ +#if (STM32_PWM_TIMER_CHANNEL == 0) || (STM32_PWM_TIMER_CHANNEL > STM32_PWM_NCH) + /* We requested a channel not available */ + return -1; +#else +/* Try to find prescaler value that gives requested frequency with 25 % tolerance */ + uint32_t pclk = STM32_PWM_PCLK; + uint32_t psc0 = ((pclk <<1)/ (*freq)) >> bits; + uint32_t psc1 = (pclk / (*freq)) >> bits; + + if (psc0 & 1) psc1++; /* Round up*/ + *freq = pclk/psc1 >> bits; + if (( 5 * (*freq << bits) < 4 * pclk) || ( 5 * pclk < 4 * (*freq << bits))) + return -1; + STM32_PWM_CLK = 1; + STM32_PWM_RST = 1; + STM32_PWM_RST = 0; + /* All registers now reset*/ + STM32_PWM_OUTPUT_EN(); + STM32_PWM_MODE(); + TIM_AutoReloadValue(STM32_PWM_BASE) = (1< TIM_AutoReloadValue(STM32_PWM_BASE)) + /* Clip at maximum*/ + STM32_PWM_VALUE = TIM_AutoReloadValue(STM32_PWM_BASE); + else + STM32_PWM_VALUE = value; +} + +/*! + * \brief Return current set PWM value + * + * + * \return Set PWM value. + */ +uint32_t stm32_pwm0_get(void) +{ + return STM32_PWM_VALUE; +} + +#endif diff --git a/pool/shard002/C/0057980_elm_plug.c b/pool/shard002/C/0057980_elm_plug.c new file mode 100644 index 0000000000000000000000000000000000000000..38bc0e3a1f32ff0e1bb8498e9dc13722fbeb24ab --- /dev/null +++ b/pool/shard002/C/0057980_elm_plug.c @@ -0,0 +1,255 @@ +#ifdef HAVE_CONFIG_H +# include "elementary_config.h" +#endif + +#include + +#include "elm_priv.h" +#include "elm_widget_plug.h" + +EAPI Eo_Op ELM_OBJ_PLUG_BASE_ID = EO_NOOP; + +#define MY_CLASS ELM_OBJ_PLUG_CLASS + +#define MY_CLASS_NAME "Elm_Plug" +#define MY_CLASS_NAME_LEGACY "elm_plug" + +static const char PLUG_KEY[] = "__Plug_Ecore_Evas"; + +static const char SIG_CLICKED[] = "clicked"; +static const char SIG_IMAGE_DELETED[] = "image,deleted"; +static const char SIG_IMAGE_RESIZED[] = "image,resized"; +static const Evas_Smart_Cb_Description _smart_callbacks[] = { + {SIG_CLICKED, ""}, + {SIG_IMAGE_DELETED, ""}, + {SIG_IMAGE_RESIZED, "ii"}, + {NULL, NULL} +}; + +static void +_sizing_eval(Evas_Object *obj EINA_UNUSED) +{ + //Evas_Coord minw = -1, minh = -1, maxw = -1, maxh = -1; + + //TODO: get socket object size + //this reset plug's min/max size + //evas_object_size_hint_min_set(obj, minw, minh); + //evas_object_size_hint_max_set(obj, maxw, maxh); +} + +static void +_elm_plug_disconnected(Ecore_Evas *ee) +{ + Evas_Object *plug = ecore_evas_data_get(ee, PLUG_KEY); + EINA_SAFETY_ON_NULL_RETURN(plug); + evas_object_smart_callback_call(plug, SIG_IMAGE_DELETED, NULL); + /* TODO: was a typo. Deprecated, remove in future releases: */ + evas_object_smart_callback_call(plug, "image.deleted", NULL); +} + +static void +_elm_plug_resized(Ecore_Evas *ee) +{ + Evas_Coord_Size size = {0, 0}; + Evas_Object *plug = ecore_evas_data_get(ee, PLUG_KEY); + EINA_SAFETY_ON_NULL_RETURN(plug); + + ecore_evas_geometry_get(ee, NULL, NULL, &(size.w), &(size.h)); + evas_object_smart_callback_call(plug, SIG_IMAGE_RESIZED, &size); +} + +static void +_elm_plug_smart_on_focus(Eo *obj, void *_pd EINA_UNUSED, va_list *list) +{ + Eina_Bool *ret = va_arg(*list, Eina_Bool *); + Eina_Bool int_ret = EINA_FALSE; + + ELM_WIDGET_DATA_GET_OR_RETURN(obj, wd); + + if (ret) *ret = EINA_FALSE; + + eo_do_super(obj, MY_CLASS, elm_wdg_on_focus(&int_ret)); + if (!int_ret) return; + + if (elm_widget_focus_get(obj)) + { + evas_object_focus_set(wd->resize_obj, EINA_TRUE); + } + else + { + evas_object_focus_set(wd->resize_obj, EINA_FALSE); + } + + if (ret) *ret = EINA_TRUE; +} + +static void +_elm_plug_smart_theme(Eo *obj, void *_pd EINA_UNUSED, va_list *list) +{ + Eina_Bool *ret = va_arg(*list, Eina_Bool *); + if (ret) *ret = EINA_FALSE; + Eina_Bool int_ret = EINA_FALSE; + + eo_do_super(obj, MY_CLASS, elm_wdg_theme_apply(&int_ret)); + if (!int_ret) return; + + _sizing_eval(obj); + + if (ret) *ret = EINA_TRUE; +} + +static void +_on_mouse_up(void *data, + Evas *e EINA_UNUSED, + Evas_Object *obj EINA_UNUSED, + void *event_info) +{ + Evas_Event_Mouse_Up *ev = event_info; + + if (ev->button != 1) return; + if (ev->event_flags & EVAS_EVENT_FLAG_ON_HOLD) return; + + evas_object_smart_callback_call(data, SIG_CLICKED, NULL); +} + +static void +_elm_plug_smart_add(Eo *obj, void *_pd EINA_UNUSED, va_list *list EINA_UNUSED) +{ + Evas_Object *p_obj; + Ecore_Evas *ee; + ELM_WIDGET_DATA_GET_OR_RETURN(obj, wd); + + eo_do_super(obj, MY_CLASS, evas_obj_smart_add()); + elm_widget_sub_object_parent_add(obj); + + ee = ecore_evas_ecore_evas_get(evas_object_evas_get(obj)); + if (!ee) return; + + p_obj = ecore_evas_extn_plug_new(ee); + if (!p_obj) return; + + elm_widget_resize_object_set(obj, p_obj, EINA_TRUE); + + evas_object_event_callback_add + (wd->resize_obj, EVAS_CALLBACK_MOUSE_UP, _on_mouse_up, + obj); + + elm_widget_can_focus_set(obj, EINA_FALSE); + _sizing_eval(obj); +} + +EAPI Evas_Object * +elm_plug_add(Evas_Object *parent) +{ + EINA_SAFETY_ON_NULL_RETURN_VAL(parent, NULL); + Evas_Object *obj = eo_add(MY_CLASS, parent); + eo_unref(obj); + return obj; +} + +static void +_constructor(Eo *obj, void *_pd EINA_UNUSED, va_list *list EINA_UNUSED) +{ + eo_do_super(obj, MY_CLASS, eo_constructor()); + eo_do(obj, + evas_obj_type_set(MY_CLASS_NAME_LEGACY), + evas_obj_smart_callbacks_descriptions_set(_smart_callbacks, NULL)); +} + +EAPI Evas_Object * +elm_plug_image_object_get(const Evas_Object *obj) +{ + ELM_PLUG_CHECK(obj) NULL; + Evas_Object *ret = NULL; + eo_do((Eo *) obj, elm_obj_plug_image_object_get(&ret)); + return ret; +} + +static void +_image_object_get(Eo *obj, void *_pd EINA_UNUSED, va_list *list) +{ + Evas_Object **ret = va_arg(*list, Evas_Object **); + ELM_WIDGET_DATA_GET_OR_RETURN(obj, wd); + *ret = wd->resize_obj; +} + +EAPI Eina_Bool +elm_plug_connect(Evas_Object *obj, + const char *svcname, + int svcnum, + Eina_Bool svcsys) +{ + Eina_Bool ret = EINA_FALSE; + eo_do(obj, elm_obj_plug_connect(svcname, svcnum, svcsys, &ret)); + return ret; +} + +static void +_connect(Eo *obj, void *_pd EINA_UNUSED, va_list *list) +{ + const char *svcname = va_arg(*list, const char *); + int svcnum = va_arg(*list, int); + Eina_Bool svcsys = va_arg(*list, int); + Eina_Bool *ret = va_arg(*list, Eina_Bool *); + if (ret) *ret = EINA_FALSE; + + Evas_Object *plug_img = NULL; + + ELM_PLUG_CHECK(obj); + + plug_img = elm_plug_image_object_get(obj); + if (!plug_img) return; + + if (ecore_evas_extn_plug_connect(plug_img, svcname, svcnum, svcsys)) + { + Ecore_Evas *ee = NULL; + ee = ecore_evas_object_ecore_evas_get(plug_img); + if (!ee) return; + + ecore_evas_data_set(ee, PLUG_KEY, obj); + ecore_evas_callback_delete_request_set(ee, _elm_plug_disconnected); + ecore_evas_callback_resize_set(ee, _elm_plug_resized); + if (ret) *ret = EINA_TRUE; + } +} + +static void +_class_constructor(Eo_Class *klass) +{ + const Eo_Op_Func_Description func_desc[] = { + EO_OP_FUNC(EO_BASE_ID(EO_BASE_SUB_ID_CONSTRUCTOR), _constructor), + + EO_OP_FUNC(EVAS_OBJ_SMART_ID(EVAS_OBJ_SMART_SUB_ID_ADD), _elm_plug_smart_add), + + EO_OP_FUNC(ELM_WIDGET_ID(ELM_WIDGET_SUB_ID_THEME_APPLY), _elm_plug_smart_theme), + + EO_OP_FUNC(ELM_WIDGET_ID(ELM_WIDGET_SUB_ID_ON_FOCUS), + _elm_plug_smart_on_focus), + + EO_OP_FUNC(ELM_OBJ_PLUG_ID(ELM_OBJ_PLUG_SUB_ID_IMAGE_OBJECT_GET), _image_object_get), + EO_OP_FUNC(ELM_OBJ_PLUG_ID(ELM_OBJ_PLUG_SUB_ID_CONNECT), _connect), + + EO_OP_FUNC_SENTINEL + }; + eo_class_funcs_set(klass, func_desc); + + evas_smart_legacy_type_register(MY_CLASS_NAME_LEGACY, klass); +} + +static const Eo_Op_Description op_desc[] = { + EO_OP_DESCRIPTION(ELM_OBJ_PLUG_SUB_ID_IMAGE_OBJECT_GET, "Get the basic Evas_Image object from this object (widget)."), + EO_OP_DESCRIPTION(ELM_OBJ_PLUG_SUB_ID_CONNECT, "Connect a plug widget to service provided by socket image."), + EO_OP_DESCRIPTION_SENTINEL +}; + +static const Eo_Class_Description class_desc = { + EO_VERSION, + MY_CLASS_NAME, + EO_CLASS_TYPE_REGULAR, + EO_CLASS_DESCRIPTION_OPS(&ELM_OBJ_PLUG_BASE_ID, op_desc, ELM_OBJ_PLUG_SUB_ID_LAST), + NULL, + 0, + _class_constructor, + NULL +}; +EO_DEFINE_CLASS(elm_obj_plug_class_get, &class_desc, ELM_OBJ_WIDGET_CLASS, NULL); diff --git a/pool/shard002/C/0057985_mq_notify.c b/pool/shard002/C/0057985_mq_notify.c new file mode 100644 index 0000000000000000000000000000000000000000..be614e92cae9e7e44645516c9ceb51db44d00ad2 --- /dev/null +++ b/pool/shard002/C/0057985_mq_notify.c @@ -0,0 +1,310 @@ +/* Copyright (C) 2004, 2005, 2008, 2011 Free Software Foundation, Inc. + This file is part of the GNU C Library. + Contribute by Ulrich Drepper , 2004. + + The GNU C Library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + The GNU C Library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with the GNU C Library; if not, see + . */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +#ifdef __NR_mq_notify + +/* Defined in the kernel headers: */ +#define NOTIFY_COOKIE_LEN 32 /* Length of the cookie used. */ +#define NOTIFY_WOKENUP 1 /* Code for notifcation. */ +#define NOTIFY_REMOVED 2 /* Code for closed message queue + of de-notifcation. */ + + +/* Data structure for the queued notification requests. */ +union notify_data +{ + struct + { + void (*fct) (union sigval); /* The function to run. */ + union sigval param; /* The parameter to pass. */ + pthread_attr_t *attr; /* Attributes to create the thread with. */ + /* NB: on 64-bit machines the struct as a size of 24 bytes. Which means + byte 31 can still be used for returning the status. */ + }; + char raw[NOTIFY_COOKIE_LEN]; +}; + + +/* Keep track of the initialization. */ +static pthread_once_t once = PTHREAD_ONCE_INIT; + + +/* The netlink socket. */ +static int netlink_socket = -1; + + +/* Barrier used to make sure data passed to the new thread is not + resused by the parent. */ +static pthread_barrier_t notify_barrier; + + +/* Modify the signal mask. We move this into a separate function so + that the stack space needed for sigset_t is not deducted from what + the thread can use. */ +static int +__attribute__ ((noinline)) +change_sigmask (int how, sigset_t *oss) +{ + sigset_t ss; + sigfillset (&ss); + return pthread_sigmask (how, &ss, oss); +} + + +/* The function used for the notification. */ +static void * +notification_function (void *arg) +{ + /* Copy the function and parameter so that the parent thread can go + on with its life. */ + volatile union notify_data *data = (volatile union notify_data *) arg; + void (*fct) (union sigval) = data->fct; + union sigval param = data->param; + + /* Let the parent go. */ + (void) pthread_barrier_wait (¬ify_barrier); + + /* Make the thread detached. */ + (void) pthread_detach (pthread_self ()); + + /* The parent thread has all signals blocked. This is probably a + bit surprising for this thread. So we unblock all of them. */ + (void) change_sigmask (SIG_UNBLOCK, NULL); + + /* Now run the user code. */ + fct (param); + + /* And we are done. */ + return NULL; +} + + +/* Helper thread. */ +static void * +helper_thread (void *arg) +{ + while (1) + { + union notify_data data; + + ssize_t n = recv (netlink_socket, &data, sizeof (data), + MSG_NOSIGNAL | MSG_WAITALL); + if (n < NOTIFY_COOKIE_LEN) + continue; + + if (data.raw[NOTIFY_COOKIE_LEN - 1] == NOTIFY_WOKENUP) + { + /* Just create the thread as instructed. There is no way to + report a problem with creating a thread. */ + pthread_t th; + if (__builtin_expect (pthread_create (&th, data.attr, + notification_function, &data) + == 0, 0)) + /* Since we passed a pointer to DATA to the new thread we have + to wait until it is done with it. */ + (void) pthread_barrier_wait (¬ify_barrier); + } + else if (data.raw[NOTIFY_COOKIE_LEN - 1] == NOTIFY_REMOVED) + /* The only state we keep is the copy of the thread attributes. */ + free (data.attr); + } + return NULL; +} + + +static void +reset_once (void) +{ + once = PTHREAD_ONCE_INIT; +} + + +static void +init_mq_netlink (void) +{ +#ifdef SOCK_CLOEXEC +# ifndef __ASSUME_SOCK_CLOEXEC + static int have_sock_cloexec; +# else +# define have_sock_cloexec 1 +# endif +#else +# define have_sock_cloexec -1 +# define SOCK_CLOEXEC 0 +#endif + + /* This code might be called a second time after fork(). The file + descriptor is inherited from the parent. */ + if (netlink_socket == -1) + { + /* Just a normal netlink socket, not bound. */ + if (have_sock_cloexec >= 0) + { + netlink_socket = socket (AF_NETLINK, SOCK_RAW | SOCK_CLOEXEC, 0); +#if defined SOCK_CLOEXEC && !defined __ASSUME_SOCK_CLOEXEC + if (have_sock_cloexec == 0) + have_sock_cloexec = (netlink_socket != -1 || errno != EINVAL + ? 1 : -1); +#endif + } + if (have_sock_cloexec < 0) + netlink_socket = socket (AF_NETLINK, SOCK_RAW, 0); + /* No need to do more if we have no socket. */ + if (netlink_socket == -1) + return; + + /* Make sure the descriptor is closed on exec. */ + if (have_sock_cloexec < 0 + && fcntl (netlink_socket, F_SETFD, FD_CLOEXEC) != 0) + goto errout; + } + + int err = 1; + + /* Initialize the barrier. */ + if (__builtin_expect (pthread_barrier_init (¬ify_barrier, NULL, 2) == 0, + 0)) + { + /* Create the helper thread. */ + pthread_attr_t attr; + (void) pthread_attr_init (&attr); + (void) pthread_attr_setdetachstate (&attr, PTHREAD_CREATE_DETACHED); + /* We do not need much stack space, the bare minimum will be enough. */ + (void) pthread_attr_setstacksize (&attr, __pthread_get_minstack (&attr)); + + /* Temporarily block all signals so that the newly created + thread inherits the mask. */ + sigset_t oss; + int have_no_oss = change_sigmask (SIG_BLOCK, &oss); + + pthread_t th; + err = pthread_create (&th, &attr, helper_thread, NULL); + + /* Reset the signal mask. */ + if (!have_no_oss) + pthread_sigmask (SIG_SETMASK, &oss, NULL); + + (void) pthread_attr_destroy (&attr); + + if (err == 0) + { + static int added_atfork; + + if (added_atfork == 0 + && pthread_atfork (NULL, NULL, reset_once) != 0) + { + /* The child thread will call recv() which is a + cancellation point. */ + (void) pthread_cancel (th); + err = 1; + } + else + added_atfork = 1; + } + } + + if (err != 0) + { + errout: + close_not_cancel_no_status (netlink_socket); + netlink_socket = -1; + } +} + + +/* Register notification upon message arrival to an empty message queue + MQDES. */ +int +mq_notify (mqd_t mqdes, const struct sigevent *notification) +{ + /* Make sure the type is correctly defined. */ + assert (sizeof (union notify_data) == NOTIFY_COOKIE_LEN); + + /* Special treatment needed for SIGEV_THREAD. */ + if (notification == NULL || notification->sigev_notify != SIGEV_THREAD) + return INLINE_SYSCALL (mq_notify, 2, mqdes, notification); + + /* The kernel cannot directly start threads. This will have to be + done at userlevel. Since we cannot start threads from signal + handlers we have to create a dedicated thread which waits for + notifications for arriving messages and creates threads in + response. */ + + /* Initialize only once. */ + pthread_once (&once, init_mq_netlink); + + /* If we cannot create the netlink socket we cannot provide + SIGEV_THREAD support. */ + if (__builtin_expect (netlink_socket == -1, 0)) + { + __set_errno (ENOSYS); + return -1; + } + + /* Create the cookie. It will hold almost all the state. */ + union notify_data data; + memset (&data, '\0', sizeof (data)); + data.fct = notification->sigev_notify_function; + data.param = notification->sigev_value; + + if (notification->sigev_notify_attributes != NULL) + { + /* The thread attribute has to be allocated separately. */ + data.attr = (pthread_attr_t *) malloc (sizeof (pthread_attr_t)); + if (data.attr == NULL) + return -1; + + memcpy (data.attr, notification->sigev_notify_attributes, + sizeof (pthread_attr_t)); + } + + /* Construct the new request. */ + struct sigevent se; + se.sigev_notify = SIGEV_THREAD; + se.sigev_signo = netlink_socket; + se.sigev_value.sival_ptr = &data; + + /* Tell the kernel. */ + int retval = INLINE_SYSCALL (mq_notify, 2, mqdes, &se); + + /* If it failed, free the allocated memory. */ + if (__builtin_expect (retval != 0, 0)) + free (data.attr); + + return retval; +} + +#else +# include +#endif diff --git a/pool/shard002/C/0057986_PolySearcher.c b/pool/shard002/C/0057986_PolySearcher.c new file mode 100644 index 0000000000000000000000000000000000000000..79f1831f9046b85ca5b1f78c28b2847b9b69fa72 --- /dev/null +++ b/pool/shard002/C/0057986_PolySearcher.c @@ -0,0 +1,194 @@ +/* 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. + */ + +#define C_LUCY_POLYSEARCHER +#include "Lucy/Util/ToolSet.h" + +#include "Lucy/Search/PolySearcher.h" + +#include "Lucy/Document/HitDoc.h" +#include "Lucy/Index/DocVector.h" +#include "Lucy/Index/PolyReader.h" +#include "Lucy/Plan/Schema.h" +#include "Lucy/Search/Collector.h" +#include "Lucy/Search/HitQueue.h" +#include "Lucy/Search/Query.h" +#include "Lucy/Search/MatchDoc.h" +#include "Lucy/Search/Matcher.h" +#include "Lucy/Search/Searcher.h" +#include "Lucy/Search/SortSpec.h" +#include "Lucy/Search/TopDocs.h" +#include "Lucy/Search/Compiler.h" + +PolySearcher* +PolySearcher_new(Schema *schema, Vector *searchers) { + PolySearcher *self = (PolySearcher*)Class_Make_Obj(POLYSEARCHER); + return PolySearcher_init(self, schema, searchers); +} + +PolySearcher* +PolySearcher_init(PolySearcher *self, Schema *schema, Vector *searchers) { + const uint32_t num_searchers = Vec_Get_Size(searchers); + int32_t *starts_array = (int32_t*)MALLOCATE(num_searchers * sizeof(int32_t)); + int32_t doc_max = 0; + + Searcher_init((Searcher*)self, schema); + PolySearcherIVARS *const ivars = PolySearcher_IVARS(self); + ivars->searchers = (Vector*)INCREF(searchers); + ivars->starts = NULL; // Safe cleanup. + + for (uint32_t i = 0; i < num_searchers; i++) { + Searcher *searcher + = (Searcher*)CERTIFY(Vec_Fetch(searchers, i), SEARCHER); + Schema *candidate = Searcher_Get_Schema(searcher); + Class *orig_class = Schema_get_class(schema); + Class *candidate_class = Schema_get_class(candidate); + + // Confirm that searchers all use the same schema. + if (orig_class != candidate_class) { + THROW(ERR, "Conflicting schemas: '%o', '%o'", + Schema_get_class_name(schema), + Schema_get_class_name(candidate)); + } + + // Derive doc_max and relative start offsets. + starts_array[i] = (int32_t)doc_max; + doc_max += Searcher_Doc_Max(searcher); + } + + ivars->doc_max = doc_max; + ivars->starts = I32Arr_new_steal(starts_array, num_searchers); + + return self; +} + +void +PolySearcher_Destroy_IMP(PolySearcher *self) { + PolySearcherIVARS *const ivars = PolySearcher_IVARS(self); + DECREF(ivars->searchers); + DECREF(ivars->starts); + SUPER_DESTROY(self, POLYSEARCHER); +} + +HitDoc* +PolySearcher_Fetch_Doc_IMP(PolySearcher *self, int32_t doc_id) { + PolySearcherIVARS *const ivars = PolySearcher_IVARS(self); + uint32_t tick = PolyReader_sub_tick(ivars->starts, doc_id); + Searcher *searcher = (Searcher*)Vec_Fetch(ivars->searchers, tick); + int32_t offset = I32Arr_Get(ivars->starts, tick); + if (!searcher) { THROW(ERR, "Invalid doc id: %i32", doc_id); } + HitDoc *hit_doc = Searcher_Fetch_Doc(searcher, doc_id - offset); + HitDoc_Set_Doc_ID(hit_doc, doc_id); + return hit_doc; +} + +DocVector* +PolySearcher_Fetch_Doc_Vec_IMP(PolySearcher *self, int32_t doc_id) { + PolySearcherIVARS *const ivars = PolySearcher_IVARS(self); + uint32_t tick = PolyReader_sub_tick(ivars->starts, doc_id); + Searcher *searcher = (Searcher*)Vec_Fetch(ivars->searchers, tick); + int32_t start = I32Arr_Get(ivars->starts, tick); + if (!searcher) { THROW(ERR, "Invalid doc id: %i32", doc_id); } + return Searcher_Fetch_Doc_Vec(searcher, doc_id - start); +} + +int32_t +PolySearcher_Doc_Max_IMP(PolySearcher *self) { + return PolySearcher_IVARS(self)->doc_max; +} + +uint32_t +PolySearcher_Doc_Freq_IMP(PolySearcher *self, String *field, Obj *term) { + PolySearcherIVARS *const ivars = PolySearcher_IVARS(self); + uint32_t doc_freq = 0; + for (uint32_t i = 0, max = Vec_Get_Size(ivars->searchers); i < max; i++) { + Searcher *searcher = (Searcher*)Vec_Fetch(ivars->searchers, i); + doc_freq += Searcher_Doc_Freq(searcher, field, term); + } + return doc_freq; +} + +static void +S_modify_doc_ids(Vector *match_docs, int32_t base) { + for (uint32_t i = 0, max = Vec_Get_Size(match_docs); i < max; i++) { + MatchDoc *match_doc = (MatchDoc*)Vec_Fetch(match_docs, i); + int32_t new_doc_id = MatchDoc_Get_Doc_ID(match_doc) + base; + MatchDoc_Set_Doc_ID(match_doc, new_doc_id); + } +} + +TopDocs* +PolySearcher_Top_Docs_IMP(PolySearcher *self, Query *query, + uint32_t num_wanted, SortSpec *sort_spec) { + PolySearcherIVARS *const ivars = PolySearcher_IVARS(self); + Schema *schema = PolySearcher_Get_Schema(self); + Vector *searchers = ivars->searchers; + I32Array *starts = ivars->starts; + HitQueue *hit_q = sort_spec + ? HitQ_new(schema, sort_spec, num_wanted) + : HitQ_new(NULL, NULL, num_wanted); + uint32_t total_hits = 0; + Compiler *compiler = Query_is_a(query, COMPILER) + ? ((Compiler*)INCREF(query)) + : Query_Make_Compiler(query, (Searcher*)self, + Query_Get_Boost(query), + false); + + for (uint32_t i = 0, max = Vec_Get_Size(searchers); i < max; i++) { + Searcher *searcher = (Searcher*)Vec_Fetch(searchers, i); + int32_t base = I32Arr_Get(starts, i); + TopDocs *top_docs = Searcher_Top_Docs(searcher, (Query*)compiler, + num_wanted, sort_spec); + Vector *sub_match_docs = TopDocs_Get_Match_Docs(top_docs); + + total_hits += TopDocs_Get_Total_Hits(top_docs); + + S_modify_doc_ids(sub_match_docs, base); + for (uint32_t j = 0, jmax = Vec_Get_Size(sub_match_docs); j < jmax; j++) { + MatchDoc *match_doc = (MatchDoc*)Vec_Fetch(sub_match_docs, j); + if (!HitQ_Insert(hit_q, INCREF(match_doc))) { break; } + } + + DECREF(top_docs); + } + + Vector *match_docs = HitQ_Pop_All(hit_q); + TopDocs *retval = TopDocs_new(match_docs, total_hits); + + DECREF(match_docs); + DECREF(compiler); + DECREF(hit_q); + return retval; +} + + +void +PolySearcher_Collect_IMP(PolySearcher *self, Query *query, + Collector *collector) { + PolySearcherIVARS *const ivars = PolySearcher_IVARS(self); + Vector *const searchers = ivars->searchers; + I32Array *starts = ivars->starts; + + for (uint32_t i = 0, max = Vec_Get_Size(searchers); i < max; i++) { + int32_t start = I32Arr_Get(starts, i); + Searcher *searcher = (Searcher*)Vec_Fetch(searchers, i); + OffsetCollector *offset_coll = OffsetColl_new(collector, start); + Searcher_Collect(searcher, query, (Collector*)offset_coll); + DECREF(offset_coll); + } +} + + diff --git a/pool/shard002/C/0057996_MP+PPO764.c b/pool/shard002/C/0057996_MP+PPO764.c new file mode 100644 index 0000000000000000000000000000000000000000..50fa0c3f1996750616871a18a468f426de06bbcb --- /dev/null +++ b/pool/shard002/C/0057996_MP+PPO764.c @@ -0,0 +1,66 @@ +/* Copyright (C) 2018 Magnus Lång and Tuan Phong Ngo + * This benchmark is part of SWSC */ + +#include +#include +#include +#include + +atomic_int vars[3]; +atomic_int atom_1_r1_1; +atomic_int atom_1_r9_1; + +void *t0(void *arg){ +label_1:; + atomic_store_explicit(&vars[0], 2, memory_order_seq_cst); + + atomic_store_explicit(&vars[1], 1, memory_order_seq_cst); + return NULL; +} + +void *t1(void *arg){ +label_2:; + int v2_r1 = atomic_load_explicit(&vars[1], memory_order_seq_cst); + int v3_cmpeq = (v2_r1 == v2_r1); + if (v3_cmpeq) goto lbl_LC00; else goto lbl_LC00; +lbl_LC00:; + atomic_store_explicit(&vars[2], 1, memory_order_seq_cst); + int v5_r5 = atomic_load_explicit(&vars[2], memory_order_seq_cst); + int v7_r6 = atomic_load_explicit(&vars[2], memory_order_seq_cst); + int v8_cmpeq = (v7_r6 == v7_r6); + if (v8_cmpeq) goto lbl_LC01; else goto lbl_LC01; +lbl_LC01:; + atomic_store_explicit(&vars[0], 1, memory_order_seq_cst); + int v10_r9 = atomic_load_explicit(&vars[0], memory_order_seq_cst); + int v17 = (v2_r1 == 1); + atomic_store_explicit(&atom_1_r1_1, v17, memory_order_seq_cst); + int v18 = (v10_r9 == 1); + atomic_store_explicit(&atom_1_r9_1, v18, memory_order_seq_cst); + return NULL; +} + +int main(int argc, char *argv[]){ + pthread_t thr0; + pthread_t thr1; + + atomic_init(&vars[1], 0); + atomic_init(&vars[2], 0); + atomic_init(&vars[0], 0); + atomic_init(&atom_1_r1_1, 0); + atomic_init(&atom_1_r9_1, 0); + + pthread_create(&thr0, NULL, t0, NULL); + pthread_create(&thr1, NULL, t1, NULL); + + pthread_join(thr0, NULL); + pthread_join(thr1, NULL); + + int v11 = atomic_load_explicit(&vars[0], memory_order_seq_cst); + int v12 = (v11 == 2); + int v13 = atomic_load_explicit(&atom_1_r1_1, memory_order_seq_cst); + int v14 = atomic_load_explicit(&atom_1_r9_1, memory_order_seq_cst); + int v15_conj = v13 & v14; + int v16_conj = v12 & v15_conj; + if (v16_conj == 1) assert(0); + return 0; +} diff --git a/pool/shard002/C/0058017_helloworld.c b/pool/shard002/C/0058017_helloworld.c new file mode 100644 index 0000000000000000000000000000000000000000..7958d3808aa2fa2c967acc6411c3d7eafe79b0ca --- /dev/null +++ b/pool/shard002/C/0058017_helloworld.c @@ -0,0 +1,42 @@ +/* + * You can use safely use mpi4py between multiple + * Py_Initialize()/Py_Finalize() calls ... + * but do not blame me for the memory leaks ;-) + * + */ + +#include +#include + +const char helloworld[] = \ + "from mpi4py import MPI \n" + "hwmess = 'Hello, World! I am process %d of %d on %s.' \n" + "myrank = MPI.COMM_WORLD.Get_rank() \n" + "nprocs = MPI.COMM_WORLD.Get_size() \n" + "procnm = MPI.Get_processor_name() \n" + "print (hwmess % (myrank, nprocs, procnm)) \n" + ""; + +int main(int argc, char *argv[]) +{ + int i,n=5; + + MPI_Init(&argc, &argv); + + for (i=0; iname = strdup(name); + this->value = strdup(value); + return this; +} + +void dictionnary_entry_delete(dictionnary_entry * this) { + free(this->name); + free(this->value); + free(this); +} + +void dictionnary_entry_delete_void(void * entry) { + dictionnary_entry_delete((dictionnary_entry *) entry); +} + +dictionnary * dictionnary_new() { + dictionnary * dic = malloc(sizeof ( dictionnary)); + dictionnary_init(dic); + return dic; +} + +void dictionnary_init(dictionnary* this) { + linkedlist_init(& this->list); +} + +void dictionnary_add(dictionnary * this, const char* name, const char* value) { + linkedlist_insert_first(& this->list, dictionnary_entry_new(name, value)); +} + +void dictionnary_put(dictionnary* this, const char* name, const char* value) { + dictionnary_rmv(this, name); + dictionnary_add(this, name, value); +} + +dictionnary_entry * dictionnary_get_entry(dictionnary* this, const char* name) { + linkedlist_node * node = this->list.first; + while (node) { + dictionnary_entry * entry = (dictionnary_entry *) node->element; + if (!strcmp(name, entry->name)) + return entry; + node = node->next; + } + return NULL; +} + +char * dictionnary_get_value(dictionnary* this, const char* name) { + dictionnary_entry * entry = dictionnary_get_entry( this, name ); + return entry ? entry->value : NULL; +} + +dictionnary_entry ** dictionnary_get_all(dictionnary* this) { + dictionnary_entry ** array = (dictionnary_entry **) linkedlist_get_array( & this->list ); + + return array; +} + +unsigned char dictionnary_rmv(dictionnary * this, const char * name) { + linkedlist_node * node = this->list.first; + while (node) { + dictionnary_entry * entry = (dictionnary_entry *) node->element; + if (!strcmp(name, entry->name)) { + linkedlist_remove(& this->list, (void*) entry); + return 0; + } + node = node->next; + } + return 1; +} + +void dictionnary_clear(dictionnary* this) { + linkedlist_empty( & this->list, dictionnary_entry_delete_void ); +} + +void dictionnary_delete(dictionnary * this) { + dictionnary_clear(this); + free(this); +} diff --git a/pool/shard002/C/0058038_subfile.c b/pool/shard002/C/0058038_subfile.c new file mode 100644 index 0000000000000000000000000000000000000000..5d8659c8c428e4c4e4f976a93f5ade20f1dc1581 --- /dev/null +++ b/pool/shard002/C/0058038_subfile.c @@ -0,0 +1,158 @@ +/* + * Copyright (c) 2014 Nicolas George + * + * 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 "libavutil/avassert.h" +#include "libavutil/avstring.h" +#include "libavutil/opt.h" +#include "avformat.h" +#include "url.h" + +typedef struct SubfileContext { + const AVClass *class; + URLContext *h; + int64_t start; + int64_t end; + int64_t pos; +} SubfileContext; + +#define OFFSET(field) offsetof(SubfileContext, field) +#define D AV_OPT_FLAG_DECODING_PARAM + +static const AVOption subfile_options[] = { + { "start", "start offset", OFFSET(start), AV_OPT_TYPE_INT64, {.i64 = 0}, 0, INT64_MAX, D }, + { "end", "end offset", OFFSET(end), AV_OPT_TYPE_INT64, {.i64 = 0}, 0, INT64_MAX, D }, + { NULL } +}; + +#undef OFFSET +#undef D + +static const AVClass subfile_class = { + .class_name = "subfile", + .item_name = av_default_item_name, + .option = subfile_options, + .version = LIBAVUTIL_VERSION_INT, +}; + +static int slave_seek(URLContext *h) +{ + SubfileContext *c = h->priv_data; + int64_t ret; + + if ((ret = ffurl_seek(c->h, c->pos, SEEK_SET)) != c->pos) { + if (ret >= 0) + ret = AVERROR_BUG; + av_log(h, AV_LOG_ERROR, "Impossible to seek in file: %s\n", + av_err2str(ret)); + return ret; + } + return 0; +} + +static int subfile_open(URLContext *h, const char *filename, int flags, + AVDictionary **options) +{ + SubfileContext *c = h->priv_data; + int ret; + + if (!c->end) + c->end = INT64_MAX; + + if (c->end <= c->start) { + av_log(h, AV_LOG_ERROR, "end before start\n"); + return AVERROR(EINVAL); + } + av_strstart(filename, "subfile:", &filename); + ret = ffurl_open_whitelist(&c->h, filename, flags, &h->interrupt_callback, + options, h->protocol_whitelist, h->protocol_blacklist, h); + if (ret < 0) + return ret; + c->pos = c->start; + if ((ret = slave_seek(h)) < 0) { + ffurl_close(c->h); + return ret; + } + return 0; +} + +static int subfile_close(URLContext *h) +{ + SubfileContext *c = h->priv_data; + return ffurl_close(c->h); +} + +static int subfile_read(URLContext *h, unsigned char *buf, int size) +{ + SubfileContext *c = h->priv_data; + int64_t rest = c->end - c->pos; + int ret; + + if (rest <= 0) + return AVERROR_EOF; + size = FFMIN(size, rest); + ret = ffurl_read(c->h, buf, size); + if (ret >= 0) + c->pos += ret; + return ret; +} + +static int64_t subfile_seek(URLContext *h, int64_t pos, int whence) +{ + SubfileContext *c = h->priv_data; + int64_t new_pos, end; + int ret; + + if (whence == AVSEEK_SIZE || whence == SEEK_END) { + end = c->end; + if (end == INT64_MAX && (end = ffurl_seek(c->h, 0, AVSEEK_SIZE)) < 0) + return end; + } + + if (whence == AVSEEK_SIZE) + return end - c->start; + switch (whence) { + case SEEK_SET: + new_pos = c->start + pos; + break; + case SEEK_CUR: + new_pos = c->pos + pos; + break; + case SEEK_END: + new_pos = end + pos; + break; + } + if (new_pos < c->start) + return AVERROR(EINVAL); + c->pos = new_pos; + if ((ret = slave_seek(h)) < 0) + return ret; + return c->pos - c->start; +} + +const URLProtocol ff_subfile_protocol = { + .name = "subfile", + .url_open2 = subfile_open, + .url_read = subfile_read, + .url_seek = subfile_seek, + .url_close = subfile_close, + .priv_data_size = sizeof(SubfileContext), + .priv_data_class = &subfile_class, + .default_whitelist = "file", +}; diff --git a/pool/shard002/C/0058046_ccmode.c b/pool/shard002/C/0058046_ccmode.c new file mode 100644 index 0000000000000000000000000000000000000000..b1c219929be1264f00e517ef1e3de812f558b114 --- /dev/null +++ b/pool/shard002/C/0058046_ccmode.c @@ -0,0 +1,39 @@ +/* + * FIPS 200 support. + * + * Copyright (c) 2008 Neil Horman + * + * 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 "internal.h" + +int cc_mode; +int cc_mode_flag; + +EXPORT_SYMBOL_GPL(cc_mode); +EXPORT_SYMBOL_GPL(cc_mode_flag); + +int get_cc_mode_state(void) +{ + return cc_mode_flag; +} +EXPORT_SYMBOL_GPL(get_cc_mode_state); + +static int cc_mode_enable(char *str) +{ + cc_mode_flag = simple_strtol(str, NULL, 10); + if ((cc_mode_flag > 0x3f) || (cc_mode_flag < 0)) { + cc_mode_flag = 0; + } + cc_mode = cc_mode_flag & 0x01; + printk(KERN_INFO "CCMODE: CC mode %s\n", + cc_mode ? "enabled" : "disabled"); + return 1; +} + +__setup("cc_mode=", cc_mode_enable); diff --git a/pool/shard002/C/0058053_server_common.c b/pool/shard002/C/0058053_server_common.c new file mode 100644 index 0000000000000000000000000000000000000000..14b1892c2e9fc0ef293a9c60c47535a0e72c7426 --- /dev/null +++ b/pool/shard002/C/0058053_server_common.c @@ -0,0 +1,113 @@ +/* + * + * Copyright 2015, Google Inc. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following disclaimer + * in the documentation and/or other materials provided with the + * distribution. + * * Neither the name of Google Inc. nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + */ + +#include +#include +#include + +#include "test/core/bad_ssl/server_common.h" +#include "test/core/util/test_config.h" + +/* Common server implementation details for all servers in servers/. + * There's nothing *wrong* with these servers per-se, but they are + * configured to cause some failure case in the SSL connection path. + */ + +static int got_sigint = 0; + +static void sigint_handler(int x) { got_sigint = 1; } + +const char *bad_ssl_addr(int argc, char **argv) { + gpr_cmdline *cl; + char *addr = NULL; + cl = gpr_cmdline_create("test server"); + gpr_cmdline_add_string(cl, "bind", "Bind host:port", &addr); + gpr_cmdline_parse(cl, argc, argv); + gpr_cmdline_destroy(cl); + GPR_ASSERT(addr); + return addr; +} + +void bad_ssl_run(grpc_server *server) { + int shutdown_started = 0; + int shutdown_finished = 0; + grpc_event ev; + grpc_call_error error; + grpc_call *s = NULL; + grpc_call_details call_details; + grpc_metadata_array request_metadata_recv; + grpc_completion_queue *cq = grpc_completion_queue_create(NULL); + + grpc_call_details_init(&call_details); + grpc_metadata_array_init(&request_metadata_recv); + + grpc_server_register_completion_queue(server, cq, NULL); + grpc_server_start(server); + + error = grpc_server_request_call(server, &s, &call_details, + &request_metadata_recv, cq, cq, (void *)1); + GPR_ASSERT(GRPC_CALL_OK == error); + + signal(SIGINT, sigint_handler); + while (!shutdown_finished) { + if (got_sigint && !shutdown_started) { + gpr_log(GPR_INFO, "Shutting down due to SIGINT"); + grpc_server_shutdown_and_notify(server, cq, NULL); + GPR_ASSERT(grpc_completion_queue_pluck( + cq, NULL, GRPC_TIMEOUT_SECONDS_TO_DEADLINE(5), NULL) + .type == GRPC_OP_COMPLETE); + grpc_completion_queue_shutdown(cq); + shutdown_started = 1; + } + ev = grpc_completion_queue_next( + cq, gpr_time_add(gpr_now(GPR_CLOCK_REALTIME), + gpr_time_from_micros(1000000, GPR_TIMESPAN)), + NULL); + switch (ev.type) { + case GRPC_OP_COMPLETE: + GPR_ASSERT(ev.tag == (void *)1); + GPR_ASSERT(ev.success == 0); + break; + case GRPC_QUEUE_SHUTDOWN: + GPR_ASSERT(shutdown_started); + shutdown_finished = 1; + break; + case GRPC_QUEUE_TIMEOUT: + break; + } + } + + GPR_ASSERT(s == NULL); + grpc_call_details_destroy(&call_details); + grpc_metadata_array_destroy(&request_metadata_recv); +} diff --git a/pool/shard002/C/0058054_random.c b/pool/shard002/C/0058054_random.c new file mode 100644 index 0000000000000000000000000000000000000000..1a0c9647c13bd39d6b04abcc0a0706381984dbd3 --- /dev/null +++ b/pool/shard002/C/0058054_random.c @@ -0,0 +1,63 @@ +/* Psoudo-random number generator + * + * Uses xorshift1024 from “An experimental exploration of Marsaglia’s xorshift + * generators, scrambled”, Sebastiano Vigna + */ + +#include +#include +#include +#include +#include + +#include "random.h" + +uint64_t rand_u64 (randctx * const st) { + uint64_t s0 = st->s[ st->p ]; + uint64_t s1 = st->s[ st->p = ( st->p + 1 ) & (XORSHIFT_S-1) ]; + s1 ^= s1 << 31; // a + s1 ^= s1 >> 11; // b + s0 ^= s0 >> 30; // c + return ( st->s[ st->p ] = s0 ^ s1 ) * 1181783497276652981LL; +} + +/* Generate random double in [0,1] + */ +double rand_d01 (randctx * const st) { + return (double) rand_u64 (st) / (double) UINT64_MAX; +} + +/* Generate random double in [-1,1] + */ +double rand_d11 (randctx * const st) { + return rand_d01 (st) * 2.0 - 1.0; +} + +/* Random boolean value in {0,1} + */ +int rand_bool (randctx * const st) { + return rand_u64 (st) & 1; +} + +/* Seed rng with rdrand + */ +void rand_seed (randctx * const st) { + int fd = open ("/dev/urandom", O_RDONLY); + assert (fd != -1); + int ret = read (fd, &st->s, sizeof (st->s)); + assert (ret != -1); + close (fd); + st->p = 0; +} + +#if 0 +uint64_t xorshift_step (randctx * const st) { + uint64_t x = st->s[0]; + x ^= x >> 12; // a + x ^= x << 25; // b + x ^= x >> 27; // c + st->s[0] = x; + return x * 2685821657736338717LL; +} +#endif + diff --git a/pool/shard002/C/0058056_Tensor.c b/pool/shard002/C/0058056_Tensor.c new file mode 100644 index 0000000000000000000000000000000000000000..9e5b5b461afc0c39e9604ce4b8b63a0722e1e559 --- /dev/null +++ b/pool/shard002/C/0058056_Tensor.c @@ -0,0 +1,244 @@ +#include "torch/utils.h" +#include "THC.h" +#include "THFile.h" +#include "luaT.h" + +/* everything is as the generic Storage.c, except few things (see below) */ + +static void THCudaTensor_maskedFill(THCState *state, THCudaTensor *tensor, THByteTensor *mask, float value) +{ + THError("not yet implemented for CUDA"); +} + +static void THCudaTensor_maskedCopy(THCState *state, THCudaTensor *tensor, THByteTensor *mask, THCudaTensor* src) +{ + THError("not yet implemented for CUDA"); +} + +void THCudaTensor_maskedSelect(THCState *state, THCudaTensor *tensor, THCudaTensor* src, THByteTensor *mask) +{ + THError("not yet implemented for CUDA"); +} + +#define real float +#define Real Cuda + +#define torch_Storage_(NAME) TH_CONCAT_4(torch_,Real,Storage_,NAME) +#define torch_Storage TH_CONCAT_STRING_3(torch.,Real,Storage) +#define torch_Tensor_(NAME) TH_CONCAT_4(torch_,Real,Tensor_,NAME) +#define torch_Tensor TH_CONCAT_STRING_3(torch.,Real,Tensor) + +#define TH_GENERIC_FILE "generic/Tensor.c" +#include "generic/Tensor.c" +#undef TH_GENERIC_FILE + +#undef real +#undef Real + +/* now we overwrite some methods specific to CudaTensor */ +static int cutorch_CudaTensor_copy(lua_State *L) +{ + THCState *state = cutorch_getstate(L); + THCudaTensor *storage = luaT_checkudata(L, 1, "torch.CudaTensor"); + void *src; + if( (src = luaT_toudata(L, 2, "torch.CudaTensor")) ) + THCudaTensor_copy(state, storage, src); + else if( (src = luaT_toudata(L, 2, "torch.ByteTensor")) ) + THCudaTensor_copyByte(state, storage, src); + else if( (src = luaT_toudata(L, 2, "torch.CharTensor")) ) + THCudaTensor_copyChar(state, storage, src); + else if( (src = luaT_toudata(L, 2, "torch.ShortTensor")) ) + THCudaTensor_copyShort(state, storage, src); + else if( (src = luaT_toudata(L, 2, "torch.IntTensor")) ) + THCudaTensor_copyInt(state, storage, src); + else if( (src = luaT_toudata(L, 2, "torch.LongTensor")) ) + THCudaTensor_copyLong(state, storage, src); + else if( (src = luaT_toudata(L, 2, "torch.FloatTensor")) ) + THCudaTensor_copyFloat(state, storage, src); + else if( (src = luaT_toudata(L, 2, "torch.DoubleTensor")) ) + THCudaTensor_copyDouble(state, storage, src); + else if( (src = luaT_toudata(L, 2, "torch.CudaTensor")) ) + THCudaTensor_copyCuda(state, storage, src); + else + luaL_typerror(L, 2, "torch.*Tensor"); + + lua_settop(L, 1); + return 1; +} + +#define CUDA_IMPLEMENT_TENSOR_COPY(TYPEC) \ + static int cutorch_##TYPEC##Tensor_copy(lua_State *L) \ + { \ + TH##TYPEC##Tensor *storage = luaT_checkudata(L, 1, "torch." #TYPEC "Tensor"); \ + void *src; \ + if( (src = luaT_toudata(L, 2, "torch." #TYPEC "Tensor")) ) \ + TH##TYPEC##Tensor_copy(storage, src); \ + else if( (src = luaT_toudata(L, 2, "torch.ByteTensor")) ) \ + TH##TYPEC##Tensor_copyByte(storage, src); \ + else if( (src = luaT_toudata(L, 2, "torch.CharTensor")) ) \ + TH##TYPEC##Tensor_copyChar(storage, src); \ + else if( (src = luaT_toudata(L, 2, "torch.ShortTensor")) ) \ + TH##TYPEC##Tensor_copyShort(storage, src); \ + else if( (src = luaT_toudata(L, 2, "torch.IntTensor")) ) \ + TH##TYPEC##Tensor_copyInt(storage, src); \ + else if( (src = luaT_toudata(L, 2, "torch.LongTensor")) ) \ + TH##TYPEC##Tensor_copyLong(storage, src); \ + else if( (src = luaT_toudata(L, 2, "torch.FloatTensor")) ) \ + TH##TYPEC##Tensor_copyFloat(storage, src); \ + else if( (src = luaT_toudata(L, 2, "torch.DoubleTensor")) ) \ + TH##TYPEC##Tensor_copyDouble(storage, src); \ + else if( (src = luaT_toudata(L, 2, "torch.CudaTensor")) ) \ + TH##TYPEC##Tensor_copyCuda(cutorch_getstate(L), storage, src); \ + else \ + luaL_typerror(L, 2, "torch.*Tensor"); \ + \ + lua_settop(L, 1); \ + return 1; \ + } + +CUDA_IMPLEMENT_TENSOR_COPY(Byte) +CUDA_IMPLEMENT_TENSOR_COPY(Char) +CUDA_IMPLEMENT_TENSOR_COPY(Short) +CUDA_IMPLEMENT_TENSOR_COPY(Int) +CUDA_IMPLEMENT_TENSOR_COPY(Long) +CUDA_IMPLEMENT_TENSOR_COPY(Float) +CUDA_IMPLEMENT_TENSOR_COPY(Double) + +static void THFloatTensor_computesz(THFloatTensor *self, long **sz_, long **st_) +{ + long *sz, *st, *szh; + int i; + + sz = (long*)THAlloc(sizeof(long)*self->nDimension); + st = (long*)THAlloc(sizeof(long)*self->nDimension); + szh = (long*)THAlloc(sizeof(long)*self->nDimension); + + for(i = self->nDimension-1; i >= 0; i--) + { + if(i == self->nDimension-1) + szh[i] = 1; + else + szh[i] = szh[i+1]*self->size[i+1]; + } + + memcpy(sz, szh, self->nDimension * sizeof(long)); + memcpy(st, self->stride, self->nDimension * sizeof(long)); + THFree(szh); + + *sz_ = sz; + *st_ = st; +} + +void THFloatTensor_kernel_copy(float *dst, + long *dst_sz, long *dst_st, int dst_dim, + float *src, + long *src_sz, long *src_st, int src_dim, + long n_elem) +{ + long k; + + for(k = 0; k < n_elem; k++) + { + long src_idx = 0; + long src_rest = k; + long dst_idx = 0; + long dst_rest = k; + int dim; + + for(dim = 0; dim < dst_dim; dim++) + { + dst_idx += (dst_rest/dst_sz[dim])*dst_st[dim]; + dst_rest = dst_rest % dst_sz[dim]; + } + + for(dim = 0; dim < src_dim; dim++) + { + src_idx += (src_rest/src_sz[dim])*src_st[dim]; + src_rest = src_rest % src_sz[dim]; + } + + dst[dst_idx] = src[src_idx]; + } +} + +static int cuda_FloatTensor_fakecopy(lua_State *L) +{ + THFloatTensor *self = luaT_checkudata(L, 1, "torch.FloatTensor"); + THFloatTensor *src = luaT_checkudata(L, 2, "torch.FloatTensor"); + long *d_self_sz, *d_self_st, *d_src_sz, *d_src_st; + long nElement = THFloatTensor_nElement(self); + + THArgCheck(THFloatTensor_nElement(self) == THFloatTensor_nElement(src), 2, "sizes do not match"); + + THFloatTensor_computesz(self, &d_self_sz, &d_self_st); + THFloatTensor_computesz(src, &d_src_sz, &d_src_st); + + THFloatTensor_kernel_copy(THFloatTensor_data(self), + d_self_sz, d_self_st, self->nDimension, + THFloatTensor_data(src), + d_src_sz, d_src_st, src->nDimension, + nElement); + + THFree(d_self_sz); + THFree(d_self_st); + THFree(d_src_sz); + THFree(d_src_st); + + lua_settop(L, 1); + return 1; +} + +static int cutorch_CudaTensor_getDevice(lua_State *L) { + THCudaTensor *tensor = luaT_checkudata(L, 1, "torch.CudaTensor"); + lua_pushinteger(L, THCudaTensor_getDevice(cutorch_getstate(L), tensor) + 1); + return 1; +} + +void cutorch_CudaTensor_init(lua_State* L) +{ + /* the standard stuff */ + torch_CudaTensor_init(L); + + /* additional methods */ + luaT_pushmetatable(L, "torch.FloatTensor"); + lua_pushcfunction(L, cuda_FloatTensor_fakecopy); + lua_setfield(L, -2, "fakecopy"); + lua_pop(L, 1); + + /* the copy methods */ + { + int i; + + const void* tnames[8] = {"torch.ByteTensor", + "torch.CharTensor", + "torch.ShortTensor", + "torch.IntTensor", + "torch.LongTensor", + "torch.FloatTensor", + "torch.DoubleTensor", + "torch.CudaTensor"}; + + static int (*funcs[8])(lua_State*) = {cutorch_ByteTensor_copy, + cutorch_CharTensor_copy, + cutorch_ShortTensor_copy, + cutorch_IntTensor_copy, + cutorch_LongTensor_copy, + cutorch_FloatTensor_copy, + cutorch_DoubleTensor_copy, + cutorch_CudaTensor_copy}; + + for(i = 0; i < 8; i++) + { + luaT_pushmetatable(L, tnames[i]); + lua_pushcfunction(L, funcs[i]); + lua_setfield(L, -2, "copy"); + lua_pop(L, 1); + } + } + + luaT_pushmetatable(L, "torch.CudaTensor"); + lua_pushcfunction(L, cutorch_CudaTensor_getDevice); + lua_setfield(L, -2, "getDevice"); + + lua_pop(L, 1); +} diff --git a/pool/shard002/C/0058057_Kata.c b/pool/shard002/C/0058057_Kata.c new file mode 100644 index 0000000000000000000000000000000000000000..f253ad86dd0ab510ae5a09c9539b666ef22ad96b --- /dev/null +++ b/pool/shard002/C/0058057_Kata.c @@ -0,0 +1,20 @@ +int calc(const char *source) +{ + int sevenCount = 0; + + for(char* ptr = source; *ptr != '\0'; ptr++) + { + char buffer[4]; + snprintf(buffer, 4, "%d", (int)*ptr); + + for(char* bufPtr = buffer; *bufPtr; *bufPtr++) + { + if (*bufPtr == '7') + { + sevenCount++; + } + } + } + + return sevenCount * 6; +} diff --git a/pool/shard002/C/0058059_devcfg-demo.c b/pool/shard002/C/0058059_devcfg-demo.c new file mode 100644 index 0000000000000000000000000000000000000000..507394c95f7f471586f84fb2f73d030505aef9ef --- /dev/null +++ b/pool/shard002/C/0058059_devcfg-demo.c @@ -0,0 +1,52 @@ +#include +#include +#include +#include +#include +#include +#include + +#define DEVCFG_ADDR 0x1fc0f000 +#define DEVSN_ADDR 0x1fc54000 + +int main() +{ + // Obtain handle to physical memory + int fd = open("/dev/mem", O_RDWR | O_SYNC); + if (fd < 0) { + printf("Unable to open /dev/mem: %s\n", strerror(errno)); + return -1; + } + + // Map a page of memory to the physical address + int32_t devcfg_base = (int32_t) mmap(0, 4096, PROT_READ|PROT_WRITE, MAP_SHARED, fd, DEVCFG_ADDR); + int32_t devsn_base = (int32_t) mmap(0, 4096, PROT_READ|PROT_WRITE, MAP_SHARED, fd, DEVSN_ADDR); + if (devcfg_base < 0 || devsn_base < 0) { + printf("Mmap failed: %s\n", strerror(errno)); + return -1; + } + + uint32_t devcfg4 = *(uint32_t*) (devcfg_base + 0xfbc); + uint32_t devcfg3 = *(uint32_t*) (devcfg_base + 0xfc0); + uint32_t devcfg2 = *(uint32_t*) (devcfg_base + 0xfc4); + uint32_t devcfg1 = *(uint32_t*) (devcfg_base + 0xfc8); + uint32_t devcfg0 = *(uint32_t*) (devcfg_base + 0xfcc); + + uint32_t devsn0 = *(uint32_t*) (devsn_base + 0x020); + uint32_t devsn1 = *(uint32_t*) (devsn_base + 0x024); + uint32_t devsn2 = *(uint32_t*) (devsn_base + 0x028); + uint32_t devsn3 = *(uint32_t*) (devsn_base + 0x02c); + + printf(" devcfg0 = %04x\n", devcfg0); + printf(" devcfg1 = %04x\n", devcfg1); + printf(" devcfg2 = %04x\n", devcfg2); + printf(" devcfg3 = %04x\n", devcfg3); + printf(" devcfg4 = %04x\n", devcfg4); + + printf(" devsn0 = %04x\n", devsn0); + printf(" devsn1 = %04x\n", devsn1); + printf(" devsn2 = %04x\n", devsn2); + printf(" devsn3 = %04x\n", devsn3); + + return 0; +} diff --git a/pool/shard002/C/0058064_task_netplay_nat_traversal.c b/pool/shard002/C/0058064_task_netplay_nat_traversal.c new file mode 100644 index 0000000000000000000000000000000000000000..b645ef93d030c49060abec414f2f09c54a46cf37 --- /dev/null +++ b/pool/shard002/C/0058064_task_netplay_nat_traversal.c @@ -0,0 +1,95 @@ +/* RetroArch - A frontend for libretro. + * Copyright (C) 2017 - Gregor Richards + * + * RetroArch 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 Found- + * ation, either version 3 of the License, or (at your option) any later version. + * + * RetroArch 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 RetroArch. + * If not, see . + */ + +#include + +#include "tasks_internal.h" + +#ifdef HAVE_CONFIG_H +#include "../config.h" +#endif + +#ifdef HAVE_NETWORKING +#include +#endif + +#include "../network/netplay/netplay.h" + +#ifdef HAVE_NETWORKING +struct nat_traversal_state_data +{ + struct natt_status *nat_traversal_state; + uint16_t port; +}; + +static void netplay_nat_traversal_callback(retro_task_t *task, + void *task_data, + void *user_data, const char *error) +{ + struct nat_traversal_state_data *ntsd = + (struct nat_traversal_state_data *) task_data; + + free(ntsd); + + netplay_driver_ctl(RARCH_NETPLAY_CTL_FINISHED_NAT_TRAVERSAL, NULL); +} + +static void task_netplay_nat_traversal_handler(retro_task_t *task) +{ + struct nat_traversal_state_data *ntsd = + (struct nat_traversal_state_data *) task->task_data; + + natt_init(); + + if (natt_new(ntsd->nat_traversal_state)) + natt_open_port_any(ntsd->nat_traversal_state, + ntsd->port, SOCKET_PROTOCOL_TCP); + + task_set_progress(task, 100); + task_set_finished(task, true); +} + +bool task_push_netplay_nat_traversal(void *nat_traversal_state, uint16_t port) +{ + struct nat_traversal_state_data *ntsd; + retro_task_t *task = task_init(); + + if (!task) + return false; + + ntsd = (struct nat_traversal_state_data *) + calloc(1, sizeof(*ntsd)); + + if (!ntsd) + { + free(task); + return false; + } + + ntsd->nat_traversal_state = (struct natt_status *)nat_traversal_state; + ntsd->port = port; + + task->type = TASK_TYPE_BLOCKING; + task->handler = task_netplay_nat_traversal_handler; + task->callback = netplay_nat_traversal_callback; + task->task_data = ntsd; + + task_queue_push(task); + + return true; +} +#else +bool task_push_netplay_nat_traversal(void *nat_traversal_state, uint16_t port) { return false; } +#endif diff --git a/pool/shard002/C/0058084_Can.c b/pool/shard002/C/0058084_Can.c new file mode 100644 index 0000000000000000000000000000000000000000..9e97efd3a4e4da855094b199b9a694804c8aeebc --- /dev/null +++ b/pool/shard002/C/0058084_Can.c @@ -0,0 +1,126 @@ +#include "Can.h" + +static CAN_U8 buff[400]; +static CAN_U32 can_id; + +void Can_initialize(void) +{ + if (CAN_DEBUG) + UART_printf("call Can_initialize\n\r"); + canInitialize(); +} + +size_t Can_send(CAN_U8* start, size_t length) +{ + CAN_U8 send_length; + int current_length = 0; + int i, j; + + if (CAN_DEBUG) { + UART_printf("call Can_send\n\r"); + CanDebug(start, length); + } + + do { + + if ((length - current_length) >= 8) + send_length = 8; + else + send_length = (length - current_length); + + canSendData(4, send_length, &start[current_length]); + + for(i = 0; i < 25000; i++) // 2500 ‚­‚ç‚¢‚ÅOK + j += i; +// if (CAN_DEBUG) { +// CanDebug(&start[current_length], send_length); +// } + + current_length += send_length; + + } while (current_length < length); + + if (CAN_DEBUG) + UART_printf("Can_send current_length = %d\n\r", current_length); + + return current_length; +} + +size_t Can_recv(CAN_U8* start, size_t length) +{ + CAN_U8 ret = CAN_RECV_OK; + CAN_U32 canID, recv_length = 0; + CAN_U8 dlc; + static CAN_U32 current_length = 0, giop_length = 0; + + if (CAN_DEBUG) + UART_printf("call Can_recv\n\r"); + + if (giop_length == 0) { + do { + ret = canRecvData(1, &canID, &dlc, &buff[recv_length]); + if (ret != CAN_RECV_OK) + continue; + else + recv_length += dlc; + + if ((giop_length == 0) && (recv_length >= GIOP_HDR)) { + giop_length = getLength(); + } + } while ((giop_length + GIOP_HDR) > recv_length); + + can_id = canID; + } + + memcpy(start, &buff[current_length], length); + current_length += length; + + if (CAN_DEBUG) + CanDebug(start, length); + + if (current_length >= (giop_length + GIOP_HDR)) + { + current_length = 0; + giop_length = 0; + } + + return length; +} + +CAN_U32 getLength() +{ + CAN_U32 length = 0; + CAN_U8 tmp; + CAN_U8 endian = buff[6]; + CAN_U8 work[4]; + + memcpy(work, &buff[8], 4); + + if (endian == 1) + { + tmp = work[0]; + work[0] = work[3]; + work[3] = tmp; + tmp = work[1]; + work[1] = work[2]; + work[2] = tmp; + } + + length += (work[0] << 24); + length += (work[1] << 16); + length += (work[2] << 8); + length += work[3]; + + return length; +} + +void CanDebug(CAN_U8* data, size_t length) +{ + int i; + + UART_printf("data = "); + for (i = 0; i < length; i++) + UART_printf("%02x ", data[i]); + UART_printf("\n\r"); +} + diff --git a/pool/shard002/C/0058085_t-engine-info.c b/pool/shard002/C/0058085_t-engine-info.c new file mode 100644 index 0000000000000000000000000000000000000000..db46bf86cc3706d161102141bbf5525c59e7c2a9 --- /dev/null +++ b/pool/shard002/C/0058085_t-engine-info.c @@ -0,0 +1,148 @@ +/* t-engine-info.c - Regression test for gpgme_get_engine_info. + * Copyright (C) 2003, 2004, 2007 g10 Code GmbH + * + * This file is part of GPGME. + * + * GPGME 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. + * + * GPGME 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 . + * SPDX-License-Identifier: LGPL-2.1-or-later + */ + +#ifdef HAVE_CONFIG_H +#include +#endif + +#include +#include +#include + +#include + +#define PGM "t-engine-info" + +static int verbose; + + + + +#define fail_if_err(err) \ + do \ + { \ + if (err) \ + { \ + fprintf (stderr, "%s:%d: gpgme_error_t %s\n", \ + __FILE__, __LINE__, gpgme_strerror (err)); \ + exit (1); \ + } \ + } \ + while (0) + + +int +main (int argc, char **argv ) +{ + int last_argc = -1; + gpgme_engine_info_t info; + gpgme_error_t err; + + if (argc) + { argc--; argv++; } + + while (argc && last_argc != argc ) + { + last_argc = argc; + if (!strcmp (*argv, "--")) + { + argc--; argv++; + break; + } + else if (!strcmp (*argv, "--help")) + { + fputs ("usage: " PGM " [options]\n" + "Options:\n" + " --set-global-flag KEY VALUE\n", + stdout); + exit (0); + } + else if (!strcmp (*argv, "--verbose")) + { + verbose++; + argc--; argv++; + } + else if (!strcmp (*argv, "--set-global-flag")) + { + argc--; argv++; + if (argc < 2) + { + fprintf (stderr, PGM ": not enough arguments for option\n"); + exit (1); + } + if (gpgme_set_global_flag (argv[0], argv[1])) + { + fprintf (stderr, PGM ": gpgme_set_global_flag failed\n"); + exit (1); + } + argc--; argv++; + argc--; argv++; + } + else if (!strncmp (*argv, "--", 2)) + { + fprintf (stderr, PGM ": unknown option '%s'\n", *argv); + exit (1); + } + } + + if (argc) + { + fprintf (stderr, PGM ": unexpected arguments\n"); + exit (1); + } + + gpgme_check_version (NULL); + + { + const char *keys[] = {"homedir", + "sysconfdir", + "bindir", + "libexecdir", + "libdir", + "datadir", + "localedir", + "agent-socket", + "agent-ssh-socket", + "dirmngr-socket", + "uiserver-socket", + "gpgconf-name", + "gpg-name", + "gpgsm-name", + "g13-name", + "gpg-wks-client-name", + NULL }; + const char *s; + int i; + + for (i=0; keys[i]; i++) + if ((s = gpgme_get_dirinfo (keys[i]))) + fprintf (stderr, "dirinfo: %s='%s'\n", keys[i], s); + } + + err = gpgme_get_engine_info (&info); + fail_if_err (err); + + for (; info; info = info->next) + fprintf (stdout, "protocol=%d engine='%s' v='%s' (min='%s') home='%s'\n", + info->protocol, info->file_name, info->version, info->req_version, + info->home_dir? info->home_dir : "[default]"); + + return 0; +} diff --git a/pool/shard002/C/0058089_test.c b/pool/shard002/C/0058089_test.c new file mode 100644 index 0000000000000000000000000000000000000000..33bf0774a192d3f8c95bb25c5308a2f12f37af0c --- /dev/null +++ b/pool/shard002/C/0058089_test.c @@ -0,0 +1,18 @@ +#include +#include + +#define assert(cond, msg) if (!(cond)) { \ + printf("assert fail: %s\n", msg); \ + exit(-1); \ +} + +int trap(int* height, int heightSize); + +int main(int argc, char* argv[]) { + int h1[] = { 2, 0, 2 }; + int h2[] = { 0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1 }; + assert(trap(h1, 3) == 2, "h1 == 2"); + assert(trap(h2, 12) == 6, "h2 == 6"); + printf("everything is fine!\n"); + return 0; +} \ No newline at end of file diff --git a/pool/shard002/C/0058090_nl_langinfo_l.c b/pool/shard002/C/0058090_nl_langinfo_l.c new file mode 100644 index 0000000000000000000000000000000000000000..db2b094cdac82771b4b39b6622183b3c4766e21d --- /dev/null +++ b/pool/shard002/C/0058090_nl_langinfo_l.c @@ -0,0 +1,69 @@ +/* User interface for extracting locale-dependent parameters. + Copyright (C) 1995-2015 Free Software Foundation, Inc. + This file is part of the GNU C Library. + + 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 "localeinfo.h" + + +/* Return a string with the data for locale-dependent parameter ITEM. */ + +char * +__nl_langinfo_l (nl_item item, __locale_t l) +{ + int category = _NL_ITEM_CATEGORY (item); + unsigned int index = _NL_ITEM_INDEX (item); + const struct __locale_data *data; + + if (category < 0 || category == LC_ALL || category >= __LC_LAST) + /* Bogus category: bogus item. */ + return (char *) ""; + + /* Special case value for NL_LOCALE_NAME (category). + This is not a real item index in the string table. */ + if (index == _NL_ITEM_INDEX (_NL_LOCALE_NAME (category))) + return (char *) l->__names[category]; + +#if defined NL_CURRENT_INDIRECT + /* Make direct reference to every _nl_current_CATEGORY symbol, + since we know only at runtime which categories are used. */ + switch (category) + { +# define DEFINE_CATEGORY(category, category_name, items, a) \ + case category: data = *_nl_current_##category; break; +# include "categories.def" +# undef DEFINE_CATEGORY + default: /* Should be impossible. */ + abort(); + } +#else + data = l->__locales[category]; +#endif + + if (index >= data->nstrings) + /* Bogus index for this category: bogus item. */ + return (char *) ""; + + /* Return the string for the specified item. */ + return (char *) data->values[index].string; +} +libc_hidden_def (__nl_langinfo_l) +weak_alias (__nl_langinfo_l, nl_langinfo_l) diff --git a/pool/shard002/C/0058092_mux.c b/pool/shard002/C/0058092_mux.c new file mode 100644 index 0000000000000000000000000000000000000000..137acb4523362fb97bc26075b2cbf7d4e039cc1b --- /dev/null +++ b/pool/shard002/C/0058092_mux.c @@ -0,0 +1,51 @@ +/* + * mux.c + * + * Copyright (C) 2011 Texas Instruments Incorporated - http://www.ti.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 version 2. + * + * 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 "evm.h" + +static struct module_pin_mux uart0_pin_mux[] = { + {OFFSET(pincntl70), PULLUP_EN | MODE(0x01)}, /* UART0_RXD */ + {OFFSET(pincntl71), PULLUP_EN | MODE(0x01)}, /* UART0_TXD */ + {-1}, +}; + +static struct module_pin_mux mmc1_pin_mux[] = { + {OFFSET(pincntl1), PULLUP_EN | MODE(0x01)}, /* SD1_CLK */ + {OFFSET(pincntl2), PULLUP_EN | MODE(0x01)}, /* SD1_CMD */ + {OFFSET(pincntl3), PULLUP_EN | MODE(0x01)}, /* SD1_DAT[0] */ + {OFFSET(pincntl4), PULLUP_EN | MODE(0x01)}, /* SD1_DAT[1] */ + {OFFSET(pincntl5), PULLUP_EN | MODE(0x01)}, /* SD1_DAT[2] */ + {OFFSET(pincntl6), PULLUP_EN | MODE(0x01)}, /* SD1_DAT[3] */ + {OFFSET(pincntl74), PULLUP_EN | MODE(0x40)}, /* SD1_POW */ + {OFFSET(pincntl75), MODE(0x40)}, /* SD1_SDWP */ + {OFFSET(pincntl80), PULLUP_EN | MODE(0x02)}, /* SD1_SDCD */ + {-1}, +}; + +void enable_uart0_pin_mux(void) +{ + configure_module_pin_mux(uart0_pin_mux); +} + +void enable_mmc1_pin_mux(void) +{ + configure_module_pin_mux(mmc1_pin_mux); +} diff --git a/pool/shard002/C/0058102_main-hmac-sha1-test.c b/pool/shard002/C/0058102_main-hmac-sha1-test.c new file mode 100644 index 0000000000000000000000000000000000000000..0cf9a1baab6cfb6bc56caa490972922523edb573 --- /dev/null +++ b/pool/shard002/C/0058102_main-hmac-sha1-test.c @@ -0,0 +1,76 @@ +/* main-hmac-sha1-test.c */ +/* + This file is part of the AVR-Crypto-Lib. + Copyright (C) 2008 Daniel Otte (daniel.otte@rub.de) + + 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 . +*/ +/* + * HMAC-SHA1 test-suit + * +*/ + +#include "main-test-common.h" + +#include "sha1.h" +#include "hmac-sha1.h" + +#include "nessie_mac_test.h" + +char *algo_name = "HMAC-SHA1"; + +/***************************************************************************** + * additional validation-functions * + *****************************************************************************/ + +void testrun_nessie_hmacsha1(void){ + nessie_mac_ctx.macsize_b = HMAC_SHA1_BITS; + nessie_mac_ctx.keysize_b = HMAC_SHA1_BLOCK_BITS; + nessie_mac_ctx.blocksize_B = HMAC_SHA1_BLOCK_BYTES; + nessie_mac_ctx.ctx_size_B = sizeof(hmac_sha1_ctx_t); + nessie_mac_ctx.name = algo_name; + nessie_mac_ctx.mac_init = (nessie_mac_init_fpt)hmac_sha1_init; + nessie_mac_ctx.mac_next = (nessie_mac_next_fpt)hmac_sha1_nextBlock; + nessie_mac_ctx.mac_last = (nessie_mac_last_fpt)hmac_sha1_lastBlock; + nessie_mac_ctx.mac_conv = (nessie_mac_conv_fpt)hmac_sha1_final; + + nessie_mac_run(); +} + + +/***************************************************************************** + * main * + *****************************************************************************/ + +const char nessie_str[] PROGMEM = "nessie"; +const char test_str[] PROGMEM = "test"; +/* const char performance_str[] PROGMEM = "performance"; */ +const char echo_str[] PROGMEM = "echo"; + +const cmdlist_entry_t cmdlist[] PROGMEM = { + { nessie_str, NULL, testrun_nessie_hmacsha1}, + { test_str, NULL, testrun_nessie_hmacsha1}, +/* { performance_str, NULL, testrun_performance_hmacsha1}, */ + { echo_str, (void*)1, (void_fpt)echo_ctrl}, + { NULL, NULL, NULL} +}; + +int main (void){ + main_setup(); + + for(;;){ + welcome_msg(algo_name); + cmd_interface(cmdlist); + } +} diff --git a/pool/shard002/C/0058104_platform_utils.c b/pool/shard002/C/0058104_platform_utils.c new file mode 100644 index 0000000000000000000000000000000000000000..c77b775c50a8b28734571ae9eeb3b76206ba45b9 --- /dev/null +++ b/pool/shard002/C/0058104_platform_utils.c @@ -0,0 +1,161 @@ +/* + * platform_utils.c + * + * All rights reserved. + * + * Created on: 17-10-2013 + * Author: Karol Lasończyk + */ + +#include "platform_utils.h" + +#include "ch.h" +#include "hal.h" +#include "usb.h" + +// addresses of registers +volatile uint32_t *DWT_CONTROL = (uint32_t *)0xE0001000; +volatile uint32_t *DWT_CYCCNT = (uint32_t *)0xE0001004; +volatile uint32_t *DEMCR = (uint32_t *)0xE000EDFC; + + +/** + * @brief Init function executed in first lines of tests. Started properly Chibios and ARM + */ +void init(void) +{ + /* + * System initializations. + * - HAL initialization, this also initializes the configured device drivers + * and performs the board-specific initializations. + * - Kernel initialization, the main() function becomes a thread and the + * RTOS is active. + */ + halInit(); + chSysInit(); + + /* Timer configuration.*/ + *DEMCR = *DEMCR | 0x01000000; + rccEnableTIM5(FALSE); + rccResetTIM5(); + TIM5->CR1 = 0; /* Initially stopped. */ + + TIM5->CR2 = 0; + TIM5->PSC = 0; /* Prescaler value. */ + TIM5->SR = 0; /* Clear pending IRQs. */ + TIM5->DIER = 0; + TIM5->SMCR = 0; + + TIM5->CNT = 0; /* Initially stopped. */ + + start_count_time(); + chThdSleepMilliseconds(1000); + stop_count_time(); + + /* + * Initializes a serial-over-USB CDC driver. + */ + sduObjectInit(&SDU1); + sduStart(&SDU1, &serusbcfg); + + /* + * Activates the USB driver and then the USB bus pull-up on D+. + * Note, a delay is inserted in order to not have to disconnect the cable + * after a reset. + */ + usbDisconnectBus(serusbcfg.usbp); + chThdSleepMilliseconds(250); + usbStart(serusbcfg.usbp, &usbcfg); + usbConnectBus(serusbcfg.usbp); + + /* + * Stopping and restarting the USB in order to test the stop procedure. The + * following lines are not usually required. + */ + chThdSleepMilliseconds(3000); + info("---------------ECDSA ECDH Test Suite---------------"); + info("CPU frequency %f MHz", STM32_SYSCLK/1000000.0); + info("TIMER frequency %f MHz", STM32_TIMCLK1/1000000.0); + info("---------------------------------------------------"); + info("-----------------Timer second test-----------------"); + info("Start timer and wait 1 sec"); + start_count_time(); + chThdSleepMilliseconds(1000); + stop_count_time(); + info("Timer result 1sec = %u us", get_us()); + info("---------------------------------------------------"); +} + +void inf_loop(void){ + chThdSleepMilliseconds(1000); + usbDisconnectBus(serusbcfg.usbp); + while(1){ + chThdSleepSeconds(1); + } +} + +/** + * @brief start counting time + */ +void start_count_time(void) +{ + TIM5->CNT = 0; + TIM5->CR1 = TIM_CR1_CEN; + *DWT_CYCCNT = 0; + *DWT_CONTROL = *DWT_CONTROL | 1 ; + +} + +/** + * @brief stop counting time + */ +void stop_count_time(void) +{ + TIM5->CR1 = 0; + *DWT_CONTROL &= 0xFE; +} +/** + * @brief Function returns elapsed time (stop-start) in µs + * @return time in µs + */ +uint32_t get_us(void) +{ + return RTC2US(STM32_SYSCLK, *DWT_CYCCNT); + //return RTC2US(STM32_TIMCLK1, TIM5->CNT); +} + +uint32_t get_ticks(void) +{ + return *DWT_CYCCNT; +} + +/** + * @brief Function required to properly using format library + * @param c char + * @return + */ +int fm_putchar(int c) +{ + chSequentialStreamPut(&SDU1, (uint8_t)c); + return 1; +} + +/*Not pseudo random generator but function returns different numbers*/ +static uint32_t j; + +/** + * @brief very bad implementation pseudo random generator looks like high quality prgn + * @param output pseudo random number + */ +void default_prgn(bn_uint_t *output) +{ + BN_CREATE_VARIABLE(tmp, output->length); + uint32_t i; + + for(i=0;ilength); +} diff --git a/pool/shard002/C/0058107_empty-Seed4-RandomFuns-Type_short-ControlStructures_14-BB2-ForBound_input-Operators_Shiftlt_Shiftrt_Lt_Gt_Le_Ge_Eq_Ne_BAnd_BXor_BOr.c b/pool/shard002/C/0058107_empty-Seed4-RandomFuns-Type_short-ControlStructures_14-BB2-ForBound_input-Operators_Shiftlt_Shiftrt_Lt_Gt_Le_Ge_Eq_Ne_BAnd_BXor_BOr.c new file mode 100644 index 0000000000000000000000000000000000000000..85c00b136d7008e79c260646a547acd25780f6ec --- /dev/null +++ b/pool/shard002/C/0058107_empty-Seed4-RandomFuns-Type_short-ControlStructures_14-BB2-ForBound_input-Operators_Shiftlt_Shiftrt_Lt_Gt_Le_Ge_Eq_Ne_BAnd_BXor_BOr.c @@ -0,0 +1,110 @@ +/* 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 , ...) ; +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 megaInit(void) +{ + + + { + +} +} +void RandomFunc(unsigned short input[1] , unsigned short output[1] ) +{ + unsigned short state[1] ; + unsigned short local1 ; + char copy11 ; + char copy15 ; + + { + state[0UL] = (input[0UL] & 914778474UL) << (unsigned short)7; + local1 = 0UL; + while (local1 < input[1UL]) { + if (state[0UL] > local1) { + if (state[0UL] > local1) { + copy11 = *((char *)(& state[local1]) + 0); + *((char *)(& state[local1]) + 0) = *((char *)(& state[local1]) + 1); + *((char *)(& state[local1]) + 1) = copy11; + } else { + state[local1] >>= ((state[0UL] >> (unsigned short)3) & (unsigned short)7) | 1UL; + state[local1] >>= ((state[local1] >> (unsigned short)3) & (unsigned short)7) | 1UL; + } + } else + if (! (state[0UL] == local1)) { + state[0UL] >>= ((state[local1] >> (unsigned short)4) & (unsigned short)7) | 1UL; + copy15 = *((char *)(& state[local1]) + 0); + *((char *)(& state[local1]) + 0) = *((char *)(& state[local1]) + 1); + *((char *)(& state[local1]) + 1) = copy15; + } + local1 ++; + } + output[0UL] = state[0UL] | 547249631UL; +} +} diff --git a/pool/shard002/C/0058116_testmod_iterate.c b/pool/shard002/C/0058116_testmod_iterate.c new file mode 100644 index 0000000000000000000000000000000000000000..2f9cb97ea35e4713b193a244d54024d41c8bfb71 --- /dev/null +++ b/pool/shard002/C/0058116_testmod_iterate.c @@ -0,0 +1,67 @@ +/** + * @file + * + * @brief Tests for iterate plugin + * + * @copyright BSD License (see LICENSE.md or https://www.libelektra.org) + * + */ + +#include +#include + +#include + +#include + +static void test_basics (void) +{ + printf ("test basics\n"); + + Key * parentKey = keyNew ("user/tests/iterate", KEY_END); + KeySet * conf = ksNew (0, KS_END); + PLUGIN_OPEN ("iterate"); + + KeySet * ks = ksNew (0, KS_END); + + succeed_if (plugin->kdbOpen (plugin, parentKey) == 1, "call to kdbOpen was not successful"); + + succeed_if (plugin->kdbGet (plugin, ks, parentKey) == 0, "call to kdbGet was not successful"); + + succeed_if (plugin->kdbSet (plugin, ks, parentKey) == 0, "call to kdbSet was not successful"); + + // clang-format off + ksAppendKey (ks, keyNew("user/tests/iterate/key", + KEY_META, "iterate", "has", + KEY_END)); + // clang-format on + + ksRewind (ks); + succeed_if (plugin->kdbGet (plugin, ks, parentKey) == 1, "call to kdbGet was not successful"); + + ksRewind (ks); + succeed_if (plugin->kdbSet (plugin, ks, parentKey) == 1, "call to kdbSet was not successful"); + + succeed_if (plugin->kdbError (plugin, ks, parentKey) == 1, "call to kdbError was not successful"); + + succeed_if (plugin->kdbClose (plugin, parentKey) == 1, "call to kdbClose was not successful"); + + keyDel (parentKey); + ksDel (ks); + PLUGIN_CLOSE (); +} + + +int main (int argc, char ** argv) +{ + printf ("ITERATE TESTS\n"); + printf ("==================\n\n"); + + init (argc, argv); + + test_basics (); + + print_result ("testmod_iterate"); + + return nbError; +} diff --git a/pool/shard002/C/0058153_p_median3x3.c b/pool/shard002/C/0058153_p_median3x3.c new file mode 100644 index 0000000000000000000000000000000000000000..925d1d174548c7e737d76ad3585c35809bedeed3 --- /dev/null +++ b/pool/shard002/C/0058153_p_median3x3.c @@ -0,0 +1,118 @@ +#include + +#define SORT(a,b) \ +do { \ + if (a < b) { \ + float d = a; \ + a = b; \ + b = d; \ + } \ +} while(0) + +#define SORT_HI(a,b) \ +do { \ + b = (a < b) ? a : b; \ +} while(0) + +#define SORT_LO(a,b) \ +do { \ + a = (a < b) ? b : a; \ +} while(0) + +static __inline __attribute__((__always_inline__)) +float my_median( + float v0, float v1, float v2, + float v3, float v4, float v5, + float v6, float v7, float v8); + +/* + * A median 3x3 filter. + * + * @param x Pointer to input image, a 2D array of size 'rows' x 'cols' + * @param r Pointer to output image, a 2D array pf size 'rows-2' x 'cols-2' + * @param rows Number of rows in input image + * @param cols Number of columns in input image + * @return None + */ + +void p_median3x3_f32(const float *x, float *r, int rows, int cols) +{ + float v0,v1,v2,v3,v4,v5,v6,v7,v8; + const float *px = x; + float *pr = r; + int i, j; + + for (i = 0; i < rows - 2; i++) { + v3 = *(px); + v4 = *(px + cols); + v5 = *(px + 2*cols); + SORT(v4,v5); + SORT(v3,v4); + SORT(v4,v5); + v6 = *(px + 1); + v7 = *(px + cols + 1); + v8 = *(px + 2*cols + 1); + SORT(v7,v8); + SORT(v6,v7); + SORT(v7,v8); + for (j = 0; j < cols - 2; j++) { + v0 = v3; + v1 = v4; + v2 = v5; + v3 = v6; + v4 = v7; + v5 = v8; + v6 = *(px + 2); + v7 = *(px + cols + 2); + v8 = *(px + 2*cols + 2); + SORT(v7,v8); + SORT(v6,v7); + SORT(v7,v8); + + *(pr++) = my_median(v0,v1,v2,v3,v4,v5,v6,v7,v8); + px++; + } + px += 2; + } +} + +/* + * A specialized median 3x3 filter. + * + * The routine is inlined for performance and requires that the v0-v2, + * v3-v5, and v6-v8 triplets be ordered from largest to smallest. This + * improves performance while sweeping through columns of values. + * Macros handle the swapping of values and do not swap values which + * won't be used again. + * + * @param v0 The largest value in the triplet v0-v2 + * @param v1 The median value in the triplet v0-v2 + * @param v2 The smallest value in the triplet v0-v2 + * @param v3 The largest value in the triplet v3-v5 + * @param v4 The median value in the triplet v3-v5 + * @param v5 The smallest value in the triplet v3-v5 + * @param v6 The largest value in the triplet v6-v8 + * @param v7 The median value in the triplet v6-v8 + * @param v8 The smallest value in the triplet v6-v8 + * @return The median value of the set v0-v8 + */ + +static __inline __attribute((__always_inline__)) +float my_median( + float v0, float v1, float v2, + float v3, float v4, float v5, + float v6, float v7, float v8) +{ + SORT_HI(v0,v3); + SORT_LO(v5,v8); + SORT(v4,v7); + SORT_HI(v3,v6); + SORT_HI(v1,v4); + SORT_LO(v2,v5); + SORT_LO(v4,v7); + SORT(v4,v2); + SORT_HI(v6,v4); + SORT_LO(v4,v2); + return v4; +} + diff --git a/pool/shard002/C/0058156_loupe.c b/pool/shard002/C/0058156_loupe.c new file mode 100644 index 0000000000000000000000000000000000000000..9508d662b74bf66fead33e9fe74b102bea0a411d --- /dev/null +++ b/pool/shard002/C/0058156_loupe.c @@ -0,0 +1,212 @@ +#include +#include +#include + +/* #define USE_IMAGEMAGICK 1 */ + +#define ZOOMWN_WIDTH 256 +#define ZOOMWN_HEIGHT 256 + +typedef struct _pixel_rgb { + unsigned char a; + unsigned char r; + unsigned char g; + unsigned char b; +} pixel_rgb; + +/* 1¥Ô¥¯¥»¥ë¤ò¥²¥Ã¥È */ +static pixel_rgb get_pixel( int width, int height, const unsigned char *buf, + int x, int y ) +{ + const unsigned char (*p)[4] = (const unsigned char (*)[4])buf; + pixel_rgb pix; + if ( 0 <= x && x < width && 0 <= y && y < height ) { + long i = (long)y * width + (long)x; + pix.a = p[i][0]; + pix.r = p[i][1]; + pix.g = p[i][2]; + pix.b = p[i][3]; + } + else { + pix.a = 0; + pix.r = 0; + pix.g = 0; + pix.b = 0; + } + return pix; +} + +/* ³ÈÂ礵¤ì¤¿¥¤¥á¡¼¥¸¤ò¼èÆÀ */ +static void get_zoom_image( int src_width, int src_height, + const unsigned char *src_buf, + int center_x, int center_y, int zoom_factor, + int dest_width, int dest_height, + unsigned char *dest_buf ) +{ + unsigned char (*dest_p)[4] = (unsigned char (*)[4])dest_buf; + pixel_rgb pix; + long i; + for ( i=0 ; i < dest_height ; i++ ) { + long j, sx, sy; + sy = center_y - dest_height/2/zoom_factor + i/zoom_factor; + for ( j=0 ; j < dest_width ; j++ ) { + long idx = i * dest_width + j; + sx = center_x - dest_width/2/zoom_factor + j/zoom_factor; + pix = get_pixel(src_width, src_height, src_buf, sx, sy); + dest_p[idx][0] = pix.a; + dest_p[idx][1] = pix.r; + dest_p[idx][2] = pix.g; + dest_p[idx][3] = pix.b; + } + } +} + +int main( int argc, char *argv[] ) +{ + int ret = 1; + int win_main, win_zoom, zoom_factor = 2; + double p_x = -1, p_y = -1; + unsigned char *zoom_buf = NULL; + unsigned char *img_buf = NULL; + int img_width, img_height, img_msk; + int crosshairs = 1; + + if ( argc < 2 ) { + fprintf(stderr,"[USAGE]\n"); + fprintf(stderr,"%s filename.png\n",argv[0]); + return 1; + } + + /* zoom ¥¦¥£¥ó¥É¥¥ÍѤβèÁü¥Ð¥Ã¥Õ¥¡ */ + zoom_buf = (unsigned char *)malloc(ZOOMWN_WIDTH * ZOOMWN_HEIGHT * 4); + if ( zoom_buf == NULL ) goto quit; + + //img_buf = readimage(NULL,argv[1],&img_width,&img_height,&img_msk); + //img_buf = readimage("xbmtopbm",argv[1],&img_width,&img_height,&img_msk); +#ifdef USE_IMAGEMAGICK + img_buf = readimage("convert",argv[1],&img_width,&img_height,&img_msk); +#else + img_buf = readimage("pngtopnm",argv[1],&img_width,&img_height,&img_msk); +#endif + if ( img_buf == NULL ) { + fprintf(stderr,"ERROR: cannot read file\n"); + goto quit; + } + printf("mask value = %d\n",img_msk); + + /* °À­ÀßÄê(º¸¾å¤ò¸¶ÅÀ¤Ë¤¹¤ë) */ + gsetinitialattributes(DISABLE, BOTTOM_LEFT_ORIGIN); + /* ¥¦¥£¥ó¥É¥¥¤Î¥ª¡¼¥×¥ó */ + win_zoom = gopen(ZOOMWN_WIDTH*2, ZOOMWN_HEIGHT); + win_main = gopen(img_width, img_height); + layer(win_zoom,0,1); + + /* ¥á¥¤¥ó¥¦¥£¥ó¥É¥¥¤Ø¤Î²èÁü¤ÎžÁ÷ */ + gclr(win_main); + gputimage(win_main, 0,0, img_buf, img_width, img_height, img_msk); + + /* ¥«¡¼¥½¥ëÉÁ²è¤Î¤¿¤á¤Ë¡¤XOR ¤Ç¤ÎÉÁ²èfunction¤ËÀßÄê */ + newgcfunction(win_main, GXxor); + newcolor(win_main, "red"); + +#if 0 /* Êݸ¤Î¥Æ¥¹¥È */ + //writeimage(img_buf,img_width,img_height,img_msk,"pnmtopng",256,"hoge.png"); + //writeimage(img_buf,img_width,img_height,img_msk,NULL,256,"hoge.pam"); + gsaveimage( win_main,0,0,0,1999,1999,"pnmtopng",256,"capt0.png"); + { + int im_w, im_h; + unsigned char *im = ggetimage(win_main,0,0,0,1999,1999,&im_w,&im_h); + writeimage(im_w,im_h,im,0,"pnmtopng",256,"capt.png"); + if ( im != NULL ) free(im); + } +#endif + + /* ¥á¥¤¥ó¥ë¡¼¥× */ + while ( 1 ) { + int win_ev, type, b; + int needs_redraw = 0; + double x, y; + win_ev = ggetevent(&type,&b,&x,&y) ; + if ( type == EnterNotify ) { + fprintf(stderr,"event type = EnterNotify wid=%d\n",win_ev); + } + else if ( type == LeaveNotify ) { + fprintf(stderr,"event type = LeaveNotify wid=%d\n",win_ev); + } + else { + fprintf(stderr,"event type = %d wid=%d\n",type,win_ev); + } + if ( win_ev == win_main ) { + if ( type == MotionNotify || + type == EnterNotify || type == LeaveNotify ) { + if ( type == LeaveNotify ) { + x = -32000; y = -32000; + } + if ( crosshairs ) { + /* crosshairs ¥«¡¼¥½¥ë¤ò¾Ã¤¹ */ + drawline(win_main, 0,p_y, img_width,p_y); + drawline(win_main, p_x,0, p_x,img_height); + /* crosshairs ¥«¡¼¥½¥ë¤òɽ¼¨¤¹¤ë */ + drawline(win_main, 0,y, img_width,y); + drawline(win_main, x,0, x,img_height); + } + needs_redraw = 1; + p_x = x; + p_y = y; + } + else if ( type == ButtonPress ) { + if ( b == 1 ) zoom_factor++; + else if ( b == 3 ) zoom_factor--; + needs_redraw = 1; + } + } + if ( type == KeyPress ) { + if ( b == 'q' ) goto quit; + else if ( b == '>' || b == '+' ) zoom_factor++; + else if ( b == '<' || b == '-' ) zoom_factor--; + else if ( b == ' ' ) { + if ( crosshairs ) { + /* crosshairs ¥«¡¼¥½¥ë¤ò¾Ã¤¹ */ + drawline(win_main, 0,p_y, img_width,p_y); + drawline(win_main, p_x,0, p_x,img_height); + crosshairs = 0; + } + else { + /* crosshairs ¥«¡¼¥½¥ë¤òɽ¼¨¤¹¤ë */ + drawline(win_main, 0,p_y, img_width,p_y); + drawline(win_main, p_x,0, p_x,img_height); + crosshairs = 1; + } + } + needs_redraw = 1; + } + if ( needs_redraw ) { + if ( zoom_factor < 2 ) zoom_factor = 2; + else if ( 32 < zoom_factor ) zoom_factor = 32; + get_zoom_image(img_width, img_height, + img_buf, p_x, p_y, zoom_factor, + ZOOMWN_WIDTH, ZOOMWN_HEIGHT, zoom_buf); + gclr(win_zoom); + /* ÉáÄ̤Υ³¥Ô¡¼ */ + newgcfunction(win_zoom, GXcopy); + gputimage(win_zoom, 0, 0, + zoom_buf, ZOOMWN_WIDTH, ZOOMWN_HEIGHT, img_msk); + /* ȿž¥³¥Ô¡¼ */ + newgcfunction(win_zoom, GXcopyInverted); + gputarea(win_zoom, ZOOMWN_WIDTH, 0, + win_zoom,1, 0,0,ZOOMWN_WIDTH-1, ZOOMWN_HEIGHT-1); + /* ¥º¡¼¥à¥¦¥£¥ó¥É¥¥¤Ç¡¤Ê¸»úÎó¤òȿžÉÁ²è¤¹¤ë */ + newgcfunction(win_zoom, GXinvert); + drawstr(win_zoom,2,14,14,0, + "%dx zoom pos=(%g,%g)\n",zoom_factor,p_x,p_y); + copylayer(win_zoom,1,0); + } + } + + ret = 0; + quit: + gcloseall(); + if ( img_buf != NULL ) free(img_buf); + if ( zoom_buf != NULL ) free(zoom_buf); + return ret; +} diff --git a/pool/shard002/C/0058157_opt_only_diff_items.c b/pool/shard002/C/0058157_opt_only_diff_items.c new file mode 100644 index 0000000000000000000000000000000000000000..481f32088d95841b81cbaa90f2165f59841c1800 --- /dev/null +++ b/pool/shard002/C/0058157_opt_only_diff_items.c @@ -0,0 +1,117 @@ +#include +#include +#include +#include + +#include +#include "tdb_test.h" + +#define NUM_EVENTS 1234 + +static void simple_case(const char *root) +{ + static uint8_t uuid[16]; + const char *fields[] = {"a"}; + const char *values[] = {"foobar"}; + uint64_t lengths[] = {6}; + uint64_t i; + tdb_opt_value value = {.value = 0}; + + tdb_cons* c = tdb_cons_init(); + test_cons_settings(c); + assert(tdb_cons_open(c, root, fields, 1) == 0); + for (i = 0; i < NUM_EVENTS; i++) + assert(tdb_cons_add(c, uuid, i, values, lengths) == 0); + assert(tdb_cons_finalize(c) == 0); + tdb_cons_close(c); + + tdb* t = tdb_init(); + assert(tdb_open(t, root) == 0); + + /* basic get_opt */ + assert(tdb_get_opt(t, 0, &value) == TDB_ERR_UNKNOWN_OPTION); + assert(tdb_get_opt(t, TDB_OPT_ONLY_DIFF_ITEMS, &value) == 0); + assert(value.value == TDB_FALSE.value); + + /* basic set_opt */ + assert(tdb_set_opt(t, 0, value) == TDB_ERR_UNKNOWN_OPTION); + assert(tdb_set_opt(t, TDB_OPT_ONLY_DIFF_ITEMS, TDB_TRUE) == 0); + assert(tdb_get_opt(t, TDB_OPT_ONLY_DIFF_ITEMS, &value) == 0); + assert(value.value == TDB_TRUE.value); + + tdb_cursor *cursor = tdb_cursor_new(t); + assert(tdb_get_trail(cursor, 0) == 0); + const tdb_event *event = tdb_cursor_next(cursor); + assert(event->timestamp == 0); + assert(event->num_items == 1); + assert(event->items[0] == tdb_get_item(t, 1, "foobar", 6)); + + for (i = 0; (event = tdb_cursor_next(cursor)); i++){ + assert(event->timestamp == i + 1); + /* + this is the point of OPT_ONLY_DIFF_ITEMS: + since the value doesn't change, no items are returned + */ + assert(event->num_items == 0); + } + assert(i == NUM_EVENTS - 1); + + tdb_close(t); + tdb_cursor_free(cursor); +} + +static void two_field_case(const char *root) +{ + static uint8_t uuid[16]; + const char *fields[] = {"a", "b"}; + char val1 = 0; + char val2 = 0; + const char *values[] = {&val1, &val2}; + uint64_t lengths[] = {1, 1}; + uint64_t i; + const tdb_event *event; + + tdb_cons* c = tdb_cons_init(); + test_cons_settings(c); + assert(tdb_cons_open(c, root, fields, 2) == 0); + for (i = 0; i < NUM_EVENTS; i++){ + val1 = i; + assert(tdb_cons_add(c, uuid, i, values, lengths) == 0); + } + val2 = 1; + for (i = 0; i < NUM_EVENTS; i++){ + val1 = i; + assert(tdb_cons_add(c, uuid, NUM_EVENTS + i, values, lengths) == 0); + } + assert(tdb_cons_finalize(c) == 0); + tdb_cons_close(c); + + tdb* t = tdb_init(); + assert(tdb_open(t, root) == 0); + assert(tdb_set_opt(t, TDB_OPT_ONLY_DIFF_ITEMS, TDB_TRUE) == 0); + tdb_cursor *cursor = tdb_cursor_new(t); + assert(tdb_get_trail(cursor, 0) == 0); + + /* the first field changes at every event, the second field changes twice: + in the beginning and at the midpoint */ + for (i = 0; (event = tdb_cursor_next(cursor)); i++){ + assert(event->timestamp == i); + if (event->num_items == 2) + assert(i == 0 || i == NUM_EVENTS); + else{ + assert(event->num_items == 1); + assert(tdb_item_field(event->items[0]) == 1); + } + } + assert(i == NUM_EVENTS * 2); + + tdb_close(t); + tdb_cursor_free(cursor); +} + +int main(int argc, char** argv) +{ + simple_case(getenv("TDB_TMP_DIR")); + two_field_case(getenv("TDB_TMP_DIR")); + return 0; +} diff --git a/pool/shard002/C/0058160_loox720_ts.c b/pool/shard002/C/0058160_loox720_ts.c new file mode 100644 index 0000000000000000000000000000000000000000..aa5c607e4987cbe74d90853143f6f874106dfd0a --- /dev/null +++ b/pool/shard002/C/0058160_loox720_ts.c @@ -0,0 +1,161 @@ +/* + * Touchscreen driver for Axim X50/X51(v). + * + * 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) 2007 Pierre Gaufillet + * + */ + +#include +#include +#include +#include +#include + +#include +#include +#include + +//#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "../generic.h" + +/* borrowed from lubbock.c */ + +static int loox720_ads7846_pendown_state(void) +{ + return ((gpio_get_value(GPIO_NR_LOOX720_TOUCHPANEL_IRQ_N)) ? 0 : 1); +} + +static struct ads7846_platform_data ads_info = { + .model = 7845, + .get_pendown_state = loox720_ads7846_pendown_state, + .debounce_max = 12, + .debounce_tol = 4, + .debounce_rep = 1, + .penirq_recheck_delay_usecs = 20, +}; + +static struct pxa2xx_spi_chip ads_hw = { + .tx_threshold = 3, + .rx_threshold = 3, +// .cs_control = ads7846_cs, +// .timeout = 1200, + .enable_loopback = 0, + .dma_burst_size = 0, +}; + +static struct spi_board_info spi_board_info[] __initdata = { + { + .modalias = "ads7846", + .platform_data = &ads_info, + .controller_data = &ads_hw, + .irq = IRQ_GPIO(GPIO_NR_LOOX720_TOUCHPANEL_IRQ_N), + .max_speed_hz = 100000, + .bus_num = 1, + .chip_select = 0, + .mode = SPI_MODE_0, + }, +}; + +#if 0 +static struct ads7846_ssp_platform_data loox720_ts_ssp_params = { + .port = 1, + .pd_bits = 1, + .freq = 50000, +}; +static struct platform_device ads7846_ssp = { + .name = "ads7846-ssp", + .id = -1, + .dev = { + .platform_data = &loox720_ts_ssp_params, + } +}; + +static struct tsadc_platform_data loox720_ts_params = { +// .pen_irq = LOOX720_IRQ(TOUCHPANEL_IRQ_N), + .pen_gpio = GPIO_NR_LOOX720_TOUCHPANEL_IRQ_N, + .x_pin = "ads7846-ssp:x", + .y_pin = "ads7846-ssp:y", + .z1_pin = "ads7846-ssp:z1", + .z2_pin = "ads7846-ssp:z2", + .pressure_factor = 100000, + .min_pressure = 5, + .delayed_pressure=1, + .max_jitter = 8, + .num_xy_samples = 10, +}; +static struct resource loox720_pen_irq = { + .start = IRQ_GPIO(GPIO_NR_LOOX720_TOUCHPANEL_IRQ_N), + .end = IRQ_GPIO(GPIO_NR_LOOX720_TOUCHPANEL_IRQ_N), + .flags = IORESOURCE_IRQ, +}; +static struct platform_device loox720_ts = { + .name = "ts-adc", + .id = -1, + .resource = &loox720_pen_irq, + .num_resources = 1, + .dev = { + .platform_data = &loox720_ts_params, + } +}; +#endif + +static int __devinit loox720_ts_probe(struct platform_device *dev) +{ + //platform_device_register(&ads7846_ssp); + //platform_device_register(&loox720_ts); + + // commented out since this currently hangs the kernel. + if (gpio_request(GPIO_NR_LOOX720_TOUCHPANEL_IRQ_N, "Touchscreen IRQ") != 0) + return -ENODEV; + spi_register_board_info(spi_board_info, ARRAY_SIZE(spi_board_info)); + return 0; +} + +static int __devexit loox720_ts_remove(struct platform_device *dev) +{ + gpio_free(GPIO_NR_LOOX720_TOUCHPANEL_IRQ_N); + return 0; +} + +static struct platform_driver loox720_ts_driver = { + .driver = { + .name = "loox720-ts", + }, + .probe = loox720_ts_probe, + .remove = loox720_ts_remove, +}; + +static int __init loox720_ts_init(void) +{ + if (!machine_is_loox720()) + return -ENODEV; + + return platform_driver_register(&loox720_ts_driver); +} + +static void __exit loox720_ts_exit(void) +{ + platform_driver_unregister(&loox720_ts_driver); +} + + +module_init(loox720_ts_init); +module_exit(loox720_ts_exit); + +MODULE_AUTHOR ("Pierre Gaufillet"); +MODULE_DESCRIPTION ("Touchscreen support for LOOX718/720"); +MODULE_LICENSE ("GPL"); diff --git a/pool/shard002/C/0058161_uart_interrupt.c b/pool/shard002/C/0058161_uart_interrupt.c new file mode 100644 index 0000000000000000000000000000000000000000..69c455ba29048be204ef849b022d067d8cc0c046 --- /dev/null +++ b/pool/shard002/C/0058161_uart_interrupt.c @@ -0,0 +1,140 @@ + +#include "lpc17xx_libcfg_default.h" +#include "lpc17xx_pinsel.h" +#include "lpc17xx_uart.h" +#include "uart_interrupt.h" + +void UART_IntErr(uint8_t bLSErrType); +void UART_IntTransmit(void); +void UART_IntReceive(void); + +// UART Ring buffer +UART_RING_BUFFER_T * rb; + +// Current Tx Interrupt enable state +__IO FlagStatus TxIntStat; + +/*----------------- INTERRUPT SERVICE ROUTINES --------------------------*/ +/*********************************************************************//** + * @brief UART0 interrupt handler sub-routine + * @param[in] None + * @return None + **********************************************************************/ +void UART0_IRQHandler(void) +{ + uint32_t intsrc, tmp, tmp1; + + /* Determine the interrupt source */ + intsrc = UART_GetIntId(LPC_UART0); + tmp = intsrc & UART_IIR_INTID_MASK; + + // Receive Line Status + if (tmp == UART_IIR_INTID_RLS){ + // Check line status + tmp1 = UART_GetLineStatus(LPC_UART0); + // Mask out the Receive Ready and Transmit Holding empty status + tmp1 &= (UART_LSR_OE | UART_LSR_PE | UART_LSR_FE \ + | UART_LSR_BI | UART_LSR_RXFE); + // If any error exist + if (tmp1) { + UART_IntErr(tmp1); + } + } + + // Receive Data Available or Character time-out + if ((tmp == UART_IIR_INTID_RDA) || (tmp == UART_IIR_INTID_CTI)){ + UART_IntReceive(); + } + + // Transmit Holding Empty + if (tmp == UART_IIR_INTID_THRE){ + UART_IntTransmit(); + } +} + +/********************************************************************//** + * @brief UART receive function (ring buffer used) + * @param[in] None + * @return None + *********************************************************************/ +void UART_IntReceive(void) +{ + uint8_t tmpc; + uint32_t rLen; + + while(1){ + // Call UART read function in UART driver + rLen = UART_Receive((LPC_UART_TypeDef *)LPC_UART0, &tmpc, 1, NONE_BLOCKING); + // If data received + if (rLen){ + /* Check if buffer is more space + * If no more space, remaining character will be trimmed out + */ + if (!__BUF_IS_FULL(rb->rx_head,rb->rx_tail)){ + rb->rx[rb->rx_head] = tmpc; + __BUF_INCR(rb->rx_head); + } + } + // no more data + else { + break; + } + } +} + +/********************************************************************//** + * @brief UART transmit function (ring buffer used) + * @param[in] None + * @return None + *********************************************************************/ +void UART_IntTransmit(void) +{ + // Disable THRE interrupt + UART_IntConfig((LPC_UART_TypeDef *)LPC_UART0, UART_INTCFG_THRE, DISABLE); + + /* Wait for FIFO buffer empty, transfer UART_TX_FIFO_SIZE bytes + * of data or break whenever ring buffers are empty */ + /* Wait until THR empty */ + while (UART_CheckBusy((LPC_UART_TypeDef *)LPC_UART0) == SET); + + while (!__BUF_IS_EMPTY(rb->tx_head,rb->tx_tail)) + { + /* Move a piece of data into the transmit FIFO */ + if (UART_Send((LPC_UART_TypeDef *)LPC_UART0, (uint8_t *)&rb->tx[rb->tx_tail], 1, NONE_BLOCKING)){ + /* Update transmit ring FIFO tail pointer */ + __BUF_INCR(rb->tx_tail); + } else { + break; + } + } + + /* If there is no more data to send, disable the transmit + interrupt - else enable it or keep it enabled */ + if (__BUF_IS_EMPTY(rb->tx_head, rb->tx_tail)) { + UART_IntConfig((LPC_UART_TypeDef *)LPC_UART0, UART_INTCFG_THRE, DISABLE); + // Reset Tx Interrupt state + TxIntStat = RESET; + } + else{ + // Set Tx Interrupt state + TxIntStat = SET; + UART_IntConfig((LPC_UART_TypeDef *)LPC_UART0, UART_INTCFG_THRE, ENABLE); + } +} + + +/*********************************************************************//** + * @brief UART Line Status Error + * @param[in] bLSErrType UART Line Status Error Type + * @return None + **********************************************************************/ +void UART_IntErr(uint8_t bLSErrType) +{ + uint8_t test; + // Loop forever + while (1){ + // For testing purpose + test = bLSErrType; + } +} + diff --git a/pool/shard002/C/0058169_customCudaUtils.c b/pool/shard002/C/0058169_customCudaUtils.c new file mode 100644 index 0000000000000000000000000000000000000000..ad220faf3bd7cfb808c7e9873975ea85ee28d722 --- /dev/null +++ b/pool/shard002/C/0058169_customCudaUtils.c @@ -0,0 +1,175 @@ +#ifdef __cplusplus +extern "C" +{ +#endif + +#include +#include +#include +#include + +#include "customCudaUtils.h" + +// get number of devices available +int getGPUDeviceCount(){ + cudaError_t err; + int numDevices; + + err = cudaGetDeviceCount(&numDevices); + if( err == cudaSuccess ) + return numDevices; + return 0; +} + +// get the max or min in a float array. type is 'M' for max, 'm' for min +float findExtremeFloatArray(float* A, int size, int onDevice, char type, int* index) +{ + cudaError_t err; + int i; + float max = 0; + + if(onDevice) + { + float* temp = A; + A = (float*)malloc(size * sizeof(float)); + + err = cudaMemcpy(A, temp, size * sizeof(float), cudaMemcpyDeviceToHost); + checkCudaError(err); + } + + for(i = 0; i < size; i++) + { + if(type == 'M') + { + if(A[i] > max) + { + max = A[i]; + *index = i; + } + }else if(type == 'm') + { + if(A[i] < max) + { + max = A[i]; + *index = i; + } + } + } + + if(onDevice) + free(A); + + return max; +} + +void printFloatArray(float* A, int M, int N, int onDevice) +{ + cudaError_t err; + int i, j; + + if(onDevice) + { + float* temp = A; + A = (float*)malloc(M * N * sizeof(float)); + + err = cudaMemcpy(A, temp, M * N * sizeof(float), cudaMemcpyDeviceToHost); + checkCudaError(err); + } + + for(i = 0; i < M; i++) + { + for(j = 0; j < N; j++) + { + printf("%f ", A[j + i * N]); + } + printf("\n"); + } + + printf("\n"); + + if(onDevice) + { + free(A); + } +} + + +// Takes in two arrays, each of size ldA * ldB. It takes the contents of A and stores it in B +// in the opposite storage orientation (eg if A is row major, then B comes out column major) +// lda is the leading dimension of A, ldb that of B +void switchFloatArrayStorage(float* A, float* B, int ldA, int ldB) +{ + int i, j; + + for(i=0;i + * + * 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; only 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. + */ +/* + * supports for GGZ code + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "server.h" +#include "player.h" + +#ifdef WITH_GGZ + +#include +#include + +static GGZdMod *g_ggzdmod = NULL; + +static void _handle_ggz_state(GGZdMod *ggz, GGZdModEvent event, const void *data); +static void _handle_ggz_error(GGZdMod *ggz, GGZdModEvent event, const void *data); + +static void _handle_ggz_join(GGZdMod *ggz, GGZdModEvent event, const void *data); +static void _handle_ggz_leave(GGZdMod *ggz, GGZdModEvent event, const void *data); +static void _handle_ggz_player(GGZdMod *ggz, GGZdModEvent event, const void *data); + +static void _handle_ggz_spectator_join(GGZdMod *ggz, GGZdModEvent event, const void *data); +static void _handle_ggz_spectator_leave(GGZdMod *ggz, GGZdModEvent event, const void *data); +static void _handle_ggz_spectator(GGZdMod *ggz, GGZdModEvent event, const void *data); + + +/* Setup game state and board */ +static int teg_ggz_init() +{ + g_ggzdmod = ggzdmod_new(GGZDMOD_GAME); + if( ! g_ggzdmod ) + return -1; + + /* Setup GGZ game module */ + ggzdmod_set_handler(g_ggzdmod, GGZDMOD_EVENT_STATE, &_handle_ggz_state); + ggzdmod_set_handler(g_ggzdmod, GGZDMOD_EVENT_ERROR, &_handle_ggz_error); + + ggzdmod_set_handler(g_ggzdmod, GGZDMOD_EVENT_JOIN, &_handle_ggz_join); + ggzdmod_set_handler(g_ggzdmod, GGZDMOD_EVENT_LEAVE, &_handle_ggz_leave); + ggzdmod_set_handler(g_ggzdmod, GGZDMOD_EVENT_PLAYER_DATA, &_handle_ggz_player); + + ggzdmod_set_handler(g_ggzdmod, GGZDMOD_EVENT_SPECTATOR_JOIN, &_handle_ggz_spectator_join); + ggzdmod_set_handler(g_ggzdmod, GGZDMOD_EVENT_SPECTATOR_LEAVE, &_handle_ggz_spectator_leave); + ggzdmod_set_handler(g_ggzdmod, GGZDMOD_EVENT_SPECTATOR_DATA, &_handle_ggz_spectator); + + return 0; +} +/* Callback for GGZDMOD_EVENT_STATE */ +static void _handle_ggz_state(GGZdMod *ggz, GGZdModEvent event, const void *data) +{ + switch(ggzdmod_get_state(ggz)) { + case GGZDMOD_STATE_PLAYING: + break; + case GGZDMOD_STATE_WAITING: + { + GGZSeat seat; + int i; + int robot_socket; + int max = ggzdmod_get_num_seats( g_ggzdmod ); + + // launch robots if necesary + for (i = 0; i < max; i++) { + seat = ggzdmod_get_seat( g_ggzdmod, i ); + if( seat.type == GGZ_SEAT_BOT ) { + if (launch_robot( &robot_socket, "--ggz" ) == TEG_STATUS_SUCCESS ) + { + seat.fd = robot_socket; + + ggzdmod_set_seat( g_ggzdmod, &seat ); + + net_printf(seat.fd,"%s=1\n",TOKEN_GGZ); + } else + ggzdmod_log(g_ggzdmod, "\tegserver: Failed launching bot :-(!"); + } + } + break; + } + case GGZDMOD_STATE_DONE: + break; + default: + break; + } +} + +static int seats_is_full(void) +{ + return ggzdmod_count_seats(g_ggzdmod, GGZ_SEAT_OPEN) + + ggzdmod_count_seats(g_ggzdmod, GGZ_SEAT_RESERVED) == 0; +} + +/* Callback for GGZDMOD_EVENT_ERROR */ +static void _handle_ggz_error(GGZdMod *ggz, GGZdModEvent event, const void *data) +{ +} + +/* Callback for GGZDMOD_EVENT_JOIN */ +static void _handle_ggz_join(GGZdMod *ggz, GGZdModEvent event, const void *data) +{ + GGZSeat *old_seat = (GGZSeat*)data; + GGZSeat new_seat = ggzdmod_get_seat(ggz, old_seat->num); + + net_printf(new_seat.fd,"%s=1\n", TOKEN_GGZ); + + /* XXX: We start playing only when there are no open seats. */ + if (seats_is_full()) + ggzdmod_set_state( g_ggzdmod, GGZDMOD_STATE_PLAYING); +} + +/* Callback for GGZDMOD_EVENT_LEAVE */ +static void _handle_ggz_leave(GGZdMod *ggz, GGZdModEvent event, const void *data) +{ + GGZSeat *s = (GGZSeat*) data; + token_exit( s->fd ); + + if( ggzdmod_count_seats(ggz, GGZ_SEAT_PLAYER) == 0 ) + // the game will exit when all human players are gone + ggzdmod_set_state(ggz, GGZDMOD_STATE_DONE); +} + +/* Handle message from player */ +static void _handle_ggz_player(GGZdMod *ggz, GGZdModEvent event, const void *data) +{ + int num = *(int*)data; + int fd; + GGZSeat seat; + + seat = ggzdmod_get_seat(ggz, num); + fd = seat.fd; + if(play_teg( fd )== TEG_STATUS_CONNCLOSED) { + seat.type = GGZ_SEAT_OPEN; + ggzdmod_set_seat( g_ggzdmod, &seat ); + } +} + +/* Callback for GGZDMOD_EVENT_SPECTATOR_JOIN */ +static void _handle_ggz_spectator_join(GGZdMod *ggz, GGZdModEvent event, const void *data) +{ + GGZSpectator s; + s = ggzdmod_get_spectator( ggz, *(int*) data ); + +/* fprintf( stderr, "new spectator in fd: %d-%s (%d)\n",s.fd,s.name, *(int*) data ); */ + + net_printf(s.fd,"%s=0\n", TOKEN_GGZ); +} + +/* Callback for GGZDMOD_EVENT_SPECTATOR_LEAVE */ +static void _handle_ggz_spectator_leave(GGZdMod *ggz, GGZdModEvent event, const void *data) +{ + GGZSeat *s = (GGZSeat*) data; + + token_exit( s->fd ); +} + +/* Handle message from observer*/ +static void _handle_ggz_spectator(GGZdMod *ggz, GGZdModEvent event, const void *data) +{ + GGZSpectator s; + s = ggzdmod_get_spectator( ggz, *(int*) data ); + +/* fprintf( stderr, "data from spectator in fd: %d-%s (%d)\n",s.fd,s.name, *(int*) data ); */ + + if(play_teg( s.fd )== TEG_STATUS_CONNCLOSED) { + /* XXX: What do I have to do when an spectator leaves ? */ + } +} + +TEG_STATUS ggz_server_find_ggzname( int fd, char *n, int len ) +{ + int max, i; + GGZSeat seat; + GGZSpectator spectator; + + if(!n) + return TEG_STATUS_ERROR; + + max = ggzdmod_get_num_seats( g_ggzdmod ); + for(i=0;ifd == seat.fd ){ + scores[i] = pJ->player_stats.score; + } + pL = LIST_NEXT(pL); + } + } + + ggzdmod_report_game( g_ggzdmod, NULL, results, scores ); +} + +int ggz_server_main_loop() +{ + if( teg_ggz_init() == -1 ) + return -1; + + /* Connect to GGZ server; main loop */ + if (ggzdmod_connect( g_ggzdmod) < 0) + return -1; + + (void) ggzdmod_loop( g_ggzdmod ); + (void) ggzdmod_disconnect( g_ggzdmod ); + + ggzdmod_free( g_ggzdmod ); + + return 0; +} + + +#endif /* WITH_GGZ */ diff --git a/pool/shard002/C/0058191_Tarea4_ejer3.c b/pool/shard002/C/0058191_Tarea4_ejer3.c new file mode 100644 index 0000000000000000000000000000000000000000..254273d602a7648b13f1e31e092bbc118fbd4b7b --- /dev/null +++ b/pool/shard002/C/0058191_Tarea4_ejer3.c @@ -0,0 +1,43 @@ +/* +PUNTO A) linea: 7, 38 +PUNTO B) linea: 15, 35 +*/ +#include +char *corta_string(char *apuntador){ + // ### PUNTO A) + if(*(apuntador=apuntador+1)!='\0'){ + return apuntador; + } + printf("Error: Se introdujo un único caracter\n"); + return --apuntador; +} + +// ### PUNTO B) +char *corta_string_B(char *apuntador){ + if ( *(apuntador+1)=='\0' ) + { + printf("Error: Se introdujo un único caracter\n"); + return apuntador; + } + printf("%s\n", apuntador); + while(*(apuntador+1)!=' ' && *(apuntador+1)!='\0'){ + apuntador++; + } + return apuntador+2; +} + +int main(void){ + char *s="Campos verdes"; + char *f="X"; + printf("Cadena original: %s\n", s); + s=corta_string(s); + printf("Quitando primer caracter: %s\n",s); + // ### PUNTO B) + s=corta_string_B(s); + printf("Quitando hasta primer espacio: %s\n",s); + printf("Intentando con un solo caracter (X): \n"); + f=corta_string(f); + printf("%s\n", f); + +return 0; +} \ No newline at end of file diff --git a/pool/shard002/C/0058209_packet-yppasswd.c b/pool/shard002/C/0058209_packet-yppasswd.c new file mode 100644 index 0000000000000000000000000000000000000000..3f26a4c7e72dae8ed2006eff5d2aabd4c272d69e --- /dev/null +++ b/pool/shard002/C/0058209_packet-yppasswd.c @@ -0,0 +1,173 @@ +/* packet-yppasswd.c + * Routines for yppasswd dissection + * + * $Id: packet-yppasswd.c 45017 2012-09-20 02:03:38Z morriss $ + * + * Wireshark - Network traffic analyzer + * By Gerald Combs + * Copyright 1998 Gerald Combs + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +#include "config.h" + +#if defined(LEAN_YP) +# error LEAN_YP: Should not be build +#endif + +#include "packet-rpc.h" +#include "packet-yppasswd.h" + +static int proto_yppasswd = -1; +static int hf_yppasswd_procedure_v1 = -1; +static int hf_yppasswd_status = -1; +static int hf_yppasswd_oldpass = -1; +static int hf_yppasswd_newpw = -1; +static int hf_yppasswd_newpw_name = -1; +static int hf_yppasswd_newpw_passwd = -1; +static int hf_yppasswd_newpw_uid = -1; +static int hf_yppasswd_newpw_gid = -1; +static int hf_yppasswd_newpw_gecos = -1; +static int hf_yppasswd_newpw_dir = -1; +static int hf_yppasswd_newpw_shell = -1; + +static gint ett_yppasswd = -1; +static gint ett_yppasswd_newpw = -1; + +static int +dissect_yppasswd_call(tvbuff_t *tvb, int offset, packet_info *pinfo _U_, proto_tree *tree) +{ + proto_item *lock_item = NULL; + proto_tree *lock_tree = NULL; + + offset = dissect_rpc_string(tvb, tree, hf_yppasswd_oldpass, + offset, NULL); + + lock_item = proto_tree_add_item(tree, hf_yppasswd_newpw, tvb, + offset, -1, ENC_NA); + + lock_tree = proto_item_add_subtree(lock_item, ett_yppasswd_newpw); + + offset = dissect_rpc_string(tvb, lock_tree, + hf_yppasswd_newpw_name, offset, NULL); + offset = dissect_rpc_string(tvb, lock_tree, + hf_yppasswd_newpw_passwd, offset, NULL); + offset = dissect_rpc_uint32(tvb, lock_tree, + hf_yppasswd_newpw_uid, offset); + offset = dissect_rpc_uint32(tvb, lock_tree, + hf_yppasswd_newpw_gid, offset); + offset = dissect_rpc_string(tvb, lock_tree, + hf_yppasswd_newpw_gecos, offset, NULL); + offset = dissect_rpc_string(tvb, lock_tree, + hf_yppasswd_newpw_dir, offset, NULL); + offset = dissect_rpc_string(tvb, lock_tree, + hf_yppasswd_newpw_shell, offset, NULL); + + return offset; +} + +static int +dissect_yppasswd_reply(tvbuff_t *tvb, int offset, packet_info *pinfo _U_, proto_tree *tree) +{ + offset = dissect_rpc_uint32(tvb, tree, hf_yppasswd_status, offset); + + return offset; +} + +/* proc number, "proc name", dissect_request, dissect_reply */ +/* NULL as function pointer means: type of arguments is "void". */ +static const vsff yppasswd1_proc[] = { + { YPPASSWDPROC_NULL, "NULL", + NULL, NULL }, + { YPPASSWDPROC_UPDATE, "UPDATE", + dissect_yppasswd_call, dissect_yppasswd_reply }, + { 0, NULL, NULL, NULL } +}; +static const value_string yppasswd1_proc_vals[] = { + { YPPASSWDPROC_NULL, "NULL" }, + { YPPASSWDPROC_UPDATE, "UPDATE" }, + { 0, NULL } +}; + +void +proto_register_yppasswd(void) +{ + static hf_register_info hf[] = { + { &hf_yppasswd_procedure_v1, { + "V1 Procedure", "yppasswd.procedure_v1", FT_UINT32, BASE_DEC, + VALS(yppasswd1_proc_vals), 0, NULL, HFILL }}, + { &hf_yppasswd_status, { + "status", "yppasswd.status", FT_UINT32, BASE_DEC, + NULL, 0, "YPPasswd update status", HFILL }}, + + { &hf_yppasswd_oldpass, { + "oldpass", "yppasswd.oldpass", FT_STRING, BASE_NONE, + NULL, 0, "Old encrypted password", HFILL }}, + + { &hf_yppasswd_newpw, { + "newpw", "yppasswd.newpw", FT_NONE, BASE_NONE, + NULL, 0, "New passwd entry", HFILL }}, + + { &hf_yppasswd_newpw_name, { + "name", "yppasswd.newpw.name", FT_STRING, BASE_NONE, + NULL, 0, "Username", HFILL }}, + + { &hf_yppasswd_newpw_passwd, { + "passwd", "yppasswd.newpw.passwd", FT_STRING, BASE_NONE, + NULL, 0, "Encrypted passwd", HFILL }}, + + { &hf_yppasswd_newpw_uid, { + "uid", "yppasswd.newpw.uid", FT_UINT32, BASE_DEC, + NULL, 0, "UserID", HFILL }}, + + { &hf_yppasswd_newpw_gid, { + "gid", "yppasswd.newpw.gid", FT_UINT32, BASE_DEC, + NULL, 0, "GroupID", HFILL }}, + + { &hf_yppasswd_newpw_gecos, { + "gecos", "yppasswd.newpw.gecos", FT_STRING, BASE_NONE, + NULL, 0, "In real life name", HFILL }}, + + { &hf_yppasswd_newpw_dir, { + "dir", "yppasswd.newpw.dir", FT_STRING, BASE_NONE, + NULL, 0, "Home Directory", HFILL }}, + + { &hf_yppasswd_newpw_shell, { + "shell", "yppasswd.newpw.shell", FT_STRING, BASE_NONE, + NULL, 0, "Default shell", HFILL }}, + + }; + + static gint *ett[] = { + &ett_yppasswd, + &ett_yppasswd_newpw, + }; + + proto_yppasswd = proto_register_protocol("Yellow Pages Passwd", + "YPPASSWD", "yppasswd"); + proto_register_field_array(proto_yppasswd, hf, array_length(hf)); + proto_register_subtree_array(ett, array_length(ett)); +} + +void +proto_reg_handoff_yppasswd(void) +{ + /* Register the protocol as RPC */ + rpc_init_prog(proto_yppasswd, YPPASSWD_PROGRAM, ett_yppasswd); + /* Register the procedure tables */ + rpc_init_proc_table(YPPASSWD_PROGRAM, 1, yppasswd1_proc, hf_yppasswd_procedure_v1); +} + diff --git a/pool/shard002/C/0058212_space.c b/pool/shard002/C/0058212_space.c new file mode 100644 index 0000000000000000000000000000000000000000..c98600b88dc6edecac53d1e0417d533a312c1c4e --- /dev/null +++ b/pool/shard002/C/0058212_space.c @@ -0,0 +1,36 @@ +#include "gui.h" +#include "gui_defs.h" +#include + +static void paint(gui *_gui, widget *_w) +{ + /* nothing */ +} + +static void hints(gui *_gui, widget *_w, int *width, int *height) +{ + struct space_widget *w = _w; + LOGD("HINTS space %p\n", w); + *width = w->wanted_width; + *height = w->wanted_height; +} + +widget *new_space(gui *_gui, int width, int height) +{ + struct gui *g = _gui; + struct space_widget *w; + + glock(g); + + w = new_widget(g, SPACE, sizeof(struct space_widget)); + + w->wanted_width = width; + w->wanted_height = height; + + w->common.paint = paint; + w->common.hints = hints; + + gunlock(g); + + return w; +} diff --git a/pool/shard002/C/0058215_gcc_linux_arm.c b/pool/shard002/C/0058215_gcc_linux_arm.c new file mode 100644 index 0000000000000000000000000000000000000000..9a6e585948a62c68b78ead7e5a272bfd22900096 --- /dev/null +++ b/pool/shard002/C/0058215_gcc_linux_arm.c @@ -0,0 +1,69 @@ +// Copyright 2010 The Go 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 "libcgo.h" + +static void *threadentry(void*); + +static void (*setmg_gcc)(void*, void*); + +void +x_cgo_init(G *g, void (*setmg)(void*, void*)) +{ + pthread_attr_t attr; + size_t size; + + setmg_gcc = setmg; + pthread_attr_init(&attr); + pthread_attr_getstacksize(&attr, &size); + g->stackguard = (uintptr)&attr - size + 4096; + pthread_attr_destroy(&attr); +} + + +void +_cgo_sys_thread_start(ThreadStart *ts) +{ + pthread_attr_t attr; + pthread_t p; + size_t size; + int err; + + // Not sure why the memset is necessary here, + // but without it, we get a bogus stack size + // out of pthread_attr_getstacksize. C'est la Linux. + memset(&attr, 0, sizeof attr); + pthread_attr_init(&attr); + size = 0; + pthread_attr_getstacksize(&attr, &size); + ts->g->stackguard = size; + err = pthread_create(&p, &attr, threadentry, ts); + if (err != 0) { + fprintf(stderr, "runtime/cgo: pthread_create failed: %s\n", strerror(err)); + abort(); + } +} + +extern void crosscall_arm2(void (*fn)(void), void (*setmg_gcc)(void*, void*), void*, void*); +static void* +threadentry(void *v) +{ + ThreadStart ts; + + ts = *(ThreadStart*)v; + free(v); + + ts.g->stackbase = (uintptr)&ts; + + /* + * _cgo_sys_thread_start set stackguard to stack size; + * change to actual guard pointer. + */ + ts.g->stackguard = (uintptr)&ts - ts.g->stackguard + 4096 * 2; + + crosscall_arm2(ts.fn, setmg_gcc, (void*)ts.m, (void*)ts.g); + return nil; +} diff --git a/pool/shard002/C/0058217_strerror.c b/pool/shard002/C/0058217_strerror.c new file mode 100644 index 0000000000000000000000000000000000000000..39289231d90c207194abe49da9d3fa92d9931bbf --- /dev/null +++ b/pool/shard002/C/0058217_strerror.c @@ -0,0 +1,21 @@ +#include "system.h" + +extern int sys_nerr; +extern char *sys_errlist[]; +static char buf[64]; + +char * +strerror(int errnum) +{ + if (errnum < 0 || errnum > sys_nerr) + { + static char fmt[] = "Unknown error %d"; + size_t len = (size_t) sprintf (buf, fmt, errnum); + if (len < (size_t) sizeof(fmt) - 2) + return NULL; + buf[len - 1] = '\0'; + return buf; + } + + return (char *) sys_errlist[errnum]; +} diff --git a/pool/shard002/C/0058219_DETOUR0827.c b/pool/shard002/C/0058219_DETOUR0827.c new file mode 100644 index 0000000000000000000000000000000000000000..3c43aa683ab23120ca85383aaf15e974cf06b025 --- /dev/null +++ b/pool/shard002/C/0058219_DETOUR0827.c @@ -0,0 +1,81 @@ +/* Copyright (C) 2018 Magnus Lång and Tuan Phong Ngo + * This benchmark is part of SWSC */ + +#include +#include +#include +#include + +atomic_int vars[2]; +atomic_int atom_1_r1_1; +atomic_int atom_1_r5_2; +atomic_int atom_1_r6_3; + +void *t0(void *arg){ +label_1:; + atomic_store_explicit(&vars[0], 4, memory_order_seq_cst); + + atomic_store_explicit(&vars[1], 1, memory_order_seq_cst); + return NULL; +} + +void *t1(void *arg){ +label_2:; + int v2_r1 = atomic_load_explicit(&vars[1], memory_order_seq_cst); + atomic_store_explicit(&vars[0], 1, memory_order_seq_cst); + int v4_r5 = atomic_load_explicit(&vars[0], memory_order_seq_cst); + int v6_r6 = atomic_load_explicit(&vars[0], memory_order_seq_cst); + int v15 = (v2_r1 == 1); + atomic_store_explicit(&atom_1_r1_1, v15, memory_order_seq_cst); + int v16 = (v4_r5 == 2); + atomic_store_explicit(&atom_1_r5_2, v16, memory_order_seq_cst); + int v17 = (v6_r6 == 3); + atomic_store_explicit(&atom_1_r6_3, v17, memory_order_seq_cst); + return NULL; +} + +void *t2(void *arg){ +label_3:; + atomic_store_explicit(&vars[0], 2, memory_order_seq_cst); + return NULL; +} + +void *t3(void *arg){ +label_4:; + atomic_store_explicit(&vars[0], 3, memory_order_seq_cst); + return NULL; +} + +int main(int argc, char *argv[]){ + pthread_t thr0; + pthread_t thr1; + pthread_t thr2; + pthread_t thr3; + + atomic_init(&vars[1], 0); + atomic_init(&vars[0], 0); + atomic_init(&atom_1_r1_1, 0); + atomic_init(&atom_1_r5_2, 0); + atomic_init(&atom_1_r6_3, 0); + + pthread_create(&thr0, NULL, t0, NULL); + pthread_create(&thr1, NULL, t1, NULL); + pthread_create(&thr2, NULL, t2, NULL); + pthread_create(&thr3, NULL, t3, NULL); + + pthread_join(thr0, NULL); + pthread_join(thr1, NULL); + pthread_join(thr2, NULL); + pthread_join(thr3, NULL); + + int v7 = atomic_load_explicit(&vars[0], memory_order_seq_cst); + int v8 = (v7 == 4); + int v9 = atomic_load_explicit(&atom_1_r1_1, memory_order_seq_cst); + int v10 = atomic_load_explicit(&atom_1_r5_2, memory_order_seq_cst); + int v11 = atomic_load_explicit(&atom_1_r6_3, memory_order_seq_cst); + int v12_conj = v10 & v11; + int v13_conj = v9 & v12_conj; + int v14_conj = v8 & v13_conj; + if (v14_conj == 1) assert(0); + return 0; +} diff --git a/pool/shard002/C/0058230_w1_ds2760.c b/pool/shard002/C/0058230_w1_ds2760.c new file mode 100644 index 0000000000000000000000000000000000000000..22d6e83bcaf4102c921c4297430529fa670ec2c1 --- /dev/null +++ b/pool/shard002/C/0058230_w1_ds2760.c @@ -0,0 +1,240 @@ +/* + * 1-Wire implementation for the ds2760 chip + * + * Copyright © 2004-2005, Szabolcs Gyurko + * + * Use consistent with the GNU GPL is permitted, + * provided that this copyright notice is + * preserved in its entirety in all copies and derived works. + * + */ + +#include +#include +#include +#include +#include +#include +#include +#include + +#include "../w1.h" +#include "../w1_int.h" +#include "../w1_family.h" +#include "w1_ds2760.h" + +static int w1_ds2760_io(struct device *dev, char *buf, int addr, size_t count, + int io) +{ + struct w1_slave *sl = container_of(dev, struct w1_slave, dev); + + if (!dev) + return 0; + + mutex_lock(&sl->master->mutex); + + if (addr > DS2760_DATA_SIZE || addr < 0) { + count = 0; + goto out; + } + if (addr + count > DS2760_DATA_SIZE) + count = DS2760_DATA_SIZE - addr; + + if (!w1_reset_select_slave(sl)) { + if (!io) { + w1_write_8(sl->master, W1_DS2760_READ_DATA); + w1_write_8(sl->master, addr); + count = w1_read_block(sl->master, buf, count); + } else { + w1_write_8(sl->master, W1_DS2760_WRITE_DATA); + w1_write_8(sl->master, addr); + w1_write_block(sl->master, buf, count); + /* XXX w1_write_block returns void, not n_written */ + } + } + +out: + mutex_unlock(&sl->master->mutex); + + return count; +} + +int w1_ds2760_read(struct device *dev, char *buf, int addr, size_t count) +{ + return w1_ds2760_io(dev, buf, addr, count, 0); +} + +int w1_ds2760_write(struct device *dev, char *buf, int addr, size_t count) +{ + return w1_ds2760_io(dev, buf, addr, count, 1); +} + +static int w1_ds2760_eeprom_cmd(struct device *dev, int addr, int cmd) +{ + struct w1_slave *sl = container_of(dev, struct w1_slave, dev); + + if (!dev) + return -EINVAL; + + mutex_lock(&sl->master->mutex); + + if (w1_reset_select_slave(sl) == 0) { + w1_write_8(sl->master, cmd); + w1_write_8(sl->master, addr); + } + + mutex_unlock(&sl->master->mutex); + return 0; +} + +int w1_ds2760_store_eeprom(struct device *dev, int addr) +{ + return w1_ds2760_eeprom_cmd(dev, addr, W1_DS2760_COPY_DATA); +} + +int w1_ds2760_recall_eeprom(struct device *dev, int addr) +{ + return w1_ds2760_eeprom_cmd(dev, addr, W1_DS2760_RECALL_DATA); +} + +static ssize_t w1_ds2760_read_bin(struct file *filp, struct kobject *kobj, + struct bin_attribute *bin_attr, + char *buf, loff_t off, size_t count) +{ + struct device *dev = container_of(kobj, struct device, kobj); + return w1_ds2760_read(dev, buf, off, count); +} + +static struct bin_attribute w1_ds2760_bin_attr = { + .attr = { + .name = "w1_slave", + .mode = S_IRUGO, + }, + .size = DS2760_DATA_SIZE, + .read = w1_ds2760_read_bin, +}; + +static DEFINE_IDR(bat_idr); +static DEFINE_MUTEX(bat_idr_lock); + +static int new_bat_id(void) +{ + int ret; + + while (1) { + int id; + + ret = idr_pre_get(&bat_idr, GFP_KERNEL); + if (ret == 0) + return -ENOMEM; + + mutex_lock(&bat_idr_lock); + ret = idr_get_new(&bat_idr, NULL, &id); + mutex_unlock(&bat_idr_lock); + + if (ret == 0) { + ret = id & MAX_ID_MASK; + break; + } else if (ret == -EAGAIN) { + continue; + } else { + break; + } + } + + return ret; +} + +static void release_bat_id(int id) +{ + mutex_lock(&bat_idr_lock); + idr_remove(&bat_idr, id); + mutex_unlock(&bat_idr_lock); +} + +static int w1_ds2760_add_slave(struct w1_slave *sl) +{ + int ret; + int id; + struct platform_device *pdev; + + id = new_bat_id(); + if (id < 0) { + ret = id; + goto noid; + } + + pdev = platform_device_alloc("ds2760-battery", id); + if (!pdev) { + ret = -ENOMEM; + goto pdev_alloc_failed; + } + pdev->dev.parent = &sl->dev; + + ret = platform_device_add(pdev); + if (ret) + goto pdev_add_failed; + + ret = sysfs_create_bin_file(&sl->dev.kobj, &w1_ds2760_bin_attr); + if (ret) + goto bin_attr_failed; + + dev_set_drvdata(&sl->dev, pdev); + + goto success; + +bin_attr_failed: +pdev_add_failed: + platform_device_unregister(pdev); +pdev_alloc_failed: + release_bat_id(id); +noid: +success: + return ret; +} + +static void w1_ds2760_remove_slave(struct w1_slave *sl) +{ + struct platform_device *pdev = dev_get_drvdata(&sl->dev); + int id = pdev->id; + + platform_device_unregister(pdev); + release_bat_id(id); + sysfs_remove_bin_file(&sl->dev.kobj, &w1_ds2760_bin_attr); +} + +static struct w1_family_ops w1_ds2760_fops = { + .add_slave = w1_ds2760_add_slave, + .remove_slave = w1_ds2760_remove_slave, +}; + +static struct w1_family w1_ds2760_family = { + .fid = W1_FAMILY_DS2760, + .fops = &w1_ds2760_fops, +}; + +static int __init w1_ds2760_init(void) +{ + printk(KERN_INFO "1-Wire driver for the DS2760 battery monitor " + " chip - (c) 2004-2005, Szabolcs Gyurko\n"); + idr_init(&bat_idr); + return w1_register_family(&w1_ds2760_family); +} + +static void __exit w1_ds2760_exit(void) +{ + w1_unregister_family(&w1_ds2760_family); + idr_destroy(&bat_idr); +} + +EXPORT_SYMBOL(w1_ds2760_read); +EXPORT_SYMBOL(w1_ds2760_write); +EXPORT_SYMBOL(w1_ds2760_store_eeprom); +EXPORT_SYMBOL(w1_ds2760_recall_eeprom); + +module_init(w1_ds2760_init); +module_exit(w1_ds2760_exit); + +MODULE_LICENSE("GPL"); +MODULE_AUTHOR("Szabolcs Gyurko "); +MODULE_DESCRIPTION("1-wire Driver Dallas 2760 battery monitor chip"); diff --git a/pool/shard002/C/0058235_9-4.c b/pool/shard002/C/0058235_9-4.c new file mode 100644 index 0000000000000000000000000000000000000000..21614d2b7f058c2ad8454304c0295f293866db68 --- /dev/null +++ b/pool/shard002/C/0058235_9-4.c @@ -0,0 +1,24 @@ +#include + +int hash(char string[]) { + int index = 0; + int code = 0; + while(string[index] != '\0') { + code += string[index]; + ++index; + } + return code; +} + +int main(int argc, char const *argv[]) { + char s1[100] = "Tell me about it"; + printf("%s, %i\n", s1, hash(s1)); + + char s2[100] = "a"; + printf("%s, %i\n", s2, hash(s2)); + + char s3[100] = ""; + printf("%s, %i\n", s3, hash(s3)); + + return 0; +} diff --git a/pool/shard002/C/0058238_rtc.c b/pool/shard002/C/0058238_rtc.c new file mode 100644 index 0000000000000000000000000000000000000000..6b83ec3cee7a136eb29e6688fb98c008c7449dae --- /dev/null +++ b/pool/shard002/C/0058238_rtc.c @@ -0,0 +1,89 @@ +#include +#include +#define TZ_OFFSET_HOUR +8 +#define TZ_OFFSET_MIN 0 +struct time_struct{ + uint8_t date_sec; /* Seconds. [0-60] (1 leap second) */ + uint8_t date_min; /* Minutes. [0-59] */ + uint8_t date_hour; /* Hours. [0-23] */ + uint8_t date_mday; /* Day. [1-31] */ + uint8_t date_mon; /* monthnl. [0-11] */ + uint16_t date_year; /* Year - 1900. */ +}; +#define MINUTE 60 +#define HOUR (60*MINUTE) +#define DAY (24*HOUR) +#define YEAR (365*DAY) +static int month[12] = { + 0, + DAY*(31), + DAY*(31+29), + DAY*(31+29+31), + DAY*(31+29+31+30), + DAY*(31+29+31+30+31), + DAY*(31+29+31+30+31+30), + DAY*(31+29+31+30+31+30+31), + DAY*(31+29+31+30+31+30+31+31), + DAY*(31+29+31+30+31+30+31+31+30), + DAY*(31+29+31+30+31+30+31+31+30+31), + DAY*(31+29+31+30+31+30+31+31+30+31+30) +}; +typedef struct time_struct time_t; +uint16_t lyd(uint16_t year){ + year += 1900; + if(year%4 == 0){ + if(year%100 != 0){ + return 366; + }else if(year%400 == 0){ + return 366; + } + } + return 365; +} +time_t ctime(unsigned long timestamp){ + time_t time; + uint16_t y = 0; + timestamp += TZ_OFFSET_HOUR*HOUR; + timestamp += TZ_OFFSET_MIN*MINUTE; + time.date_sec = timestamp%MINUTE; + time.date_min = (timestamp%HOUR)/MINUTE; + time.date_hour = (timestamp%DAY)/HOUR; + if(timestamp != 0){//If timestamp = 0,it will be still 0 + timestamp-=timestamp%DAY; + } + while(1){ + if(timestamp<(lyd(y+70)*DAY)){ + break; + } + timestamp-=lyd(y+70)*DAY; + y++; + } + time.date_year = y+70; + for(int i = 0;;i++){ + if(i+1 == 12){ + time.date_mon = 11; + break; + } + if((i < 2)||(lyd(y+70) == 366)){ + if((timestamp >= month[i]) && (timestamp < month[i+1])){ + time.date_mon = i; + break; + } + }else{ + if((timestamp >= (month[i]-DAY)) && (timestamp < (month[i+1]-DAY))){ + time.date_mon = i; + break; + } + } + } + if((time.date_mon < 2)||(lyd(y+70) == 366)){ + time.date_mday = (timestamp-month[time.date_mon])/DAY; + }else{ + time.date_mday = (timestamp-(month[time.date_mon]-DAY))/DAY; + } + return time; +} +int main(){ + time_t t = ctime(1409331329L); + printf("%d %d %d %d %d %d\n",t.date_year+1900,t.date_mon+1,t.date_mday+1,t.date_hour,t.date_min,t.date_sec); +} diff --git a/pool/shard002/C/0058247_ert-jansson-helpers.c b/pool/shard002/C/0058247_ert-jansson-helpers.c new file mode 100644 index 0000000000000000000000000000000000000000..298fe1029631c5c3cded46e28c894fde571e91c0 --- /dev/null +++ b/pool/shard002/C/0058247_ert-jansson-helpers.c @@ -0,0 +1,43 @@ +#include +#include + +#include "ert-jansson-helpers.h" +#include "ert-time.h" + +int ert_jansson_serialize_timestamp_millis(json_t *json_obj, char *key, struct timespec *ts) +{ + int64_t timestamp_millis = + (int64_t) (((int64_t) ts->tv_sec) * 1000LL + + (((int64_t) ts->tv_nsec) / 1000000LL)); + return json_object_set_new(json_obj, key, json_integer(timestamp_millis)); +} + +int ert_jansson_serialize_timestamp_iso8601(json_t *json_obj, char *key, struct timespec *ts) +{ + if (ert_timespec_is_zero(ts)) { + return json_object_set_new(json_obj, key, json_null()); + } + + uint8_t timestamp_string[64]; + ert_format_iso8601_timestamp(ts, 64, timestamp_string); + return json_object_set_new(json_obj, key, json_string((const char *) timestamp_string)); +} + +int ert_jansson_serialize_timestamp_iso8601_and_millis(json_t *json_obj, char *key_prefix, struct timespec *ts) +{ + size_t key_millis_length = 128; + char key_millis[key_millis_length]; + strncpy(key_millis, key_prefix, key_millis_length); + strncat(key_millis, "_millis", key_millis_length - strlen(key_millis)); + + int result = ert_jansson_serialize_timestamp_iso8601(json_obj, key_prefix, ts); + if (result < 0) { + return result; + } + result = ert_jansson_serialize_timestamp_millis(json_obj, key_millis, ts); + if (result < 0) { + return result; + } + + return 0; +} diff --git a/pool/shard002/C/0058252_lluv_fs_event.c b/pool/shard002/C/0058252_lluv_fs_event.c new file mode 100644 index 0000000000000000000000000000000000000000..133cb3aa9245c163e388267e8cd2484fe5f42277 --- /dev/null +++ b/pool/shard002/C/0058252_lluv_fs_event.c @@ -0,0 +1,173 @@ +/****************************************************************************** +* Author: Alexey Melnichuk +* +* Copyright (C) 2014-2016 Alexey Melnichuk +* +* Licensed according to the included 'LICENSE' document +* +* This file is part of lua-lluv library. +******************************************************************************/ + +#include "lluv.h" +#include "lluv_handle.h" +#include "lluv_fs_event.h" +#include "lluv_loop.h" +#include "lluv_error.h" +#include + +#define LLUV_FS_EVENT_NAME LLUV_PREFIX" FS Event" +static const char *LLUV_FS_EVENT = LLUV_FS_EVENT_NAME; + +LLUV_INTERNAL int lluv_fs_event_index(lua_State *L){ + return lluv__index(L, LLUV_FS_EVENT, lluv_handle_index); +} + +LLUV_IMPL_SAFE(lluv_fs_event_create){ + lluv_loop_t *loop = lluv_opt_loop_ex(L, 1, LLUV_FLAG_OPEN); + lluv_handle_t *handle = lluv_handle_create(L, UV_FS_EVENT, safe_flag | INHERITE_FLAGS(loop)); + int err = uv_fs_event_init(loop->handle, LLUV_H(handle, uv_fs_event_t)); + if(err < 0){ + lluv_handle_cleanup(L, handle, -1); + return lluv_fail(L, safe_flag | loop->flags, LLUV_ERR_UV, (uv_errno_t)err, NULL); + } + return 1; +} + +static lluv_handle_t* lluv_check_fs_event(lua_State *L, int idx, lluv_flags_t flags){ + lluv_handle_t *handle = lluv_check_handle(L, idx, flags); + luaL_argcheck (L, LLUV_H(handle, uv_handle_t)->type == UV_FS_EVENT, idx, LLUV_FS_EVENT_NAME" expected"); + + return handle; +} + +static void lluv_on_fs_event_start(uv_fs_event_t *arg, const char* filename, int events, int status){ + lluv_handle_t *handle = lluv_handle_byptr((uv_handle_t*)arg); + lua_State *L = LLUV_HCALLBACK_L(handle); + + LLUV_CHECK_LOOP_CB_INVARIANT(L); + + lua_rawgeti(L, LLUV_LUA_REGISTRY, LLUV_START_CB(handle)); + assert(!lua_isnil(L, -1)); /* is callble */ + + lluv_handle_pushself(L, handle); + lluv_push_status(L, status); + + if(filename)lua_pushstring(L, filename); else lua_pushnil(L); + lua_pushinteger(L, events); + + LLUV_HANDLE_CALL_CB(L, handle, 4); + + LLUV_CHECK_LOOP_CB_INVARIANT(L); +} + +static int lluv_fs_event_start(lua_State *L){ + static const lluv_uv_const_t FLAGS[] = { + { UV_FS_EVENT_WATCH_ENTRY, "watch_entry" }, + { UV_FS_EVENT_STAT, "stat" }, + { UV_FS_EVENT_RECURSIVE, "recursive" }, + + { 0, NULL } + }; + + lluv_handle_t *handle = lluv_check_fs_event(L, 1, LLUV_FLAG_OPEN); + const char *path = luaL_checkstring(L, 2); + unsigned int flags = 0; + int err; + + if(!lua_isfunction(L, 3)) flags = lluv_opt_flags_ui(L, 3, flags, FLAGS); + + lluv_check_args_with_cb(L, 4); + LLUV_START_CB(handle) = luaL_ref(L, LLUV_LUA_REGISTRY); + + err = uv_fs_event_start(LLUV_H(handle, uv_fs_event_t), lluv_on_fs_event_start, path, flags); + + if(err >= 0) lluv_handle_lock(L, handle, LLUV_LOCK_START); + + return lluv_return(L, handle, LLUV_START_CB(handle), err); +} + +static int lluv_fs_event_stop(lua_State *L){ + lluv_handle_t *handle = lluv_check_fs_event(L, 1, LLUV_FLAG_OPEN); + int err = uv_fs_event_stop(LLUV_H(handle, uv_fs_event_t)); + if(err < 0){ + return lluv_fail(L, handle->flags, LLUV_ERR_UV, err, NULL); + } + + lluv_handle_unlock(L, handle, LLUV_LOCK_START); + + lua_settop(L, 1); + return 1; +} + +static int lluv_fs_getpath(lua_State *L){ + lluv_handle_t *handle = lluv_check_fs_event(L, 1, LLUV_FLAG_OPEN); + char buf[255]; size_t len = sizeof(buf); + int err = uv_fs_event_getpath(LLUV_H(handle, uv_fs_event_t), buf, &len); + if(err >= 0){ + lua_pushlstring(L, buf, len); + return 1; + } + if(err != UV_ENOBUFS){ + return lluv_fail(L, handle->flags, LLUV_ERR_UV, err, NULL); + } + { + char *buf = lluv_alloc(L, len); + if(!buf){ + return lluv_fail(L, handle->flags, LLUV_ERR_UV, err, NULL); + } + err = uv_fs_event_getpath(LLUV_H(handle, uv_fs_event_t), buf, &len); + if(err < 0){ + lluv_free(L, buf); + return lluv_fail(L, handle->flags, LLUV_ERR_UV, err, NULL); + } + lua_pushlstring(L, buf, len); + lluv_free(L, buf); + return 1; + } +} + +static const struct luaL_Reg lluv_fs_event_methods[] = { + { "start", lluv_fs_event_start }, + { "stop", lluv_fs_event_stop }, + { "path", lluv_fs_getpath }, + + {NULL,NULL} +}; + +#define LLUV_FS_EVENT_FUNCTIONS(F) \ + {"fs_event", lluv_fs_event_create_##F}, \ + +static const struct luaL_Reg lluv_fs_event_functions[][2] = { + { + LLUV_FS_EVENT_FUNCTIONS(unsafe) + + {NULL,NULL} + }, + { + LLUV_FS_EVENT_FUNCTIONS(safe) + + {NULL,NULL} + }, +}; + +static const lluv_uv_const_t lluv_fs_event_constants[] = { + { UV_RENAME, "RENAME" }, + { UV_CHANGE, "CHANGE" }, + { UV_FS_EVENT_WATCH_ENTRY, "FS_EVENT_WATCH_ENTRY" }, + { UV_FS_EVENT_STAT, "FS_EVENT_STAT" }, + { UV_FS_EVENT_RECURSIVE, "FS_EVENT_RECURSIVE" }, + + { 0, NULL } +}; + +LLUV_INTERNAL void lluv_fs_event_initlib(lua_State *L, int nup, int safe){ + assert((safe == 0) || (safe == 1)); + + lutil_pushnvalues(L, nup); + if(!lutil_createmetap(L, LLUV_FS_EVENT, lluv_fs_event_methods, nup)) + lua_pop(L, nup); + lua_pop(L, 1); + + luaL_setfuncs(L, lluv_fs_event_functions[safe], nup); + lluv_register_constants(L, lluv_fs_event_constants); +} diff --git a/pool/shard002/C/0058259_t0004.c b/pool/shard002/C/0058259_t0004.c new file mode 100644 index 0000000000000000000000000000000000000000..f8277644122402f7f66e02d65898dc665d0451d0 --- /dev/null +++ b/pool/shard002/C/0058259_t0004.c @@ -0,0 +1,132 @@ +/* + * Purpose: Test retrieving data and attempting to initiate a new query with results pending + * Functions: dbnextrow dbresults dbsqlexec dbgetchar + */ + +#include "common.h" +#include + +int +main(int argc, char **argv) +{ + const int rows_to_add = 50; + LOGINREC *login; + DBPROCESS *dbproc; + int i, expected_error; + char *s, teststr[1024]; + DBINT testint; + int failed = 0; + + set_malloc_options(); + + read_login_info(argc, argv); + + printf("Starting %s\n", argv[0]); + + dbinit(); + + dberrhandle(syb_err_handler); + dbmsghandle(syb_msg_handler); + + printf("About to logon\n"); + + login = dblogin(); + DBSETLPWD(login, PASSWORD); + DBSETLUSER(login, USER); + DBSETLAPP(login, "t0004"); + + printf("About to open\n"); + + dbproc = dbopen(login, SERVER); + if (strlen(DATABASE)) + dbuse(dbproc, DATABASE); + dbloginfree(login); + + printf("creating table\n"); + sql_cmd(dbproc); + dbsqlexec(dbproc); + while (dbresults(dbproc) != NO_MORE_RESULTS) { + /* nop */ + } + + printf("insert\n"); + for (i = 1; i < rows_to_add; i++) { + sql_cmd(dbproc); + dbsqlexec(dbproc); + while (dbresults(dbproc) != NO_MORE_RESULTS) { + /* nop */ + } + } + + sql_cmd(dbproc); /* select */ + dbsqlexec(dbproc); + + if (dbresults(dbproc) != SUCCEED) { + printf("Was expecting a result set."); + exit(1); + } + + for (i = 1; i <= dbnumcols(dbproc); i++) + printf("col %d is %s\n", i, dbcolname(dbproc, i)); + + dbbind(dbproc, 1, INTBIND, 0, (BYTE *) & testint); + dbbind(dbproc, 2, STRINGBIND, 0, (BYTE *) teststr); + + for (i = 1; i <= 24; i++) { + char expected[1024]; + + sprintf(expected, "row %04d", i); + + if (i % 5 == 0) { + dbclrbuf(dbproc, 5); + } + + + testint = -1; + strcpy(teststr, "bogus"); + + if (REG_ROW != dbnextrow(dbproc)) { + fprintf(stderr, "Failed. Expected a row\n"); + exit(1); + } + if (testint != i) { + fprintf(stderr, "Failed. Expected i to be %d, was %d\n", i, (int) testint); + abort(); + } + if (0 != strncmp(teststr, expected, strlen(expected))) { + printf("Failed. Expected s to be |%s|, was |%s|\n", expected, teststr); + abort(); + } + printf("Read a row of data -> %d %s\n", (int) testint, teststr); + } + + + + printf("second select\n"); + printf("testing dbgetchar...\n"); + for (i=0; (s = dbgetchar(dbproc, i)) != NULL; i++) { + putchar(*s); + if (!(isprint((unsigned char)*s) || iscntrl((unsigned char)*s))) { + fprintf(stderr, "%s:%d: dbgetchar failed with %x at position %d\n", __FILE__, __LINE__, *s, i); + failed = 1; + break; + } + } + printf("<== end of command buffer\n"); + + if (SUCCEED != sql_cmd(dbproc)) { + fprintf(stderr, "%s:%d: dbcmd failed\n", __FILE__, __LINE__); + failed = 1; + } + printf("About to exec for the second time. Should fail\n"); + expected_error = 20019; + dbsetuserdata(dbproc, (BYTE*) &expected_error); + if (FAIL != dbsqlexec(dbproc)) { + fprintf(stderr, "%s:%d: dbsqlexec should have failed but didn't\n", __FILE__, __LINE__); + failed = 1; + } + dbexit(); + + printf("%s %s\n", __FILE__, (failed ? "failed!" : "OK")); + return failed ? 1 : 0; +} diff --git a/pool/shard002/C/0058261_thunder_xcv.c b/pool/shard002/C/0058261_thunder_xcv.c new file mode 100644 index 0000000000000000000000000000000000000000..2d5e8dab1f700640d14d9daf5b90e2fccd098ab7 --- /dev/null +++ b/pool/shard002/C/0058261_thunder_xcv.c @@ -0,0 +1,234 @@ +/* + * Copyright (C) 2016 Cavium, Inc. + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of version 2 of the GNU General Public License + * as published by the Free Software Foundation. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "nic.h" +#include "thunder_bgx.h" + +#define DRV_NAME "thunder_xcv" +#define DRV_VERSION "1.0" + +/* Register offsets */ +#define XCV_RESET 0x00 +#define PORT_EN BIT_ULL(63) +#define CLK_RESET BIT_ULL(15) +#define DLL_RESET BIT_ULL(11) +#define COMP_EN BIT_ULL(7) +#define TX_PKT_RESET BIT_ULL(3) +#define TX_DATA_RESET BIT_ULL(2) +#define RX_PKT_RESET BIT_ULL(1) +#define RX_DATA_RESET BIT_ULL(0) +#define XCV_DLL_CTL 0x10 +#define CLKRX_BYP BIT_ULL(23) +#define CLKTX_BYP BIT_ULL(15) +#define XCV_COMP_CTL 0x20 +#define DRV_BYP BIT_ULL(63) +#define XCV_CTL 0x30 +#define XCV_INT 0x40 +#define XCV_INT_W1S 0x48 +#define XCV_INT_ENA_W1C 0x50 +#define XCV_INT_ENA_W1S 0x58 +#define XCV_INBND_STATUS 0x80 +#define XCV_BATCH_CRD_RET 0x100 + +struct xcv { + void __iomem *reg_base; + struct pci_dev *pdev; +}; + +static struct xcv *xcv; + +/* Supported devices */ +static const struct pci_device_id xcv_id_table[] = { + { PCI_DEVICE(PCI_VENDOR_ID_CAVIUM, 0xA056) }, + { 0, } /* end of table */ +}; + +MODULE_AUTHOR("Cavium Inc"); +MODULE_DESCRIPTION("Cavium Thunder RGX/XCV Driver"); +MODULE_LICENSE("GPL v2"); +MODULE_VERSION(DRV_VERSION); +MODULE_DEVICE_TABLE(pci, xcv_id_table); + +void xcv_init_hw(void) +{ + u64 cfg; + + /* Take DLL out of reset */ + cfg = readq_relaxed(xcv->reg_base + XCV_RESET); + cfg &= ~DLL_RESET; + writeq_relaxed(cfg, xcv->reg_base + XCV_RESET); + + /* Take clock tree out of reset */ + cfg = readq_relaxed(xcv->reg_base + XCV_RESET); + cfg &= ~CLK_RESET; + writeq_relaxed(cfg, xcv->reg_base + XCV_RESET); + /* Wait for DLL to lock */ + msleep(1); + + /* Configure DLL - enable or bypass + * TX no bypass, RX bypass + */ + cfg = readq_relaxed(xcv->reg_base + XCV_DLL_CTL); + cfg &= ~0xFF03; + cfg |= CLKRX_BYP; + writeq_relaxed(cfg, xcv->reg_base + XCV_DLL_CTL); + + /* Enable compensation controller and force the + * write to be visible to HW by readig back. + */ + cfg = readq_relaxed(xcv->reg_base + XCV_RESET); + cfg |= COMP_EN; + writeq_relaxed(cfg, xcv->reg_base + XCV_RESET); + readq_relaxed(xcv->reg_base + XCV_RESET); + /* Wait for compensation state machine to lock */ + msleep(10); + + /* enable the XCV block */ + cfg = readq_relaxed(xcv->reg_base + XCV_RESET); + cfg |= PORT_EN; + writeq_relaxed(cfg, xcv->reg_base + XCV_RESET); + + cfg = readq_relaxed(xcv->reg_base + XCV_RESET); + cfg |= CLK_RESET; + writeq_relaxed(cfg, xcv->reg_base + XCV_RESET); +} +EXPORT_SYMBOL(xcv_init_hw); + +void xcv_setup_link(bool link_up, int link_speed) +{ + u64 cfg; + int speed = 2; + + if (!xcv) { + pr_err("XCV init not done, probe may have failed\n"); + return; + } + + if (link_speed == 100) + speed = 1; + else if (link_speed == 10) + speed = 0; + + if (link_up) { + /* set operating speed */ + cfg = readq_relaxed(xcv->reg_base + XCV_CTL); + cfg &= ~0x03; + cfg |= speed; + writeq_relaxed(cfg, xcv->reg_base + XCV_CTL); + + /* Reset datapaths */ + cfg = readq_relaxed(xcv->reg_base + XCV_RESET); + cfg |= TX_DATA_RESET | RX_DATA_RESET; + writeq_relaxed(cfg, xcv->reg_base + XCV_RESET); + + /* Enable the packet flow */ + cfg = readq_relaxed(xcv->reg_base + XCV_RESET); + cfg |= TX_PKT_RESET | RX_PKT_RESET; + writeq_relaxed(cfg, xcv->reg_base + XCV_RESET); + + /* Return credits to RGX */ + writeq_relaxed(0x01, xcv->reg_base + XCV_BATCH_CRD_RET); + } else { + /* Disable packet flow */ + cfg = readq_relaxed(xcv->reg_base + XCV_RESET); + cfg &= ~(TX_PKT_RESET | RX_PKT_RESET); + writeq_relaxed(cfg, xcv->reg_base + XCV_RESET); + readq_relaxed(xcv->reg_base + XCV_RESET); + } +} +EXPORT_SYMBOL(xcv_setup_link); + +static int xcv_probe(struct pci_dev *pdev, const struct pci_device_id *ent) +{ + int err; + struct device *dev = &pdev->dev; + + xcv = devm_kzalloc(dev, sizeof(struct xcv), GFP_KERNEL); + if (!xcv) + return -ENOMEM; + xcv->pdev = pdev; + + pci_set_drvdata(pdev, xcv); + + err = pci_enable_device(pdev); + if (err) { + dev_err(dev, "Failed to enable PCI device\n"); + goto err_kfree; + } + + err = pci_request_regions(pdev, DRV_NAME); + if (err) { + dev_err(dev, "PCI request regions failed 0x%x\n", err); + goto err_disable_device; + } + + /* MAP configuration registers */ + xcv->reg_base = pcim_iomap(pdev, PCI_CFG_REG_BAR_NUM, 0); + if (!xcv->reg_base) { + dev_err(dev, "XCV: Cannot map CSR memory space, aborting\n"); + err = -ENOMEM; + goto err_release_regions; + } + + return 0; + +err_release_regions: + pci_release_regions(pdev); +err_disable_device: + pci_disable_device(pdev); +err_kfree: + devm_kfree(dev, xcv); + xcv = NULL; + return err; +} + +static void xcv_remove(struct pci_dev *pdev) +{ + struct device *dev = &pdev->dev; + + if (xcv) { + devm_kfree(dev, xcv); + xcv = NULL; + } + + pci_release_regions(pdev); + pci_disable_device(pdev); +} + +static struct pci_driver xcv_driver = { + .name = DRV_NAME, + .id_table = xcv_id_table, + .probe = xcv_probe, + .remove = xcv_remove, +}; + +static int __init xcv_init_module(void) +{ + pr_info("%s, ver %s\n", DRV_NAME, DRV_VERSION); + + return pci_register_driver(&xcv_driver); +} + +static void __exit xcv_cleanup_module(void) +{ + pci_unregister_driver(&xcv_driver); +} + +module_init(xcv_init_module); +module_exit(xcv_cleanup_module); diff --git a/pool/shard002/C/0058271_main.c b/pool/shard002/C/0058271_main.c new file mode 100644 index 0000000000000000000000000000000000000000..ff0a797b4178386b335e52dc0abf082d4c649a24 --- /dev/null +++ b/pool/shard002/C/0058271_main.c @@ -0,0 +1,208 @@ +/*==================[inclusions]=============================================*/ + +#include "main.h" + + +/*==================[macros and definitions]=================================*/ +#define LPC_UART LPC_USART2 +#define UARTx_IRQn USART2_IRQn + +/* Ring buffer size */ +#define UART_RB_SIZE 256 + +/*==================[internal data declaration]==============================*/ + +/* Transmit and receive ring buffers */ +static RINGBUFF_T txring, rxring; + +/* Transmit and receive buffers */ +static uint8_t rxbuff[UART_RB_SIZE], txbuff[UART_RB_SIZE]; + +/*==================[internal functions declaration]=========================*/ + +/*==================[internal data definition]===============================*/ + +//Constante para definir si el anti rebote pasó +const uint8_t BTN_SHOULD_CLICK = 10; +const uint8_t MSG_FTO[] = "Introduzca el valor de entrada en el formato :XY y presione Enter\r\n"; + +/** @brief used for delay counter */ +static uint32_t pausems_count; + +/*==================[external data definition]===============================*/ + +/*==================[internal functions definition]==========================*/ + +/*==================[external functions definition]==========================*/ +/** + * @brief UART interrupt handler sub-routine + * @return Nothing + */ +void UART2_IRQHandler(void) +{ + Chip_UART_IRQRBHandler(LPC_UART, &rxring, &txring); +} + +void init_hw_UART(void){ + + Board_UART_Init(LPC_UART); + Chip_UART_Init(LPC_UART); + + Chip_UART_SetBaud(LPC_UART, 115200); + Chip_UART_ConfigData(LPC_UART, UART_LCR_WLEN8 | UART_LCR_SBS_1BIT); /* Default 8-N-1 */ + + /* Enable UART Transmit */ + Chip_UART_TXEnable(LPC_UART); + + /* Reset FIFOs, Enable FIFOs and DMA mode in UART */ + Chip_UART_SetupFIFOS(LPC_UART, (UART_FCR_FIFO_EN | UART_FCR_RX_RS | UART_FCR_TX_RS | UART_FCR_TRG_LEV0)); + + /* Enable UART Rx & line status interrupts */ + /* + * Do not enable transmit interrupt here, since it is handled by + * UART_Send() function, just to reset Tx Interrupt state for the + * first time + */ + Chip_UART_IntEnable(LPC_UART, (UART_IER_RBRINT)); + + /* Before using the ring buffers, initialize them using the ring + buffer init function */ + RingBuffer_Init(&rxring, rxbuff, 1, UART_RB_SIZE); + RingBuffer_Init(&txring, txbuff, 1, UART_RB_SIZE); + + /* Enable Interrupt for UART channel */ + /* Priority = 1 */ + NVIC_SetPriority(UARTx_IRQn, 1); + /* Enable Interrupt for UART channel */ + NVIC_EnableIRQ(UARTx_IRQn); + +} + +void init_hw_PWM(void){ + Chip_SCTPWM_Init(LPC_SCT); + + Chip_SCTPWM_SetRate(LPC_SCT, 10000); + + Chip_SCU_PinMux(2,10,0,FUNC1); + Chip_SCU_PinMux(2,11,0,FUNC1); + Chip_SCU_PinMux(2,12,0,FUNC1); + + Chip_SCTPWM_SetOutPin(LPC_SCT, 1, 2); + Chip_SCTPWM_SetOutPin(LPC_SCT, 2, 5); + Chip_SCTPWM_SetOutPin(LPC_SCT, 3, 4); + + Chip_SCTPWM_Start(LPC_SCT); +} + +void initHardware(void) +{ + Board_Init(); + Board_Buttons_Init(); + SystemCoreClockUpdate(); + SysTick_Config(SystemCoreClock/1000); + init_hw_UART (); + init_hw_PWM (); +} + +uint8_t boton_salida(uint8_t current_duty1, uint8_t num_boton){ + uint8_t nuevo_duty = (uint8_t) botones[num_boton].funcion_btn(current_duty1); + + //convierto el duty hexadecimal en un porcentaje + uint8_t percentage = (nuevo_duty * (uint8_t)0x64)/((uint8_t)0xff); + //funcion de interpolacion lineal + uint16_t interpolado = interpolar_num(nuevo_duty); + //convierto el duty interpolado en un porcentaje + uint8_t percent_interpolado = ((uint8_t)interpolado * (uint8_t)0x64)/((uint8_t)0xff); + + //Entrada por LED 2 + Chip_SCTPWM_SetDutyCycle(LPC_SCT, 2, Chip_SCTPWM_PercentageToTicks(LPC_SCT, percentage)); + //Salida por LED 3 + Chip_SCTPWM_SetDutyCycle(LPC_SCT, 3, Chip_SCTPWM_PercentageToTicks(LPC_SCT, percent_interpolado)); + + /* Devuelvo el valor de duty para poder guardarlo */ + return nuevo_duty; +} + +void pausems(uint32_t t) +{ + pausems_count = t; + while(pausems_count != 0) { + __WFI(); + } +} + +void SysTick_Handler(void) +{ + if(pausems_count > 0) pausems_count--; +} + +int main(void) +{ + uint8_t buffer[1]; + int ret = 0; + int len; + volatile int antiRebAcum = 0; + uint8_t salidaUART; + uint8_t percentageUART; + uint8_t hexValue; + uint32_t BUTTON_STATUS_POLLED = 0x00; + uint8_t current_duty = 0x00; + + InputDTO maquina = {.state=IDLE_MSG, .data={[0]='0', [1]='0', [2]='\0'}}; + + initHardware(); + + //Enviar mensaje con instrucciones por UART + Chip_UART_SendRB(LPC_UART,&txring,&MSG_FTO,sizeof(MSG_FTO)); + + /* Read some data from the buffer */ + while (1) + { + + len = Chip_UART_ReadRB(LPC_UART, &rxring, &buffer, sizeof(buffer)); + + Chip_UART_SendRB(LPC_UART, &txring, &buffer, len); + + //Si llegó un nuevo char desde UART, hago transicionar la maquina de estados. + if(len > 0) + transicionar_dto(&maquina, buffer[0]); + + //Si la maquina procesó una palabra, se hace la interpolacion lineal y se calculan los porcentajes + if(maquina.state == END_MSG){ + hexValue = string_to_8bit_hex(maquina.data); + percentageUART = ( hexValue * (uint8_t)0x64)/((uint8_t)0xff); + salidaUART = (interpolar_string(maquina.data) * (uint8_t)0x64)/((uint8_t)0xff); + //cambiar intensidad del LED 0 con la entrada + //LED_Duty_change(maquina.data, LED0); + Chip_SCTPWM_SetDutyCycle(LPC_SCT, 2, Chip_SCTPWM_PercentageToTicks(LPC_SCT, percentageUART)); + //cambiar intensidad del LED 1 con la salida + //LED_Duty_change(salidaUART, LED1); + Chip_SCTPWM_SetDutyCycle(LPC_SCT, 3, Chip_SCTPWM_PercentageToTicks(LPC_SCT, salidaUART)); + maquina.state = IDLE_MSG; + } + + BUTTON_STATUS_POLLED = Buttons_GetStatus(); + //Si se presionan varios botones al mismo tiempo BUTTON_STATUS_POLLED no va a estar entre 1..4 + if(BUTTON_STATUS_POLLED != 0 && BUTTON_STATUS_POLLED > 0 && BUTTON_STATUS_POLLED < 5 ){ + while(antiRebAcum < BTN_SHOULD_CLICK && Buttons_GetStatus() == BUTTON_STATUS_POLLED){ + antiRebAcum++; + pausems(10); + } + + if(antiRebAcum == BTN_SHOULD_CLICK){ + current_duty = boton_salida(current_duty, BUTTON_STATUS_POLLED-1); + } + + antiRebAcum = 0; + } + + } + + return ret; +} + + + +/** @} doxygen end group definition */ + +/*==================[end of file]============================================*/ diff --git a/pool/shard002/C/0058300_left.c b/pool/shard002/C/0058300_left.c new file mode 100644 index 0000000000000000000000000000000000000000..af850576dffb3d910455d1a49705dcb75965e1b9 --- /dev/null +++ b/pool/shard002/C/0058300_left.c @@ -0,0 +1,11 @@ +#include + +int main() { + CGEventRef event1, event2; + event1 = CGEventCreateKeyboardEvent (NULL, (CGKeyCode)123, true); + event2 = CGEventCreateKeyboardEvent (NULL, (CGKeyCode)123, false); + CGEventTapLocation loc = kCGSessionEventTap; + CGEventPost(loc, event1); + CGEventPost(loc, event2); + return 0; +} diff --git a/pool/shard002/C/0058306_mc-test.c b/pool/shard002/C/0058306_mc-test.c new file mode 100644 index 0000000000000000000000000000000000000000..2b0ac89d1e3a14c88740a743436d772c8b2c4fd3 --- /dev/null +++ b/pool/shard002/C/0058306_mc-test.c @@ -0,0 +1,90 @@ +/*******************************************************************************/ +/* Copyright (C) 1994 - 1998, Performance Dynamics Company */ +/* */ +/* This software is licensed as described in the file COPYING, which */ +/* you should have received as part of this distribution. The terms */ +/* are also available at http://www.perfdynamics.com/Tools/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. */ +/*******************************************************************************/ + +/* + * multiclass-test.c + * + * Test PDQ_Exact.c lib + * + * From A.Allen Example 6.3.4, p.413 + * + * $Id: mc-test.c,v 4.4 2009/04/03 02:19:40 pfeller Exp $ + */ + +//------------------------------------------------------------------------- + +#include +#include +#include "PDQ_Lib.h" + +//------------------------------------------------------------------------- + +int main() +{ + + /************************ + * PDQ global variables * + ************************/ + + int noNodes; + int noStreams; + + /************************ + * Initialize the model * + ************************/ + + /* Give model a name */ + + PDQ_Init("Multiclass Test"); + + /* Define the workload and circuit type */ + + noStreams = PDQ_CreateClosed("term1", TERM, 5.0, 20.0); + noStreams = PDQ_CreateClosed("term2", TERM, 15.0, 30.0); + noStreams = PDQ_CreateClosed("batch", BATCH, 5.0, 0.0); + + /* Define the queueing center */ + + noNodes = PDQ_CreateNode("node1", CEN, FCFS); + noNodes = PDQ_CreateNode("node2", CEN, FCFS); + noNodes = PDQ_CreateNode("node3", CEN, FCFS); + + /* Define service demand */ + + PDQ_SetDemand("node1", "term1", 0.50); + PDQ_SetDemand("node1", "term2", 0.04); + PDQ_SetDemand("node1", "batch", 0.06); + + PDQ_SetDemand("node2", "term1", 0.40); + PDQ_SetDemand("node2", "term2", 0.20); + PDQ_SetDemand("node2", "batch", 0.30); + + PDQ_SetDemand("node3", "term1", 1.20); + PDQ_SetDemand("node3", "term2", 0.05); + PDQ_SetDemand("node3", "batch", 0.06); + + /******************* + * Solve the model * + *******************/ + + PDQ_Solve(EXACT); + + PDQ_Report(); + + return(0); +} /* main */ + +//------------------------------------------------------------------------- + diff --git a/pool/shard002/C/0058310_setup_teardown.c b/pool/shard002/C/0058310_setup_teardown.c new file mode 100644 index 0000000000000000000000000000000000000000..4a047779a87c35cc28d80e932ab4ae0fc10f2dc3 --- /dev/null +++ b/pool/shard002/C/0058310_setup_teardown.c @@ -0,0 +1,93 @@ +/* +* kinetic-c +* Copyright (C) 2015 Seagate 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. +* +*/ + +#include "kinetic_client.h" +#include "kinetic_types.h" +#include "byte_array.h" +#include +#include +#include +#include +#include +#include +#include + +static char *kinetic_host = "localhost"; +static long idle_seconds = 0; + +static void usage(void) { + fprintf(stderr, "usage: setup_teardown [-h KINETIC_HOST] [-i IDLE_SECONDS]\n"); + exit(1); +} + +static void handle_args(int argc, char **argv) { + int fl = 0; + while ((fl = getopt(argc, argv, "i:h:")) != -1) { + switch (fl) { + case 'h': /* host */ + kinetic_host = optarg; + break; + case 'i': /* idle seconds */ + idle_seconds = strtol(optarg, NULL, 10); + break; + case '?': + default: + usage(); + } + } +} + +int main(int argc, char** argv) +{ + handle_args(argc, argv); + + // Initialize kinetic-c and configure sessions + KineticSession* session; + KineticClientConfig clientConfig = { + .logFile = "stdout", + .logLevel = 1, + }; + KineticClient * client = KineticClient_Init(&clientConfig); + if (client == NULL) { return 1; } + const char HmacKeyString[] = "asdfasdf"; + KineticSessionConfig sessionConfig = { + .host = "localhost", + .port = KINETIC_PORT, + .clusterVersion = 0, + .identity = 1, + .hmacKey = ByteArray_CreateWithCString(HmacKeyString), + }; + KineticStatus status = KineticClient_CreateSession(&sessionConfig, client, &session); + if (status != KINETIC_STATUS_SUCCESS) { + fprintf(stderr, "Failed connecting to the Kinetic device w/status: %s\n", + Kinetic_GetStatusDescription(status)); + exit(1); + } + + if (idle_seconds > 0) { + printf(" -- Sleeping %ld seconds\n", idle_seconds); + sleep(idle_seconds); + } + + // Shutdown client connection and cleanup + KineticClient_DestroySession(session); + KineticClient_Shutdown(client); + return 0; +} diff --git a/pool/shard002/C/0058321_prologtest.c b/pool/shard002/C/0058321_prologtest.c new file mode 100644 index 0000000000000000000000000000000000000000..5fca0a5c4594459bb923f8f1991f44b4a5394bca --- /dev/null +++ b/pool/shard002/C/0058321_prologtest.c @@ -0,0 +1,113 @@ +/************************************************************************* +This file is part of libprolog + +Copyright (C) 2010 Nokia Corporation. + +This library is free software; you can redistribute +it and/or modify it under the terms of the GNU Lesser General Public +License as published by the Free Software Foundation +version 2.1 of the License. + +This library is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +Lesser General Public License for more details. + +You should have received a copy of the GNU Lesser General Public +License along with this library; if not, write to the Free Software +Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 +USA. +*************************************************************************/ + + + +#include +#include +#include + +#include + +#define fatal(ec, fmt, args...) do { \ + printf("fatal error: "fmt"\n", ## args); \ + exit(ec); \ +} while (0) + +#define TESTPL "./libtest.pl" + + +int +main(int argc, char *argv[]) +{ + char *default_files[] = { + "prolog/hwconfig", + "prolog/devconfig", + "prolog/interface", + "prolog/profile", + "prolog/audio", + "prolog/test" + }; + char **files; + int nfile = sizeof(default_files)/sizeof(default_files[0]); + + prolog_predicate_t *predicates, *undef, *p, *set_routes; + char ***actions; + int i; + + /* initialize our prolog library */ + if (prolog_init("test", 0, 0, 0, 0, NULL) != 0) + fatal(1, "failed to initialize prolog library"); + + if (argc <= 1) + files = default_files; + else { + files = argv + 1; + nfile = argc - 1; + } + + /* load our test files */ + for (i = 0; i < nfile; i++) { + printf("loading file %s...\n", files[i]); + if (prolog_load_file(files[i])) + fatal(2, "failed to load %s", files[i]); + } + + if (prolog_rules(&predicates, &undef) != 0) + fatal(3, "failed to get exported predicates from prolog"); + + set_routes = NULL; + for (p = predicates; p->name; p++) { + printf("found exported predicate: %s%s%s/%d (0x%x)\n", + p->module ?: "", p->module ? ":" : "", + p->name, p->arity, + (unsigned int)p->predicate); + if (!strcmp(p->name, "set_routes") && p->arity == 1) + set_routes = p; + } + + if (set_routes == NULL) + fatal(4, "failed to find exported predicate \"set_routes\""); + + printf("invoking prolog predicate %s\n", set_routes->name); + if (!prolog_call(set_routes, &actions)) + fatal(5, "failed to invoke exported predicate %s", set_routes->name); + + prolog_dump_results(actions); + + /* clean up our prolog library */ + prolog_exit(); + + return 0; +} + + + + +/* + * Local Variables: + * c-basic-offset: 4 + * indent-tabs-mode: nil + * End: +*/ + + + diff --git a/pool/shard002/C/0058332_em_letimer.c b/pool/shard002/C/0058332_em_letimer.c new file mode 100644 index 0000000000000000000000000000000000000000..90c507018474df2459771c531078c757e557d9bc --- /dev/null +++ b/pool/shard002/C/0058332_em_letimer.c @@ -0,0 +1,529 @@ +/***************************************************************************//** + * @file em_letimer.c + * @brief Low Energy Timer (LETIMER) Peripheral API + * @version 5.3.3 + ******************************************************************************* + * # License + * Copyright 2016 Silicon Laboratories, Inc. http://www.silabs.com + ******************************************************************************* + * + * Permission is granted to anyone to use this software for any purpose, + * including commercial applications, and to alter it and redistribute it + * freely, subject to the following restrictions: + * + * 1. The origin of this software must not be misrepresented; you must not + * claim that you wrote the original software. + * 2. Altered source versions must be plainly marked as such, and must not be + * misrepresented as being the original software. + * 3. This notice may not be removed or altered from any source distribution. + * + * DISCLAIMER OF WARRANTY/LIMITATION OF REMEDIES: Silicon Labs has no + * obligation to support this Software. Silicon Labs is providing the + * Software "AS IS", with no express or implied warranties of any kind, + * including, but not limited to, any implied warranties of merchantability + * or fitness for any particular purpose or warranties against infringement + * of any proprietary rights of a third party. + * + * Silicon Labs will not be liable for any consequential, incidental, or + * special damages, or any other relief, or for any claim by any third party, + * arising from your use of this Software. + * + ******************************************************************************/ + +#include "em_letimer.h" +#if defined(LETIMER_COUNT) && (LETIMER_COUNT > 0) +#include "em_cmu.h" +#include "em_assert.h" + +/***************************************************************************//** + * @addtogroup emlib + * @{ + ******************************************************************************/ + +/***************************************************************************//** + * @addtogroup LETIMER + * @brief Low Energy Timer (LETIMER) Peripheral API + * @details + * This module contains functions to control the LETIMER peripheral of Silicon + * Labs 32-bit MCUs and SoCs. The LETIMER is a down-counter that can keep track + * of time and output configurable waveforms. + * @{ + ******************************************************************************/ + +/******************************************************************************* + ******************************* DEFINES *********************************** + ******************************************************************************/ + +/** @cond DO_NOT_INCLUDE_WITH_DOXYGEN */ + +/** Validation of valid comparator register for assert statements. */ +#define LETIMER_COMP_REG_VALID(reg) (((reg) <= 1)) + +/** Validation of LETIMER register block pointer reference for assert statements. */ +#if (LETIMER_COUNT == 1) +#define LETIMER_REF_VALID(ref) ((ref) == LETIMER0) +#elif (LETIMER_COUNT == 2) +#define LETIMER_REF_VALID(ref) (((ref) == LETIMER0) || ((ref) == LETIMER1)) +#else +#error Undefined number of analog comparators (ACMP). +#endif + +/** Validation of valid repeat counter register for assert statements. */ +#define LETIMER_REP_REG_VALID(reg) (((reg) <= 1)) + +/** @endcond */ + +/******************************************************************************* + ************************** LOCAL FUNCTIONS ******************************** + ******************************************************************************/ + +/** @cond DO_NOT_INCLUDE_WITH_DOXYGEN */ + +#if defined(_EFM32_GECKO_FAMILY) +/***************************************************************************//** + * @brief + * Wait for ongoing sync of register(s) to low frequency domain to complete. + * + * @note + * This only applies to the Gecko Family, see the reference manual + * chapter about Access to Low Energy Peripherals (Asynchronos Registers) + * for details. + * + * @param[in] letimer + * Pointer to LETIMER peripheral register block + * + * @param[in] mask + * Bitmask corresponding to SYNCBUSY register defined bits, indicating + * registers that must complete any ongoing synchronization. + ******************************************************************************/ +__STATIC_INLINE void regSync(LETIMER_TypeDef *letimer, uint32_t mask) +{ +#if defined(_LETIMER_FREEZE_MASK) + /* Avoid deadlock if modifying the same register twice when freeze mode is */ + /* activated. */ + if (letimer->FREEZE & LETIMER_FREEZE_REGFREEZE) { + return; + } +#endif + + /* Wait for any pending previous write operation to have been completed */ + /* in low frequency domain, only required for Gecko Family of devices */ + while (letimer->SYNCBUSY & mask) + ; +} +#endif + +/** @endcond */ + +/******************************************************************************* + ************************** GLOBAL FUNCTIONS ******************************* + ******************************************************************************/ + +/***************************************************************************//** + * @brief + * Get LETIMER compare register value. + * + * @param[in] letimer + * Pointer to LETIMER peripheral register block + * + * @param[in] comp + * Compare register to get, either 0 or 1 + * + * @return + * Compare register value, 0 if invalid register selected. + ******************************************************************************/ +uint32_t LETIMER_CompareGet(LETIMER_TypeDef *letimer, unsigned int comp) +{ + uint32_t ret; + + EFM_ASSERT(LETIMER_REF_VALID(letimer) && LETIMER_COMP_REG_VALID(comp)); + + /* Initialize selected compare value */ + switch (comp) { + case 0: + ret = letimer->COMP0; + break; + + case 1: + ret = letimer->COMP1; + break; + + default: + /* Unknown compare register selected */ + ret = 0; + break; + } + + return(ret); +} + +/***************************************************************************//** + * @brief + * Set LETIMER compare register value. + * + * @note + * The setting of a compare register requires synchronization into the + * low frequency domain. If the same register is modified before a previous + * update has completed, this function will stall until the previous + * synchronization has completed. This only applies to the Gecko Family, see + * comment in the LETIMER_Sync() internal function call. + * + * @param[in] letimer + * Pointer to LETIMER peripheral register block + * + * @param[in] comp + * Compare register to set, either 0 or 1 + * + * @param[in] value + * Initialization value (<= 0x0000ffff) + ******************************************************************************/ +void LETIMER_CompareSet(LETIMER_TypeDef *letimer, + unsigned int comp, + uint32_t value) +{ + volatile uint32_t *compReg; + + EFM_ASSERT(LETIMER_REF_VALID(letimer) + && LETIMER_COMP_REG_VALID(comp) + && ((value & ~(_LETIMER_COMP0_COMP0_MASK + >> _LETIMER_COMP0_COMP0_SHIFT)) + == 0)); + + /* Initialize selected compare value */ + switch (comp) { + case 0: + compReg = &(letimer->COMP0); + break; + + case 1: + compReg = &(letimer->COMP1); + break; + + default: + /* Unknown compare register selected, abort */ + return; + } + +#if defined(_EFM32_GECKO_FAMILY) + /* LF register about to be modified require sync. busy check */ + regSync(letimer, comp ? LETIMER_SYNCBUSY_COMP1 : LETIMER_SYNCBUSY_COMP0); +#endif + + *compReg = value; +} + +/***************************************************************************//** + * @brief + * Start/stop LETIMER. + * + * @note + * The enabling/disabling of the LETIMER modifies the LETIMER CMD register + * which requires synchronization into the low frequency domain. If this + * register is modified before a previous update to the same register has + * completed, this function will stall until the previous synchronization has + * completed. This only applies to the Gecko Family, see comment in the + * LETIMER_Sync() internal function call. + * + * @param[in] letimer + * Pointer to LETIMER peripheral register block. + * + * @param[in] enable + * true to enable counting, false to disable. + ******************************************************************************/ +void LETIMER_Enable(LETIMER_TypeDef *letimer, bool enable) +{ + EFM_ASSERT(LETIMER_REF_VALID(letimer)); + +#if defined(_EFM32_GECKO_FAMILY) + /* LF register about to be modified require sync. busy check */ + regSync(letimer, LETIMER_SYNCBUSY_CMD); +#endif + + if (enable) { + letimer->CMD = LETIMER_CMD_START; + } else { + letimer->CMD = LETIMER_CMD_STOP; + } +} + +#if defined(_LETIMER_FREEZE_MASK) +/***************************************************************************//** + * @brief + * LETIMER register synchronization freeze control. + * + * @details + * Some LETIMER registers require synchronization into the low frequency (LF) + * domain. The freeze feature allows for several such registers to be + * modified before passing them to the LF domain simultaneously (which + * takes place when the freeze mode is disabled). + * + * @note + * When enabling freeze mode, this function will wait for all current + * ongoing LETIMER synchronization to LF domain to complete (Normally + * synchronization will not be in progress.) However for this reason, when + * using freeze mode, modifications of registers requiring LF synchronization + * should be done within one freeze enable/disable block to avoid unecessary + * stalling. + * + * @param[in] letimer + * Pointer to LETIMER peripheral register block. + * + * @param[in] enable + * @li true - enable freeze, modified registers are not propagated to the + * LF domain + * @li false - disables freeze, modified registers are propagated to LF + * domain + ******************************************************************************/ +void LETIMER_FreezeEnable(LETIMER_TypeDef *letimer, bool enable) +{ + if (enable) { + /* + * Wait for any ongoing LF synchronization to complete. This is just to + * protect against the rare case when a user + * - modifies a register requiring LF sync + * - then enables freeze before LF sync completed + * - then modifies the same register again + * since modifying a register while it is in sync progress should be + * avoided. + */ + while (letimer->SYNCBUSY) + ; + + letimer->FREEZE = LETIMER_FREEZE_REGFREEZE; + } else { + letimer->FREEZE = 0; + } +} +#endif /* defined(_LETIMER_FREEZE_MASK) */ + +/***************************************************************************//** + * @brief + * Initialize LETIMER. + * + * @details + * Note that the compare/repeat values must be set separately with + * LETIMER_CompareSet() and LETIMER_RepeatSet(). That should probably be done + * prior to the use of this function if configuring the LETIMER to start when + * initialization is completed. + * + * @note + * The initialization of the LETIMER modifies the LETIMER CTRL/CMD registers + * which require synchronization into the low frequency domain. If any of those + * registers are modified before a previous update to the same register has + * completed, this function will stall until the previous synchronization has + * completed. This only applies to the Gecko Family, see comment in the + * LETIMER_Sync() internal function call. + * + * @param[in] letimer + * Pointer to LETIMER peripheral register block. + * + * @param[in] init + * Pointer to LETIMER initialization structure. + ******************************************************************************/ +void LETIMER_Init(LETIMER_TypeDef *letimer, const LETIMER_Init_TypeDef *init) +{ + uint32_t tmp = 0; + + EFM_ASSERT(LETIMER_REF_VALID(letimer)); + + /* Stop timer if specified to be disabled and running */ + if (!(init->enable) && (letimer->STATUS & LETIMER_STATUS_RUNNING)) { +#if defined(_EFM32_GECKO_FAMILY) + /* LF register about to be modified require sync. busy check */ + regSync(letimer, LETIMER_SYNCBUSY_CMD); +#endif + letimer->CMD = LETIMER_CMD_STOP; + } + + /* Configure DEBUGRUN flag, sets whether or not counter should be + * updated when debugger is active */ + if (init->debugRun) { + tmp |= LETIMER_CTRL_DEBUGRUN; + } + +#if defined(LETIMER_CTRL_RTCC0TEN) + if (init->rtcComp0Enable) { + tmp |= LETIMER_CTRL_RTCC0TEN; + } + + if (init->rtcComp1Enable) { + tmp |= LETIMER_CTRL_RTCC1TEN; + } +#endif + + if (init->comp0Top) { + tmp |= LETIMER_CTRL_COMP0TOP; + } + + if (init->bufTop) { + tmp |= LETIMER_CTRL_BUFTOP; + } + + if (init->out0Pol) { + tmp |= LETIMER_CTRL_OPOL0; + } + + if (init->out1Pol) { + tmp |= LETIMER_CTRL_OPOL1; + } + + tmp |= init->ufoa0 << _LETIMER_CTRL_UFOA0_SHIFT; + tmp |= init->ufoa1 << _LETIMER_CTRL_UFOA1_SHIFT; + tmp |= init->repMode << _LETIMER_CTRL_REPMODE_SHIFT; + +#if defined(_EFM32_GECKO_FAMILY) + /* LF register about to be modified require sync. busy check */ + regSync(letimer, LETIMER_SYNCBUSY_CTRL); +#endif + letimer->CTRL = tmp; + + /* Start timer if specified to be enabled and not already running */ + if (init->enable && !(letimer->STATUS & LETIMER_STATUS_RUNNING)) { +#if defined(_EFM32_GECKO_FAMILY) + /* LF register about to be modified require sync. busy check */ + regSync(letimer, LETIMER_SYNCBUSY_CMD); +#endif + letimer->CMD = LETIMER_CMD_START; + } +} + +/***************************************************************************//** + * @brief + * Get LETIMER repeat register value. + * + * @param[in] letimer + * Pointer to LETIMER peripheral register block + * + * @param[in] rep + * Repeat register to get, either 0 or 1 + * + * @return + * Repeat register value, 0 if invalid register selected. + ******************************************************************************/ +uint32_t LETIMER_RepeatGet(LETIMER_TypeDef *letimer, unsigned int rep) +{ + uint32_t ret; + + EFM_ASSERT(LETIMER_REF_VALID(letimer) && LETIMER_REP_REG_VALID(rep)); + + /* Initialize selected compare value */ + switch (rep) { + case 0: + ret = letimer->REP0; + break; + + case 1: + ret = letimer->REP1; + break; + + default: + /* Unknown compare register selected */ + ret = 0; + break; + } + + return(ret); +} + +/***************************************************************************//** + * @brief + * Set LETIMER repeat counter register value. + * + * @note + * The setting of a repeat counter register requires synchronization into the + * low frequency domain. If the same register is modified before a previous + * update has completed, this function will stall until the previous + * synchronization has completed. This only applies to the Gecko Family, see + * comment in the LETIMER_Sync() internal function call. + * + * @param[in] letimer + * Pointer to LETIMER peripheral register block + * + * @param[in] rep + * Repeat counter register to set, either 0 or 1 + * + * @param[in] value + * Initialization value (<= 0x0000ffff) + ******************************************************************************/ +void LETIMER_RepeatSet(LETIMER_TypeDef *letimer, + unsigned int rep, + uint32_t value) +{ + volatile uint32_t *repReg; +#if defined(_EFM32_GECKO_FAMILY) + uint32_t syncbusy; +#endif + EFM_ASSERT(LETIMER_REF_VALID(letimer) + && LETIMER_REP_REG_VALID(rep) + && ((value & ~(_LETIMER_REP0_REP0_MASK + >> _LETIMER_REP0_REP0_SHIFT)) + == 0)); + + /* Initialize selected compare value */ + switch (rep) { + case 0: + repReg = &(letimer->REP0); +#if defined(_EFM32_GECKO_FAMILY) + syncbusy = LETIMER_SYNCBUSY_REP0; +#endif + break; + + case 1: + repReg = &(letimer->REP1); +#if defined(_EFM32_GECKO_FAMILY) + syncbusy = LETIMER_SYNCBUSY_REP1; +#endif + break; + + default: + /* Unknown compare register selected, abort */ + return; + } + +#if defined(_EFM32_GECKO_FAMILY) + /* LF register about to be modified require sync. busy check */ + regSync(letimer, syncbusy); +#endif + + *repReg = value; +} + +/***************************************************************************//** + * @brief + * Reset LETIMER to same state as after a HW reset. + * + * @note + * The ROUTE register is NOT reset by this function, in order to allow for + * centralized setup of this feature. + * + * @param[in] letimer + * Pointer to LETIMER peripheral register block. + ******************************************************************************/ +void LETIMER_Reset(LETIMER_TypeDef *letimer) +{ +#if defined(_LETIMER_FREEZE_MASK) + /* Freeze registers to avoid stalling for LF synchronization */ + LETIMER_FreezeEnable(letimer, true); +#endif + + /* Make sure disabled first, before resetting other registers */ + letimer->CMD = LETIMER_CMD_STOP | LETIMER_CMD_CLEAR + | LETIMER_CMD_CTO0 | LETIMER_CMD_CTO1; + letimer->CTRL = _LETIMER_CTRL_RESETVALUE; + letimer->COMP0 = _LETIMER_COMP0_RESETVALUE; + letimer->COMP1 = _LETIMER_COMP1_RESETVALUE; + letimer->REP0 = _LETIMER_REP0_RESETVALUE; + letimer->REP1 = _LETIMER_REP1_RESETVALUE; + letimer->IEN = _LETIMER_IEN_RESETVALUE; + letimer->IFC = _LETIMER_IFC_MASK; + /* Do not reset route register, setting should be done independently */ + +#if defined(_LETIMER_FREEZE_MASK) + /* Unfreeze registers, pass new settings on to LETIMER */ + LETIMER_FreezeEnable(letimer, false); +#endif +} + +/** @} (end addtogroup LETIMER) */ +/** @} (end addtogroup emlib) */ +#endif /* defined(LETIMER_COUNT) && (LETIMER_COUNT > 0) */ diff --git a/pool/shard002/C/0058349_mod.c b/pool/shard002/C/0058349_mod.c new file mode 100644 index 0000000000000000000000000000000000000000..6f1841b7ffcc674ebfdf08c5ac1d132bdb071ac3 --- /dev/null +++ b/pool/shard002/C/0058349_mod.c @@ -0,0 +1,201 @@ +/* + * net/9p/9p.c + * + * 9P entry point + * + * Copyright (C) 2007 by Latchesar Ionkov + * Copyright (C) 2004 by Eric Van Hensbergen + * Copyright (C) 2002 by Ron Minnich + * + * 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: + * Free Software Foundation + * 51 Franklin Street, Fifth Floor + * Boston, MA 02111-1301 USA + * + */ + +#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#ifdef CONFIG_NET_9P_DEBUG +unsigned int p9_debug_level = 0; /* feature-rific global debug level */ +EXPORT_SYMBOL(p9_debug_level); +module_param_named(debug, p9_debug_level, uint, 0); +MODULE_PARM_DESC(debug, "9P debugging level"); + +void _p9_debug(enum p9_debug_flags level, const char *func, + const char *fmt, ...) +{ + struct va_format vaf; + va_list args; + + if ((p9_debug_level & level) != level) + return; + + va_start(args, fmt); + + vaf.fmt = fmt; + vaf.va = &args; + + if (level == P9_DEBUG_9P) + pr_notice("(%8.8d) %pV", task_pid_nr(current), &vaf); + else + pr_notice("-- %s (%d): %pV", func, task_pid_nr(current), &vaf); + + va_end(args); +} +EXPORT_SYMBOL(_p9_debug); +#endif + +/* + * Dynamic Transport Registration Routines + * + */ + +static DEFINE_SPINLOCK(v9fs_trans_lock); +static LIST_HEAD(v9fs_trans_list); + +/** + * v9fs_register_trans - register a new transport with 9p + * @m: structure describing the transport module and entry points + * + */ +void v9fs_register_trans(struct p9_trans_module *m) +{ + spin_lock(&v9fs_trans_lock); + pax_list_add_tail((struct list_head *)&m->list, &v9fs_trans_list); + spin_unlock(&v9fs_trans_lock); +} +EXPORT_SYMBOL(v9fs_register_trans); + +/** + * v9fs_unregister_trans - unregister a 9p transport + * @m: the transport to remove + * + */ +void v9fs_unregister_trans(struct p9_trans_module *m) +{ + spin_lock(&v9fs_trans_lock); + pax_list_del_init((struct list_head *)&m->list); + spin_unlock(&v9fs_trans_lock); +} +EXPORT_SYMBOL(v9fs_unregister_trans); + +/** + * v9fs_get_trans_by_name - get transport with the matching name + * @name: string identifying transport + * + */ +struct p9_trans_module *v9fs_get_trans_by_name(char *s) +{ + struct p9_trans_module *t, *found = NULL; + + spin_lock(&v9fs_trans_lock); + + list_for_each_entry(t, &v9fs_trans_list, list) + if (strcmp(t->name, s) == 0 && + try_module_get(t->owner)) { + found = t; + break; + } + + spin_unlock(&v9fs_trans_lock); + return found; +} +EXPORT_SYMBOL(v9fs_get_trans_by_name); + +/** + * v9fs_get_default_trans - get the default transport + * + */ + +struct p9_trans_module *v9fs_get_default_trans(void) +{ + struct p9_trans_module *t, *found = NULL; + + spin_lock(&v9fs_trans_lock); + + list_for_each_entry(t, &v9fs_trans_list, list) + if (t->def && try_module_get(t->owner)) { + found = t; + break; + } + + if (!found) + list_for_each_entry(t, &v9fs_trans_list, list) + if (try_module_get(t->owner)) { + found = t; + break; + } + + spin_unlock(&v9fs_trans_lock); + return found; +} +EXPORT_SYMBOL(v9fs_get_default_trans); + +/** + * v9fs_put_trans - put trans + * @m: transport to put + * + */ +void v9fs_put_trans(struct p9_trans_module *m) +{ + if (m) + module_put(m->owner); +} + +/** + * init_p9 - Initialize module + * + */ +static int __init init_p9(void) +{ + int ret = 0; + + p9_error_init(); + pr_info("Installing 9P2000 support\n"); + p9_trans_fd_init(); + + return ret; +} + +/** + * exit_p9 - shutdown module + * + */ + +static void __exit exit_p9(void) +{ + pr_info("Unloading 9P2000 support\n"); + + p9_trans_fd_exit(); +} + +module_init(init_p9) +module_exit(exit_p9) + +MODULE_AUTHOR("Latchesar Ionkov "); +MODULE_AUTHOR("Eric Van Hensbergen "); +MODULE_AUTHOR("Ron Minnich "); +MODULE_LICENSE("GPL"); diff --git a/pool/shard002/C/0058363_main.c b/pool/shard002/C/0058363_main.c new file mode 100644 index 0000000000000000000000000000000000000000..c011eb8ed37cce7961556000e3cb3abddd004a5e --- /dev/null +++ b/pool/shard002/C/0058363_main.c @@ -0,0 +1,229 @@ +/* + * main.c + * Copyright (C) 2021 xent + * Project is distributed under the terms of the MIT License + */ + +#include "default_fs.h" +#include "helpers.h" +#include "virtual_mem.h" +#include +#include +#include +#include +#include +/*----------------------------------------------------------------------------*/ +START_TEST(testCapacityReading) +{ + struct TestContext context = makeTestHandle(); + enum Result res; + + struct FsNode * const node = fsOpenNode(context.handle, PATH_HOME_ROOT_ALIG); + ck_assert_ptr_nonnull(node); + + /* Read capacity length */ + + FsLength length; + + res = fsNodeLength(node, FS_NODE_CAPACITY, &length); + ck_assert_uint_eq(res, E_OK); + ck_assert_uint_eq(length, sizeof(FsCapacity)); + + /* Read capacity */ + + FsCapacity capacity; + size_t count; + + res = fsNodeRead(node, FS_NODE_CAPACITY, 0, &capacity, sizeof(capacity), + &count); + ck_assert_uint_eq(res, E_OK); + ck_assert_uint_eq(capacity, ALIG_FILE_SIZE); + ck_assert_uint_eq(count, sizeof(capacity)); + + /* Read capacity failure */ + + res = fsNodeRead(node, FS_NODE_CAPACITY, 0, &capacity, 0, 0); + ck_assert_uint_ne(res, E_OK); + + fsNodeFree(node); + freeTestHandle(context); +} +/*----------------------------------------------------------------------------*/ +START_TEST(testClusterSizeReading) +{ + struct TestContext context = makeTestHandle(); + + const size_t size = fat32GetClusterSize(context.handle); + ck_assert_uint_eq(size, FS_CLUSTER_SIZE); + + freeTestHandle(context); +} +/*----------------------------------------------------------------------------*/ +START_TEST(testEmptyVolumeUsage) +{ + enum Result res; + + static const struct VirtualMemConfig vmemConfig = { + .size = FS_TOTAL_SIZE + }; + struct Interface * const vmem = init(VirtualMem, &vmemConfig); + ck_assert_ptr_nonnull(vmem); + + static const struct Fat32FsConfig makeFsConfig = { + .clusterSize = FS_CLUSTER_SIZE, + .tableCount = FS_TABLE_COUNT + }; + res = fat32MakeFs(vmem, &makeFsConfig); + ck_assert_uint_eq(res, E_OK); + + struct Fat32Config fsConfig = { + .interface = vmem, + .nodes = FS_NODE_POOL_SIZE, + .threads = FS_THREAD_POOL_SIZE + }; + struct FsHandle * const handle = init(FatHandle, &fsConfig); + ck_assert_ptr_nonnull(handle); + + /* Read file system statistics */ + + FsCapacity used; + uint8_t buffer[MAX_BUFFER_LENGTH]; + + res = fat32GetUsage(handle, buffer, sizeof(buffer), &used); + ck_assert_uint_eq(res, E_OK); + ck_assert_uint_eq(used, FS_CLUSTER_SIZE); + + /* Free all resources */ + + deinit(handle); + deinit(vmem); +} +END_TEST +/*----------------------------------------------------------------------------*/ +START_TEST(testFullVolumeUsage) +{ + enum Result res; + + static const struct VirtualMemConfig vmemConfig = { + .size = FS_TOTAL_SIZE + }; + struct Interface * const vmem = init(VirtualMem, &vmemConfig); + ck_assert_ptr_nonnull(vmem); + + static const struct Fat32FsConfig makeFsConfig = { + .clusterSize = FS_CLUSTER_SIZE, + .tableCount = FS_TABLE_COUNT + }; + res = fat32MakeFs(vmem, &makeFsConfig); + ck_assert_uint_eq(res, E_OK); + + struct Fat32Config fsConfig = { + .interface = vmem, + .nodes = FS_NODE_POOL_SIZE, + .threads = FS_THREAD_POOL_SIZE + }; + struct FsHandle * const handle = init(FatHandle, &fsConfig); + ck_assert_ptr_nonnull(handle); + + makeNode(handle, PATH_IMAGE, false, false); + + /* Create a very long file */ + + struct FsNode * const node = fsOpenNode(handle, PATH_IMAGE); + ck_assert_ptr_nonnull(node); + + for (size_t i = 0; i < UINT32_MAX / MAX_BUFFER_LENGTH; ++i) + { + size_t count = 0; + char buffer[MAX_BUFFER_LENGTH]; + + memset(buffer, (char)i, MAX_BUFFER_LENGTH); + + res = fsNodeWrite(node, FS_NODE_DATA, i * MAX_BUFFER_LENGTH, + buffer, MAX_BUFFER_LENGTH, &count); + ck_assert(res == E_OK || res == E_FULL); + + if (res == E_FULL) + break; + } + + fsNodeFree(node); + + /* Read file system statistics */ + + FsCapacity size; + FsCapacity used; + uint8_t buffer[MAX_BUFFER_LENGTH]; + + size = fat32GetCapacity(handle); + ck_assert_uint_ne(size, 0); + + res = fat32GetUsage(handle, buffer, sizeof(buffer), &used); + ck_assert_uint_eq(res, E_OK); + ck_assert_uint_eq(used, size); + + /* Cross-verification */ + + size = fsFindUsedSpace(handle, 0); + ck_assert_uint_eq(size, used); + + /* Read failures */ + + vmemAddMarkedRegion(vmem, vmemExtractTableSectorRegion(vmem, 0, 0), + false, true, true); + + res = fat32GetUsage(handle, buffer, sizeof(buffer), &used); + ck_assert_uint_ne(res, E_OK); + + vmemClearRegions(vmem); + + /* Free all resources */ + + freeNode(handle, PATH_IMAGE); + deinit(handle); + deinit(vmem); +} +END_TEST +/*----------------------------------------------------------------------------*/ +START_TEST(testUsedSpaceCalculation) +{ + static const FsCapacity TOTAL_SPACE_USED = + 7 * FS_CLUSTER_SIZE + ALIG_FILE_SIZE + + ((UNALIG_FILE_SIZE + FS_CLUSTER_SIZE - 1) & ~(FS_CLUSTER_SIZE - 1)); + + struct TestContext context = makeTestHandle(); + FsCapacity used; + + used = fsFindUsedSpace(context.handle, 0); + ck_assert_uint_eq(used, TOTAL_SPACE_USED); + + /* Simulate context allocation error */ + PointerQueue contexts = drainContextPool(context.handle); + used = fsFindUsedSpace(context.handle, 0); + ck_assert_uint_eq(used, 0); + restoreContextPool(context.handle, &contexts); + + freeTestHandle(context); +} +END_TEST +/*----------------------------------------------------------------------------*/ +int main(void) +{ + Suite * const suite = suite_create("HandleUsage"); + TCase * const testcase = tcase_create("Core"); + + tcase_add_test(testcase, testCapacityReading); + tcase_add_test(testcase, testClusterSizeReading); + tcase_add_test(testcase, testEmptyVolumeUsage); + tcase_add_test(testcase, testFullVolumeUsage); + tcase_add_test(testcase, testUsedSpaceCalculation); + suite_add_tcase(suite, testcase); + + SRunner * const runner = srunner_create(suite); + + srunner_run_all(runner, CK_NORMAL); + const int numberFailed = srunner_ntests_failed(runner); + srunner_free(runner); + + return numberFailed == 0 ? EXIT_SUCCESS : EXIT_FAILURE; +} diff --git a/pool/shard002/C/0058366_llist.c b/pool/shard002/C/0058366_llist.c new file mode 100644 index 0000000000000000000000000000000000000000..cd5a93046d84c9d631244c069c7a091664d2667c --- /dev/null +++ b/pool/shard002/C/0058366_llist.c @@ -0,0 +1,138 @@ +/*************************************************************************** +* _ _ ____ _ +* Project ___| | | | _ \| | +* / __| | | | |_) | | +* | (__| |_| | _ <| |___ +* \___|\___/|_| \_\_____| +* +* Copyright (C) 1998 - 2020, Daniel Stenberg, , et al. +* +* This software is licensed as described in the file COPYING, which +* you should have received as part of this distribution. The terms +* are also available at https://curl.haxx.se/docs/copyright.html. +* +* You may opt to use, copy, modify, merge, publish, distribute and/or sell +* copies of the Software, and permit persons to whom the Software is +* furnished to do so, under the terms of the COPYING file. +* +* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY +* KIND, either express or implied. +* +***************************************************************************/ + +#include "curl_setup.h" +#pragma hdrstop +//#include +//#include "llist.h" +#include "curl_memory.h" +/* this must be the last include file */ +#include "memdebug.h" +/* + * @unittest: 1300 + */ +void Curl_llist_init(struct Curl_llist * l, Curl_llist_dtor dtor) +{ + l->size = 0; + l->dtor = dtor; + l->head = NULL; + l->tail = NULL; +} + +/* + * Curl_llist_insert_next() + * + * Inserts a new list element after the given one 'e'. If the given existing + * entry is NULL and the list already has elements, the new one will be + * inserted first in the list. + * + * The 'ne' argument should be a pointer into the object to store. + * + * @unittest: 1300 + */ +void Curl_llist_insert_next(struct Curl_llist * list, struct Curl_llist_element * e, + const void * p, + struct Curl_llist_element * ne) +{ + ne->ptr = (void *)p; + if(list->size == 0) { + list->head = ne; + list->head->prev = NULL; + list->head->next = NULL; + list->tail = ne; + } + else { + /* if 'e' is NULL here, we insert the new element first in the list */ + ne->next = e ? e->next : list->head; + ne->prev = e; + if(!e) { + list->head->prev = ne; + list->head = ne; + } + else if(e->next) { + e->next->prev = ne; + } + else { + list->tail = ne; + } + if(e) + e->next = ne; + } + + ++list->size; +} + +/* + * @unittest: 1300 + */ +void Curl_llist_remove(struct Curl_llist * list, struct Curl_llist_element * e, + void * user) +{ + void * ptr; + if(e == NULL || list->size == 0) + return; + + if(e == list->head) { + list->head = e->next; + + if(list->head == NULL) + list->tail = NULL; + else + e->next->prev = NULL; + } + else { + if(!e->prev) + list->head = e->next; + else + e->prev->next = e->next; + + if(!e->next) + list->tail = e->prev; + else + e->next->prev = e->prev; + } + + ptr = e->ptr; + + e->ptr = NULL; + e->prev = NULL; + e->next = NULL; + + --list->size; + + /* call the dtor() last for when it actually frees the 'e' memory itself */ + if(list->dtor) + list->dtor(user, ptr); +} + +void Curl_llist_destroy(struct Curl_llist * list, void * user) +{ + if(list) { + while(list->size > 0) + Curl_llist_remove(list, list->tail, user); + } +} + +size_t Curl_llist_count(struct Curl_llist * list) +{ + return list->size; +} diff --git a/pool/shard002/C/0058367_dlopenold.c b/pool/shard002/C/0058367_dlopenold.c new file mode 100644 index 0000000000000000000000000000000000000000..a3db5007058f4737303b6ce441a0d122cacd9593 --- /dev/null +++ b/pool/shard002/C/0058367_dlopenold.c @@ -0,0 +1,79 @@ +/* Load a shared object at run time. + Copyright (C) 1995-2017 Free Software Foundation, Inc. + This file is part of the GNU C Library. + + 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 + +/* This file is for compatibility with glibc 2.0. Compile it only if + versioning is used. */ +#include +#if SHLIB_COMPAT (libdl, GLIBC_2_0, GLIBC_2_1) + +struct dlopen_args +{ + /* The arguments for dlopen_doit. */ + const char *file; + int mode; + /* The return value of dlopen_doit. */ + void *new; + /* Address of the caller. */ + const void *caller; +}; + + +/* Non-shared code has no support for multiple namespaces. */ +#ifdef SHARED +# define NS __LM_ID_CALLER +#else +# define NS LM_ID_BASE +#endif + + +static void +dlopen_doit (void *a) +{ + struct dlopen_args *args = (struct dlopen_args *) a; + + args->new = GLRO(dl_open) (args->file ?: "", args->mode | __RTLD_DLOPEN, + args->caller, + args->file == NULL ? LM_ID_BASE : NS, + __dlfcn_argc, __dlfcn_argv, __environ); +} + +extern void *__dlopen_nocheck (const char *file, int mode); +void * +__dlopen_nocheck (const char *file, int mode) +{ + struct dlopen_args args; + args.file = file; + args.caller = RETURN_ADDRESS (0); + + if ((mode & RTLD_BINDING_MASK) == 0) + /* By default assume RTLD_LAZY. */ + mode |= RTLD_LAZY; + args.mode = mode; + + if (__glibc_unlikely (_dlfcn_hook != NULL)) + return _dlfcn_hook->dlopen (file, mode, RETURN_ADDRESS (0)); + + return _dlerror_run (dlopen_doit, &args) ? NULL : args.new; +} +compat_symbol (libdl, __dlopen_nocheck, dlopen, GLIBC_2_0); +#endif diff --git a/pool/shard002/C/0058382_logo.c b/pool/shard002/C/0058382_logo.c new file mode 100644 index 0000000000000000000000000000000000000000..a2595c6e3143657f955928d2d93a3d4ebe599a17 --- /dev/null +++ b/pool/shard002/C/0058382_logo.c @@ -0,0 +1,135 @@ + +/* + * Linux logo to be displayed on boot + * + * Copyright (C) 1996 Larry Ewing (lewing@isc.tamu.edu) + * Copyright (C) 1996,1998 Jakub Jelinek (jj@sunsite.mff.cuni.cz) + * Copyright (C) 2001 Greg Banks + * Copyright (C) 2001 Jan-Benedict Glaw + * Copyright (C) 2003 Geert Uytterhoeven + */ + +#include +#include +#include + +#ifdef CONFIG_M68K +#include +#endif + +#ifdef CONFIG_MIPS +#include +#endif + +extern const struct linux_logo logo_linux_mono; +extern const struct linux_logo logo_linux_vga16; +extern const struct linux_logo logo_linux_clut224; +extern const struct linux_logo logo_blackfin_vga16; +extern const struct linux_logo logo_linux_landscaped_clut224; +extern const struct linux_logo logo_blackfin_clut224; +extern const struct linux_logo logo_brcm_clut224; +extern const struct linux_logo logo_brcm_catalina_clut224; +extern const struct linux_logo logo_dec_clut224; +extern const struct linux_logo logo_mac_clut224; +extern const struct linux_logo logo_parisc_clut224; +extern const struct linux_logo logo_sgi_clut224; +extern const struct linux_logo logo_sun_clut224; +extern const struct linux_logo logo_superh_mono; +extern const struct linux_logo logo_superh_vga16; +extern const struct linux_logo logo_superh_clut224; +extern const struct linux_logo logo_m32r_clut224; + +static int nologo; +module_param(nologo, bool, 0); +MODULE_PARM_DESC(nologo, "Disables startup logo"); + +/* logo's are marked __initdata. Use __init_refok to tell + * modpost that it is intended that this function uses data + * marked __initdata. + */ +const struct linux_logo * __init_refok fb_find_logo(int depth) +{ + const struct linux_logo *logo = NULL; + + if (nologo) + return NULL; + + if (depth >= 1) { +#ifdef CONFIG_LOGO_LINUX_MONO + /* Generic Linux logo */ + logo = &logo_linux_mono; +#endif +#ifdef CONFIG_LOGO_SUPERH_MONO + /* SuperH Linux logo */ + logo = &logo_superh_mono; +#endif + } + + if (depth >= 4) { +#ifdef CONFIG_LOGO_LINUX_VGA16 + /* Generic Linux logo */ + logo = &logo_linux_vga16; +#endif +#ifdef CONFIG_LOGO_BLACKFIN_VGA16 + /* Blackfin processor logo */ + logo = &logo_blackfin_vga16; +#endif +#ifdef CONFIG_LOGO_SUPERH_VGA16 + /* SuperH Linux logo */ + logo = &logo_superh_vga16; +#endif + } + + if (depth >= 8) { +#ifdef CONFIG_LOGO_LINUX_BRCM + /* Broadcom splash screen */ + logo = &logo_brcm_clut224; +#endif +#ifdef CONFIG_LOGO_LINUX_BRCM_CATALINA + /* Broadcom splash screen */ + logo = &logo_brcm_catalina_clut224; +#endif +#ifdef CONFIG_LOGO_LINUX_CLUT224 + /* Generic Linux logo */ + logo = &logo_linux_clut224; +#endif +#ifdef CONFIG_LOGO_LINUX_LANDSCAPED_CLUT224 + logo = &logo_linux_landscaped_clut224; +#endif +#ifdef CONFIG_LOGO_BLACKFIN_CLUT224 + /* Blackfin Linux logo */ + logo = &logo_blackfin_clut224; +#endif +#ifdef CONFIG_LOGO_DEC_CLUT224 + /* DEC Linux logo on MIPS/MIPS64 or ALPHA */ + logo = &logo_dec_clut224; +#endif +#ifdef CONFIG_LOGO_MAC_CLUT224 + /* Macintosh Linux logo on m68k */ + if (MACH_IS_MAC) + logo = &logo_mac_clut224; +#endif +#ifdef CONFIG_LOGO_PARISC_CLUT224 + /* PA-RISC Linux logo */ + logo = &logo_parisc_clut224; +#endif +#ifdef CONFIG_LOGO_SGI_CLUT224 + /* SGI Linux logo on MIPS/MIPS64 and VISWS */ + logo = &logo_sgi_clut224; +#endif +#ifdef CONFIG_LOGO_SUN_CLUT224 + /* Sun Linux logo */ + logo = &logo_sun_clut224; +#endif +#ifdef CONFIG_LOGO_SUPERH_CLUT224 + /* SuperH Linux logo */ + logo = &logo_superh_clut224; +#endif +#ifdef CONFIG_LOGO_M32R_CLUT224 + /* M32R Linux logo */ + logo = &logo_m32r_clut224; +#endif + } + return logo; +} +EXPORT_SYMBOL_GPL(fb_find_logo); diff --git a/pool/shard002/C/0058392_example1.c b/pool/shard002/C/0058392_example1.c new file mode 100644 index 0000000000000000000000000000000000000000..8df66a91a534d4bf7c9bf59da11ab720c14eb861 --- /dev/null +++ b/pool/shard002/C/0058392_example1.c @@ -0,0 +1,106 @@ +/* example1 - Simple example from OpenCL specification. + + Copyright (c) 2011 Universidad Rey Juan Carlos + + 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 + +#define N 128 + +#ifdef __cplusplus +# define CALLAPI "C" +#else +# define CALLAPI +#endif + +extern CALLAPI int exec_dot_product_kernel (const char *program_source, + int n, void *srcA, void *srcB, void *dst); + +int +main (void) +{ + FILE *source_file; + char *source; + int source_size; + cl_float4 *srcA, *srcB; + cl_float *dst; + int ierr; + int i; + + source_file = fopen("example1.cl", "r"); + if (source_file == NULL) + source_file = fopen (SRCDIR "/example1.cl", "r"); + + assert(source_file != NULL && "example1.cl not found!"); + + fseek (source_file, 0, SEEK_END); + source_size = ftell (source_file); + fseek (source_file, 0, SEEK_SET); + + source = (char *) malloc (source_size +1 ); + assert (source != NULL); + + fread (source, source_size, 1, source_file); + source[source_size] = '\0'; + + fclose (source_file); + + srcA = (cl_float4 *) malloc (N * sizeof (cl_float4)); + srcB = (cl_float4 *) malloc (N * sizeof (cl_float4)); + dst = (cl_float *) malloc (N * sizeof (cl_float)); + + for (i = 0; i < N; ++i) + { + srcA[i].s[0] = (cl_float)i; + srcA[i].s[1] = (cl_float)i; + srcA[i].s[2] = (cl_float)i; + srcA[i].s[3] = (cl_float)i; + srcB[i].s[0] = (cl_float)i; + srcB[i].s[1] = (cl_float)i; + srcB[i].s[2] = (cl_float)i; + srcB[i].s[3] = (cl_float)i; + } + + ierr = exec_dot_product_kernel (source, N, srcA, srcB, dst); + if (ierr) printf ("ERROR\n"); + + for (i = 0; i < 4; ++i) + { + printf ("(%f, %f, %f, %f) . (%f, %f, %f, %f) = %f\n", + srcA[i].s[0], srcA[i].s[1], srcA[i].s[2], srcA[i].s[3], + srcB[i].s[0], srcB[i].s[1], srcB[i].s[2], srcB[i].s[3], + dst[i]); + if (srcA[i].s[0] * srcB[i].s[0] + + srcA[i].s[1] * srcB[i].s[1] + + srcA[i].s[2] * srcB[i].s[2] + + srcA[i].s[3] * srcB[i].s[3] != dst[i]) + { + printf ("FAIL\n"); + return -1; + } + } + + printf ("OK\n"); + return 0; +} diff --git a/pool/shard002/C/0058401_vas-debug.c b/pool/shard002/C/0058401_vas-debug.c new file mode 100644 index 0000000000000000000000000000000000000000..41fa90d2f4abdfecbfde352f1d4fb5253eed83e4 --- /dev/null +++ b/pool/shard002/C/0058401_vas-debug.c @@ -0,0 +1,165 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +/* + * Copyright 2016-17 IBM Corp. + */ + +#define pr_fmt(fmt) "vas: " fmt + +#include +#include +#include +#include +#include "vas.h" + +static struct dentry *vas_debugfs; + +static char *cop_to_str(int cop) +{ + switch (cop) { + case VAS_COP_TYPE_FAULT: return "Fault"; + case VAS_COP_TYPE_842: return "NX-842 Normal Priority"; + case VAS_COP_TYPE_842_HIPRI: return "NX-842 High Priority"; + case VAS_COP_TYPE_GZIP: return "NX-GZIP Normal Priority"; + case VAS_COP_TYPE_GZIP_HIPRI: return "NX-GZIP High Priority"; + case VAS_COP_TYPE_FTW: return "Fast Thread-wakeup"; + default: return "Unknown"; + } +} + +static int info_show(struct seq_file *s, void *private) +{ + struct vas_window *window = s->private; + + mutex_lock(&vas_mutex); + + /* ensure window is not unmapped */ + if (!window->hvwc_map) + goto unlock; + + seq_printf(s, "Type: %s, %s\n", cop_to_str(window->cop), + window->tx_win ? "Send" : "Receive"); + seq_printf(s, "Pid : %d\n", vas_window_pid(window)); + +unlock: + mutex_unlock(&vas_mutex); + return 0; +} + +DEFINE_SHOW_ATTRIBUTE(info); + +static inline void print_reg(struct seq_file *s, struct vas_window *win, + char *name, u32 reg) +{ + seq_printf(s, "0x%016llx %s\n", read_hvwc_reg(win, name, reg), name); +} + +static int hvwc_show(struct seq_file *s, void *private) +{ + struct vas_window *window = s->private; + + mutex_lock(&vas_mutex); + + /* ensure window is not unmapped */ + if (!window->hvwc_map) + goto unlock; + + print_reg(s, window, VREG(LPID)); + print_reg(s, window, VREG(PID)); + print_reg(s, window, VREG(XLATE_MSR)); + print_reg(s, window, VREG(XLATE_LPCR)); + print_reg(s, window, VREG(XLATE_CTL)); + print_reg(s, window, VREG(AMR)); + print_reg(s, window, VREG(SEIDR)); + print_reg(s, window, VREG(FAULT_TX_WIN)); + print_reg(s, window, VREG(OSU_INTR_SRC_RA)); + print_reg(s, window, VREG(HV_INTR_SRC_RA)); + print_reg(s, window, VREG(PSWID)); + print_reg(s, window, VREG(LFIFO_BAR)); + print_reg(s, window, VREG(LDATA_STAMP_CTL)); + print_reg(s, window, VREG(LDMA_CACHE_CTL)); + print_reg(s, window, VREG(LRFIFO_PUSH)); + print_reg(s, window, VREG(CURR_MSG_COUNT)); + print_reg(s, window, VREG(LNOTIFY_AFTER_COUNT)); + print_reg(s, window, VREG(LRX_WCRED)); + print_reg(s, window, VREG(LRX_WCRED_ADDER)); + print_reg(s, window, VREG(TX_WCRED)); + print_reg(s, window, VREG(TX_WCRED_ADDER)); + print_reg(s, window, VREG(LFIFO_SIZE)); + print_reg(s, window, VREG(WINCTL)); + print_reg(s, window, VREG(WIN_STATUS)); + print_reg(s, window, VREG(WIN_CTX_CACHING_CTL)); + print_reg(s, window, VREG(TX_RSVD_BUF_COUNT)); + print_reg(s, window, VREG(LRFIFO_WIN_PTR)); + print_reg(s, window, VREG(LNOTIFY_CTL)); + print_reg(s, window, VREG(LNOTIFY_PID)); + print_reg(s, window, VREG(LNOTIFY_LPID)); + print_reg(s, window, VREG(LNOTIFY_TID)); + print_reg(s, window, VREG(LNOTIFY_SCOPE)); + print_reg(s, window, VREG(NX_UTIL_ADDER)); +unlock: + mutex_unlock(&vas_mutex); + return 0; +} + +DEFINE_SHOW_ATTRIBUTE(hvwc); + +void vas_window_free_dbgdir(struct vas_window *window) +{ + if (window->dbgdir) { + debugfs_remove_recursive(window->dbgdir); + kfree(window->dbgname); + window->dbgdir = NULL; + window->dbgname = NULL; + } +} + +void vas_window_init_dbgdir(struct vas_window *window) +{ + struct dentry *d; + + if (!window->vinst->dbgdir) + return; + + window->dbgname = kzalloc(16, GFP_KERNEL); + if (!window->dbgname) + return; + + snprintf(window->dbgname, 16, "w%d", window->winid); + + d = debugfs_create_dir(window->dbgname, window->vinst->dbgdir); + window->dbgdir = d; + + debugfs_create_file("info", 0444, d, window, &info_fops); + debugfs_create_file("hvwc", 0444, d, window, &hvwc_fops); +} + +void vas_instance_init_dbgdir(struct vas_instance *vinst) +{ + struct dentry *d; + + vas_init_dbgdir(); + + vinst->dbgname = kzalloc(16, GFP_KERNEL); + if (!vinst->dbgname) + return; + + snprintf(vinst->dbgname, 16, "v%d", vinst->vas_id); + + d = debugfs_create_dir(vinst->dbgname, vas_debugfs); + vinst->dbgdir = d; +} + +/* + * Set up the "root" VAS debugfs dir. Return if we already set it up + * (or failed to) in an earlier instance of VAS. + */ +void vas_init_dbgdir(void) +{ + static bool first_time = true; + + if (!first_time) + return; + + first_time = false; + vas_debugfs = debugfs_create_dir("vas", NULL); +} diff --git a/pool/shard002/C/0058404_mempool.c b/pool/shard002/C/0058404_mempool.c new file mode 100644 index 0000000000000000000000000000000000000000..e1e5a997d67cc10f159b4d79d926905f34c53244 --- /dev/null +++ b/pool/shard002/C/0058404_mempool.c @@ -0,0 +1,153 @@ +#include +#include +#include +#include +#include +#include +#include + +#include "mempool.h" +#include "mixed_limits.h" + +static int _mempool_grow(mempool_t *mp, size_t length) { + mempool_area_t *areas = realloc(mp->areas, (mp->num_areas + 1) * sizeof(mempool_area_t)); + if (!areas) { + perror("out of memory"); + return -1; + } + + mempool_area_t *area = areas + mp->num_areas; + memset(area, 0, sizeof(mempool_area_t)); + mp->areas = areas; + + void *addr = mmap(NULL, length, mp->prot, mp->flags, -1, 0); + if (addr == MAP_FAILED) { + perror("mmap failed"); + return -1; + } + + area->addr = addr; + area->length = length; + area->index = 0; + mp->num_areas++; + return 0; +} + +int mempool_init(mempool_t *mp, size_t align, int locked) { + memset(mp, 0, sizeof(mempool_t)); + + mp->prot = PROT_READ | PROT_WRITE; + mp->flags = MAP_ANONYMOUS | MAP_PRIVATE; + if (locked) { + mp->flags |= MAP_LOCKED; + } + + long page_size = sysconf(_SC_PAGESIZE); + if (page_size < 0) { + perror("error querying pagesize"); + return -1; + } + if (page_size == 0 || page_size > LONG_SIZE_MAX) { + perror("illegal pagesize"); + return -1; + } + mp->page_size = page_size; + + if (align < 1 || align > mp->page_size || (align & (align - 1))) { + fprintf(stderr, "invalid alignment\n"); + return -1; + } + mp->align_mask = align - 1; + +#ifdef MULTITHREADED + if (pthread_mutex_init(&mp->mutex, NULL)) { + fprintf(stderr, "pthread_mutex_init failed\n"); + return -1; + } +#endif + + if (_mempool_grow(mp, mp->page_size)) { + fprintf(stderr, "_mempool_grow failed\n"); + goto err; + } + + return 0; + +err: +#ifdef MULTITHREADED + if (pthread_mutex_destroy(&mp->mutex)) { + fprintf(stderr, "pthread_mutex_destroy failed\n"); + } +#endif + return -1; +} + +void *mempool_alloc(mempool_t *mp, size_t size) { + void* result = NULL; + +#ifdef MULTITHREADED + if (pthread_mutex_lock(&mp->mutex)) { + fprintf(stderr, "pthread_mutex_lock failed\n"); + return NULL; + } +#endif + + mempool_area_t *area = mp->areas + mp->num_areas - 1; + if (size > area->length || area->index > area->length - size) { + size_t length; + if (mp->num_areas == 1) { + length = mp->page_size; + } else { + length = mp->areas[mp->num_areas - 2].length + area->length; + } + if (size > length) { + if (size > SIZE_MAX - mp->page_size + 1) { + fprintf(stderr, "requested size too large\n"); + goto out; + } + length = size + (-size) % mp->page_size; + } + if (_mempool_grow(mp, length)) { + fprintf(stderr, "_mempool_grow failed\n"); + goto out; + } + area = mp->areas + mp->num_areas - 1; + assert(size <= area->length && area->index == 0); + } + + result = area->addr + area->index; + area->index += size; + const size_t padding = (-size) & mp->align_mask; + if (padding < area->length - area->index) { + area->index += padding; + } else { + area->index = area->length; + } + +out: +#ifdef MULTITHREADED + if (pthread_mutex_unlock(&mp->mutex)) { + fprintf(stderr, "(in mempool_alloc) pthread_mutex_unlock failed\n"); + } +#endif + return result; +} + +void mempool_free(mempool_t *mp) { + for (size_t i = 0; i < mp->num_areas; i++) { + mempool_area_t *area = mp->areas + i; + if (mp->prot & MAP_LOCKED) { + memset(area->addr, 0, area->length); + } + if (munmap(area->addr, area->length)) { + fprintf(stderr, "(in mempool_free) munmap failed\n"); + } + } + free(mp->areas); + +#ifdef MULTITHREADED + if (pthread_mutex_destroy(&mp->mutex)) { + fprintf(stderr, "(in mempool_free) pthread_mutex_destroy failed\n"); + } +#endif +} diff --git a/pool/shard002/C/0058407_arcsvc.c b/pool/shard002/C/0058407_arcsvc.c new file mode 100644 index 0000000000000000000000000000000000000000..d9130d283f5916e6c713458145168425ae2729a3 --- /dev/null +++ b/pool/shard002/C/0058407_arcsvc.c @@ -0,0 +1,172 @@ +/* + * $Header: /cvsroot/arc/arc/arcsvc.c,v 1.4 2005/10/09 01:38:22 highlandsun Exp $ + */ + +/* ARC - Archive utility - ARCSVC + + Version 2.23, created on 04/22/87 at 13:10:10 + +(C) COPYRIGHT 1985-87 by System Enhancement Associates; ALL RIGHTS RESERVED + + By: Thom Henderson + + Description: + This file contains service routines needed to maintain an archive. + + Language: + Computer Innovations Optimizing C86 +*/ +#include +#include +#include +#include +#include "arc.h" +#if _MTS +#include +#endif + +#include "proto.h" + +VOID arcdie(), setstamp(); +int unlink(); + +VOID +openarc(chg) /* open archive */ + int chg; /* true to open for changes */ +{ + FILE *fopen();/* file opener */ + + if (!(arc = fopen(arcname, OPEN_R))) { + if (chg) { + if (note) + printf("Creating new archive: %s\n", arcname); + } + else + arcdie("Archive not found: %s", arcname); + } +#if _MTS /* allow reading archives of max MTS record length */ + { + char *buf, *malloc(); + int inlen; + struct GDDSECT *region; + + region=gdinfo(arc->_fd._fdub); + inlen=region->GDINLEN; + buf=malloc(inlen); + setbuffer(arc, buf, inlen); + } +#endif + if (chg) { /* if opening for changes */ + if (!(new = tmpopen(newname))) + arcdie("Cannot create archive copy: %s", newname); + + changing = chg; /* note if open for changes */ + } +} + +VOID +closearc(chg) /* close an archive */ + int chg; /* true if archive was changed */ +{ + if (arc) { /* if we had an initial archive */ + fclose(arc); +#if !_MTS + if (kludge) /* kludge to update timestamp */ + setstamp(arcname, olddate, oldtime); +#endif + } + if (chg) { /* if things have changed */ + fclose(new); /* close the new copy */ + if (arc) { /* if we had an original archive */ +#if _MTS + { + fortran VOID permit(); + char what[FNLEN+2]; +/* copy permissions */ char who[FNLEN+6]; +/* of old archive to */ int how,whotyp,wholen,info; +/* new copy... */ strcpy(what, newname); + strcat(what," "); + whotyp=9; + sprintf(who,"like %s",arcname); + wholen=strlen(who); + info=0; + permit(what,&how,&whotyp,&wholen,who,&info); + } +#endif + if (keepbak) { /* if a backup is wanted */ + unlink(bakname); /* erase any old copies */ + if (move(arcname, bakname)) + arcdie("Cannot rename %s to %s", arcname, bakname); + printf("Keeping backup archive: %s\n", bakname); + } else if (unlink(arcname)) + arcdie("Cannot delete old archive: %s", arcname); + } + if (move(newname, arcname)) + arcdie("Cannot move %s to %s", newname, arcname); +#if !_MTS + setstamp(arcname, arcdate, arctime); +#endif + } +} + +/* + * CRC computation logic + * + * The logic for this method of calculating the CRC 16 bit polynomial is taken + * from an article by David Schwaderer in the April 1985 issue of PC Tech + * Journal. + */ + +static short crctab[] = /* CRC lookup table */ +{ + 0x0000, 0xC0C1, 0xC181, 0x0140, 0xC301, 0x03C0, 0x0280, 0xC241, + 0xC601, 0x06C0, 0x0780, 0xC741, 0x0500, 0xC5C1, 0xC481, 0x0440, + 0xCC01, 0x0CC0, 0x0D80, 0xCD41, 0x0F00, 0xCFC1, 0xCE81, 0x0E40, + 0x0A00, 0xCAC1, 0xCB81, 0x0B40, 0xC901, 0x09C0, 0x0880, 0xC841, + 0xD801, 0x18C0, 0x1980, 0xD941, 0x1B00, 0xDBC1, 0xDA81, 0x1A40, + 0x1E00, 0xDEC1, 0xDF81, 0x1F40, 0xDD01, 0x1DC0, 0x1C80, 0xDC41, + 0x1400, 0xD4C1, 0xD581, 0x1540, 0xD701, 0x17C0, 0x1680, 0xD641, + 0xD201, 0x12C0, 0x1380, 0xD341, 0x1100, 0xD1C1, 0xD081, 0x1040, + 0xF001, 0x30C0, 0x3180, 0xF141, 0x3300, 0xF3C1, 0xF281, 0x3240, + 0x3600, 0xF6C1, 0xF781, 0x3740, 0xF501, 0x35C0, 0x3480, 0xF441, + 0x3C00, 0xFCC1, 0xFD81, 0x3D40, 0xFF01, 0x3FC0, 0x3E80, 0xFE41, + 0xFA01, 0x3AC0, 0x3B80, 0xFB41, 0x3900, 0xF9C1, 0xF881, 0x3840, + 0x2800, 0xE8C1, 0xE981, 0x2940, 0xEB01, 0x2BC0, 0x2A80, 0xEA41, + 0xEE01, 0x2EC0, 0x2F80, 0xEF41, 0x2D00, 0xEDC1, 0xEC81, 0x2C40, + 0xE401, 0x24C0, 0x2580, 0xE541, 0x2700, 0xE7C1, 0xE681, 0x2640, + 0x2200, 0xE2C1, 0xE381, 0x2340, 0xE101, 0x21C0, 0x2080, 0xE041, + 0xA001, 0x60C0, 0x6180, 0xA141, 0x6300, 0xA3C1, 0xA281, 0x6240, + 0x6600, 0xA6C1, 0xA781, 0x6740, 0xA501, 0x65C0, 0x6480, 0xA441, + 0x6C00, 0xACC1, 0xAD81, 0x6D40, 0xAF01, 0x6FC0, 0x6E80, 0xAE41, + 0xAA01, 0x6AC0, 0x6B80, 0xAB41, 0x6900, 0xA9C1, 0xA881, 0x6840, + 0x7800, 0xB8C1, 0xB981, 0x7940, 0xBB01, 0x7BC0, 0x7A80, 0xBA41, + 0xBE01, 0x7EC0, 0x7F80, 0xBF41, 0x7D00, 0xBDC1, 0xBC81, 0x7C40, + 0xB401, 0x74C0, 0x7580, 0xB541, 0x7700, 0xB7C1, 0xB681, 0x7640, + 0x7200, 0xB2C1, 0xB381, 0x7340, 0xB101, 0x71C0, 0x7080, 0xB041, + 0x5000, 0x90C1, 0x9181, 0x5140, 0x9301, 0x53C0, 0x5280, 0x9241, + 0x9601, 0x56C0, 0x5780, 0x9741, 0x5500, 0x95C1, 0x9481, 0x5440, + 0x9C01, 0x5CC0, 0x5D80, 0x9D41, 0x5F00, 0x9FC1, 0x9E81, 0x5E40, + 0x5A00, 0x9AC1, 0x9B81, 0x5B40, 0x9901, 0x59C0, 0x5880, 0x9841, + 0x8801, 0x48C0, 0x4980, 0x8941, 0x4B00, 0x8BC1, 0x8A81, 0x4A40, + 0x4E00, 0x8EC1, 0x8F81, 0x4F40, 0x8D01, 0x4DC0, 0x4C80, 0x8C41, + 0x4400, 0x84C1, 0x8581, 0x4540, 0x8701, 0x47C0, 0x4680, 0x8641, + 0x8201, 0x42C0, 0x4380, 0x8341, 0x4100, 0x81C1, 0x8081, 0x4040 +}; + +/* + * Update a CRC check on the given buffer. + */ + +int +crcbuf(crc, len, buf) + register int crc; /* running CRC value */ + register u_int len; + register u_char *buf; +{ + register u_int i; + + for (i=0; i> 8) & 0xff) ^ crctab[(crc ^ *buf++) & 0xff]; + + return (crc); +} diff --git a/pool/shard002/C/0058416_cc-hostname-entry.c b/pool/shard002/C/0058416_cc-hostname-entry.c new file mode 100644 index 0000000000000000000000000000000000000000..f10df4f1f4e90c01a0b17d3a7f3dbc1c6ee94607 --- /dev/null +++ b/pool/shard002/C/0058416_cc-hostname-entry.c @@ -0,0 +1,299 @@ +/* -*- mode: C; c-file-style: "gnu"; indent-tabs-mode: nil; -*- + * + * Copyright (C) 2013 Intel, Inc + * Copyright (C) 2011,2012 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + * + */ + + +#include "cc-hostname-entry.h" +#include "hostname-helper.h" + +#include + + +G_DEFINE_TYPE (CcHostnameEntry, cc_hostname_entry, GTK_TYPE_ENTRY) + +#define HOSTNAME_ENTRY_PRIVATE(o) \ + (G_TYPE_INSTANCE_GET_PRIVATE ((o), CC_TYPE_HOSTNAME_ENTRY, CcHostnameEntryPrivate)) + +#define SET_HOSTNAME_TIMEOUT 1 + +struct _CcHostnameEntryPrivate +{ + GDBusProxy *hostnamed_proxy; + guint set_hostname_timeout_source_id; +}; + +static void +cc_hostname_entry_set_hostname (CcHostnameEntry *self) +{ + char *hostname; + GVariant *variant; + GError *error = NULL; + const gchar *text; + + text = gtk_entry_get_text (GTK_ENTRY (self)); + + g_debug ("Setting PrettyHostname to '%s'", text); + variant = g_dbus_proxy_call_sync (self->priv->hostnamed_proxy, + "SetPrettyHostname", + g_variant_new ("(sb)", text, FALSE), + G_DBUS_CALL_FLAGS_NONE, + -1, NULL, &error); + if (variant == NULL) + { + g_warning ("Could not set PrettyHostname: %s", error->message); + g_error_free (error); + error = NULL; + } + else + { + g_variant_unref (variant); + } + + /* Set the static hostname */ + hostname = pretty_hostname_to_static (text, FALSE); + g_assert (hostname); + + g_debug ("Setting StaticHostname to '%s'", hostname); + variant = g_dbus_proxy_call_sync (self->priv->hostnamed_proxy, + "SetStaticHostname", + g_variant_new ("(sb)", hostname, FALSE), + G_DBUS_CALL_FLAGS_NONE, + -1, NULL, &error); + if (variant == NULL) + { + g_warning ("Could not set StaticHostname: %s", error->message); + g_error_free (error); + } + else + { + g_variant_unref (variant); + } + g_free (hostname); +} + +static char * +get_hostname_property (CcHostnameEntry *self, + const char *property) +{ + CcHostnameEntryPrivate *priv = self->priv; + GVariant *variant; + char *str; + + if (!priv->hostnamed_proxy) + return g_strdup (""); + + variant = g_dbus_proxy_get_cached_property (priv->hostnamed_proxy, + property); + if (!variant) + { + GError *error = NULL; + GVariant *inner; + + /* Work around systemd-hostname not sending us back + * the property value when changing values */ + variant = g_dbus_proxy_call_sync (priv->hostnamed_proxy, + "org.freedesktop.DBus.Properties.Get", + g_variant_new ("(ss)", "org.freedesktop.hostname1", property), + G_DBUS_CALL_FLAGS_NONE, + -1, + NULL, + &error); + if (variant == NULL) + { + g_warning ("Failed to get property '%s': %s", property, error->message); + g_error_free (error); + return NULL; + } + + g_variant_get (variant, "(v)", &inner); + str = g_variant_dup_string (inner, NULL); + g_variant_unref (variant); + } + else + { + str = g_variant_dup_string (variant, NULL); + g_variant_unref (variant); + } + + return str; +} + +static char * +cc_hostname_entry_get_display_hostname (CcHostnameEntry *self) +{ + char *str; + + str = get_hostname_property (self, "PrettyHostname"); + + /* Empty strings means that we need to fallback */ + if (str != NULL && + *str == '\0') + { + g_free (str); + str = get_hostname_property (self, "Hostname"); + } + + return str; +} + +static gboolean +set_hostname_timeout (CcHostnameEntry *self) +{ + self->priv->set_hostname_timeout_source_id = 0; + + cc_hostname_entry_set_hostname (self); + + return FALSE; +} + +static void +remove_hostname_timeout (CcHostnameEntry *entry) +{ + CcHostnameEntryPrivate *priv = entry->priv; + + if (priv->set_hostname_timeout_source_id) + g_source_remove (priv->set_hostname_timeout_source_id); + + priv->set_hostname_timeout_source_id = 0; +} + +static void +reset_hostname_timeout (CcHostnameEntry *entry) +{ + remove_hostname_timeout (entry); + + entry->priv->set_hostname_timeout_source_id = g_timeout_add_seconds (SET_HOSTNAME_TIMEOUT, + (GSourceFunc) set_hostname_timeout, + entry); +} + +static void +text_changed_cb (CcHostnameEntry *entry) +{ + reset_hostname_timeout (entry); +} + +static void +cc_hostname_entry_dispose (GObject *object) +{ + CcHostnameEntry *entry = CC_HOSTNAME_ENTRY (object); + CcHostnameEntryPrivate *priv = entry->priv; + + if (priv->set_hostname_timeout_source_id) + { + remove_hostname_timeout (entry); + set_hostname_timeout (entry); + } + + g_clear_object (&priv->hostnamed_proxy); + + G_OBJECT_CLASS (cc_hostname_entry_parent_class)->dispose (object); +} + +static void +cc_hostname_entry_constructed (GObject *self) +{ + CcHostnameEntryPrivate *priv = CC_HOSTNAME_ENTRY (self)->priv; + GError *error = NULL; + GPermission *permission; + char *str; + + permission = polkit_permission_new_sync ("org.freedesktop.hostname1.set-static-hostname", + NULL, NULL, NULL); + + /* Is hostnamed installed? */ + if (permission == NULL) + { + g_debug ("Will not show hostname, hostnamed not installed"); + + gtk_widget_set_sensitive (GTK_WIDGET (self), FALSE); + + return; + } + + if (g_permission_get_allowed (permission)) + gtk_widget_set_sensitive (GTK_WIDGET (self), TRUE); + else + { + g_debug ("Not allowed to change the hostname"); + gtk_widget_set_sensitive (GTK_WIDGET (self), FALSE); + } + + gtk_widget_set_sensitive (GTK_WIDGET (self), + g_permission_get_allowed (permission)); + + priv->hostnamed_proxy = g_dbus_proxy_new_for_bus_sync (G_BUS_TYPE_SYSTEM, + G_DBUS_PROXY_FLAGS_NONE, + NULL, + "org.freedesktop.hostname1", + "/org/freedesktop/hostname1", + "org.freedesktop.hostname1", + NULL, + &error); + + /* This could only happen if the policy file was installed + * but not hostnamed, which points to a system bug */ + if (priv->hostnamed_proxy == NULL) + { + g_debug ("Couldn't get hostnamed to start, bailing: %s", error->message); + g_error_free (error); + return; + } + + str = cc_hostname_entry_get_display_hostname (CC_HOSTNAME_ENTRY (self)); + + if (str != NULL) + gtk_entry_set_text (GTK_ENTRY (self), str); + else + gtk_entry_set_text (GTK_ENTRY (self), ""); + g_free (str); + + g_signal_connect (G_OBJECT (self), "changed", G_CALLBACK (text_changed_cb), + self); +} + +static void +cc_hostname_entry_class_init (CcHostnameEntryClass *klass) +{ + GObjectClass *object_class = G_OBJECT_CLASS (klass); + + g_type_class_add_private (klass, sizeof (CcHostnameEntryPrivate)); + + object_class->constructed = cc_hostname_entry_constructed; + object_class->dispose = cc_hostname_entry_dispose; +} + +static void +cc_hostname_entry_init (CcHostnameEntry *self) +{ + self->priv = HOSTNAME_ENTRY_PRIVATE (self); +} + +CcHostnameEntry * +cc_hostname_entry_new (void) +{ + return g_object_new (CC_TYPE_HOSTNAME_ENTRY, NULL); +} + +gchar* +cc_hostname_entry_get_hostname (CcHostnameEntry *entry) +{ + return get_hostname_property (entry, "Hostname"); +} diff --git a/pool/shard002/C/0058447_readpvpheader.c b/pool/shard002/C/0058447_readpvpheader.c new file mode 100644 index 0000000000000000000000000000000000000000..589e34d0d1e0cc71fbb64ede240963495e1314f8 --- /dev/null +++ b/pool/shard002/C/0058447_readpvpheader.c @@ -0,0 +1,176 @@ +#include +#include +#include +#include + +/* + * readheader.c, a C program for printing the header of a .pvp file + * in human-readable form. + * Usage: ./readheader file1 file2 file3 etc + */ + +#define PARSE_SUCCESS 0 +#define PARSE_FAILURE 1 +#define PARSE_CANTOPEN 1 +#define PARSE_NOHEADER 2 +#define PARSE_BADHEADERSIZE 3 +#define PARSE_BADNUMPARAMS 4 +#define PARSE_BADFILETYPE 5 +#define PARSE_NOMEM 12 + +#define INDEX_HEADER_SIZE 0 +#define INDEX_NUM_PARAMS 1 +#define INDEX_FILE_TYPE 2 +#define INDEX_NX 3 +#define INDEX_NY 4 +#define INDEX_NF 5 +#define INDEX_NUM_RECORDS 6 +#define INDEX_RECORD_SIZE 7 +#define INDEX_DATA_SIZE 8 +#define INDEX_DATA_TYPE 9 +#define INDEX_NX_PROCS 10 +#define INDEX_NY_PROCS 11 +#define INDEX_NX_GLOBAL 12 +#define INDEX_NY_GLOBAL 13 +#define INDEX_KX0 14 +#define INDEX_KY0 15 +#define INDEX_NB 16 +#define INDEX_NBANDS 17 +#define INDEX_TIME 18 + +#define INDEX_WGT_NXP 0 +#define INDEX_WGT_NYP 1 +#define INDEX_WGT_NFP 2 +#define INDEX_WGT_MIN 3 +#define INDEX_WGT_MAX 4 +#define INDEX_WGT_NUMPATCHES 5 + +#define PVP_FILE_TYPE 1 +#define PVP_ACT_FILE_TYPE 2 +#define PVP_WGT_FILE_TYPE 3 +#define PVP_NONSPIKING_ACT_FILE_TYPE 4 +#define PVP_KERNEL_FILE_TYPE 5 +#define PVP_ACT_SPARSEVALUES_FILE_TYPE 6 + +int parseheader(FILE * fid); + +int main(int argc, char * argv[]) +{ + int status = PARSE_SUCCESS; + if (argc==1 || (argc==2 && (!strcmp(argv[1],"--help")||!strcmp(argv[1],"-h")))) + { + printf("Usage: %s filename\nThis function parses the header of filename assuming filename is a pvp file.\n", argv[0]); + return status; + } + int arg; + for (arg=1; arg + */ + +#include +#include +#include +#include + +#include "wm8804.h" + +static int wm8804_i2c_probe(struct i2c_client *i2c, + const struct i2c_device_id *id) +{ + struct regmap *regmap; + + regmap = devm_regmap_init_i2c(i2c, &wm8804_regmap_config); + if (IS_ERR(regmap)) + return PTR_ERR(regmap); + + return wm8804_probe(&i2c->dev, regmap); +} + +static int wm8804_i2c_remove(struct i2c_client *i2c) +{ + wm8804_remove(&i2c->dev); + return 0; +} + +static const struct i2c_device_id wm8804_i2c_id[] = { + { "wm8804", 0 }, + { } +}; +MODULE_DEVICE_TABLE(i2c, wm8804_i2c_id); + +#if defined(CONFIG_OF) +static const struct of_device_id wm8804_of_match[] = { + { .compatible = "wlf,wm8804", }, + { } +}; +MODULE_DEVICE_TABLE(of, wm8804_of_match); +#endif + +#ifdef CONFIG_ACPI +static const struct acpi_device_id wm8804_acpi_match[] = { + { "1AEC8804", 0 }, /* Wolfson PCI ID + part ID */ + { "10138804", 0 }, /* Cirrus Logic PCI ID + part ID */ + { }, +}; +MODULE_DEVICE_TABLE(acpi, wm8804_acpi_match); +#endif + +static struct i2c_driver wm8804_i2c_driver = { + .driver = { + .name = "wm8804", + .pm = &wm8804_pm, + .of_match_table = of_match_ptr(wm8804_of_match), + .acpi_match_table = ACPI_PTR(wm8804_acpi_match), + }, + .probe = wm8804_i2c_probe, + .remove = wm8804_i2c_remove, + .id_table = wm8804_i2c_id +}; + +module_i2c_driver(wm8804_i2c_driver); + +MODULE_DESCRIPTION("ASoC WM8804 driver - I2C"); +MODULE_AUTHOR("Charles Keepax "); +MODULE_LICENSE("GPL"); diff --git a/pool/shard002/C/0058461_videodisplay.c b/pool/shard002/C/0058461_videodisplay.c new file mode 100644 index 0000000000000000000000000000000000000000..b1ac2c9bbbac29fddf460658904ee3dcbf5ec62f --- /dev/null +++ b/pool/shard002/C/0058461_videodisplay.c @@ -0,0 +1,138 @@ +/* + * Copyright (c) 2010-2019 Belledonne Communications SARL. + * + * This file is part of mediastreamer2. + * + * 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 "mediastreamer2/mediastream.h" +#include "mediastreamer2/msvideoout.h" +#include "mediastreamer2/msv4l.h" + +static int stopped=FALSE; + +static void stop(int signum){ + stopped=TRUE; +} + +int main(int argc, char *argv[]){ + VideoStream *vs; + MSWebCam *cam; + MSVideoSize vsize; + MSFactory* factory; + int i; + + vsize.width=MS_VIDEO_SIZE_CIF_W; + vsize.height=MS_VIDEO_SIZE_CIF_H; + + ortp_init(); + ortp_set_log_level_mask(ORTP_LOG_DOMAIN, ORTP_MESSAGE|ORTP_WARNING|ORTP_ERROR|ORTP_FATAL); + //ms_init(); + + factory = ms_factory_new(); + ms_factory_init_voip(factory); + ms_factory_init_plugins(factory); + + cam=ms_web_cam_manager_get_cam(ms_factory_get_web_cam_manager(factory),"StaticImage: Static picture"); + //cam=ms_web_cam_manager_get_cam(ms_web_cam_manager_get(),"StaticImage: Static picture"); + + signal(SIGINT,stop); + /* this is to test the sequence start/stop */ + for(i=0;i<1;++i){ + int n; + vs=video_preview_new(factory); + + /*video_preview_set_display_filter_name(vs,"MSVideoOut");*/ + video_preview_set_size(vs,vsize); + video_preview_start(vs, cam); + + for(n=0;n<60000 && !stopped;++n){ +#ifdef _WIN32 + MSG msg; + Sleep(100); + while (PeekMessage(&msg, NULL, 0, 0,1)){ + TranslateMessage(&msg); + DispatchMessage(&msg); + } +#else + struct timespec ts; + ts.tv_sec=0; + ts.tv_nsec=10000000; + nanosleep(&ts,NULL); + + if (vs) video_stream_iterate(vs); +#endif + +/* test code */ + if (n==400) + { + ms_ticker_detach (vs->ms.sessions.ticker, vs->source); + + vs->tee = ms_factory_create_filter(factory, MS_TEE_ID); + + ms_filter_unlink(vs->pixconv,0, vs->output2,0); + + ms_filter_link(vs->pixconv,0,vs->tee,0); + ms_filter_link(vs->tee,0,vs->output2,0); + ms_filter_link(vs->tee,1,vs->output2,1); + + //ms_filter_unlink(vs->tee,0,vs->output,0); + ms_ticker_attach (vs->ms.sessions.ticker, vs->source); + + } + if (n==500) + { + int corner=1; + ms_filter_call_method(vs->output2,MS_VIDEO_DISPLAY_SET_LOCAL_VIEW_MODE,&corner); + } + if (n==600) + { + int corner=2; + ms_filter_call_method(vs->output2,MS_VIDEO_DISPLAY_SET_LOCAL_VIEW_MODE,&corner); + } + if (n==700) + { + int corner=3; + ms_filter_call_method(vs->output2,MS_VIDEO_DISPLAY_SET_LOCAL_VIEW_MODE,&corner); + } + if (n==800) + { + int corner=-1; + ms_filter_call_method(vs->output2,MS_VIDEO_DISPLAY_SET_LOCAL_VIEW_MODE,&corner); + } + if (n==900) + { + ms_ticker_detach (vs->ms.sessions.ticker, vs->source); + + ms_filter_unlink(vs->pixconv,0,vs->tee,0); + ms_filter_unlink(vs->tee,0,vs->output2,0); + ms_filter_unlink(vs->tee,1,vs->output2,1); + ms_filter_destroy(vs->tee); + vs->tee=NULL; + + ms_filter_link(vs->pixconv,0, vs->output2,0); + + + ms_ticker_attach (vs->ms.sessions.ticker, vs->source); + } + } + video_preview_stop(vs); + } + return 0; +} + diff --git a/pool/shard002/C/0058463_reader_modified.c b/pool/shard002/C/0058463_reader_modified.c new file mode 100644 index 0000000000000000000000000000000000000000..7fb3ed07d17c8e278e89f9180e88c3ef9317139c --- /dev/null +++ b/pool/shard002/C/0058463_reader_modified.c @@ -0,0 +1,98 @@ +#include +#include +#include +#include +#include +#include +#include +#define MAX_BUF 1024 + +#include "../base/s3fnet-definitions.h" +// Above #include added by Vlad in order to have a single point (s3fnet-definitions.h) that need to be modified + +//This is just a directory to where you want the data to be stored +const char *PATH_TO_DATA = PATH_TO_READER_DATA; + +int main() +{ + int fd; + char buf[MAX_BUF]; + char hostname[MAX_BUF]; + char debug[MAX_BUF]; + char command[MAX_BUF]; + gethostname(hostname,MAX_BUF); + char myfifo[MAX_BUF]; + sprintf(myfifo, "/tmp/%s", hostname); + mkfifo(myfifo, 0666); + /* open, read, and display the message from the FIFO */ + fd = open(myfifo, O_RDWR | O_NONBLOCK ); + struct pollfd ufds; + int result; + int rv; + int pid; + int i = 0; + + struct epoll_event event; + struct epoll_event *events; + int efd, n, s; + + efd = epoll_create1 (0); + + // allocate events array + events = calloc(64, sizeof event); + + // register read end of pipe using edge-triggered mode with ONESHOT. + event.data.fd = fd; + event.events = EPOLLIN | EPOLLET | EPOLLONESHOT; + + + printf("Starting debug\n"); + sprintf(debug, "echo Starting Debug for %s > %s/%s", hostname, PATH_TO_DATA, hostname); + system(debug); + + // wait on read-end becoming readable. + //printf("PARENT: waiting on pipe\n"); + //sprintf(debug, "echo waiting on pipe %s >> %s/%s", hostname, PATH_TO_DATA, hostname); + //system(debug); + + + + //ufds.fd = fd; + //ufds.events = POLLIN; + while (1) { + s = epoll_ctl (efd, EPOLL_CTL_ADD, fd, &event); + rv = epoll_wait (efd, events, 64, -1); + //rv = poll(&ufds, 1, -1); + if (rv == -1) { + perror("epoll error:"); // error occurred in poll() + } else if (rv == 0) { + printf("rv is 0\n"); + } else { + // check for events on s1: + //if (ufds.revents & POLLIN) { + result = read(fd, buf, MAX_BUF); // receive normal data + if (strcmp(buf, "exit") == 0) { + printf("Exiting..\n"); + break; + } + pid = fork(); + if (pid == 0) { //in child + printf("Running Command %s\n", buf); + for(i = 0; i < MAX_BUF; i++) + debug[i] = '\0'; + + sprintf(debug, "echo Running Command %s >> %s/%s", buf, PATH_TO_DATA, hostname); + system(debug); + + sprintf(command, "%s >> %s/%s 2>&1", buf, PATH_TO_DATA, hostname); + system(command); + return 0; + } + //} + } + + } + close(fd); + + return 0; +} diff --git a/pool/shard002/C/0058475_selsort.c b/pool/shard002/C/0058475_selsort.c new file mode 100644 index 0000000000000000000000000000000000000000..45c75d3d94a59dc8b2ba5e57b6755ac353d82549 --- /dev/null +++ b/pool/shard002/C/0058475_selsort.c @@ -0,0 +1,81 @@ +#include +#include +#include +#include +#include + +#define MAX 100 +#define TEST_LOOP_CNT 100 + +struct CElem { + int key; + /* ............. + Някакви данни + ............. */ +}; + +void swap(struct CElem *x1, struct CElem *x2) +{ struct CElem tmp = *x1; *x1 = *x2; *x2 = tmp; } + +void init(struct CElem m[], unsigned n) /* Запълва масива със случайни цели числа */ +{ unsigned i; + srand(time(NULL)); + for (i = 0; i < n; i++) + m[i].key = rand() % n; +} + +void straightSelection(struct CElem m[], unsigned n) +{ unsigned i, j; + for (i = 0; i < n-1; i++) + for (j = i+1; j <= n; j++) + if (m[i].key > m[j].key) + swap(m+i, m+j); +} + +void print(struct CElem m[], unsigned n) /* Извежда ключовете на масива на екрана */ +{ unsigned i; + for (i = 0; i < n; i++) + printf("%8d", m[i].key); +} + +void check(const struct CElem m[], + const struct CElem saveM[], + unsigned n) +{ unsigned i, j; + char *found; /* третира се като масив от булев тип */ + + /* 1. Проверка за наредба във възходящ ред */ + for (i = 0; i < n-1; i++) + assert(m[i].key <= m[i + 1].key); + + /* 2. Проверка за пермутация на изходните елементи */ + found = (char *) calloc(n + 1, sizeof(*found)); + for (i = 0; i < n; i++) { + for (j = 0; j < n; j++) + if (!found[j] && m[i].key == saveM[j].key) { + found[j] = 1; + break; + } + + assert(j < n); /* Пропада, ако не е намерен съответен */ + } + + free(found); +} + +int main(void) +{ struct CElem m[MAX], saveM[MAX]; + unsigned loopInd; + for (loopInd = 1; loopInd <= TEST_LOOP_CNT; loopInd++) { + printf("\n<<<<< Тест %u >>>>>\n", loopInd); + init(m, MAX); + memcpy(saveM, m, sizeof(m)); /* Запазва се копие на масива */ + printf("Масивът преди сортирането:\n"); + print(m, MAX); + straightSelection(m, MAX); + printf("Масивът след сортирането:\n"); + print(m, MAX); + check(m, saveM, MAX); + } + return 0; +} \ No newline at end of file diff --git a/pool/shard002/C/0058489_surge.c b/pool/shard002/C/0058489_surge.c new file mode 100644 index 0000000000000000000000000000000000000000..ed6ae244ffd8a171477595cffcf3592946692d0a --- /dev/null +++ b/pool/shard002/C/0058489_surge.c @@ -0,0 +1,232 @@ +/* -*- Mode: C; tab-width:4 -*- */ +/* ex: set ts=4 shiftwidth=4 softtabstop=4 cindent: */ +/* tab:4 + * "Copyright (c) 2000-2003 The Regents of the University of California. + * All rights reserved. + * + * Permission to use, copy, modify, and distribute this software and its + * documentation for any purpose, without fee, and without written agreement is + * hereby granted, provided that the above copyright notice, the following + * two paragraphs and the author appear in all copies of this software. + * + * IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR + * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT + * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF + * CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES, + * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY + * AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS + * ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO + * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS." + * + * Copyright (c) 2002-2003 Intel Corporation + * All rights reserved. + * + * This file is distributed under the terms in the attached INTEL-LICENSE + * file. If you do not find these files, copies can be found by writing to + * Intel Research Berkeley, 2150 Shattuck Avenue, Suite 1300, Berkeley, CA, + * 94704. Attention: Intel License Inquiry. + */ + +/** + * @brief Surge application + * @author Ram Kumar {ram@ee.ucla.edu} + */ + +/** + * Periodically samples sensor data and sends it to the tree routing module + * MODULE DEPENDENCIES - TREE_ROUTING, PHOTOTEMP_SENSOR + */ + + +#include +#include +#include "surge.h" +#include +#include + +#ifndef SOS_SURGE_DEBUG +#undef DEBUG +#define DEBUG(...) +#endif + +#ifdef TEST_SURGE +// This memory is used by Avrora to collect Surge statistic +static uint16_t data_node_id; +#endif + +//------------------------------------------------------------- +// MODULE STATE +//------------------------------------------------------------- +/** + * @struct surge_state_t + * @brief State of the Surge module + * @note Size is 11 bytes + */ +typedef struct { + func_cb_ptr get_hdr_size; //! Function pointer to get the size of the tree routing header + int16_t timer_ticks; //! Count of number of timer ticks + uint32_t seq_no; //! Sequence number of the surge message + sos_pid_t dest_pid; //! The destination module that will receive the message + SurgeMsg* smsg; //! Surge Message pointer +} surge_state_t; + + + +//------------------------------------------------------------- +// MODULE TIMERS +//------------------------------------------------------------- +enum + { + SURGE_TIMER_TID = 0, + SURGE_BACKOFF_TID = 1, + }; + + +//------------------------------------------------------------- +// STATIC FUNCTIONS +//------------------------------------------------------------- +int8_t surge_module_handler(void *state, Message *msg); + + +//------------------------------------------------------------- +// MODULE HEADER +//------------------------------------------------------------- +static const mod_header_t mod_header SOS_MODULE_HEADER = { + .mod_id = SURGE_MOD_PID, + .state_size = sizeof(surge_state_t), + .num_sub_func = 1, + .num_prov_func = 0, + .platform_type = HW_TYPE /* or PLATFORM_ANY */, + .processor_type = MCU_TYPE, + .code_id = ehtons(SURGE_MOD_PID), + .module_handler = surge_module_handler, + .funct = { + [0] = {error_8, "Cvv0", TREE_ROUTING_PID, MOD_GET_HDR_SIZE_FID}, + }, +}; + + +//------------------------------------------------------------- +// MODULE IMPLEMENTATION +//------------------------------------------------------------- +int8_t surge_module_handler(void *state, Message *msg) +{ + surge_state_t *s = (surge_state_t*)state; + + switch (msg->type){ + + //! First message from the SOS kernel + case MSG_INIT: + { + s->seq_no = 0; + sys_timer_start(SURGE_BACKOFF_TID, sys_rand() % 1024L, TIMER_ONE_SHOT); + s->dest_pid = SURGE_MOD_PID; + break; + } + + //! Timer timeout message + case MSG_TIMER_TIMEOUT: + { + MsgParam *param = (MsgParam*) (msg->data); + switch (param->byte){ + case SURGE_TIMER_TID: + { + s->timer_ticks++; + if (s->timer_ticks % TIMER_GETADC_COUNT == 0){ + if(sys_sensor_get_data(MTS310_PHOTO_SID) < 0){ + LED_DBG(LED_RED_TOGGLE); + sys_post_value(SURGE_MOD_PID, MSG_DATA_READY, 0x00ffff00, 0); + } + } + return SOS_OK; + } + case SURGE_BACKOFF_TID: + { + sys_timer_start(SURGE_TIMER_TID, INITIAL_TIMER_RATE, TIMER_REPEAT); + return SOS_OK; + } + default: return -EINVAL; + } + return SOS_OK; + } + + // Requested sensor data ready + case MSG_DATA_READY: + { + MsgParam* param = (MsgParam*) (msg->data); + int8_t hdr_size; + uint8_t *pkt; + + LED_DBG(LED_YELLOW_TOGGLE); + hdr_size = SOS_CALL(s->get_hdr_size, get_hdr_size_proto); + if( hdr_size < 0 ) { return SOS_OK; } + pkt = (uint8_t*)sys_malloc(hdr_size + sizeof(SurgeMsg)); + if (pkt == NULL) break; + s->smsg = (SurgeMsg*)(pkt + hdr_size); + s->smsg->type = SURGE_TYPE_SENSORREADING; + s->smsg->reading = ehtons(param->word); + s->smsg->seq_no = ehtonl(s->seq_no); + s->smsg->originaddr = ehtons(sys_id()); + LED_DBG(LED_YELLOW_TOGGLE); + DEBUG(" Send Surge PKT addr = %d, seq = %d, val = %d\n", + s->smsg->originaddr, + s->smsg->seq_no, + s->smsg->reading); + s->seq_no++; + sys_post(TREE_ROUTING_PID, MSG_SEND_PACKET, hdr_size + sizeof(SurgeMsg), (void*)pkt, SOS_MSG_RELEASE); + break; + } + + // Message from the tree routing module upon delivery of the data at the base-station + case MSG_TR_DATA_PKT: + { + uint8_t hdr_size; + SurgeMsg *smsg; + hdr_size = SOS_CALL(s->get_hdr_size, get_hdr_size_proto); + smsg = (SurgeMsg*)(((uint8_t*)(msg->data)) + hdr_size); + DEBUG(" Recv Surge PKT addr = %d, seq = %d, val = %d \n", + entohs(smsg->originaddr), + entohl(smsg->seq_no), + entohs(smsg->reading)); + if (sys_id() == SURGE_BASE_STATION_ADDRESS){ + uint8_t *payload; + uint8_t msg_len; + msg_len = msg->len; + payload = sys_msg_take_data(msg); +#ifdef TEST_SURGE + data_node_id = entohs(smsg->originaddr); +#endif + sys_post_uart(SURGE_MOD_PID, + msg->type, + msg_len, + payload, + SOS_MSG_RELEASE, + BCAST_ADDRESS); + LED_DBG(LED_GREEN_TOGGLE); + return SOS_OK; + } + break; + } + + //! Last message from SOS kernel before the module is kicked out + case MSG_FINAL: + { + break; + } + + default: + return -EINVAL; + } + + return SOS_OK; +} + + +#ifndef _MODULE_ +mod_header_ptr surge_get_header() +{ + return sos_get_header_address(mod_header); +} +#endif diff --git a/pool/shard002/C/0058494_sys_sdl_img_bmp.c b/pool/shard002/C/0058494_sys_sdl_img_bmp.c new file mode 100644 index 0000000000000000000000000000000000000000..7cd0e04c35b47f556e37a708ad1279c9a65b5d6c --- /dev/null +++ b/pool/shard002/C/0058494_sys_sdl_img_bmp.c @@ -0,0 +1,66 @@ +/* +* libtcod 1.5.0 +* Copyright (c) 2008,2009,2010 Jice +* 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. +* * The name of Jice may not be used to endorse or promote products +* derived from this software without specific prior written permission. +* +* THIS SOFTWARE IS PROVIDED BY Jice ``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 Jice 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 "libtcod.h" +#include "libtcod_int.h" + +bool TCOD_sys_check_bmp(const char *filename) { + static uint8 magic_number[]={0x42, 0x4d}; + return TCOD_sys_check_magic_number(filename,sizeof(magic_number),magic_number); +} + +SDL_Surface *TCOD_sys_read_bmp(const char *filename) { + SDL_Surface *ret=SDL_LoadBMP(filename); + if( !ret ) TCOD_fatal("SDL : %s",SDL_GetError()); + // convert low color images to 24 bits + if ( ret->format->BytesPerPixel != 3 ) { + Uint32 rmask,gmask,bmask; + SDL_Surface * tmp; + if ( SDL_BYTEORDER == SDL_LIL_ENDIAN ) { + rmask=0xFF0000; + gmask=0x00FF00; + bmask=0x0000FF; + } else { + rmask=0x0000FF; + gmask=0x00FF00; + bmask=0xFF0000; + } + tmp=SDL_CreateRGBSurface(SDL_SWSURFACE,ret->w,ret->h,24, rmask, gmask, bmask, 0); + SDL_BlitSurface(ret,NULL,tmp,NULL); + SDL_FreeSurface(ret); + ret=tmp; + } + + return ret; +} + +void TCOD_sys_write_bmp(const SDL_Surface *surf, const char *filename) { + SDL_SaveBMP((SDL_Surface *)surf,filename); +} + + diff --git a/pool/shard002/C/0058501_gwwvmenubar.c b/pool/shard002/C/0058501_gwwvmenubar.c new file mode 100644 index 0000000000000000000000000000000000000000..aac561b889ee17647c31a959d0e6e7e6c49a330d --- /dev/null +++ b/pool/shard002/C/0058501_gwwvmenubar.c @@ -0,0 +1,257 @@ +#include +#include "gwwvmenubar.h" + +#define BORDER_SPACING 0 /* Must match value in gtkmenubar.c */ + +/* This implements a "variable-sized" menubar */ +/* If the window shrinks below the size needed to display all the components */ +/* then it will display as many components as it can, and then add a final */ +/* arrow which will be attached to a pulldown menu containing any undisplayed */ +/* components. */ + +static GtkWidgetClass *parent_class = NULL; + +static GtkShadowType get_shadow_type (GtkMenuBar *menubar) { + GtkShadowType shadow_type = GTK_SHADOW_OUT; + + gtk_widget_style_get (GTK_WIDGET (menubar), + "shadow_type", &shadow_type, + NULL); + + return shadow_type; +} + +static void gww_vmenu_bar_size_request (GtkWidget *widget, + GtkRequisition *requisition) { + GwwVMenuBar *menu_bar; + GtkMenuShell *menu_shell; + GtkRequisition child_requisition; + gint ipadding; + GtkWidget *child; + GList *children; + + g_return_if_fail (GWW_IS_VMENU_BAR (widget)); + g_return_if_fail (requisition != NULL); + + requisition->width = 0; + requisition->height = 0; + + if (GTK_WIDGET_VISIBLE (widget)) { + menu_bar = GWW_VMENU_BAR (widget); + menu_shell = GTK_MENU_SHELL (widget); + + gtk_widget_size_request (menu_bar->extra_arrow, requisition); + + for ( children = menu_bar->children; children!=NULL; children=children->next ) { + child = children->data; + + if (GTK_WIDGET_VISIBLE (child)) { + gtk_widget_size_request (child, &child_requisition); + requisition->height = MAX (requisition->height, child_requisition.height); + } + } + + gtk_widget_style_get (widget, "internal_padding", &ipadding, NULL); + + requisition->width += (GTK_CONTAINER (menu_bar)->border_width + + ipadding + + BORDER_SPACING) * 2; + requisition->height += (GTK_CONTAINER (menu_bar)->border_width + + ipadding + + BORDER_SPACING) * 2; + + if (get_shadow_type ( GTK_MENU_BAR(menu_bar)) != GTK_SHADOW_NONE) { + requisition->width += widget->style->xthickness * 2; + requisition->height += widget->style->ythickness * 2; + } + } +} + +static void gww_vmenu_bar_size_allocate (GtkWidget *widget, + GtkAllocation *allocation) { + GwwVMenuBar *vmenu_bar; + GtkRequisition arrow_requisition, child_requisition; + GList *children; + gint i, goodi, extra_active; + gint width, total_width; + gint ipadding; + + g_return_if_fail (GWW_IS_VMENU_BAR (widget)); + g_return_if_fail (allocation != NULL); + + vmenu_bar = GWW_VMENU_BAR (widget); + + /* First figure out what widgets we want to display under the new */ + /* allocation scheme */ + gtk_widget_size_request (vmenu_bar->extra_arrow, &arrow_requisition); + + total_width = allocation->width; + gtk_widget_style_get (widget, "internal_padding", &ipadding, NULL); + total_width -= (GTK_CONTAINER (vmenu_bar)->border_width + + ipadding + + BORDER_SPACING) * 2; + if (get_shadow_type ( GTK_MENU_BAR(vmenu_bar)) != GTK_SHADOW_NONE) + total_width -= widget->style->xthickness * 2; + + goodi = -1; + width = 0; + for ( i=0, children = vmenu_bar->children; children!=NULL ; + ++i, children=children->next ) { + if (!GTK_WIDGET_VISIBLE (children->data)) + continue; + if ( width+arrow_requisition.width <= total_width || + ( children->next==NULL && width <= total_width )) + goodi = i-1; + gtk_widget_size_request (children->data, &child_requisition); + if ( width + child_requisition.width > total_width ) + break; + width += child_requisition.width + 6; /* Why do I need a fudge factor of 6? I'm doing something wrong */ + } + if ( children==NULL ) ++goodi; + extra_active = ( children!=NULL ); + if ( vmenu_bar->child_last==goodi && + vmenu_bar->extra_active == extra_active ) { + if ( widget->allocation.x == allocation->x && + widget->allocation.y == allocation->y && + widget->allocation.width == allocation->width && + widget->allocation.height == allocation->height ) +return; + } else { + /* Then undo any previous allocation */ + for ( i=0, children = vmenu_bar->children; children!=NULL && i<=vmenu_bar->child_last; + ++i, children=children->next ) { + ((GtkContainerClass*) parent_class)->remove( GTK_CONTAINER(vmenu_bar), + children->data ); + } + + if ( vmenu_bar->extra_active ) { + ((GtkContainerClass*) parent_class)->remove( GTK_CONTAINER(vmenu_bar), + vmenu_bar->extra_arrow ); + for ( ; children!=NULL ; children=children->next ) { + gtk_container_remove( GTK_CONTAINER(vmenu_bar->extra_menu), + children->data ); + } + } + + /* Then configure the new scheme */ + vmenu_bar->extra_active = extra_active; + vmenu_bar->child_last = goodi; + + for ( i=0, children = vmenu_bar->children; children!=NULL && i<=goodi; + ++i, children=children->next ) { + ((GtkContainerClass*) parent_class)->add( GTK_CONTAINER(vmenu_bar), + children->data ); + } + + if ( vmenu_bar->extra_active ) { + ((GtkContainerClass*) parent_class)->add( GTK_CONTAINER(vmenu_bar), + vmenu_bar->extra_arrow ); + for ( ; children!=NULL ; children=children->next ) { + gtk_container_add( GTK_CONTAINER(vmenu_bar->extra_menu), + children->data ); + } + } + } + + /* Finally ask the underlying menubar to do whatever it needs to do */ + /* with the widget set which we chose to be active */ + ((GtkWidgetClass*) parent_class)->size_allocate( GTK_WIDGET(vmenu_bar), + allocation ); +} + +static void gww_vmenu_bar_add( GtkContainer *widget, + GtkWidget *child) { + GwwVMenuBar *vmenu_bar; + + g_return_if_fail (GWW_IS_VMENU_BAR (widget)); + vmenu_bar = GWW_VMENU_BAR (widget); + + vmenu_bar->children = g_list_insert (vmenu_bar->children, child, -1); /* Add to end */ + g_object_ref( G_OBJECT(child)); + + /*gtk_widget_set_parent (child, GTK_WIDGET (vmenu_bar));*/ + /* Don't set the parent until we actually display it */ + + /* BUG!!! I am presuming that any adds/removes will be done before */ + /* the widget is actually displayed */ +} + +static void gww_vmenu_bar_remove( GtkContainer *widget, + GtkWidget *child) { + GwwVMenuBar *vmenu_bar; + + g_return_if_fail (GWW_IS_VMENU_BAR (widget)); + if ( child->parent!=NULL ) + ((GtkContainerClass*) parent_class)->remove( GTK_CONTAINER(child->parent), + child ); + vmenu_bar = GWW_VMENU_BAR (widget); + + vmenu_bar->children = g_list_remove (vmenu_bar->children, child); + /* BUG!!! I am presuming that any adds/removes will be done before */ + /* the widget is actually displayed */ + g_object_unref( G_OBJECT(child)); +} + + +static void gww_vmenu_bar_class_init (GwwVMenuBarClass *class) { + GtkWidgetClass *widget_class; + GtkContainerClass *container_class; + + parent_class = g_type_class_peek_parent (class); + + widget_class = (GtkWidgetClass*) class; + container_class = (GtkContainerClass*) class; + + widget_class->size_request = gww_vmenu_bar_size_request; + widget_class->size_allocate = gww_vmenu_bar_size_allocate; + + container_class->add = gww_vmenu_bar_add; + container_class->remove = gww_vmenu_bar_remove; +} + +static void gww_vmenu_bar_init (GwwVMenuBar *mbar) { + GtkWidget *arrow; + + arrow = gtk_arrow_new(GTK_ARROW_DOWN,GTK_SHADOW_OUT); + gtk_widget_show( arrow ); + mbar->extra_arrow = gtk_menu_item_new(); + gtk_widget_show( mbar->extra_arrow ); + gtk_container_add ( GTK_CONTAINER(mbar->extra_arrow), arrow); + mbar->extra_menu = gtk_menu_new (); + gtk_menu_item_set_submenu (GTK_MENU_ITEM (mbar->extra_arrow), mbar->extra_menu); + g_object_ref( G_OBJECT( mbar->extra_arrow )); + + mbar->children = NULL; + mbar->child_last = -1; + mbar->extra_active = FALSE; +} + +GType gww_vmenu_bar_get_type (void) { + static GType vmenu_bar_type = 0; + + if (!vmenu_bar_type) + { + static const GTypeInfo vmenu_bar_info = + { + sizeof (GtkMenuBarClass), + NULL, /* base_init */ + NULL, /* base_finalize */ + (GClassInitFunc) gww_vmenu_bar_class_init, + NULL, /* class_finalize */ + NULL, /* class_data */ + sizeof (GwwVMenuBar), + 0, /* n_preallocs */ + (GtkObjectInitFunc) gww_vmenu_bar_init, + }; + + vmenu_bar_type = g_type_register_static (GTK_TYPE_MENU_BAR, "GwwVMenuBar", + &vmenu_bar_info, 0); + } + + return vmenu_bar_type; +} + +GtkWidget *gww_vmenu_bar_new (void) +{ + return g_object_new (GWW_TYPE_VMENU_BAR, NULL); +} diff --git a/pool/shard002/C/0058510_avs_il_register.c b/pool/shard002/C/0058510_avs_il_register.c new file mode 100644 index 0000000000000000000000000000000000000000..c220ec766db82f5c75acbb38aebd4bfc4cf9f6b4 --- /dev/null +++ b/pool/shard002/C/0058510_avs_il_register.c @@ -0,0 +1,111 @@ +#include +#include +#include +#include +#include + +#include "avs.h" + +static void convert_argument(AvsCompilerArgument *arg, ILRegister *reg) +{ + arg->type = AvsCompilerArgumentPrivate; + arg->value.ptr = reg; +} + +static ILRegister * load_constant(AvsILAssemblerContext *ctx, AvsRunnable *robj, AvsCompilerArgument *arg) +{ + ILRegister *reg = avs_il_register_create(); + + reg->type = ILRegisterTypeConstant; + reg->value.constant = arg->value.constant; + + /* Convert argument */ + convert_argument(arg, reg); + return reg; +} + +static ILRegister * load_identifier(AvsILAssemblerContext *ctx, AvsRunnable *robj, AvsCompilerArgument *arg) +{ + ILRegister *reg = avs_il_register_create(); + AvsRunnableVariable *var; + + /* Lookup variable */ + var = avs_runnable_variable_find(robj->variable_manager, arg->value.identifier); + if (var == NULL) { + /* Variable not found, auto-create one */ + var = avs_runnable_variable_create(robj->variable_manager, arg->value.identifier, 0); + } + + avs_debug(print("ILR: Variable name: %s", var->name)); + + reg->type = ILRegisterTypeVariable; + reg->value.variable = var; + + /* Convert argument */ + convert_argument(arg, reg); + return reg; +} + +static ILRegister * load_worker(AvsILAssemblerContext *ctx, AvsRunnable *robj, AvsCompilerArgument *arg) +{ + ILRegister *reg = avs_il_register_create(); + + reg->type = ILRegisterTypeConstant; + convert_argument(arg, reg); + return reg; +} + +ILRegister * avs_il_register_load_worker(AvsILAssemblerContext *ctx, AvsRunnable *robj, AvsCompilerArgument *arg) +{ + return load_worker(ctx, robj, arg); +} + +ILRegister * avs_il_register_load_from_argument(AvsILAssemblerContext *ctx, AvsRunnable *robj, AvsCompilerArgument *arg) +{ + ILRegister *reg; + + switch (arg->type) { + case AvsCompilerArgumentConstant: + /* Generate load instruction */ + reg = load_constant(ctx, robj, arg); + break; + + case AvsCompilerArgumentIdentifier: + reg = load_identifier(ctx, robj, arg); + break; + + case AvsCompilerArgumentPrivate: + /* Data already loaded into a register */ + reg = (ILRegister *)arg->value.ptr; + break; + + default: + return NULL; /* Unsupported */ + } + + return reg; +} + + +void avs_il_register_dereference(ILRegister *reg) +{ + reg->ref--; + if(reg->ref <= 0) + free(reg); +} + +void avs_il_register_reference(ILRegister *reg) +{ + reg->ref++; +} + +ILRegister * avs_il_register_create(void) +{ + ILRegister *reg; + + reg = malloc(sizeof(ILRegister)); + memset(reg, 0, sizeof(ILRegister)); + + return reg; +} + diff --git a/pool/shard002/C/0058530_j0g.c b/pool/shard002/C/0058530_j0g.c new file mode 100644 index 0000000000000000000000000000000000000000..c73cbbf3a93cb7103fab722e388783dfd710b20c --- /dev/null +++ b/pool/shard002/C/0058530_j0g.c @@ -0,0 +1,64 @@ +#include +#include +#include +#include "js0n.h" +#include "j0g.h" + +// dumbed down parser, expects null terminated json, if fails the *index is 0 (and safe to pass into j0g_*) +char *j0g(char *json, unsigned short *index, int ilen) +{ + int ret, len; + if(!json) return NULL; + len = strlen(json); + ret = js0n((unsigned char*)json, len, index, ilen); + if(ret) *index = 0; + return json; +} + +// return the null-terminated string value matching the given key +char *j0g_str(char *key, char *json, unsigned short *index) +{ + char *str, *cursor; + int val = j0g_val(key, json, index); + if(!val) return NULL; + *(json+(index[val]+index[val+1])) = 0; // null terminate + // unescape stuff + for(cursor=str=json+index[val]; *cursor; cursor++,str++) + { + if(*cursor == '\\' && *(cursor+1) == 'n') + { + *str = '\n'; + cursor++; + }else if(*cursor == '\\' && *(cursor+1) == '"'){ + *str = '"'; + cursor++; + }else{ + *str = *cursor; + } + } + *str = *cursor; // copy null terminator too + return (char*)json+index[val]; +} + +// return 1 if the value is the bool value true, number 1, or even the string "true", false otherwise +int j0g_test(char *key, char *json, unsigned short *index) +{ + char *val = j0g_str(key, json, index); + if(!val) return 0; + if(strcmp(val, "true") == 0) return 1; + if(strcmp(val, "1") == 0) return 1; + return 0; +} + +// return the index offset of the value matching the given key +int j0g_val(char *key, char *json, unsigned short *index) +{ + if(!key || !json) return 0; + int i, klen = strlen(key); + for(i=0;index[i];i+=4) + { + if(klen == index[i+1] && strncmp(key,(char*)json+index[i],klen) == 0) return i+2; + } + return 0; +} + diff --git a/pool/shard002/C/0058533_mtxwriter.c b/pool/shard002/C/0058533_mtxwriter.c new file mode 100644 index 0000000000000000000000000000000000000000..38fb71176c7426ae23a47d109ba713f2ae0d6111 --- /dev/null +++ b/pool/shard002/C/0058533_mtxwriter.c @@ -0,0 +1,36 @@ +#include +#include +#include +#include +#include +#include +#include "mtxmydata.h" + +int main() +{ + int fd; + unsigned int value = 1; + struct mydata *addr; + + fd = shm_open(DATA, O_RDWR, 0); + if (fd == -1) { + perror("shm_open"); + exit(1); + } + + addr = + (struct mydata *)mmap(NULL, sizeof(struct mydata), + PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); + if (addr == MAP_FAILED) { + perror("mmap"); + exit(1); + } + pthread_mutex_lock (&addr->mtxlock); + addr->a = 10; + sleep(10); + addr->b = 30; + pthread_mutex_lock (&addr->mtxlock); + munmap(addr, sizeof(struct mydata)); + + return 0; +} diff --git a/pool/shard002/C/0058547_esys-audit.int.c b/pool/shard002/C/0058547_esys-audit.int.c new file mode 100644 index 0000000000000000000000000000000000000000..767bdfb78e16fa841a36d495e4d5f30a1c415c7c --- /dev/null +++ b/pool/shard002/C/0058547_esys-audit.int.c @@ -0,0 +1,286 @@ +/* SPDX-License-Identifier: BSD-2-Clause */ +/******************************************************************************* + * Copyright 2017-2018, Fraunhofer SIT sponsored by Infineon Technologies AG + * All rights reserved. + *******************************************************************************/ + +#ifdef HAVE_CONFIG_H +#include +#endif + +#include + +#include "tss2_esys.h" + +#include "esys_iutil.h" +#include "test-esys.h" +#define LOGMODULE test +#include "util/log.h" +#include "util/aux_util.h" + +/** This test is intended to test the ESYS audit commands. + * + * First a key for signing the audit digest is computed. + * A audit session is started, and for the command GetCapability the + * command audit digest and the session audit digest is computed. + * (Esys_GetCommandAuditDigest, Esys_GetSessionAuditDigest). In the + * last test the audit hash alg is changed with Esys_SetCommandCodeAuditStatus. + * + *\b Note: platform authorization needed. + * + * Tested ESYS commands: + * - Esys_CreatePrimary() (M) + * - Esys_FlushContext() (M) + * - Esys_GetCapability() (M) + * - Esys_GetCommandAuditDigest() (O) + * - Esys_GetSessionAuditDigest() (M) + * - Esys_SetCommandCodeAuditStatus() (O) + * - Esys_StartAuthSession() (M) + * - Esys_StartAuthSession() (M) + * + * @param[in,out] esys_context The ESYS_CONTEXT. + * @retval EXIT_FAILURE + * @retval EXIT_SKIP + * @retval EXIT_SUCCESS + */ + +int +test_esys_audit(ESYS_CONTEXT * esys_context) +{ + TSS2_RC r; + ESYS_TR signHandle = ESYS_TR_NONE; + ESYS_TR session = ESYS_TR_NONE; + int failure_return = EXIT_FAILURE; + + TPM2B_PUBLIC *outPublic = NULL; + TPM2B_CREATION_DATA *creationData = NULL; + TPM2B_DIGEST *creationHash = NULL; + TPMT_TK_CREATION *creationTicket = NULL; + TPMS_CAPABILITY_DATA *capabilityData = NULL; + TPM2B_ATTEST *auditInfo = NULL; + TPMT_SIGNATURE *signature = NULL; + + /* Compute a signing key */ + TPM2B_AUTH authValuePrimary = { + .size = 5, + .buffer = {1, 2, 3, 4, 5} + }; + + TPM2B_SENSITIVE_CREATE inSensitivePrimary = { + .size = 0, + .sensitive = { + .userAuth = { + .size = 0, + .buffer = {0}, + }, + .data = { + .size = 0, + .buffer = {0}, + }, + }, + }; + + inSensitivePrimary.sensitive.userAuth = authValuePrimary; + + TPM2B_PUBLIC inPublic = { + .size = 0, + .publicArea = { + .type = TPM2_ALG_RSA, + .nameAlg = TPM2_ALG_SHA256, + .objectAttributes = ( + TPMA_OBJECT_USERWITHAUTH | + TPMA_OBJECT_RESTRICTED | + TPMA_OBJECT_SIGN_ENCRYPT | + TPMA_OBJECT_FIXEDTPM | + TPMA_OBJECT_FIXEDPARENT | + TPMA_OBJECT_SENSITIVEDATAORIGIN + ), + .authPolicy = { + .size = 0, + }, + .parameters.rsaDetail = { + .symmetric = { + .algorithm = TPM2_ALG_NULL, + .keyBits.aes = 128, + .mode.aes = TPM2_ALG_CFB, + }, + .scheme = { + .scheme = TPM2_ALG_RSASSA, + .details = { .rsassa = { .hashAlg = TPM2_ALG_SHA256 }}, + + }, + .keyBits = 2048, + .exponent = 0, + }, + .unique.rsa = { + .size = 0, + .buffer = {}, + }, + }, + }; + + TPM2B_AUTH authValue = { + .size = 0, + .buffer = {} + }; + + TPM2B_DATA outsideInfo = { + .size = 0, + .buffer = {}, + }; + + TPML_PCR_SELECTION creationPCR = { + .count = 0, + }; + + r = Esys_TR_SetAuth(esys_context, ESYS_TR_RH_OWNER, &authValue); + goto_if_error(r, "Error: TR_SetAuth", error); + + r = Esys_CreatePrimary(esys_context, ESYS_TR_RH_OWNER, ESYS_TR_PASSWORD, + ESYS_TR_NONE, ESYS_TR_NONE, &inSensitivePrimary, + &inPublic, &outsideInfo, &creationPCR, + &signHandle, &outPublic, &creationData, + &creationHash, &creationTicket); + goto_if_error(r, "Error esys create primary", error); + + /* Start a audit session */ + TPMA_SESSION sessionAttributes = TPMA_SESSION_CONTINUESESSION | + TPMA_SESSION_AUDIT; + TPM2_SE sessionType = TPM2_SE_HMAC; + TPMI_ALG_HASH authHash = TPM2_ALG_SHA256; + TPMT_SYM_DEF symmetric = {.algorithm = TPM2_ALG_NULL }; + + r = Esys_StartAuthSession(esys_context, ESYS_TR_NONE, ESYS_TR_NONE, + ESYS_TR_NONE, ESYS_TR_NONE, ESYS_TR_NONE, + NULL, + sessionType, &symmetric, authHash, &session); + + goto_if_error(r, "Error Esys_StartAuthSession", error); + r = Esys_TRSess_SetAttributes(esys_context, session, sessionAttributes, + 0xff); + goto_if_error(r, "Error Esys_TRSess_SetAttributes", error); + + /* Execute one command to be audited */ + TPM2_CAP capability = TPM2_CAP_TPM_PROPERTIES; + UINT32 property = TPM2_PT_LOCKOUT_COUNTER; + UINT32 propertyCount = 1; + TPMI_YES_NO moreData; + + r = Esys_GetCapability(esys_context, + session, ESYS_TR_NONE, ESYS_TR_NONE, + capability, property, propertyCount, + &moreData, &capabilityData); + + goto_if_error(r, "Error esys get capability", error); + + ESYS_TR privacyHandle = ESYS_TR_RH_ENDORSEMENT; + TPM2B_DATA qualifyingData = {0}; + TPMT_SIG_SCHEME inScheme = { .scheme = TPM2_ALG_NULL }; + + /* Test the audit commands */ + r = Esys_GetCommandAuditDigest( + esys_context, + privacyHandle, + signHandle, + ESYS_TR_PASSWORD, + ESYS_TR_PASSWORD, + ESYS_TR_NONE, + &qualifyingData, + &inScheme, + &auditInfo, + &signature); + + if ((r == TPM2_RC_COMMAND_CODE) || + (r == (TPM2_RC_COMMAND_CODE | TSS2_RESMGR_RC_LAYER)) || + (r == (TPM2_RC_COMMAND_CODE | TSS2_RESMGR_TPM_RC_LAYER))) { + LOG_WARNING("Command TPM2_GetCommandAuditDigest not supported by TPM."); + failure_return = EXIT_SKIP; + goto error; + } + + Esys_Free(auditInfo); + Esys_Free(signature); + + goto_if_error(r, "Error: GetCommandAuditDigest", error); + + r = Esys_GetSessionAuditDigest( + esys_context, + privacyHandle, + signHandle, + session, + ESYS_TR_PASSWORD, + ESYS_TR_PASSWORD, + ESYS_TR_NONE, + &qualifyingData, + &inScheme, + &auditInfo, + &signature); + goto_if_error(r, "Error: GetSessionAuditDigest", error); + + TPMI_ALG_HASH auditAlg = TPM2_ALG_SHA256; + TPML_CC clearList = {0}; + TPML_CC setList = {0}; + + r = Esys_SetCommandCodeAuditStatus( + esys_context, + ESYS_TR_RH_PLATFORM, + ESYS_TR_PASSWORD, + ESYS_TR_NONE, + ESYS_TR_NONE, + auditAlg, + &setList, + &clearList); + + if (number_rc(r) == TPM2_RC_BAD_AUTH) { + /* Platform authorization not possible test will be skipped */ + LOG_WARNING("Platform authorization not possible."); + failure_return = EXIT_SKIP; + goto error; + } + + goto_if_error(r, "Error: SetCommandCodeAuditStatus", error); + + r = Esys_FlushContext(esys_context, signHandle); + goto_if_error(r, "Error: FlushContext", error); + + signHandle = ESYS_TR_NONE; + + r = Esys_FlushContext(esys_context, session); + goto_if_error(r, "Error during FlushContext", error); + + Esys_Free(outPublic); + Esys_Free(creationData); + Esys_Free(creationHash); + Esys_Free(creationTicket); + Esys_Free(capabilityData); + Esys_Free(auditInfo); + Esys_Free(signature); + return EXIT_SUCCESS; + + error: + + if (session != ESYS_TR_NONE) { + if (Esys_FlushContext(esys_context, session) != TSS2_RC_SUCCESS) { + LOG_ERROR("Cleanup session failed."); + } + } + + if (signHandle != ESYS_TR_NONE) { + if (Esys_FlushContext(esys_context, signHandle) != TSS2_RC_SUCCESS) { + LOG_ERROR("Cleanup signHandle failed."); + } + } + Esys_Free(outPublic); + Esys_Free(creationData); + Esys_Free(creationHash); + Esys_Free(creationTicket); + Esys_Free(capabilityData); + Esys_Free(auditInfo); + Esys_Free(signature); + return failure_return; +} + +int +test_invoke_esys(ESYS_CONTEXT * esys_context) { + return test_esys_audit(esys_context); +} diff --git a/pool/shard002/C/0058552_mca_subr.c b/pool/shard002/C/0058552_mca_subr.c new file mode 100644 index 0000000000000000000000000000000000000000..156aefaa7b74ae9d7ef92f2d128fad5fbdeea2ea --- /dev/null +++ b/pool/shard002/C/0058552_mca_subr.c @@ -0,0 +1,107 @@ +/* $NetBSD: mca_subr.c,v 1.1 2000/05/11 15:42:05 jdolecek Exp $ */ + +/*- + * Copyright (c) 2000 The NetBSD Foundation, Inc. + * Copyright (c) 1996-1999 Scott D. Telford. + * All rights reserved. + * + * This code is derived from software contributed to The NetBSD Foundation + * by Scott Telford . + * + * 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 NetBSD + * Foundation, Inc. and its contributors. + * 4. Neither the name of The NetBSD Foundation 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 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. + */ + +/* + * MCA Bus subroutines + */ + +#include "opt_mcaverbose.h" + +#include +#include +#include + +#include +#include + +#ifdef MCAVERBOSE +/* + * Descriptions of of known MCA devices + */ +struct mca_knowndev { + int id; /* MCA ID */ + const char *name; /* text description */ +}; + +#include + +#endif /* MCAVERBOSE */ + +/* supported peripheals */ +const int mca_suppdevs[] = { + MCA_PRODUCT_AHA1640, + MCA_PRODUCT_3C523, + MCA_PRODUCT_ITR, + 0 +}; + +/* + * Returns 1 if a device is supported (i.e. device driver exists for it) + * 0 otherwise. + */ +int +mca_issupp(id) + int id; +{ + int i; + for(i=0; mca_suppdevs[i]; i++) { + if (id == mca_suppdevs[i]) + return 1; + } + + return 0; +} + +void +mca_devinfo(id, cp) + int id; + char *cp; +{ +#ifdef MCAVERBOSE + const struct mca_knowndev *kdp; + + kdp = mca_knowndevs; + for (; kdp->name != NULL && kdp->id != id; kdp++); + + if (kdp->name != NULL) + sprintf(cp, "%s (0x%04x)", kdp->name, id); + else +#endif /* MCAVERBOSE */ + sprintf(cp, "product 0x%04x", id); +} diff --git a/pool/shard002/C/0058556_gedit-statusbar.c b/pool/shard002/C/0058556_gedit-statusbar.c new file mode 100644 index 0000000000000000000000000000000000000000..2572f76a91306a8def674d18a4cf946ddbb32fb6 --- /dev/null +++ b/pool/shard002/C/0058556_gedit-statusbar.c @@ -0,0 +1,258 @@ +/* + * gedit-statusbar.c + * This file is part of gedit + * + * Copyright (C) 2005 - Paolo Borelli + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, see . + */ + +#include "config.h" + +#include "gedit-statusbar.h" + +#include +#include +#include + +#include "gedit-app.h" +#include "gedit-status-menu-button.h" + +struct _GeditStatusbar +{ + GtkStatusbar parent_instance; + + GtkWidget *error_frame; + GtkWidget *error_image; + GtkWidget *state_frame; + GtkWidget *load_image; + GtkWidget *save_image; + GtkWidget *print_image; + GtkWidget *overwrite_mode_label; + + /* tmp flash timeout data */ + guint flash_timeout; + guint flash_context_id; + guint flash_message_id; +}; + +G_DEFINE_TYPE (GeditStatusbar, gedit_statusbar, GTK_TYPE_STATUSBAR) + +static gchar * +get_overwrite_mode_string (gboolean overwrite) +{ + /* Use spaces to leave padding proportional to the font size */ + return g_strdup_printf (" %s ", overwrite ? _("OVR") : _("INS")); +} + +static gint +get_overwrite_mode_length (void) +{ + return 4 + MAX (g_utf8_strlen (_("OVR"), -1), g_utf8_strlen (_("INS"), -1)); +} + +static void +gedit_statusbar_dispose (GObject *object) +{ + GeditStatusbar *statusbar = GEDIT_STATUSBAR (object); + + if (statusbar->flash_timeout > 0) + { + g_source_remove (statusbar->flash_timeout); + statusbar->flash_timeout = 0; + } + + G_OBJECT_CLASS (gedit_statusbar_parent_class)->dispose (object); +} + +static void +gedit_statusbar_class_init (GeditStatusbarClass *klass) +{ + GObjectClass *object_class = G_OBJECT_CLASS (klass); + GtkWidgetClass *widget_class = GTK_WIDGET_CLASS (klass); + + object_class->dispose = gedit_statusbar_dispose; + + gtk_widget_class_set_template_from_resource (widget_class, + "/org/gnome/gedit/ui/gedit-statusbar.ui"); + + gtk_widget_class_bind_template_child (widget_class, GeditStatusbar, error_frame); + gtk_widget_class_bind_template_child (widget_class, GeditStatusbar, error_image); + gtk_widget_class_bind_template_child (widget_class, GeditStatusbar, state_frame); + gtk_widget_class_bind_template_child (widget_class, GeditStatusbar, load_image); + gtk_widget_class_bind_template_child (widget_class, GeditStatusbar, save_image); + gtk_widget_class_bind_template_child (widget_class, GeditStatusbar, print_image); + gtk_widget_class_bind_template_child (widget_class, GeditStatusbar, overwrite_mode_label); +} + +static void +gedit_statusbar_init (GeditStatusbar *statusbar) +{ + gtk_widget_init_template (GTK_WIDGET (statusbar)); + + gtk_label_set_width_chars (GTK_LABEL (statusbar->overwrite_mode_label), + get_overwrite_mode_length ()); +} + +/** + * gedit_statusbar_new: + * + * Creates a new #GeditStatusbar. + * + * Return value: the new #GeditStatusbar object + **/ +GtkWidget * +gedit_statusbar_new (void) +{ + return GTK_WIDGET (g_object_new (GEDIT_TYPE_STATUSBAR, NULL)); +} + +/** + * gedit_statusbar_set_overwrite: + * @statusbar: a #GeditStatusbar + * @overwrite: if the overwrite mode is set + * + * Sets the overwrite mode on the statusbar. + **/ +void +gedit_statusbar_set_overwrite (GeditStatusbar *statusbar, + gboolean overwrite) +{ + gchar *msg; + + g_return_if_fail (GEDIT_IS_STATUSBAR (statusbar)); + + msg = get_overwrite_mode_string (overwrite); + gtk_label_set_text (GTK_LABEL (statusbar->overwrite_mode_label), msg); + g_free (msg); +} + +void +gedit_statusbar_clear_overwrite (GeditStatusbar *statusbar) +{ + g_return_if_fail (GEDIT_IS_STATUSBAR (statusbar)); + + gtk_label_set_text (GTK_LABEL (statusbar->overwrite_mode_label), NULL); +} + +static gboolean +remove_message_timeout (GeditStatusbar *statusbar) +{ + gtk_statusbar_remove (GTK_STATUSBAR (statusbar), + statusbar->flash_context_id, + statusbar->flash_message_id); + + /* remove the timeout */ + statusbar->flash_timeout = 0; + return FALSE; +} + +/* FIXME this is an issue for introspection */ +/** + * gedit_statusbar_flash_message: + * @statusbar: a #GeditStatusbar + * @context_id: message context_id + * @format: message to flash on the statusbar + * @...: the arguments to insert in @format + * + * Flash a temporary message on the statusbar. + */ +void +gedit_statusbar_flash_message (GeditStatusbar *statusbar, + guint context_id, + const gchar *format, + ...) +{ + const guint32 flash_length = 3000; /* three seconds */ + va_list args; + gchar *msg; + + g_return_if_fail (GEDIT_IS_STATUSBAR (statusbar)); + g_return_if_fail (format != NULL); + + va_start (args, format); + msg = g_strdup_vprintf (format, args); + va_end (args); + + /* remove a currently ongoing flash message */ + if (statusbar->flash_timeout > 0) + { + g_source_remove (statusbar->flash_timeout); + statusbar->flash_timeout = 0; + + gtk_statusbar_remove (GTK_STATUSBAR (statusbar), + statusbar->flash_context_id, + statusbar->flash_message_id); + } + + statusbar->flash_context_id = context_id; + statusbar->flash_message_id = gtk_statusbar_push (GTK_STATUSBAR (statusbar), + context_id, + msg); + + statusbar->flash_timeout = g_timeout_add (flash_length, + (GSourceFunc) remove_message_timeout, + statusbar); + + g_free (msg); +} + +void +gedit_statusbar_set_window_state (GeditStatusbar *statusbar, + GeditWindowState state, + gint num_of_errors) +{ + g_return_if_fail (GEDIT_IS_STATUSBAR (statusbar)); + + gtk_widget_hide (statusbar->state_frame); + gtk_widget_hide (statusbar->save_image); + gtk_widget_hide (statusbar->load_image); + gtk_widget_hide (statusbar->print_image); + + if (state & GEDIT_WINDOW_STATE_SAVING) + { + gtk_widget_show (statusbar->state_frame); + gtk_widget_show (statusbar->save_image); + } + if (state & GEDIT_WINDOW_STATE_LOADING) + { + gtk_widget_show (statusbar->state_frame); + gtk_widget_show (statusbar->load_image); + } + if (state & GEDIT_WINDOW_STATE_PRINTING) + { + gtk_widget_show (statusbar->state_frame); + gtk_widget_show (statusbar->print_image); + } + if (state & GEDIT_WINDOW_STATE_ERROR) + { + gchar *tip; + + tip = g_strdup_printf (ngettext("There is a tab with errors", + "There are %d tabs with errors", + num_of_errors), + num_of_errors); + + gtk_widget_set_tooltip_text (statusbar->error_image, tip); + g_free (tip); + + gtk_widget_show (statusbar->error_frame); + } + else + { + gtk_widget_hide (statusbar->error_frame); + } +} + +/* ex:set ts=8 noet: */ diff --git a/pool/shard002/C/0058566_write.c b/pool/shard002/C/0058566_write.c new file mode 100644 index 0000000000000000000000000000000000000000..62ffe2ecf28fb95ac9d394b6c58851316a330107 --- /dev/null +++ b/pool/shard002/C/0058566_write.c @@ -0,0 +1,81 @@ +/* + Unix SMB/CIFS implementation. + + SMB2 client write call + + Copyright (C) Andrew Tridgell 2005 + + 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 "includes.h" +#include "libcli/smb2/smb2.h" +#include "libcli/smb2/smb2_calls.h" + +/* + send a write request +*/ +struct smb2_request *smb2_write_send(struct smb2_tree *tree, struct smb2_write *io) +{ + NTSTATUS status; + struct smb2_request *req; + + req = smb2_request_init_tree(tree, SMB2_OP_WRITE, 0x30, true, io->in.data.length); + if (req == NULL) return NULL; + + status = smb2_push_o16s32_blob(&req->out, 0x02, io->in.data); + if (!NT_STATUS_IS_OK(status)) { + talloc_free(req); + return NULL; + } + + SBVAL(req->out.body, 0x08, io->in.offset); + smb2_push_handle(req->out.body+0x10, &io->in.file.handle); + + SBVAL(req->out.body, 0x20, io->in.unknown1); + SBVAL(req->out.body, 0x28, io->in.unknown2); + + smb2_transport_send(req); + + return req; +} + + +/* + recv a write reply +*/ +NTSTATUS smb2_write_recv(struct smb2_request *req, struct smb2_write *io) +{ + if (!smb2_request_receive(req) || + !smb2_request_is_ok(req)) { + return smb2_request_destroy(req); + } + + SMB2_CHECK_PACKET_RECV(req, 0x10, true); + + io->out._pad = SVAL(req->in.body, 0x02); + io->out.nwritten = IVAL(req->in.body, 0x04); + io->out.unknown1 = BVAL(req->in.body, 0x08); + + return smb2_request_destroy(req); +} + +/* + sync write request +*/ +NTSTATUS smb2_write(struct smb2_tree *tree, struct smb2_write *io) +{ + struct smb2_request *req = smb2_write_send(tree, io); + return smb2_write_recv(req, io); +} diff --git a/pool/shard002/C/0058567_ipmi-attn.c b/pool/shard002/C/0058567_ipmi-attn.c new file mode 100644 index 0000000000000000000000000000000000000000..280b2525fafea358c3b8a345933d89b48ad0a066 --- /dev/null +++ b/pool/shard002/C/0058567_ipmi-attn.c @@ -0,0 +1,100 @@ +// SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later +/* + * When everything is terrible, tell the FSP as much as possible as to why + * + * Copyright 2013-2019 IBM Corp. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +/* Use same attention SRC for BMC based machine */ +DEFINE_LOG_ENTRY(OPAL_RC_ATTN, OPAL_PLATFORM_ERR_EVT, + OPAL_ATTN, OPAL_PLATFORM_FIRMWARE, + OPAL_ERROR_PANIC, OPAL_ABNORMAL_POWER_OFF); + +/* Maximum buffer size to capture backtrace and other useful information */ +#define IPMI_TI_BUFFER_SIZE (IPMI_MAX_PEL_SIZE - PEL_MIN_SIZE) +static char ti_buffer[IPMI_TI_BUFFER_SIZE]; + +#define STACK_BUF_ENTRIES 20 +static struct bt_entry bt_buf[STACK_BUF_ENTRIES]; + +/* Log eSEL event with OPAL backtrace */ +static void ipmi_log_terminate_event(const char *msg) +{ + struct bt_metadata metadata; + unsigned int ti_len; + unsigned int ti_size; + struct errorlog *elog_buf; + + /* Fill OPAL version */ + ti_len = snprintf(ti_buffer, IPMI_TI_BUFFER_SIZE, + "OPAL version : %s\n", version); + + /* File information */ + ti_len += snprintf(ti_buffer + ti_len, IPMI_TI_BUFFER_SIZE - ti_len, + "File info : %s\n", msg); + ti_size = IPMI_TI_BUFFER_SIZE - ti_len; + + /* Backtrace */ + backtrace_create(bt_buf, STACK_BUF_ENTRIES, &metadata); + metadata.token = OPAL_LAST + 1; + backtrace_print(bt_buf, &metadata, ti_buffer + ti_len, &ti_size, true); + + /* Create eSEL event and commit */ + elog_buf = opal_elog_create(&e_info(OPAL_RC_ATTN), 0); + log_append_data(elog_buf, (char *)&ti_buffer, ti_len + ti_size); + log_commit(elog_buf); +} + +void __attribute__((noreturn)) ipmi_terminate(const char *msg) +{ + /* Log eSEL event */ + if (ipmi_present()) + ipmi_log_terminate_event(msg); + + /* + * If mpipl is supported then trigger SBE interrupt + * to initiate mpipl + */ + p9_sbe_terminate(); + + /* + * Trigger software xstop (OPAL TI). It will stop all the CPU threads + * moving them into quiesced state. OCC will collect all FIR data. + * Upon checkstop signal, BMC will then decide whether to reboot/IPL or + * not depending on AutoReboot policy, if any. This helps in cases + * where OPAL is crashing/terminating before host reaches to runtime. + * With OpenBMC AutoReboot policy, in such cases, it will make sure + * that system is moved to Quiesced state after 3 or so attempts to + * IPL. Without OPAL TI, OpenBMC will never know that OPAL is + * terminating and system would go into never ending IPL'ing loop. + * + * Once the system reaches to runtime, OpenBMC resets the boot counter. + * Hence next time when BMC receieves the OPAL TI, it will IPL the + * system if AutoReboot is enabled. We don't need to worry about self + * rebooting. + */ + + xscom_trigger_xstop(); + /* + * Control will not reach here if software xstop has been supported and + * enabled. If not supported then fallback to cec reboot path below. + */ + + /* Reboot call */ + if (platform.cec_reboot) + platform.cec_reboot(); + + while (1) + time_wait_ms(100); +} diff --git a/pool/shard002/C/0058568_tst.c b/pool/shard002/C/0058568_tst.c new file mode 100644 index 0000000000000000000000000000000000000000..c0dabea37d5308237c1e9b2942ba894d15fe3b93 --- /dev/null +++ b/pool/shard002/C/0058568_tst.c @@ -0,0 +1,139 @@ +/* $Id: tst.c 435 2004-06-02 15:46:36Z max $ */ + +/* + * + * Copyright (C) 1999 David Mazieres (dm@uun.org) + * + * 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 "sfs-internal.h" + +#if 0 + +static void +getfh (const char *path) +{ + int fd; + sfs_desc sd; + + fd = open (path, O_RDONLY); + if (fd < 0) { + perror (path); + return; + } + if (sfs_fgetdesc (&sd, fd) < 0) + fprintf (stderr, "%s: not found\n", path); + else { + unsigned i; + printf ("%s %s ", path, sd.fsname); + for (i = 0; i < sd.fhsize; i++) + printf ("%02x", (u_char) sd.fhdata[i]); + printf ("\n"); + } + + close (fd); +} + +static void +getfh2 (const char *path) +{ + sfs_desc sd; + if (sfs_getdesc (&sd, path) < 0) + fprintf (stderr, "%s: not found\n", path); + else { + unsigned i; + printf ("%s %s ", path, sd.fsname); + for (i = 0; i < sd.fhsize; i++) + printf ("%02x", (u_char) sd.fhdata[i]); + printf ("\n"); + } + +} + +static void +pstat (const char *path) +{ + struct stat sb; + struct sfs_names sn; + + if (stat (path, &sb) < 0) { + perror (path); + return; + } + sfs_stat2names (&sn, &sb); + + printf ("%s %s %s\n", sn.uidname, sn.gidname, path); +} + +static void +pids (const char *path) +{ + struct stat sb; + sfs_remoteid id; + + if (stat (path, &sb) < 0) { + perror (path); + return; + } + sfs_getremoteid (&id, sb.st_dev); + if (id.valid) { + printf ("%s: uid = %u, gid = %u", path, id.uid, id.gid); + if (id.ngroups > 0) { + u_int i; + printf (", groups = { %u", id.groups[0]); + for (i = 1; i < id.ngroups; i++) + printf (", %u", id.groups[i]); + printf (" }\n"); + } + else + printf ("\n"); + } + else + printf ("%s: no credentials\n", path); +} + +int +main (int argc, char **argv) +{ + int i; + + if (argc <= 1) { + getfh ("."); + getfh2 ("."); + pstat ("."); + pids ("."); + } + else + for (i = 1; i < argc; i++) { + getfh (argv[i]); + getfh2 (argv[i]); + pstat (argv[i]); + pids (argv[i]); + } + return 0; +} + +#else + +int +main (int argc, char **argv) +{ + return 0; +} + +#endif diff --git a/pool/shard002/C/0058623_grid_1_3d_z.c b/pool/shard002/C/0058623_grid_1_3d_z.c new file mode 100644 index 0000000000000000000000000000000000000000..2bda9fc02f98318860c828a7d97deba60555b08b --- /dev/null +++ b/pool/shard002/C/0058623_grid_1_3d_z.c @@ -0,0 +1,159 @@ +/* + A simple test program that generates one Geographic porjection Grid with + 3d variable and 1d level. + + Compilation instruction: + + %h5cc -I/path/to/hdfeos5/include -L/path/to/hdfeos5/lib -o grid_1_3d_z \ + -lhe5_hdfeos -lgctp grid_1_3d_z.c + + To generate the test file, run + %./grid_1_3d_z + + Copyright (C) 2012 The HDF Group + + */ +#include + +herr_t write_attr(hid_t gdid, char* field_name, char* attr_name, char* value); +herr_t write_field_1d(hid_t gdid, char* field_name); +herr_t write_field_3d(hid_t gdid, char* field_name); +herr_t write_grid(hid_t gdfid, char* gname); + +/* Write a local attribute. See HDF-EOS5 testdrivers/grid/TestGrid.c. */ +herr_t write_attr(hid_t gdid, char* field_name, char* attr_name, char* value) +{ + hsize_t count[1]; + count[0] = strlen(value); + return HE5_GDwritelocattr(gdid, field_name, attr_name, H5T_NATIVE_CHAR, + count, value); +} + +herr_t write_field_1d(hid_t gdid, char* field_name) +{ + int zdim = 0; + + float val = 0.0; + float var[2]; + + hssize_t start[1]; + hsize_t count[1]; + + start[0] = 0; + count[0] = 2; + + + while(zdim < 2) { + var[zdim] = val; + val = val + 1.0; + zdim++; + } + + + HE5_GDdeffield(gdid, field_name, "ZDim", NULL, + H5T_NATIVE_FLOAT, 0); + HE5_GDwritefield(gdid, field_name, start, NULL, count, var); + return write_attr(gdid, field_name, "units", "hPa"); +} + +herr_t write_field_3d(hid_t gdid, char* field_name) +{ + int ydim = 0; + int xdim = 0; + int zdim = 0; + + float val = 0.0; + float var[2][4][8]; + + hssize_t start[3]; + hsize_t count[3]; + + start[0] = 0; + start[1] = 0; + start[2] = 0; + count[0] = 2; + count[1] = 4; + count[2] = 8; + + while(zdim < 2) { + while(ydim < 4) { + while(xdim < 8) { + var[zdim][ydim][xdim] = val; + val = val + 1.0; + xdim++; + } + ydim++; + xdim = 0; + } + zdim++; + ydim = 0; + xdim = 0; + } + + HE5_GDdeffield(gdid, field_name, "ZDim,YDim,XDim", NULL, + H5T_NATIVE_FLOAT, 0); + HE5_GDwritefield(gdid, field_name, start, NULL, count, var); + return write_attr(gdid, field_name, "units", "K"); +} + +herr_t write_grid(hid_t gdfid, char* gname) +{ + double upleft[2]; + double lowright[2]; + + herr_t status = FAIL; + + hid_t gdid = FAIL; + + int dummy = 0; + + long xdim = 8; + long ydim = 4; + long zdim = 2; + + /* Set corner points. */ + upleft[0] = HE5_EHconvAng(0., HE5_HDFE_DEG_DMS); /* left */ + upleft[1] = HE5_EHconvAng((float)ydim, HE5_HDFE_DEG_DMS); /* up */ + lowright[0] = HE5_EHconvAng((float)xdim, HE5_HDFE_DEG_DMS); /* right */ + lowright[1] = HE5_EHconvAng(0., HE5_HDFE_DEG_DMS); /* low */ + + + /* Create Grids. */ + gdid = HE5_GDcreate(gdfid, gname, xdim, ydim, upleft, lowright); + + /* Set projection. */ + status = HE5_GDdefproj(gdid, HE5_GCTP_GEO, dummy, dummy, NULL); + + /* Define "Level" Dimension */ + status = HE5_GDdefdim(gdid, "ZDim", zdim); + + /* Write field. */ + write_field_3d(gdid, "temperature"); + write_field_1d(gdid, "pressure"); + + /* Close the Grid. */ + status = HE5_GDdetach(gdid); + return status; +} + +int main() +{ + herr_t status = FAIL; + hid_t gdfid = FAIL; + /* Create a file. */ + gdfid = HE5_GDopen("grid_1_3d_z.h5", H5F_ACC_TRUNC); + + /* Write a grid. */ + write_grid(gdfid, "GeoGrid"); + + /* Close the file. */ + status = HE5_GDclose(gdfid); + return 0; +} + +/* +References + [1] hdfeos5/samples/he5_gd_setup.c + [2] hdfeos5/samples/he5_gd_definefields.c + [3] hdfeos5/samples/he5_gd_writedata.c +*/ diff --git a/pool/shard002/C/0058645_machine.c b/pool/shard002/C/0058645_machine.c new file mode 100644 index 0000000000000000000000000000000000000000..e796bbe27d2c92d508ab7ecbe6d49294b512f104 --- /dev/null +++ b/pool/shard002/C/0058645_machine.c @@ -0,0 +1,89 @@ +#include "hw/hw.h" +#include "hw/boards.h" + +static int get_fpcr(QEMUFile *f, void *opaque, size_t size) +{ + CPUAlphaState *env = opaque; + cpu_alpha_store_fpcr(env, qemu_get_be64(f)); + return 0; +} + +static void put_fpcr(QEMUFile *f, void *opaque, size_t size) +{ + CPUAlphaState *env = opaque; + qemu_put_be64(f, cpu_alpha_load_fpcr(env)); +} + +static const VMStateInfo vmstate_fpcr = { + .name = "fpcr", + .get = get_fpcr, + .put = put_fpcr, +}; + +static VMStateField vmstate_env_fields[] = { + VMSTATE_UINTTL_ARRAY(ir, CPUAlphaState, 31), + VMSTATE_UINTTL_ARRAY(fir, CPUAlphaState, 31), + /* Save the architecture value of the fpcr, not the internally + expanded version. Since this architecture value does not + exist in memory to be stored, this requires a but of hoop + jumping. We want OFFSET=0 so that we effectively pass ENV + to the helper functions, and we need to fill in the name by + hand since there's no field of that name. */ + { + .name = "fpcr", + .version_id = 0, + .size = sizeof(uint64_t), + .info = &vmstate_fpcr, + .flags = VMS_SINGLE, + .offset = 0 + }, + VMSTATE_UINTTL(pc, CPUAlphaState), + VMSTATE_UINTTL(unique, CPUAlphaState), + VMSTATE_UINTTL(lock_addr, CPUAlphaState), + VMSTATE_UINTTL(lock_value, CPUAlphaState), + /* Note that lock_st_addr is not saved; it is a temporary + used during the execution of the st[lq]_c insns. */ + + VMSTATE_UINT8(ps, CPUAlphaState), + VMSTATE_UINT8(intr_flag, CPUAlphaState), + VMSTATE_UINT8(pal_mode, CPUAlphaState), + VMSTATE_UINT8(fen, CPUAlphaState), + + VMSTATE_UINT32(pcc_ofs, CPUAlphaState), + + VMSTATE_UINTTL(trap_arg0, CPUAlphaState), + VMSTATE_UINTTL(trap_arg1, CPUAlphaState), + VMSTATE_UINTTL(trap_arg2, CPUAlphaState), + + VMSTATE_UINTTL(exc_addr, CPUAlphaState), + VMSTATE_UINTTL(palbr, CPUAlphaState), + VMSTATE_UINTTL(ptbr, CPUAlphaState), + VMSTATE_UINTTL(vptptr, CPUAlphaState), + VMSTATE_UINTTL(sysval, CPUAlphaState), + VMSTATE_UINTTL(usp, CPUAlphaState), + + VMSTATE_UINTTL_ARRAY(shadow, CPUAlphaState, 8), + VMSTATE_UINTTL_ARRAY(scratch, CPUAlphaState, 24), + + VMSTATE_END_OF_LIST() +}; + +static const VMStateDescription vmstate_env = { + .name = "env", + .version_id = 1, + .minimum_version_id = 1, + .fields = vmstate_env_fields, +}; + +static VMStateField vmstate_cpu_fields[] = { + VMSTATE_CPU(), + VMSTATE_STRUCT(env, AlphaCPU, 1, vmstate_env, CPUAlphaState), + VMSTATE_END_OF_LIST() +}; + +const VMStateDescription vmstate_alpha_cpu = { + .name = "cpu", + .version_id = 1, + .minimum_version_id = 1, + .fields = vmstate_cpu_fields, +}; diff --git a/pool/shard002/C/0058665_audio_ctl.c b/pool/shard002/C/0058665_audio_ctl.c new file mode 100644 index 0000000000000000000000000000000000000000..73100190d944b8611958a43bbb4b7adb87bcfc41 --- /dev/null +++ b/pool/shard002/C/0058665_audio_ctl.c @@ -0,0 +1,181 @@ +/* + * Copyright (C) 2009 Google, Inc. + * Copyright (C) 2009 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 + +#define BUFSZ (0) + +static DEFINE_MUTEX(voice_lock); +static int voice_started; + +static struct audio_client *voc_tx_clnt; +static struct audio_client *voc_rx_clnt; + +static int q6_voice_start(void) +{ + int rc = 0; + + mutex_lock(&voice_lock); + + if (voice_started) { + pr_err("[%s:%s] busy\n", __MM_FILE__, __func__); + rc = -EBUSY; + goto done; + } + + voc_tx_clnt = q6voice_open(AUDIO_FLAG_WRITE); + if (!voc_tx_clnt) { + pr_err("[%s:%s] open voice tx failed.\n", __MM_FILE__, + __func__); + rc = -ENOMEM; + goto done; + } + + voc_rx_clnt = q6voice_open(AUDIO_FLAG_READ); + if (!voc_rx_clnt) { + pr_err("[%s:%s] open voice rx failed.\n", __MM_FILE__, + __func__); + q6voice_close(voc_tx_clnt); + rc = -ENOMEM; + } + + voice_started = 1; +done: + mutex_unlock(&voice_lock); + return rc; +} + +static int q6_voice_stop(void) +{ + mutex_lock(&voice_lock); + if (voice_started) { + q6voice_close(voc_tx_clnt); + q6voice_close(voc_rx_clnt); + voice_started = 0; + } + mutex_unlock(&voice_lock); + return 0; +} + +static int q6_open(struct inode *inode, struct file *file) +{ + pr_debug("[%s:%s]\n", __MM_FILE__, __func__); + return 0; +} + +static int q6_ioctl(struct inode *inode, struct file *file, + unsigned int cmd, unsigned long arg) +{ + int rc; + uint32_t n; + uint32_t id[2]; + uint32_t mute_status; + + switch (cmd) { + case AUDIO_SWITCH_DEVICE: + rc = copy_from_user(&id, (void *)arg, sizeof(id)); + if (!rc) { + rc = q6audio_do_routing(id[0], id[1]); + pr_info("[Audio_CTL] id[0] = 0x%x, id[1] = 0x%x\n",id[0], id[1]); + } + break; + case AUDIO_SET_VOLUME: + rc = copy_from_user(&n, (void *)arg, sizeof(n)); + pr_debug("[%s:%s] SET_VOLUME: vol = %d\n", __MM_FILE__, + __func__, n); + if (!rc) + rc = q6audio_set_rx_volume(n); + break; + case AUDIO_SET_MUTE: + rc = copy_from_user(&n, (void *)arg, sizeof(n)); + if (!rc) + rc = q6audio_set_tx_mute(n); + if (!rc) { + if (voice_started) { + if (n == 1) + mute_status = STREAM_MUTE; + else + mute_status = STREAM_UNMUTE; + } else { + if (n == 1) + mute_status = DEVICE_MUTE; + else + mute_status = DEVICE_UNMUTE; + } + + pr_debug("[%s:%s] SET_MUTE: mute_status = %d\n", + __MM_FILE__, __func__, mute_status); + rc = q6audio_set_tx_mute(mute_status); + } + break; + case AUDIO_UPDATE_ACDB: + rc = copy_from_user(&id, (void *)arg, sizeof(id)); + pr_debug("[%s:%s] UPDATE_ACDB: id[0] = 0x%x, id[1] = 0x%x\n", + __MM_FILE__, __func__, id[0], id[1]); + if (!rc) + rc = q6audio_update_acdb(id[0], 0); + break; + case AUDIO_START_VOICE: + pr_debug("[%s:%s] START_VOICE\n", __MM_FILE__, __func__); + rc = q6_voice_start(); + break; + case AUDIO_STOP_VOICE: + pr_debug("[%s:%s] STOP_VOICE\n", __MM_FILE__, __func__); + rc = q6_voice_stop(); + break; + case AUDIO_REINIT_ACDB: + pr_debug("[%s:%s] REINIT_ACDB\n", __MM_FILE__, __func__); + rc = 0; + break; + default: + rc = -EINVAL; + } + + return rc; +} + + +static int q6_release(struct inode *inode, struct file *file) +{ + pr_debug("[%s:%s]\n", __MM_FILE__, __func__); + return 0; +} + +static struct file_operations q6_dev_fops = { + .owner = THIS_MODULE, + .open = q6_open, + .ioctl = q6_ioctl, + .release = q6_release, +}; + +struct miscdevice q6_control_device = { + .minor = MISC_DYNAMIC_MINOR, + .name = "msm_audio_ctl", + .fops = &q6_dev_fops, +}; + + +static int __init q6_audio_ctl_init(void) { + return misc_register(&q6_control_device); +} + +device_initcall(q6_audio_ctl_init); diff --git a/pool/shard002/C/0058679_rpmatch.c b/pool/shard002/C/0058679_rpmatch.c new file mode 100644 index 0000000000000000000000000000000000000000..8b4e332f2631c5c292111c68bf91c52b09dd45bf --- /dev/null +++ b/pool/shard002/C/0058679_rpmatch.c @@ -0,0 +1,64 @@ +/* Determine whether string value is affirmation or negative response + according to current locale's data. + This file is part of the GNU C Library. + Copyright (C) 1996, 1997, 2000, 2003 Free Software Foundation, Inc. + + 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, write to the Free + Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA + 02111-1307 USA. */ + +#include +#include +#include + + +int +rpmatch (response) + const char *response; +{ + /* Match against one of the response patterns, compiling the pattern + first if necessary. */ + auto int try (const int tag, const int match, const int nomatch, + const char **lastp, regex_t *re); + + int try (const int tag, const int match, const int nomatch, + const char **lastp, regex_t *re) + { + const char *pattern = nl_langinfo (tag); + if (pattern != *lastp) + { + /* The pattern has changed. */ + if (*lastp) + { + /* Free the old compiled pattern. */ + regfree (re); + *lastp = NULL; + } + /* Compile the pattern and cache it for future runs. */ + if (regcomp (re, pattern, REG_EXTENDED) != 0) + return -1; + *lastp = pattern; + } + + /* Try the pattern. */ + return regexec (re, response, 0, NULL, 0) == 0 ? match : nomatch; + } + + /* We cache the response patterns and compiled regexps here. */ + static const char *yesexpr, *noexpr; + static regex_t yesre, nore; + + return (try (YESEXPR, 1, 0, &yesexpr, &yesre) ?: + try (NOEXPR, 0, -1, &noexpr, &nore)); +} diff --git a/pool/shard002/C/0058683_mi_df.c b/pool/shard002/C/0058683_mi_df.c new file mode 100644 index 0000000000000000000000000000000000000000..95d9c79ddca3b306bb919f20980cacb21f0410ad --- /dev/null +++ b/pool/shard002/C/0058683_mi_df.c @@ -0,0 +1,35 @@ +#include +#include +#include +#include +#include +#include +#include "ficheros_basico.h" + + +int main (int argc, char *argv[]) { + int fdin, i = 0; + superblock *sb; + + if (argc < 2) + return -1; + if ((fdin = open (argv[1], O_RDWR)) < 0) + printf("[ERROR] No se pot obrir %s \n", argv[1]); + if ((sb = mmap(0, sizeof(superblock), PROT_READ | PROT_WRITE, MAP_SHARED, fdin, 0)) < 0) + printf("[ERROR] Error a l'assignació mmap!"); + + + printf ("Nom de la unitat: %s\n",sb->name); + + printf(" \t \t \t lliures \t ocupats \t total \n"); + printf("Blocs d'Inodes: \t %i \t %i \t %i \n", sb->qfb, (sb->tqb)-(sb->qfb), sb->tqb); + printf("Blocs de Dades: \t %i \t %i \t %i \n", sb->qfb, (sb->tqb)-(sb->qfb), sb->tqb); + + printf(" \t \t lliures \t ocupats \n"); + printf("Blocs d'Inodes: \t %i \t %i \n", ((sb->qfb)/(sb->tqb)), 1-((sb->qfb)/(sb->tqb)) ); + printf("Blocs de dades: \t %i \t %i \n", ((sb->qfb)/(sb->tqb)), 1-((sb->qfb)/(sb->tqb)) ); +} + + + + diff --git a/pool/shard002/C/0058685_LIF.c b/pool/shard002/C/0058685_LIF.c new file mode 100644 index 0000000000000000000000000000000000000000..48bf5cf9088d78caa5da22901dea6f0aed264ab2 --- /dev/null +++ b/pool/shard002/C/0058685_LIF.c @@ -0,0 +1,88 @@ +/* + * LIF.cpp + * + * Created on: Aug 4, 2008 + * Author: dcoates + */ + +// --------------------------------------------------- +// Common leaky integrate-and-fire layer routines +// --------------------------------------------------- + +#include "LIF.h" +#include "../include/pv_common.h" +#include "../utils/pv_random.h" + +#include +#include +#include +#include + +#ifdef _MSC_VER +#define inline _inline +#endif + +#define PARAMS(p) (((LIF_params*)l->params)->p) + +// Default handlers for a layer of leaky integrate-and-fire neurons. +static inline int update_f(PVLayer *l) +{ + int i; + const float Vth = PARAMS(LIF_V_TH_0); + + for (i = 0; i < l->numNeurons; i++) { + l->activity->data[i] = ((l->V[i] - Vth) > 0.0) ? 1.0 : 0.0; + l->V[i] -= l->activity->data[i] * l->V[i]; // reset cells that fired + } + + return 0; +} + +int LIF_update(PVLayer *l) +{ + int i; + float r = 0.0; + float phiAve = 0.0, phiMax = FLT_MIN, phiMin = FLT_MAX; + float VAve = 0.0, VMax = FLT_MIN, VMin = FLT_MAX; + + for (i = 0; i < l->numNeurons; i++) { + if (pv_random_prob() < PARAMS(LIF_NOISE_FREQ)) { + r = PARAMS(LIF_NOISE_AMP) * 2 * (pv_random_prob() - 0.5); + } + else r = 0.0; + + l->V[i] += PARAMS(LIF_DT_d_TAU) * (r + l->phi[PHI0][i] - l->V[i]); + l->V[i] = (l->V[i] < PARAMS(LIF_V_Min)) ? PARAMS(LIF_V_Min) : l->V[i]; // hard lower limit + + // Gather some statistics + // TODO - take into account extended border + phiAve += l->phi[0][i]; + if (l->phi[PHI0][i] < phiMin) phiMin = l->phi[PHI0][i]; + if (l->phi[PHI0][i] > phiMax) phiMax = l->phi[PHI0][i]; + + VAve += l->V[i]; + if (l->V[i] < VMin) VMin = l->V[i]; + if (l->V[i] > VMax) VMax = l->V[i]; + + //pv_log("V1 PHI %d=%f\n", i, phi[i]); + + // TODO - take into account extended border + l->phi[PHI0][i] = 0.0; + } + +#ifdef DEBUG_OUTPUT + { + char msg[128]; + sprintf(msg, "IF1: phi: Max: %1.4f, Avg=%1.4f Min=%1.4f\n", phiMax, phiAve + / l->numNeurons, phiMin); + pv_log(stderr, msg); + sprintf(msg, "IF1: V : Max: %1.4f, Avg=%1.4f Min=%1.4f\n", VMax, + VAve / l->numNeurons, VMin); + pv_log(stderr, msg); + } +#endif + + update_f(l); + + return 0; +} diff --git a/pool/shard002/C/0058688_py_net_dckeytab.c b/pool/shard002/C/0058688_py_net_dckeytab.c new file mode 100644 index 0000000000000000000000000000000000000000..cf43da71c60ea0e33309edcbe6e1f599eb804a9f --- /dev/null +++ b/pool/shard002/C/0058688_py_net_dckeytab.c @@ -0,0 +1,118 @@ +/* + Unix SMB/CIFS implementation. + Samba utility functions + + Copyright (C) Jelmer Vernooij 2008-2010 + Copyright (C) Kamen Mazdrashki 2009 + Copyright (C) Alexander Bokovoy 2012 + + 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 "includes.h" +#include "python/py3compat.h" +#include "py_net.h" +#include "libnet_export_keytab.h" + +void initdckeytab(void); + +static PyObject *py_net_export_keytab(py_net_Object *self, PyObject *args, PyObject *kwargs) +{ + struct libnet_export_keytab r; + TALLOC_CTX *mem_ctx; + const char *kwnames[] = { "keytab", "principal", NULL }; + NTSTATUS status; + r.in.principal = NULL; + + if (!PyArg_ParseTupleAndKeywords(args, kwargs, "s|z:export_keytab", discard_const_p(char *, kwnames), + &r.in.keytab_name, + &r.in.principal)) { + return NULL; + } + + mem_ctx = talloc_new(self->mem_ctx); + if (mem_ctx == NULL) { + PyErr_NoMemory(); + return NULL; + } + + status = libnet_export_keytab(self->libnet_ctx, mem_ctx, &r); + if (NT_STATUS_IS_ERR(status)) { + PyErr_SetString(PyExc_RuntimeError, + r.out.error_string?r.out.error_string:nt_errstr(status)); + talloc_free(mem_ctx); + return NULL; + } + + talloc_free(mem_ctx); + + Py_RETURN_NONE; +} + +static const char py_net_export_keytab_doc[] = "export_keytab(keytab, name)\n\n" +"Export the DC keytab to a keytab file."; + +static PyMethodDef export_keytab_method_table[] = { + {"export_keytab", (PyCFunction)py_net_export_keytab, METH_VARARGS|METH_KEYWORDS, py_net_export_keytab_doc}, + { NULL, NULL, 0, NULL } +}; + +/* + * A fake Python module to inject export_keytab() method into existing samba.net.Net class. + * Python enforces that every loaded module actually creates Python module record in + * the global module table even if we don't really need that record. Thus, we initialize + * dckeytab module but never use it. + * */ +void initdckeytab(void); +static struct PyModuleDef moduledef = { + PyModuleDef_HEAD_INIT, + .m_name = "dckeytab", + .m_doc = "dckeytab", + .m_size = -1, + .m_methods = NULL +}; + +MODULE_INIT_FUNC(dckeytab) +{ + PyObject *m = NULL; + PyObject *Net; + PyObject *descr; + int ret; + + m = PyModule_Create(&moduledef); + if (m == NULL) + return m; + + m = PyImport_ImportModule("samba.net"); + if (m == NULL) + return m; + + Net = (PyObject *)PyObject_GetAttrString(m, "Net"); + if (Net == NULL) + return m; + + descr = PyDescr_NewMethod((PyTypeObject*)Net, &export_keytab_method_table[0]); + if (descr == NULL) + return m; + + ret = PyDict_SetItemString(((PyTypeObject*)Net)->tp_dict, + export_keytab_method_table[0].ml_name, + descr); + if (ret != -1) { + Py_DECREF(descr); + } + + return m; +} diff --git a/pool/shard002/C/0058693_InitNiKom.c b/pool/shard002/C/0058693_InitNiKom.c new file mode 100644 index 0000000000000000000000000000000000000000..210f7774c7857df2b488c21d4771e76eba953376 --- /dev/null +++ b/pool/shard002/C/0058693_InitNiKom.c @@ -0,0 +1,232 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "NiKomStr.h" + +int deleteDir(char *dirname); + +struct Library *NiKomBase; + +/* A minimal user with name "Sysop" and password "sysop". */ +struct User userData = { + 0L,0L,0L,0L,0L,0L,0L,0L,0L,0L,0L,0L,0L,0L,0L,0L,0L,0L, + "Sysop","","","","","","hX62xN2A/dI0Q", + 100,25,0,"-->","","","" +}; +struct SysInfo sysInfo; +struct UnreadTexts unreadTexts; + +void createDirOrDie(char *dirname) { + BPTR lock; + struct FileInfoBlock __aligned fib; + + if(lock = Lock(dirname, ACCESS_READ)) { + if(!Examine(lock, &fib)) { + printf("Could not examine %s\n", dirname); + UnLock(lock); + exit(10); + } + UnLock(lock); + if(fib.fib_DirEntryType <= 0) { + printf("Can't create dir %s, there is a file with the same name.\n", dirname); + exit(10); + } + return; + } + if(!(lock=CreateDir(dirname))) { + printf("Couldn't create directory %s\n", dirname); + exit(10); + } + UnLock(lock); + printf("Created directory %s\n", dirname); +} + +void createFile(char *filename, void *data, int size) { + FILE *fp; + if(fp = fopen(filename, "w")) { + if(size > 0) { + fwrite(data, size, 1, fp); + } + fclose(fp); + } else { + printf("Could not write %s\n", filename); + exit(10); + } + printf("Created file %s\n", filename); +} + +void createZeroFilledFile(char *filename, int size) { + void *data; + + data = malloc(size); + memset(data, 0, size); + createFile(filename, data, size); + free(data); +} + +void createEmptyFile(char *filename) { + createFile(filename, NULL, 0); +} + +void initSysop(void) { + long tid; + + createDirOrDie("NiKom:Users"); + createDirOrDie("NiKom:Users/0"); + createDirOrDie("NiKom:Users/0/0"); + + time(&tid); + userData.forst_in=tid; + userData.senast_in=tid; + createFile("NiKom:Users/0/0/Data", &userData, sizeof(struct User)); + + unreadTexts.bitmapStartText = 0; + memset(unreadTexts.bitmap, 0xff, UNREADTEXTS_BITMAPSIZE/8); + memset(unreadTexts.lowestPossibleUnreadText, 0, MAXMOTE * sizeof(long)); + createFile("NiKom:Users/0/0/UnreadTexts", &unreadTexts, sizeof(struct UnreadTexts)); + + createFile("Nikom:Users/0/0/.firstletter", "0", 1); + createFile("Nikom:Users/0/0/.nextletter", "0", 1); +} + +void initFiles(void) { + initSysop(); + createDirOrDie("NiKom:DatoCfg"); + createDirOrDie("NiKom:Moten"); + createZeroFilledFile("NiKom:DatoCfg/Sysinfo.dat", sizeof(struct SysInfo)); + createEmptyFile("NiKom:DatoCfg/Möten.dat"); + createEmptyFile("NiKom:DatoCfg/ConferenceTexts.dat"); + createEmptyFile("NiKom:DatoCfg/Areor.dat"); + createEmptyFile("NiKom:DatoCfg/Grupper.dat"); + createZeroFilledFile("NiKom:DatoCfg/Senaste.dat", sizeof(struct Inloggning) * MAXSENASTE); +} + +int deleteFile(char *filename) { + BPTR lock; + + if(!(lock = Lock(filename, ACCESS_READ))) { + // Can't get lock, assume it doesn't exist. + return 1; + } + UnLock(lock); + if(!DeleteFile(filename)) { + printf("Couldn't delete file/dir '%s'\n", filename); + return 0; + } + printf("Deleted file/dir '%s'\n", filename); + return 1; +} + +void deleteFileOrDie(char *filename) { + if(!deleteFile(filename)) { + exit(10); + } +} + +int handleExAllResult(struct ExAllControl *ec, struct ExAllData *ed, char *dirname) { + char filename[100]; + int success; + if(ec->eac_Entries == 0) { + return 1; + } + while(ed != NULL) { + sprintf(filename, "%s/%s", dirname, ed->ed_Name); + if(ed->ed_Type < 0) { + success = deleteFile(filename); + } else { + success = deleteDir(filename); + } + if(!success) { + return 0; + } + ed=ed->ed_Next; + } + return 1; +} + +int deleteDir(char *dirname) { + char __aligned buffer[2048]; + struct ExAllControl *ec; + int moreFromExAll, success = TRUE; + BPTR lock; + + if(!(lock = Lock(dirname, ACCESS_READ))) { + return 1; + } + printf("Deleting all files in directory %s\n", dirname); + + ec = (struct ExAllControl *) AllocDosObject(DOS_EXALLCONTROL, NULL); + ec->eac_LastKey=0L; + ec->eac_MatchString=NULL; + ec->eac_MatchFunc=NULL; + do { + moreFromExAll = ExAll(lock, (struct ExAllData *)buffer, 2048, ED_TYPE, ec); + if(!handleExAllResult(ec, (struct ExAllData *) buffer, dirname)) { + success = FALSE; + break; + } + } while(moreFromExAll); + + UnLock(lock); + FreeDosObject(DOS_EXALLCONTROL,ec); + if(success) { + success = deleteFile(dirname); + } + return success; +} + +void deleteDirOrDie(char *dirname) { + if(!deleteDir(dirname)) { + exit(10); + } +} + +void clearFiles(void) { + deleteDirOrDie("NiKom:Users"); + deleteDirOrDie("NiKom:Moten"); + deleteFileOrDie("NiKom:DatoCfg/Sysinfo.dat"); + deleteFileOrDie("NiKom:DatoCfg/Möten.dat"); + deleteFileOrDie("NiKom:DatoCfg/ConferenceTexts.dat"); + deleteFileOrDie("NiKom:DatoCfg/Areor.dat"); + deleteFileOrDie("NiKom:DatoCfg/Grupper.dat"); + deleteFileOrDie("NiKom:DatoCfg/Senaste.dat"); +} + +int main(int argc, char **argv) { + char input[20]; + int count=0; + + printf("The following files/dirs will be reset/deleted:\n"); + printf(" Users\n"); + printf(" Moten\n"); + printf(" DatoCfg/Sysinfo.dat\n"); + printf(" DatoCfg/Möten.dat\n"); + printf(" DatoCfg/ConferenceTexts.dat\n"); + printf(" DatoCfg/Areor.dat\n"); + printf(" DatoCfg/Grupper.dat\n"); + printf(" DatoCfg/Senaste.dat\n\n"); + printf("Is this ok? (y/N) "); + while((input[count++] = getchar()) != '\n'); + if(input[0] != 'y' && input[0] != 'Y') { + printf("Nope!\n"); + return 0; + } + + printf("Yep!\n\n"); + printf("Creating files necessary for NiKom to start up, please wait...\n"); + fflush(stdout); + clearFiles(); + initFiles(); + printf("Done!\n"); + + return 0; +} + diff --git a/pool/shard002/C/0058697_mou_ps2.c b/pool/shard002/C/0058697_mou_ps2.c new file mode 100644 index 0000000000000000000000000000000000000000..39c82050a4255bcec0b99ecd7da86ce042be1a44 --- /dev/null +++ b/pool/shard002/C/0058697_mou_ps2.c @@ -0,0 +1,123 @@ +/* + * Copyright (c) 1999 Greg Haerr + * + * NULL Mouse Driver + */ +#include +#include "device.h" + +#define SCALE 3 /* default scaling factor for acceleration */ +#define THRESH 5 /* default threshhold for acceleration */ + +static int PS2M_Open(MOUSEDEVICE *pmd); +static void PS2M_Close(void); +static int PS2M_GetButtonInfo(void); +static void PS2M_GetDefaultAccel(int *pscale,int *pthresh); +static int PS2M_Read(MWCOORD *dx, MWCOORD *dy, MWCOORD *dz, int *bp); +static int PS2M_Poll(void); + +MOUSEDEVICE mousedev = { + PS2M_Open, + PS2M_Close, + PS2M_GetButtonInfo, + PS2M_GetDefaultAccel, + PS2M_Read, + PS2M_Poll +}; + +/* + * Poll for events + */ + +static int +PS2M_Poll(void) +{ + return Ps2MicePoll(); + //return 1; +} + +/* + * Open up the mouse device. + */ +static int +PS2M_Open(MOUSEDEVICE *pmd) +{ + //return -2; /* no mouse*/ + return 9; +} + +/* + * Close the mouse device. + */ +static void +PS2M_Close(void) +{ +} + +/* + * Get mouse buttons supported + */ +static int +PS2M_GetButtonInfo(void) +{ + return MWBUTTON_L | MWBUTTON_R; +} + +/* + * Get default mouse acceleration settings + */ +static void +PS2M_GetDefaultAccel(int *pscale,int *pthresh) +{ + *pscale = SCALE; + *pthresh = THRESH; +} +/* +#define SCREEN_WIDTH 800 +#define SCREEN_HIGHT 600 +*/ +/* + * Attempt to read bytes from the mouse and interpret them. + * Returns -1 on error, 0 if either no bytes were read or not enough + * was read for a complete state, or 1 if the new state was read. + * When a new state is read, the current buttons and x and y deltas + * are returned. This routine does not block. + */ +static int +PS2M_Read(MWCOORD *dx, MWCOORD *dy, MWCOORD *dz, int *bp) +{ + INT vdx, vdy, vdz, vdb; + INT buttons; + + if(Ps2MiceRead(&vdx, &vdy, &vdz, &vdb)) + { + if(vdx <-10) + vdx = -10; + if(vdy < -10) + vdy = -10; + if(vdx >10) + vdx = 10; + if(vdy >10) + vdy = 10; + + buttons = 0; + if(vdb & 0x1) + buttons |= MWBUTTON_L; + if(vdb & 0x2) + buttons |= MWBUTTON_R; + *bp = buttons; + + *dx = vdy; + *dy = -vdx; + *dz = 0; + /* YIRtlKernelMsg("<%2x,%2x,%2x>", vdx, vdy, vdb);*/ + return 1; + } + + //YIRtlKernelMsg("[%d,%d]", x, y); + /**dx = Rand()%(200); + *dy = Rand()%(200);*/ + + return 0; +} + diff --git a/pool/shard002/C/0058700_read_write_dev.c b/pool/shard002/C/0058700_read_write_dev.c new file mode 100644 index 0000000000000000000000000000000000000000..dbb4bc18dcc501dc4a943d837c2b981a2cd5fd57 --- /dev/null +++ b/pool/shard002/C/0058700_read_write_dev.c @@ -0,0 +1,169 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +#define CHDEV_DEBUG +#undef PDEBUG /* undef it, just in case */ +#ifdef CHDEV_DEBUG + #ifdef __KERNEL__ + /* This one if debugging is on, and kernel space */ + #define PDEBUG(fmt,args...) printk(KERN_EMERG "chdev: " fmt,## args) + #else + /* This one for user space */ + #define PDEBUG(fmt, args…) fprintf(stderr, fmt, ## args) + #endif +#else + #define PDEBUG(fmt, args…) /* not debugging: nothing */ +#endif + + + +static int chdev_major = 0;// major dev number +static int chdev_minor = 0;// minor dev number +static int chdev_nr_devs = 4;// +static struct cdev *chdev_cdev; +static struct class *chdev_class; +static struct device *chdev_device; +static unsigned char chdev_buff[4]; + +static void __exit chdev_exit(void); +static int __init chdev_init(void); +static int chdev_open(struct inode *inode, struct file *file); +static ssize_t chdev_read(struct file *filp, char __user *buff, size_t count, loff_t *f_pos); +static ssize_t chdev_write(struct file *filp, const char __user *buff, size_t count, loff_t *offp); +static int chdev_close(struct inode *inode, struct file *file); +static void chdev_setup_cdev(struct cdev *temp,int index); + +module_param(chdev_major,int,S_IRUGO); +module_init(chdev_init); +module_exit(chdev_exit); + +MODULE_AUTHOR("Bear 965006619@qq.com"); +MODULE_DESCRIPTION("prj 6"); +MODULE_LICENSE("GPL"); + +struct file_operations chdev_fops = +{ + .owner = THIS_MODULE, + .open = chdev_open, + .read = chdev_read, + .write = chdev_write, + .release = chdev_close +}; + + +static int chdev_open(struct inode *inode, struct file *file) +{ + PDEBUG("open\n"); + return 0; +} + +static ssize_t chdev_read(struct file *filp, char __user *buff, size_t count, loff_t *f_pos) +{ + unsigned long ret; + PDEBUG("read\n"); + ret = copy_to_user(buff,chdev_buff,4); + if( 0 > ret ) + { + PDEBUG("copy fail %lu data\n",ret); + } + return 0; +} + +static ssize_t chdev_write(struct file *filp, const char __user *buff, size_t count, loff_t *offp) +{ + unsigned long ret; + PDEBUG("write"); + ret = copy_from_user(chdev_buff,buff,4); + if( 0 > ret ) + { + PDEBUG("copy fail %lu data\n",ret); + } + return 0; +} + +static int chdev_close(struct inode *inode, struct file *file) +{ + PDEBUG("close\n"); + return 0; +} + +static int __init chdev_init(void) +{ + int ret; + int i; + dev_t dev = 0; + + PDEBUG("init\n"); + if(chdev_major) + { + dev = MKDEV(chdev_major,chdev_minor); + ret = register_chrdev_region(dev,chdev_nr_devs,"chdev"); + } + else + { + ret = alloc_chrdev_region(&dev,0,chdev_nr_devs,"chdev"); + chdev_major = MAJOR(dev); + } + if(ret < 0) + { + printk("can't register major number\n"); + goto ERR; + } + + PDEBUG("major %d \n",chdev_major); + chdev_cdev = cdev_alloc(); + chdev_cdev->ops = &chdev_fops; + chdev_cdev->owner = THIS_MODULE; + for( i = 0 ; i < chdev_nr_devs ; i++ ) + chdev_setup_cdev(chdev_cdev,chdev_minor + i); + + chdev_class = class_create(THIS_MODULE, "chdev"); + chdev_device = device_create(chdev_class, NULL, MKDEV(chdev_major, 0), NULL, "chdev"); + + + return 0; + +ERR: + chdev_exit(); + return 1; +} + +static void __exit chdev_exit(void) +{ + dev_t dev = MKDEV(chdev_major,chdev_minor); + printk("chdev_exit\n"); + + device_unregister(chdev_device); + class_destroy(chdev_class); + + cdev_del(chdev_cdev); + unregister_chrdev_region(dev,chdev_nr_devs); +} + + +static void chdev_setup_cdev(struct cdev *temp,int index) +{ + dev_t devno; + int ret; + devno = MKDEV(chdev_major,index); + PDEBUG("devno %u \n",devno); + PDEBUG("index %d \n",index); + + ret = cdev_add (chdev_cdev, devno, 1); + if(ret < 0) + { + printk("cdev add fail\n"); + } +} + + diff --git a/pool/shard002/C/0058701_dvbctrl.c b/pool/shard002/C/0058701_dvbctrl.c new file mode 100644 index 0000000000000000000000000000000000000000..0558435b5b011fda17128854606a070f579fe392 --- /dev/null +++ b/pool/shard002/C/0058701_dvbctrl.c @@ -0,0 +1,55 @@ +/* + * vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4 foldmethod=marker: + * + * dvbctrl.c + * + * Started: Sunday 27 July 2014, 06:07:48 + * Last Modified: Tuesday 12 August 2014, 05:43:12 + * + * Copyright (c) 2014 Chris Allison chris.allison@hotmail.com + * + * This file is part of cristel. + * + * cristel 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. + * + * cristel 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 cristel. If not, see . + */ + +#include "dvbctrl.h" + +void doCommand(char cmd) +{ + int nlines; + + nlines=request(cmd); + DBGL("%d lines recieved for request %s",nlines,cmd); +} +void lsjunk()/*{{{*/ +{ + int nlines; + char cmd[]="lsjunk"; + + nlines=request(cmd); + DBGL("%d lines recieved for request %s",nlines,cmd); + DBGL("%s",rcvbuf); + clear_dvbcmsg(); +}/*}}}*/ +void lssfs()/*{{{*/ +{ + int nlines; + + sprintf(line,"lssfs"); + nlines=request(line); + DBGL("%d lines recieved for request lssfs",nlines); + DBGL("%s",rcvbuf); + clear_dvbcmsg(); +}/*}}}*/ diff --git a/pool/shard002/C/0058703_gtkutils.c b/pool/shard002/C/0058703_gtkutils.c new file mode 100644 index 0000000000000000000000000000000000000000..cd166a9129bdce92758df0aaa59cba8382184920 --- /dev/null +++ b/pool/shard002/C/0058703_gtkutils.c @@ -0,0 +1,301 @@ +/* + * Ayttm + * + * Copyright (C) 2003, the Ayttm team + * + * Ayttm is derivative of Everybuddy + * Copyright (C) 1999-2002, Torrey Searle + * + * 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 "gtkutils.h" +#include "gtk_globals.h" +#include "account.h" + +static void s_set_option(GtkWidget *inWidget, int *ioData) +{ + *ioData = !(*ioData); +} + +GtkWidget *gtkut_button(const char *inText, int *inValue, GtkWidget *inPage, + GtkAccelGroup *inAccelGroup) +{ + GtkWidget *button = gtk_check_button_new_with_mnemonic(inText); + + assert(inValue != NULL); + + gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(button), *inValue); + gtk_box_pack_start(GTK_BOX(inPage), button, FALSE, FALSE, 0); + g_signal_connect(button, "clicked", G_CALLBACK(s_set_option), inValue); + gtk_widget_show(button); + + return (button); +} + +GtkWidget *gtkut_create_icon_widget(const char **inXPM, GtkWidget *inParent) +{ + GtkWidget *iconwid = NULL; + GdkPixbuf *buf = NULL; + + buf = gdk_pixbuf_new_from_xpm_data(inXPM); + iconwid = gtk_image_new_from_pixbuf(buf); + gtk_widget_show(iconwid); + + return (iconwid); +} + +GtkWidget *gtkut_stock_button_new_with_label(const char *label, + const char *stock) +{ + GtkWidget *hbox = gtk_hbox_new(FALSE, 5); + GtkWidget *button = gtk_button_new(); + GtkWidget *iconwid = + gtk_image_new_from_stock(stock, GTK_ICON_SIZE_BUTTON); + GtkWidget *labelwid = gtk_label_new(label); + + gtk_box_pack_start(GTK_BOX(hbox), iconwid, FALSE, FALSE, 2); + gtk_box_pack_start(GTK_BOX(hbox), labelwid, FALSE, FALSE, 2); + gtk_container_add(GTK_CONTAINER(button), hbox); + + gtk_widget_show(iconwid); + gtk_widget_show(labelwid); + gtk_widget_show(hbox); + gtk_widget_show(button); + + return button; +} + +GtkWidget *gtkut_create_icon_button(const char *inLabel, const char **inXPM, + GtkWidget *inParent) +{ + GtkWidget *button = NULL; + GtkWidget *label = NULL; + GtkWidget *hbox = NULL; + GtkWidget *iconwid = NULL; + GtkStyle *style = NULL; + const int min_width = 80; + int width = min_width; + int height = -1; + int using_label = (inLabel != NULL); + + if (using_label) { + hbox = gtk_hbox_new(FALSE, 0); + gtk_widget_show(hbox); + } + + style = gtk_widget_get_style(inParent); + + iconwid = gtkut_create_icon_widget(inXPM, inParent); + height = gdk_pixbuf_get_height(gtk_image_get_pixbuf(GTK_IMAGE(iconwid))) + + 5; + + if (using_label) { + gtk_box_pack_start(GTK_BOX(hbox), iconwid, FALSE, FALSE, 0); + + label = gtk_label_new(inLabel); + gtk_widget_show(label); + gtk_box_pack_start(GTK_BOX(hbox), label, TRUE, TRUE, 0); + } + + button = gtk_button_new(); + if (using_label) { + gtk_container_add(GTK_CONTAINER(button), hbox); + + if (button->requisition.width > width) + width = button->requisition.width; + gtk_widget_set_size_request(button, width, height); + } else { + gtk_container_add(GTK_CONTAINER(button), iconwid); + } + + gtk_widget_show(button); + + return (button); +} + +void gtkut_set_pixbuf(eb_local_account *ela, const char **inXPM, + GdkPixbuf **outPixbuf) +{ + + if ((inXPM == NULL) || (*outPixbuf == NULL)) + return; + /* + * FIXME: This is slowing things down for now as it compulsarily + * reloads the pixbuf everytime regardless of whether it has changed + * or not + */ + *outPixbuf = gdk_pixbuf_new_from_xpm_data(inXPM); +} + +void gtkut_set_pixbuf_from_xpm(const char **inXPM, GdkPixbuf **outPixbuf) +{ + if ((inXPM == NULL) || (*outPixbuf == NULL)) + return; + +#ifndef __MINGW32__ + *outPixbuf = gdk_pixbuf_new_from_xpm_data(inXPM); +#endif +} + +void gtkut_widget_get_uposition(GtkWidget *inWidget, int *outXpos, int *outYpos) +{ + int x = 0; + int y = 0; + int sx = 0; + int sy = 0; + + if (outXpos != NULL) + *outXpos = 0; + + if (outYpos != NULL) + *outYpos = 0; + + if ((inWidget == NULL) || (inWidget->window == NULL)) + return; + + sx = gdk_screen_width(); + sy = gdk_screen_height(); + + gdk_window_get_root_origin(inWidget->window, &x, &y); + + x %= sx; + if (x < 0) + x = 0; + + y %= sy; + if (y < 0) + y = 0; + + if (outXpos != NULL) + *outXpos = x; + + if (outYpos != NULL) + *outYpos = y; +} + +GtkWidget *gtkut_create_label_button(const char *inButtonText, + GCallback inSignalFunc, void *inCallbackData) +{ + GtkWidget *button = NULL; + + button = gtk_button_new_with_mnemonic(inButtonText); + gtk_widget_show(button); + + g_signal_connect(button, "clicked", inSignalFunc, inCallbackData); + + return (button); +} + +GSList *gtkut_add_radio_button_to_group(GSList *ioGroup, GtkWidget *inParentBox, + const char *inButtonText, int inIsSelected, + GCallback inSignalFunc, void *inCallbackData) +{ + GtkWidget *radio = NULL; + + if (inButtonText == NULL) + radio = gtk_radio_button_new(ioGroup); + else + radio = gtk_radio_button_new_with_label(ioGroup, inButtonText); + + gtk_widget_show(radio); + + gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(radio), inIsSelected); + + gtk_box_pack_start(GTK_BOX(inParentBox), radio, FALSE, FALSE, 0); + + g_signal_connect(radio, "clicked", inSignalFunc, inCallbackData); + + return (gtk_radio_button_get_group(GTK_RADIO_BUTTON(radio))); +} + +GtkWidget *gtkut_check_button(GtkWidget *inParentBox, const char *inButtonText, + int inIsSelected, GCallback inSignalFunc, void *inCallbackData) +{ + GtkWidget *button = NULL; + + if (inButtonText == NULL) + button = gtk_check_button_new(); + else + button = gtk_check_button_new_with_mnemonic(inButtonText); + + gtk_widget_show(button); + + gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(button), inIsSelected); + + gtk_box_pack_start(GTK_BOX(inParentBox), button, FALSE, FALSE, 0); + + g_signal_connect(GTK_OBJECT(button), "clicked", inSignalFunc, + inCallbackData); + + return (button); +} + +GtkWidget *gtkut_create_menu_button(GtkMenu *inMenu, const char *inLabel, + GCallback inSignalFunc, void *inCallbackData) +{ + GtkWidget *button = NULL; + + assert(inMenu != NULL); + + if (inLabel == NULL) + button = gtk_menu_item_new(); + else + button = gtk_menu_item_new_with_label(inLabel); + + if (inSignalFunc != NULL) + g_signal_connect(button, "activate", inSignalFunc, + inCallbackData); + + gtk_menu_shell_append(GTK_MENU_SHELL(inMenu), button); + gtk_widget_show(button); + + return (button); +} + +GtkWidget *gtkut_attach_submenu(GtkMenu *inMenu, const char *inLabel, + GtkWidget *inSubmenu, int inActive) +{ + GtkWidget *button = NULL; + + if (inLabel == NULL) + button = gtk_menu_item_new(); + else + button = gtk_menu_item_new_with_label(inLabel); + + gtk_widget_set_sensitive(button, inActive); + + gtk_menu_shell_append(GTK_MENU_SHELL(inMenu), button); + + gtk_menu_item_set_submenu(GTK_MENU_ITEM(button), inSubmenu); + gtk_widget_show(button); + + return (button); +} + +void gtkut_set_window_icon(GtkWindow *inWindow, const gchar **inXPM) +{ + GdkPixbuf *the_pixbuf = NULL; + + if (inXPM != NULL) { + the_pixbuf = gdk_pixbuf_new_from_xpm_data(inXPM); + gtk_window_set_icon(inWindow, the_pixbuf); + } +} diff --git a/pool/shard002/C/0058714_pspinlock.c b/pool/shard002/C/0058714_pspinlock.c new file mode 100644 index 0000000000000000000000000000000000000000..e5a5545227b6a7bb97a4b13fb5cf124d8eaa807c --- /dev/null +++ b/pool/shard002/C/0058714_pspinlock.c @@ -0,0 +1,82 @@ +/* POSIX spinlock implementation. hppa version. + Copyright (C) 2000 Free Software Foundation, Inc. + This file is part of the GNU C Library. + + 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; see the file COPYING.LIB. If not, + write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, + Boston, MA 02111-1307, USA. */ + +#include +#include +#include "internals.h" + +int +__pthread_spin_lock (pthread_spinlock_t *lock) +{ + volatile unsigned int *addr = __ldcw_align (lock); + + while (__ldcw (addr) == 0) + while (*addr == 0) ; + + return 0; +} +weak_alias (__pthread_spin_lock, pthread_spin_lock) + + +int +__pthread_spin_trylock (pthread_spinlock_t *lock) +{ + volatile unsigned int *a = __ldcw_align (lock); + + return __ldcw (a) ? 0 : EBUSY; +} +weak_alias (__pthread_spin_trylock, pthread_spin_trylock) + + +int +__pthread_spin_unlock (pthread_spinlock_t *lock) +{ + volatile unsigned int *a = __ldcw_align (lock); + int tmp = 1; + /* This should be a memory barrier to newer compilers */ + __asm__ __volatile__ ("stw,ma %1,0(%0)" + : : "r" (a), "r" (tmp) : "memory"); + return 0; +} +weak_alias (__pthread_spin_unlock, pthread_spin_unlock) + + +int +__pthread_spin_init (pthread_spinlock_t *lock, int pshared) +{ + /* We can ignore the `pshared' parameter. Since we are busy-waiting + all processes which can access the memory location `lock' points + to can use the spinlock. */ + volatile unsigned int *a = __ldcw_align (lock); + int tmp = 1; + /* This should be a memory barrier to newer compilers */ + __asm__ __volatile__ ("stw,ma %1,0(%0)" + : : "r" (a), "r" (tmp) : "memory"); + return 0; +} +weak_alias (__pthread_spin_init, pthread_spin_init) + + +int +__pthread_spin_destroy (pthread_spinlock_t *lock) +{ + /* Nothing to do. */ + return 0; +} +weak_alias (__pthread_spin_destroy, pthread_spin_destroy) diff --git a/pool/shard002/C/0058719_entity.c b/pool/shard002/C/0058719_entity.c new file mode 100644 index 0000000000000000000000000000000000000000..803bb70eec922423b583effbe375e1eec50a1f32 --- /dev/null +++ b/pool/shard002/C/0058719_entity.c @@ -0,0 +1,195 @@ +/* + +----------------------------------------------------------------------+ + | PHP Version 5 | + +----------------------------------------------------------------------+ + | Copyright (c) 1997-2014 The PHP Group | + +----------------------------------------------------------------------+ + | This source file is subject to version 3.01 of the PHP 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.php.net/license/3_01.txt | + | If you did not receive a copy of the PHP license and are unable to | + | obtain it through the world-wide-web, please send a note to | + | license@php.net so we can mail you a copy immediately. | + +----------------------------------------------------------------------+ + | Authors: Christian Stocker | + | Rob Richards | + +----------------------------------------------------------------------+ +*/ + +/* $Id$ */ + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +#include "php.h" +#if HAVE_LIBXML && HAVE_DOM +#include "php_dom.h" + + +/* +* class DOMEntity extends DOMNode +* +* URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#ID-527DCFF2 +* Since: +*/ + +const zend_function_entry php_dom_entity_class_functions[] = { + PHP_FE_END +}; + +/* {{{ publicId string +readonly=yes +URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#ID-D7303025 +Since: +*/ +int dom_entity_public_id_read(dom_object *obj, zval **retval TSRMLS_DC) +{ + xmlEntity *nodep; + + nodep = (xmlEntity *) dom_object_get_node(obj); + + if (nodep == NULL) { + php_dom_throw_error(INVALID_STATE_ERR, 0 TSRMLS_CC); + return FAILURE; + } + + ALLOC_ZVAL(*retval); + if (nodep->etype != XML_EXTERNAL_GENERAL_UNPARSED_ENTITY) { + ZVAL_NULL(*retval); + } else { + ZVAL_STRING(*retval, (char *) (nodep->ExternalID), 1); + } + + return SUCCESS; +} + +/* }}} */ + +/* {{{ systemId string +readonly=yes +URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#ID-D7C29F3E +Since: +*/ +int dom_entity_system_id_read(dom_object *obj, zval **retval TSRMLS_DC) +{ + xmlEntity *nodep; + + nodep = (xmlEntity *) dom_object_get_node(obj); + + if (nodep == NULL) { + php_dom_throw_error(INVALID_STATE_ERR, 0 TSRMLS_CC); + return FAILURE; + } + + ALLOC_ZVAL(*retval); + if (nodep->etype != XML_EXTERNAL_GENERAL_UNPARSED_ENTITY) { + ZVAL_NULL(*retval); + } else { + ZVAL_STRING(*retval, (char *) (nodep->SystemID), 1); + } + + return SUCCESS; +} + +/* }}} */ + +/* {{{ notationName string +readonly=yes +URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#ID-6ABAEB38 +Since: +*/ +int dom_entity_notation_name_read(dom_object *obj, zval **retval TSRMLS_DC) +{ + xmlEntity *nodep; + char *content; + + nodep = (xmlEntity *) dom_object_get_node(obj); + + if (nodep == NULL) { + php_dom_throw_error(INVALID_STATE_ERR, 0 TSRMLS_CC); + return FAILURE; + } + + ALLOC_ZVAL(*retval); + if (nodep->etype != XML_EXTERNAL_GENERAL_UNPARSED_ENTITY) { + ZVAL_NULL(*retval); + } else { + content = xmlNodeGetContent((xmlNodePtr) nodep); + ZVAL_STRING(*retval, content, 1); + xmlFree(content); + } + + return SUCCESS; +} + +/* }}} */ + +/* {{{ actualEncoding string +readonly=no +URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#Entity3-actualEncoding +Since: DOM Level 3 +*/ +int dom_entity_actual_encoding_read(dom_object *obj, zval **retval TSRMLS_DC) +{ + ALLOC_ZVAL(*retval); + ZVAL_NULL(*retval); + return SUCCESS; +} + +int dom_entity_actual_encoding_write(dom_object *obj, zval *newval TSRMLS_DC) +{ + return SUCCESS; +} + +/* }}} */ + +/* {{{ encoding string +readonly=no +URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#Entity3-encoding +Since: DOM Level 3 +*/ +int dom_entity_encoding_read(dom_object *obj, zval **retval TSRMLS_DC) +{ + ALLOC_ZVAL(*retval); + ZVAL_NULL(*retval); + return SUCCESS; +} + +int dom_entity_encoding_write(dom_object *obj, zval *newval TSRMLS_DC) +{ + return SUCCESS; +} + +/* }}} */ + +/* {{{ version string +readonly=no +URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#Entity3-version +Since: DOM Level 3 +*/ +int dom_entity_version_read(dom_object *obj, zval **retval TSRMLS_DC) +{ + ALLOC_ZVAL(*retval); + ZVAL_NULL(*retval); + return SUCCESS; +} + +int dom_entity_version_write(dom_object *obj, zval *newval TSRMLS_DC) +{ + return SUCCESS; +} + +/* }}} */ + +#endif + +/* + * Local variables: + * tab-width: 4 + * c-basic-offset: 4 + * End: + * vim600: noet sw=4 ts=4 fdm=marker + * vim<600: noet sw=4 ts=4 + */ diff --git a/pool/shard002/C/0058729_scheduler.c b/pool/shard002/C/0058729_scheduler.c new file mode 100644 index 0000000000000000000000000000000000000000..f8554643757bda8ab4df5f23ed477d19b632c13f --- /dev/null +++ b/pool/shard002/C/0058729_scheduler.c @@ -0,0 +1,110 @@ +/* + * This file is part of ROCKCLOCK firmware. + * + * Copyright (c) 2015 Alexander Kühn + * + * 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 . + */ + +/* external standard includes */ +#include + +/* external includes */ + +/* project includes */ +#include "../hal/timer_if.h" + +/* component includes */ +#include "scheduler_if.h" +#include "scheduler.h" +#include "../schedule_table.h" + + +/** @brief calculate number of elements in scheduler table + * + */ +#define SCHEDULETABLE_SIZE (sizeof(scheduletable)/sizeof(scheduletable[0])) + +static const scheduletable_t scheduletable[] = schedule_cb_table; /**< constant instance of scheduler table */ +static const uint8_t scheduletable_size = SCHEDULETABLE_SIZE; /**< precalculated number of elements in schedule table */ + +static uint32_t tickstart[SCHEDULETABLE_SIZE]; /**< table for last execution time tick */ +static schedule_ctrl_state_t scheduler_state[SCHEDULETABLE_SIZE]; /**< table for actual task state */ +static uint8_t schedule_runflag[SCHEDULETABLE_SIZE]; /**< mark table for upcoming running tasks */ + + +void scheduler_init() +{ + uint8_t i; + + /* initialize the scheduling time tables */ + for( i = 0; i < scheduletable_size; i++ ) + { + tickstart[i] = timer_get(); + schedule_runflag[i] = 0; + scheduler_state[i] = SCHED_RUN; + } +} + + +void scheduler_process() +{ + uint8_t i; + uint32_t tickend, tickdiff; + uint32_t period; + + + tickend = timer_get(); + /* evaluation and execution of scheduled tasks is splitted to + * obtain consistent timeline + */ + + /* evaluate which tasks should be executed and mark them */ + for( i = 0; i < scheduletable_size; i++ ) + { + + + period = scheduletable[i].period; + + tickdiff = tickend - tickstart[i]; + if( tickdiff >= period ) + { + tickstart[i] = tickend; + schedule_runflag[i] = 1; + } + } + + /* execute the tasks, which are marked for running */ + for( i = 0; i < scheduletable_size; i++ ) + { + if( (schedule_runflag[i] == 1) && + (scheduletable[i].periodic_cb != 0) + ) + { + if( scheduler_state[i] == SCHED_RUN ) + { + scheduletable[i].periodic_cb(); + } + schedule_runflag[i] = 0; + } + } +} + +void scheduler_control( uint8_t processid, schedule_ctrl_state_t controlcmd ) +{ + if( processid < SCHEDULETABLE_SIZE ) + { + scheduler_state[processid] = controlcmd; + } +} diff --git a/pool/shard002/C/0058731_phy-qcom-ipq4019-usb.c b/pool/shard002/C/0058731_phy-qcom-ipq4019-usb.c new file mode 100644 index 0000000000000000000000000000000000000000..465f0d3a01e61aa8e9863553f14a4099ec6b83fc --- /dev/null +++ b/pool/shard002/C/0058731_phy-qcom-ipq4019-usb.c @@ -0,0 +1,145 @@ +// SPDX-License-Identifier: GPL-2.0 +/* + * Copyright (c) 2019 Sartura Ltd. + * + * Author: Robert Marko + * + * Based on Linux driver + */ + +#include +#include +#include +#include +#include +#include +#include +#include + +struct ipq4019_usb_phy { + phys_addr_t base; + struct reset_ctl por_rst; + struct reset_ctl srif_rst; +}; + +static int ipq4019_ss_phy_power_off(struct phy *_phy) +{ + struct ipq4019_usb_phy *phy = dev_get_priv(_phy->dev); + + reset_assert(&phy->por_rst); + mdelay(10); + + return 0; +} + +static int ipq4019_ss_phy_power_on(struct phy *_phy) +{ + struct ipq4019_usb_phy *phy = dev_get_priv(_phy->dev); + + ipq4019_ss_phy_power_off(_phy); + + reset_deassert(&phy->por_rst); + + return 0; +} + +static struct phy_ops ipq4019_usb_ss_phy_ops = { + .power_on = ipq4019_ss_phy_power_on, + .power_off = ipq4019_ss_phy_power_off, +}; + +static int ipq4019_usb_ss_phy_probe(struct udevice *dev) +{ + struct ipq4019_usb_phy *phy = dev_get_priv(dev); + int ret; + + phy->base = dev_read_addr(dev); + if (phy->base == FDT_ADDR_T_NONE) + return -EINVAL; + + ret = reset_get_by_name(dev, "por_rst", &phy->por_rst); + if (ret) + return ret; + + return 0; +} + +static const struct udevice_id ipq4019_usb_ss_phy_ids[] = { + { .compatible = "qcom,usb-ss-ipq4019-phy" }, + { } +}; + +U_BOOT_DRIVER(ipq4019_usb_ss_phy) = { + .name = "ipq4019-usb-ss-phy", + .id = UCLASS_PHY, + .of_match = ipq4019_usb_ss_phy_ids, + .ops = &ipq4019_usb_ss_phy_ops, + .probe = ipq4019_usb_ss_phy_probe, + .priv_auto_alloc_size = sizeof(struct ipq4019_usb_phy), +}; + +static int ipq4019_hs_phy_power_off(struct phy *_phy) +{ + struct ipq4019_usb_phy *phy = dev_get_priv(_phy->dev); + + reset_assert(&phy->por_rst); + mdelay(10); + + reset_assert(&phy->srif_rst); + mdelay(10); + + return 0; +} + +static int ipq4019_hs_phy_power_on(struct phy *_phy) +{ + struct ipq4019_usb_phy *phy = dev_get_priv(_phy->dev); + + ipq4019_hs_phy_power_off(_phy); + + reset_deassert(&phy->srif_rst); + mdelay(10); + + reset_deassert(&phy->por_rst); + + return 0; +} + +static struct phy_ops ipq4019_usb_hs_phy_ops = { + .power_on = ipq4019_hs_phy_power_on, + .power_off = ipq4019_hs_phy_power_off, +}; + +static int ipq4019_usb_hs_phy_probe(struct udevice *dev) +{ + struct ipq4019_usb_phy *phy = dev_get_priv(dev); + int ret; + + phy->base = dev_read_addr(dev); + if (phy->base == FDT_ADDR_T_NONE) + return -EINVAL; + + ret = reset_get_by_name(dev, "por_rst", &phy->por_rst); + if (ret) + return ret; + + ret = reset_get_by_name(dev, "srif_rst", &phy->srif_rst); + if (ret) + return ret; + + return 0; +} + +static const struct udevice_id ipq4019_usb_hs_phy_ids[] = { + { .compatible = "qcom,usb-hs-ipq4019-phy" }, + { } +}; + +U_BOOT_DRIVER(ipq4019_usb_hs_phy) = { + .name = "ipq4019-usb-hs-phy", + .id = UCLASS_PHY, + .of_match = ipq4019_usb_hs_phy_ids, + .ops = &ipq4019_usb_hs_phy_ops, + .probe = ipq4019_usb_hs_phy_probe, + .priv_auto_alloc_size = sizeof(struct ipq4019_usb_phy), +}; diff --git a/pool/shard002/C/0058733_test.c b/pool/shard002/C/0058733_test.c new file mode 100644 index 0000000000000000000000000000000000000000..0c04e7e8aae8562b0408ef82ed6217d97a48808e --- /dev/null +++ b/pool/shard002/C/0058733_test.c @@ -0,0 +1,98 @@ +#include +#include +#include +#include + +void masstest(isotope_t *isotope) { + fprintf(stderr, "Mass of %s is %lf u and abundance %lf\n", isotope->name, isotope->mass, isotope->abundance); +} + +int test1(int Z1, int Z2) { /* Example of "advanced" assignments. */ + double v; + gsto_table_t *table; + table=gsto_init(91, "stoppings.txt"); /* This allocates memory for file assignments and loads in the list of available stopping files */ + if(!table) { + fprintf(stderr, "Could not init stopping table!\n"); + return 0; + } + gsto_print_files(table); /* Prints list of files */ + gsto_add_file(table, "verygoodcarbon", "carbon.tot", 1, 92, 6, 6, "total"); + gsto_print_files(table); /* Prints list of files, again, now with carbon stopping as well */ + gsto_auto_assign(table, Z1, Z2); /* This assigns only a partial Z1, Z2 list (in this case ONLY the stopping user requested in arguments */ + gsto_print_assignments(table); /* Printing the list of assignments */ + gsto_auto_assign_range(table, 1, 91, 1, 91); /* This assigns Z1=1...91 and Z2=1...91 all possible combinations. */ + gsto_print_assignments(table); /* Print the list of assignments, again, now with all possible stoppings */ + gsto_load(table); /* After this all assigned stoppings are read from appropriate files */ + + for(v=0; v<3e8; v+= 1000) { + printf("%lf %lf\n", v, gsto_sto_v(table, Z1, Z2, v)); + } + return 1; +} + +int test2(int Z1, int Z2, double v_min, double v_max, int points) { /* Simple example of extracting tabulated (linearly spaced in velocity-space) stopping data */ + double v_step=(v_max-v_min)/(points-1.0); + int i; + gsto_table_t *table; + double *stop=malloc(sizeof(double)*points); + + /* Only three lines of code to initialize stopping table! */ + table=gsto_init(91, "stoppings.txt"); + gsto_auto_assign(table, Z1, Z2); + gsto_load(table); + + stop=gsto_sto_v_table(table, Z1, Z2, v_min, v_max, points); + for(i=0; imass); + printf("%e %e\n", E, gsto_sto_v(table, Z1, Z2, v)); + } + gsto_print_files(table); + free(stop); + gsto_deallocate(table); + return 1; +} + +int main(int argc, char **argv) { + if(argc != 4) { + fprintf(stderr, "Wrong number of arguments!\n"); + return 0; + } + int Z1=strtol(argv[1], NULL, 10); + int Z2=strtol(argv[2], NULL, 10); + int A1=strtol(argv[3], NULL, 10); + return test3(Z1, A1, Z2, 10*KEV, 10.0010*MEV, 10001); + +} diff --git a/pool/shard002/C/0058735_chip.c b/pool/shard002/C/0058735_chip.c new file mode 100644 index 0000000000000000000000000000000000000000..f8033485db93a878ad41133c0383baa16420d026 --- /dev/null +++ b/pool/shard002/C/0058735_chip.c @@ -0,0 +1,220 @@ +/* + * Linux driver for TerraTec DMX 6Fire USB + * + * Main routines and module definitions. + * + * Author: Torsten Schenk + * Created: Jan 01, 2011 + * Copyright: (C) Torsten Schenk + * + * 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 "chip.h" +#include "firmware.h" +#include "pcm.h" +#include "control.h" +#include "comm.h" +#include "midi.h" + +#include +#include +#include +#include +#include +#include + +MODULE_AUTHOR("Torsten Schenk "); +MODULE_DESCRIPTION("TerraTec DMX 6Fire USB audio driver"); +MODULE_LICENSE("GPL v2"); +MODULE_SUPPORTED_DEVICE("{{TerraTec, DMX 6Fire USB}}"); + +static int index[SNDRV_CARDS] = SNDRV_DEFAULT_IDX; /* Index 0-max */ +static char *id[SNDRV_CARDS] = SNDRV_DEFAULT_STR; /* Id for card */ +static bool enable[SNDRV_CARDS] = SNDRV_DEFAULT_ENABLE_PNP; /* Enable card */ +static struct sfire_chip *chips[SNDRV_CARDS] = SNDRV_DEFAULT_PTR; +static struct usb_device *devices[SNDRV_CARDS] = SNDRV_DEFAULT_PTR; + +module_param_array(index, int, NULL, 0444); +MODULE_PARM_DESC(index, "Index value for the 6fire sound device"); +module_param_array(id, charp, NULL, 0444); +MODULE_PARM_DESC(id, "ID string for the 6fire sound device."); +module_param_array(enable, bool, NULL, 0444); +MODULE_PARM_DESC(enable, "Enable the 6fire sound device."); + +static DEFINE_MUTEX(register_mutex); + +static void usb6fire_chip_abort(struct sfire_chip *chip) +{ + if (chip) { + if (chip->pcm) + usb6fire_pcm_abort(chip); + if (chip->midi) + usb6fire_midi_abort(chip); + if (chip->comm) + usb6fire_comm_abort(chip); + if (chip->control) + usb6fire_control_abort(chip); + if (chip->card) { + snd_card_disconnect(chip->card); + snd_card_free_when_closed(chip->card); + chip->card = NULL; + } + } +} + +static void usb6fire_chip_destroy(struct sfire_chip *chip) +{ + if (chip) { + if (chip->pcm) + usb6fire_pcm_destroy(chip); + if (chip->midi) + usb6fire_midi_destroy(chip); + if (chip->comm) + usb6fire_comm_destroy(chip); + if (chip->control) + usb6fire_control_destroy(chip); + if (chip->card) + snd_card_free(chip->card); + } +} + +static int __devinit usb6fire_chip_probe(struct usb_interface *intf, + const struct usb_device_id *usb_id) +{ + int ret; + int i; + struct sfire_chip *chip = NULL; + struct usb_device *device = interface_to_usbdev(intf); + int regidx = -1; /* index in module parameter array */ + struct snd_card *card = NULL; + + /* look if we already serve this card and return if so */ + mutex_lock(®ister_mutex); + for (i = 0; i < SNDRV_CARDS; i++) { + if (devices[i] == device) { + if (chips[i]) + chips[i]->intf_count++; + usb_set_intfdata(intf, chips[i]); + mutex_unlock(®ister_mutex); + return 0; + } else if (!devices[i] && regidx < 0) + regidx = i; + } + if (regidx < 0) { + mutex_unlock(®ister_mutex); + snd_printk(KERN_ERR PREFIX "too many cards registered.\n"); + return -ENODEV; + } + devices[regidx] = device; + mutex_unlock(®ister_mutex); + + /* check, if firmware is present on device, upload it if not */ + ret = usb6fire_fw_init(intf); + if (ret < 0) + return ret; + else if (ret == FW_NOT_READY) /* firmware update performed */ + return 0; + + /* if we are here, card can be registered in alsa. */ + if (usb_set_interface(device, 0, 0) != 0) { + snd_printk(KERN_ERR PREFIX "can't set first interface.\n"); + return -EIO; + } + ret = snd_card_create(index[regidx], id[regidx], THIS_MODULE, + sizeof(struct sfire_chip), &card); + if (ret < 0) { + snd_printk(KERN_ERR PREFIX "cannot create alsa card.\n"); + return ret; + } + strcpy(card->driver, "6FireUSB"); + strcpy(card->shortname, "TerraTec DMX6FireUSB"); + sprintf(card->longname, "%s at %d:%d", card->shortname, + device->bus->busnum, device->devnum); + snd_card_set_dev(card, &intf->dev); + + chip = card->private_data; + chips[regidx] = chip; + chip->dev = device; + chip->regidx = regidx; + chip->intf_count = 1; + chip->card = card; + + ret = usb6fire_comm_init(chip); + if (ret < 0) { + usb6fire_chip_destroy(chip); + return ret; + } + + ret = usb6fire_midi_init(chip); + if (ret < 0) { + usb6fire_chip_destroy(chip); + return ret; + } + + ret = usb6fire_pcm_init(chip); + if (ret < 0) { + usb6fire_chip_destroy(chip); + return ret; + } + + ret = usb6fire_control_init(chip); + if (ret < 0) { + usb6fire_chip_destroy(chip); + return ret; + } + + ret = snd_card_register(card); + if (ret < 0) { + snd_printk(KERN_ERR PREFIX "cannot register card."); + usb6fire_chip_destroy(chip); + return ret; + } + usb_set_intfdata(intf, chip); + return 0; +} + +static void usb6fire_chip_disconnect(struct usb_interface *intf) +{ + struct sfire_chip *chip; + struct snd_card *card; + + chip = usb_get_intfdata(intf); + if (chip) { /* if !chip, fw upload has been performed */ + card = chip->card; + chip->intf_count--; + if (!chip->intf_count) { + mutex_lock(®ister_mutex); + devices[chip->regidx] = NULL; + chips[chip->regidx] = NULL; + mutex_unlock(®ister_mutex); + + chip->shutdown = true; + usb6fire_chip_abort(chip); + usb6fire_chip_destroy(chip); + } + } +} + +static struct usb_device_id device_table[] = { + { + .match_flags = USB_DEVICE_ID_MATCH_DEVICE, + .idVendor = 0x0ccd, + .idProduct = 0x0080 + }, + {} +}; + +MODULE_DEVICE_TABLE(usb, device_table); + +static struct usb_driver usb_driver = { + .name = "snd-usb-6fire", + .probe = usb6fire_chip_probe, + .disconnect = usb6fire_chip_disconnect, + .id_table = device_table, +}; + +module_usb_driver(usb_driver); diff --git a/pool/shard002/C/0058751_echo_rest.c b/pool/shard002/C/0058751_echo_rest.c new file mode 100644 index 0000000000000000000000000000000000000000..6f05e8d166d4d755e2874b2fd5999b1f7a6fa6b4 --- /dev/null +++ b/pool/shard002/C/0058751_echo_rest.c @@ -0,0 +1,229 @@ + +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "echo_util.h" +#include +#include +#include +#include + +int +main( + int argc, + char **argv) +{ + const axutil_env_t *env = NULL; + const axis2_char_t *address = NULL; + axis2_endpoint_ref_t *endpoint_ref = NULL; + axis2_options_t *options = NULL; + const axis2_char_t *client_home = NULL; + axis2_svc_client_t *svc_client = NULL; + axiom_node_t *payload = NULL; + axiom_node_t *ret_node = NULL; + axis2_bool_t method_get = AXIS2_FALSE; + axis2_bool_t method_head = AXIS2_FALSE; + axis2_bool_t method_put = AXIS2_FALSE; + axis2_bool_t method_delete = AXIS2_FALSE; + + /* Set up the environment */ + env = axutil_env_create_all("echo_rest.log", AXIS2_LOG_LEVEL_TRACE); + + /* Set end point reference of echo service */ + address = "http://localhost:9090/axis2/services/echo/echoString"; + if (argc > 1) + { + if (0 == strncmp(argv[1], "-mGET", 5)) + { + method_get = AXIS2_TRUE; + } + else if (0 == strncmp(argv[1], "-mHEAD", 6)) + { + method_head = AXIS2_TRUE; + } + else if (0 == strncmp(argv[1], "-mPUT", 5)) + { + method_put = AXIS2_TRUE; + } + else if (0 == strncmp(argv[1], "-mDELETE",8 )) + { + method_delete = AXIS2_TRUE; + } + else if (0 == axutil_strcmp(argv[1], "-h")) + { + printf("Usage : %s [endpoint_url] \n", argv[0]); + printf("\nNOTE: You can test for other HTTP methods by changing the"); + printf(" services.xml of the echo service\n and providing the correct REST HTTP method"); + printf(" and the location to be used for operation.\n"); + printf(" Also note that you have to restart the server after changing the services.xml.\n"); + printf(" use %s -mGET for HTTP GET\n", argv[0]); + printf(" use %s -mHEAD for HTTP HEAD\n", argv[0]); + printf(" use %s -mDELETE for HTTP DELETE\n", argv[0]); + printf(" use %s -mPUT for HTTP PUT\n", argv[0]); + printf(" use -h for help\n"); + return 0; + } + else + { + address = argv[1]; + } + } + + if (argc > 2) + { + if (0 == strncmp(argv[2], "-mGET", 5)) + { + method_get = AXIS2_TRUE; + } + else if (0 == strncmp(argv[2], "-mHEAD", 6)) + { + method_head = AXIS2_TRUE; + } + else if (0 == strncmp(argv[2], "-mPUT", 5)) + { + method_put = AXIS2_TRUE; + } + else if (0 == strncmp(argv[2], "-mDELETE",8 )) + { + method_delete = AXIS2_TRUE; + } + else + { + address = argv[2]; + } + } + + printf("Using endpoint : %s\n", address); + + /* Create EPR with given address */ + endpoint_ref = axis2_endpoint_ref_create(env, address); + + /* Setup options */ + options = axis2_options_create(env); + axis2_options_set_to(options, env, endpoint_ref); + /* Enable REST at the client side */ + axis2_options_set_enable_rest(options, env, AXIS2_TRUE); + + if (AXIS2_TRUE == method_get) + { + axis2_options_set_http_method(options, env, AXIS2_HTTP_GET); + } + else if (AXIS2_TRUE == method_head) + { + axis2_options_set_http_method(options, env, AXIS2_HTTP_HEAD); + } + else if (AXIS2_TRUE == method_put) + { + axis2_options_set_http_method(options, env, AXIS2_HTTP_PUT); + } + else if (AXIS2_TRUE == method_delete) + { + axis2_options_set_http_method(options, env, AXIS2_HTTP_DELETE); + } + /* Set up deploy folder. It is from the deploy folder, the configuration is picked up + * using the axis2.xml file. + * In this sample client_home points to the Axis2/C default deploy folder. The client_home can + * be different from this folder on your system. For example, you may have a different folder + * (say, my_client_folder) with its own axis2.xml file. my_client_folder/modules will have the + * modules that the client uses + */ + client_home = AXIS2_GETENV("AXIS2C_HOME"); + if (!client_home || !strcmp(client_home, "")) + client_home = "../.."; + + /* Create service client */ + svc_client = axis2_svc_client_create(env, client_home); + if (!svc_client) + { + printf + ("Error creating service client, Please check AXIS2C_HOME again\n"); + AXIS2_LOG_ERROR(env->log, AXIS2_LOG_SI, + "Stub invoke FAILED: Error code:" " %d :: %s", + env->error->error_number, + AXIS2_ERROR_GET_MESSAGE(env->error)); + return -1; + } + + /* Set service client options */ + axis2_svc_client_set_options(svc_client, env, options); + + /* Build the SOAP request message payload using OM API. */ + payload = build_om_payload_for_echo_svc(env); + + /* Send request */ + ret_node = axis2_svc_client_send_receive(svc_client, env, payload); + + if (ret_node && + axis2_svc_client_get_last_response_has_fault(svc_client, env)) + { + axis2_char_t *om_str = NULL; + om_str = axiom_node_to_string(ret_node, env); + if (om_str) + { + printf("\nReceived OM : %s\n", om_str); + AXIS2_FREE(env->allocator, om_str); + } + printf("\necho client invoke FAILED!\n"); + } + else if (ret_node) + { + axis2_char_t *om_str = NULL; + om_str = axiom_node_to_string(ret_node, env); + if (om_str) + { + printf("\nReceived OM : %s\n", om_str); + AXIS2_FREE(env->allocator, om_str); + } + printf("\necho client invoke SUCCESSFUL!\n"); + } + else if (method_head && + axis2_svc_client_get_last_response_has_fault(svc_client, env)) + { + /* HEAD request should probably be removed from this file, + * and be relocated to transport unit tests. + */ + printf("\necho client invoke FAILED!\n"); + } + else if (method_head) + { + /* HEAD request should probably be removed from this file, + * and be relocated to transport unit tests. + */ + printf("\necho client invoke SUCCESSFUL!\n"); + } + else + { + AXIS2_LOG_ERROR(env->log, AXIS2_LOG_SI, + "Stub invoke FAILED: Error code:" " %d :: %s", + env->error->error_number, + AXIS2_ERROR_GET_MESSAGE(env->error)); + printf("echo client invoke FAILED!\n"); + } + + if (svc_client) + { + axis2_svc_client_free(svc_client, env); + svc_client = NULL; + } + + if (env) + { + axutil_env_free((axutil_env_t *) env); + env = NULL; + } + return 0; +} diff --git a/pool/shard002/C/0058752_test_wzd_fs.c b/pool/shard002/C/0058752_test_wzd_fs.c new file mode 100644 index 0000000000000000000000000000000000000000..92a37974885a98d89f47f7029e92fd95c13ad197 --- /dev/null +++ b/pool/shard002/C/0058752_test_wzd_fs.c @@ -0,0 +1,74 @@ +#include +#include +#include + +#include +#include + +#include + +#include +#include + +#include + +#define C1 0x12345678 +#define C2 0x9abcdef0 + +int main() +{ + unsigned long c1 = C1; + fs_dir_t * dir; + fs_fileinfo_t * fileinfo; + int err; + const char * test_dirname = "_T_fs_mkdir"; + unsigned long c2 = C2; + + struct stat s; + int ret; + + if (stat(".",&s) < 0) { + fprintf(stderr,"FATAL: could not stat() current directory\n"); + return 1; + } + + /** fs_mkdir **/ + ret = fs_mkdir(test_dirname, 0755, &err); + if (ret < 0) { + fprintf(stderr,"WARNING: could not create test directory %s\n", test_dirname); + fprintf(stderr," errno is %d %s\n", errno, strerror(errno)); + } else { + ret = rmdir(test_dirname); + if (ret < 0) { + fprintf(stderr,"WARNING: could not remove test directory %s\n", test_dirname); + fprintf(stderr," errno is %d %s\n", errno, strerror(errno)); + } + } + + /** fs_dir_open current directory **/ + ret = fs_dir_open(".", &dir); + if (ret < 0) { + fprintf(stderr,"FATAL: could not fs_dir_open() current directory\n"); + return 1; + } + + /** \todo XXX '.' does not appear in the list ?! */ + while ( fs_dir_read(dir, &fileinfo) >= 0 ) { + printf(" +--> %s\n", fs_fileinfo_getname(fileinfo)); + } + + + + fs_dir_close(dir); + + if (c1 != C1) { + fprintf(stderr, "c1 nuked !\n"); + return -1; + } + if (c2 != C2) { + fprintf(stderr, "c2 nuked !\n"); + return -1; + } + + return 0; +} diff --git a/pool/shard002/C/0058758_ubnt.c b/pool/shard002/C/0058758_ubnt.c new file mode 100644 index 0000000000000000000000000000000000000000..638550e4c8649d92ff0a66f6d144c1c9d5c10b69 --- /dev/null +++ b/pool/shard002/C/0058758_ubnt.c @@ -0,0 +1,72 @@ +/* + * Copyright 2006-2012, Ubiquiti Networks, 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. + * 3. Neither the name of the author nor the names of other 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 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. + */ + +//#include +//#include +#include +//#include +#include + +#include +#include +#include + +#include "ubnt-airos.h" + +static int +ubnt_mib_update(struct odb **odb) { + abz_clear_error(); + odb_destroy(odb); + + log_printf(LOG_VERBOSE, "updating airos table\n"); + int rc = update_airos_table(odb, 1); + log_printf(LOG_VERBOSE,"done. rc: %d\n", rc); + + return rc; +} + +extern void airos_cleanup_stats(void); + +static void ubnt_mib_destroy(void) +{ + airos_cleanup_stats(); +} + +static const uint32_t ubnt_oid[] = { 6, 43, 6, 1, 4, 1, 41112 }; + +struct module module = { + .name = "ubnt", + .descr = "Ubiquiti Networks MIB module ", + .mod_oid = ubnt_oid, + .con_oid = ubnt_oid, + .parse = NULL, + .open = NULL, + .update = ubnt_mib_update, + .close = ubnt_mib_destroy +}; + diff --git a/pool/shard002/C/0058760_yescrypt-r32.c b/pool/shard002/C/0058760_yescrypt-r32.c new file mode 100644 index 0000000000000000000000000000000000000000..079e9b874e9805038ba1d88c9e78e6842d9abcb4 --- /dev/null +++ b/pool/shard002/C/0058760_yescrypt-r32.c @@ -0,0 +1,107 @@ +/*- + * Copyright 2014 Alexander Peslyak + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted. + * + * 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. + */ +#include "yescrypt.h" + +#define YESCRYPT_N 4096 +#define YESCRYPT_R 32 +#define YESCRYPT_P 1 +#define YESCRYPT_T 0 +#define YESCRYPT_FLAGS (YESCRYPT_RW | YESCRYPT_PWXFORM) + +#ifdef __clang__ + +static int yescrypt_wavi(const uint8_t *passwd, size_t passwdlen, + const uint8_t *salt, size_t saltlen, + uint8_t *buf, size_t buflen) +{ + yescrypt_shared_t shared; + yescrypt_local_t local; + int retval; + + if (yescrypt_init_shared(&shared, NULL, 0, + 0, 0, 0, YESCRYPT_SHARED_DEFAULTS, 0, NULL, 0)) + return -1; + if (yescrypt_init_local(&local)) { + yescrypt_free_shared(&shared); + return -1; + } + retval = yescrypt_kdf(&shared, &local, passwd, passwdlen, salt, saltlen, + YESCRYPT_N, YESCRYPT_R, YESCRYPT_P, YESCRYPT_T, + YESCRYPT_FLAGS, buf, buflen); + if (yescrypt_free_local(&local)) { + yescrypt_free_shared(&shared); + return -1; + } + if (yescrypt_free_shared(&shared)) + return -1; + + return retval; +} + +#else + +static int yescrypt_wavi(const uint8_t *passwd, size_t passwdlen, + const uint8_t *salt, size_t saltlen, + uint8_t *buf, size_t buflen) +{ + static __thread int initialized = 0; + static __thread yescrypt_shared_t shared; + static __thread yescrypt_local_t local; + int retval; + if (!initialized) { + /* "shared" could in fact be shared, but it's simpler to keep it private + * along with "local". It's dummy and tiny anyway. */ + if (yescrypt_init_shared(&shared, NULL, 0, + 0, 0, 0, YESCRYPT_SHARED_DEFAULTS, 0, NULL, 0)) + return -1; + if (yescrypt_init_local(&local)) { + yescrypt_free_shared(&shared); + return -1; + } + initialized = 1; + } + retval = yescrypt_kdf(&shared, &local, passwd, passwdlen, salt, saltlen, + YESCRYPT_N, YESCRYPT_R, YESCRYPT_P, YESCRYPT_T, + YESCRYPT_FLAGS, buf, buflen); +#if 0 + if (yescrypt_free_local(&local)) { + yescrypt_free_shared(&shared); + return -1; + } + if (yescrypt_free_shared(&shared)) + return -1; + initialized = 0; +#endif + if (retval < 0) { + yescrypt_free_local(&local); + yescrypt_free_shared(&shared); + } + return retval; +} + +#endif + +void yescrypt_r32_hash(const char *input, char *output) +{ + yescrypt_wavi((const uint8_t *) input, 80, + (const uint8_t *) input, 80, + (uint8_t *) output, 32); +} + diff --git a/pool/shard002/C/0058768_lowlevel.c b/pool/shard002/C/0058768_lowlevel.c new file mode 100644 index 0000000000000000000000000000000000000000..05226866f828088d64a80a7b78242a8ce0dc7fba --- /dev/null +++ b/pool/shard002/C/0058768_lowlevel.c @@ -0,0 +1,123 @@ +// SPDX-License-Identifier: GPL-2.0+ +/* + * Copyright (C) 2018 Christian Hemp + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "ddr.h" + +extern char __dtb_imx8mq_phytec_phycore_som_start[]; + +#define UART_PAD_CTRL MUX_PAD_CTRL(PAD_CTL_DSE_3P3V_45_OHM) + +static void setup_uart(void) +{ + void __iomem *uart = IOMEM(MX8M_UART1_BASE_ADDR); + + imx8m_early_setup_uart_clock(); + + imx8mq_setup_pad(IMX8MQ_PAD_UART1_TXD__UART1_TX | UART_PAD_CTRL); + + imx8m_uart_setup(uart); + + pbl_set_putc(imx_uart_putc, uart); + + putc_ll('>'); +} + +static void phytec_imx8mq_som_sram_setup(void) +{ + enum bootsource src = BOOTSOURCE_UNKNOWN; + int instance = BOOTSOURCE_INSTANCE_UNKNOWN; + int ret = -ENOTSUPP; + + ddr_init(); + + imx8mq_get_boot_source(&src, &instance); + + if (src == BOOTSOURCE_MMC) + ret = imx8m_esdhc_load_image(instance, true); + + BUG_ON(ret); +} + +static __noreturn noinline void phytec_phycore_imx8mq_start(void) +{ + setup_uart(); + + if (get_pc() < MX8MQ_DDR_CSD1_BASE_ADDR) { + /* + * We assume that we were just loaded by MaskROM into + * SRAM if we are not running from DDR. We also assume + * that means DDR needs to be initialized for the + * first time. + */ + phytec_imx8mq_som_sram_setup(); + } + /* + * Straight from the power-on we are at EL3, so the following + * code _will_ load and jump to ATF. + * + * However when we are re-executed upon exit from ATF's + * initialization routine, it is EL2 which means we'll skip + * loadting ATF blob again + */ + if (current_el() == 3) { + const u8 *bl31; + size_t bl31_size; + + get_builtin_firmware(imx8mq_bl31_bin, &bl31, &bl31_size); + imx8mq_atf_load_bl31(bl31, bl31_size); + } + + /* + * Standard entry we hit once we initialized both DDR and ATF + */ + imx8mq_barebox_entry(__dtb_imx8mq_phytec_phycore_som_start); +} + +/* + * Power-on execution flow of start_phytec_phycore_imx8mq() might not be + * obvious for a very first read, so here's, hopefully helpful, + * summary: + * + * 1. MaskROM uploads PBL into OCRAM and that's where this function is + * executed for the first time + * + * 2. DDR is initialized and full i.MX image is loaded to the + * beginning of RAM + * + * 3. start_phytec_phycore_imx8mq, now in RAM, is executed again + * + * 4. BL31 blob is uploaded to OCRAM and the control is transfer to it + * + * 5. BL31 exits EL3 into EL2 at address MX8MQ_ATF_BL33_BASE_ADDR, + * executing start_phytec_phycore_imx8mq() the third time + * + * 6. Standard barebox boot flow continues + */ +ENTRY_FUNCTION(start_phytec_phycore_imx8mq, r0, r1, r2) +{ + imx8mq_cpu_lowlevel_init(); + relocate_to_current_adr(); + setup_c(); + + phytec_phycore_imx8mq_start(); +} diff --git a/pool/shard002/C/0058774_generate.c b/pool/shard002/C/0058774_generate.c new file mode 100644 index 0000000000000000000000000000000000000000..27b41ae3478bd300d17db869c9eddf4bdf1ba080 --- /dev/null +++ b/pool/shard002/C/0058774_generate.c @@ -0,0 +1,124 @@ +#include +#include +#include +#include + +void generate_line(uint32_t len) +{ + FILE *f; + f = fopen ("out", "w+"); + + uint32_t i; + for (i = 1; i <= len; i++) { + if (i == 1) { /*First vertex*/ + fprintf(f, "1 --> 2\n"); + } else if (i == len) { /*Last vertex*/ + fprintf(f, "%d --> %d\n", len, len - 1); + } else { + fprintf(f, "%d --> %d %d\n", i, i - 1, i + 1); + } + + if (i != len) + fprintf(f, "\n"); + } + fclose(f); +} + +void generate_circle(uint32_t len) +{ + FILE *f; + f = fopen ("out", "w+"); + + uint32_t i; + for (i = 1; i <= len; i++) { + if (i == 1) { /*First vertex*/ + fprintf(f, "1 --> 2 %d\n", len); + } else if (i == len) { /*Last vertex*/ + fprintf(f, "%d --> %d 1\n", len, len - 1); + } else { + fprintf(f, "%d --> %d %d\n", i, i - 1, i + 1); + } + + if (i != len) + fprintf(f, "\n"); + } + + fclose(f); +} + +void generate_star(uint32_t len) +{ + FILE *f; + uint32_t i; + f = fopen ("out", "w+"); + /*First line*/ + fprintf(f, "1 -->"); + for (i = 2; i <= len; i++) + fprintf(f, " %d", i); + fprintf(f, "\n"); + + for (i = 2; i <= len; i++) { + fprintf(f, "%d --> 1", i); + + if (i != len) + fprintf(f, "\n"); + } + + fclose(f); +} + +void generate_complete(uint32_t len) +{ + FILE *f; + uint32_t i; + f = fopen ("out", "w+"); + + for (i = 1; i <= len; i++) { + fprintf(f, "%d -->", i); + + uint32_t j; + for (j = 1; j <= len; j++) { + if (j != i) { + fprintf(f, " %d", j); + } + } + + fprintf(f, "\n"); + + if (i != len) + fprintf(f, "\n"); + } + + fclose(f); +} + +void generate_dandelion(uint32_t len) +{ + FILE *f; + uint32_t i; + f = fopen ("out", "w+"); + + /*Root vertex*/ + + fprintf(f, "1 -->"); + for (i = 2; i <= len; i++) { + fprintf(f, " %d", i); + } + + fprintf(f, "\n\n"); + + for (i = 2; i <= len; i++) { + if (i == 2) { + fprintf(f, "2 --> 1 3\n"); + } else if (i == len) { + fprintf(f, "%d --> 1 %d\n", len, len - 1); + } else { + fprintf(f, "%d --> 1 %d %d\n", i, i - 1, i + 1); + } + + if (i != len) + fprintf(f, "\n"); + } + + fclose(f); +} diff --git a/pool/shard002/C/0058781_stage.c b/pool/shard002/C/0058781_stage.c new file mode 100644 index 0000000000000000000000000000000000000000..0f3b2983210e9a04acb1409f50c5f8265f59be65 --- /dev/null +++ b/pool/shard002/C/0058781_stage.c @@ -0,0 +1,62 @@ +#include "clar_libgit2.h" +#include "index.h" +#include "git2/repository.h" + +static git_repository *repo; +static git_index *repo_index; + +#define TEST_REPO_PATH "mergedrepo" +#define TEST_INDEX_PATH TEST_REPO_PATH "/.git/index" + +// Fixture setup and teardown +void test_index_stage__initialize(void) +{ + repo = cl_git_sandbox_init("mergedrepo"); + git_repository_index(&repo_index, repo); +} + +void test_index_stage__cleanup(void) +{ + git_index_free(repo_index); + repo_index = NULL; + + cl_git_sandbox_cleanup(); +} + + +void test_index_stage__add_always_adds_stage_0(void) +{ + int entry_idx; + const git_index_entry *entry; + + cl_git_mkfile("./mergedrepo/new-file.txt", "new-file\n"); + + cl_git_pass(git_index_add_from_workdir(repo_index, "new-file.txt")); + + cl_assert((entry_idx = git_index_find(repo_index, "new-file.txt")) >= 0); + cl_assert((entry = git_index_get_byindex(repo_index, entry_idx)) != NULL); + cl_assert(git_index_entry_stage(entry) == 0); +} + +void test_index_stage__find_gets_first_stage(void) +{ + int entry_idx; + const git_index_entry *entry; + + cl_assert((entry_idx = git_index_find(repo_index, "one.txt")) >= 0); + cl_assert((entry = git_index_get_byindex(repo_index, entry_idx)) != NULL); + cl_assert(git_index_entry_stage(entry) == 0); + + cl_assert((entry_idx = git_index_find(repo_index, "two.txt")) >= 0); + cl_assert((entry = git_index_get_byindex(repo_index, entry_idx)) != NULL); + cl_assert(git_index_entry_stage(entry) == 0); + + cl_assert((entry_idx = git_index_find(repo_index, "conflicts-one.txt")) >= 0); + cl_assert((entry = git_index_get_byindex(repo_index, entry_idx)) != NULL); + cl_assert(git_index_entry_stage(entry) == 1); + + cl_assert((entry_idx = git_index_find(repo_index, "conflicts-two.txt")) >= 0); + cl_assert((entry = git_index_get_byindex(repo_index, entry_idx)) != NULL); + cl_assert(git_index_entry_stage(entry) == 1); +} + diff --git a/pool/shard002/C/0058786_doveadm-util.c b/pool/shard002/C/0058786_doveadm-util.c new file mode 100644 index 0000000000000000000000000000000000000000..800166c7d493cc43f63d93c5fa009db06d9e9d97 --- /dev/null +++ b/pool/shard002/C/0058786_doveadm-util.c @@ -0,0 +1,170 @@ +/* Copyright (c) 2009-2014 Dovecot authors, see the included COPYING file */ + +#include "lib.h" +#include "array.h" +#include "net.h" +#include "time-util.h" +#include "master-service.h" +#include "module-dir.h" +#include "doveadm-settings.h" +#include "doveadm-mail.h" +#include "doveadm-util.h" + +#include +#include +#include + +bool doveadm_verbose = FALSE, doveadm_debug = FALSE, doveadm_server = FALSE; +static struct module *modules = NULL; + +void doveadm_load_modules(void) +{ + struct module_dir_load_settings mod_set; + + /* some doveadm plugins have dependencies to mail plugins. we can load + only those whose dependencies have been loaded earlier, the rest are + ignored. */ + memset(&mod_set, 0, sizeof(mod_set)); + mod_set.abi_version = DOVECOT_ABI_VERSION; + mod_set.require_init_funcs = TRUE; + mod_set.debug = doveadm_debug; + mod_set.ignore_dlopen_errors = TRUE; + + modules = module_dir_load_missing(modules, DOVEADM_MODULEDIR, + NULL, &mod_set); + module_dir_init(modules); +} + +void doveadm_unload_modules(void) +{ + module_dir_unload(&modules); +} + +bool doveadm_has_unloaded_plugin(const char *name) +{ + struct module *module; + DIR *dir; + struct dirent *d; + const char *plugin_name; + unsigned int name_len = strlen(name); + bool found = FALSE; + + /* first check that it's not actually loaded */ + for (module = modules; module != NULL; module = module->next) { + if (strcmp(module_get_plugin_name(module), name) == 0) + return FALSE; + } + + dir = opendir(DOVEADM_MODULEDIR); + if (dir == NULL) + return FALSE; + + while ((d = readdir(dir)) != NULL) { + plugin_name = module_file_get_name(d->d_name); + if (strncmp(plugin_name, "doveadm_", 8) == 0) + plugin_name += 8; + + if (strncmp(plugin_name, name, name_len) == 0 && + (plugin_name[name_len] == '\0' || + strcmp(plugin_name + name_len, "_plugin") == 0)) { + found = TRUE; + break; + } + } + (void)closedir(dir); + return found; +} + +const char *unixdate2str(time_t timestamp) +{ + return t_strflocaltime("%Y-%m-%d %H:%M:%S", timestamp); +} + +const char *doveadm_plugin_getenv(const char *name) +{ + const char *const *envs; + unsigned int i, count; + + if (!array_is_created(&doveadm_settings->plugin_envs)) + return NULL; + + envs = array_get(&doveadm_settings->plugin_envs, &count); + for (i = 0; i < count; i += 2) { + if (strcmp(envs[i], name) == 0) + return envs[i+1]; + } + return NULL; +} + +static bool +parse_hostport(const char *str, unsigned int default_port, + const char **host_r, unsigned int *port_r) +{ + const char *p; + + /* host:port */ + p = strrchr(str, ':'); + if (p == NULL && default_port != 0) { + *host_r = str; + *port_r = default_port; + } else { + if (p == NULL || str_to_uint(p+1, port_r) < 0) + return FALSE; + *host_r = t_strdup_until(str, p); + } + return TRUE; +} + +static int +doveadm_tcp_connect_port(const char *host, unsigned int port) +{ + struct ip_addr *ips; + unsigned int ips_count; + int ret, fd; + + ret = net_gethostbyname(host, &ips, &ips_count); + if (ret != 0) { + i_fatal("Lookup of host %s failed: %s", + host, net_gethosterror(ret)); + } + fd = net_connect_ip_blocking(&ips[0], port, NULL); + if (fd == -1) { + i_fatal("connect(%s:%u) failed: %m", + net_ip2addr(&ips[0]), port); + } + return fd; +} + +int doveadm_tcp_connect(const char *target, unsigned int default_port) +{ + const char *host; + unsigned int port; + + if (!parse_hostport(target, default_port, &host, &port)) { + i_fatal("Port not known for %s. Either set proxy_port " + "or use %s:port", target, target); + } + return doveadm_tcp_connect_port(host, port); +} + +int doveadm_connect_with_default_port(const char *path, + unsigned int default_port) +{ + int fd; + + /* we'll assume UNIX sockets typically have an absolute path, + or at the very least '/' somewhere. */ + if (strchr(path, '/') == NULL) + fd = doveadm_tcp_connect(path, default_port); + else { + fd = net_connect_unix(path); + if (fd == -1) + i_fatal("net_connect_unix(%s) failed: %m", path); + } + return fd; +} + +int doveadm_connect(const char *path) +{ + return doveadm_connect_with_default_port(path, 0); +} diff --git a/pool/shard002/C/0058788_htdigest.c b/pool/shard002/C/0058788_htdigest.c new file mode 100644 index 0000000000000000000000000000000000000000..f76036d7a5bd34e3e583d0f8e6027d2e7fe64482 --- /dev/null +++ b/pool/shard002/C/0058788_htdigest.c @@ -0,0 +1,293 @@ +/* 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. + */ + +/****************************************************************************** + ****************************************************************************** + * NOTE! This program is not safe as a setuid executable! Do not make it + * setuid! + ****************************************************************************** + *****************************************************************************/ +/* + * htdigest.c: simple program for manipulating digest passwd file for Apache + * + * by Alexei Kosut, based on htpasswd.c, by Rob McCool + */ + +#include "apr.h" +#include "apr_file_io.h" +#include "apr_md5.h" +#include "apr_lib.h" /* for apr_getpass() */ +#include "apr_general.h" +#include "apr_signal.h" +#include "apr_strings.h" /* for apr_pstrdup() */ + +#define APR_WANT_STDIO +#define APR_WANT_STRFUNC +#include "apr_want.h" + +#if APR_HAVE_SYS_TYPES_H +#include +#endif +#if APR_HAVE_STDLIB_H +#include +#endif + +#ifdef WIN32 +#include +#endif + + +#if APR_CHARSET_EBCDIC +#define LF '\n' +#define CR '\r' +#else +#define LF 10 +#define CR 13 +#endif /* APR_CHARSET_EBCDIC */ + +#define MAX_STRING_LEN 256 + +apr_file_t *tfp = NULL; +apr_file_t *errfile; +apr_pool_t *cntxt; +#if APR_CHARSET_EBCDIC +apr_xlate_t *to_ascii; +#endif + +static void cleanup_tempfile_and_exit(int rc) +{ + if (tfp) { + apr_file_close(tfp); + } + exit(rc); +} + +static void getword(char *word, char *line, char stop) +{ + int x = 0, y; + + for (x = 0; ((line[x]) && (line[x] != stop)); x++) + word[x] = line[x]; + + word[x] = '\0'; + if (line[x]) + ++x; + y = 0; + + while ((line[y++] = line[x++])); +} + +static int get_line(char *s, int n, apr_file_t *f) +{ + register int i = 0; + char ch; + apr_status_t rv = APR_EINVAL; + + /* we need 2 remaining bytes in buffer */ + while (i < (n - 2) && + ((rv = apr_file_getc(&ch, f)) == APR_SUCCESS) && (ch != '\n')) { + s[i++] = ch; + } + /* First remaining byte potentially used here */ + if (ch == '\n') + s[i++] = ch; + /* Second remaining byte used here */ + s[i] = '\0'; + + if (rv != APR_SUCCESS) + return 1; + + return 0; +} + +static void putline(apr_file_t *f, char *l) +{ + int x; + + for (x = 0; l[x]; x++) + apr_file_putc(l[x], f); +} + + +static void add_password(const char *user, const char *realm, apr_file_t *f) +{ + char *pw; + apr_md5_ctx_t context; + unsigned char digest[16]; + char string[3 * MAX_STRING_LEN]; /* this includes room for 2 * ':' + '\0' */ + char pwin[MAX_STRING_LEN]; + char pwv[MAX_STRING_LEN]; + unsigned int i; + apr_size_t len = sizeof(pwin); + + if (apr_password_get("New password: ", pwin, &len) != APR_SUCCESS) { + apr_file_printf(errfile, "password too long"); + cleanup_tempfile_and_exit(5); + } + len = sizeof(pwin); + apr_password_get("Re-type new password: ", pwv, &len); + if (strcmp(pwin, pwv) != 0) { + apr_file_printf(errfile, "They don't match, sorry.\n"); + cleanup_tempfile_and_exit(1); + } + pw = pwin; + apr_file_printf(f, "%s:%s:", user, realm); + + /* Do MD5 stuff */ + apr_snprintf(string, sizeof(string), "%s:%s:%s", user, realm, pw); + + apr_md5_init(&context); +#if APR_CHARSET_EBCDIC + apr_md5_set_xlate(&context, to_ascii); +#endif + apr_md5_update(&context, (unsigned char *) string, strlen(string)); + apr_md5_final(digest, &context); + + for (i = 0; i < 16; i++) + apr_file_printf(f, "%02x", digest[i]); + + apr_file_printf(f, "\n"); +} + +static void usage(void) +{ + apr_file_printf(errfile, "Usage: htdigest [-c] passwordfile realm username\n"); + apr_file_printf(errfile, "The -c flag creates a new file.\n"); + exit(1); +} + +static void interrupted(void) +{ + apr_file_printf(errfile, "Interrupted.\n"); + cleanup_tempfile_and_exit(1); +} + +static void terminate(void) +{ + apr_terminate(); +#ifdef NETWARE + pressanykey(); +#endif +} + +int main(int argc, const char * const argv[]) +{ + apr_file_t *f; + apr_status_t rv; + char tn[] = "htdigest.tmp.XXXXXX"; + char *dirname; + char user[MAX_STRING_LEN]; + char realm[MAX_STRING_LEN]; + char line[3 * MAX_STRING_LEN]; + char l[3 * MAX_STRING_LEN]; + char w[MAX_STRING_LEN]; + char x[MAX_STRING_LEN]; + int found; + + apr_app_initialize(&argc, &argv, NULL); + atexit(terminate); + apr_pool_create(&cntxt, NULL); + apr_file_open_stderr(&errfile, cntxt); + +#if APR_CHARSET_EBCDIC + rv = apr_xlate_open(&to_ascii, "ISO-8859-1", APR_DEFAULT_CHARSET, cntxt); + if (rv) { + apr_file_printf(errfile, "apr_xlate_open(): %pm (%d)\n", + &rv, rv); + exit(1); + } +#endif + + apr_signal(SIGINT, (void (*)(int)) interrupted); + if (argc == 5) { + if (strcmp(argv[1], "-c")) + usage(); + rv = apr_file_open(&f, argv[2], APR_WRITE | APR_CREATE, + APR_OS_DEFAULT, cntxt); + if (rv != APR_SUCCESS) { + apr_file_printf(errfile, "Could not open passwd file %s for writing: %pm\n", + argv[2], &rv); + exit(1); + } + apr_cpystrn(user, argv[4], sizeof(user)); + apr_cpystrn(realm, argv[3], sizeof(realm)); + apr_file_printf(errfile, "Adding password for %s in realm %s.\n", + user, realm); + add_password(user, realm, f); + apr_file_close(f); + exit(0); + } + else if (argc != 4) + usage(); + + if (apr_temp_dir_get((const char**)&dirname, cntxt) != APR_SUCCESS) { + apr_file_printf(errfile, "%s: could not determine temp dir\n", + argv[0]); + exit(1); + } + dirname = apr_psprintf(cntxt, "%s/%s", dirname, tn); + + if (apr_file_mktemp(&tfp, dirname, 0, cntxt) != APR_SUCCESS) { + apr_file_printf(errfile, "Could not open temp file %s.\n", dirname); + exit(1); + } + + if (apr_file_open(&f, argv[1], APR_READ, APR_OS_DEFAULT, cntxt) != APR_SUCCESS) { + apr_file_printf(errfile, + "Could not open passwd file %s for reading.\n", argv[1]); + apr_file_printf(errfile, "Use -c option to create new one.\n"); + cleanup_tempfile_and_exit(1); + } + apr_cpystrn(user, argv[3], sizeof(user)); + apr_cpystrn(realm, argv[2], sizeof(realm)); + + found = 0; + while (!(get_line(line, sizeof(line), f))) { + if (found || (line[0] == '#') || (!line[0])) { + putline(tfp, line); + continue; + } + strcpy(l, line); + getword(w, l, ':'); + getword(x, l, ':'); + if (strcmp(user, w) || strcmp(realm, x)) { + putline(tfp, line); + continue; + } + else { + apr_file_printf(errfile, "Changing password for user %s in realm %s\n", + user, realm); + add_password(user, realm, tfp); + found = 1; + } + } + if (!found) { + apr_file_printf(errfile, "Adding user %s in realm %s\n", user, realm); + add_password(user, realm, tfp); + } + apr_file_close(f); + + /* The temporary file has all the data, just copy it to the new location. + */ + if (apr_file_copy(dirname, argv[1], APR_FILE_SOURCE_PERMS, cntxt) != + APR_SUCCESS) { + apr_file_printf(errfile, "%s: unable to update file %s\n", + argv[0], argv[1]); + } + apr_file_close(tfp); + + return 0; +} diff --git a/pool/shard002/C/0058793_test_pquery.c b/pool/shard002/C/0058793_test_pquery.c new file mode 100644 index 0000000000000000000000000000000000000000..9c711ddd4854415fb2c7b18abbe4281e940e35f5 --- /dev/null +++ b/pool/shard002/C/0058793_test_pquery.c @@ -0,0 +1,94 @@ +/* This file is part of the YAZ toolkit. + * Copyright (C) Index Data + * See the file LICENSE for details. + */ +#if HAVE_CONFIG_H +#include +#endif + +#include +#include + +#include +#include +#include +#include +#include + +int expect_pqf(const char *pqf, const char *expect_pqf, int expect_error) +{ + YAZ_PQF_Parser parser = yaz_pqf_create(); + int res = 0; + ODR odr = odr_createmem(ODR_ENCODE); + Z_RPNQuery *rpn; + + if (!parser) + return 0; + + if (!odr) + return 0; + + rpn = yaz_pqf_parse(parser, odr, pqf); + + if (!rpn) + { + const char *msg; + size_t offset; + int got_error = yaz_pqf_error (parser, &msg, &offset); + + if (expect_error == got_error) + res = 1; + } + else if (expect_error == YAZ_PQF_ERROR_NONE) + { + WRBUF wrbuf = wrbuf_alloc(); + + if (wrbuf) + { + yaz_rpnquery_to_wrbuf(wrbuf, rpn); + + if (!strcmp(wrbuf_cstr(wrbuf), expect_pqf)) + { + res = 1; + } + wrbuf_destroy(wrbuf); + } + } + yaz_pqf_destroy(parser); + odr_destroy(odr); + return res; +} + +static void tst(void) +{ + YAZ_CHECK(expect_pqf("a", "@attrset Bib-1 a", YAZ_PQF_ERROR_NONE)); + YAZ_CHECK(expect_pqf("@attr 1=4 a", "@attrset Bib-1 @attr 1=4 a", YAZ_PQF_ERROR_NONE)); + YAZ_CHECK(expect_pqf("@attr 1=title a", "@attrset Bib-1 @attr 1=title a", YAZ_PQF_ERROR_NONE)); + YAZ_CHECK(expect_pqf("a b", "", YAZ_PQF_ERROR_EXTRA)); + YAZ_CHECK(expect_pqf("@and a", "", YAZ_PQF_ERROR_MISSING)); + YAZ_CHECK(expect_pqf("@attr p=q a", "", YAZ_PQF_ERROR_BAD_INTEGER)); + YAZ_CHECK(expect_pqf("@prox 0 0 0 0 k 0 a b", + "@attrset Bib-1 @prox 0 0 0 0 k 0 a b", + YAZ_PQF_ERROR_NONE)); + YAZ_CHECK(expect_pqf("@prox 0 0 0 0 3 0 a b", "", + YAZ_PQF_ERROR_PROXIMITY)); + YAZ_CHECK(expect_pqf("@attr 1=12345678901 x", "@attrset Bib-1 @attr 1=12345678901 x", YAZ_PQF_ERROR_NONE)); + YAZ_CHECK(expect_pqf("@attr 1=1234567890.1 x", "@attrset Bib-1 @attr 1=1234567890.1 x", YAZ_PQF_ERROR_NONE)); +} + +int main (int argc, char **argv) +{ + YAZ_CHECK_INIT(argc, argv); + tst(); + YAZ_CHECK_TERM; +} + +/* + * Local variables: + * c-basic-offset: 4 + * c-file-style: "Stroustrup" + * indent-tabs-mode: nil + * End: + * vim: shiftwidth=4 tabstop=8 expandtab + */ + diff --git a/pool/shard002/C/0058807_time.c b/pool/shard002/C/0058807_time.c new file mode 100644 index 0000000000000000000000000000000000000000..60349062595a9f5c0d420a75bab4faf3a9ace8d8 --- /dev/null +++ b/pool/shard002/C/0058807_time.c @@ -0,0 +1,180 @@ +/* + * linux/arch/mips/dec/time.c + * + * Copyright (C) 1991, 1992, 1995 Linus Torvalds + * Copyright (C) 2000, 2003 Maciej W. Rozycki + * + * This file contains the time handling details for PC-style clocks as + * found in some MIPS systems. + * + */ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +unsigned long read_persistent_clock(void) +{ + unsigned int year, mon, day, hour, min, sec, real_year; + unsigned long flags; + + spin_lock_irqsave(&rtc_lock, flags); + + do { + sec = CMOS_READ(RTC_SECONDS); + min = CMOS_READ(RTC_MINUTES); + hour = CMOS_READ(RTC_HOURS); + day = CMOS_READ(RTC_DAY_OF_MONTH); + mon = CMOS_READ(RTC_MONTH); + year = CMOS_READ(RTC_YEAR); + /* + * The PROM will reset the year to either '72 or '73. + * Therefore we store the real year separately, in one + * of unused BBU RAM locations. + */ + real_year = CMOS_READ(RTC_DEC_YEAR); + } while (sec != CMOS_READ(RTC_SECONDS)); + + spin_unlock_irqrestore(&rtc_lock, flags); + + if (!(CMOS_READ(RTC_CONTROL) & RTC_DM_BINARY) || RTC_ALWAYS_BCD) { + sec = BCD2BIN(sec); + min = BCD2BIN(min); + hour = BCD2BIN(hour); + day = BCD2BIN(day); + mon = BCD2BIN(mon); + year = BCD2BIN(year); + } + + year += real_year - 72 + 2000; + + return mktime(year, mon, day, hour, min, sec); +} + +/* + * In order to set the CMOS clock precisely, rtc_mips_set_mmss has to + * be called 500 ms after the second nowtime has started, because when + * nowtime is written into the registers of the CMOS clock, it will + * jump to the next second precisely 500 ms later. Check the Dallas + * DS1287 data sheet for details. + */ +int rtc_mips_set_mmss(unsigned long nowtime) +{ + int retval = 0; + int real_seconds, real_minutes, cmos_minutes; + unsigned char save_control, save_freq_select; + + /* irq are locally disabled here */ + spin_lock(&rtc_lock); + /* tell the clock it's being set */ + save_control = CMOS_READ(RTC_CONTROL); + CMOS_WRITE((save_control | RTC_SET), RTC_CONTROL); + + /* stop and reset prescaler */ + save_freq_select = CMOS_READ(RTC_FREQ_SELECT); + CMOS_WRITE((save_freq_select | RTC_DIV_RESET2), RTC_FREQ_SELECT); + + cmos_minutes = CMOS_READ(RTC_MINUTES); + if (!(save_control & RTC_DM_BINARY) || RTC_ALWAYS_BCD) + cmos_minutes = BCD2BIN(cmos_minutes); + + /* + * since we're only adjusting minutes and seconds, + * don't interfere with hour overflow. This avoids + * messing with unknown time zones but requires your + * RTC not to be off by more than 15 minutes + */ + real_seconds = nowtime % 60; + real_minutes = nowtime / 60; + if (((abs(real_minutes - cmos_minutes) + 15) / 30) & 1) + real_minutes += 30; /* correct for half hour time zone */ + real_minutes %= 60; + + if (abs(real_minutes - cmos_minutes) < 30) { + if (!(save_control & RTC_DM_BINARY) || RTC_ALWAYS_BCD) { + real_seconds = BIN2BCD(real_seconds); + real_minutes = BIN2BCD(real_minutes); + } + CMOS_WRITE(real_seconds, RTC_SECONDS); + CMOS_WRITE(real_minutes, RTC_MINUTES); + } else { + printk(KERN_WARNING + "set_rtc_mmss: can't update from %d to %d\n", + cmos_minutes, real_minutes); + retval = -1; + } + + /* The following flags have to be released exactly in this order, + * otherwise the DS1287 will not reset the oscillator and will not + * update precisely 500 ms later. You won't find this mentioned + * in the Dallas Semiconductor data sheets, but who believes data + * sheets anyway ... -- Markus Kuhn + */ + CMOS_WRITE(save_control, RTC_CONTROL); + CMOS_WRITE(save_freq_select, RTC_FREQ_SELECT); + spin_unlock(&rtc_lock); + + return retval; +} + +static int dec_timer_state(void) +{ + return (CMOS_READ(RTC_REG_C) & RTC_PF) != 0; +} + +static void dec_timer_ack(void) +{ + CMOS_READ(RTC_REG_C); /* Ack the RTC interrupt. */ +} + +static cycle_t dec_ioasic_hpt_read(void) +{ + /* + * The free-running counter is 32-bit which is good for about + * 2 minutes, 50 seconds at possible count rates of up to 25MHz. + */ + return ioasic_read(IO_REG_FCTR); +} + + +void __init plat_time_init(void) +{ + mips_timer_ack = dec_timer_ack; + + if (!cpu_has_counter && IOASIC) + /* For pre-R4k systems we use the I/O ASIC's counter. */ + clocksource_mips.read = dec_ioasic_hpt_read; + + /* Set up the rate of periodic DS1287 interrupts. */ + CMOS_WRITE(RTC_REF_CLCK_32KHZ | (16 - __ffs(HZ)), RTC_REG_A); +} + +void __init plat_timer_setup(struct irqaction *irq) +{ + setup_irq(dec_interrupt[DEC_IRQ_RTC], irq); + + /* Enable periodic DS1287 interrupts. */ + CMOS_WRITE(CMOS_READ(RTC_REG_B) | RTC_PIE, RTC_REG_B); +} diff --git a/pool/shard002/C/0058823_vbox_drv.c b/pool/shard002/C/0058823_vbox_drv.c new file mode 100644 index 0000000000000000000000000000000000000000..48fd95acf9e32bd602b6fb8a29ec97e334121fa0 --- /dev/null +++ b/pool/shard002/C/0058823_vbox_drv.c @@ -0,0 +1,159 @@ +/** @file $Id: vbox_drv.c 52864 2014-09-26 09:15:04Z vboxsync $ + * + * VirtualBox Additions Linux kernel video driver + */ + +/* + * Copyright (C) 2013 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. + * -------------------------------------------------------------------- + * + * This code is based on + * ast_drv.c + * with the following copyright and permission notice: + * + * 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, sub license, 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 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 NON-INFRINGEMENT. IN NO EVENT SHALL + * THE COPYRIGHT HOLDERS, AUTHORS AND/OR ITS SUPPLIERS 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. + * + * The above copyright notice and this permission notice (including the + * next paragraph) shall be included in all copies or substantial portions + * of the Software. + * + */ +/* + * Authors: Dave Airlie + */ +#include "vbox_drv.h" + +#include + +#include +#include + +#include +#include + +int vbox_modeset = -1; + +MODULE_PARM_DESC(modeset, "Disable/Enable modesetting"); +module_param_named(modeset, vbox_modeset, int, 0400); + +static struct drm_driver driver; + +static DEFINE_PCI_DEVICE_TABLE(pciidlist) = +{ + {0x80ee, 0xbeef, PCI_ANY_ID, PCI_ANY_ID, 0, 0, 0}, + {0, 0, 0}, +}; + +MODULE_DEVICE_TABLE(pci, pciidlist); + +static int vbox_pci_probe(struct pci_dev *pdev, const struct pci_device_id *ent) +{ + return drm_get_pci_dev(pdev, ent, &driver); +} + + +static void vbox_pci_remove(struct pci_dev *pdev) +{ + struct drm_device *dev = pci_get_drvdata(pdev); + + drm_put_dev(dev); +} + + +static struct pci_driver vbox_pci_driver = +{ + .name = DRIVER_NAME, + .id_table = pciidlist, + .probe = vbox_pci_probe, + .remove = vbox_pci_remove, +}; + + +static const struct file_operations vbox_fops = +{ + .owner = THIS_MODULE, + .open = drm_open, + .release = drm_release, + .unlocked_ioctl = drm_ioctl, + .mmap = vbox_mmap, + .poll = drm_poll, +#if LINUX_VERSION_CODE < KERNEL_VERSION(3, 12, 0) + .fasync = drm_fasync, +#endif +#ifdef CONFIG_COMPAT + .compat_ioctl = drm_compat_ioctl, +#endif + .read = drm_read, +}; + +static struct drm_driver driver = +{ + .driver_features = DRIVER_MODESET | DRIVER_GEM, + .dev_priv_size = 0, + + .load = vbox_driver_load, + .unload = vbox_driver_unload, + .lastclose = vbox_driver_lastclose, + + .fops = &vbox_fops, + .name = DRIVER_NAME, + .desc = DRIVER_DESC, + .date = DRIVER_DATE, + .major = DRIVER_MAJOR, + .minor = DRIVER_MINOR, + .patchlevel = DRIVER_PATCHLEVEL, + + .gem_free_object = vbox_gem_free_object, + .dumb_create = vbox_dumb_create, + .dumb_map_offset = vbox_dumb_mmap_offset, + .dumb_destroy = vbox_dumb_destroy, + +}; + +static int __init vbox_init(void) +{ +#ifdef CONFIG_VGA_CONSOLE + if (vgacon_text_force() && vbox_modeset == -1) + return -EINVAL; +#endif + + if (vbox_modeset == 0) + return -EINVAL; + return drm_pci_init(&driver, &vbox_pci_driver); +} +static void __exit vbox_exit(void) +{ + drm_pci_exit(&driver, &vbox_pci_driver); +} + +module_init(vbox_init); +module_exit(vbox_exit); + +MODULE_AUTHOR(DRIVER_AUTHOR); +MODULE_DESCRIPTION(DRIVER_DESC); +MODULE_LICENSE("GPL and additional rights"); + diff --git a/pool/shard002/C/0058828_basic_integ.c b/pool/shard002/C/0058828_basic_integ.c new file mode 100644 index 0000000000000000000000000000000000000000..8d79121812cf1fc6e4b3840f64de6c08379737a0 --- /dev/null +++ b/pool/shard002/C/0058828_basic_integ.c @@ -0,0 +1,118 @@ + +/************************************************************************/ +/* Copyright Jérôme Lelong */ +/* */ +/* 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, 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 */ +/* 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 */ +/* . */ +/************************************************************************/ + +#include +#include "pnl/pnl_mathtools.h" +#include "pnl/pnl_integration.h" + +/** + * Evaluate an integral over [x0, x1] with a non-adaptive method + * + * @param *F a PnlFunc to be integrated + * @param x0 left corner of domain + * @param x1 rightt corner of domain + * @param n the number of steps to be used + * @param meth a character string can be "rect" (rectangle rule), "trap" + * (trapezoidal rule), "simpson" (Simpson's rule) + * @return the value of the integral + */ +double pnl_integration(PnlFunc *F, double x0, double x1, int n, const char *meth) +{ + double h, xh, sum; + + h = (x1 - x0) / (double)n; + sum = 0.; + + /* sum over the strictly inner points */ + for (xh = x0 + h; xh < x1; xh += h) + { + sum += PNL_EVAL_FUNC(F, xh); + } + + if (strcmp(meth, "rect") == 0) + { + sum += PNL_EVAL_FUNC(F, x0); + } + else if (strcmp(meth, "trap") == 0) + { + sum += (PNL_EVAL_FUNC(F, x0) + PNL_EVAL_FUNC(F, x1)) / 2.; + } + else if (strcmp(meth, "simpson") == 0) + { + double sum2 = 0.; + for (xh = x0 + h / 2; xh < x1; xh += h) + { + sum2 += PNL_EVAL_FUNC(F, xh); + } + sum = 2. * sum + PNL_EVAL_FUNC(F, x0) + PNL_EVAL_FUNC(F, x1) + 4. * sum2; + sum /= 6.; + } + else + { + PNL_ERROR("unknow method", "pnl_integration"); + } + + sum *= h; + return sum; +} + + +static double xsav, y0sav, y1sav; +static int nysav; +static const char *methsav; +static const PnlFunc2D *globalfunc; + +static double func1D(double y, void *params) +{ + return globalfunc->F(xsav, y, params); +} + +static double int_1d(double x, void *params) +{ + PnlFunc wrap_1d; + wrap_1d.F = func1D; + wrap_1d.params = params; + xsav = x; + return pnl_integration(&wrap_1d, y0sav, y1sav, nysav, methsav); +} +/** + * integrate a function on [x0,x1]x[y0, y1] + * @param *F a PnlFunc of two variables to be integrated + * @param x0 bottom left corner of domain + * @param x1 bottom right corner of domain + * @param y0 top left corner of domain + * @param y1 top right corner of domain + * @param nx the number of steps to discretise [x0, x1] + * @param ny the number of steps to discretise [y0, y1] + * @param meth a character string can be "rect" (rectangle rule), "trap" + * (rapezoidal rule), "simpson" (Simpson's rule) + * @return the value of the integral + */ +double pnl_integration_2d(PnlFunc2D *F, double x0, double x1, double y0, double y1, int nx, int ny, const char *meth) +{ + PnlFunc func_1d; + func_1d.F = &int_1d; + func_1d.params = NULL; + globalfunc = F; + y0sav = y0; + y1sav = y1; + nysav = ny; + methsav = meth; + return pnl_integration(&func_1d, x0, x1, nx, meth); +} diff --git a/pool/shard002/C/0058836_mutex_kernel.c b/pool/shard002/C/0058836_mutex_kernel.c new file mode 100644 index 0000000000000000000000000000000000000000..28d62a3e9ed204d076be89f58539b51e7b31540b --- /dev/null +++ b/pool/shard002/C/0058836_mutex_kernel.c @@ -0,0 +1,285 @@ +/* + * Linux 2.6.32 and later Kernel module for VMware MVP Hypervisor Support + * + * Copyright (C) 2010-2012 VMware, Inc. 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; see the file COPYING. If not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + */ +#line 5 + + +#include + +#include +#include +#include +#include +#include +#include +#include + +#include "mvp.h" + +#include "arm_inline.h" +#include "coproc_defs.h" +#include "mutex_kernel.h" + +#define POLL_IN_PROGRESS_FLAG (1<<(30-MUTEX_CVAR_MAX)) + +#define INITWAITQ(waitQ) do { \ + init_waitqueue_head((wait_queue_head_t *)(waitQ)); \ +} while (0) + +#define WAKEUPALL(waitQ) do { \ + wake_up_all((wait_queue_head_t *)(waitQ)); \ +} while (0) + +#define WAKEUPONE(waitQ) do { \ + wake_up((wait_queue_head_t *)(waitQ)); \ +} while (0) + +void +Mutex_Init(Mutex *mutex) +{ + wait_queue_head_t *wq; + int i; + + wq = kcalloc(MUTEX_CVAR_MAX + 1, sizeof(wait_queue_head_t), 0); + FATAL_IF(wq == NULL); + + memset(mutex, 0, sizeof *mutex); + mutex->mtxHKVA = (HKVA)mutex; + mutex->lockWaitQ = (HKVA)&wq[0]; + INITWAITQ(mutex->lockWaitQ); + for (i = 0; i < MUTEX_CVAR_MAX; i ++) { + mutex->cvarWaitQs[i] = (HKVA)&wq[i + 1]; + INITWAITQ(mutex->cvarWaitQs[i]); + } +} + +static void +MutexCheckSleep(const char *file, int line) +{ +#ifdef MVP_DEVEL + static unsigned long prev_jiffy; + +#ifdef CONFIG_PREEMPT + if (preemptible() && !irqs_disabled()) { + return; + } +#else + if (!irqs_disabled()) { + return; + } +#endif + if (time_before(jiffies, prev_jiffy + HZ) && prev_jiffy) { + return; + } + prev_jiffy = jiffies; + printk(KERN_ERR + "BUG: sleeping function called from invalid context at %s:%d\n", + file, line); + printk(KERN_ERR + "irqs_disabled(): %d, preemtible(): %d, pid: %d, name: %s\n", + irqs_disabled(), + preemptible(), + current->pid, current->comm); + dump_stack(); +#endif +} + +void +Mutex_Destroy(Mutex *mutex) +{ + kfree((void*)mutex->lockWaitQ); +} + +int +Mutex_LockLine(Mutex *mutex, MutexMode mode, const char *file, int line) +{ + Mutex_State newState, oldState; + + MutexCheckSleep(file, line); + + do { +lock_start: + oldState.state = ATOMIC_GETO(mutex->state); + newState.mode = oldState.mode + mode; + newState.blck = oldState.blck; + + if ((uint32)newState.mode >= (uint32)mode) { + if (!ATOMIC_SETIF(mutex->state, newState.state, oldState.state)) { + goto lock_start; + } + DMB(); + mutex->line = line; + mutex->lineUnl = -1; + return 0; + } + + newState.mode = oldState.mode; + newState.blck = oldState.blck + 1; + } while (!ATOMIC_SETIF(mutex->state, newState.state, oldState.state)); + + ATOMIC_ADDV(mutex->blocked, 1); + + do { + DEFINE_WAIT(waiter); + + prepare_to_wait((wait_queue_head_t *)mutex->lockWaitQ, + &waiter, + TASK_INTERRUPTIBLE); + + +set_new_state: + oldState.state = ATOMIC_GETO(mutex->state); + newState.mode = oldState.mode + mode; + newState.blck = oldState.blck - 1; + ASSERT(oldState.blck); + + if ((uint32)newState.mode >= (uint32)mode) { + if (!ATOMIC_SETIF(mutex->state, newState.state, oldState.state)) { + goto set_new_state; + } + finish_wait((wait_queue_head_t *)mutex->lockWaitQ, &waiter); + DMB(); + mutex->line = line; + mutex->lineUnl = -1; + return 0; + } + + WARN(!schedule_timeout(10*HZ), "Mutex_Lock: soft lockup - stuck for 10s!\n"); + finish_wait((wait_queue_head_t *)mutex->lockWaitQ, &waiter); + } while (!signal_pending(current)); + + do { + oldState.state = ATOMIC_GETO(mutex->state); + newState.mode = oldState.mode; + newState.blck = oldState.blck - 1; + + ASSERT(oldState.blck); + + } while (!ATOMIC_SETIF(mutex->state, newState.state, oldState.state)); + + return -ERESTARTSYS; +} + + +void +Mutex_UnlockLine(Mutex *mutex, MutexMode mode, int line) +{ + Mutex_State newState, oldState; + + DMB(); + do { + oldState.state = ATOMIC_GETO(mutex->state); + newState.mode = oldState.mode - mode; + newState.blck = oldState.blck; + mutex->lineUnl = line; + + ASSERT(oldState.mode >= mode); + } while (!ATOMIC_SETIF(mutex->state, newState.state, oldState.state)); + + if (oldState.blck) { + if (mode == MutexModeSH) { + WAKEUPONE(mutex->lockWaitQ); + } else { + WAKEUPALL(mutex->lockWaitQ); + } + } +} + + +int +Mutex_UnlSleepLine(Mutex *mutex, MutexMode mode, uint32 cvi, const char *file, int line) +{ + return Mutex_UnlSleepTestLine(mutex, mode, cvi, NULL, 0, file, line); +} + +int +Mutex_UnlSleepTestLine(Mutex *mutex, MutexMode mode, uint32 cvi, AtmUInt32 *test, uint32 mask, const char *file, int line) +{ + DEFINE_WAIT(waiter); + + MutexCheckSleep(file, line); + + ASSERT(cvi < MUTEX_CVAR_MAX); + + ATOMIC_ADDV(mutex->waiters, 1); + + prepare_to_wait_exclusive((wait_queue_head_t *)mutex->cvarWaitQs[cvi], + &waiter, + TASK_INTERRUPTIBLE); + + Mutex_Unlock(mutex, mode); + + if (test == NULL || (ATOMIC_GETO(*test) & mask) == 0) { + schedule(); + } + finish_wait((wait_queue_head_t *)mutex->cvarWaitQs[cvi], &waiter); + + ATOMIC_SUBV(mutex->waiters, 1); + + if (signal_pending(current)) { + return -ERESTARTSYS; + } + + return 0; +} + + +void +Mutex_UnlPoll(Mutex *mutex, MutexMode mode, uint32 cvi, void *filp, void *wait) +{ + ASSERT(cvi < MUTEX_CVAR_MAX); + + poll_wait(filp, (wait_queue_head_t *)mutex->cvarWaitQs[cvi], wait); + + DMB(); + ATOMIC_ORO(mutex->waiters, (POLL_IN_PROGRESS_FLAG << cvi)); + + Mutex_Unlock(mutex, mode); +} + + +void +Mutex_UnlWake(Mutex *mutex, MutexMode mode, uint32 cvi, _Bool all) +{ + Mutex_Unlock(mutex, mode); + Mutex_CondSig(mutex, cvi, all); +} + + +void +Mutex_CondSig(Mutex *mutex, uint32 cvi, _Bool all) +{ + uint32 waiters; + + ASSERT(cvi < MUTEX_CVAR_MAX); + + waiters = ATOMIC_GETO(mutex->waiters); + if (waiters != 0) { + if ((waiters >= POLL_IN_PROGRESS_FLAG) && + !waitqueue_active((wait_queue_head_t *)mutex->cvarWaitQs[cvi])) { + ATOMIC_ANDO(mutex->waiters, ~(POLL_IN_PROGRESS_FLAG << cvi)); + } + DMB(); + + if (all) { + WAKEUPALL(mutex->cvarWaitQs[cvi]); + } else { + WAKEUPONE(mutex->cvarWaitQs[cvi]); + } + } +} diff --git a/pool/shard002/C/0058864_stm32f4xx_hal_iwdg.c b/pool/shard002/C/0058864_stm32f4xx_hal_iwdg.c new file mode 100644 index 0000000000000000000000000000000000000000..ba86cd652ad3f0ed1509073f235b4e5b6bb88f6c --- /dev/null +++ b/pool/shard002/C/0058864_stm32f4xx_hal_iwdg.c @@ -0,0 +1,361 @@ +/** + ****************************************************************************** + * @file stm32f4xx_hal_iwdg.c + * @author MCD Application Team + * @version V1.3.0 + * @date 09-March-2015 + * @brief IWDG HAL module driver. + * This file provides firmware functions to manage the following + * functionalities of the Independent Watchdog (IWDG) peripheral: + * + Initialization and Configuration functions + * + IO operation functions + * + Peripheral State functions + * + @verbatim + ============================================================================== + ##### IWDG Specific features ##### + ============================================================================== + [..] + (+) The IWDG can be started by either software or hardware (configurable + through option byte). + + (+) The IWDG is clocked by its own dedicated Low-Speed clock (LSI) and + thus stays active even if the main clock fails. + Once the IWDG is started, the LSI is forced ON and cannot be disabled + (LSI cannot be disabled too), and the counter starts counting down from + the reset value of 0xFFF. When it reaches the end of count value (0x000) + a system reset is generated. + + (+) The IWDG counter should be refreshed at regular intervals, otherwise the + watchdog generates an MCU reset when the counter reaches 0. + + (+) The IWDG is implemented in the VDD voltage domain that is still functional + in STOP and STANDBY mode (IWDG reset can wake-up from STANDBY). + IWDGRST flag in RCC_CSR register can be used to inform when an IWDG + reset occurs. + + (+) Min-max timeout value @32KHz (LSI): ~125us / ~32.7s + The IWDG timeout may vary due to LSI frequency dispersion. STM32F4xx + devices provide the capability to measure the LSI frequency (LSI clock + connected internally to TIM5 CH4 input capture). The measured value + can be used to have an IWDG timeout with an acceptable accuracy. + + + ##### How to use this driver ##### + ============================================================================== + [..] + If Window option is disabled + (+) Use IWDG using HAL_IWDG_Init() function to : + (++) Enable write access to IWDG_PR, IWDG_RLR. + (++) Configure the IWDG prescaler, counter reload value. + This reload value will be loaded in the IWDG counter each time the counter + is reloaded, then the IWDG will start counting down from this value. + [..] + (+) Use IWDG using HAL_IWDG_Start() function to: + (++) Reload IWDG counter with value defined in the IWDG_RLR register. + (++) Start the IWDG, when the IWDG is used in software mode (no need + to enable the LSI, it will be enabled by hardware). + (+) Then the application program must refresh the IWDG counter at regular + intervals during normal operation to prevent an MCU reset, using + HAL_IWDG_Refresh() function. + [..] + if Window option is enabled: + + (+) Use IWDG using HAL_IWDG_Start() function to enable IWDG downcounter + (+) Use IWDG using HAL_IWDG_Init() function to : + (++) Enable write access to IWDG_PR, IWDG_RLR and IWDG_WINR registers. + (++) Configure the IWDG prescaler, reload value and window value. + (+) Then the application program must refresh the IWDG counter at regular + intervals during normal operation to prevent an MCU reset, using + HAL_IWDG_Refresh() function. + + *** IWDG HAL driver macros list *** + ==================================== + [..] + Below the list of most used macros in IWDG HAL driver. + + (+) __HAL_IWDG_START: Enable the IWDG peripheral + (+) __HAL_IWDG_RELOAD_COUNTER: Reloads IWDG counter with value defined in the reload register + (+) __HAL_IWDG_GET_FLAG: Get the selected IWDG's flag status + + @endverbatim + ****************************************************************************** + * @attention + * + *

© 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 "stm32f4xx_hal.h" + +/** @addtogroup STM32F4xx_HAL_Driver + * @{ + */ + +/** @defgroup IWDG IWDG + * @brief IWDG HAL module driver. + * @{ + */ + +#ifdef HAL_IWDG_MODULE_ENABLED + +/* Private typedef -----------------------------------------------------------*/ +/* Private define ------------------------------------------------------------*/ + /** @addtogroup IWDG_Private_Constants + * @{ + */ +#define IWDG_TIMEOUT_FLAG ((uint32_t)1000) /* 1 s */ +/** + * @} + */ +/* Private macro -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private function prototypes -----------------------------------------------*/ +/* Private functions ---------------------------------------------------------*/ +/* Exported functions --------------------------------------------------------*/ +/** @defgroup IWDG_Exported_Functions IWDG Exported Functions + * @{ + */ + +/** @defgroup IWDG_Exported_Functions_Group1 Initialization and de-initialization functions + * @brief Initialization and Configuration functions. + * +@verbatim + =============================================================================== + ##### Initialization and de-initialization functions ##### + =============================================================================== + [..] This section provides functions allowing to: + (+) Initialize the IWDG according to the specified parameters + in the IWDG_InitTypeDef and create the associated handle + (+) Initialize the IWDG MSP + (+) DeInitialize IWDG MSP + +@endverbatim + * @{ + */ + +/** + * @brief Initializes the IWDG according to the specified + * parameters in the IWDG_InitTypeDef and creates the associated handle. + * @param hiwdg: pointer to a IWDG_HandleTypeDef structure that contains + * the configuration information for the specified IWDG module. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_IWDG_Init(IWDG_HandleTypeDef *hiwdg) +{ + /* Check the IWDG handle allocation */ + if(hiwdg == NULL) + { + return HAL_ERROR; + } + + /* Check the parameters */ + assert_param(IS_IWDG_ALL_INSTANCE(hiwdg->Instance)); + assert_param(IS_IWDG_PRESCALER(hiwdg->Init.Prescaler)); + assert_param(IS_IWDG_RELOAD(hiwdg->Init.Reload)); + + if(hiwdg->State == HAL_IWDG_STATE_RESET) + { + /* Allocate lock resource and initialize it */ + hiwdg->Lock = HAL_UNLOCKED; + /* Init the low level hardware */ + HAL_IWDG_MspInit(hiwdg); + } + + /* Change IWDG peripheral state */ + hiwdg->State = HAL_IWDG_STATE_BUSY; + + /* Enable write access to IWDG_PR and IWDG_RLR registers */ + IWDG_ENABLE_WRITE_ACCESS(hiwdg); + + /* Write to IWDG registers the IWDG_Prescaler & IWDG_Reload values to work with */ + MODIFY_REG(hiwdg->Instance->PR, IWDG_PR_PR, hiwdg->Init.Prescaler); + MODIFY_REG(hiwdg->Instance->RLR, IWDG_RLR_RL, hiwdg->Init.Reload); + + /* Change IWDG peripheral state */ + hiwdg->State = HAL_IWDG_STATE_READY; + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Initializes the IWDG MSP. + * @param hiwdg: pointer to a IWDG_HandleTypeDef structure that contains + * the configuration information for the specified IWDG module. + * @retval None + */ +__weak void HAL_IWDG_MspInit(IWDG_HandleTypeDef *hiwdg) +{ + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_IWDG_MspInit could be implemented in the user file + */ +} + +/** + * @} + */ + +/** @defgroup IWDG_Exported_Functions_Group2 IO operation functions + * @brief IO operation functions + * +@verbatim + =============================================================================== + ##### IO operation functions ##### + =============================================================================== + [..] This section provides functions allowing to: + (+) Start the IWDG. + (+) Refresh the IWDG. + +@endverbatim + * @{ + */ + +/** + * @brief Starts the IWDG. + * @param hiwdg: pointer to a IWDG_HandleTypeDef structure that contains + * the configuration information for the specified IWDG module. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_IWDG_Start(IWDG_HandleTypeDef *hiwdg) +{ + /* Process Locked */ + __HAL_LOCK(hiwdg); + + /* Change IWDG peripheral state */ + hiwdg->State = HAL_IWDG_STATE_BUSY; + + /* Start the IWDG peripheral */ + __HAL_IWDG_START(hiwdg); + + /* Reload IWDG counter with value defined in the RLR register */ + __HAL_IWDG_RELOAD_COUNTER(hiwdg); + + /* Change IWDG peripheral state */ + hiwdg->State = HAL_IWDG_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hiwdg); + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Refreshes the IWDG. + * @param hiwdg: pointer to a IWDG_HandleTypeDef structure that contains + * the configuration information for the specified IWDG module. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_IWDG_Refresh(IWDG_HandleTypeDef *hiwdg) +{ + uint32_t tickstart = 0; + + /* Process Locked */ + __HAL_LOCK(hiwdg); + + /* Change IWDG peripheral state */ + hiwdg->State = HAL_IWDG_STATE_BUSY; + + tickstart = HAL_GetTick(); + + /* Wait until RVU flag is RESET */ + while(__HAL_IWDG_GET_FLAG(hiwdg, IWDG_FLAG_RVU) != RESET) + { + if((HAL_GetTick() - tickstart ) > IWDG_TIMEOUT_FLAG) + { + /* Set IWDG state */ + hiwdg->State = HAL_IWDG_STATE_TIMEOUT; + + /* Process unlocked */ + __HAL_UNLOCK(hiwdg); + + return HAL_TIMEOUT; + } + } + + /* Reload IWDG counter with value defined in the reload register */ + __HAL_IWDG_RELOAD_COUNTER(hiwdg); + + /* Change IWDG peripheral state */ + hiwdg->State = HAL_IWDG_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hiwdg); + + /* Return function status */ + return HAL_OK; +} + +/** + * @} + */ + +/** @defgroup IWDG_Exported_Functions_Group3 Peripheral State functions + * @brief Peripheral State functions. + * +@verbatim + =============================================================================== + ##### Peripheral State functions ##### + =============================================================================== + [..] + This subsection permits to get in run-time the status of the peripheral + and the data flow. + +@endverbatim + * @{ + */ + +/** + * @brief Returns the IWDG state. + * @param hiwdg: pointer to a IWDG_HandleTypeDef structure that contains + * the configuration information for the specified IWDG module. + * @retval HAL state + */ +HAL_IWDG_StateTypeDef HAL_IWDG_GetState(IWDG_HandleTypeDef *hiwdg) +{ + return hiwdg->State; +} + +/** + * @} + */ + +/** + * @} + */ + +#endif /* HAL_IWDG_MODULE_ENABLED */ +/** + * @} + */ + +/** + * @} + */ + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/pool/shard002/C/0058876_check_json.c b/pool/shard002/C/0058876_check_json.c new file mode 100644 index 0000000000000000000000000000000000000000..8bd2cc496627a7af2d5f3af08086613bbb200c76 --- /dev/null +++ b/pool/shard002/C/0058876_check_json.c @@ -0,0 +1,59 @@ +/* + * check_json.c + * Copyright (C) 2014 c9s + * + * Distributed under terms of the MIT license. + */ +#include "config.h" +#include +#include +#include +#include +#include "r3.h" +#include "r3_str.h" +#include "r3_json.h" +#include "zmalloc.h" + +START_TEST (test_json_encode) +{ + node * n; + n = r3_tree_create(10); + + ck_assert(n); + + r3_tree_insert_path(n, "/zoo", NULL); + r3_tree_insert_path(n, "/foo", NULL); + r3_tree_insert_path(n, "/bar", NULL); + + r3_tree_insert_route(n, METHOD_GET, "/post/get", NULL); + r3_tree_insert_route(n, METHOD_POST, "/post/post", NULL); + + r3_tree_compile(n, NULL); + + json_object * obj = r3_node_to_json_object(n); + ck_assert(obj); + + const char *json = r3_node_to_json_pretty_string(n); + + printf("JSON: %s\n",json); +} +END_TEST + +Suite* r3_suite (void) { + Suite *suite = suite_create("json test"); + TCase *tcase = tcase_create("json test"); + tcase_add_test(tcase, test_json_encode); + suite_add_tcase(suite, tcase); + return suite; +} + +int main (int argc, char *argv[]) { + int number_failed; + Suite *suite = r3_suite(); + SRunner *runner = srunner_create(suite); + srunner_run_all(runner, CK_NORMAL); + number_failed = srunner_ntests_failed(runner); + srunner_free(runner); + return number_failed; +} + diff --git a/pool/shard002/C/0058885_main.c b/pool/shard002/C/0058885_main.c new file mode 100644 index 0000000000000000000000000000000000000000..d45f92efe875652665aceb0e00c805602b30d1ae --- /dev/null +++ b/pool/shard002/C/0058885_main.c @@ -0,0 +1,216 @@ +/* + * Copyright (c) 2015 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. + */ + +/** + * @file Sample app to utilize GPIO on Arduino 101 and Arduino Due. + * + * Arduino 101 - x86 + * -------------------- + * + * On x86 side of Arduino 101: + * 1. GPIO_16 is on IO8 + * 2. GPIO_19 is on IO4 + * + * The gpio_dw driver is being used. + * + * This sample app toggles GPIO_16/IO8. It also waits for + * GPIO_19/IO4 to go high and display a message. + * + * If IO4 and IO8 are connected together, the GPIO should + * triggers every 2 seconds. And you should see this repeatedly + * on console: + * " + * Toggling GPIO_16 + * Toggling GPIO_16 + * GPIO_19 triggered + * " + * + * Arduino 101 - Sensor Subsystem + * ------------------------------ + * + * On Sensor Subsystem of Arduino 101: + * 1. GPIO_SS[ 2] is on A00 + * 2. GPIO_SS[ 3] is on A01 + * 3. GPIO_SS[ 4] is on A02 + * 4. GPIO_SS[ 5] is on A03 + * 5. GPIO_SS[10] is on IO3 + * 6. GPIO_SS[11] is on IO5 + * 7. GPIO_SS[12] is on IO6 + * 8. GPIO_SS[13] is on IO9 + * + * There are two 8-bit GPIO controllers on the sensor subsystem. + * GPIO_SS[0-7] are on GPIO_0 while GPIO_SS[8-15] are on GPIO_1. + * + * The gpio_dw driver is being used. The first GPIO controller + * is mapped to device "GPIO_0", and the second GPIO controller + * is mapped to device "GPIO_1". + * + * This sample app toggles GPIO_SS_2/A0. It also waits for + * GPIO_SS_3/A1 to go high and display a message. + * + * If A0 and A1 are connected together, the GPIO should + * triggers every 2 seconds. And you should see this repeatedly + * on console (via ipm_console0): + * " + * Toggling GPIO_SS_2 + * Toggling GPIO_SS_2 + * GPIO_SS_3 triggered + * " + * + * Arduino Due + * ----------- + * + * On Arduino Due: + * 1. IO_2 is PB25 + * 2. IO_13 is PB27 (linked to the LED marked "L") + * + * The gpio_atmel_sam3 driver is being used. + * + * This sample app toggles IO_2. It also waits for + * IO_13 to go high and display a message. + * + * If IO_2 and IO_13 are connected together, the GPIO should + * triggers every 2 seconds. And you should see this repeatedly + * on console: + * " + * Toggling GPIO_25 + * Toggling GPIO_25 + * GPIO_27 triggered + * " + * + * Quark D2000 CRB + * --------------- + * + * In order to this sample app work with Quark D2000 CRB you should + * use a "jumper cable" connecting the pins as described below: + * Header J5 pin 9 + * Header J6 pin 7 + * + * If the app runs successfully you should see this repeatedly on + * console: + * " + * Toggling GPIO_8 + * Toggling GPIO_8 + * GPIO_24 triggered + * " + */ + +#include + +#include + +#include +#include +#include +#include + +#define SLEEPTICKS SECONDS(1) + +#if defined(CONFIG_SOC_QUARK_SE_SS) +#define GPIO_OUT_PIN 2 +#define GPIO_INT_PIN 3 +#define GPIO_NAME "GPIO_SS_" +#elif defined(CONFIG_SOC_QUARK_SE) +#define GPIO_OUT_PIN 16 +#define GPIO_INT_PIN 19 +#define GPIO_NAME "GPIO_" +#elif defined(CONFIG_SOC_ATMEL_SAM3) +#define GPIO_OUT_PIN 25 +#define GPIO_INT_PIN 27 +#define GPIO_NAME "GPIO_" +#elif defined(CONFIG_SOC_QUARK_D2000) +#define GPIO_OUT_PIN 8 +#define GPIO_INT_PIN 24 +#define GPIO_NAME "GPIO_" +#endif + +#if defined(CONFIG_GPIO_DW_0) +#define GPIO_DRV_NAME CONFIG_GPIO_DW_0_NAME +#elif defined(CONFIG_GPIO_QMSI_0) +#define GPIO_DRV_NAME CONFIG_GPIO_QMSI_0_NAME +#elif defined(CONFIG_GPIO_ATMEL_SAM3) +#define GPIO_DRV_NAME CONFIG_GPIO_ATMEL_SAM3_PORTB_DEV_NAME +#else +#define GPIO_DRV_NAME "GPIO_0" +#endif + +void gpio_callback(struct device *port, + struct gpio_callback *cb, uint32_t pins) +{ + printk(GPIO_NAME "%d triggered\n", GPIO_INT_PIN); +} + +static struct gpio_callback gpio_cb; + +void main(void) +{ + struct nano_timer timer; + void *timer_data[1]; + struct device *gpio_dev; + int ret; + int toggle = 1; + + nano_timer_init(&timer, timer_data); + + gpio_dev = device_get_binding(GPIO_DRV_NAME); + if (!gpio_dev) { + printk("Cannot find %s!\n", GPIO_DRV_NAME); + } + + /* Setup GPIO output */ + ret = gpio_pin_configure(gpio_dev, GPIO_OUT_PIN, (GPIO_DIR_OUT)); + if (ret) { + printk("Error configuring " GPIO_NAME "%d!\n", GPIO_OUT_PIN); + } + + /* Setup GPIO input, and triggers on rising edge. */ + ret = gpio_pin_configure(gpio_dev, GPIO_INT_PIN, + (GPIO_DIR_IN | GPIO_INT | GPIO_INT_EDGE + | GPIO_INT_ACTIVE_HIGH | GPIO_INT_DEBOUNCE)); + if (ret) { + printk("Error configuring " GPIO_NAME "%d!\n", GPIO_INT_PIN); + } + + gpio_init_callback(&gpio_cb, gpio_callback, BIT(GPIO_INT_PIN)); + + ret = gpio_add_callback(gpio_dev, &gpio_cb); + if (ret) { + printk("Cannot setup callback!\n"); + } + + ret = gpio_pin_enable_callback(gpio_dev, GPIO_INT_PIN); + if (ret) { + printk("Error enabling callback!\n"); + } + + while (1) { + printk("Toggling " GPIO_NAME "%d\n", GPIO_OUT_PIN); + + ret = gpio_pin_write(gpio_dev, GPIO_OUT_PIN, toggle); + if (ret) { + printk("Error set " GPIO_NAME "%d!\n", GPIO_OUT_PIN); + } + + if (toggle) { + toggle = 0; + } else { + toggle = 1; + } + + nano_timer_start(&timer, SLEEPTICKS); + nano_timer_test(&timer, TICKS_UNLIMITED); + } +} diff --git a/pool/shard002/C/0058889_block.c b/pool/shard002/C/0058889_block.c new file mode 100644 index 0000000000000000000000000000000000000000..c094054b8fdccf323d3111d9b31e15ae2ef53120 --- /dev/null +++ b/pool/shard002/C/0058889_block.c @@ -0,0 +1,201 @@ +/* + * Copyright (c) 2002 Juli Mallett. All rights reserved. + * + * This software was written by Juli Mallett for the + * FreeBSD project. Redistribution and use in source and binary forms, with + * or without modification, are permitted provided that the following + * conditions are met: + * + * 1. Redistribution of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistribution 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. + */ + +#include +__FBSDID("$FreeBSD: soc2013/dpl/head/lib/libufs/block.c 228631 2011-12-08 12:31:47Z rmh $"); + +#include +#include +#include +#include +#include + +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +#include + +ssize_t +bread(struct uufsd *disk, ufs2_daddr_t blockno, void *data, size_t size) +{ + void *p2; + ssize_t cnt; + + ERROR(disk, NULL); + + p2 = data; + /* + * XXX: various disk controllers require alignment of our buffer + * XXX: which is stricter than struct alignment. + * XXX: Bounce the buffer if not 64 byte aligned. + * XXX: this can be removed if/when the kernel is fixed + */ + if (((intptr_t)data) & 0x3f) { + p2 = malloc(size); + if (p2 == NULL) { + ERROR(disk, "allocate bounce buffer"); + goto fail; + } + } + cnt = pread(disk->d_fd, p2, size, (off_t)(blockno * disk->d_bsize)); + if (cnt == -1) { + ERROR(disk, "read error from block device"); + goto fail; + } + if (cnt == 0) { + ERROR(disk, "end of file from block device"); + goto fail; + } + if ((size_t)cnt != size) { + ERROR(disk, "short read or read error from block device"); + goto fail; + } + if (p2 != data) { + memcpy(data, p2, size); + free(p2); + } + return (cnt); +fail: memset(data, 0, size); + if (p2 != data) { + free(p2); + } + return (-1); +} + +ssize_t +bwrite(struct uufsd *disk, ufs2_daddr_t blockno, const void *data, size_t size) +{ + ssize_t cnt; + int rv; + void *p2 = NULL; + + ERROR(disk, NULL); + + rv = ufs_disk_write(disk); + if (rv == -1) { + ERROR(disk, "failed to open disk for writing"); + return (-1); + } + + /* + * XXX: various disk controllers require alignment of our buffer + * XXX: which is stricter than struct alignment. + * XXX: Bounce the buffer if not 64 byte aligned. + * XXX: this can be removed if/when the kernel is fixed + */ + if (((intptr_t)data) & 0x3f) { + p2 = malloc(size); + if (p2 == NULL) { + ERROR(disk, "allocate bounce buffer"); + return (-1); + } + memcpy(p2, data, size); + data = p2; + } + cnt = pwrite(disk->d_fd, data, size, (off_t)(blockno * disk->d_bsize)); + if (p2 != NULL) + free(p2); + if (cnt == -1) { + ERROR(disk, "write error to block device"); + return (-1); + } + if ((size_t)cnt != size) { + ERROR(disk, "short write to block device"); + return (-1); + } + + return (cnt); +} + +#ifdef __FreeBSD_kernel__ + +static int +berase_helper(struct uufsd *disk, ufs2_daddr_t blockno, ufs2_daddr_t size) +{ + off_t ioarg[2]; + + ioarg[0] = blockno * disk->d_bsize; + ioarg[1] = size; + return (ioctl(disk->d_fd, DIOCGDELETE, ioarg)); +} + +#else + +static int +berase_helper(struct uufsd *disk, ufs2_daddr_t blockno, ufs2_daddr_t size) +{ + char *zero_chunk; + off_t offset, zero_chunk_size, pwrite_size; + int rv; + + offset = blockno * disk->d_bsize; + zero_chunk_size = 65536 * disk->d_bsize; + zero_chunk = calloc(1, zero_chunk_size); + if (zero_chunk == NULL) { + ERROR(disk, "failed to allocate memory"); + return (-1); + } + while (size > 0) { + pwrite_size = size; + if (pwrite_size > zero_chunk_size) + pwrite_size = zero_chunk_size; + rv = pwrite(disk->d_fd, zero_chunk, pwrite_size, offset); + if (rv == -1) { + ERROR(disk, "failed writing to disk"); + break; + } + size -= rv; + offset += rv; + rv = 0; + } + free(zero_chunk); + return (rv); +} + +#endif + +int +berase(struct uufsd *disk, ufs2_daddr_t blockno, ufs2_daddr_t size) +{ + int rv; + + ERROR(disk, NULL); + rv = ufs_disk_write(disk); + if (rv == -1) { + ERROR(disk, "failed to open disk for writing"); + return(rv); + } + return (berase_helper(disk, blockno, size)); +} diff --git a/pool/shard002/C/0058906_autotools-notebook-page.c b/pool/shard002/C/0058906_autotools-notebook-page.c new file mode 100644 index 0000000000000000000000000000000000000000..e63f7d7027ac832cf4a7c38fe8db736465de418f --- /dev/null +++ b/pool/shard002/C/0058906_autotools-notebook-page.c @@ -0,0 +1,130 @@ +/* + * Copyright (C) 2010 - Jeff Johnston + * + * 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 "autotools-notebook-page.h" + +static void autotools_notebook_page_class_init (AutotoolsNotebookPageClass *klass); +static void autotools_notebook_page_init (AutotoolsNotebookPage *notebook_page); +static void autotools_notebook_page_finalize (AutotoolsNotebookPage *notebook_page); + +static void add_output (AutotoolsNotebookPage *notebook_page, + GtkWidget *output); +static void add_buttons (AutotoolsNotebookPage *notebook_page, + GtkWidget *output); +static void clear_action (GtkWidget *output); + +#define AUTOTOOLS_NOTEBOOK_PAGE_GET_PRIVATE(obj) \ + (G_TYPE_INSTANCE_GET_PRIVATE ((obj), AUTOTOOLS_NOTEBOOK_PAGE_TYPE, AutotoolsNotebookPagePrivate)) + +typedef struct _AutotoolsNotebookPagePrivate AutotoolsNotebookPagePrivate; + +struct _AutotoolsNotebookPagePrivate +{ + GtkWidget *output; +}; + +G_DEFINE_TYPE (AutotoolsNotebookPage, autotools_notebook_page, GTK_TYPE_HBOX) + +static void +autotools_notebook_page_class_init (AutotoolsNotebookPageClass *klass) +{ + GObjectClass *gobject_class = G_OBJECT_CLASS (klass); + gobject_class->finalize = (GObjectFinalizeFunc) autotools_notebook_page_finalize; + g_type_class_add_private (klass, sizeof (AutotoolsNotebookPagePrivate)); +} + +static void +autotools_notebook_page_init (AutotoolsNotebookPage *notebook_page) {} + +static void +autotools_notebook_page_finalize (AutotoolsNotebookPage *notebook_page) +{ + G_OBJECT_CLASS (autotools_notebook_page_parent_class)->finalize (G_OBJECT(notebook_page)); +} + +GtkWidget* +autotools_notebook_page_new (GtkWidget *output) +{ + AutotoolsNotebookPagePrivate *priv; + GtkWidget *notebook_page; + + notebook_page = g_object_new (autotools_notebook_page_get_type (), NULL); + priv = AUTOTOOLS_NOTEBOOK_PAGE_GET_PRIVATE (notebook_page); + priv->output = output; + + add_output (AUTOTOOLS_NOTEBOOK_PAGE (notebook_page), output); + add_buttons (AUTOTOOLS_NOTEBOOK_PAGE (notebook_page), output); + + return notebook_page; +} + +static void +add_buttons (AutotoolsNotebookPage *notebook_page, + GtkWidget *output) +{ + GtkWidget *grid; + GtkWidget *clear_button; + GtkWidget *clear_image; + + grid = gtk_grid_new (); + gtk_grid_set_row_spacing (GTK_GRID (grid), 2); + + clear_button = gtk_button_new (); + gtk_widget_set_tooltip_text (clear_button, "Clear"); + + gtk_button_set_relief (GTK_BUTTON (clear_button), GTK_RELIEF_NONE); + gtk_button_set_focus_on_click (GTK_BUTTON (clear_button), FALSE); + clear_image = gtk_image_new_from_stock (GTK_STOCK_CLEAR, GTK_ICON_SIZE_MENU); + gtk_container_add (GTK_CONTAINER (clear_button), clear_image); + gtk_widget_set_can_focus (clear_button, FALSE); + + gtk_grid_attach (GTK_GRID (grid), clear_button, 0, 0, 1, 1); + + gtk_box_pack_start (GTK_BOX (notebook_page), grid, FALSE, FALSE, 2); + + g_signal_connect_swapped (G_OBJECT (clear_button), "clicked", + G_CALLBACK (clear_action), output); +} + +static void +add_output (AutotoolsNotebookPage *notebook_page, + GtkWidget *output) +{ + GtkWidget *scrolled_window; + + scrolled_window = gtk_scrolled_window_new (NULL, NULL); + gtk_scrolled_window_set_policy (GTK_SCROLLED_WINDOW (scrolled_window), + GTK_POLICY_AUTOMATIC, GTK_POLICY_AUTOMATIC); + gtk_container_add (GTK_CONTAINER (scrolled_window), GTK_WIDGET (output)); + + gtk_box_pack_start (GTK_BOX (notebook_page), scrolled_window, TRUE, TRUE, 0); +} + +static void +clear_action (GtkWidget *output) +{ + GtkTextBuffer *buffer; + buffer = gtk_text_view_get_buffer (GTK_TEXT_VIEW (output)); + gtk_text_buffer_set_text (buffer, "", -1); +} + +GtkWidget* +autotools_notebook_page_get_output (AutotoolsNotebookPage *notebook_page) +{ + return AUTOTOOLS_NOTEBOOK_PAGE_GET_PRIVATE (notebook_page)->output; +} diff --git a/pool/shard002/C/0058921_stl_io.c b/pool/shard002/C/0058921_stl_io.c new file mode 100644 index 0000000000000000000000000000000000000000..7845831a487d5d1ecfe9a7549d6c2c12be513173 --- /dev/null +++ b/pool/shard002/C/0058921_stl_io.c @@ -0,0 +1,139 @@ +/**************************************************************************** +** Copyright (c) 2017, Fougue Ltd. +** 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 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 "stl_io.h" + +#include "stl_error.h" +#include "internal/stla_write.h" +#include "internal/stlb_write.h" +#include "../gmio_core/error.h" +#include "../gmio_core/internal/byte_codec.h" +#include "../gmio_core/internal/helper_memblock.h" +#include "../gmio_core/internal/helper_stream.h" + +int gmio_stl_read( + struct gmio_stream* stream, + struct gmio_stl_mesh_creator* mesh_creator, + const struct gmio_stl_read_options* options) +{ + const enum gmio_stl_format format = gmio_stl_format_probe(stream); + switch (format) { + case GMIO_STL_FORMAT_ASCII: + return gmio_stla_read(stream, mesh_creator, options); + case GMIO_STL_FORMAT_BINARY_BE: + return gmio_stlb_read( + stream, mesh_creator, GMIO_ENDIANNESS_BIG, options); + case GMIO_STL_FORMAT_BINARY_LE: + return gmio_stlb_read( + stream, mesh_creator, GMIO_ENDIANNESS_LITTLE, options); + case GMIO_STL_FORMAT_UNKNOWN: + return GMIO_STL_ERROR_UNKNOWN_FORMAT; + } + return GMIO_ERROR_UNKNOWN; +} + +int gmio_stl_read_file( + const char* filepath, + struct gmio_stl_mesh_creator* mesh_creator, + const struct gmio_stl_read_options* options) +{ + FILE* file = fopen(filepath, "rb"); + if (file != NULL) { + struct gmio_stream stream = gmio_stream_stdio(file); + const int error = gmio_stl_read(&stream, mesh_creator, options); + fclose(file); + return error; + } + return GMIO_ERROR_STDIO; +} + +int gmio_stl_write( + enum gmio_stl_format format, + struct gmio_stream* stream, + const struct gmio_stl_mesh* mesh, + const struct gmio_stl_write_options* options) +{ + switch (format) { + case GMIO_STL_FORMAT_ASCII: + return gmio_stla_write(stream, mesh, options); + case GMIO_STL_FORMAT_BINARY_BE: + return gmio_stlb_write(GMIO_ENDIANNESS_BIG, stream, mesh, options); + case GMIO_STL_FORMAT_BINARY_LE: + return gmio_stlb_write(GMIO_ENDIANNESS_LITTLE, stream, mesh, options); + case GMIO_STL_FORMAT_UNKNOWN: + return GMIO_STL_ERROR_UNKNOWN_FORMAT; + } + return GMIO_ERROR_UNKNOWN; +} + +int gmio_stl_write_file( + enum gmio_stl_format format, + const char* filepath, + const struct gmio_stl_mesh* mesh, + const struct gmio_stl_write_options* options) +{ + FILE* file = fopen(filepath, "wb"); + if (file != NULL) { + struct gmio_stream stream = gmio_stream_stdio(file); + const int error = gmio_stl_write(format, &stream, mesh, options); + fclose(file); + return error; + } + return GMIO_ERROR_STDIO; +} + +static const struct gmio_stlb_header internal_stlb_zero_header = {0}; + +int gmio_stlb_header_write( + struct gmio_stream *stream, + enum gmio_endianness byte_order, + const struct gmio_stlb_header *header, + uint32_t facet_count) +{ + uint8_t facet_count_bytes[sizeof(uint32_t)]; + const struct gmio_stlb_header* non_null_header = + header != NULL ? header : &internal_stlb_zero_header; + + /* Write 80-byte header */ + if (gmio_stream_write(stream, non_null_header, GMIO_STLB_HEADER_SIZE, 1) + != 1) + { + return GMIO_ERROR_STREAM; + } + + /* Write facet count */ + if (byte_order == GMIO_ENDIANNESS_LITTLE) + gmio_encode_uint32_le(facet_count, facet_count_bytes); + else + gmio_encode_uint32_be(facet_count, facet_count_bytes); + if (gmio_stream_write(stream, facet_count_bytes, sizeof(uint32_t), 1) != 1) + return GMIO_ERROR_STREAM; + + return GMIO_ERROR_OK; +} diff --git a/pool/shard002/C/0058933_veritysetup.c b/pool/shard002/C/0058933_veritysetup.c new file mode 100644 index 0000000000000000000000000000000000000000..7b8fd60bf8fe9b9e56186b94bed422cf4febd973 --- /dev/null +++ b/pool/shard002/C/0058933_veritysetup.c @@ -0,0 +1,136 @@ +/* SPDX-License-Identifier: LGPL-2.1+ */ +/*** + This file is part of systemd. + + Copyright 2016 Lennart Poettering +***/ + +#include +#include +#include + +#include "alloc-util.h" +#include "crypt-util.h" +#include "hexdecoct.h" +#include "log.h" +#include "string-util.h" + +static char *arg_root_hash = NULL; +static char *arg_data_what = NULL; +static char *arg_hash_what = NULL; + +static int help(void) { + printf("%s attach VOLUME DATADEVICE HASHDEVICE ROOTHASH\n" + "%s detach VOLUME\n\n" + "Attaches or detaches an integrity protected block device.\n", + program_invocation_short_name, + program_invocation_short_name); + + return 0; +} + +int main(int argc, char *argv[]) { + _cleanup_(crypt_freep) struct crypt_device *cd = NULL; + int r; + + if (argc <= 1) { + r = help(); + goto finish; + } + + if (argc < 3) { + log_error("This program requires at least two arguments."); + r = -EINVAL; + goto finish; + } + + log_set_target(LOG_TARGET_AUTO); + log_parse_environment(); + log_open(); + + umask(0022); + + if (streq(argv[1], "attach")) { + _cleanup_free_ void *m = NULL; + crypt_status_info status; + size_t l; + + if (argc < 6) { + log_error("attach requires at least two arguments."); + r = -EINVAL; + goto finish; + } + + r = unhexmem(argv[5], strlen(argv[5]), &m, &l); + if (r < 0) { + log_error("Failed to parse root hash."); + goto finish; + } + + r = crypt_init(&cd, argv[4]); + if (r < 0) { + log_error_errno(r, "Failed to open verity device %s: %m", argv[4]); + goto finish; + } + + crypt_set_log_callback(cd, cryptsetup_log_glue, NULL); + + status = crypt_status(cd, argv[2]); + if (IN_SET(status, CRYPT_ACTIVE, CRYPT_BUSY)) { + log_info("Volume %s already active.", argv[2]); + r = 0; + goto finish; + } + + r = crypt_load(cd, CRYPT_VERITY, NULL); + if (r < 0) { + log_error_errno(r, "Failed to load verity superblock: %m"); + goto finish; + } + + r = crypt_set_data_device(cd, argv[3]); + if (r < 0) { + log_error_errno(r, "Failed to configure data device: %m"); + goto finish; + } + + r = crypt_activate_by_volume_key(cd, argv[2], m, l, CRYPT_ACTIVATE_READONLY); + if (r < 0) { + log_error_errno(r, "Failed to set up verity device: %m"); + goto finish; + } + + } else if (streq(argv[1], "detach")) { + + r = crypt_init_by_name(&cd, argv[2]); + if (r == -ENODEV) { + log_info("Volume %s already inactive.", argv[2]); + goto finish; + } else if (r < 0) { + log_error_errno(r, "crypt_init_by_name() failed: %m"); + goto finish; + } + + crypt_set_log_callback(cd, cryptsetup_log_glue, NULL); + + r = crypt_deactivate(cd, argv[2]); + if (r < 0) { + log_error_errno(r, "Failed to deactivate: %m"); + goto finish; + } + + } else { + log_error("Unknown verb %s.", argv[1]); + r = -EINVAL; + goto finish; + } + + r = 0; + +finish: + free(arg_root_hash); + free(arg_data_what); + free(arg_hash_what); + + return r < 0 ? EXIT_FAILURE : EXIT_SUCCESS; +} diff --git a/pool/shard002/C/0058938_com_sableio.c b/pool/shard002/C/0058938_com_sableio.c new file mode 100644 index 0000000000000000000000000000000000000000..160b8046744b5e54803061f88dbcc3fc0bf78ec7 --- /dev/null +++ b/pool/shard002/C/0058938_com_sableio.c @@ -0,0 +1,146 @@ +/* $NetBSD: com_sableio.c,v 1.1 2000/12/21 20:51:56 thorpej Exp $ */ + +/*- + * Copyright (c) 1999 The NetBSD Foundation, Inc. + * All rights reserved. + * + * This code is derived from software contributed to The NetBSD Foundation + * by Jason R. Thorpe. + * + * 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 NetBSD + * Foundation, Inc. and its contributors. + * 4. Neither the name of The NetBSD Foundation 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 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 /* RCS ID & Copyright macro defns */ + +__KERNEL_RCSID(0, "$NetBSD: com_sableio.c,v 1.1 2000/12/21 20:51:56 thorpej Exp $"); + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +#include +#include + +#include +#include + +#include + +struct com_sableio_softc { + struct com_softc sc_com; /* real "com" softc */ + + /* STDIO-specific goo. */ + void *sc_ih; /* interrupt handler */ +}; + +int com_sableio_match(struct device *, struct cfdata *, void *); +void com_sableio_attach(struct device *, struct device *, void *); +void com_sableio_cleanup(void *); + +struct cfattach com_sableio_ca = { + sizeof(struct com_sableio_softc), com_sableio_match, com_sableio_attach +}; + +int +com_sableio_match(struct device *parent, struct cfdata *match, void *aux) +{ + struct sableio_attach_args *sa = aux; + + /* Always present. */ + if (strcmp(sa->sa_name, match->cf_driver->cd_name) == 0) + return (1); + + return (0); +} + +void +com_sableio_attach(struct device *parent, struct device *self, void *aux) +{ + struct com_sableio_softc *ssc = (void *)self; + struct com_softc *sc = &ssc->sc_com; + struct sableio_attach_args *sa = aux; + const char *intrstr; + + sc->sc_iot = sa->sa_iot; + sc->sc_iobase = sa->sa_ioaddr; + + if (com_is_console(sc->sc_iot, sc->sc_iobase, &sc->sc_ioh) == 0 && + bus_space_map(sc->sc_iot, sc->sc_iobase, COM_NPORTS, 0, + &sc->sc_ioh) != 0) { + printf(": can't map i/o space\n"); + return; + } + + sc->sc_frequency = COM_FREQ; + + com_attach_subr(sc); + + intrstr = pci_intr_string(sa->sa_pc, sa->sa_sableirq[0]); + ssc->sc_ih = pci_intr_establish(sa->sa_pc, sa->sa_sableirq[0], + IPL_SERIAL, comintr, sc); + if (ssc->sc_ih == NULL) { + printf("%s: unable to establish interrupt", + sc->sc_dev.dv_xname); + if (intrstr != NULL) + printf(" at %s", intrstr); + printf("\n"); + return; + } + printf("%s: interrupting at %s\n", sc->sc_dev.dv_xname, intrstr); + + /* + * Shutdown hook for buggy BIOSs that don't recognize the UART + * without a disabled FIFO. + */ + if (shutdownhook_establish(com_sableio_cleanup, sc) == NULL) + panic("com_sableio_attach: could not establish shutdown hook"); +} + +void +com_sableio_cleanup(void *arg) +{ + struct com_softc *sc = arg; + + if (ISSET(sc->sc_hwflags, COM_HW_FIFO)) + bus_space_write_1(sc->sc_iot, sc->sc_ioh, com_fifo, 0); +} diff --git a/pool/shard002/C/0058952_besselpoly.c b/pool/shard002/C/0058952_besselpoly.c new file mode 100644 index 0000000000000000000000000000000000000000..b4356bae35b08ab4a4bb56ba2acc62965393b649 --- /dev/null +++ b/pool/shard002/C/0058952_besselpoly.c @@ -0,0 +1,43 @@ + +#include +extern double cephes_Gamma (double x); + + +#define EPS 1.0e-17 + +double besselpoly(double a, double lambda, double nu) { + + int m, factor=0; + double Sm, relerr, Sol; + double sum=0.0; + + /* Special handling for a = 0.0 */ + if (a == 0.0) { + if (nu == 0.0) return 1.0/(lambda + 1); + else return 0.0; + } + /* Special handling for negative and integer nu */ + if ((nu < 0) && (floor(nu)==nu)) { + nu = -nu; + factor = ((int) nu) % 2; + } + Sm = exp(nu*log(a))/(cephes_Gamma(nu+1)*(lambda+nu+1)); + m = 0; + do { + sum += Sm; + Sol = Sm; + Sm *= -a*a*(lambda+nu+1+2*m)/((nu+m+1)*(m+1)*(lambda+nu+1+2*m+2)); + m++; + relerr = fabs((Sm-Sol)/Sm); + } while (relerr > EPS && m < 1000); + if (!factor) + return sum; + else + return -sum; +} + + + + + + diff --git a/pool/shard002/C/0058954_grib_accessor_class_evaluate.c b/pool/shard002/C/0058954_grib_accessor_class_evaluate.c new file mode 100644 index 0000000000000000000000000000000000000000..d7e63c75a7b79a091370dcd2632a4afb03067fe4 --- /dev/null +++ b/pool/shard002/C/0058954_grib_accessor_class_evaluate.c @@ -0,0 +1,159 @@ +/* + * Copyright 2005-2017 ECMWF. + * + * This software is licensed under the terms of the Apache Licence Version 2.0 + * which can be obtained at http://www.apache.org/licenses/LICENSE-2.0. + * + * In applying this licence, ECMWF does not waive the privileges and immunities granted to it by + * virtue of its status as an intergovernmental organisation nor does it submit to any jurisdiction. + */ + +#include "grib_api_internal.h" +/* + This is used by make_class.pl + + START_CLASS_DEF + CLASS = accessor + SUPER = grib_accessor_class_long + IMPLEMENTS = unpack_long;pack_long + IMPLEMENTS = init + MEMBERS= grib_arguments* arg + END_CLASS_DEF + + */ + +/* START_CLASS_IMP */ + +/* + +Don't edit anything between START_CLASS_IMP and END_CLASS_IMP +Instead edit values between START_CLASS_DEF and END_CLASS_DEF +or edit "accessor.class" and rerun ./make_class.pl + +*/ + +static int pack_long(grib_accessor*, const long* val,size_t *len); +static int unpack_long(grib_accessor*, long* val,size_t *len); +static void init(grib_accessor*,const long, grib_arguments* ); +static void init_class(grib_accessor_class*); + +typedef struct grib_accessor_evaluate { + grib_accessor att; +/* Members defined in gen */ +/* Members defined in long */ +/* Members defined in evaluate */ + grib_arguments* arg; +} grib_accessor_evaluate; + +extern grib_accessor_class* grib_accessor_class_long; + +static grib_accessor_class _grib_accessor_class_evaluate = { + &grib_accessor_class_long, /* super */ + "evaluate", /* name */ + sizeof(grib_accessor_evaluate), /* size */ + 0, /* inited */ + &init_class, /* init_class */ + &init, /* init */ + 0, /* post_init */ + 0, /* free mem */ + 0, /* describes himself */ + 0, /* get length of section */ + 0, /* get length of string */ + 0, /* get number of values */ + 0, /* get number of bytes */ + 0, /* get offset to bytes */ + 0, /* get native type */ + 0, /* get sub_section */ + 0, /* grib_pack procedures long */ + 0, /* grib_pack procedures long */ + &pack_long, /* grib_pack procedures long */ + &unpack_long, /* grib_unpack procedures long */ + 0, /* grib_pack procedures double */ + 0, /* grib_unpack procedures double */ + 0, /* grib_pack procedures string */ + 0, /* grib_unpack procedures string */ + 0, /* grib_pack array procedures string */ + 0, /* grib_unpack array procedures string */ + 0, /* grib_pack procedures bytes */ + 0, /* grib_unpack procedures bytes */ + 0, /* pack_expression */ + 0, /* notify_change */ + 0, /* update_size */ + 0, /* preferred_size */ + 0, /* resize */ + 0, /* nearest_smaller_value */ + 0, /* next accessor */ + 0, /* compare vs. another accessor */ + 0, /* unpack only ith value */ + 0, /* unpack a subarray */ + 0, /* clear */ + 0, /* clone accessor */ +}; + + +grib_accessor_class* grib_accessor_class_evaluate = &_grib_accessor_class_evaluate; + + +static void init_class(grib_accessor_class* c) +{ + c->dump = (*(c->super))->dump; + c->next_offset = (*(c->super))->next_offset; + c->string_length = (*(c->super))->string_length; + c->value_count = (*(c->super))->value_count; + c->byte_count = (*(c->super))->byte_count; + c->byte_offset = (*(c->super))->byte_offset; + c->get_native_type = (*(c->super))->get_native_type; + c->sub_section = (*(c->super))->sub_section; + c->pack_missing = (*(c->super))->pack_missing; + c->is_missing = (*(c->super))->is_missing; + c->pack_double = (*(c->super))->pack_double; + c->unpack_double = (*(c->super))->unpack_double; + c->pack_string = (*(c->super))->pack_string; + c->unpack_string = (*(c->super))->unpack_string; + c->pack_string_array = (*(c->super))->pack_string_array; + c->unpack_string_array = (*(c->super))->unpack_string_array; + c->pack_bytes = (*(c->super))->pack_bytes; + c->unpack_bytes = (*(c->super))->unpack_bytes; + c->pack_expression = (*(c->super))->pack_expression; + c->notify_change = (*(c->super))->notify_change; + c->update_size = (*(c->super))->update_size; + c->preferred_size = (*(c->super))->preferred_size; + c->resize = (*(c->super))->resize; + c->nearest_smaller_value = (*(c->super))->nearest_smaller_value; + c->next = (*(c->super))->next; + c->compare = (*(c->super))->compare; + c->unpack_double_element = (*(c->super))->unpack_double_element; + c->unpack_double_subarray = (*(c->super))->unpack_double_subarray; + c->clear = (*(c->super))->clear; + c->make_clone = (*(c->super))->make_clone; +} + +/* END_CLASS_IMP */ + +static void init(grib_accessor* a,const long l, grib_arguments* c) +{ + grib_accessor_evaluate* self = (grib_accessor_evaluate*)a; + self->arg = c; + a->flags |= GRIB_ACCESSOR_FLAG_READ_ONLY; +} + +static int pack_long(grib_accessor* a, const long* val, size_t *len){ + + return GRIB_NOT_IMPLEMENTED; + +} + + +static int unpack_long(grib_accessor* a, long* val, size_t *len) +{ + int ret=0; + grib_accessor_evaluate* self = (grib_accessor_evaluate*)a; + grib_expression* e = grib_arguments_get_expression(grib_handle_of_accessor(a),self->arg,0); + + + ret = grib_expression_evaluate_long(grib_handle_of_accessor(a),e,val); + *len = 1; + + return ret; +} + diff --git a/pool/shard002/C/0058970_test_Trmm.c b/pool/shard002/C/0058970_test_Trmm.c new file mode 100644 index 0000000000000000000000000000000000000000..3b92cdecd3c13e9a7d77033a7cdf0b9a99808529 --- /dev/null +++ b/pool/shard002/C/0058970_test_Trmm.c @@ -0,0 +1,222 @@ +/* + + Copyright (C) 2014, The University of Texas at Austin + + This file is part of libflame and is available under the 3-Clause + BSD license, which can be found in the LICENSE file at the top-level + directory, or at http://opensource.org/licenses/BSD-3-Clause + +*/ + +#include "FLAME.h" + + +#define N_PARAM_COMBOS 12 + +#define FLA_ALG_REFERENCE 0 +#define FLA_ALG_FRONT 1 + +char* pc_str[N_PARAM_COMBOS] = { "llh", "lln", "llt", + "luh", "lun", "lut", + "rlh", "rln", "rlt", + "ruh", "run", "rut" }; + +void time_Trmm( + int param_combo, int type, int n_repeats, int m, int n, + FLA_Obj A, FLA_Obj C, FLA_Obj C_ref, + double *dtime, double *diff, double *gflops ); + + +int main(int argc, char *argv[]) +{ + int + datatype, + precision, + m_input, n_input, + m, n, + p_first, p_last, p_inc, + p, + n_repeats, + param_combo, + i, + n_param_combos = N_PARAM_COMBOS; + + dim_t nb_alg, n_threads; + + char *colors = "brkgmcbrkgmcbrkgmc"; + char *ticks = "o+*xso+*xso+*xso+*xs"; + char m_dim_desc[14]; + char n_dim_desc[14]; + char m_dim_tag[10]; + char n_dim_tag[10]; + + double max_gflops=6.0; + + double + dtime, + gflops, + diff; + + FLA_Obj + A, C, C_ref; + + FLA_Init( ); + + + fprintf( stdout, "%c number of repeats: ", '%' ); + scanf( "%d", &n_repeats ); + fprintf( stdout, "%c %d\n", '%', n_repeats ); + + fprintf( stdout, "%c enter FLASH blocksize: ", '%' ); + scanf( "%d", &nb_alg ); + fprintf( stdout, "%c %d\n", '%', nb_alg ); + + fprintf( stdout, "%c enter problem size first, last, inc: ", '%' ); + scanf( "%d%d%d", &p_first, &p_last, &p_inc ); + fprintf( stdout, "%c %d %d %d\n", '%', p_first, p_last, p_inc ); + + fprintf( stdout, "%c enter m n (-1 means bind to problem size): ", '%' ); + scanf( "%d%d", &m_input, &n_input ); + fprintf( stdout, "%c %d %d\n", '%', m_input, n_input ); + + fprintf( stdout, "%c enter the number of SuperMatrix threads: ", '%' ); + scanf( "%d", &n_threads ); + fprintf( stdout, "%c %d\n", '%', n_threads ); + + + fprintf( stdout, "\nclear all;\n\n" ); + + + if ( m_input > 0 ) { + sprintf( m_dim_desc, "m = %d", m_input ); + sprintf( m_dim_tag, "m%dc", m_input); + } + else if( m_input < -1 ) { + sprintf( m_dim_desc, "m = p/%d", -m_input ); + sprintf( m_dim_tag, "m%dp", -m_input ); + } + else if( m_input == -1 ) { + sprintf( m_dim_desc, "m = p" ); + sprintf( m_dim_tag, "m%dp", 1 ); + } + if ( n_input > 0 ) { + sprintf( n_dim_desc, "n = %d", n_input ); + sprintf( n_dim_tag, "n%dc", n_input); + } + else if( n_input < -1 ) { + sprintf( n_dim_desc, "n = p/%d", -n_input ); + sprintf( n_dim_tag, "n%dp", -n_input ); + } + else if( n_input == -1 ) { + sprintf( n_dim_desc, "n = p" ); + sprintf( n_dim_tag, "n%dp", 1 ); + } + + //precision = FLA_SINGLE_PRECISION; + precision = FLA_DOUBLE_PRECISION; + + FLASH_Queue_set_num_threads( n_threads ); + //FLASH_Queue_set_verbose_output( TRUE ); + + for ( p = p_first, i = 1; p <= p_last; p += p_inc, i += 1 ) + { + m = m_input; + n = n_input; + + if( m < 0 ) m = p / abs(m_input); + if( n < 0 ) n = p / abs(n_input); + + for ( param_combo = 0; param_combo < n_param_combos; param_combo++ ){ + + // Determine datatype based on trans argument. + if ( pc_str[param_combo][2] == 'h' ) + { + if ( precision == FLA_SINGLE_PRECISION ) + datatype = FLA_COMPLEX; + else + datatype = FLA_DOUBLE_COMPLEX; + } + else + { + if ( precision == FLA_SINGLE_PRECISION ) + datatype = FLA_FLOAT; + else + datatype = FLA_DOUBLE; + } + + // If multiplying A on the left, A is m x m; ...on the right, A is n x n. + if ( pc_str[param_combo][0] == 'l' ) + FLASH_Obj_create( datatype, m, m, 1, &nb_alg, &A ); + else + FLASH_Obj_create( datatype, n, n, 1, &nb_alg, &A ); + + FLASH_Obj_create( datatype, m, n, 1, &nb_alg, &C ); + FLASH_Obj_create( datatype, m, n, 1, &nb_alg, &C_ref ); + + FLASH_Random_matrix( A ); + FLASH_Random_matrix( C ); + + FLASH_Copy( C, C_ref ); + + fprintf( stdout, "data_trmm_%s( %d, 1:5 ) = [ %d ", pc_str[param_combo], i, p ); + fflush( stdout ); + + time_Trmm( param_combo, FLA_ALG_REFERENCE, n_repeats, m, n, + A, C, C_ref, &dtime, &diff, &gflops ); + + fprintf( stdout, "%6.3lf %6.2le ", gflops, diff ); + fflush( stdout ); + + time_Trmm( param_combo, FLA_ALG_FRONT, n_repeats, m, n, + A, C, C_ref, &dtime, &diff, &gflops ); + + fprintf( stdout, "%6.3lf %6.2le ", gflops, diff ); + fflush( stdout ); + + + fprintf( stdout, " ]; \n" ); + fflush( stdout ); + + FLASH_Obj_free( &A ); + FLASH_Obj_free( &C ); + FLASH_Obj_free( &C_ref ); + } + + fprintf( stdout, "\n" ); + } + +/* + fprintf( stdout, "figure;\n" ); + + fprintf( stdout, "hold on;\n" ); + + for ( i = 0; i < n_param_combos; i++ ) { + fprintf( stdout, "plot( data_trmm_%s( :,1 ), data_trmm_%s( :, 2 ), '%c:%c' ); \n", + pc_str[i], pc_str[i], colors[ i ], ticks[ i ] ); + fprintf( stdout, "plot( data_trmm_%s( :,1 ), data_trmm_%s( :, 4 ), '%c-.%c' ); \n", + pc_str[i], pc_str[i], colors[ i ], ticks[ i ] ); + } + + fprintf( stdout, "legend( ... \n" ); + + for ( i = 0; i < n_param_combos; i++ ) + fprintf( stdout, "'ref\\_trmm\\_%s', 'fla\\_trmm\\_%s', ... \n", pc_str[i], pc_str[i] ); + + fprintf( stdout, "'Location', 'SouthEast' ); \n" ); + + + fprintf( stdout, "xlabel( 'problem size p' );\n" ); + fprintf( stdout, "ylabel( 'GFLOPS/sec.' );\n" ); + fprintf( stdout, "axis( [ 0 %d 0 %.2f ] ); \n", p_last, max_gflops ); + fprintf( stdout, "title( 'FLAME trmm front-end performance (%s, %s)' );\n", + m_dim_desc, n_dim_desc ); + fprintf( stdout, "print -depsc trmm_front_%s_%s.eps\n", m_dim_tag, n_dim_tag ); + fprintf( stdout, "hold off;\n"); + fflush( stdout ); +*/ + + FLA_Finalize( ); + + return 0; +} + diff --git a/pool/shard002/C/0058978_wakeup.c b/pool/shard002/C/0058978_wakeup.c new file mode 100644 index 0000000000000000000000000000000000000000..f25727bf064198f34baf708a69b8ea8b6aa5e61d --- /dev/null +++ b/pool/shard002/C/0058978_wakeup.c @@ -0,0 +1,86 @@ + + +#include +#include +#include +#include +#include + +#include "internal.h" +#include "sleep.h" + +#define _COMPONENT ACPI_SYSTEM_COMPONENT +ACPI_MODULE_NAME("wakeup_devices") + +void acpi_enable_wakeup_device_prep(u8 sleep_state) +{ + struct list_head *node, *next; + + list_for_each_safe(node, next, &acpi_wakeup_device_list) { + struct acpi_device *dev = container_of(node, + struct acpi_device, + wakeup_list); + + if (!dev->wakeup.flags.valid || !dev->wakeup.state.enabled + || (sleep_state > (u32) dev->wakeup.sleep_state)) + continue; + + acpi_enable_wakeup_device_power(dev, sleep_state); + } +} + +void acpi_enable_wakeup_device(u8 sleep_state) +{ + struct list_head *node, *next; + + /* + * Caution: this routine must be invoked when interrupt is disabled + * Refer ACPI2.0: P212 + */ + list_for_each_safe(node, next, &acpi_wakeup_device_list) { + struct acpi_device *dev = + container_of(node, struct acpi_device, wakeup_list); + + if (!dev->wakeup.flags.valid || !dev->wakeup.state.enabled + || sleep_state > (u32) dev->wakeup.sleep_state) + continue; + + /* The wake-up power should have been enabled already. */ + acpi_enable_gpe(dev->wakeup.gpe_device, dev->wakeup.gpe_number, + ACPI_GPE_TYPE_WAKE); + } +} + +void acpi_disable_wakeup_device(u8 sleep_state) +{ + struct list_head *node, *next; + + list_for_each_safe(node, next, &acpi_wakeup_device_list) { + struct acpi_device *dev = + container_of(node, struct acpi_device, wakeup_list); + + if (!dev->wakeup.flags.valid || !dev->wakeup.state.enabled + || (sleep_state > (u32) dev->wakeup.sleep_state)) + continue; + + acpi_disable_gpe(dev->wakeup.gpe_device, dev->wakeup.gpe_number, + ACPI_GPE_TYPE_WAKE); + acpi_disable_wakeup_device_power(dev); + } +} + +int __init acpi_wakeup_device_init(void) +{ + struct list_head *node, *next; + + mutex_lock(&acpi_device_lock); + list_for_each_safe(node, next, &acpi_wakeup_device_list) { + struct acpi_device *dev = container_of(node, + struct acpi_device, + wakeup_list); + if (dev->wakeup.flags.always_enabled) + dev->wakeup.state.enabled = 1; + } + mutex_unlock(&acpi_device_lock); + return 0; +} diff --git a/pool/shard002/C/0058991_pci_rescan_bus.c b/pool/shard002/C/0058991_pci_rescan_bus.c new file mode 100644 index 0000000000000000000000000000000000000000..e926c0b15375e4af61d3cd0db6cc8952bd6e8d48 --- /dev/null +++ b/pool/shard002/C/0058991_pci_rescan_bus.c @@ -0,0 +1,29 @@ +/* +pci_rescan_bus.c +*/ + +#include "pci.h" +#include "syslib.h" +#include + +/*===========================================================================* + * pci_rescan_bus * + *===========================================================================*/ +PUBLIC void pci_rescan_bus(u8_t busnr) +{ + int r; + message m; + + m.m_type= BUSC_PCI_RESCAN; + m.m1_i1= busnr; + + r= sendrec(pci_procnr, &m); + if (r != 0) + panic("pci_rescan_bus: can't talk to PCI: %d", r); + + if (m.m_type != 0) + { + panic("pci_rescan_bus: got bad reply from PCI: %d", m.m_type); + } +} + diff --git a/pool/shard002/C/0058992_test2.c b/pool/shard002/C/0058992_test2.c new file mode 100644 index 0000000000000000000000000000000000000000..14d1a975bc8e00d57ffedb4032ca35801ff30e43 --- /dev/null +++ b/pool/shard002/C/0058992_test2.c @@ -0,0 +1,46 @@ +// GNU gcc compiler -std=c11 +// Binary search +#include "stdio.h" +#include "stdlib.h" +#include "math.h" + +#ifndef MAX +#define MAX 20 +#endif + +int search(int *array,int a,int be,int en){ + + if (be==en-1) return be; + if (array[be]==a) return be; + int result; + int mid; + mid=(be+en)/2; + if (array[mid]> 32)); + shift_val = 32 - leading_zeroes; + work_normalized = (u32)(accumulated_work_time >> shift_val); + period_normalized = (u32)(time_period >> shift_val); + + /* + * Now, we should report the usage in parts of 256 + * this means we must shift up the dividend or down the divisor by 8 + * (we could do a combination, but we just use one for simplicity, + * but the end result should be good enough anyway) + */ + if (period_normalized > 0x00FFFFFF) + { + /* The divisor is so big that it is safe to shift it down */ + period_normalized >>= 8; + } + else + { + /* + * The divisor is so small that we can shift up the dividend, without loosing any data. + * (dividend is always smaller than the divisor) + */ + work_normalized <<= 8; + } + + utilization = work_normalized / period_normalized; + + last_utilization = utilization; + + accumulated_work_time = 0; + period_start_time = time_now; /* starting a new period */ + + _mali_osk_lock_signal(time_data_lock, _MALI_OSK_LOCKMODE_RW); + + _mali_osk_timer_add(utilization_timer, _mali_osk_time_mstoticks(mali_utilization_timeout)); + + if (NULL != mali_utilization_callback) + { + mali_utilization_callback(utilization); + } +} + +_mali_osk_errcode_t mali_utilization_init(void) +{ +#if USING_GPU_UTILIZATION + struct _mali_osk_device_data data; + if (_MALI_OSK_ERR_OK == _mali_osk_device_data_get(&data)) + { + /* Use device specific settings (if defined) */ + if (0 != data.utilization_interval) + { + mali_utilization_timeout = data.utilization_interval; + } + if (NULL != data.utilization_handler) + { + mali_utilization_callback = data.utilization_handler; + } + } +#endif + + if (NULL != mali_utilization_callback) + { + MALI_DEBUG_PRINT(2, ("Mali GPU Utilization: Utilization handler installed with interval %u\n", mali_utilization_timeout)); + } + else + { + MALI_DEBUG_PRINT(2, ("Mali GPU Utilization: No utilization handler installed\n")); + } + + time_data_lock = _mali_osk_lock_init(_MALI_OSK_LOCKFLAG_ORDERED | _MALI_OSK_LOCKFLAG_SPINLOCK_IRQ | + _MALI_OSK_LOCKFLAG_NONINTERRUPTABLE, 0, _MALI_OSK_LOCK_ORDER_UTILIZATION); + + if (NULL == time_data_lock) + { + return _MALI_OSK_ERR_FAULT; + } + + _mali_osk_atomic_init(&num_running_cores, 0); + + utilization_timer = _mali_osk_timer_init(); + if (NULL == utilization_timer) + { + _mali_osk_lock_term(time_data_lock); + return _MALI_OSK_ERR_FAULT; + } + _mali_osk_timer_setcallback(utilization_timer, calculate_gpu_utilization, NULL); + + return _MALI_OSK_ERR_OK; +} + +void mali_utilization_suspend(void) +{ + if (NULL != utilization_timer) + { + _mali_osk_timer_del(utilization_timer); + timer_running = MALI_FALSE; + } +} + +void mali_utilization_term(void) +{ + if (NULL != utilization_timer) + { + _mali_osk_timer_del(utilization_timer); + timer_running = MALI_FALSE; + _mali_osk_timer_term(utilization_timer); + utilization_timer = NULL; + } + + _mali_osk_atomic_term(&num_running_cores); + + _mali_osk_lock_term(time_data_lock); +} + +void mali_utilization_core_start(u64 time_now) +{ + if (_mali_osk_atomic_inc_return(&num_running_cores) == 1) + { + /* + * We went from zero cores working, to one core working, + * we now consider the entire GPU for being busy + */ + + _mali_osk_lock_wait(time_data_lock, _MALI_OSK_LOCKMODE_RW); + + if (time_now < period_start_time) + { + /* + * This might happen if the calculate_gpu_utilization() was able + * to run between the sampling of time_now and us grabbing the lock above + */ + time_now = period_start_time; + } + + work_start_time = time_now; + if (timer_running != MALI_TRUE) + { + timer_running = MALI_TRUE; + period_start_time = work_start_time; /* starting a new period */ + + _mali_osk_lock_signal(time_data_lock, _MALI_OSK_LOCKMODE_RW); + + _mali_osk_timer_add(utilization_timer, _mali_osk_time_mstoticks(mali_utilization_timeout)); + } + else + { + _mali_osk_lock_signal(time_data_lock, _MALI_OSK_LOCKMODE_RW); + } + } +} + +void mali_utilization_core_end(u64 time_now) +{ + if (_mali_osk_atomic_dec_return(&num_running_cores) == 0) + { + /* + * No more cores are working, so accumulate the time we was busy. + */ + _mali_osk_lock_wait(time_data_lock, _MALI_OSK_LOCKMODE_RW); + + if (time_now < work_start_time) + { + /* + * This might happen if the calculate_gpu_utilization() was able + * to run between the sampling of time_now and us grabbing the lock above + */ + time_now = work_start_time; + } + + accumulated_work_time += (time_now - work_start_time); + work_start_time = 0; + + _mali_osk_lock_signal(time_data_lock, _MALI_OSK_LOCKMODE_RW); + } +} + +u32 _mali_ukk_utilization_gp_pp(void) +{ + return last_utilization; +} + +u32 _mali_ukk_utilization_gp(void) +{ + return last_utilization; +} + +u32 _mali_ukk_utilization_pp(void) +{ + return last_utilization; +} diff --git a/pool/shard002/C/0058999_msg_clk_cmp.c b/pool/shard002/C/0058999_msg_clk_cmp.c new file mode 100644 index 0000000000000000000000000000000000000000..ddcec89a616f36f2c5b0d7096b36cdcf7a217621 --- /dev/null +++ b/pool/shard002/C/0058999_msg_clk_cmp.c @@ -0,0 +1,162 @@ +/* msg_clk_cmp.c + * WiMax MAC Management CLK_CMP Message decoders + * + * Copyright (c) 2007 by Intel Corporation. + * + * Author: Lu Pan + * + * $Id: msg_clk_cmp.c 39292 2011-10-06 14:46:34Z wmeier $ + * + * Wireshark - Network traffic analyzer + * By Gerald Combs + * Copyright 1999 Gerald Combs + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. + */ + +/* Include files */ + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +#include +#include +#include "wimax_mac.h" + +static gint proto_mac_mgmt_msg_clk_cmp_decoder = -1; + +static gint ett_mac_mgmt_msg_clk_cmp_decoder = -1; + +/* CLK_CMP fields */ +static gint hf_clk_cmp_message_type = -1; +static gint hf_clk_cmp_clock_count = -1; +static gint hf_clk_cmp_clock_id = -1; +static gint hf_clk_cmp_seq_number = -1; +static gint hf_clk_cmp_comparison_value = -1; +static gint hf_clk_cmp_invalid_tlv = -1; + + +/* Decode CLK_CMP messages. */ +void dissect_mac_mgmt_msg_clk_cmp_decoder(tvbuff_t *tvb, packet_info *pinfo _U_, proto_tree *tree) +{ + guint offset = 0; + guint i; + guint clock_count; + guint tvb_len, payload_type; + proto_item *clk_cmp_item = NULL; + proto_tree *clk_cmp_tree = NULL; + + /* Ensure the right payload type */ + payload_type = tvb_get_guint8(tvb, 0); + if(payload_type != MAC_MGMT_MSG_CLK_CMP) + { + return; + } + + if (tree) + { /* we are being asked for details */ + /* Get the tvb reported length */ + tvb_len = tvb_reported_length(tvb); + /* display MAC payload type CLK_CMP */ + clk_cmp_item = proto_tree_add_protocol_format(tree, proto_mac_mgmt_msg_clk_cmp_decoder, tvb, offset, tvb_len, "Clock Comparison (CLK-CMP) (%u bytes)", tvb_len); + /* add MAC CLK_CMP subtree */ + clk_cmp_tree = proto_item_add_subtree(clk_cmp_item, ett_mac_mgmt_msg_clk_cmp_decoder); + /* display the Message Type */ + proto_tree_add_item(clk_cmp_tree, hf_clk_cmp_message_type, tvb, offset, 1, ENC_BIG_ENDIAN); + /* set the offset for clock count */ + offset ++; + /* get the clock count */ + clock_count = tvb_get_guint8(tvb, offset); + /* display the clock count */ + proto_tree_add_item(clk_cmp_tree, hf_clk_cmp_clock_count, tvb, offset, 1, ENC_BIG_ENDIAN); + /* set the offset for clock comparison */ + offset++; + for (i = 0; i < clock_count; i++ ) + { /* display the Clock ID */ + proto_tree_add_item(clk_cmp_tree, hf_clk_cmp_clock_id, tvb, offset++, 1, ENC_BIG_ENDIAN); + /* display the sequence number */ + proto_tree_add_item(clk_cmp_tree, hf_clk_cmp_seq_number, tvb, offset++, 1, ENC_BIG_ENDIAN); + /* display the comparison value */ + proto_tree_add_item(clk_cmp_tree, hf_clk_cmp_comparison_value, tvb, offset++, 1, ENC_BIG_ENDIAN); + } + } +} + +/* Register Wimax Mac Payload Protocol and Dissector */ +void proto_register_mac_mgmt_msg_clk_cmp(void) +{ + /* CLK_CMP fields display */ + static hf_register_info hf_clk_cmp[] = + { + { + &hf_clk_cmp_message_type, + { + "MAC Management Message Type", "wmx.macmgtmsgtype.clk_cmp", + FT_UINT8, BASE_DEC, NULL, 0x0, NULL, HFILL + } + }, + { + &hf_clk_cmp_clock_count, + { + "Clock Count", "wmx.clk_cmp.clock_count", + FT_UINT8, BASE_DEC, NULL, 0x0, NULL, HFILL + } + }, + { + &hf_clk_cmp_clock_id, + { + "Clock ID", "wmx.clk_cmp.clock_id", + FT_UINT8, BASE_DEC, NULL, 0x0, NULL, HFILL + } + }, + { + &hf_clk_cmp_comparison_value, + { + "Comparison Value", "wmx.clk_cmp.comparison_value", + FT_INT8, BASE_DEC, NULL, 0x0, NULL, HFILL + } + }, + { + &hf_clk_cmp_invalid_tlv, + { + "Invalid TLV", "wmx.clk_cmp.invalid_tlv", + FT_BYTES, BASE_NONE, NULL, 0, NULL, HFILL + } + }, + { + &hf_clk_cmp_seq_number, + { + "Sequence Number", "wmx.clk_cmp.seq_number", + FT_UINT8, BASE_DEC, NULL, 0x0, NULL, HFILL + } + } + }; + + /* Setup protocol subtree array */ + static gint *ett[] = + { + &ett_mac_mgmt_msg_clk_cmp_decoder, + }; + + proto_mac_mgmt_msg_clk_cmp_decoder = proto_register_protocol ( + "WiMax CLK-CMP Message", /* name */ + "WiMax CLK-CMP (clk)", /* short name */ + "wmx.clk" /* abbrev */ + ); + + proto_register_field_array(proto_mac_mgmt_msg_clk_cmp_decoder, hf_clk_cmp, array_length(hf_clk_cmp)); + proto_register_subtree_array(ett, array_length(ett)); +} diff --git a/pool/shard002/C/0059003_f32_mul.c b/pool/shard002/C/0059003_f32_mul.c new file mode 100644 index 0000000000000000000000000000000000000000..5d5f9a885301081239deee1db390a22cf4bc6be5 --- /dev/null +++ b/pool/shard002/C/0059003_f32_mul.c @@ -0,0 +1,137 @@ + +/*============================================================================ + +This C source file is part of the SoftFloat IEEE Floating-Point Arithmetic +Package, Release 3b, by John R. Hauser. + +Copyright 2011, 2012, 2013, 2014, 2015 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. 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. + +=============================================================================*/ + +#include +#include +#include "platform.h" +#include "internals.h" +#include "specialize.h" +#include "softfloat.h" + +float32_t f32_mul( float32_t a, float32_t b ) +{ + union ui32_f32 uA; + uint_fast32_t uiA; + bool signA; + int_fast16_t expA; + uint_fast32_t sigA; + union ui32_f32 uB; + uint_fast32_t uiB; + bool signB; + int_fast16_t expB; + uint_fast32_t sigB; + bool signZ; + uint_fast32_t magBits; + struct exp16_sig32 normExpSig; + int_fast16_t expZ; + uint_fast32_t sigZ, uiZ; + union ui32_f32 uZ; + + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + uA.f = a; + uiA = uA.ui; + signA = signF32UI( uiA ); + expA = expF32UI( uiA ); + sigA = fracF32UI( uiA ); + uB.f = b; + uiB = uB.ui; + signB = signF32UI( uiB ); + expB = expF32UI( uiB ); + sigB = fracF32UI( uiB ); + signZ = signA ^ signB; + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + if ( expA == 0xFF ) { + if ( sigA || ((expB == 0xFF) && sigB) ) goto propagateNaN; + magBits = expB | sigB; + goto infArg; + } + if ( expB == 0xFF ) { + if ( sigB ) goto propagateNaN; + magBits = expA | sigA; + goto infArg; + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + if ( ! expA ) { + if ( ! sigA ) goto zero; + normExpSig = softfloat_normSubnormalF32Sig( sigA ); + expA = normExpSig.exp; + sigA = normExpSig.sig; + } + if ( ! expB ) { + if ( ! sigB ) goto zero; + normExpSig = softfloat_normSubnormalF32Sig( sigB ); + expB = normExpSig.exp; + sigB = normExpSig.sig; + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + expZ = expA + expB - 0x7F; + sigA = (sigA | 0x00800000)<<7; + sigB = (sigB | 0x00800000)<<8; + sigZ = softfloat_shortShiftRightJam64( (uint_fast64_t) sigA * sigB, 32 ); + if ( sigZ < 0x40000000 ) { + --expZ; + sigZ <<= 1; + } + return softfloat_roundPackToF32( signZ, expZ, sigZ ); + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + propagateNaN: + uiZ = softfloat_propagateNaNF32UI( uiA, uiB ); + goto uiZ; + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + infArg: + if ( ! magBits ) { + softfloat_raiseFlags( softfloat_flag_invalid ); + uiZ = defaultNaNF32UI; + } else { + uiZ = packToF32UI( signZ, 0xFF, 0 ); + } + goto uiZ; + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + zero: + uiZ = packToF32UI( signZ, 0, 0 ); + uiZ: + uZ.ui = uiZ; + return uZ.f; + +} + diff --git a/pool/shard002/C/0059004_findkey.c b/pool/shard002/C/0059004_findkey.c new file mode 100644 index 0000000000000000000000000000000000000000..05b03d3e2dfb5bc00de425f591a21e1c29232f19 --- /dev/null +++ b/pool/shard002/C/0059004_findkey.c @@ -0,0 +1,156 @@ +/* findkey.c - The routine that finds a key entry in the file. */ + +/* This file is part of GDBM, the GNU data base manager, by Philip A. Nelson. + Copyright (C) 1990, 1991, 1993 Free Software Foundation, Inc. + + GDBM 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. + + GDBM 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 GDBM; see the file COPYING. If not, write to + the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA. + + You may contact the author by: + e-mail: phil@cs.wwu.edu + us-mail: Philip A. Nelson + Computer Science Department + Western Washington University + Bellingham, WA 98226 + +*************************************************************************/ + +#include "gdbmdefs.h" + + +/* Read the data found in bucket entry ELEM_LOC in file DBF and + return a pointer to it. Also, cache the read value. */ + +char * +_gdbm_read_entry (dbf, elem_loc) + gdbm_file_info *dbf; + int elem_loc; +{ + int num_bytes; /* For seeking and reading. */ + int key_size; + int data_size; + off_t file_pos; + data_cache_elem *data_ca; + + /* Is it already in the cache? */ + if (dbf->cache_entry->ca_data.elem_loc == elem_loc) + return dbf->cache_entry->ca_data.dptr; + + /* Set sizes and pointers. */ + key_size = dbf->bucket->h_table[elem_loc].key_size; + data_size = dbf->bucket->h_table[elem_loc].data_size; + data_ca = &dbf->cache_entry->ca_data; + + /* Set up the cache. */ + if (data_ca->dptr != NULL) free (data_ca->dptr); + data_ca->key_size = key_size; + data_ca->data_size = data_size; + data_ca->elem_loc = elem_loc; + data_ca->hash_val = dbf->bucket->h_table[elem_loc].hash_value; + if (key_size+data_size == 0) + data_ca->dptr = (char *) malloc (1); + else + data_ca->dptr = (char *) malloc (key_size+data_size); + if (data_ca->dptr == NULL) _gdbm_fatal (dbf, "malloc error"); + + + /* Read into the cache. */ + file_pos = lseek (dbf->desc, + dbf->bucket->h_table[elem_loc].data_pointer, L_SET); + if (file_pos != dbf->bucket->h_table[elem_loc].data_pointer) + _gdbm_fatal (dbf, "lseek error"); + num_bytes = read (dbf->desc, data_ca->dptr, key_size+data_size); + if (num_bytes != key_size+data_size) _gdbm_fatal (dbf, "read error"); + + return data_ca->dptr; +} + + + +/* Find the KEY in the file and get ready to read the associated data. The + return value is the location in the current hash bucket of the KEY's + entry. If it is found, a pointer to the data and the key are returned + in DPTR. If it is not found, the value -1 is returned. Since find + key computes the hash value of key, that value */ +int +_gdbm_findkey (dbf, key, dptr, new_hash_val) + gdbm_file_info *dbf; + datum key; + char **dptr; + int *new_hash_val; /* The new hash value. */ +{ + int bucket_hash_val; /* The hash value from the bucket. */ + char *file_key; /* The complete key as stored in the file. */ + int elem_loc; /* The location in the bucket. */ + int home_loc; /* The home location in the bucket. */ + int key_size; /* Size of the key on the file. */ + + /* Compute hash value and load proper bucket. */ + *new_hash_val = _gdbm_hash (key); + _gdbm_get_bucket (dbf, *new_hash_val>> (31-dbf->header->dir_bits)); + + /* Is the element the last one found for this bucket? */ + if (dbf->cache_entry->ca_data.elem_loc != -1 + && *new_hash_val == dbf->cache_entry->ca_data.hash_val + && dbf->cache_entry->ca_data.key_size == key.dsize + && dbf->cache_entry->ca_data.dptr != NULL + && bcmp (dbf->cache_entry->ca_data.dptr, key.dptr, key.dsize) == 0) + { + /* This is it. Return the cache pointer. */ + *dptr = dbf->cache_entry->ca_data.dptr+key.dsize; + return dbf->cache_entry->ca_data.elem_loc; + } + + /* It is not the cached value, search for element in the bucket. */ + elem_loc = *new_hash_val % dbf->header->bucket_elems; + home_loc = elem_loc; + bucket_hash_val = dbf->bucket->h_table[elem_loc].hash_value; + while (bucket_hash_val != -1) + { + key_size = dbf->bucket->h_table[elem_loc].key_size; + if (bucket_hash_val != *new_hash_val + || key_size != key.dsize + || bcmp (dbf->bucket->h_table[elem_loc].key_start, key.dptr, + (SMALL < key_size ? SMALL : key_size)) != 0) + { + /* Current elem_loc is not the item, go to next item. */ + elem_loc = (elem_loc + 1) % dbf->header->bucket_elems; + if (elem_loc == home_loc) return -1; + bucket_hash_val = dbf->bucket->h_table[elem_loc].hash_value; + } + else + { + /* This may be the one we want. + The only way to tell is to read it. */ + file_key = _gdbm_read_entry (dbf, elem_loc); + if (bcmp (file_key, key.dptr, key_size) == 0) + { + /* This is the item. */ + *dptr = file_key+key.dsize; + return elem_loc; + } + else + { + /* Not the item, try the next one. Return if not found. */ + elem_loc = (elem_loc + 1) % dbf->header->bucket_elems; + if (elem_loc == home_loc) return -1; + bucket_hash_val = dbf->bucket->h_table[elem_loc].hash_value; + } + } + } + + /* If we get here, we never found the key. */ + return -1; + +} diff --git a/pool/shard002/C/0059025_dpt_isa.c b/pool/shard002/C/0059025_dpt_isa.c new file mode 100644 index 0000000000000000000000000000000000000000..3a34fa43811cd06dec8f5418f8a81fbad195fa21 --- /dev/null +++ b/pool/shard002/C/0059025_dpt_isa.c @@ -0,0 +1,324 @@ +/* $NetBSD: dpt_isa.c,v 1.22 2012/10/27 17:18:24 chs Exp $ */ + +/* + * Copyright (c) 1999, 2000, 2001 Andrew Doran + * 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 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. + * + */ + +/* + * ISA front-end for DPT EATA SCSI driver. + */ + +#include +__KERNEL_RCSID(0, "$NetBSD: dpt_isa.c,v 1.22 2012/10/27 17:18:24 chs Exp $"); + +#include +#include +#include +#include + +#include +#include + +#include +#include + +#include +#include + +#include +#include + +#include +#include + +#include + +#define DPT_ISA_IOSIZE 16 +#define DPT_ISA_MAXCCBS 16 + +static void dpt_isa_attach(device_t, device_t, void *); +static int dpt_isa_match(device_t, cfdata_t, void *); +static int dpt_isa_probe(struct isa_attach_args *, int); +static int dpt_isa_wait(bus_space_handle_t, bus_space_tag_t, u_int8_t, + u_int8_t); + +CFATTACH_DECL_NEW(dpt_isa, sizeof(struct dpt_softc), + dpt_isa_match, dpt_isa_attach, NULL, NULL); + +/* Try 'less intrusive' addresses first */ +static const int dpt_isa_iobases[] = { 0x230, 0x330, 0x1f0, 0x170, 0 }; + +/* + * Wait for the HBA status register to reach a specific state. + */ +static int +dpt_isa_wait(bus_space_handle_t ioh, bus_space_tag_t iot, u_int8_t mask, + u_int8_t state) +{ + int ms; + + for (ms = 2000 * 10; ms; ms--) { + if ((bus_space_read_1(iot, ioh, HA_STATUS) & mask) == state) + return (0); + DELAY(100); + } + + return (-1); +} + +/* + * Match a supported board. + */ +static int +dpt_isa_match(device_t parent, cfdata_t match, void *aux) +{ + struct isa_attach_args *ia = aux; + int i; + + if (ia->ia_nio < 1) + return (0); + if (ia->ia_nirq < 1) + return (0); + if (ia->ia_ndrq < 1) + return (0); + + if (ISA_DIRECT_CONFIG(ia)) + return (0); + + if (ia->ia_io[0].ir_addr != ISA_UNKNOWN_PORT) + return (dpt_isa_probe(ia, ia->ia_io[0].ir_addr)); + + for (i = 0; dpt_isa_iobases[i] != 0; i++) { + if (dpt_isa_probe(ia, dpt_isa_iobases[i])) { + ia->ia_io[0].ir_addr = dpt_isa_iobases[i]; + return (1); + } + } + + return (0); +} + +/* + * Probe for a supported board. + */ +static int +dpt_isa_probe(struct isa_attach_args *ia, int iobase) +{ + struct eata_cfg ec; + bus_space_handle_t ioh; + bus_space_tag_t iot; + int i, j, stat, irq, drq; + u_int16_t *p; + + iot = ia->ia_iot; + + if (bus_space_map(iot, iobase, DPT_ISA_IOSIZE, 0, &ioh) != 0) + return(0); + + /* + * Assumuing the DPT BIOS reset the board, we shouldn't need to + * re-do it here. The tests below should weed out non-EATA devices + * before we start poking any registers. + */ + for (i = 1000; i; i--) { + if ((bus_space_read_1(iot, ioh, HA_STATUS) & HA_ST_READY) != 0) + break; + DELAY(2000); + } + + if (i == 0) + goto bad; + + while((((stat = bus_space_read_1(iot, ioh, HA_STATUS)) + != (HA_ST_READY|HA_ST_SEEK_COMPLETE)) + && (stat != (HA_ST_READY|HA_ST_SEEK_COMPLETE|HA_ST_ERROR)) + && (stat != (HA_ST_READY|HA_ST_SEEK_COMPLETE|HA_ST_ERROR|HA_ST_DRQ))) + || (dpt_isa_wait(ioh, iot, HA_ST_BUSY, 0))) + /* RAID drives still spinning up? */ + if (bus_space_read_1(iot, ioh, HA_ERROR) != 'D' || + bus_space_read_1(iot, ioh, HA_ERROR + 1) != 'P' || + bus_space_read_1(iot, ioh, HA_ERROR + 2) != 'T') + goto bad; + + /* + * At this point we can be confident that we are dealing with a DPT + * HBA. Issue the read-config command and wait for the data to + * appear. XXX We shouldn't be doing this with PIO, but it makes it + * a lot easier as no DMA setup is required. + */ + bus_space_write_1(iot, ioh, HA_COMMAND, CP_PIO_GETCFG); + memset(&ec, 0, sizeof(ec)); + i = ((uintptr_t)&((struct eata_cfg *)0)->ec_cfglen + + sizeof(ec.ec_cfglen)) >> 1; + p = (u_int16_t *)&ec; + + if (dpt_isa_wait(ioh, iot, 0xFF, HA_ST_DATA_RDY)) + goto bad; + + /* Begin reading */ + while (i--) + *p++ = bus_space_read_stream_2(iot, ioh, HA_DATA); + + if ((i = ec.ec_cfglen) > (sizeof(struct eata_cfg) + - (uintptr_t)(&(((struct eata_cfg *)0L)->ec_cfglen)) + - sizeof(ec.ec_cfglen))) + i = sizeof(struct eata_cfg) + - (uintptr_t)(&(((struct eata_cfg *)0L)->ec_cfglen)) + - sizeof(ec.ec_cfglen); + + j = i + (uintptr_t)(&(((struct eata_cfg *)0L)->ec_cfglen)) + + sizeof(ec.ec_cfglen); + i >>= 1; + + while (i--) + *p++ = bus_space_read_stream_2(iot, ioh, HA_DATA); + + /* Flush until we have read 512 bytes. */ + i = (512 - j + 1) >> 1; + while (i--) + bus_space_read_stream_2(iot, ioh, HA_DATA); + + /* Puke if we don't like the returned configuration data. */ + if ((bus_space_read_1(iot, ioh, HA_STATUS) & HA_ST_ERROR) != 0 || + memcmp(ec.ec_eatasig, "EATA", 4) != 0 || + (ec.ec_feat0 & (EC_F0_HBA_VALID | EC_F0_DMA_SUPPORTED)) != + (EC_F0_HBA_VALID | EC_F0_DMA_SUPPORTED)) + goto bad; + + /* + * Which DMA channel to use: if it was hardwired in the kernel + * configuration, use that value. If the HBA told us, use that + * value. Otherwise, puke. + */ + if ((drq = ia->ia_drq[0].ir_drq) == ISA_UNKNOWN_DRQ) { + int dmanum = ((ec.ec_feat1 & EC_F1_DMA_NUM_MASK) >> + EC_F1_DMA_NUM_SHIFT); + + if ((ec.ec_feat0 & EC_F0_DMA_NUM_VALID) == 0 || dmanum > 3) + goto bad; + drq = "\0\7\6\5"[dmanum]; + } + + /* + * Which IRQ to use: if it was hardwired in the kernel configuration, + * use that value. Otherwise, use what the HBA told us. + */ + if ((irq = ia->ia_irq[0].ir_irq) == ISA_UNKNOWN_IRQ) + irq = ((ec.ec_feat1 & EC_F1_IRQ_NUM_MASK) >> + EC_F1_IRQ_NUM_SHIFT); + + ia->ia_nio = 1; + ia->ia_io[0].ir_size = DPT_ISA_IOSIZE; + + ia->ia_nirq = 1; + ia->ia_irq[0].ir_irq = irq; + + ia->ia_ndrq = 1; + ia->ia_drq[0].ir_drq = drq; + + ia->ia_niomem = 0; + + bus_space_unmap(iot, ioh, DPT_ISA_IOSIZE); + return (1); + bad: + bus_space_unmap(iot, ioh, DPT_ISA_IOSIZE); + return (0); +} + +/* + * Attach a matched board. + */ +static void +dpt_isa_attach(device_t parent, device_t self, void *aux) +{ + struct isa_attach_args *ia; + isa_chipset_tag_t ic; + bus_space_handle_t ioh; + bus_space_tag_t iot; + struct dpt_softc *sc; + struct eata_cfg *ec; + int error; + + ia = aux; + sc = device_private(self); + sc->sc_dev = self; + iot = ia->ia_iot; + ic = ia->ia_ic; + + printf(": "); + + if ((error = bus_space_map(iot, ia->ia_io[0].ir_addr, DPT_ISA_IOSIZE, + 0, &ioh)) != 0) { + printf("can't map i/o space, error = %d\n", error); + return; + } + + sc->sc_iot = iot; + sc->sc_ioh = ioh; + sc->sc_dmat = ia->ia_dmat; + + if ((error = isa_dmacascade(ic, ia->ia_drq[0].ir_drq)) != 0) { + printf("unable to cascade DRQ, error = %d\n", error); + return; + } + + /* Establish the interrupt. */ + sc->sc_ih = isa_intr_establish(ic, ia->ia_irq[0].ir_irq, IST_EDGE, + IPL_BIO, dpt_intr, sc); + if (sc->sc_ih == NULL) { + printf("can't establish interrupt\n"); + return; + } + + if (dpt_readcfg(sc)) { + printf("readcfg failed - see dpt(4)\n"); + return; + } + + /* + * Now attach to the bus-independent code. XXX We need to force + * parameters that aren't filled in by some ISA boards. In + * particular, due to the limited amount of memory we have to play + * with for DMA, clamp the number of CCBs to 16. + */ + ec = &sc->sc_ec; + + if (be16toh(*(int16_t *)ec->ec_queuedepth) > DPT_ISA_MAXCCBS) + *(int16_t *)ec->ec_queuedepth = htobe16(DPT_ISA_MAXCCBS); + if (ec->ec_maxlun == 0) + ec->ec_maxlun = 7; + if ((ec->ec_feat3 & EC_F3_MAX_TARGET_MASK) >> EC_F3_MAX_TARGET_SHIFT + == 0) + ec->ec_feat3 = (ec->ec_feat3 & ~EC_F3_MAX_TARGET_MASK) | + (7 << EC_F3_MAX_TARGET_SHIFT); + + sc->sc_bustype = SI_ISA_BUS; + sc->sc_isaport = ia->ia_io[0].ir_addr; + sc->sc_isairq = ia->ia_irq[0].ir_irq; + sc->sc_isadrq = ia->ia_drq[0].ir_drq; + + dpt_init(sc, NULL); +} diff --git a/pool/shard002/C/0059034_main.c b/pool/shard002/C/0059034_main.c new file mode 100644 index 0000000000000000000000000000000000000000..fc4029b61c3088e32a3e7126485b1c7ae9beeebd --- /dev/null +++ b/pool/shard002/C/0059034_main.c @@ -0,0 +1,24 @@ +#include // rand +#include +#include "nonsimple.h" + +#include // memset + +void game_init() +{ + for (int i=0; i +#include "file.h" +#include "fproc.h" +#include "inode.h" +#include "param.h" + +FORWARD _PROTOTYPE( int change, (struct inode **iip, char *name_ptr, int len)); +FORWARD _PROTOTYPE( int stat_inode, (struct inode *rip, struct filp *fil_ptr, + char *user_addr) ); + +/*===========================================================================* + * do_chdir * + *===========================================================================*/ +PUBLIC int do_chdir() +{ +/* Change directory. This function is also called by MM to simulate a chdir + * in order to do EXEC, etc. It also changes the root directory, the uids and + * gids, and the umask. + */ + + int r; + register struct fproc *rfp; + + if (who == MM_PROC_NR) { + rfp = &fproc[slot1]; + put_inode(fp->fp_rootdir); + dup_inode(fp->fp_rootdir = rfp->fp_rootdir); + put_inode(fp->fp_workdir); + dup_inode(fp->fp_workdir = rfp->fp_workdir); + + /* MM uses access() to check permissions. To make this work, pretend + * that the user's real ids are the same as the user's effective ids. + * FS calls other than access() do not use the real ids, so are not + * affected. + */ + fp->fp_realuid = + fp->fp_effuid = rfp->fp_effuid; + fp->fp_realgid = + fp->fp_effgid = rfp->fp_effgid; + fp->fp_umask = rfp->fp_umask; + return(OK); + } + + /* Perform the chdir(name) system call. */ + r = change(&fp->fp_workdir, name, name_length); + return(r); +} + + +/*===========================================================================* + * do_chroot * + *===========================================================================*/ +PUBLIC int do_chroot() +{ +/* Perform the chroot(name) system call. */ + + register int r; + + if (!super_user) return(EPERM); /* only su may chroot() */ + r = change(&fp->fp_rootdir, name, name_length); + return(r); +} + + +/*===========================================================================* + * change * + *===========================================================================*/ +PRIVATE int change(iip, name_ptr, len) +struct inode **iip; /* pointer to the inode pointer for the dir */ +char *name_ptr; /* pointer to the directory name to change to */ +int len; /* length of the directory name string */ +{ +/* Do the actual work for chdir() and chroot(). */ + + struct inode *rip; + register int r; + + /* Try to open the new directory. */ + if (fetch_name(name_ptr, len, M3) != OK) return(err_code); + if ( (rip = eat_path(user_path)) == NIL_INODE) return(err_code); + + /* It must be a directory and also be searchable. */ + if ( (rip->i_mode & I_TYPE) != I_DIRECTORY) + r = ENOTDIR; + else + r = forbidden(rip, X_BIT); /* check if dir is searchable */ + + /* If error, return inode. */ + if (r != OK) { + put_inode(rip); + return(r); + } + + /* Everything is OK. Make the change. */ + put_inode(*iip); /* release the old directory */ + *iip = rip; /* acquire the new one */ + return(OK); +} + + +/*===========================================================================* + * do_stat * + *===========================================================================*/ +PUBLIC int do_stat() +{ +/* Perform the stat(name, buf) system call. */ + + register struct inode *rip; + register int r; + + /* Both stat() and fstat() use the same routine to do the real work. That + * routine expects an inode, so acquire it temporarily. + */ + if (fetch_name(name1, name1_length, M1) != OK) return(err_code); + if ( (rip = eat_path(user_path)) == NIL_INODE) return(err_code); + r = stat_inode(rip, NIL_FILP, name2); /* actually do the work.*/ + put_inode(rip); /* release the inode */ + return(r); +} + + +/*===========================================================================* + * do_fstat * + *===========================================================================*/ +PUBLIC int do_fstat() +{ +/* Perform the fstat(fd, buf) system call. */ + + register struct filp *rfilp; + + /* Is the file descriptor valid? */ + if ( (rfilp = get_filp(fd)) == NIL_FILP) return(err_code); + + return(stat_inode(rfilp->filp_ino, rfilp, buffer)); +} + + +/*===========================================================================* + * stat_inode * + *===========================================================================*/ +PRIVATE int stat_inode(rip, fil_ptr, user_addr) +register struct inode *rip; /* pointer to inode to stat */ +struct filp *fil_ptr; /* filp pointer, supplied by 'fstat' */ +char *user_addr; /* user space address where stat buf goes */ +{ +/* Common code for stat and fstat system calls. */ + + struct stat statbuf; + mode_t mo; + int r, s; + + /* Update the atime, ctime, and mtime fields in the inode, if need be. */ + if (rip->i_update) update_times(rip); + + /* Fill in the statbuf struct. */ + mo = rip->i_mode & I_TYPE; + s = (mo == I_CHAR_SPECIAL || mo == I_BLOCK_SPECIAL); /* true iff special */ + statbuf.st_dev = rip->i_dev; + statbuf.st_ino = rip->i_num; + statbuf.st_mode = rip->i_mode; + statbuf.st_nlink = rip->i_nlinks; + statbuf.st_uid = rip->i_uid; + statbuf.st_gid = rip->i_gid; + statbuf.st_rdev = (dev_t) (s ? rip->i_zone[0] : NO_DEV); + statbuf.st_size = rip->i_size; + + if (rip->i_pipe == I_PIPE) { + statbuf.st_mode &= ~I_REGULAR; /* wipe out I_REGULAR bit for pipes */ + if (fil_ptr != NIL_FILP && fil_ptr->filp_mode & R_BIT) + statbuf.st_size -= fil_ptr->filp_pos; + } + + statbuf.st_atime = rip->i_atime; + statbuf.st_mtime = rip->i_mtime; + statbuf.st_ctime = rip->i_ctime; + + /* Copy the struct to user space. */ + r = sys_copy(FS_PROC_NR, D, (phys_bytes) &statbuf, + who, D, (phys_bytes) user_addr, (phys_bytes) sizeof(statbuf)); + return(r); +} diff --git a/pool/shard002/C/0059119_sgen-toggleref.c b/pool/shard002/C/0059119_sgen-toggleref.c new file mode 100644 index 0000000000000000000000000000000000000000..1f4e1c64dbe18c50c8085d059ebd2b709103cc8e --- /dev/null +++ b/pool/shard002/C/0059119_sgen-toggleref.c @@ -0,0 +1,221 @@ +/** + * \file + * toggleref support for sgen + * + * Author: + * Rodrigo Kumpera (kumpera@gmail.com) + * + * Copyright 2011 Xamarin, Inc. + * Copyright (C) 2012 Xamarin Inc + * + * Licensed under the MIT license. See LICENSE file in the project root for full license information. + */ + +#include "config.h" + +#ifdef HAVE_SGEN_GC + +#include "sgen/sgen-gc.h" +#include "sgen-toggleref.h" +#include "sgen/sgen-client.h" + + +/*only one of the two can be non null at a given time*/ +typedef struct { + GCObject *strong_ref; + GCObject *weak_ref; +} MonoGCToggleRef; + +static MonoToggleRefStatus (*toggleref_callback) (MonoObject *obj); +static MonoGCToggleRef *toggleref_array; +static int toggleref_array_size; +static int toggleref_array_capacity; + +void +sgen_process_togglerefs (void) +{ + int i, w; + int toggle_ref_counts [3] = { 0, 0, 0 }; + + SGEN_LOG (4, "Proccessing ToggleRefs %d", toggleref_array_size); + + for (i = w = 0; i < toggleref_array_size; ++i) { + int res; + MonoGCToggleRef r = toggleref_array [i]; + + MonoObject *obj; + + if (r.strong_ref) + obj = r.strong_ref; + else if (r.weak_ref) + obj = r.weak_ref; + else + continue; + + res = toggleref_callback (obj); + ++toggle_ref_counts [res]; + switch (res) { + case MONO_TOGGLE_REF_DROP: + break; + case MONO_TOGGLE_REF_STRONG: + toggleref_array [w].strong_ref = obj; + toggleref_array [w].weak_ref = NULL; + ++w; + break; + case MONO_TOGGLE_REF_WEAK: + toggleref_array [w].strong_ref = NULL; + toggleref_array [w].weak_ref = obj; + ++w; + break; + default: + g_assert_not_reached (); + } + } + + toggleref_array_size = w; + + SGEN_LOG (4, "Done Proccessing ToggleRefs dropped %d strong %d weak %d final size %d", + toggle_ref_counts [MONO_TOGGLE_REF_DROP], + toggle_ref_counts [MONO_TOGGLE_REF_STRONG], + toggle_ref_counts [MONO_TOGGLE_REF_WEAK], + w); +} + +void sgen_client_mark_togglerefs (char *start, char *end, ScanCopyContext ctx) +{ + CopyOrMarkObjectFunc copy_func = ctx.ops->copy_or_mark_object; + SgenGrayQueue *queue = ctx.queue; + int i; + + SGEN_LOG (4, "Marking ToggleRefs %d", toggleref_array_size); + + for (i = 0; i < toggleref_array_size; ++i) { + if (toggleref_array [i].strong_ref) { + GCObject *object = toggleref_array [i].strong_ref; + if ((char*)object >= start && (char*)object < end) { + SGEN_LOG (6, "\tcopying strong slot %d", i); + copy_func (&toggleref_array [i].strong_ref, queue); + } + } + } + sgen_drain_gray_stack (ctx); +} + +void sgen_client_clear_togglerefs (char *start, char *end, ScanCopyContext ctx) +{ + CopyOrMarkObjectFunc copy_func = ctx.ops->copy_or_mark_object; + SgenGrayQueue *queue = ctx.queue; + int i; + + SGEN_LOG (4, "Clearing ToggleRefs %d", toggleref_array_size); + + for (i = 0; i < toggleref_array_size; ++i) { + if (toggleref_array [i].weak_ref) { + GCObject *object = toggleref_array [i].weak_ref; + + if ((char*)object >= start && (char*)object < end) { + if (sgen_gc_is_object_ready_for_finalization (object)) { + SGEN_LOG (6, "\tcleaning weak slot %d", i); + toggleref_array [i].weak_ref = NULL; /* We defer compaction to only happen on the callback step. */ + } else { + SGEN_LOG (6, "\tkeeping weak slot %d", i); + copy_func (&toggleref_array [i].weak_ref, queue); + } + } + } + } + sgen_drain_gray_stack (ctx); +} + +static void +ensure_toggleref_capacity (int capacity) +{ + if (!toggleref_array) { + toggleref_array_capacity = 32; + toggleref_array = (MonoGCToggleRef *)sgen_alloc_internal_dynamic ( + toggleref_array_capacity * sizeof (MonoGCToggleRef), + INTERNAL_MEM_TOGGLEREF_DATA, + TRUE); + } + if (toggleref_array_size + capacity >= toggleref_array_capacity) { + MonoGCToggleRef *tmp; + int old_capacity = toggleref_array_capacity; + while (toggleref_array_capacity < toggleref_array_size + capacity) + toggleref_array_capacity *= 2; + + tmp = (MonoGCToggleRef *)sgen_alloc_internal_dynamic ( + toggleref_array_capacity * sizeof (MonoGCToggleRef), + INTERNAL_MEM_TOGGLEREF_DATA, + TRUE); + + memcpy (tmp, toggleref_array, toggleref_array_size * sizeof (MonoGCToggleRef)); + + sgen_free_internal_dynamic (toggleref_array, old_capacity * sizeof (MonoGCToggleRef), INTERNAL_MEM_TOGGLEREF_DATA); + toggleref_array = tmp; + } +} + +/** + * mono_gc_toggleref_add: + * @object object to register for toggleref processing + * @strong_ref if true the object is registered with a strong ref, a weak one otherwise + * + * Register a given object for toggleref processing. It will be stored internally and the toggleref callback will be called + * on it until it returns MONO_TOGGLE_REF_DROP or is collected. +*/ +void +mono_gc_toggleref_add (MonoObject *object, mono_bool strong_ref) +{ + if (!toggleref_callback) + return; + + SGEN_LOG (4, "Adding toggleref %p %d", object, strong_ref); + + sgen_gc_lock (); + + ensure_toggleref_capacity (1); + toggleref_array [toggleref_array_size].strong_ref = strong_ref ? object : NULL; + toggleref_array [toggleref_array_size].weak_ref = strong_ref ? NULL : object; + ++toggleref_array_size; + + sgen_gc_unlock (); +} + +/** + * mono_gc_toggleref_register_callback: + * \param callback callback used to determine the new state of the given object. + * + * The callback must decide the status of a given object. It must return one of the values in the \c MONO_TOGGLE_REF_ enum. + * This function is called with the world running but with the GC locked. This means that you can do everything that doesn't + * require GC interaction. This includes, but not limited to, allocating objects, (de)registering for finalization, manipulating + * gchandles, storing to reference fields or interacting with other threads that might perform such operations. + */ +void +mono_gc_toggleref_register_callback (MonoToggleRefStatus (*proccess_toggleref) (MonoObject *obj)) +{ + toggleref_callback = proccess_toggleref; +} + +static MonoToggleRefStatus +test_toggleref_callback (MonoObject *obj) +{ + static MonoClassField *mono_toggleref_test_field; + MonoToggleRefStatus status = MONO_TOGGLE_REF_DROP; + + if (!mono_toggleref_test_field) { + mono_toggleref_test_field = mono_class_get_field_from_name (mono_object_get_class (obj), "__test"); + g_assert (mono_toggleref_test_field); + } + + mono_field_get_value (obj, mono_toggleref_test_field, &status); + printf ("toggleref-cb obj %d\n", status); + return status; +} + +void +sgen_register_test_toggleref_callback (void) +{ + toggleref_callback = test_toggleref_callback; +} + +#endif diff --git a/pool/shard002/C/0059126_ksocket.c b/pool/shard002/C/0059126_ksocket.c new file mode 100644 index 0000000000000000000000000000000000000000..b60efe68eb9ca8111448e5b6cfbef10ba92c392c --- /dev/null +++ b/pool/shard002/C/0059126_ksocket.c @@ -0,0 +1,177 @@ +//***************************************************************************** +// Copyright (C) 2014 ZenoTec LLC (http://www.zenotec.net) +// +// 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. +// +// File: ksocket.c +// Description: This is a trimmed down version of ksocket to support only +// sending UDP packets to a specified host (listener). +// +//***************************************************************************** + +//***************************************************************************** +// Includes +//***************************************************************************** + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "rtap-ko.h" +#include "ksocket.h" + +//***************************************************************************** +// Functions +//***************************************************************************** + +//***************************************************************************** +ksocket_t ksocket( int domain, int type, int protocol ) +{ + struct socket *sk = NULL; + int ret = 0; + + ret = sock_create( domain, type, protocol, &sk ); + if ( ret < 0 ) + { + return( NULL ); + } // end if + + return( sk ); +} + +//***************************************************************************** +int kclose( ksocket_t socket ) +{ + struct socket *sk; + int ret; + + sk = (struct socket *)socket; + ret = sk->ops->release( sk ); + + if ( sk ) + { + sock_release( sk ); + } // end if + + return( ret ); +} + +//***************************************************************************** +ssize_t ksendto( ksocket_t socket, void *message, size_t length, int flags, + const struct sockaddr *dest_addr, int dest_len ) +{ + struct socket *sk; + struct msghdr msg; + struct iovec vec; + int len = 0; + mm_segment_t fs; + + sk = (struct socket *)socket; + + vec.iov_base = (void *)message; + vec.iov_len = (__kernel_size_t)length; + +#if LINUX_VERSION_CODE <= KERNEL_VERSION(3,18,0) + msg.msg_iov = &vec; + msg.msg_iovlen = 1; +#else + iov_iter_init( &msg.msg_iter, WRITE | ITER_IOVEC, &vec, 1, length ); +#endif + msg.msg_control = NULL; + msg.msg_controllen = 0; + + msg.msg_flags = flags; + if ( dest_addr ) + { + msg.msg_name = (void *)dest_addr; + msg.msg_namelen = dest_len; + } // end if + + fs = get_fs(); + set_fs( KERNEL_DS ); +#if LINUX_VERSION_CODE <= KERNEL_VERSION(3,18,0) + len = sock_sendmsg( sk, &msg, length ); +#else +// printk( KERN_INFO "RTAP: ksendto(): Sending %d bytes\n", (int)length ); +// len = length; + len = sock_sendmsg( sk, &msg ); +#endif + set_fs( fs ); + + return( len ); +} + +//***************************************************************************** +int inet_aton( const char *cp, struct in_addr *inp ) +{ + + int a, b, c, d; + __be32 addr; + + if( cp == NULL ) + { + return( 0 ); + } // end if + + sscanf( cp, "%d.%d.%d.%d", &a, &b, &c, &d ); + + addr = a; + addr <<= 8; + addr |= b; + addr <<= 8; + addr |= c; + addr <<= 8; + addr |= d; + + if( inp ) + { + inp->s_addr = htonl( addr ); + } // end if + + return( 1 ); + +} + +//***************************************************************************** +const char *inet_ntoa( struct in_addr in ) +{ + char *ip = NULL; + uint32_t addr = ntohl( in.s_addr ); + int a, b, c, d; + + ip = kmalloc( 16 * sizeof(char), GFP_KERNEL ); + if ( ip != NULL ) + { + memset( ip, 0, 16 ); + d = (addr & 0xff); + addr >>= 8; + c = (addr & 0xff); + addr >>= 8; + b = (addr & 0xff); + addr >>= 8; + a = (addr & 0xff); + sprintf( ip, "%d.%d.%d.%d", a, b, c, d ); + } // end if + + return( ip ); +} + + diff --git a/pool/shard002/C/0059139_bmp.c b/pool/shard002/C/0059139_bmp.c new file mode 100644 index 0000000000000000000000000000000000000000..e5c9d08707272dc34b49d542cbf90605cb324bd7 --- /dev/null +++ b/pool/shard002/C/0059139_bmp.c @@ -0,0 +1,273 @@ +/* bmp.c */ +/* Version 0.52 */ +/* This is a File input and output filter for the */ +/* Gimp. It loads and saves images in windows(TM) */ +/* bitmap format. */ +/* Some Parts that deal with the interaction with */ +/* GIMP are taken from the GIF plugin by */ +/* Peter Mattis & Spencer Kimball and from the */ +/* PCX plugin by Francisco Bustamante. */ +/* */ +/* Alexander.Schulz@stud.uni-karlsruhe.de */ + +/* Changes: 28.11.1997 Noninteractive operation */ +/* 16.03.1998 Endian-independent!! */ +/* 21.03.1998 Little Bug-fix */ +/* 06.04.1998 Bugfix in Padding */ +/* 11.04.1998 Arch. cleanup (-Wall) */ +/* Parses gtkrc */ +/* 14.04.1998 Another Bug in Padding */ +/* 28.04.1998 RLE-Encoding rewritten */ +/* 29.10.1998 Changes by Tor Lillqvist */ +/* to support */ +/* 16 and 32 bit images */ +/* 28.11.1998 Bug in RLE-read-padding */ +/* fixed. */ +/* 19.12.1999 Resolution support added */ +/* 06.05.2000 Overhaul for 16&24-bit */ +/* plus better OS/2 code */ +/* by njl195@zepler.org.uk */ +/* 29.06.2006 Full support for 16/32 */ +/* bits bitmaps and support */ +/* for alpha channel */ +/* by p.filiciak@zax.pl */ + +/* + * GIMP - The GNU Image Manipulation Program + * Copyright (C) 1995 Spencer Kimball and Peter Mattis + * + * 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 "bmp.h" + +#include "libgimp/stdplugins-intl.h" + + +const gchar *filename = NULL; +gboolean interactive = FALSE; +gboolean lastvals = FALSE; + +struct Bitmap_File_Head_Struct Bitmap_File_Head; +struct Bitmap_Head_Struct Bitmap_Head; + + +/* Declare some local functions. + */ +static void query (void); +static void run (const gchar *name, + gint nparams, + const GimpParam *param, + gint *nreturn_vals, + GimpParam **return_vals); + +const GimpPlugInInfo PLUG_IN_INFO = +{ + NULL, /* init_proc */ + NULL, /* quit_proc */ + query, /* query_proc */ + run, /* run_proc */ +}; + +MAIN () + +static void +query (void) +{ + static const GimpParamDef load_args[] = + { + { GIMP_PDB_INT32, "run-mode", "The run mode { RUN-INTERACTIVE (0), RUN-NONINTERACTIVE (1) }" }, + { GIMP_PDB_STRING, "filename", "The name of the file to load" }, + { GIMP_PDB_STRING, "raw-filename", "The name entered" }, + }; + static const GimpParamDef load_return_vals[] = + { + { GIMP_PDB_IMAGE, "image", "Output image" }, + }; + + static const GimpParamDef save_args[] = + { + { GIMP_PDB_INT32, "run-mode", "The run mode { RUN-INTERACTIVE (0), RUN-NONINTERACTIVE (1) }" }, + { GIMP_PDB_IMAGE, "image", "Input image" }, + { GIMP_PDB_DRAWABLE, "drawable", "Drawable to save" }, + { GIMP_PDB_STRING, "filename", "The name of the file to save the image in" }, + { GIMP_PDB_STRING, "raw-filename", "The name entered" }, + }; + + gimp_install_procedure (LOAD_PROC, + "Loads files of Windows BMP file format", + "Loads files of Windows BMP file format", + "Alexander Schulz", + "Alexander Schulz", + "1997", + N_("Windows BMP image"), + NULL, + GIMP_PLUGIN, + G_N_ELEMENTS (load_args), + G_N_ELEMENTS (load_return_vals), + load_args, load_return_vals); + + gimp_register_file_handler_mime (LOAD_PROC, "image/bmp"); + gimp_register_magic_load_handler (LOAD_PROC, + "bmp", + "", + "0,string,BM"); + + gimp_install_procedure (SAVE_PROC, + "Saves files in Windows BMP file format", + "Saves files in Windows BMP file format", + "Alexander Schulz", + "Alexander Schulz", + "1997", + N_("Windows BMP image"), + "INDEXED, GRAY, RGB*", + GIMP_PLUGIN, + G_N_ELEMENTS (save_args), 0, + save_args, NULL); + + gimp_register_file_handler_mime (SAVE_PROC, "image/bmp"); + gimp_register_save_handler (SAVE_PROC, "bmp", ""); +} + +static void +run (const gchar *name, + gint nparams, + const GimpParam *param, + gint *nreturn_vals, + GimpParam **return_vals) +{ + static GimpParam values[2]; + GimpRunMode run_mode; + GimpPDBStatusType status = GIMP_PDB_SUCCESS; + gint32 image_ID; + gint32 drawable_ID; + GimpExportReturn export = GIMP_EXPORT_CANCEL; + GError *error = NULL; + + INIT_I18N (); + gegl_init (NULL, NULL); + + run_mode = param[0].data.d_int32; + + *nreturn_vals = 1; + *return_vals = values; + + values[0].type = GIMP_PDB_STATUS; + values[0].data.d_status = GIMP_PDB_EXECUTION_ERROR; + + if (strcmp (name, LOAD_PROC) == 0) + { + switch (run_mode) + { + case GIMP_RUN_INTERACTIVE: + interactive = TRUE; + break; + + case GIMP_RUN_NONINTERACTIVE: + /* Make sure all the arguments are there! */ + if (nparams != 3) + status = GIMP_PDB_CALLING_ERROR; + break; + + default: + break; + } + + if (status == GIMP_PDB_SUCCESS) + { + image_ID = ReadBMP (param[1].data.d_string, &error); + + if (image_ID != -1) + { + *nreturn_vals = 2; + values[1].type = GIMP_PDB_IMAGE; + values[1].data.d_image = image_ID; + } + else + { + status = GIMP_PDB_EXECUTION_ERROR; + } + } + } + else if (strcmp (name, SAVE_PROC) == 0) + { + image_ID = param[1].data.d_int32; + drawable_ID = param[2].data.d_int32; + + /* eventually export the image */ + switch (run_mode) + { + case GIMP_RUN_INTERACTIVE: + interactive = TRUE; + /* fallthrough */ + + case GIMP_RUN_WITH_LAST_VALS: + if (run_mode == GIMP_RUN_WITH_LAST_VALS) + lastvals = TRUE; + + gimp_ui_init (PLUG_IN_BINARY, FALSE); + + export = gimp_export_image (&image_ID, &drawable_ID, "BMP", + GIMP_EXPORT_CAN_HANDLE_RGB | + GIMP_EXPORT_CAN_HANDLE_GRAY | + GIMP_EXPORT_CAN_HANDLE_ALPHA | + GIMP_EXPORT_CAN_HANDLE_INDEXED); + + if (export == GIMP_EXPORT_CANCEL) + { + values[0].data.d_status = GIMP_PDB_CANCEL; + return; + } + break; + + case GIMP_RUN_NONINTERACTIVE: + /* Make sure all the arguments are there! */ + if (nparams != 5) + status = GIMP_PDB_CALLING_ERROR; + break; + + default: + break; + } + + if (status == GIMP_PDB_SUCCESS) + status = WriteBMP (param[3].data.d_string, image_ID, drawable_ID, + &error); + + if (export == GIMP_EXPORT_EXPORT) + gimp_image_delete (image_ID); + } + else + { + status = GIMP_PDB_CALLING_ERROR; + } + + if (status != GIMP_PDB_SUCCESS && error) + { + *nreturn_vals = 2; + values[1].type = GIMP_PDB_STRING; + values[1].data.d_string = error->message; + } + + values[0].data.d_status = status; +} diff --git a/pool/shard002/C/0059142_fork.c b/pool/shard002/C/0059142_fork.c new file mode 100644 index 0000000000000000000000000000000000000000..fdf54e7c4327775d00de62a2783f1e3d068a9440 --- /dev/null +++ b/pool/shard002/C/0059142_fork.c @@ -0,0 +1,201 @@ +// implement fork from user space + +#include +#include + +// PTE_COW marks copy-on-write page table entries. +// It is one of the bits explicitly allocated to user processes (PTE_AVAIL). +#define PTE_COW 0x800 + +#define PGNUM(la) (((uintptr_t) (la)) >> PTXSHIFT) +// +// Custom page fault handler - if faulting page is copy-on-write, +// map in our own private writable copy. +// +static void +pgfault(struct UTrapframe *utf) +{ + void *addr = (void *) utf->utf_fault_va; + uint32_t err = utf->utf_err; + int r; + + // Check that the faulting access was (1) a write, and (2) to a + // copy-on-write page. If not, panic. + // Hint: + // Use the read-only page table mappings at uvpt + // (see ). + + // LAB 4: Your code here. + + // Allocate a new page, map it at a temporary location (PFTEMP), + // copy the data from the old page to the new page, then move the new + // page to the old page's address. + // Hint: + // You should make three system calls. + + // LAB 4: Your code here. + //check + if(!(err & FEC_WR)) { + panic("error in errno, %x",err); + } + unsigned pn = PGNUM(addr); + pte_t ptep = uvpt[pn]; + assert(ptep & PTE_COW); + + //Allocate a new page, map it at a temporary location (PFTEMP), + /* int sys_page_alloc(envid_t envid, void *va, int perm) */ + r = sys_page_alloc(0, (void *)(PFTEMP), PTE_U|PTE_P|PTE_W); + if(r != 0) { + panic("fail to alloc a new page, %e", r); + } + addr = ROUNDDOWN(addr, PGSIZE); + memmove((void *)PFTEMP, addr, PGSIZE); + /* int sys_page_map(envid_t srcenvid, void *srcva, envid_t dstenvid, void *dstva, int perm) */ + r = sys_page_map(0, (void *)(PFTEMP), 0, addr, PTE_U|PTE_P|PTE_W); + if(r != 0) { + panic("fail to map page PFTEMP, %e", r); + } + //panic("pgfault not implemented"); +} + +// +// Map our virtual page pn (address pn*PGSIZE) into the target envid +// at the same virtual address. If the page is writable or copy-on-write, +// the new mapping must be created copy-on-write, and then our mapping must be +// marked copy-on-write as well. (Exercise: Why do we need to mark ours +// copy-on-write again if it was already copy-on-write at the beginning of +// this function?) +// +// Returns: 0 on success, < 0 on error. +// It is also OK to panic on error. +// +static int +duppage(envid_t envid, unsigned pn) +{ + int r; + + // LAB 4: Your code here. + //panic("duppage not implemented"); + pte_t ptep = uvpt[pn]; + assert(ptep & PTE_U); + assert(ptep & PTE_P); + + + + void *va = (void *)(pn * PGSIZE); + if(ptep & PTE_SHARE) { + r = sys_page_map(0, va, envid, va, ptep & PTE_SYSCALL); + if(r != 0) { + panic("sys_page_map failed, %e",r); + } + } + else if((ptep & (PTE_COW | PTE_W)) != 0){ + /* int sys_page_map(envid_t srcenv, void *srcva, envid_t dstenv, void *dstva, int perm) */ + r = sys_page_map(0, va, envid, va, PTE_COW | PTE_U | PTE_P); + if(r != 0) { + panic("sys_page_map failed, %e",r); + } + r = sys_page_map(0, va, 0, va, PTE_COW | PTE_U | PTE_P); + if(r != 0) { + panic("sys_page_map failed, %e",r); + } + } + else { + r = sys_page_map(0, va, envid, va, ptep & PTE_SYSCALL); + if(r != 0) { + panic("sys_page_map failed, %e",r); + } + } + return 0; +} + +// +// User-level fork with copy-on-write. +// Set up our page fault handler appropriately. +// Create a child. +// Copy our address space and page fault handler setup to the child. +// Then mark the child as runnable and return. +// +// Returns: child's envid to the parent, 0 to the child, < 0 on error. +// It is also OK to panic on error. +// +// Hint: +// Use uvpd, uvpt, and duppage. +// Remember to fix "thisenv" in the child process. +// Neither user exception stack should ever be marked copy-on-write, +// so you must allocate a new page for the child's user exception stack. +// +envid_t +fork(void) +{ + // LAB 4: Your code here. + //panic("fork not implemented"); + + int r; + // set up our page fault handler appropriately. + assert(pgfault != NULL); + set_pgfault_handler(pgfault); + assert(thisenv->env_pgfault_upcall != NULL); + // Create a child. + envid_t envid; + envid = sys_exofork(); + if (envid < 0) + panic("sys_exofork: %e", envid); + if (envid == 0) { + // We're the child. + // The copied value of the global variable 'thisenv' + // is no longer valid (it refers to the parent!). + // Fix it and return 0. + thisenv = &envs[ENVX(sys_getenvid())]; + return 0; + } + + // Copy our address space to the child. + uint8_t *addr; + for (addr = 0; addr < (uint8_t *)UTOP; addr += PGSIZE){ + unsigned pn = PGNUM(addr); + if (!(uvpd[PDX(pn<env_pgfault_upcall != NULL); + r = sys_env_set_pgfault_upcall(envid, thisenv->env_pgfault_upcall); + if(r != 0) { + panic("fail to sys_env_set_pgfault_upcall, %e", r); + } + + r = sys_env_set_status(envid, ENV_RUNNABLE); + if(r != 0) { + panic("fail to sys_env_set_status, %e", r); + } + + return envid; +} + +// Challenge! +int +sfork(void) +{ + panic("sfork not implemented"); + return -E_INVAL; +} diff --git a/pool/shard002/C/0059159_main.c b/pool/shard002/C/0059159_main.c new file mode 100644 index 0000000000000000000000000000000000000000..8c26ee560ec32fbc5575fcdba73e3ebb95daa66a --- /dev/null +++ b/pool/shard002/C/0059159_main.c @@ -0,0 +1,90 @@ +#include +#include + +#include +#include +#include +#include +#include + +PSP_MODULE_INFO("kernel_functions", PSP_MODULE_KERNEL, 0, 0); +PSP_MAIN_THREAD_ATTR(0); + +static volatile int thread_active; +static unsigned int buttons; +static SceUID main_thread_id; + +static int main_thread(SceSize args, void *argp) +{ + SceCtrlData paddata; + + thread_active = 1; + + while (thread_active) + { + sceCtrlPeekBufferPositive(&paddata, 1); + buttons = paddata.Buttons; + sceKernelDelayThread(1000000/60); + } + + sceKernelExitThread(0); + + return 0; +} + +unsigned int read_system_buttons(void) +{ + return buttons; +} + +void exitspawn_kernel(const char *fileName, SceSize args, void *argp) +{ + int k1; + struct SceKernelLoadExecVSHParam game_param; + + thread_active = 0; + + memset(&game_param,0,sizeof(game_param)); + + game_param.size = sizeof(game_param); + game_param.args = args; + game_param.argp = argp; + game_param.key = "game"; + game_param.vshmain_args_size = 0; + game_param.vshmain_args = NULL; + game_param.configfile = 0; + game_param.unk4 = 0; + game_param.unk5 = 0x10000; + + k1 = pspSdkSetK1(0); +#if 0 + sceKernelSuspendAllUserThreads(); +#endif + sceKernelLoadExecVSHMs2(fileName, &game_param); + pspSdkSetK1(k1); +} + +int module_start(SceSize args, void *argp) +{ + (void)args; + (void)argp; + + buttons = 0; + thread_active = 0; + main_thread_id = sceKernelCreateThread("main Thread", main_thread, 0x11, 0x200, 0, NULL); + + if (main_thread >= 0) + sceKernelStartThread(main_thread_id, 0, 0); + + return 0; +} + +int module_stop(void) +{ + if (main_thread_id >= 0) + { + thread_active = 0; + sceKernelWaitThreadEnd(main_thread_id, NULL); + } + return 0; +} diff --git a/pool/shard002/C/0059170_CWE191_Integer_Underflow__int_fscanf_predec_34.c b/pool/shard002/C/0059170_CWE191_Integer_Underflow__int_fscanf_predec_34.c new file mode 100644 index 0000000000000000000000000000000000000000..9ef3ee077f6d6015aed24bd0d11c9a87fe269eec --- /dev/null +++ b/pool/shard002/C/0059170_CWE191_Integer_Underflow__int_fscanf_predec_34.c @@ -0,0 +1,130 @@ +/* TEMPLATE GENERATED TESTCASE FILE +Filename: CWE191_Integer_Underflow__int_fscanf_predec_34.c +Label Definition File: CWE191_Integer_Underflow__int.label.xml +Template File: sources-sinks-34.tmpl.c +*/ +/* + * @description + * CWE: 191 Integer Underflow + * BadSource: fscanf Read data from the console using fscanf() + * GoodSource: Set data to a small, non-zero number (negative two) + * Sinks: decrement + * GoodSink: Ensure there will not be an underflow before decrementing data + * BadSink : Decrement data, which can cause an Underflow + * Flow Variant: 34 Data flow: use of a union containing two methods of accessing the same data (within the same function) + * + * */ + +#include "std_testcase.h" + +typedef union +{ + int unionFirst; + int unionSecond; +} CWE191_Integer_Underflow__int_fscanf_predec_34_unionType; + +#ifndef OMITBAD + +void CWE191_Integer_Underflow__int_fscanf_predec_34_bad() +{ + int data; + CWE191_Integer_Underflow__int_fscanf_predec_34_unionType myUnion; + /* Initialize data */ + data = 0; + /* POTENTIAL FLAW: Read data from the console using fscanf() */ + fscanf(stdin, "%d", &data); + myUnion.unionFirst = data; + { + int data = myUnion.unionSecond; + { + /* POTENTIAL FLAW: Decrementing data could cause an underflow */ + --data; + int result = data; + printIntLine(result); + } + } +} + +#endif /* OMITBAD */ + +#ifndef OMITGOOD + +/* goodG2B() uses the GoodSource with the BadSink */ +static void goodG2B() +{ + int data; + CWE191_Integer_Underflow__int_fscanf_predec_34_unionType myUnion; + /* Initialize data */ + data = 0; + /* FIX: Use a small, non-zero value that will not cause an integer underflow in the sinks */ + data = -2; + myUnion.unionFirst = data; + { + int data = myUnion.unionSecond; + { + /* POTENTIAL FLAW: Decrementing data could cause an underflow */ + --data; + int result = data; + printIntLine(result); + } + } +} + +/* goodB2G() uses the BadSource with the GoodSink */ +static void goodB2G() +{ + int data; + CWE191_Integer_Underflow__int_fscanf_predec_34_unionType myUnion; + /* Initialize data */ + data = 0; + /* POTENTIAL FLAW: Read data from the console using fscanf() */ + fscanf(stdin, "%d", &data); + myUnion.unionFirst = data; + { + int data = myUnion.unionSecond; + /* FIX: Add a check to prevent an underflow from occurring */ + if (data > INT_MIN) + { + --data; + int result = data; + printIntLine(result); + } + else + { + printLine("data value is too large to perform arithmetic safely."); + } + } +} + +void CWE191_Integer_Underflow__int_fscanf_predec_34_good() +{ + goodG2B(); + goodB2G(); +} + +#endif /* OMITGOOD */ + +/* Below is the main(). It is only used when building this testcase on + its own for testing or for building a binary to use in testing binary + analysis tools. It is not used when compiling all the testcases as one + application, which is how source code analysis tools are tested. */ +#ifdef INCLUDEMAIN + +int main(int argc, char * argv[]) +{ + /* seed randomness */ + srand( (unsigned)time(NULL) ); +#ifndef OMITGOOD + printLine("Calling good()..."); + CWE191_Integer_Underflow__int_fscanf_predec_34_good(); + printLine("Finished good()"); +#endif /* OMITGOOD */ +#ifndef OMITBAD + printLine("Calling bad()..."); + CWE191_Integer_Underflow__int_fscanf_predec_34_bad(); + printLine("Finished bad()"); +#endif /* OMITBAD */ + return 0; +} + +#endif diff --git a/pool/shard002/C/0059178_main_eZ430_RF.c b/pool/shard002/C/0059178_main_eZ430_RF.c new file mode 100644 index 0000000000000000000000000000000000000000..65e26baf12f8bcea677de612ea011c33d47ad1fe --- /dev/null +++ b/pool/shard002/C/0059178_main_eZ430_RF.c @@ -0,0 +1,129 @@ +/* --COPYRIGHT--,BSD + * Copyright (c) 2011, Texas Instruments Incorporated + * 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 Texas Instruments Incorporated 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. + * --/COPYRIGHT--*/ +//****************************************************************************** +// Demo Application for MSP430 eZ430-RF2500 / CC1100-2500 Interface +// Main code application library v1.2 +// +// W. Goh +// Version 1.2 +// Texas Instruments, Inc +// December 2009 +// Built with IAR Embedded Workbench Version: 4.20 +//****************************************************************************** +// Change Log: +//****************************************************************************** +// Version: 1.2 +// Comments: Add startup delay for startup difference between MSP430 and CCxxxx +// Version: 1.1 +// Comments: Main application code designed for eZ430-RF2500 board +// Version: 1.00 +// Comments: Initial Release Version +//****************************************************************************** + +#include "include.h" + +extern char paTable[]; +extern char paTableLen; + +char txBuffer[4]; +char rxBuffer[4]; +unsigned int i = 0; + +void main (void) +{ + WDTCTL = WDTPW + WDTHOLD; // Stop WDT + + // 5ms delay to compensate for time to startup between MSP430 and CC1100/2500 + __delay_cycles(5000); + + TI_CC_SPISetup(); // Initialize SPI port + + P2SEL = 0; // Sets P2.6 & P2.7 as GPIO + TI_CC_PowerupResetCCxxxx(); // Reset CCxxxx + writeRFSettings(); // Write RF settings to config reg + TI_CC_SPIWriteBurstReg(TI_CCxxx0_PATABLE, paTable, paTableLen);//Write PATABLE + + // Configure ports -- switch inputs, LEDs, GDO0 to RX packet info from CCxxxx + TI_CC_SW_PxREN = TI_CC_SW1; // Enable Pull up resistor + TI_CC_SW_PxOUT = TI_CC_SW1; // Enable pull up resistor + TI_CC_SW_PxIES = TI_CC_SW1; // Int on falling edge + TI_CC_SW_PxIFG &= ~(TI_CC_SW1); // Clr flags + TI_CC_SW_PxIE = TI_CC_SW1; // Activate interrupt enables + TI_CC_LED_PxOUT &= ~(TI_CC_LED1 + TI_CC_LED2); // Outputs = 0 + TI_CC_LED_PxDIR |= TI_CC_LED1 + TI_CC_LED2;// LED Direction to Outputs + + TI_CC_GDO0_PxIES |= TI_CC_GDO0_PIN; // Int on falling edge (end of pkt) + TI_CC_GDO0_PxIFG &= ~TI_CC_GDO0_PIN; // Clear flag + TI_CC_GDO0_PxIE |= TI_CC_GDO0_PIN; // Enable int on end of packet + + TI_CC_SPIStrobe(TI_CCxxx0_SRX); // Initialize CCxxxx in RX mode. + // When a pkt is received, it will + // signal on GDO0 and wake CPU + + __bis_SR_register(LPM3_bits + GIE); // Enter LPM3, enable interrupts +} + + +// The ISR assumes the interrupt came from a pressed button +#pragma vector=PORT1_VECTOR +__interrupt void Port1_ISR (void) +{ + // If Switch was pressed + if(TI_CC_SW_PxIFG & TI_CC_SW1) + { + // Build packet + txBuffer[0] = 2; // Packet length + txBuffer[1] = 0x01; // Packet address + txBuffer[2] = (~TI_CC_SW_PxIFG << 1) & 0x02; // Load switch inputs + RFSendPacket(txBuffer, 3); // Send value over RF + __delay_cycles(5000); // Switch debounce + } + TI_CC_SW_PxIFG &= ~(TI_CC_SW1); // Clr flag that caused int +} + +// The ISR assumes the interrupt came from GDO0. GDO0 fires indicating that +// CCxxxx received a packet +#pragma vector=PORT2_VECTOR +__interrupt void Port2_ISR(void) +{ + // if GDO fired + if(TI_CC_GDO0_PxIFG & TI_CC_GDO0_PIN) + { + char len=2; // Len of pkt to be RXed (only addr + // plus data; size byte not incl b/c + // stripped away within RX function) + if (RFReceivePacket(rxBuffer,&len)) // Fetch packet from CCxxxx + TI_CC_LED_PxOUT ^= rxBuffer[1]; // Toggle LEDs according to pkt data + } + + TI_CC_GDO0_PxIFG &= ~TI_CC_GDO0_PIN; // After pkt RX, this flag is set. +} diff --git a/pool/shard002/C/0059179_multipath.c b/pool/shard002/C/0059179_multipath.c new file mode 100644 index 0000000000000000000000000000000000000000..4e9ca7c76407da4d1ddfeb29ba5e80322effafda --- /dev/null +++ b/pool/shard002/C/0059179_multipath.c @@ -0,0 +1,55 @@ +/* multipath.c: IPV4 multipath algorithm support. + * + * Copyright (C) 2004, 2005 Einar Lueck + * Copyright (C) 2005 David S. Miller + */ + +#include +#include +#include +#include + +#include + +static DEFINE_SPINLOCK(alg_table_lock); +struct ip_mp_alg_ops *ip_mp_alg_table[IP_MP_ALG_MAX + 1]; + +int multipath_alg_register(struct ip_mp_alg_ops *ops, enum ip_mp_alg n) +{ + struct ip_mp_alg_ops **slot; + int err; + + if (n < IP_MP_ALG_NONE || n > IP_MP_ALG_MAX || + !ops->mp_alg_select_route) + return -EINVAL; + + spin_lock(&alg_table_lock); + slot = &ip_mp_alg_table[n]; + if (*slot != NULL) { + err = -EBUSY; + } else { + *slot = ops; + err = 0; + } + spin_unlock(&alg_table_lock); + + return err; +} +EXPORT_SYMBOL(multipath_alg_register); + +void multipath_alg_unregister(struct ip_mp_alg_ops *ops, enum ip_mp_alg n) +{ + struct ip_mp_alg_ops **slot; + + if (n < IP_MP_ALG_NONE || n > IP_MP_ALG_MAX) + return; + + spin_lock(&alg_table_lock); + slot = &ip_mp_alg_table[n]; + if (*slot == ops) + *slot = NULL; + spin_unlock(&alg_table_lock); + + synchronize_net(); +} +EXPORT_SYMBOL(multipath_alg_unregister); diff --git a/pool/shard002/C/0059182_conjure.c b/pool/shard002/C/0059182_conjure.c new file mode 100644 index 0000000000000000000000000000000000000000..da2d6b37bf10245c709fffd7756f340b444e524e --- /dev/null +++ b/pool/shard002/C/0059182_conjure.c @@ -0,0 +1,126 @@ +/* +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +% % +% % +% % +% CCCC OOO N N JJJJJ U U RRRR EEEEE % +% C O O NN N J U U R R E % +% C O O N N N J U U RRRR EEE % +% C O O N NN J J U U R R E % +% CCCC OOO N N JJJ UUU R R EEEEE % +% % +% % +% Interpret Magick Scripting Language. % +% % +% Software Design % +% John Cristy % +% December 2001 % +% % +% % +% Copyright 1999-2013 ImageMagick Studio LLC, a non-profit organization % +% dedicated to making software imaging solutions freely available. % +% % +% You may not use this file except in compliance with the License. You may % +% obtain a copy of the License at % +% % +% http://www.imagemagick.org/script/license.php % +% % +% 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. % +% % +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +% +% Conjure interprets and executes scripts in the Magick Scripting Language +% (MSL). The Magick scripting language (MSL) will primarily benefit those +% that want to accomplish custom image processing tasks but do not wish +% to program, or those that do not have access to a Perl interpreter or a +% compiler. The interpreter is called conjure and here is an example script: +% +% +% +% +% +% +% +% +% +% +% +% +*/ + +/* + Include declarations. +*/ + +/* + Include declarations. +*/ +#include "wand/studio.h" +#include "wand/MagickWand.h" + +/* +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +% % +% % +% % +% M a i n % +% % +% % +% % +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +% +% +*/ + +static int ConjureMain(int argc,char **argv) +{ + ExceptionInfo + *exception; + + ImageInfo + *image_info; + + MagickBooleanType + status; + + MagickCoreGenesis(*argv,MagickTrue); + exception=AcquireExceptionInfo(); + image_info=AcquireImageInfo(); + status=MagickCommandGenesis(image_info,ConjureImageCommand,argc,argv, + (char **) NULL,exception); + image_info=DestroyImageInfo(image_info); + exception=DestroyExceptionInfo(exception); + MagickCoreTerminus(); + return(status == MagickFalse ? 0 : 1); +} + +#if !defined(MAGICKCORE_WINDOWS_SUPPORT) || defined(__CYGWIN__) || defined(__MINGW32__) || defined(__MINGW64__) +int main(int argc,char **argv) +{ + return(ConjureMain(argc,argv)); +} +#else +int wmain(int argc,wchar_t *argv[]) +{ + char + **utf8; + + int + status; + + register int + i; + + utf8=NTArgvToUTF8(argc,argv); + status=ConjureMain(argc,utf8); + for (i=0; i < argc; i++) + utf8[i]=DestroyString(utf8[i]); + utf8=(char **) RelinquishMagickMemory(utf8); + return(status == MagickFalse ? 0 : 1); +} +#endif diff --git a/pool/shard002/C/0059184_app_bt.c b/pool/shard002/C/0059184_app_bt.c new file mode 100644 index 0000000000000000000000000000000000000000..2b3a5bbf2922c29f56d8de725af68328612d8c87 --- /dev/null +++ b/pool/shard002/C/0059184_app_bt.c @@ -0,0 +1,261 @@ +// Copyright 2015-2016 Espressif Systems (Shanghai) PTE LTD +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at + +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#include +#include +#include "freertos/FreeRTOS.h" +#include "freertos/task.h" +#include "bt.h" +#include "esp_log.h" +#include "nvs_flash.h" + +static const char *tag = "BLE_ADV"; + +#define HCI_H4_CMD_PREAMBLE_SIZE (4) + +/* HCI Command opcode group field(OGF) */ +#define HCI_GRP_HOST_CONT_BASEBAND_CMDS (0x03 << 10) /* 0x0C00 */ +#define HCI_GRP_BLE_CMDS (0x08 << 10) + +#define HCI_RESET (0x0003 | HCI_GRP_HOST_CONT_BASEBAND_CMDS) +#define HCI_BLE_WRITE_ADV_ENABLE (0x000A | HCI_GRP_BLE_CMDS) +#define HCI_BLE_WRITE_ADV_PARAMS (0x0006 | HCI_GRP_BLE_CMDS) +#define HCI_BLE_WRITE_ADV_DATA (0x0008 | HCI_GRP_BLE_CMDS) + +#define HCIC_PARAM_SIZE_WRITE_ADV_ENABLE (1) +#define HCIC_PARAM_SIZE_BLE_WRITE_ADV_PARAMS (15) +#define HCIC_PARAM_SIZE_BLE_WRITE_ADV_DATA (31) + +#define BD_ADDR_LEN (6) /* Device address length */ +typedef uint8_t bd_addr_t[BD_ADDR_LEN]; /* Device address */ + +#define UINT16_TO_STREAM(p, u16) {*(p)++ = (uint8_t)(u16); *(p)++ = (uint8_t)((u16) >> 8);} +#define UINT8_TO_STREAM(p, u8) {*(p)++ = (uint8_t)(u8);} +#define BDADDR_TO_STREAM(p, a) {int ijk; for (ijk = 0; ijk < BD_ADDR_LEN; ijk++) *(p)++ = (uint8_t) a[BD_ADDR_LEN - 1 - ijk];} +#define ARRAY_TO_STREAM(p, a, len) {int ijk; for (ijk = 0; ijk < len; ijk++) *(p)++ = (uint8_t) a[ijk];} + +enum { + H4_TYPE_COMMAND = 1, + H4_TYPE_ACL = 2, + H4_TYPE_SCO = 3, + H4_TYPE_EVENT = 4 +}; + +static uint8_t hci_cmd_buf[128]; + +/* + * @brief: BT controller callback function, used to notify the upper layer that + * controller is ready to receive command + */ +static void controller_rcv_pkt_ready(void) +{ + printf("controller rcv pkt ready\n"); +} + +/* + * @brief: BT controller callback function, to transfer data packet to upper + * controller is ready to receive command + */ +static int host_rcv_pkt(uint8_t *data, uint16_t len) +{ + printf("host rcv pkt: "); + for (uint16_t i = 0; i < len; i++) { + printf("%02x", data[i]); + } + printf("\n"); + return 0; +} + +static esp_vhci_host_callback_t vhci_host_cb = { + controller_rcv_pkt_ready, + host_rcv_pkt +}; + +static uint16_t make_cmd_reset(uint8_t *buf) +{ + UINT8_TO_STREAM (buf, H4_TYPE_COMMAND); + UINT16_TO_STREAM (buf, HCI_RESET); + UINT8_TO_STREAM (buf, 0); + return HCI_H4_CMD_PREAMBLE_SIZE; +} + +static uint16_t make_cmd_ble_set_adv_enable (uint8_t *buf, uint8_t adv_enable) +{ + UINT8_TO_STREAM (buf, H4_TYPE_COMMAND); + UINT16_TO_STREAM (buf, HCI_BLE_WRITE_ADV_ENABLE); + UINT8_TO_STREAM (buf, HCIC_PARAM_SIZE_WRITE_ADV_ENABLE); + UINT8_TO_STREAM (buf, adv_enable); + return HCI_H4_CMD_PREAMBLE_SIZE + HCIC_PARAM_SIZE_WRITE_ADV_ENABLE; +} + +static uint16_t make_cmd_ble_set_adv_param (uint8_t *buf, uint16_t adv_int_min, uint16_t adv_int_max, + uint8_t adv_type, uint8_t addr_type_own, + uint8_t addr_type_dir, bd_addr_t direct_bda, + uint8_t channel_map, uint8_t adv_filter_policy) +{ + UINT8_TO_STREAM (buf, H4_TYPE_COMMAND); + UINT16_TO_STREAM (buf, HCI_BLE_WRITE_ADV_PARAMS); + UINT8_TO_STREAM (buf, HCIC_PARAM_SIZE_BLE_WRITE_ADV_PARAMS ); + + UINT16_TO_STREAM (buf, adv_int_min); + UINT16_TO_STREAM (buf, adv_int_max); + UINT8_TO_STREAM (buf, adv_type); + UINT8_TO_STREAM (buf, addr_type_own); + UINT8_TO_STREAM (buf, addr_type_dir); + BDADDR_TO_STREAM (buf, direct_bda); + UINT8_TO_STREAM (buf, channel_map); + UINT8_TO_STREAM (buf, adv_filter_policy); + return HCI_H4_CMD_PREAMBLE_SIZE + HCIC_PARAM_SIZE_BLE_WRITE_ADV_PARAMS; +} + + +static uint16_t make_cmd_ble_set_adv_data(uint8_t *buf, uint8_t data_len, uint8_t *p_data) +{ + UINT8_TO_STREAM (buf, H4_TYPE_COMMAND); + UINT16_TO_STREAM (buf, HCI_BLE_WRITE_ADV_DATA); + UINT8_TO_STREAM (buf, HCIC_PARAM_SIZE_BLE_WRITE_ADV_DATA + 1); + + memset(buf, 0, HCIC_PARAM_SIZE_BLE_WRITE_ADV_DATA); + + if (p_data != NULL && data_len > 0) { + if (data_len > HCIC_PARAM_SIZE_BLE_WRITE_ADV_DATA) { + data_len = HCIC_PARAM_SIZE_BLE_WRITE_ADV_DATA; + } + + UINT8_TO_STREAM (buf, data_len); + + ARRAY_TO_STREAM (buf, p_data, data_len); + } + return HCI_H4_CMD_PREAMBLE_SIZE + HCIC_PARAM_SIZE_BLE_WRITE_ADV_DATA + 1; +} + +static void hci_cmd_send_reset(void) +{ + uint16_t sz = make_cmd_reset (hci_cmd_buf); + esp_vhci_host_send_packet(hci_cmd_buf, sz); +} + +static void hci_cmd_send_ble_adv_start(void) +{ + uint16_t sz = make_cmd_ble_set_adv_enable (hci_cmd_buf, 1); + esp_vhci_host_send_packet(hci_cmd_buf, sz); +} + +static void hci_cmd_send_ble_set_adv_param(void) +{ + uint16_t adv_intv_min = 256; // 160ms + uint16_t adv_intv_max = 256; // 160ms + uint8_t adv_type = 0; // connectable undirected advertising (ADV_IND) + uint8_t own_addr_type = 0; // Public Device Address + uint8_t peer_addr_type = 0; // Public Device Address + uint8_t peer_addr[6] = {0x80, 0x81, 0x82, 0x83, 0x84, 0x85}; + uint8_t adv_chn_map = 0x07; // 37, 38, 39 + uint8_t adv_filter_policy = 0; // Process All Conn and Scan + + uint16_t sz = make_cmd_ble_set_adv_param(hci_cmd_buf, + adv_intv_min, + adv_intv_max, + adv_type, + own_addr_type, + peer_addr_type, + peer_addr, + adv_chn_map, + adv_filter_policy); + esp_vhci_host_send_packet(hci_cmd_buf, sz); +} + +static void hci_cmd_send_ble_set_adv_data(void) +{ + char *adv_name = "ESP-BLE-HELLO"; + uint8_t name_len = (uint8_t)strlen(adv_name); + uint8_t adv_data[31] = {0x02, 0x01, 0x06, 0x0, 0x09}; + uint8_t adv_data_len; + + adv_data[3] = name_len + 1; + for (int i = 0; i < name_len; i++) { + adv_data[5 + i] = (uint8_t)adv_name[i]; + } + adv_data_len = 5 + name_len; + + uint16_t sz = make_cmd_ble_set_adv_data(hci_cmd_buf, adv_data_len, (uint8_t *)adv_data); + esp_vhci_host_send_packet(hci_cmd_buf, sz); +} + +/* + * @brief: send HCI commands to perform BLE advertising; + */ +void bleAdvtTask(void *pvParameters) +{ + int cmd_cnt = 0; + bool send_avail = false; + esp_vhci_host_register_callback(&vhci_host_cb); + printf("BLE advt task start\n"); + while (1) { + vTaskDelay(1000 / portTICK_PERIOD_MS); + send_avail = esp_vhci_host_check_send_available(); + if (send_avail) { + switch (cmd_cnt) { + case 0: hci_cmd_send_reset(); ++cmd_cnt; break; + case 1: hci_cmd_send_ble_set_adv_param(); ++cmd_cnt; break; + case 2: hci_cmd_send_ble_set_adv_data(); ++cmd_cnt; break; + case 3: hci_cmd_send_ble_adv_start(); ++cmd_cnt; break; + } + } + printf("BLE Advertise, flag_send_avail: %d, cmd_sent: %d\n", send_avail, cmd_cnt); + } +} + +void app_main() +{ + /* Initialize NVS — it is used to store PHY calibration data */ + esp_err_t ret = nvs_flash_init(); + if (ret == ESP_ERR_NVS_NO_FREE_PAGES) { + ESP_ERROR_CHECK(nvs_flash_erase()); + ret = nvs_flash_init(); + } + ESP_ERROR_CHECK( ret ); + esp_bt_controller_config_t bt_cfg = BT_CONTROLLER_INIT_CONFIG_DEFAULT(); + + ret = esp_bt_controller_mem_release(ESP_BT_MODE_CLASSIC_BT); + if (ret) { + ESP_LOGI(tag, "Bluetooth controller release classic bt memory failed"); + return; + } + + if (esp_bt_controller_init(&bt_cfg) != ESP_OK) { + ESP_LOGI(tag, "Bluetooth controller initialize failed"); + return; + } + + if (esp_bt_controller_enable(ESP_BT_MODE_BLE) != ESP_OK) { + ESP_LOGI(tag, "Bluetooth controller enable failed"); + return; + } + + /* + * If call mem release here, also work. Input ESP_BT_MODE_CLASSIC_BT, the function will + * release the memory of classic bt mode. + * esp_bt_controller_mem_release(ESP_BT_MODE_CLASSIC_BT); + * + */ + + /* + * If call mem release here, also work. Input ESP_BT_MODE_BTDM, the function will calculate + * that the BLE mode is already used, so it will release of only classic bt mode. + * esp_bt_controller_mem_release(ESP_BT_MODE_BTDM); + */ + + xTaskCreatePinnedToCore(&bleAdvtTask, "bleAdvtTask", 2048, NULL, 5, NULL, 0); +} + diff --git a/pool/shard002/C/0059194_test.c b/pool/shard002/C/0059194_test.c new file mode 100644 index 0000000000000000000000000000000000000000..4d4b546066abe5fc783f404e9452b8214c285cb8 --- /dev/null +++ b/pool/shard002/C/0059194_test.c @@ -0,0 +1,135 @@ +#include "test.h" + +void +test_read_halo(uint64_t m, uint64_t n, size_t typesize) +{ + gaspi_queue_id_t queue_id = 0; + gaspi_barrier(GASPI_GROUP_ALL, GASPI_BLOCK); + + if(west_rank.rank_no != NO_NEIGHBOUR) + { + read_halo(west_rank, west_halo, SEG_V, typesize, queue_id); + gaspi_wait(queue_id, GASPI_BLOCK); + + gaspi_pointer_t seg_ptr; + gaspi_segment_ptr(vid, &seg_ptr); + for(int i = 0; i < west_rank.element_count ; ++i) + { + double * v = (double *)(seg_ptr + west_halo.halo_offset + (west_halo.jump_offset * i)); + if(*v != (west_rank.rank_no + 1)) + { + gaspi_printf("Wrong value in element %lu\n",i); + } + } + } + + if(east_rank.rank_no != NO_NEIGHBOUR) + { + read_halo(east_rank, east_halo, SEG_V, typesize, queue_id); + gaspi_wait(queue_id, GASPI_BLOCK); + + gaspi_pointer_t seg_ptr; + gaspi_segment_ptr(vid, &seg_ptr); + + for (int i = 0; i < east_rank.element_count; ++i) + { + double * v = (double *) (seg_ptr + east_halo.halo_offset + (east_halo.jump_offset * i)); + if (*v != (east_rank.rank_no + 1)) + { + gaspi_printf("Wrong value in element %lu\n", i); + } + } + } + + if(north_rank.rank_no != NO_NEIGHBOUR) + { + read_halo(north_rank, north_halo, SEG_V, typesize, queue_id); + gaspi_wait(queue_id, GASPI_BLOCK); + + gaspi_pointer_t seg_ptr; + gaspi_segment_ptr(vid, &seg_ptr); + + for (int i = 0; i < north_rank.element_count; ++i) + { + double * v = (double *) (seg_ptr + north_halo.halo_offset + (north_halo.jump_offset * i)); + if (*v != (north_rank.rank_no + 1)) + { + gaspi_printf("Wrong value in element %lu\n", i); + } + } + } + + if(south_rank.rank_no != NO_NEIGHBOUR) + { + read_halo(south_rank, south_halo, SEG_V, typesize, queue_id); + gaspi_wait(queue_id, GASPI_BLOCK); + + gaspi_pointer_t seg_ptr; + gaspi_segment_ptr(vid, &seg_ptr); + + gaspi_printf("in south rank %d\n",south_rank.rank_no); + for (int i = 0; i < south_rank.element_count; ++i) + { + double * v = (double *) (seg_ptr + south_halo.halo_offset + (south_halo.jump_offset * i)); + if (*v != (south_rank.rank_no + 1)) + { + gaspi_printf("Wrong value in element %lu\n", i); + } + } + } + + //~ FILE * out = get_file_handle(); + //~ if (out == NULL) + //~ { + //~ gaspi_printf("Get no file handle\n"); + //~ return; + //~ } + //~ print_map(out, SEG_V); + //~ fclose(out); + + gaspi_barrier(GASPI_GROUP_ALL, GASPI_BLOCK); +} + +void test_notify_all() +{ + seg_type_t seg_type = SEG_U; + gaspi_barrier(GASPI_GROUP_ALL, GASPI_BLOCK); + notify_all_neighbours(seg_type, 0); + + gaspi_return_t ret = GASPI_SUCCESS; + gaspi_segment_id_t seg = SEG_ID(seg_type); + + FILE * out = get_file_handle("test-halo"); + + for (uint64_t i = 0; i < neighbour_count; ++i) + { + gaspi_notification_id_t notify_id; + gaspi_notification_t notify_val; + + ret = blocking_waitsome(NOTIFY_ID_BEGIN, NOTIFY_ID_END, ¬ify_id, ¬ify_val, seg); + check_errors(ret, "test_notify_all", "blocking_waitsome"); + + if (check_notify(north_rank, notify_id, notify_val)) + { + fprintf(out, "get notify from north rank %lu\n",north_rank.rank_no); + } + if (check_notify(south_rank, notify_id, notify_val)) + { + fprintf(out, "get notify from south rank %lu\n",south_rank.rank_no); + gaspi_printf("south rank\n"); + } + if (check_notify(east_rank, notify_id, notify_val)) + { + gaspi_printf("east rank\n"); + fprintf(out, "get notify from east rank %lu\n",east_rank.rank_no); + } + if (check_notify(west_rank, notify_id, notify_val)) + { + fprintf(out, "get notify from west rank %lu\n",west_rank.rank_no); + } + } + + fclose(out); + gaspi_barrier(GASPI_GROUP_ALL, GASPI_BLOCK); +} + diff --git a/pool/shard002/C/0059196_autorefresh.c b/pool/shard002/C/0059196_autorefresh.c new file mode 100644 index 0000000000000000000000000000000000000000..defe27b28365aa277d259ef10cbcaa7ed4e402c4 --- /dev/null +++ b/pool/shard002/C/0059196_autorefresh.c @@ -0,0 +1,152 @@ +/* Copyright 1995 by Abacus Research and + * Development, Inc. All rights reserved. + */ + +#if !defined (OMIT_RCSID_STRINGS) +char ROMlib_rcsid_autorefresh[] = + "$Id: autorefresh.c 63 2004-12-24 18:19:43Z ctm $"; +#endif + +#include "rsys/common.h" +#include "rsys/autorefresh.h" +#include "rsys/vdriver.h" +#include "rsys/refresh.h" +#include "rsys/flags.h" +#include "rsys/prefs.h" + + +/* This file provides a mechanism to detect when applications are + * bypassing QuickDraw and writing directly to screen memory. + * It works by partitioning the screen into NUM_AUTOREFRESH_STRIPS + * horizontal strips of equal size. Each strip is periodically + * checksummed and compared against the last checksum. If the + * checksum value changes, and QuickDraw didn't change that area + * of the screen, we know we need to turn on "refresh" mode. + */ + + +static boolean_t executor_changed_screen_p[NUM_AUTOREFRESH_STRIPS]; + + +/* Check auto refresh? */ +boolean_t do_autorefresh_p; + + +/* Returns a value that will tend to change when the screen contents change + * for the specified horizontal strip on the screen. + */ +static uint32 +checksum_strip (int which_strip) +{ + int n, row_size, strip_rows, next_row_delta; + const uint32 *base; + uint32 sum; + + strip_rows = vdriver_height / NUM_AUTOREFRESH_STRIPS; + base = (const uint32 *) (vdriver_fbuf + + which_strip * strip_rows * vdriver_row_bytes); + row_size = vdriver_row_bytes / (4U * sizeof (uint32)); + next_row_delta = (vdriver_row_bytes * 2 / sizeof (uint32)) - (row_size * 4U); + + /* Sum (most of) the longs on every other row in this strip. */ + for (sum = 0, n = strip_rows; n > 0; n -= 2) + { + int r; + + for (r = row_size; r > 0; r--) + { +#if defined (i386) + uint32 t1, t2; + + /* Hand-scheduled for the Pentium. gcc does a terrible job. */ + asm ("movl (%3),%1\n\t" + "movl 4(%3),%2\n\t" + "addl %1,%0\n\t" + "movl 8(%3),%1\n\t" + "addl %2,%0\n\t" + "movl 12(%3),%2\n\t" + "addl %1,%0\n\t" + "addl $16,%3\n\t" + "addl %2,%0" + : "=r" (sum), "=r" (t1), "=r" (t2), "=r" (base) + : "0" (sum), "3" (base) + : "cc"); +#else + sum += base[0] + base[1] + base[2] + base[3]; + base += 4; +#endif + } + + base += next_row_delta; + } + + return sum; +} + + +/* Call this when part of the screen has been changed by Executor, + * so we don't mistakenly think we need refresh mode. + */ +void +note_executor_changed_screen (int top, int bottom) +{ + int i, first, last, strip_rows; + + strip_rows = vdriver_height / NUM_AUTOREFRESH_STRIPS; + first = top / strip_rows; + last = (bottom - 1) / strip_rows; + + if (first >= (int) NUM_AUTOREFRESH_STRIPS || last < 0) + return; + + if (first < 0) + first = 0; + if (last > (int) NUM_AUTOREFRESH_STRIPS - 1) + last = NUM_AUTOREFRESH_STRIPS - 1; + + for (i = first; i <= last; i++) + executor_changed_screen_p[i] = TRUE; +} + + +/* Returns TRUE if refresh should be turned on. */ +boolean_t +autodetect_refresh (void) +{ + static uint32 last_checksum[NUM_AUTOREFRESH_STRIPS]; + static boolean_t last_checksum_valid_p[NUM_AUTOREFRESH_STRIPS]; + boolean_t need_refresh_p; + int i; + + /* We don't need to autodetect refresh if we're already doing refresh + * or if we have direct screen access. + */ + if (ROMlib_refresh != 0 || !ROMlib_shadow_screen_p) + { + memset (last_checksum_valid_p, 0, sizeof last_checksum_valid_p); + return FALSE; + } + + need_refresh_p = FALSE; /* default value */ + + /* Compute checksums for the screen. */ + for (i = NUM_AUTOREFRESH_STRIPS - 1; i >= 0; i--) + { + if (executor_changed_screen_p[i]) + { + executor_changed_screen_p[i] = FALSE; /* reset it */ + last_checksum_valid_p[i] = FALSE; + } + else + { + uint32 c; + c = checksum_strip (i); + if (last_checksum_valid_p[i] && c != last_checksum[i]) + need_refresh_p = TRUE; + last_checksum[i] = c; + last_checksum_valid_p[i] = TRUE; + } + } + + return need_refresh_p; +} diff --git a/pool/shard002/C/0059207_em_gpio.c b/pool/shard002/C/0059207_em_gpio.c new file mode 100644 index 0000000000000000000000000000000000000000..5452df936f056e85d49fbfa57f9eb8450002b405 --- /dev/null +++ b/pool/shard002/C/0059207_em_gpio.c @@ -0,0 +1,384 @@ +/***************************************************************************//** + * @file + * @brief General Purpose IO (GPIO) peripheral API + * devices. + ******************************************************************************* + * # License + * Copyright 2018 Silicon Laboratories Inc. www.silabs.com + ******************************************************************************* + * + * SPDX-License-Identifier: Zlib + * + * The licensor of this software is Silicon Laboratories Inc. + * + * This software is provided 'as-is', without any express or implied + * warranty. In no event will the authors be held liable for any damages + * arising from the use of this software. + * + * Permission is granted to anyone to use this software for any purpose, + * including commercial applications, and to alter it and redistribute it + * freely, subject to the following restrictions: + * + * 1. The origin of this software must not be misrepresented; you must not + * claim that you wrote the original software. If you use this software + * in a product, an acknowledgment in the product documentation would be + * appreciated but is not required. + * 2. Altered source versions must be plainly marked as such, and must not be + * misrepresented as being the original software. + * 3. This notice may not be removed or altered from any source distribution. + * + ******************************************************************************/ + +#include "em_gpio.h" + +#if defined(GPIO_COUNT) && (GPIO_COUNT > 0) + +/***************************************************************************//** + * @addtogroup emlib + * @{ + ******************************************************************************/ + +/***************************************************************************//** + * @addtogroup GPIO + * @brief General Purpose Input/Output (GPIO) API + * @details + * This module contains functions to control the GPIO peripheral of Silicon + * Labs 32-bit MCUs and SoCs. The GPIO peripheral is used for pin configuration + * and direct pin manipulation and sensing as well as routing for peripheral + * pin connections. + * @{ + ******************************************************************************/ + +/******************************************************************************* + ******************************* DEFINES *********************************** + ******************************************************************************/ + +/** @cond DO_NOT_INCLUDE_WITH_DOXYGEN */ + +/** Validation of the pin typically usable in assert statements. */ +#define GPIO_DRIVEMODE_VALID(mode) ((mode) <= 3) +#define GPIO_STRENGTH_VALID(strength) (!((strength) \ + & ~(_GPIO_P_CTRL_DRIVESTRENGTH_MASK \ + | _GPIO_P_CTRL_DRIVESTRENGTHALT_MASK))) +/** @endcond */ + +/******************************************************************************* + ************************** GLOBAL FUNCTIONS ******************************* + ******************************************************************************/ + +/***************************************************************************//** + * @brief + * Sets the pin location of the debug pins (Serial Wire interface). + * + * @note + * Changing the pins used for debugging uncontrolled, may result in a lockout. + * + * @param[in] location + * The debug pin location to use (0-3). + ******************************************************************************/ +void GPIO_DbgLocationSet(unsigned int location) +{ +#if defined (_GPIO_ROUTE_SWLOCATION_MASK) + EFM_ASSERT(location < AFCHANLOC_MAX); + + GPIO->ROUTE = (GPIO->ROUTE & ~_GPIO_ROUTE_SWLOCATION_MASK) + | (location << _GPIO_ROUTE_SWLOCATION_SHIFT); +#elif defined (_GPIO_ROUTELOC0_SWVLOC_MASK) + EFM_ASSERT(location < AFCHANLOC_MAX); + + GPIO->ROUTELOC0 = (GPIO->ROUTELOC0 & ~_GPIO_ROUTELOC0_SWVLOC_MASK) + | (location << _GPIO_ROUTELOC0_SWVLOC_SHIFT); +#else + (void)location; +#endif +} + +#if defined (_GPIO_P_CTRL_DRIVEMODE_MASK) +/***************************************************************************//** + * @brief + * Sets drive mode for a GPIO port. + * + * @param[in] port + * The GPIO port to access. + * + * @param[in] mode + * Drive mode to use for the port. + ******************************************************************************/ +void GPIO_DriveModeSet(GPIO_Port_TypeDef port, GPIO_DriveMode_TypeDef mode) +{ + EFM_ASSERT(GPIO_PORT_VALID(port) && GPIO_DRIVEMODE_VALID(mode)); + + GPIO->P[port].CTRL = (GPIO->P[port].CTRL & ~(_GPIO_P_CTRL_DRIVEMODE_MASK)) + | (mode << _GPIO_P_CTRL_DRIVEMODE_SHIFT); +} +#endif + +#if defined (_GPIO_P_CTRL_DRIVESTRENGTH_MASK) +/***************************************************************************//** + * @brief + * Sets the drive strength for a GPIO port. + * + * @param[in] port + * The GPIO port to access. + * + * @param[in] strength + * The drive strength to use for the port. + ******************************************************************************/ +void GPIO_DriveStrengthSet(GPIO_Port_TypeDef port, + GPIO_DriveStrength_TypeDef strength) +{ + EFM_ASSERT(GPIO_PORT_VALID(port) && GPIO_STRENGTH_VALID(strength)); + BUS_RegMaskedWrite(&GPIO->P[port].CTRL, + _GPIO_P_CTRL_DRIVESTRENGTH_MASK | _GPIO_P_CTRL_DRIVESTRENGTHALT_MASK, + strength); +} +#endif + +/***************************************************************************//** + * @brief + * Configure the GPIO external pin interrupt. + * + * @details + * It is recommended to disable interrupts before configuring the GPIO pin interrupt. + * See @ref GPIO_IntDisable() for more information. + * + * The GPIO interrupt handler must be in place before enabling the + * interrupt. + * + * Notice that any pending interrupt for the selected interrupt is cleared + * by this function. + * + * @note + * On series 0 devices, the pin number parameter is not used. The + * pin number used on these devices is hardwired to the interrupt with the + * same number. @n + * On series 1 devices, the pin number can be selected freely within a group. + * Interrupt numbers are divided into 4 groups (intNo / 4) and valid pin + * number within the interrupt groups are: + * 0: pins 0-3 (interrupt number 0-3) + * 1: pins 4-7 (interrupt number 4-7) + * 2: pins 8-11 (interrupt number 8-11) + * 3: pins 12-15 (interrupt number 12-15) + * + * @param[in] port + * The port to associate with the @p pin. + * + * @param[in] pin + * The pin number on the port. + * + * @param[in] intNo + * The interrupt number to trigger. + * + * @param[in] risingEdge + * Set to true if the interrupt will be enabled on the rising edge. Otherwise, false. + * + * @param[in] fallingEdge + * Set to true if the interrupt will be enabled on the falling edge. Otherwise, false. + * + * @param[in] enable + * Set to true if the interrupt will be enabled after the configuration is complete. + * False to leave disabled. See @ref GPIO_IntDisable() and @ref GPIO_IntEnable(). + ******************************************************************************/ +void GPIO_ExtIntConfig(GPIO_Port_TypeDef port, + unsigned int pin, + unsigned int intNo, + bool risingEdge, + bool fallingEdge, + bool enable) +{ +#if defined (_GPIO_EXTIPSELH_MASK) + uint32_t tmp = 0; +#endif +#if !defined(_GPIO_EXTIPINSELL_MASK) + (void)pin; +#endif + + EFM_ASSERT(GPIO_PORT_PIN_VALID(port, pin)); +#if defined(_GPIO_EXTIPINSELL_MASK) + EFM_ASSERT(GPIO_INTNO_PIN_VALID(intNo, pin)); +#endif + + /* The EXTIPSELL register controls pins 0-7 and EXTIPSELH controls + * pins 8-15 of the interrupt configuration. */ + if (intNo < 8) { + BUS_RegMaskedWrite(&GPIO->EXTIPSELL, + _GPIO_EXTIPSELL_EXTIPSEL0_MASK + << (_GPIO_EXTIPSELL_EXTIPSEL1_SHIFT * intNo), + port << (_GPIO_EXTIPSELL_EXTIPSEL1_SHIFT * intNo)); + } else { +#if defined(_GPIO_EXTIPSELH_MASK) + tmp = intNo - 8; +#if defined(_GPIO_EXTIPSELH_EXTIPSEL0_MASK) + BUS_RegMaskedWrite(&GPIO->EXTIPSELH, + _GPIO_EXTIPSELH_EXTIPSEL0_MASK + << (_GPIO_EXTIPSELH_EXTIPSEL1_SHIFT * tmp), + port << (_GPIO_EXTIPSELH_EXTIPSEL1_SHIFT * tmp)); +#elif defined(_GPIO_EXTIPSELH_EXTIPSEL8_MASK) + BUS_RegMaskedWrite(&GPIO->EXTIPSELH, + _GPIO_EXTIPSELH_EXTIPSEL8_MASK + << (_GPIO_EXTIPSELH_EXTIPSEL9_SHIFT * tmp), + port << (_GPIO_EXTIPSELH_EXTIPSEL9_SHIFT * tmp)); +#else +#error Invalid GPIO_EXTIPINSELH bit fields +#endif +#endif /* #if defined(_GPIO_EXTIPSELH_MASK) */ + } + +#if defined(_GPIO_EXTIPINSELL_MASK) + + /* The EXTIPINSELL register controls interrupt 0-7 and EXTIPINSELH controls + * interrupt 8-15 of the interrupt/pin number mapping. */ + if (intNo < 8) { + BUS_RegMaskedWrite(&GPIO->EXTIPINSELL, + _GPIO_EXTIPINSELL_EXTIPINSEL0_MASK + << (_GPIO_EXTIPINSELL_EXTIPINSEL1_SHIFT * intNo), + ((pin % 4) & _GPIO_EXTIPINSELL_EXTIPINSEL0_MASK) + << (_GPIO_EXTIPINSELL_EXTIPINSEL1_SHIFT * intNo)); + } else { +#if defined (_GPIO_EXTIPINSELH_MASK) && !defined(_SILICON_LABS_32B_SERIES_2) + BUS_RegMaskedWrite(&GPIO->EXTIPINSELH, + _GPIO_EXTIPINSELH_EXTIPINSEL8_MASK + << (_GPIO_EXTIPINSELH_EXTIPINSEL9_SHIFT * tmp), + ((pin % 4) & _GPIO_EXTIPINSELH_EXTIPINSEL8_MASK) + << (_GPIO_EXTIPSELH_EXTIPSEL9_SHIFT * tmp)); +#endif + } +#endif + + /* Enable/disable the rising edge interrupt. */ + BUS_RegBitWrite(&(GPIO->EXTIRISE), intNo, risingEdge); + + /* Enable/disable the falling edge interrupt. */ + BUS_RegBitWrite(&(GPIO->EXTIFALL), intNo, fallingEdge); + + /* Clear any pending interrupt. */ + GPIO_IntClear(1 << intNo); + + /* Finally enable/disable interrupt. */ + BUS_RegBitWrite(&(GPIO->IEN), intNo, enable); +} + +/***************************************************************************//** + * @brief + * Set the mode for a GPIO pin. + * + * @param[in] port + * The GPIO port to access. + * + * @param[in] pin + * The pin number in the port. + * + * @param[in] mode + * The desired pin mode. + * + * @param[in] out + * A value to set for the pin in the DOUT register. The DOUT setting is important for + * some input mode configurations to determine the pull-up/down direction. + ******************************************************************************/ +void GPIO_PinModeSet(GPIO_Port_TypeDef port, + unsigned int pin, + GPIO_Mode_TypeDef mode, + unsigned int out) +{ + EFM_ASSERT(GPIO_PORT_PIN_VALID(port, pin)); + + /* If disabling a pin, do not modify DOUT to reduce the chance of */ + /* a glitch/spike (may not be sufficient precaution in all use cases). */ + if (mode != gpioModeDisabled) { + if (out) { + GPIO_PinOutSet(port, pin); + } else { + GPIO_PinOutClear(port, pin); + } + } + + /* There are two registers controlling the pins for each port. The MODEL + * register controls pins 0-7 and MODEH controls pins 8-15. */ + if (pin < 8) { + GPIO->P[port].MODEL = (GPIO->P[port].MODEL & ~(0xFu << (pin * 4))) + | (mode << (pin * 4)); + } else { + GPIO->P[port].MODEH = (GPIO->P[port].MODEH & ~(0xFu << ((pin - 8) * 4))) + | (mode << ((pin - 8) * 4)); + } + + if (mode == gpioModeDisabled) { + if (out) { + GPIO_PinOutSet(port, pin); + } else { + GPIO_PinOutClear(port, pin); + } + } +} + +/***************************************************************************//** + * @brief + * Get the mode for a GPIO pin. + * + * @param[in] port + * The GPIO port to access. + * + * @param[in] pin + * The pin number in the port. + * + * @return + * The pin mode. + ******************************************************************************/ +GPIO_Mode_TypeDef GPIO_PinModeGet(GPIO_Port_TypeDef port, + unsigned int pin) +{ + EFM_ASSERT(GPIO_PORT_PIN_VALID(port, pin)); + + if (pin < 8) { + return (GPIO_Mode_TypeDef) ((GPIO->P[port].MODEL >> (pin * 4)) & 0xF); + } else { + return (GPIO_Mode_TypeDef) ((GPIO->P[port].MODEH >> ((pin - 8) * 4)) & 0xF); + } +} + +#if defined(_GPIO_EM4WUEN_MASK) +/**************************************************************************//** + * @brief + * Enable GPIO pin wake-up from EM4. When the function exits, + * EM4 mode can be safely entered. + * + * @note + * It is assumed that the GPIO pin modes are set correctly. + * Valid modes are @ref gpioModeInput and @ref gpioModeInputPull. + * + * @param[in] pinmask + * A bitmask containing the bitwise logic OR of which GPIO pin(s) to enable. + * See Reference Manuals for a pinmask to the GPIO port/pin mapping. + * @param[in] polaritymask + * A bitmask containing the bitwise logic OR of GPIO pin(s) wake-up polarity. + * See Reference Manuals for pinmask-to-GPIO port/pin mapping. + *****************************************************************************/ +void GPIO_EM4EnablePinWakeup(uint32_t pinmask, uint32_t polaritymask) +{ + EFM_ASSERT((pinmask & ~_GPIO_EM4WUEN_MASK) == 0); + +#if defined(_GPIO_EM4WUPOL_MASK) + EFM_ASSERT((polaritymask & ~_GPIO_EM4WUPOL_MASK) == 0); + GPIO->EM4WUPOL &= ~pinmask; /* Set the wakeup polarity. */ + GPIO->EM4WUPOL |= pinmask & polaritymask; +#elif defined(_GPIO_EXTILEVEL_MASK) + EFM_ASSERT((polaritymask & ~_GPIO_EXTILEVEL_MASK) == 0); + GPIO->EXTILEVEL &= ~pinmask; + GPIO->EXTILEVEL |= pinmask & polaritymask; +#endif + GPIO->EM4WUEN |= pinmask; /* Enable wakeup. */ + + GPIO_EM4SetPinRetention(true); /* Enable the pin retention. */ + +#if defined(_GPIO_CMD_EM4WUCLR_MASK) + GPIO->CMD = GPIO_CMD_EM4WUCLR; /* Clear the wake-up logic. */ +#elif defined(_GPIO_IF_EM4WU_MASK) + GPIO_IntClear(pinmask); +#endif +} +#endif + +/** @} (end addtogroup GPIO) */ +/** @} (end addtogroup emlib) */ + +#endif /* defined(GPIO_COUNT) && (GPIO_COUNT > 0) */ diff --git a/pool/shard002/C/0059211_mptable.c b/pool/shard002/C/0059211_mptable.c new file mode 100644 index 0000000000000000000000000000000000000000..a374f5c6d7196d9b8fa0ec07af3585e10f000597 --- /dev/null +++ b/pool/shard002/C/0059211_mptable.c @@ -0,0 +1,169 @@ +#include +#include +#include +#include +#include +#include + +static void *smp_write_config_table(void *v) +{ + struct mp_config_table *mc; + int bus_isa; + unsigned char bus_pxhd_1; + unsigned char bus_pxhd_2; + unsigned char bus_pxhd_3; + unsigned char bus_pxhd_4; + unsigned char bus_ich5r_1; + + mc = (void *)(((char *)v) + SMP_FLOATING_TABLE_LEN); + + mptable_init(mc, LAPIC_ADDR); + + smp_write_processors(mc); + + { + device_t dev; + + /* ich5r */ + dev = dev_find_slot(0, PCI_DEVFN(0x1e,0)); + if (dev) { + bus_ich5r_1 = pci_read_config8(dev, PCI_SECONDARY_BUS); + } + else { + printk(BIOS_DEBUG, "ERROR - could not find PCI 0:1e.0, using defaults\n"); + + bus_ich5r_1 = 7; + } + /* pxhd-1 */ + dev = dev_find_slot(1, PCI_DEVFN(0x0,0)); + if (dev) { + bus_pxhd_1 = pci_read_config8(dev, PCI_SECONDARY_BUS); + + } + else { + printk(BIOS_DEBUG, "ERROR - could not find PCI 1:00.0, using defaults\n"); + + bus_pxhd_1 = 2; + } + /* pxhd-2 */ + dev = dev_find_slot(1, PCI_DEVFN(0x00,2)); + if (dev) { + bus_pxhd_2 = pci_read_config8(dev, PCI_SECONDARY_BUS); + + } + else { + printk(BIOS_DEBUG, "ERROR - could not find PCI 1:00.2, using defaults\n"); + + bus_pxhd_2 = 3; + } + + /* pxhd-3 */ + dev = dev_find_slot(0, PCI_DEVFN(0x4,0)); + if (dev) { + bus_pxhd_3 = pci_read_config8(dev, PCI_SECONDARY_BUS); + + } + else { + printk(BIOS_DEBUG, "ERROR - could not find PCI 0:04.0, using defaults\n"); + + bus_pxhd_3 = 5; + } + /* pxhd-4 */ + dev = dev_find_slot(0, PCI_DEVFN(0x06,0)); + if (dev) { + bus_pxhd_4 = pci_read_config8(dev, PCI_SECONDARY_BUS); + + } + else { + printk(BIOS_DEBUG, "ERROR - could not find PCI 0:06.0, using defaults\n"); + + bus_pxhd_4 = 6; + } + + } + + mptable_write_buses(mc, NULL, &bus_isa); + + /* IOAPIC handling */ + + smp_write_ioapic(mc, 2, 0x20, IO_APIC_ADDR); + { + struct resource *res; + device_t dev; + /* pxhd apic 3 */ + dev = dev_find_slot(1, PCI_DEVFN(0x00,1)); + if (dev) { + res = find_resource(dev, PCI_BASE_ADDRESS_0); + if (res) { + smp_write_ioapic(mc, 0x03, 0x20, res->base); + } + } + else { + printk(BIOS_DEBUG, "ERROR - could not find IOAPIC PCI 1:00.1\n"); + } + /* pxhd apic 4 */ + dev = dev_find_slot(1, PCI_DEVFN(0x00,3)); + if (dev) { + res = find_resource(dev, PCI_BASE_ADDRESS_0); + if (res) { + smp_write_ioapic(mc, 0x04, 0x20, res->base); + } + } + else { + printk(BIOS_DEBUG, "ERROR - could not find IOAPIC PCI 1:00.3\n"); + } + } + mptable_add_isa_interrupts(mc, bus_isa, 0x2, 0); + + /* ISA backward compatibility interrupts */ + smp_write_intsrc(mc, mp_INT, MP_IRQ_TRIGGER_LEVEL|MP_IRQ_POLARITY_LOW, + 0x00, 0x74, 0x02, 0x10); + smp_write_intsrc(mc, mp_INT, MP_IRQ_TRIGGER_LEVEL|MP_IRQ_POLARITY_LOW, + 0x00, 0x76, 0x02, 0x12); + smp_write_intsrc(mc, mp_INT, MP_IRQ_TRIGGER_LEVEL|MP_IRQ_POLARITY_LOW, + 0x00, 0x77, 0x02, 0x17); + smp_write_intsrc(mc, mp_INT, MP_IRQ_TRIGGER_LEVEL|MP_IRQ_POLARITY_LOW, + 0x00, 0x75, 0x02, 0x13); + smp_write_intsrc(mc, mp_INT, MP_IRQ_TRIGGER_LEVEL|MP_IRQ_POLARITY_LOW, + 0x00, 0x74, 0x02, 0x10); + smp_write_intsrc(mc, mp_INT, MP_IRQ_TRIGGER_LEVEL|MP_IRQ_POLARITY_LOW, + 0x00, 0x7c, 0x02, 0x12); + smp_write_intsrc(mc, mp_INT, MP_IRQ_TRIGGER_LEVEL|MP_IRQ_POLARITY_LOW, + 0x00, 0x7d, 0x02, 0x11); + smp_write_intsrc(mc, mp_INT, MP_IRQ_TRIGGER_LEVEL|MP_IRQ_POLARITY_LOW, + bus_pxhd_1, 0x08, 0x03, 0x00); + smp_write_intsrc(mc, mp_INT, MP_IRQ_TRIGGER_LEVEL|MP_IRQ_POLARITY_LOW, + bus_pxhd_1, 0x0c, 0x03, 0x06); + smp_write_intsrc(mc, mp_INT, MP_IRQ_TRIGGER_LEVEL|MP_IRQ_POLARITY_LOW, + bus_pxhd_1, 0x0d, 0x03, 0x07); + smp_write_intsrc(mc, mp_INT, MP_IRQ_TRIGGER_LEVEL|MP_IRQ_POLARITY_LOW, + bus_pxhd_2, 0x08, 0x04, 0x00); + smp_write_intsrc(mc, mp_INT, MP_IRQ_TRIGGER_LEVEL|MP_IRQ_POLARITY_LOW, + bus_ich5r_1, 0x04, 0x02, 0x10); + smp_write_intsrc(mc, mp_INT, MP_IRQ_TRIGGER_LEVEL|MP_IRQ_POLARITY_LOW, + bus_pxhd_4, 0x00, 0x02, 0x10); +#if 0 + smp_write_intsrc(mc, mp_INT, MP_IRQ_TRIGGER_LEVEL|MP_IRQ_POLARITY_LOW, + (bus_isa - 1), 0x04, 0x02, 0x10); +#endif + /* Standard local interrupt assignments */ +#if 0 + smp_write_lintsrc(mc, mp_ExtINT, MP_IRQ_TRIGGER_EDGE|MP_IRQ_POLARITY_HIGH, + bus_isa, 0x00, MP_APIC_ALL, 0x00); +#endif + smp_write_lintsrc(mc, mp_NMI, MP_IRQ_TRIGGER_EDGE|MP_IRQ_POLARITY_HIGH, + bus_isa, 0x00, MP_APIC_ALL, 0x01); + + /* There is no extension information... */ + + /* Compute the checksums */ + return mptable_finalize(mc); +} + +unsigned long write_smp_table(unsigned long addr) +{ + void *v; + v = smp_write_floating_table(addr, 0); + return (unsigned long)smp_write_config_table(v); +} + diff --git a/pool/shard002/C/0059222_ll_map.c b/pool/shard002/C/0059222_ll_map.c new file mode 100644 index 0000000000000000000000000000000000000000..66401da77fac47ac8172e7bc5a6ca871856c00e7 --- /dev/null +++ b/pool/shard002/C/0059222_ll_map.c @@ -0,0 +1,178 @@ +/* vi: set sw=4 ts=4: */ +/* + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version + * 2 of the License, or (at your option) any later version. + * + * Authors: Alexey Kuznetsov, + */ +#include /* struct ifreq and co. */ + +#include "libbb.h" +#include "libnetlink.h" +#include "ll_map.h" + +struct idxmap { + struct idxmap *next; + int index; + int type; + int alen; + unsigned flags; + unsigned char addr[8]; + char name[16]; +}; + +static struct idxmap **idxmap; /* treat as *idxmap[16] */ + +static struct idxmap *find_by_index(int idx) +{ + struct idxmap *im; + + if (idxmap) + for (im = idxmap[idx & 0xF]; im; im = im->next) + if (im->index == idx) + return im; + return NULL; +} + +int FAST_FUNC ll_remember_index(const struct sockaddr_nl *who UNUSED_PARAM, + struct nlmsghdr *n, + void *arg UNUSED_PARAM) +{ + int h; + struct ifinfomsg *ifi = NLMSG_DATA(n); + struct idxmap *im, **imp; + struct rtattr *tb[IFLA_MAX+1]; + + if (n->nlmsg_type != RTM_NEWLINK) + return 0; + + if (n->nlmsg_len < NLMSG_LENGTH(sizeof(ifi))) + return -1; + + //memset(tb, 0, sizeof(tb)); - parse_rtattr does this + parse_rtattr(tb, IFLA_MAX, IFLA_RTA(ifi), IFLA_PAYLOAD(n)); + if (tb[IFLA_IFNAME] == NULL) + return 0; + + if (!idxmap) + idxmap = xzalloc(sizeof(idxmap[0]) * 16); + + h = ifi->ifi_index & 0xF; + for (imp = &idxmap[h]; (im = *imp) != NULL; imp = &im->next) + if (im->index == ifi->ifi_index) + goto found; + + im = xmalloc(sizeof(*im)); + im->next = *imp; + im->index = ifi->ifi_index; + *imp = im; + found: + im->type = ifi->ifi_type; + im->flags = ifi->ifi_flags; + if (tb[IFLA_ADDRESS]) { + int alen; + im->alen = alen = RTA_PAYLOAD(tb[IFLA_ADDRESS]); + if (alen > (int)sizeof(im->addr)) + alen = sizeof(im->addr); + memcpy(im->addr, RTA_DATA(tb[IFLA_ADDRESS]), alen); + } else { + im->alen = 0; + memset(im->addr, 0, sizeof(im->addr)); + } + strcpy(im->name, RTA_DATA(tb[IFLA_IFNAME])); + return 0; +} + +static +const char FAST_FUNC *ll_idx_n2a(int idx/*, char *buf*/) +{ + struct idxmap *im; + + if (idx == 0) + return "*"; + im = find_by_index(idx); + if (im) + return im->name; + //snprintf(buf, 16, "if%d", idx); + //return buf; + return auto_string(xasprintf("if%d", idx)); +} + +const char FAST_FUNC *ll_index_to_name(int idx) +{ + //static char nbuf[16]; + return ll_idx_n2a(idx/*, nbuf*/); +} + +#ifdef UNUSED +int ll_index_to_type(int idx) +{ + struct idxmap *im; + + if (idx == 0) + return -1; + im = find_by_index(idx); + if (im) + return im->type; + return -1; +} +#endif + +unsigned FAST_FUNC ll_index_to_flags(int idx) +{ + struct idxmap *im; + + if (idx == 0) + return 0; + im = find_by_index(idx); + if (im) + return im->flags; + return 0; +} + +int FAST_FUNC xll_name_to_index(const char *name) +{ + int ret = 0; + +/* caching is not warranted - no users which repeatedly call it */ +#ifdef UNUSED + static char ncache[16]; + static int icache; + + struct idxmap *im; + int i; + + if (name == NULL) + goto out; + if (icache && strcmp(name, ncache) == 0) { + ret = icache; + goto out; + } + if (idxmap) { + for (i = 0; i < 16; i++) { + for (im = idxmap[i]; im; im = im->next) { + if (strcmp(im->name, name) == 0) { + icache = im->index; + strcpy(ncache, name); + ret = im->index; + goto out; + } + } + } + } +#endif + ret = if_nametoindex(name); +/* out:*/ + if (ret <= 0) + bb_error_msg_and_die("can't find device '%s'", name); + return ret; +} + +int FAST_FUNC ll_init_map(struct rtnl_handle *rth) +{ + xrtnl_wilddump_request(rth, AF_UNSPEC, RTM_GETLINK); + xrtnl_dump_filter(rth, ll_remember_index, NULL); + return 0; +} diff --git a/pool/shard002/C/0059227_ht.c b/pool/shard002/C/0059227_ht.c new file mode 100644 index 0000000000000000000000000000000000000000..bbb33ef64851c27eee53123e3b9f2f60fb5b96ca --- /dev/null +++ b/pool/shard002/C/0059227_ht.c @@ -0,0 +1,195 @@ +/* + * This file is part of the coreboot project. + * + * Copyright (C) 2008 Advanced Micro Devices, Inc. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; version 2 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + */ + +#include +#include +#include +#include +#include +#include +#include +#include "rs690.h" + +static void ht_dev_set_resources(device_t dev) +{ +#if CONFIG_EXT_CONF_SUPPORT + unsigned reg; + device_t k8_f1; + resource_t rbase, rend; + u32 base, limit; + struct resource *resource; + + printk(BIOS_DEBUG,"%s %s\n", dev_path(dev), __func__); + + resource = probe_resource(dev, 0x1C); + if (resource) { + set_nbmisc_enable_bits(dev, 0x0, 1 << 3, 0 << 3); // make bar3 visible + set_nbcfg_enable_bits(dev, 0x7C, 1 << 30, 1 << 30); /* Enables writes to the BAR3 register. */ + set_nbcfg_enable_bits(dev, 0x84, 7 << 16, 0 << 16); // program bus range: 255 busses + pci_write_config32(dev, 0x1C, resource->base); + /* Enable MMCONFIG decoding. */ + set_htiu_enable_bits(dev, 0x32, 1 << 28, 1 << 28); /* PCIEMiscInit */ + set_nbcfg_enable_bits(dev, 0x7C, 1 << 30, 0 << 30); /* Disable writes to the BAR3 register. */ + set_nbmisc_enable_bits(dev, 0x0, 1 << 3, 1 << 3); // hide bar 3 + + // setup resource nonposted in k8 mmio + /* Get the base address */ + rbase = resource->base; + /* Get the limit (rounded up) */ + rend = resource_end(resource); + printk(BIOS_DEBUG,"%s: %s[0x1C] base = %0llx limit = %0llx\n", __func__, dev_path(dev), rbase, rend); + k8_f1 = dev_find_slot(0,PCI_DEVFN(0x18,1)); + // find a not assigned resource + for ( reg = 0xb8; reg >= 0x80; reg -= 8 ) { + base = pci_read_config32(k8_f1,reg); + limit = pci_read_config32(k8_f1,reg+4); + if ( !(base & 3) ) break; // found a not assigned resource + } + if ( !(base & 3) ) { + u32 sblk; + device_t k8_f0 = dev_find_slot(0, PCI_DEVFN(0x18, 0)); + /* Remember this resource has been stored. */ + resource->flags |= IORESOURCE_STORED; + report_resource_stored(dev, resource, " "); + /* Get SBLink value (HyperTransport I/O Hub Link ID). */ + sblk = (pci_read_config32(k8_f0, 0x64) >> 8) & 0x3; + base &= 0x000000f0; + base |= ((rbase >> 8) & 0xffffff00); + base |= 3; + limit &= 0x00000048; + limit |= ((rend >> 8) & 0xffffff00); + limit |= (sblk << 4); + limit |= (1 << 7); + printk(BIOS_INFO, "%s <- index %x base %04x limit %04x\n", dev_path(k8_f1), reg, base, limit); + pci_write_config32(k8_f1, reg+4, limit); + pci_write_config32(k8_f1, reg, base); + } + } +#endif + pci_dev_set_resources(dev); +} + +unsigned long acpi_fill_mcfg(unsigned long current) +{ +#if CONFIG_EXT_CONF_SUPPORT + struct resource *res; + resource_t mmconf_base = EXT_CONF_BASE_ADDRESS; // default + + device_t dev = dev_find_slot(0,PCI_DEVFN(0,0)); + // we report mmconf base + res = probe_resource(dev, 0x1C); + if ( res ) + mmconf_base = res->base; + + current += acpi_create_mcfg_mmconfig((acpi_mcfg_mmconfig_t *)current, mmconf_base, 0x0, 0x0, 0x1f); // Fix me: should i reserve 255 busses ? +#endif + return current; +} + +static void ht_dev_read_resources(device_t dev) +{ +#if CONFIG_EXT_CONF_SUPPORT + struct resource *res; + + printk(BIOS_DEBUG,"%s %s\n", dev_path(dev), __func__); + set_nbmisc_enable_bits(dev, 0x0, 1 << 3, 1 << 3); // hide bar 3 +#endif + + pci_dev_read_resources(dev); + +#if CONFIG_EXT_CONF_SUPPORT + /* Add an MMCONFIG resource. */ + res = new_resource(dev, 0x1C); + res->base = EXT_CONF_BASE_ADDRESS; + res->size = 256 * 1024 * 1024; // 256 busses, 1MB memory space each + res->align = log2(res->size); + res->gran = log2(res->size); + res->limit = 0xffffffffffffffffULL; /* 64bit */ + res->flags = IORESOURCE_FIXED | IORESOURCE_MEM | IORESOURCE_PCI64 | + IORESOURCE_ASSIGNED | IORESOURCE_RESERVE; + + compact_resources(dev); +#endif +} + +/* for UMA internal graphics */ +void avoid_lpc_dma_deadlock(device_t nb_dev, device_t sb_dev) +{ + device_t k8_f0; + u8 reg; + + k8_f0 = dev_find_slot(0, PCI_DEVFN(0x18, 0)); + set_nbcfg_enable_bits(k8_f0, 0x68, 3 << 21, 1 << 21); + + reg = nbpcie_p_read_index(sb_dev, 0x10); + reg |= 0x100; /* bit9=1 */ + nbpcie_p_write_index(sb_dev, 0x10, reg); + + reg = nbpcie_p_read_index(nb_dev, 0x10); + reg |= 0x100; /* bit9=1 */ + nbpcie_p_write_index(nb_dev, 0x10, reg); + + /* Enable NP protocol over PCIE for memory-mapped writes targeting LPC + * Set this bit to avoid a deadlock condition. */ + reg = htiu_read_index(nb_dev, 0x6); + reg |= 0x1000000; /* bit26 */ + htiu_write_index(nb_dev, 0x6, reg); +} + +static void pcie_init(struct device *dev) +{ + /* Enable pci error detecting */ + u32 dword; + + printk(BIOS_INFO, "pcie_init in rs690_ht.c\n"); + + /* System error enable */ + dword = pci_read_config32(dev, 0x04); + dword |= (1 << 8); /* System error enable */ + dword |= (1 << 30); /* Clear possible errors */ + pci_write_config32(dev, 0x04, dword); + + /* + * 1 is APIC enable + * 18 is enable nb to accept A4 interrupt request from SB. + */ + dword = pci_read_config32(dev, 0x4C); + dword |= 1 << 1 | 1 << 18; /* Clear possible errors */ + pci_write_config32(dev, 0x4C, dword); +} + +static void ht_dev_set_subsystem(struct device *dev, unsigned vendor, unsigned device) +{ + pci_write_config32(dev, 0x50, ((device & 0xffff) << 16) | (vendor & 0xffff)); +} + +static struct pci_operations lops_pci = { + .set_subsystem = ht_dev_set_subsystem, +}; + +static struct device_operations ht_ops = { + .read_resources = ht_dev_read_resources, + .set_resources = ht_dev_set_resources, + .enable_resources = pci_dev_enable_resources, + .init = pcie_init, + .scan_bus = 0, + .ops_pci = &lops_pci, +}; + +static const struct pci_driver ht_driver __pci_driver = { + .ops = &ht_ops, + .vendor = PCI_VENDOR_ID_ATI, + .device = PCI_DEVICE_ID_ATI_RS690_HT, +}; diff --git a/pool/shard002/C/0059231_omp_thread_attach_test_2.c b/pool/shard002/C/0059231_omp_thread_attach_test_2.c new file mode 100644 index 0000000000000000000000000000000000000000..6dad0a2d55468c827af57cc364a8148d24485974 --- /dev/null +++ b/pool/shard002/C/0059231_omp_thread_attach_test_2.c @@ -0,0 +1,58 @@ +// execute in sequence +// input the number of num_user_threadsation + +#include +#include +#include +#include +#include +#include + +/* read timer in second */ +double read_timer() { + struct timeb tm; + ftime(&tm); + return (double) tm.time + (double) tm.millitm / 1000.0; +} + +int user_thread_return = 0; + +void *test_fun(void *arg){ + printf("thread: %d\n", *((int*)arg)); + omp_thread_attach_with_callback(NULL, &user_thread_return); + printf("thread call back: %d\n", *((int*)arg)); + + return ((void*)0); +} + +int main(int argc, char * argv[]) { + if (argc >= 2){ + omp_set_num_threads(atoi(argv[1])); + num_user_threads = atoi(argv[1]); + } + + int num_user_threads = 100; + pthread_t pthreads[num_user_threads]; + + // pthread_create + for(i=0; i. +*/ +/** \file mmm-common.c + Common parts of the MMM family of methods for the + electrostatic interaction, MMM1D, MMM2D and ELC. This file contains the code for the polygamma + expansions used for the near formulas of MMM1D and MMM2D. + + The expansion of the polygamma functions is fairly easy and follows directly from Abramowitz and Stegun. + For details, see Axel Arnold and Christian Holm, "MMM2D: A fast and accurate summation method for + electrostatic interactions in 2D slab geometries", Comp. Phys. Comm., 148/3(2002),327-348. +*/ + +#include "mmm-common.h" +#include "utils.h" + +Polynom *modPsi = NULL; +int n_modPsi = 0; + +static void preparePolygammaEven(int n, double binom, Polynom *series) +{ + /* (-0.5 n) psi^2n/2n! (-0.5 n) and psi^(2n+1)/(2n)! series expansions + note that BOTH carry 2n! */ + int order; + double deriv; + double maxx, x_order, coeff, pref; + + deriv = 2*n; + if (n == 0) { + // psi^0 has a slightly different series expansion + maxx = 0.25; + alloc_doublelist(series, 1); + series->e[0] = 2*(1 - C_GAMMA); + for (order = 1;; order += 1) { + x_order = 2*order; + coeff = -2*hzeta(x_order + 1, 2); + if (fabs(maxx*coeff)*(4.0/3.0) < ROUND_ERROR_PREC) + break; + realloc_doublelist(series, order + 1); + series->e[order] = coeff; + maxx *= 0.25; + } + series->n = order; + } + else { + // even, n > 0 + maxx = 1; + pref = 2; + init_doublelist(series); + for (order = 0;; order++) { + // only even exponents of x + x_order = 2*order; + coeff = pref*hzeta(1 + deriv + x_order, 2); + if ((fabs(maxx*coeff)*(4.0/3.0) < ROUND_ERROR_PREC) && (x_order > deriv)) + break; + realloc_doublelist(series, order + 1); + series->e[order] = -binom*coeff; + maxx *= 0.25; + pref *= (1.0 + deriv/(x_order + 1)); + pref *= (1.0 + deriv/(x_order + 2)); + } + series->n = order; + } +} + +static void preparePolygammaOdd(int n, double binom, Polynom *series) +{ + int order; + double deriv; + double maxx, x_order, coeff, pref; + + deriv = 2*n + 1; + maxx = 0.5; + // to get 1/(2n)! instead of 1/(2n+1)! + pref = 2*deriv*(1 + deriv); + init_doublelist(series); + for (order = 0;; order++) { + // only odd exponents of x + x_order = 2*order + 1; + coeff = pref*hzeta(1 + deriv + x_order, 2); + if ((fabs(maxx*coeff)*(4.0/3.0) < ROUND_ERROR_PREC) && (x_order > deriv)) + break; + realloc_doublelist(series, order + 1); + series->e[order] = -binom*coeff; + maxx *= 0.25; + pref *= (1.0 + deriv/(x_order + 1)); + pref *= (1.0 + deriv/(x_order + 2)); + } + series->n = order; +} + +void create_mod_psi_up_to(int new_n) +{ + int n; + double binom; + + if (new_n > n_modPsi) { + int old = n_modPsi; + n_modPsi = new_n; + modPsi = realloc(modPsi, 2*n_modPsi*sizeof(Polynom)); + + binom = 1.0; + for (n = 0; n < old; n++) + binom *= (-0.5 - n)/(double)(n+1); + + for (; n < n_modPsi; n++) { + preparePolygammaEven(n, binom, &modPsi[2*n]); + preparePolygammaOdd(n, binom, &modPsi[2*n + 1]); + binom *= (-0.5 - n)/(double)(n+1); + } + } +} diff --git a/pool/shard002/C/0059240_unique_arr3.c b/pool/shard002/C/0059240_unique_arr3.c new file mode 100644 index 0000000000000000000000000000000000000000..0668f3dddc397e7316183d063e3aeab93f29b9bb --- /dev/null +++ b/pool/shard002/C/0059240_unique_arr3.c @@ -0,0 +1,27 @@ +#include +#include + +#define NINTS 3 + +int ** ARRAY create () { + int **arr = malloc(NINTS * sizeof (int*)); + + for (int i = 0; i < NINTS; i++) { + int *x = malloc (sizeof (int)); + *x = i; + arr[i] = x; + } + + return arr; +} + +void main () { + int **arr = create (); + + for (int i = 0; i < NINTS; i++) { + int *x = arr[i]; + if (x != NULL) { + csolve_assert (*x == i); + } + } +} diff --git a/pool/shard002/C/0059255_warmboot.c b/pool/shard002/C/0059255_warmboot.c new file mode 100644 index 0000000000000000000000000000000000000000..ffc637c2a9ba5ecdfdce9d0a5d7e7ee1c2632c7c --- /dev/null +++ b/pool/shard002/C/0059255_warmboot.c @@ -0,0 +1,324 @@ +/* + * (C) Copyright 2010 + * NVIDIA Corporation + * + * 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 +#include + +NvBootError sign_data_block(NvU8 *source, + NvU32 length, + NvU8 *hash); + +/* ------------------------------------- + * Configuration parameters + * ------------------------------------- + */ + +/* ------------------------------------- + * Definitions + * ------------------------------------- + */ + +/* NOTE: If more than one of the following is enabled, only one of them will + * actually be used. RANDOM takes precedence over PATTERN and ZERO, and + * PATTERN takes precedence overy ZERO. + */ +#define RANDOM_AES_BLOCK_IS_RANDOM 1 /* to randomize the header */ +#define RANDOM_AES_BLOCK_IS_PATTERN 1 /* to patternize the header */ +#define RANDOM_AES_BLOCK_IS_ZERO 1 /* to clear the header */ + +/* Address at which AP20 WB0 code runs */ +/* The address must not overlap the bootrom's IRAM usage */ +#define AP20_WB0_RUN_ADDRESS 0x40020000 +#define AP20_IRAM_BASE 0x40000000 + +/* ------------------------------------- + * Global External Labels + * ------------------------------------- + */ + +void wb_start(void); /* Start of WB assembly code */ +void wb_end(void); /* End of WB assembly code */ + +#define NV_ADDRESS_MAP_FUSE_BASE 0x7000F800UL +#define FUSE_PRODUCTION_MODE_0 _MK_ADDR_CONST(0x100) +#define FUSE_FA_0 _MK_ADDR_CONST(0x148) +#define FUSE_SECURITY_MODE_0 _MK_ADDR_CONST(0x1a0) + +/* ------------------------------------- + * Local Functions + * ------------------------------------- + */ +static NvU32 get_major_version(void) +{ + NvU32 reg = 0; + NvU32 major_id = 0; + + reg = NV_READ32( NV_ADDRESS_MAP_APB_MISC_BASE + APB_MISC_GP_HIDREV_0) ; + major_id = NV_DRF_VAL(APB_MISC, GP_HIDREV, MAJORREV, reg); + return major_id; +} + +static NvBool is_production_mode_fuse_set(void) +{ + NvU32 reg; + + reg = NV_READ32(NV_ADDRESS_MAP_FUSE_BASE + FUSE_PRODUCTION_MODE_0); + if (reg) + return NV_TRUE; + else + return NV_FALSE; +} + +static NvBool is_odm_production_mode_fuse_set(void) +{ + NvU32 reg; + + reg = NV_READ32(NV_ADDRESS_MAP_FUSE_BASE + FUSE_SECURITY_MODE_0); + if (reg) + return NV_TRUE; + else + return NV_FALSE; +} + +static NvBool ap20_is_failure_analysis_mode(void) +{ + volatile NvU32 reg; + + reg = NV_READ32(NV_ADDRESS_MAP_FUSE_BASE + FUSE_FA_0); + if (reg) + return NV_TRUE; + else + return NV_FALSE; +} + +static NvBool ap20_is_odm_production_mode(void) +{ + if (!ap20_is_failure_analysis_mode() && + is_odm_production_mode_fuse_set()) + return NV_TRUE; + else + return NV_FALSE; +} + +static NvBool ap20_is_production_mode(void) +{ + if (get_major_version() == 0) + return NV_TRUE; + + if (!ap20_is_failure_analysis_mode() && + is_production_mode_fuse_set() && + !is_odm_production_mode_fuse_set()) + return NV_TRUE; + else + return NV_FALSE; +} + +static NvBool fuse_get_ap20_hal(nv_fuse_hal *hal) +{ + NvU32 reg; + + reg = NV_READ32(NV_ADDRESS_MAP_APB_MISC_BASE + APB_MISC_GP_HIDREV_0); + if (NV_DRF_VAL(APB_MISC_GP, HIDREV, CHIPID, reg) == 0x20) { + hal->is_odm_production_mode = ap20_is_odm_production_mode; + hal->is_nv_production_mode = ap20_is_production_mode; + return NV_TRUE; + } + return NV_FALSE; +} + +static nvbl_operating_mode nv_fuse_get_operation_mode(void) +{ + nv_fuse_hal hal; + if (fuse_get_ap20_hal(&hal)) { + if (hal.is_odm_production_mode()) { + printf("!!! OdmProductionMode is not supported !!!\n"); + return nvbl_mode_undefined; + } else { + if (hal.is_nv_production_mode()) + return nvbl_mode_production; + else + return nvbl_mode_undefined; + } + } + return nvbl_mode_undefined; +} + +static NvU64 query_random_seed(void) +{ + return 0; +} + +static void determine_crypto_options(NvBool* is_encrypted, NvBool* is_signed, + NvBool* use_zero_key) +{ + switch (nv_fuse_get_operation_mode()) { + case nvbl_mode_production: + *is_encrypted = NV_FALSE; + *is_signed = NV_TRUE; + *use_zero_key = NV_TRUE; + break; + + case nvbl_mode_undefined: + default: + *is_encrypted = NV_FALSE; + *is_signed = NV_FALSE; + *use_zero_key = NV_FALSE; + break; + } +} + +static NvBootError sign_wb_code(NvU32 start, NvU32 length, NvBool use_zero_key) +{ + NvBootError e; + NvU8 *source; /* Pointer to source */ + NvU8 *hash; + + /* Calculate AES block parameters. */ + source = (NvU8 *)(start + offsetof(nvboot_wb_header, random_aes_block)); + length -= offsetof(nvboot_wb_header, random_aes_block); + hash = (NvU8 *)(start + offsetof(nvboot_wb_header, hash)); + e = sign_data_block(source, length, hash); + return e; +} + +/* ------------------------------------- + * Global Functions + * ------------------------------------- + */ + +NvBootError prepare_wb_code(NvU32 seg_address, NvU32 seg_length) +{ + NvBootError e = NvBootError_NotInitialized; /* Error code */ + + NvU32 start; /* start of the actual code */ + NvU32 end; /* end of the actual code */ + NvU32 actual_length; /* length of the actual code */ + NvU32 length; /* length of the + signed/encrypted code */ + nvboot_wb_header *src_header; /* Pointer to src WB header */ + nvboot_wb_header *dst_header; /* Pointer to dest WB header */ + NvBool is_encrypted; /* Segment is encrypted */ + NvBool is_signed; /* Segment is signed */ + NvBool use_zero_key; /* Use key of all zeros */ + + /* Determine crypto options. */ + determine_crypto_options(&is_encrypted, &is_signed, &use_zero_key); + + /* Get the actual code limits. */ + start = (NvU32)wb_start; + end = (NvU32)wb_end; + actual_length = end - start; + length = ((actual_length + 15) >> 4) << 4; + + /* The region specified by seg_address must be in SDRAM and must be + * nonzero in length. + */ + if ((seg_length == 0) ||(seg_address == 0) || + (seg_address >= AP20_IRAM_BASE)) { + goto fail; + } + + /* Things must be 16-byte aligned. */ + if ((seg_length & 0xF) || (seg_address & 0xF)) { + goto fail; + } + + /* Will the code fit? */ + if (seg_length < length) { + goto fail; + } + + /* Get a pointers to the source and destination region header. */ + src_header = (nvboot_wb_header*)start; + dst_header = (nvboot_wb_header*)seg_address; + + /* Populate the random_aes_block as requested. */ +#if RANDOM_AES_BLOCK_IS_RANDOM + { + NvU64 *pAesBlock = (NvU64*)&(src_header->random_aes_block); + NvU64 *pEnd = (NvU64*)(((NvU32)pAesBlock) + + sizeof(src_header->random_aes_block)); + do { + *pAesBlock++ = query_random_seed(); + } while (pAesBlock < pEnd); + } +#elif RANDOM_AES_BLOCK_IS_PATTERN + { + NvU32 *pAesBlock = (NvU32*)&(src_header->random_aes_block); + NvU32 *pEnd = (NvU32*)(((NvU32)pAesBlock) + + sizeof(src_header->random_aes_block)); + + do { + *pAesBlock++ = RANDOM_AES_BLOCK_IS_PATTERN; + } while (pAesBlock < pEnd); + } +#elif RANDOM_AES_BLOCK_IS_ZERO + { + NvU32 *pAesBlock = (NvU32*)&(src_header->random_aes_block); + NvU32 *pEnd = (NvU32*)(((NvU32)pAesBlock) + + sizeof(src_header->random_aes_block)); + + do { + *pAesBlock++ = 0; + } while (pRandomAesBlock < pEnd); + } +#endif + + /* Populate the header. */ + src_header->length_in_secure = length; + src_header->length_secure = length; + src_header->destination = AP20_WB0_RUN_ADDRESS; + src_header->entry_point = AP20_WB0_RUN_ADDRESS; + src_header->code_length = length - sizeof(nvboot_wb_header); + + if (is_encrypted) { + /* Encryption is not supported */ + printf("!!!! No Encrypion implemented!!!!\n"); + dst_header->length_in_secure = 0; + e = NvBootError_Unimplemented; + goto fail; + } else { + /* No, just copy the code directly. */ + memcpy(dst_header, src_header, length); + } + + /* Clear the signature in the destination code segment. */ + memset(&(dst_header->hash), 0, sizeof(dst_header->hash)); + + if (is_signed) { + NV_CHECK_ERROR_CLEANUP(sign_wb_code(seg_address, length, + use_zero_key)); + } + +fail: + if (e != NvBootError_Success) + printf("WB code not copied to LP0 location! (error=0x%x)\n", e); + + return e; +} diff --git a/pool/shard002/C/0059265_init.c b/pool/shard002/C/0059265_init.c new file mode 100644 index 0000000000000000000000000000000000000000..434ed37e90830f63aa289e3eb1e8ff0195fbe252 --- /dev/null +++ b/pool/shard002/C/0059265_init.c @@ -0,0 +1,162 @@ +/* -*- Mode: C; c-basic-offset:4 ; -*- */ +/* + * (C) 2001 by Argonne National Laboratory. + * See COPYRIGHT in top-level directory. + */ + +#include "mpiimpl.h" +#include "mpi_init.h" + + +/* -- Begin Profiling Symbol Block for routine MPI_Init */ +#if defined(HAVE_PRAGMA_WEAK) +#pragma weak MPI_Init = PMPI_Init +#elif defined(HAVE_PRAGMA_HP_SEC_DEF) +#pragma _HP_SECONDARY_DEF PMPI_Init MPI_Init +#elif defined(HAVE_PRAGMA_CRI_DUP) +#pragma _CRI duplicate MPI_Init as PMPI_Init +#endif +/* -- End Profiling Symbol Block */ + +/* Define MPICH_MPI_FROM_PMPI if weak symbols are not supported to build + the MPI routines */ +#ifndef MPICH_MPI_FROM_PMPI +#undef MPI_Init +#define MPI_Init PMPI_Init + +/* Fortran logical values. extern'd in mpiimpl.h */ +/* MPI_Fint MPIR_F_TRUE, MPIR_F_FALSE; */ + +/* Any internal routines can go here. Make them static if possible */ + +/* must go inside this #ifdef block to prevent duplicate storage on darwin */ +int MPIR_async_thread_initialized = 0; +#endif + +#undef FUNCNAME +#define FUNCNAME MPI_Init + +/*@ + MPI_Init - Initialize the MPI execution environment + + Input Parameters: ++ argc - Pointer to the number of arguments +- argv - Pointer to the argument vector + +Thread and Signal Safety: +This routine must be called by one thread only. That thread is called +the `main thread` and must be the thread that calls 'MPI_Finalize'. + +Notes: + The MPI standard does not say what a program can do before an 'MPI_INIT' or + after an 'MPI_FINALIZE'. In the MPICH implementation, you should do + as little as possible. In particular, avoid anything that changes the + external state of the program, such as opening files, reading standard + input or writing to standard output. + +Notes for Fortran: +The Fortran binding for 'MPI_Init' has only the error return +.vb + subroutine MPI_INIT( ierr ) + integer ierr +.ve + +.N Errors +.N MPI_SUCCESS +.N MPI_ERR_INIT + +.seealso: MPI_Init_thread, MPI_Finalize +@*/ +int MPI_Init( int *argc, char ***argv ) +{ + static const char FCNAME[] = "MPI_Init"; + int mpi_errno = MPI_SUCCESS; + int rc; + int threadLevel, provided; + MPID_MPI_INIT_STATE_DECL(MPID_STATE_MPI_INIT); + + rc = MPID_Wtime_init(); +#ifdef USE_DBG_LOGGING + MPIU_DBG_PreInit( argc, argv, rc ); +#endif + + MPID_MPI_INIT_FUNC_ENTER(MPID_STATE_MPI_INIT); +# ifdef HAVE_ERROR_CHECKING + { + MPID_BEGIN_ERROR_CHECKS; + { + if (MPIR_Process.initialized != MPICH_PRE_INIT) { + mpi_errno = MPIR_Err_create_code( MPI_SUCCESS, MPIR_ERR_RECOVERABLE, FCNAME, __LINE__, MPI_ERR_OTHER, + "**inittwice", NULL ); + } + if (mpi_errno) goto fn_fail; + } + MPID_END_ERROR_CHECKS; + } +# endif /* HAVE_ERROR_CHECKING */ + + /* ... body of routine ... */ + +#if (MPICH_THREAD_LEVEL == MPI_THREAD_MULTIPLE) + /* If we support all thread levels, allow the use of an environment + variable to set the default thread level */ + { + const char *str = 0; + threadLevel = MPI_THREAD_SINGLE; + if (MPL_env2str( "MPICH_THREADLEVEL_DEFAULT", &str )) { + if (strcmp(str,"MULTIPLE") == 0 || strcmp(str,"multiple") == 0) { + threadLevel = MPI_THREAD_MULTIPLE; + } + else if (strcmp(str,"SERIALIZED") == 0 || strcmp(str,"serialized") == 0) { + threadLevel = MPI_THREAD_SERIALIZED; + } + else if (strcmp(str,"FUNNELED") == 0 || strcmp(str,"funneled") == 0) { + threadLevel = MPI_THREAD_FUNNELED; + } + else if (strcmp(str,"SINGLE") == 0 || strcmp(str,"single") == 0) { + threadLevel = MPI_THREAD_SINGLE; + } + else { + MPIU_Error_printf( "Unrecognized thread level %s\n", str ); + exit(1); + } + } + } +#else + threadLevel = MPI_THREAD_SINGLE; +#endif + + /* If the user requested for asynchronous progress, request for + * THREAD_MULTIPLE. */ + rc = 0; + MPL_env2bool("MPICH_ASYNC_PROGRESS", &rc); + if (rc) + threadLevel = MPI_THREAD_MULTIPLE; + + mpi_errno = MPIR_Init_thread( argc, argv, threadLevel, &provided ); + if (mpi_errno != MPI_SUCCESS) goto fn_fail; + + if (rc && provided == MPI_THREAD_MULTIPLE) { + mpi_errno = MPIR_Init_async_thread(); + if (mpi_errno) goto fn_fail; + + MPIR_async_thread_initialized = 1; + } + + /* ... end of body of routine ... */ + MPID_MPI_INIT_FUNC_EXIT(MPID_STATE_MPI_INIT); + return mpi_errno; + + fn_fail: + /* --BEGIN ERROR HANDLING-- */ +# ifdef HAVE_ERROR_REPORTING + { + mpi_errno = MPIR_Err_create_code( + mpi_errno, MPIR_ERR_RECOVERABLE, FCNAME, __LINE__, MPI_ERR_OTHER, + "**mpi_init", "**mpi_init %p %p", argc, argv); + } +# endif + mpi_errno = MPIR_Err_return_comm( 0, FCNAME, mpi_errno ); + return mpi_errno; + /* --END ERROR HANDLING-- */ +} diff --git a/pool/shard002/C/0059266_llid_kernel.c b/pool/shard002/C/0059266_llid_kernel.c new file mode 100644 index 0000000000000000000000000000000000000000..83262ab9c89a9b822cb8fa74bf4bb53f296c8bef --- /dev/null +++ b/pool/shard002/C/0059266_llid_kernel.c @@ -0,0 +1,241 @@ +/* + * llid.c + * + * Low-Level Interface Driver + * + * COPYRIGHT(C) Samsung Electronics Co.Ltd. 2009-2010 All Right Reserved. + * + * 2009.02 - First editing by SungHwan.yun @LDK@ + * + * 2009.03 - Currently managed by SungHwan.yun @LDK@ + * + */ +#include +#include +#include "j4fs.h" + +#if defined(J4FS_USE_XSR) + +#if (LINUX_VERSION_CODE >= KERNEL_VERSION(2, 6, 28)) +#include "./Inc/XsrTypes.h" +#include "./Inc/STL.h" +#else +#include "../../drivers/txsr/Inc/XsrTypes.h" +#include "../../drivers/txsr/Inc/STL.h" +#endif + +#elif defined(J4FS_USE_FSR) + +#if (LINUX_VERSION_CODE >= KERNEL_VERSION(2, 6, 28)) +#include "../../fsr/Inc/FSR.h" +#include "../../fsr/Inc/FSR_STL.h" +#else +#include "../fsr/Inc/FSR.h" +#include "../fsr/Inc/FSR_STL.h" +#endif + +// J4FS for moviNAND merged from ROSSI +#elif defined(J4FS_USE_MOVI) +/* j4fs device node name */ +#define J4FS_DEVNAME "/dev/block/mmcblk0p4" +static struct file *j4fs_filp; +// J4FS for moviNAND merged from ROSSI + +#else +'compile error' +#endif + +extern j4fs_device_info device_info; +extern unsigned int j4fs_traceMask; + +/* + * Fills the specified buffer with the number of bytes defined by length from the device's absolute physical address + * parameters + * offset : start physical page number + * length : bytes to write + * buffer : buffer to write data + * return value + * The return code should indicate ERROR (1) or OK(0). If the return code indicates ERROR, the dev_ptr->status field should indicate + * the return error code. + */ +int FlashDevRead(j4fs_device_info *dev_ptr, DWORD offset, DWORD length, BYTE *buffer) +{ + int ret=-1; +#if defined(J4FS_USE_XSR) + DWORD nVol=0; + int part_id=dev_ptr->device; +#endif + +// J4FS for moviNAND merged from ROSSI +#ifdef J4FS_USE_MOVI + mm_segment_t oldfs; +#endif +// J4FS for moviNAND merged from ROSSI + +#if defined(J4FS_USE_XSR) + ret = STL_Read(nVol, part_id, offset/512, length/512, buffer); + if (ret != STL_SUCCESS) { + T(J4FS_TRACE_ALWAYS,("%s %d: Error(offset,length,j4fs_end,nErr)=(0x%x,0x%x,0x%x,0x%x)\n",__FUNCTION__,__LINE__,offset,length,device_info.j4fs_end,ret)); + return J4FS_FAIL; + } +#elif defined(J4FS_USE_FSR) + ret = FSR_STL_Read(nVol, part_id, offset/512, length/512, buffer, FSR_STL_FLAG_DEFAULT); + if (ret != FSR_STL_SUCCESS) { + T(J4FS_TRACE_ALWAYS,("%s %d: Error(offset,length,j4fs_end,nErr)=(0x%x,0x%x,0x%x,0x%x)\n",__FUNCTION__,__LINE__,offset,length,device_info.j4fs_end,ret)); + return J4FS_FAIL; + } +// J4FS for moviNAND merged from ROSSI +#elif defined(J4FS_USE_MOVI) + if (!j4fs_filp) { + printk("J4FS not available\n"); + return J4FS_FAIL; + } + j4fs_filp->f_flags |= O_NONBLOCK; + oldfs = get_fs(); set_fs(get_ds()); + ret = j4fs_filp->f_op->llseek(j4fs_filp, offset, SEEK_SET); + ret = j4fs_filp->f_op->read(j4fs_filp, buffer, length, &j4fs_filp->f_pos); + set_fs(oldfs); + j4fs_filp->f_flags &= ~O_NONBLOCK; + if (ret < 0) { + printk(1, "j4fs_filp->read() failed: %d\n", ret); + return J4FS_FAIL; + } +// J4FS for moviNAND merged from ROSSI +#else +'compile error' +#endif + + return J4FS_SUCCESS; +} + +/* + * This function writes length bytes of data from a specified buffer to the destination address within the device + * parameters + * offset : start physical page number + * length : bytes to write + * buffer : buffer to write data + * return value + * The return code should indicate ERROR (1) or OK(0). If the return code indicates ERROR, the dev_ptr->status field should indicate + * the return error code. + */ +int FlashDevWrite(j4fs_device_info *dev_ptr, DWORD offset, DWORD length, BYTE *buffer) +{ + int ret=-1; +#if defined(J4FS_USE_XSR) + DWORD nVol=0; + int part_id=dev_ptr->device; +#endif + +// J4FS for moviNAND merged from ROSSI +#ifdef J4FS_USE_MOVI + mm_segment_t oldfs; +#endif +// J4FS for moviNAND merged from ROSSI + +#if defined(J4FS_USE_XSR) + ret = STL_Write(nVol, part_id, offset/512, length/512, buffer); + if (ret != STL_SUCCESS) { + T(J4FS_TRACE_ALWAYS,("%s %d: Error(offset,length,j4fs_end,nErr)=(0x%x,0x%x,0x%x,0x%x)\n",__FUNCTION__,__LINE__,offset,length,device_info.j4fs_end,ret)); + return J4FS_FAIL; + } +#elif defined(J4FS_USE_FSR) + ret = FSR_STL_Write(nVol, part_id, offset/512, length/512, buffer, FSR_STL_FLAG_DEFAULT); + if (ret != FSR_STL_SUCCESS) { + T(J4FS_TRACE_ALWAYS,("%s %d: Error(offset,length,j4fs_end,nErr)=(0x%x,0x%x,0x%x,0x%x)\n",__FUNCTION__,__LINE__,offset,length,device_info.j4fs_end,ret)); + return J4FS_FAIL; + } +// J4FS for moviNAND merged from ROSSI +#elif defined(J4FS_USE_MOVI) + if (!j4fs_filp) { + printk("J4FS not available\n"); + return J4FS_FAIL; + } + j4fs_filp->f_flags |= O_NONBLOCK; + oldfs = get_fs(); set_fs(get_ds()); + ret = j4fs_filp->f_op->llseek(j4fs_filp, offset, SEEK_SET); + ret = j4fs_filp->f_op->write(j4fs_filp, buffer, length, &j4fs_filp->f_pos); + set_fs(oldfs); + j4fs_filp->f_flags &= ~O_NONBLOCK; + if (ret < 0) { + printk(1, "j4fs_filp->write() failed: %d\n", ret); + return J4FS_FAIL; + } +// J4FS for moviNAND merged from ROSSI +#else +'compile error' +#endif + + return J4FS_SUCCESS; +} + +/* + * In order to reuse the flash media, an erase command must be provided for the FSD. This command erases a single flash erase-block beginning + * at the address specified by the aux field in the DEVICE_INFO structure. The blocksize field of the DEVICE_INFO structure is used to force the aux ptr + * to a block boundary. + * parameters + * dev_ptr->aux : start block address to be erased + */ +int FlashDevErase(j4fs_device_info *dev_ptr) +{ + // TODO + return J4FS_SUCCESS; +} + +int FlashDevSpecial(j4fs_device_info *dev_ptr, DWORD scmd) +{ + switch(scmd) + { + case J4FS_INIT: + // Initialize the internal FSD structures to use a device + FlashDevMount(); + + break; + + case J4FS_GET_INFO: + break; + +// J4FS for moviNAND merged from ROSSI + case J4FS_EXIT: + FlashDevUnmount(); +// J4FS for moviNAND merged from ROSSI + + default: + break; + } + + return J4FS_SUCCESS; +} + +int FlashDevMount() +{ + DWORD media_status_table_size=1; // Media Status Table occupys 1 block + +// J4FS for moviNAND merged from ROSSI +#ifdef J4FS_USE_MOVI + j4fs_filp = filp_open(J4FS_DEVNAME, O_RDWR|O_SYNC, 0); + if (IS_ERR(j4fs_filp)) { + printk("FlashDevMount : filp_open() failed~!: %ld\n", PTR_ERR(j4fs_filp)); + return J4FS_FAIL; + } + printk("FlashDevMount : filp_open() OK....!\n"); +#endif +// J4FS for moviNAND merged from ROSSI + + device_info.device=J4FS_PARTITION_ID; + device_info.blocksize=PHYSICAL_BLOCK_SIZE; + device_info.pagesize=PHYSICAL_PAGE_SIZE; + device_info.j4fs_offset=media_status_table_size*device_info.blocksize; // j4fs_offset follows the Media Status Table. + return J4FS_SUCCESS; +} + +int FlashDevUnmount() +{ +// ROSSI Projecct(hyunkwon.kim) 2010.09.06 Add J4FS for Parameter Infomation +#ifdef J4FS_USE_MOVI + filp_close(j4fs_filp, NULL); + printk("FlashDevUnmount : filp_close() OK....!\n"); +#endif +// ROSSI Projecct(hyunkwon.kim) 2010.09.06 End + + return J4FS_SUCCESS; +} diff --git a/pool/shard002/C/0059269_CWE190_Integer_Overflow__unsigned_int_rand_square_66a.c b/pool/shard002/C/0059269_CWE190_Integer_Overflow__unsigned_int_rand_square_66a.c new file mode 100644 index 0000000000000000000000000000000000000000..add0f48540c03f43dbb2ef5c3ded3be496bc5871 --- /dev/null +++ b/pool/shard002/C/0059269_CWE190_Integer_Overflow__unsigned_int_rand_square_66a.c @@ -0,0 +1,103 @@ +/* TEMPLATE GENERATED TESTCASE FILE +Filename: CWE190_Integer_Overflow__unsigned_int_rand_square_66a.c +Label Definition File: CWE190_Integer_Overflow.label.xml +Template File: sources-sinks-66a.tmpl.c +*/ +/* + * @description + * CWE: 190 Integer Overflow + * BadSource: rand Set data to result of rand() + * 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 + +/* bad function declaration */ +void CWE190_Integer_Overflow__unsigned_int_rand_square_66b_badSink(unsigned int dataArray[]); + +void CWE190_Integer_Overflow__unsigned_int_rand_square_66_bad() +{ + unsigned int data; + unsigned int dataArray[5]; + data = 0; + /* POTENTIAL FLAW: Use a random value */ + data = (unsigned int)RAND32(); + /* put data in array */ + dataArray[2] = data; + CWE190_Integer_Overflow__unsigned_int_rand_square_66b_badSink(dataArray); +} + +#endif /* OMITBAD */ + +#ifndef OMITGOOD + +/* goodG2B uses the GoodSource with the BadSink */ +void CWE190_Integer_Overflow__unsigned_int_rand_square_66b_goodG2BSink(unsigned int dataArray[]); + +static void goodG2B() +{ + unsigned int data; + unsigned int dataArray[5]; + data = 0; + /* FIX: Use a small, non-zero value that will not cause an overflow in the sinks */ + data = 2; + dataArray[2] = data; + CWE190_Integer_Overflow__unsigned_int_rand_square_66b_goodG2BSink(dataArray); +} + +/* goodB2G uses the BadSource with the GoodSink */ +void CWE190_Integer_Overflow__unsigned_int_rand_square_66b_goodB2GSink(unsigned int dataArray[]); + +static void goodB2G() +{ + unsigned int data; + unsigned int dataArray[5]; + data = 0; + /* POTENTIAL FLAW: Use a random value */ + data = (unsigned int)RAND32(); + dataArray[2] = data; + CWE190_Integer_Overflow__unsigned_int_rand_square_66b_goodB2GSink(dataArray); +} + +void CWE190_Integer_Overflow__unsigned_int_rand_square_66_good() +{ + goodG2B(); + goodB2G(); +} + +#endif /* OMITGOOD */ + +/* Below is the main(). It is only used when building this testcase on + its own for testing or for building a binary to use in testing binary + analysis tools. It is not used when compiling all the testcases as one + application, which is how source code analysis tools are tested. */ + +#ifdef INCLUDEMAIN + +int main(int argc, char * argv[]) +{ + /* seed randomness */ + srand( (unsigned)time(NULL) ); +#ifndef OMITGOOD + printLine("Calling good()..."); + CWE190_Integer_Overflow__unsigned_int_rand_square_66_good(); + printLine("Finished good()"); +#endif /* OMITGOOD */ +#ifndef OMITBAD + printLine("Calling bad()..."); + CWE190_Integer_Overflow__unsigned_int_rand_square_66_bad(); + printLine("Finished bad()"); +#endif /* OMITBAD */ + return 0; +} + +#endif diff --git a/pool/shard002/C/0059284_cgi_test.c b/pool/shard002/C/0059284_cgi_test.c new file mode 100644 index 0000000000000000000000000000000000000000..bd446c0a966d7048108b6b398afedd4397b55ec4 --- /dev/null +++ b/pool/shard002/C/0059284_cgi_test.c @@ -0,0 +1,40 @@ +#include +#include +#include + +#if defined(_WIN32) || defined(WIN32) || defined(WINDOWS) +#include +#include +#endif + +int +main(int argc, char *argv[]) +{ + char buf[1024]; + size_t rec_len = 0; + const char *response_header = "Content-Type: text/plain\r\n" + "Connection: close\r\n" + "\r\n"; + const char *req_method = getenv("REQUEST_METHOD"); + const char *con_length = getenv("CONTENT_LENGTH"); + +#if defined(_WIN32) || defined(WIN32) || defined(WINDOWS) + _setmode(_fileno(stdin), _O_BINARY); + _setmode(_fileno(stdout), _O_BINARY); +#endif + + /* Write the response header with \r\n */ + fwrite(response_header, 1, strlen(response_header), stdout); + + /* Headline for generated reply: */ + printf("Got message:\n Method: %s\n Content-Length: %s\n Content: ", + req_method, + con_length ? con_length : "not set"); + + /* Read all data from stdin and send it to stdout */ + while ((rec_len = fread(buf, 1, sizeof(buf) - 1, stdin)) > 0) { + fwrite(buf, 1, rec_len, stdout); + } + + return 0; +} diff --git a/pool/shard002/C/0059288_tabuada.c b/pool/shard002/C/0059288_tabuada.c new file mode 100644 index 0000000000000000000000000000000000000000..fa4adbdb439bd0dc4a5cc236b3ce21339b75e5db --- /dev/null +++ b/pool/shard002/C/0059288_tabuada.c @@ -0,0 +1,11 @@ +#include + +int main() { + int numero; + printf("Qual tabuada você quer?"); + scanf("%d", &numero); + for(int i = 0; i <= 10; i++) { + int multiplicacao = numero * i; + printf("%d x %d = %d\n", numero, i, multiplicacao); + } +} diff --git a/pool/shard002/C/0059289_super.c b/pool/shard002/C/0059289_super.c new file mode 100644 index 0000000000000000000000000000000000000000..0dac9097f7b786c1d635d80fc1264c75fa07c8d4 --- /dev/null +++ b/pool/shard002/C/0059289_super.c @@ -0,0 +1,203 @@ +/* + * Copyright (c) 1998-2011 Erez Zadok + * Copyright (c) 2009 Shrikar Archak + * Copyright (c) 2003-2011 Stony Brook University + * Copyright (c) 2003-2011 The Research Foundation of SUNY + * + * 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 "sdcardfsjb.h" + +/* + * The inode cache is used with alloc_inode for both our inode info and the + * vfs inode. + */ +static struct kmem_cache *sdcardfsjb_inode_cachep; + +/* final actions when unmounting a file system */ +static void sdcardfsjb_put_super(struct super_block *sb) +{ + struct sdcardfsjb_sb_info *spd; + struct super_block *s; + + spd = SDCARDFSJB_SB(sb); + if (!spd) + return; + + /* decrement lower super references */ + s = sdcardfsjb_lower_super(sb); + sdcardfsjb_set_lower_super(sb, NULL); + atomic_dec(&s->s_active); + + kfree(spd); + sb->s_fs_info = NULL; +} + +static int sdcardfsjb_statfs(struct dentry *dentry, struct kstatfs *buf) +{ + int err; + struct path lower_path; + +#if defined(LOWER_FS_MIN_FREE_SIZE) + u32 min_blocks; +#endif + + sdcardfsjb_get_lower_path(dentry, &lower_path); + err = vfs_statfs(&lower_path, buf); + sdcardfsjb_put_lower_path(dentry, &lower_path); + +#if defined(LOWER_FS_MIN_FREE_SIZE) + /* Invalid statfs informations. */ + if (buf->f_bsize == 0) { + printk(KERN_ERR "Returned block size is zero.\n"); + return -EINVAL; + } + + min_blocks = (LOWER_FS_MIN_FREE_SIZE/buf->f_bsize); + buf->f_blocks -= min_blocks; + + if (buf->f_bavail > min_blocks) + buf->f_bavail -= min_blocks; + else + buf->f_bavail = 0; + + /* Make reserved blocks invisiable to media storage */ + buf->f_bfree = buf->f_bavail; +#endif + /* set return buf to our f/s to avoid confusing user-level utils */ + buf->f_type = SDCARDFS_SUPER_MAGIC; + + return err; +} + +/* + * @flags: numeric mount options + * @options: mount options string + */ +static int sdcardfsjb_remount_fs(struct super_block *sb, int *flags, char *options) +{ + int err = 0; + + /* + * The VFS will take care of "ro" and "rw" flags among others. We + * can safely accept a few flags (RDONLY, MANDLOCK), and honor + * SILENT, but anything else left over is an error. + */ + if ((*flags & ~(MS_RDONLY | MS_MANDLOCK | MS_SILENT)) != 0) { + printk(KERN_ERR + "sdcardfsjb: remount flags 0x%x unsupported\n", *flags); + err = -EINVAL; + } + + return err; +} + +/* + * Called by iput() when the inode reference count reached zero + * and the inode is not hashed anywhere. Used to clear anything + * that needs to be, before the inode is completely destroyed and put + * on the inode free list. + */ +static void sdcardfsjb_evict_inode(struct inode *inode) +{ + struct inode *lower_inode; + + truncate_inode_pages(&inode->i_data, 0); + end_writeback(inode); + /* + * Decrement a reference to a lower_inode, which was incremented + * by our read_inode when it was created initially. + */ + lower_inode = sdcardfsjb_lower_inode(inode); + sdcardfsjb_set_lower_inode(inode, NULL); + iput(lower_inode); +} + +static struct inode *sdcardfsjb_alloc_inode(struct super_block *sb) +{ + struct sdcardfsjb_inode_info *i; + + i = kmem_cache_alloc(sdcardfsjb_inode_cachep, GFP_KERNEL); + if (!i) + return NULL; + + /* memset everything up to the inode to 0 */ + memset(i, 0, offsetof(struct sdcardfsjb_inode_info, vfs_inode)); + + i->vfs_inode.i_version = 1; + return &i->vfs_inode; +} + +static void sdcardfsjb_destroy_inode(struct inode *inode) +{ + kmem_cache_free(sdcardfsjb_inode_cachep, SDCARDFSJB_I(inode)); +} + +/* sdcardfsjb inode cache constructor */ +static void init_once(void *obj) +{ + struct sdcardfsjb_inode_info *i = obj; + + inode_init_once(&i->vfs_inode); +} + +int sdcardfsjb_init_inode_cache(void) +{ + int err = 0; + + sdcardfsjb_inode_cachep = + kmem_cache_create("sdcardfsjb_inode_cache", + sizeof(struct sdcardfsjb_inode_info), 0, + SLAB_RECLAIM_ACCOUNT, init_once); + if (!sdcardfsjb_inode_cachep) + err = -ENOMEM; + return err; +} + +/* sdcardfsjb inode cache destructor */ +void sdcardfsjb_destroy_inode_cache(void) +{ + if (sdcardfsjb_inode_cachep) + kmem_cache_destroy(sdcardfsjb_inode_cachep); +} + +/* + * Used only in nfs, to kill any pending RPC tasks, so that subsequent + * code can actually succeed and won't leave tasks that need handling. + */ +static void sdcardfsjb_umount_begin(struct super_block *sb) +{ + struct super_block *lower_sb; + + lower_sb = sdcardfsjb_lower_super(sb); + if (lower_sb && lower_sb->s_op && lower_sb->s_op->umount_begin) + lower_sb->s_op->umount_begin(lower_sb); +} + +static int sdcardfsjb_show_options(struct seq_file *m, struct vfsmount *mnt) +{ + struct sdcardfsjb_sb_info *sbi = SDCARDFSJB_SB(mnt->mnt_sb); + struct sdcardfsjb_mount_options *opts = &sbi->options; + + if (opts->fs_low_uid != 0) + seq_printf(m, ",uid=%u", opts->fs_low_uid); + if (opts->fs_low_gid != 0) + seq_printf(m, ",gid=%u", opts->fs_low_gid); + + return 0; +}; + +const struct super_operations sdcardfsjb_sops = { + .put_super = sdcardfsjb_put_super, + .statfs = sdcardfsjb_statfs, + .remount_fs = sdcardfsjb_remount_fs, + .evict_inode = sdcardfsjb_evict_inode, + .umount_begin = sdcardfsjb_umount_begin, + .show_options = sdcardfsjb_show_options, + .alloc_inode = sdcardfsjb_alloc_inode, + .destroy_inode = sdcardfsjb_destroy_inode, + .drop_inode = generic_delete_inode, +}; diff --git a/pool/shard002/C/0059308_hdac_bus.c b/pool/shard002/C/0059308_hdac_bus.c new file mode 100644 index 0000000000000000000000000000000000000000..09ddab5f5caebebe39b4a5a8363fe7fde30a696d --- /dev/null +++ b/pool/shard002/C/0059308_hdac_bus.c @@ -0,0 +1,254 @@ +// SPDX-License-Identifier: GPL-2.0-only +/* + * HD-audio core bus driver + */ + +#include +#include +#include +#include +#include +#include +#include "local.h" +#include "trace.h" + +static void snd_hdac_bus_process_unsol_events(struct work_struct *work); + +static const struct hdac_bus_ops default_ops = { + .command = snd_hdac_bus_send_cmd, + .get_response = snd_hdac_bus_get_response, +}; + +/** + * snd_hdac_bus_init - initialize a HD-audio bas bus + * @bus: the pointer to bus object + * @dev: device pointer + * @ops: bus verb operators + * + * Returns 0 if successful, or a negative error code. + */ +int snd_hdac_bus_init(struct hdac_bus *bus, struct device *dev, + const struct hdac_bus_ops *ops) +{ + memset(bus, 0, sizeof(*bus)); + bus->dev = dev; + if (ops) + bus->ops = ops; + else + bus->ops = &default_ops; + bus->dma_type = SNDRV_DMA_TYPE_DEV; + INIT_LIST_HEAD(&bus->stream_list); + INIT_LIST_HEAD(&bus->codec_list); + INIT_WORK(&bus->unsol_work, snd_hdac_bus_process_unsol_events); + spin_lock_init(&bus->reg_lock); + mutex_init(&bus->cmd_mutex); + mutex_init(&bus->lock); + INIT_LIST_HEAD(&bus->hlink_list); + init_waitqueue_head(&bus->rirb_wq); + bus->irq = -1; + return 0; +} +EXPORT_SYMBOL_GPL(snd_hdac_bus_init); + +/** + * snd_hdac_bus_exit - clean up a HD-audio bas bus + * @bus: the pointer to bus object + */ +void snd_hdac_bus_exit(struct hdac_bus *bus) +{ + WARN_ON(!list_empty(&bus->stream_list)); + WARN_ON(!list_empty(&bus->codec_list)); + cancel_work_sync(&bus->unsol_work); +} +EXPORT_SYMBOL_GPL(snd_hdac_bus_exit); + +/** + * snd_hdac_bus_exec_verb - execute a HD-audio verb on the given bus + * @bus: bus object + * @addr: the HDAC device address + * @cmd: HD-audio encoded verb + * @res: pointer to store the response, NULL if performing asynchronously + * + * Returns 0 if successful, or a negative error code. + */ +int snd_hdac_bus_exec_verb(struct hdac_bus *bus, unsigned int addr, + unsigned int cmd, unsigned int *res) +{ + int err; + + mutex_lock(&bus->cmd_mutex); + err = snd_hdac_bus_exec_verb_unlocked(bus, addr, cmd, res); + mutex_unlock(&bus->cmd_mutex); + return err; +} + +/** + * snd_hdac_bus_exec_verb_unlocked - unlocked version + * @bus: bus object + * @addr: the HDAC device address + * @cmd: HD-audio encoded verb + * @res: pointer to store the response, NULL if performing asynchronously + * + * Returns 0 if successful, or a negative error code. + */ +int snd_hdac_bus_exec_verb_unlocked(struct hdac_bus *bus, unsigned int addr, + unsigned int cmd, unsigned int *res) +{ + unsigned int tmp; + int err; + + if (cmd == ~0) + return -EINVAL; + + if (res) + *res = -1; + else if (bus->sync_write) + res = &tmp; + for (;;) { + trace_hda_send_cmd(bus, cmd); + err = bus->ops->command(bus, cmd); + if (err != -EAGAIN) + break; + /* process pending verbs */ + err = bus->ops->get_response(bus, addr, &tmp); + if (err) + break; + } + if (!err && res) { + err = bus->ops->get_response(bus, addr, res); + trace_hda_get_response(bus, addr, *res); + } + return err; +} +EXPORT_SYMBOL_GPL(snd_hdac_bus_exec_verb_unlocked); + +/** + * snd_hdac_bus_queue_event - add an unsolicited event to queue + * @bus: the BUS + * @res: unsolicited event (lower 32bit of RIRB entry) + * @res_ex: codec addr and flags (upper 32bit or RIRB entry) + * + * Adds the given event to the queue. The events are processed in + * the workqueue asynchronously. Call this function in the interrupt + * hanlder when RIRB receives an unsolicited event. + */ +void snd_hdac_bus_queue_event(struct hdac_bus *bus, u32 res, u32 res_ex) +{ + unsigned int wp; + + if (!bus) + return; + + trace_hda_unsol_event(bus, res, res_ex); + wp = (bus->unsol_wp + 1) % HDA_UNSOL_QUEUE_SIZE; + bus->unsol_wp = wp; + + wp <<= 1; + bus->unsol_queue[wp] = res; + bus->unsol_queue[wp + 1] = res_ex; + + schedule_work(&bus->unsol_work); +} + +/* + * process queued unsolicited events + */ +static void snd_hdac_bus_process_unsol_events(struct work_struct *work) +{ + struct hdac_bus *bus = container_of(work, struct hdac_bus, unsol_work); + struct hdac_device *codec; + struct hdac_driver *drv; + unsigned int rp, caddr, res; + + spin_lock_irq(&bus->reg_lock); + while (bus->unsol_rp != bus->unsol_wp) { + rp = (bus->unsol_rp + 1) % HDA_UNSOL_QUEUE_SIZE; + bus->unsol_rp = rp; + rp <<= 1; + res = bus->unsol_queue[rp]; + caddr = bus->unsol_queue[rp + 1]; + if (!(caddr & (1 << 4))) /* no unsolicited event? */ + continue; + codec = bus->caddr_tbl[caddr & 0x0f]; + if (!codec || !codec->dev.driver) + continue; + spin_unlock_irq(&bus->reg_lock); + drv = drv_to_hdac_driver(codec->dev.driver); + if (drv->unsol_event) + drv->unsol_event(codec, res); + spin_lock_irq(&bus->reg_lock); + } + spin_unlock_irq(&bus->reg_lock); +} + +/** + * snd_hdac_bus_add_device - Add a codec to bus + * @bus: HDA core bus + * @codec: HDA core device to add + * + * Adds the given codec to the list in the bus. The caddr_tbl array + * and codec_powered bits are updated, as well. + * Returns zero if success, or a negative error code. + */ +int snd_hdac_bus_add_device(struct hdac_bus *bus, struct hdac_device *codec) +{ + if (bus->caddr_tbl[codec->addr]) { + dev_err(bus->dev, "address 0x%x is already occupied\n", + codec->addr); + return -EBUSY; + } + + list_add_tail(&codec->list, &bus->codec_list); + bus->caddr_tbl[codec->addr] = codec; + set_bit(codec->addr, &bus->codec_powered); + bus->num_codecs++; + return 0; +} + +/** + * snd_hdac_bus_remove_device - Remove a codec from bus + * @bus: HDA core bus + * @codec: HDA core device to remove + */ +void snd_hdac_bus_remove_device(struct hdac_bus *bus, + struct hdac_device *codec) +{ + WARN_ON(bus != codec->bus); + if (list_empty(&codec->list)) + return; + list_del_init(&codec->list); + bus->caddr_tbl[codec->addr] = NULL; + clear_bit(codec->addr, &bus->codec_powered); + bus->num_codecs--; + flush_work(&bus->unsol_work); +} + +#ifdef CONFIG_SND_HDA_ALIGNED_MMIO +/* Helpers for aligned read/write of mmio space, for Tegra */ +unsigned int snd_hdac_aligned_read(void __iomem *addr, unsigned int mask) +{ + void __iomem *aligned_addr = + (void __iomem *)((unsigned long)(addr) & ~0x3); + unsigned int shift = ((unsigned long)(addr) & 0x3) << 3; + unsigned int v; + + v = readl(aligned_addr); + return (v >> shift) & mask; +} +EXPORT_SYMBOL_GPL(snd_hdac_aligned_read); + +void snd_hdac_aligned_write(unsigned int val, void __iomem *addr, + unsigned int mask) +{ + void __iomem *aligned_addr = + (void __iomem *)((unsigned long)(addr) & ~0x3); + unsigned int shift = ((unsigned long)(addr) & 0x3) << 3; + unsigned int v; + + v = readl(aligned_addr); + v &= ~(mask << shift); + v |= val << shift; + writel(v, aligned_addr); +} +EXPORT_SYMBOL_GPL(snd_hdac_aligned_write); +#endif /* CONFIG_SND_HDA_ALIGNED_MMIO */ diff --git a/pool/shard002/C/0059311_fd4.c b/pool/shard002/C/0059311_fd4.c new file mode 100644 index 0000000000000000000000000000000000000000..a06e706e726ef5e5977a2a75d49bfa803d931f89 --- /dev/null +++ b/pool/shard002/C/0059311_fd4.c @@ -0,0 +1,82 @@ +#include + +/* + Copyright (C) 2012 Zhonghuan Chen, UT Austin, Tsinghua University + + 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 WA:RRANTY; 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 +*/ + + +typedef struct tag_fd4 +{ + int n1; + int n2; + double c0; + double c11; + double c21; + double c12; + double c22; +}fd4; + +void * sf_fd4_init(int n1, int n2, float d1, float d2) +/*< initialize >*/ +{ + double t; + fd4 *p; + + p = (fd4*) malloc(sizeof(fd4)); + if(p==NULL) return NULL; + + t = d1; + t = 1.0/(t*t); + p->c11 = 4.0*t/3.0; + p->c12= -t/12.0; + + t = d2; + t = 1.0/(t*t); + p->c21 = 4.0*t/3.0; + p->c22= -t/12.0; + + p->c0 = -2.0 * (p->c11 + p->c12 + p->c21 + p->c22); + p->n1=n1; + p->n2=n2; + return (void *)p; +} + +void sf_fd4_laplacian(void * h, float **uin, float **uout) +/*< Laplacian operator, 4th-order finite-difference >*/ +{ + int i1, i2; + fd4 *p; + p = (fd4*)h; + for (i2=2; i2 < p->n2-2; i2++) + { + for (i1=2; i1 < p->n1-2; i1++) + { + uout[i2][i1] = + p->c11*(uin[i2][i1-1]+uin[i2][i1+1]) + + p->c12*(uin[i2][i1-2]+uin[i2][i1+2]) + + p->c21*(uin[i2-1][i1]+uin[i2+1][i1]) + + p->c22*(uin[i2-2][i1]+uin[i2+2][i1]) + + p->c0*uin[i2][i1]; + } + } +} + +void sf_fd4_close(void * h) +/*< release memory >*/ +{ + free(h); +} diff --git a/pool/shard002/C/0059314_tap-sctpchunkstat.c b/pool/shard002/C/0059314_tap-sctpchunkstat.c new file mode 100644 index 0000000000000000000000000000000000000000..2adaa42c54fb67ecf28c41548b49cc7a44b85d78 --- /dev/null +++ b/pool/shard002/C/0059314_tap-sctpchunkstat.c @@ -0,0 +1,271 @@ +/* tap_sctpchunkstat.c + * SCTP chunk counter for wireshark + * Copyright 2005 Oleg Terletsky + * + * Wireshark - Network traffic analyzer + * By Gerald Combs + * Copyright 1998 Gerald Combs + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +#include "config.h" + +#include +#include +#include + +#include "epan/packet_info.h" +#include "epan/addr_resolv.h" +#include +#include +#include "epan/value_string.h" +#include +#include + +void register_tap_listener_sctpstat(void); + +typedef struct sctp_ep { + struct sctp_ep *next; + address src; + address dst; + guint16 sport; + guint16 dport; + guint32 chunk_count[256]; +} sctp_ep_t; + + +/* used to keep track of the statistics for an entire program interface */ +typedef struct _sctpstat_t { + char *filter; + guint32 number_of_packets; + sctp_ep_t *ep_list; +} sctpstat_t; + + +#define SCTP_DATA_CHUNK_ID 0 +#define SCTP_INIT_CHUNK_ID 1 +#define SCTP_INIT_ACK_CHUNK_ID 2 +#define SCTP_SACK_CHUNK_ID 3 +#define SCTP_HEARTBEAT_CHUNK_ID 4 +#define SCTP_HEARTBEAT_ACK_CHUNK_ID 5 +#define SCTP_ABORT_CHUNK_ID 6 +#define SCTP_SHUTDOWN_CHUNK_ID 7 +#define SCTP_SHUTDOWN_ACK_CHUNK_ID 8 +#define SCTP_ERROR_CHUNK_ID 9 +#define SCTP_COOKIE_ECHO_CHUNK_ID 10 +#define SCTP_COOKIE_ACK_CHUNK_ID 11 +#define SCTP_ECNE_CHUNK_ID 12 +#define SCTP_CWR_CHUNK_ID 13 +#define SCTP_SHUTDOWN_COMPLETE_CHUNK_ID 14 +#define SCTP_AUTH_CHUNK_ID 0x16 +#define SCTP_ASCONF_ACK_CHUNK_ID 0x80 +#define SCTP_PKTDROP_CHUNK_ID 0x81 +#define SCTP_FORWARD_TSN_CHUNK_ID 0xC0 +#define SCTP_ASCONF_CHUNK_ID 0xC1 +#define SCTP_IETF_EXT 0xFF + +#define CHUNK_TYPE_OFFSET 0 +#define CHUNK_TYPE(x)(tvb_get_guint8((x), CHUNK_TYPE_OFFSET)) + +static void +sctpstat_reset(void *phs) +{ + sctpstat_t *sctp_stat = (sctpstat_t *)phs; + sctp_ep_t *list = (sctp_ep_t *)sctp_stat->ep_list; + sctp_ep_t *tmp = NULL; + guint16 chunk_type; + + if (!list) + return; + + for (tmp = list; tmp; tmp = tmp->next) + for (chunk_type = 0; chunk_type < 256; chunk_type++) + tmp->chunk_count[chunk_type] = 0; + + sctp_stat->number_of_packets = 0; +} + + +static sctp_ep_t * +alloc_sctp_ep(const struct _sctp_info *si) +{ + sctp_ep_t *ep; + guint16 chunk_type; + + if (!si) + return NULL; + + if (!(ep = g_new(sctp_ep_t, 1))) + return NULL; + + COPY_ADDRESS(&ep->src, &si->ip_src); + COPY_ADDRESS(&ep->dst, &si->ip_dst); + ep->sport = si->sport; + ep->dport = si->dport; + ep->next = NULL; + for (chunk_type = 0; chunk_type < 256; chunk_type++) + ep->chunk_count[chunk_type] = 0; + return ep; +} + + + + +static int +sctpstat_packet(void *phs, packet_info *pinfo _U_, epan_dissect_t *edt _U_, const void *phi) +{ + + sctpstat_t *hs = (sctpstat_t *)phs; + sctp_ep_t *tmp = NULL, *te = NULL; + const struct _sctp_info *si = (const struct _sctp_info *)phi; + guint32 tvb_number; + guint8 chunk_type; + + if (!hs) + return (0); + + hs->number_of_packets++; + + if (!hs->ep_list) { + hs->ep_list = alloc_sctp_ep(si); + te = hs->ep_list; + } else { + for (tmp = hs->ep_list; tmp; tmp = tmp->next) + { + if ((!CMP_ADDRESS(&tmp->src, &si->ip_src)) && + (!CMP_ADDRESS(&tmp->dst, &si->ip_dst)) && + (tmp->sport == si->sport) && + (tmp->dport == si->dport)) + { + te = tmp; + break; + } + } + if (!te) { + if ((te = alloc_sctp_ep(si))) { + te->next = hs->ep_list; + hs->ep_list = te; + } + } + } + + if (!te) + return (0); + + + if (si->number_of_tvbs > 0) { + chunk_type = CHUNK_TYPE(si->tvb[0]); + if ((chunk_type == SCTP_INIT_CHUNK_ID) || + (chunk_type == SCTP_INIT_ACK_CHUNK_ID)) { + te->chunk_count[chunk_type]++; + } else { + for (tvb_number = 0; tvb_number < si->number_of_tvbs; tvb_number++) + te->chunk_count[CHUNK_TYPE(si->tvb[tvb_number])]++; + } + } + return (1); +} + + +static void +sctpstat_draw(void *phs) +{ + sctpstat_t *hs = (sctpstat_t *)phs; + sctp_ep_t *list = hs->ep_list, *tmp; + + printf("-------------------------------------------- SCTP Statistics --------------------------------------------------------------------------\n"); + printf("| Total packets RX/TX %u\n", hs->number_of_packets); + printf("---------------------------------------------------------------------------------------------------------------------------------------\n"); + printf("| Source IP |PortA| Dest. IP |PortB| DATA | SACK | HBEAT |HBEATACK| INIT | INITACK| COOKIE |COOKIACK| ABORT | ERROR |\n"); + printf("---------------------------------------------------------------------------------------------------------------------------------------\n"); + + for (tmp = list; tmp; tmp = tmp->next) { + printf("|%15s|%5u|%15s|%5u|%8u|%8u|%8u|%8u|%8u|%8u|%8u|%8u|%8u|%8u|\n", + ep_address_to_str(&tmp->src), tmp->sport, + ep_address_to_str(&tmp->dst), tmp->dport, + tmp->chunk_count[SCTP_DATA_CHUNK_ID], + tmp->chunk_count[SCTP_SACK_CHUNK_ID], + tmp->chunk_count[SCTP_HEARTBEAT_CHUNK_ID], + tmp->chunk_count[SCTP_HEARTBEAT_ACK_CHUNK_ID], + tmp->chunk_count[SCTP_INIT_CHUNK_ID], + tmp->chunk_count[SCTP_INIT_ACK_CHUNK_ID], + tmp->chunk_count[SCTP_COOKIE_ECHO_CHUNK_ID], + tmp->chunk_count[SCTP_COOKIE_ACK_CHUNK_ID], + tmp->chunk_count[SCTP_ABORT_CHUNK_ID], + tmp->chunk_count[SCTP_ERROR_CHUNK_ID]); + } + printf("---------------------------------------------------------------------------------------------------------------------------------------\n"); +} + + +static void +sctpstat_init(const char *opt_arg, void *userdata _U_) +{ + sctpstat_t *hs; + GString *error_string; + + hs = (sctpstat_t *)g_malloc(sizeof(sctpstat_t)); + if (!strncmp(opt_arg, "sctp,stat,", 11)) { + hs->filter = g_strdup(opt_arg+11); + } else { + hs->filter = NULL; + } + hs->ep_list = NULL; + hs->number_of_packets = 0; + + sctpstat_reset(hs); + + error_string = register_tap_listener("sctp", hs, hs->filter, 0, NULL, sctpstat_packet, sctpstat_draw); + if (error_string) { + /* error, we failed to attach to the tap. clean up */ + g_free(hs->filter); + g_free(hs); + + fprintf(stderr, "tshark: Couldn't register sctp,stat tap: %s\n", + error_string->str); + g_string_free(error_string, TRUE); + exit(1); + } +} + +static stat_tap_ui sctpstat_ui = { + REGISTER_STAT_GROUP_GENERIC, + NULL, + "sctp,stat", + sctpstat_init, + -1, + 0, + NULL +}; + +void +register_tap_listener_sctpstat(void) +{ + register_stat_tap_ui(&sctpstat_ui, NULL); +} + +/* + * Editor modelines - http://www.wireshark.org/tools/modelines.html + * + * Local variables: + * c-basic-offset: 8 + * tab-width: 8 + * indent-tabs-mode: t + * End: + * + * vi: set shiftwidth=8 tabstop=8 noexpandtab: + * :indentSize=8:tabSize=8:noTabs=false: + */ diff --git a/pool/shard002/C/0059320_01_domashno.c b/pool/shard002/C/0059320_01_domashno.c new file mode 100644 index 0000000000000000000000000000000000000000..300dfda40e05318a779ccdee81f23b06410829bb --- /dev/null +++ b/pool/shard002/C/0059320_01_domashno.c @@ -0,0 +1,13 @@ +#include +int main(){ +int n,m,i=0,s; +float a; +scanf("%d",&n); +for(s=0;i + +#include "defines.h" +#include "state_construct.h" +#include "cb_construct.h" +#include "index_conv_dec.h" +#include "do_plc.h" +#include "constants.h" +#include "enhancer_interface.h" +#include "xcorr_coef.h" +#include "lsf_check.h" + +/*----------------------------------------------------------------* + * frame residual decoder function (subrutine to iLBC_decode) + *---------------------------------------------------------------*/ + +bool WebRtcIlbcfix_DecodeResidual( + IlbcDecoder *iLBCdec_inst, + /* (i/o) the decoder state structure */ + iLBC_bits *iLBC_encbits, /* (i/o) Encoded bits, which are used + for the decoding */ + int16_t *decresidual, /* (o) decoded residual frame */ + int16_t *syntdenum /* (i) the decoded synthesis filter + coefficients */ + ) { + size_t meml_gotten, diff, start_pos; + size_t subcount, subframe; + int16_t *reverseDecresidual = iLBCdec_inst->enh_buf; /* Reversed decoded data, used for decoding backwards in time (reuse memory in state) */ + int16_t *memVec = iLBCdec_inst->prevResidual; /* Memory for codebook and filter state (reuse memory in state) */ + int16_t *mem = &memVec[CB_HALFFILTERLEN]; /* Memory for codebook */ + + diff = STATE_LEN - iLBCdec_inst->state_short_len; + + if (iLBC_encbits->state_first == 1) { + start_pos = (iLBC_encbits->startIdx-1)*SUBL; + } else { + start_pos = (iLBC_encbits->startIdx-1)*SUBL + diff; + } + + /* decode scalar part of start state */ + + WebRtcIlbcfix_StateConstruct(iLBC_encbits->idxForMax, + iLBC_encbits->idxVec, &syntdenum[(iLBC_encbits->startIdx-1)*(LPC_FILTERORDER+1)], + &decresidual[start_pos], iLBCdec_inst->state_short_len + ); + + if (iLBC_encbits->state_first) { /* put adaptive part in the end */ + + /* setup memory */ + + WebRtcSpl_MemSetW16(mem, 0, CB_MEML - iLBCdec_inst->state_short_len); + WEBRTC_SPL_MEMCPY_W16(mem+CB_MEML-iLBCdec_inst->state_short_len, decresidual+start_pos, + iLBCdec_inst->state_short_len); + + /* construct decoded vector */ + + if (!WebRtcIlbcfix_CbConstruct( + &decresidual[start_pos + iLBCdec_inst->state_short_len], + iLBC_encbits->cb_index, iLBC_encbits->gain_index, + mem + CB_MEML - ST_MEM_L_TBL, ST_MEM_L_TBL, diff)) + return false; // Error. + + } + else {/* put adaptive part in the beginning */ + + /* setup memory */ + + meml_gotten = iLBCdec_inst->state_short_len; + WebRtcSpl_MemCpyReversedOrder(mem+CB_MEML-1, + decresidual+start_pos, meml_gotten); + WebRtcSpl_MemSetW16(mem, 0, CB_MEML - meml_gotten); + + /* construct decoded vector */ + + if (!WebRtcIlbcfix_CbConstruct(reverseDecresidual, iLBC_encbits->cb_index, + iLBC_encbits->gain_index, + mem + CB_MEML - ST_MEM_L_TBL, ST_MEM_L_TBL, + diff)) + return false; // Error. + + /* get decoded residual from reversed vector */ + + WebRtcSpl_MemCpyReversedOrder(&decresidual[start_pos-1], + reverseDecresidual, diff); + } + + /* counter for predicted subframes */ + + subcount=1; + + /* forward prediction of subframes */ + + if (iLBCdec_inst->nsub > iLBC_encbits->startIdx + 1) { + + /* setup memory */ + WebRtcSpl_MemSetW16(mem, 0, CB_MEML-STATE_LEN); + WEBRTC_SPL_MEMCPY_W16(mem+CB_MEML-STATE_LEN, + decresidual+(iLBC_encbits->startIdx-1)*SUBL, STATE_LEN); + + /* loop over subframes to encode */ + + size_t Nfor = iLBCdec_inst->nsub - iLBC_encbits->startIdx - 1; + for (subframe=0; subframestartIdx + 1 + subframe) * SUBL], + iLBC_encbits->cb_index + subcount * CB_NSTAGES, + iLBC_encbits->gain_index + subcount * CB_NSTAGES, mem, MEM_LF_TBL, + SUBL)) + return false; // Error; + + /* update memory */ + memmove(mem, mem + SUBL, (CB_MEML - SUBL) * sizeof(*mem)); + WEBRTC_SPL_MEMCPY_W16(mem+CB_MEML-SUBL, + &decresidual[(iLBC_encbits->startIdx+1+subframe)*SUBL], SUBL); + + subcount++; + } + + } + + /* backward prediction of subframes */ + + if (iLBC_encbits->startIdx > 1) { + + /* setup memory */ + + meml_gotten = SUBL*(iLBCdec_inst->nsub+1-iLBC_encbits->startIdx); + if( meml_gotten > CB_MEML ) { + meml_gotten=CB_MEML; + } + + WebRtcSpl_MemCpyReversedOrder(mem+CB_MEML-1, + decresidual+(iLBC_encbits->startIdx-1)*SUBL, meml_gotten); + WebRtcSpl_MemSetW16(mem, 0, CB_MEML - meml_gotten); + + /* loop over subframes to decode */ + + size_t Nback = iLBC_encbits->startIdx - 1; + for (subframe=0; subframecb_index + subcount * CB_NSTAGES, + iLBC_encbits->gain_index + subcount * CB_NSTAGES, mem, MEM_LF_TBL, + SUBL)) + return false; // Error. + + /* update memory */ + memmove(mem, mem + SUBL, (CB_MEML - SUBL) * sizeof(*mem)); + WEBRTC_SPL_MEMCPY_W16(mem+CB_MEML-SUBL, + &reverseDecresidual[subframe*SUBL], SUBL); + + subcount++; + } + + /* get decoded residual from reversed vector */ + WebRtcSpl_MemCpyReversedOrder(decresidual+SUBL*Nback-1, + reverseDecresidual, SUBL*Nback); + } + + return true; // Success. +} diff --git a/pool/shard002/C/0059325_nict.c b/pool/shard002/C/0059325_nict.c new file mode 100644 index 0000000000000000000000000000000000000000..e133d6338e4f7d51a2821be98c117d47bdcb5bbf --- /dev/null +++ b/pool/shard002/C/0059325_nict.c @@ -0,0 +1,199 @@ +/* + The oSIP library implements the Session Initiation Protocol (SIP -rfc3261-) + Copyright (C) 2001,2002,2003 Aymeric MOIZARD jack@atosc.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 "fsm.h" +#include "xixt.h" + +int +__osip_nict_init (osip_nict_t ** nict, osip_t * osip, osip_message_t * request) +{ + osip_route_t *route; + int i; + time_t now; + + OSIP_TRACE (osip_trace + (__FILE__, __LINE__, OSIP_INFO2, NULL, "allocating NICT context\n")); + + *nict = (osip_nict_t *) osip_malloc (sizeof (osip_nict_t)); + if (*nict == NULL) + return -1; + now = time (NULL); + memset (*nict, 0, sizeof (osip_nict_t)); + /* for REQUEST retransmissions */ + { + osip_via_t *via; + char *proto; + + i = osip_message_get_via (request, 0, &via); /* get top via */ + if (i != 0) + goto ii_error_1; + proto = via_get_protocol (via); + if (proto == NULL) + goto ii_error_1; + + if (osip_strcasecmp (proto, "TCP") != 0 + && osip_strcasecmp (proto, "TLS") != 0 + && osip_strcasecmp (proto, "SCTP") != 0) + { + (*nict)->timer_e_length = DEFAULT_T1; + (*nict)->timer_k_length = DEFAULT_T4; + (*nict)->timer_e_start.tv_sec = -1; + (*nict)->timer_k_start.tv_sec = -1; /* not started */ + } else + { /* reliable protocol is used: */ + (*nict)->timer_e_length = -1; /* E is not ACTIVE */ + (*nict)->timer_k_length = 0; /* MUST do the transition immediatly */ + (*nict)->timer_e_start.tv_sec = -1; + (*nict)->timer_k_start.tv_sec = -1; /* not started */ + } + } + + /* for PROXY, the destination MUST be set by the application layer, + this one may not be correct. */ + osip_message_get_route (request, 0, &route); + if (route != NULL && route->url != NULL) + { + osip_uri_param_t *lr_param; + + osip_uri_uparam_get_byname (route->url, "lr", &lr_param); + if (lr_param == NULL) + { + /* using uncompliant proxy: destination is the request-uri */ + route = NULL; + } + } + + if (route != NULL) + { + int port = 5060; + + if (route->url->port != NULL) + port = osip_atoi (route->url->port); + osip_nict_set_destination ((*nict), osip_strdup (route->url->host), port); + } else + { + int port = 5060; + + if (request->req_uri->port != NULL) + port = osip_atoi (request->req_uri->port); + osip_nict_set_destination ((*nict), + osip_strdup (request->req_uri->host), port); + } + + (*nict)->timer_f_length = 64 * DEFAULT_T1; + osip_gettimeofday (&(*nict)->timer_f_start, NULL); + add_gettimeofday (&(*nict)->timer_f_start, (*nict)->timer_f_length); + + /* Oups! a Bug! */ + /* (*nict)->port = 5060; */ + + return 0; + +ii_error_1: + osip_free (*nict); + return -1; +} + +int +__osip_nict_free (osip_nict_t * nict) +{ + if (nict == NULL) + return -1; + OSIP_TRACE (osip_trace + (__FILE__, __LINE__, OSIP_INFO2, NULL, "free nict ressource\n")); + + osip_free (nict->destination); + osip_free (nict); + return 0; +} + +int +osip_nict_set_destination (osip_nict_t * nict, char *destination, int port) +{ + if (nict == NULL) + return -1; + if (nict->destination != NULL) + osip_free (nict->destination); + nict->destination = destination; + nict->port = port; + return 0; +} + +osip_event_t * +__osip_nict_need_timer_e_event (osip_nict_t * nict, state_t state, + int transactionid) +{ + struct timeval now; + + osip_gettimeofday (&now, NULL); + + if (nict == NULL) + return NULL; + if (state == NICT_PROCEEDING || state == NICT_TRYING) + { + if (nict->timer_e_start.tv_sec == -1) + return NULL; + if (osip_timercmp (&now, &nict->timer_e_start, >)) + return __osip_event_new (TIMEOUT_E, transactionid); + } + return NULL; +} + +osip_event_t * +__osip_nict_need_timer_f_event (osip_nict_t * nict, state_t state, + int transactionid) +{ + struct timeval now; + + osip_gettimeofday (&now, NULL); + + if (nict == NULL) + return NULL; + if (state == NICT_PROCEEDING || state == NICT_TRYING) + { + if (nict->timer_f_start.tv_sec == -1) + return NULL; + if (osip_timercmp (&now, &nict->timer_f_start, >)) + return __osip_event_new (TIMEOUT_F, transactionid); + } + return NULL; +} + +osip_event_t * +__osip_nict_need_timer_k_event (osip_nict_t * nict, state_t state, + int transactionid) +{ + struct timeval now; + + osip_gettimeofday (&now, NULL); + + if (nict == NULL) + return NULL; + if (state == NICT_COMPLETED) + { + if (nict->timer_k_start.tv_sec == -1) + return NULL; + if (osip_timercmp (&now, &nict->timer_k_start, >)) + return __osip_event_new (TIMEOUT_K, transactionid); + } + return NULL; +} diff --git a/pool/shard002/C/0059331_16-1.c b/pool/shard002/C/0059331_16-1.c new file mode 100644 index 0000000000000000000000000000000000000000..d8dc4edae7bdaccb49c4884f777e7e1ff8465a87 --- /dev/null +++ b/pool/shard002/C/0059331_16-1.c @@ -0,0 +1,173 @@ +/* + * Copyright (c) 2004, Intel Corporation. All rights reserved. + * 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. + * adam.li@intel.com - 2004-04-29 + */ + +/* + * Test that if the message queue is full and O_NONBLOCK is not set, + * mq_timedsend() will block until abs_timeout is reached. + * + * Test by sending messages in a child process until the message queue is full. + * At this point, the child should be blocking on sending. Then, have the + * parent wait for the timeout and return pass when the next message is sent + * to the message queue. + * + * If Timers is supported, then abs_timeout is based on CLOCK_REALTIME. + * Otherwise, the timeout is based on the system clock (time() function). + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "posixtest.h" + +#define NAMESIZE 50 +#define MSGSTR "0123456789" +#define BUFFER 40 +#define MAXMSG 5 + +#define TIMEOUT 7 + +#define CHILDPASS 1 +#define CHILDFAIL 0 + +char gqname[NAMESIZE]; +mqd_t gqueue; + +/* + * This handler is just used to catch the signal and stop sleep (so the + * parent knows the child is still busy sending signals). + */ +void stopsleep_handler(int signo) +{ + return; +} + +int main() +{ + int pid; + struct mq_attr attr; + const char *msgptr = MSGSTR; + + sprintf(gqname, "/mq_timedsend_16-1_%d", getpid()); + + attr.mq_maxmsg = MAXMSG; + attr.mq_msgsize = BUFFER; + gqueue = mq_open(gqname, O_CREAT | O_RDWR, S_IRUSR | S_IWUSR, &attr); + mq_unlink(gqname); + if (gqueue == (mqd_t) - 1) { + perror("mq_open() did not return success"); + return PTS_UNRESOLVED; + } + + if ((pid = fork()) == 0) { + /* child here */ + int i, sig; + struct timespec ts; + sigset_t mask; + + /* wait for parent to set up handler */ + sigemptyset(&mask); + sigaddset(&mask, SIGUSR1); + sigprocmask(SIG_BLOCK, &mask, NULL); + sigwait(&mask, &sig); + + /* child should block in < TIMEOUT seconds */ +#ifdef _POSIX_TIMERS + printf("Using CLOCK_REALTIME\n"); + clock_gettime(CLOCK_REALTIME, &ts); + ts.tv_sec += TIMEOUT; +#else + ts.tv_sec = time(NULL) + TIMEOUT; +#endif + ts.tv_nsec = 0; + + for (i = 0; i < MAXMSG + 1; i++) { + if (mq_timedsend(gqueue, msgptr, + strlen(msgptr), 1, &ts) != 0) { + /* send will fail after timeout occurs */ + kill(getppid(), SIGABRT); + return CHILDPASS; + } + /* send signal to parent each time message is sent */ + kill(getppid(), SIGABRT); + } + printf("Child never interrupted\n"); + return CHILDFAIL; + } else { + /* parent here */ + struct sigaction act; + int j; + + /* parent runs stopsleep_handler when sleep is interrupted + by child */ + act.sa_handler = stopsleep_handler; + act.sa_flags = 0; + sigemptyset(&act.sa_mask); + sigaction(SIGABRT, &act, 0); + + /* wait 1 second and tell child handler is set up */ + struct timespec ts; + ts.tv_sec = 1; + ts.tv_nsec = 0; + nanosleep(&ts, NULL); + kill(pid, SIGUSR1); + + /* wait for heartbeats from child */ + for (j = 0; j < MAXMSG + 1; j++) { + ts.tv_sec = 3; + ts.tv_nsec = 0; + if (nanosleep(&ts, NULL) + == 0) { + /* If sleep finished, child is probably blocking */ + break; + } + } + + if (j == MAXMSG + 1) { + printf("Child never blocked\n"); + printf("Test FAILED\n"); + kill(pid, SIGKILL); //kill child + mq_close(gqueue); + mq_unlink(gqname); + return PTS_FAIL; + } + + /* + * Wait for timeout to complete. + */ + ts.tv_sec = TIMEOUT; + ts.tv_nsec = 0; + if (nanosleep(&ts, NULL) == 0) { + /* + * If sleep lasted the full time, child never timed out + */ + printf("Child never timed out\n"); + kill(pid, SIGKILL); //kill child + mq_close(gqueue); + mq_unlink(gqname); + printf("Test FAILED\n"); + return PTS_FAIL; + } + + mq_close(gqueue); + mq_unlink(gqname); + printf("Test PASSED\n"); + return PTS_PASS; + } + + return PTS_UNRESOLVED; +} diff --git a/pool/shard002/C/0059336_decutf8sub.c b/pool/shard002/C/0059336_decutf8sub.c new file mode 100644 index 0000000000000000000000000000000000000000..82209241b4bf4e84fa2960bb17009d9131587c8b --- /dev/null +++ b/pool/shard002/C/0059336_decutf8sub.c @@ -0,0 +1,84 @@ +/* decutf8sub.c + + Copyright (c) 2003-2015 HandBrake Team + This file is part of the HandBrake source code + Homepage: . + It may be used under the terms of the GNU General Public License v2. + For full terms see the file COPYING file or visit http://www.gnu.org/licenses/gpl-2.0.html + */ + +/* + * Decoder for UTF-8 subtitles obtained from file input-sources. + * + * Input and output packet format is UTF-8 encoded text, + * with limited HTML-style markup (only , , and ). + * + * @author David Foster (davidfstr) + */ + +#include +#include +#include "hb.h" +#include "decsrtsub.h" + +struct hb_work_private_s +{ + int line; // SSA line number +}; + +static int decutf8Init(hb_work_object_t *w, hb_job_t *job) +{ + hb_work_private_t * pv; + pv = calloc( 1, sizeof( hb_work_private_t ) ); + if (pv == NULL) + return 1; + w->private_data = pv; + + // Generate generic SSA Script Info. + int height = job->title->geometry.height - job->crop[0] - job->crop[1]; + int width = job->title->geometry.width - job->crop[2] - job->crop[3]; + hb_subtitle_add_ssa_header(w->subtitle, "Arial", .066 * height, + width, height); + + return 0; +} + +static int decutf8Work(hb_work_object_t * w, + hb_buffer_t **buf_in, hb_buffer_t **buf_out) +{ + hb_work_private_t * pv = w->private_data; + // Pass the packets through without modification + hb_buffer_t *out = *buf_in; + + out->s.frametype = HB_FRAME_SUBTITLE; + + // Warn if the subtitle's duration has not been passed through by the + // demuxer, which will prevent the subtitle from displaying at all + if (out->s.stop == 0) + { + hb_log("decutf8sub: subtitle packet lacks duration"); + } + + hb_srt_to_ssa(out, ++pv->line); + + *buf_in = NULL; + *buf_out = out; + + if (out->size == 0) + return HB_WORK_DONE; + return HB_WORK_OK; +} + +static void decutf8Close(hb_work_object_t *w) +{ + free(w->private_data); +} + +hb_work_object_t hb_decutf8sub = +{ + WORK_DECUTF8SUB, + "UTF-8 Subtitle Decoder", + decutf8Init, + decutf8Work, + decutf8Close +}; diff --git a/pool/shard002/C/0059343_lib_icmpv4.c b/pool/shard002/C/0059343_lib_icmpv4.c new file mode 100644 index 0000000000000000000000000000000000000000..114d6f8ac9fd6c3f18455c3b80593984ae32816f --- /dev/null +++ b/pool/shard002/C/0059343_lib_icmpv4.c @@ -0,0 +1,141 @@ +//=========================================================================== +// lib_icmpv4.c +// Copyright (C) 2016 Free Software Foundation, Inc. +// Originally by ZhaoFeng Liang +// +//This file is part of DTHAS. +// +//DTHAS 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. +// +//DTHAS 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 DTHAS; If not, see . +//=========================================================================== + +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +#include "module_global.h" +#include "module_type.h" +#include "module_ip_port.h" +#include "module_prototype.h" +#include "module_ipv4.h" +#include "module_icmpv4.h" + +/* +struct icmphdr { + __u8 type; + __u8 code; + __sum16 checksum; + union { + struct { + __be16 id; + __be16 sequence; + } echo; + __be32 gateway; + struct { + __be16 __unused; + __be16 mtu; + } frag; + } un; +}; +*/ + +//================================================================= +// 初始化 icmpv4_trans_info +//================================================================= +int icmpv4_trans_info(struct sk_buff *skb) +{ + printk("======================icmpv4 trans info======================\n"); + + //---------------------------------------------------------------------- + //获取icmpv4信息 + //---------------------------------------------------------------------- + struct icmphdr *icmpv4 = icmp_hdr(skb); + + unsigned char type; + unsigned char code; + + type = icmpv4->type; + code = icmpv4->code; + + printk("type: %d , code: %d\n",type, code); + + return NF_ACCEPT; +} + +//================================================================= +// 通过ip地址、端口过滤icmpv4数据包 +//================================================================= +int icmpv4_modi_main(struct sk_buff *skb) +{ + unsigned char type; + unsigned char code; + + type = 12; + //code = 12 + + //修改 type + icmpv4_modi(ICMPV4_TYPE_MODI, type, skb); + + //修改 code + //icmpv4_modi(ICMPV4_CODE_MODI, code, skb); + + icmpv4_prt_info(skb); + + return NF_ACCEPT; + +} + +//================================================================= +// 通过ip地址、端口过滤icmpv4数据包 +//================================================================= +int icmpv4_modi(int type, unsigned char val, struct sk_buff *skb) +{ + struct icmphdr *icmpv4 = icmp_hdr(skb); + + switch(type) + { + case ICMPV4_TYPE_MODI: + icmpv4->type = val; + break; + case ICMPV4_CODE_MODI: + icmpv4->code = val; + break; + default: + return 0; + break; + } + + return 1; +} + +//================================================================= +// 打印icmpv4的信息 +//================================================================= +int icmpv4_prt_info(struct sk_buff *skb) +{ + printk("======================icmpv4 info======================\n"); + + //---------------------------------------------------------------------- + //获取icmpv4信息 + //---------------------------------------------------------------------- + struct icmphdr *icmpv4 = icmp_hdr(skb); + + printk("type: %d , code: %d\n",icmpv4->type, icmpv4->code); +} diff --git a/pool/shard002/C/0059348_delete_deo_preference.c b/pool/shard002/C/0059348_delete_deo_preference.c new file mode 100644 index 0000000000000000000000000000000000000000..07bd52ff4e58b437dce7a15ad06f024a2ddebf15 --- /dev/null +++ b/pool/shard002/C/0059348_delete_deo_preference.c @@ -0,0 +1,71 @@ +/* This file is (C) copyright 2001 Software Improvements, Pty 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., 675 Mass Ave, Cambridge, MA 02139, USA. */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "move_deo_cursor.h" +#include "delete_deo_preference.h" + +/* DDS3.20: Delete Preference */ +static void delete_preference(unsigned int group_index, unsigned int dbci) +{ + const struct preference_set *vip; + unsigned int i; + + vip = get_vote_in_progress(); + for (i=0; i < vip->num_preferences; i++) { + if ((vip->candidates[i].group_index == group_index) + && (vip->candidates[i].db_candidate_index == dbci)) { +/* shift preferences back one and delete empty pref */ + remove_pref(i); + } + + } +} + + + +/* DDS3.20: Delete DEO Preference */ +void delete_deo_preference(void) +{ + struct cursor cursor; + unsigned int group_index, dbci; + int candidate_index; + struct ballot_contents *ballot; + const struct rotation *rotation; + + cursor = get_cursor_position(); + group_index = cursor.group_index; + candidate_index = cursor.screen_candidate_index; + + if (candidate_index > -1) { + ballot = get_ballot_contents(); + rotation = get_current_rotation(); + /* SIPL 2011-06-28 Use updated translate function. */ + dbci = translate_group_sci_to_dbci + (cursor.group_index, + candidate_index, rotation); + delete_preference(group_index, dbci); + draw_group_entry(cursor, YES, NO); + } +} diff --git a/pool/shard002/C/0059361_PolyTimeTest.c b/pool/shard002/C/0059361_PolyTimeTest.c new file mode 100644 index 0000000000000000000000000000000000000000..8a51e79790bdfdc0a4088c23d0782a4b34622e60 --- /dev/null +++ b/pool/shard002/C/0059361_PolyTimeTest.c @@ -0,0 +1,177 @@ + +#include + +#include + +NTL_CLIENT + + +double clean_data(double *t) +{ + double x, y, z; + long i, ix, iy, n; + + x = t[0]; ix = 0; + y = t[0]; iy = 0; + + for (i = 1; i < 5; i++) { + if (t[i] < x) { + x = t[i]; + ix = i; + } + if (t[i] > y) { + y = t[i]; + iy = i; + } + } + + z = 0; n = 0; + for (i = 0; i < 5; i++) { + if (i != ix && i != iy) z+= t[i], n++; + } + + z = z/n; + + return z; +} + +void print_flag() +{ + + +#if (defined(NTL_TBL_REM)) +printf("TBL_REM "); +#elif (defined(NTL_TBL_REM_LL)) +printf("TBL_REM_LL "); +#else +printf("DEFAULT "); +#endif + + +printf("\n"); + +} + + +int main() +{ + +#if (defined(NTL_TBL_REM) && defined(NTL_GMP_LIP)) + + if (sizeof(NTL_ULL_TYPE) != 2*sizeof(long) || + NTL_ZZ_NBITS != NTL_BITS_PER_LONG || + (1L << (NTL_ZZ_NBITS-NTL_SP_NBITS)) < 800) { + printf("999999999999999 "); + print_flag(); + return 0; + } + + +#endif + + long n, k; + + n = 200; + k = 10*NTL_ZZ_NBITS; + + ZZ p; + + RandomLen(p, k); + + + ZZ_p::init(p); // initialization + + ZZ_pX f, g, h, r1, r2, r3; + + random(g, n); // g = random polynomial of degree < n + random(h, n); // h = " " + random(f, n); // f = " " + + SetCoeff(f, n); // Sets coefficient of X^n to 1 + + // For doing arithmetic mod f quickly, one must pre-compute + // some information. + + ZZ_pXModulus F; + build(F, f); + + PlainMul(r1, g, h); // this uses classical arithmetic + PlainRem(r1, r1, f); + + MulMod(r2, g, h, F); // this uses the FFT + + MulMod(r3, g, h, f); // uses FFT, but slower + + // compare the results... + + if (r1 != r2) { + printf("999999999999999 "); + print_flag(); + return 0; + } + else if (r1 != r3) { + printf("999999999999999 "); + print_flag(); + return 0; + } + + double t; + long i; + long iter; + + n = 1024; + k = 1024; + RandomLen(p, k); + + ZZ_p::init(p); + + ZZ_pX j1, j2, j3; + + random(j1, n); + random(j2, n); + + mul(j3, j1, j2); + + iter = 1; + + do { + t = GetTime(); + for (i = 0; i < iter; i++) { + FFTMul(j3, j1, j2); + } + t = GetTime() - t; + iter = 2*iter; + } while(t < 1); + + iter = iter/2; + + iter = long((2/t)*iter) + 1; + + double tvec[5]; + long w; + + for (w = 0; w < 5; w++) { + t = GetTime(); + for (i = 0; i < iter; i++) { + FFTMul(j3, j1, j2); + } + t = GetTime() - t; + tvec[w] = t; + } + + + t = clean_data(tvec); + + t = floor((t/iter)*1e12); + + if (t < 0 || t >= 1e15) + printf("999999999999999 "); + else + printf("%015.0f ", t); + + printf(" [%ld] ", iter); + + print_flag(); + + return 0; +} diff --git a/pool/shard002/C/0059362_logs.c b/pool/shard002/C/0059362_logs.c new file mode 100644 index 0000000000000000000000000000000000000000..3d72cd466d7f94530e04f71a3ab2eaa5d9c92c41 --- /dev/null +++ b/pool/shard002/C/0059362_logs.c @@ -0,0 +1,33 @@ +#include +#include +#include +#include "logs.h" + +void logs__on_stdio(char* data, forza__stdio_type_t type) { + forza_metric_t* metric; + + metric = forza_new_metric(); + + metric->metric = 1.0; + metric->description = data; + metric->service = (type == STDIO_STDOUT) ? "logs/stdout" : "logs/stderr"; + + forza_send(metric); + + forza_free_metric(metric); +} + +void logs__on_stdout(char* data) { + logs__on_stdio(data, STDIO_STDOUT); +} + +void logs__on_stderr(char* data) { + logs__on_stdio(data, STDIO_STDERR); +} + +int logs_init(forza_plugin_t* plugin) { + plugin->stdout_data_cb = logs__on_stdout; + plugin->stderr_data_cb = logs__on_stderr; + + return 0; +} diff --git a/pool/shard002/C/0059363_cm_t3517.c b/pool/shard002/C/0059363_cm_t3517.c new file mode 100644 index 0000000000000000000000000000000000000000..cac1ad9ef11d1ca5be5c100c6677a4795bac0b5e --- /dev/null +++ b/pool/shard002/C/0059363_cm_t3517.c @@ -0,0 +1,231 @@ +/* + * (C) Copyright 2014 CompuLab, Ltd. + * + * Authors: Igor Grinberg + * + * SPDX-License-Identifier: GPL-2.0+ + */ + +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +#include "../common/common.h" +#include "../common/eeprom.h" + +DECLARE_GLOBAL_DATA_PTR; + +const omap3_sysinfo sysinfo = { + DDR_DISCRETE, + "CM-T3517 board", + "NAND 128/512M", +}; + +#ifdef CONFIG_USB_MUSB_AM35X +static struct musb_hdrc_config cm_t3517_musb_config = { + .multipoint = 1, + .dyn_fifo = 1, + .num_eps = 16, + .ram_bits = 12, +}; + +static struct omap_musb_board_data cm_t3517_musb_board_data = { + .set_phy_power = am35x_musb_phy_power, + .clear_irq = am35x_musb_clear_irq, + .reset = am35x_musb_reset, +}; + +static struct musb_hdrc_platform_data cm_t3517_musb_pdata = { +#if defined(CONFIG_MUSB_HOST) + .mode = MUSB_HOST, +#elif defined(CONFIG_MUSB_GADGET) + .mode = MUSB_PERIPHERAL, +#else +#error "Please define either CONFIG_MUSB_HOST or CONFIG_MUSB_GADGET" +#endif + .config = &cm_t3517_musb_config, + .power = 250, + .platform_ops = &am35x_ops, + .board_data = &cm_t3517_musb_board_data, +}; + +static void cm_t3517_musb_init(void) +{ + /* + * Set up USB clock/mode in the DEVCONF2 register. + * USB2.0 PHY reference clock is 13 MHz + */ + clrsetbits_le32(&am35x_scm_general_regs->devconf2, + CONF2_REFFREQ | CONF2_OTGMODE | CONF2_PHY_GPIOMODE, + CONF2_REFFREQ_13MHZ | CONF2_SESENDEN | + CONF2_VBDTCTEN | CONF2_DATPOL); + + if (musb_register(&cm_t3517_musb_pdata, &cm_t3517_musb_board_data, + (void *)AM35XX_IPSS_USBOTGSS_BASE)) + printf("Failed initializing AM35x MUSB!\n"); +} +#else +static inline void am3517_evm_musb_init(void) {} +#endif + +int board_init(void) +{ + gpmc_init(); /* in SRAM or SDRAM, finish GPMC */ + + /* boot param addr */ + gd->bd->bi_boot_params = (OMAP34XX_SDRC_CS0 + 0x100); + +#if defined(CONFIG_STATUS_LED) && defined(STATUS_LED_BOOT) + status_led_set(STATUS_LED_BOOT, STATUS_LED_ON); +#endif + + cm_t3517_musb_init(); + + return 0; +} + +int misc_init_r(void) +{ + cl_print_pcb_info(); + dieid_num_r(); + + return 0; +} + +#if defined(CONFIG_GENERIC_MMC) && !defined(CONFIG_SPL_BUILD) +#define SB_T35_CD_GPIO 144 +#define SB_T35_WP_GPIO 59 + +int board_mmc_init(bd_t *bis) +{ + return omap_mmc_init(0, 0, 0, SB_T35_CD_GPIO, SB_T35_WP_GPIO); +} +#endif + +#ifdef CONFIG_DRIVER_TI_EMAC +#define CONTROL_EFUSE_EMAC_LSB 0x48002380 +#define CONTROL_EFUSE_EMAC_MSB 0x48002384 + +static int am3517_get_efuse_enetaddr(u8 *enetaddr) +{ + u32 lsb = __raw_readl(CONTROL_EFUSE_EMAC_LSB); + u32 msb = __raw_readl(CONTROL_EFUSE_EMAC_MSB); + + enetaddr[0] = (u8)((msb >> 16) & 0xff); + enetaddr[1] = (u8)((msb >> 8) & 0xff); + enetaddr[2] = (u8)(msb & 0xff); + enetaddr[3] = (u8)((lsb >> 16) & 0xff); + enetaddr[4] = (u8)((lsb >> 8) & 0xff); + enetaddr[5] = (u8)(lsb & 0xff); + + return is_valid_ether_addr(enetaddr); +} + +static inline int cm_t3517_init_emac(bd_t *bis) +{ + int ret = cpu_eth_init(bis); + + if (ret > 0) + return ret; + + printf("Failed initializing EMAC! "); + return 0; +} +#else /* !CONFIG_DRIVER_TI_EMAC */ +static inline int am3517_get_efuse_enetaddr(u8 *enetaddr) { return 1; } +static inline int cm_t3517_init_emac(bd_t *bis) { return 0; } +#endif /* CONFIG_DRIVER_TI_EMAC */ + +/* + * Routine: handle_mac_address + * Description: prepare MAC address for on-board Ethernet. + */ +static int cm_t3517_handle_mac_address(void) +{ + unsigned char enetaddr[6]; + int ret; + + ret = eth_getenv_enetaddr("ethaddr", enetaddr); + if (ret) + return 0; + + ret = cl_eeprom_read_mac_addr(enetaddr); + if (ret) { + ret = am3517_get_efuse_enetaddr(enetaddr); + if (ret) + return ret; + } + + if (!is_valid_ether_addr(enetaddr)) + return -1; + + return eth_setenv_enetaddr("ethaddr", enetaddr); +} + +#define SB_T35_ETH_RST_GPIO 164 + +/* + * Routine: board_eth_init + * Description: initialize module and base-board Ethernet chips + */ +int board_eth_init(bd_t *bis) +{ + int rc = 0, rc1 = 0; + + rc1 = cm_t3517_handle_mac_address(); + if (rc1) + printf("No MAC address found! "); + + rc1 = cm_t3517_init_emac(bis); + if (rc1 > 0) + rc++; + + rc1 = cl_omap3_smc911x_init(0, 4, CONFIG_SMC911X_BASE, + NULL, SB_T35_ETH_RST_GPIO); + if (rc1 > 0) + rc++; + + return rc; +} + +#ifdef CONFIG_USB_EHCI_OMAP +static struct omap_usbhs_board_data cm_t3517_usbhs_bdata = { + .port_mode[0] = OMAP_EHCI_PORT_MODE_PHY, + .port_mode[1] = OMAP_EHCI_PORT_MODE_PHY, + .port_mode[2] = OMAP_USBHS_PORT_MODE_UNUSED, +}; + +#define CM_T3517_USB_HUB_RESET_GPIO 152 +#define SB_T35_USB_HUB_RESET_GPIO 98 + +int ehci_hcd_init(int index, enum usb_init_type init, + struct ehci_hccr **hccr, struct ehci_hcor **hcor) +{ + cl_usb_hub_init(CM_T3517_USB_HUB_RESET_GPIO, "cm-t3517 hub rst"); + cl_usb_hub_init(SB_T35_USB_HUB_RESET_GPIO, "sb-t35 hub rst"); + + return omap_ehci_hcd_init(index, &cm_t3517_usbhs_bdata, hccr, hcor); +} + +int ehci_hcd_stop(void) +{ + cl_usb_hub_deinit(CM_T3517_USB_HUB_RESET_GPIO); + cl_usb_hub_deinit(SB_T35_USB_HUB_RESET_GPIO); + + return omap_ehci_hcd_stop(); +} +#endif /* CONFIG_USB_EHCI_OMAP */ diff --git a/pool/shard002/C/0059365_pvrusb2-wm8775.c b/pool/shard002/C/0059365_pvrusb2-wm8775.c new file mode 100644 index 0000000000000000000000000000000000000000..8c1eae05aa08837072c54298e2d136885862022f --- /dev/null +++ b/pool/shard002/C/0059365_pvrusb2-wm8775.c @@ -0,0 +1,71 @@ +/* + * + * + * Copyright (C) 2005 Mike Isely + * Copyright (C) 2004 Aurelien Alleaume + * + * 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 + * + * 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 + * + */ + +/* + + This source file is specifically designed to interface with the + wm8775. + +*/ + +#include "pvrusb2-wm8775.h" + + +#include "pvrusb2-hdw-internal.h" +#include "pvrusb2-debug.h" +#include +#include +#include +#include + +void pvr2_wm8775_subdev_update(struct pvr2_hdw *hdw, struct v4l2_subdev *sd) +{ + if (hdw->input_dirty || hdw->force_dirty) { + u32 input; + + switch (hdw->input_val) { + case PVR2_CVAL_INPUT_RADIO: + input = 1; + break; + default: + /* All other cases just use the second input */ + input = 2; + break; + } + pvr2_trace(PVR2_TRACE_CHIPS, "subdev wm8775" + " set_input(val=%d route=0x%x)", + hdw->input_val, input); + + sd->ops->audio->s_routing(sd, input, 0, 0); + } +} + + + +/* + Stuff for Emacs to see, in order to encourage consistent editing style: + *** Local Variables: *** + *** mode: c *** + *** fill-column: 70 *** + *** tab-width: 8 *** + *** c-basic-offset: 8 *** + *** End: *** + */ diff --git a/pool/shard002/C/0059366_bind_by_name.c b/pool/shard002/C/0059366_bind_by_name.c new file mode 100644 index 0000000000000000000000000000000000000000..06302b4b3a6cd4b7852fa4a421f71721d87b41d8 --- /dev/null +++ b/pool/shard002/C/0059366_bind_by_name.c @@ -0,0 +1,234 @@ +/* + This is free and unencumbered software released into the public domain. + + Anyone is free to copy, modify, publish, use, compile, sell, or + distribute this software, either in source code form or as a compiled + binary, for any purpose, commercial or non-commercial, and by any + means. + + In jurisdictions that recognize copyright laws, the author or authors + of this software dedicate any and all copyright interest in the + software to the public domain. We make this dedication for the benefit + of the public at large and to the detriment of our heirs and + successors. We intend this dedication to be an overt act of + relinquishment in perpetuity of all present and future rights to this + software under copyright law. + + 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 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. + + For more information, please refer to +*/ + +#include +#include +#include +#include + +#include "cassandra.h" + +struct Basic_ { + cass_bool_t bln; + cass_float_t flt; + cass_double_t dbl; + cass_int32_t i32; + cass_int64_t i64; +}; + +typedef struct Basic_ Basic; + +void print_error(CassFuture* future) { + const char* message; + size_t message_length; + cass_future_error_message(future, &message, &message_length); + fprintf(stderr, "Error: %.*s\n", (int)message_length, message); +} + +CassCluster* create_cluster() { + CassCluster* cluster = cass_cluster_new(); + cass_cluster_set_contact_points(cluster, "127.0.0.1"); + return cluster; +} + +CassError connect_session(CassSession* session, const CassCluster* cluster) { + CassError rc = CASS_OK; + CassFuture* future = cass_session_connect(session, cluster); + + cass_future_wait(future); + rc = cass_future_error_code(future); + if (rc != CASS_OK) { + print_error(future); + } + cass_future_free(future); + + return rc; +} + +CassError execute_query(CassSession* session, const char* query) { + CassError rc = CASS_OK; + CassStatement* statement = cass_statement_new(query, 0); + CassFuture* future = cass_session_execute(session, statement); + + cass_future_wait(future); + + rc = cass_future_error_code(future); + if (rc != CASS_OK) { + print_error(future); + } + + cass_future_free(future); + cass_statement_free(statement); + + return rc; +} + +CassError prepare_query(CassSession* session, const char* query, const CassPrepared** prepared) { + CassError rc = CASS_OK; + CassFuture* future = NULL; + + future = cass_session_prepare(session, query); + cass_future_wait(future); + + rc = cass_future_error_code(future); + if (rc != CASS_OK) { + print_error(future); + } else { + *prepared = cass_future_get_prepared(future); + } + + cass_future_free(future); + + return rc; +} + +CassError insert_into_basic(CassSession* session, const CassPrepared* prepared, const char* key, const Basic* basic) { + CassError rc = CASS_OK; + CassStatement* statement = NULL; + CassFuture* future = NULL; + + statement = cass_prepared_bind(prepared); + + cass_statement_bind_string_by_name(statement, "key", key); + cass_statement_bind_bool_by_name(statement, "BLN", basic->bln); + cass_statement_bind_float_by_name(statement, "FLT", basic->flt); + cass_statement_bind_double_by_name(statement, "\"dbl\"", basic->dbl); + cass_statement_bind_int32_by_name(statement, "i32", basic->i32); + cass_statement_bind_int64_by_name(statement, "I64", basic->i64); + + future = cass_session_execute(session, statement); + + cass_future_wait(future); + + rc = cass_future_error_code(future); + if (rc != CASS_OK) { + print_error(future); + } + + cass_future_free(future); + cass_statement_free(statement); + + return rc; +} + +CassError select_from_basic(CassSession* session, const CassPrepared * prepared, const char* key, Basic* basic) { + CassError rc = CASS_OK; + CassStatement* statement = NULL; + CassFuture* future = NULL; + + statement = cass_prepared_bind(prepared); + + cass_statement_bind_string_by_name(statement, "key", key); + + future = cass_session_execute(session, statement); + cass_future_wait(future); + + rc = cass_future_error_code(future); + if (rc != CASS_OK) { + print_error(future); + } else { + const CassResult* result = cass_future_get_result(future); + CassIterator* iterator = cass_iterator_from_result(result); + + if (cass_iterator_next(iterator)) { + const CassRow* row = cass_iterator_get_row(iterator); + + cass_value_get_bool(cass_row_get_column_by_name(row, "BLN"), &basic->bln); + cass_value_get_double(cass_row_get_column_by_name(row, "dbl"), &basic->dbl); + cass_value_get_float(cass_row_get_column_by_name(row, "flt"), &basic->flt); + cass_value_get_int32(cass_row_get_column_by_name(row, "\"i32\""), &basic->i32); + cass_value_get_int64(cass_row_get_column_by_name(row, "i64"), &basic->i64); + } + + cass_result_free(result); + cass_iterator_free(iterator); + } + + cass_future_free(future); + cass_statement_free(statement); + + return rc; +} + +int main() { + CassCluster* cluster = create_cluster(); + CassSession* session = cass_session_new(); + CassFuture* close_future = NULL; + Basic input = { cass_true, 0.001f, 0.0002, 1, 2 }; + Basic output; + const CassPrepared* insert_prepared = NULL; + const CassPrepared* select_prepared = NULL; + + const char* insert_query + = "INSERT INTO examples.basic (key, bln, flt, dbl, i32, i64) VALUES (?, ?, ?, ?, ?, ?);"; + const char* select_query + = "SELECT * FROM examples.basic WHERE key = ?"; + + if (connect_session(session, cluster) != CASS_OK) { + cass_cluster_free(cluster); + cass_session_free(session); + return -1; + } + + execute_query(session, + "CREATE KEYSPACE examples WITH replication = { \ + 'class': 'SimpleStrategy', 'replication_factor': '3' };"); + + + execute_query(session, + "CREATE TABLE examples.basic (key text, \ + bln boolean, \ + flt float, dbl double,\ + i32 int, i64 bigint, \ + PRIMARY KEY (key));"); + + + if (prepare_query(session, insert_query, &insert_prepared) == CASS_OK) { + insert_into_basic(session, insert_prepared, "prepared_test", &input); + cass_prepared_free(insert_prepared); + } + + if (prepare_query(session, select_query, &select_prepared) == CASS_OK) { + select_from_basic(session, select_prepared, "prepared_test", &output); + + assert(input.bln == output.bln); + assert(input.flt == output.flt); + assert(input.dbl == output.dbl); + assert(input.i32 == output.i32); + assert(input.i64 == output.i64); + cass_prepared_free(select_prepared); + } + + close_future = cass_session_close(session); + cass_future_wait(close_future); + cass_future_free(close_future); + + cass_cluster_free(cluster); + cass_session_free(session); + + return 0; +} diff --git a/pool/shard002/C/0059379_mrecv_f.c b/pool/shard002/C/0059379_mrecv_f.c new file mode 100644 index 0000000000000000000000000000000000000000..33a122510cd989b1fd87e51b03286b2aff400b9a --- /dev/null +++ b/pool/shard002/C/0059379_mrecv_f.c @@ -0,0 +1,97 @@ +/* + * Copyright (c) 2004-2005 The Trustees of Indiana University and Indiana + * University Research and Technology + * Corporation. All rights reserved. + * Copyright (c) 2004-2005 The University of Tennessee and The University + * of Tennessee Research Foundation. All rights + * reserved. + * Copyright (c) 2004-2005 High Performance Computing Center Stuttgart, + * University of Stuttgart. All rights reserved. + * Copyright (c) 2004-2005 The Regents of the University of California. + * All rights reserved. + * Copyright (c) 2012 Cisco Systems, Inc. All rights reserved. + * Copyright (c) 2012 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2015 Research Organization for Information Science + * and Technology (RIST). All rights reserved. + * Copyright (c) 2015 FUJITSU LIMITED. All rights reserved. + * $COPYRIGHT$ + * + * Additional copyrights may follow + * + * $HEADER$ + */ + +#include "ompi_config.h" + +#include "ompi/mpi/fortran/mpif-h/bindings.h" +#include "ompi/mpi/fortran/mpif-h/status-conversion.h" +#include "ompi/mpi/fortran/base/constants.h" +#include "ompi/communicator/communicator.h" + +#if OMPI_BUILD_MPI_PROFILING +#if OPAL_HAVE_WEAK_SYMBOLS +#pragma weak PMPI_MRECV = ompi_mrecv_f +#pragma weak pmpi_mrecv = ompi_mrecv_f +#pragma weak pmpi_mrecv_ = ompi_mrecv_f +#pragma weak pmpi_mrecv__ = ompi_mrecv_f + +#pragma weak PMPI_Mrecv_f = ompi_mrecv_f +#pragma weak PMPI_Mrecv_f08 = ompi_mrecv_f +#else +OMPI_GENERATE_F77_BINDINGS (PMPI_MRECV, + pmpi_mrecv, + pmpi_mrecv_, + pmpi_mrecv__, + pompi_mrecv_f, + (char *buf, MPI_Fint *count, MPI_Fint *datatype, MPI_Fint *message, + MPI_Fint *status, MPI_Fint *ierr), + (buf, count, datatype, message, status, ierr) ) +#endif +#endif + +#if OPAL_HAVE_WEAK_SYMBOLS +#pragma weak MPI_MRECV = ompi_mrecv_f +#pragma weak mpi_mrecv = ompi_mrecv_f +#pragma weak mpi_mrecv_ = ompi_mrecv_f +#pragma weak mpi_mrecv__ = ompi_mrecv_f + +#pragma weak MPI_Mrecv_f = ompi_mrecv_f +#pragma weak MPI_Mrecv_f08 = ompi_mrecv_f +#else +#if ! OMPI_BUILD_MPI_PROFILING +OMPI_GENERATE_F77_BINDINGS (MPI_MRECV, + mpi_mrecv, + mpi_mrecv_, + mpi_mrecv__, + ompi_mrecv_f, + (char *buf, MPI_Fint *count, MPI_Fint *datatype, + MPI_Fint *message, MPI_Fint *status, MPI_Fint *ierr), + (buf, count, datatype, message, status, ierr) ) +#else +#define ompi_mrecv_f pompi_mrecv_f +#endif +#endif + + +void ompi_mrecv_f(char *buf, MPI_Fint *count, MPI_Fint *datatype, + MPI_Fint *message, MPI_Fint *status, MPI_Fint *ierr) +{ + int c_ierr; + OMPI_FORTRAN_STATUS_DECLARATION(c_status,c_status2) + MPI_Message c_message = PMPI_Message_f2c(*message); + MPI_Datatype c_type = PMPI_Type_f2c(*datatype); + + OMPI_FORTRAN_STATUS_SET_POINTER(c_status,c_status2,status) + + /* Call the C function */ + c_ierr = OMPI_INT_2_FINT(PMPI_Mrecv(OMPI_F2C_BOTTOM(buf), OMPI_FINT_2_INT(*count), + c_type, &c_message, + c_status)); + if (NULL != ierr) *ierr = OMPI_INT_2_FINT(c_ierr); + + if (MPI_SUCCESS == c_ierr) { + OMPI_FORTRAN_STATUS_RETURN(c_status,c_status2,status,c_ierr) + /* message is an INOUT, and may be updated by the recv */ + *message = PMPI_Message_c2f(c_message); + } +} diff --git a/pool/shard002/C/0059381_irq-rm9000.c b/pool/shard002/C/0059381_irq-rm9000.c new file mode 100644 index 0000000000000000000000000000000000000000..923211166653b118eb82615d3af33695b6fac735 --- /dev/null +++ b/pool/shard002/C/0059381_irq-rm9000.c @@ -0,0 +1,106 @@ +/* + * Copyright (C) 2003 Ralf Baechle + * + * 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. + * + * Handler for RM9000 extended interrupts. These are a non-standard + * feature so we handle them separately from standard interrupts. + */ +#include +#include +#include +#include +#include + +#include +#include + +static inline void unmask_rm9k_irq(struct irq_data *d) +{ + set_c0_intcontrol(0x1000 << (d->irq - RM9K_CPU_IRQ_BASE)); +} + +static inline void mask_rm9k_irq(struct irq_data *d) +{ + clear_c0_intcontrol(0x1000 << (d->irq - RM9K_CPU_IRQ_BASE)); +} + +static inline void rm9k_cpu_irq_enable(struct irq_data *d) +{ + unsigned long flags; + + local_irq_save(flags); + unmask_rm9k_irq(d); + local_irq_restore(flags); +} + +/* + * Performance counter interrupts are global on all processors. + */ +static void local_rm9k_perfcounter_irq_startup(void *args) +{ + rm9k_cpu_irq_enable(args); +} + +static unsigned int rm9k_perfcounter_irq_startup(struct irq_data *d) +{ + on_each_cpu(local_rm9k_perfcounter_irq_startup, d, 1); + + return 0; +} + +static void local_rm9k_perfcounter_irq_shutdown(void *args) +{ + unsigned long flags; + + local_irq_save(flags); + mask_rm9k_irq(args); + local_irq_restore(flags); +} + +static void rm9k_perfcounter_irq_shutdown(struct irq_data *d) +{ + on_each_cpu(local_rm9k_perfcounter_irq_shutdown, d, 1); +} + +static struct irq_chip rm9k_irq_controller = { + .name = "RM9000", + .irq_ack = mask_rm9k_irq, + .irq_mask = mask_rm9k_irq, + .irq_mask_ack = mask_rm9k_irq, + .irq_unmask = unmask_rm9k_irq, + .irq_eoi = unmask_rm9k_irq +}; + +static struct irq_chip rm9k_perfcounter_irq = { + .name = "RM9000", + .irq_startup = rm9k_perfcounter_irq_startup, + .irq_shutdown = rm9k_perfcounter_irq_shutdown, + .irq_ack = mask_rm9k_irq, + .irq_mask = mask_rm9k_irq, + .irq_mask_ack = mask_rm9k_irq, + .irq_unmask = unmask_rm9k_irq, +}; + +unsigned int rm9000_perfcount_irq; + +EXPORT_SYMBOL(rm9000_perfcount_irq); + +void __init rm9k_cpu_irq_init(void) +{ + int base = RM9K_CPU_IRQ_BASE; + int i; + + clear_c0_intcontrol(0x0000f000); /* Mask all */ + + for (i = base; i < base + 4; i++) + irq_set_chip_and_handler(i, &rm9k_irq_controller, + handle_level_irq); + + rm9000_perfcount_irq = base + 1; + irq_set_chip_and_handler(rm9000_perfcount_irq, &rm9k_perfcounter_irq, + handle_percpu_irq); +} diff --git a/pool/shard002/C/0059382_test-oss4.c b/pool/shard002/C/0059382_test-oss4.c new file mode 100644 index 0000000000000000000000000000000000000000..1715c663ee72d4aaeaac71763247673d470e92b9 --- /dev/null +++ b/pool/shard002/C/0059382_test-oss4.c @@ -0,0 +1,126 @@ +/* GStreamer OSS4 audio tests + * Copyright (C) 2007-2008 Tim-Philipp Müller + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Library General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Library General Public License for more details. + * + * You should have received a copy of the GNU Library General Public + * License along with this library; if not, write to the + * Free Software Foundation, Inc., 59 Temple Place - Suite 330, + * Boston, MA 02111-1307, USA. + */ + +/* FIXME 0.11: suppress warnings for deprecated API such as GValueArray + * with newer GLib versions (>= 2.31.0) */ +#define GLIB_DISABLE_DEPRECATION_WARNINGS + +#ifdef HAVE_CONFIG_H +#include +#endif + +#include +#include + +#include + +static gboolean opt_show_mixer_messages = FALSE; + +#define WAIT_TIME 60.0 /* in seconds */ + +static void +probe_pad (GstElement * element, const gchar * pad_name) +{ + GstCaps *caps = NULL; + GstPad *pad; + guint i; + + pad = gst_element_get_static_pad (element, pad_name); + if (pad == NULL) + return; + + caps = gst_pad_query_caps (pad, NULL); + g_return_if_fail (caps != NULL); + + for (i = 0; i < gst_caps_get_size (caps); ++i) { + gchar *s; + + s = gst_structure_to_string (gst_caps_get_structure (caps, i)); + g_print (" %4s[%d]: %s\n", GST_PAD_NAME (pad), i, s); + g_free (s); + } + gst_caps_unref (caps); + gst_object_unref (pad); +} + +static void +probe_details (GstElement * element) +{ + GstStateChangeReturn ret; + + ret = gst_element_set_state (element, GST_STATE_READY); + if (ret == GST_STATE_CHANGE_FAILURE) { + g_print ("Could not set element %s to READY.", GST_ELEMENT_NAME (element)); + return; + } + + probe_pad (element, "sink"); + probe_pad (element, "src"); + + gst_element_set_state (element, GST_STATE_NULL); +} + +static void +probe_element (const gchar * name) +{ + GstElement *element; + gchar *devname = NULL; + + element = gst_element_factory_make (name, name); + + /* make sure we don't deadlock on GST_ELEMENT_ERROR or do other silly things + * if we try to query the "device-name" property when the device isn't open */ + g_object_set (element, "device", "/dev/does/not/exist", NULL); + g_object_get (element, "device-name", &devname, NULL); + GST_LOG ("devname: '%s'", GST_STR_NULL (devname)); + g_assert (devname == NULL || *devname == '\0'); + + /* and now for real */ + + probe_details (element); + + gst_object_unref (element); +} + +int +main (int argc, char **argv) +{ + GOptionEntry options[] = { + {"show-mixer-messages", 'm', 0, G_OPTION_ARG_NONE, &opt_show_mixer_messages, + "For mixer elements, wait 60 seconds and show any mixer messages " + "(for debugging auto-notifications)", NULL}, + {NULL,} + }; + GOptionContext *ctx; + GError *err = NULL; + + ctx = g_option_context_new (""); + g_option_context_add_main_entries (ctx, options, NULL); + g_option_context_add_group (ctx, gst_init_get_option_group ()); + if (!g_option_context_parse (ctx, &argc, &argv, &err)) { + g_print ("Error initializing: %s\n", err->message); + exit (1); + } + g_option_context_free (ctx); + + probe_element ("oss4sink"); + probe_element ("oss4src"); + + return 0; +} diff --git a/pool/shard002/C/0059385_layerflags.c b/pool/shard002/C/0059385_layerflags.c new file mode 100644 index 0000000000000000000000000000000000000000..13daa3194769464b902fa12350c38bba09a9cbe8 --- /dev/null +++ b/pool/shard002/C/0059385_layerflags.c @@ -0,0 +1,225 @@ +/*! + * \file src/layerflags.c + * + * \brief Functions for changing layer flags. + * + *
+ * + *

Copyright.

\n + * + * PCB, interactive printed circuit board design + * + * Copyright (C) 2007 DJ Delorie + * Copyright (C) 2015 Markus "Traumflug" Hitter + * + * 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., 675 Mass Ave, Cambridge, MA 02139, USA. + */ + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +#include +#include +#ifdef HAVE_STDLIB_H +#include +#endif +#ifdef HAVE_STRING_H +#include +#endif + +#include "globalconst.h" +#include "global.h" +#include "compat.h" +#include "data.h" +#include "error.h" +#include "hid.h" +#include "strflags.h" + + +/** + * These are the names of all the Layertypes defined in hid.h. Order here + * has to match the order of typedef enum LayertypeType there. + * + * They're used for parsing/writing layer types from/to the layout file. + */ +static char *layertype_name[LT_NUM_LAYERTYPES + 1] = { + "copper", /* LT_COPPER */ + "silk", /* LT_SILK */ + "mask", /* LT_MASK */ + "paste", /* LT_PASTE */ + "outline", /* LT_OUTLINE */ + "route", /* LT_ROUTE */ + "keepout", /* LT_KEEPOUT */ + "fab", /* LT_FAB */ + "assy", /* LT_ASSY */ + "notes", /* LT_NOTES */ + "no_type" /* LT_NUM_LAYERTYPES */ +}; + + +LayertypeType +string_to_layertype (const char *flagstring, + int (*error) (const char *msg)) +{ + LayertypeType type = 0; + + if (*flagstring == '"') + flagstring++; + + while (flagstring > (char *)1 && strlen (flagstring) > 1) + { + for (type = 0; type < LT_NUM_LAYERTYPES; type++) + { + if (strcmp (flagstring, layertype_name[type]) == 0) + break; + } + + if (type == LT_NUM_LAYERTYPES) + flagstring = strchr (flagstring, ',') + 1; + else + break; + } + + return type; +} + +const char * +layertype_to_string (LayertypeType type) +{ + const char *rv = ""; + + if (type < LT_NUM_LAYERTYPES) + rv = layertype_name[type]; + + return rv; +} + +/*! + * Given a layer without type, try to guess its type, mostly from its name. + * This is used by parse_y.y for compatibility with old file formats and + * _not_ used when such flags are already present in the file. + */ +LayertypeType +guess_layertype (const char *name, int layer_number, DataType *data) +{ + LayertypeType type; + + /* First try to find known (partial) matches. */ + for (type = 0; type < LT_NUM_LAYERTYPES; type++) + { + if (strcasestr (name, layertype_name[type])) + break; + } + + /* Nothing found? Then it's likely copper. */ + if (type == LT_NUM_LAYERTYPES) + type = LT_COPPER; + + return type; +} + +/* --------------------------------------------------------------------------- */ + +static const char listlayertypes_syntax[] = + N_("ListLayertypes()"); + +static const char listlayertypes_help[] = + N_("List all available layertypes.\n"); + +/* %start-doc actions ListLayertypes + +Lists all available layer types. These are the valid types for the second +argument of @pxref{SetLayertype Action} or when editing the layout file with +a text editor. + +%end-doc */ + +static int +ActionListLayertypes (int argc, char **argv, Coord x, Coord y) +{ + LayertypeType type; + + Message (N_("Available layer types:\n")); + for (type = 0; type < LT_NUM_LAYERTYPES; type++) + Message (" %s (%d)\n", layertype_name[type], type); + + return 0; +} + +/* --------------------------------------------------------------------------- */ + +static const char setlayertype_syntax[] = + N_("SetLayertype(layer, type)"); + +static const char setlayertype_help[] = + N_("Sets the type of a layer. Type can be given by name or by number.\n" + "For a list of available types, run ListLayertypes()."); + +/* %start-doc actions SetLayertype + +Layers can have various types, like @emph{copper}, @emph{silk} or +@emph{outline}. Behaviour of GUI and exporters largely depend on these types. +For example, searching for electrical connections searches only layers of type +@emph{copper}, all other layers are ignored. + +For a list of available types see @pxref{ListLayertypes Action}. + +%end-doc */ + +int +ActionSetLayertype (int argc, char **argv, Coord x, Coord y) +{ + int index; + LayertypeType type; + + if (argc != 2) + AFAIL (setlayertype); + + /* layer array is zero-based, file format counts layers starting at 1. */ + index = atoi (argv[0]) - 1; + if (index < 0 || index >= max_copper_layer + SILK_LAYER) + { + Message (N_("Layer index %d out of range, must be 0 ... %d\n"), + index + 1, max_copper_layer + SILK_LAYER); + return 1; + } + + if (isdigit (argv[1][0])) + type = atoi (argv[1]); + else + type = string_to_layertype (argv[1], NULL); + + if (type < 0 || type >= LT_NUM_LAYERTYPES) + { + Message (N_("Invalid layer type (%d) requested. " + "See ListLayertypes() for a list.\n"), type); + return 1; + } + + PCB->Data->Layer[index].Type = type; + + return 0; +} + +HID_Action layerflags_action_list[] = { + {"ListLayertypes", 0, ActionListLayertypes, + listlayertypes_help, listlayertypes_syntax} + , + {"SetLayertype", 0, ActionSetLayertype, + setlayertype_help, setlayertype_syntax} +}; + +REGISTER_ACTIONS (layerflags_action_list) diff --git a/pool/shard002/C/0059390_ulimits.c b/pool/shard002/C/0059390_ulimits.c new file mode 100644 index 0000000000000000000000000000000000000000..2533f4dec00b6a397f065d1aaaa8c3c19f4c7094 --- /dev/null +++ b/pool/shard002/C/0059390_ulimits.c @@ -0,0 +1,323 @@ +/*****************************************************************************\ + * src/slurmd/slurmstepd/ulimits.c - set user limits for job + * $Id$ + ***************************************************************************** + * Copyright (C) 2002-2007 The Regents of the University of California. + * Copyright (C) 2008-2010 Lawrence Livermore National Security. + * Produced at Lawrence Livermore National Laboratory (cf, DISCLAIMER). + * Written by Mark Grondona . + * CODE-OCEC-09-009. All rights reserved. + * + * This file is part of SLURM, a resource management program. + * For details, see . + * Please also read the included file: DISCLAIMER. + * + * SLURM 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. + * + * In addition, as a special exception, the copyright holders give permission + * to link the code of portions of this program with the OpenSSL library under + * certain conditions as described in each individual source file, and + * distribute linked combinations including the two. You must obey the GNU + * General Public License in all respects for all of the code used other than + * OpenSSL. If you modify file(s) with this exception, you may extend this + * exception to your version of the file(s), but you are not obligated to do + * so. If you do not wish to do so, delete this exception statement from your + * version. If you delete this exception statement from all source files in + * the program, then also delete it here. + * + * SLURM 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 SLURM; 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 + +#include +#include +#include +#include +#include +#include + +#include "src/common/log.h" +#include "src/common/env.h" /* For unsetenvp() */ +#include "src/common/strlcpy.h" +#include "src/common/xmalloc.h" +#include "src/common/macros.h" +#include "src/common/slurm_rlimits_info.h" + +#include "src/slurmd/slurmstepd/slurmstepd_job.h" + +/* + * Prototypes: + * + */ +static int _get_env_val(char **env, const char *name, unsigned long *valp, + bool *u_req_propagate); +static int _set_limit(char **env, slurm_rlimits_info_t *rli); + +/* + * Set user resource limits using the values of the environment variables + * of the name "SLURM_RLIMIT_*" that are found in job->env. + * + * The sys admin can control the propagation of user limits in the slurm + * conf file by setting values for the PropagateResourceRlimits and + * ResourceLimits keywords. + * + * NOTE: THIS FUNCTION SHOULD ONLY BE CALLED RIGHT BEFORE THE EXEC OF + * A SCRIPT AFTER THE FORK SO AS TO LIMIT THE ABOUT OF EFFECT THE + * LIMITS HAVE WHEN COMBINED WITH THE SLURMSTEPD. RLIMIT_FSIZE IS THE + * MAIN REASON SINCE IF THE USER SETS THIS TO BE LOWER THAN THE SIZE + * OF THE CURRENT SLURMD.LOG THE STEPD WILL CORE THE NEXT TIME + * ANYTHING IS WRITTEN TO IT. SO IF RUNNING +DEBUG2 AND THE USER IS + * GETTING CORES WITH FILE SYSTEM LIMIT ERRORS THIS IS THE REASON. + * + * NOTE: The slurmstepd will not normally write a core file due to setuid(). + * Run as normal user to disable setuid() and permit a core file to be written. + */ + +int set_user_limits(stepd_step_rec_t *job) +{ +#ifdef RLIMIT_AS +#define SLURM_RLIMIT_VSIZE RLIMIT_AS +#define SLURM_RLIMIT_VNAME "RLIMIT_AS" +#elif defined(RLIMIT_DATA) +/* RLIMIT_DATA is useless on many systems which provide anonymous + * mmap()'s in addition to brk(), use it here only as a fallback for + * oddball systems lacking RLIMIT_AS. */ +#define SLURM_RLIMIT_VSIZE RLIMIT_DATA +#define SLURM_RLIMIT_VNAME "RLIMIT_DATA" +#endif + slurm_rlimits_info_t *rli; + struct rlimit r; + rlim_t task_mem_bytes; +#ifdef SLURM_RLIMIT_VSIZE + uint16_t vsize_factor; +#endif + + if (getrlimit(RLIMIT_CPU, &r) == 0) { + if (r.rlim_max != RLIM_INFINITY) { + error("SLURM process CPU time limit is %d seconds", + (int) r.rlim_max); + } + } + + for (rli = get_slurm_rlimits_info(); rli->name; rli++) + _set_limit( job->env, rli ); + + /* Set soft and hard rss and vsize limit for this process, + * handle job limit (for all spawned processes) in slurmd */ + task_mem_bytes = job->step_mem; /* MB */ + task_mem_bytes *= (1024 * 1024); + + /* Many systems, Linux included, ignore RSS limits, but set it + * here anyway for consistency and to provide a way for + * applications to interrogate what the RSS limit is (with the + * caveat that the real RSS limit is over all job tasks on the + * node and not per process, but hopefully this is better than + * nothing). */ +#ifdef RLIMIT_RSS + if ((task_mem_bytes) && (getrlimit(RLIMIT_RSS, &r) == 0) && + (r.rlim_max > task_mem_bytes)) { + r.rlim_max = r.rlim_cur = task_mem_bytes; + if (setrlimit(RLIMIT_RSS, &r)) { + /* Indicates that limit has already been exceeded */ + fatal("setrlimit(RLIMIT_RSS, %u MB): %m", + job->step_mem); + } else + debug2("Set task rss(%u MB)", job->step_mem); +#if 0 + getrlimit(RLIMIT_RSS, &r); + info("task RSS limits: %u %u", r.rlim_cur, r.rlim_max); +#endif + } +#endif + +#ifdef SLURM_RLIMIT_VSIZE + if ((task_mem_bytes) && + ((vsize_factor = slurm_get_vsize_factor()) != 0) && + (getrlimit(SLURM_RLIMIT_VSIZE, &r) == 0) && + (r.rlim_max > task_mem_bytes)) { + r.rlim_max = task_mem_bytes * (vsize_factor / 100.0); + r.rlim_cur = r.rlim_max; + if (setrlimit(SLURM_RLIMIT_VSIZE, &r)) { + /* Indicates that limit has already been exceeded */ + fatal("setrlimit(%s, %u MB): %m", + SLURM_RLIMIT_VNAME, job->step_mem); + } else + debug2("Set task vsize(%u MB)", job->step_mem); +#if 0 + getrlimit(SLURM_RLIMIT_VSIZE, &r); + info("task VSIZE limits: %u %u", r.rlim_cur, r.rlim_max); +#endif + } +#endif + + return SLURM_SUCCESS; +} + +/* + * Return an rlimit as a string suitable for printing. + */ +static char * rlim_to_string (unsigned long rlim, char *buf, size_t n) +{ + if (rlim == (unsigned long) RLIM_INFINITY) + strlcpy (buf, "inf", n); + else + snprintf (buf, n, "%lu", rlim); + return (buf); +} + +/* Set umask using value of env var SLURM_UMASK */ +extern int +set_umask(stepd_step_rec_t *job) +{ + mode_t mask; + char *val; + + if (!(val = getenvp(job->env, "SLURM_UMASK"))) { + debug("Couldn't find SLURM_UMASK in environment"); + return SLURM_ERROR; + } + + mask = strtol(val, (char **)NULL, 8); + unsetenvp(job->env, "SLURM_UMASK"); + umask(mask); + return SLURM_SUCCESS; +} + +/* + * Set rlimit using value of env vars such as SLURM_RLIMIT_FSIZE if + * the slurm config file has PropagateResourceLimits=YES or the user + * requested it with srun --propagate. + * + * NOTE: THIS FUNCTION SHOULD ONLY BE CALLED RIGHT BEFORE THE EXEC OF + * A SCRIPT AFTER THE FORK SO AS TO LIMIT THE ABOUT OF EFFECT THE + * LIMITS HAVE WHEN COMBINED WITH THE SLURMSTEPD. RLIMIT_FSIZE IS THE + * MAIN REASON SINCE IF THE USER SETS THIS TO BE LOWER THAN THE SIZE + * OF THE CURRENT SLURMD.LOG THE STEPD WILL CORE THE NEXT TIME + * ANYTHING IS WRITTEN TO IT. SO IF RUNNING +DEBUG2 AND THE USER IS + * GETTING CORES WITH FILE SYSTEM LIMIT ERRORS THIS IS THE REASON. + */ +static int +_set_limit(char **env, slurm_rlimits_info_t *rli) +{ + unsigned long env_value; + char max[24], cur[24], req[24]; + struct rlimit r; + bool u_req_propagate; /* e.g. TRUE if 'srun --propagate' */ + + char env_name[25] = "SLURM_RLIMIT_"; + char *rlimit_name = &env_name[6]; + + strcpy( &env_name[sizeof("SLURM_RLIMIT_")-1], rli->name ); + + if (_get_env_val( env, env_name, &env_value, &u_req_propagate )){ + debug( "Couldn't find %s in environment", env_name ); + return SLURM_ERROR; + } + + /* + * Users shouldn't get the SLURM_RLIMIT_* env vars in their environ + */ + unsetenvp( env, env_name ); + + /* + * We'll only attempt to set the propagated soft rlimit when indicated + * by the slurm conf file settings, or the user requested it. + */ + if ( ! (rli->propagate_flag == PROPAGATE_RLIMITS || u_req_propagate)) + return SLURM_SUCCESS; + + if (getrlimit( rli->resource, &r ) < 0) { + error("getrlimit(%s): %m", rlimit_name); + return SLURM_ERROR; + } + + /* + * Nothing to do if the rlimit won't change + */ + if (r.rlim_cur == (rlim_t) env_value) { + debug2( "_set_limit: %s setrlimit %s no change in value: %lu", + u_req_propagate?"user":"conf", rlimit_name, + (unsigned long) r.rlim_cur); + return SLURM_SUCCESS; + } + + debug2("_set_limit: %-14s: max:%s cur:%s req:%s", rlimit_name, + rlim_to_string (r.rlim_max, max, sizeof (max)), + rlim_to_string (r.rlim_cur, cur, sizeof (cur)), + rlim_to_string (env_value, req, sizeof (req)) ); + + r.rlim_cur = (rlim_t) env_value; + + if (setrlimit( rli->resource, &r ) < 0) { + /* + * Report an error only if the user requested propagate + */ + if (u_req_propagate) { + error( "Can't propagate %s of %s from submit host: %m", + rlimit_name, + r.rlim_cur == RLIM_INFINITY ? "'unlimited'" : + rlim_to_string( r.rlim_cur, cur, sizeof(cur))); + } else { + verbose("Can't propagate %s of %s from submit host: %m", + rlimit_name, + r.rlim_cur == RLIM_INFINITY ? "'unlimited'" : + rlim_to_string( r.rlim_cur, cur, sizeof(cur))); + } + return SLURM_ERROR; + } + debug2( "_set_limit: %s setrlimit %s succeeded", + u_req_propagate?"user":"conf", rlimit_name ); + + return SLURM_SUCCESS; +} + +/* + * Determine the value of the env var 'name' (if it exists) and whether + * or not the user wants to use its value as the jobs soft rlimit. + */ +static int _get_env_val(char **env, const char *name, unsigned long *valp, + bool *u_req_propagate) +{ + char *val = NULL; + char *p = NULL; + + xassert(env != NULL); + xassert(name != NULL); + + if (!(val = getenvp(env, name))) + return (-1); + + /* + * The letter 'U' would have been prepended to the string value if the + * user requested to have this rlimit propagated via 'srun --propagate' + */ + if (*val == 'U') { + *u_req_propagate = TRUE; + debug2( "_get_env_val: %s propagated by user option", &name[6]); + val++; + } + else + *u_req_propagate = FALSE; + + *valp = strtoul(val, &p, 10); + + if (p && (*p != '\0')) { + error("Invalid %s env var, value = `%s'", name, val); + return (-1); + } + + return (0); +} diff --git a/pool/shard002/C/0059392_system_LPC17xx.c b/pool/shard002/C/0059392_system_LPC17xx.c new file mode 100644 index 0000000000000000000000000000000000000000..021506842b577562103d054698fcfb3c66c594bf --- /dev/null +++ b/pool/shard002/C/0059392_system_LPC17xx.c @@ -0,0 +1,619 @@ +/**************************************************************************//** + * @file system_LPC17xx.c + * @brief CMSIS Cortex-M3 Device Peripheral Access Layer Source File + * for the NXP LPC17xx Device Series + * @version V1.03 + * @date 07. October 2009 + * + * @note + * Copyright (C) 2009 ARM Limited. All rights reserved. + * + * @par + * ARM Limited (ARM) is supplying this software for use with Cortex-M + * processor based microcontrollers. This file can be freely distributed + * within development tools that are supporting such ARM based processors. + * + * @par + * THIS SOFTWARE IS PROVIDED "AS IS". NO WARRANTIES, WHETHER EXPRESS, IMPLIED + * OR STATUTORY, INCLUDING, BUT NOT LIMITED TO, IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE APPLY TO THIS SOFTWARE. + * ARM SHALL NOT, IN ANY CIRCUMSTANCES, BE LIABLE FOR SPECIAL, INCIDENTAL, OR + * CONSEQUENTIAL DAMAGES, FOR ANY REASON WHATSOEVER. + * + ******************************************************************************/ + + +/** @addtogroup LPC17xx_System + * @{ + */ + +/* +//-------- <<< Use Configuration Wizard in Context Menu >>> ------------------ +*/ + +/*--------------------- Clock Configuration ---------------------------------- +// +// Clock Configuration +// System Controls and Status Register (SCS) +// OSCRANGE: Main Oscillator Range Select +// <0=> 1 MHz to 20 MHz +// <1=> 15 MHz to 24 MHz +// OSCEN: Main Oscillator Enable +// +// +// +// Clock Source Select Register (CLKSRCSEL) +// CLKSRC: PLL Clock Source Selection +// <0=> Internal RC oscillator +// <1=> Main oscillator +// <2=> RTC oscillator +// +// +// PLL0 Configuration (Main PLL) +// PLL0 Configuration Register (PLL0CFG) +// F_cco0 = (2 * M * F_in) / N +// F_in must be in the range of 32 kHz to 50 MHz +// F_cco0 must be in the range of 275 MHz to 550 MHz +// MSEL: PLL Multiplier Selection +// <6-32768><#-1> +// M Value +// NSEL: PLL Divider Selection +// <1-256><#-1> +// N Value +// +// +// +// PLL1 Configuration (USB PLL) +// PLL1 Configuration Register (PLL1CFG) +// F_usb = M * F_osc or F_usb = F_cco1 / (2 * P) +// F_cco1 = F_osc * M * 2 * P +// F_cco1 must be in the range of 156 MHz to 320 MHz +// MSEL: PLL Multiplier Selection +// <1-32><#-1> +// M Value (for USB maximum value is 4) +// PSEL: PLL Divider Selection +// <0=> 1 +// <1=> 2 +// <2=> 4 +// <3=> 8 +// P Value +// +// +// +// CPU Clock Configuration Register (CCLKCFG) +// CCLKSEL: Divide Value for CPU Clock from PLL0 +// <3-256><#-1> +// +// +// USB Clock Configuration Register (USBCLKCFG) +// USBSEL: Divide Value for USB Clock from PLL0 +// <0-15> +// Divide is USBSEL + 1 +// +// +// Peripheral Clock Selection Register 0 (PCLKSEL0) +// PCLK_WDT: Peripheral Clock Selection for WDT +// <0=> Pclk = Cclk / 4 +// <1=> Pclk = Cclk +// <2=> Pclk = Cclk / 2 +// <3=> Pclk = Hclk / 8 +// PCLK_TIMER0: Peripheral Clock Selection for TIMER0 +// <0=> Pclk = Cclk / 4 +// <1=> Pclk = Cclk +// <2=> Pclk = Cclk / 2 +// <3=> Pclk = Hclk / 8 +// PCLK_TIMER1: Peripheral Clock Selection for TIMER1 +// <0=> Pclk = Cclk / 4 +// <1=> Pclk = Cclk +// <2=> Pclk = Cclk / 2 +// <3=> Pclk = Hclk / 8 +// PCLK_UART0: Peripheral Clock Selection for UART0 +// <0=> Pclk = Cclk / 4 +// <1=> Pclk = Cclk +// <2=> Pclk = Cclk / 2 +// <3=> Pclk = Hclk / 8 +// PCLK_UART1: Peripheral Clock Selection for UART1 +// <0=> Pclk = Cclk / 4 +// <1=> Pclk = Cclk +// <2=> Pclk = Cclk / 2 +// <3=> Pclk = Hclk / 8 +// PCLK_PWM1: Peripheral Clock Selection for PWM1 +// <0=> Pclk = Cclk / 4 +// <1=> Pclk = Cclk +// <2=> Pclk = Cclk / 2 +// <3=> Pclk = Hclk / 8 +// PCLK_I2C0: Peripheral Clock Selection for I2C0 +// <0=> Pclk = Cclk / 4 +// <1=> Pclk = Cclk +// <2=> Pclk = Cclk / 2 +// <3=> Pclk = Hclk / 8 +// PCLK_SPI: Peripheral Clock Selection for SPI +// <0=> Pclk = Cclk / 4 +// <1=> Pclk = Cclk +// <2=> Pclk = Cclk / 2 +// <3=> Pclk = Hclk / 8 +// PCLK_SSP1: Peripheral Clock Selection for SSP1 +// <0=> Pclk = Cclk / 4 +// <1=> Pclk = Cclk +// <2=> Pclk = Cclk / 2 +// <3=> Pclk = Hclk / 8 +// PCLK_DAC: Peripheral Clock Selection for DAC +// <0=> Pclk = Cclk / 4 +// <1=> Pclk = Cclk +// <2=> Pclk = Cclk / 2 +// <3=> Pclk = Hclk / 8 +// PCLK_ADC: Peripheral Clock Selection for ADC +// <0=> Pclk = Cclk / 4 +// <1=> Pclk = Cclk +// <2=> Pclk = Cclk / 2 +// <3=> Pclk = Hclk / 8 +// PCLK_CAN1: Peripheral Clock Selection for CAN1 +// <0=> Pclk = Cclk / 4 +// <1=> Pclk = Cclk +// <2=> Pclk = Cclk / 2 +// <3=> Pclk = Hclk / 6 +// PCLK_CAN2: Peripheral Clock Selection for CAN2 +// <0=> Pclk = Cclk / 4 +// <1=> Pclk = Cclk +// <2=> Pclk = Cclk / 2 +// <3=> Pclk = Hclk / 6 +// PCLK_ACF: Peripheral Clock Selection for ACF +// <0=> Pclk = Cclk / 4 +// <1=> Pclk = Cclk +// <2=> Pclk = Cclk / 2 +// <3=> Pclk = Hclk / 6 +// +// +// Peripheral Clock Selection Register 1 (PCLKSEL1) +// PCLK_QEI: Peripheral Clock Selection for the Quadrature Encoder Interface +// <0=> Pclk = Cclk / 4 +// <1=> Pclk = Cclk +// <2=> Pclk = Cclk / 2 +// <3=> Pclk = Hclk / 8 +// PCLK_GPIO: Peripheral Clock Selection for GPIOs +// <0=> Pclk = Cclk / 4 +// <1=> Pclk = Cclk +// <2=> Pclk = Cclk / 2 +// <3=> Pclk = Hclk / 8 +// PCLK_PCB: Peripheral Clock Selection for the Pin Connect Block +// <0=> Pclk = Cclk / 4 +// <1=> Pclk = Cclk +// <2=> Pclk = Cclk / 2 +// <3=> Pclk = Hclk / 8 +// PCLK_I2C1: Peripheral Clock Selection for I2C1 +// <0=> Pclk = Cclk / 4 +// <1=> Pclk = Cclk +// <2=> Pclk = Cclk / 2 +// <3=> Pclk = Hclk / 8 +// PCLK_SSP0: Peripheral Clock Selection for SSP0 +// <0=> Pclk = Cclk / 4 +// <1=> Pclk = Cclk +// <2=> Pclk = Cclk / 2 +// <3=> Pclk = Hclk / 8 +// PCLK_TIMER2: Peripheral Clock Selection for TIMER2 +// <0=> Pclk = Cclk / 4 +// <1=> Pclk = Cclk +// <2=> Pclk = Cclk / 2 +// <3=> Pclk = Hclk / 8 +// PCLK_TIMER3: Peripheral Clock Selection for TIMER3 +// <0=> Pclk = Cclk / 4 +// <1=> Pclk = Cclk +// <2=> Pclk = Cclk / 2 +// <3=> Pclk = Hclk / 8 +// PCLK_UART2: Peripheral Clock Selection for UART2 +// <0=> Pclk = Cclk / 4 +// <1=> Pclk = Cclk +// <2=> Pclk = Cclk / 2 +// <3=> Pclk = Hclk / 8 +// PCLK_UART3: Peripheral Clock Selection for UART3 +// <0=> Pclk = Cclk / 4 +// <1=> Pclk = Cclk +// <2=> Pclk = Cclk / 2 +// <3=> Pclk = Hclk / 8 +// PCLK_I2C2: Peripheral Clock Selection for I2C2 +// <0=> Pclk = Cclk / 4 +// <1=> Pclk = Cclk +// <2=> Pclk = Cclk / 2 +// <3=> Pclk = Hclk / 8 +// PCLK_I2S: Peripheral Clock Selection for I2S +// <0=> Pclk = Cclk / 4 +// <1=> Pclk = Cclk +// <2=> Pclk = Cclk / 2 +// <3=> Pclk = Hclk / 8 +// PCLK_RIT: Peripheral Clock Selection for the Repetitive Interrupt Timer +// <0=> Pclk = Cclk / 4 +// <1=> Pclk = Cclk +// <2=> Pclk = Cclk / 2 +// <3=> Pclk = Hclk / 8 +// PCLK_SYSCON: Peripheral Clock Selection for the System Control Block +// <0=> Pclk = Cclk / 4 +// <1=> Pclk = Cclk +// <2=> Pclk = Cclk / 2 +// <3=> Pclk = Hclk / 8 +// PCLK_MC: Peripheral Clock Selection for the Motor Control PWM +// <0=> Pclk = Cclk / 4 +// <1=> Pclk = Cclk +// <2=> Pclk = Cclk / 2 +// <3=> Pclk = Hclk / 8 +// +// +// Power Control for Peripherals Register (PCONP) +// PCTIM0: Timer/Counter 0 power/clock enable +// PCTIM1: Timer/Counter 1 power/clock enable +// PCUART0: UART 0 power/clock enable +// PCUART1: UART 1 power/clock enable +// PCPWM1: PWM 1 power/clock enable +// PCI2C0: I2C interface 0 power/clock enable +// PCSPI: SPI interface power/clock enable +// PCRTC: RTC power/clock enable +// PCSSP1: SSP interface 1 power/clock enable +// PCAD: A/D converter power/clock enable +// PCCAN1: CAN controller 1 power/clock enable +// PCCAN2: CAN controller 2 power/clock enable +// PCGPIO: GPIOs power/clock enable +// PCRIT: Repetitive interrupt timer power/clock enable +// PCMC: Motor control PWM power/clock enable +// PCQEI: Quadrature encoder interface power/clock enable +// PCI2C1: I2C interface 1 power/clock enable +// PCSSP0: SSP interface 0 power/clock enable +// PCTIM2: Timer 2 power/clock enable +// PCTIM3: Timer 3 power/clock enable +// PCUART2: UART 2 power/clock enable +// PCUART3: UART 3 power/clock enable +// PCI2C2: I2C interface 2 power/clock enable +// PCI2S: I2S interface power/clock enable +// PCGPDMA: GP DMA function power/clock enable +// PCENET: Ethernet block power/clock enable +// PCUSB: USB interface power/clock enable +// +// +// Clock Output Configuration Register (CLKOUTCFG) +// CLKOUTSEL: Selects clock source for CLKOUT +// <0=> CPU clock +// <1=> Main oscillator +// <2=> Internal RC oscillator +// <3=> USB clock +// <4=> RTC oscillator +// CLKOUTDIV: Selects clock divider for CLKOUT +// <1-16><#-1> +// CLKOUT_EN: CLKOUT enable control +// +// +// +*/ + + + +/** @addtogroup LPC17xx_System_Defines LPC17xx System Defines + @{ + */ + +#define CLOCK_SETUP 1 +#define SCS_Val 0x00000020 +#define CLKSRCSEL_Val 0x00000001 +#define PLL0_SETUP 1 +#define PLL0CFG_Val 0x00000013 +// F_CRYSTAL = 12MHz +// MSEL0 = 0x13 +// NSEL0 = 0x0 +// M = MSEL + 1 +// N = NSEL + 1 +// F_PLL0 = 2 * M * 12MHz / N +// F_PLL0 = 480MHz +// F_cpu = F_PLL0 / CCLKCFG +// F_cpu = 120MHz + +#define PLL1_SETUP 1 +#define PLL1CFG_Val 0x00000023 + +#define CCLKCFG_Val 0x00000003 + +#define USBCLKCFG_Val 0x00000009 + +#define PCLKSEL0_Val 0x00000000 +#define PCLKSEL1_Val 0x00000000 + +#define PCTIM0 (1<<1) +#define PCTIM1 (1<<2) +#define PCUART0 (1<<3) +#define PCUART1 (1<<4) +#define PCPWM1 (1<<6) +#define PCI2C0 (1<<7) +#define PCSPI (1<<8) +#define PCRTC (1<<9) +#define PCSSP1 (1<<10) +#define PCADC (1<<12) +#define PCCAN1 (1<<13) +#define PCCAN2 (1<<14) +#define PCGPIO (1<<15) +#define PCRIT (1<<16) +#define PCMCPWM (1<<17) +#define PCQEI (1<<18) +#define PCI2C1 (1<<19) +#define PCSSP0 (1<<21) +#define PCTIM2 (1<<22) +#define PCTIM3 (1<<23) +#define PCUART2 (1<<24) +#define PCUART3 (1<<25) +#define PCI2C2 (1<<26) +#define PCI2S (1<<27) +#define PCGPDMA (1<<29) +#define PCENET (1<<30) +#define PCUSB (1<<31) +#define PCONP_Val (PCUART0 | PCSSP0 | PCSSP1 | PCGPIO | PCUSB) + +#define CLKOUTCFG_Val 0x00000000 + + +/*--------------------- Flash Accelerator Configuration ---------------------- +// +// Flash Accelerator Configuration +// Reserved +// FLASHTIM: Flash Access Time +// <0=> 1 CPU clock (for CPU clock up to 20 MHz) +// <1=> 2 CPU clocks (for CPU clock up to 40 MHz) +// <2=> 3 CPU clocks (for CPU clock up to 60 MHz) +// <3=> 4 CPU clocks (for CPU clock up to 80 MHz) +// <4=> 5 CPU clocks (for CPU clock up to 100 MHz) +// <5=> 6 CPU clocks (for any CPU clock) +// +*/ +#define FLASH_SETUP 1 +#define FLASHCFG_Val 0x0000503A + +/* +//-------- <<< end of configuration section >>> ------------------------------ +*/ + +/*---------------------------------------------------------------------------- + Check the register settings + *----------------------------------------------------------------------------*/ +#define CHECK_RANGE(val, min, max) ((val < min) || (val > max)) +#define CHECK_RSVD(val, mask) (val & mask) + +/* Clock Configuration -------------------------------------------------------*/ +#if (CHECK_RSVD((SCS_Val), ~0x00000030)) + #error "SCS: Invalid values of reserved bits!" +#endif + +#if (CHECK_RANGE((CLKSRCSEL_Val), 0, 2)) + #error "CLKSRCSEL: Value out of range!" +#endif + +#if (CHECK_RSVD((PLL0CFG_Val), ~0x00FF7FFF)) + #error "PLL0CFG: Invalid values of reserved bits!" +#endif + +#if (CHECK_RSVD((PLL1CFG_Val), ~0x0000007F)) + #error "PLL1CFG: Invalid values of reserved bits!" +#endif + +#if (CHECK_RANGE(CCLKCFG_Val, 2, 255)) + #error "CCLKCFG: CCLKSEL field does not contain value in range from 2 to 255!" +#endif + +#if (CHECK_RSVD((USBCLKCFG_Val), ~0x0000000F)) + #error "USBCLKCFG: Invalid values of reserved bits!" +#endif + +#if (CHECK_RSVD((PCLKSEL0_Val), 0x000C0C00)) + #error "PCLKSEL0: Invalid values of reserved bits!" +#endif + +#if (CHECK_RSVD((PCLKSEL1_Val), 0x03000300)) + #error "PCLKSEL1: Invalid values of reserved bits!" +#endif + +#if (CHECK_RSVD((PCONP_Val), 0x10100821)) + #error "PCONP: Invalid values of reserved bits!" +#endif + +#if (CHECK_RSVD((CLKOUTCFG_Val), ~0x000001FF)) + #error "CLKOUTCFG: Invalid values of reserved bits!" +#endif + +/* Flash Accelerator Configuration -------------------------------------------*/ +#if (CHECK_RSVD((FLASHCFG_Val), ~0x0000F07F)) + #error "FLASHCFG: Invalid values of reserved bits!" +#endif + + +/*---------------------------------------------------------------------------- + DEFINES + *----------------------------------------------------------------------------*/ + +/*---------------------------------------------------------------------------- + Define clocks + *----------------------------------------------------------------------------*/ +#define XTAL (12000000UL) /* Oscillator frequency */ +#define OSC_CLK ( XTAL) /* Main oscillator frequency */ +#define RTC_CLK ( 32768UL) /* RTC oscillator frequency */ +#define IRC_OSC ( 4000000UL) /* Internal RC oscillator frequency */ + + +/* F_cco0 = (2 * M * F_in) / N */ +#define __M (((PLL0CFG_Val ) & 0x7FFF) + 1) +#define __N (((PLL0CFG_Val >> 16) & 0x00FF) + 1) +#define __FCCO(__F_IN) ((2 * __M * __F_IN) / __N) +#define __CCLK_DIV (((CCLKCFG_Val ) & 0x00FF) + 1) + +/* Determine core clock frequency according to settings */ + #if (PLL0_SETUP) + #if ((CLKSRCSEL_Val & 0x03) == 1) + #define __CORE_CLK (__FCCO(OSC_CLK) / __CCLK_DIV) + #elif ((CLKSRCSEL_Val & 0x03) == 2) + #define __CORE_CLK (__FCCO(RTC_CLK) / __CCLK_DIV) + #else + #define __CORE_CLK (__FCCO(IRC_OSC) / __CCLK_DIV) + #endif + #else + #if ((CLKSRCSEL_Val & 0x03) == 1) + #define __CORE_CLK (OSC_CLK / __CCLK_DIV) + #elif ((CLKSRCSEL_Val & 0x03) == 2) + #define __CORE_CLK (RTC_CLK / __CCLK_DIV) + #else + #define __CORE_CLK (IRC_OSC / __CCLK_DIV) + #endif + #endif + + /** + * @} + */ + + #ifdef __LPC17XX__ + + #include + #include "LPC17xx.h" + + +/** @addtogroup LPC17xx_System_Public_Variables LPC17xx System Public Variables + @{ + */ +/*---------------------------------------------------------------------------- + Clock Variable definitions + *----------------------------------------------------------------------------*/ +uint32_t SystemCoreClock = __CORE_CLK;/*!< System Clock Frequency (Core Clock)*/ + +/** + * @} + */ + + +/** @addtogroup LPC17xx_System_Public_Functions LPC17xx System Public Functions + @{ + */ + +/*---------------------------------------------------------------------------- + Clock functions + *----------------------------------------------------------------------------*/ + + +void SystemCoreClockUpdate (void) /* Get Core Clock Frequency */ +{ + /* Determine clock frequency according to clock register values */ + if (((LPC_SC->PLL0STAT >> 24) & 3) == 3) { /* If PLL0 enabled and connected */ + switch (LPC_SC->CLKSRCSEL & 0x03) { + case 0: /* Int. RC oscillator => PLL0 */ + case 3: /* Reserved, default to Int. RC */ + SystemCoreClock = (IRC_OSC * + ((2 * ((LPC_SC->PLL0STAT & 0x7FFF) + 1))) / + (((LPC_SC->PLL0STAT >> 16) & 0xFF) + 1) / + ((LPC_SC->CCLKCFG & 0xFF)+ 1)); + break; + case 1: /* Main oscillator => PLL0 */ + SystemCoreClock = (OSC_CLK * + ((2 * ((LPC_SC->PLL0STAT & 0x7FFF) + 1))) / + (((LPC_SC->PLL0STAT >> 16) & 0xFF) + 1) / + ((LPC_SC->CCLKCFG & 0xFF)+ 1)); + break; + case 2: /* RTC oscillator => PLL0 */ + SystemCoreClock = (RTC_CLK * + ((2 * ((LPC_SC->PLL0STAT & 0x7FFF) + 1))) / + (((LPC_SC->PLL0STAT >> 16) & 0xFF) + 1) / + ((LPC_SC->CCLKCFG & 0xFF)+ 1)); + break; + } + } else { + switch (LPC_SC->CLKSRCSEL & 0x03) { + case 0: /* Int. RC oscillator => PLL0 */ + case 3: /* Reserved, default to Int. RC */ + SystemCoreClock = IRC_OSC / ((LPC_SC->CCLKCFG & 0xFF)+ 1); + break; + case 1: /* Main oscillator => PLL0 */ + SystemCoreClock = OSC_CLK / ((LPC_SC->CCLKCFG & 0xFF)+ 1); + break; + case 2: /* RTC oscillator => PLL0 */ + SystemCoreClock = RTC_CLK / ((LPC_SC->CCLKCFG & 0xFF)+ 1); + break; + } + } + +} + +/** + * Initialize the system + * + * @param none + * @return none + * + * @brief Setup the microcontroller system. + * Initialize the System. + */ +void SystemInit (void) +{ +#if (CLOCK_SETUP) /* Clock Setup */ + LPC_SC->SCS = SCS_Val; + if (LPC_SC->SCS & (1 << 5)) { /* If Main Oscillator is enabled */ + while ((LPC_SC->SCS & (1<<6)) == 0);/* Wait for Oscillator to be ready */ + } + + LPC_SC->CCLKCFG = CCLKCFG_Val; /* Setup Clock Divider */ + /* Periphral clock must be selected before PLL0 enabling and connecting + * - according errata.lpc1768-16.March.2010 - + */ + LPC_SC->PCLKSEL0 = PCLKSEL0_Val; /* Peripheral Clock Selection */ + LPC_SC->PCLKSEL1 = PCLKSEL1_Val; + +#if (PLL0_SETUP) + LPC_SC->CLKSRCSEL = CLKSRCSEL_Val; /* Select Clock Source for PLL0 */ + + LPC_SC->PLL0CFG = PLL0CFG_Val; /* configure PLL0 */ + LPC_SC->PLL0FEED = 0xAA; + LPC_SC->PLL0FEED = 0x55; + + LPC_SC->PLL0CON = 0x01; /* PLL0 Enable */ + LPC_SC->PLL0FEED = 0xAA; + LPC_SC->PLL0FEED = 0x55; + while (!(LPC_SC->PLL0STAT & (1<<26)));/* Wait for PLOCK0 */ + + LPC_SC->PLL0CON = 0x03; /* PLL0 Enable & Connect */ + LPC_SC->PLL0FEED = 0xAA; + LPC_SC->PLL0FEED = 0x55; + while (!(LPC_SC->PLL0STAT & ((1<<25) | (1<<24))));/* Wait for PLLC0_STAT & PLLE0_STAT */ +#endif + +#if (PLL1_SETUP) + LPC_SC->PLL1CFG = PLL1CFG_Val; + LPC_SC->PLL1FEED = 0xAA; + LPC_SC->PLL1FEED = 0x55; + + LPC_SC->PLL1CON = 0x01; /* PLL1 Enable */ + LPC_SC->PLL1FEED = 0xAA; + LPC_SC->PLL1FEED = 0x55; + while (!(LPC_SC->PLL1STAT & (1<<10)));/* Wait for PLOCK1 */ + + LPC_SC->PLL1CON = 0x03; /* PLL1 Enable & Connect */ + LPC_SC->PLL1FEED = 0xAA; + LPC_SC->PLL1FEED = 0x55; + while (!(LPC_SC->PLL1STAT & ((1<< 9) | (1<< 8))));/* Wait for PLLC1_STAT & PLLE1_STAT */ +#else + LPC_SC->USBCLKCFG = USBCLKCFG_Val; /* Setup USB Clock Divider */ +#endif + LPC_SC->PCONP = PCONP_Val; /* Power Control for Peripherals */ + + LPC_SC->CLKOUTCFG = CLKOUTCFG_Val; /* Clock Output Configuration */ +#endif + +#if (FLASH_SETUP == 1) /* Flash Accelerator Setup */ + LPC_SC->FLASHCFG = FLASHCFG_Val; +#endif + + +// Set Vector table offset value +#if (__RAM_MODE__==1) + extern uint32_t __cs3_region_start_ram; + SCB->VTOR = __cs3_region_start_ram & 0x3FFFFF80; +#else + extern uint32_t __cs3_region_start_rom; + SCB->VTOR = __cs3_region_start_rom & 0x3FFFFF80; +#endif +} + +/** + * @} + */ + +/** + * @} + */ +#endif /* __LPC17XX__ */ diff --git a/pool/shard002/C/0059393_pr58673-2.c b/pool/shard002/C/0059393_pr58673-2.c new file mode 100644 index 0000000000000000000000000000000000000000..ab84670a7362246331e82e8ead6c124c917d8d91 --- /dev/null +++ b/pool/shard002/C/0059393_pr58673-2.c @@ -0,0 +1,220 @@ +/* { dg-do compile { target { powerpc*-*-* && lp64 } } } */ +/* { dg-skip-if "" { powerpc*-*-darwin* } { "*" } { "" } } */ +/* { dg-require-effective-target powerpc_p8vector_ok } */ +/* { dg-options "-mcpu=power8 -O3 -m64 -funroll-loops" } */ + +#include +#include +#include +#include + +typedef long unsigned int size_t; +typedef struct _IO_FILE FILE; +typedef float real; +typedef real rvec[3]; +typedef real matrix[3][3]; +typedef real tensor[3][3]; +enum +{ + F_BONDS, F_G96BONDS, F_MORSE, F_CUBICBONDS, F_CONNBONDS, F_HARMONIC, + F_ANGLES, F_G96ANGLES, F_PDIHS, F_RBDIHS, F_IDIHS, F_LJ14, F_COUL14, F_LJ, + F_BHAM, F_LJLR, F_DISPCORR, F_SR, F_LR, F_WPOL, F_POSRES, F_DISRES, + F_DISRESVIOL, F_ORIRES, F_ORIRESDEV, F_ANGRES, F_ANGRESZ, F_SHAKE, + F_SHAKENC, F_SETTLE, F_DUMMY2, F_DUMMY3, F_DUMMY3FD, F_DUMMY3FAD, + F_DUMMY3OUT, F_DUMMY4FD, F_EQM, F_EPOT, F_EKIN, F_ETOT, F_TEMP, F_PRES, + F_DVDL, F_DVDLKIN, F_NRE +}; +typedef union +{ + struct + { + } + bham; + struct + { + real rA, krA, rB, krB; + } + harmonic; +} +t_iparams; +typedef struct +{ + t_iparams *iparams; +} +t_idef; +typedef struct +{ +} +t_inputrec; +typedef struct +{ +} +t_commrec; +typedef struct +{ +} +t_forcerec; +typedef struct +{ +} +t_mdatoms; +typedef struct +{ +} +t_filenm; +enum +{ + eoPres, eoEpot, eoVir, eoDist, eoMu, eoForce, eoFx, eoFy, eoFz, eoPx, eoPy, + eoPz, eoPolarizability, eoDipole, eoObsNR, eoMemory = + eoObsNR, eoInter, eoUseVirial, eoNR +}; +extern char *eoNames[eoNR]; +typedef struct +{ + int bPrint; +} +t_coupl_LJ; +typedef struct +{ + int eObs; + t_iparams xi; +} +t_coupl_iparams; +typedef struct +{ + real act_value[eoObsNR]; + real av_value[eoObsNR]; + real ref_value[eoObsNR]; + int bObsUsed[eoObsNR]; + int nLJ, nBU, nQ, nIP; + t_coupl_LJ *tcLJ; +} +t_coupl_rec; +void xvgr_legend (); +real calc_deviation (); +void pr_dev (); +static void +pr_ff (t_coupl_rec * tcr, real time, t_idef * idef, t_commrec * cr, int nfile, + t_filenm fnm[]) +{ + static FILE *prop; + static FILE **out = ((void *) 0); + static FILE **qq = ((void *) 0); + static FILE **ip = ((void *) 0); + char buf[256]; + char *leg[] = { + "C12", "C6" + }; + char **raleg; + int i, j, index; + if ((prop == ((void *) 0)) && (out == ((void *) 0)) && (qq == ((void *) 0)) + && (ip == ((void *) 0))) + { + for (i = j = 0; (i < eoObsNR); i++) + { + if (tcr->bObsUsed[i]) + { + raleg[j++] = + (__extension__ + (__builtin_constant_p (eoNames[i]) + && ((size_t) (const void *) ((eoNames[i]) + 1) - + (size_t) (const void *) (eoNames[i]) == + 1) ? (((const char *) (eoNames[i]))[0] == + '\0' ? (char *) calloc ((size_t) 1, + (size_t) 1) : ( + { + size_t + __len + = + strlen + (eoNames + [i]) + + + 1; + char + *__retval + = + (char + *) + malloc + (__len); + __retval;} + )): __strdup (eoNames[i]))); + raleg[j++] = + (__extension__ + (__builtin_constant_p (buf) + && ((size_t) (const void *) ((buf) + 1) - + (size_t) (const void *) (buf) == + 1) ? (((const char *) (buf))[0] == + '\0' ? (char *) calloc ((size_t) 1, + (size_t) 1) : ( + { + size_t + __len + = + strlen + (buf) + + + 1; + char + *__retval + = + (char + *) + malloc + (__len); + __retval;} + )): __strdup (buf))); + } + } + if (tcr->nLJ) + { + for (i = 0; (i < tcr->nLJ); i++) + { + if (tcr->tcLJ[i].bPrint) + { + xvgr_legend (out[i], (sizeof (leg) / sizeof ((leg)[0])), + leg); + } + } + } + } +} + +void +do_coupling (FILE * log, int nfile, t_filenm fnm[], t_coupl_rec * tcr, real t, + int step, real ener[], t_forcerec * fr, t_inputrec * ir, + int bMaster, t_mdatoms * md, t_idef * idef, real mu_aver, + int nmols, t_commrec * cr, matrix box, tensor virial, + tensor pres, rvec mu_tot, rvec x[], rvec f[], int bDoIt) +{ + int i, j, ati, atj, atnr2, type, ftype; + real deviation[eoObsNR], prdev[eoObsNR], epot0, dist, rmsf; + real ff6, ff12, ffa, ffb, ffc, ffq, factor, dt, mu_ind; + int bTest, bPrint; + t_coupl_iparams *tip; + if (bPrint) + { + pr_ff (tcr, t, idef, cr, nfile, fnm); + } + for (i = 0; (i < eoObsNR); i++) + { + deviation[i] = + calc_deviation (tcr->av_value[i], tcr->act_value[i], + tcr->ref_value[i]); + prdev[i] = tcr->ref_value[i] - tcr->act_value[i]; + } + if (bPrint) + pr_dev (tcr, t, prdev, cr, nfile, fnm); + for (i = 0; (i < atnr2); i++) + { + factor = dt * deviation[tip->eObs]; + switch (ftype) + { + case F_BONDS: + if (fabs (tip->xi.harmonic.krA) > 1.2e-38) + idef->iparams[type].harmonic.krA *= + (1 + factor / tip->xi.harmonic.krA); + } + } +} diff --git a/pool/shard002/C/0059397_query_group_constraint.c b/pool/shard002/C/0059397_query_group_constraint.c new file mode 100644 index 0000000000000000000000000000000000000000..e7aff3c18d3a64aecb0b6cd30c52515110fac59a --- /dev/null +++ b/pool/shard002/C/0059397_query_group_constraint.c @@ -0,0 +1,127 @@ +/* + * Copyright (C) 2007 Piotr Pokora + * + * 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; 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 "query_group_constraint.h" +#include "query_constraint.h" +#include "midgard_mysql.h" +#include "midgard/midgard_object.h" + +G_DEFINE_TYPE(MidgardQueryGroupConstraint, midgard_query_group_constraint, G_TYPE_OBJECT) + +MidgardQueryGroupConstraint *midgard_query_group_constraint_new(void) +{ + MidgardQueryGroupConstraint *self = + g_object_new(MIDGARD_TYPE_QUERY_GROUP_CONSTRAINT, NULL); + + return self; +} + +static const gchar *valid_types[] = {"OR", "AND", NULL }; + +gboolean midgard_query_group_constraint_type_is_valid(const gchar *type) +{ + guint i; + + for (i = 0; valid_types[i] != NULL; i++) { + + if (g_str_equal(type, valid_types[i])) + return TRUE; + + } + + if (valid_types[i] == NULL) { + + /* FIXME, emmit signal here */ + g_warning("Invalid group operator type %s", type); + return FALSE; + } + + return TRUE; +} + +void midgard_query_group_constraint_add_sql( + MidgardQueryGroupConstraint *self, GString *sql) +{ + g_assert(self != NULL); + g_assert(sql != NULL); + + if(self->priv->constraints == NULL) + return; + + g_string_append_printf(sql, + " %s ( ", + self->priv->group_type); + + g_string_append(sql, " )"); +} + +/* GOBJECT ROUTINES */ +MidgardQueryGroupConstraintPrivate *midgard_query_group_constraint_private_new() +{ + MidgardQueryGroupConstraintPrivate *priv = + g_new(MidgardQueryGroupConstraintPrivate, 1); + priv->group_type = NULL; + priv->constraints = NULL; + + return priv; +} + +void midgard_query_group_constraint_private_free( + MidgardQueryGroupConstraintPrivate *priv) +{ + g_assert(priv != NULL); + + if(priv->group_type != NULL) + g_free(priv->group_type); + + GSList *list = NULL; + + /* free constraints */ + for(list = priv->constraints; list != NULL; list = list->next) + g_object_unref(list->data); + + if(list) + g_slist_free(list); + + return; +} + +static void midgard_query_group_constraint_init(MidgardQueryGroupConstraint *self) +{ + g_assert(self != NULL); + + self->priv = midgard_query_group_constraint_private_new(); +} + +static void midgard_query_group_constraint_finalize(GObject *object) +{ + g_assert(object != NULL); + + MidgardQueryGroupConstraint *self = MIDGARD_QUERY_GROUP_CONSTRAINT(object); + midgard_query_group_constraint_private_free(self->priv); +} + +static void midgard_query_group_constraint_class_init( + MidgardQueryGroupConstraintClass *klass) +{ + g_assert(klass != NULL); + + klass->parent.finalize = midgard_query_group_constraint_finalize; + klass->add_sql = midgard_query_group_constraint_add_sql; +} diff --git a/pool/shard002/C/0059403_read_storage.c b/pool/shard002/C/0059403_read_storage.c new file mode 100644 index 0000000000000000000000000000000000000000..2bdb1d6ba6fbc1f83a81e3a86b6b57471d9c2a60 --- /dev/null +++ b/pool/shard002/C/0059403_read_storage.c @@ -0,0 +1,229 @@ +/* + Copyright (c) 2010 Fizians SAS. + This file is part of Rozofs. + + Rozofs 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. + + Rozofs 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 +#include +#include +#include +#include +#include +/* +** ____________________________________________________________________ +** C O M P I L A T I O N +** +** This source requires include file storage.h under src/storaged +** which requires some other includes +** +** gcc -I../src/storaged/ -I.. -I./build read_storage.c -g -o read_storage +** ____________________________________________________________________ +** +*/ +char FILENAME[500]; +int rozofs_safe; +int rozofs_psizes_max; +static void usage() { + printf("\n./read_storage [ ... []]\n\n"); + printf("eg: \n./read_storage storage_1-*/*/*/*/0853b843-dc9c-4d89-815b-d12805121f66.bins\n"); + printf(" to display the content of each pieces of file\n"); + printf(" whose FID is 0853b843-dc9c-4d89-815b-d12805121f66\n"); + exit(-100); +} +void rozofs_layout_initialize(int layout) { + int angleP[64]; + int angleQ[64]; + int rozofs_psizes[64]; + int i; + int rozofs_forward; + int rozofs_inverse; + + switch (layout) { + case 0: + rozofs_safe = 4; + rozofs_forward = 3; + rozofs_inverse = 2; + break; + case 1: + rozofs_safe = 8; + rozofs_inverse = 4; + rozofs_forward = 6; + break; + case 2: + rozofs_safe = 16; + rozofs_inverse = 8; + rozofs_forward = 12; + break; + default: + break; + } + + + for (i = 0; i < rozofs_forward; i++) { + angleP[i] = i - rozofs_forward / 2; + angleQ[i] = 1; + rozofs_psizes[i] = abs(i - rozofs_forward / 2) * (rozofs_inverse - 1) + + (ROZOFS_BSIZE / sizeof (pxl_t) / rozofs_inverse - 1) + 1; + if (rozofs_psizes[i] > rozofs_psizes_max) rozofs_psizes_max = rozofs_psizes[i]; + } + +} + +int do_read_header(int fd, int display) { + size_t nb_read=0; + rozofs_stor_bins_file_hdr_t file_hdr; + int i; + + nb_read = pread(fd, &file_hdr, sizeof (file_hdr), 0); + if (nb_read != sizeof (file_hdr)) { + printf("Can not read header of size %d %s\n",sizeof (file_hdr), strerror(errno)); + return -1; + } + + rozofs_layout_initialize(file_hdr.layout); + if (!display) return file_hdr.layout; + + printf(" Version %d Layout %d distribution current ",file_hdr.version, file_hdr.layout); + + for (i=0; i bins_hdr.s.timestamp) start_time = bins_hdr.s.timestamp; + } +} +int do_read_block(int fd, int layout, int bid) { + off_t offset = 0; + rozofs_stor_bins_hdr_t bins_hdr; + size_t nb_read=0; + + + offset = ((rozofs_psizes_max * sizeof (bin_t)+ sizeof(bins_hdr)) * bid) + ROZOFS_ST_BINS_FILE_HDR_SIZE; + + // Write nb_proj * (projection + header) + // printf("offset 0x%8x \n",offset ); + nb_read = pread(fd, &bins_hdr, sizeof (bins_hdr), offset); + if (nb_read != sizeof (bins_hdr)) return -1; + + if ((bins_hdr.s.timestamp==0) && (bins_hdr.s.effective_length==0)) return 0; + + printf (" 0x%8.8x %4d | %20llu | %8d | %6d | %3d | %3d |\n", + offset,bid, + bins_hdr.s.timestamp, (int) (bins_hdr.s.timestamp - start_time), + bins_hdr.s.effective_length, + bins_hdr.s.projection_id, + bins_hdr.s.version); + return 0; +} +int do_read(char * filename) { + int fd; + int block; + int layout; + + printf("%s\n",filename); + + fd = open(filename, O_RDONLY , 0640); + if (fd == -1) { + printf("proc %3d - open %s %s\n",filename, strerror(errno)); + return -1; + } + + layout = do_read_header(fd,1); + if (layout == -1) { + close (fd); + return -1; + } + + + block = 0; + printf (" offset & block | Time Stamp | relative | length | Pid |Vers.|\n"); + printf (" ----------------+----------------------+----------+--------+-----+-----+\n"); + + while (do_read_block(fd,layout,block) == 0) block++; + + close(fd); + return 0; +} + +int main(int argc, char **argv) { + int idx=1; + + if (argc <= 1) { + usage(); + } + if (argv[1][0] == '-') { + usage(); + } + + start_time=0xFFFFFFFFFFFFFFFF; + + idx=1; + while (idx < argc) { + do_search_start_time(argv[idx]); + idx++; + } + + idx=1; + while (idx < argc) { + do_read(argv[idx]); + idx++; + } + return 0; +} diff --git a/pool/shard002/C/0059415_early_setup.c b/pool/shard002/C/0059415_early_setup.c new file mode 100644 index 0000000000000000000000000000000000000000..3de3c564d16c369c3d454b92b29c7b9fb2e63230 --- /dev/null +++ b/pool/shard002/C/0059415_early_setup.c @@ -0,0 +1,242 @@ +/* + * This file is part of the coreboot project. + * + * Copyright (C) 2010 Advanced Micro Devices, Inc. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; version 2 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + */ + +#ifndef _HUDSON_EARLY_SETUP_C_ +#define _HUDSON_EARLY_SETUP_C_ + +#include +#include +#include +#include +#include +#include +#include +#include "hudson.h" +#include "pci_devs.h" +#include + +#if IS_ENABLED(CONFIG_HUDSON_UART) + +#include +#include + +void configure_hudson_uart(void) +{ + u8 byte; + + byte = read8((void *)ACPI_MMIO_BASE + AOAC_BASE + FCH_AOAC_REG56 + CONFIG_UART_FOR_CONSOLE * 2); + byte |= 1 << 3; + write8((void *)ACPI_MMIO_BASE + AOAC_BASE + FCH_AOAC_REG56 + CONFIG_UART_FOR_CONSOLE * 2, byte); + byte = read8((void *)ACPI_MMIO_BASE + AOAC_BASE + FCH_AOAC_REG62); + byte |= 1 << 3; + write8((void *)ACPI_MMIO_BASE + AOAC_BASE + FCH_AOAC_REG62, byte); + write8((void *)FCH_IOMUXx89_UART0_RTS_L_EGPIO137, 0); + write8((void *)FCH_IOMUXx8A_UART0_TXD_EGPIO138, 0); + write8((void *)FCH_IOMUXx8E_UART1_RTS_L_EGPIO142, 0); + write8((void *)FCH_IOMUXx8F_UART1_TXD_EGPIO143, 0); + + udelay(2000); + write8((void *)0xFEDC6000 + 0x2000 * CONFIG_UART_FOR_CONSOLE + 0x88, 0x01); /* reset UART */ +} + +#endif + +void hudson_pci_port80(void) +{ + u8 byte; + pci_devfn_t dev; + + /* P2P Bridge */ + dev = PCI_DEV(0, 0x14, 4); + + /* Chip Control: Enable subtractive decoding */ + byte = pci_read_config8(dev, 0x40); + byte |= 1 << 5; + pci_write_config8(dev, 0x40, byte); + + /* Misc Control: Enable subtractive decoding if 0x40 bit 5 is set */ + byte = pci_read_config8(dev, 0x4B); + byte |= 1 << 7; + pci_write_config8(dev, 0x4B, byte); + + /* The same IO Base and IO Limit here is meaningful because we set the + * bridge to be subtractive. During early setup stage, we have to make + * sure that data can go through port 0x80. + */ + /* IO Base: 0xf000 */ + byte = pci_read_config8(dev, 0x1C); + byte |= 0xF << 4; + pci_write_config8(dev, 0x1C, byte); + + /* IO Limit: 0xf000 */ + byte = pci_read_config8(dev, 0x1D); + byte |= 0xF << 4; + pci_write_config8(dev, 0x1D, byte); + + /* PCI Command: Enable IO response */ + byte = pci_read_config8(dev, 0x04); + byte |= 1 << 0; + pci_write_config8(dev, 0x04, byte); + + /* LPC controller */ + dev = PCI_DEV(0, 0x14, 3); + + byte = pci_read_config8(dev, 0x4A); + byte &= ~(1 << 5); /* disable lpc port 80 */ + pci_write_config8(dev, 0x4A, byte); +} + +void hudson_lpc_port80(void) +{ + u8 byte; + pci_devfn_t dev; + + /* Enable LPC controller */ + outb(0xEC, 0xCD6); + byte = inb(0xCD7); + byte |= 1; + outb(0xEC, 0xCD6); + outb(byte, 0xCD7); + + /* Enable port 80 LPC decode in pci function 3 configuration space. */ + dev = PCI_DEV(0, 0x14, 3); + byte = pci_read_config8(dev, 0x4a); + byte |= 1 << 5; /* enable port 80 */ + pci_write_config8(dev, 0x4a, byte); +} + +void hudson_lpc_decode(void) +{ + pci_devfn_t dev; + u32 tmp = 0; + + /* Enable I/O decode to LPC bus */ + dev = PCI_DEV(0, PCU_DEV, LPC_FUNC); + tmp = DECODE_ENABLE_PARALLEL_PORT0 | DECODE_ENABLE_PARALLEL_PORT2 + | DECODE_ENABLE_PARALLEL_PORT4 | DECODE_ENABLE_SERIAL_PORT0 + | DECODE_ENABLE_SERIAL_PORT1 | DECODE_ENABLE_SERIAL_PORT2 + | DECODE_ENABLE_SERIAL_PORT3 | DECODE_ENABLE_SERIAL_PORT4 + | DECODE_ENABLE_SERIAL_PORT5 | DECODE_ENABLE_SERIAL_PORT6 + | DECODE_ENABLE_SERIAL_PORT7 | DECODE_ENABLE_AUDIO_PORT0 + | DECODE_ENABLE_AUDIO_PORT1 | DECODE_ENABLE_AUDIO_PORT2 + | DECODE_ENABLE_AUDIO_PORT3 | DECODE_ENABLE_MSS_PORT2 + | DECODE_ENABLE_MSS_PORT3 | DECODE_ENABLE_FDC_PORT0 + | DECODE_ENABLE_FDC_PORT1 | DECODE_ENABLE_GAME_PORT + | DECODE_ENABLE_KBC_PORT | DECODE_ENABLE_ACPIUC_PORT + | DECODE_ENABLE_ADLIB_PORT; + + pci_write_config32(dev, LPC_IO_PORT_DECODE_ENABLE, tmp); +} + +int s3_save_nvram_early(u32 dword, int size, int nvram_pos) +{ + int i; + printk(BIOS_DEBUG, "Writing %x of size %d to nvram pos: %d\n", dword, size, nvram_pos); + + for (i = 0; i < size; i++) { + outb(nvram_pos, BIOSRAM_INDEX); + outb((dword >>(8 * i)) & 0xff , BIOSRAM_DATA); + nvram_pos++; + } + + return nvram_pos; +} + +int s3_load_nvram_early(int size, u32 *old_dword, int nvram_pos) +{ + u32 data = *old_dword; + int i; + for (i = 0; i < size; i++) { + outb(nvram_pos, BIOSRAM_INDEX); + data &= ~(0xff << (i * 8)); + data |= inb(BIOSRAM_DATA) << (i *8); + nvram_pos++; + } + *old_dword = data; + printk(BIOS_DEBUG, "Loading %x of size %d to nvram pos:%d\n", *old_dword, size, + nvram_pos-size); + return nvram_pos; +} + +void hudson_clk_output_48Mhz(void) +{ + u32 data, *memptr; + + /* + * Enable the X14M_25M_48M_OSC pin and leaving it at it's default so + * 48Mhz will be on ball AP13 (FT3b package) + */ + memptr = (u32 *)(ACPI_MMIO_BASE + MISC_BASE + FCH_MISC_REG40 ); + data = *memptr; + + /* clear the OSCOUT1_ClkOutputEnb to enable the 48 Mhz clock */ + data &= (u32)~(1<<2); + *memptr = data; +} + +static uintptr_t hudson_spibase(void) +{ + /* Make sure the base address is predictable */ + device_t dev = PCI_DEV(0, 0x14, 3); + + u32 base = pci_read_config32(dev, SPIROM_BASE_ADDRESS_REGISTER) + & 0xfffffff0; + if (!base){ + base = SPI_BASE_ADDRESS; + pci_write_config32(dev, SPIROM_BASE_ADDRESS_REGISTER, base + | SPI_ROM_ENABLE); + /* PCI_COMMAND_MEMORY is read-only and enabled. */ + } + return (uintptr_t)base; +} + +void hudson_set_spi100(u16 norm, u16 fast, u16 alt, u16 tpm) +{ + uintptr_t base = hudson_spibase(); + write16((void *)base + SPI100_SPEED_CONFIG, + (norm << SPI_NORM_SPEED_NEW_SH) | + (fast << SPI_FAST_SPEED_NEW_SH) | + (alt << SPI_ALT_SPEED_NEW_SH) | + (tpm << SPI_TPM_SPEED_NEW_SH)); + write16((void *)base + SPI100_ENABLE, SPI_USE_SPI100); +} + +void hudson_disable_4dw_burst(void) +{ + uintptr_t base = hudson_spibase(); + write16((void *)base + SPI100_HOST_PREF_CONFIG, + read16((void *)base + SPI100_HOST_PREF_CONFIG) + & ~SPI_RD4DW_EN_HOST); +} + +/* Hudson 1-3 only. For Hudson 1, call with fast=1 */ +void hudson_set_readspeed(u16 norm, u16 fast) +{ + uintptr_t base = hudson_spibase(); + write16((void *)base + SPI_CNTRL1, (read16((void *)base + SPI_CNTRL1) + & ~SPI_CNTRL1_SPEED_MASK) + | (norm << SPI_NORM_SPEED_SH) + | (fast << SPI_FAST_SPEED_SH)); +} + +void hudson_read_mode(u32 mode) +{ + uintptr_t base = hudson_spibase(); + write32((void *)base + SPI_CNTRL0, + (read32((void *)base + SPI_CNTRL0) + & ~SPI_READ_MODE_MASK) | mode); +} + +#endif diff --git a/pool/shard002/C/0059419_prime.c b/pool/shard002/C/0059419_prime.c new file mode 100644 index 0000000000000000000000000000000000000000..77fe5de09b9d3b77343bcd2c509d13f6c4a1f6b9 --- /dev/null +++ b/pool/shard002/C/0059419_prime.c @@ -0,0 +1,57 @@ +uint32 +prime_numeral_next(uint32 prime) +{ + uint32 *iter; + + if (prime < FIXED_PRIME_MAX) { + iter = (uint32 *)fixed_prime; + while (iter < fixed_prime + array_sizeof(fixed_prime)) { + if (prime <= *iter) { + break; + } + iter++; + } + return *iter; + } else { + return prime_numeral_calculate_next(prime); + } +} + +static inline uint32 +prime_numeral_calculate_next(uint32 prime) +{ + uint32 start; + uint32 next; + uint32 limit; + uint32 retval; + + prime |= 0x1u; + + retval = 0; + next = prime + 2; + while (next != UINT_MAX) { + start = 3; + limit = (uint32)dp_sqrt(next); + while (start < limit) { + if (0u == next % start) { + break; + } + start += 2; + } + + if (start < limit) { + /* If next is not PRIME */ + next += 2; + } else { + retval = next; + break; + } + } + + if (0 == retval) { + pr_log_warn("Failed to find next PRIME numeral less than UINT_MAX.\n"); + } + + return retval; +} + diff --git a/pool/shard002/C/0059426_dwarf_begin_elf.c b/pool/shard002/C/0059426_dwarf_begin_elf.c new file mode 100644 index 0000000000000000000000000000000000000000..a9aa197cf81d47f53d7c3d31f387079d64698880 --- /dev/null +++ b/pool/shard002/C/0059426_dwarf_begin_elf.c @@ -0,0 +1,251 @@ +/* Create descriptor from ELF descriptor for processing file. + Copyright (C) 2002, 2003, 2004 Red Hat, Inc. + Written by Ulrich Drepper , 2002. + + This program is Open Source software; you can redistribute it and/or + modify it under the terms of the Open Software License version 1.0 as + published by the Open Source Initiative. + + You should have received a copy of the Open Software License along + with this program; if not, you may obtain a copy of the Open Software + License version 1.0 from http://www.opensource.org/licenses/osl.php or + by writing the Open Source Initiative c/o Lawrence Rosen, Esq., + 3001 King Ranch Road, Ukiah, CA 95482. */ + +#ifdef HAVE_CONFIG_H +# include +#endif + +#include +#include +#include +#include +#include +#include + +#include "libdwP.h" + + +/* Section names. */ +static const char dwarf_scnnames[IDX_last][17] = +{ + [IDX_debug_info] = ".debug_info", + [IDX_debug_abbrev] = ".debug_abbrev", + [IDX_debug_aranges] = ".debug_aranges", + [IDX_debug_line] = ".debug_line", + [IDX_debug_frame] = ".debug_frame", + [IDX_eh_frame] = ".eh_frame", + [IDX_debug_loc] = ".debug_loc", + [IDX_debug_pubnames] = ".debug_pubnames", + [IDX_debug_str] = ".debug_str", + [IDX_debug_funcnames] = ".debug_funcnames", + [IDX_debug_typenames] = ".debug_typenames", + [IDX_debug_varnames] = ".debug_varnames", + [IDX_debug_weaknames] = ".debug_weaknames", + [IDX_debug_macinfo] = ".debug_macinfo" +}; +#define ndwarf_scnnames (sizeof (dwarf_scnnames) / sizeof (dwarf_scnnames[0])) + + +static void +check_section (Dwarf *result, GElf_Ehdr *ehdr, Elf_Scn *scn, bool inscngrp) +{ + GElf_Shdr shdr_mem; + GElf_Shdr *shdr; + + /* Get the section header data. */ + shdr = gelf_getshdr (scn, &shdr_mem); + if (shdr == NULL) + /* This should never happen. If it does something is + wrong in the libelf library. */ + abort (); + + + /* Make sure the section is part of a section group only iff we + really need it. If we are looking for the global (= non-section + group debug info) we have to ignore all the info in section + groups. If we are looking into a section group we cannot look at + a section which isn't part of the section group. */ + if (! inscngrp && (shdr->sh_flags & SHF_GROUP) != 0) + /* Ignore the section. */ + return; + + + /* We recognize the DWARF section by their names. This is not very + safe and stable but the best we can do. */ + const char *scnname = elf_strptr (result->elf, ehdr->e_shstrndx, + shdr->sh_name); + if (scnname == NULL) + { + /* The section name must be valid. Otherwise is the ELF file + invalid. */ + __libdw_seterrno (DWARF_E_INVALID_ELF); + free (result); + return; + } + + + /* Recognize the various sections. Most names start with .debug_. */ + size_t cnt; + for (cnt = 0; cnt < ndwarf_scnnames; ++cnt) + if (strcmp (scnname, dwarf_scnnames[cnt]) == 0) + { + /* Found it. Remember where the data is. */ + if (unlikely (result->sectiondata[cnt] != NULL)) + /* A section appears twice. That's bad. We ignore the section. */ + break; + + /* Get the section data. */ + Elf_Data *data = elf_getdata (scn, NULL); + if (data != NULL && data->d_size != 0) + /* Yep, there is actually data available. */ + result->sectiondata[cnt] = data; + + break; + } +} + + +/* Check whether all the necessary DWARF information is available. */ +static Dwarf * +valid_p (Dwarf *result) +{ + /* We looked at all the sections. Now determine whether all the + sections with debugging information we need are there. + + XXX Which sections are absolutely necessary? Add tests if + necessary. For now we require only .debug_info. Hopefully this + is correct. */ + if (unlikely (result->sectiondata[IDX_debug_info] == NULL)) + { + __libdw_seterrno (DWARF_E_NO_DWARF); + result = NULL; + } + + return result; +} + + +static Dwarf * +global_read (Dwarf *result, Elf *elf, GElf_Ehdr *ehdr, Dwarf_Cmd cmd) +{ + Elf_Scn *scn = NULL; + + while ((scn = elf_nextscn (elf, scn)) != NULL) + check_section (result, ehdr, scn, false); + + return valid_p (result); +} + + +static Dwarf * +scngrp_read (Dwarf *result, Elf *elf, GElf_Ehdr *ehdr, Dwarf_Cmd cmd, + Elf_Scn *scngrp) +{ + /* SCNGRP is the section descriptor for a section group which might + contain debug sections. */ + Elf_Data *data = elf_getdata (scngrp, NULL); + if (data == NULL) + { + /* We cannot read the section content. Fail! */ + free (result); + return NULL; + } + + /* The content of the section is a number of 32-bit words which + represent section indices. The first word is a flag word. */ + Elf32_Word *scnidx = (Elf32_Word *) data->d_buf; + size_t cnt; + for (cnt = 1; cnt * sizeof (Elf32_Word) <= data->d_size; ++cnt) + { + Elf_Scn *scn = elf_getscn (elf, scnidx[cnt]); + if (scn == NULL) + { + /* A section group refers to a non-existing section. Should + never happen. */ + __libdw_seterrno (DWARF_E_INVALID_ELF); + free (result); + return NULL; + } + + check_section (result, ehdr, scn, true); + } + + return valid_p (result); +} + + +Dwarf * +dwarf_begin_elf (elf, cmd, scngrp) + Elf *elf; + Dwarf_Cmd cmd; + Elf_Scn *scngrp; +{ + GElf_Ehdr *ehdr; + GElf_Ehdr ehdr_mem; + + /* Get the ELF header of the file. We need various pieces of + information from it. */ + ehdr = gelf_getehdr (elf, &ehdr_mem); + if (ehdr == NULL) + { + if (elf_kind (elf) != ELF_K_ELF) + __libdw_seterrno (DWARF_E_NOELF); + else + __libdw_seterrno (DWARF_E_GETEHDR_ERROR); + + return NULL; + } + + + /* Default memory allocation size. */ + size_t mem_default_size = sysconf (_SC_PAGESIZE) - 4 * sizeof (void *); + + /* Allocate the data structure. */ + Dwarf *result = (Dwarf *) calloc (1, sizeof (Dwarf) + mem_default_size); + if (result == NULL) + { + __libdw_seterrno (DWARF_E_NOMEM); + return NULL; + } + + /* Fill in some values. */ + if ((BYTE_ORDER == LITTLE_ENDIAN && ehdr->e_ident[EI_DATA] == ELFDATA2MSB) + || (BYTE_ORDER == BIG_ENDIAN && ehdr->e_ident[EI_DATA] == ELFDATA2LSB)) + result->other_byte_order = true; + + result->elf = elf; + + /* Initialize the memory handling. */ + result->mem_default_size = mem_default_size; + result->oom_handler = __libdw_oom; + result->mem_tail = (struct libdw_memblock *) (result + 1); + result->mem_tail->size = (result->mem_default_size + - offsetof (struct libdw_memblock, mem)); + result->mem_tail->remaining = result->mem_tail->size; + result->mem_tail->prev = NULL; + + + if (cmd == DWARF_C_READ || cmd == DWARF_C_RDWR) + { + /* If the caller provides a section group we get the DWARF + sections only from this setion group. Otherwise we search + for the first section with the required name. Further + sections with the name are ignored. The DWARF specification + does not really say this is allowed. */ + if (scngrp == NULL) + return global_read (result, elf, ehdr, cmd); + else + return scngrp_read (result, elf, ehdr, cmd, scngrp); + } + else if (cmd == DWARF_C_WRITE) + { + __libdw_seterrno (DWARF_E_UNIMPL); + free (result); + return NULL; + } + + __libdw_seterrno (DWARF_E_INVALID_CMD); + free (result); + return NULL; +} diff --git a/pool/shard002/C/0059434_drv_generic.c b/pool/shard002/C/0059434_drv_generic.c new file mode 100644 index 0000000000000000000000000000000000000000..7b92b8f58e4aa1f14f5e5929ff96c588e936f523 --- /dev/null +++ b/pool/shard002/C/0059434_drv_generic.c @@ -0,0 +1,115 @@ +/* $Id$ + * $URL$ + * + * generic driver helper + * + * Copyright (C) 2006 Michael Reinelt + * Copyright (C) 2006 The LCD4Linux Team + * + * This file is part of LCD4Linux. + * + * LCD4Linux 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. + * + * LCD4Linux 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. + * + */ + +/* + * + * exported functions: + * + * drv_generic_init (void) + * initializes generic stuff and registers plugins + * + */ + + +#include "config.h" + +#include +#include +#include + +#include "debug.h" +#include "plugin.h" +#include "drv_generic.h" + +#ifdef WITH_DMALLOC +#include +#endif + +/* these values are chars (text displays) or pixels (graphic displays) */ + +int LROWS = 0; /* layout size: rows */ +int LCOLS = 0; /* layout size: columns */ + +int DROWS = 4; /* display size: rows */ +int DCOLS = 20; /* display size: columns */ + +int XRES = 6; /* pixel widtht of one char */ +int YRES = 8; /* pixel height of one char */ + + +void (*drv_generic_blit) () = NULL; + + +static void my_drows(RESULT * result) +{ + double value = DROWS; + SetResult(&result, R_NUMBER, &value); +} + +static void my_dcols(RESULT * result) +{ + double value = DCOLS; + SetResult(&result, R_NUMBER, &value); +} + +static void my_xres(RESULT * result) +{ + double value = XRES; + SetResult(&result, R_NUMBER, &value); +} + +static void my_yres(RESULT * result) +{ + double value = YRES; + SetResult(&result, R_NUMBER, &value); +} + +static void my_lrows(RESULT * result) +{ + double value = LROWS; + SetResult(&result, R_NUMBER, &value); +} + +static void my_lcols(RESULT * result) +{ + double value = LCOLS; + SetResult(&result, R_NUMBER, &value); +} + +int drv_generic_init(void) +{ + + AddFunction("LCD::height", 0, my_drows); + AddFunction("LCD::width", 0, my_dcols); + + AddFunction("LCD::xres", 0, my_xres); + AddFunction("LCD::yres", 0, my_yres); + + AddFunction("Layout::height", 0, my_lrows); + AddFunction("Layout::width", 0, my_lcols); + + return 0; +} diff --git a/pool/shard002/C/0059435_t_snapshot.c b/pool/shard002/C/0059435_t_snapshot.c new file mode 100644 index 0000000000000000000000000000000000000000..8b5708f843a38277e6834ff820898157188c7b6b --- /dev/null +++ b/pool/shard002/C/0059435_t_snapshot.c @@ -0,0 +1,51 @@ +/* $NetBSD: t_snapshot.c,v 1.3 2014/06/10 13:15:18 martin Exp $ */ + +#include +#include + +#include +#include + +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +#include "../../h_macros.h" + +#define IMGNAME "msdosfs.img" +#define NEWFS "newfs_msdos -C 5M " IMGNAME +#define FSCK "fsck_msdos -fn" +#define BAKNAME "/stor/snap" + +static void +mount_diskfs(const char *fspec, const char *path) +{ + struct msdosfs_args margs; + + memset(&margs, 0, sizeof(margs)); + margs.fspec = __UNCONST(fspec); + margs.version = MSDOSFSMNT_VERSION; + + if (rump_sys_mount(MOUNT_MSDOS, path, 0, &margs, sizeof(margs)) == -1) + err(1, "mount msdosfs %s", path); +} + +static void +begin(void) +{ + struct tmpfs_args targs = { .ta_version = TMPFS_ARGS_VERSION, }; + + if (rump_sys_mkdir("/stor", 0777) == -1) + atf_tc_fail_errno("mkdir /stor"); + if (rump_sys_mount(MOUNT_TMPFS, "/stor", 0, &targs,sizeof(targs)) == -1) + atf_tc_fail_errno("mount storage"); +} + +#include "../common/snapshot.c" diff --git a/pool/shard002/C/0059436_open.c b/pool/shard002/C/0059436_open.c new file mode 100644 index 0000000000000000000000000000000000000000..db8d92e669da17175c775a53faadb7426951de93 --- /dev/null +++ b/pool/shard002/C/0059436_open.c @@ -0,0 +1,184 @@ +/* + * Copyright (C) 2007 Michael 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 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., 675 Mass Ave, Cambridge, MA 02139, USA. + */ + +#include +#include +#include +#include +#include +#include +#include + +/** @file + * + * Data transfer interface opening + * + */ + +/** Registered URI openers */ +static struct uri_opener uri_openers[0] + __table_start ( struct uri_opener, uri_openers ); +static struct uri_opener uri_openers_end[0] + __table_end ( struct uri_opener, uri_openers ); + +/** Registered socket openers */ +static struct socket_opener socket_openers[0] + __table_start ( struct socket_opener, socket_openers ); +static struct socket_opener socket_openers_end[0] + __table_end ( struct socket_opener, socket_openers ); + +/** + * Open URI + * + * @v xfer Data transfer interface + * @v uri URI + * @ret rc Return status code + * + * The URI will be regarded as being relative to the current working + * URI (see churi()). + */ +int xfer_open_uri ( struct xfer_interface *xfer, struct uri *uri ) { + struct uri_opener *opener; + struct uri *resolved_uri; + int rc = -ENOTSUP; + + /* Resolve URI */ + resolved_uri = resolve_uri ( cwuri, uri ); + if ( ! resolved_uri ) + return -ENOMEM; + + /* Find opener which supports this URI scheme */ + for ( opener = uri_openers ; opener < uri_openers_end ; opener++ ) { + if ( strcmp ( resolved_uri->scheme, opener->scheme ) == 0 ) { + rc = opener->open ( xfer, resolved_uri ); + goto done; + } + } + DBGC ( xfer, "XFER %p attempted to open unsupported URI scheme " + "\"%s\"\n", xfer, resolved_uri->scheme ); + + done: + uri_put ( resolved_uri ); + return rc; +} + +/** + * Open URI string + * + * @v xfer Data transfer interface + * @v uri_string URI string (e.g. "http://etherboot.org/kernel") + * @ret rc Return status code + * + * The URI will be regarded as being relative to the current working + * URI (see churi()). + */ +int xfer_open_uri_string ( struct xfer_interface *xfer, + const char *uri_string ) { + struct uri *uri; + int rc; + + DBGC ( xfer, "XFER %p opening URI %s\n", xfer, uri_string ); + + uri = parse_uri ( uri_string ); + if ( ! uri ) + return -ENOMEM; + + rc = xfer_open_uri ( xfer, uri ); + + uri_put ( uri ); + return rc; +} + +/** + * Open socket + * + * @v xfer Data transfer interface + * @v semantics Communication semantics (e.g. SOCK_STREAM) + * @v peer Peer socket address + * @v local Local socket address, or NULL + * @ret rc Return status code + */ +int xfer_open_socket ( struct xfer_interface *xfer, int semantics, + struct sockaddr *peer, struct sockaddr *local ) { + struct socket_opener *opener; + + DBGC ( xfer, "XFER %p opening (%s,%s) socket\n", xfer, + socket_semantics_name ( semantics ), + socket_family_name ( peer->sa_family ) ); + + for ( opener = socket_openers; opener < socket_openers_end; opener++ ){ + if ( ( opener->semantics == semantics ) && + ( opener->family == peer->sa_family ) ) { + return opener->open ( xfer, peer, local ); + } + } + + DBGC ( xfer, "XFER %p attempted to open unsupported socket type " + "(%s,%s)\n", xfer, socket_semantics_name ( semantics ), + socket_family_name ( peer->sa_family ) ); + return -ENOTSUP; +} + +/** + * Open location + * + * @v xfer Data transfer interface + * @v type Location type + * @v args Remaining arguments depend upon location type + * @ret rc Return status code + */ +int xfer_vopen ( struct xfer_interface *xfer, int type, va_list args ) { + switch ( type ) { + case LOCATION_URI_STRING: { + const char *uri_string = va_arg ( args, const char * ); + + return xfer_open_uri_string ( xfer, uri_string ); } + case LOCATION_URI: { + struct uri *uri = va_arg ( args, struct uri * ); + + return xfer_open_uri ( xfer, uri ); } + case LOCATION_SOCKET: { + int semantics = va_arg ( args, int ); + struct sockaddr *peer = va_arg ( args, struct sockaddr * ); + struct sockaddr *local = va_arg ( args, struct sockaddr * ); + + return xfer_open_socket ( xfer, semantics, peer, local ); } + default: + DBGC ( xfer, "XFER %p attempted to open unsupported location " + "type %d\n", xfer, type ); + return -ENOTSUP; + } +} + +/** + * Open location + * + * @v xfer Data transfer interface + * @v type Location type + * @v ... Remaining arguments depend upon location type + * @ret rc Return status code + */ +int xfer_open ( struct xfer_interface *xfer, int type, ... ) { + va_list args; + int rc; + + va_start ( args, type ); + rc = xfer_vopen ( xfer, type, args ); + va_end ( args ); + return rc; +} diff --git a/pool/shard002/C/0059438_big5.c b/pool/shard002/C/0059438_big5.c new file mode 100644 index 0000000000000000000000000000000000000000..8629e582ea3c34a52eee443837568dc5051e5a90 --- /dev/null +++ b/pool/shard002/C/0059438_big5.c @@ -0,0 +1,180 @@ +/*- + * Copyright (c) 2002-2004 Tim J. Robbins. All rights reserved. + * Copyright (c) 1993 + * The Regents of the University of California. All rights reserved. + * + * This code is derived from software contributed to Berkeley by + * Paul Borman at Krystal Technologies. + * + * Copyright (c) 2011 The FreeBSD Foundation + * All rights reserved. + * Portions of this software were developed by David Chisnall + * under sponsorship from the FreeBSD Foundation. + * + * 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. + */ + +#if defined(LIBC_SCCS) && !defined(lint) +static char sccsid[] = "@(#)big5.c 8.1 (Berkeley) 6/4/93"; +#endif /* LIBC_SCCS and not lint */ +#include +__FBSDID("$FreeBSD: soc2013/dpl/head/lib/libc/locale/big5.c 228034 2011-11-20 14:45:42Z theraven $"); + +#include +#include +#include +#include +#include +#include +#include "mblocal.h" + +extern int __mb_sb_limit; + +static size_t _BIG5_mbrtowc(wchar_t * __restrict, const char * __restrict, + size_t, mbstate_t * __restrict); +static int _BIG5_mbsinit(const mbstate_t *); +static size_t _BIG5_wcrtomb(char * __restrict, wchar_t, + mbstate_t * __restrict); + +typedef struct { + wchar_t ch; +} _BIG5State; + +int +_BIG5_init(struct xlocale_ctype *l, _RuneLocale *rl) +{ + + l->__mbrtowc = _BIG5_mbrtowc; + l->__wcrtomb = _BIG5_wcrtomb; + l->__mbsinit = _BIG5_mbsinit; + l->runes = rl; + l->__mb_cur_max = 2; + l->__mb_sb_limit = 128; + return (0); +} + +static int +_BIG5_mbsinit(const mbstate_t *ps) +{ + + return (ps == NULL || ((const _BIG5State *)ps)->ch == 0); +} + +static __inline int +_big5_check(u_int c) +{ + + c &= 0xff; + return ((c >= 0xa1 && c <= 0xfe) ? 2 : 1); +} + +static size_t +_BIG5_mbrtowc(wchar_t * __restrict pwc, const char * __restrict s, size_t n, + mbstate_t * __restrict ps) +{ + _BIG5State *bs; + wchar_t wc; + size_t len; + + bs = (_BIG5State *)ps; + + if ((bs->ch & ~0xFF) != 0) { + /* Bad conversion state. */ + errno = EINVAL; + return ((size_t)-1); + } + + if (s == NULL) { + s = ""; + n = 1; + pwc = NULL; + } + + if (n == 0) + /* Incomplete multibyte sequence */ + return ((size_t)-2); + + if (bs->ch != 0) { + if (*s == '\0') { + errno = EILSEQ; + return ((size_t)-1); + } + wc = (bs->ch << 8) | (*s & 0xFF); + if (pwc != NULL) + *pwc = wc; + bs->ch = 0; + return (1); + } + + len = (size_t)_big5_check(*s); + wc = *s++ & 0xff; + if (len == 2) { + if (n < 2) { + /* Incomplete multibyte sequence */ + bs->ch = wc; + return ((size_t)-2); + } + if (*s == '\0') { + errno = EILSEQ; + return ((size_t)-1); + } + wc = (wc << 8) | (*s++ & 0xff); + if (pwc != NULL) + *pwc = wc; + return (2); + } else { + if (pwc != NULL) + *pwc = wc; + return (wc == L'\0' ? 0 : 1); + } +} + +static size_t +_BIG5_wcrtomb(char * __restrict s, wchar_t wc, mbstate_t * __restrict ps) +{ + _BIG5State *bs; + + bs = (_BIG5State *)ps; + + if (bs->ch != 0) { + errno = EINVAL; + return ((size_t)-1); + } + + if (s == NULL) + /* Reset to initial shift state (no-op) */ + return (1); + if (wc & 0x8000) { + *s++ = (wc >> 8) & 0xff; + *s = wc & 0xff; + return (2); + } + *s = wc & 0xff; + return (1); +} diff --git a/pool/shard002/C/0059442_interface.c b/pool/shard002/C/0059442_interface.c new file mode 100644 index 0000000000000000000000000000000000000000..c6c5c4d8cdda631fdc1558319db0c0cf6482843a --- /dev/null +++ b/pool/shard002/C/0059442_interface.c @@ -0,0 +1,121 @@ +/* + * DO NOT EDIT THIS FILE - it is generated by Glade. + */ + +#ifdef HAVE_CONFIG_H +# include +#endif + +#include +#include +#include +#include +#include + +#include +#include + +#include "callbacks.h" +#include "interface.h" +#include "support.h" + +#define GLADE_HOOKUP_OBJECT(component,widget,name) \ + g_object_set_data_full (G_OBJECT (component), name, \ + gtk_widget_ref (widget), (GDestroyNotify) gtk_widget_unref) + +#define GLADE_HOOKUP_OBJECT_NO_REF(component,widget,name) \ + g_object_set_data (G_OBJECT (component), name, widget) + +GtkWidget * +create_mainWindow (void) +{ + GtkWidget *mainWindow; + GtkWidget *vbox1; + GtkWidget *timeEntry; + GtkWidget *hbox1; + GtkWidget *startButton; + GtkWidget *image1; + GtkWidget *stopButton; + GtkWidget *image2; + GtkWidget *scrolledwindow1; + GtkWidget *historyView; + + mainWindow = gtk_window_new (GTK_WINDOW_TOPLEVEL); + gtk_widget_set_name (mainWindow, "mainWindow"); + gtk_window_set_title (GTK_WINDOW (mainWindow), Q_ ("gstpw - stopwatch")); + gtk_window_set_default_size (GTK_WINDOW (mainWindow), 200, 250); + + vbox1 = gtk_vbox_new (FALSE, 0); + gtk_widget_set_name (vbox1, "vbox1"); + gtk_widget_show (vbox1); + gtk_container_add (GTK_CONTAINER (mainWindow), vbox1); + + timeEntry = gtk_entry_new (); + gtk_widget_set_name (timeEntry, "timeEntry"); + gtk_widget_show (timeEntry); + gtk_box_pack_start (GTK_BOX (vbox1), timeEntry, FALSE, TRUE, 0); + GTK_WIDGET_UNSET_FLAGS (timeEntry, GTK_CAN_FOCUS); + gtk_editable_set_editable (GTK_EDITABLE (timeEntry), FALSE); + gtk_entry_set_invisible_char (GTK_ENTRY (timeEntry), 9679); + + hbox1 = gtk_hbox_new (FALSE, 0); + gtk_widget_set_name (hbox1, "hbox1"); + gtk_widget_show (hbox1); + gtk_box_pack_start (GTK_BOX (vbox1), hbox1, FALSE, TRUE, 0); + + startButton = gtk_toggle_button_new (); + gtk_widget_set_name (startButton, "startButton"); + gtk_widget_show (startButton); + gtk_box_pack_start (GTK_BOX (hbox1), startButton, TRUE, TRUE, 0); + + image1 = gtk_image_new_from_stock ("gtk-media-play", GTK_ICON_SIZE_BUTTON); + gtk_widget_set_name (image1, "image1"); + gtk_widget_show (image1); + gtk_container_add (GTK_CONTAINER (startButton), image1); + + stopButton = gtk_button_new (); + gtk_widget_set_name (stopButton, "stopButton"); + gtk_widget_show (stopButton); + gtk_box_pack_start (GTK_BOX (hbox1), stopButton, TRUE, TRUE, 0); + + image2 = gtk_image_new_from_stock ("gtk-media-stop", GTK_ICON_SIZE_BUTTON); + gtk_widget_set_name (image2, "image2"); + gtk_widget_show (image2); + gtk_container_add (GTK_CONTAINER (stopButton), image2); + + scrolledwindow1 = gtk_scrolled_window_new (NULL, NULL); + gtk_scrolled_window_set_policy (GTK_SCROLLED_WINDOW (scrolledwindow1), + GTK_POLICY_AUTOMATIC, GTK_POLICY_AUTOMATIC); + gtk_widget_set_name (scrolledwindow1, "scrolledwindow1"); + gtk_widget_show (scrolledwindow1); + gtk_box_pack_start (GTK_BOX (vbox1), scrolledwindow1, TRUE, TRUE, 0); + gtk_scrolled_window_set_shadow_type (GTK_SCROLLED_WINDOW (scrolledwindow1), + GTK_SHADOW_IN); + + historyView = gtk_tree_view_new (); + gtk_widget_set_name (historyView, "historyView"); + gtk_widget_show (historyView); + gtk_container_add (GTK_CONTAINER (scrolledwindow1), historyView); + gtk_tree_view_set_reorderable (GTK_TREE_VIEW (historyView), TRUE); + + g_signal_connect ((gpointer) mainWindow, "destroy", + G_CALLBACK (on_mainWindow_destroy), NULL); + g_signal_connect ((gpointer) startButton, "toggled", + G_CALLBACK (on_startButton_toggled), NULL); + g_signal_connect ((gpointer) stopButton, "clicked", + G_CALLBACK (on_stopButton_clicked), NULL); + + /* Store pointers to all widgets, for use by lookup_widget(). */ + GLADE_HOOKUP_OBJECT_NO_REF (mainWindow, mainWindow, "mainWindow"); + GLADE_HOOKUP_OBJECT (mainWindow, vbox1, "vbox1"); + GLADE_HOOKUP_OBJECT (mainWindow, timeEntry, "timeEntry"); + GLADE_HOOKUP_OBJECT (mainWindow, hbox1, "hbox1"); + GLADE_HOOKUP_OBJECT (mainWindow, startButton, "startButton"); + GLADE_HOOKUP_OBJECT (mainWindow, image1, "image1"); + GLADE_HOOKUP_OBJECT (mainWindow, stopButton, "stopButton"); + GLADE_HOOKUP_OBJECT (mainWindow, image2, "image2"); + GLADE_HOOKUP_OBJECT (mainWindow, scrolledwindow1, "scrolledwindow1"); + GLADE_HOOKUP_OBJECT (mainWindow, historyView, "historyView"); + + return mainWindow; +} diff --git a/pool/shard002/C/0059456_zlarf.c b/pool/shard002/C/0059456_zlarf.c new file mode 100644 index 0000000000000000000000000000000000000000..697c5fd0af02ea345a07372c73152473d1bfbca5 --- /dev/null +++ b/pool/shard002/C/0059456_zlarf.c @@ -0,0 +1,199 @@ +/* zlarf.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 "pnl/pnl_f2c.h" + +/* Table of constant values */ + +static doublecomplex c_b1 = {1.,0.}; +static doublecomplex c_b2 = {0.,0.}; +static int c__1 = 1; + + int zlarf_(char *side, int *m, int *n, doublecomplex + *v, int *incv, doublecomplex *tau, doublecomplex *c__, int * + ldc, doublecomplex *work) +{ + /* System generated locals */ + int c_dim1, c_offset, i__1; + doublecomplex z__1; + + /* Local variables */ + int i__; + int applyleft; + extern int lsame_(char *, char *); + int lastc; + extern int zgerc_(int *, int *, doublecomplex *, + doublecomplex *, int *, doublecomplex *, int *, + doublecomplex *, int *), zgemv_(char *, int *, int *, + doublecomplex *, doublecomplex *, int *, doublecomplex *, + int *, doublecomplex *, doublecomplex *, int *); + int lastv; + extern int ilazlc_(int *, int *, doublecomplex *, int *), + ilazlr_(int *, int *, doublecomplex *, int *); + + +/* -- LAPACK auxiliary routine (version 3.2) -- */ +/* Univ. of Tennessee, Univ. of California Berkeley and NAG Ltd.. */ +/* November 2006 */ + +/* .. Scalar Arguments .. */ +/* .. */ +/* .. Array Arguments .. */ +/* .. */ + +/* Purpose */ +/* ======= */ + +/* ZLARF applies a complex elementary reflector H to a complex M-by-N */ +/* matrix C, from either the left or the right. H is represented in the */ +/* form */ + +/* H = I - tau * v * v' */ + +/* where tau is a complex scalar and v is a complex vector. */ + +/* If tau = 0, then H is taken to be the unit matrix. */ + +/* To apply H' (the conjugate transpose of H), supply conjg(tau) instead */ +/* tau. */ + +/* Arguments */ +/* ========= */ + +/* SIDE (input) CHARACTER*1 */ +/* = 'L': form H * C */ +/* = 'R': form C * H */ + +/* M (input) INTEGER */ +/* The number of rows of the matrix C. */ + +/* N (input) INTEGER */ +/* The number of columns of the matrix C. */ + +/* V (input) COMPLEX*16 array, dimension */ +/* (1 + (M-1)*ABS(INCV)) if SIDE = 'L' */ +/* or (1 + (N-1)*ABS(INCV)) if SIDE = 'R' */ +/* The vector v in the representation of H. V is not used if */ +/* TAU = 0. */ + +/* INCV (input) INTEGER */ +/* The increment between elements of v. INCV <> 0. */ + +/* TAU (input) COMPLEX*16 */ +/* The value tau in the representation of H. */ + +/* C (input/output) COMPLEX*16 array, dimension (LDC,N) */ +/* On entry, the M-by-N matrix C. */ +/* On exit, C is overwritten by the matrix H * C if SIDE = 'L', */ +/* or C * H if SIDE = 'R'. */ + +/* LDC (input) INTEGER */ +/* The leading dimension of the array C. LDC >= MAX(1,M). */ + +/* WORK (workspace) COMPLEX*16 array, dimension */ +/* (N) if SIDE = 'L' */ +/* or (M) if SIDE = 'R' */ + +/* ===================================================================== */ + +/* .. Parameters .. */ +/* .. */ +/* .. Local Scalars .. */ +/* .. */ +/* .. External Subroutines .. */ +/* .. */ +/* .. External Functions .. */ +/* .. */ +/* .. Executable Statements .. */ + + /* Parameter adjustments */ + --v; + c_dim1 = *ldc; + c_offset = 1 + c_dim1; + c__ -= c_offset; + --work; + + /* Function Body */ + applyleft = lsame_(side, "L"); + lastv = 0; + lastc = 0; + if (tau->r != 0. || tau->i != 0.) { +/* Set up variables for scanning V. LASTV begins pointing to the end */ +/* of V. */ + if (applyleft) { + lastv = *m; + } else { + lastv = *n; + } + if (*incv > 0) { + i__ = (lastv - 1) * *incv + 1; + } else { + i__ = 1; + } +/* Look for the last non-zero row in V. */ + for(;;) { /* while(complicated condition) */ + i__1 = i__; + if (!(lastv > 0 && (v[i__1].r == 0. && v[i__1].i == 0.))) + break; + --lastv; + i__ -= *incv; + } + if (applyleft) { +/* Scan for the last non-zero column in C(1:lastv,:). */ + lastc = ilazlc_(&lastv, n, &c__[c_offset], ldc); + } else { +/* Scan for the last non-zero row in C(:,1:lastv). */ + lastc = ilazlr_(m, &lastv, &c__[c_offset], ldc); + } + } +/* Note that lastc.eq.0 renders the BLAS operations null; no special */ +/* case is needed at this level. */ + if (applyleft) { + +/* Form H * C */ + + if (lastv > 0) { + +/* w(1:lastc,1) := C(1:lastv,1:lastc)' * v(1:lastv,1) */ + + zgemv_("Conjugate transpose", &lastv, &lastc, &c_b1, &c__[ + c_offset], ldc, &v[1], incv, &c_b2, &work[1], &c__1); + +/* C(1:lastv,1:lastc) := C(...) - v(1:lastv,1) * w(1:lastc,1)' */ + + z__1.r = -tau->r, z__1.i = -tau->i; + zgerc_(&lastv, &lastc, &z__1, &v[1], incv, &work[1], &c__1, &c__[ + c_offset], ldc); + } + } else { + +/* Form C * H */ + + if (lastv > 0) { + +/* w(1:lastc,1) := C(1:lastc,1:lastv) * v(1:lastv,1) */ + + zgemv_("No transpose", &lastc, &lastv, &c_b1, &c__[c_offset], ldc, + &v[1], incv, &c_b2, &work[1], &c__1); + +/* C(1:lastc,1:lastv) := C(...) - w(1:lastc,1) * v(1:lastv,1)' */ + + z__1.r = -tau->r, z__1.i = -tau->i; + zgerc_(&lastc, &lastv, &z__1, &work[1], &c__1, &v[1], incv, &c__[ + c_offset], ldc); + } + } + return 0; + +/* End of ZLARF */ + +} /* zlarf_ */ diff --git a/pool/shard002/C/0059463_tty_tty.c b/pool/shard002/C/0059463_tty_tty.c new file mode 100644 index 0000000000000000000000000000000000000000..e1e0beca4615f12bd0e9d5cfca19649d3baf8503 --- /dev/null +++ b/pool/shard002/C/0059463_tty_tty.c @@ -0,0 +1,94 @@ +/*- + * Copyright (c) 2003 Poul-Henning Kamp. 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 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. + */ + +#include +__FBSDID("$FreeBSD: releng/9.3/sys/kern/tty_tty.c 216952 2011-01-04 10:59:38Z kib $"); + +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +static d_open_t cttyopen; + +static struct cdevsw ctty_cdevsw = { + .d_version = D_VERSION, + .d_open = cttyopen, + .d_name = "ctty", +}; + +static struct cdev *ctty; + +static int +cttyopen(struct cdev *dev, int flag, int mode, struct thread *td) +{ + + return (ENXIO); +} + +static void +ctty_clone(void *arg, struct ucred *cred, char *name, int namelen, + struct cdev **dev) +{ + + if (*dev != NULL) + return; + if (strcmp(name, "tty")) + return; + sx_sunlock(&clone_drain_lock); + sx_slock(&proctree_lock); + sx_slock(&clone_drain_lock); + dev_lock(); + if (!(curthread->td_proc->p_flag & P_CONTROLT)) + *dev = ctty; + else if (curthread->td_proc->p_session->s_ttyvp == NULL) + *dev = ctty; + else if (curthread->td_proc->p_session->s_ttyvp->v_type == VBAD || + curthread->td_proc->p_session->s_ttyvp->v_rdev == NULL) { + /* e.g. s_ttyvp was revoked */ + *dev = ctty; + } else + *dev = curthread->td_proc->p_session->s_ttyvp->v_rdev; + dev_refl(*dev); + dev_unlock(); + sx_sunlock(&proctree_lock); +} + +static void +ctty_drvinit(void *unused) +{ + + EVENTHANDLER_REGISTER(dev_clone, ctty_clone, 0, 1000); + ctty = make_dev_credf(MAKEDEV_ETERNAL, &ctty_cdevsw, 0, NULL, UID_ROOT, + GID_WHEEL, 0666, "ctty"); +} + +SYSINIT(cttydev,SI_SUB_DRIVERS,SI_ORDER_MIDDLE,ctty_drvinit,NULL); diff --git a/pool/shard002/C/0059468_time.c b/pool/shard002/C/0059468_time.c new file mode 100644 index 0000000000000000000000000000000000000000..4897cd2b21490672bea554c2e1388e727dca70b4 --- /dev/null +++ b/pool/shard002/C/0059468_time.c @@ -0,0 +1,89 @@ +/* + * Copyright 2010-2018 Amazon.com, Inc. or its affiliates. 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. + * A copy of the License is located at + * + * http://aws.amazon.com/apache2.0 + * + * or in the "license" file accompanying this file. This file 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 + +#if defined(__ANDROID__) && !defined(__LP64__) +/* + * This branch brought to you by the kind folks at google chromium. It's been modified a bit, but + * gotta give credit where it's due.... I'm not a lawyer so I'm just gonna drop their copyright + * notification here to avoid all of that. + */ + +/* + * Copyright 2014 The Chromium Authors. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following disclaimer + * in the documentation and/or other materials provided with the + * distribution. + * Neither the name of Google Inc. nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + * From src/base/os_compat_android.cc: + */ +# include + +static const time_t s_time_max = ~(1L << ((sizeof(time_t) * __CHAR_BIT__ - 1))); +static const time_t s_time_min = (1L << ((sizeof(time_t)) * __CHAR_BIT__ - 1)); + +/* 32-bit Android has only timegm64() and not timegm(). */ +time_t aws_timegm(struct tm *const t) { + + time64_t result = timegm64(t); + if (result < s_time_min || result > s_time_max) { + return -1; + } + return (time_t)result; +} + +#else + +# ifndef __APPLE__ +/* glibc.... you disappoint me.. */ +extern time_t timegm(struct tm *); +# endif + +time_t aws_timegm(struct tm *const t) { + return timegm(t); +} + +#endif /* defined(__ANDROID__) && !defined(__LP64__) */ + +void aws_localtime(time_t time, struct tm *t) { + localtime_r(&time, t); +} + +void aws_gmtime(time_t time, struct tm *t) { + gmtime_r(&time, t); +} diff --git a/pool/shard002/C/0059481_time_bench_kmem_cache1.c b/pool/shard002/C/0059481_time_bench_kmem_cache1.c new file mode 100644 index 0000000000000000000000000000000000000000..61def29940a4a1205c9ecf4c3e77f6e97b8fb710 --- /dev/null +++ b/pool/shard002/C/0059481_time_bench_kmem_cache1.c @@ -0,0 +1,86 @@ +/* + * Benchmarking kmem_cache slab/slub + */ +#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt + +#include +#include +#include +#include +#include + +static int verbose=1; + +struct my_elem { + /* element used for benchmark testing */ + struct sk_buff skb; +}; + +/* For comparison benchmark against the fastpath of the + * slab/kmem_cache allocator + */ +static int benchmark_kmem_cache_fastpath_reuse( + struct time_bench_record *rec, void *data) +{ + uint64_t loops_cnt = 0; + int i; + struct my_elem *elem; + struct kmem_cache *slab; + + slab = kmem_cache_create("time_bench_test1", sizeof(struct my_elem), + 0, SLAB_HWCACHE_ALIGN, NULL); + time_bench_start(rec); + /** Loop to measure **/ + for (i = 0; i < rec->loops; i++) { + + /* request new elem */ + elem = kmem_cache_alloc(slab, GFP_ATOMIC); + if (elem == NULL) + goto out; + + barrier(); /* compiler barrier */ + + /* return elem */ + kmem_cache_free(slab, elem); + loops_cnt++; + } +out: + time_bench_stop(rec, loops_cnt); + /* cleanup */ + kmem_cache_destroy(slab); + return loops_cnt; +} + +int run_timing_tests(void) +{ + uint32_t loops = 100000000; + + time_bench_loop(loops, 0, "kmem fastpath reuse", NULL, + benchmark_kmem_cache_fastpath_reuse); + + return 0; +} + +static int __init time_bench_sample_module_init(void) +{ + if (verbose) + pr_info("Loaded\n"); + + if (run_timing_tests() < 0) { + return -ECANCELED; + } + + return 0; +} +module_init(time_bench_sample_module_init); + +static void __exit time_bench_sample_module_exit(void) +{ + if (verbose) + pr_info("Unloaded\n"); +} +module_exit(time_bench_sample_module_exit); + +MODULE_DESCRIPTION("Benchmark kmem_cache/slab/slub"); +MODULE_AUTHOR("Jesper Dangaard Brouer "); +MODULE_LICENSE("GPL"); diff --git a/pool/shard002/C/0059483_paramNodeList.c b/pool/shard002/C/0059483_paramNodeList.c new file mode 100644 index 0000000000000000000000000000000000000000..cf1093f304f4a38c7849918e9d6647c179fa030c --- /dev/null +++ b/pool/shard002/C/0059483_paramNodeList.c @@ -0,0 +1,167 @@ +/* +** Splint - annotation-assisted static program checker +** Copyright (C) 1994-2003 University of Virginia, +** 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. +** +** The GNU General Public License is available from http://www.gnu.org/ or +** the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, +** MA 02111-1307, USA. +** +** For information on splint: info@splint.org +** To report a bug: splint-bug@splint.org +** For more information: http://www.splint.org +*/ +/* +** paramNodeList.c +** +** based on list_template.c +** +** where T has T_equal (or change this) and T_unparse +*/ + +# include "splintMacros.nf" +# include "basic.h" + +/*@only@*/ paramNodeList +paramNodeList_new () +{ + paramNodeList s = (paramNodeList) dmalloc (sizeof (*s)); + + s->nelements = 0; + s->nspace = paramNodeListBASESIZE; + s->elements = (paramNode *) + dmalloc (sizeof (*s->elements) * paramNodeListBASESIZE); + + return (s); +} + +/*@only@*/ paramNodeList +paramNodeList_single (/*@keep@*/ paramNode p) +{ + paramNodeList s = (paramNodeList) dmalloc (sizeof (*s)); + + s->nelements = 1; + s->nspace = paramNodeListBASESIZE - 1; + s->elements = (paramNode *) dmalloc (sizeof (*s->elements) * paramNodeListBASESIZE); + s->elements[0] = p; + + return (s); +} + +static void +paramNodeList_grow (/*@notnull@*/ paramNodeList s) +{ + int i; + paramNode *newelements; + + s->nspace += paramNodeListBASESIZE; + + newelements = (paramNode *) dmalloc (sizeof (*newelements) + * (s->nelements + s->nspace)); + + for (i = 0; i < s->nelements; i++) + { + newelements[i] = s->elements[i]; + } + + sfree (s->elements); + s->elements = newelements; +} + +paramNodeList +paramNodeList_add (paramNodeList s, paramNode el) +{ + llassert (paramNodeList_isDefined (s)); + + if (s->nspace <= 0) + paramNodeList_grow (s); + + s->nspace--; + s->elements[s->nelements] = el; + + s->nelements++; + return s; +} + +/*@only@*/ paramNodeList +paramNodeList_copy (paramNodeList s) +{ + paramNodeList r = paramNodeList_new (); + + paramNodeList_elements (s, x) + { + r = paramNodeList_add (r, paramNode_copy (x)); + } end_paramNodeList_elements; + + return r; +} + +/*@only@*/ cstring +paramNodeList_unparse (paramNodeList s) +{ + bool first = TRUE; + cstring st = cstring_undefined; + + paramNodeList_elements (s, current) + { + if (first) + { + st = paramNode_unparse (current); + first = FALSE; + } + else + { + st = message ("%q, %q", st, paramNode_unparse (current)); + } + } end_paramNodeList_elements; + + return st; +} + +/*@only@*/ cstring +paramNodeList_unparseComments (paramNodeList s) +{ + bool first = TRUE; + cstring st = cstring_undefined; + + paramNodeList_elements (s, current) + { + if (first) + { + st = paramNode_unparseComments (current); + first = FALSE; + } + else + { + st = message ("%q, %q", st, paramNode_unparseComments (current)); + } + } end_paramNodeList_elements; + + return st; +} + +void +paramNodeList_free (/*@only@*/ paramNodeList s) +{ + if (paramNodeList_isDefined (s)) + { + int i; + for (i = 0; i < s->nelements; i++) + { + paramNode_free (s->elements[i]); + } + + sfree (s->elements); + sfree (s); + } +} diff --git a/pool/shard002/C/0059494_point.c b/pool/shard002/C/0059494_point.c new file mode 100644 index 0000000000000000000000000000000000000000..fc079d4ecd56db6e507428d6ab1cd006bf8cfa61 --- /dev/null +++ b/pool/shard002/C/0059494_point.c @@ -0,0 +1,46 @@ +/** +Auteur : Rémi Synave +Mail : synave@labri.fr +Date : 10/10/2006 + **/ + +#include "point.h" + +/** +Initialisation d'un point3d (x,y,z) +@param p pointeur sur un point3d +@param x +@param y +@param z +@return aucun + */ +void +point3d_init(point3d *p, double x, double y, double z) +{ + p->x=x; + p->y=y; + p->z=z; +} + +/** +Affichage d'un point3d +@param p le point +@return aucun +**/ +void +point3d_display(point3d p) +{ + printf("POINT --> (%lf , %lf , %lf)\n",p.x,p.y,p.z); +} + +/** +Teste l'égalité de 2 points +@param p1 premier point +@param p2 second point +@return 1 si p1==p2, 0 sinon + */ +int +point3d_equal(point3d p1, point3d p2) +{ + return(p1.x==p2.x && p1.y==p2.y && p1.z==p2.z); +} diff --git a/pool/shard002/C/0059496_IMG.c b/pool/shard002/C/0059496_IMG.c new file mode 100644 index 0000000000000000000000000000000000000000..74cc3b62c71f5f09fe2a3d6950f4bdee2cd41767 --- /dev/null +++ b/pool/shard002/C/0059496_IMG.c @@ -0,0 +1,239 @@ +/* + SDL_image: An example image loading library for use with SDL + Copyright (C) 1997-2013 Sam Lantinga + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. +*/ + +/* A simple library to load images of various formats as SDL surfaces */ + +#include +#include +#include + +#include "SDL2_image/SDL_image.h" + +#define ARRAYSIZE(a) (sizeof(a) / sizeof((a)[0])) + +/* Table of image detection and loading functions */ +static struct { + char *type; + int (SDLCALL *is)(SDL_RWops *src); + SDL_Surface *(SDLCALL *load)(SDL_RWops *src); +} supported[] = { + /* keep magicless formats first */ + { "TGA", NULL, IMG_LoadTGA_RW }, + { "CUR", IMG_isCUR, IMG_LoadCUR_RW }, + { "ICO", IMG_isICO, IMG_LoadICO_RW }, + { "BMP", IMG_isBMP, IMG_LoadBMP_RW }, + { "GIF", IMG_isGIF, IMG_LoadGIF_RW }, + { "JPG", IMG_isJPG, IMG_LoadJPG_RW }, + { "LBM", IMG_isLBM, IMG_LoadLBM_RW }, + { "PCX", IMG_isPCX, IMG_LoadPCX_RW }, + { "PNG", IMG_isPNG, IMG_LoadPNG_RW }, + { "PNM", IMG_isPNM, IMG_LoadPNM_RW }, /* P[BGP]M share code */ + { "TIF", IMG_isTIF, IMG_LoadTIF_RW }, + { "XCF", IMG_isXCF, IMG_LoadXCF_RW }, + { "XPM", IMG_isXPM, IMG_LoadXPM_RW }, + { "XV", IMG_isXV, IMG_LoadXV_RW }, + { "WEBP", IMG_isWEBP, IMG_LoadWEBP_RW }, +}; + +const SDL_version *IMG_Linked_Version(void) +{ + static SDL_version linked_version; + SDL_IMAGE_VERSION(&linked_version); + return(&linked_version); +} + +extern int IMG_InitJPG(); +extern void IMG_QuitJPG(); +extern int IMG_InitPNG(); +extern void IMG_QuitPNG(); +extern int IMG_InitTIF(); +extern void IMG_QuitTIF(); + +extern int IMG_InitWEBP(); +extern void IMG_QuitWEBP(); + +static int initialized = 0; + +int IMG_Init(int flags) +{ + int result = 0; + + if (flags & IMG_INIT_JPG) { + if ((initialized & IMG_INIT_JPG) || IMG_InitJPG() == 0) { + result |= IMG_INIT_JPG; + } + } + if (flags & IMG_INIT_PNG) { + if ((initialized & IMG_INIT_PNG) || IMG_InitPNG() == 0) { + result |= IMG_INIT_PNG; + } + } + if (flags & IMG_INIT_TIF) { + if ((initialized & IMG_INIT_TIF) || IMG_InitTIF() == 0) { + result |= IMG_INIT_TIF; + } + } + if (flags & IMG_INIT_WEBP) { + if ((initialized & IMG_INIT_WEBP) || IMG_InitWEBP() == 0) { + result |= IMG_INIT_WEBP; + } + } + initialized |= result; + + return (initialized); +} + +void IMG_Quit() +{ + if (initialized & IMG_INIT_JPG) { + IMG_QuitJPG(); + } + if (initialized & IMG_INIT_PNG) { + IMG_QuitPNG(); + } + if (initialized & IMG_INIT_TIF) { + IMG_QuitTIF(); + } + if (initialized & IMG_INIT_WEBP) { + IMG_QuitWEBP(); + } + initialized = 0; +} + +#if !defined(__APPLE__) || defined(SDL_IMAGE_USE_COMMON_BACKEND) +/* Load an image from a file */ +SDL_Surface *IMG_Load(const char *file) +{ + SDL_RWops *src = SDL_RWFromFile(file, "rb"); + const char *ext = strrchr(file, '.'); + if(ext) { + ext++; + } + if(!src) { + /* The error message has been set in SDL_RWFromFile */ + return NULL; + } + return IMG_LoadTyped_RW(src, 1, ext); +} +#endif + +/* Load an image from an SDL datasource (for compatibility) */ +SDL_Surface *IMG_Load_RW(SDL_RWops *src, int freesrc) +{ + return IMG_LoadTyped_RW(src, freesrc, NULL); +} + +/* Portable case-insensitive string compare function */ +static int IMG_string_equals(const char *str1, const char *str2) +{ + while ( *str1 && *str2 ) { + if ( toupper((unsigned char)*str1) != + toupper((unsigned char)*str2) ) + break; + ++str1; + ++str2; + } + return (!*str1 && !*str2); +} + +/* Load an image from an SDL datasource, optionally specifying the type */ +SDL_Surface *IMG_LoadTyped_RW(SDL_RWops *src, int freesrc, const char *type) +{ + int i; + SDL_Surface *image; + + /* Make sure there is something to do.. */ + if ( src == NULL ) { + IMG_SetError("Passed a NULL data source"); + return(NULL); + } + + /* See whether or not this data source can handle seeking */ + if ( SDL_RWseek(src, 0, RW_SEEK_CUR) < 0 ) { + IMG_SetError("Can't seek in this data source"); + if(freesrc) + SDL_RWclose(src); + return(NULL); + } + + /* Detect the type of image being loaded */ + image = NULL; + for ( i=0; i < ARRAYSIZE(supported); ++i ) { + if(supported[i].is) { + if(!supported[i].is(src)) + continue; + } else { + /* magicless format */ + if(!type + || !IMG_string_equals(type, supported[i].type)) + continue; + } +#ifdef DEBUG_IMGLIB + fprintf(stderr, "IMGLIB: Loading image as %s\n", + supported[i].type); +#endif + image = supported[i].load(src); + if(freesrc) + SDL_RWclose(src); + return image; + } + + if ( freesrc ) { + SDL_RWclose(src); + } + IMG_SetError("Unsupported image format"); + return NULL; +} + +#if SDL_VERSION_ATLEAST(2,0,0) +SDL_Texture *IMG_LoadTexture(SDL_Renderer *renderer, const char *file) +{ + SDL_Texture *texture = NULL; + SDL_Surface *surface = IMG_Load(file); + if (surface) { + texture = SDL_CreateTextureFromSurface(renderer, surface); + SDL_FreeSurface(surface); + } + return texture; +} + +SDL_Texture *IMG_LoadTexture_RW(SDL_Renderer *renderer, SDL_RWops *src, int freesrc) +{ + SDL_Texture *texture = NULL; + SDL_Surface *surface = IMG_Load_RW(src, freesrc); + if (surface) { + texture = SDL_CreateTextureFromSurface(renderer, surface); + SDL_FreeSurface(surface); + } + return texture; +} + +SDL_Texture *IMG_LoadTextureTyped_RW(SDL_Renderer *renderer, SDL_RWops *src, int freesrc, const char *type) +{ + SDL_Texture *texture = NULL; + SDL_Surface *surface = IMG_LoadTyped_RW(src, freesrc, type); + if (surface) { + texture = SDL_CreateTextureFromSurface(renderer, surface); + SDL_FreeSurface(surface); + } + return texture; +} +#endif /* SDL 2.0 */ diff --git a/pool/shard002/C/0059505_stm32f3_discovery_accelerometer.c b/pool/shard002/C/0059505_stm32f3_discovery_accelerometer.c new file mode 100644 index 0000000000000000000000000000000000000000..151631de84659aef3b5345dc298f3be5b95e3c90 --- /dev/null +++ b/pool/shard002/C/0059505_stm32f3_discovery_accelerometer.c @@ -0,0 +1,207 @@ +/** + ****************************************************************************** + * @file stm32f3_discovery_accelerometer.c + * @author MCD Application Team + * @version V2.1.1 + * @date 30-December-2014 + * @brief This file provides a set of functions needed to manage the ACCELEROMETER + * MEMS available on STM32F3-Discovery Kit. + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2014 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 "stm32f3_discovery_accelerometer.h" + +/** @addtogroup BSP + * @{ + */ + +/** @addtogroup STM32F3_DISCOVERY + * @{ + */ + +/** @addtogroup STM32F3_DISCOVERY_ACCELEROMETER + * @{ + */ + + +/** @defgroup STM32F3_DISCOVERY_ACCELERO_Private_TypesDefinitions + * @{ + */ + +/** + * @} + */ + +/** @defgroup STM32F3_DISCOVERY_ACCELERO_Private_Defines + * @{ + */ + +/** + * @} + */ + +/** @defgroup STM32F3_DISCOVERY_ACCELERO_Private_Macros + * @{ + */ + +/** + * @} + */ + +/** @defgroup STM32F3_DISCOVERY_ACCELERO_Private_Variables + * @{ + */ +static ACCELERO_DrvTypeDef *AccelerometerDrv; + +/** + * @} + */ + +/** @defgroup STM32F3_DISCOVERY_ACCELERO_Private_FunctionPrototypes + * @{ + */ + +/** + * @} + */ + +/** @defgroup STM32F3_DISCOVERY_ACCELERO_Private_Functions + * @{ + */ + +/** + * @brief Set ACCELEROMETER Initialization. + * @param None + * @retval ACCELERO_OK if no problem during initialization + */ +uint8_t BSP_ACCELERO_Init(void) +{ + uint8_t ret = ACCELERO_ERROR; + uint16_t ctrl = 0x0000; + ACCELERO_InitTypeDef LSM303DLHC_InitStructure; + ACCELERO_FilterConfigTypeDef LSM303DLHC_FilterStructure; + + if(Lsm303dlhcDrv.ReadID() == I_AM_LMS303DLHC) + { + /* Initialize the gyroscope driver structure */ + AccelerometerDrv = &Lsm303dlhcDrv; + + /* MEMS configuration ------------------------------------------------------*/ + /* Fill the accelerometer structure */ + LSM303DLHC_InitStructure.Power_Mode = LSM303DLHC_NORMAL_MODE; + LSM303DLHC_InitStructure.AccOutput_DataRate = LSM303DLHC_ODR_50_HZ; + LSM303DLHC_InitStructure.Axes_Enable= LSM303DLHC_AXES_ENABLE; + LSM303DLHC_InitStructure.AccFull_Scale = LSM303DLHC_FULLSCALE_2G; + LSM303DLHC_InitStructure.BlockData_Update = LSM303DLHC_BlockUpdate_Continous; + LSM303DLHC_InitStructure.Endianness=LSM303DLHC_BLE_LSB; + LSM303DLHC_InitStructure.High_Resolution=LSM303DLHC_HR_ENABLE; + + /* Configure MEMS: data rate, power mode, full scale and axes */ + ctrl |= (LSM303DLHC_InitStructure.Power_Mode | LSM303DLHC_InitStructure.AccOutput_DataRate | \ + LSM303DLHC_InitStructure.Axes_Enable); + + ctrl |= ((LSM303DLHC_InitStructure.BlockData_Update | LSM303DLHC_InitStructure.Endianness | \ + LSM303DLHC_InitStructure.AccFull_Scale | LSM303DLHC_InitStructure.High_Resolution) << 8); + + /* Configure the accelerometer main parameters */ + AccelerometerDrv->Init(ctrl); + + /* Fill the accelerometer LPF structure */ + LSM303DLHC_FilterStructure.HighPassFilter_Mode_Selection =LSM303DLHC_HPM_NORMAL_MODE; + LSM303DLHC_FilterStructure.HighPassFilter_CutOff_Frequency = LSM303DLHC_HPFCF_16; + LSM303DLHC_FilterStructure.HighPassFilter_AOI1 = LSM303DLHC_HPF_AOI1_DISABLE; + LSM303DLHC_FilterStructure.HighPassFilter_AOI2 = LSM303DLHC_HPF_AOI2_DISABLE; + + /* Configure MEMS: mode, cutoff frquency, Filter status, Click, AOI1 and AOI2 */ + ctrl = (uint8_t) (LSM303DLHC_FilterStructure.HighPassFilter_Mode_Selection |\ + LSM303DLHC_FilterStructure.HighPassFilter_CutOff_Frequency|\ + LSM303DLHC_FilterStructure.HighPassFilter_AOI1|\ + LSM303DLHC_FilterStructure.HighPassFilter_AOI2); + + /* Configure the accelerometer LPF main parameters */ + AccelerometerDrv->FilterConfig(ctrl); + + ret = ACCELERO_OK; + } + else + { + ret = ACCELERO_ERROR; + } + + return ret; +} + +/** + * @brief Reboot memory content of ACCELEROMETER + * @param None + * @retval None + */ +void BSP_ACCELERO_Reset(void) + { + if(AccelerometerDrv->Reset != NULL) +{ + AccelerometerDrv->Reset(); +} +} + +/** + * @brief Get XYZ acceleration + * @param pDataXYZ Pointeur on 3 angular accelerations + * pDataXYZ[0] = X axis, pDataXYZ[1] = Y axis, pDataXYZ[2] = Z axis +* @retval None +*/ +void BSP_ACCELERO_GetXYZ(int16_t *pDataXYZ) +{ + if(AccelerometerDrv->GetXYZ!= NULL) + { + AccelerometerDrv->GetXYZ(pDataXYZ); + } +} + + +/** + * @} + */ + +/** + * @} + */ + +/** + * @} + */ + +/** + * @} + */ + + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/pool/shard002/C/0059507_unwind-forcedunwind.c b/pool/shard002/C/0059507_unwind-forcedunwind.c new file mode 100644 index 0000000000000000000000000000000000000000..60dfbe6c92b4314234b6a93e5c6c9f1fd1c35b47 --- /dev/null +++ b/pool/shard002/C/0059507_unwind-forcedunwind.c @@ -0,0 +1,151 @@ +/* Copyright (C) 2003-2012 Free Software Foundation, Inc. + This file is part of the GNU C Library. + Contributed by Jakub Jelinek . + + 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; see the file COPYING.LIB. If + not, see . */ + +#include +#include +#include +#include +#include +#include + +static void *libgcc_s_handle; +static void (*libgcc_s_resume) (struct _Unwind_Exception *exc); +static _Unwind_Reason_Code (*libgcc_s_personality) + (int, _Unwind_Action, _Unwind_Exception_Class, struct _Unwind_Exception *, + struct _Unwind_Context *); +static _Unwind_Reason_Code (*libgcc_s_forcedunwind) + (struct _Unwind_Exception *, _Unwind_Stop_Fn, void *); +static _Unwind_Word (*libgcc_s_getcfa) (struct _Unwind_Context *); + +void +__attribute_noinline__ +pthread_cancel_init (void) +{ + void *resume; + void *personality; + void *forcedunwind; + void *getcfa; + void *handle; + + if (__builtin_expect (libgcc_s_handle != NULL, 1)) + { + /* Force gcc to reload all values. */ + asm volatile ("" ::: "memory"); + return; + } + + handle = __libc_dlopen (LIBGCC_S_SO); + + if (handle == NULL + || (resume = __libc_dlsym (handle, "_Unwind_Resume")) == NULL + || (personality = __libc_dlsym (handle, "__gcc_personality_v0")) == NULL + || (forcedunwind = __libc_dlsym (handle, "_Unwind_ForcedUnwind")) + == NULL + || (getcfa = __libc_dlsym (handle, "_Unwind_GetCFA")) == NULL +#ifdef ARCH_CANCEL_INIT + || ARCH_CANCEL_INIT (handle) +#endif + ) + __libc_fatal (LIBGCC_S_SO " must be installed for pthread_cancel to work\n"); + + PTR_MANGLE (resume); + libgcc_s_resume = resume; + PTR_MANGLE (personality); + libgcc_s_personality = personality; + PTR_MANGLE (forcedunwind); + libgcc_s_forcedunwind = forcedunwind; + PTR_MANGLE (getcfa); + libgcc_s_getcfa = getcfa; + /* Make sure libgcc_s_handle is written last. Otherwise, + pthread_cancel_init might return early even when the pointer the + caller is interested in is not initialized yet. */ + atomic_write_barrier (); + libgcc_s_handle = handle; +} + +void +__libc_freeres_fn_section +__unwind_freeres (void) +{ + void *handle = libgcc_s_handle; + if (handle != NULL) + { + libgcc_s_handle = NULL; + __libc_dlclose (handle); + } +} + +void +_Unwind_Resume (struct _Unwind_Exception *exc) +{ + if (__builtin_expect (libgcc_s_handle == NULL, 0)) + pthread_cancel_init (); + else + atomic_read_barrier (); + + void (*resume) (struct _Unwind_Exception *exc) = libgcc_s_resume; + PTR_DEMANGLE (resume); + resume (exc); +} + +_Unwind_Reason_Code +__gcc_personality_v0 (int version, _Unwind_Action actions, + _Unwind_Exception_Class exception_class, + struct _Unwind_Exception *ue_header, + struct _Unwind_Context *context) +{ + if (__builtin_expect (libgcc_s_handle == NULL, 0)) + pthread_cancel_init (); + else + atomic_read_barrier (); + + _Unwind_Reason_Code (*personality) + (int, _Unwind_Action, _Unwind_Exception_Class, struct _Unwind_Exception *, + struct _Unwind_Context *) = libgcc_s_personality; + PTR_DEMANGLE (personality); + return personality (version, actions, exception_class, ue_header, context); +} + +_Unwind_Reason_Code +_Unwind_ForcedUnwind (struct _Unwind_Exception *exc, _Unwind_Stop_Fn stop, + void *stop_argument) +{ + if (__builtin_expect (libgcc_s_handle == NULL, 0)) + pthread_cancel_init (); + else + atomic_read_barrier (); + + _Unwind_Reason_Code (*forcedunwind) + (struct _Unwind_Exception *, _Unwind_Stop_Fn, void *) + = libgcc_s_forcedunwind; + PTR_DEMANGLE (forcedunwind); + return forcedunwind (exc, stop, stop_argument); +} + +_Unwind_Word +_Unwind_GetCFA (struct _Unwind_Context *context) +{ + if (__builtin_expect (libgcc_s_handle == NULL, 0)) + pthread_cancel_init (); + else + atomic_read_barrier (); + + _Unwind_Word (*getcfa) (struct _Unwind_Context *) = libgcc_s_getcfa; + PTR_DEMANGLE (getcfa); + return getcfa (context); +} diff --git a/pool/shard002/C/0059509_net-device.c b/pool/shard002/C/0059509_net-device.c new file mode 100644 index 0000000000000000000000000000000000000000..bcb72532923280d67f1e88fada33f7f2e19bf51b --- /dev/null +++ b/pool/shard002/C/0059509_net-device.c @@ -0,0 +1,97 @@ +/* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 8 -*- + * + * Copyright (C) 2011 Richard Hughes + * + * Licensed under the GNU General Public License Version 2 + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +#include "config.h" + +#include +#include + +#include "net-device.h" + +#define NET_DEVICE_GET_PRIVATE(o) (G_TYPE_INSTANCE_GET_PRIVATE ((o), NET_TYPE_DEVICE, NetDevicePrivate)) + +struct _NetDevicePrivate +{ + NMDevice *nm_device; +}; + +G_DEFINE_TYPE (NetDevice, net_device, NET_TYPE_OBJECT) + +static void +state_changed_cb (NMDevice *device, + NMDeviceState new_state, + NMDeviceState old_state, + NMDeviceStateReason reason, + NetDevice *net_device) +{ + net_object_emit_changed (NET_OBJECT (net_device)); +} + +void +net_device_set_nm_device (NetDevice *device, NMDevice *nm_device) +{ + device->priv->nm_device = g_object_ref (nm_device); + g_signal_connect (nm_device, + "state-changed", + G_CALLBACK (state_changed_cb), + device); +} + +NMDevice * +net_device_get_nm_device (NetDevice *device) +{ + return device->priv->nm_device; +} + +static void +net_device_finalize (GObject *object) +{ + NetDevice *device = NET_DEVICE (object); + NetDevicePrivate *priv = device->priv; + + if (priv->nm_device != NULL) + g_object_unref (priv->nm_device); + + G_OBJECT_CLASS (net_device_parent_class)->finalize (object); +} + +static void +net_device_class_init (NetDeviceClass *klass) +{ + GObjectClass *object_class = G_OBJECT_CLASS (klass); + object_class->finalize = net_device_finalize; + g_type_class_add_private (klass, sizeof (NetDevicePrivate)); +} + +static void +net_device_init (NetDevice *device) +{ + device->priv = NET_DEVICE_GET_PRIVATE (device); +} + +NetDevice * +net_device_new (void) +{ + NetDevice *device; + device = g_object_new (NET_TYPE_DEVICE, NULL); + return NET_DEVICE (device); +} + diff --git a/pool/shard002/C/0059510_soc_config.c b/pool/shard002/C/0059510_soc_config.c new file mode 100644 index 0000000000000000000000000000000000000000..13e30a7cb151a526e80d9780bfbc80bea649d25b --- /dev/null +++ b/pool/shard002/C/0059510_soc_config.c @@ -0,0 +1,66 @@ +/* + * Copyright (c) 2019 Gerson Fernando Budke + * Copyright (c) 2016 Piotr Mienkowski + * SPDX-License-Identifier: Apache-2.0 + */ + +/** @file + * @brief System module to support early Atmel SAM V71 MCU configuration + */ + +#include +#include +#include +#include + +/** + * @brief Perform SoC configuration at boot. + * + * This should be run early during the boot process but after basic hardware + * initialization is done. + * + * @return 0 + */ +static int atmel_samv71_config(const struct device *dev) +{ +#ifdef CONFIG_SOC_ATMEL_SAMV71_DISABLE_ERASE_PIN + /* Disable ERASE function on PB12 pin, this is controlled by Bus + * Matrix + */ + MATRIX->CCFG_SYSIO |= CCFG_SYSIO_SYSIO12; +#endif + + /* In Cortex-M based SoCs JTAG interface can be used to perform + * IEEE1149.1 JTAG Boundary scan only. It can not be used as a debug + * interface therefore there is no harm done by disabling the JTAG TDI + * pin by default. + */ + /* Disable TDI function on PB4 pin, this is controlled by Bus Matrix + */ + MATRIX->CCFG_SYSIO |= CCFG_SYSIO_SYSIO4; + +#ifdef CONFIG_LOG_BACKEND_SWO + /* Disable PCK3 clock used by ETM module */ + PMC->PMC_SCDR = PMC_SCDR_PCK3; + while ((PMC->PMC_SCSR) & PMC_SCSR_PCK3) { + ; + } + /* Select PLLA clock as PCK3 clock */ + PMC->PMC_PCK[3] = PMC_MCKR_CSS_PLLA_CLK; + /* Enable PCK3 clock */ + PMC->PMC_SCER = PMC_SCER_PCK3; + /* Wait for PCK3 setup to complete */ + while (!((PMC->PMC_SR) & PMC_SR_PCKRDY3)) { + ; + } + /* Enable TDO/TRACESWO function on PB5 pin */ + MATRIX->CCFG_SYSIO &= ~CCFG_SYSIO_SYSIO5; +#else + /* Disable TDO/TRACESWO function on PB5 pin */ + MATRIX->CCFG_SYSIO |= CCFG_SYSIO_SYSIO5; +#endif + + return 0; +} + +SYS_INIT(atmel_samv71_config, PRE_KERNEL_1, 1); diff --git a/pool/shard002/C/0059517_CWE78_OS_Command_Injection__wchar_t_listen_socket_execl_09.c b/pool/shard002/C/0059517_CWE78_OS_Command_Injection__wchar_t_listen_socket_execl_09.c new file mode 100644 index 0000000000000000000000000000000000000000..44cd9301686e19255c39edb31e26181bbffac5d1 --- /dev/null +++ b/pool/shard002/C/0059517_CWE78_OS_Command_Injection__wchar_t_listen_socket_execl_09.c @@ -0,0 +1,231 @@ +/* TEMPLATE GENERATED TESTCASE FILE +Filename: CWE78_OS_Command_Injection__wchar_t_listen_socket_execl_09.c +Label Definition File: CWE78_OS_Command_Injection.strings.label.xml +Template File: sources-sink-09.tmpl.c +*/ +/* + * @description + * CWE: 78 OS Command Injection + * BadSource: listen_socket Read data using a listen socket (server side) + * GoodSource: Fixed string + * Sink: execl + * BadSink : execute command with wexecl + * Flow Variant: 09 Control flow: if(GLOBAL_CONST_TRUE) and if(GLOBAL_CONST_FALSE) + * + * */ + +#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 + +#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 +#define INVALID_SOCKET -1 +#define SOCKET_ERROR -1 +#define CLOSE_SOCKET close +#define SOCKET int +#endif + +#define TCP_PORT 27015 +#define LISTEN_BACKLOG 5 + +#ifdef _WIN32 +#include +#define EXECL _wexecl +#else /* NOT _WIN32 */ +#define EXECL execl +#endif + +#ifndef OMITBAD + +void CWE78_OS_Command_Injection__wchar_t_listen_socket_execl_09_bad() +{ + wchar_t * data; + wchar_t dataBuffer[100] = COMMAND_ARG2; + data = dataBuffer; + if(GLOBAL_CONST_TRUE) + { + { +#ifdef _WIN32 + WSADATA wsaData; + int wsaDataInit = 0; +#endif + int recvResult; + struct sockaddr_in service; + wchar_t *replace; + SOCKET listenSocket = INVALID_SOCKET; + SOCKET acceptSocket = INVALID_SOCKET; + size_t dataLen = wcslen(data); + do + { +#ifdef _WIN32 + if (WSAStartup(MAKEWORD(2,2), &wsaData) != NO_ERROR) + { + break; + } + wsaDataInit = 1; +#endif + /* POTENTIAL FLAW: Read data using a listen socket */ + listenSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); + if (listenSocket == INVALID_SOCKET) + { + break; + } + memset(&service, 0, sizeof(service)); + service.sin_family = AF_INET; + service.sin_addr.s_addr = INADDR_ANY; + service.sin_port = htons(TCP_PORT); + if (bind(listenSocket, (struct sockaddr*)&service, sizeof(service)) == SOCKET_ERROR) + { + break; + } + if (listen(listenSocket, LISTEN_BACKLOG) == SOCKET_ERROR) + { + break; + } + acceptSocket = accept(listenSocket, NULL, NULL); + if (acceptSocket == SOCKET_ERROR) + { + break; + } + /* Abort on error or the connection was closed */ + recvResult = recv(acceptSocket, (char *)(data + dataLen), sizeof(wchar_t) * (100 - dataLen - 1), 0); + if (recvResult == SOCKET_ERROR || recvResult == 0) + { + break; + } + /* Append null terminator */ + data[dataLen + recvResult / sizeof(wchar_t)] = L'\0'; + /* Eliminate CRLF */ + replace = wcschr(data, L'\r'); + if (replace) + { + *replace = L'\0'; + } + replace = wcschr(data, L'\n'); + if (replace) + { + *replace = L'\0'; + } + } + while (0); + if (listenSocket != INVALID_SOCKET) + { + CLOSE_SOCKET(listenSocket); + } + if (acceptSocket != INVALID_SOCKET) + { + CLOSE_SOCKET(acceptSocket); + } +#ifdef _WIN32 + if (wsaDataInit) + { + WSACleanup(); + } +#endif + } + } + /* wexecl - specify the path where the command is located */ + /* POTENTIAL FLAW: Execute command without validating input possibly leading to command injection */ + EXECL(COMMAND_INT_PATH, COMMAND_INT_PATH, COMMAND_ARG1, COMMAND_ARG3, NULL); +} + +#endif /* OMITBAD */ + +#ifndef OMITGOOD + +/* goodG2B1() - use goodsource and badsink by changing the GLOBAL_CONST_TRUE to GLOBAL_CONST_FALSE */ +static void goodG2B1() +{ + wchar_t * data; + wchar_t dataBuffer[100] = COMMAND_ARG2; + data = dataBuffer; + if(GLOBAL_CONST_FALSE) + { + /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */ + printLine("Benign, fixed string"); + } + else + { + /* FIX: Append a fixed string to data (not user / external input) */ + wcscat(data, L"*.*"); + } + /* wexecl - specify the path where the command is located */ + /* POTENTIAL FLAW: Execute command without validating input possibly leading to command injection */ + EXECL(COMMAND_INT_PATH, COMMAND_INT_PATH, COMMAND_ARG1, COMMAND_ARG3, NULL); +} + +/* goodG2B2() - use goodsource and badsink by reversing the blocks in the if statement */ +static void goodG2B2() +{ + wchar_t * data; + wchar_t dataBuffer[100] = COMMAND_ARG2; + data = dataBuffer; + if(GLOBAL_CONST_TRUE) + { + /* FIX: Append a fixed string to data (not user / external input) */ + wcscat(data, L"*.*"); + } + /* wexecl - specify the path where the command is located */ + /* POTENTIAL FLAW: Execute command without validating input possibly leading to command injection */ + EXECL(COMMAND_INT_PATH, COMMAND_INT_PATH, COMMAND_ARG1, COMMAND_ARG3, NULL); +} + +void CWE78_OS_Command_Injection__wchar_t_listen_socket_execl_09_good() +{ + goodG2B1(); + goodG2B2(); +} + +#endif /* OMITGOOD */ + +/* Below is the main(). It is only used when building this testcase on + * its own for testing or for building a binary to use in testing binary + * analysis tools. It is not used when compiling all the testcases as one + * application, which is how source code analysis tools are tested. + */ + +#ifdef INCLUDEMAIN + +int main(int argc, char * argv[]) +{ + /* seed randomness */ + srand( (unsigned)time(NULL) ); +#ifndef OMITGOOD + printLine("Calling good()..."); + CWE78_OS_Command_Injection__wchar_t_listen_socket_execl_09_good(); + printLine("Finished good()"); +#endif /* OMITGOOD */ +#ifndef OMITBAD + printLine("Calling bad()..."); + CWE78_OS_Command_Injection__wchar_t_listen_socket_execl_09_bad(); + printLine("Finished bad()"); +#endif /* OMITBAD */ + return 0; +} + +#endif diff --git a/pool/shard002/C/0059521_remount-fs.c b/pool/shard002/C/0059521_remount-fs.c new file mode 100644 index 0000000000000000000000000000000000000000..f904e48e753d35c5a80c40ef16f5c2b8f03e444e --- /dev/null +++ b/pool/shard002/C/0059521_remount-fs.c @@ -0,0 +1,166 @@ +/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/ + +/*** + This file is part of systemd. + + Copyright 2010 Lennart Poettering + + systemd 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. + + systemd 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 systemd; If not, see . +***/ + +#include +#include +#include +#include +#include +#include + +#include "log.h" +#include "util.h" +#include "path-util.h" +#include "signal-util.h" +#include "mount-setup.h" +#include "exit-status.h" + +/* Goes through /etc/fstab and remounts all API file systems, applying + * options that are in /etc/fstab that systemd might not have + * respected */ + +int main(int argc, char *argv[]) { + int ret = EXIT_FAILURE; + _cleanup_endmntent_ FILE *f = NULL; + struct mntent* me; + Hashmap *pids = NULL; + + if (argc > 1) { + log_error("This program takes no argument."); + return EXIT_FAILURE; + } + + log_set_target(LOG_TARGET_AUTO); + log_parse_environment(); + log_open(); + + umask(0022); + + f = setmntent("/etc/fstab", "r"); + if (!f) { + if (errno == ENOENT) + return EXIT_SUCCESS; + + log_error_errno(errno, "Failed to open /etc/fstab: %m"); + return EXIT_FAILURE; + } + + pids = hashmap_new(NULL); + if (!pids) { + log_error("Failed to allocate set"); + goto finish; + } + + ret = EXIT_SUCCESS; + + while ((me = getmntent(f))) { + pid_t pid; + int k; + char *s; + + /* Remount the root fs, /usr and all API VFS */ + if (!mount_point_is_api(me->mnt_dir) && + !path_equal(me->mnt_dir, "/") && + !path_equal(me->mnt_dir, "/usr")) + continue; + + log_debug("Remounting %s", me->mnt_dir); + + pid = fork(); + if (pid < 0) { + log_error_errno(errno, "Failed to fork: %m"); + ret = EXIT_FAILURE; + continue; + } + + if (pid == 0) { + const char *arguments[5]; + /* Child */ + + (void) reset_all_signal_handlers(); + (void) reset_signal_mask(); + + arguments[0] = MOUNT_PATH; + arguments[1] = me->mnt_dir; + arguments[2] = "-o"; + arguments[3] = "remount"; + arguments[4] = NULL; + + execv(MOUNT_PATH, (char **) arguments); + + log_error_errno(errno, "Failed to execute " MOUNT_PATH ": %m"); + _exit(EXIT_FAILURE); + } + + /* Parent */ + + s = strdup(me->mnt_dir); + if (!s) { + log_oom(); + ret = EXIT_FAILURE; + continue; + } + + + k = hashmap_put(pids, UINT_TO_PTR(pid), s); + if (k < 0) { + log_error_errno(k, "Failed to add PID to set: %m"); + ret = EXIT_FAILURE; + continue; + } + } + + while (!hashmap_isempty(pids)) { + siginfo_t si = {}; + char *s; + + if (waitid(P_ALL, 0, &si, WEXITED) < 0) { + + if (errno == EINTR) + continue; + + log_error_errno(errno, "waitid() failed: %m"); + ret = EXIT_FAILURE; + break; + } + + s = hashmap_remove(pids, UINT_TO_PTR(si.si_pid)); + if (s) { + if (!is_clean_exit(si.si_code, si.si_status, NULL)) { + if (si.si_code == CLD_EXITED) + log_error(MOUNT_PATH " for %s exited with exit status %i.", s, si.si_status); + else + log_error(MOUNT_PATH " for %s terminated by signal %s.", s, signal_to_string(si.si_status)); + + ret = EXIT_FAILURE; + } + + free(s); + } + } + +finish: + + if (pids) + hashmap_free_free(pids); + + return ret; +} diff --git a/pool/shard002/C/0059523_task.c b/pool/shard002/C/0059523_task.c new file mode 100644 index 0000000000000000000000000000000000000000..b262000e2c5b12c31d6dfb061daccc22d3bd9a3f --- /dev/null +++ b/pool/shard002/C/0059523_task.c @@ -0,0 +1,89 @@ +/* + * opsys - A small, experimental operating system + * Copyright (C) 2009-2010 Thomas Zimmermann + * Copyright (C) 2016 Thomas Zimmermann + * + * 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 "task.h" +#include +#include +#include "bitset.h" + +enum +{ + MAXTASK = 1024 +}; + +static unsigned char g_taskid[MAXTASK >> 3]; + +int +task_init(struct task *task, struct vmem *as) +{ + int err; + ssize_t taskid; + + if ((taskid = bitset_find_unset(g_taskid, sizeof(g_taskid))) < 0) + { + err = taskid; + goto err_find_taskid; + } + + bitset_set(g_taskid, taskid); + + task->as = as; + task->nthreads = 0; + task->id = taskid; + memset(task->threadid, 0, sizeof(task->threadid)); + + return 0; + +err_find_taskid: + return err; +} + +void +task_uninit(struct task *task) +{ + bitset_unset(g_taskid, task->id); +} + +size_t +task_max_nthreads(const struct task *task) +{ + return sizeof(task->threadid) * 8; +} + +int +task_ref(struct task *task) +{ + if (!(task->nthreads < task_max_nthreads(task))) + { + return -EAGAIN; + } + + return ++task->nthreads; +} + +int +task_unref(struct task *task) +{ + if (!task->nthreads) + { + return -EINVAL; + } + + return --task->nthreads; +} diff --git a/pool/shard002/C/0059524_cpia.c b/pool/shard002/C/0059524_cpia.c new file mode 100644 index 0000000000000000000000000000000000000000..44226fb46bb29595f27abeaf67ad524bd5813f14 --- /dev/null +++ b/pool/shard002/C/0059524_cpia.c @@ -0,0 +1,233 @@ +/* + * CPiA video decoder. + * Copyright (c) 2010 Hans de Goede + * + * This decoder is based on the LGPL code available at + * https://v4l4j.googlecode.com/svn/v4l4j/trunk/libvideo/libv4lconvert/cpia1.c + * + * 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 "avcodec.h" +#include "get_bits.h" +#include "internal.h" + + +#define FRAME_HEADER_SIZE 64 +#define MAGIC_0 0x19 /**< First header byte */ +#define MAGIC_1 0x68 /**< Second header byte */ +#define SUBSAMPLE_420 0 +#define SUBSAMPLE_422 1 +#define YUVORDER_YUYV 0 +#define YUVORDER_UYVY 1 +#define NOT_COMPRESSED 0 +#define COMPRESSED 1 +#define NO_DECIMATION 0 +#define DECIMATION_ENAB 1 +#define EOL 0xfd /**< End Of Line marker */ +#define EOI 0xff /**< End Of Image marker */ + + +typedef struct { + AVFrame *frame; +} CpiaContext; + + +static int cpia_decode_frame(AVCodecContext *avctx, + void *data, int *got_frame, AVPacket* avpkt) +{ + CpiaContext* const cpia = avctx->priv_data; + int i,j,ret; + + uint8_t* const header = avpkt->data; + uint8_t* src; + int src_size; + uint16_t linelength; + uint8_t skip; + + AVFrame *frame = cpia->frame; + uint8_t *y, *u, *v, *y_end, *u_end, *v_end; + + // Check header + if ( avpkt->size < FRAME_HEADER_SIZE + || header[0] != MAGIC_0 || header[1] != MAGIC_1 + || (header[17] != SUBSAMPLE_420 && header[17] != SUBSAMPLE_422) + || (header[18] != YUVORDER_YUYV && header[18] != YUVORDER_UYVY) + || (header[28] != NOT_COMPRESSED && header[28] != COMPRESSED) + || (header[29] != NO_DECIMATION && header[29] != DECIMATION_ENAB) + ) { + av_log(avctx, AV_LOG_ERROR, "Invalid header!\n"); + return AVERROR_INVALIDDATA; + } + + // currently unsupported properties + if (header[17] == SUBSAMPLE_422) { + av_log(avctx, AV_LOG_ERROR, "Unsupported subsample!\n"); + return AVERROR_PATCHWELCOME; + } + if (header[18] == YUVORDER_UYVY) { + av_log(avctx, AV_LOG_ERROR, "Unsupported YUV byte order!\n"); + return AVERROR_PATCHWELCOME; + } + if (header[29] == DECIMATION_ENAB) { + av_log(avctx, AV_LOG_ERROR, "Decimation unsupported!\n"); + return AVERROR_PATCHWELCOME; + } + + src = header + FRAME_HEADER_SIZE; + src_size = avpkt->size - FRAME_HEADER_SIZE; + + if (header[28] == NOT_COMPRESSED) { + frame->pict_type = AV_PICTURE_TYPE_I; + frame->key_frame = 1; + } else { + frame->pict_type = AV_PICTURE_TYPE_P; + frame->key_frame = 0; + } + + // Get buffer filled with previous frame + if ((ret = ff_reget_buffer(avctx, frame)) < 0) + return ret; + + + for ( i = 0; + i < frame->height; + i++, src += linelength, src_size -= linelength + ) { + // Read line length, two byte little endian + linelength = AV_RL16(src); + src += 2; + + if (src_size < linelength) { + av_frame_set_decode_error_flags(frame, FF_DECODE_ERROR_INVALID_BITSTREAM); + av_log(avctx, AV_LOG_WARNING, "Frame ended enexpectedly!\n"); + break; + } + if (src[linelength - 1] != EOL) { + av_frame_set_decode_error_flags(frame, FF_DECODE_ERROR_INVALID_BITSTREAM); + av_log(avctx, AV_LOG_WARNING, "Wrong line length %d or line not terminated properly (found 0x%02x)!\n", linelength, src[linelength - 1]); + break; + } + + /* Update the data pointers. Y data is on every line. + * U and V data on every second line + */ + y = &frame->data[0][i * frame->linesize[0]]; + u = &frame->data[1][(i >> 1) * frame->linesize[1]]; + v = &frame->data[2][(i >> 1) * frame->linesize[2]]; + y_end = y + frame->linesize[0] - 1; + u_end = u + frame->linesize[1] - 1; + v_end = v + frame->linesize[2] - 1; + + if ((i & 1) && header[17] == SUBSAMPLE_420) { + /* We are on a odd line and 420 subsample is used. + * On this line only Y values are specified, one per pixel. + */ + for (j = 0; j < linelength - 1; j++) { + if (y > y_end) { + av_frame_set_decode_error_flags(frame, FF_DECODE_ERROR_INVALID_BITSTREAM); + av_log(avctx, AV_LOG_WARNING, "Decoded data exceeded linesize!\n"); + break; + } + if ((src[j] & 1) && header[28] == COMPRESSED) { + /* It seems that odd lines are always uncompressed, but + * we do it according to specification anyways. + */ + skip = src[j] >> 1; + y += skip; + } else { + *(y++) = src[j]; + } + } + } else if (header[17] == SUBSAMPLE_420) { + /* We are on an even line and 420 subsample is used. + * On this line each pair of pixels is described by four bytes. + */ + for (j = 0; j < linelength - 4; ) { + if (y + 1 > y_end || u > u_end || v > v_end) { + av_frame_set_decode_error_flags(frame, FF_DECODE_ERROR_INVALID_BITSTREAM); + av_log(avctx, AV_LOG_WARNING, "Decoded data exceeded linesize!\n"); + break; + } + if ((src[j] & 1) && header[28] == COMPRESSED) { + // Skip amount of pixels and move forward one byte + skip = src[j] >> 1; + y += skip; + u += skip >> 1; + v += skip >> 1; + j++; + } else { + // Set image data as specified and move forward 4 bytes + *(y++) = src[j]; + *(u++) = src[j+1]; + *(y++) = src[j+2]; + *(v++) = src[j+3]; + j += 4; + } + } + } + } + + *got_frame = 1; + if ((ret = av_frame_ref(data, cpia->frame)) < 0) + return ret; + + return avpkt->size; +} + +static av_cold int cpia_decode_init(AVCodecContext *avctx) +{ + CpiaContext *s = avctx->priv_data; + + // output pixel format + avctx->pix_fmt = AV_PIX_FMT_YUV420P; + + /* The default timebase set by the v4l2 demuxer leads to probing which is buggy. + * Set some reasonable time_base to skip this. + */ + if (avctx->time_base.num == 1 && avctx->time_base.den == 1000000) { + avctx->time_base.num = 1; + avctx->time_base.den = 60; + } + + s->frame = av_frame_alloc(); + if (!s->frame) + return AVERROR(ENOMEM); + + return 0; +} + +static av_cold int cpia_decode_end(AVCodecContext *avctx) +{ + CpiaContext *s = avctx->priv_data; + + av_frame_free(&s->frame); + + return 0; +} + +AVCodec ff_cpia_decoder = { + .name = "cpia", + .long_name = NULL_IF_CONFIG_SMALL("CPiA video format"), + .type = AVMEDIA_TYPE_VIDEO, + .id = AV_CODEC_ID_CPIA, + .priv_data_size = sizeof(CpiaContext), + .init = cpia_decode_init, + .close = cpia_decode_end, + .decode = cpia_decode_frame, + .capabilities = CODEC_CAP_DR1, +}; diff --git a/pool/shard002/C/0059525_gpm-prefs.c b/pool/shard002/C/0059525_gpm-prefs.c new file mode 100644 index 0000000000000000000000000000000000000000..7acc6530ad87c4d86942208542c6692ab99ae1d9 --- /dev/null +++ b/pool/shard002/C/0059525_gpm-prefs.c @@ -0,0 +1,133 @@ +/* -*- Mode: C; tab-width: 8; indent-tabs-mode: t; c-basic-offset: 8 -*- + * + * Copyright (C) 2005 Jaap Haitsma + * Copyright (C) 2005 William Jon McCann + * Copyright (C) 2005-2008 Richard Hughes + * + * Licensed under the GNU General Public License Version 2 + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +#ifdef HAVE_CONFIG_H +# include +#endif + +#include +#include +#include +#include + +/* local .la */ +#include + +#include "gpm-common.h" +#include "egg-debug.h" +#include "gpm-prefs-core.h" + +/** + * gpm_prefs_help_cb + * @prefs: This prefs class instance + * + * What to do when help is requested + **/ +static void +gpm_prefs_help_cb (GpmPrefs *prefs) +{ + gpm_help_display ("preferences"); +} + +/** + * gpm_prefs_close_cb + * @prefs: This prefs class instance + * + * What to do when we are asked to close for whatever reason + **/ +static void +gpm_prefs_close_cb (GpmPrefs *prefs) +{ + gtk_main_quit (); +} + +/** + * gpm_prefs_activated_cb + * @prefs: This prefs class instance + * + * We have been asked to show the window + **/ +static void +gpm_prefs_activated_cb (EggUnique *egg_unique, GpmPrefs *prefs) +{ + gpm_prefs_activate_window (prefs); +} + +/** + * main: + **/ +int +main (int argc, char **argv) +{ + gboolean verbose = FALSE; + GOptionContext *context; + GpmPrefs *prefs = NULL; + gboolean ret; + EggUnique *egg_unique; + + const GOptionEntry options[] = { + { "verbose", '\0', 0, G_OPTION_ARG_NONE, &verbose, + N_("Show extra debugging information"), NULL }, + { NULL} + }; + + context = g_option_context_new (N_("GNOME Power Preferences")); + + bindtextdomain (GETTEXT_PACKAGE, GNOMELOCALEDIR); + bind_textdomain_codeset (GETTEXT_PACKAGE, "UTF-8"); + textdomain (GETTEXT_PACKAGE); + + g_option_context_set_translation_domain(context, GETTEXT_PACKAGE); + g_option_context_add_main_entries (context, options, GETTEXT_PACKAGE); + g_option_context_add_group (context, gtk_get_option_group (FALSE)); + g_option_context_parse (context, &argc, &argv, NULL); + + gtk_init (&argc, &argv); + egg_debug_init (verbose); + + /* are we already activated? */ + egg_unique = egg_unique_new (); + ret = egg_unique_assign (egg_unique, "org.gnome.PowerManager.Preferences"); + if (!ret) { + goto unique_out; + } + + prefs = gpm_prefs_new (); + + g_signal_connect (egg_unique, "activated", + G_CALLBACK (gpm_prefs_activated_cb), prefs); + g_signal_connect (prefs, "action-help", + G_CALLBACK (gpm_prefs_help_cb), prefs); + g_signal_connect (prefs, "action-close", + G_CALLBACK (gpm_prefs_close_cb), prefs); + gtk_main (); + g_object_unref (prefs); + +unique_out: + g_object_unref (egg_unique); + +/* seems to not work... + g_option_context_free (context); */ + + return 0; +} diff --git a/pool/shard002/C/0059531_play_level.c b/pool/shard002/C/0059531_play_level.c new file mode 100644 index 0000000000000000000000000000000000000000..f338e9dfcbe6c0a2f5bed22352c54398daf4a630 --- /dev/null +++ b/pool/shard002/C/0059531_play_level.c @@ -0,0 +1,120 @@ +/* $NetBSD: play_level.c,v 1.9 2009/07/20 06:39:06 dholland Exp $ */ + +/* + * Copyright (c) 1980, 1993 + * 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. 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. + */ + +#include +#ifndef lint +#if 0 +static char sccsid[] = "@(#)play_level.c 8.1 (Berkeley) 5/31/93"; +#else +__RCSID("$NetBSD: play_level.c,v 1.9 2009/07/20 06:39:06 dholland Exp $"); +#endif +#endif /* not lint */ + +#include +#include +#include "robots.h" + +/* + * play_level: + * Let the player play the current level + */ +void +play_level(void) +{ + COORD *cp; + + move(My_pos.y, My_pos.x); + addch(PLAYER); + refresh(); + for (cp = Robots; cp < &Robots[MAXROBOTS]; cp++) { + if (cp->y < 0) + continue; + move(cp->y, cp->x); + addch(ROBOT); + } + refresh(); +#ifdef DEBUG + standout(); + move(Min.y, Min.x); + addch(inch()); + move(Max.y, Max.x); + addch(inch()); + standend(); +#endif /* DEBUG */ + setjmp(End_move); + flush_in(); + while (!Dead && Num_robots > 0) { + move(My_pos.y, My_pos.x); + if (!jumping()) + refresh(); + get_move(); + if (Real_time) + alarm(0); + if (Field[My_pos.y][My_pos.x] != 0) + Dead = true; + if (!Dead) + move_robots(false); + if (Was_bonus) { + move(Y_PROMPT, X_PROMPT); + clrtoeol(); + move(Y_PROMPT + 1, X_PROMPT); + clrtoeol(); + Was_bonus = false; + } + } + + /* + * if the player didn't die, add on the possible bonuses + */ + + if (!Dead) { + Was_bonus = false; + + if (Level == Start_level && Start_level > 1) { + move(Y_PROMPT, X_PROMPT); + printw("Advance bonus: %d", S_BONUS); + refresh(); + add_score(S_BONUS); + Was_bonus = true; + } + + if (Wait_bonus != 0) { + if (!Was_bonus) + move(Y_PROMPT, X_PROMPT); + else + move(Y_PROMPT + 1, X_PROMPT); + printw("Wait bonus: %d", Wait_bonus); + refresh(); + add_score(Wait_bonus); + Was_bonus = true; + } + } +} diff --git a/pool/shard002/C/0059536_init.c b/pool/shard002/C/0059536_init.c new file mode 100644 index 0000000000000000000000000000000000000000..4a3da7592b99c938eed72dd583475bef4ae131a1 --- /dev/null +++ b/pool/shard002/C/0059536_init.c @@ -0,0 +1,177 @@ +// SPDX-License-Identifier: GPL-2.0 +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include + +struct real_mode_header *real_mode_header; +u32 *trampoline_cr4_features; + +/* Hold the pgd entry used on booting additional CPUs */ +pgd_t trampoline_pgd_entry; + +void __init reserve_real_mode(void) +{ + phys_addr_t mem; + size_t size = real_mode_size_needed(); + + if (!size) + return; + + WARN_ON(slab_is_available()); + + /* Has to be under 1M so we can execute real-mode AP code. */ + mem = memblock_phys_alloc_range(size, PAGE_SIZE, 0, 1<<20); + if (!mem) + pr_info("No sub-1M memory is available for the trampoline\n"); + else + set_real_mode_mem(mem); + + /* + * Unconditionally reserve the entire fisrt 1M, see comment in + * setup_arch(). + */ + memblock_reserve(0, SZ_1M); +} + +static void sme_sev_setup_real_mode(struct trampoline_header *th) +{ +#ifdef CONFIG_AMD_MEM_ENCRYPT + if (cc_platform_has(CC_ATTR_HOST_MEM_ENCRYPT)) + th->flags |= TH_FLAGS_SME_ACTIVE; + + if (cc_platform_has(CC_ATTR_GUEST_STATE_ENCRYPT)) { + /* + * Skip the call to verify_cpu() in secondary_startup_64 as it + * will cause #VC exceptions when the AP can't handle them yet. + */ + th->start = (u64) secondary_startup_64_no_verify; + + if (sev_es_setup_ap_jump_table(real_mode_header)) + panic("Failed to get/update SEV-ES AP Jump Table"); + } +#endif +} + +static void __init setup_real_mode(void) +{ + u16 real_mode_seg; + const u32 *rel; + u32 count; + unsigned char *base; + unsigned long phys_base; + struct trampoline_header *trampoline_header; + size_t size = PAGE_ALIGN(real_mode_blob_end - real_mode_blob); +#ifdef CONFIG_X86_64 + u64 *trampoline_pgd; + u64 efer; +#endif + + base = (unsigned char *)real_mode_header; + + /* + * If SME is active, the trampoline area will need to be in + * decrypted memory in order to bring up other processors + * successfully. This is not needed for SEV. + */ + if (cc_platform_has(CC_ATTR_HOST_MEM_ENCRYPT)) + set_memory_decrypted((unsigned long)base, size >> PAGE_SHIFT); + + memcpy(base, real_mode_blob, size); + + phys_base = __pa(base); + real_mode_seg = phys_base >> 4; + + rel = (u32 *) real_mode_relocs; + + /* 16-bit segment relocations. */ + count = *rel++; + while (count--) { + u16 *seg = (u16 *) (base + *rel++); + *seg = real_mode_seg; + } + + /* 32-bit linear relocations. */ + count = *rel++; + while (count--) { + u32 *ptr = (u32 *) (base + *rel++); + *ptr += phys_base; + } + + /* Must be performed *after* relocation. */ + trampoline_header = (struct trampoline_header *) + __va(real_mode_header->trampoline_header); + +#ifdef CONFIG_X86_32 + trampoline_header->start = __pa_symbol(startup_32_smp); + trampoline_header->gdt_limit = __BOOT_DS + 7; + trampoline_header->gdt_base = __pa_symbol(boot_gdt); +#else + /* + * Some AMD processors will #GP(0) if EFER.LMA is set in WRMSR + * so we need to mask it out. + */ + rdmsrl(MSR_EFER, efer); + trampoline_header->efer = efer & ~EFER_LMA; + + trampoline_header->start = (u64) secondary_startup_64; + trampoline_cr4_features = &trampoline_header->cr4; + *trampoline_cr4_features = mmu_cr4_features; + + trampoline_header->flags = 0; + + trampoline_pgd = (u64 *) __va(real_mode_header->trampoline_pgd); + trampoline_pgd[0] = trampoline_pgd_entry.pgd; + trampoline_pgd[511] = init_top_pgt[511].pgd; +#endif + + sme_sev_setup_real_mode(trampoline_header); +} + +/* + * reserve_real_mode() gets called very early, to guarantee the + * availability of low memory. This is before the proper kernel page + * tables are set up, so we cannot set page permissions in that + * function. Also trampoline code will be executed by APs so we + * need to mark it executable at do_pre_smp_initcalls() at least, + * thus run it as a early_initcall(). + */ +static void __init set_real_mode_permissions(void) +{ + unsigned char *base = (unsigned char *) real_mode_header; + size_t size = PAGE_ALIGN(real_mode_blob_end - real_mode_blob); + + size_t ro_size = + PAGE_ALIGN(real_mode_header->ro_end) - + __pa(base); + + size_t text_size = + PAGE_ALIGN(real_mode_header->ro_end) - + real_mode_header->text_start; + + unsigned long text_start = + (unsigned long) __va(real_mode_header->text_start); + + set_memory_nx((unsigned long) base, size >> PAGE_SHIFT); + set_memory_ro((unsigned long) base, ro_size >> PAGE_SHIFT); + set_memory_x((unsigned long) text_start, text_size >> PAGE_SHIFT); +} + +static int __init init_real_mode(void) +{ + if (!real_mode_header) + panic("Real mode trampoline was not allocated"); + + setup_real_mode(); + set_real_mode_permissions(); + + return 0; +} +early_initcall(init_real_mode); diff --git a/pool/shard002/C/0059542_squeue.c b/pool/shard002/C/0059542_squeue.c new file mode 100644 index 0000000000000000000000000000000000000000..a761e6a62a2f73e2db0029dc9c1d6d9d2ff80356 --- /dev/null +++ b/pool/shard002/C/0059542_squeue.c @@ -0,0 +1,241 @@ +/* + * Copyright (C) 2021 Jakub Kruszona-Zawadzki, Core Technology Sp. z o.o. + * + * This file is part of MooseFS. + * + * MooseFS 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). + * + * MooseFS 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 MooseFS; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02111-1301, USA + * or visit http://www.gnu.org/licenses/gpl-2.0.html + */ + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +#include +#include +#include +#include + +#include "massert.h" + +typedef struct _qentry { + void *data; + struct _qentry *next; +} qentry; + +typedef struct _queue { + qentry *head,**tail; + uint32_t elements; + uint32_t maxelements; + uint32_t closed; + pthread_cond_t waitfree,waitfull; + pthread_mutex_t lock; +} queue; + +void* squeue_new(uint32_t length) { + queue *q; + q = (queue*)malloc(sizeof(queue)); + passert(q); + q->head = NULL; + q->tail = &(q->head); + q->elements = 0; + q->maxelements = length; + q->closed = 0; + if (length) { + zassert(pthread_cond_init(&(q->waitfull),NULL)); + } + zassert(pthread_cond_init(&(q->waitfree),NULL)); + zassert(pthread_mutex_init(&(q->lock),NULL)); + return q; +} + +void squeue_delete(void *que) { + queue *q = (queue*)que; + qentry *qe,*qen; + zassert(pthread_mutex_lock(&(q->lock))); + for (qe = q->head ; qe ; qe = qen) { + qen = qe->next; + free(qe->data); + free(qe); + } + zassert(pthread_mutex_unlock(&(q->lock))); + zassert(pthread_mutex_destroy(&(q->lock))); + zassert(pthread_cond_destroy(&(q->waitfree))); + if (q->maxelements) { + zassert(pthread_cond_destroy(&(q->waitfull))); + } + free(q); +} + +void squeue_close(void *que) { + queue *q = (queue*)que; + zassert(pthread_mutex_lock(&(q->lock))); + q->closed = 1; + zassert(pthread_cond_broadcast(&(q->waitfree))); + if (q->maxelements) { + zassert(pthread_cond_broadcast(&(q->waitfull))); + } + zassert(pthread_mutex_unlock(&(q->lock))); +} + +int squeue_isempty(void *que) { + queue *q = (queue*)que; + int r; + zassert(pthread_mutex_lock(&(q->lock))); + r=(q->elements==0)?1:0; + zassert(pthread_mutex_unlock(&(q->lock))); + return r; +} + +uint32_t squeue_elements(void *que) { + queue *q = (queue*)que; + uint32_t r; + zassert(pthread_mutex_lock(&(q->lock))); + r=q->elements; + zassert(pthread_mutex_unlock(&(q->lock))); + return r; +} + +int squeue_isfull(void *que) { + queue *q = (queue*)que; + int r; + zassert(pthread_mutex_lock(&(q->lock))); + r = (q->maxelements>0 && q->maxelements<=q->elements)?1:0; + zassert(pthread_mutex_unlock(&(q->lock))); + return r; +} + +uint32_t squeue_sizeleft(void *que) { + queue *q = (queue*)que; + uint32_t r; + zassert(pthread_mutex_lock(&(q->lock))); + if (q->maxelements>0) { + r = q->maxelements-q->elements; + } else { + r = 0xFFFFFFFF; + } + zassert(pthread_mutex_unlock(&(q->lock))); + return r; +} + +int squeue_put(void *que,void *data) { + queue *q = (queue*)que; + qentry *qe; + qe = malloc(sizeof(qentry)); + passert(qe); + qe->data = data; + qe->next = NULL; + zassert(pthread_mutex_lock(&(q->lock))); + if (q->maxelements) { + while (q->elements>=q->maxelements && q->closed==0) { + zassert(pthread_cond_wait(&(q->waitfull),&(q->lock))); + } + if (q->closed) { + zassert(pthread_mutex_unlock(&(q->lock))); + free(qe); + errno = EIO; + return -1; + } + } + q->elements++; + *(q->tail) = qe; + q->tail = &(qe->next); + zassert(pthread_cond_signal(&(q->waitfree))); + zassert(pthread_mutex_unlock(&(q->lock))); + return 0; +} + +int squeue_tryput(void *que,void *data) { + queue *q = (queue*)que; + qentry *qe; + zassert(pthread_mutex_lock(&(q->lock))); + if (q->maxelements) { + if (q->elements>=q->maxelements) { + zassert(pthread_mutex_unlock(&(q->lock))); + errno = EBUSY; + return -1; + } + } + qe = malloc(sizeof(qentry)); + passert(qe); + qe->data = data; + qe->next = NULL; + q->elements++; + *(q->tail) = qe; + q->tail = &(qe->next); + zassert(pthread_cond_signal(&(q->waitfree))); + zassert(pthread_mutex_unlock(&(q->lock))); + return 0; +} + +int squeue_get(void *que,void **data) { + queue *q = (queue*)que; + qentry *qe; + zassert(pthread_mutex_lock(&(q->lock))); + while (q->elements==0 && q->closed==0) { + zassert(pthread_cond_wait(&(q->waitfree),&(q->lock))); + } + if (q->closed) { + zassert(pthread_mutex_unlock(&(q->lock))); + if (data) { + *data=NULL; + } + errno = EIO; + return -1; + } + qe = q->head; + q->head = qe->next; + if (q->head==NULL) { + q->tail = &(q->head); + } + q->elements--; + if (q->maxelements) { + zassert(pthread_cond_signal(&(q->waitfull))); + } + zassert(pthread_mutex_unlock(&(q->lock))); + if (data) { + *data = qe->data; + } + free(qe); + return 0; +} + +int squeue_tryget(void *que,void **data) { + queue *q = (queue*)que; + qentry *qe; + zassert(pthread_mutex_lock(&(q->lock))); + if (q->elements==0) { + zassert(pthread_mutex_unlock(&(q->lock))); + if (data) { + *data=NULL; + } + errno = EBUSY; + return -1; + } + qe = q->head; + q->head = qe->next; + if (q->head==NULL) { + q->tail = &(q->head); + } + q->elements--; + if (q->maxelements) { + zassert(pthread_cond_signal(&(q->waitfull))); + } + zassert(pthread_mutex_unlock(&(q->lock))); + if (data) { + *data = qe->data; + } + free(qe); + return 0; +} diff --git a/pool/shard002/C/0059550_ot-admin-instutil-builtin-grub2-generate.c b/pool/shard002/C/0059550_ot-admin-instutil-builtin-grub2-generate.c new file mode 100644 index 0000000000000000000000000000000000000000..9f31c67a8730b6a4977032ae9c481e56e351f7c6 --- /dev/null +++ b/pool/shard002/C/0059550_ot-admin-instutil-builtin-grub2-generate.c @@ -0,0 +1,86 @@ +/* -*- mode: C; c-file-style: "gnu"; indent-tabs-mode: nil; -*- + * + * Copyright (C) 2014 Colin Walters + * + * 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; either version 2 of the licence 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 "config.h" + +#include +#include + +#include "ot-main.h" +#include "ot-admin-instutil-builtins.h" +#include "ostree-cmdprivate.h" + +#include "otutil.h" + +static GOptionEntry options[] = { + { NULL } +}; + +gboolean +ot_admin_instutil_builtin_grub2_generate (int argc, char **argv, GCancellable *cancellable, GError **error) +{ + gboolean ret = FALSE; + guint bootversion; + g_autoptr(GFile) subpath = NULL; + glnx_unref_object OstreeSePolicy *sepolicy = NULL; + g_autoptr(GPtrArray) deployments = NULL; + GOptionContext *context = NULL; + glnx_unref_object OstreeSysroot *sysroot = NULL; + g_autoptr(GFile) deployment_path = NULL; + + context = g_option_context_new ("[BOOTVERSION] - generate GRUB2 configuration from given BLS entries"); + + if (!ostree_admin_option_context_parse (context, options, &argc, &argv, + OSTREE_ADMIN_BUILTIN_FLAG_SUPERUSER | OSTREE_ADMIN_BUILTIN_FLAG_UNLOCKED, + &sysroot, cancellable, error)) + goto out; + + if (argc >= 2) + { + bootversion = (guint) g_ascii_strtoull (argv[1], NULL, 10); + if (!(bootversion == 0 || bootversion == 1)) + { + g_set_error (error, G_IO_ERROR, G_IO_ERROR_FAILED, + "Invalid bootversion: %u", bootversion); + goto out; + } + } + else + { + const char *bootversion_env = g_getenv ("_OSTREE_GRUB2_BOOTVERSION"); + if (bootversion_env) + bootversion = g_ascii_strtoull (bootversion_env, NULL, 10); + else + bootversion = ostree_sysroot_get_bootversion (sysroot); + g_assert (bootversion == 0 || bootversion == 1); + } + + if (!ostree_sysroot_load (sysroot, cancellable, error)) + goto out; + + if (!ostree_cmd__private__()->ostree_generate_grub2_config (sysroot, bootversion, 1, cancellable, error)) + goto out; + + ret = TRUE; + out: + if (context) + g_option_context_free (context); + return ret; +} diff --git a/pool/shard002/C/0059564_Sec6.c b/pool/shard002/C/0059564_Sec6.c new file mode 100644 index 0000000000000000000000000000000000000000..4b2b73c86e0c49bbd1b5da5752cda726a73632f0 --- /dev/null +++ b/pool/shard002/C/0059564_Sec6.c @@ -0,0 +1,54 @@ +#include +#include "grb2.h" +#include "wgrib2.h" +#include "fnlist.h" + +/* + * routines involving Section 6 + * public domain 2006: Wesley Ebisuzaki + * 1/2007: cleanup M. Schwarb + */ + +/* + * HEADER:700:bitmap:inv:0:bitmap mode + */ + + +int f_bitmap(ARG0) { + + int i; + unsigned int nmiss; + if (mode >= 0) { + i = code_table_6_0(sec); + if (i == 0) { +// nmiss = GB2_Sec3_npts(sec)-uint4(sec[5]+5); + nmiss = GB2_Sec3_npts(sec) - GB2_Sec5_nval(sec); + sprintf(inv_out,"bitmap %d undef pts", nmiss); + if (nmiss != missing_points(sec[6]+6, GB2_Sec3_npts(sec))) + fatal_error("inconsistent number of undefined points",""); + } + else if (i == 255) { + sprintf(inv_out,"no bitmap"); + } + else if (i == 254) { + sprintf(inv_out,"old bitmap"); + } + else { + sprintf(inv_out, "predefined bitmap #%d", i); + } + } + return 0; +} + +/* + * HEADER:700:Sec6:inv:0:show bit-map section + */ + +int f_Sec6(ARG0) { + + if (mode >= 0) { + sprintf(inv_out,"Sec6 length %u bitmap indicator %u", uint4(sec[6]), + (unsigned int) sec[6][5]); + } + return 0; +} diff --git a/pool/shard002/C/0059566_huffman-rar.c b/pool/shard002/C/0059566_huffman-rar.c new file mode 100644 index 0000000000000000000000000000000000000000..8fa6f593238415007cff7ecb470750e758715b7d --- /dev/null +++ b/pool/shard002/C/0059566_huffman-rar.c @@ -0,0 +1,149 @@ +/* Copyright 2018 the unarr project authors (see AUTHORS file). + License: LGPLv3 */ + +/* adapted from https://code.google.com/p/theunarchiver/source/browse/XADMaster/XADPrefixCode.m */ + +#include "rar.h" + +bool rar_new_node(struct huffman_code *code) +{ + if (!code->tree) { + code->minlength = INT_MAX; + code->maxlength = INT_MIN; + } + if (code->numentries + 1 >= code->capacity) { + /* in my small file sample, 1024 is the value needed most often */ + int new_capacity = code->capacity ? code->capacity * 2 : 1024; + void *new_tree = calloc(new_capacity, sizeof(*code->tree)); + if (!new_tree) { + warn("OOM during decompression"); + return false; + } + if (code->tree) { + memcpy(new_tree, code->tree, code->capacity * sizeof(*code->tree)); + free(code->tree); + } + code->tree = new_tree; + code->capacity = new_capacity; + } + /* if we have no code->tree at this point something went wrong */ + if (!code->tree) { + warn("Invalid huffman code tree, aborting"); + return false; + } + code->tree[code->numentries].branches[0] = -1; + code->tree[code->numentries].branches[1] = -2; + code->numentries++; + return true; +} + +bool rar_add_value(struct huffman_code *code, int value, int codebits, int length) +{ + int lastnode, bitpos, bit; + + free(code->table); + code->table = NULL; + + if (length > code->maxlength) + code->maxlength = length; + if (length < code->minlength) + code->minlength = length; + + lastnode = 0; + for (bitpos = length - 1; bitpos >= 0; bitpos--) { + bit = (codebits >> bitpos) & 1; + if (rar_is_leaf_node(code, lastnode)) { + warn("Invalid data in bitstream"); /* prefix found */ + return false; + } + if (code->tree[lastnode].branches[bit] < 0) { + if (!rar_new_node(code)) + return false; + code->tree[lastnode].branches[bit] = code->numentries - 1; + } + lastnode = code->tree[lastnode].branches[bit]; + } + + if (code->tree[lastnode].branches[0] != -1 || code->tree[lastnode].branches[1] != -2) { + warn("Invalid data in bitstream"); /* prefix found */ + return false; + } + code->tree[lastnode].branches[0] = code->tree[lastnode].branches[1] = value; + return true; +} + +bool rar_create_code(struct huffman_code *code, uint8_t *lengths, int numsymbols) +{ + int symbolsleft = numsymbols; + int codebits = 0; + int i, j; + + if (!rar_new_node(code)) + return false; + + for (i = 1; i <= 0x0F; i++) { + for (j = 0; j < numsymbols; j++) { + if (lengths[j] != i) + continue; + if (!rar_add_value(code, j, codebits, i)) + return false; + if (--symbolsleft <= 0) + return true; + codebits++; + } + codebits <<= 1; + } + return true; +} + +static bool rar_make_table_rec(struct huffman_code *code, int node, int offset, int depth, int maxdepth) +{ + int currtablesize = 1 << (maxdepth - depth); + + if (node < 0 || code->numentries <= node) { + warn("Invalid data in bitstream"); /* invalid location to Huffman tree specified */ + return false; + } + + if (rar_is_leaf_node(code, node)) { + int i; + for (i = 0; i < currtablesize; i++) { + code->table[offset + i].length = depth; + code->table[offset + i].value = code->tree[node].branches[0]; + } + } + else if (depth == maxdepth) { + code->table[offset].length = maxdepth + 1; + code->table[offset].value = node; + } + else { + if (!rar_make_table_rec(code, code->tree[node].branches[0], offset, depth + 1, maxdepth)) + return false; + if (!rar_make_table_rec(code, code->tree[node].branches[1], offset + currtablesize / 2, depth + 1, maxdepth)) + return false; + } + return true; +} + +bool rar_make_table(struct huffman_code *code) +{ + if (code->minlength <= code->maxlength && code->maxlength <= 10) + code->tablesize = code->maxlength; + else + code->tablesize = 10; + + code->table = calloc(1ULL << code->tablesize, sizeof(*code->table)); + if (!code->table) { + warn("OOM during decompression"); + return false; + } + + return rar_make_table_rec(code, 0, 0, 0, code->tablesize); +} + +void rar_free_code(struct huffman_code *code) +{ + free(code->tree); + free(code->table); + memset(code, 0, sizeof(*code)); +} diff --git a/pool/shard002/C/0059580_flowinfo_ipv4_icmp_test.c b/pool/shard002/C/0059580_flowinfo_ipv4_icmp_test.c new file mode 100644 index 0000000000000000000000000000000000000000..1faa3d6a8197d97e1604f92e9026c6438f1381eb --- /dev/null +++ b/pool/shard002/C/0059580_flowinfo_ipv4_icmp_test.c @@ -0,0 +1,94 @@ +/* + * Copyright 2014-2015 Nippon Telegraph and Telephone 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. + */ + + +#include "unity.h" + +#include "lagopus/dpmgr.h" +#include "lagopus/flowdb.h" +#include "lagopus/port.h" +#include "pktbuf.h" +#include "packet.h" +#include "lagopus/dataplane.h" +#include "lagopus/flowinfo.h" +#include "lagopus/ptree.h" +#include "datapath_test_misc.h" +#include "datapath_test_misc_macros.h" +#include "datapath_test_match.h" +#include "datapath_test_match_macros.h" +#include "flowinfo_test.h" + +#define FLOW_ADD_UT_PREREQUISITE(_x) \ + FLOW_ADD_IPV4_ICMP_PREREQUISITE(_x) +#define TEST_ASSERT_FLOW_MATCH_UT_PREREQUISITE(_x) \ + TEST_ASSERT_FLOW_MATCH_IPV4_ICMP_PREREQUISITE(_x) +#define ETHERTYPE_UT ETHERTYPE_IP +#define IPPROTO_UT IPPROTO_ICMP + +#include "flowinfo_l4_test.c" + + +/* Test ICMP type and code. */ +#define TEST_ICMP_TYPE(_s) ((uint8_t)((_s) + 1)) +#define TEST_ICMP_CODE(_s) ((uint8_t)((_s) + 1)) + + +/* + * The ICMP header matches are stored in the leaf basic flowinfo. del + * -> 2*add -> 3*del is hence sufficient. + */ + +void +test_flowinfo_ipv4_icmp_type_adddel(void) { + size_t s; + + TEST_ASSERT_OBJECTS(); + + /* Add the ICMP type matches. */ + for (s = 0; s < ARRAY_LEN(test_flow); s++) { + FLOW_ADD_ICMP_TYPE_MATCH(test_flow[s], TEST_ICMP_TYPE(s)); + } + + /* Run the sideeffect-free scenario. */ + TEST_SCENARIO_FLOWINFO_SEF(flowinfo); + + /* Reset the matches. Mind the prerequisite. */ + for (s = 0; s < ARRAY_LEN(test_flow); s++) { + TAILQ_INIT(&test_flow[s]->match_list); + FLOW_ADD_IPV4_ICMP_PREREQUISITE(test_flow[s]); + } +} + +void +test_flowinfo_ipv4_icmp_code_adddel(void) { + size_t s; + + TEST_ASSERT_OBJECTS(); + + /* Add the ICMP code matches. */ + for (s = 0; s < ARRAY_LEN(test_flow); s++) { + FLOW_ADD_ICMP_CODE_MATCH(test_flow[s], TEST_ICMP_CODE(s)); + } + + /* Run the sideeffect-free scenario. */ + TEST_SCENARIO_FLOWINFO_SEF(flowinfo); + + /* Reset the matches. Mind the prerequisite. */ + for (s = 0; s < ARRAY_LEN(test_flow); s++) { + TAILQ_INIT(&test_flow[s]->match_list); + FLOW_ADD_IPV4_ICMP_PREREQUISITE(test_flow[s]); + } +} diff --git a/pool/shard002/C/0059590_alloc.c b/pool/shard002/C/0059590_alloc.c new file mode 100644 index 0000000000000000000000000000000000000000..3ce6dd7a461a8e4d269f19b80d12077b7946ddb8 --- /dev/null +++ b/pool/shard002/C/0059590_alloc.c @@ -0,0 +1,82 @@ +/****************************************************************************** + * + * Copyright (C) 2014 The Android Open Source Project + * Copyright 2003 - 2004 Open Interface North America, Inc. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ******************************************************************************/ +#include "common/bt_target.h" +#include +#include + +#if (defined(SBC_DEC_INCLUDED) && SBC_DEC_INCLUDED == TRUE) + +/********************************************************************************** + $Revision: #1 $ +***********************************************************************************/ + +PRIVATE OI_STATUS OI_CODEC_SBC_Alloc(OI_CODEC_SBC_COMMON_CONTEXT *common, + OI_UINT32 *codecDataAligned, + OI_UINT32 codecDataBytes, + OI_UINT8 maxChannels, + OI_UINT8 pcmStride) +{ + int i; + size_t filterBufferCount; + size_t subdataSize; + OI_BYTE *codecData = (OI_BYTE *)codecDataAligned; + + if (maxChannels < 1 || maxChannels > 2) { + return OI_STATUS_INVALID_PARAMETERS; + } + + if (pcmStride < 1 || pcmStride > maxChannels) { + return OI_STATUS_INVALID_PARAMETERS; + } + + common->maxChannels = maxChannels; + common->pcmStride = pcmStride; + + /* Compute sizes needed for the memory regions, and bail if we don't have + * enough memory for them. */ + subdataSize = maxChannels * sizeof(common->subdata[0]) * SBC_MAX_BANDS * SBC_MAX_BLOCKS; + if (subdataSize > codecDataBytes) { + return OI_STATUS_OUT_OF_MEMORY; + } + + filterBufferCount = (codecDataBytes - subdataSize) / (sizeof(common->filterBuffer[0][0]) * SBC_MAX_BANDS * maxChannels); + if (filterBufferCount < SBC_CODEC_MIN_FILTER_BUFFERS) { + return OI_STATUS_OUT_OF_MEMORY; + } + common->filterBufferLen = filterBufferCount * SBC_MAX_BANDS; + + /* Allocate memory for the subband data */ + common->subdata = (OI_INT32 *)codecData; + codecData += subdataSize; + OI_ASSERT(codecDataBytes >= subdataSize); + codecDataBytes -= subdataSize; + + /* Allocate memory for the synthesis buffers */ + for (i = 0; i < maxChannels; ++i) { + size_t allocSize = common->filterBufferLen * sizeof(common->filterBuffer[0][0]); + common->filterBuffer[i] = (SBC_BUFFER_T *)codecData; + OI_ASSERT(codecDataBytes >= allocSize); + codecData += allocSize; + codecDataBytes -= allocSize; + } + + return OI_OK; +} + +#endif /* #if (defined(SBC_DEC_INCLUDED) && SBC_DEC_INCLUDED == TRUE) */ diff --git a/pool/shard002/C/0059592_intc.c b/pool/shard002/C/0059592_intc.c new file mode 100644 index 0000000000000000000000000000000000000000..d1caf1dbc239dedd765db95b09a6e4d7b4040c42 --- /dev/null +++ b/pool/shard002/C/0059592_intc.c @@ -0,0 +1,60 @@ +#include "intc.h" + +XStatus InitInterruptController(INTC* intc) { + int Status; + // Start the interrupt controller +#ifdef XPAR_INTC_0_DEVICE_ID + // Initialize the driver instance + RETURN_ON_FAILURE(XIntc_Initialize(intc, INTC_DEVICE_ID)); + RETURN_ON_FAILURE(XIntc_Start(intc, XIN_REAL_MODE)); + +#else + XScuGic_Config *GicConfig; + GicConfig = XScuGic_LookupConfig(INTC_DEVICE_ID); + XScuGic_CfgInitialize(intc, GicConfig, GicConfig->CpuBaseAddress); + Status = XScuGic_SelfTest(intc); + if (Status != XST_SUCCESS) { + return XST_FAILURE; + } +#endif + + Xil_ExceptionInit(); + + /* + * register the interrupt controller handler with the exception table. + * This is in fact the ISR dispatch routine, calling our ISRs + */ + Xil_ExceptionRegisterHandler(XIL_EXCEPTION_ID_INT, + (Xil_ExceptionHandler) INTC_HANDLER, intc); + Xil_ExceptionEnable(); + + return XST_SUCCESS; +} + +/* + * This function enables interrupts and connects interupt service routines + * declared in and interrupt vector table + */ +void EnableInterrupts(INTC *intc, const ivt_t *ivt, unsigned int IVectors) { + unsigned int isIVector; + + Xil_AssertVoid(intc != NULL); + //Xil_assertVoid(intc != NULL); + Xil_AssertVoid(intc->IsReady == XIL_COMPONENT_IS_READY); + + // Hook up interrupt service routines from the passed ivt + for (isIVector = 0; isIVector < IVectors; isIVector++) { + +#ifdef XPAR_INTC_0_DEVICE_ID + // Initialize the driver instance + XIntc_Connect(intc, ivt[isIVector].id, ivt[isIVector].handler, + ivt[isIVector].CallbackRef); + XIntc_Enable(intc, ivt[isIVector].id); + +#else + XScuGic_Connect(intc, ivt[isIVector].id, ivt[isIVector].handler, + ivt[isIVector].CallbackRef); + XScuGic_Enable(intc, ivt[isIVector].id); +#endif + } +} diff --git a/pool/shard002/C/0059597_device_irq.c b/pool/shard002/C/0059597_device_irq.c new file mode 100644 index 0000000000000000000000000000000000000000..c74c82f1f154f9d453bb0053669b3382553e5d88 --- /dev/null +++ b/pool/shard002/C/0059597_device_irq.c @@ -0,0 +1,150 @@ +/* + * Copyright 2014, NICTA + * + * This software may be distributed and modified according to the terms of + * the BSD 2-Clause license. Note that NO WARRANTY is provided. + * See "LICENSE_BSD2.txt" for details. + * + * @TAG(NICTA_BSD) + */ + +#include +#include +#include +#include +#include +#include +#include + +/*! @file + @brief Device IRQ handling library. */ + +void dev_irq_init(dev_irq_state_t *irqState, dev_irq_config_t config) +{ + assert(irqState); + memset(irqState, 0, sizeof(dev_irq_state_t)); + dprintf("Initialising IRQ handler state...\n"); + + if (config.numIRQChannels <= 0 || config.numIRQChannels >= DEVICE_IRQ_BADGE_MAX_CHANNELS) { + ROS_ERROR("config.numIRQChannels is invalid.\n"); + ROS_ERROR("IRQ handler init failed.\n"); + return; + } + if (!config.getIRQHandlerEndpoint) { + ROS_ERROR("Please provide a callback function for minting a IRQ handler cap.\n"); + ROS_ERROR("IRQ handler init failed.\n"); + return; + } + if (!config.notifyAsyncEP) { + ROS_ERROR("Please provide an async endpoint to mint IRQ badges from.\n"); + ROS_ERROR("IRQ handler init failed.\n"); + return; + } + + /* Initialise IRQ channel table. */ + for (int i = 0; i < config.numIRQChannels; i++) { + cvector_init(&irqState->channel[i]); + } + + irqState->cfg = config; + irqState->magic = DEVICE_IRQ_MAGIC; +} + +int dev_handle_irq(dev_irq_state_t *irqState, uint32_t irq, + dev_irq_callback_fn_t callback, void *cookie) +{ + assert(irqState && irqState->magic == DEVICE_IRQ_MAGIC); + + if (irq >= DEVICE_MAX_IRQ) { + ROS_ERROR("dev_handle_irq IRQ num too high. Try raising DEVICE_MAX_IRQ."); + assert(!"Try raising DEVICE_MAX_IRQ."); + return EINVALIDPARAM; + } + + /* Retrieve the handler, if necessary. */ + if (!irqState->handler[irq].handler) { + assert(irqState->cfg.getIRQHandlerEndpoint); + irqState->handler[irq].handler = irqState->cfg.getIRQHandlerEndpoint( + irqState->cfg.getIRQHandlerEndpointCookie, irq + ); + if (!irqState->handler[irq].handler) { + ROS_WARNING("dev_handle_irq : could not get IRQ handler for irq %u.\n", irq); + return EINVALID; + } + } + + /* Determine next round-robin channel to go in. */ + uint32_t nextChannel = irqState->cfg.badgeBaseBit + irqState->nextIRQChannel; + cvector_add(&irqState->channel[irqState->nextIRQChannel], (cvector_item_t) irq); + irqState->nextIRQChannel = (irqState->nextIRQChannel + 1) % irqState->cfg.numIRQChannels; + + /* Mint the badged AEP. */ + assert(irqState->cfg.notifyAsyncEP); + seL4_CPtr irqBadge = srv_mint((1 << nextChannel) | irqState->cfg.badgeMaskBits, + irqState->cfg.notifyAsyncEP); + if (!irqBadge) { + ROS_WARNING("dev_handle_irq : could not mint badged aep for irq %u.\n", irq); + return EINVALID; + } + + /* Assign AEP to the IRQ handler. */ + int error = seL4_IRQHandler_SetEndpoint(irqState->handler[irq].handler, irqBadge); + if (error) { + ROS_WARNING("dev_handle_irq : could not set notify aep for irq %u.\n", irq); + csfree_delete(irqBadge); + return EINVALID; + } + seL4_IRQHandler_Ack(irqState->handler[irq].handler); + + /* Set callback function and cookie. */ + irqState->handler[irq].callback = callback; + irqState->handler[irq].cookie = cookie; + + csfree_delete(irqBadge); + return ESUCCESS; +} + +int dev_dispatch_interrupt(dev_irq_state_t *irqState, srv_msg_t *m) +{ + assert(irqState && irqState->magic == DEVICE_IRQ_MAGIC); + + if ((m->badge & irqState->cfg.badgeMaskBits) == 0) { + return DISPATCH_PASS; + } + + /* Loop through every bit in the bitmask to determine which IRQs fired. */ + bool IRQFound = false; + for (int i = 0; i < irqState->cfg.numIRQChannels; i++) { + if (m->badge & (1 << (irqState->cfg.badgeBaseBit + i))) { + IRQFound = true; + + /* Go through every IRQ clash. If the server needs to handle a lot of different IRQs + then this will lead to false positives. This seems to be a kernel API limitation + of a single threaded server design. More threads listening to multiple endpoints + will avoid this problem of IRQ clash. + + Hopefully in practical environments, this won't be a problem since we probably won't + have a small system that needs a lot of different interrupts. + */ + int nIRQs = cvector_count(&irqState->channel[i]); + for (int j = 0; j < nIRQs; j++) { + uint32_t irq = (uint32_t) cvector_get(&irqState->channel[i], j); + assert (irq < DEVICE_MAX_IRQ); + + if (irqState->handler[irq].callback) { + irqState->handler[irq].callback(irqState->handler[irq].cookie, irq); + } + if (irqState->handler[irq].handler) { + seL4_IRQHandler_Ack(irqState->handler[irq].handler); + } + } + + } + } + + if (!IRQFound) { + return DISPATCH_PASS; + } + + return DISPATCH_SUCCESS; +} \ No newline at end of file diff --git a/pool/shard002/C/0059620_moto_flashmdm.c b/pool/shard002/C/0059620_moto_flashmdm.c new file mode 100644 index 0000000000000000000000000000000000000000..49170f573471c0a53f0a35ae8a1285db7f99e31e --- /dev/null +++ b/pool/shard002/C/0059620_moto_flashmdm.c @@ -0,0 +1,143 @@ +/* + * Motorola Modem flash mode driver + * + * Copyright (C) 2008 Greg Kroah-Hartman + * Copyright (C) 2009 Motorola, Inc. + * + * 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 +#if defined(CONFIG_ARCH_OMAP34XX) +#include "../host/ehci-omap.h" +#endif + +static struct usb_device_id id_table[] = { + {USB_DEVICE_AND_INTERFACE_INFO(0x22b8, 0x2db4, 0x0a, 0, 0xfc)}, + {USB_DEVICE_AND_INTERFACE_INFO(0x22b8, 0x4281, 0x0a, 0, 0xfc)}, + {USB_DEVICE(0x22b8, 0x4260)}, /* wrigley in flash mode */ + {USB_DEVICE(0x22b8, 0x426d)}, /* wrigley in flash bl3080 */ + {}, +}; + +MODULE_DEVICE_TABLE(usb, id_table); + +#define MOTO_FLASHMDM_BULKOUT_SIZE 8192 + +#if defined(CONFIG_ARCH_OMAP34XX) +/* disable the uhh_sysconfig auto idle bit, + * so that, host iclk will not be disabled and BP + * can re-enumerated on AP + */ +static void omap_flashmdm_disable_uhh_smart_idle(void) +{ + u32 sysconfig; + + sysconfig = omap_readl(OMAP_UHH_SYSCONFIG); + sysconfig &= ~(1 << OMAP_UHH_SYSCONFIG_AUTOIDLE_SHIFT); + omap_writel(sysconfig, OMAP_UHH_SYSCONFIG); +} +#endif + +static int moto_flashmdm_attach(struct usb_serial *serial) +{ + struct usb_serial_port *port = serial->port[0]; + int i; + + if (port->bulk_out_size >= MOTO_FLASHMDM_BULKOUT_SIZE) { + dev_info(&serial->dev->dev, + "bulk_out_size %d\n", port->bulk_out_size); + return 0; + } + + kfree(port->bulk_out_buffer); + port->bulk_out_size = MOTO_FLASHMDM_BULKOUT_SIZE; + port->bulk_out_buffer = kmalloc(port->bulk_out_size, GFP_KERNEL); + if (!port->bulk_out_buffer) { + dev_err(&serial->dev->dev, + "Couldn't allocate bulk_out_buffer\n"); + return -ENOMEM; + } + usb_fill_bulk_urb(port->write_urb, serial->dev, + usb_sndbulkpipe(serial->dev, + port->bulk_out_endpointAddress), + port->bulk_out_buffer, port->bulk_out_size, + serial->type->write_bulk_callback, port); + + for (i = 0; i < ARRAY_SIZE(port->write_urbs); ++i) { + kfree(port->bulk_out_buffers[i]); + port->bulk_out_buffers[i] = kmalloc(port->bulk_out_size, + GFP_KERNEL); + if (!port->bulk_out_buffers[i]) { + dev_err(&serial->dev->dev, + "Couldn't allocate bulk_out_buffer\n"); + return -ENOMEM; + } + usb_fill_bulk_urb(port->write_urbs[i], serial->dev, + usb_sndbulkpipe(serial->dev, + port->bulk_out_endpointAddress), + port->bulk_out_buffers[i], port->bulk_out_size, + serial->type->write_bulk_callback, port); + } + +#if defined(CONFIG_ARCH_OMAP34XX) + /* need to disable the AUTO IDLE for the usb iclk */ + omap_flashmdm_disable_uhh_smart_idle(); +#endif + + return 0; +} + +static struct usb_driver moto_flashmdm_driver = { + .name = "moto-flashmdm", + .probe = usb_serial_probe, + .disconnect = usb_serial_disconnect, + .id_table = id_table, + .no_dynamic_id = 1, + +}; + +static struct usb_serial_driver moto_flashmdm_device = { + .driver = { + .owner = THIS_MODULE, + .name = "moto-flashmdm", + }, + .id_table = id_table, + .num_ports = 1, + .attach = moto_flashmdm_attach, +}; + +static int __init moto_flashmdm_init(void) +{ + int retval; + + retval = usb_serial_register(&moto_flashmdm_device); + if (retval) + return retval; + retval = usb_register(&moto_flashmdm_driver); + if (retval) + usb_serial_deregister(&moto_flashmdm_device); + return retval; +} + +static void __exit moto_flashmdm_exit(void) +{ + usb_deregister(&moto_flashmdm_driver); + usb_serial_deregister(&moto_flashmdm_device); +} + +module_init(moto_flashmdm_init); +module_exit(moto_flashmdm_exit); +MODULE_LICENSE("GPL"); + diff --git a/pool/shard002/C/0059621_ui_spinner.c b/pool/shard002/C/0059621_ui_spinner.c new file mode 100644 index 0000000000000000000000000000000000000000..e1d5a546b92d5eb315a5efbaf1fbc6213d8d9d30 --- /dev/null +++ b/pool/shard002/C/0059621_ui_spinner.c @@ -0,0 +1,214 @@ +/* + * (SLIK) SimpLIstic sKin functions + * (C) 2004 John Ellis + * Copyright (C) 2008 - 2012 The Geeqie Team + * + * Author: John Ellis + * + * This software is released under the GNU General Public License (GNU GPL). + * Please read the included file COPYING for more information. + * This software comes with no warranty of any kind, use at your own risk! + */ + +#ifdef HAVE_CONFIG_H +# include "config.h" +#endif +#include "intl.h" + +#include +#include +#include + +#include + +#include "main.h" +#include "ui_spinner.h" + +#include "ui_icons.h" +#include "ui_fileops.h" + + +#define SPINNER_FRAMES 19 + + +/* + *----------------------------------------------------------------------------- + * spinner utility + *----------------------------------------------------------------------------- + */ + +typedef struct _SpinnerData SpinnerData; +struct _SpinnerData { + GtkWidget *image; + GList *list; /* list of pixbufs */ + guint frame; + guint timer_id; /* event source id */ +}; + +static void spinner_set_frame(SpinnerData *sp, guint frame) +{ + GdkPixbuf *pb; + + pb = g_list_nth_data(sp->list, frame); + if (pb) gtk_image_set_from_pixbuf(GTK_IMAGE(sp->image), pb); + + sp->frame = frame; +} + +static void spinner_increment_frame(SpinnerData *sp) +{ + sp->frame++; + if (sp->frame >= g_list_length(sp->list)) sp->frame = 1; + spinner_set_frame(sp, sp->frame); +} + +static gboolean spinner_loop_cb(gpointer data) +{ + SpinnerData *sp = data; + + if (sp->list) spinner_increment_frame(sp); + + return TRUE; +} + +static void spinner_set_timeout(SpinnerData *sp, gint interval) +{ + if (!sp) return; + + if (sp->timer_id) + { + g_source_remove(sp->timer_id); + sp->timer_id = 0; + } + + if (interval > 0) + { + sp->timer_id = g_timeout_add(interval, spinner_loop_cb, sp); + } + else if (interval < 0) + { + spinner_set_frame(sp, 0); + } + + gtk_widget_set_sensitive(sp->image, (interval >= 0)); +} + +static void spinner_destroy_cb(GtkWidget *widget, gpointer data) +{ + SpinnerData *sp = data; + GList *work; + + spinner_set_timeout(sp, 0); + + work = sp->list; + while (work) + { + GdkPixbuf *pb = work->data; + work = work->next; + + g_object_unref(pb); + } + g_list_free(sp->list); + g_free(sp); +} + +GtkWidget *spinner_new(const gchar *path, gint interval) +{ + SpinnerData *sp; + + sp = g_new0(SpinnerData, 1); + + if (path) + { + gchar *pathl; + GdkPixbuf *pb; + gint n; + gchar *buf; + + pathl = path_from_utf8(path); + + n = 0; + buf = g_strdup_printf("%s%02d.png", pathl, n); + while ((pb = gdk_pixbuf_new_from_file(buf, NULL))) + { + sp->list = g_list_append(sp->list, pb); + + n++; + g_free(buf); + buf = g_strdup_printf("%s%02d.png", pathl, n); + } + g_free(buf); + + g_free(pathl); + } + + if (!sp->list) + { + GdkPixbuf *pb; + gint n; + gint w, h; + + pb = gdk_pixbuf_new_from_inline(-1, icon_spinner, FALSE, NULL); + w = gdk_pixbuf_get_width(pb); + h = gdk_pixbuf_get_height(pb) / SPINNER_FRAMES; + for (n = 0; n < SPINNER_FRAMES; n++) + { + sp->list = g_list_append(sp->list, + gdk_pixbuf_new_subpixbuf(pb, 0, n * h, w, h)); + } + /* pb pixels is inline static, so the subpixbufs in sp->list will be ok */ + g_object_unref(pb); + } + + if (sp->list) + { + GdkPixbuf *pb; + + pb = sp->list->data; + sp->image = gtk_image_new_from_pixbuf(pb); + } + else + { + sp->image = gtk_image_new_from_stock(GTK_STOCK_MISSING_IMAGE, GTK_ICON_SIZE_DIALOG); + } + + g_object_set_data(G_OBJECT(sp->image), "spinner", sp); + + g_signal_connect(G_OBJECT(sp->image), "destroy", + G_CALLBACK(spinner_destroy_cb), sp); + + spinner_set_timeout(sp, interval); + + return sp->image; +} + +void spinner_set_interval(GtkWidget *spinner, gint interval) +{ + SpinnerData *sp; + + sp = g_object_get_data(G_OBJECT(spinner), "spinner"); + + spinner_set_timeout(sp, interval); +} + +void spinner_step(GtkWidget *spinner, gboolean reset) +{ + SpinnerData *sp; + + sp = g_object_get_data(G_OBJECT(spinner), "spinner"); + if (sp->timer_id) + { + log_printf("spinner warning: attempt to step with timer set\n"); + return; + } + + if (reset) + { + spinner_set_frame(sp, 0); + } + else + { + spinner_increment_frame(sp); + } +} +/* vim: set shiftwidth=8 softtabstop=0 cindent cinoptions={1s: */ diff --git a/pool/shard002/C/0059624_mknod09.c b/pool/shard002/C/0059624_mknod09.c new file mode 100644 index 0000000000000000000000000000000000000000..5a0c4ae50eff35afee80d095d4b5d64530194280 --- /dev/null +++ b/pool/shard002/C/0059624_mknod09.c @@ -0,0 +1,171 @@ +/* + * Copyright (C) Bull S.A. 2001 + * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ +/* + * Test Name: mknod09 + * + * Test Description: + * Verify that, mknod() fails with -1 and sets errno to EINVAL if the mode is + * different than a normal file, device special file or FIFO. + * + * Expected Result: + * mknod() should fail with return value -1 and sets expected errno. + * + * Algorithm: + * Setup: + * Setup signal handling. + * Check id is super/root + * Pause for SIGUSR1 if option specified. + * Create temporary directory. + * + * Test: + * Loop if the proper options are given. + * Execute system call + * Check return code, if system call failed (return=-1) + * if errno set == expected errno + * Issue sys call fails with expected return value and errno. + * Otherwise, + * Issue sys call fails with unexpected errno. + * Otherwise, + * Issue sys call returns unexpected value. + * + * Cleanup: + * Print errno log and/or timing stats if options given + * Delete the temporary directory created. + * + * Usage: + * mknod09 [-c n] [-e] [-f] [-i n] [-I x] [-P x] [-t] + * where, -c n : Run n copies concurrently. + * -e : Turn on errno logging. + * -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 + * 05/2002 Ported by André Merlier + * + * RESTRICTIONS: + * This test should be run by 'super-user' (root) only. + * + */ + +#include +#include +#include "test.h" +#include "usctest.h" + +#define MODE_RWX S_IFMT /* mode different from those expected */ +#define TNODE "tnode" /*pathname */ + +char *TCID = "mknod09"; /* Test program identifier. */ +int TST_TOTAL = 1; /* Total number of test cases. */ +int exp_enos[] = { EINVAL, 0 }; + +void setup(); /* setup function for the test */ +void cleanup(); /* cleanup function for the test */ + +int main(int ac, char **av) +{ + int lc; /* loop counter */ + char *msg; /* message returned from parse_opts */ + char *test_desc; /* test specific error message */ + + /* Parse standard options given to run the test. */ + msg = parse_opts(ac, av, NULL, NULL); + if (msg != NULL) { + tst_brkm(TBROK, NULL, "OPTION PARSING ERROR - %s", msg); + + } + + setup(); + + /* set the expected errnos... */ + TEST_EXP_ENOS(exp_enos); + + for (lc = 0; TEST_LOOPING(lc); lc++) { + test_desc = "EINVAL"; + + Tst_count = 0; + + /* + * Call mknod(2) to test condition. + * verify that it fails with -1 return value and + * sets appropriate errno. + */ + TEST(mknod(TNODE, MODE_RWX, 0)); + + /* Check return code from mknod(2) */ + if (TEST_RETURN != -1) { + tst_resm(TFAIL, "mknod() returned %ld," + "expected -1, errno=%d", TEST_RETURN, + exp_enos[0]); + } else { + TEST_ERROR_LOG(TEST_ERRNO); + + if (TEST_ERRNO == exp_enos[0]) { + tst_resm(TPASS, "mknod() fails with expected " + "error EINVAL errno:%d", TEST_ERRNO); + } else { + tst_resm(TFAIL, "mknod() fails, %s, " + "errno=%d, expected errno=%d", + test_desc, TEST_ERRNO, exp_enos[0]); + } + } + } + + cleanup(); + + tst_exit(); +} + +/* + * setup(void) + */ +void setup() +{ + /* Capture unexpected signals */ + tst_sig(NOFORK, DEF_HANDLER, cleanup); + + /* Check that the test process id is super/root */ + if (geteuid() != 0) { + tst_brkm(TBROK, NULL, "Must be super/root for this test!"); + tst_exit(); + } + + TEST_PAUSE; + + /* Make a temp dir and cd to it */ + tst_tmpdir(); +} + +/* + * cleanup() + */ +void cleanup() +{ + /* + * print timing stats if that option was specified. + * print errno log if that option was specified. + */ + TEST_CLEANUP; + + tst_rmdir(); + +} \ No newline at end of file diff --git a/pool/shard002/C/0059650_pack_r16.c b/pool/shard002/C/0059650_pack_r16.c new file mode 100644 index 0000000000000000000000000000000000000000..c18fd6ca08077332f5c4019a9e19bcafcf4c2ce2 --- /dev/null +++ b/pool/shard002/C/0059650_pack_r16.c @@ -0,0 +1,259 @@ +/* Specific implementation of the PACK intrinsic + Copyright (C) 2002-2013 Free Software Foundation, Inc. + Contributed by Paul Brook + +This file is part of the GNU Fortran runtime library (libgfortran). + +Libgfortran is free software; you can redistribute it and/or +modify it under the terms of the GNU General Public +License as published by the Free Software Foundation; either +version 3 of the License, or (at your option) any later version. + +Ligbfortran is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +Under Section 7 of GPL version 3, you are granted additional +permissions described in the GCC Runtime Library Exception, version +3.1, as published by the Free Software Foundation. + +You should have received a copy of the GNU General Public License and +a copy of the GCC Runtime Library Exception along with this program; +see the files COPYING3 and COPYING.RUNTIME respectively. If not, see +. */ + +#include "libgfortran.h" +#include +#include +#include + + +#if defined (HAVE_GFC_REAL_16) + +/* PACK is specified as follows: + + 13.14.80 PACK (ARRAY, MASK, [VECTOR]) + + Description: Pack an array into an array of rank one under the + control of a mask. + + Class: Transformational function. + + Arguments: + ARRAY may be of any type. It shall not be scalar. + MASK shall be of type LOGICAL. It shall be conformable with ARRAY. + VECTOR (optional) shall be of the same type and type parameters + as ARRAY. VECTOR shall have at least as many elements as + there are true elements in MASK. If MASK is a scalar + with the value true, VECTOR shall have at least as many + elements as there are in ARRAY. + + Result Characteristics: The result is an array of rank one with the + same type and type parameters as ARRAY. If VECTOR is present, the + result size is that of VECTOR; otherwise, the result size is the + number /t/ of true elements in MASK unless MASK is scalar with the + value true, in which case the result size is the size of ARRAY. + + Result Value: Element /i/ of the result is the element of ARRAY + that corresponds to the /i/th true element of MASK, taking elements + in array element order, for /i/ = 1, 2, ..., /t/. If VECTOR is + present and has size /n/ > /t/, element /i/ of the result has the + value VECTOR(/i/), for /i/ = /t/ + 1, ..., /n/. + + Examples: The nonzero elements of an array M with the value + | 0 0 0 | + | 9 0 0 | may be "gathered" by the function PACK. The result of + | 0 0 7 | + PACK (M, MASK = M.NE.0) is [9,7] and the result of PACK (M, M.NE.0, + VECTOR = (/ 2,4,6,8,10,12 /)) is [9,7,6,8,10,12]. + +There are two variants of the PACK intrinsic: one, where MASK is +array valued, and the other one where MASK is scalar. */ + +void +pack_r16 (gfc_array_r16 *ret, const gfc_array_r16 *array, + const gfc_array_l1 *mask, const gfc_array_r16 *vector) +{ + /* r.* indicates the return array. */ + index_type rstride0; + GFC_REAL_16 * restrict rptr; + /* s.* indicates the source array. */ + index_type sstride[GFC_MAX_DIMENSIONS]; + index_type sstride0; + const GFC_REAL_16 *sptr; + /* m.* indicates the mask array. */ + index_type mstride[GFC_MAX_DIMENSIONS]; + index_type mstride0; + const GFC_LOGICAL_1 *mptr; + + index_type count[GFC_MAX_DIMENSIONS]; + index_type extent[GFC_MAX_DIMENSIONS]; + int zero_sized; + index_type n; + index_type dim; + index_type nelem; + index_type total; + int mask_kind; + + dim = GFC_DESCRIPTOR_RANK (array); + + mptr = mask->base_addr; + + /* Use the same loop for all logical types, by using GFC_LOGICAL_1 + and using shifting to address size and endian issues. */ + + mask_kind = GFC_DESCRIPTOR_SIZE (mask); + + if (mask_kind == 1 || mask_kind == 2 || mask_kind == 4 || mask_kind == 8 +#ifdef HAVE_GFC_LOGICAL_16 + || mask_kind == 16 +#endif + ) + { + /* Do not convert a NULL pointer as we use test for NULL below. */ + if (mptr) + mptr = GFOR_POINTER_TO_L1 (mptr, mask_kind); + } + else + runtime_error ("Funny sized logical array"); + + zero_sized = 0; + for (n = 0; n < dim; n++) + { + count[n] = 0; + extent[n] = GFC_DESCRIPTOR_EXTENT(array,n); + if (extent[n] <= 0) + zero_sized = 1; + sstride[n] = GFC_DESCRIPTOR_STRIDE(array,n); + mstride[n] = GFC_DESCRIPTOR_STRIDE_BYTES(mask,n); + } + if (sstride[0] == 0) + sstride[0] = 1; + if (mstride[0] == 0) + mstride[0] = mask_kind; + + if (zero_sized) + sptr = NULL; + else + sptr = array->base_addr; + + if (ret->base_addr == NULL || unlikely (compile_options.bounds_check)) + { + /* Count the elements, either for allocating memory or + for bounds checking. */ + + if (vector != NULL) + { + /* The return array will have as many + elements as there are in VECTOR. */ + total = GFC_DESCRIPTOR_EXTENT(vector,0); + if (total < 0) + { + total = 0; + vector = NULL; + } + } + else + { + /* We have to count the true elements in MASK. */ + total = count_0 (mask); + } + + if (ret->base_addr == NULL) + { + /* Setup the array descriptor. */ + GFC_DIMENSION_SET(ret->dim[0], 0, total-1, 1); + + ret->offset = 0; + + /* xmallocarray allocates a single byte for zero size. */ + ret->base_addr = xmallocarray (total, sizeof (GFC_REAL_16)); + + if (total == 0) + return; + } + else + { + /* We come here because of range checking. */ + index_type ret_extent; + + ret_extent = GFC_DESCRIPTOR_EXTENT(ret,0); + if (total != ret_extent) + runtime_error ("Incorrect extent in return value of PACK intrinsic;" + " is %ld, should be %ld", (long int) total, + (long int) ret_extent); + } + } + + rstride0 = GFC_DESCRIPTOR_STRIDE(ret,0); + if (rstride0 == 0) + rstride0 = 1; + sstride0 = sstride[0]; + mstride0 = mstride[0]; + rptr = ret->base_addr; + + while (sptr && mptr) + { + /* Test this element. */ + if (*mptr) + { + /* Add it. */ + *rptr = *sptr; + rptr += rstride0; + } + /* Advance to the next element. */ + sptr += sstride0; + mptr += mstride0; + count[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. */ + sptr -= sstride[n] * extent[n]; + mptr -= mstride[n] * extent[n]; + n++; + if (n >= dim) + { + /* Break out of the loop. */ + sptr = NULL; + break; + } + else + { + count[n]++; + sptr += sstride[n]; + mptr += mstride[n]; + } + } + } + + /* Add any remaining elements from VECTOR. */ + if (vector) + { + n = GFC_DESCRIPTOR_EXTENT(vector,0); + nelem = ((rptr - ret->base_addr) / rstride0); + if (n > nelem) + { + sstride0 = GFC_DESCRIPTOR_STRIDE(vector,0); + if (sstride0 == 0) + sstride0 = 1; + + sptr = vector->base_addr + sstride0 * nelem; + n -= nelem; + while (n--) + { + *rptr = *sptr; + rptr += rstride0; + sptr += sstride0; + } + } + } +} + +#endif + diff --git a/pool/shard002/C/0059669_sunxi_cedrus.c b/pool/shard002/C/0059669_sunxi_cedrus.c new file mode 100644 index 0000000000000000000000000000000000000000..3001440de850c89a0a0f8283c186a1c64400da78 --- /dev/null +++ b/pool/shard002/C/0059669_sunxi_cedrus.c @@ -0,0 +1,285 @@ +/* + * Sunxi Cedrus codec driver + * + * Copyright (C) 2016 Florent Revest + * Florent Revest + * + * Based on vim2m + * + * Copyright (c) 2009-2010 Samsung Electronics Co., Ltd. + * Pawel Osciak, + * Marek Szyprowski, + * + * 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 "sunxi_cedrus_common.h" + +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +#include "sunxi_cedrus_dec.h" +#include "sunxi_cedrus_hw.h" + +static int sunxi_cedrus_s_ctrl(struct v4l2_ctrl *ctrl) +{ + struct sunxi_cedrus_ctx *ctx = + container_of(ctrl->handler, struct sunxi_cedrus_ctx, hdl); + + switch (ctrl->id) { + case V4L2_CID_MPEG_VIDEO_MPEG4_FRAME_HDR: + case V4L2_CID_MPEG_VIDEO_MPEG2_FRAME_HDR: + /* This is kept in memory and used directly. */ + break; + default: + v4l2_err(&ctx->dev->v4l2_dev, "Invalid control\n"); + return -EINVAL; + } + + return 0; +} + +static const struct v4l2_ctrl_ops sunxi_cedrus_ctrl_ops = { + .s_ctrl = sunxi_cedrus_s_ctrl, +}; + +static const struct v4l2_ctrl_config sunxi_cedrus_ctrl_mpeg2_frame_hdr = { + .ops = &sunxi_cedrus_ctrl_ops, + .id = V4L2_CID_MPEG_VIDEO_MPEG2_FRAME_HDR, + .type = V4L2_CTRL_TYPE_PRIVATE, + .name = "MPEG2 Frame Header Parameters", + .max_reqs = VIDEO_MAX_FRAME, + .elem_size = sizeof(struct v4l2_ctrl_mpeg2_frame_hdr), +}; + +static const struct v4l2_ctrl_config sunxi_cedrus_ctrl_mpeg4_frame_hdr = { + .ops = &sunxi_cedrus_ctrl_ops, + .id = V4L2_CID_MPEG_VIDEO_MPEG4_FRAME_HDR, + .type = V4L2_CTRL_TYPE_PRIVATE, + .name = "MPEG4 Frame Header Parameters", + .max_reqs = VIDEO_MAX_FRAME, + .elem_size = sizeof(struct v4l2_ctrl_mpeg4_frame_hdr), +}; + +/* + * File operations + */ +static int sunxi_cedrus_open(struct file *file) +{ + struct sunxi_cedrus_dev *dev = video_drvdata(file); + struct sunxi_cedrus_ctx *ctx = NULL; + struct v4l2_ctrl_handler *hdl; + int rc = 0; + + if (mutex_lock_interruptible(&dev->dev_mutex)) + return -ERESTARTSYS; + ctx = kzalloc(sizeof(*ctx), GFP_KERNEL); + if (!ctx) { + rc = -ENOMEM; + goto open_unlock; + } + + v4l2_fh_init(&ctx->fh, video_devdata(file)); + file->private_data = &ctx->fh; + ctx->dev = dev; + hdl = &ctx->hdl; + v4l2_ctrl_handler_init(hdl, 1); + + ctx->mpeg2_frame_hdr_ctrl = v4l2_ctrl_new_custom(hdl, + &sunxi_cedrus_ctrl_mpeg2_frame_hdr, NULL); + ctx->mpeg2_frame_hdr_ctrl->flags |= V4L2_CTRL_FLAG_REQ_KEEP; + + ctx->mpeg4_frame_hdr_ctrl = v4l2_ctrl_new_custom(hdl, + &sunxi_cedrus_ctrl_mpeg4_frame_hdr, NULL); + ctx->mpeg4_frame_hdr_ctrl->flags |= V4L2_CTRL_FLAG_REQ_KEEP; + + if (hdl->error) { + rc = hdl->error; + v4l2_ctrl_handler_free(hdl); + goto open_unlock; + } + ctx->fh.ctrl_handler = hdl; + v4l2_ctrl_handler_setup(hdl); + + ctx->fh.m2m_ctx = v4l2_m2m_ctx_init(dev->m2m_dev, ctx, &queue_init); + + if (IS_ERR(ctx->fh.m2m_ctx)) { + rc = PTR_ERR(ctx->fh.m2m_ctx); + + v4l2_ctrl_handler_free(hdl); + kfree(ctx); + goto open_unlock; + } + + v4l2_fh_add(&ctx->fh); + + dev_dbg(dev->dev, "Created instance: %p, m2m_ctx: %p\n", + ctx, ctx->fh.m2m_ctx); + +open_unlock: + mutex_unlock(&dev->dev_mutex); + return rc; +} + +static int sunxi_cedrus_release(struct file *file) +{ + struct sunxi_cedrus_dev *dev = video_drvdata(file); + struct sunxi_cedrus_ctx *ctx = container_of(file->private_data, + struct sunxi_cedrus_ctx, fh); + + dev_dbg(dev->dev, "Releasing instance %p\n", ctx); + + v4l2_fh_del(&ctx->fh); + v4l2_fh_exit(&ctx->fh); + v4l2_ctrl_handler_free(&ctx->hdl); + ctx->mpeg2_frame_hdr_ctrl = NULL; + ctx->mpeg4_frame_hdr_ctrl = NULL; + mutex_lock(&dev->dev_mutex); + v4l2_m2m_ctx_release(ctx->fh.m2m_ctx); + mutex_unlock(&dev->dev_mutex); + kfree(ctx); + + return 0; +} + +static const struct v4l2_file_operations sunxi_cedrus_fops = { + .owner = THIS_MODULE, + .open = sunxi_cedrus_open, + .release = sunxi_cedrus_release, + .poll = v4l2_m2m_fop_poll, + .unlocked_ioctl = video_ioctl2, + .mmap = v4l2_m2m_fop_mmap, +}; + +static struct video_device sunxi_cedrus_viddev = { + .name = SUNXI_CEDRUS_NAME, + .vfl_dir = VFL_DIR_M2M, + .fops = &sunxi_cedrus_fops, + .ioctl_ops = &sunxi_cedrus_ioctl_ops, + .minor = -1, + .release = video_device_release_empty, +}; + +static struct v4l2_m2m_ops m2m_ops = { + .device_run = device_run, + .job_abort = job_abort, +}; + +static int sunxi_cedrus_probe(struct platform_device *pdev) +{ + struct sunxi_cedrus_dev *dev; + struct video_device *vfd; + int ret; + + dev = devm_kzalloc(&pdev->dev, sizeof(*dev), GFP_KERNEL); + if (!dev) + return -ENOMEM; + + dev->dev = &pdev->dev; + dev->pdev = pdev; + + ret = sunxi_cedrus_hw_probe(dev); + if (ret) { + dev_err(&pdev->dev, "sunxi_cedrus_hw_probe failed\n"); + return ret; + } + + spin_lock_init(&dev->irqlock); + + ret = v4l2_device_register(&pdev->dev, &dev->v4l2_dev); + if (ret) + return ret; + + mutex_init(&dev->dev_mutex); + + dev->vfd = sunxi_cedrus_viddev; + vfd = &dev->vfd; + vfd->lock = &dev->dev_mutex; + vfd->v4l2_dev = &dev->v4l2_dev; + + ret = video_register_device(vfd, VFL_TYPE_GRABBER, 0); + if (ret) { + v4l2_err(&dev->v4l2_dev, "Failed to register video device\n"); + goto unreg_dev; + } + + video_set_drvdata(vfd, dev); + snprintf(vfd->name, sizeof(vfd->name), "%s", sunxi_cedrus_viddev.name); + v4l2_info(&dev->v4l2_dev, + "Device registered as /dev/video%d\n", vfd->num); + + platform_set_drvdata(pdev, dev); + + dev->m2m_dev = v4l2_m2m_init(&m2m_ops); + if (IS_ERR(dev->m2m_dev)) { + v4l2_err(&dev->v4l2_dev, "Failed to init mem2mem device\n"); + ret = PTR_ERR(dev->m2m_dev); + goto err_m2m; + } + + return 0; + +err_m2m: + v4l2_m2m_release(dev->m2m_dev); + video_unregister_device(&dev->vfd); +unreg_dev: + v4l2_device_unregister(&dev->v4l2_dev); + + return ret; +} + +static int sunxi_cedrus_remove(struct platform_device *pdev) +{ + struct sunxi_cedrus_dev *dev = platform_get_drvdata(pdev); + + v4l2_info(&dev->v4l2_dev, "Removing " SUNXI_CEDRUS_NAME); + v4l2_m2m_release(dev->m2m_dev); + video_unregister_device(&dev->vfd); + v4l2_device_unregister(&dev->v4l2_dev); + sunxi_cedrus_hw_remove(dev); + + return 0; +} + +#ifdef CONFIG_OF +static const struct of_device_id of_sunxi_cedrus_match[] = { + { .compatible = "allwinner,sun5i-a13-video-engine" }, + { /* sentinel */ } +}; +MODULE_DEVICE_TABLE(of, of_sunxi_cedrus_match); +#endif + +static struct platform_driver sunxi_cedrus_driver = { + .probe = sunxi_cedrus_probe, + .remove = sunxi_cedrus_remove, + .driver = { + .name = SUNXI_CEDRUS_NAME, + .owner = THIS_MODULE, + .of_match_table = of_match_ptr(of_sunxi_cedrus_match), + }, +}; +module_platform_driver(sunxi_cedrus_driver); + +MODULE_LICENSE("GPL v2"); +MODULE_AUTHOR("Florent Revest "); +MODULE_DESCRIPTION("Sunxi Cedrus codec driver"); diff --git a/pool/shard002/C/0059671_ioctl.c b/pool/shard002/C/0059671_ioctl.c new file mode 100644 index 0000000000000000000000000000000000000000..29970531b4f5459acc4fb073ca54738c4a3d4728 --- /dev/null +++ b/pool/shard002/C/0059671_ioctl.c @@ -0,0 +1,85 @@ +/** + * @file + * + * @brief + * + * @date 06.11.2011 + * @author Anton Bondarev + */ + +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +/* POSIX says, that this way to make read/write nonblocking is old + * and recommend use fcntl(fd, O_NONBLOCK, ...) + * */ +static int io_fionbio(int fd, va_list args) { + const int *val_p = va_arg(args, const int *); + int flags; + + /* if fcntl returns -1, then errno already set, can just return -1 */ + + flags = fcntl(fd, F_GETFL); + if (-1 == flags) { + return -1; + } + + if (*val_p != 0) { + flags |= O_NONBLOCK; + } else { + flags &= ~O_NONBLOCK; + } + + if (-1 == fcntl(fd, F_SETFL, flags)) { + return -1; + } + + return 0; +} + +int ioctl(int fd, int request, ...) { + void *data; + va_list args; + int rc; + + if (!idesc_index_valid(fd)) { + return SET_ERRNO(EBADF); + } + + switch (request) { + case FIONBIO: + va_start(args, request); + rc = io_fionbio(fd, args); + va_end(args); + break; + case FIONREAD: + rc = index_descriptor_status(fd, POLLIN); + if (rc < 0) { + rc = SET_ERRNO(-rc); + } + break; + default: + va_start(args, request); + data = va_arg(args, void*); + va_end(args); + + rc = index_descriptor_ioctl(fd, request, data); + if (rc < 0) { + rc = SET_ERRNO(-rc); + } + break; + } + + return rc; +} + + + diff --git a/pool/shard002/C/0059674_timer.c b/pool/shard002/C/0059674_timer.c new file mode 100644 index 0000000000000000000000000000000000000000..6c16571d35b1ee5392e4d2367092d34a63382e7f --- /dev/null +++ b/pool/shard002/C/0059674_timer.c @@ -0,0 +1,275 @@ +/* + * timer driver for the Hitachi SH 7750 + * + * This file manages the benchmark timer used by the RTEMS Timing Test + * Suite. Each measured time period is demarcated by calls to + * benchmark_timer_initialize() and benchmark_timer_read(). benchmark_timer_read() usually returns + * the number of microseconds since benchmark_timer_initialize() exitted. + * + * NOTE: It is important that the timer start/stop overhead be + * determined when porting or modifying this code. + * + * Copyright (C) 2001 OKTET Ltd., St.-Petersburg, Russia + * Author: Victor V. Vengerov + * + * COPYRIGHT (c) 1998. + * 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. + * + * $Id: timer.c,v 1.10 2008/09/05 12:09:05 ralf Exp $ + */ + +#include + +#include +#include + +extern uint32_t bsp_clicks_per_second; + +#ifndef TIMER_PRIO +#define TIMER_PRIO 15 +#endif + +/* Timer prescaler division ratio */ +#define TIMER_PRESCALER 4 +#define TCR1_TPSC SH7750_TCR_TPSC_DIV4 + +#define TIMER_VECTOR SH7750_EVT_TO_NUM(SH7750_EVT_TUNI1) + +extern rtems_isr timerisr(void); + +static uint32_t Timer_interrupts; + +/* Counter should be divided to this value to obtain time in microseconds */ +static uint32_t microseconds_divider; + +/* Interrupt period in microseconds */ +static uint32_t microseconds_per_int; + +bool benchmark_timer_find_average_overhead; + +/* benchmark_timer_initialize -- + * Initialize Timer 1 to operate as a RTEMS benchmark timer: + * - determine timer clock frequency + * - install timer interrupt handler + * - configure the Timer 1 hardware + * - start the timer + * + * PARAMETERS: + * none + * + * RETURNS: + * none + */ +void +benchmark_timer_initialize(void) +{ + uint8_t temp8; + uint16_t temp16; + rtems_interrupt_level level; + rtems_isr *ignored; + int cpudiv = 1; + int tidiv = 1; + + Timer_interrupts = 0; + rtems_interrupt_disable(level); + + /* Get CPU frequency divider from clock unit */ + switch (read16(SH7750_FRQCR) & SH7750_FRQCR_IFC) + { + case SH7750_FRQCR_IFCDIV1: + cpudiv = 1; + break; + + case SH7750_FRQCR_IFCDIV2: + cpudiv = 2; + break; + + case SH7750_FRQCR_IFCDIV3: + cpudiv = 3; + break; + + case SH7750_FRQCR_IFCDIV4: + cpudiv = 4; + break; + + case SH7750_FRQCR_IFCDIV6: + cpudiv = 6; + break; + + case SH7750_FRQCR_IFCDIV8: + cpudiv = 8; + break; + + default: + rtems_fatal_error_occurred( RTEMS_NOT_CONFIGURED); + } + + /* Get peripheral module frequency divider from clock unit */ + switch (read16(SH7750_FRQCR) & SH7750_FRQCR_PFC) + { + case SH7750_FRQCR_PFCDIV2: + tidiv = 2 * TIMER_PRESCALER; + break; + + case SH7750_FRQCR_PFCDIV3: + tidiv = 3 * TIMER_PRESCALER; + break; + + case SH7750_FRQCR_PFCDIV4: + tidiv = 4 * TIMER_PRESCALER; + break; + + case SH7750_FRQCR_PFCDIV6: + tidiv = 6 * TIMER_PRESCALER; + break; + + case SH7750_FRQCR_PFCDIV8: + tidiv = 8 * TIMER_PRESCALER; + break; + + default: + rtems_fatal_error_occurred( RTEMS_NOT_CONFIGURED); + } + + microseconds_divider = bsp_clicks_per_second * cpudiv / (tidiv * 1000000); + microseconds_per_int = 0xFFFFFFFF / microseconds_divider; + + /* + * Hardware specific initialization + */ + + /* Stop the Timer 0 */ + temp8 = read8(SH7750_TSTR); + temp8 &= ~SH7750_TSTR_STR1; + write8(temp8, SH7750_TSTR); + + /* Establish interrupt handler */ + _CPU_ISR_install_raw_handler( TIMER_VECTOR, timerisr, &ignored ); + + /* Reset timer constant and counter */ + write32(0xFFFFFFFF, SH7750_TCOR1); + write32(0xFFFFFFFF, SH7750_TCNT1); + + /* Select timer mode */ + write16( + SH7750_TCR_UNIE | /* Enable Underflow Interrupt */ + SH7750_TCR_CKEG_RAISE | /* Count on rising edge */ + TCR1_TPSC, /* Timer prescaler ratio */ + SH7750_TCR1); + + /* Set timer interrupt priority */ + temp16 = read16(SH7750_IPRA); + temp16 = (temp16 & ~SH7750_IPRA_TMU1) | (TIMER_PRIO << SH7750_IPRA_TMU1_S); + write16(temp16, SH7750_IPRA); + + + rtems_interrupt_enable(level); + + /* Start the Timer 1 */ + temp8 = read8(SH7750_TSTR); + temp8 |= SH7750_TSTR_STR1; + write8(temp8, SH7750_TSTR); + +} + +/* + * The following controls the behavior of benchmark_timer_read(). + * + * AVG_OVERHEAD is the overhead for starting and stopping the timer. It + * is usually deducted from the number returned. + * + * LEAST_VALID is the lowest number this routine should trust. Numbers + * below this are "noise" and zero is returned. + */ + +#define AVG_OVERHEAD 0 /* It typically takes X.X microseconds */ + /* (Y countdowns) to start/stop the timer. */ + /* This value is in microseconds. */ +#define LEAST_VALID 0 /* 20 */ /* Don't trust a clicks value lower than this */ + +/* benchmark_timer_read -- + * Read timer value in microsecond units since timer start. + * + * PARAMETERS: + * none + * + * RETURNS: + * number of microseconds since timer has been started + */ +int +benchmark_timer_read(void) +{ + uint32_t clicks; + uint32_t ints; + uint32_t total; + rtems_interrupt_level level; + uint32_t tcr; + + + rtems_interrupt_disable(level); + + clicks = 0xFFFFFFFF - read32(SH7750_TCNT1); + tcr = read32(SH7750_TCR1); + ints = Timer_interrupts; + + rtems_interrupt_enable(level); + + /* Handle the case when timer overflowed but interrupt was not processed */ + if ((clicks > 0xFF000000) && ((tcr & SH7750_TCR_UNF) != 0)) + { + ints++; + } + + total = microseconds_per_int * ints + (clicks / microseconds_divider); + + if ( benchmark_timer_find_average_overhead ) + return total; /* in microsecond units */ + else + { + if ( total < LEAST_VALID ) + return 0; /* below timer resolution */ + /* + * Somehow convert total into microseconds + */ + return (total - AVG_OVERHEAD) ; + } +} + +/* benchmark_timer_disable_subtracting_average_overhead -- + * This routine is invoked by the "Check Timer" (tmck) test in the + * RTEMS Timing Test Suite. It makes the benchmark_timer_read routine not + * subtract the overhead required to initialize and read the benchmark + * timer. + * + * PARAMETERS: + * find_flag - boolean flag, true if overhead must not be subtracted. + * + * RETURNS: + * none + */ +void +benchmark_timer_disable_subtracting_average_overhead(bool find_flag) +{ + benchmark_timer_find_average_overhead = find_flag; +} + +/* timerisr -- + * Timer interrupt handler routine. This function invoked on timer + * underflow event; once per 2^32 clocks. It should reset the timer + * event and increment timer interrupts counter. + */ +void +timerisr(void) +{ + uint8_t temp8; + + /* reset the flags of the status register */ + temp8 = read8(SH7750_TCR1) & ~SH7750_TCR_UNF; + write8(temp8, SH7750_TCR1); + + Timer_interrupts += 1; +} diff --git a/pool/shard002/C/0059679_error-test.c b/pool/shard002/C/0059679_error-test.c new file mode 100644 index 0000000000000000000000000000000000000000..36855aae81308b278b978adb5dd0a7eaba8223d4 --- /dev/null +++ b/pool/shard002/C/0059679_error-test.c @@ -0,0 +1,174 @@ +/* + * Copyright 1999-2008 University of Chicago + * + * 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 "globus_common.h" +#include "gssapi.h" +#include "globus_i_gsi_gss_utils.h" + +#define TEST_ASSERT(assertion) if (!(assertion)) { fprintf(stderr, "%s:%d:%s %s\n", __FILE__, __LINE__, __func__, #assertion); return 1; } + +static +int +malloc_error_test(void) +{ + globus_result_t result; + globus_object_t *error; + + errno = ENOMEM; + GLOBUS_GSI_GSSAPI_MALLOC_ERROR(&result); + + TEST_ASSERT(result != GLOBUS_SUCCESS); + + error = globus_error_get(result); + + TEST_ASSERT(error != NULL); + TEST_ASSERT(globus_error_get_source(error) == GLOBUS_GSI_GSSAPI_MODULE); + TEST_ASSERT(globus_error_get_type(error) == + GLOBUS_GSI_GSSAPI_ERROR_OUT_OF_MEMORY); + + globus_object_free(error); + return 0; +} + +static +int +gssapi_error_test(void) +{ + globus_result_t result; + globus_object_t * error; + + GLOBUS_GSI_GSSAPI_ERROR_RESULT( + &result, + GLOBUS_GSI_GSSAPI_ERROR_NO_GLOBUSID, + ("no globusid")); + + TEST_ASSERT(result != GLOBUS_SUCCESS); + + error = globus_error_get(result); + + TEST_ASSERT(error != NULL); + TEST_ASSERT(globus_error_get_source(error) == GLOBUS_GSI_GSSAPI_MODULE); + TEST_ASSERT(globus_error_get_type(error) == + GLOBUS_GSI_GSSAPI_ERROR_NO_GLOBUSID); + + globus_object_free(error); + return 0; +} + +static +int +error_join_chains_test(void) +{ + globus_result_t result1, result2; + globus_result_t chain1, chain2, chain3; + + errno = ENOMEM; + GLOBUS_GSI_GSSAPI_MALLOC_ERROR(&result1); + TEST_ASSERT(result1 != GLOBUS_SUCCESS); + + chain1 = globus_i_gsi_gssapi_error_join_chains_result( + result1, + GLOBUS_SUCCESS); + TEST_ASSERT(chain1 != GLOBUS_SUCCESS); + result1 = GLOBUS_SUCCESS; + + TEST_ASSERT(globus_error_get_type(globus_error_peek(chain1)) == + GLOBUS_GSI_GSSAPI_ERROR_CREATING_ERROR_OBJ); + + + GLOBUS_GSI_GSSAPI_ERROR_RESULT( + &result2, + GLOBUS_GSI_GSSAPI_ERROR_NO_GLOBUSID, + ("no globusid")); + TEST_ASSERT(result2 != GLOBUS_SUCCESS); + + chain2 = globus_i_gsi_gssapi_error_join_chains_result( + GLOBUS_SUCCESS, + result2); + TEST_ASSERT(chain2 != GLOBUS_SUCCESS); + result2 = GLOBUS_SUCCESS; + + TEST_ASSERT(globus_error_get_type(globus_error_peek(chain2)) == + GLOBUS_GSI_GSSAPI_ERROR_NO_GLOBUSID); + + errno = ENOMEM; + GLOBUS_GSI_GSSAPI_MALLOC_ERROR(&result1); + TEST_ASSERT(result1 != GLOBUS_SUCCESS); + + GLOBUS_GSI_GSSAPI_ERROR_RESULT( + &result2, + GLOBUS_GSI_GSSAPI_ERROR_NO_GLOBUSID, + ("no globusid")); + + chain3 = globus_i_gsi_gssapi_error_join_chains_result( + result1, + result2); + result1 = result2 = GLOBUS_SUCCESS; + TEST_ASSERT(chain3 != GLOBUS_SUCCESS); + + TEST_ASSERT(globus_error_match( + globus_error_peek(chain3), + GLOBUS_GSI_GSSAPI_MODULE, + GLOBUS_GSI_GSSAPI_ERROR_OUT_OF_MEMORY)); + TEST_ASSERT(globus_error_match( + globus_error_peek(chain3), + GLOBUS_GSI_GSSAPI_MODULE, + GLOBUS_GSI_GSSAPI_ERROR_NO_GLOBUSID)); + + return 0; +} + +struct test_case +{ + char *name; + int (*func)(void); +}; + +#define TEST_CASE(t) { .name = #t, .func = t } + +int +main(int argc, char *argv[]) +{ + struct test_case tests[] = + { + TEST_CASE(malloc_error_test), + TEST_CASE(gssapi_error_test), + TEST_CASE(error_join_chains_test) + }; + size_t test_count; + int failed = 0; + + test_count = sizeof(tests)/sizeof(tests[0]); + + printf("1..%zd\n", test_count); + globus_module_activate(GLOBUS_GSI_GSSAPI_MODULE); + + for (size_t i = 0; i < test_count; i++) + { + int rc = tests[i].func(); + + printf("%s - %s\n", rc ? "not ok" : "ok", tests[i].name); + + if (rc != 0) + { + failed++; + } + } + globus_module_deactivate(GLOBUS_GSI_GSSAPI_MODULE); + + return failed; +} +/* main() */ diff --git a/pool/shard002/C/0059691_core.c b/pool/shard002/C/0059691_core.c new file mode 100644 index 0000000000000000000000000000000000000000..24a670e0ceac45b592831fb61592c5f301e0cd9e --- /dev/null +++ b/pool/shard002/C/0059691_core.c @@ -0,0 +1,323 @@ +#include +#include +#include +#include +#include +#include + +/* Common receive buffer */ +static __lowmem char packet_buf[PKTBUF_SIZE] __aligned(16); + +extern uint16_t get_port(void); +extern void free_port(uint16_t); + +const struct url_scheme url_schemes[] = { + { "tftp", tftp_open, 0 }, + { NULL, NULL, 0 } +}; + +/** + * Open a socket + * + * @param:socket, the socket to open + * + * @out: error code, 0 on success, -1 on failure + */ +int core_udp_open(struct pxe_pvt_inode *socket __unused) +{ + struct net_private_tftp *priv = &socket->net.tftp; + + /* Allocate local UDP port number */ + priv->localport = get_port(); + + return 0; +} + +/** + * Close a socket + * + * @param:socket, the socket to open + */ +void core_udp_close(struct pxe_pvt_inode *socket) +{ + struct net_private_tftp *priv = &socket->net.tftp; + + if (priv->localport) + free_port(priv->localport); +} + +/** + * Establish a connection on an open socket + * + * @param:socket, the open socket + * @param:ip, the ip address + * @param:port, the port number, host-byte order + */ +void core_udp_connect(struct pxe_pvt_inode *socket, uint32_t ip, + uint16_t port) +{ + struct net_private_tftp *priv = &socket->net.tftp; + + socket->tftp_remoteport = htons(port); + priv->remoteip = ip; + +} + +/** + * Tear down a connection on an open socket + * + * @param:socket, the open socket + */ +void core_udp_disconnect(struct pxe_pvt_inode *socket __unused) +{ +} + +/** + * Read data from the network stack + * + * @param:socket, the open socket + * @param:buf, location of buffer to store data + * @param:buf_len, size of buffer + + * @out: src_ip, ip address of the data source + * @out: src_port, port number of the data source, host-byte order + */ +int core_udp_recv(struct pxe_pvt_inode *socket, void *buf, uint16_t *buf_len, + uint32_t *src_ip, uint16_t *src_port) +{ + static __lowmem struct s_PXENV_UDP_READ udp_read; + struct net_private_tftp *priv = &socket->net.tftp; + uint16_t bytes; + int err; + + udp_read.status = 0; + udp_read.buffer = FAR_PTR(packet_buf); + udp_read.buffer_size = PKTBUF_SIZE; + udp_read.dest_ip = IPInfo.myip; + udp_read.d_port = priv->localport; + + err = pxe_call(PXENV_UDP_READ, &udp_read); + if (err) + return err; + + if (udp_read.status) + return udp_read.status; + + bytes = min(udp_read.buffer_size, *buf_len); + memcpy(buf, packet_buf, bytes); + + *src_ip = udp_read.src_ip; + *src_port = ntohs(udp_read.s_port); + *buf_len = bytes; + + return 0; +} + +/** + * Send a UDP packet. + * + * @param:socket, the open socket + * @param:data, data buffer to send + * @param:len, size of data bufer + */ +void core_udp_send(struct pxe_pvt_inode *socket, const void *data, size_t len) +{ + static __lowmem struct s_PXENV_UDP_WRITE udp_write; + struct net_private_tftp *priv = &socket->net.tftp; + void *lbuf; + uint16_t tid; + + lbuf = lmalloc(len); + if (!lbuf) + return; + + memcpy(lbuf, data, len); + + tid = priv->localport; /* TID(local port No) */ + udp_write.buffer = FAR_PTR(lbuf); + udp_write.ip = priv->remoteip; + udp_write.gw = gateway(udp_write.ip); + udp_write.src_port = tid; + udp_write.dst_port = socket->tftp_remoteport; + udp_write.buffer_size = len; + + pxe_call(PXENV_UDP_WRITE, &udp_write); + + lfree(lbuf); +} + +/** + * Send a UDP packet to a destination + * + * @param:socket, the open socket + * @param:data, data buffer to send + * @param:len, size of data bufer + * @param:ip, the ip address + * @param:port, the port number, host-byte order + */ +void core_udp_sendto(struct pxe_pvt_inode *socket, const void *data, size_t len, + uint32_t ip, uint16_t port) +{ + static __lowmem struct s_PXENV_UDP_WRITE udp_write; + struct net_private_tftp *priv = &socket->net.tftp; + void *lbuf; + uint16_t tid; + + lbuf = lmalloc(len); + if (!lbuf) + return; + + memcpy(lbuf, data, len); + + tid = priv->localport; /* TID(local port No) */ + udp_write.buffer = FAR_PTR(lbuf); + udp_write.ip = ip; + udp_write.gw = gateway(udp_write.ip); + udp_write.src_port = tid; + udp_write.dst_port = htons(port); + udp_write.buffer_size = len; + + pxe_call(PXENV_UDP_WRITE, &udp_write); + + lfree(lbuf); +} + + +/** + * Network stack-specific initialization + * + * Initialize UDP stack + */ +void net_core_init(void) +{ + int err; + static __lowmem struct s_PXENV_UDP_OPEN udp_open; + udp_open.src_ip = IPInfo.myip; + err = pxe_call(PXENV_UDP_OPEN, &udp_open); + if (err || udp_open.status) { + printf("Failed to initialize UDP stack "); + printf("%d\n", udp_open.status); + kaboom(); + } +} + +void probe_undi(void) +{ +} + +void pxe_init_isr(void) +{ +} + +int reset_pxe(void) +{ + static __lowmem struct s_PXENV_UDP_CLOSE udp_close; + int err = 0; + + pxe_idle_cleanup(); + + pxe_call(PXENV_UDP_CLOSE, &udp_close); + + return err; +} + +#if GPXE + +static void gpxe_close_file(struct inode *inode) +{ + struct pxe_pvt_inode *socket = PVT(inode); + static __lowmem struct s_PXENV_FILE_CLOSE file_close; + + file_close.FileHandle = socket->tftp_remoteport; + pxe_call(PXENV_FILE_CLOSE, &file_close); +} + +/** + * Get a fresh packet from a gPXE socket + * @param: inode -> Inode pointer + * + */ +static void gpxe_get_packet(struct inode *inode) +{ + struct pxe_pvt_inode *socket = PVT(inode); + static __lowmem struct s_PXENV_FILE_READ file_read; + int err; + + while (1) { + file_read.FileHandle = socket->tftp_remoteport; + file_read.Buffer = FAR_PTR(packet_buf); + file_read.BufferSize = PKTBUF_SIZE; + err = pxe_call(PXENV_FILE_READ, &file_read); + if (!err) /* successed */ + break; + + if (file_read.Status != PXENV_STATUS_TFTP_OPEN) + kaboom(); + } + + memcpy(socket->tftp_pktbuf, packet_buf, file_read.BufferSize); + + socket->tftp_dataptr = socket->tftp_pktbuf; + socket->tftp_bytesleft = file_read.BufferSize; + socket->tftp_filepos += file_read.BufferSize; + + if (socket->tftp_bytesleft == 0) + inode->size = socket->tftp_filepos; + + /* if we're done here, close the file */ + if (inode->size > socket->tftp_filepos) + return; + + /* Got EOF, close it */ + socket->tftp_goteof = 1; + gpxe_close_file(inode); +} + +const struct pxe_conn_ops gpxe_conn_ops = { + .fill_buffer = gpxe_get_packet, + .close = gpxe_close_file, +}; + +/** + * Open a url using gpxe + * + * @param:inode, the inode to store our state in + * @param:url, the url we want to open + * + * @out: open_file_t structure, stores in file->open_file + * @out: the lenght of this file, stores in file->file_len + * + */ +void gpxe_open(struct inode *inode, const char *url) +{ + static __lowmem struct s_PXENV_FILE_OPEN file_open; + static __lowmem struct s_PXENV_GET_FILE_SIZE file_size; + static __lowmem char lowurl[2*FILENAME_MAX]; + struct pxe_pvt_inode *socket = PVT(inode); + int err; + + socket->tftp_pktbuf = malloc(PKTBUF_SIZE); + if (!socket->tftp_pktbuf) + return; + + snprintf(lowurl, sizeof lowurl, "%s", url); + file_open.Status = PXENV_STATUS_BAD_FUNC; + file_open.FileName = FAR_PTR(lowurl); + err = pxe_call(PXENV_FILE_OPEN, &file_open); + if (err) + return; + + + socket->ops = &gpxe_conn_ops; + socket->tftp_remoteport = file_open.FileHandle; + file_size.Status = PXENV_STATUS_BAD_FUNC; + file_size.FileHandle = file_open.FileHandle; + err = pxe_call(PXENV_GET_FILE_SIZE, &file_size); + if (err) { + inode->size = -1; /* fallback size; this shouldn't be an error */ + } else { + inode->size = file_size.FileSize; + } +} + +#endif /* GPXE */ diff --git a/pool/shard002/C/0059696_getcgi.c b/pool/shard002/C/0059696_getcgi.c new file mode 100644 index 0000000000000000000000000000000000000000..2f8d438d07f248c0c10b4d92e8156202aa4a0121 --- /dev/null +++ b/pool/shard002/C/0059696_getcgi.c @@ -0,0 +1,283 @@ +/****************************************** + * + * GETCGI.C - Nagios CGI Input Routines + * + * Last Modified: 05-15-2006 + * + *****************************************/ + +#include "../include/config.h" +#include "../include/getcgi.h" +#include +#include + + +#undef PARANOID_CGI_INPUT + + +/* Remove potentially harmful characters from CGI input that we don't need or want */ +void sanitize_cgi_input(char **cgivars) { + char *strptr; + int x, y, i; + int keep; + + /* don't strip for now... */ + return; + + for(strptr = cgivars[i = 0]; strptr != NULL; strptr = cgivars[++i]) { + + for(x = 0, y = 0; strptr[x] != '\x0'; x++) { + + keep = 1; + + /* remove potentially nasty characters */ + if(strptr[x] == ';' || strptr[x] == '|' || strptr[x] == '&' || strptr[x] == '<' || strptr[x] == '>') + keep = 0; +#ifdef PARANOID_CGI_INPUT + else if(strptr[x] == '/' || strptr[x] == '\\') + keep = 0; +#endif + if(keep == 1) + strptr[y++] = strptr[x]; + } + + strptr[y] = '\x0'; + } + + return; + } + + +/* convert encoded hex string (2 characters representing an 8-bit number) to its ASCII char equivalent */ +unsigned char hex_to_char(char *input) { + unsigned char outchar = '\x0'; + unsigned int outint; + char tempbuf[3]; + + /* NULL or empty string */ + if(input == NULL) + return '\x0'; + if(input[0] == '\x0') + return '\x0'; + + tempbuf[0] = input[0]; + tempbuf[1] = input[1]; + tempbuf[2] = '\x0'; + + sscanf(tempbuf, "%X", &outint); + + /* only convert "normal" ASCII characters - we don't want the rest. Normally you would + convert all characters (i.e. for allowing users to post binary files), but since we + aren't doing this, stay on the cautious side of things and reject outsiders... */ +#ifdef PARANOID_CGI_INPUT + if(outint < 32 || outint > 126) + outint = 0; +#endif + + outchar = (unsigned char)outint; + + return outchar; + } + + + +/* unescape hex characters in CGI input */ +void unescape_cgi_input(char *input) { + int x, y; + int len; + + if(input == NULL) + return; + + len = strlen(input); + for(x = 0, y = 0; x < len; x++, y++) { + + if(input[x] == '\x0') + break; + else if(input[x] == '%') { + input[y] = hex_to_char(&input[x + 1]); + x += 2; + } + else + input[y] = input[x]; + } + input[y] = '\x0'; + + return; + } + + + +/* read the CGI input and place all name/val pairs into list. returns list containing name1, value1, name2, value2, ... , NULL */ +/* this is a hacked version of a routine I found a long time ago somewhere - can't remember where anymore */ +char **getcgivars(void) { + register int i; + char *request_method; + char *content_type; + char *content_length_string; + int content_length; + char *cgiinput; + char **cgivars; + char **pairlist; + int paircount; + char *nvpair; + char *eqpos; + + /* initialize char variable(s) */ + cgiinput = ""; + + /* depending on the request method, read all CGI input into cgiinput */ + + request_method = getenv("REQUEST_METHOD"); + if(request_method == NULL) + request_method = ""; + + if(!strcmp(request_method, "GET") || !strcmp(request_method, "HEAD")) { + + /* check for NULL query string environment variable - 04/28/00 (Ludo Bosmans) */ + if(getenv("QUERY_STRING") == NULL) { + cgiinput = (char *)malloc(1); + if(cgiinput == NULL) { + printf("getcgivars(): Could not allocate memory for CGI input.\n"); + exit(1); + } + cgiinput[0] = '\x0'; + } + else + cgiinput = strdup(getenv("QUERY_STRING")); + } + + else if(!strcmp(request_method, "POST") || !strcmp(request_method, "PUT")) { + + /* if CONTENT_TYPE variable is not specified, RFC-2068 says we should assume it is "application/octet-string" */ + /* mobile (WAP) stations generate CONTENT_TYPE with charset, we we should only check first 33 chars */ + + content_type = getenv("CONTENT_TYPE"); + if(content_type == NULL) + content_type = ""; + + if(strlen(content_type) && strncasecmp(content_type, "application/x-www-form-urlencoded", 33)) { + printf("getcgivars(): Unsupported Content-Type.\n"); + exit(1); + } + + content_length_string = getenv("CONTENT_LENGTH"); + if(content_length_string == NULL) + content_length_string = "0"; + + if(!(content_length = atoi(content_length_string))) { + printf("getcgivars(): No Content-Length was sent with the POST request.\n") ; + exit(1); + } + /* suspicious content length */ + if((content_length < 0) || (content_length >= INT_MAX - 1)) { + printf("getcgivars(): Suspicious Content-Length was sent with the POST request.\n"); + exit(1); + } + + if(!(cgiinput = (char *)malloc(content_length + 1))) { + printf("getcgivars(): Could not allocate memory for CGI input.\n"); + exit(1); + } + if(!fread(cgiinput, content_length, 1, stdin)) { + printf("getcgivars(): Could not read input from STDIN.\n"); + exit(1); + } + cgiinput[content_length] = '\0'; + } + else { + + printf("getcgivars(): Unsupported REQUEST_METHOD -> '%s'\n", request_method); + printf("\n"); + printf("I'm guessing you're trying to execute the CGI from a command line.\n"); + printf("In order to do that, you need to set the REQUEST_METHOD environment\n"); + printf("variable to either \"GET\", \"HEAD\", or \"POST\". When using the\n"); + printf("GET and HEAD methods, arguments can be passed to the CGI\n"); + printf("by setting the \"QUERY_STRING\" environment variable. If you're\n"); + printf("using the POST method, data is read from standard input. Also of\n"); + printf("note: if you've enabled authentication in the CGIs, you must set the\n"); + printf("\"REMOTE_USER\" environment variable to be the name of the user you're\n"); + printf("\"authenticated\" as.\n"); + printf("\n"); + + exit(1); + } + + /* change all plus signs back to spaces */ + for(i = 0; cgiinput[i]; i++) { + if(cgiinput[i] == '+') + cgiinput[i] = ' '; + } + + /* first, split on ampersands (&) to extract the name-value pairs into pairlist */ + /* allocate memory for 256 name-value pairs at a time, increasing by same + amount as necessary... */ + pairlist = (char **)malloc(256 * sizeof(char **)); + if(pairlist == NULL) { + printf("getcgivars(): Could not allocate memory for name-value pairlist.\n"); + exit(1); + } + paircount = 0; + nvpair = strtok(cgiinput, "&"); + while(nvpair) { + pairlist[paircount++] = strdup(nvpair); + if(!(paircount % 256)) { + pairlist = (char **)realloc(pairlist, (paircount + 256) * sizeof(char **)); + if(pairlist == NULL) { + printf("getcgivars(): Could not re-allocate memory for name-value pairlist.\n"); + exit(1); + } + } + nvpair = strtok(NULL, "&"); + } + + /* terminate the list */ + pairlist[paircount] = '\x0'; + + /* extract the names and values from the pairlist */ + cgivars = (char **)malloc((paircount * 2 + 1) * sizeof(char **)); + if(cgivars == NULL) { + printf("getcgivars(): Could not allocate memory for name-value list.\n"); + exit(1); + } + for(i = 0; i < paircount; i++) { + + /* get the variable name preceding the equal (=) sign */ + if((eqpos = strchr(pairlist[i], '=')) != NULL) { + *eqpos = '\0'; + unescape_cgi_input(cgivars[i * 2 + 1] = strdup(eqpos + 1)); + } + else + unescape_cgi_input(cgivars[i * 2 + 1] = strdup("")); + + /* get the variable value (or name/value of there was no real "pair" in the first place) */ + unescape_cgi_input(cgivars[i * 2] = strdup(pairlist[i])); + } + + /* terminate the name-value list */ + cgivars[paircount * 2] = '\x0'; + + /* free allocated memory */ + free(cgiinput); + for(i = 0; pairlist[i] != NULL; i++) + free(pairlist[i]); + free(pairlist); + + /* sanitize the name-value strings */ + sanitize_cgi_input(cgivars); + + /* return the list of name-value strings */ + return cgivars; + } + + + +/* free() memory allocated to storing the CGI variables */ +void free_cgivars(char **cgivars) { + register int x; + + for(x = 0; cgivars[x] != '\x0'; x++) + free(cgivars[x]); + + return; + } diff --git a/pool/shard002/C/0059710_modutimeq.c b/pool/shard002/C/0059710_modutimeq.c new file mode 100644 index 0000000000000000000000000000000000000000..a5640a486a723830aa2d5d765fbc935e1745de07 --- /dev/null +++ b/pool/shard002/C/0059710_modutimeq.c @@ -0,0 +1,233 @@ +/* + * This file is part of the MicroPython project, http://micropython.org/ + * + * The MIT License (MIT) + * + * Copyright (c) 2014 Damien P. George + * Copyright (c) 2016-2017 Paul Sokolovsky + * + * 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 "py/objlist.h" +#include "py/runtime.h" +#include "py/smallint.h" + +#if MICROPY_PY_UTIMEQ + +#define MODULO MICROPY_PY_UTIME_TICKS_PERIOD + +#define DEBUG 0 + +// the algorithm here is modelled on CPython's heapq.py + +struct qentry { + mp_uint_t time; + mp_uint_t id; + mp_obj_t callback; + mp_obj_t args; +}; + +typedef struct _mp_obj_utimeq_t { + mp_obj_base_t base; + mp_uint_t alloc; + mp_uint_t len; + struct qentry items[]; +} mp_obj_utimeq_t; + +STATIC mp_uint_t utimeq_id; + +STATIC mp_obj_utimeq_t *utimeq_get_heap(mp_obj_t heap_in) { + return MP_OBJ_TO_PTR(heap_in); +} + +STATIC bool time_less_than(struct qentry *item, struct qentry *parent) { + mp_uint_t item_tm = item->time; + mp_uint_t parent_tm = parent->time; + mp_uint_t res = parent_tm - item_tm; + if (res == 0) { + // TODO: This actually should use the same "ring" logic + // as for time, to avoid artifacts when id's overflow. + return item->id < parent->id; + } + if ((mp_int_t)res < 0) { + res += MODULO; + } + return res && res < (MODULO / 2); +} + +STATIC mp_obj_t utimeq_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *args) { + mp_arg_check_num(n_args, n_kw, 1, 1, false); + mp_uint_t alloc = mp_obj_get_int(args[0]); + mp_obj_utimeq_t *o = m_new_obj_var(mp_obj_utimeq_t, struct qentry, alloc); + o->base.type = type; + memset(o->items, 0, sizeof(*o->items) * alloc); + o->alloc = alloc; + o->len = 0; + return MP_OBJ_FROM_PTR(o); +} + +STATIC void utimeq_heap_siftdown(mp_obj_utimeq_t *heap, mp_uint_t start_pos, mp_uint_t pos) { + struct qentry item = heap->items[pos]; + while (pos > start_pos) { + mp_uint_t parent_pos = (pos - 1) >> 1; + struct qentry *parent = &heap->items[parent_pos]; + bool lessthan = time_less_than(&item, parent); + if (lessthan) { + heap->items[pos] = *parent; + pos = parent_pos; + } else { + break; + } + } + heap->items[pos] = item; +} + +STATIC void utimeq_heap_siftup(mp_obj_utimeq_t *heap, mp_uint_t pos) { + mp_uint_t start_pos = pos; + mp_uint_t end_pos = heap->len; + struct qentry item = heap->items[pos]; + for (mp_uint_t child_pos = 2 * pos + 1; child_pos < end_pos; child_pos = 2 * pos + 1) { + // choose right child if it's <= left child + if (child_pos + 1 < end_pos) { + bool lessthan = time_less_than(&heap->items[child_pos], &heap->items[child_pos + 1]); + if (!lessthan) { + child_pos += 1; + } + } + // bubble up the smaller child + heap->items[pos] = heap->items[child_pos]; + pos = child_pos; + } + heap->items[pos] = item; + utimeq_heap_siftdown(heap, start_pos, pos); +} + +STATIC mp_obj_t mod_utimeq_heappush(size_t n_args, const mp_obj_t *args) { + (void)n_args; + mp_obj_t heap_in = args[0]; + mp_obj_utimeq_t *heap = utimeq_get_heap(heap_in); + if (heap->len == heap->alloc) { + mp_raise_msg(&mp_type_IndexError, "queue overflow"); + } + mp_uint_t l = heap->len; + heap->items[l].time = MP_OBJ_SMALL_INT_VALUE(args[1]); + heap->items[l].id = utimeq_id++; + heap->items[l].callback = args[2]; + heap->items[l].args = args[3]; + utimeq_heap_siftdown(heap, 0, heap->len); + heap->len++; + return mp_const_none; +} +STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(mod_utimeq_heappush_obj, 4, 4, mod_utimeq_heappush); + +STATIC mp_obj_t mod_utimeq_heappop(mp_obj_t heap_in, mp_obj_t list_ref) { + mp_obj_utimeq_t *heap = utimeq_get_heap(heap_in); + if (heap->len == 0) { + mp_raise_msg(&mp_type_IndexError, "empty heap"); + } + mp_obj_list_t *ret = MP_OBJ_TO_PTR(list_ref); + if (!mp_obj_is_type(list_ref, &mp_type_list) || ret->len < 3) { + mp_raise_TypeError(NULL); + } + + struct qentry *item = &heap->items[0]; + ret->items[0] = MP_OBJ_NEW_SMALL_INT(item->time); + ret->items[1] = item->callback; + ret->items[2] = item->args; + heap->len -= 1; + heap->items[0] = heap->items[heap->len]; + heap->items[heap->len].callback = MP_OBJ_NULL; // so we don't retain a pointer + heap->items[heap->len].args = MP_OBJ_NULL; + if (heap->len) { + utimeq_heap_siftup(heap, 0); + } + return mp_const_none; +} +STATIC MP_DEFINE_CONST_FUN_OBJ_2(mod_utimeq_heappop_obj, mod_utimeq_heappop); + +STATIC mp_obj_t mod_utimeq_peektime(mp_obj_t heap_in) { + mp_obj_utimeq_t *heap = utimeq_get_heap(heap_in); + if (heap->len == 0) { + mp_raise_msg(&mp_type_IndexError, "empty heap"); + } + + struct qentry *item = &heap->items[0]; + return MP_OBJ_NEW_SMALL_INT(item->time); +} +STATIC MP_DEFINE_CONST_FUN_OBJ_1(mod_utimeq_peektime_obj, mod_utimeq_peektime); + +#if DEBUG +STATIC mp_obj_t mod_utimeq_dump(mp_obj_t heap_in) { + mp_obj_utimeq_t *heap = utimeq_get_heap(heap_in); + for (int i = 0; i < heap->len; i++) { + printf(UINT_FMT "\t%p\t%p\n", heap->items[i].time, + MP_OBJ_TO_PTR(heap->items[i].callback), MP_OBJ_TO_PTR(heap->items[i].args)); + } + return mp_const_none; +} +STATIC MP_DEFINE_CONST_FUN_OBJ_1(mod_utimeq_dump_obj, mod_utimeq_dump); +#endif + +STATIC mp_obj_t utimeq_unary_op(mp_unary_op_t op, mp_obj_t self_in) { + mp_obj_utimeq_t *self = MP_OBJ_TO_PTR(self_in); + switch (op) { + case MP_UNARY_OP_BOOL: + return mp_obj_new_bool(self->len != 0); + case MP_UNARY_OP_LEN: + return MP_OBJ_NEW_SMALL_INT(self->len); + default: + return MP_OBJ_NULL; // op not supported + } +} + +STATIC const mp_rom_map_elem_t utimeq_locals_dict_table[] = { + { MP_ROM_QSTR(MP_QSTR_push), MP_ROM_PTR(&mod_utimeq_heappush_obj) }, + { MP_ROM_QSTR(MP_QSTR_pop), MP_ROM_PTR(&mod_utimeq_heappop_obj) }, + { MP_ROM_QSTR(MP_QSTR_peektime), MP_ROM_PTR(&mod_utimeq_peektime_obj) }, + #if DEBUG + { MP_ROM_QSTR(MP_QSTR_dump), MP_ROM_PTR(&mod_utimeq_dump_obj) }, + #endif +}; + +STATIC MP_DEFINE_CONST_DICT(utimeq_locals_dict, utimeq_locals_dict_table); + +STATIC const mp_obj_type_t utimeq_type = { + { &mp_type_type }, + .name = MP_QSTR_utimeq, + .make_new = utimeq_make_new, + .unary_op = utimeq_unary_op, + .locals_dict = (void *)&utimeq_locals_dict, +}; + +STATIC const mp_rom_map_elem_t mp_module_utimeq_globals_table[] = { + { MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_utimeq) }, + { MP_ROM_QSTR(MP_QSTR_utimeq), MP_ROM_PTR(&utimeq_type) }, +}; + +STATIC MP_DEFINE_CONST_DICT(mp_module_utimeq_globals, mp_module_utimeq_globals_table); + +const mp_obj_module_t mp_module_utimeq = { + .base = { &mp_type_module }, + .globals = (mp_obj_dict_t *)&mp_module_utimeq_globals, +}; + +#endif //MICROPY_PY_UTIMEQ diff --git a/pool/shard002/C/0059716_zzip-stat.c b/pool/shard002/C/0059716_zzip-stat.c new file mode 100644 index 0000000000000000000000000000000000000000..c34590486ce77f9d326fba3a15a177b7553c6074 --- /dev/null +++ b/pool/shard002/C/0059716_zzip-stat.c @@ -0,0 +1,82 @@ +/* + * Author: + * Guido Draheim + * Tomi Ollila + * + * Copyright (c) 1999,2000,2001,2002 Guido Draheim + * All rights reserved, + * use under the restrictions of the + * Lesser GNU General Public License + * note the additional license information + * that can be found in COPYING.ZZIP + * + * Description: + * although this file is defining a function called zzip_stat it + * will not need a real stat(2) exported by the Operating System. + * It will just try to fill the fields of the ZZIP_STAT structure + * of + */ + +#if HAVE_CONFIG_H +#include "clamav-config.h" +#endif + +#include /* exported...*/ +#include + +#include "strc.h" + +/** + * obtain information about a filename in an opened zip-archive without + * opening that file first. Mostly used to obtain the uncompressed + * size of a file inside a zip-archive. see => zzip_dir_open. + */ +int +zzip_dir_stat(ZZIP_DIR * dir, zzip_char_t* name, ZZIP_STAT * zs, int flags) +{ + struct zzip_dir_hdr * hdr = dir->hdr0; + int (*cmp)(zzip_char_t*, zzip_char_t*); + + cmp = (flags & ZZIP_CASEINSENSITIVE) ? strcasecmp : strcmp; + + if (flags & ZZIP_IGNOREPATH) + { + char* n = strrchr(name, '/'); + if (n) name = n + 1; + } + + if (hdr) + while (1) + { + register char* hdr_name = hdr->d_name; + if (flags & ZZIP_IGNOREPATH) + { + register char* n = strrchr(hdr_name, '/'); + if (n) hdr_name = n + 1; + } + + if (! cmp(hdr_name, name)) + break; + + if (! hdr->d_reclen) + { + dir->errcode = ZZIP_ENOENT; + return -1; + } + + hdr = (struct zzip_dir_hdr *) ((char *)hdr + hdr->d_reclen); + } + + zs->d_compr = hdr->d_compr; + zs->d_csize = hdr->d_csize; + zs->st_size = hdr->d_usize; + zs->d_name = hdr->d_name; + + return 0; +} + +/* + * Local variables: + * c-file-style: "stroustrup" + * End: + */ diff --git a/pool/shard002/C/0059730_cgm_Picture.c b/pool/shard002/C/0059730_cgm_Picture.c new file mode 100644 index 0000000000000000000000000000000000000000..1b243c811fede4c4cc48a2f6fe0a3ab40563d568 --- /dev/null +++ b/pool/shard002/C/0059730_cgm_Picture.c @@ -0,0 +1,56 @@ +/* ========================================================================= + * This file is part of NITRO + * ========================================================================= + * + * (C) Copyright 2004 - 2014, MDA Information Systems LLC + * + * NITRO 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 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, If not, + * see . + * + */ + +#include "cgm_Picture.h" +#include "cgm_JNI.h" + +CGM_JNI_DECLARE_OBJ(cgm_Picture) + +JNIEXPORT jstring JNICALL Java_cgm_Picture_getName +(JNIEnv *env, jobject self) +{ + cgm_Picture *picture = _GetObj(env, self); + return (*env)->NewStringUTF(env, picture->name); +} + +JNIEXPORT void JNICALL Java_cgm_Picture_setName +(JNIEnv *env, jobject self, jstring name) +{ + cgm_Picture *picture = _GetObj(env, self); + if (picture->name) + NITF_FREE(picture->name); + picture->name = _NewCharArrayFromString(env, name); +} + +JNIEXPORT jobject JNICALL Java_cgm_Picture_getPictureBody +(JNIEnv *env, jobject self) +{ + cgm_Picture *picture = _GetObj(env, self); + return _NewObject(env, "cgm/PictureBody", (jlong) picture->body); +} + +JNIEXPORT jobject JNICALL Java_cgm_Picture_getVDCExtent +(JNIEnv *env, jobject self) +{ + cgm_Picture *picture = _GetObj(env, self); + return _NewObject(env, "cgm/Rectangle", (jlong) picture->vdcExtent); +} diff --git a/pool/shard002/C/0059731_example1b.c b/pool/shard002/C/0059731_example1b.c new file mode 100644 index 0000000000000000000000000000000000000000..8456f3a81e048edfbd3a1fa0794749866204ee60 --- /dev/null +++ b/pool/shard002/C/0059731_example1b.c @@ -0,0 +1,155 @@ +#include +#include + +#include "yices.h" + + +/* + * How to call the pretty printer + * - this also shows how to check for errors + * and print an error message if something goes wrong + */ +static void print_term(term_t term) { + char *s; + + s = yices_term_to_string(term, 80, 20, 0); + if (s == NULL) { + // An error occurred + s = yices_error_string(); + fprintf(stderr, "Error in print_term: %s\n", s); + yices_free_string(s); + exit(1); + } + // print the string then free it + printf("%s\n", s); + yices_free_string(s); +} + + +/* + * Small example: equivalent to + * + * (define x::int) + * (define y::int) + * (assert (and (>= x 0) (>= y 0)(= (+ x y) 100))) + * (check) + * + * Then we query the model to get the values of x and y. + */ +static void simple_test(void) { + int code, v; + term_t x, y, f, f_var; + type_t int_type; + context_t *ctx; + model_t* model; + char *s; + + /* + * Build the formula + */ + // Create two uninterpreted terms of type int. + int_type = yices_int_type(); + x = yices_new_uninterpreted_term(int_type); + y = yices_new_uninterpreted_term(int_type); + + // Assign names "x" and "y" to these terms. + // This is optional, but we need the names in yices_parse_term + // and it makes pretty printing nicer. + yices_set_term_name(x, "x"); + yices_set_term_name(y, "y"); + + // Build the formula (and (>= x 0) (>= y 0) (= (+ x y) 100)) + f = yices_and3(yices_arith_geq0_atom(x), // x >= 0 + yices_arith_geq0_atom(y), // y >= 0 + yices_arith_eq_atom(yices_add(x, y), yices_int32(100))); // x + y = 100 + + + // Another way to do it + f_var = yices_parse_term("(and (>= x 0) (>= y 0) (= (+ x y) 100))"); + + + /* + * Print the formulas: f and f_var should be identical + */ + printf("Formula f\n"); + print_term(f); + printf("Formula f_var\n"); + print_term(f_var); + + + /* + * To check whether f is satisfiable + * - first build a context + * - assert f in the context + * - call check_context + * - if check_context returns SAT, build a model + * and make queries about the model. + */ + ctx = yices_new_context(NULL); // NULL means 'use default configuration' + code = yices_assert_formula(ctx, f); + if (code < 0) { + fprintf(stderr, "Assert failed: code = %d, error = %d\n", code, yices_error_code()); + // yices_print_error(stderr); + } + + switch (yices_check_context(ctx, NULL)) { // call check_context, NULL means 'use default heuristics' + case STATUS_SAT: + printf("The formula is satisfiable\n"); + model = yices_get_model(ctx, 1); // get the model + if (model == NULL) { + fprintf(stderr, "Error in get_model\n"); + // yices_print_error(stderr); + } else { + s = yices_model_to_string(model, 80, 4, 0); + printf("Model\n"); + printf("%s\n", s); + yices_free_string(s); + + code = yices_get_int32_value(model, x, &v); // get the value of x, we know it fits int32 + if (code < 0) { + fprintf(stderr, "Error in get_int32_value for 'x'\n"); + // yices_print_error(stderr); + } else { + printf("Value of x = %d\n", v); + } + + code = yices_get_int32_value(model, y, &v); // get the value of y + if (code < 0) { + fprintf(stderr, "Error in get_int32_value for 'y'\n"); + // yices_print_error(stderr); + } else { + printf("Value of y = %d\n", v); + } + + yices_free_model(model); // clean up: delete the model + } + break; + + case STATUS_UNSAT: + printf("The formula is not satisfiable\n"); + break; + + case STATUS_UNKNOWN: + printf("The status is unknown\n"); + break; + + case STATUS_IDLE: + case STATUS_SEARCHING: + case STATUS_INTERRUPTED: + case STATUS_ERROR: + fprintf(stderr, "Error in check_context\n"); + yices_print_error(stderr); + break; + } + + yices_free_context(ctx); // delete the context +} + + +int main(void) { + yices_init(); // Always call this first + simple_test(); + yices_exit(); // Cleanup + + return 0; +} diff --git a/pool/shard002/C/0059738_mpn2ldbl.c b/pool/shard002/C/0059738_mpn2ldbl.c new file mode 100644 index 0000000000000000000000000000000000000000..3df42c5666de89e1d88457b8e37dd56aa77b068c --- /dev/null +++ b/pool/shard002/C/0059738_mpn2ldbl.c @@ -0,0 +1,150 @@ +/* Copyright (C) 1995-2013 Free Software Foundation, Inc. + This file is part of the GNU C Library. + + 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 "gmp.h" +#include "gmp-impl.h" +#include +#include +#include + +/* Convert a multi-precision integer of the needed number of bits (106 + for long double) and an integral power of two to a `long double' in + IBM extended format. */ + +long double +__mpn_construct_long_double (mp_srcptr frac_ptr, int expt, int sign) +{ + union ibm_extended_long_double u; + unsigned long lzcount; + unsigned long long hi, lo; + int exponent2; + + u.ieee.negative = sign; + u.ieee.negative2 = sign; + u.ieee.exponent = expt + IBM_EXTENDED_LONG_DOUBLE_BIAS; + u.ieee.exponent2 = 0; + exponent2 = expt - 53 + IBM_EXTENDED_LONG_DOUBLE_BIAS; + +#if BITS_PER_MP_LIMB == 32 + /* The low order 53 bits (52 + hidden) go into the lower double */ + lo = frac_ptr[0]; + lo |= (frac_ptr[1] & ((1LL << (53 - 32)) - 1)) << 32; + /* The high order 53 bits (52 + hidden) go into the upper double */ + hi = (frac_ptr[1] >> (53 - 32)) & ((1 << 11) - 1); + hi |= ((unsigned long long) frac_ptr[2]) << 11; + hi |= ((unsigned long long) frac_ptr[3]) << (32 + 11); +#elif BITS_PER_MP_LIMB == 64 + /* The low order 53 bits (52 + hidden) go into the lower double */ + lo = frac_ptr[0] & (((mp_limb_t) 1 << 53) - 1); + /* The high order 53 bits (52 + hidden) go into the upper double */ + hi = (frac_ptr[0] >> 53) & (((mp_limb_t) 1 << 11) - 1); + hi |= (frac_ptr[1] << 11); +#else + #error "mp_limb size " BITS_PER_MP_LIMB "not accounted for" +#endif + + if ((hi & (1LL << 52)) == 0 && (hi | lo) != 0) + { + /* denormal number */ + unsigned long long val = hi ? hi : lo; + + if (sizeof (val) == sizeof (long)) + lzcount = __builtin_clzl (val); + else if ((val >> 32) != 0) + lzcount = __builtin_clzl ((long) (val >> 32)); + else + lzcount = __builtin_clzl ((long) val) + 32; + if (hi) + lzcount = lzcount - 11; + else + lzcount = lzcount + 42; + + if (lzcount > u.ieee.exponent) + { + lzcount = u.ieee.exponent; + u.ieee.exponent = 0; + exponent2 -= lzcount; + } + else + { + u.ieee.exponent -= (lzcount - 1); + exponent2 -= (lzcount - 1); + } + + if (lzcount <= 53) + { + hi = (hi << lzcount) | (lo >> (53 - lzcount)); + lo = (lo << lzcount) & ((1LL << 53) - 1); + } + else + { + hi = lo << (lzcount - 53); + lo = 0; + } + } + + if (lo != 0L) + { + /* hidden2 bit of low double controls rounding of the high double. + If hidden2 is '1' and either the explicit mantissa is non-zero + or hi is odd, then round up hi and adjust lo (2nd mantissa) + plus change the sign of the low double to compensate. */ + if ((lo & (1LL << 52)) != 0 + && ((hi & 1) != 0 || (lo & ((1LL << 52) - 1)))) + { + hi++; + if ((hi & ((1LL << 52) - 1)) == 0) + { + if ((hi & (1LL << 53)) != 0) + hi -= 1LL << 52; + u.ieee.exponent++; + } + u.ieee.negative2 = !sign; + lo = (1LL << 53) - lo; + } + + /* The hidden bit of the lo mantissa is zero so we need to normalize + it for the low double. Shift it left until the hidden bit is '1' + then adjust the 2nd exponent accordingly. */ + + if (sizeof (lo) == sizeof (long)) + lzcount = __builtin_clzl (lo); + else if ((lo >> 32) != 0) + lzcount = __builtin_clzl ((long) (lo >> 32)); + else + lzcount = __builtin_clzl ((long) lo) + 32; + lzcount = lzcount - 11; + if (lzcount > 0) + { + lo = lo << lzcount; + exponent2 = exponent2 - lzcount; + } + if (exponent2 > 0) + u.ieee.exponent2 = exponent2; + else + lo >>= 1 - exponent2; + } + else + u.ieee.negative2 = 0; + + u.ieee.mantissa3 = lo & 0xffffffffLL; + u.ieee.mantissa2 = (lo >> 32) & 0xfffff; + u.ieee.mantissa1 = hi & 0xffffffffLL; + u.ieee.mantissa0 = (hi >> 32) & ((1LL << (LDBL_MANT_DIG - 86)) - 1); + + return u.d; +} diff --git a/pool/shard002/C/0059746_rsdos.c b/pool/shard002/C/0059746_rsdos.c new file mode 100644 index 0000000000000000000000000000000000000000..304e5eb234b19c8a0ef2a018ca8a61f7ca3f1202 --- /dev/null +++ b/pool/shard002/C/0059746_rsdos.c @@ -0,0 +1,195 @@ +/* XRoar - a Dragon/Tandy Coco emulator + * Copyright (C) 2003-2010 Ciaran Anscomb + * + * 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 + */ + +/* Sources: + * CoCo DOS cartridge detail: + * http://www.coco3.com/unravalled/disk-basic-unravelled.pdf + */ + +#include +#include + +#include "types.h" +#include "cart.h" +#include "events.h" +#include "logging.h" +#include "m6809.h" +#include "machine.h" +#include "rsdos.h" +#include "vdrive.h" +#include "wd279x.h" +#include "xroar.h" + +static int io_read(int addr); +static void io_write(int addr, int val); +static void reset(void); +static void detach(void); +static struct cart cart; + +/* Handle signals from WD2793 */ +static void set_drq_handler(void); +static void reset_drq_handler(void); +static void set_intrq_handler(void); +static void reset_intrq_handler(void); + +/* NMIs queued to allow CPU to run next instruction */ +static event_t nmi_event; +static void do_nmi(void); +#define QUEUE_NMI() do { \ + nmi_event.at_cycle = current_cycle + 1; \ + event_queue(&MACHINE_EVENT_LIST, &nmi_event); \ + } while (0) + +/* Latch that's part of the RSDOS cart: */ +static int ic1_old; +static int ic1_drive_select; +static int ic1_density; +static int drq_flag; +static int intrq_flag; +static int halt_enable; + +static void ff40_write(int octet); + +struct cart *rsdos_new(const char *filename) { + cart.type = CART_RSDOS; + memset(cart.mem_data, 0x7e, sizeof(cart.mem_data)); + machine_load_rom(filename, cart.mem_data, sizeof(cart.mem_data)); + cart.mem_writable = 0; + cart.io_read = io_read; + cart.io_write = io_write; + cart.reset = reset; + cart.detach = detach; + wd279x_type = WD2793; + wd279x_set_drq_handler = set_drq_handler; + wd279x_reset_drq_handler = reset_drq_handler; + wd279x_set_intrq_handler = set_intrq_handler; + wd279x_reset_intrq_handler = reset_intrq_handler; + event_init(&nmi_event); + nmi_event.dispatch = do_nmi; + return &cart; +} + +static void reset(void) { + wd279x_reset(); + ic1_old = 0xff; + ic1_drive_select = 0xff; + ic1_density = 0xff; + halt_enable = 0xff; + drq_flag = intrq_flag = 0; + ff40_write(0); +} + +static void detach(void) { + event_dequeue(&nmi_event); +} + +static int io_read(int addr) { + if ((addr & 15) == 8) return wd279x_status_read(); + if ((addr & 15) == 9) return wd279x_track_register_read(); + if ((addr & 15) == 10) return wd279x_sector_register_read(); + if ((addr & 15) == 11) return wd279x_data_register_read(); + return 0x7e; +} + +static void io_write(int addr, int val) { + if ((addr & 15) == 8) wd279x_command_write(val); + if ((addr & 15) == 9) wd279x_track_register_write(val); + if ((addr & 15) == 10) wd279x_sector_register_write(val); + if ((addr & 15) == 11) wd279x_data_register_write(val); + if (!(addr & 8)) ff40_write(val); +} + +/* RSDOS cartridge circuitry */ +static void ff40_write(int octet) { + int new_drive_select = 0; + octet ^= 0x20; + if (octet & 0x01) { + new_drive_select = 0; + } else if (octet & 0x02) { + new_drive_select = 1; + } else if (octet & 0x04) { + new_drive_select = 2; + } + vdrive_set_side(octet & 0x40 ? 1 : 0); + if (octet != ic1_old) { + LOG_DEBUG(4, "RSDOS: Write to FF40: "); + if (new_drive_select != ic1_drive_select) { + LOG_DEBUG(4, "DRIVE SELECT %d, ", new_drive_select); + } + if ((octet ^ ic1_old) & 0x08) { + LOG_DEBUG(4, "MOTOR %s, ", (octet & 0x08)?"ON":"OFF"); + } + if ((octet ^ ic1_old) & 0x20) { + LOG_DEBUG(4, "DENSITY %s, ", (octet & 0x20)?"SINGLE":"DOUBLE"); + } + if ((octet ^ ic1_old) & 0x10) { + LOG_DEBUG(4, "PRECOMP %s, ", (octet & 0x10)?"ON":"OFF"); + } + if ((octet ^ ic1_old) & 0x40) { + LOG_DEBUG(4, "SIDE %d, ", (octet & 0x40) >> 6); + } + if ((octet ^ ic1_old) & 0x80) { + LOG_DEBUG(4, "HALT %s, ", (octet & 0x80)?"ENABLED":"DISABLED"); + } + LOG_DEBUG(4, "\n"); + ic1_old = octet; + } + ic1_drive_select = new_drive_select; + vdrive_set_drive(ic1_drive_select); + ic1_density = octet & 0x20; + wd279x_set_density(ic1_density); + if (ic1_density && intrq_flag) { + nmi = 1; + } + halt_enable = octet & 0x80; + if (intrq_flag) halt_enable = 0; + if (halt_enable && !drq_flag) { + halt = 1; + } else { + halt = 0; + } +} + +static void set_drq_handler(void) { + drq_flag = 1; + halt = 0; +} + +static void reset_drq_handler(void) { + drq_flag = 0; + if (halt_enable) { + halt = 1; + } +} + +static void set_intrq_handler(void) { + intrq_flag = 1; + halt_enable = halt = 0; + QUEUE_NMI(); +} + +static void reset_intrq_handler(void) { + intrq_flag = 0; + nmi = 0; +} + +static void do_nmi(void) { + if (!ic1_density && intrq_flag) { + nmi = 1; + } +} diff --git a/pool/shard002/C/0059763_hdmi.c b/pool/shard002/C/0059763_hdmi.c new file mode 100644 index 0000000000000000000000000000000000000000..880ae726861131e73b54f52ffeb1372a8ef446ce --- /dev/null +++ b/pool/shard002/C/0059763_hdmi.c @@ -0,0 +1,109 @@ +/* + * ALSA SoC codec driver for HDMI audio codecs. + * Copyright (C) 2012 Texas Instruments Incorporated - http://www.ti.com/ + * Author: Ricardo Neri + * + * 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 + +#define DRV_NAME "hdmi-audio-codec" + +static const struct snd_soc_dapm_widget hdmi_widgets[] = { + SND_SOC_DAPM_INPUT("RX"), + SND_SOC_DAPM_OUTPUT("TX"), +}; + +static const struct snd_soc_dapm_route hdmi_routes[] = { + { "Capture", NULL, "RX" }, + { "TX", NULL, "Playback" }, +}; + +static struct snd_soc_dai_driver hdmi_codec_dai = { + .name = "hdmi-hifi", + .playback = { + .stream_name = "Playback", + .channels_min = 2, + .channels_max = 8, + .rates = SNDRV_PCM_RATE_32000 | + SNDRV_PCM_RATE_44100 | SNDRV_PCM_RATE_48000 | + SNDRV_PCM_RATE_88200 | SNDRV_PCM_RATE_96000 | + SNDRV_PCM_RATE_176400 | SNDRV_PCM_RATE_192000, + .formats = SNDRV_PCM_FMTBIT_S16_LE | + SNDRV_PCM_FMTBIT_S24_LE | SNDRV_PCM_FMTBIT_S32_LE, +// .sig_bits = 24, + }, + .capture = { + .stream_name = "Capture", + .channels_min = 2, + .channels_max = 2, + .rates = SNDRV_PCM_RATE_32000 | + SNDRV_PCM_RATE_44100 | SNDRV_PCM_RATE_48000 | + SNDRV_PCM_RATE_88200 | SNDRV_PCM_RATE_96000 | + SNDRV_PCM_RATE_176400 | SNDRV_PCM_RATE_192000, + .formats = SNDRV_PCM_FMTBIT_S16_LE | + SNDRV_PCM_FMTBIT_S24_LE, + }, + +}; + +#ifdef CONFIG_OF +static const struct of_device_id hdmi_audio_codec_ids[] = { + { .compatible = "linux,hdmi-audio", }, + { } +}; +MODULE_DEVICE_TABLE(of, hdmi_audio_codec_ids); +#endif + +static struct snd_soc_codec_driver hdmi_codec = { + .dapm_widgets = hdmi_widgets, + .num_dapm_widgets = ARRAY_SIZE(hdmi_widgets), + .dapm_routes = hdmi_routes, + .num_dapm_routes = ARRAY_SIZE(hdmi_routes), + .ignore_pmdown_time = true, +}; + +static int hdmi_codec_probe(struct platform_device *pdev) +{ + return snd_soc_register_codec(&pdev->dev, &hdmi_codec, + &hdmi_codec_dai, 1); +} + +static int hdmi_codec_remove(struct platform_device *pdev) +{ + snd_soc_unregister_codec(&pdev->dev); + return 0; +} + +static struct platform_driver hdmi_codec_driver = { + .driver = { + .name = DRV_NAME, + .of_match_table = of_match_ptr(hdmi_audio_codec_ids), + }, + + .probe = hdmi_codec_probe, + .remove = hdmi_codec_remove, +}; + +module_platform_driver(hdmi_codec_driver); + +MODULE_AUTHOR("Ricardo Neri "); +MODULE_DESCRIPTION("ASoC generic HDMI codec driver"); +MODULE_LICENSE("GPL"); +MODULE_ALIAS("platform:" DRV_NAME); diff --git a/pool/shard002/C/0059773_strstr.c b/pool/shard002/C/0059773_strstr.c new file mode 100644 index 0000000000000000000000000000000000000000..fd22ca8b9b585295790332f5e04ab4601a120f3d --- /dev/null +++ b/pool/shard002/C/0059773_strstr.c @@ -0,0 +1,82 @@ +/* Copyright (C) 1991-1994, 1996-1998, 2000, 2004, 2007-2012 Free Software + Foundation, Inc. + This file is part of the GNU C Library. + + 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, see . */ + +/* This particular implementation was written by Eric Blake, 2008. */ + +#ifndef _LIBC +# include +#endif + +/* Specification of strstr. */ +#include + +#include + +#ifndef _LIBC +# define __builtin_expect(expr, val) (expr) +#endif + +#define RETURN_TYPE char * +#define AVAILABLE(h, h_l, j, n_l) \ + (!memchr ((h) + (h_l), '\0', (j) + (n_l) - (h_l)) \ + && ((h_l) = (j) + (n_l))) +#include "str-two-way.h" + +/* Return the first occurrence of NEEDLE in HAYSTACK. Return HAYSTACK + if NEEDLE is empty, otherwise NULL if NEEDLE is not found in + HAYSTACK. */ +char * +strstr (const char *haystack_start, const char *needle_start) +{ + const char *haystack = haystack_start; + const char *needle = needle_start; + size_t needle_len; /* Length of NEEDLE. */ + size_t haystack_len; /* Known minimum length of HAYSTACK. */ + bool ok = true; /* True if NEEDLE is prefix of HAYSTACK. */ + + /* Determine length of NEEDLE, and in the process, make sure + HAYSTACK is at least as long (no point processing all of a long + NEEDLE if HAYSTACK is too short). */ + while (*haystack && *needle) + ok &= *haystack++ == *needle++; + if (*needle) + return NULL; + if (ok) + return (char *) haystack_start; + + /* Reduce the size of haystack using strchr, since it has a smaller + linear coefficient than the Two-Way algorithm. */ + needle_len = needle - needle_start; + haystack = strchr (haystack_start + 1, *needle_start); + if (!haystack || __builtin_expect (needle_len == 1, 0)) + return (char *) haystack; + needle -= needle_len; + haystack_len = (haystack > haystack_start + needle_len ? 1 + : needle_len + haystack_start - haystack); + + /* Perform the search. Abstract memory is considered to be an array + of 'unsigned char' values, not an array of 'char' values. See + ISO C 99 section 6.2.6.1. */ + if (needle_len < LONG_NEEDLE_THRESHOLD) + return two_way_short_needle ((const unsigned char *) haystack, + haystack_len, + (const unsigned char *) needle, needle_len); + return two_way_long_needle ((const unsigned char *) haystack, haystack_len, + (const unsigned char *) needle, needle_len); +} + +#undef LONG_NEEDLE_THRESHOLD diff --git a/pool/shard002/C/0059792_config.c b/pool/shard002/C/0059792_config.c new file mode 100644 index 0000000000000000000000000000000000000000..17be9b2beb81594c38027dbcd1a1a4856c67d82f --- /dev/null +++ b/pool/shard002/C/0059792_config.c @@ -0,0 +1,115 @@ +/* + * Copyright 2007, Intel Corporation + * + * This file is part of PowerTOP + * + * This program file 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 in a file named COPYING; if not, write to the + * Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, + * Boston, MA 02110-1301 USA + * + * Authors: + * Arjan van de Ven + */ + +#include +#include +#include +#include +#include +#include +#include + +#include "powertop.h" + +/* static arrays are not nice programming.. but they're easy */ +#define MAXCONFIGLINES 10000 +static char configlines[MAXCONFIGLINES][100]; +static int configcount; + +static void read_kernel_config(void) +{ + FILE *file; + char version[100], *c; + char filename[100]; + if (configcount) + return; + if (access("/proc/config.gz", R_OK) == 0) { + file = popen("zcat /proc/config.gz 2> /dev/null", "r"); + while (file && !feof(file)) { + char line[100]; + if (fgets(line, 100, file) == NULL) + break; + if (configcount >= MAXCONFIGLINES) + break; + strcpy(configlines[configcount++], line); + } + pclose(file); + return; + } + file = fopen("/proc/sys/kernel/osrelease", "r"); + if (!file) + return; + if (fgets(version, 100, file) == NULL) { + fclose(file); + return; + } + fclose(file); + c = strchr(version, '\n'); + if (c) + *c = 0; + sprintf(filename, "/boot/config-%s", version); + file = fopen(filename, "r"); + if (!file) { + sprintf(filename, "/lib/modules/%s/build/.config", version); + file = fopen(filename, "r"); + } + if (!file) + return; + while (!feof(file)) { + char line[100]; + if (fgets(line, 100, file) == NULL) + break; + strcpy(configlines[configcount++], line); + } + fclose(file); +} + +/* + * Suggest the user to turn on/off a kernel config option. + * "comment" gets displayed if it's not already set to the right value + */ +void suggest_kernel_config(char *string, int onoff, char *comment, int weight) +{ + int i; + char searchon[100]; + char searchoff[100]; + int found = 0; + + read_kernel_config(); + + sprintf(searchon, "%s=", string); + sprintf(searchoff, "# %s is not set", string); + + for (i = 0; i < configcount; i++) { + if (onoff && strstr(configlines[i], searchon)) + return; + if (onoff==0 && strstr(configlines[i], searchoff)) + return; + if (onoff==0 && strstr(configlines[i], searchon)) + found = 1; + } + if (onoff || found) + add_suggestion(comment, weight, 0, NULL, NULL); + fflush(stdout); +} diff --git a/pool/shard002/C/0059799_test-getpeername.c b/pool/shard002/C/0059799_test-getpeername.c new file mode 100644 index 0000000000000000000000000000000000000000..ef6abb7c4eacf006bda06ebbc386b9d4a2d19f4f --- /dev/null +++ b/pool/shard002/C/0059799_test-getpeername.c @@ -0,0 +1,56 @@ +/* -*- buffer-read-only: t -*- vi: set ro: */ +/* DO NOT EDIT! GENERATED AUTOMATICALLY! */ +/* Test getpeername() function. + Copyright (C) 2011 Free Software Foundation, Inc. + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . */ + +#include + +#include + +#include "signature.h" +SIGNATURE_CHECK (getpeername, int, (int, struct sockaddr *, socklen_t *)); + +#include +#include + +#include "sockets.h" +#include "macros.h" + +int +main (void) +{ + gl_sockets_startup (SOCKETS_1_1); + + /* Test behaviour for invalid file descriptors. */ + { + struct sockaddr_in addr; + socklen_t addrlen = sizeof (addr); + + errno = 0; + ASSERT (getpeername (-1, (struct sockaddr *) &addr, &addrlen) == -1); + ASSERT (errno == EBADF); + } + { + struct sockaddr_in addr; + socklen_t addrlen = sizeof (addr); + + errno = 0; + ASSERT (getpeername (99, (struct sockaddr *) &addr, &addrlen) == -1); + ASSERT (errno == EBADF); + } + + return 0; +} diff --git a/pool/shard002/C/0059804_grey.c b/pool/shard002/C/0059804_grey.c new file mode 100644 index 0000000000000000000000000000000000000000..2c602833a204a583d371745a7f2b7acc5c7abbc3 --- /dev/null +++ b/pool/shard002/C/0059804_grey.c @@ -0,0 +1,133 @@ +/* grey ramps + * + * Copyright: 1990, N. Dessipris. + * + * Author: Nicos Dessipris + * Written on: 02/02/1990 + * Modified on: + * 22/7/93 JC + * - im_outcheck() added + * - externs removed + * 8/2/95 JC + * - ANSIfied + * - im_fgrey() made from im_grey() + * 31/8/95 JC + * - now makes [0,1], rather than [0,256) + * - im_grey() now defined in terms of im_fgrey() + * 2/3/98 JC + * - partialed + * 1/2/11 + * - gtk-doc + * 13/6/13 + * - redo as a class + */ + +/* + + This file is part of VIPS. + + VIPS is free software; you can redistribute it and/or modify + it under the terms of the GNU Lesser General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA + 02110-1301 USA + + */ + +/* + + These files are distributed with VIPS - http://www.vips.ecs.soton.ac.uk + + */ + +/* +#define VIPS_DEBUG + */ + +#ifdef HAVE_CONFIG_H +#include +#endif /*HAVE_CONFIG_H*/ +#include + +#include +#include +#include +#include + +#include + +#include "pcreate.h" +#include "point.h" + +typedef VipsPoint VipsGrey; +typedef VipsPointClass VipsGreyClass; + +G_DEFINE_TYPE( VipsGrey, vips_grey, VIPS_TYPE_POINT ); + +static float +vips_grey_point( VipsPoint *point, int x, int y ) +{ + return( (double) x / (point->width - 1) ); +} + +static void +vips_grey_class_init( VipsGreyClass *class ) +{ + VipsObjectClass *vobject_class = VIPS_OBJECT_CLASS( class ); + VipsPointClass *point_class = VIPS_POINT_CLASS( class ); + + vobject_class->nickname = "grey"; + vobject_class->description = _( "make a grey ramp image" ); + + point_class->point = vips_grey_point; + point_class->min = 0.0; + point_class->max = 1.0; +} + +static void +vips_grey_init( VipsGrey *grey ) +{ +} + +/** + * vips_grey: + * @out: output image + * @width: image size + * @height: image size + * @...: %NULL-terminated list of optional named arguments + * + * Optional arguments: + * + * @uchar: output a uchar image + * + * Create a one-band float image with the left-most column zero and the + * right-most 1. Intermediate pixels are a linear ramp. + * + * Set @uchar to output a uchar image with the leftmost pixel 0 and the + * rightmost 255. + * + * See also: vips_xyz(), vips_identity(). + * + * Returns: 0 on success, -1 on error + */ +int +vips_grey( VipsImage **out, int width, int height, ... ) +{ + va_list ap; + int result; + + va_start( ap, height ); + result = vips_call_split( "grey", ap, out, width, height ); + va_end( ap ); + + return( result ); +} diff --git a/pool/shard002/C/0059807_scm-pas.c b/pool/shard002/C/0059807_scm-pas.c new file mode 100644 index 0000000000000000000000000000000000000000..78a758650e70410dbdcef0167f98305903b60047 --- /dev/null +++ b/pool/shard002/C/0059807_scm-pas.c @@ -0,0 +1,208 @@ +/* Copyright (c) 2010-2011, Code Aurora Forum. 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) "scm-pas: " fmt + +#include +#include +#include +#include + +#include +#include +#include +#include +#include "scm-pas.h" + +#define PAS_INIT_IMAGE_CMD 1 +#define PAS_AUTH_AND_RESET_CMD 5 +#define PAS_SHUTDOWN_CMD 6 +#define PAS_IS_SUPPORTED_CMD 7 + +int pas_init_image(enum pas_id id, const u8 *metadata, size_t size) +{ + int ret; + struct pas_init_image_req { + u32 proc; + u32 image_addr; + } request; + u32 scm_ret = 0; + /* Make memory physically contiguous */ + void *mdata_buf = kmemdup(metadata, size, GFP_KERNEL); + + if (!mdata_buf) + return -ENOMEM; + + request.proc = id; + request.image_addr = virt_to_phys(mdata_buf); + + ret = scm_call(SCM_SVC_PIL, PAS_INIT_IMAGE_CMD, &request, + sizeof(request), &scm_ret, sizeof(scm_ret)); + kfree(mdata_buf); + + if (ret) + return ret; + return scm_ret; +} +EXPORT_SYMBOL(pas_init_image); + +static struct msm_bus_paths scm_pas_bw_tbl[] = { + { + .vectors = (struct msm_bus_vectors[]){ + { + .src = MSM_BUS_MASTER_SPS, + .dst = MSM_BUS_SLAVE_EBI_CH0, + }, + }, + .num_paths = 1, + }, + { + .vectors = (struct msm_bus_vectors[]){ + { + .src = MSM_BUS_MASTER_SPS, + .dst = MSM_BUS_SLAVE_EBI_CH0, + .ib = 492 * 8 * 1000000UL, + .ab = 492 * 8 * 100000UL, + }, + }, + .num_paths = 1, + }, +}; + +static struct msm_bus_scale_pdata scm_pas_bus_pdata = { + .usecase = scm_pas_bw_tbl, + .num_usecases = ARRAY_SIZE(scm_pas_bw_tbl), + .name = "scm_pas", +}; + +static uint32_t scm_perf_client; +static struct clk *scm_bus_clk; + +static DEFINE_MUTEX(scm_pas_bw_mutex); +static int scm_pas_bw_count; + +static int scm_pas_enable_bw(void) +{ + int ret = 0; + + if (!scm_perf_client || !scm_bus_clk) + return -EINVAL; + + mutex_lock(&scm_pas_bw_mutex); + if (!scm_pas_bw_count) { + ret = msm_bus_scale_client_update_request(scm_perf_client, 1); + if (ret) { + pr_err("bandwidth request failed (%d)\n", ret); + } else { + ret = clk_enable(scm_bus_clk); + if (ret) + pr_err("clock enable failed\n"); + } + } + if (ret) + msm_bus_scale_client_update_request(scm_perf_client, 0); + else + scm_pas_bw_count++; + mutex_unlock(&scm_pas_bw_mutex); + return ret; +} + +static void scm_pas_disable_bw(void) +{ + mutex_lock(&scm_pas_bw_mutex); + if (scm_pas_bw_count-- == 1) { + msm_bus_scale_client_update_request(scm_perf_client, 0); + clk_disable(scm_bus_clk); + } + mutex_unlock(&scm_pas_bw_mutex); +} + +int pas_auth_and_reset(enum pas_id id) +{ + int ret, bus_ret; + u32 proc = id, scm_ret = 0; + + bus_ret = scm_pas_enable_bw(); + ret = scm_call(SCM_SVC_PIL, PAS_AUTH_AND_RESET_CMD, &proc, + sizeof(proc), &scm_ret, sizeof(scm_ret)); + if (ret) + scm_ret = ret; + if (!bus_ret) + scm_pas_disable_bw(); + + return scm_ret; +} +EXPORT_SYMBOL(pas_auth_and_reset); + +int pas_shutdown(enum pas_id id) +{ + int ret; + u32 proc = id, scm_ret = 0; + + ret = scm_call(SCM_SVC_PIL, PAS_SHUTDOWN_CMD, &proc, sizeof(proc), + &scm_ret, sizeof(scm_ret)); + if (ret) + return ret; + + return scm_ret; +} +EXPORT_SYMBOL(pas_shutdown); + +static bool secure_pil = true; +module_param(secure_pil, bool, S_IRUGO); +MODULE_PARM_DESC(secure_pil, "Use secure PIL"); + +int pas_supported(enum pas_id id) +{ + int ret; + u32 periph = id, ret_val = 0; + + if (!secure_pil) + return 0; + + /* + * 8660 SCM doesn't support querying secure PIL support so just return + * true if not overridden on the command line. + */ + if (cpu_is_msm8x60()) + return 1; + + if (scm_is_call_available(SCM_SVC_PIL, PAS_IS_SUPPORTED_CMD) <= 0) + return 0; + + ret = scm_call(SCM_SVC_PIL, PAS_IS_SUPPORTED_CMD, &periph, + sizeof(periph), &ret_val, sizeof(ret_val)); + if (ret) + return ret; + + return ret_val; +} +EXPORT_SYMBOL(pas_supported); + +static int __init scm_pas_init(void) +{ + /* TODO: Remove once bus scaling driver is in place */ + if (!cpu_is_apq8064()) + scm_perf_client = msm_bus_scale_register_client( + &scm_pas_bus_pdata); + if (!scm_perf_client) + pr_warn("unable to register bus client\n"); + scm_bus_clk = clk_get_sys("scm", "bus_clk"); + if (!IS_ERR(scm_bus_clk)) { + clk_set_rate(scm_bus_clk, 64000000); + } else { + scm_bus_clk = NULL; + pr_warn("unable to get bus clock\n"); + } + return 0; +} +module_init(scm_pas_init); diff --git a/pool/shard002/C/0059809_shared.c b/pool/shard002/C/0059809_shared.c new file mode 100644 index 0000000000000000000000000000000000000000..a56c70fa7f65c847e1dbc61ac0001362deadeffc --- /dev/null +++ b/pool/shard002/C/0059809_shared.c @@ -0,0 +1,390 @@ +/* + * Mesa 3-D graphics library + * Version: 7.5 + * + * Copyright (C) 2009 VMware, Inc. All Rights Reserved. + * + * 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 + * BRIAN PAUL 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. + */ + +/** + * \file shared.c + * Shared-context state + */ + + + +#include "imports.h" +#include "mtypes.h" +#include "hash.h" +#if FEATURE_ATI_fragment_shader +#include "atifragshader.h" +#endif +#include "bufferobj.h" +#include "shared.h" +#include "program/program.h" +#include "dlist.h" +#include "shaderobj.h" +#include "syncobj.h" + +/** + * Allocate and initialize a shared context state structure. + * Initializes the display list, texture objects and vertex programs hash + * tables, allocates the texture objects. If it runs out of memory, frees + * everything already allocated before returning NULL. + * + * \return pointer to a gl_shared_state structure on success, or NULL on + * failure. + */ +struct gl_shared_state * +_mesa_alloc_shared_state(GLcontext *ctx) +{ + struct gl_shared_state *shared; + GLuint i; + + shared = CALLOC_STRUCT(gl_shared_state); + if (!shared) + return NULL; + + _glthread_INIT_MUTEX(shared->Mutex); + + shared->DisplayList = _mesa_NewHashTable(); + shared->TexObjects = _mesa_NewHashTable(); + shared->Programs = _mesa_NewHashTable(); + +#if FEATURE_ARB_vertex_program + shared->DefaultVertexProgram = (struct gl_vertex_program *) + ctx->Driver.NewProgram(ctx, GL_VERTEX_PROGRAM_ARB, 0); +#endif + +#if FEATURE_ARB_fragment_program + shared->DefaultFragmentProgram = (struct gl_fragment_program *) + ctx->Driver.NewProgram(ctx, GL_FRAGMENT_PROGRAM_ARB, 0); +#endif + +#if FEATURE_ATI_fragment_shader + shared->ATIShaders = _mesa_NewHashTable(); + shared->DefaultFragmentShader = _mesa_new_ati_fragment_shader(ctx, 0); +#endif + +#if FEATURE_ARB_shader_objects + shared->ShaderObjects = _mesa_NewHashTable(); +#endif + +#if FEATURE_ARB_vertex_buffer_object || FEATURE_ARB_pixel_buffer_object + shared->BufferObjects = _mesa_NewHashTable(); +#endif + + /* Allocate the default buffer object */ + shared->NullBufferObj = ctx->Driver.NewBufferObject(ctx, 0, 0); + + /* Create default texture objects */ + for (i = 0; i < NUM_TEXTURE_TARGETS; i++) { + /* NOTE: the order of these enums matches the TEXTURE_x_INDEX values */ + static const GLenum targets[NUM_TEXTURE_TARGETS] = { + GL_TEXTURE_2D_ARRAY_EXT, + GL_TEXTURE_1D_ARRAY_EXT, + GL_TEXTURE_CUBE_MAP, + GL_TEXTURE_3D, + GL_TEXTURE_RECTANGLE_NV, + GL_TEXTURE_2D, + GL_TEXTURE_1D + }; + shared->DefaultTex[i] = ctx->Driver.NewTextureObject(ctx, 0, targets[i]); + } + + /* sanity check */ + assert(shared->DefaultTex[TEXTURE_1D_INDEX]->RefCount == 1); + + /* Mutex and timestamp for texobj state validation */ + _glthread_INIT_MUTEX(shared->TexMutex); + shared->TextureStateStamp = 0; + +#if FEATURE_EXT_framebuffer_object + shared->FrameBuffers = _mesa_NewHashTable(); + shared->RenderBuffers = _mesa_NewHashTable(); +#endif + + make_empty_list(& shared->SyncObjects); + + return shared; +} + + +/** + * Callback for deleting a display list. Called by _mesa_HashDeleteAll(). + */ +static void +delete_displaylist_cb(GLuint id, void *data, void *userData) +{ + struct gl_display_list *list = (struct gl_display_list *) data; + GLcontext *ctx = (GLcontext *) userData; + _mesa_delete_list(ctx, list); +} + + +/** + * Callback for deleting a texture object. Called by _mesa_HashDeleteAll(). + */ +static void +delete_texture_cb(GLuint id, void *data, void *userData) +{ + struct gl_texture_object *texObj = (struct gl_texture_object *) data; + GLcontext *ctx = (GLcontext *) userData; + ctx->Driver.DeleteTexture(ctx, texObj); +} + + +/** + * Callback for deleting a program object. Called by _mesa_HashDeleteAll(). + */ +static void +delete_program_cb(GLuint id, void *data, void *userData) +{ + struct gl_program *prog = (struct gl_program *) data; + GLcontext *ctx = (GLcontext *) userData; + if(prog != &_mesa_DummyProgram) { + ASSERT(prog->RefCount == 1); /* should only be referenced by hash table */ + prog->RefCount = 0; /* now going away */ + ctx->Driver.DeleteProgram(ctx, prog); + } +} + + +#if FEATURE_ATI_fragment_shader +/** + * Callback for deleting an ATI fragment shader object. + * Called by _mesa_HashDeleteAll(). + */ +static void +delete_fragshader_cb(GLuint id, void *data, void *userData) +{ + struct ati_fragment_shader *shader = (struct ati_fragment_shader *) data; + GLcontext *ctx = (GLcontext *) userData; + _mesa_delete_ati_fragment_shader(ctx, shader); +} +#endif + + +/** + * Callback for deleting a buffer object. Called by _mesa_HashDeleteAll(). + */ +static void +delete_bufferobj_cb(GLuint id, void *data, void *userData) +{ + struct gl_buffer_object *bufObj = (struct gl_buffer_object *) data; + GLcontext *ctx = (GLcontext *) userData; + if (_mesa_bufferobj_mapped(bufObj)) { + ctx->Driver.UnmapBuffer(ctx, 0, bufObj); + bufObj->Pointer = NULL; + } + _mesa_reference_buffer_object(ctx, &bufObj, NULL); +} + + +/** + * Callback for freeing shader program data. Call it before delete_shader_cb + * to avoid memory access error. + */ +static void +free_shader_program_data_cb(GLuint id, void *data, void *userData) +{ + GLcontext *ctx = (GLcontext *) userData; + struct gl_shader_program *shProg = (struct gl_shader_program *) data; + + if (shProg->Type == GL_SHADER_PROGRAM_MESA) { + _mesa_free_shader_program_data(ctx, shProg); + } +} + + +/** + * Callback for deleting shader and shader programs objects. + * Called by _mesa_HashDeleteAll(). + */ +static void +delete_shader_cb(GLuint id, void *data, void *userData) +{ + GLcontext *ctx = (GLcontext *) userData; + struct gl_shader *sh = (struct gl_shader *) data; + if (sh->Type == GL_FRAGMENT_SHADER || sh->Type == GL_VERTEX_SHADER) { + ctx->Driver.DeleteShader(ctx, sh); + } + else { + struct gl_shader_program *shProg = (struct gl_shader_program *) data; + ASSERT(shProg->Type == GL_SHADER_PROGRAM_MESA); + ctx->Driver.DeleteShaderProgram(ctx, shProg); + } +} + + +/** + * Callback for deleting a framebuffer object. Called by _mesa_HashDeleteAll() + */ +static void +delete_framebuffer_cb(GLuint id, void *data, void *userData) +{ + struct gl_framebuffer *fb = (struct gl_framebuffer *) data; + /* The fact that the framebuffer is in the hashtable means its refcount + * is one, but we're removing from the hashtable now. So clear refcount. + */ + /*assert(fb->RefCount == 1);*/ + fb->RefCount = 0; + + /* NOTE: Delete should always be defined but there are two reports + * of it being NULL (bugs 13507, 14293). Work-around for now. + */ + if (fb->Delete) + fb->Delete(fb); +} + + +/** + * Callback for deleting a renderbuffer object. Called by _mesa_HashDeleteAll() + */ +static void +delete_renderbuffer_cb(GLuint id, void *data, void *userData) +{ + struct gl_renderbuffer *rb = (struct gl_renderbuffer *) data; + rb->RefCount = 0; /* see comment for FBOs above */ + if (rb->Delete) + rb->Delete(rb); +} + + +/** + * Deallocate a shared state object and all children structures. + * + * \param ctx GL context. + * \param shared shared state pointer. + * + * Frees the display lists, the texture objects (calling the driver texture + * deletion callback to free its private data) and the vertex programs, as well + * as their hash tables. + * + * \sa alloc_shared_state(). + */ +static void +free_shared_state(GLcontext *ctx, struct gl_shared_state *shared) +{ + GLuint i; + + /* Free the dummy/fallback texture object */ + if (shared->FallbackTex) + ctx->Driver.DeleteTexture(ctx, shared->FallbackTex); + + /* + * Free display lists + */ + _mesa_HashDeleteAll(shared->DisplayList, delete_displaylist_cb, ctx); + _mesa_DeleteHashTable(shared->DisplayList); + +#if FEATURE_ARB_shader_objects + _mesa_HashWalk(shared->ShaderObjects, free_shader_program_data_cb, ctx); + _mesa_HashDeleteAll(shared->ShaderObjects, delete_shader_cb, ctx); + _mesa_DeleteHashTable(shared->ShaderObjects); +#endif + + _mesa_HashDeleteAll(shared->Programs, delete_program_cb, ctx); + _mesa_DeleteHashTable(shared->Programs); + +#if FEATURE_ARB_vertex_program + _mesa_reference_vertprog(ctx, &shared->DefaultVertexProgram, NULL); +#endif + +#if FEATURE_ARB_fragment_program + _mesa_reference_fragprog(ctx, &shared->DefaultFragmentProgram, NULL); +#endif + +#if FEATURE_ATI_fragment_shader + _mesa_HashDeleteAll(shared->ATIShaders, delete_fragshader_cb, ctx); + _mesa_DeleteHashTable(shared->ATIShaders); + _mesa_delete_ati_fragment_shader(ctx, shared->DefaultFragmentShader); +#endif + +#if FEATURE_ARB_vertex_buffer_object || FEATURE_ARB_pixel_buffer_object + _mesa_HashDeleteAll(shared->BufferObjects, delete_bufferobj_cb, ctx); + _mesa_DeleteHashTable(shared->BufferObjects); +#endif + +#if FEATURE_EXT_framebuffer_object + _mesa_HashDeleteAll(shared->FrameBuffers, delete_framebuffer_cb, ctx); + _mesa_DeleteHashTable(shared->FrameBuffers); + _mesa_HashDeleteAll(shared->RenderBuffers, delete_renderbuffer_cb, ctx); + _mesa_DeleteHashTable(shared->RenderBuffers); +#endif + +#if FEATURE_ARB_vertex_buffer_object + _mesa_reference_buffer_object(ctx, &shared->NullBufferObj, NULL); +#endif + + { + struct simple_node *node; + struct simple_node *temp; + + foreach_s(node, temp, & shared->SyncObjects) { + _mesa_unref_sync_object(ctx, (struct gl_sync_object *) node); + } + } + + /* + * Free texture objects (after FBOs since some textures might have + * been bound to FBOs). + */ + ASSERT(ctx->Driver.DeleteTexture); + /* the default textures */ + for (i = 0; i < NUM_TEXTURE_TARGETS; i++) { + ctx->Driver.DeleteTexture(ctx, shared->DefaultTex[i]); + } + + /* all other textures */ + _mesa_HashDeleteAll(shared->TexObjects, delete_texture_cb, ctx); + _mesa_DeleteHashTable(shared->TexObjects); + + _glthread_DESTROY_MUTEX(shared->Mutex); + _glthread_DESTROY_MUTEX(shared->TexMutex); + + free(shared); +} + + +/** + * Decrement shared state object reference count and potentially free it + * and all children structures. + * + * \param ctx GL context. + * \param shared shared state pointer. + * + * \sa free_shared_state(). + */ +void +_mesa_release_shared_state(GLcontext *ctx, struct gl_shared_state *shared) +{ + GLint RefCount; + + _glthread_LOCK_MUTEX(shared->Mutex); + RefCount = --shared->RefCount; + _glthread_UNLOCK_MUTEX(shared->Mutex); + + assert(RefCount >= 0); + + if (RefCount == 0) { + /* free shared state */ + free_shared_state( ctx, shared ); + } +} diff --git a/pool/shard002/C/0059820_cmd_bmp.c b/pool/shard002/C/0059820_cmd_bmp.c new file mode 100644 index 0000000000000000000000000000000000000000..58debf375e589bbac7b2561b9e58bfe6fe55a19f --- /dev/null +++ b/pool/shard002/C/0059820_cmd_bmp.c @@ -0,0 +1,288 @@ +/* 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. + */ + +/* + * (C) Copyright 2002 + * Detlev Zundel, DENX Software Engineering, dzu@denx.de. + * + * 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 + */ + +/* + * BMP handling routines + */ + +#include +#include +#include +#include +#include +#include + +static int bmp_info (ulong addr); +static int bmp_display (ulong addr, int x, int y); + +/* + * Allocate and decompress a BMP image using gunzip(). + * + * Returns a pointer to the decompressed image data. Must be freed by + * the caller after use. + * + * Returns NULL if decompression failed, or if the decompressed data + * didn't contain a valid BMP signature. + */ +#ifdef CONFIG_VIDEO_BMP_GZIP +bmp_image_t *gunzip_bmp(unsigned long addr, unsigned long *lenp) +{ + void *dst; + unsigned long len; + bmp_image_t *bmp; + + /* + * Decompress bmp image + */ + len = CONFIG_SYS_VIDEO_LOGO_MAX_SIZE; + dst = malloc(CONFIG_SYS_VIDEO_LOGO_MAX_SIZE); + if (dst == NULL) { + puts("Error: malloc in gunzip failed!\n"); + return NULL; + } + if (gunzip(dst, CONFIG_SYS_VIDEO_LOGO_MAX_SIZE, (uchar *)addr, &len) != 0) { + free(dst); + return NULL; + } + if (len == CONFIG_SYS_VIDEO_LOGO_MAX_SIZE) + puts("Image could be truncated" + " (increase CONFIG_SYS_VIDEO_LOGO_MAX_SIZE)!\n"); + + bmp = dst; + + /* + * Check for bmp mark 'BM' + */ + if (!((bmp->header.signature[0] == 'B') && + (bmp->header.signature[1] == 'M'))) { + free(dst); + return NULL; + } + + puts("Gzipped BMP image detected!\n"); + + return bmp; +} +#else +bmp_image_t *gunzip_bmp(unsigned long addr, unsigned long *lenp) +{ + return NULL; +} +#endif + +static int do_bmp_info(cmd_tbl_t * cmdtp, int flag, int argc, char *argv[]) +{ + ulong addr; + + switch (argc) { + case 1: /* use load_addr as default address */ + addr = load_addr; + break; + case 2: /* use argument */ + addr = simple_strtoul(argv[1], NULL, 16); + break; + default: + cmd_usage(cmdtp); + return 1; + } + + return (bmp_info(addr)); +} + +static int do_bmp_display(cmd_tbl_t * cmdtp, int flag, int argc, char *argv[]) +{ + ulong addr; + int x = 0, y = 0; + + switch (argc) { + case 1: /* use load_addr as default address */ + addr = load_addr; + break; + case 2: /* use argument */ + addr = simple_strtoul(argv[1], NULL, 16); + break; + case 4: + addr = simple_strtoul(argv[1], NULL, 16); + x = simple_strtoul(argv[2], NULL, 10); + y = simple_strtoul(argv[3], NULL, 10); + break; + default: + cmd_usage(cmdtp); + return 1; + } + + return (bmp_display(addr, x, y)); +} + +static cmd_tbl_t cmd_bmp_sub[] = { + U_BOOT_CMD_MKENT(info, 3, 0, do_bmp_info, "", ""), + U_BOOT_CMD_MKENT(display, 5, 0, do_bmp_display, "", ""), +}; + +/* + * Subroutine: do_bmp + * + * Description: Handler for 'bmp' command.. + * + * Inputs: argv[1] contains the subcommand + * + * Return: None + * + */ +static int do_bmp(cmd_tbl_t *cmdtp, int flag, int argc, char *argv[]) +{ + cmd_tbl_t *c; + + /* Strip off leading 'bmp' command argument */ + argc--; + argv++; + + c = find_cmd_tbl(argv[0], &cmd_bmp_sub[0], ARRAY_SIZE(cmd_bmp_sub)); + + if (c) { + return c->cmd(cmdtp, flag, argc, argv); + } else { + cmd_usage(cmdtp); + return 1; + } +} + +U_BOOT_CMD( + bmp, 5, 1, do_bmp, + "manipulate BMP image data", + "info - display image info\n" + "bmp display [x y] - display image at x,y" +); + +/* + * Subroutine: bmp_info + * + * Description: Show information about bmp file in memory + * + * Inputs: addr address of the bmp file + * + * Return: None + * + */ +static int bmp_info(ulong addr) +{ + bmp_image_t *bmp=(bmp_image_t *)addr; + unsigned long len; + + if (!((bmp->header.signature[0]=='B') && + (bmp->header.signature[1]=='M'))) + bmp = gunzip_bmp(addr, &len); + + if (bmp == NULL) { + printf("There is no valid bmp file at the given address\n"); + return 1; + } + + printf("Image size : %d x %d\n", le32_to_cpu(bmp->header.width), + le32_to_cpu(bmp->header.height)); + printf("Bits per pixel: %d\n", le16_to_cpu(bmp->header.bit_count)); + printf("Compression : %d\n", le32_to_cpu(bmp->header.compression)); + + if ((unsigned long)bmp != addr) + free(bmp); + + return(0); +} + +/* + * Subroutine: bmp_display + * + * Description: Display bmp file located in memory + * + * Inputs: addr address of the bmp file + * + * Return: None + * + */ +static int bmp_display(ulong addr, int x, int y) +{ + int ret; + bmp_image_t *bmp = (bmp_image_t *)addr; + unsigned long len; + + if (!((bmp->header.signature[0]=='B') && + (bmp->header.signature[1]=='M'))) + bmp = gunzip_bmp(addr, &len); + + if (!bmp) { + printf("There is no valid bmp file at the given address\n"); + return 1; + } + +#if defined(CONFIG_LCD) + extern int lcd_display_bitmap (ulong, int, int); + + ret = lcd_display_bitmap ((unsigned long)bmp, x, y); +#elif defined(CONFIG_VIDEO) + extern int video_display_bitmap (ulong, int, int); + + ret = video_display_bitmap ((unsigned long)bmp, x, y); +#else +# error bmp_display() requires CONFIG_LCD or CONFIG_VIDEO +#endif + + if ((unsigned long)bmp != addr) + free(bmp); + + return ret; +} diff --git a/pool/shard002/C/0059842_lib.c b/pool/shard002/C/0059842_lib.c new file mode 100644 index 0000000000000000000000000000000000000000..77c0dcb39fccbc39b2b375b0d8659c13dbcbd387 --- /dev/null +++ b/pool/shard002/C/0059842_lib.c @@ -0,0 +1,88 @@ +/*- + * Copyright (c) 1999 Global Technology Associates, 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 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. + */ + +#include +__FBSDID("$FreeBSD: soc2013/dpl/head/sys/boot/i386/kgzldr/lib.c 119525 2003-08-25 23:28:32Z obrien $"); + +#include +#include + +#include "kgzldr.h" + +#define MEMSIZ 0x8000 /* Memory pool size */ + +int kgz_con; /* Console control */ + +static size_t memtot; /* Memory allocated: bytes */ +static u_int memcnt; /* Memory allocated: blocks */ + +/* + * Library functions required by inflate(). + */ + +/* + * Allocate memory block. + */ +unsigned char * +kzipmalloc(int size) +{ + static u_char mem[MEMSIZ]; + void *ptr; + + if (memtot + size > MEMSIZ) + return NULL; + ptr = mem + memtot; + memtot += size; + memcnt++; + return ptr; +} + +/* + * Free allocated memory block. + */ +void +kzipfree(void *ptr) +{ + memcnt--; + if (!memcnt) + memtot = 0; +} + +/* + * Write a string to the console. + */ +void +putstr(const char *str) +{ + int c; + + while ((c = *str++)) { + if (kgz_con & KGZ_CRT) + crt_putchr(c); + if (kgz_con & KGZ_SIO) + sio_putchr(c); + } +} diff --git a/pool/shard002/C/0059845_S5-BASE.c b/pool/shard002/C/0059845_S5-BASE.c new file mode 100644 index 0000000000000000000000000000000000000000..bfe7b1d0fa2bae39948e9ab226f2cd716e281987 --- /dev/null +++ b/pool/shard002/C/0059845_S5-BASE.c @@ -0,0 +1,17 @@ +void main( void ) +{ +if (&s5-jop == 1) +{ + //create guy + &temp1hold = create_sprite(330, 290, 0, 0, 0); + sp_script(&temp1hold, "s5-guy"); + + //create mom + &temp2hold = create_sprite(115, 160, 0, 0, 0); + sp_script(&temp2hold, "s5-mom"); + } + + + +} + diff --git a/pool/shard002/C/0059848_lab2_sem.c b/pool/shard002/C/0059848_lab2_sem.c new file mode 100644 index 0000000000000000000000000000000000000000..a5303cb356b6014ab0c0b2f2f225455a51576513 --- /dev/null +++ b/pool/shard002/C/0059848_lab2_sem.c @@ -0,0 +1,84 @@ +/* **************** LPD:1.0 s_19/lab2_sem.c **************** */ +/* + * The code herein is: Copyright Jerry Cooperstein, 2009 + * + * This Copyright is retained for the purpose of protecting free + * redistribution of source. + * + * URL: http://www.coopj.com + * email: coop@coopj.com + * + * The primary maintainer for this code is Jerry Cooperstein + * The CONTRIBUTORS file (distributed with this + * file) lists those known to have contributed to the source. + * + * This code is distributed under Version 2 of the GNU General Public + * License, which you should have received with the source. + * + */ +/* + * POSIX Semaphores and Threads + * + * Modify the pthreads exercise (which may have already been enhanced + * to use mutexes), to use POSIX semaphores to protect the counter + * variable. + @*/ + +#include +#include +#include +#include +#include + +#include + +#define DEATH(mess) { perror(mess); exit(errno); } + +/* volatile char running = 1; */ +static char running = 1; /* note this can be static now! */ +static long long counter = 0; + +sem_t c_sem; + +/* This is the "computational" thread */ +void *process (void *arg) +{ + while (running) { + sem_wait (&c_sem); + counter++; + sem_post (&c_sem); + } + pthread_exit (NULL); +} + +/* This is the "user interface" thread */ +int main (int argc, char **argv) +{ + int i; + pthread_t threadId; + void *retval; + + /* Initialize a semaphore up */ + sem_init (&c_sem, 0, 1); + + /* Start up the processing thread. */ + if (pthread_create (&threadId, NULL, process, "0")) + DEATH ("pthread_create"); + + /* Every so often, look at the counter and print it out. */ + for (i = 0; i < 10; i++) { + sleep (1); + sem_wait (&c_sem); + printf ("%lld\n", counter); + sem_post (&c_sem); + } + + /* Tell the processing thread to quit. */ + running = 0; + + /* Wait for the processing thread to quit. */ + if (pthread_join (threadId, &retval)) + DEATH ("pthread_join"); + + return 0; +} diff --git a/pool/shard002/C/0059867_timer.c b/pool/shard002/C/0059867_timer.c new file mode 100644 index 0000000000000000000000000000000000000000..c11329ae706f7b02d19a2d69fde6a8a4655a0b96 --- /dev/null +++ b/pool/shard002/C/0059867_timer.c @@ -0,0 +1,155 @@ +/* + * arch/arm/mach-vt8500/timer.c + * + * Copyright (C) 2010 Alexey Charkov + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ + +#include +#include +#include +#include +#include +#include + +#include + +#include "devices.h" + +#define VT8500_TIMER_OFFSET 0x0100 +#define TIMER_MATCH_VAL 0x0000 +#define TIMER_COUNT_VAL 0x0010 +#define TIMER_STATUS_VAL 0x0014 +#define TIMER_IER_VAL 0x001c /* */ +#define TIMER_CTRL_VAL 0x0020 +#define TIMER_AS_VAL 0x0024 /* */ +#define TIMER_COUNT_R_ACTIVE (1 << 5) /* */ +#define TIMER_COUNT_W_ACTIVE (1 << 4) /* */ +#define TIMER_MATCH_W_ACTIVE (1 << 0) /* */ +#define VT8500_TIMER_HZ 3000000 + +#define msecs_to_loops(t) (loops_per_jiffy / 1000 * HZ * t) + +static void __iomem *regbase; + +static cycle_t vt8500_timer_read(struct clocksource *cs) +{ + int loops = msecs_to_loops(10); + writel(3, regbase + TIMER_CTRL_VAL); + while ((readl((regbase + TIMER_AS_VAL)) & TIMER_COUNT_R_ACTIVE) + && --loops) + cpu_relax(); + return readl(regbase + TIMER_COUNT_VAL); +} + +struct clocksource clocksource = { + .name = "vt8500_timer", + .rating = 200, + .read = vt8500_timer_read, + .mask = CLOCKSOURCE_MASK(32), + .flags = CLOCK_SOURCE_IS_CONTINUOUS, +}; + +static int vt8500_timer_set_next_event(unsigned long cycles, + struct clock_event_device *evt) +{ + int loops = msecs_to_loops(10); + cycle_t alarm = clocksource.read(&clocksource) + cycles; + while ((readl(regbase + TIMER_AS_VAL) & TIMER_MATCH_W_ACTIVE) + && --loops) + cpu_relax(); + writel((unsigned long)alarm, regbase + TIMER_MATCH_VAL); + + if ((signed)(alarm - clocksource.read(&clocksource)) <= 16) + return -ETIME; + + writel(1, regbase + TIMER_IER_VAL); + + return 0; +} + +static void vt8500_timer_set_mode(enum clock_event_mode mode, + struct clock_event_device *evt) +{ + switch (mode) { + case CLOCK_EVT_MODE_RESUME: + case CLOCK_EVT_MODE_PERIODIC: + break; + case CLOCK_EVT_MODE_ONESHOT: + case CLOCK_EVT_MODE_UNUSED: + case CLOCK_EVT_MODE_SHUTDOWN: + writel(readl(regbase + TIMER_CTRL_VAL) | 1, + regbase + TIMER_CTRL_VAL); + writel(0, regbase + TIMER_IER_VAL); + break; + } +} + +struct clock_event_device clockevent = { + .name = "vt8500_timer", + .features = CLOCK_EVT_FEAT_ONESHOT, + .rating = 200, + .set_next_event = vt8500_timer_set_next_event, + .set_mode = vt8500_timer_set_mode, +}; + +static irqreturn_t vt8500_timer_interrupt(int irq, void *dev_id) +{ + struct clock_event_device *evt = dev_id; + writel(0xf, regbase + TIMER_STATUS_VAL); + evt->event_handler(evt); + + return IRQ_HANDLED; +} + +struct irqaction irq = { + .name = "vt8500_timer", + .flags = IRQF_DISABLED | IRQF_TIMER | IRQF_IRQPOLL, + .handler = vt8500_timer_interrupt, + .dev_id = &clockevent, +}; + +static void __init vt8500_timer_init(void) +{ + regbase = ioremap(wmt_pmc_base + VT8500_TIMER_OFFSET, 0x28); + if (!regbase) + printk(KERN_ERR "vt8500_timer_init: failed to map MMIO registers\n"); + + writel(1, regbase + TIMER_CTRL_VAL); + writel(0xf, regbase + TIMER_STATUS_VAL); + writel(~0, regbase + TIMER_MATCH_VAL); + + if (clocksource_register_hz(&clocksource, VT8500_TIMER_HZ)) + printk(KERN_ERR "vt8500_timer_init: clocksource_register failed for %s\n", + clocksource.name); + + clockevents_calc_mult_shift(&clockevent, VT8500_TIMER_HZ, 4); + + /* */ + clockevent.max_delta_ns = + clockevent_delta2ns(0xf0000000, &clockevent); + clockevent.min_delta_ns = clockevent_delta2ns(4, &clockevent); + clockevent.cpumask = cpumask_of(0); + + if (setup_irq(wmt_timer_irq, &irq)) + printk(KERN_ERR "vt8500_timer_init: setup_irq failed for %s\n", + clockevent.name); + clockevents_register_device(&clockevent); +} + +struct sys_timer vt8500_timer = { + .init = vt8500_timer_init +}; diff --git a/pool/shard002/C/0059880_check_pgsql_slave.c b/pool/shard002/C/0059880_check_pgsql_slave.c new file mode 100644 index 0000000000000000000000000000000000000000..7682a350fb675dc8daf8c6b50dfe0ca3e9355cba --- /dev/null +++ b/pool/shard002/C/0059880_check_pgsql_slave.c @@ -0,0 +1,162 @@ +/*** + * Monitoring Plugin - check_pgsql_slave.c + ** + * + * check_pgsql_slave - Check PostgreSQL r/o slave status and delay. + * + * Copyright (C) 2013 Marius Rieder + * + * 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. + * + * $Id$ + */ + +const char *progname = "check_pgsql_slave"; +const char *progdesc = "Check PostgreSQL r/o slave status and delay."; +const char *progvers = "0.1"; +const char *progcopy = "2013"; +const char *progauth = "Marius Rieder "; +const char *progusage = "[-H ] [-u ] [-P ] [-D ]"; + +/* MP Includes */ +#include "mp_common.h" +#include "pgsql_utils.h" +/* Default Includes */ +#include +#include +#include +#include +#include +#include + +/* Global Vars */ +thresholds *delay_thresholds = NULL; + +int main (int argc, char **argv) { + /* Local Vars */ + PGconn *conn; + PGresult *res; + char *val, *val2; + float delay = 0; + + /* Set signal handling and alarm */ + if (signal(SIGALRM, timeout_alarm_handler) == SIG_ERR) + critical("Setup SIGALRM trap failed!"); + + /* Process check arguments */ + if (process_arguments(argc, argv) != OK) + unknown("Parsing arguments failed!"); + + /* Start plugin timeout */ + alarm(mp_timeout); + + /* Connectiong to PostgreSQL server */ + conn = mp_pgsql_init(); + + /* Check Recovery state */ + res = mp_pgsql_exec(conn, "SELECT pg_is_in_recovery() AS recovery, NOW() - pg_last_xact_replay_timestamp() AS replication_delay;"); + if (PQresultStatus(res) != PGRES_TUPLES_OK) { + critical("Query 'SELECT pg_is_in_recovery() AS recovery, NOW() - pg_last_xact_replay_timestamp() AS replication_delay;' failed: %s", + PQerrorMessage(conn)); + } + + val = PQgetvalue(res, 0, 0); + if (val[0] == 'f') { + mp_pgsql_deinit(conn); + critical("PostgreSQL is not in recover mode."); + } + + /* Calculate delay */ + val = PQgetvalue(res, 0, 1); + + delay = strtol(val, &val2, 10) * 3600; + delay += strtol(++val2, NULL,10) * 60; + delay += strtof((val2+=3), NULL); + + val = mp_strdup(val); + + mp_pgsql_deinit(conn); + + mp_perfdata_float("delay", (float)delay, "s", delay_thresholds); + + switch(get_status(delay, delay_thresholds)) { + case STATE_OK: + free_threshold(delay_thresholds); + ok("PostgreSQL Slave Delay: %s", val); + break; + case STATE_WARNING: + free_threshold(delay_thresholds); + warning("PostgreSQL Slave Delay: %s", val); + break; + case STATE_CRITICAL: + free_threshold(delay_thresholds); + critical("PostgreSQL Slave Delay: %s", val); + break; + } + free_threshold(delay_thresholds); + + critical("You should never reach this point."); +} + +int process_arguments (int argc, char **argv) { + int c; + int option = 0; + + static struct option longopts[] = { + MP_LONGOPTS_DEFAULT, + MP_LONGOPTS_HOST, + PGSQL_LONGOPTS, + MP_LONGOPTS_END + }; + + /* Set default */ + mp_threshold_set_warning_time(&delay_thresholds, "300s"); + mp_threshold_set_critical_time(&delay_thresholds, "3600s"); + + while (1) { + c = mp_getopt(&argc, &argv, MP_OPTSTR_DEFAULT"H:w:c:"PGSQL_OPTSTR, longopts, &option); + + getopt_wc_time(c, optarg, &delay_thresholds); + + if (c == -1 || c == EOF) + break; + + getopt_pgsql(c); + + } + + return(OK); +} + +void print_help (void) { + print_revision(); + print_revision_pgsql(); + print_copyright(); + + printf("\n"); + + printf("Check description: %s", progdesc); + + printf("\n\n"); + + print_usage(); + + print_help_default(); + print_help_pgsql(); + print_help_warn_time("300 sec"); + print_help_crit_time("3600 sec"); +} + +/* vim: set ts=4 sw=4 et syn=c : */ diff --git a/pool/shard002/C/0059896_stun.c b/pool/shard002/C/0059896_stun.c new file mode 100644 index 0000000000000000000000000000000000000000..06f97f06135e0f4842febe3ad1bdfe935767aab0 --- /dev/null +++ b/pool/shard002/C/0059896_stun.c @@ -0,0 +1,236 @@ +/* + * transsip - the telephony network + * By Daniel Borkmann + * Copyright 2011 Daniel Borkmann , + * Swiss federal institute of technology (ETH Zurich) + * Subject to the GPL, version 2. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "die.h" +#include "xmalloc.h" +#include "stun.h" +#include "timespec.h" + +/* Discovery type result */ +#define RESULT_NONE 0 +#define RESULT_OPEN_INTERNET 1 +#define RESULT_FIREWALL_BLOCKS_UDP 2 +#define RESULT_SYMMETRIC_UDP_FIREWALL 3 +#define RESULT_FULL_CONE_NAT 4 +#define RESULT_SYMMETRIC_NAT 5 +#define RESULT_RESTRICTED_CONE_NAT 6 +#define RESULT_PORT_RESTR_CONE_NAT 7 + +/* Message types */ +#define BINDING_REQUEST 0x0001 +#define BINDING_RESPONSE 0x0101 +#define BINDING_ERROR_RESPONSE 0x0111 +#define SHARED_SECRET_REQUEST 0x0002 +#define SHARED_SECRET_RESPONSE 0x0102 +#define SHARED_SECRET_ERROR_RESPONSE 0x0112 + +/* Attribute types */ +#define MAPPED_ADDRESS 0x0001 +#define RESPONSE_ADDRESS 0x0002 +#define CHANGE_REQUEST 0x0003 +#define SOURCE_ADDRESS 0x0004 +#define CHANGED_ADDRESS 0x0005 +#define USERNAME 0x0006 +#define PASSWORD 0x0007 +#define MESSAGE_INTEGRITY 0x0008 +#define ERROR_CODE 0x0009 +#define UNKNOWN_ATTRIBUTES 0x000a +#define REFLECTED_FROM 0x000b + +/* Error response codes */ +#define ERROR_BAD_REQUEST 400 +#define ERROR_UNAUTHORIZED 401 +#define ERROR_UNKNOWN_ATTRIBUTE 420 +#define ERROR_STALE_CREDENTIALS 430 +#define ERROR_INTEGRITY_CHECK_FAIL 431 +#define ERROR_MISSING_USERNAME 432 +#define ERROR_USE_TLS 433 +#define ERROR_SERVER_ERROR 500 +#define ERROR_GLOBAL_FAILURE 600 + +#define TIMEOUT 1000 +#define REQUEST_LEN 20 + +#define ID_COOKIE_FIELD htonl(((int) 'a' << 24) + \ + ((int) 'c' << 16) + \ + ((int) 'd' << 8) + \ + (int) 'c') + +struct stun_header { + uint16_t type; + /* + * Message length is the count, in bytes, of the size of the + * message, not including the 20 byte header. (RFC-3489) + */ + uint16_t len; + /* + * transid also serves as salt to randomize the request and the + * response. All responses carry the same identifier as + * the request they correspond to. + */ + /* For the new RFC this would be 0x2112A442 in network Byte order. */ + uint32_t magic_cookie; + uint32_t transid[3]; +}; + +struct stun_attrib { + uint16_t type; + uint16_t len; + uint8_t *value; +}; + +struct stun_mapped_addr { + uint8_t none; + uint8_t family; + uint16_t port; + uint32_t ip; +}; + +static int stun_test(const char *server_ip, uint16_t server_port, + uint16_t tun_port) +{ + int ret, sock, set = 1; + uint8_t pkt[256]; + uint8_t rpkt[256]; + size_t len, off, max; + struct in_addr in; + struct timeval timeout; + struct stun_header *hdr, *rhdr; + struct stun_attrib *attr; + struct stun_mapped_addr *addr; + struct sockaddr_in saddr, daddr; + fd_set fdset; + + if (!server_ip) + return -EINVAL; + + sock = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP); + if (sock < 0) + panic("Cannot obtain socket!\n"); + + ret = setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &set, sizeof(set)); + if (ret) + panic("Cannot set socket option!\n"); + + saddr.sin_family = PF_INET; + saddr.sin_port = htons(tun_port); + saddr.sin_addr.s_addr = INADDR_ANY; + + ret = bind(sock, (struct sockaddr *) &saddr, sizeof(saddr)); + if (ret) + panic("Cannot bind udp socket!\n"); + + len = REQUEST_LEN; + hdr = (struct stun_header *) pkt; + hdr->type = htons(BINDING_REQUEST); + hdr->len = 0; + hdr->magic_cookie = ID_COOKIE_FIELD; + hdr->transid[0] = htonl(rand()); + hdr->transid[1] = htonl(rand()); + hdr->transid[2] = htonl(rand()); + + daddr.sin_family = PF_INET; + daddr.sin_port = htons(server_port); + daddr.sin_addr.s_addr = inet_addr(server_ip); + + ret = sendto(sock, pkt, len, 0, (struct sockaddr *) &daddr, + sizeof(daddr)); + if (ret != len) { + whine("Error sending request (%s)!\n", strerror(errno)); + return -EIO; + } + + set_timeout(&timeout, TIMEOUT); + + FD_ZERO(&fdset); + FD_SET(sock, &fdset); + + ret = select(sock + 1, &fdset, NULL, NULL, &timeout); + if (ret <= 0) { + whine("STUN server timeout!\n"); + return -EIO; + } + + memset(rpkt, 0, sizeof(rpkt)); + len = read(sock, rpkt, sizeof(rpkt)); + + close(sock); + + if (len < REQUEST_LEN) { + whine("Bad STUN response (%s)!\n", strerror(errno)); + return -EIO; + } + + rhdr = (struct stun_header *) rpkt; + if (ntohs(rhdr->type) != BINDING_RESPONSE) { + whine("Wrong STUN response type!\n"); + return -EIO; + } + + if (rhdr->len == 0) { + whine("No attributes in STUN response!\n"); + return -EIO; + } + + if (rhdr->magic_cookie != hdr->magic_cookie || + rhdr->transid[0] != hdr->transid[0] || + rhdr->transid[1] != hdr->transid[1] || + rhdr->transid[2] != hdr->transid[2]) { + whine("Got wrong STUN transaction id!\n"); + return -EIO; + } + + off = REQUEST_LEN; + max = ntohs(rhdr->len) + REQUEST_LEN; + + while (off + 8 < max) { + attr = (struct stun_attrib *) (rpkt + off); + if (ntohs(attr->type) != MAPPED_ADDRESS) + goto next; + + addr = (struct stun_mapped_addr *) (rpkt + off + 4); + if (addr->family != 0x1) + break; + + in.s_addr = addr->ip; + info("Public mapping %s:%u!\n", inet_ntoa(in), ntohs(addr->port)); + break; +next: + off += 4; + off += ntohs(attr->len); + } + + return 0; +} + +void print_stun_probe(char *server, uint16_t sport, uint16_t tunport) +{ + char *address; + struct hostent *hp; + + printf("STUN on %s:%u\n", server, sport); + srand(time(NULL)); + hp = gethostbyname(server); + if (!hp) + return; + address = inet_ntoa(*(struct in_addr *) hp->h_addr_list[0]); + stun_test(address, sport, tunport); +} diff --git a/pool/shard002/C/0059898_capfs_symlink.c b/pool/shard002/C/0059898_capfs_symlink.c new file mode 100644 index 0000000000000000000000000000000000000000..ed146f6383904cacd2f0de54da17488400e78a0e --- /dev/null +++ b/pool/shard002/C/0059898_capfs_symlink.c @@ -0,0 +1,219 @@ +/* + * (C) 2005 Penn State University + * (C) 1995-2001 Clemson University and Argonne National Laboratory. + * + * See COPYING in top-level directory. + */ + + +/* This file contains CAPFS library call for unlink. */ +/* It will determine if file is UNIX or CAPFS and then */ +/* make the proper request. */ + +#include +#include +#include +#include +#include + +/* This file contains CAPFS library call for symlink and hard links. */ +/* It will determine if file is UNIX or CAPFS and then */ +/* make the proper request. */ + + +extern int capfs_checks_disabled; + +int capfs_symlink(const char* target_name, const char *link_name) +{ + int i; + mreq req; + mack ack; + struct sockaddr *saddr; + char *fn; + int64_t fs_ino; + char bothname[MAXPATHLEN + MAXPATHLEN + 2]; + int len = 0, bothlen = 0; + struct capfs_options opt; + + opt.tcp = MGR_USE_TCP; + opt.use_hcache = 0; + + memset(&req, 0, sizeof(req)); + if (!target_name || !link_name) { + errno = EFAULT; + return(-1); + } + if (capfs_checks_disabled) return symlink(target_name, link_name); + /* Check to see if .capfsdir exists in directory of link_name */ + if ((i = capfs_detect(link_name, &fn, &saddr, &fs_ino, NULL, NOFOLLOW_LINK)) < 1) { + if (i < 0) { + PERROR(SUBSYS_LIB,"Error finding file"); + return(-1); + } + return symlink(target_name, link_name); + } + len = snprintf(bothname, MAXPATHLEN, "%s", fn); + if(len <= 0 || len >= MAXPATHLEN) { + errno = EINVAL; + PERROR(SUBSYS_LIB,"Could not append file names to string\n"); + return (-1); + } + bothlen += (len + 1); + bothlen += snprintf(bothname + len + 1, MAXPATHLEN, "%s", target_name); + /* Prepare request for file system */ + req.dsize = bothlen; + req.uid = getuid(); + req.gid = getgid(); + req.type = MGR_LINK; + req.req.link.soft = 1; + req.req.link.meta.fs_ino = fs_ino; + req.req.link.meta.u_stat.st_uid = req.uid; + req.req.link.meta.u_stat.st_gid = req.gid; + req.req.link.meta.u_stat.st_mode = S_IFLNK | S_IRWXU | S_IRWXG | S_IRWXO; + + /* Send request to mgr */ + if (send_mreq_saddr(&opt, saddr, &req, bothname, &ack, NULL) < 0) { + PERROR(SUBSYS_LIB,"capfs_symlink: send_mreq_saddr -"); + return(-1); + } + else if (ack.status) { + errno = ack.eno; + PERROR(SUBSYS_LIB,"capfs_symlink:"); + } + return ack.status; +} + +int capfs_link(const char* target_name, const char *link_name) +{ + int i; + mreq req; + mack ack; + struct sockaddr *saddr; + char *fn = NULL; + char bothname[MAXPATHLEN + MAXPATHLEN + 2]; + int len = 0, bothlen = 0; + int64_t oldfs_ino, newfs_ino; + struct capfs_options opt; + + opt.tcp = MGR_USE_TCP; + opt.use_hcache = 0; + + memset(&req, 0, sizeof(req)); + if (!target_name || !link_name) { + errno = EFAULT; + return(-1); + } + if (capfs_checks_disabled) return link(target_name, link_name); + /* Check to see if .capfsdir exists in directory of link_name and target_name */ + if ((i = capfs_detect(link_name, &fn, &saddr, &newfs_ino, NULL, NOFOLLOW_LINK)) < 1) { + if (i < 0) { + PERROR(SUBSYS_LIB,"Error finding file"); + return(-1); + } + return link(target_name, link_name); + } + len = snprintf(bothname, MAXPATHLEN, "%s", fn); + if(len <= 0 || len >= MAXPATHLEN) { + errno = EINVAL; + PERROR(SUBSYS_LIB,"Could not append file names to string\n"); + return (-1); + } + bothlen += (len + 1); + /* since link_name exists on a CAPFS volume, target_name should also be on a CAPFS volume */ + if ((i = capfs_detect(target_name, &fn, &saddr, &oldfs_ino, NULL, NOFOLLOW_LINK)) < 1) { + if (i < 0) { + PERROR(SUBSYS_LIB,"Error finding file"); + return(-1); + } + errno = EXDEV; /* cross file system */ + return (-1); + } + bothlen += snprintf(bothname + len + 1, MAXPATHLEN, "%s", fn); + if(oldfs_ino != newfs_ino) { + errno = EXDEV; /* cross file system */ + return (-1); + } + /* Prepare request for file system */ + req.dsize = bothlen; + req.uid = getuid(); + req.gid = getgid(); + req.type = MGR_LINK; + req.req.link.soft = 0; + req.req.link.meta.fs_ino = newfs_ino; + req.req.link.meta.u_stat.st_uid = req.uid; + req.req.link.meta.u_stat.st_gid = req.gid; + req.req.link.meta.u_stat.st_mode = S_IFLNK | S_IRWXU | S_IRWXG | S_IRWXO; + + /* Send request to mgr */ + if (send_mreq_saddr(&opt, saddr, &req, bothname, &ack, NULL) < 0) { + PERROR(SUBSYS_LIB,"capfs_link: send_mreq_saddr -"); + return(-1); + } + else if (ack.status) { + errno = ack.eno; + PERROR(SUBSYS_LIB,"capfs_link:"); + } + return ack.status; +} + +int capfs_readlink(const char *path, char *buf, size_t bufsiz) +{ + int i; + mreq req; + mack ack; + struct sockaddr *saddr; + char *fn = NULL; + int64_t fs_ino; + struct ackdata_c ackdata; + struct capfs_options opt; + + opt.tcp = MGR_USE_TCP; + opt.use_hcache = 0; + + memset(&req, 0, sizeof(req)); + if(!path || !buf) { + errno = EFAULT; + return -1; + } + if(bufsiz <= 0) { + errno = EINVAL; + return -1; + } + if (capfs_checks_disabled) return readlink(path, buf, bufsiz); + /* Check to see if .capfsdir exists in directory of link_name and target_name */ + if ((i = capfs_detect(path, &fn, &saddr, &fs_ino, NULL, NOFOLLOW_LINK)) < 1) { + if (i < 0) { + PERROR(SUBSYS_LIB,"Error finding file"); + return(-1); + } + return readlink(path, buf, bufsiz); + } + /* Prepare request for file system */ + req.dsize = strlen(fn); + req.uid = getuid(); + req.gid = getgid(); + req.type = MGR_READLINK; + ackdata.type = MGR_READLINK; + ackdata.u.readlink.link_len = bufsiz; + ackdata.u.readlink.link_name = buf; + /* Send request to mgr */ + if (send_mreq_saddr(&opt, saddr, &req, fn, &ack, &ackdata) < 0) { + PERROR(SUBSYS_LIB,"capfs_readlink: send_mreq_saddr -"); + return(-1); + } + if (ack.status) /* error */ { + errno = ack.eno; + return(-1); + } + return ack.dsize; +} + +/* + * Local variables: + * c-indent-level: 3 + * c-basic-offset: 3 + * tab-width: 3 + * + * vim: ts=3 + * End: + */ diff --git a/pool/shard002/C/0059901_mtox.c b/pool/shard002/C/0059901_mtox.c new file mode 100644 index 0000000000000000000000000000000000000000..b35760f063ca1624213d74ab43c404e71894b623 --- /dev/null +++ b/pool/shard002/C/0059901_mtox.c @@ -0,0 +1,63 @@ +/* mtox -- Convert OPERAND to hexadecimal and return a malloc'ed string + with the result of the conversion. + +Copyright 1991, 1994, 2000, 2001, 2002 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 2.1 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; 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 +#include "mp.h" +#include "gmp.h" +#include "gmp-impl.h" +#include "longlong.h" + +char * +mtox (const MINT *x) +{ + mp_size_t xsize = x->_mp_size; + mp_ptr xp; + mp_size_t xsign; + unsigned char *str, *s; + size_t str_size, alloc_size, i; + + xsign = xsize; + if (xsize < 0) + xsize = -xsize; + + /* digits, plus '\0', plus possible '-', for an exact size */ + xp = x->_mp_d; + MPN_SIZEINBASE_16 (alloc_size, xp, xsize); + alloc_size += 1 + (xsign < 0); + + str = (unsigned char *) (*__gmp_allocate_func) (alloc_size); + s = str; + + if (xsign < 0) + *s++ = '-'; + + str_size = mpn_get_str (s, 16, xp, xsize); + ASSERT (str_size <= alloc_size - (xsign < 0)); + ASSERT (str_size == 1 || *s != 0); + + for (i = 0; i < str_size; i++) + s[i] = "0123456789abcdef"[s[i]]; + s[str_size] = 0; + + ASSERT (strlen (str) + 1 == alloc_size); + return (char *) str; +} diff --git a/pool/shard002/C/0059910_pthread_copy.c b/pool/shard002/C/0059910_pthread_copy.c new file mode 100644 index 0000000000000000000000000000000000000000..105bef4df54025f377fe51c21958e5d4f0ef7c69 --- /dev/null +++ b/pool/shard002/C/0059910_pthread_copy.c @@ -0,0 +1,45 @@ +#include +#include +#include + +const int NUM_THREADS = 3; + +void* threadFunc(void* arg); + +int main() +{ + printf("Starting: pthread_copy test\n"); + + pthread_t threads[NUM_THREADS]; + + // Create threads + for (int i = 0; i < NUM_THREADS; i++) + { + pthread_t thread; + int ret = pthread_create(&thread, NULL, threadFunc, (void*) i); + if (ret != 0) + { + fprintf(stderr, "Ending: pthread_copy test [FAILED] pthread_create\n"); + exit(EXIT_FAILURE); + } + + threads[i] = thread; + } + + // Join threads + for (int i = 0; i < NUM_THREADS; i++) + { + pthread_join(threads[i], NULL); + } + + printf("Ending: pthread_copy test [PASSED]\n"); + + return 0; +} + +void* threadFunc(void* arg) +{ + long int tid = (long int) arg; + printf("Spawned thread(%li)\n", tid); + return NULL; +} diff --git a/pool/shard002/C/0059926_server.c b/pool/shard002/C/0059926_server.c new file mode 100644 index 0000000000000000000000000000000000000000..f211736f9410cad50d2094f4f3f672a7f44afa32 --- /dev/null +++ b/pool/shard002/C/0059926_server.c @@ -0,0 +1,174 @@ +/* server.c */ +#include "openssl/ssl.h" +#include "../test.h" + + +#ifdef CYASSL_CALLBACKS + int srvHandShakeCB(HandShakeInfo*); + int srvTimeoutCB(TimeoutInfo*); + Timeval srvTo; +#endif + +#if defined(NON_BLOCKING) || defined(CYASSL_CALLBACKS) + void NonBlockingSSL_Accept(SSL* ssl) + { + #ifndef CYASSL_CALLBACKS + int ret = SSL_accept(ssl); + #else + int ret = CyaSSL_accept_ex(ssl, srvHandShakeCB, srvTimeoutCB, srvTo); + #endif + int error = SSL_get_error(ssl, 0); + while (ret != SSL_SUCCESS && (error == SSL_ERROR_WANT_READ || + error == SSL_ERROR_WANT_WRITE)) { + printf("... server would block\n"); + #ifdef _WIN32 + Sleep(1000); + #else + sleep(1); + #endif + #ifndef CYASSL_CALLBACKS + ret = SSL_accept(ssl); + #else + ret = CyaSSL_accept_ex(ssl, srvHandShakeCB, srvTimeoutCB,srvTo); + #endif + error = SSL_get_error(ssl, 0); + } + if (ret != SSL_SUCCESS) + err_sys("SSL_accept failed"); + } +#endif + + +THREAD_RETURN CYASSL_API server_test(void* args) +{ + SOCKET_T sockfd = 0; + int clientfd = 0; + + SSL_METHOD* method = 0; + SSL_CTX* ctx = 0; + SSL* ssl = 0; + + char msg[] = "I hear you fa shizzle!"; + char input[1024]; + int idx; + + ((func_args*)args)->return_code = -1; /* error state */ +#if defined(CYASSL_DTLS) + method = DTLSv1_server_method(); +#elif !defined(NO_TLS) + method = TLSv1_server_method(); +#else + method = SSLv3_server_method(); +#endif + ctx = SSL_CTX_new(method); + +#ifndef NO_PSK + SSL_CTX_set_psk_server_callback(ctx, my_psk_server_cb); + SSL_CTX_use_psk_identity_hint(ctx, "cyassl server"); +#endif + +#ifdef OPENSSL_EXTRA + SSL_CTX_set_default_passwd_cb(ctx, PasswordCallBack); +#endif + + SSL_CTX_set_verify(ctx,SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT,0); + + if (SSL_CTX_load_verify_locations(ctx, caCert, 0) != SSL_SUCCESS) + err_sys("can't load ca file"); + + /* for client auth */ + if (SSL_CTX_load_verify_locations(ctx, cliCert, 0) != SSL_SUCCESS) + err_sys("can't load ca file"); + + if (SSL_CTX_use_certificate_file(ctx, svrCert, SSL_FILETYPE_PEM) + != SSL_SUCCESS) + err_sys("can't load server cert file"); + + if (SSL_CTX_use_PrivateKey_file(ctx, svrKey, SSL_FILETYPE_PEM) + != SSL_SUCCESS) + err_sys("can't load server key file"); + + ssl = SSL_new(ctx); + tcp_accept(&sockfd, &clientfd, (func_args*)args); +#ifndef CYASSL_DTLS + CloseSocket(sockfd); +#endif + + SSL_set_fd(ssl, clientfd); + +#ifdef NON_BLOCKING + tcp_set_nonblocking(&clientfd); + NonBlockingSSL_Accept(ssl); +#else + #ifndef CYASSL_CALLBACKS + if (SSL_accept(ssl) != SSL_SUCCESS) { + int err = SSL_get_error(ssl, 0); + char buffer[80]; + printf("error = %d, %s\n", err, ERR_error_string(err, buffer)); + err_sys("SSL_accept failed"); + } + #else + NonBlockingSSL_Accept(ssl); + #endif +#endif + showPeer(ssl); + + idx = SSL_read(ssl, input, sizeof(input)); + if (idx > 0) { + input[idx] = 0; + printf("Client message: %s\n", input); + } + + if (SSL_write(ssl, msg, sizeof(msg)) != sizeof(msg)) + err_sys("SSL_write failed"); + + SSL_shutdown(ssl); + SSL_free(ssl); + SSL_CTX_free(ctx); + + CloseSocket(clientfd); + ((func_args*)args)->return_code = 0; + return 0; +} + + +/* so overall tests can pull in test function */ +#ifndef NO_MAIN_DRIVER + + int main(int argc, char** argv) + { + func_args args; + + StartTCP(); + + args.argc = argc; + args.argv = argv; + + InitCyaSSL(); + server_test(&args); + FreeCyaSSL(); + + return args.return_code; + } + +#endif /* NO_MAIN_DRIVER */ + + +#ifdef CYASSL_CALLBACKS + + int srvHandShakeCB(HandShakeInfo* info) + { + + return 0; + } + + + int srvTimeoutCB(TimeoutInfo* info) + { + + return 0; + } + +#endif + + diff --git a/pool/shard002/C/0059929_FuncHostageRescue.c b/pool/shard002/C/0059929_FuncHostageRescue.c new file mode 100644 index 0000000000000000000000000000000000000000..501f9f53f39793dca7821d47fccee3593d5ac984 --- /dev/null +++ b/pool/shard002/C/0059929_FuncHostageRescue.c @@ -0,0 +1,108 @@ +/* +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. +*/ + +/* +================= +func_hostage_rescue_touch +================= +*/ +void func_hostage_rescue_touch( void ) { + if ( ( other.classname == "player" ) && ( other.team == TEAM_CT ) ) { + other.fInHostageZone = TRUE; // Note: this will be cleared every frame inside SV_RunClientCommand + } else if ( other.classname == "hostage_entity" ) { + if ( self.solid == SOLID_NOT ) { + return; + } + + Radio_BroadcastMessage( RADIO_RESCUED ); + iHostagesRescued++; + + Money_AddMoney( other.eUser, 1000 ); + Money_QueTeamReward( TEAM_CT, 800 ); + + if ( other.eTargetPoint != other.eUser ) { + remove( other.eTargetPoint ); + } + + other.eTargetPoint = other.eUser = world; + + entity eOld = self; + self = other; + Entities_Remove(); + self = eOld; + + if ( iHostagesRescued >= iHostagesMax ) { + // TODO: Broadcast_Print: All Hostages have been rescued! + Rules_RoundOver( TEAM_CT, 0, FALSE ); + } + } +} + +/* +================= +SPAWN: func_hostage_rescue + +Entry function for the rescue area-markings. +================= +*/ +void func_hostage_rescue( void ) { + self.angles = '0 0 0'; + self.movetype = MOVETYPE_NONE; + self.solid = SOLID_TRIGGER; + + if ( self.model ) { + setmodel( self, self.model ); + } else { + setsize( self, self.mins, self.maxs ); + } + + self.model = 0; + self.touch = func_hostage_rescue_touch; + + iRescueZones++; +} + +void info_hostage_rescue( void ) { + self.mins = '-128 -128 -36'; + self.maxs = '128 128 36'; + func_hostage_rescue(); +} + +/* +================= +Game_CreateRescueZones + +Called by StartFrame if we somehow got no rescue zones +================= +*/ +void Game_CreateRescueZones( void ) { + entity eFind = findchain( classname, "info_player_start" ); + + while ( eFind ) { + entity eRescueZone = spawn(); + setorigin( eRescueZone, eFind.origin ); + + entity eOld = self; + self = eRescueZone; + info_hostage_rescue(); + self = eOld; + eFind = eFind.chain; + } +} diff --git a/pool/shard002/C/0059934_gnc-currency-edit.c b/pool/shard002/C/0059934_gnc-currency-edit.c new file mode 100644 index 0000000000000000000000000000000000000000..369ac56bdea35509fa257034f198f891712c4600 --- /dev/null +++ b/pool/shard002/C/0059934_gnc-currency-edit.c @@ -0,0 +1,298 @@ +/* + * gnc-currency-edit.c -- Currency editor widget + * + * Copyright (C) 1997, 1998, 1999, 2000 Free Software Foundation + * All rights reserved. + * + * Gnucash 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. + * + * Gnucash 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, contact: + * + * Free Software Foundation Voice: +1-617-542-5942 + * 51 Franklin Street, Fifth Floor Fax: +1-617-542-2652 + * Boston, MA 02110-1301, USA gnu@gnu.org + * + */ + +/** @addtogroup GUI + @{ */ +/** @addtogroup GncCurrencyEdit + * @{ */ +/** @file gnc-currency-edit.c + * @brief Currency selection widget. + * @author Dave Peticolas + * @author David Hampton + * + * This widget is a GtkComboBox that is wrapped with support + * functions for building/selecting from a list of ISO4217 currency + * names. All data is maintained within the widget itself, which + * makes the name/item lookup functions somewhat complicated. The + * alternative coding would be to keep an auxiliary list of strings + * attacked to the widget for lookup purposes, but that would be 100% + * redundant information. + * + * This function currently builds a new GtkListStore for each widget + * created. It could be optimized to build a single list store and + * share across all extant version of the widget, or even build the + * list store once and maintain for the life of the application. + * + * When the GtkComboCellEntry widget supports completion, this Gnucash + * widget should be modified so that it is based upon that widget. + * That would give users the capability to select a currency by typing + * its ISO 4217 code (e.g. USD, GBP, etc). Moving to that widget + * today, however, would cause more problems that its worth. There is + * currently no way to get access to the embedded GtkEntry widget, and + * therefore no way to implement completion in gnucash or prevent the + * user from typing in random data. + */ + +#include "config.h" + +#include +#include +#include +#include + +#include "gnc-currency-edit.h" +#include "gnc-commodity.h" +#include "gnc-gtk-utils.h" +#include "gnc-ui-util.h" + +static void gnc_currency_edit_init (GNCCurrencyEdit *gce); +static void gnc_currency_edit_class_init (GNCCurrencyEditClass *class); + +static GtkComboBoxClass *parent_class; + +/** The instance private data for a content plugin. */ +typedef struct _GNCCurrencyEditPrivate +{ + gint dummy; +} GNCCurrencyEditPrivate; + +#define GET_PRIVATE(o) \ + (G_TYPE_INSTANCE_GET_PRIVATE ((o), GNC_TYPE_CURRENCY_EDIT, GNCCurrencyEditPrivate)) + +/** @name Basic Object Implementation */ +/** @{ */ + +/* Return the GType for the GNCCurrencyEdit currency selection widget. + */ +GType +gnc_currency_edit_get_type (void) +{ + static GType currency_edit_type = 0; + + if (currency_edit_type == 0) + { + static const GTypeInfo currency_edit_info = + { + sizeof (GNCCurrencyEditClass), + NULL, + NULL, + (GClassInitFunc) gnc_currency_edit_class_init, + NULL, + NULL, + sizeof (GNCCurrencyEdit), + 0, /* n_preallocs */ + (GInstanceInitFunc) gnc_currency_edit_init, + NULL + }; + + currency_edit_type = g_type_register_static (GTK_TYPE_COMBO_BOX_ENTRY, + "GNCCurrencyEdit", + ¤cy_edit_info, 0); + } + + return currency_edit_type; +} + + +/** Initialize the GncCurrencyEdit class object. + * + * @internal + * + * @param klass A pointer to the newly created class object. + */ +static void +gnc_currency_edit_class_init (GNCCurrencyEditClass *klass) +{ + parent_class = g_type_class_peek_parent (klass); + + g_type_class_add_private(klass, sizeof(GNCCurrencyEditPrivate)); +} + + +/** Initialize a GncCurrencyEdit object. This function is currently a + * noop. + * + * @internal + * + * @param gce A pointer to the newly created object. + */ +static void +gnc_currency_edit_init (GNCCurrencyEdit *gce) +{ +} + + +/** This auxiliary function adds a single currency name to the combo + * box. It is called as an iterator function when running a list of + * currencies. + * + * @internal + * + * @param commodity The currency to add to the selection widget. + * + * @param gce A pointer to the selection widget. + */ +static void +add_item(gnc_commodity *commodity, GNCCurrencyEdit *gce) +{ + const char *string; + + string = gnc_commodity_get_printname(commodity); + gtk_combo_box_append_text(GTK_COMBO_BOX(gce), string); +} + + +/** This auxiliary function adds all the currency names to a combo + * box. + * + * @internal + * + * @param gce A pointer to the widget that should be filled with + * currency names. + */ +static void +fill_currencies(GNCCurrencyEdit *gce) +{ + GList *currencies; + + currencies = gnc_commodity_table_get_commodities + (gnc_get_current_commodities (), GNC_COMMODITY_NS_CURRENCY); + g_list_foreach(currencies, (GFunc)add_item, gce); + g_list_free(currencies); +} + + +/* Create a new GNCCurrencyEdit widget which can be used to provide + * an easy way to enter ISO currency codes. + * + * @return A GNCCurrencyEdit widget. + */ +GtkWidget * +gnc_currency_edit_new (void) +{ + GNCCurrencyEdit *gce; + GtkListStore *store; + + store = gtk_list_store_new (1, G_TYPE_STRING); + gce = g_object_new (GNC_TYPE_CURRENCY_EDIT, + "model", store, + "text-column", 0, + NULL); + g_object_unref (store); + + /* Now the signals to make sure the user can't leave the + widget without a valid currency. */ + gnc_cbe_require_list_item(GTK_COMBO_BOX_ENTRY(gce)); + + /* Fill in all the data. */ + fill_currencies (gce); + gtk_tree_sortable_set_sort_column_id + (GTK_TREE_SORTABLE(store), 0, GTK_SORT_ASCENDING); + + return GTK_WIDGET (gce); +} + +/** @} */ + +/** @name Get/Set Functions */ +/** @{ */ + +/* Set the widget to display a certain currency name. + * + * @param gce The currency editor widget to set. + * + * @param currency The currency to set as the displayed/selected + * value of the widget. + */ +void +gnc_currency_edit_set_currency (GNCCurrencyEdit *gce, + const gnc_commodity *currency) +{ + const gchar *printname; + + g_return_if_fail(gce != NULL); + g_return_if_fail(GNC_IS_CURRENCY_EDIT(gce)); + g_return_if_fail(currency != NULL); + + printname = gnc_commodity_get_printname(currency); + gnc_cbe_set_by_string(GTK_COMBO_BOX_ENTRY(gce), printname); +} + + +/* Retrieve the displayed currency of the widget. + * + * @param gce The currency editor widget whose values should be retrieved. + * + * @return A pointer to the selected currency (a gnc_commodity + * structure). + */ +gnc_commodity * +gnc_currency_edit_get_currency (GNCCurrencyEdit *gce) +{ + gnc_commodity *commodity; + const char *fullname; + char *mnemonic, *name; + GtkTreeModel *model; + GtkTreeIter iter; + GValue value = { 0 }; + + g_return_val_if_fail(gce != NULL, NULL); + g_return_val_if_fail(GNC_IS_CURRENCY_EDIT(gce), NULL); + + if (gtk_combo_box_get_active_iter(GTK_COMBO_BOX(gce), &iter)) + { + model = gtk_combo_box_get_model(GTK_COMBO_BOX(gce)); + gtk_tree_model_get_value(model, &iter, 0, &value); + fullname = g_value_get_string(&value); + mnemonic = g_strdup(fullname); + g_value_unset(&value); + + name = strchr(mnemonic, ' '); + if (name != NULL) + *name = '\0'; + commodity = gnc_commodity_table_lookup (gnc_get_current_commodities (), + GNC_COMMODITY_NS_CURRENCY, + mnemonic); + g_free(mnemonic); + } + else + { + g_warning("Combo box returned 'inactive'. Using locale default currency."); + commodity = gnc_locale_default_currency(); + } + + + return commodity; +} + +/** @} */ +/** @} */ +/** @} */ + +/* + Local Variables: + c-basic-offset: 8 + End: +*/ diff --git a/pool/shard002/C/0059937_pool.c b/pool/shard002/C/0059937_pool.c new file mode 100644 index 0000000000000000000000000000000000000000..c0ed1caa386025b4ff39ccf9435dab30cc340e8f --- /dev/null +++ b/pool/shard002/C/0059937_pool.c @@ -0,0 +1,254 @@ +/** + * WinPR: Windows Portable Runtime + * Thread Pool API (Pool) + * + * Copyright 2012 Marc-Andre Moreau + * + * 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. + */ + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +#include +#include +#include + +#include "pool.h" + +#ifdef WINPR_THREAD_POOL + +#ifdef _WIN32 +static INIT_ONCE init_once_module = INIT_ONCE_STATIC_INIT; +static PTP_POOL(WINAPI* pCreateThreadpool)(PVOID reserved); +static VOID(WINAPI* pCloseThreadpool)(PTP_POOL ptpp); +static BOOL(WINAPI* pSetThreadpoolThreadMinimum)(PTP_POOL ptpp, DWORD cthrdMic); +static VOID(WINAPI* pSetThreadpoolThreadMaximum)(PTP_POOL ptpp, DWORD cthrdMost); + +static BOOL CALLBACK init_module(PINIT_ONCE once, PVOID param, PVOID* context) +{ + HMODULE kernel32 = LoadLibraryA("kernel32.dll"); + if (kernel32) + { + pCreateThreadpool = (void*)GetProcAddress(kernel32, "CreateThreadpool"); + pCloseThreadpool = (void*)GetProcAddress(kernel32, "CloseThreadpool"); + pSetThreadpoolThreadMinimum = (void*)GetProcAddress(kernel32, "SetThreadpoolThreadMinimum"); + pSetThreadpoolThreadMaximum = (void*)GetProcAddress(kernel32, "SetThreadpoolThreadMaximum"); + } + return TRUE; +} +#endif + +static TP_POOL DEFAULT_POOL = { + 0, /* DWORD Minimum */ + 500, /* DWORD Maximum */ + NULL, /* wArrayList* Threads */ + NULL, /* wQueue* PendingQueue */ + NULL, /* HANDLE TerminateEvent */ + NULL, /* wCountdownEvent* WorkComplete */ +}; + +static DWORD WINAPI thread_pool_work_func(LPVOID arg) +{ + DWORD status; + PTP_POOL pool; + PTP_WORK work; + HANDLE events[2]; + PTP_CALLBACK_INSTANCE callbackInstance; + + pool = (PTP_POOL)arg; + + events[0] = pool->TerminateEvent; + events[1] = Queue_Event(pool->PendingQueue); + + while (1) + { + status = WaitForMultipleObjects(2, events, FALSE, INFINITE); + + if (status == WAIT_OBJECT_0) + break; + + if (status != (WAIT_OBJECT_0 + 1)) + break; + + callbackInstance = (PTP_CALLBACK_INSTANCE)Queue_Dequeue(pool->PendingQueue); + + if (callbackInstance) + { + work = callbackInstance->Work; + work->WorkCallback(callbackInstance, work->CallbackParameter, work); + CountdownEvent_Signal(pool->WorkComplete, 1); + free(callbackInstance); + } + } + + ExitThread(0); + return 0; +} + +static void threads_close(void* thread) +{ + WaitForSingleObject(thread, INFINITE); + CloseHandle(thread); +} + +static BOOL InitializeThreadpool(PTP_POOL pool) +{ + BOOL rc = FALSE; + int index; + wObject* obj; + HANDLE thread; + + if (pool->Threads) + return TRUE; + + pool->Minimum = 0; + pool->Maximum = 500; + + if (!(pool->PendingQueue = Queue_New(TRUE, -1, -1))) + goto fail; + + if (!(pool->WorkComplete = CountdownEvent_New(0))) + goto fail; + + if (!(pool->TerminateEvent = CreateEvent(NULL, TRUE, FALSE, NULL))) + goto fail; + + if (!(pool->Threads = ArrayList_New(TRUE))) + goto fail; + + obj = ArrayList_Object(pool->Threads); + obj->fnObjectFree = threads_close; + + for (index = 0; index < 4; index++) + { + if (!(thread = CreateThread(NULL, 0, thread_pool_work_func, (void*)pool, 0, NULL))) + { + goto fail; + } + + if (!ArrayList_Append(pool->Threads, thread)) + { + CloseHandle(thread); + goto fail; + } + } + + rc = TRUE; + +fail: + return rc; +} + +PTP_POOL GetDefaultThreadpool(void) +{ + PTP_POOL pool = NULL; + + pool = &DEFAULT_POOL; + + if (!InitializeThreadpool(pool)) + return NULL; + + return pool; +} + +PTP_POOL winpr_CreateThreadpool(PVOID reserved) +{ + PTP_POOL pool = NULL; +#ifdef _WIN32 + InitOnceExecuteOnce(&init_once_module, init_module, NULL, NULL); + if (pCreateThreadpool) + return pCreateThreadpool(reserved); +#else + WINPR_UNUSED(reserved); +#endif + if (!(pool = (PTP_POOL)calloc(1, sizeof(TP_POOL)))) + return NULL; + + if (!InitializeThreadpool(pool)) + { + winpr_CloseThreadpool(pool); + return NULL; + } + + return pool; +} + +VOID winpr_CloseThreadpool(PTP_POOL ptpp) +{ +#ifdef _WIN32 + InitOnceExecuteOnce(&init_once_module, init_module, NULL, NULL); + if (pCloseThreadpool) + { + pCloseThreadpool(ptpp); + return; + } +#endif + SetEvent(ptpp->TerminateEvent); + + ArrayList_Free(ptpp->Threads); + Queue_Free(ptpp->PendingQueue); + CountdownEvent_Free(ptpp->WorkComplete); + CloseHandle(ptpp->TerminateEvent); + + { + TP_POOL empty = { 0 }; + *ptpp = empty; + } + + if (ptpp != &DEFAULT_POOL) + free(ptpp); +} + +BOOL winpr_SetThreadpoolThreadMinimum(PTP_POOL ptpp, DWORD cthrdMic) +{ + HANDLE thread; +#ifdef _WIN32 + InitOnceExecuteOnce(&init_once_module, init_module, NULL, NULL); + if (pSetThreadpoolThreadMinimum) + return pSetThreadpoolThreadMinimum(ptpp, cthrdMic); +#endif + ptpp->Minimum = cthrdMic; + + while (ArrayList_Count(ptpp->Threads) < (INT64)ptpp->Minimum) + { + if (!(thread = CreateThread(NULL, 0, thread_pool_work_func, (void*)ptpp, 0, NULL))) + { + return FALSE; + } + + if (!ArrayList_Append(ptpp->Threads, thread)) + { + CloseHandle(thread); + return FALSE; + } + } + + return TRUE; +} + +VOID winpr_SetThreadpoolThreadMaximum(PTP_POOL ptpp, DWORD cthrdMost) +{ +#ifdef _WIN32 + InitOnceExecuteOnce(&init_once_module, init_module, NULL, NULL); + if (pSetThreadpoolThreadMaximum) + { + pSetThreadpoolThreadMaximum(ptpp, cthrdMost); + return; + } +#endif + ptpp->Maximum = cthrdMost; +} + +#endif /* WINPR_THREAD_POOL defined */ diff --git a/pool/shard002/C/0059944_cancel5.c b/pool/shard002/C/0059944_cancel5.c new file mode 100644 index 0000000000000000000000000000000000000000..9bc770b7ebdad06a38a4c83e5043dc23e4ba9e1c --- /dev/null +++ b/pool/shard002/C/0059944_cancel5.c @@ -0,0 +1,200 @@ +/* + * File: cancel5.c + * + * + * -------------------------------------------------------------------------- + * + * Pthreads4w - POSIX Threads for Windows + * Copyright 1998 John E. Bossom + * Copyright 1999-2018, Pthreads4w contributors + * + * Homepage: https://sourceforge.net/projects/pthreads4w/ + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * + * https://sourceforge.net/p/pthreads4w/wiki/Contributors/ + * + * 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. + * + * -------------------------------------------------------------------------- + * + * Test Synopsis: Test calling pthread_cancel from the main thread + * without calling pthread_self() in main. + * + * Test Method (Validation or Falsification): + * - + * + * Requirements Tested: + * - + * + * Features Tested: + * - + * + * Cases Tested: + * - + * + * Description: + * - + * + * Environment: + * - + * + * Input: + * - None. + * + * Output: + * - File name, Line number, and failed expression on failure. + * - No output on success. + * + * Assumptions: + * - have working pthread_create, pthread_self, pthread_mutex_lock/unlock + * pthread_testcancel, pthread_cancel, pthread_join + * + * Pass Criteria: + * - Process returns zero exit status. + * + * Fail Criteria: + * - Process returns non-zero exit status. + */ + +#include "test.h" + +/* + * Create NUMTHREADS threads in addition to the Main thread. + */ +enum +{ + NUMTHREADS = 4 +}; + +typedef struct bag_t_ bag_t; +struct bag_t_ +{ + int threadnum; + int started; + /* Add more per-thread state variables here */ + int count; +}; + +static bag_t threadbag[NUMTHREADS + 1]; + +void * +mythread (void *arg) +{ + void* result = (void*)((int)(size_t)PTHREAD_CANCELED + 1); + bag_t *bag = (bag_t *) arg; + + assert (bag == &threadbag[bag->threadnum]); + assert (bag->started == 0); + bag->started = 1; + + /* Set to known state and type */ + + assert (pthread_setcancelstate (PTHREAD_CANCEL_ENABLE, NULL) == 0); + + assert (pthread_setcanceltype (PTHREAD_CANCEL_ASYNCHRONOUS, NULL) == 0); + + /* + * We wait up to 10 seconds, waking every 0.1 seconds, + * for a cancellation to be applied to us. + */ + for (bag->count = 0; bag->count < 100; bag->count++) + Sleep (100); + + return result; +} + +int +main () +{ + int failed = 0; + int i; + pthread_t t[NUMTHREADS + 1]; + + DWORD dwMode = SetErrorMode(SEM_NOGPFAULTERRORBOX); + SetErrorMode(dwMode | SEM_NOGPFAULTERRORBOX); + + for (i = 1; i <= NUMTHREADS; i++) + { + threadbag[i].started = 0; + threadbag[i].threadnum = i; + assert (pthread_create (&t[i], NULL, mythread, (void *) &threadbag[i]) + == 0); + } + + /* + * Code to control or manipulate child threads should probably go here. + */ + Sleep (500); + + for (i = 1; i <= NUMTHREADS; i++) + { + assert (pthread_cancel (t[i]) == 0); + } + + /* + * Give threads time to run. + */ + Sleep (NUMTHREADS * 100); + + /* + * Standard check that all threads started. + */ + for (i = 1; i <= NUMTHREADS; i++) + { + if (!threadbag[i].started) + { + failed |= !threadbag[i].started; + fprintf (stderr, "Thread %d: started %d\n", i, + threadbag[i].started); + } + } + + assert (!failed); + + /* + * Check any results here. Set "failed" and only print output on failure. + */ + failed = 0; + for (i = 1; i <= NUMTHREADS; i++) + { + int fail = 0; + void* result = (void*)((int)(size_t)PTHREAD_CANCELED + 1); + + /* + * The thread does not contain any cancellation points, so + * a return value of PTHREAD_CANCELED confirms that async + * cancellation succeeded. + */ + assert (pthread_join (t[i], &result) == 0); + + fail = (result != PTHREAD_CANCELED); + + if (fail) + { + fprintf (stderr, "Thread %d: started %d: count %d\n", + i, threadbag[i].started, threadbag[i].count); + } + failed = (failed || fail); + } + + assert (!failed); + + /* + * Success. + */ + return 0; +} diff --git a/pool/shard002/C/0059952_caps.c b/pool/shard002/C/0059952_caps.c new file mode 100644 index 0000000000000000000000000000000000000000..cecf672750bdaabbb9f7aa374daefece003e7171 --- /dev/null +++ b/pool/shard002/C/0059952_caps.c @@ -0,0 +1,270 @@ +/* + * Copyright (c) 2004-2008 Reyk Floeter + * Copyright (c) 2006-2008 Nick Kossifidis + * Copyright (c) 2007-2008 Jiri Slaby + * + * Permission to use, copy, modify, and distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF 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. + * + */ + +/**************\ +* Capabilities * +\**************/ + +#include "ath5k.h" +#include "reg.h" +#include "debug.h" +#include "base.h" + +/* + * Fill the capabilities struct + * TODO: Merge this with EEPROM code when we are done with it + */ +int ath5k_hw_set_capabilities(struct ath5k_hw *ah) +{ +<<<<<<< HEAD + struct ath5k_capabilities *caps = &ah->ah_capabilities; + u16 ee_header; + + /* Capabilities stored in the EEPROM */ + ee_header = caps->cap_eeprom.ee_header; +======= + u16 ee_header; + + ATH5K_TRACE(ah->ah_sc); + /* Capabilities stored in the EEPROM */ + ee_header = ah->ah_capabilities.cap_eeprom.ee_header; +>>>>>>> 296c66da8a02d52243f45b80521febece5ed498a + + if (ah->ah_version == AR5K_AR5210) { + /* + * Set radio capabilities + * (The AR5110 only supports the middle 5GHz band) + */ +<<<<<<< HEAD + caps->cap_range.range_5ghz_min = 5120; + caps->cap_range.range_5ghz_max = 5430; + caps->cap_range.range_2ghz_min = 0; + caps->cap_range.range_2ghz_max = 0; + + /* Set supported modes */ + __set_bit(AR5K_MODE_11A, caps->cap_mode); +======= + ah->ah_capabilities.cap_range.range_5ghz_min = 5120; + ah->ah_capabilities.cap_range.range_5ghz_max = 5430; + ah->ah_capabilities.cap_range.range_2ghz_min = 0; + ah->ah_capabilities.cap_range.range_2ghz_max = 0; + + /* Set supported modes */ + __set_bit(AR5K_MODE_11A, ah->ah_capabilities.cap_mode); + __set_bit(AR5K_MODE_11A_TURBO, ah->ah_capabilities.cap_mode); +>>>>>>> 296c66da8a02d52243f45b80521febece5ed498a + } else { + /* + * XXX The tranceiver supports frequencies from 4920 to 6100GHz + * XXX and from 2312 to 2732GHz. There are problems with the + * XXX current ieee80211 implementation because the IEEE + * XXX channel mapping does not support negative channel + * XXX numbers (2312MHz is channel -19). Of course, this +<<<<<<< HEAD + * XXX doesn't matter because these channels are out of the + * XXX legal range. +======= + * XXX doesn't matter because these channels are out of range + * XXX but some regulation domains like MKK (Japan) will + * XXX support frequencies somewhere around 4.8GHz. +>>>>>>> 296c66da8a02d52243f45b80521febece5ed498a + */ + + /* + * Set radio capabilities + */ + + if (AR5K_EEPROM_HDR_11A(ee_header)) { +<<<<<<< HEAD + if (ath_is_49ghz_allowed(caps->cap_eeprom.ee_regdomain)) + caps->cap_range.range_5ghz_min = 4920; + else + caps->cap_range.range_5ghz_min = 5005; + caps->cap_range.range_5ghz_max = 6100; + + /* Set supported modes */ + __set_bit(AR5K_MODE_11A, caps->cap_mode); +======= + /* 4920 */ + ah->ah_capabilities.cap_range.range_5ghz_min = 5005; + ah->ah_capabilities.cap_range.range_5ghz_max = 6100; + + /* Set supported modes */ + __set_bit(AR5K_MODE_11A, + ah->ah_capabilities.cap_mode); + __set_bit(AR5K_MODE_11A_TURBO, + ah->ah_capabilities.cap_mode); + if (ah->ah_version == AR5K_AR5212) + __set_bit(AR5K_MODE_11G_TURBO, + ah->ah_capabilities.cap_mode); +>>>>>>> 296c66da8a02d52243f45b80521febece5ed498a + } + + /* Enable 802.11b if a 2GHz capable radio (2111/5112) is + * connected */ + if (AR5K_EEPROM_HDR_11B(ee_header) || + (AR5K_EEPROM_HDR_11G(ee_header) && + ah->ah_version != AR5K_AR5211)) { + /* 2312 */ +<<<<<<< HEAD + caps->cap_range.range_2ghz_min = 2412; + caps->cap_range.range_2ghz_max = 2732; + + if (AR5K_EEPROM_HDR_11B(ee_header)) + __set_bit(AR5K_MODE_11B, caps->cap_mode); + + if (AR5K_EEPROM_HDR_11G(ee_header) && + ah->ah_version != AR5K_AR5211) + __set_bit(AR5K_MODE_11G, caps->cap_mode); + } + } + + if ((ah->ah_radio_5ghz_revision & 0xf0) == AR5K_SREV_RAD_2112) + __clear_bit(AR5K_MODE_11A, caps->cap_mode); + + /* Set number of supported TX queues */ + if (ah->ah_version == AR5K_AR5210) + caps->cap_queues.q_tx_num = AR5K_NUM_TX_QUEUES_NOQCU; + else + caps->cap_queues.q_tx_num = AR5K_NUM_TX_QUEUES; + + /* newer hardware has PHY error counters */ + if (ah->ah_mac_srev >= AR5K_SREV_AR5213A) + caps->cap_has_phyerr_counters = true; + else + caps->cap_has_phyerr_counters = false; +======= + ah->ah_capabilities.cap_range.range_2ghz_min = 2412; + ah->ah_capabilities.cap_range.range_2ghz_max = 2732; + + if (AR5K_EEPROM_HDR_11B(ee_header)) + __set_bit(AR5K_MODE_11B, + ah->ah_capabilities.cap_mode); + + if (AR5K_EEPROM_HDR_11G(ee_header) && + ah->ah_version != AR5K_AR5211) + __set_bit(AR5K_MODE_11G, + ah->ah_capabilities.cap_mode); + } + } + + /* Set number of supported TX queues */ + if (ah->ah_version == AR5K_AR5210) + ah->ah_capabilities.cap_queues.q_tx_num = + AR5K_NUM_TX_QUEUES_NOQCU; + else + ah->ah_capabilities.cap_queues.q_tx_num = AR5K_NUM_TX_QUEUES; + + /* newer hardware has PHY error counters */ + if (ah->ah_mac_srev >= AR5K_SREV_AR5213A) + ah->ah_capabilities.cap_has_phyerr_counters = true; + else + ah->ah_capabilities.cap_has_phyerr_counters = false; +>>>>>>> 296c66da8a02d52243f45b80521febece5ed498a + + return 0; +} + +/* Main function used by the driver part to check caps */ +int ath5k_hw_get_capability(struct ath5k_hw *ah, + enum ath5k_capability_type cap_type, + u32 capability, u32 *result) +{ +<<<<<<< HEAD +======= + ATH5K_TRACE(ah->ah_sc); + +>>>>>>> 296c66da8a02d52243f45b80521febece5ed498a + switch (cap_type) { + case AR5K_CAP_NUM_TXQUEUES: + if (result) { + if (ah->ah_version == AR5K_AR5210) + *result = AR5K_NUM_TX_QUEUES_NOQCU; + else + *result = AR5K_NUM_TX_QUEUES; + goto yes; + } + case AR5K_CAP_VEOL: + goto yes; + case AR5K_CAP_COMPRESSION: + if (ah->ah_version == AR5K_AR5212) + goto yes; + else + goto no; + case AR5K_CAP_BURST: + goto yes; + case AR5K_CAP_TPC: + goto yes; + case AR5K_CAP_BSSIDMASK: + if (ah->ah_version == AR5K_AR5212) + goto yes; + else + goto no; + case AR5K_CAP_XR: + if (ah->ah_version == AR5K_AR5212) + goto yes; + else + goto no; + default: + goto no; + } + +no: + return -EINVAL; +yes: + return 0; +} + +/* + * TODO: Following functions should be part of a new function + * set_capability + */ + +int ath5k_hw_enable_pspoll(struct ath5k_hw *ah, u8 *bssid, + u16 assoc_id) +{ +<<<<<<< HEAD +======= + ATH5K_TRACE(ah->ah_sc); + +>>>>>>> 296c66da8a02d52243f45b80521febece5ed498a + if (ah->ah_version == AR5K_AR5210) { + AR5K_REG_DISABLE_BITS(ah, AR5K_STA_ID1, + AR5K_STA_ID1_NO_PSPOLL | AR5K_STA_ID1_DEFAULT_ANTENNA); + return 0; + } + + return -EIO; +} + +int ath5k_hw_disable_pspoll(struct ath5k_hw *ah) +{ +<<<<<<< HEAD +======= + ATH5K_TRACE(ah->ah_sc); + +>>>>>>> 296c66da8a02d52243f45b80521febece5ed498a + if (ah->ah_version == AR5K_AR5210) { + AR5K_REG_ENABLE_BITS(ah, AR5K_STA_ID1, + AR5K_STA_ID1_NO_PSPOLL | AR5K_STA_ID1_DEFAULT_ANTENNA); + return 0; + } + + return -EIO; +} diff --git a/pool/shard002/C/0059953_polyun.c b/pool/shard002/C/0059953_polyun.c new file mode 100644 index 0000000000000000000000000000000000000000..1e6fcf42b7a582fad237d5dde19c1fc183d92737 --- /dev/null +++ b/pool/shard002/C/0059953_polyun.c @@ -0,0 +1,112 @@ +/* + Copyright (C) 2020 Daniel Schultz + + This file is part of FLINT. + + FLINT 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. See . +*/ + +#include "fq_zech_mpoly_factor.h" + + +void fq_zech_polyun_clear(fq_zech_polyun_t A, const fq_zech_ctx_t ctx) +{ + slong i; + for (i = 0; i < A->alloc; i++) + fq_zech_poly_clear(A->coeffs + i, ctx); + flint_free(A->coeffs); + flint_free(A->exps); +} + +void fq_zech_polyun_realloc(fq_zech_polyun_t A, slong len, const fq_zech_ctx_t ctx) +{ + slong i; + slong old_alloc = A->alloc; + slong new_alloc = FLINT_MAX(len, old_alloc + 1 + old_alloc/2); + + FLINT_ASSERT(A->alloc >= 0); + if (len <= A->alloc) + return; + + A->coeffs = FLINT_ARRAY_REALLOC(A->coeffs, new_alloc, fq_zech_poly_struct); + A->exps = FLINT_ARRAY_REALLOC(A->exps, new_alloc, ulong); + + for (i = old_alloc; i < new_alloc; i++) + fq_zech_poly_init(A->coeffs + i, ctx); + + A->alloc = new_alloc; +} + +void fq_zech_polyu2n_print_pretty( + const fq_zech_polyun_t A, + const char * var0, + const char * var1, + const char * varlast, + const fq_zech_ctx_t ctx) +{ + slong i; + int first = 1; + + for (i = 0; i < A->length; i++) + { + if (!first) + flint_printf(" + "); + first = 0; + flint_printf("("); + fq_zech_poly_print_pretty(A->coeffs + i, varlast, ctx); + flint_printf(")*%s^%wu*%s^%wu", + var0, extract_exp(A->exps[i], 1, 2), + var1, extract_exp(A->exps[i], 0, 2)); + } + + if (first) + flint_printf("0"); +} + +void fq_zech_polyu3n_print_pretty( + const fq_zech_polyun_t A, + const char * var0, + const char * var1, + const char * var2, + const char * varlast, + const fq_zech_ctx_t ctx) +{ + slong i; + int first = 1; + + for (i = 0; i < A->length; i++) + { + if (!first) + flint_printf(" + "); + first = 0; + flint_printf("("); + fq_zech_poly_print_pretty(A->coeffs + i, varlast, ctx); + flint_printf(")*%s^%wu*%s^%wu*%s^%wu", + var0, extract_exp(A->exps[i], 2, 3), + var1, extract_exp(A->exps[i], 1, 3), + var2, extract_exp(A->exps[i], 0, 3)); + } + + if (first) + flint_printf("0"); +} + +int fq_zech_polyun_is_canonical( + const fq_zech_polyun_t A, + const fq_zech_ctx_t ctx) +{ + slong i; + if (A->length < 0) + return 0; + for (i = 0; i < A->length; i++) + { + if (fq_zech_poly_is_zero(A->coeffs + i, ctx)) + return 0; + if (i > 0 && A->exps[i] >= A->exps[i - 1]) + return 0; + } + return 1; +} diff --git a/pool/shard002/C/0059957_config_test.c b/pool/shard002/C/0059957_config_test.c new file mode 100644 index 0000000000000000000000000000000000000000..dacf2d74e7daf05ce74b7e1ea86b7adb16b96b8b --- /dev/null +++ b/pool/shard002/C/0059957_config_test.c @@ -0,0 +1,71 @@ +/* + * config_test.c + * + * Created: Sa 31. Jan 2015 + * Author: Georg von Zengen + * + * Please start this test on a erased eeprom twice to verify whether the save and load function are working correctly + */ + +#include +#include + +#include "config.h" +#include "display.h" +#include "eeprom-config.h" +#include "buttons.h" + +void erase(void){ + uint16_t i = 0; + for(; i < sizeof(config_t); i++){ + *(((uint8_t*) &config) + i) = 0xff ; + } + uint16_t num = config_save(); + display_number(num); + _delay_ms(1000); +} + + + +config_t *conf; + +int main(void) +{ + clock_init(); + display_init(); + conf = config_load(); + buttons_init(0,0,0,&erase); + display_number(100); + uint8_t initialized = 0; + uint16_t i = 0; + for(; i < sizeof(config_t); i++){ + if ( (*(((uint8_t*) conf) + i) != 0xff) && (*(((uint8_t*) conf) + i) != 0)){ + initialized = 1; + break; + } + } + if(!initialized){ + display_number(1000); //to display ERR + conf->pid_d = PID_D; + conf->pid_i = PID_I; + conf->pid_p = PID_P; + conf->default_temp = 300; + _delay_ms(1000); + } + uint16_t num = config_save(); + display_number(num); + _delay_ms(200); + + + while(1) + { + display_number(conf->pid_p); + _delay_ms(300); + display_number(conf->pid_i); + _delay_ms(300); + display_number(conf->pid_d); + _delay_ms(300); + display_number(conf->default_temp); + _delay_ms(300); + } +} diff --git a/pool/shard002/C/0059971_unix_lat.c b/pool/shard002/C/0059971_unix_lat.c new file mode 100644 index 0000000000000000000000000000000000000000..312a313b152e7680a020ec9f58481b7c91db6f59 --- /dev/null +++ b/pool/shard002/C/0059971_unix_lat.c @@ -0,0 +1,141 @@ +/* + Measure latency of IPC using unix domain sockets + + + Copyright (c) 2016 Erik Rigtorp + + 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. +*/ + +#define __STDC_FORMAT_MACROS +#include +#include +#include +#include +#include +#include +#include +#include + +#if defined(_POSIX_TIMERS) && (_POSIX_TIMERS > 0) && \ + defined(_POSIX_MONOTONIC_CLOCK) +#define HAS_CLOCK_GETTIME_MONOTONIC +#endif + +int main(int argc, char *argv[]) { + int sv[2]; /* the pair of socket descriptors */ + int size; + char *buf; + int64_t count, i, delta; +#ifdef HAS_CLOCK_GETTIME_MONOTONIC + struct timespec start, stop; +#else + struct timeval start, stop; +#endif + + if (argc != 3) { + printf("usage: unix_lat \n"); + return 1; + } + + size = atoi(argv[1]); + count = atol(argv[2]); + + buf = malloc(size); + if (buf == NULL) { + perror("malloc"); + return 1; + } + + printf("message size: %i octets\n", size); + printf("roundtrip count: %" PRId64 "\n", count); + + if (socketpair(AF_UNIX, SOCK_STREAM, 0, sv) == -1) { + perror("socketpair"); + return 1; + } + + if (!fork()) { /* child */ + for (i = 0; i < count; i++) { + + if (read(sv[1], buf, size) != size) { + perror("read"); + return 1; + } + + if (write(sv[1], buf, size) != size) { + perror("write"); + return 1; + } + } + } else { /* parent */ + +#ifdef HAS_CLOCK_GETTIME_MONOTONIC + if (clock_gettime(CLOCK_MONOTONIC, &start) == -1) { + perror("clock_gettime"); + return 1; + } +#else + if (gettimeofday(&start, NULL) == -1) { + perror("gettimeofday"); + return 1; + } +#endif + + for (i = 0; i < count; i++) { + + if (write(sv[0], buf, size) != size) { + perror("write"); + return 1; + } + + if (read(sv[0], buf, size) != size) { + perror("read"); + return 1; + } + } + +#ifdef HAS_CLOCK_GETTIME_MONOTONIC + if (clock_gettime(CLOCK_MONOTONIC, &stop) == -1) { + perror("clock_gettime"); + return 1; + } + + delta = ((stop.tv_sec - start.tv_sec) * 1000000000 + + (stop.tv_nsec - start.tv_nsec)); + +#else + if (gettimeofday(&stop, NULL) == -1) { + perror("gettimeofday"); + return 1; + } + + delta = (stop.tv_sec - start.tv_sec) * 1000000000 + + (stop.tv_usec - start.tv_usec) * 1000; + +#endif + + printf("average latency: %" PRId64 " ns\n", delta / (count * 2)); + } + + return 0; +} diff --git a/pool/shard002/C/0059972_led.c b/pool/shard002/C/0059972_led.c new file mode 100644 index 0000000000000000000000000000000000000000..4aeff312a67665e217cff92a70abeb7fdadcc48f --- /dev/null +++ b/pool/shard002/C/0059972_led.c @@ -0,0 +1,151 @@ +/****************************************************************************** + * + * Copyright(c) 2009-2012 Realtek Corporation. + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of version 2 of the GNU General Public License as + * published by the Free Software Foundation. + * + * This program is distributed in the hope that it 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, USA + * + * The full GNU General Public License is included in this distribution in the + * file called LICENSE. + * + * Contact Information: + * wlanfae + * Realtek Corporation, No. 2, Innovation Road II, Hsinchu Science Park, + * Hsinchu 300, Taiwan. + * + * Larry Finger + * + *****************************************************************************/ + +#include "../wifi.h" +#include "../pci.h" +#include "reg.h" +#include "led.h" + +static void _rtl92se_init_led(struct ieee80211_hw *hw, + struct rtl_led *pled, enum rtl_led_pin ledpin) +{ + pled->hw = hw; + pled->ledpin = ledpin; + pled->ledon = false; +} + +void rtl92se_init_sw_leds(struct ieee80211_hw *hw) +{ + struct rtl_pci_priv *pcipriv = rtl_pcipriv(hw); + _rtl92se_init_led(hw, &(pcipriv->ledctl.sw_led0), LED_PIN_LED0); + _rtl92se_init_led(hw, &(pcipriv->ledctl.sw_led1), LED_PIN_LED1); +} + +void rtl92se_sw_led_on(struct ieee80211_hw *hw, struct rtl_led *pled) +{ + u8 ledcfg; + struct rtl_priv *rtlpriv = rtl_priv(hw); + + RT_TRACE(rtlpriv, COMP_LED, DBG_LOUD, "LedAddr:%X ledpin=%d\n", + LEDCFG, pled->ledpin); + + ledcfg = rtl_read_byte(rtlpriv, LEDCFG); + + switch (pled->ledpin) { + case LED_PIN_GPIO0: + break; + case LED_PIN_LED0: + rtl_write_byte(rtlpriv, LEDCFG, ledcfg & 0xf0); + break; + case LED_PIN_LED1: + rtl_write_byte(rtlpriv, LEDCFG, ledcfg & 0x0f); + break; + default: + RT_TRACE(rtlpriv, COMP_ERR, DBG_EMERG, + "switch case not processed\n"); + break; + } + pled->ledon = true; +} + +void rtl92se_sw_led_off(struct ieee80211_hw *hw, struct rtl_led *pled) +{ + struct rtl_priv *rtlpriv; + struct rtl_pci_priv *pcipriv = rtl_pcipriv(hw); + u8 ledcfg; + + rtlpriv = rtl_priv(hw); + if (!rtlpriv || rtlpriv->max_fw_size) + return; + RT_TRACE(rtlpriv, COMP_LED, DBG_LOUD, "LedAddr:%X ledpin=%d\n", + LEDCFG, pled->ledpin); + + ledcfg = rtl_read_byte(rtlpriv, LEDCFG); + + switch (pled->ledpin) { + case LED_PIN_GPIO0: + break; + case LED_PIN_LED0: + ledcfg &= 0xf0; + if (pcipriv->ledctl.led_opendrain) + rtl_write_byte(rtlpriv, LEDCFG, (ledcfg | BIT(1))); + else + rtl_write_byte(rtlpriv, LEDCFG, (ledcfg | BIT(3))); + break; + case LED_PIN_LED1: + ledcfg &= 0x0f; + rtl_write_byte(rtlpriv, LEDCFG, (ledcfg | BIT(3))); + break; + default: + RT_TRACE(rtlpriv, COMP_ERR, DBG_EMERG, + "switch case not processed\n"); + break; + } + pled->ledon = false; +} + +static void _rtl92se_sw_led_control(struct ieee80211_hw *hw, + enum led_ctl_mode ledaction) +{ + struct rtl_pci_priv *pcipriv = rtl_pcipriv(hw); + struct rtl_led *pLed0 = &(pcipriv->ledctl.sw_led0); + switch (ledaction) { + case LED_CTL_POWER_ON: + case LED_CTL_LINK: + case LED_CTL_NO_LINK: + rtl92se_sw_led_on(hw, pLed0); + break; + case LED_CTL_POWER_OFF: + rtl92se_sw_led_off(hw, pLed0); + break; + default: + break; + } +} + +void rtl92se_led_control(struct ieee80211_hw *hw, enum led_ctl_mode ledaction) +{ + struct rtl_priv *rtlpriv = rtl_priv(hw); + struct rtl_ps_ctl *ppsc = rtl_psc(rtl_priv(hw)); + + if ((ppsc->rfoff_reason > RF_CHANGE_BY_PS) && + (ledaction == LED_CTL_TX || + ledaction == LED_CTL_RX || + ledaction == LED_CTL_SITE_SURVEY || + ledaction == LED_CTL_LINK || + ledaction == LED_CTL_NO_LINK || + ledaction == LED_CTL_START_TO_LINK || + ledaction == LED_CTL_POWER_ON)) { + return; + } + RT_TRACE(rtlpriv, COMP_LED, DBG_LOUD, "ledaction %d\n", ledaction); + + _rtl92se_sw_led_control(hw, ledaction); +} + diff --git a/pool/shard002/C/0059975_cpu.c b/pool/shard002/C/0059975_cpu.c new file mode 100644 index 0000000000000000000000000000000000000000..924592717cfae2426f6c116d678de4849c579c61 --- /dev/null +++ b/pool/shard002/C/0059975_cpu.c @@ -0,0 +1,154 @@ +/* + * Copyright (C) ST-Ericsson SA 2010 + * + * Author: Rabin Vincent for ST-Ericsson + * Author: Lee Jones for ST-Ericsson + * License terms: GNU General Public License (GPL) version 2 + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +#include +#include +#include + +#include "clock.h" + +void __iomem *_PRCMU_BASE; + +/* + * FIXME: Should we set up the GPIO domain here? + * + * The problem is that we cannot put the interrupt resources into the platform + * device until the irqdomain has been added. Right now, we set the GIC interrupt + * domain from init_irq(), then load the gpio driver from + * core_initcall(nmk_gpio_init) and add the platform devices from + * arch_initcall(customize_machine). + * + * This feels fragile because it depends on the gpio device getting probed + * _before_ any device uses the gpio interrupts. +*/ +static const struct of_device_id ux500_dt_irq_match[] = { + { .compatible = "arm,cortex-a9-gic", .data = gic_of_init, }, + {}, +}; + +void __init ux500_init_irq(void) +{ + void __iomem *dist_base; + void __iomem *cpu_base; + + if (cpu_is_u8500_family()) { + dist_base = __io_address(U8500_GIC_DIST_BASE); + cpu_base = __io_address(U8500_GIC_CPU_BASE); + } else + ux500_unknown_soc(); + +#ifdef CONFIG_OF + if (of_have_populated_dt()) + of_irq_init(ux500_dt_irq_match); + else +#endif + gic_init(0, 29, dist_base, cpu_base); + + /* + * Init clocks here so that they are available for system timer + * initialization. + */ + if (cpu_is_u8500_family()) + db8500_prcmu_early_init(); +#ifndef CONFIG_COMMON_CLK + clk_init(); +#endif +} + +void __init ux500_init_late(void) +{ +#ifndef CONFIG_COMMON_CLK + clk_debugfs_init(); +#endif + clk_init_smp_twd_cpufreq(); +} + +static const char * __init ux500_get_machine(void) +{ + return kasprintf(GFP_KERNEL, "DB%4x", dbx500_partnumber()); +} + +static const char * __init ux500_get_family(void) +{ + return kasprintf(GFP_KERNEL, "ux500"); +} + +static const char * __init ux500_get_revision(void) +{ + unsigned int rev = dbx500_revision(); + + if (rev == 0x01) + return kasprintf(GFP_KERNEL, "%s", "ED"); + else if (rev >= 0xA0) + return kasprintf(GFP_KERNEL, "%d.%d", + (rev >> 4) - 0xA + 1, rev & 0xf); + + return kasprintf(GFP_KERNEL, "%s", "Unknown"); +} + +static ssize_t ux500_get_process(struct device *dev, + struct device_attribute *attr, + char *buf) +{ + if (dbx500_id.process == 0x00) + return sprintf(buf, "Standard\n"); + + return sprintf(buf, "%02xnm\n", dbx500_id.process); +} + +static void __init soc_info_populate(struct soc_device_attribute *soc_dev_attr, + const char *soc_id) +{ + soc_dev_attr->soc_id = soc_id; + soc_dev_attr->machine = ux500_get_machine(); + soc_dev_attr->family = ux500_get_family(); + soc_dev_attr->revision = ux500_get_revision(); +} + +struct device_attribute ux500_soc_attr = + __ATTR(process, S_IRUGO, ux500_get_process, NULL); + +struct device * __init ux500_soc_device_init(const char *soc_id) +{ + struct device *parent; + struct soc_device *soc_dev; + struct soc_device_attribute *soc_dev_attr; + + soc_dev_attr = kzalloc(sizeof(*soc_dev_attr), GFP_KERNEL); + if (!soc_dev_attr) + return ERR_PTR(-ENOMEM); + + soc_info_populate(soc_dev_attr, soc_id); + + soc_dev = soc_device_register(soc_dev_attr); + if (IS_ERR_OR_NULL(soc_dev)) { + kfree(soc_dev_attr); + return NULL; + } + + parent = soc_device_to_device(soc_dev); + if (!IS_ERR_OR_NULL(parent)) + device_create_file(parent, &ux500_soc_attr); + + return parent; +} diff --git a/pool/shard002/C/0059985_drstemplates.c b/pool/shard002/C/0059985_drstemplates.c new file mode 100644 index 0000000000000000000000000000000000000000..0797645d7d987af38fd9ed1e8df58566a4fae70f --- /dev/null +++ b/pool/shard002/C/0059985_drstemplates.c @@ -0,0 +1,157 @@ +/********************************************************** + * Version $Id: drstemplates.c 911 2011-02-14 16:38:15Z reklov_w $ + *********************************************************/ +#include +#include "grib2.h" +#include "drstemplates.h" + +g2int getdrsindex(g2int number) +/*!$$$ SUBPROGRAM DOCUMENTATION BLOCK +! . . . . +! SUBPROGRAM: getdrsindex +! PRGMMR: Gilbert ORG: W/NP11 DATE: 2001-06-28 +! +! ABSTRACT: This function returns the index of specified Data +! Representation Template 5.NN (NN=number) in array templates. +! +! PROGRAM HISTORY LOG: +! 2001-06-28 Gilbert +! +! USAGE: index=getdrsindex(number) +! INPUT ARGUMENT LIST: +! number - NN, indicating the number of the Data Representation +! Template 5.NN that is being requested. +! +! RETURNS: Index of DRT 5.NN in array templates, if template exists. +! = -1, otherwise. +! +! REMARKS: None +! +! ATTRIBUTES: +! LANGUAGE: C +! MACHINE: IBM SP +! +!$$$*/ +{ + g2int j,getdrsindex=-1; + + for (j=0;jtype=5; + new->num=templatesdrs[index].template_num; + new->maplen=templatesdrs[index].mapdrslen; + new->needext=templatesdrs[index].needext; + new->map=(g2int *)templatesdrs[index].mapdrs; + new->extlen=0; + new->ext=0; //NULL + return(new); + } + else { + printf("getdrstemplate: DRS Template 5.%d not defined.\n",(int)number); + return(0); //NULL + } + + return(0); //NULL +} + +template *extdrstemplate(g2int number,g2int *list) +/*!$$$ SUBPROGRAM DOCUMENTATION BLOCK +! . . . . +! SUBPROGRAM: extdrstemplate +! PRGMMR: Gilbert ORG: W/NP11 DATE: 2000-05-11 +! +! ABSTRACT: This subroutine generates the remaining octet map for a +! given Data Representation Template, if required. Some Templates can +! vary depending on data values given in an earlier part of the +! Template, and it is necessary to know some of the earlier entry +! values to generate the full octet map of the Template. +! +! PROGRAM HISTORY LOG: +! 2000-05-11 Gilbert +! +! USAGE: new=extdrstemplate(number,list); +! INPUT ARGUMENT LIST: +! number - NN, indicating the number of the Data Representation +! Template 5.NN that is being requested. +! list() - The list of values for each entry in the +! the Data Representation Template 5.NN. +! +! RETURN VALUE: +! - Pointer to the returned template struct. +! Returns NULL pointer, if template not found. +! +! ATTRIBUTES: +! LANGUAGE: C +! MACHINE: IBM SP +! +!$$$*/ +{ + template *new; + g2int index,i; + + index=getdrsindex(number); + if (index == -1) return(0); + + new=getdrstemplate(number); + + if ( ! new->needext ) return(new); + + if ( number == 1 ) { + new->extlen=list[10]+list[12]; + new->ext=(g2int *)malloc(sizeof(g2int)*new->extlen); + for (i=0;iextlen;i++) { + new->ext[i]=4; + } + } + return(new); + +} + diff --git a/pool/shard002/C/0059991_sys_parisc32.c b/pool/shard002/C/0059991_sys_parisc32.c new file mode 100644 index 0000000000000000000000000000000000000000..68ea75d12461177a4dd79c29f7b70c87c52f3dca --- /dev/null +++ b/pool/shard002/C/0059991_sys_parisc32.c @@ -0,0 +1,228 @@ +/* + * sys_parisc32.c: Conversion between 32bit and 64bit native syscalls. + * + * Copyright (C) 2000-2001 Hewlett Packard Company + * Copyright (C) 2000 John Marvin + * Copyright (C) 2001 Matthew Wilcox + * + * These routines maintain argument size conversion between 32bit and 64bit + * environment. Based heavily on sys_ia32.c and sys_sparc32.c. + */ + +#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 +#include +#include + +#include +#include +#include + +#include "sys32.h" + +#undef DEBUG + +#ifdef DEBUG +#define DBG(x) printk x +#else +#define DBG(x) +#endif + +/* + * sys32_execve() executes a new program. + */ + +asmlinkage int sys32_execve(struct pt_regs *regs) +{ + int error; + struct filename *filename; + + DBG(("sys32_execve(%p) r26 = 0x%lx\n", regs, regs->gr[26])); + filename = getname((const char __user *) regs->gr[26]); + error = PTR_ERR(filename); + if (IS_ERR(filename)) + goto out; + error = compat_do_execve(filename->name, compat_ptr(regs->gr[25]), + compat_ptr(regs->gr[24]), regs); + putname(filename); +out: + + return error; +} + +asmlinkage long sys32_unimplemented(int r26, int r25, int r24, int r23, + int r22, int r21, int r20) +{ + printk(KERN_ERR "%s(%d): Unimplemented 32 on 64 syscall #%d!\n", + current->comm, current->pid, r20); + return -ENOSYS; +} + +asmlinkage long sys32_sched_rr_get_interval(pid_t pid, + struct compat_timespec __user *interval) +{ + struct timespec t; + int ret; + + KERNEL_SYSCALL(ret, sys_sched_rr_get_interval, pid, (struct timespec __user *)&t); + if (put_compat_timespec(&t, interval)) + return -EFAULT; + return ret; +} + +struct msgbuf32 { + int mtype; + char mtext[1]; +}; + +asmlinkage long sys32_msgsnd(int msqid, + struct msgbuf32 __user *umsgp32, + size_t msgsz, int msgflg) +{ + struct msgbuf *mb; + struct msgbuf32 mb32; + int err; + + if ((mb = kmalloc(msgsz + sizeof *mb + 4, GFP_KERNEL)) == NULL) + return -ENOMEM; + + err = get_user(mb32.mtype, &umsgp32->mtype); + mb->mtype = mb32.mtype; + err |= copy_from_user(mb->mtext, &umsgp32->mtext, msgsz); + + if (err) + err = -EFAULT; + else + KERNEL_SYSCALL(err, sys_msgsnd, msqid, (struct msgbuf __user *)mb, msgsz, msgflg); + + kfree(mb); + return err; +} + +asmlinkage long sys32_msgrcv(int msqid, + struct msgbuf32 __user *umsgp32, + size_t msgsz, long msgtyp, int msgflg) +{ + struct msgbuf *mb; + struct msgbuf32 mb32; + int err, len; + + if ((mb = kmalloc(msgsz + sizeof *mb + 4, GFP_KERNEL)) == NULL) + return -ENOMEM; + + KERNEL_SYSCALL(err, sys_msgrcv, msqid, (struct msgbuf __user *)mb, msgsz, msgtyp, msgflg); + + if (err >= 0) { + len = err; + mb32.mtype = mb->mtype; + err = put_user(mb32.mtype, &umsgp32->mtype); + err |= copy_to_user(&umsgp32->mtext, mb->mtext, len); + if (err) + err = -EFAULT; + else + err = len; + } + + kfree(mb); + return err; +} + +asmlinkage int sys32_sendfile(int out_fd, int in_fd, compat_off_t __user *offset, s32 count) +{ + mm_segment_t old_fs = get_fs(); + int ret; + off_t of; + + if (offset && get_user(of, offset)) + return -EFAULT; + + set_fs(KERNEL_DS); + ret = sys_sendfile(out_fd, in_fd, offset ? (off_t __user *)&of : NULL, count); + set_fs(old_fs); + + if (offset && put_user(of, offset)) + return -EFAULT; + + return ret; +} + +asmlinkage int sys32_sendfile64(int out_fd, int in_fd, compat_loff_t __user *offset, s32 count) +{ + mm_segment_t old_fs = get_fs(); + int ret; + loff_t lof; + + if (offset && get_user(lof, offset)) + return -EFAULT; + + set_fs(KERNEL_DS); + ret = sys_sendfile64(out_fd, in_fd, offset ? (loff_t __user *)&lof : NULL, count); + set_fs(old_fs); + + if (offset && put_user(lof, offset)) + return -EFAULT; + + return ret; +} + +asmlinkage long sys32_semctl(int semid, int semnum, int cmd, union semun arg) +{ + union semun u; + + if (cmd == SETVAL) { + /* Ugh. arg is a union of int,ptr,ptr,ptr, so is 8 bytes. + * The int should be in the first 4, but our argument + * frobbing has left it in the last 4. + */ + u.val = *((int *)&arg + 1); + return sys_semctl (semid, semnum, cmd, u); + } + return sys_semctl (semid, semnum, cmd, arg); +} + +long sys32_lookup_dcookie(u32 cookie_high, u32 cookie_low, char __user *buf, + size_t len) +{ + return sys_lookup_dcookie((u64)cookie_high << 32 | cookie_low, + buf, len); +} + +asmlinkage long compat_sys_fallocate(int fd, int mode, u32 offhi, u32 offlo, + u32 lenhi, u32 lenlo) +{ + return sys_fallocate(fd, mode, ((loff_t)offhi << 32) | offlo, + ((loff_t)lenhi << 32) | lenlo); +} + +asmlinkage long compat_sys_fanotify_mark(int fan_fd, int flags, u32 mask_hi, + u32 mask_lo, int fd, + const char __user *pathname) +{ + return sys_fanotify_mark(fan_fd, flags, ((u64)mask_hi << 32) | mask_lo, + fd, pathname); +} diff --git a/pool/shard002/C/0059993_file.c b/pool/shard002/C/0059993_file.c new file mode 100644 index 0000000000000000000000000000000000000000..80415ea99411094fe8c236cb1345ff9df24b923e --- /dev/null +++ b/pool/shard002/C/0059993_file.c @@ -0,0 +1,202 @@ +/* + * $Id: file.c,v 1.15 2008-07-27 03:18:38 haley Exp $ + */ +/************************************************************************ +* * +* Copyright (C) 2000 * +* University Corporation for Atmospheric Research * +* All Rights Reserved * +* * +* The use of this Software is governed by a License Agreement. * +* * +************************************************************************/ + +/* + * file.c + * + * Author John Clyne + * + * Date Tue Jul 31 18:12:46 MDT 1990 + * + * This file together with 'w_file.c' define a file selection box. + * Nonwidget-dependent code is located in this module. Widget-dependent + * code is in 'w_file.c' + */ +#include +#include +#include +#include +#include "glob.h" +#include "idt.h" + +static char *currentFileSelection = NULL; /* user's current selection */ +static char *currentPath = NULL; /* path to the current file */ + +/* + * GetFiles + * [ exported to w_file.c ] + * + * Get a list of files from the shell using file name substitution. + * The memory allocated is available until the next invocation GetFiles. + * The path to the files in the file list is stored internaly. + * + * on entry + * *file_filter : filter passed to the shell to match file + * on exit + * *longest : length of longest file found + * return : a null terminated, newline separated list of files; + */ +char *GetFiles(file_filter, longest) + char *file_filter; + int *longest; + +{ + char **files; + char *s; + int file_count; + int len = 0; + int total_len = 0; + int i; + + static char *buf = NULL; /* storage for list of files */ + static char *pathBuf = NULL;/* storage for path to files */ + + + if (buf) { + free((Voidptr) buf); + buf = NULL; + } + if (pathBuf) { + free((Voidptr) pathBuf); + pathBuf = NULL; + } + *longest = 10; + + /* + * perform globing using the file filter + */ + glob(file_filter, &files, &file_count); + + if (file_count == 0) return (""); + + /* + * get the path to the file(s) + */ + s = strrchr(files[0], '/'); + if (s) { + s++; + if ( !(pathBuf = malloc((unsigned) (s - files[0] + 1)))) { + perror("malloc()"); + return(NULL); + } + (void) strncpy(pathBuf, files[0], s - files[0]); + pathBuf[s - files[0]] = '\0'; + } + else { /* default path is "./" */ + if ( !(pathBuf = malloc((unsigned) (strlen("./") + 1)))) { + perror("malloc()"); + return(NULL); + } + (void) strcpy(pathBuf, "./"); + } + currentPath = pathBuf; + + + /* + * find out how much memory we need and what the longest file name is + * and stip off path of file + */ + for (i = 0, *longest = 0; i < file_count; i++) { + /*SUPPRESS 624*/ + s = (s = strrchr(files[i], '/')) ? ++s : files[i]; + files[i] = s; + len = strlen(files[i]); + *longest = *longest < len ? len : *longest; + total_len += len; + } + + if ( !(buf = malloc( (unsigned) (total_len + file_count + 1 )))) { + perror("malloc()"); + return(NULL); + } + buf[0] = '\0'; + + /* + * create a newline separated list of files + */ + for (i = 0; i < file_count; i++) { + (void) strcat(buf, files[i]); + (void) strcat(buf, "\n"); + } + + return (buf); +} + +/* + * SetFileSelection + * [ exported to w_file.c ] + * + * Record the users file selection + * on entry + * *file : the selection + */ +void +SetFileSelection(file, select_action) + char *file; + FuncPtrPasser select_action; +{ + + if (currentFileSelection) free ((Voidptr) currentFileSelection); + + if (! *file) { + currentFileSelection = NULL; + return; + } + + /* + * if file name already contains a path name or currentPath is NULL + * don't cat on the current path name + */ + if ((*file == '.' && (*(file+1) == '.' || *(file+1) == '/')) + || *file == '/' || *file == '~' || (! currentPath)) { + + currentFileSelection = malloc((unsigned) (strlen (file) +1)); + if (! currentFileSelection) { + perror("malloc()"); + return; + } + (void) strcpy(currentFileSelection, file); + if (select_action.func) { + select_action.func(); + } + return; + } + + /* + * build the path to the file and store it + */ + currentFileSelection = malloc((unsigned) + (strlen(currentPath) + strlen (file) +1)); + if (! currentFileSelection) { + perror("malloc()"); + return; + } + + (void) strcpy(currentFileSelection, currentPath); + (void) strcat(currentFileSelection, file); + + if (select_action.func) { + select_action.func(); + } +} + +/* + * GetFileSelection + * [exported] + * + * Retrieve the user's selection + */ +char *GetFileSelection() +{ + return (currentFileSelection); +} diff --git a/pool/shard002/C/0059995_strwide.c b/pool/shard002/C/0059995_strwide.c new file mode 100644 index 0000000000000000000000000000000000000000..c8915bb5e6aa8a15ce62c5c2a70383c8c6d9b45c --- /dev/null +++ b/pool/shard002/C/0059995_strwide.c @@ -0,0 +1,141 @@ +/* + * libdpkg - Debian packaging suite library routines + * strwide.c - wide character string handling routines + * + * Copyright © 2004 Changwoo Ryu + * Copyright © 2012-2013 Guillem Jover + * + * This is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This 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 +#ifdef ENABLE_NLS +#include +#endif + +#include +#include +#include + +/** + * Compute the screen width of a string. + * + * @param str The multibyte string. + * + * @return The width of the string. + */ +int +str_width(const char *str) +{ +#ifdef ENABLE_NLS + mbstate_t state; + wchar_t *wcs; + const char *mbs = str; + size_t len, res; + int width; + + len = strlen(str) + 1; + wcs = m_malloc(sizeof(wcs[0]) * len); + + memset(&state, 0, sizeof(state)); + + res = mbsrtowcs(wcs, &mbs, len, &state); + if (res == (size_t)-1) { +#ifdef DPKG_UNIFORM_ENCODING + ohshit(_("cannot convert multibyte string '%s' " + "to a wide-character string"), str); +#else + /* Cannot convert, fallback to ASCII method. */ + free(wcs); + return strlen(str); +#endif + } + + width = wcswidth(wcs, res); + + free(wcs); + + return width; +#else + return strlen(str); +#endif +} + +/** + * Generate the crop values for a string given a maximum screen width. + * + * This function analyzes the string passed and computes the correct point + * where to crop the string, returning the amount of string and maximum + * bytes to use for padding for example. + * + * On NLS enabled builds, in addition the string will be cropped on any + * newline. + * + * @param str The string to crop. + * @param max_width The max screen width to use. + * @param crop[out] The generated crop values for the string. + */ +void +str_gen_crop(const char *str, int max_width, struct str_crop_info *crop) +{ +#ifdef ENABLE_NLS + mbstate_t state; + size_t str_bytes; + int mbs_bytes = 0; + int mbs_width = 0; + + str_bytes = strlen(str) + 1; + memset(&state, 0, sizeof(state)); + + for (;;) { + wchar_t wc; + int wc_width; + size_t mb_bytes; + + mb_bytes = mbrtowc(&wc, str, str_bytes, &state); + if (mb_bytes == (size_t)-1 || mb_bytes == (size_t)-2) { +#ifdef DPKG_UNIFORM_ENCODING + ohshit(_("cannot convert multibyte sequence '%s' " + "to a wide character"), str); +#else + /* Cannot convert, fallback to ASCII method. */ + crop->str_bytes = crop->max_bytes = max_width; + return; +#endif + } + if (mb_bytes == 0) + break; + + wc_width = wcwidth(wc); + if (wc_width < 0) + break; + if (mbs_width + wc_width > max_width) + break; + + mbs_width += wc_width; + mbs_bytes += mb_bytes; + str_bytes -= mb_bytes; + str += mb_bytes; + } + + crop->str_bytes = mbs_bytes; + crop->max_bytes = mbs_bytes + max_width - mbs_width; +#else + crop->str_bytes = crop->max_bytes = max_width; +#endif +} diff --git a/pool/shard002/C/0060011_preload-temp-home.c b/pool/shard002/C/0060011_preload-temp-home.c new file mode 100644 index 0000000000000000000000000000000000000000..90b547e5a6237414ac8cd40f2bd514b9d50ba647 --- /dev/null +++ b/pool/shard002/C/0060011_preload-temp-home.c @@ -0,0 +1,62 @@ +/* + * This file is part of Cockpit. + * + * Copyright (C) 2018 Red Hat, Inc. + * + * Cockpit 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. + * + * Cockpit 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 Cockpit; If not, see . + */ + +#include "config.h" + +#include +#include +#include +#include +#include +#include + +static void * +get_libc_func(const char *f) +{ + void *fp; + fp = dlsym(RTLD_NEXT, f); + assert(fp); + return fp; +} + +#define libc_func(name, rettype, ...) \ + static rettype (*_ ## name) (__VA_ARGS__) = NULL; \ + if (_ ## name == NULL) \ + _ ## name = get_libc_func(#name); + +/** + * Change pw_dir to the value of $HOME for the current uid. + * This is useful for libssh's expansion of ~ to point to our temporary test + * $HOME instead of the real one from /etc/passwd. + * + */ +int getpwuid_r(uid_t uid, struct passwd *pwd, char *buf, size_t buflen, struct passwd **result) +{ + int res; + libc_func(getpwuid_r, int, uid_t, struct passwd *, char*, size_t, struct passwd **); + res = _getpwuid_r(uid, pwd, buf, buflen, result); + if (res == 0 && uid == getuid()) { + /* fprintf(stderr, "temp-home wrapped getpwuid_r(uid %i): changing original home %s to $HOME %s\n", (int) uid, pwd->pw_dir, getenv("HOME")); */ + /* note: in theory the caller might change this and thus change the + * environment, but this is only for the unit tests where we know that + * libssh doesn't do that, so avoid any unnecessary copying here */ + pwd->pw_dir = getenv("HOME"); + } + return res; +} diff --git a/pool/shard002/C/0060018_subpage_prot.c b/pool/shard002/C/0060018_subpage_prot.c new file mode 100644 index 0000000000000000000000000000000000000000..473dd430e30632c8a38ff629b007a77b3363d857 --- /dev/null +++ b/pool/shard002/C/0060018_subpage_prot.c @@ -0,0 +1,289 @@ +/* + * Copyright 2007-2008 Paul Mackerras, IBM Corp. + * + * 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 + +/* + * Free all pages allocated for subpage protection maps and pointers. + * Also makes sure that the subpage_prot_table structure is + * reinitialized for the next user. + */ +void subpage_prot_free(struct mm_struct *mm) +{ + struct subpage_prot_table *spt = mm_ctx_subpage_prot(&mm->context); + unsigned long i, j, addr; + u32 **p; + + if (!spt) + return; + + for (i = 0; i < 4; ++i) { + if (spt->low_prot[i]) { + free_page((unsigned long)spt->low_prot[i]); + spt->low_prot[i] = NULL; + } + } + addr = 0; + for (i = 0; i < (TASK_SIZE_USER64 >> 43); ++i) { + p = spt->protptrs[i]; + if (!p) + continue; + spt->protptrs[i] = NULL; + for (j = 0; j < SBP_L2_COUNT && addr < spt->maxaddr; + ++j, addr += PAGE_SIZE) + if (p[j]) + free_page((unsigned long)p[j]); + free_page((unsigned long)p); + } + spt->maxaddr = 0; + kfree(spt); +} + +static void hpte_flush_range(struct mm_struct *mm, unsigned long addr, + int npages) +{ + pgd_t *pgd; + pud_t *pud; + pmd_t *pmd; + pte_t *pte; + spinlock_t *ptl; + + pgd = pgd_offset(mm, addr); + if (pgd_none(*pgd)) + return; + pud = pud_offset(pgd, addr); + if (pud_none(*pud)) + return; + pmd = pmd_offset(pud, addr); + if (pmd_none(*pmd)) + return; + pte = pte_offset_map_lock(mm, pmd, addr, &ptl); + arch_enter_lazy_mmu_mode(); + for (; npages > 0; --npages) { + pte_update(mm, addr, pte, 0, 0, 0); + addr += PAGE_SIZE; + ++pte; + } + arch_leave_lazy_mmu_mode(); + pte_unmap_unlock(pte - 1, ptl); +} + +/* + * Clear the subpage protection map for an address range, allowing + * all accesses that are allowed by the pte permissions. + */ +static void subpage_prot_clear(unsigned long addr, unsigned long len) +{ + struct mm_struct *mm = current->mm; + struct subpage_prot_table *spt; + u32 **spm, *spp; + unsigned long i; + size_t nw; + unsigned long next, limit; + + down_write(&mm->mmap_sem); + + spt = mm_ctx_subpage_prot(&mm->context); + if (!spt) + goto err_out; + + limit = addr + len; + if (limit > spt->maxaddr) + limit = spt->maxaddr; + for (; addr < limit; addr = next) { + next = pmd_addr_end(addr, limit); + if (addr < 0x100000000UL) { + spm = spt->low_prot; + } else { + spm = spt->protptrs[addr >> SBP_L3_SHIFT]; + if (!spm) + continue; + } + spp = spm[(addr >> SBP_L2_SHIFT) & (SBP_L2_COUNT - 1)]; + if (!spp) + continue; + spp += (addr >> PAGE_SHIFT) & (SBP_L1_COUNT - 1); + + i = (addr >> PAGE_SHIFT) & (PTRS_PER_PTE - 1); + nw = PTRS_PER_PTE - i; + if (addr + (nw << PAGE_SHIFT) > next) + nw = (next - addr) >> PAGE_SHIFT; + + memset(spp, 0, nw * sizeof(u32)); + + /* now flush any existing HPTEs for the range */ + hpte_flush_range(mm, addr, nw); + } + +err_out: + up_write(&mm->mmap_sem); +} + +#ifdef CONFIG_TRANSPARENT_HUGEPAGE +static int subpage_walk_pmd_entry(pmd_t *pmd, unsigned long addr, + unsigned long end, struct mm_walk *walk) +{ + struct vm_area_struct *vma = walk->vma; + split_huge_pmd(vma, pmd, addr); + return 0; +} + +static void subpage_mark_vma_nohuge(struct mm_struct *mm, unsigned long addr, + unsigned long len) +{ + struct vm_area_struct *vma; + struct mm_walk subpage_proto_walk = { + .mm = mm, + .pmd_entry = subpage_walk_pmd_entry, + }; + + /* + * We don't try too hard, we just mark all the vma in that range + * VM_NOHUGEPAGE and split them. + */ + vma = find_vma(mm, addr); + /* + * If the range is in unmapped range, just return + */ + if (vma && ((addr + len) <= vma->vm_start)) + return; + + while (vma) { + if (vma->vm_start >= (addr + len)) + break; + vma->vm_flags |= VM_NOHUGEPAGE; + walk_page_vma(vma, &subpage_proto_walk); + vma = vma->vm_next; + } +} +#else +static void subpage_mark_vma_nohuge(struct mm_struct *mm, unsigned long addr, + unsigned long len) +{ + return; +} +#endif + +/* + * Copy in a subpage protection map for an address range. + * The map has 2 bits per 4k subpage, so 32 bits per 64k page. + * Each 2-bit field is 0 to allow any access, 1 to prevent writes, + * 2 or 3 to prevent all accesses. + * Note that the normal page protections also apply; the subpage + * protection mechanism is an additional constraint, so putting 0 + * in a 2-bit field won't allow writes to a page that is otherwise + * write-protected. + */ +SYSCALL_DEFINE3(subpage_prot, unsigned long, addr, + unsigned long, len, u32 __user *, map) +{ + struct mm_struct *mm = current->mm; + struct subpage_prot_table *spt; + u32 **spm, *spp; + unsigned long i; + size_t nw; + unsigned long next, limit; + int err; + + if (radix_enabled()) + return -ENOENT; + + /* Check parameters */ + if ((addr & ~PAGE_MASK) || (len & ~PAGE_MASK) || + addr >= mm->task_size || len >= mm->task_size || + addr + len > mm->task_size) + return -EINVAL; + + if (is_hugepage_only_range(mm, addr, len)) + return -EINVAL; + + if (!map) { + /* Clear out the protection map for the address range */ + subpage_prot_clear(addr, len); + return 0; + } + + if (!access_ok(map, (len >> PAGE_SHIFT) * sizeof(u32))) + return -EFAULT; + + down_write(&mm->mmap_sem); + + spt = mm_ctx_subpage_prot(&mm->context); + if (!spt) { + /* + * Allocate subpage prot table if not already done. + * Do this with mmap_sem held + */ + spt = kzalloc(sizeof(struct subpage_prot_table), GFP_KERNEL); + if (!spt) { + err = -ENOMEM; + goto out; + } + mm->context.hash_context->spt = spt; + } + + subpage_mark_vma_nohuge(mm, addr, len); + for (limit = addr + len; addr < limit; addr = next) { + next = pmd_addr_end(addr, limit); + err = -ENOMEM; + if (addr < 0x100000000UL) { + spm = spt->low_prot; + } else { + spm = spt->protptrs[addr >> SBP_L3_SHIFT]; + if (!spm) { + spm = (u32 **)get_zeroed_page(GFP_KERNEL); + if (!spm) + goto out; + spt->protptrs[addr >> SBP_L3_SHIFT] = spm; + } + } + spm += (addr >> SBP_L2_SHIFT) & (SBP_L2_COUNT - 1); + spp = *spm; + if (!spp) { + spp = (u32 *)get_zeroed_page(GFP_KERNEL); + if (!spp) + goto out; + *spm = spp; + } + spp += (addr >> PAGE_SHIFT) & (SBP_L1_COUNT - 1); + + local_irq_disable(); + demote_segment_4k(mm, addr); + local_irq_enable(); + + i = (addr >> PAGE_SHIFT) & (PTRS_PER_PTE - 1); + nw = PTRS_PER_PTE - i; + if (addr + (nw << PAGE_SHIFT) > next) + nw = (next - addr) >> PAGE_SHIFT; + + up_write(&mm->mmap_sem); + if (__copy_from_user(spp, map, nw * sizeof(u32))) + return -EFAULT; + map += nw; + down_write(&mm->mmap_sem); + + /* now flush any existing HPTEs for the range */ + hpte_flush_range(mm, addr, nw); + } + if (limit > spt->maxaddr) + spt->maxaddr = limit; + err = 0; + out: + up_write(&mm->mmap_sem); + return err; +} diff --git a/pool/shard002/C/0060021_ToggleUtil.c b/pool/shard002/C/0060021_ToggleUtil.c new file mode 100644 index 0000000000000000000000000000000000000000..3168c798f5e681b1fcc9e58af58ea6ab7eaa2db3 --- /dev/null +++ b/pool/shard002/C/0060021_ToggleUtil.c @@ -0,0 +1,154 @@ +#ifndef TOGGLEUTIL_H +#define TOGGLEUTIL_H + +void toggle_AddToRadioGroup(RadioGroup*, Widget); +void toggle_CreateRadioGroup(Widget, Widget); +RadioGroup *toggle_GetRadioGroup(Widget); +void toggle_RemoveFromRadioGroup(Widget); +void toggle_TurnOffRadioSiblings(Widget); + + +/* + * Function: + * GetRadioGroup + * + * Parameters: + * w - toggle widget who's radio group we are getting + * + * Description: + * Gets the radio group associated with a give toggle widget. + * + * Returns: + * The radio group associated with this toggle group + */ +RadioGroup *toggle_GetRadioGroup(Widget w) +{ + ToggleWidget tw = (ToggleWidget)w; + + if (tw == NULL) + return (NULL); + + return (tw->toggle.radio_group); +} + +/* + * Function: + * CreateRadioGroup + * + * Parameters: + * w1 - toggle widgets to add to the radio group + * w2 - "" + * + * Description: + * Creates a radio group. give two widgets. + * + * Note: + * A pointer to the group is added to each widget's radio_group field. + */ +static void +CreateRadioGroup(Widget w1, Widget w2) +{ + ToggleWidget tw1 = (ToggleWidget)w1; + ToggleWidget tw2 = (ToggleWidget) w2; + + if (tw1->toggle.radio_group != NULL || tw2->toggle.radio_group != NULL) + XtAppWarning(XtWidgetToApplicationContext(w1), + "Toggle Widget Error - Attempting to create a " + "new toggle group, when one already exists."); + + AddToRadioGroup(NULL, w1); + AddToRadioGroup(GetRadioGroup(w1), w2); +} + +/* + * Function: + * AddToRadioGroup + * + * Parameters: + * group - element of the radio group the we are adding to + * w - new toggle widget to add to the group + * + * Description: + * Adds a toggle to the radio group. + */ +static void +AddToRadioGroup(RadioGroup *group, Widget w) +{ + ToggleWidget tw = (ToggleWidget)w; + RadioGroup *local; + + local = (RadioGroup *)XtMalloc(sizeof(RadioGroup)); + local->widget = w; + tw->toggle.radio_group = local; + + if (group == NULL) { /* Creating new group */ + group = local; + group->next = NULL; + group->prev = NULL; + return; + } + local->prev = group; /* Adding to previous group */ + if ((local->next = group->next) != NULL) + local->next->prev = local; + group->next = local; +} + +/* + * Function: + * TurnOffRadioSiblings + * + * Parameters: + * widget - toggle widget + * + * Description: + * Deactivates all radio siblings. + */ +static void +TurnOffRadioSiblings(Widget w) +{ + RadioGroup *group; + ToggleWidgetClass cclass = (ToggleWidgetClass)w->core.widget_class; + + if ((group = GetRadioGroup(w)) == NULL) /* Punt if there is no group */ + return; + + /* Go to the top of the group */ + for (; group->prev != NULL ; group = group->prev) + ; + + while (group != NULL) { + ToggleWidget local_tog = (ToggleWidget)group->widget; + + if (local_tog->command.set) { + cclass->toggle_class.Unset(group->widget, NULL, NULL, NULL); + Notify(group->widget, NULL, NULL, NULL); + } + group = group->next; + } +} + +/* + * Function: + * RemoveFromRadioGroup + * + * Parameters: + * w - toggle widget to remove + * + * Description: + * Removes a toggle from a RadioGroup. + */ +static void +RemoveFromRadioGroup(Widget w) +{ + RadioGroup *group = GetRadioGroup(w); + if (group != NULL) { + if (group->prev != NULL) + (group->prev)->next = group->next; + if (group->next != NULL) + (group->next)->prev = group->prev; + XtFree((char *)group); + } +} + + +#endif diff --git a/pool/shard002/C/0060028_tnl-ports.c b/pool/shard002/C/0060028_tnl-ports.c new file mode 100644 index 0000000000000000000000000000000000000000..e6739b9f0387b5e099399209a5e27be371e5e310 --- /dev/null +++ b/pool/shard002/C/0060028_tnl-ports.c @@ -0,0 +1,195 @@ +/* + * Copyright (c) 2014, 2015 Nicira, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include +#include + +#include "classifier.h" +#include "dynamic-string.h" +#include "hash.h" +#include "ofpbuf.h" +#include "ovs-thread.h" +#include "odp-util.h" +#include "tnl-arp-cache.h" +#include "tnl-ports.h" +#include "ovs-thread.h" +#include "unixctl.h" +#include "util.h" + +static struct ovs_mutex mutex = OVS_MUTEX_INITIALIZER; +static struct classifier cls; /* Tunnel ports. */ + +struct tnl_port_in { + struct cls_rule cr; + odp_port_t portno; + struct ovs_refcount ref_cnt; + char dev_name[IFNAMSIZ]; +}; + +static struct tnl_port_in * +tnl_port_cast(const struct cls_rule *cr) +{ + BUILD_ASSERT_DECL(offsetof(struct tnl_port_in, cr) == 0); + + return CONTAINER_OF(cr, struct tnl_port_in, cr); +} + +static void +tnl_port_free(struct tnl_port_in *p) +{ + cls_rule_destroy(&p->cr); + free(p); +} + +static void +tnl_port_init_flow(struct flow *flow, ovs_be32 ip_dst, ovs_be16 udp_port) +{ + memset(flow, 0, sizeof *flow); + flow->dl_type = htons(ETH_TYPE_IP); + if (udp_port) { + flow->nw_proto = IPPROTO_UDP; + } else { + flow->nw_proto = IPPROTO_GRE; + } + flow->tp_dst = udp_port; + /* When matching on incoming flow from remove tnl end point, + * our dst ip address is source ip for them. */ + flow->nw_src = ip_dst; +} + +void +tnl_port_map_insert(odp_port_t port, ovs_be32 ip_dst, ovs_be16 udp_port, + const char dev_name[]) +{ + const struct cls_rule *cr; + struct tnl_port_in *p; + struct match match; + + memset(&match, 0, sizeof match); + tnl_port_init_flow(&match.flow, ip_dst, udp_port); + + ovs_mutex_lock(&mutex); + do { + cr = classifier_lookup(&cls, &match.flow, NULL); + p = tnl_port_cast(cr); + /* Try again if the rule was released before we get the reference. */ + } while (p && !ovs_refcount_try_ref_rcu(&p->ref_cnt)); + + if (!p) { + p = xzalloc(sizeof *p); + p->portno = port; + + match.wc.masks.dl_type = OVS_BE16_MAX; + match.wc.masks.nw_proto = 0xff; + match.wc.masks.nw_frag = 0xff; /* XXX: No fragments support. */ + match.wc.masks.tp_dst = OVS_BE16_MAX; + match.wc.masks.nw_src = OVS_BE32_MAX; + + cls_rule_init(&p->cr, &match, 0); /* Priority == 0. */ + ovs_refcount_init(&p->ref_cnt); + strncpy(p->dev_name, dev_name, IFNAMSIZ); + + classifier_insert(&cls, &p->cr, NULL, 0); + } + ovs_mutex_unlock(&mutex); +} + +static void +tnl_port_unref(const struct cls_rule *cr) +{ + struct tnl_port_in *p = tnl_port_cast(cr); + + if (cr && ovs_refcount_unref_relaxed(&p->ref_cnt) == 1) { + ovs_mutex_lock(&mutex); + if (classifier_remove(&cls, cr)) { + ovsrcu_postpone(tnl_port_free, p); + } + ovs_mutex_unlock(&mutex); + } +} + +void +tnl_port_map_delete(ovs_be32 ip_dst, ovs_be16 udp_port) +{ + const struct cls_rule *cr; + struct flow flow; + + tnl_port_init_flow(&flow, ip_dst, udp_port); + + cr = classifier_lookup(&cls, &flow, NULL); + tnl_port_unref(cr); +} + +/* 'flow' is non-const to allow for temporary modifications during the lookup. + * Any changes are restored before returning. */ +odp_port_t +tnl_port_map_lookup(struct flow *flow, struct flow_wildcards *wc) +{ + const struct cls_rule *cr = classifier_lookup(&cls, flow, wc); + + return (cr) ? tnl_port_cast(cr)->portno : ODPP_NONE; +} + +static void +tnl_port_show(struct unixctl_conn *conn, int argc OVS_UNUSED, + const char *argv[] OVS_UNUSED, void *aux OVS_UNUSED) +{ + struct ds ds = DS_EMPTY_INITIALIZER; + const struct tnl_port_in *p; + + ds_put_format(&ds, "Listening ports:\n"); + CLS_FOR_EACH(p, cr, &cls) { + struct odputil_keybuf keybuf; + struct odputil_keybuf maskbuf; + struct flow flow; + const struct nlattr *key, *mask; + size_t key_len, mask_len; + struct flow_wildcards wc; + struct ofpbuf buf; + + ds_put_format(&ds, "%s (%"PRIu32") : ", p->dev_name, p->portno); + minimask_expand(&p->cr.match.mask, &wc); + miniflow_expand(&p->cr.match.flow, &flow); + + /* Key. */ + ofpbuf_use_stack(&buf, &keybuf, sizeof keybuf); + odp_flow_key_from_flow(&buf, &flow, &wc.masks, + flow.in_port.odp_port, true); + key = ofpbuf_data(&buf); + key_len = ofpbuf_size(&buf); + /* mask*/ + ofpbuf_use_stack(&buf, &maskbuf, sizeof maskbuf); + odp_flow_key_from_mask(&buf, &wc.masks, &flow, + odp_to_u32(wc.masks.in_port.odp_port), + SIZE_MAX, false); + mask = ofpbuf_data(&buf); + mask_len = ofpbuf_size(&buf); + + /* build string. */ + odp_flow_format(key, key_len, mask, mask_len, NULL, &ds, false); + ds_put_format(&ds, "\n"); + } + unixctl_command_reply(conn, ds_cstr(&ds)); + ds_destroy(&ds); +} + +void +tnl_port_map_init(void) +{ + classifier_init(&cls, flow_segment_u64s); + unixctl_command_register("tnl/ports/show", "", 0, 0, tnl_port_show, NULL); +} diff --git a/pool/shard002/C/0060029_clique.c b/pool/shard002/C/0060029_clique.c new file mode 100644 index 0000000000000000000000000000000000000000..337f60e8f8bf9b0d8516fc06f66863264c44e7c0 --- /dev/null +++ b/pool/shard002/C/0060029_clique.c @@ -0,0 +1,254 @@ +#include +#include + +#include "src/common/libpmi/clique.h" +#include "src/common/libpmi/pmi.h" +#include "src/common/libtap/tap.h" +#include "src/common/libutil/xzmalloc.h" + +struct spec { + char *vec; + int size; +}; + +static struct spec valid [] = { + /* flux rfc 13 */ + { "(vector,(0,16,16))", 256 }, // [0] + { "(vector,(0,8,16),(0,4,32))", 256 }, + + { " (vector, (0, 16,16) )", 256 }, + + /* notes in openmpi code */ + /* c.f. opal/mca/pmix/s2/pmi2_pmap_parser.c */ + { "(vector,(0,4,4),(0,4,1))", 20 }, + { "(vector,(0,2,1),(0,2,1))", 4 }, // [4] + { "(vector,(0,2,2))", 4 }, // [5] + + /* mpich unit test */ + /* c.f. src/mpid/ch3/src/mpid_vc.c */ + { "(vector, (0,1,1))", 5 }, + { "(vector, (0,1,1), (1,5,3), (6,2, 5))", 100 }, + { "(vector, (1,1,1), (0,2,2))", 5 }, + { "(vector, (1,1,1), (0,2,2),)", 5 }, + { "" , 1 }, + + /* grondo */ + { "(vector,(0,4,2),(1,3,1))", 10 }, + + { NULL, 0 }, +}; + +static struct spec invalid[] = { + + /* mpich unit test */ + /* c.f. src/mpid/ch3/src/mpid_vc.c */ + { "XXX, (1,1))", 1 }, + { "vector, (1,1))", 1 }, + { "(vector, (1.11, 2,2))", 1 }, + + { NULL, 0}, +}; + +static char *cliquetostr (int rank, int len, int *clique) +{ + int i, slen = (len + 1)*16; + char *s; + + if (len == 0) + return NULL; + + s = xzmalloc (slen); + sprintf (s, "%d: ", rank); + for (i = 0; i < len; i++) + sprintf (s + strlen (s), "%s%d", i > 0 ? "," : "", clique[i]); + return s; +} + +static char *cliqueN (struct pmi_map_block *blocks, int nblocks, int size, + int rank) +{ + int rc; + int nranks; + int *ranks = NULL; + char *s; + + rc = pmi_process_mapping_find_nranks (blocks, nblocks, rank, size, &nranks); + if (rc != PMI_SUCCESS) + return NULL; + ranks = xzmalloc (sizeof (int) * nranks); + rc = pmi_process_mapping_find_ranks (blocks, nblocks, rank, size, + ranks, nranks); + if (rc != PMI_SUCCESS) { + free (ranks); + return NULL; + } + s = cliquetostr (rank, nranks, ranks); + free (ranks); + return s; +} + +int main (int argc, char *argv[]) +{ + int nblocks, nodeid; + int nranks, *ranks; + struct pmi_map_block *blocks = NULL; + int i, rank, rc; + char *s; + + plan (NO_PLAN); + + /* Check the parser. + */ + + rc = pmi_process_mapping_parse (valid[0].vec, &blocks, &nblocks); + ok (rc == PMI_SUCCESS && nblocks == 1 + && blocks[0].nodeid == 0 + && blocks[0].nodes == 16 + && blocks[0].procs == 16, + "correctly parsed single-block vector"); + if (rc == PMI_SUCCESS) + free (blocks); + + rc = pmi_process_mapping_parse (valid[1].vec, &blocks, &nblocks); + ok (rc == PMI_SUCCESS && nblocks == 2 + && blocks[0].nodeid == 0 + && blocks[0].nodes == 8 + && blocks[0].procs == 16 + && blocks[1].nodeid == 0 + && blocks[1].nodes == 4 + && blocks[1].procs == 32, + "correctly parsed 2-block vector"); + if (rc == PMI_SUCCESS) + free (blocks); + + rc = pmi_process_mapping_parse (valid[2].vec, &blocks, &nblocks); + ok (rc == PMI_SUCCESS && nblocks == 1 + && blocks[0].nodeid == 0 + && blocks[0].nodes == 16 + && blocks[0].procs == 16, + "correctly parsed single-block vector with whitespace"); + if (rc == PMI_SUCCESS) + free (blocks); + + /* Detailed check of regular cyclic layout + */ + + rc = pmi_process_mapping_parse (valid[4].vec, &blocks, &nblocks); + ok (rc == PMI_SUCCESS, + "parsed cyclic layout of 4 procs on 2 nodes"); + if (rc != PMI_SUCCESS) + BAIL_OUT ("cannot continue"); + rc = pmi_process_mapping_find_nodeid (blocks, nblocks, 0, &nodeid); + ok (rc == PMI_SUCCESS && nodeid == 0, + "find_nodeid says node 0 runs proc 0"); + rc = pmi_process_mapping_find_nodeid (blocks, nblocks, 1, &nodeid); + ok (rc == PMI_SUCCESS && nodeid == 1, + "find_nodeid says node 1 runs proc 1"); + rc = pmi_process_mapping_find_nodeid (blocks, nblocks, 2, &nodeid); + ok (rc == PMI_SUCCESS && nodeid == 0, + "find_nodeid says node 0 runs proc 2"); + rc = pmi_process_mapping_find_nodeid (blocks, nblocks, 3, &nodeid); + ok (rc == PMI_SUCCESS && nodeid == 1, + "find_nodeid says node 1 runs proc 3"); + + rc = pmi_process_mapping_find_nranks (blocks, nblocks, 0, + valid[4].size, &nranks); + ok (rc == PMI_SUCCESS && nranks == 2, + "find_nranks says node 0 runs two procs"); + ranks = xzmalloc (sizeof (int)*nranks); + rc = pmi_process_mapping_find_ranks (blocks, nblocks, 0, + valid[4].size, ranks, nranks); + ok (rc == PMI_SUCCESS && ranks[0] == 0 && ranks [1] == 2, + "find_ranks says node 0 runs 0,2"); + free (ranks); + + rc = pmi_process_mapping_find_nranks (blocks, nblocks, 1, + valid[4].size, &nranks); + ok (rc == PMI_SUCCESS && nranks == 2, + "find_nranks says node 1 runs two procs"); + ranks = xzmalloc (sizeof (int)*nranks); + rc = pmi_process_mapping_find_ranks (blocks, nblocks, 1, + valid[4].size, ranks, nranks); + ok (rc == PMI_SUCCESS && ranks[0] == 1 && ranks [1] == 3, + "find_ranks says node 1 runs 1,3"); + free (ranks); + + free (blocks); + + /* Detailed check of regular block layout + */ + + rc = pmi_process_mapping_parse (valid[5].vec, &blocks, &nblocks); + ok (rc == PMI_SUCCESS, + "parsed block layout of 4 procs on 2 nodes"); + if (rc != PMI_SUCCESS) + BAIL_OUT ("cannot continue"); + rc = pmi_process_mapping_find_nodeid (blocks, nblocks, 0, &nodeid); + ok (rc == PMI_SUCCESS && nodeid == 0, + "find_nodeid says node 0 runs proc 0"); + rc = pmi_process_mapping_find_nodeid (blocks, nblocks, 1, &nodeid); + ok (rc == PMI_SUCCESS && nodeid == 0, + "find_nodeid says node 0 runs proc 1"); + rc = pmi_process_mapping_find_nodeid (blocks, nblocks, 2, &nodeid); + ok (rc == PMI_SUCCESS && nodeid == 1, + "find_nodeid says node 1 runs proc 2"); + rc = pmi_process_mapping_find_nodeid (blocks, nblocks, 3, &nodeid); + ok (rc == PMI_SUCCESS && nodeid == 1, + "find_nodeid says node 1 runs proc 3"); + + rc = pmi_process_mapping_find_nranks (blocks, nblocks, 0, + valid[5].size, &nranks); + ok (rc == PMI_SUCCESS && nranks == 2, + "find_nranks says node 0 runs two procs"); + ranks = xzmalloc (sizeof (int)*nranks); + rc = pmi_process_mapping_find_ranks (blocks, nblocks, 0, + valid[5].size, ranks, nranks); + ok (rc == PMI_SUCCESS && ranks[0] == 0 && ranks [1] == 1, + "find_ranks says node 0 runs 0,1"); + free (ranks); + + rc = pmi_process_mapping_find_nranks (blocks, nblocks, 1, + valid[5].size, &nranks); + ok (rc == PMI_SUCCESS && nranks == 2, + "find_nranks says node 1 runs two procs"); + ranks = xzmalloc (sizeof (int)*nranks); + rc = pmi_process_mapping_find_ranks (blocks, nblocks, 1, + valid[5].size, ranks, nranks); + ok (rc == PMI_SUCCESS && ranks[0] == 2 && ranks [1] == 3, + "find_ranks says node 1 runs 2,3"); + free (ranks); + free (blocks); + + /* Valid + */ + + for (i = 0; valid[i].vec != NULL; i++) { + rc = pmi_process_mapping_parse (valid[i].vec, &blocks, &nblocks); + ok (rc == PMI_SUCCESS, + "parsed %s size=%d", valid[i].vec, valid[i].size); + for (rank = 0; rank < valid[i].size; rank++) { + s = cliqueN (blocks, nblocks, valid[i].size, rank); + if (!s) + break; + diag ("%s", s); + free (s); + } + free (blocks); + } + + /* Invalid + */ + + for (i = 0; invalid[i].vec != NULL; i++) { + rc = pmi_process_mapping_parse (invalid[i].vec, &blocks, &nblocks); + ok (rc == PMI_FAIL, + "refused to parse %s", invalid[i].vec); + } + + done_testing (); + return 0; +} + +/* + * vi:tabstop=4 shiftwidth=4 expandtab + */ diff --git a/pool/shard002/C/0060039_1-1.c b/pool/shard002/C/0060039_1-1.c new file mode 100644 index 0000000000000000000000000000000000000000..2e77bd127f12243f420aa2dc7d742d02ccc415a7 --- /dev/null +++ b/pool/shard002/C/0060039_1-1.c @@ -0,0 +1,59 @@ +/* + * Copyright (c) 2002-2003, Intel Corporation. All rights reserved. + * Created by: Rusty.Lnch REMOVE-THIS AT intel DOT com + * 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. + + Test case for assertion #1 of the sigaction system call that shows + sigaction (when used with a non-null act pointer) changes the action + for a signal. + + Steps: + 1. Initialize a global variable to indicate the signal + handler has not been called. (A signal handler of the + prototype "void func(int signo);" will set the global + variable to indicate otherwise. + 2. Use sigaction to setup a signal handler for SIGABRT + 3. Raise SIGABRT. + 4. Verify the global indicates the signal was called. +*/ + +#include +#include +#include "posixtest.h" + +static volatile int handler_called; + +static void handler(int signo PTS_ATTRIBUTE_UNUSED) +{ + handler_called = 1; +} + +int main(void) +{ + struct sigaction act; + + act.sa_handler = handler; + act.sa_flags = 0; + sigemptyset(&act.sa_mask); + if (sigaction(SIGABRT, &act, 0) == -1) { + perror("Unexpected error while attempting to setup test " + "pre-conditions"); + return PTS_UNRESOLVED; + } + + if (raise(SIGABRT) == -1) { + perror("Unexpected error while attempting to setup test " + "pre-conditions"); + return PTS_UNRESOLVED; + } + + if (handler_called) { + printf("Test PASSED\n"); + return PTS_PASS; + } + + printf("Test FAILED\n"); + return PTS_FAIL; +} diff --git a/pool/shard002/C/0060051_xcbc_plugin.c b/pool/shard002/C/0060051_xcbc_plugin.c new file mode 100644 index 0000000000000000000000000000000000000000..9d903bfaa85af6c569d732255e8494965aa7d581 --- /dev/null +++ b/pool/shard002/C/0060051_xcbc_plugin.c @@ -0,0 +1,63 @@ +/* + * Copyright (C) 2008 Martin Willi + * Hochschule fuer Technik Rapperswil + * + * 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. See . + * + * 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 "xcbc_plugin.h" + +#include +#include "xcbc_signer.h" +#include "xcbc_prf.h" + +typedef struct private_xcbc_plugin_t private_xcbc_plugin_t; + +/** + * private data of xcbc_plugin + */ +struct private_xcbc_plugin_t { + + /** + * public functions + */ + xcbc_plugin_t public; +}; + +/** + * Implementation of xcbc_plugin_t.xcbctroy + */ +static void destroy(private_xcbc_plugin_t *this) +{ + lib->crypto->remove_prf(lib->crypto, + (prf_constructor_t)xcbc_prf_create); + lib->crypto->remove_signer(lib->crypto, + (signer_constructor_t)xcbc_signer_create); + free(this); +} + +/* + * see header file + */ +plugin_t *xcbc_plugin_create() +{ + private_xcbc_plugin_t *this = malloc_thing(private_xcbc_plugin_t); + + this->public.plugin.destroy = (void(*)(plugin_t*))destroy; + + lib->crypto->add_prf(lib->crypto, PRF_AES128_XCBC, + (prf_constructor_t)xcbc_prf_create); + lib->crypto->add_signer(lib->crypto, AUTH_AES_XCBC_96, + (signer_constructor_t)xcbc_signer_create); + + return &this->public.plugin; +} + diff --git a/pool/shard002/C/0060062_usb.c b/pool/shard002/C/0060062_usb.c new file mode 100644 index 0000000000000000000000000000000000000000..bd0307a7e03e34c180cde06a338da8498909ae28 --- /dev/null +++ b/pool/shard002/C/0060062_usb.c @@ -0,0 +1,223 @@ +// Copyright 2014 Technical Machine, Inc. See the COPYRIGHT +// file at the top-level directory of this distribution. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +#include "boot.h" +#include "tessel.h" + +const USB_DeviceDescriptor device_descriptor = { + .bLength = sizeof(USB_DeviceDescriptor), + .bDescriptorType = USB_DTYPE_Device, + + .bcdUSB = 0x0200, + .bDeviceClass = 0, + .bDeviceSubClass = USB_CSCP_NoDeviceSubclass, + .bDeviceProtocol = USB_CSCP_NoDeviceProtocol, + + .bMaxPacketSize0 = 64, + .idVendor = 0x1d50, + .idProduct = 0x6097, + .bcdDevice = 0x0002, + + .iManufacturer = 0x01, + .iProduct = 0x02, + .iSerialNumber = 0xf0, + + .bNumConfigurations = 1 +}; + +typedef struct ConfigDesc { + USB_ConfigurationDescriptor Config; + USB_InterfaceDescriptor dfu_intf_flash; + DFU_FunctionalDescriptor dfu_desc_flash; + USB_InterfaceDescriptor dfu_intf_ram; + DFU_FunctionalDescriptor dfu_desc_ram; +} ConfigDesc; + +const ConfigDesc configuration_descriptor = { + .Config = { + .bLength = sizeof(USB_ConfigurationDescriptor), + .bDescriptorType = USB_DTYPE_Configuration, + .wTotalLength = sizeof(ConfigDesc), + .bNumInterfaces = 1, + .bConfigurationValue = 1, + .iConfiguration = 0, + .bmAttributes = USB_CONFIG_ATTR_BUSPOWERED, + .bMaxPower = USB_CONFIG_POWER_MA(500) + }, + .dfu_intf_flash = { + .bLength = sizeof(USB_InterfaceDescriptor), + .bDescriptorType = USB_DTYPE_Interface, + .bInterfaceNumber = 0, + .bAlternateSetting = 0, + .bNumEndpoints = 0, + .bInterfaceClass = DFU_INTERFACE_CLASS, + .bInterfaceSubClass = DFU_INTERFACE_SUBCLASS, + .bInterfaceProtocol = DFU_INTERFACE_PROTOCOL, + .iInterface = 0x10 + }, + .dfu_desc_flash = { + .bLength = sizeof(DFU_FunctionalDescriptor), + .bDescriptorType = DFU_DESCRIPTOR_TYPE, + .bmAttributes = DFU_ATTR_CAN_DOWNLOAD | DFU_ATTR_WILL_DETACH, + .wDetachTimeout = 0, + .wTransferSize = DFU_TRANSFER_SIZE, + .bcdDFUVersion = 0x0101, + }, + .dfu_intf_ram = { + .bLength = sizeof(USB_InterfaceDescriptor), + .bDescriptorType = USB_DTYPE_Interface, + .bInterfaceNumber = 0, + .bAlternateSetting = 1, + .bNumEndpoints = 0, + .bInterfaceClass = DFU_INTERFACE_CLASS, + .bInterfaceSubClass = DFU_INTERFACE_SUBCLASS, + .bInterfaceProtocol = DFU_INTERFACE_PROTOCOL, + .iInterface = 0x11 + }, + .dfu_desc_ram = { + .bLength = sizeof(DFU_FunctionalDescriptor), + .bDescriptorType = DFU_DESCRIPTOR_TYPE, + .bmAttributes = DFU_ATTR_CAN_DOWNLOAD | DFU_ATTR_WILL_DETACH, + .wDetachTimeout = 0, + .wTransferSize = DFU_TRANSFER_SIZE, + .bcdDFUVersion = 0x0101, + }, +}; + +const USB_StringDescriptor language_string = { + .bLength = USB_STRING_LEN(1), + .bDescriptorType = USB_DTYPE_String, + .bString = {USB_LANGUAGE_EN_US}, +}; + +const USB_StringDescriptor msft_os = { + .bLength = 18, + .bDescriptorType = USB_DTYPE_String, + .bString = {'M','S','F','T','1','0','0',0xee}, +}; + +const USB_MicrosoftCompatibleDescriptor msft_compatible = { + .dwLength = sizeof(USB_MicrosoftCompatibleDescriptor) + sizeof(USB_MicrosoftCompatibleDescriptor_Interface), + .bcdVersion = 0x0100, + .wIndex = 0x0004, + .bCount = 1, + .reserved = {0, 0, 0, 0, 0, 0, 0}, + .interfaces = { + { + .bFirstInterfaceNumber = 0, + .reserved1 = 0, + .compatibleID = "WINUSB\0\0", + .subCompatibleID = {0, 0, 0, 0, 0, 0, 0, 0}, + .reserved2 = {0, 0, 0, 0, 0, 0}, + } + } +}; + +uint16_t usb_cb_get_descriptor(uint8_t type, uint8_t index, const uint8_t** ptr) { + const void* address = NULL; + uint16_t size = 0; + + switch (type) { + case USB_DTYPE_Device: + address = &device_descriptor; + size = sizeof(USB_DeviceDescriptor); + break; + case USB_DTYPE_Configuration: + address = &configuration_descriptor; + size = sizeof(ConfigDesc); + break; + case USB_DTYPE_String: + switch (index) { + case 0x00: + address = &language_string; + break; + case 0x01: + address = usb_string_to_descriptor("Technical Machine"); + break; + case 0x02: + address = usb_string_to_descriptor("Tessel DFU"); + break; + case 0x10: + address = usb_string_to_descriptor("Flash"); + break; + case 0x11: + address = usb_string_to_descriptor("SRAM"); + break; + case 0xf0: + address = usb_string_to_descriptor(tessel_board_uuid()); + break; + case 0xee: + address = &msft_os; + break; + } + size = (((USB_StringDescriptor*)address))->bLength; + break; + } + + *ptr = address; + return size; +} + +void usb_cb_reset(void) { +} + +bool usb_cb_set_configuration(uint8_t config) { + if (config <= 1) { + return true; + } + return false; +} + +void usb_cb_control_setup(void) { + uint8_t recipient = usb_setup.bmRequestType & USB_REQTYPE_RECIPIENT_MASK; + if (recipient == USB_RECIPIENT_DEVICE) { + if (usb_setup.bRequest == 0xee) { + return usb_handle_msft_compatible(&msft_compatible); + } + } else if (recipient == USB_RECIPIENT_INTERFACE) { + if (usb_setup.wIndex == DFU_INTF) { + return dfu_control_setup(); + } + } + return usb_ep0_stall(); +} + +void usb_cb_control_in_completion(void) { + uint8_t recipient = usb_setup.bmRequestType & USB_REQTYPE_RECIPIENT_MASK; + if (recipient == USB_RECIPIENT_INTERFACE) { + if (usb_setup.wIndex == DFU_INTF) { + dfu_control_in_completion(); + } + } +} + +void usb_cb_control_out_completion(void) { + uint8_t recipient = usb_setup.bmRequestType & USB_REQTYPE_RECIPIENT_MASK; + if (recipient == USB_RECIPIENT_INTERFACE) { + if (usb_setup.wIndex == DFU_INTF) { + dfu_control_out_completion(); + } + } +} + +void usb_cb_completion(void) { + +} + +bool usb_cb_set_interface(uint16_t interface, uint16_t altsetting) { + if (interface == DFU_INTF) { + if (altsetting <= 1) { + dfu_target = altsetting; + dfu_reset(); + return true; + } + } + return false; +} + diff --git a/pool/shard002/C/0060068_my_fopen.c b/pool/shard002/C/0060068_my_fopen.c new file mode 100644 index 0000000000000000000000000000000000000000..c720e2c91683dcb84f2779cbe93356768ffc2c50 --- /dev/null +++ b/pool/shard002/C/0060068_my_fopen.c @@ -0,0 +1,354 @@ +/* Copyright (c) 2000, 2012, Oracle and/or its affiliates + Copyright (c) 1985, 2011, Monty Program Ab + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; version 2 of the License. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA */ + +#include "mysys_priv.h" +#include "my_static.h" +#include +#include "mysys_err.h" + +#if defined(__FreeBSD__) +extern int getosreldate(void); +#endif + +static void make_ftype(char * to,int flag); + +/* + Open a file as stream + + SYNOPSIS + my_fopen() + FileName Path-name of file + Flags Read | write | append | trunc (like for open()) + MyFlags Flags for handling errors + + RETURN + 0 Error + # File handler +*/ + +FILE *my_fopen(const char *filename, int flags, myf MyFlags) +{ + FILE *fd; + char type[10]; + DBUG_ENTER("my_fopen"); + DBUG_PRINT("my",("Name: '%s' flags: %d MyFlags: %lu", + filename, flags, MyFlags)); + + make_ftype(type,flags); + +#ifdef _WIN32 + fd= my_win_fopen(filename, type); +#else + fd= fopen(filename, type); +#endif + if (fd != 0) + { + /* + The test works if MY_NFILE < 128. The problem is that fileno() is char + on some OS (SUNOS). Actually the filename save isn't that important + so we can ignore if this doesn't work. + */ + + int filedesc= my_fileno(fd); + if ((uint)filedesc >= my_file_limit) + { + thread_safe_increment(my_stream_opened,&THR_LOCK_open); + DBUG_RETURN(fd); /* safeguard */ + } + mysql_mutex_lock(&THR_LOCK_open); + my_file_info[filedesc].name= (char*) my_strdup(filename,MyFlags); + my_stream_opened++; + my_file_total_opened++; + my_file_info[filedesc].type= STREAM_BY_FOPEN; + mysql_mutex_unlock(&THR_LOCK_open); + DBUG_PRINT("exit",("stream: 0x%lx", (long) fd)); + DBUG_RETURN(fd); + } + else + my_errno=errno; + DBUG_PRINT("error",("Got error %d on open",my_errno)); + if (MyFlags & (MY_FFNF | MY_FAE | MY_WME)) + my_error((flags & O_RDONLY) ? EE_FILENOTFOUND : EE_CANTCREATEFILE, + MYF(ME_BELL+ME_WAITTANG), filename, my_errno); + DBUG_RETURN((FILE*) 0); +} /* my_fopen */ + + +#if defined(_WIN32) + +static FILE *my_win_freopen(const char *path, const char *mode, FILE *stream) +{ + int handle_fd, fd= _fileno(stream); + HANDLE osfh; + + DBUG_ASSERT(path && stream); + DBUG_ASSERT(strchr(mode, 'a')); /* We use FILE_APPEND_DATA below */ + + /* Services don't have stdout/stderr on Windows, so _fileno returns -1. */ + if (fd < 0) + { + if (!freopen(path, mode, stream)) + return NULL; + + fd= _fileno(stream); + } + + if ((osfh= CreateFile(path, GENERIC_READ | FILE_APPEND_DATA, + FILE_SHARE_READ | FILE_SHARE_WRITE | + FILE_SHARE_DELETE, NULL, + OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, + NULL)) == INVALID_HANDLE_VALUE) + return NULL; + + if ((handle_fd= _open_osfhandle((intptr_t)osfh, _O_TEXT)) == -1) + { + CloseHandle(osfh); + return NULL; + } + + if (_dup2(handle_fd, fd) < 0) + { + CloseHandle(osfh); + return NULL; + } + + _close(handle_fd); + + return stream; +} + +#elif defined(__FreeBSD__) + +/* No close operation hook. */ + +static int no_close(void *cookie __attribute__((unused))) +{ + return 0; +} + +/* + A hack around a race condition in the implementation of freopen. + + The race condition stems from the fact that the current fd of + the stream is closed before its number is used to duplicate the + new file descriptor. This defeats the desired atomicity of the + close and duplicate of dup2(). + + See PR number 79887 for reference: + http://www.freebsd.org/cgi/query-pr.cgi?pr=79887 +*/ + +static FILE *my_freebsd_freopen(const char *path, const char *mode, FILE *stream) +{ + int old_fd; + FILE *result; + + flockfile(stream); + + old_fd= fileno(stream); + + /* Use a no operation close hook to avoid having the fd closed. */ + stream->_close= no_close; + + /* Relies on the implicit dup2 to close old_fd. */ + result= freopen(path, mode, stream); + + /* If successful, the _close hook was replaced. */ + + if (result == NULL) + close(old_fd); + else + funlockfile(result); + + return result; +} + +#endif + + +/** + Change the file associated with a file stream. + + @param path Path to file. + @param mode Mode of the stream. + @param stream File stream. + + @note + This function is used to redirect stdout and stderr to a file and + subsequently to close and reopen that file for log rotation. + + @retval A FILE pointer on success. Otherwise, NULL. +*/ + +FILE *my_freopen(const char *path, const char *mode, FILE *stream) +{ + FILE *result; + +#if defined(_WIN32) + result= my_win_freopen(path, mode, stream); +#elif defined(__FreeBSD__) + /* + XXX: Once the fix is ported to the stable releases, this should + be dependent upon the specific FreeBSD versions. Check at: + http://www.freebsd.org/cgi/query-pr.cgi?pr=79887 + */ + if (getosreldate() > 900027) + result= freopen(path, mode, stream); + else + result= my_freebsd_freopen(path, mode, stream); +#else + result= freopen(path, mode, stream); +#endif + + return result; +} + + +/* Close a stream */ +int my_fclose(FILE *fd, myf MyFlags) +{ + int err,file; + DBUG_ENTER("my_fclose"); + DBUG_PRINT("my",("stream: 0x%lx MyFlags: %lu", (long) fd, MyFlags)); + + mysql_mutex_lock(&THR_LOCK_open); + file= my_fileno(fd); +#ifndef _WIN32 + err= fclose(fd); +#else + err= my_win_fclose(fd); +#endif + if(err < 0) + { + my_errno=errno; + if (MyFlags & (MY_FAE | MY_WME)) + my_error(EE_BADCLOSE, MYF(ME_BELL+ME_WAITTANG), + my_filename(file),errno); + } + else + my_stream_opened--; + if ((uint) file < my_file_limit && my_file_info[file].type != UNOPEN) + { + my_file_info[file].type = UNOPEN; + my_free(my_file_info[file].name); + } + mysql_mutex_unlock(&THR_LOCK_open); + DBUG_RETURN(err); +} /* my_fclose */ + + + /* Make a stream out of a file handle */ + /* Name may be 0 */ + +FILE *my_fdopen(File Filedes, const char *name, int Flags, myf MyFlags) +{ + FILE *fd; + char type[5]; + DBUG_ENTER("my_fdopen"); + DBUG_PRINT("my",("fd: %d Flags: %d MyFlags: %lu", + Filedes, Flags, MyFlags)); + + make_ftype(type,Flags); +#ifdef _WIN32 + fd= my_win_fdopen(Filedes, type); +#else + fd= fdopen(Filedes, type); +#endif + if (!fd) + { + my_errno=errno; + if (MyFlags & (MY_FAE | MY_WME)) + my_error(EE_CANT_OPEN_STREAM, MYF(ME_BELL+ME_WAITTANG),errno); + } + else + { + mysql_mutex_lock(&THR_LOCK_open); + my_stream_opened++; + if ((uint) Filedes < (uint) my_file_limit) + { + if (my_file_info[Filedes].type != UNOPEN) + { + my_file_opened--; /* File is opened with my_open ! */ + } + else + { + my_file_info[Filedes].name= my_strdup(name,MyFlags); + } + my_file_info[Filedes].type = STREAM_BY_FDOPEN; + } + mysql_mutex_unlock(&THR_LOCK_open); + } + + DBUG_PRINT("exit",("stream: 0x%lx", (long) fd)); + DBUG_RETURN(fd); +} /* my_fdopen */ + + +/* + Make a fopen() typestring from a open() type bitmap + + SYNOPSIS + make_ftype() + to String for fopen() is stored here + flag Flag used by open() + + IMPLEMENTATION + This routine attempts to find the best possible match + between a numeric option and a string option that could be + fed to fopen. There is not a 1 to 1 mapping between the two. + + NOTE + On Unix, O_RDONLY is usually 0 + + MAPPING + r == O_RDONLY + w == O_WRONLY|O_TRUNC|O_CREAT + a == O_WRONLY|O_APPEND|O_CREAT + r+ == O_RDWR + w+ == O_RDWR|O_TRUNC|O_CREAT + a+ == O_RDWR|O_APPEND|O_CREAT +*/ + +static void make_ftype(register char * to, register int flag) +{ + /* check some possible invalid combinations */ + DBUG_ASSERT((flag & (O_TRUNC | O_APPEND)) != (O_TRUNC | O_APPEND)); + DBUG_ASSERT((flag & (O_WRONLY | O_RDWR)) != (O_WRONLY | O_RDWR)); + + if ((flag & (O_RDONLY|O_WRONLY)) == O_WRONLY) + *to++= (flag & O_APPEND) ? 'a' : 'w'; + else if (flag & O_RDWR) + { + /* Add '+' after theese */ + if (flag & (O_TRUNC | O_CREAT)) + *to++= 'w'; + else if (flag & O_APPEND) + *to++= 'a'; + else + *to++= 'r'; + *to++= '+'; + } + else + *to++= 'r'; + + if (flag & FILE_BINARY) + *to++='b'; + + if (O_CLOEXEC) + *to++= 'e'; + + *to='\0'; +} /* make_ftype */ diff --git a/pool/shard002/C/0060073_pwritev01.c b/pool/shard002/C/0060073_pwritev01.c new file mode 100644 index 0000000000000000000000000000000000000000..1cb35cb07e4078960ca05745a15b07ae9a5d5639 --- /dev/null +++ b/pool/shard002/C/0060073_pwritev01.c @@ -0,0 +1,146 @@ +/* +* Copyright (c) 2015 Fujitsu Ltd. +* Author: Xiao Yang +* +* This program is free software; you can redistribute it and/or modify it +* under the terms of version 2 of the GNU General Public License as +* published by the Free Software Foundation. +* +* This program is distributed in the hope that it would be useful, but +* WITHOUT ANY WARRANTY; without even the implied warranty of +* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. +* +* You should have received a copy of the GNU General Public License +* alone with this program. +*/ + +/* +* Test Name: pwritev01 +* +* Test Description: +* Testcase to check the basic functionality of the pwritev(2). +* pwritev(2) should succeed to write the expected content of data +* and after writing the file, the file offset is not changed. +*/ + +#include + +#include "test.h" +#include "pwritev.h" +#include "safe_macros.h" + +#define CHUNK 64 + +static char buf[CHUNK]; +static char initbuf[CHUNK * 2]; +static char preadbuf[CHUNK]; +static int fd; + +static struct iovec wr_iovec[] = { + {buf, CHUNK}, + {NULL, 0}, +}; + +static struct test_case_t { + int count; + off_t offset; + ssize_t size; +} tc[] = { + {1, 0, CHUNK}, + {2, 0, CHUNK}, + {1, CHUNK/2, CHUNK}, +}; + +void verify_pwritev(struct test_case_t *); +void setup(void); +void cleanup(void); + +char *TCID = "pwritev01"; +int TST_TOTAL = ARRAY_SIZE(tc); + +int main(int ac, char **av) +{ + int lc; + int i; + + tst_parse_opts(ac, av, NULL, NULL); + + setup(); + + for (lc = 0; TEST_LOOPING(lc); lc++) { + tst_count = 0; + + for (i = 0; i < TST_TOTAL; i++) + verify_pwritev(&tc[i]); + } + cleanup(); + tst_exit(); +} + +void verify_pwritev(struct test_case_t *tc) +{ + int i; + + SAFE_PWRITE(cleanup, 1, fd, initbuf, sizeof(initbuf), 0); + + SAFE_LSEEK(cleanup, fd, 0, SEEK_SET); + + TEST(pwritev(fd, wr_iovec, tc->count, tc->offset)); + if (TEST_RETURN < 0) { + tst_resm(TFAIL | TTERRNO, "Pwritev(2) failed"); + return; + } + + if (TEST_RETURN != tc->size) { + tst_resm(TFAIL, "Pwritev(2) write %li bytes, expected %li", + TEST_RETURN, tc->size); + return; + } + + if (SAFE_LSEEK(cleanup, fd, 0, SEEK_CUR) != 0) { + tst_resm(TFAIL, "Pwritev(2) has changed file offset"); + return; + } + + SAFE_PREAD(cleanup, 1, fd, preadbuf, tc->size, tc->offset); + + for (i = 0; i < tc->size; i++) { + if (preadbuf[i] != 0x61) + break; + } + + if (i != tc->size) { + tst_resm(TFAIL, "Buffer wrong at %i have %02x expected 61", + i, preadbuf[i]); + return; + } + + tst_resm(TPASS, "Pwritev(2) write %li bytes successfully " + "with content 'a' expectedly ", tc->size); +} + +void setup(void) +{ + if ((tst_kvercmp(2, 6, 30)) < 0) { + tst_brkm(TCONF, NULL, "This test can only run on kernels " + "that are 2.6.30 and higher"); + } + + tst_sig(NOFORK, DEF_HANDLER, cleanup); + + TEST_PAUSE; + + tst_tmpdir(); + + memset(&buf, 0x61, CHUNK); + + fd = SAFE_OPEN(cleanup, "file", O_RDWR | O_CREAT, 0644); +} + +void cleanup(void) +{ + if (fd > 0 && close(fd)) + tst_resm(TWARN | TERRNO, "Failed to close file"); + + tst_rmdir(); +} diff --git a/pool/shard002/C/0060094_local_variables_abuse.c b/pool/shard002/C/0060094_local_variables_abuse.c new file mode 100644 index 0000000000000000000000000000000000000000..d0b8d531d954c68a685e2921b9930b0ce0977563 --- /dev/null +++ b/pool/shard002/C/0060094_local_variables_abuse.c @@ -0,0 +1,36 @@ +#include + +void set_a(int x){ + int abc[3]; + abc[0] = x; +} + +void set_b(int x){ + int abc[3]; + abc[1] = x; +} + +void add_ab(int x){ + int abc[3]; + abc[2] = abc[0] + abc[1]; +} + +int get_c(int x){ + int abc[3]; + return abc[2]; +} + +void pabc(int x){ + int abc[3]; + printf("a=%d, b=%d, c=%d\n",abc[0],abc[1],abc[2]); +} + +void main(){ + pabc(0); + set_a(3); + pabc(0); + set_b(4); + pabc(0); + add_ab(0); + pabc(0); +} diff --git a/pool/shard002/C/0060111_dlarf.c b/pool/shard002/C/0060111_dlarf.c new file mode 100644 index 0000000000000000000000000000000000000000..2432bfd4f074844e94e65a13331ff6d61a037a84 --- /dev/null +++ b/pool/shard002/C/0060111_dlarf.c @@ -0,0 +1,132 @@ +#include "blaswrap.h" +#include "f2c.h" + +/* Subroutine */ int dlarf_(char *side, integer *m, integer *n, doublereal *v, + integer *incv, doublereal *tau, doublereal *c__, integer *ldc, + doublereal *work) +{ +/* -- LAPACK auxiliary routine (version 3.0) -- + Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., + Courant Institute, Argonne National Lab, and Rice University + February 29, 1992 + + + Purpose + ======= + + DLARF applies a real elementary reflector H to a real m by n matrix + C, from either the left or the right. H is represented in the form + + H = I - tau * v * v' + + where tau is a real scalar and v is a real vector. + + If tau = 0, then H is taken to be the unit matrix. + + Arguments + ========= + + SIDE (input) CHARACTER*1 + = 'L': form H * C + = 'R': form C * H + + M (input) INTEGER + The number of rows of the matrix C. + + N (input) INTEGER + The number of columns of the matrix C. + + V (input) DOUBLE PRECISION array, dimension + (1 + (M-1)*abs(INCV)) if SIDE = 'L' + or (1 + (N-1)*abs(INCV)) if SIDE = 'R' + The vector v in the representation of H. V is not used if + TAU = 0. + + INCV (input) INTEGER + The increment between elements of v. INCV <> 0. + + TAU (input) DOUBLE PRECISION + The value tau in the representation of H. + + C (input/output) DOUBLE PRECISION array, dimension (LDC,N) + On entry, the m by n matrix C. + On exit, C is overwritten by the matrix H * C if SIDE = 'L', + or C * H if SIDE = 'R'. + + LDC (input) INTEGER + The leading dimension of the array C. LDC >= max(1,M). + + WORK (workspace) DOUBLE PRECISION array, dimension + (N) if SIDE = 'L' + or (M) if SIDE = 'R' + + ===================================================================== + + + Parameter adjustments */ + /* Table of constant values */ + static doublereal c_b4 = 1.; + static doublereal c_b5 = 0.; + static integer c__1 = 1; + + /* System generated locals */ + integer c_dim1, c_offset; + doublereal d__1; + /* Local variables */ + extern /* Subroutine */ int dger_(integer *, integer *, doublereal *, + doublereal *, integer *, doublereal *, integer *, doublereal *, + integer *); + extern logical lsame_(char *, char *); + extern /* Subroutine */ int dgemv_(char *, integer *, integer *, + doublereal *, doublereal *, integer *, doublereal *, integer *, + doublereal *, doublereal *, integer *); + + + --v; + c_dim1 = *ldc; + c_offset = 1 + c_dim1 * 1; + c__ -= c_offset; + --work; + + /* Function Body */ + if (lsame_(side, "L")) { + +/* Form H * C */ + + if (*tau != 0.) { + +/* w := C' * v */ + + dgemv_("Transpose", m, n, &c_b4, &c__[c_offset], ldc, &v[1], incv, + &c_b5, &work[1], &c__1); + +/* C := C - v * w' */ + + d__1 = -(*tau); + dger_(m, n, &d__1, &v[1], incv, &work[1], &c__1, &c__[c_offset], + ldc); + } + } else { + +/* Form C * H */ + + if (*tau != 0.) { + +/* w := C * v */ + + dgemv_("No transpose", m, n, &c_b4, &c__[c_offset], ldc, &v[1], + incv, &c_b5, &work[1], &c__1); + +/* C := C - w * v' */ + + d__1 = -(*tau); + dger_(m, n, &d__1, &work[1], &c__1, &v[1], incv, &c__[c_offset], + ldc); + } + } + return 0; + +/* End of DLARF */ + +} /* dlarf_ */ + diff --git a/pool/shard002/C/0060126_test_div_algo.c b/pool/shard002/C/0060126_test_div_algo.c new file mode 100644 index 0000000000000000000000000000000000000000..111ad8baedab2b70d778336540e6062c18abc863 --- /dev/null +++ b/pool/shard002/C/0060126_test_div_algo.c @@ -0,0 +1,114 @@ +#include +#include +#include "bn.h" + +/* + +Division algorithms using bitwise operations + +To showcase different methods for implementing division + +*/ + + +static int divide(int dividend, int divisor) +{ + int current = 1; + int denom = divisor; + // This step is required to find the biggest current number which can be + // divided with the number safely. + while (denom <= dividend) { + current <<= 1; + denom <<= 1; + } + // Since we may have increased the denomitor more than dividend + // thus we need to go back one shift, and same would apply for current. + denom >>= 1; + current >>= 1; + int answer = 0; + // Now deal with the smaller number. + while (current != 0) + { + if (dividend >= denom) + { + dividend -= denom; + answer |= current; + } + current >>= 1; + denom >>= 1; + } + return answer; +} + +void divide2(unsigned dividend, unsigned divisor, unsigned* quotient, unsigned* remainder) +{ + unsigned t, num_bits; + unsigned q, bit, d; + unsigned i; + + *remainder = 0; + *quotient = 0; + + if (divisor == 0) + return; + + if (divisor > dividend) { + *remainder = dividend; + return; + } + + if (divisor == dividend) { + *quotient = 1; + return; + } + + num_bits = 32; + + while ((*remainder) < divisor) { + bit = (dividend & 0x80000000) >> 31; + *remainder = ((*remainder) << 1) | bit; + d = dividend; + dividend = dividend << 1; + num_bits--; + } + + /* The loop, above, always goes one iteration too far. + To avoid inserting an "if" statement inside the loop + the last iteration is simply reversed. */ + dividend = d; + *remainder = (*remainder) >> 1; + num_bits++; + + for (i = 0; i < num_bits; i++) { + bit = (dividend & 0x80000000) >> 31; + *remainder = ((*remainder) << 1) | bit; + t = (*remainder) - divisor; + q = !((t & 0x80000000) >> 31); + dividend = dividend << 1; + *quotient = ((*quotient) << 1) | q; + if (q) { + *remainder = t; + } + } +} /* unsigned_divide */ + +int main() +{ + unsigned a,b,q,r; + + a = 255; + b = 8; + + /* + a div b = q [with remainder r] + */ + + printf("1: %d / %d = %d \n", a,b,divide(a, b)); + divide2(a,b,&q, &r); + printf("2: %d / %d = %d (%d) \n", a,b,q,r); + + + return 0; +} + + diff --git a/pool/shard002/C/0060128_library.c b/pool/shard002/C/0060128_library.c new file mode 100644 index 0000000000000000000000000000000000000000..989e0ca18b8da36e063e3555856ca3ecda3fe9cc --- /dev/null +++ b/pool/shard002/C/0060128_library.c @@ -0,0 +1,154 @@ +/*========================================================= + Copyright © 2008 Broadcom Europe Limited. All rights reserved. + + Project : VMCS Host Apps + Module : Platform framework test application + File : $Id: $ + + FILE DESCRIPTION: + Library tests for platform framework test application + =========================================================*/ + +#include /* for strcpy/cmp, etc. */ +#include +#include +#include "interface/vcos/vcos.h" + +#ifdef LATER + +int time_test() +{ + int passed = 1; + int32_t then, now, diff; + + then = platform_get_ticks(); + platform_sleep(5); + now = platform_get_ticks(); + + diff = now - then; + if(diff < 4 || diff > 20) + passed = 0; + + then = platform_get_ticks(); + + diff = then - now; + if(diff < 0 || diff > 5) + passed = 0; + + platform_sleep(50); + now = platform_get_ticks(); + + diff = now - then; + if(diff < 40 || diff > 70) + passed = 0; + + return passed; +} +#endif + +static int malloc_test() +{ + int passed = 1; + int size; + + for(size = 1; size < 4096; size = (size*3)+7) + { + uint8_t *mem = vcos_malloc(size, "test"); + + if(!mem) + passed = 0; + else + { + int i; + for(i=0; i +#include +#include + +#include +#include + +int +main(int argc, char *argv[]) +{ + XtAppContext app; + Widget shell, w; + void *before; + void *after; + int iter = 0; + int diff = 0; + int total = 0; + + shell = XtAppInitialize(&app, "Test", NULL, 0, + &argc, argv, NULL, NULL, 0); + while (iter < 1000) + { + before = sbrk((ptrdiff_t) 0); + w = XtCreateWidget("name", xmGrabShellWidgetClass, shell, NULL, 0); + XtDestroyWidget(w); + after = sbrk((ptrdiff_t) 0); + if ((int)((char *)after - (char *)before) > 0) + { + if (iter != 0) + { + /* printf("%i %i %p %i\n", iter, iter - diff, after - + before, (after - before) / (iter - diff)); */ + total += (int)((char *)after - (char *)before); + } + diff = iter; + } + iter++; + } + printf("leaking %i bytes per Create/Destroy\n", total / iter); + exit((int)(total / iter)); +} diff --git a/pool/shard002/C/0060166_test-gnc-date.c b/pool/shard002/C/0060166_test-gnc-date.c new file mode 100644 index 0000000000000000000000000000000000000000..14834cd3804d0d9e2f69d8b854d5929a8a0bf78b --- /dev/null +++ b/pool/shard002/C/0060166_test-gnc-date.c @@ -0,0 +1,68 @@ + +/******************************************************************** + * test-gnc-date.c: GLib g_test test suite for gnc-date.h functions * + * Copyright 2011 Christian Stimming * + * Copyright 2011 John Ralls * + * * + * This program is free software; you can redistribute it and/or * + * modify it under the terms of the GNU General Public License as * + * published by the Free Software Foundation; either version 2 of * + * the License, or (at your option) any later version. * + * * + * This program is distributed in the hope that it will be useful, * + * but WITHOUT ANY WARRANTY; without even the implied warranty of * + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * + * GNU General Public License for more details. * + * * + * You should have received a copy of the GNU General Public License* + * along with this program; if not, contact: * + * * + * Free Software Foundation Voice: +1-617-542-5942 * + * 51 Franklin Street, Fifth Floor Fax: +1-617-542-2652 * + * Boston, MA 02110-1301, USA gnu@gnu.org * +\********************************************************************/ +#include "config.h" +#include +#include +#include "qof.h" +#include "qofbook-p.h" +#include "qofbookslots.h" +#include "test-stuff.h" + +static const gchar *suitename = "/qof/gnc-date"; +void test_suite_gnc_date ( void ); + +typedef struct +{ +} Fixture; + +static void +setup( Fixture *fixture, gconstpointer pData ) +{ +} + +static void +teardown( Fixture *fixture, gconstpointer pData ) +{ +} + +static void +test_gnc_date_dmy2gdate( void ) +{ + GDate *p_gdate; + GDate gdate; + p_gdate = g_date_new_dmy(1, 2, 2011); + gdate = gnc_dmy2gdate(1, 2, 2011); + g_assert(g_date_compare(&gdate, p_gdate) == 0); + gdate = gnc_dmy2gdate(2, 2, 2011); + g_assert(g_date_compare(&gdate, p_gdate) > 0); + g_date_subtract_days(&gdate, 1); + g_assert(g_date_compare(&gdate, p_gdate) == 0); + g_date_free(p_gdate); +} + +void +test_suite_gnc_date ( void ) +{ + GNC_TEST_ADD_FUNC( suitename, "dmy2gdate", test_gnc_date_dmy2gdate); +} diff --git a/pool/shard002/C/0060170_t-dot.c b/pool/shard002/C/0060170_t-dot.c new file mode 100644 index 0000000000000000000000000000000000000000..c214cadb392e7eafcb53dfb756d98d2c837e0b98 --- /dev/null +++ b/pool/shard002/C/0060170_t-dot.c @@ -0,0 +1,65 @@ +/* + Copyright (C) 2014 Abhinav Baid + + This file is part of FLINT. + + FLINT 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. See . +*/ + +#include +#include +#include +#include "flint.h" +#include "d_vec.h" +#include "ulong_extras.h" + +#define D_VEC_SP_EPS (1e-14) + +int +main(void) +{ + int i, result; + FLINT_TEST_INIT(state); + + flint_printf("dot...."); + fflush(stdout); + + /* check sum of scalar products of parts of vectors is equal to the + scalar product of vectors */ + for (i = 0; i < 10000 * flint_test_multiplier(); i++) + { + double *a, *b; + double res1, res2, res3; + slong len = n_randint(state, 100); + if (!len) + continue; + + a = _d_vec_init(len); + b = _d_vec_init(len); + _d_vec_randtest(a, state, len, 0, 0); + _d_vec_randtest(b, state, len, 0, 0); + + res1 = _d_vec_dot(a, b, len - 1); + res2 = _d_vec_dot(a + len - 1, b + len - 1, 1); + res3 = _d_vec_dot(a, b, len); + + result = fabs(res1 + res2 - res3) < D_VEC_SP_EPS; + if (!result) + { + flint_printf("FAIL:\n"); + printf("%g\n", fabs(res1 + res2 - res3)); + abort(); + } + + _d_vec_clear(a); + _d_vec_clear(b); + } + + FLINT_TEST_CLEANUP(state); + + flint_printf("PASS\n"); + return 0; +} diff --git a/pool/shard002/C/0060174_udp_listeningpoint.c b/pool/shard002/C/0060174_udp_listeningpoint.c new file mode 100644 index 0000000000000000000000000000000000000000..a71850d4f9146844bd74f339fab3e749de6fa505 --- /dev/null +++ b/pool/shard002/C/0060174_udp_listeningpoint.c @@ -0,0 +1,188 @@ +/* + belle-sip - SIP (RFC3261) library. + Copyright (C) 2010 Belledonne Communications SARL + + 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 "belle_sip_internal.h" + +struct belle_sip_udp_listening_point{ + belle_sip_listening_point_t base; + belle_sip_socket_t sock; + belle_sip_source_t *source; +}; + + + +static void belle_sip_udp_listening_point_uninit(belle_sip_udp_listening_point_t *lp){ + if (lp->sock!=-1) close_socket(lp->sock); + if (lp->source) { + belle_sip_main_loop_remove_source(lp->base.stack->ml,lp->source); + belle_sip_object_unref(lp->source); + } +} + +static belle_sip_channel_t *udp_create_channel(belle_sip_listening_point_t *lp, const belle_sip_hop_t *hop){ + belle_sip_channel_t *chan=belle_sip_channel_new_udp(lp->stack + ,((belle_sip_udp_listening_point_t*)lp)->sock + ,belle_sip_uri_get_host(lp->listening_uri) + ,belle_sip_uri_get_port(lp->listening_uri) + ,hop->host + ,hop->port); + return chan; +} + +BELLE_SIP_DECLARE_NO_IMPLEMENTED_INTERFACES(belle_sip_udp_listening_point_t); +BELLE_SIP_INSTANCIATE_CUSTOM_VPTR(belle_sip_udp_listening_point_t)={ + { + { + BELLE_SIP_VPTR_INIT(belle_sip_udp_listening_point_t, belle_sip_listening_point_t,TRUE), + (belle_sip_object_destroy_t)belle_sip_udp_listening_point_uninit, + NULL, + NULL + }, + "UDP", + udp_create_channel + } +}; + + +static belle_sip_socket_t create_udp_socket(const char *addr, int port, int *family){ + struct addrinfo hints={0}; + struct addrinfo *res=NULL; + int err; + belle_sip_socket_t sock; + char portnum[10]; + int optval=1; + + snprintf(portnum,sizeof(portnum),"%i",port); + hints.ai_family=AF_UNSPEC; + hints.ai_socktype=SOCK_DGRAM; + hints.ai_protocol=IPPROTO_UDP; + hints.ai_flags=AI_NUMERICSERV; + err=getaddrinfo(addr,portnum,&hints,&res); + if (err!=0){ + belle_sip_error("getaddrinfo() failed for %s port %i: %s",addr,port,gai_strerror(err)); + return -1; + } + *family=res->ai_family; + sock=socket(res->ai_family,res->ai_socktype,res->ai_protocol); + if (sock==-1){ + belle_sip_error("Cannot create UDP socket: %s",belle_sip_get_socket_error_string()); + freeaddrinfo(res); + return -1; + } + err = setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, + (char*)&optval, sizeof (optval)); + if (err == -1){ + belle_sip_warning ("Fail to set SIP/UDP address reusable: %s.", belle_sip_get_socket_error_string()); + } + + err=bind(sock,res->ai_addr,res->ai_addrlen); + if (err==-1){ + belle_sip_error("udp bind() failed for %s port %i: %s",addr,port,belle_sip_get_socket_error_string()); + close_socket(sock); + freeaddrinfo(res); + return -1; + } + freeaddrinfo(res); + return sock; +} + +static int on_udp_data(belle_sip_udp_listening_point_t *lp, unsigned int events); + +static int belle_sip_udp_listening_point_init_socket(belle_sip_udp_listening_point_t *lp){ + lp->sock=create_udp_socket(belle_sip_uri_get_host(((belle_sip_listening_point_t*)lp)->listening_uri) + ,belle_sip_uri_get_port(((belle_sip_listening_point_t*)lp)->listening_uri),&lp->base.ai_family); + if (lp->sock==(belle_sip_socket_t)-1){ + return -1; + } + if (lp->base.stack->dscp) + belle_sip_socket_set_dscp(lp->sock,lp->base.ai_family,lp->base.stack->dscp); + lp->source=belle_sip_socket_source_new((belle_sip_source_func_t)on_udp_data,lp,lp->sock,BELLE_SIP_EVENT_READ,-1); + belle_sip_main_loop_add_source(((belle_sip_listening_point_t*)lp)->stack->ml,lp->source); + return 0; +} + +static void belle_sip_udp_listening_point_init(belle_sip_udp_listening_point_t *lp, belle_sip_stack_t *s, const char *ipaddress, int port) { + belle_sip_listening_point_init((belle_sip_listening_point_t*)lp,s,ipaddress,port); + belle_sip_udp_listening_point_init_socket(lp); +} + +/*peek data from the master socket to see where it comes from, and dispatch to matching channel. + * If the channel does not exist, create it */ +static int on_udp_data(belle_sip_udp_listening_point_t *lp, unsigned int events){ + int err; + unsigned char buf[4096]; + struct sockaddr_storage addr; + socklen_t addrlen=sizeof(addr); + + if (events & BELLE_SIP_EVENT_READ){ + belle_sip_debug("udp_listening_point: data to read."); + err=recvfrom(lp->sock,(char*)buf,sizeof(buf),MSG_PEEK,(struct sockaddr*)&addr,&addrlen); + if (err==-1){ + char *tmp=belle_sip_object_to_string((belle_sip_object_t*) ((belle_sip_listening_point_t*)lp)->listening_uri); + belle_sip_error("udp_listening_point: recvfrom() failed on [%s], : [%s] reopening server socket" + ,tmp + ,belle_sip_get_socket_error_string()); + belle_sip_free(tmp); + belle_sip_udp_listening_point_uninit(lp); + /*clean all udp channels that are actually sharing the server socket with the listening points*/ + belle_sip_listening_point_clean_channels((belle_sip_listening_point_t*)lp); + belle_sip_udp_listening_point_init_socket(lp); + }else{ + belle_sip_channel_t *chan; + struct addrinfo ai={0}; + belle_sip_address_remove_v4_mapping((struct sockaddr*)&addr,(struct sockaddr*)&addr,&addrlen); + ai.ai_family=addr.ss_family; + ai.ai_addr=(struct sockaddr*)&addr; + ai.ai_addrlen=addrlen; + chan=_belle_sip_listening_point_get_channel((belle_sip_listening_point_t*)lp,NULL,&ai); + if (chan==NULL){ + /*TODO: should rather create the channel with real local ip and port and not just 0.0.0.0"*/ + chan=belle_sip_channel_new_udp_with_addr(lp->base.stack + ,lp->sock + ,belle_sip_uri_get_host(lp->base.listening_uri) + ,belle_sip_uri_get_port(lp->base.listening_uri) + ,&ai); + if (chan!=NULL){ + belle_sip_message("udp_listening_point: new channel created to %s:%i",chan->peer_name,chan->peer_port); + chan->lp=(belle_sip_listening_point_t*)lp; /*FIXME, exactly the same code as for channel creation from provider. might be good to factorize*/ + belle_sip_listening_point_add_channel((belle_sip_listening_point_t*)lp,chan); + } + } + if (chan){ + /*notify the channel*/ + belle_sip_debug("Notifying udp channel, local [%s:%i] remote [%s:%i]" + ,chan->local_ip + ,chan->local_port + ,chan->peer_name + ,chan->peer_port); + belle_sip_channel_process_data(chan,events); + } + } + } + return BELLE_SIP_CONTINUE; +} + +belle_sip_listening_point_t * belle_sip_udp_listening_point_new(belle_sip_stack_t *s, const char *ipaddress, int port){ + belle_sip_udp_listening_point_t *lp=belle_sip_object_new(belle_sip_udp_listening_point_t); + belle_sip_udp_listening_point_init(lp,s,ipaddress, port); + if (lp->sock==(belle_sip_socket_t)-1){ + belle_sip_object_unref(lp); + return NULL; + } + return (belle_sip_listening_point_t*)lp; +} + diff --git a/pool/shard002/C/0060175_mech-login.c b/pool/shard002/C/0060175_mech-login.c new file mode 100644 index 0000000000000000000000000000000000000000..f1f0f2e70a472c5fb0afdcac83a7ea339dc1ddd5 --- /dev/null +++ b/pool/shard002/C/0060175_mech-login.c @@ -0,0 +1,75 @@ +/* Copyright (c) 2013 Dovecot authors, see the included COPYING file */ + +#include "lib.h" +#include "str.h" +#include "dsasl-client-private.h" + +enum login_state { + STATE_INIT = 0, + STATE_USER, + STATE_PASS +}; + +struct login_dsasl_client { + struct dsasl_client client; + enum login_state state; +}; + +static int +mech_login_input(struct dsasl_client *_client, + const unsigned char *input ATTR_UNUSED, + unsigned int input_len ATTR_UNUSED, + const char **error_r) +{ + struct login_dsasl_client *client = + (struct login_dsasl_client *)_client; + + if (client->state == STATE_PASS) { + *error_r = "Server didn't finish authentication"; + return -1; + } + client->state++; + return 0; +} + +static int +mech_login_output(struct dsasl_client *_client, + const unsigned char **output_r, unsigned int *output_len_r, + const char **error_r) +{ + struct login_dsasl_client *client = + (struct login_dsasl_client *)_client; + + if (_client->set.authid == NULL) { + *error_r = "authid not set"; + return -1; + } + if (_client->password == NULL) { + *error_r = "password not set"; + return -1; + } + + switch (client->state) { + case STATE_INIT: + *output_r = &uchar_nul; + *output_len_r = 0; + return 0; + case STATE_USER: + *output_r = (const unsigned char *)_client->set.authid; + *output_len_r = strlen(_client->set.authid); + return 0; + case STATE_PASS: + *output_r = (const unsigned char *)_client->set.password; + *output_len_r = strlen(_client->set.password); + return 0; + } + i_unreached(); +} + +const struct dsasl_client_mech dsasl_client_mech_login = { + .name = "LOGIN", + .struct_size = sizeof(struct login_dsasl_client), + + .input = mech_login_input, + .output = mech_login_output +}; diff --git a/pool/shard002/C/0060193_platform_nc.c b/pool/shard002/C/0060193_platform_nc.c new file mode 100644 index 0000000000000000000000000000000000000000..c042390d1255c2a739bc99af8dc1b8668f25e275 --- /dev/null +++ b/pool/shard002/C/0060193_platform_nc.c @@ -0,0 +1,75 @@ +/* + * platform_nc.c: Intel MID CTP NC platform initialization file + * + * Copyright (C) 2013 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. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * Author: Zhang Dongsheng + * + */ + +#include + +#define NC_VNN_VID_PORT 0x81 +#define NC_VNN_VID_REG 0x0d + +#define NC_VNN_VID_MASK 0x7f + +#define PCI_DEVICE_ID_CTP_NC 0x08c0 + +/* + * Customer requested to log the Voltage Identifier for the CTP's Vnn. + * Add the pci quirks to print it. + */ +static void __devinit nc_pci_early_quirk(struct pci_dev *pci_dev) +{ + int ret; + u32 cmd, val; + int port, reg; + + port = NC_VNN_VID_PORT; + reg = NC_VNN_VID_REG; + + cmd = (0x10 << 24) | (port << 16) | (reg << 8) | (0xf0); + ret = pci_write_config_dword(pci_dev, 0xd0, cmd); + if (ret) { + pr_err("%s write pci config 0xd0 with 0x%x failed\n", __func__, + cmd); + goto exit; + } + + val = 0; + ret = pci_read_config_dword(pci_dev, 0xd4, &val); + if (ret) { + pr_err("%s read pci config 0xd4 failed\n", __func__); + goto exit; + } + + pr_info("Port:0x%x Reg:0x%x value:0x%x", port, reg, val); + pr_info("VNN VID: [0x%x]\n", val & NC_VNN_VID_MASK); + + return; + +exit: + pr_err("VNN VID: read failed"); + +} + +DECLARE_PCI_FIXUP_EARLY(PCI_VENDOR_ID_INTEL, PCI_DEVICE_ID_CTP_NC, + nc_pci_early_quirk); diff --git a/pool/shard002/C/0060200_mtdram.c b/pool/shard002/C/0060200_mtdram.c new file mode 100644 index 0000000000000000000000000000000000000000..d1eaafdab50d9899477ecad8e3b91f6f1cc52073 --- /dev/null +++ b/pool/shard002/C/0060200_mtdram.c @@ -0,0 +1,122 @@ +/* + * Author: Sebastian Block + * Copyright (c) 2014 + * + * Some parts are based on mtdram.c found in Linux kernel + * by Alexander Larsson + * and Joern Engel . + * + * This code 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 mtdram_priv_data { + struct mtd_info mtd; + void *base; +}; + +static int ram_erase(struct mtd_info *mtd, struct erase_info *instr) +{ + memset((char *)mtd->priv + instr->addr, 0xff, instr->len); + instr->state = MTD_ERASE_DONE; + mtd_erase_callback(instr); + return 0; +} + +static int ram_write(struct mtd_info *mtd, loff_t to, size_t len, size_t *retlen, const u_char *buf) +{ + memcpy((char*)mtd->priv + to, buf, len); + *retlen = len; + return 0; +} + +static int ram_read(struct mtd_info *mtd, loff_t from, size_t len, size_t *retlen, u_char *buf) +{ + memcpy(buf, mtd->priv + from, len); + *retlen = len; + return 0; +} + +static int mtdram_probe(struct device_d *dev) +{ + void __iomem *base; + int device_id; + struct mtd_info *mtd; + struct resource *res; + loff_t size; + int ret = 0; + + mtd = xzalloc(sizeof(struct mtd_info)); + + device_id = DEVICE_ID_SINGLE; + if (dev->device_node) { + const char *alias = of_alias_get(dev->device_node); + if (alias) + mtd->name = xstrdup(alias); + } + + if (!mtd->name) { + device_id = DEVICE_ID_DYNAMIC; + mtd->name = "mtdram"; + } + + base = dev_request_mem_region(dev, 0); + if (!base) { + ret = -EBUSY; + goto nobase; + } + + res = dev_get_resource(dev, IORESOURCE_MEM, 0); + size = (unsigned long) resource_size(res); + mtd->priv = base; + + mtd->type = MTD_RAM; + mtd->writesize = 1; + mtd->writebufsize = 64; + mtd->flags = MTD_CAP_RAM; + mtd->size = size; + + mtd->read = ram_read; + mtd->write = ram_write; + mtd->erase = ram_erase; + mtd->erasesize = 1; + + mtd->parent = dev; + + ret = add_mtd_device(mtd, mtd->name, device_id); + return ret; + +nobase: + kfree(mtd); + + return ret; +} + +static __maybe_unused struct of_device_id mtdram_dt_ids[] = { + { + .compatible = "mtd-ram", + }, { + /* sentinel */ + } +}; + +static struct driver_d mtdram_driver = { + .name = "mtdram", + .probe = mtdram_probe, + .of_compatible = DRV_OF_COMPAT(mtdram_dt_ids), +}; +device_platform_driver(mtdram_driver); + +MODULE_LICENSE("GPL"); +MODULE_AUTHOR("Sebastian Block"); +MODULE_DESCRIPTION("MTD RAM driver for NVRAMs"); diff --git a/pool/shard002/C/0060203_ascii.c b/pool/shard002/C/0060203_ascii.c new file mode 100644 index 0000000000000000000000000000000000000000..de14de0dd04aad07facb8439df1b73a6a012a923 --- /dev/null +++ b/pool/shard002/C/0060203_ascii.c @@ -0,0 +1,39 @@ +#include + +int printhead() { printf("

Tabla ASCII

\n\n"); } +int printtail() { printf("\n
\n
\n"); } +int printrowbegin() { printf("\n"); } +int printrowend() { printf("\n"); } +int printcell(int c) { + char *bg; + + bg = "#EEEEEE"; + if('A' <= c && c <= 'Z') bg = "#EEFF00"; + if('a' <= c && c <= 'z') bg = "#FFCC00"; + if('0' <= c && c <= '9') bg = "#00EEFF"; + printf("%d%c ", bg, c, bg, c); +} + +main() +{ + int i,j; + int c = 32; + int J = 8; // cols + int I; + + I = (127-31)/J; // rows + + printhead(); + for(i=0; i +#include "resizepopup.h" +#include +#include +#include + +struct _MetaResizePopup +{ + GtkWidget *size_window; + GtkWidget *size_label; + Display *display; + int screen_number; + + int vertical_size; + int horizontal_size; + + gboolean showing; + + MetaRectangle rect; +}; + +MetaResizePopup* +meta_ui_resize_popup_new (Display *display, + int screen_number) +{ + MetaResizePopup *popup; + + popup = g_new0 (MetaResizePopup, 1); + + popup->display = display; + popup->screen_number = screen_number; + + return popup; +} + +void +meta_ui_resize_popup_free (MetaResizePopup *popup) +{ + g_return_if_fail (popup != NULL); + + if (popup->size_window) + gtk_widget_destroy (popup->size_window); + + g_free (popup); +} + +static gboolean +size_window_draw (GtkWidget *widget, + cairo_t *cr, + MetaResizePopup *popup) +{ + GtkStyleContext *context; + gint width, height; + + context = gtk_widget_get_style_context (widget); + width = gtk_widget_get_allocated_width (widget); + height = gtk_widget_get_allocated_height (widget); + + gtk_render_background (context, cr, 0, 0, width, height); + gtk_render_frame (context, cr, 0, 0, width, height); + + return FALSE; +} + +static void +ensure_size_window (MetaResizePopup *popup) +{ + GdkVisual *visual; + GdkScreen *screen; + + if (popup->size_window) + return; + + popup->size_window = gtk_window_new (GTK_WINDOW_POPUP); + screen = gdk_display_get_screen (gdk_x11_lookup_xdisplay (popup->display), + popup->screen_number); + visual = gdk_screen_get_rgba_visual (screen); + + gtk_window_set_screen (GTK_WINDOW (popup->size_window), screen); + if (visual != NULL) + gtk_widget_set_visual (popup->size_window, visual); + + gtk_window_set_type_hint (GTK_WINDOW (popup->size_window), + GDK_WINDOW_TYPE_HINT_TOOLTIP); + gtk_window_set_resizable (GTK_WINDOW (popup->size_window), FALSE); + + gtk_widget_set_app_paintable (popup->size_window, TRUE); + gtk_style_context_add_class (gtk_widget_get_style_context (popup->size_window), + GTK_STYLE_CLASS_TOOLTIP); + g_signal_connect (popup->size_window, "draw", + G_CALLBACK (size_window_draw), popup); + + popup->size_label = gtk_label_new (""); + g_object_set (popup->size_label, "margin", 6, NULL); + + gtk_container_add (GTK_CONTAINER (popup->size_window), popup->size_label); + + gtk_widget_show (popup->size_label); +} + +static void +update_size_window (MetaResizePopup *popup) +{ + char *str; + int x, y; + int width, height; + + g_return_if_fail (popup->size_window != NULL); + + /* Translators: This represents the size of a window. The first number is + * the width of the window and the second is the height. + */ + str = g_strdup_printf (_("%d x %d"), + popup->horizontal_size, + popup->vertical_size); + + gtk_label_set_text (GTK_LABEL (popup->size_label), str); + + g_free (str); + + gtk_window_get_size (GTK_WINDOW (popup->size_window), &width, &height); + + x = popup->rect.x + (popup->rect.width - width) / 2; + y = popup->rect.y + (popup->rect.height - height) / 2; + + if (gtk_widget_get_realized (popup->size_window)) + { + /* using move_resize to avoid jumpiness */ + gdk_window_move_resize (gtk_widget_get_window (popup->size_window), + x, y, + width, height); + } + else + { + gtk_window_move (GTK_WINDOW (popup->size_window), + x, y); + } +} + +static void +sync_showing (MetaResizePopup *popup) +{ + if (popup->showing) + { + if (popup->size_window) + gtk_widget_show (popup->size_window); + + if (popup->size_window && gtk_widget_get_realized (popup->size_window)) + gdk_window_raise (gtk_widget_get_window (popup->size_window)); + } + else + { + if (popup->size_window) + gtk_widget_hide (popup->size_window); + } +} + +void +meta_ui_resize_popup_set (MetaResizePopup *popup, + MetaRectangle rect, + int base_width, + int base_height, + int width_inc, + int height_inc) +{ + gboolean need_update_size; + int display_w, display_h; + + g_return_if_fail (popup != NULL); + + need_update_size = FALSE; + + display_w = rect.width - base_width; + if (width_inc > 0) + display_w /= width_inc; + + display_h = rect.height - base_height; + if (height_inc > 0) + display_h /= height_inc; + + if (!meta_rectangle_equal(&popup->rect, &rect) || + display_w != popup->horizontal_size || + display_h != popup->vertical_size) + need_update_size = TRUE; + + popup->rect = rect; + popup->vertical_size = display_h; + popup->horizontal_size = display_w; + + if (need_update_size) + { + ensure_size_window (popup); + update_size_window (popup); + } + + sync_showing (popup); +} + +void +meta_ui_resize_popup_set_showing (MetaResizePopup *popup, + gboolean showing) +{ + g_return_if_fail (popup != NULL); + + if (showing == popup->showing) + return; + + popup->showing = !!showing; + + if (popup->showing) + { + ensure_size_window (popup); + update_size_window (popup); + } + + sync_showing (popup); +} diff --git a/pool/shard002/C/0060213_PLCrashFrameWalker.c b/pool/shard002/C/0060213_PLCrashFrameWalker.c new file mode 100644 index 0000000000000000000000000000000000000000..6f0a5b73a24179f7c7f120b1bf3751bf097b9389 --- /dev/null +++ b/pool/shard002/C/0060213_PLCrashFrameWalker.c @@ -0,0 +1,247 @@ +/* + * Author: Landon Fuller + * + * Copyright (c) 2008-2009 Plausible Labs Cooperative, Inc. + * All rights reserved. + * + * 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 "PLCrashFrameWalker.h" +#include "PLCrashAsync.h" + +#include "PLCrashFrameStackUnwind.h" +#include "PLCrashFrameCompactUnwind.h" +#include "PLCrashFrameDWARFUnwind.h" + +#include "PLCrashFeatureConfig.h" + +#pragma mark Error Handling + +/** + * Return an error description for the given plframe_error_t. + */ +const char *plframe_strerror (plframe_error_t error) { + switch (error) { + case PLFRAME_ESUCCESS: + return "No error"; + case PLFRAME_EUNKNOWN: + return "Unknown error"; + case PLFRAME_ENOFRAME: + return "No frames are available"; + case PLFRAME_EBADFRAME: + return "Corrupted frame"; + case PLFRAME_ENOTSUP: + return "Operation not supported"; + case PLFRAME_EINVAL: + return "Invalid argument"; + case PLFRAME_INTERNAL: + return "Internal error"; + case PLFRAME_EBADREG: + return "Invalid register"; + } + + /* Should be unreachable */ + return "Unhandled error code"; +} + +#pragma mark Frame Walking + +/** + * @internal + * Shared initializer. Assumes that the initial frame has all registers available. + * + * @param cursor Cursor record to be initialized. + * @param task The task from which @a uap was derived. All memory will be mapped from this task. + * @param image_list The task's current image list. This is a borrowed reference, and must remain valid for the lifetime of the cursor. + */ +static void plframe_cursor_internal_init (plframe_cursor_t *cursor, task_t task, plcrash_async_image_list_t *image_list) { + cursor->depth = 0; + cursor->task = task; + cursor->image_list = image_list; + mach_port_mod_refs(mach_task_self(), cursor->task, MACH_PORT_RIGHT_SEND, 1); +} + +/** + * Initialize the frame cursor using the provided thread state. + * + * @param cursor Cursor record to be initialized. + * @param task The task from which @a uap was derived. All memory will be mapped from this task. + * @param thread_state The thread state to use for cursor initialization. + * @param image_list The task's current image list. This is a borrowed reference, and must remain valid for the lifetime of the cursor. + * + * @return Returns PLFRAME_ESUCCESS on success, or standard plframe_error_t code if an error occurs. + * + * @warning Callers must call plframe_cursor_free() on @a cursor to free any associated resources, even if initialization + * fails. + */ +plframe_error_t plframe_cursor_init (plframe_cursor_t *cursor, task_t task, plcrash_async_thread_state_t *thread_state, plcrash_async_image_list_t *image_list) { + plframe_cursor_internal_init(cursor, task, image_list); + + plcrash_async_memcpy(&cursor->frame.thread_state, thread_state, sizeof(cursor->frame.thread_state)); + + return PLFRAME_ESUCCESS; +} + +/** + * Initialize the frame cursor by acquiring state from the provided mach thread. If the thread is not suspended, + * the fetched state may be inconsistent. + * + * @param cursor Cursor record to be initialized. + * @param task The task in which @a thread is running. All memory will be mapped from this task. + * @param thread The thread to use for cursor initialization. + * @param image_list The task's current image list. This is a borrowed reference, and must remain valid for the lifetime of the cursor. + * + * @return Returns PLFRAME_ESUCCESS on success, or standard plframe_error_t code if an error occurs. + * + * @warning Callers must call plframe_cursor_free() on @a cursor to free any associated resources, even if initialization + * fails. + */ +plframe_error_t plframe_cursor_thread_init (plframe_cursor_t *cursor, task_t task, thread_t thread, plcrash_async_image_list_t *image_list) { + /* Standard initialization */ + plframe_cursor_internal_init(cursor, task, image_list); + + return (plframe_error_t)plcrash_async_thread_state_mach_thread_init(&cursor->frame.thread_state, thread); +} + +/** + * Fetch the next frame using the provided frame readers. + * + * @param cursor A cursor instance initialized with plframe_cursor_init(); + * @param readers Frame readers to be used to fetch the next frame. Each reader will be executed in the provided order until a valid frame is read. + * @param reader_count The number of readers provided in @a readers. + * @return Returns PLFRAME_ESUCCESS on success, PLFRAME_ENOFRAME is no additional frames are available, or a standard plframe_error_t code if an error occurs. + */ +plframe_error_t plframe_cursor_next_with_readers (plframe_cursor_t *cursor, plframe_cursor_frame_reader_t *readers[], size_t reader_count) { + /* The first frame is already available via existing thread state. */ + if (cursor->depth == 0) { + cursor->depth++; + return PLFRAME_ESUCCESS; + } + + /* A previous frame is only available if we're on the second frame */ + plframe_stackframe_t *prev_frame = NULL; + if (cursor->depth >= 2) + prev_frame = &cursor->prev_frame; + + /* Read in the next frame using the first successful frame reader. */ + plframe_stackframe_t frame; + plframe_error_t ferr = PLFRAME_EINVAL; // default return value if reader_count is 0. + + for (size_t i = 0; i < reader_count; i++) { + ferr = readers[i](cursor->task, cursor->image_list, &cursor->frame, prev_frame, &frame); + if (ferr == PLFRAME_ESUCCESS) + break; + } + + if (ferr != PLFRAME_ESUCCESS) { + return ferr; + } + + /* Check for completion */ + if (!plcrash_async_thread_state_has_reg(&frame.thread_state, PLCRASH_REG_IP)) { + PLCF_DEBUG("Missing expected IP value in successfully read frame"); + return PLFRAME_ENOFRAME; + } + + /* A pc within the NULL page is a terminating frame */ + plcrash_greg_t ip = plcrash_async_thread_state_get_reg(&frame.thread_state, PLCRASH_REG_IP); + if (ip <= PAGE_SIZE) + return PLFRAME_ENOFRAME; + + /* Save the newly fetched frame */ + cursor->prev_frame = cursor->frame; + cursor->frame = frame; + cursor->depth++; + + return PLFRAME_ESUCCESS; +} + +/** + * Fetch the next frame. + * + * @param cursor A cursor instance initialized with plframe_cursor_init(); + * @return Returns PLFRAME_ESUCCESS on success, PLFRAME_ENOFRAME is no additional frames are available, or a standard plframe_error_t code if an error occurs. + */ +plframe_error_t plframe_cursor_next (plframe_cursor_t *cursor) { + plframe_cursor_frame_reader_t *readers[] = { + +#if PLCRASH_FEATURE_UNWIND_COMPACT + plframe_cursor_read_compact_unwind, +#endif + +#if PLCRASH_FEATURE_UNWIND_DWARF + plframe_cursor_read_dwarf_unwind, +#endif + + plframe_cursor_read_frame_ptr + }; + + return plframe_cursor_next_with_readers(cursor, readers, sizeof(readers)/sizeof(readers[0])); +} + + +/** + * Get a register value. Returns PLFRAME_ENOTSUP if the given register is unavailable within the current frame. + * + * @param cursor A cursor instance representing a valid frame, as initialized by plframe_cursor_next(). + * @param regnum The register to fetch from the current frame's state. + * @param reg On success, will be set to the register's value. + */ +plframe_error_t plframe_cursor_get_reg (plframe_cursor_t *cursor, plcrash_regnum_t regnum, plcrash_greg_t *reg) { + /* Verify that the register is available */ + if (!plcrash_async_thread_state_has_reg(&cursor->frame.thread_state, regnum)) + return PLFRAME_ENOTSUP; + + /* Fetch from thread state */ + *reg = plcrash_async_thread_state_get_reg(&cursor->frame.thread_state, regnum); + return PLFRAME_ESUCCESS; +} + +/** + * Get a register's name. + * + * @param cursor A cursor instance initialized with plframe_cursor_init(); + * @param regnum The register number for which a name should be returned. + */ +char const *plframe_cursor_get_regname (plframe_cursor_t *cursor, plcrash_regnum_t regnum) { + return plcrash_async_thread_state_get_reg_name(&cursor->frame.thread_state, regnum); +} + +/** + * Get the total number of registers supported by the @a cursor's target thread. + * + * @param cursor The target cursor. + */ +size_t plframe_cursor_get_regcount (plframe_cursor_t *cursor) { + return plcrash_async_thread_state_get_reg_count(&cursor->frame.thread_state); +} + +/** + * Free any resources associated with the frame cursor. + * + * @param cursor Cursor record to be freed + */ +void plframe_cursor_free(plframe_cursor_t *cursor) { + if (cursor->task != MACH_PORT_NULL) + mach_port_mod_refs(mach_task_self(), cursor->task, MACH_PORT_RIGHT_SEND, -1); +} diff --git a/pool/shard002/C/0060225_compare_gabor_mag_images.c b/pool/shard002/C/0060225_compare_gabor_mag_images.c new file mode 100644 index 0000000000000000000000000000000000000000..5c3780da69260768cdee48d013daa3de2a528210 --- /dev/null +++ b/pool/shard002/C/0060225_compare_gabor_mag_images.c @@ -0,0 +1,142 @@ +/* + +compare_gabor_mag_images.c - Compares two Gabor feature vectors + +COPYRIGHT (c) 2011 R.M.Barnsley (rmb@astro.ljmu.ac.uk) and Marine +Biological Lab, Woods Hole, MA. +www.mbl.edu, www.eol.org, https://github.com/EncyclopediaOfLife + +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 . + +---------------------------------------------------------------------- + +NOTES: + +1. The binary call takes the form of: + + > compare_gabor_mag_images + + [SCALES] + [ORIENTATIONS] + [GABOR_FEATURE_VECTOR_1] + [GABOR_FEATURE_VECTOR_2] + +2. The input parameters should all be in CSV format. + +3. The feature vector is given by [mean_0_0, stddev_0_0, mean_0_1, stddev_1, mean_1_1, stddev_1_1, ... mean_s_o, stddev_s_o] + where the indices s and o represent the scale and orientation level respectively. + +4. Returned is the euclidean distance between the two feature vectors. + +TODO: + +1. Circular reformatting of the feature vector should be used to ensure rotation invariance, see: + + Zhang, Dengsheng, Aylwin Wong, Maria Indrawan, and Guojun Lu. 2000. Content-based + Image Retrieval Using Gabor Texture Features. Image Rochester NY 3656 LNCS: 13–15. + http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.63.8420&rep=rep1&type=pdf + +*/ + +#include +#include +#include +#include +#include +#include +#include + +#include "compare_gabor_mag_images.h" + +int main(int argc, char **argv) { + + // REALLOCATION OF INPUT VARS + // **************************************************** + + long int scales = strtol(argv[1], NULL, 0); + long int orientations = strtol(argv[2], NULL, 0); + char *f1 = strdup(argv[3]); + char *f2 = strdup(argv[4]); + + // SEPARATE SCALES AND ORIENTATIONS INTO ARRAYS + // **************************************************** + + double f1_vector [scales*orientations*2]; // x2 to store both mean and stddev for each scale/orientation + double f2_vector [scales*orientations*2]; // x2 to store both mean and stddev for each scale/orientation + + char* f1_token = strtok(f1, ","); + + int f1_counter = 0; + + while (f1_token) + { + f1_vector[f1_counter] = strtod(f1_token, NULL); + f1_token = strtok(NULL, ","); + f1_counter++; + } + + char* f2_token = strtok(f2, ","); + + int f2_counter = 0; + + while (f2_token) + { + f2_vector[f2_counter] = strtod(f2_token, NULL); + f2_token = strtok(NULL, ","); + f2_counter++; + } + + // SEPARATE MEANS AND STDDEVS INTO SEPARATE ARRAYS + // **************************************************** + + double f1_mean_vector [scales*orientations]; + double f2_mean_vector [scales*orientations]; + + double f1_stddev_vector [scales*orientations]; + double f2_stddev_vector [scales*orientations]; + + int ii; + + int element_counter = 0; + + for (ii=0; ii +#include +#include +#include +#include +#include +#include +#include +#include +#include "fractal.h" + +#define MAX_ITER 4090 +#define itoc(x) ((0x00ffffff/MAX_ITER)*(x)) + +#if SDL_BYTEORDER == SDL_BIG_ENDIAN +#define RMASK 0xff000000 +#define GMASK 0x00ff0000 +#define BMASK 0x0000ff00 +#define AMASK 0x000000ff +#else +#define RMASK 0x000000ff +#define GMASK 0x0000ff00 +#define BMASK 0x00ff0000 +#define AMASK 0xff000000 +#endif + +int write_bitmap_sdl(const fractal_t *f, const char *fname) +{ + SDL_Surface *back; + SDL_Rect pix; + int w, h, i, j, col; + uint32_t pcol, rcol, gcol, bcol; + w = fractal_get_width(f); + h = fractal_get_height(f); + + back = SDL_CreateRGBSurface(SDL_SWSURFACE, w, h, 32, RMASK, GMASK, BMASK, AMASK); + if (!back) + return -1; + + for (i = 0; i < w; i++) { + for (j = 0; j < h; j++) { + col = itoc(fractal_get_value(f, i, j)); + rcol = col & 0xff; + gcol = (col >> 8) & 0xff; + bcol = (col >> 16) & 0xff; + pcol = SDL_MapRGB(back->format, rcol, gcol, bcol); + + pix.w = pix.h = 1; + pix.x = i; + pix.y = j; + SDL_FillRect(back, &pix, pcol); + } + } + + if (SDL_SaveBMP(back, fname) < 0) + return -1; + + SDL_FreeSurface(back); + + return 0; +} + +static int iter_julia(double zx, double zy, double a, double b, int it) +{ + /* prevent infinite loop */ + if (it > MAX_ITER) + return 0; + + /* prevent leaving Julia set + * if distance to origin >= 2 + */ + if (zx*zx + zy*zy >= 4.0) + return it; + + /* compute next iteration + * f(z) = z^2 + c + * z = x + yi + * c = a + bi + */ + return iter_julia(zx*zx - zy*zy + a, 2*zx*zy + b, a, b, it+1); +} + +int fractal_compute_value(fractal_t *f, int x, int y) +{ + double zx, zy; + double a, b; + int val; + int w, h; + + a = fractal_get_a(f); + b = fractal_get_b(f); + + w = fractal_get_width(f); + h = fractal_get_height(f); + + zx = ((double)x / (double)w) * 3.0 - 1.5; + zy = ((double)y / (double)h) * 3.0 - 1.5; + + val = iter_julia(zx, zy, a, b, 0); + fractal_set_value(f, x, y, val); + + return val; +} diff --git a/pool/shard002/C/0060237_aranbinomial.c b/pool/shard002/C/0060237_aranbinomial.c new file mode 100644 index 0000000000000000000000000000000000000000..2b919283c81c282b8eaee5a25eac47ec006aeac2 --- /dev/null +++ b/pool/shard002/C/0060237_aranbinomial.c @@ -0,0 +1,107 @@ +/* LIBARAN - Fast Multipole Method library + * Copyright (C) 2006-2007 Pierre Gay + * + * 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 "aranbinomial.h" + +#include "aranbinomialbufferd.h" + +/** + * aran_slow_binomial: + * @n: a #guint. + * @p: a #guint. + * + * Computes the binomial coefficient (choice of @p in @n) using slow + * recurrence formula. + * + * Returns: C_@p^@n. + */ +gdouble aran_slow_binomial (guint n, guint p) +{ + if (p > n) return 0.; + if (p == 0) return 1.; + + return aran_slow_binomial (n-1, p) + aran_slow_binomial (n-1, p-1); +} + +static AranBinomialBufferd *_binomial = NULL; + +static gdouble _binomial_generator (guint l, guint m, AranBinomialBufferd *buf) +{ + if (l == 0) return 1.; + if ((m == 0) || (m == l)) return 1.; + + return *aran_binomial_bufferd_get_unsafe (buf, l-1, m) + + *aran_binomial_bufferd_get_unsafe (buf, l-1, m-1); +} + +static void _binomial_atexit () +{ + if (_binomial != NULL) + aran_binomial_bufferd_free (_binomial); + + _binomial = NULL; + +} + +/** + * aran_binomial: + * @n: a #guint. + * @p: a #guint. + * + * Computes the binomial coefficient (choice of @p in @n). + */ + +/** + * aran_fast_binomial: + * @n: a #guint. + * @p: a #guint. + * + * Computes the binomial coefficient (choice of @p in @n) using fast + * buffered values. + * + * Returns: C_@p^@n. + */ +gdouble aran_fast_binomial (guint n, guint p) +{ + aran_binomial_require (n); + + return *aran_binomial_bufferd_get_unsafe (_binomial, n, p); +} + +/** + * aran_binomial_require: + * @max: a #guint. + * + * Preallocates binomial coefficients up to n=@max. Calling this for a + * sufficiently large @max can improve your program efficiency, since + * successive calls with slowly increasing values of @max can lead to + * numerous buffer reallocations. + */ +void aran_binomial_require (guint max) +{ + if (_binomial == NULL) + { + _binomial = aran_binomial_bufferd_new (_binomial_generator, max); + g_atexit (_binomial_atexit); + } + else + { + aran_binomial_bufferd_require (_binomial, max); + } +} diff --git a/pool/shard002/C/0060242_s_ldexp.c b/pool/shard002/C/0060242_s_ldexp.c new file mode 100644 index 0000000000000000000000000000000000000000..ccf7171b18a5ecf07e7c8ff013ecd71b255efd78 --- /dev/null +++ b/pool/shard002/C/0060242_s_ldexp.c @@ -0,0 +1,81 @@ + +/* @(#)s_ldexp.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. + * ==================================================== + */ + +/* +FUNCTION + <>, <>---load exponent + +INDEX + ldexp +INDEX + ldexpf + +ANSI_SYNOPSIS + #include + double ldexp(double <[val]>, int <[exp]>); + float ldexpf(float <[val]>, int <[exp]>); + +TRAD_SYNOPSIS + #include + + double ldexp(<[val]>, <[exp]>) + double <[val]>; + int <[exp]>; + + float ldexpf(<[val]>, <[exp]>) + float <[val]>; + int <[exp]>; + + +DESCRIPTION +<> calculates the value +@ifinfo +<[val]> times 2 to the power <[exp]>. +@end ifinfo +@tex +$val\times 2^{exp}$. +@end tex +<> is identical, save that it takes and returns <> +rather than <> values. + +RETURNS +<> returns the calculated value. + +Underflow and overflow both set <> to <>. +On underflow, <> and <> return 0.0. +On overflow, <> returns plus or minus <>. + +PORTABILITY +<> is ANSI, <> is an extension. + +*/ + +#include "fdlibm.h" +#include + +#ifndef _DOUBLE_IS_32BITS + +#ifdef __STDC__ + double ldexp(double value, int exp) +#else + double ldexp(value, exp) + double value; int exp; +#endif +{ + if(!finite(value)||value==0.0) return value; + value = scalbn(value,exp); + if(!finite(value)||value==0.0) errno = ERANGE; + return value; +} + +#endif /* _DOUBLE_IS_32BITS */ diff --git a/pool/shard002/C/0060244_ci13xxx_msm.c b/pool/shard002/C/0060244_ci13xxx_msm.c new file mode 100644 index 0000000000000000000000000000000000000000..a4742a5771a8d19b731a106d007250c56753ce16 --- /dev/null +++ b/pool/shard002/C/0060244_ci13xxx_msm.c @@ -0,0 +1,268 @@ +/* Copyright (c) 2010-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 "ci13xxx_udc.c" + +#define MSM_USB_BASE (udc->regs) + +struct ci13xxx_udc_context { + int irq; + void __iomem *regs; + int wake_gpio; + int wake_irq; + bool wake_irq_state; +}; + +static struct ci13xxx_udc_context _udc_ctxt; + +static irqreturn_t msm_udc_irq(int irq, void *data) +{ + return udc_irq(); +} + +static void ci13xxx_msm_suspend(void) +{ + struct device *dev = _udc->gadget.dev.parent; + dev_dbg(dev, "ci13xxx_msm_suspend\n"); + + if (_udc_ctxt.wake_irq && !_udc_ctxt.wake_irq_state) { + enable_irq_wake(_udc_ctxt.wake_irq); + enable_irq(_udc_ctxt.wake_irq); + _udc_ctxt.wake_irq_state = true; + } +} + +static void ci13xxx_msm_resume(void) +{ + struct device *dev = _udc->gadget.dev.parent; + dev_dbg(dev, "ci13xxx_msm_resume\n"); + + if (_udc_ctxt.wake_irq && _udc_ctxt.wake_irq_state) { + disable_irq_wake(_udc_ctxt.wake_irq); + disable_irq_nosync(_udc_ctxt.wake_irq); + _udc_ctxt.wake_irq_state = false; + } +} + +static void ci13xxx_msm_notify_event(struct ci13xxx *udc, unsigned event) +{ + struct device *dev = udc->gadget.dev.parent; + + switch (event) { + case CI13XXX_CONTROLLER_RESET_EVENT: + dev_info(dev, "CI13XXX_CONTROLLER_RESET_EVENT received\n"); + writel(0, USB_AHBBURST); + writel_relaxed(0x08, USB_AHBMODE); + break; + case CI13XXX_CONTROLLER_DISCONNECT_EVENT: + dev_info(dev, "CI13XXX_CONTROLLER_DISCONNECT_EVENT received\n"); + ci13xxx_msm_resume(); + break; + case CI13XXX_CONTROLLER_SUSPEND_EVENT: + dev_info(dev, "CI13XXX_CONTROLLER_SUSPEND_EVENT received\n"); + ci13xxx_msm_suspend(); + break; + case CI13XXX_CONTROLLER_RESUME_EVENT: + dev_info(dev, "CI13XXX_CONTROLLER_RESUME_EVENT received\n"); + ci13xxx_msm_resume(); + break; + + default: + dev_dbg(dev, "unknown ci13xxx_udc event\n"); + break; + } +} + +static irqreturn_t ci13xxx_msm_resume_irq(int irq, void *data) +{ + struct ci13xxx *udc = _udc; + + if (udc->transceiver && udc->vbus_active && udc->suspended) + usb_phy_set_suspend(udc->transceiver, 0); + else if (!udc->suspended) + ci13xxx_msm_resume(); + + return IRQ_HANDLED; +} + +static struct ci13xxx_udc_driver ci13xxx_msm_udc_driver = { + .name = "ci13xxx_msm", + .flags = CI13XXX_REGS_SHARED | + CI13XXX_REQUIRE_TRANSCEIVER | + CI13XXX_PULLUP_ON_VBUS | + CI13XXX_ZERO_ITC | + CI13XXX_DISABLE_STREAMING | + CI13XXX_IS_OTG, + + .notify_event = ci13xxx_msm_notify_event, +}; + +static int ci13xxx_msm_install_wake_gpio(struct platform_device *pdev, + struct resource *res) +{ + int wake_irq; + int ret; + + dev_dbg(&pdev->dev, "ci13xxx_msm_install_wake_gpio\n"); + + _udc_ctxt.wake_gpio = res->start; + gpio_request(_udc_ctxt.wake_gpio, "USB_RESUME"); + gpio_direction_input(_udc_ctxt.wake_gpio); + wake_irq = gpio_to_irq(_udc_ctxt.wake_gpio); + if (wake_irq < 0) { + dev_err(&pdev->dev, "could not register USB_RESUME GPIO.\n"); + return -ENXIO; + } + + dev_dbg(&pdev->dev, "_udc_ctxt.gpio_irq = %d and irq = %d\n", + _udc_ctxt.wake_gpio, wake_irq); + ret = request_irq(wake_irq, ci13xxx_msm_resume_irq, + IRQF_TRIGGER_RISING | IRQF_ONESHOT, "usb resume", NULL); + if (ret < 0) { + dev_err(&pdev->dev, "could not register USB_RESUME IRQ.\n"); + goto gpio_free; + } + disable_irq(wake_irq); + _udc_ctxt.wake_irq = wake_irq; + + return 0; + +gpio_free: + gpio_free(_udc_ctxt.wake_gpio); + _udc_ctxt.wake_gpio = 0; + return ret; +} + +static void ci13xxx_msm_uninstall_wake_gpio(struct platform_device *pdev) +{ + dev_dbg(&pdev->dev, "ci13xxx_msm_uninstall_wake_gpio\n"); + + if (_udc_ctxt.wake_gpio) { + gpio_free(_udc_ctxt.wake_gpio); + _udc_ctxt.wake_gpio = 0; + } +} + +static int ci13xxx_msm_probe(struct platform_device *pdev) +{ + struct resource *res; + int ret; + + dev_dbg(&pdev->dev, "ci13xxx_msm_probe\n"); + + res = platform_get_resource(pdev, IORESOURCE_MEM, 0); + if (!res) { + dev_err(&pdev->dev, "failed to get platform resource mem\n"); + return -ENXIO; + } + + _udc_ctxt.regs = ioremap(res->start, resource_size(res)); + if (!_udc_ctxt.regs) { + dev_err(&pdev->dev, "ioremap failed\n"); + return -ENOMEM; + } + + ret = udc_probe(&ci13xxx_msm_udc_driver, &pdev->dev, _udc_ctxt.regs); + if (ret < 0) { + dev_err(&pdev->dev, "udc_probe failed\n"); + goto iounmap; + } + + _udc_ctxt.irq = platform_get_irq(pdev, 0); + if (_udc_ctxt.irq < 0) { + dev_err(&pdev->dev, "IRQ not found\n"); + ret = -ENXIO; + goto udc_remove; + } + + res = platform_get_resource_byname(pdev, IORESOURCE_IO, "USB_RESUME"); + if (res) { + ret = ci13xxx_msm_install_wake_gpio(pdev, res); + if (ret < 0) { + dev_err(&pdev->dev, "gpio irq install failed\n"); + goto udc_remove; + } + } + + ret = request_irq(_udc_ctxt.irq, msm_udc_irq, IRQF_SHARED, pdev->name, + pdev); + if (ret < 0) { + dev_err(&pdev->dev, "request_irq failed\n"); + goto gpio_uninstall; + } + + pm_runtime_no_callbacks(&pdev->dev); + pm_runtime_enable(&pdev->dev); + + return 0; + +gpio_uninstall: + ci13xxx_msm_uninstall_wake_gpio(pdev); +udc_remove: + udc_remove(); +iounmap: + iounmap(_udc_ctxt.regs); + + return ret; +} + +int ci13xxx_msm_remove(struct platform_device *pdev) +{ + pm_runtime_disable(&pdev->dev); + free_irq(_udc_ctxt.irq, pdev); + ci13xxx_msm_uninstall_wake_gpio(pdev); + udc_remove(); + iounmap(_udc_ctxt.regs); + return 0; +} + +void msm_hw_bam_disable(bool bam_disable) +{ + u32 val; + struct ci13xxx *udc = _udc; + + if (bam_disable) + val = readl_relaxed(USB_GENCONFIG) | GENCONFIG_BAM_DISABLE; + else + val = readl_relaxed(USB_GENCONFIG) & ~GENCONFIG_BAM_DISABLE; + + writel_relaxed(val, USB_GENCONFIG); +} + +static struct platform_driver ci13xxx_msm_driver = { + .probe = ci13xxx_msm_probe, + .driver = { .name = "msm_hsusb", }, + .remove = ci13xxx_msm_remove, +}; +MODULE_ALIAS("platform:msm_hsusb"); + +static int __init ci13xxx_msm_init(void) +{ + return platform_driver_register(&ci13xxx_msm_driver); +} +module_init(ci13xxx_msm_init); + +static void __exit ci13xxx_msm_exit(void) +{ + platform_driver_unregister(&ci13xxx_msm_driver); +} +module_exit(ci13xxx_msm_exit); + +MODULE_LICENSE("GPL v2"); diff --git a/pool/shard002/C/0060251_main.c b/pool/shard002/C/0060251_main.c new file mode 100644 index 0000000000000000000000000000000000000000..440e45efcf7d55ca9fd2293f5e76d44dceabffb3 --- /dev/null +++ b/pool/shard002/C/0060251_main.c @@ -0,0 +1,180 @@ +#include +#include +#include +#include +#include +#include +#include + +uint16_t ramtop = PROGTOP; +uint8_t trs80_model; +uint8_t vtattr_cap; +uint8_t need_resched; + +/* + * Called when there is no work to do. On the models without serial + * interrupts we poll here so that the normal case of idling while + * waiting for input feels ok. + */ +void platform_idle(void) +{ + irqflags_t irq; + irq = di(); + tty_poll(); + irqrestore(irq); +} + +void do_beep(void) +{ +} + +/* Work around SDCC bugs */ +uint8_t sdcc_bug_2753(uint8_t v) __z88dk_fastcall +{ + return v; +} + +__sfr __at 0xE0 irqstat3; +__sfr __at 0xEC irqack3; + +/* We assign these to dummy to deal with an sdcc bug (should be fixed in next + SDCC) */ +void platform_interrupt(void) +{ + uint8_t dummy; + uint8_t irq = *((volatile uint8_t *)0x37E0); + + tty_interrupt(); + kbd_interrupt(); + + if (irq & 0x40) + dummy = sdcc_bug_2753(*((volatile uint8_t *)0x37EC)); + if (irq & 0x80) { /* FIXME??? */ + timer_interrupt(); + dummy = sdcc_bug_2753(*((volatile uint8_t *)0x37E0)); /* Ack the timer */ + } +} + +struct blkbuf *bufpool_end = &bufpool[NBUFS]; + +void platform_discard(void) +{ + bufptr bp; + uint16_t space = (uint8_t *)0x37E0 - (uint8_t *)bufpool_end; + space /= BLKSIZE; + bufpool_end += space; + kprintf("Reclaiming memory.. total buffers %d\n", + bufpool_end - bufpool); + for( bp = bufpool + NBUFS; bp < bufpool_end; ++bp ){ + bp->bf_dev = NO_DEVICE; + bp->bf_busy = BF_FREE; + } +} + +#ifdef CONFIG_RTC + +__sfr __at 0xB0 rtc_secl; +__sfr __at 0xB1 rtc_sech; +__sfr __at 0xB2 rtc_minl; +__sfr __at 0xB3 rtc_minh; +__sfr __at 0xB4 rtc_hourl; +__sfr __at 0xB5 rtc_hourh; +/* day of week is B6 */ +__sfr __at 0xB7 rtc_dayl; +__sfr __at 0xB8 rtc_dayh; +__sfr __at 0xB9 rtc_monl; +__sfr __at 0xBA rtc_monh; +__sfr __at 0xBB rtc_yearl; +__sfr __at 0xBC rtc_yearh; + +/* FIXME: the RTC is optional so we should test for it first */ +uint8_t platform_rtc_secs(void) +{ + uint8_t sl, rv; + /* BCD encoded */ + do { + sl = rtc_secl; + /* RTC may be absent */ + if (sl == 255) + return 255; + rv = sl + rtc_sech * 10; + } while (sl != rtc_secl); + return rv; +} + +/* If the compiler segfaults here you need at least SDCC #10471 */ + +int platform_rtc_read(void) +{ + uint16_t len = sizeof(struct cmos_rtc); + struct cmos_rtc cmos; + uint8_t *p; + uint8_t r, y; + + if (udata.u_count < len) + len = udata.u_count; + + if (rtc_secl == 255) { + udata.u_error = EOPNOTSUPP; + return -1; + } + + /* We do a full set of reads and if the seconds change retry - we + need to retry the lost as we might read as the second changes for + new year */ + do { + p = cmos.data.bytes; + r = rtc_secl; + y = (rtc_yearh << 4) | rtc_yearl; + if (y > 70) + *p++ = 19; + else + *p++ = 20; + *p++ = y; + *p++ = ((rtc_monh & 1)<< 4) | rtc_monl; + *p++ = ((rtc_dayh & 3) << 4) | rtc_dayl; + *p++ = ((rtc_hourh & 3) << 4) | rtc_hourl; + *p++ = ((rtc_minh & 7) << 4) | rtc_minl; + *p++ = ((rtc_sech & 7) << 4) | rtc_secl; + } while ((r ^ rtc_secl) & 0x0F); + + cmos.type = CMOS_RTC_BCD; + if (uput(&cmos, udata.u_base, len) == -1) + return -1; + return len; +} + +/* Yes I'm a slacker .. this wants adding but it's ugly + because the seconds is always just set to 0 on any change. We + also need to deal with leap years here */ +int platform_rtc_write(void) +{ + udata.u_error = EOPNOTSUPP; + return -1; +} + +#endif + +/* + * So that we don't suck in a library routine we can't use from + * the runtime + */ + +int strlen(const char *p) +{ + int len = 0; + while(*p++) + len++; + return len; +} + +uint8_t video_lower; + +uint8_t vt_map_char(uint8_t x) +{ + if (video_lower) + return x; + if (x >= 96 && x <= 127) + return x - 32; + return x; +} diff --git a/pool/shard002/C/0060262_xed-commands-view.c b/pool/shard002/C/0060262_xed-commands-view.c new file mode 100644 index 0000000000000000000000000000000000000000..581c343e0e79b6cdd32b54184e7c54a0d7c4e9ea --- /dev/null +++ b/pool/shard002/C/0060262_xed-commands-view.c @@ -0,0 +1,280 @@ +/* + * xed-view-commands.c + * This file is part of xed + * + * Copyright (C) 1998, 1999 Alex Roberts, Evan Lawrence + * Copyright (C) 2000, 2001 Chema Celorio, Paolo Maggi + * Copyright (C) 2002-2005 Paolo Maggi + * + * 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. + */ + +/* + * Modified by the xed Team, 1998-2005. See the AUTHORS file for a + * list of people on the xed Team. + * See the ChangeLog files for a list of changes. + * + * $Id$ + */ + +#include +#include + +#include "xed-commands.h" +#include "xed-debug.h" +#include "xed-window.h" +#include "xed-window-private.h" +#include "xed-paned.h" +#include "xed-view-frame.h" +#include "xed-highlight-mode-dialog.h" +#include "xed-highlight-mode-selector.h" + +void +_xed_cmd_view_show_toolbar (GtkAction *action, + XedWindow *window) +{ + gboolean visible; + + xed_debug (DEBUG_COMMANDS); + + visible = gtk_toggle_action_get_active (GTK_TOGGLE_ACTION (action)); + + if (visible) + { + gtk_widget_show (window->priv->toolbar); + } + else + { + gtk_widget_hide (window->priv->toolbar); + } +} + +void +_xed_cmd_view_show_menubar (GtkAction *action, + XedWindow *window) +{ + gboolean visible; + + xed_debug (DEBUG_COMMANDS); + + visible = gtk_toggle_action_get_active (GTK_TOGGLE_ACTION (action)); + + if (visible) + { + gtk_widget_show (window->priv->menubar); + g_settings_set_boolean (window->priv->ui_settings, XED_SETTINGS_MENUBAR_VISIBLE, TRUE); + } + else + { + gtk_widget_hide (window->priv->menubar); + g_settings_set_boolean (window->priv->ui_settings, XED_SETTINGS_MENUBAR_VISIBLE, FALSE); + } +} + +void +_xed_cmd_view_show_statusbar (GtkAction *action, + XedWindow *window) +{ + gboolean visible; + + xed_debug (DEBUG_COMMANDS); + + visible = gtk_toggle_action_get_active (GTK_TOGGLE_ACTION (action)); + + if (visible) + { + gtk_widget_show (window->priv->statusbar); + } + else + { + gtk_widget_hide (window->priv->statusbar); + } +} + +void +_xed_cmd_view_show_side_pane (GtkAction *action, + XedWindow *window) +{ + gboolean visible; + XedPanel *panel; + XedPaned *paned; + + xed_debug (DEBUG_COMMANDS); + + visible = gtk_toggle_action_get_active (GTK_TOGGLE_ACTION (action)); + + panel = xed_window_get_side_panel (window); + paned = _xed_window_get_hpaned (window); + + if (visible) + { + gtk_widget_show (GTK_WIDGET (panel)); + xed_paned_open (paned, 1, _xed_window_get_side_panel_size (window)); + gtk_widget_grab_focus (GTK_WIDGET (panel)); + } + else + { + xed_paned_close (paned, 1); + } +} + +void +_xed_cmd_view_show_bottom_pane (GtkAction *action, + XedWindow *window) +{ + gboolean visible; + XedPanel *panel; + XedPaned *paned; + + xed_debug (DEBUG_COMMANDS); + + visible = gtk_toggle_action_get_active (GTK_TOGGLE_ACTION (action)); + + panel = xed_window_get_bottom_panel (window); + paned = _xed_window_get_vpaned (window); + + if (visible) + { + gint position; + gint panel_size; + gint paned_size; + + panel_size = _xed_window_get_bottom_panel_size (window); + g_object_get (G_OBJECT (paned), "max-position", &paned_size, NULL); + position = paned_size - panel_size; + gtk_widget_show (GTK_WIDGET (panel)); + xed_paned_open (paned, 2, position); + gtk_widget_grab_focus (GTK_WIDGET (panel)); + } + else + { + xed_paned_close (paned, 2); + } +} + +void +_xed_cmd_view_toggle_overview_map (GtkAction *action, + XedWindow *window) +{ + XedTab *tab; + XedViewFrame *frame; + GtkFrame *map_frame; + gboolean visible; + + xed_debug (DEBUG_COMMANDS); + + tab = xed_window_get_active_tab (window); + + if (tab == NULL) + { + return; + } + + frame = XED_VIEW_FRAME (_xed_tab_get_view_frame (tab)); + map_frame = xed_view_frame_get_map_frame (frame); + visible = gtk_toggle_action_get_active (GTK_TOGGLE_ACTION (action)); + + gtk_widget_set_visible (GTK_WIDGET (map_frame), visible); +} + +void +_xed_cmd_view_toggle_fullscreen_mode (GtkAction *action, + XedWindow *window) +{ + xed_debug (DEBUG_COMMANDS); + + if (_xed_window_is_fullscreen (window)) + { + _xed_window_unfullscreen (window); + } + else + { + _xed_window_fullscreen (window); + } +} + +void +_xed_cmd_view_toggle_word_wrap (GtkAction *action, + XedWindow *window) +{ + XedView *view; + gboolean do_word_wrap; + + xed_debug (DEBUG_COMMANDS); + + do_word_wrap = gtk_toggle_action_get_active (GTK_TOGGLE_ACTION (action)); + view = xed_window_get_active_view (window); + + if (do_word_wrap) + { + gtk_text_view_set_wrap_mode (GTK_TEXT_VIEW (view), GTK_WRAP_WORD); + } + else + { + gtk_text_view_set_wrap_mode (GTK_TEXT_VIEW (view), GTK_WRAP_NONE); + } +} + +void +_xed_cmd_view_leave_fullscreen_mode (GtkAction *action, + XedWindow *window) +{ + GtkAction *view_action; + + view_action = gtk_action_group_get_action (window->priv->always_sensitive_action_group, "ViewFullscreen"); + g_signal_handlers_block_by_func (view_action, G_CALLBACK (_xed_cmd_view_toggle_fullscreen_mode), window); + gtk_toggle_action_set_active (GTK_TOGGLE_ACTION (view_action), FALSE); + _xed_window_unfullscreen (window); + g_signal_handlers_unblock_by_func (view_action, G_CALLBACK (_xed_cmd_view_toggle_fullscreen_mode), window); +} + +static void +on_language_selected (XedHighlightModeSelector *sel, + GtkSourceLanguage *language, + XedWindow *window) +{ + XedDocument *doc; + + doc = xed_window_get_active_document (window); + if (doc) + { + xed_document_set_language (doc, language); + } +} + +void +_xed_cmd_view_change_highlight_mode (GtkAction *action, + XedWindow *window) +{ + GtkWidget *dlg; + XedHighlightModeSelector *sel; + XedDocument *doc; + + dlg = xed_highlight_mode_dialog_new (GTK_WINDOW (window)); + sel = xed_highlight_mode_dialog_get_selector (XED_HIGHLIGHT_MODE_DIALOG (dlg)); + + doc = xed_window_get_active_document (XED_WINDOW (window)); + if (doc) + { + xed_highlight_mode_selector_select_language (sel, + xed_document_get_language (doc)); + } + + g_signal_connect (sel, "language-selected", + G_CALLBACK (on_language_selected), window); + + gtk_widget_show (GTK_WIDGET (dlg)); +} diff --git a/pool/shard002/C/0060273_simple-server.c b/pool/shard002/C/0060273_simple-server.c new file mode 100644 index 0000000000000000000000000000000000000000..35629747b1906079f1162dae36d615b88f6d2806 --- /dev/null +++ b/pool/shard002/C/0060273_simple-server.c @@ -0,0 +1,268 @@ +/* + * This file is part of the Soletta Project + * + * Copyright (C) 2015 Intel Corporation. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * * Neither the name of Intel Corporation nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "sol-log.h" +#include "sol-mainloop.h" +#include "sol-network.h" +#include "sol-str-slice.h" +#include "sol-util.h" +#include "sol-vector.h" + +#include "sol-coap.h" + +#define DEFAULT_UDP_PORT 5683 + +#define OC_CORE_JSON_SEPARATOR "," +#define OC_CORE_ELEM_JSON_START "{\"oc\":[{\"href\":\"%s\",\"rep\":{" +#define OC_CORE_PROP_JSON_NUMBER "\"%s\":%d" +#define OC_CORE_PROP_JSON_STRING "\"%s\":\"%s\"" +#define OC_CORE_PROP_JSON_BOOLEAN "\"%s\":%s" +#define OC_CORE_ELEM_JSON_END "}}]}" + + +struct light_context { + struct sol_coap_server *server; + struct sol_coap_resource *resource; +}; + +static int console_fd; + +static bool +get_scrolllock_led(void) +{ + char value; + + if (ioctl(console_fd, KDGETLED, (char *)&value)) { + perror("Could not get led state"); + return false; + } + + return value & LED_SCR; +} + +static void +set_scrolllock_led(bool on) +{ + char old; + + if (ioctl(console_fd, KDGETLED, (char *)&old)) { + perror("Could not get led state"); + return; + } + + if (ioctl(console_fd, KDSETLED, on ? (old | LED_SCR) : (old & ~LED_SCR))) { + perror("Could not set led state"); + return; + } +} + +static int +light_resource_to_rep(const struct sol_coap_resource *resource, + bool state, char *buf, int buflen) +{ + uint8_t path[64]; + int len = 0; + + memset(&path, 0, sizeof(path)); + sol_coap_uri_path_to_buf(resource->path, path, sizeof(path), NULL); + + len += snprintf(buf + len, buflen - len, OC_CORE_ELEM_JSON_START, path); + + /* FIXME */ + len += snprintf(buf + len, buflen - len, OC_CORE_PROP_JSON_NUMBER, "power", 100); + len += snprintf(buf + len, buflen - len, OC_CORE_JSON_SEPARATOR); + len += snprintf(buf + len, buflen - len, OC_CORE_PROP_JSON_STRING, "name", "Soletta LAMP!"); + len += snprintf(buf + len, buflen - len, OC_CORE_JSON_SEPARATOR); + + len += snprintf(buf + len, buflen - len, OC_CORE_PROP_JSON_BOOLEAN, "state", + state ? "true" : "false" ); + + len += snprintf(buf + len, buflen - len, OC_CORE_ELEM_JSON_END); + + return len; +} + +static int +light_method_put(struct sol_coap_server *server, + const struct sol_coap_resource *resource, struct sol_coap_packet *req, + const struct sol_network_link_addr *cliaddr, void *data) +{ + struct sol_coap_packet *resp; + char *sub = NULL; + uint8_t *p; + uint16_t len; + bool value; + sol_coap_responsecode_t code = SOL_COAP_RSPCODE_CONTENT; + + sol_coap_packet_get_payload(req, &p, &len); + + if (p) + sub = strstr((char *)p, "state\":"); + if (!sub) { + code = SOL_COAP_RSPCODE_BAD_REQUEST; + goto done; + } + + value = !memcmp(sub + strlen("state\":"), "true", sizeof("true") - 1); + + SOL_INF("Changing light state to %s", value ? "on" : "off"); + + set_scrolllock_led(value); + +done: + resp = sol_coap_packet_new(req); + if (!resp) { + SOL_WRN("Could not build response packet"); + return -1; + } + sol_coap_header_set_type(resp, SOL_COAP_TYPE_ACK); + sol_coap_header_set_code(resp, code); + + return sol_coap_send_packet(server, resp, cliaddr); +} + +static bool +update_light(void *data) +{ + struct light_context *context = data; + struct sol_coap_server *server = context->server; + struct sol_coap_resource *resource = context->resource; + struct sol_coap_packet *pkt; + uint8_t *payload; + uint16_t len; + + SOL_INF("Emitting notification"); + + pkt = sol_coap_packet_notification_new(server, resource); + SOL_NULL_CHECK(pkt, false); + + sol_coap_header_set_code(pkt, SOL_COAP_RSPCODE_CONTENT); + + sol_coap_packet_get_payload(pkt, &payload, &len); + len = light_resource_to_rep(resource, get_scrolllock_led(), (char *)payload, len); + sol_coap_packet_set_payload_used(pkt, len); + + return !sol_coap_packet_send_notification(server, resource, pkt); +} + +static int +light_method_get(struct sol_coap_server *server, + const struct sol_coap_resource *resource, struct sol_coap_packet *req, + const struct sol_network_link_addr *cliaddr, void *data) +{ + struct sol_coap_packet *resp; + uint8_t *payload; + uint16_t len; + + resp = sol_coap_packet_new(req); + if (!resp) { + SOL_WRN("Could not build response packet"); + return -1; + } + sol_coap_header_set_type(resp, SOL_COAP_TYPE_ACK); + sol_coap_header_set_code(resp, SOL_COAP_RSPCODE_CONTENT); + + sol_coap_packet_get_payload(resp, &payload, &len); + len = light_resource_to_rep(resource, get_scrolllock_led(), (char *)payload, len); + sol_coap_packet_set_payload_used(resp, len); + + return sol_coap_send_packet(server, resp, cliaddr); +} + +static struct sol_coap_resource light = { + SOL_SET_API_VERSION(.api_version = SOL_COAP_RESOURCE_API_VERSION, ) + .get = light_method_get, + .put = light_method_put, + .flags = SOL_COAP_FLAGS_WELL_KNOWN, + .path = { + SOL_STR_SLICE_LITERAL("a"), + SOL_STR_SLICE_LITERAL("light"), + SOL_STR_SLICE_EMPTY, + } +}; + +int +main(int argc, char *argv[]) +{ + struct light_context context = { .resource = &light }; + struct sol_coap_server *server; + char old_led_state; + + sol_init(); + + server = sol_coap_server_new(DEFAULT_UDP_PORT); + if (!server) { + SOL_WRN("Could not create a coap server using port %d.", DEFAULT_UDP_PORT); + return -1; + } + + if (!sol_coap_server_register_resource(server, &light, NULL)) { + SOL_WRN("Could not register resource for the light"); + return -1; + } + + console_fd = open("/dev/console", O_RDWR); + if (console_fd < 0) { + perror("Could not open '/dev/console'"); + return -1; + } + + if (ioctl(console_fd, KDGETLED, (char *)&old_led_state)) { + perror("Could not get the keyboard leds state"); + return -1; + } + + context.server = server; + sol_timeout_add(5000, update_light, &context); + + sol_run(); + + sol_coap_server_unref(server); + + if (ioctl(console_fd, KDSETLED, old_led_state)) { + perror("Could not return the leds to the old state"); + return -1; + } + + return 0; +} diff --git a/pool/shard002/C/0060278_mongoc-stream-socket.c b/pool/shard002/C/0060278_mongoc-stream-socket.c new file mode 100644 index 0000000000000000000000000000000000000000..2cc2f5c36fa44fc9e5d46ca455544ceea3dc6d2a --- /dev/null +++ b/pool/shard002/C/0060278_mongoc-stream-socket.c @@ -0,0 +1,316 @@ +/* + * Copyright 2014 MongoDB, 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 "mongoc-stream-private.h" +#include "mongoc-stream-socket.h" +#include "mongoc-trace-private.h" + + +#undef MONGOC_LOG_DOMAIN +#define MONGOC_LOG_DOMAIN "stream" + + +struct _mongoc_stream_socket_t { + mongoc_stream_t vtable; + mongoc_socket_t *sock; +}; + + +static BSON_INLINE int64_t +get_expiration (int32_t timeout_msec) +{ + if (timeout_msec < 0) { + return -1; + } else if (timeout_msec == 0) { + return 0; + } else { + return (bson_get_monotonic_time () + ((int64_t) timeout_msec * 1000L)); + } +} + + +static int +_mongoc_stream_socket_close (mongoc_stream_t *stream) +{ + mongoc_stream_socket_t *ss = (mongoc_stream_socket_t *) stream; + int ret; + + ENTRY; + + BSON_ASSERT (ss); + + if (ss->sock) { + ret = mongoc_socket_close (ss->sock); + RETURN (ret); + } + + RETURN (0); +} + + +static void +_mongoc_stream_socket_destroy (mongoc_stream_t *stream) +{ + mongoc_stream_socket_t *ss = (mongoc_stream_socket_t *) stream; + + ENTRY; + + BSON_ASSERT (ss); + + if (ss->sock) { + mongoc_socket_destroy (ss->sock); + ss->sock = NULL; + } + + bson_free (ss); + + EXIT; +} + + +static void +_mongoc_stream_socket_failed (mongoc_stream_t *stream) +{ + ENTRY; + + _mongoc_stream_socket_destroy (stream); + + EXIT; +} + + +static int +_mongoc_stream_socket_setsockopt (mongoc_stream_t *stream, + int level, + int optname, + void *optval, + socklen_t optlen) +{ + mongoc_stream_socket_t *ss = (mongoc_stream_socket_t *) stream; + int ret; + + ENTRY; + + BSON_ASSERT (ss); + BSON_ASSERT (ss->sock); + + ret = mongoc_socket_setsockopt (ss->sock, level, optname, optval, optlen); + + RETURN (ret); +} + + +static int +_mongoc_stream_socket_flush (mongoc_stream_t *stream) +{ + ENTRY; + RETURN (0); +} + + +static ssize_t +_mongoc_stream_socket_readv (mongoc_stream_t *stream, + mongoc_iovec_t *iov, + size_t iovcnt, + size_t min_bytes, + int32_t timeout_msec) +{ + mongoc_stream_socket_t *ss = (mongoc_stream_socket_t *) stream; + int64_t expire_at; + ssize_t ret = 0; + ssize_t nread; + size_t cur = 0; + + ENTRY; + + BSON_ASSERT (ss); + BSON_ASSERT (ss->sock); + + expire_at = get_expiration (timeout_msec); + + /* + * This isn't ideal, we should plumb through to recvmsg(), but we + * don't actually use this in any way but to a single buffer + * currently anyway, so should be just fine. + */ + + for (;;) { + nread = mongoc_socket_recv ( + ss->sock, iov[cur].iov_base, iov[cur].iov_len, 0, expire_at); + + if (nread <= 0) { + if (ret >= (ssize_t) min_bytes) { + RETURN (ret); + } + errno = mongoc_socket_errno (ss->sock); + RETURN (-1); + } + + ret += nread; + + while ((cur < iovcnt) && (nread >= (ssize_t) iov[cur].iov_len)) { + nread -= iov[cur++].iov_len; + } + + if (cur == iovcnt) { + break; + } + + if (ret >= (ssize_t) min_bytes) { + RETURN (ret); + } + + iov[cur].iov_base = ((char *) iov[cur].iov_base) + nread; + iov[cur].iov_len -= nread; + + BSON_ASSERT (iovcnt - cur); + BSON_ASSERT (iov[cur].iov_len); + } + + RETURN (ret); +} + + +static ssize_t +_mongoc_stream_socket_writev (mongoc_stream_t *stream, + mongoc_iovec_t *iov, + size_t iovcnt, + int32_t timeout_msec) +{ + mongoc_stream_socket_t *ss = (mongoc_stream_socket_t *) stream; + int64_t expire_at; + ssize_t ret; + + ENTRY; + + if (ss->sock) { + expire_at = get_expiration (timeout_msec); + ret = mongoc_socket_sendv (ss->sock, iov, iovcnt, expire_at); + errno = mongoc_socket_errno (ss->sock); + RETURN (ret); + } + + RETURN (-1); +} + + +static ssize_t +_mongoc_stream_socket_poll (mongoc_stream_poll_t *streams, + size_t nstreams, + int32_t timeout_msec) + +{ + int i; + ssize_t ret = -1; + mongoc_socket_poll_t *sds; + mongoc_stream_socket_t *ss; + + ENTRY; + + sds = (mongoc_socket_poll_t *) bson_malloc (sizeof (*sds) * nstreams); + + for (i = 0; i < nstreams; i++) { + ss = (mongoc_stream_socket_t *) streams[i].stream; + + if (!ss->sock) { + goto CLEANUP; + } + + sds[i].socket = ss->sock; + sds[i].events = streams[i].events; + } + + ret = mongoc_socket_poll (sds, nstreams, timeout_msec); + + if (ret > 0) { + for (i = 0; i < nstreams; i++) { + streams[i].revents = sds[i].revents; + } + } + +CLEANUP: + bson_free (sds); + + RETURN (ret); +} + + +mongoc_socket_t * +mongoc_stream_socket_get_socket (mongoc_stream_socket_t *stream) /* IN */ +{ + BSON_ASSERT (stream); + + return stream->sock; +} + + +static bool +_mongoc_stream_socket_check_closed (mongoc_stream_t *stream) /* IN */ +{ + mongoc_stream_socket_t *ss = (mongoc_stream_socket_t *) stream; + + ENTRY; + + BSON_ASSERT (stream); + + if (ss->sock) { + RETURN (mongoc_socket_check_closed (ss->sock)); + } + + RETURN (true); +} + + +/* + *-------------------------------------------------------------------------- + * + * mongoc_stream_socket_new -- + * + * Create a new mongoc_stream_t using the mongoc_socket_t for + * read and write underneath. + * + * Returns: + * None. + * + * Side effects: + * None. + * + *-------------------------------------------------------------------------- + */ + +mongoc_stream_t * +mongoc_stream_socket_new (mongoc_socket_t *sock) /* IN */ +{ + mongoc_stream_socket_t *stream; + + BSON_ASSERT (sock); + + stream = (mongoc_stream_socket_t *) bson_malloc0 (sizeof *stream); + stream->vtable.type = MONGOC_STREAM_SOCKET; + stream->vtable.close = _mongoc_stream_socket_close; + stream->vtable.destroy = _mongoc_stream_socket_destroy; + stream->vtable.failed = _mongoc_stream_socket_failed; + stream->vtable.flush = _mongoc_stream_socket_flush; + stream->vtable.readv = _mongoc_stream_socket_readv; + stream->vtable.writev = _mongoc_stream_socket_writev; + stream->vtable.setsockopt = _mongoc_stream_socket_setsockopt; + stream->vtable.check_closed = _mongoc_stream_socket_check_closed; + stream->vtable.poll = _mongoc_stream_socket_poll; + stream->sock = sock; + + return (mongoc_stream_t *) stream; +} diff --git a/pool/shard002/C/0060284_ephy-session-test.c b/pool/shard002/C/0060284_ephy-session-test.c new file mode 100644 index 0000000000000000000000000000000000000000..06b8d624c686836d7c07cb1abfbdc5ff5c6ea68c --- /dev/null +++ b/pool/shard002/C/0060284_ephy-session-test.c @@ -0,0 +1,147 @@ +/* -*- Mode: C; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* + * Copyright © 2012 - Igalia S.L. + * + * Epiphany 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. + * + * Epiphany 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 Epiphany; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, + * Boston, MA 02110-1301 USA + */ + +#include "config.h" +#include "ephy-debug.h" +#include "ephy-embed-container.h" +#include "ephy-embed-prefs.h" +#include "ephy-embed-private.h" +#include "ephy-file-helpers.h" +#include "ephy-private.h" +#include "ephy-shell.h" +#include "ephy-session.h" + +#include +#include +#include +#include + +const char *session_data = +"" +"" + "" + "" + "" +""; + +static void +test_ephy_session_load () +{ + EphySession *session; + gboolean ret; + GList *l; + EphyEmbed *embed; + EphyWebView *view; + + session = EPHY_SESSION (ephy_shell_get_session (ephy_shell)); + g_assert (session); + + ret = ephy_session_load_from_string (session, session_data, -1, 0); + g_assert (ret); + + l = ephy_session_get_windows (session); + g_assert (l); + g_assert_cmpint (g_list_length (l), ==, 1); + + embed = ephy_embed_container_get_active_child (EPHY_EMBED_CONTAINER (l->data)); + g_assert (embed); + view = ephy_embed_get_web_view (embed); + g_assert (view); + g_assert_cmpstr (ephy_web_view_get_address (view), ==, "ephy-about:memory"); + + /* FIXME: Destroy the window. I think ideally we'd like something + * like 'ephy_session_clear ()' to reset everything to its initial + * state here. That or allow EphyShell to be created more than + * once and do it once per test. */ + gtk_widget_destroy (GTK_WIDGET (l->data)); +} + +const char *session_data_many_windows = +"" +"" + "" + "" + "" + "" + "" + "" +""; + +static void +test_ephy_session_load_many_windows () +{ + EphySession *session; + gboolean ret; + GList *l, *p; + EphyEmbed *embed; + EphyWebView *view; + + session = EPHY_SESSION (ephy_shell_get_session (ephy_shell)); + g_assert (session); + + ret = ephy_session_load_from_string (session, session_data_many_windows, -1, 0); + g_assert (ret); + + l = ephy_session_get_windows (session); + g_assert (l); + g_assert_cmpint (g_list_length (l), ==, 2); + + for (p = l; p; p = p->next) { + embed = ephy_embed_container_get_active_child (EPHY_EMBED_CONTAINER (p->data)); + g_assert (embed); + view = ephy_embed_get_web_view (embed); + g_assert (view); + g_assert_cmpstr (ephy_web_view_get_address (view), ==, "ephy-about:epiphany"); + } +} + +int +main (int argc, char *argv[]) +{ + int ret; + + gtk_test_init (&argc, &argv); + + ephy_debug_init (); + ephy_embed_prefs_init (); + + if (!ephy_file_helpers_init (NULL, + EPHY_FILE_HELPERS_PRIVATE_PROFILE | EPHY_FILE_HELPERS_ENSURE_EXISTS, + NULL)) { + g_debug ("Something wrong happened with ephy_file_helpers_init()"); + return -1; + } + + _ephy_shell_create_instance (EPHY_EMBED_SHELL_MODE_TEST); + g_assert (ephy_shell); + + g_test_add_func ("/src/ephy-session/load", + test_ephy_session_load); + + g_test_add_func ("/src/ephy-session/load-many-windows", + test_ephy_session_load_many_windows); + + ret = g_test_run (); + + ephy_file_helpers_shutdown (); + g_object_unref (ephy_shell); + + return ret; +} diff --git a/pool/shard002/C/0060308_matrice_calcul.c b/pool/shard002/C/0060308_matrice_calcul.c new file mode 100644 index 0000000000000000000000000000000000000000..3c72f1c789cc556f9421c89c584edc9197fbd73d --- /dev/null +++ b/pool/shard002/C/0060308_matrice_calcul.c @@ -0,0 +1,97 @@ +/* +** matrice_calcul.c<2> for rt in /home/cruvei_t/repo-rt/src +** +** Made by +** Login +** +** Started on Wed Jun 4 03:01:11 2014 +** Last update Fri Jun 6 15:11:58 2014 +*/ + +#include +#include +#include +#include + +void init(double *matrice) +{ + int i; + + i = 0; + while (i < 9) + matrice[i++] = 0.00; + matrice[0] = 1.00; + matrice[4] = 1.00; + matrice[8] = 1.00; +} + +double *rotation_z(double angle) +{ + double *matrice; + + angle = M_PI * angle / 180.00; + if ((matrice = malloc(9 * sizeof(double))) == NULL) + exit(0); + init(matrice); + matrice[0] = cos(angle); + matrice[1] = sin(angle); + matrice[3] = -sin(angle); + matrice[4] = cos(angle); + return (matrice); +} + +double *rotation_y(double angle) +{ + double *matrice; + + angle = M_PI * angle / 180.00; + if ((matrice = malloc(9 * sizeof(double))) == NULL) + exit(0); + init(matrice); + matrice[0] = cos(angle); + matrice[6] = sin(angle); + matrice[2] = -sin(angle); + matrice[8] = cos(angle); + return (matrice); +} + +double *rotation_x(double angle) +{ + double *matrice; + + angle = M_PI * angle / 180.00; + if ((matrice = malloc(9 * sizeof(double))) == NULL) + exit(0); + init(matrice); + matrice[4] = cos(angle); + matrice[5] = sin(angle); + matrice[7] = -sin(angle); + matrice[8] = cos(angle); + return (matrice); +} + +double *multiplication(double *matrice1, double *matrice2) +{ + double *result; + + result = malloc(9 * sizeof(double)); + result[0] = matrice1[0] * matrice2[0] + matrice1[3] * matrice2[1] + + matrice1[6] * matrice2[2]; + result[1] = matrice1[1] * matrice2[0] + matrice1[4] * matrice2[1] + + matrice1[7] * matrice2[2]; + result[2] = matrice1[2] * matrice2[0] + matrice1[5] * matrice2[1] + + matrice1[8] * matrice2[2]; + result[3] = matrice1[0] * matrice2[3] + matrice1[3] * matrice2[4] + + matrice1[6] * matrice2[5]; + result[4] = matrice1[1] * matrice2[3] + matrice1[4] * matrice2[4] + + matrice1[7] * matrice2[5]; + result[5] = matrice1[2] * matrice2[3] + matrice1[5] * matrice2[4] + + matrice1[8] * matrice2[5]; + result[6] = matrice1[0] * matrice2[6] + matrice1[3] * matrice2[7] + + matrice1[6] * matrice2[8]; + result[7] = matrice1[1] * matrice2[6] + matrice1[4] * matrice2[7] + + matrice1[7] * matrice2[8]; + result[8] = matrice1[2] * matrice2[6] + matrice1[5] * matrice2[7] + + matrice1[8] * matrice2[8]; + return (result); +} diff --git a/pool/shard002/C/0060309_ao_rsound.c b/pool/shard002/C/0060309_ao_rsound.c new file mode 100644 index 0000000000000000000000000000000000000000..bd3cc2f2492ece1e348ef159336f224355770453 --- /dev/null +++ b/pool/shard002/C/0060309_ao_rsound.c @@ -0,0 +1,151 @@ +/* + * RSound audio output driver + * + * Copyright (C) 2011 Hans-Kristian Arntzen + * + * This file is part of mpv. + * + * mpv 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. + * + * mpv 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 mpv. If not, see . + */ + +#include "config.h" + +#include +#include +#include +#include + +#include "mpv_talloc.h" + +#include "options/m_option.h" +#include "osdep/timer.h" +#include "audio/format.h" +#include "ao.h" +#include "internal.h" + +struct priv { + rsound_t *rd; +}; + +static int set_format(struct ao *ao) +{ + int rsd_format; + + switch (ao->format) { + case AF_FORMAT_U8: + rsd_format = RSD_U8; + break; + case AF_FORMAT_S32: + rsd_format = RSD_S32_NE; + break; + default: + rsd_format = RSD_S16_NE; + ao->format = AF_FORMAT_S16; + } + + return rsd_format; +} + +static int init(struct ao *ao) +{ + struct priv *priv = ao->priv; + + if (rsd_init(&priv->rd) < 0) + return -1; + + // Actual channel layout unknown. + struct mp_chmap_sel sel = {0}; + mp_chmap_sel_add_waveext_def(&sel); + if (!ao_chmap_sel_adjust(ao, &sel, &ao->channels)) { + rsd_free(priv->rd); + return -1; + } + + rsd_set_param(priv->rd, RSD_SAMPLERATE, (int[]) { ao->samplerate }); + rsd_set_param(priv->rd, RSD_CHANNELS, (int[]) { ao->channels.num }); + + ao->format = af_fmt_from_planar(ao->format); + + int rsd_format = set_format(ao); + rsd_set_param(priv->rd, RSD_FORMAT, &rsd_format); + + if (rsd_start(priv->rd) < 0) { + rsd_free(priv->rd); + return -1; + } + + return 0; +} + +static void uninit(struct ao *ao) +{ + struct priv *priv = ao->priv; + + rsd_stop(priv->rd); + rsd_free(priv->rd); +} + +static void reset(struct ao *ao) +{ + struct priv *priv = ao->priv; + rsd_stop(priv->rd); + rsd_start(priv->rd); +} + +static void audio_pause(struct ao *ao) +{ + struct priv *priv = ao->priv; + rsd_pause(priv->rd, 1); +} + +static void audio_resume(struct ao *ao) +{ + struct priv *priv = ao->priv; + rsd_pause(priv->rd, 0); +} + +static int get_space(struct ao *ao) +{ + struct priv *priv = ao->priv; + return rsd_get_avail(priv->rd) / ao->sstride; +} + +static int play(struct ao *ao, void **data, int samples, int flags) +{ + struct priv *priv = ao->priv; + return rsd_write(priv->rd, data[0], samples * ao->sstride) / ao->sstride; +} + +static double get_delay(struct ao *ao) +{ + struct priv *priv = ao->priv; + return rsd_delay_ms(priv->rd) / 1000.0; +} + +#define OPT_BASE_STRUCT struct priv + +const struct ao_driver audio_out_rsound = { + .description = "RSound output driver", + .name = "rsound", + .init = init, + .uninit = uninit, + .reset = reset, + .get_space = get_space, + .play = play, + .get_delay = get_delay, + .pause = audio_pause, + .resume = audio_resume, + .priv_size = sizeof(struct priv), +}; + diff --git a/pool/shard002/C/0060311_ramblock.c b/pool/shard002/C/0060311_ramblock.c new file mode 100644 index 0000000000000000000000000000000000000000..e5ea0581508d357cf13faf18f23a3417d07b44e5 --- /dev/null +++ b/pool/shard002/C/0060311_ramblock.c @@ -0,0 +1,128 @@ + +/* ²Î¿¼: + * drivers\block\xd.c + * drivers\block\z2ram.c + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +static struct gendisk *ramblock_disk; +static request_queue_t *ramblock_queue; + +static int major; + +static DEFINE_SPINLOCK(ramblock_lock); + +#define RAMBLOCK_SIZE (1024*1024) +static unsigned char *ramblock_buf; + +static int ramblock_getgeo(struct block_device *bdev, struct hd_geometry *geo) +{ + /* ÈÝÁ¿=heads*cylinders*sectors*512 */ + geo->heads = 2; + geo->cylinders = 32; + geo->sectors = RAMBLOCK_SIZE/2/32/512; + return 0; +} + + +static struct block_device_operations ramblock_fops = { + .owner = THIS_MODULE, + .getgeo = ramblock_getgeo, +}; + +static void do_ramblock_request(request_queue_t * q) +{ + static int r_cnt = 0; + static int w_cnt = 0; + struct request *req; + + //printk("do_ramblock_request %d\n", ++cnt); + + while ((req = elv_next_request(q)) != NULL) { + /* Êý¾Ý´«ÊäÈýÒªËØ: Ô´,Ä¿µÄ,³¤¶È */ + /* Ô´/Ä¿µÄ: */ + unsigned long offset = req->sector * 512; + + /* Ä¿µÄ/Ô´: */ + // req->buffer + + /* ³¤¶È: */ + unsigned long len = req->current_nr_sectors * 512; + + if (rq_data_dir(req) == READ) + { + //printk("do_ramblock_request read %d\n", ++r_cnt); + memcpy(req->buffer, ramblock_buf+offset, len); + } + else + { + //printk("do_ramblock_request write %d\n", ++w_cnt); + memcpy(ramblock_buf+offset, req->buffer, len); + } + + end_request(req, 1); + } +} + +static int ramblock_init(void) +{ + /* 1. ·ÖÅäÒ»¸ögendisk½á¹¹Ìå */ + ramblock_disk = alloc_disk(16); /* ´ÎÉ豸ºÅ¸öÊý: ·ÖÇø¸öÊý+1 */ + + /* 2. ÉèÖà */ + /* 2.1 ·ÖÅä/ÉèÖöÓÁÐ: Ìṩ¶ÁдÄÜÁ¦ */ + ramblock_queue = blk_init_queue(do_ramblock_request, &ramblock_lock); + ramblock_disk->queue = ramblock_queue; + + /* 2.2 ÉèÖÃÆäËûÊôÐÔ: ±ÈÈçÈÝÁ¿ */ + major = register_blkdev(0, "ramblock"); /* cat /proc/devices */ + ramblock_disk->major = major; + ramblock_disk->first_minor = 0; + sprintf(ramblock_disk->disk_name, "ramblock"); + ramblock_disk->fops = &ramblock_fops; + set_capacity(ramblock_disk, RAMBLOCK_SIZE / 512); + + /* 3. Ó²¼þÏà¹Ø²Ù×÷ */ + ramblock_buf = kzalloc(RAMBLOCK_SIZE, GFP_KERNEL); + + /* 4. ×¢²á */ + add_disk(ramblock_disk); + + return 0; +} + +static void ramblock_exit(void) +{ + unregister_blkdev(major, "ramblock"); + del_gendisk(ramblock_disk); + put_disk(ramblock_disk); + blk_cleanup_queue(ramblock_queue); + + kfree(ramblock_buf); +} + +module_init(ramblock_init); +module_exit(ramblock_exit); + +MODULE_LICENSE("GPL"); + diff --git a/pool/shard002/C/0060332_Arp.c b/pool/shard002/C/0060332_Arp.c new file mode 100644 index 0000000000000000000000000000000000000000..5e07a6f96ebec2fad41cfc35200c0b91aa94885f --- /dev/null +++ b/pool/shard002/C/0060332_Arp.c @@ -0,0 +1,170 @@ +/* +Copyright 2014 Cloudbase Solutions Srl + +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 "Arp.h" +#include "Ipv4.h" + +extern PNDIS_RW_LOCK_EX g_pArpRWLock; +extern LIST_ENTRY g_arpTable; + +typedef struct _OVS_ARP_TABLE_ENTRY +{ + LIST_ENTRY listEntry; + BYTE ip[4]; + BYTE mac[OVS_ETHERNET_ADDRESS_LENGTH]; +}OVS_ARP_TABLE_ENTRY, *POVS_ARP_TABLE_ENTRY; + +OVS_ARP_HEADER* GetArpHeader(_In_ OVS_ETHERNET_HEADER* pEthHeader) +{ + UINT8* buffer = (UINT8*)(pEthHeader)+sizeof(OVS_ETHERNET_HEADER); + + OVS_ARP_HEADER* pArpHeader = (OVS_ARP_HEADER*)buffer; + OVS_CHECK(pArpHeader); + + return pArpHeader; +} + +BYTE* VerifyArpFrame(BYTE* buffer, ULONG* pLength) +{ + OVS_ARP_HEADER* pArpHeader = (OVS_ARP_HEADER*)buffer; + OVS_CHECK(pArpHeader); + WORD op = RtlUshortByteSwap(pArpHeader->operation); + + if (RtlUshortByteSwap(pArpHeader->hardwareType) != OVS_ARP_HARDWARE_TYPE_ETHERNET) + { + DEBUGP(LOG_ERROR, "arp: hardware type = 0x%x != 1", RtlUshortByteSwap(pArpHeader->hardwareType)); + return NULL; + } + + if (pArpHeader->harwareLength != OVS_ETHERNET_ADDRESS_LENGTH) + { + DEBUGP(LOG_ERROR, "arp: hardware length = 0x%x != 6", pArpHeader->harwareLength); + return NULL; + } + + if (op != OVS_ARP_OPERATION_REQUEST && + op != OVS_ARP_OPERATION_REPLY) + { + DEBUGP(LOG_ERROR, "arp: op unknown - 0x%x", RtlUshortByteSwap(pArpHeader->operation)); + return NULL; + } + + if (pArpHeader->protocolLength != OVS_IPV4_ADDRESS_LENGTH) + { + DEBUGP(LOG_ERROR, "arp: protocol length = 0x%x != 4", pArpHeader->harwareLength); + return NULL; + } + + if (RtlUshortByteSwap(pArpHeader->protocolType) != OVS_ETHERTYPE_IPV4) + { + DEBUGP(LOG_ERROR, "arp: protocol type = 0x%x != ipv4", RtlUshortByteSwap(pArpHeader->protocolType)); + return NULL; + } + + *pLength -= sizeof(OVS_ARP_HEADER); + return buffer + sizeof(OVS_ARP_HEADER); +} + +static BYTE* _Arp_FindTableEntry_Unsafe(_In_ const BYTE ip[4]) +{ + PLIST_ENTRY pCurEntry = g_arpTable.Flink; + + if (IsListEmpty(&g_arpTable)) + { + return NULL; + } + + do + { + OVS_ARP_TABLE_ENTRY* pArpEntry = CONTAINING_RECORD(pCurEntry, OVS_ARP_TABLE_ENTRY, listEntry); + + if (RtlEqualMemory(ip, pArpEntry->ip, sizeof(OVS_IPV4_ADDRESS_LENGTH))) + { + OVS_CHECK(pArpEntry->mac); + return pArpEntry->mac; + } + + pCurEntry = pCurEntry->Flink; + } while (pCurEntry != &g_arpTable); + + return NULL; +} + +VOID Arp_InsertTableEntry(_In_ const BYTE ip[4], _In_ const BYTE mac[OVS_ETHERNET_ADDRESS_LENGTH]) +{ + LOCK_STATE_EX lockState = { 0 }; + BYTE* pMacAddr = NULL; + + NdisAcquireRWLockWrite(g_pArpRWLock, &lockState, 0); + + pMacAddr = _Arp_FindTableEntry_Unsafe(ip); + if (!pMacAddr) + { + OVS_ARP_TABLE_ENTRY* pArpEntry = NULL; + + pArpEntry = KAlloc(sizeof(OVS_ARP_TABLE_ENTRY)); + if (!pArpEntry) + { + DEBUGP(LOG_ERROR, "Failed to allocate arp table entry!\n"); + return; + } + + RtlCopyMemory(pArpEntry->ip, ip, OVS_IPV4_ADDRESS_LENGTH); + RtlCopyMemory(pArpEntry->mac, mac, OVS_ETHERNET_ADDRESS_LENGTH); + + InsertHeadList(&g_arpTable, &pArpEntry->listEntry); + } + else + { + RtlCopyMemory(pMacAddr, mac, OVS_ETHERNET_ADDRESS_LENGTH); + } + + NdisReleaseRWLock(g_pArpRWLock, &lockState); +} + +const BYTE* Arp_FindTableEntry(_In_ const BYTE ip[4]) +{ + LOCK_STATE_EX lockState = { 0 }; + const BYTE* pMac = NULL; + + NdisAcquireRWLockRead(g_pArpRWLock, &lockState, 0); + + pMac = _Arp_FindTableEntry_Unsafe(ip); + + NdisReleaseRWLock(g_pArpRWLock, &lockState); + + return pMac; +} + +VOID Arp_DestroyTable() +{ + OVS_ARP_TABLE_ENTRY* pArpEntry = NULL; + PLIST_ENTRY headList = NULL; + LOCK_STATE_EX lockState = { 0 }; + + NdisAcquireRWLockWrite(g_pArpRWLock, &lockState, 0); + + while (!IsListEmpty(&g_arpTable)) + { + headList = RemoveHeadList(&g_arpTable); + + pArpEntry = CONTAINING_RECORD(headList, OVS_ARP_TABLE_ENTRY, listEntry); + + KFree(pArpEntry); + } + + NdisReleaseRWLock(g_pArpRWLock, &lockState); +} \ No newline at end of file diff --git a/pool/shard002/C/0060334_dag37t_api.c b/pool/shard002/C/0060334_dag37t_api.c new file mode 100644 index 0000000000000000000000000000000000000000..1398441dc201cca4de5b1e38a6445dff6c4ea2dc --- /dev/null +++ b/pool/shard002/C/0060334_dag37t_api.c @@ -0,0 +1,268 @@ +/* + * Copyright (c) 2006 Endace Technology Ltd, Hamilton, New Zealand. + * All rights reserved. + * + * This source code is proprietary to Endace Technology Limited and no part + * of it may be redistributed, published or disclosed except as outlined in + * the written contract supplied with this product. + * + * $Id: dag37t_api.c,v 1.6 2009/06/18 00:06:50 vladimir Exp $ + */ + + + + +#include "dag_platform.h" +#include "dagutil.h" +#include "dagapi.h" + + + +#include "../include/channel_config/dag37t_chan_cfg.h" +#include "../include/channel_config/dag37t_map_functions.h" + +extern const int phy_to_logical_line[16]; + +/* This file contains all of the dag 3.7T api functions which do not fit + * nicely into the add channel or delete channel category + */ + +uint32_t dag_set_mux(int dagfd, + uint32_t host_mode, + uint32_t line_mode, + uint32_t iop_mode) +{ + uint8_t* dagiom = dag_iom(dagfd); + + iom_write(dagiom, MUX_HOST, 0xFFFFFFFF, host_mode); + iom_write(dagiom, MUX_LINE, 0xFFFFFFFF, line_mode); + iom_write(dagiom, MUX_IOP, 0xFFFFFFFF, iop_mode); + + + return 0; +} /* dag_set_mux */ + + + + + +int dag_ifc_hec (int dagfd, + uint32_t iface, + uint32_t option) +{ + + modules_t module, module1, module2; + uint8_t* dagiom = dag_iom(dagfd); + uint32_t line = 0; + uint32_t bit_val = 0; + daginf_t* daginf; + + daginf = dag_info(dagfd); + if(daginf->device_code == PCI_DEVICE_ID_DAG3_7T4) + { + } + else if(daginf->device_code == PCI_DEVICE_ID_DAG3_70T) + {} + line = phy_to_logical_line[iface]; + + module1.type = UNDEFINED; + module2.type = UNDEFINED; + + /* check the ATM_RX Module is loaded */ + get_firmware_modules(dagfd, &module1, &module2); + + + if(module1.type != MOD_ATM_RX ) + { + if( module2.type != MOD_ATM_RX ) + { + dagutil_verbose_level(1, "ATM receive is not loaded, Header correction is not available\n"); + return -1; + } + else + module = module2; + } + else + module = module1; + + + if(option) + bit_val = (1 << (16 + line)); + + + iom_write(dagiom, module.addr+ LINE_FEATURE_CTRL_REG, (1 << (16 + line)), bit_val); + + return 0; + +} + +int get_dag_ifc_hec (int dagfd, + uint32_t iface) +{ + + modules_t module, module1, module2; + uint8_t* dagiom = dag_iom(dagfd); + uint32_t line = 0; + uint32_t reg_val = 0; + uint32_t bit_val = 0; + daginf_t* daginf; + + daginf = dag_info(dagfd); + if(daginf->device_code == PCI_DEVICE_ID_DAG3_7T4) + { + } + else if(daginf->device_code == PCI_DEVICE_ID_DAG3_70T) + { } + + line = phy_to_logical_line[iface]; + + module1.type = UNDEFINED; + module2.type = UNDEFINED; + + /* check the ATM_RX Module is loaded */ + get_firmware_modules(dagfd, &module1, &module2); + + + if(module1.type != MOD_ATM_RX ) + { + if( module2.type != MOD_ATM_RX ) + { + dagutil_verbose_level(1, "ATM receive is not loaded, Header correction is not available\n"); + return -1; + } + else + module = module2; + } + else + module = module1; + + reg_val = iom_read(dagiom, module.addr+ LINE_FEATURE_CTRL_REG); + + bit_val = (1 << (16 + line)); + + if(bit_val & reg_val) + return 1; + + return 0; + +} + + + +int dag_ifc_cell_scrambling (int dagfd, + uint32_t iface, + uint32_t option) +{ + + modules_t module, module1, module2; + uint8_t* dagiom = dag_iom(dagfd); + uint32_t line = 0; + uint32_t bit_val = 0; + daginf_t* daginf; + + daginf = dag_info(dagfd); + if(daginf->device_code == PCI_DEVICE_ID_DAG3_7T4) + { + } + else if(daginf->device_code == PCI_DEVICE_ID_DAG3_70T) + {}; + + line = phy_to_logical_line[iface]; + + module1.type = UNDEFINED; + module2.type = UNDEFINED; + + /* check the ATM_RX Module is loaded */ + get_firmware_modules(dagfd, &module1, &module2); + + if(module1.type != MOD_ATM_RX ) + { + if( module2.type != MOD_ATM_RX ) + { + dagutil_verbose_level(1, "ATM receive is not loaded, cell scrambling is not available\n"); + return -1; + } + else + module = module2; + } + else + module = module1; + + if(option) + bit_val = (1 << (line)); + + + iom_write(dagiom, module.addr+ LINE_FEATURE_CTRL_REG, (1 << (line)), bit_val); + + return 0; + +} + +int get_dag_ifc_cell_scrambling (int dagfd, + uint32_t iface) +{ + + modules_t module, module1, module2; + uint8_t* dagiom = dag_iom(dagfd); + uint32_t line = 0; + uint32_t reg_val = 0; + uint32_t bit_val = 0; + daginf_t* daginf; + + daginf = dag_info(dagfd); + #if 0 + if(daginf->device_code == PCI_DEVICE_ID_DAG3_7T4) + { + } + else if(daginf->device_code == PCI_DEVICE_ID_DAG3_70T) + {}; + #endif + line = phy_to_logical_line[iface]; + + module1.type = UNDEFINED; + module2.type = UNDEFINED; + + /* check the ATM_RX Module is loaded */ + get_firmware_modules(dagfd, &module1, &module2); + + if(module1.type != MOD_ATM_RX ) + { + if( module2.type != MOD_ATM_RX ) + { + dagutil_verbose_level(1, "ATM receive is not loaded, cell scrambling is not available\n"); + return -1; + } + else + module = module2; + } + else + module = module1; + + bit_val = (1 << (line)); + + + reg_val = iom_read(dagiom, module.addr+ LINE_FEATURE_CTRL_REG); + + + if(reg_val & bit_val) + return 1; + + return 0; + +} + + +int dag_reset_37t(int dagfd) +{ + + dagutil_verbose_level(1, "This function \"dag_reset_37t\" has been deprecated and will be removed\n"); + + return 0; +} + +void dag_channel_verbosity(uint32_t verb) +{ + dagutil_verbose_level(1, "This function \"dag_channel_verbosity\" has been deprecated and will be removed. Please use dagutil_set_verbosity instead\n"); + dagutil_set_verbosity(verb); +} + diff --git a/pool/shard002/C/0060335_dbz.c b/pool/shard002/C/0060335_dbz.c new file mode 100644 index 0000000000000000000000000000000000000000..e0b0c527a7b96bc9b506a152cfd4a245a19a1829 --- /dev/null +++ b/pool/shard002/C/0060335_dbz.c @@ -0,0 +1,167 @@ +/* + This file is part of miscutil. + Copyright (C) 2015-2018, Robert L. Thompson + + 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 . +*/ + +#define _FILE_OFFSET_BITS 64 +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +static bool dbz_discard(int fd, uint64_t *range) +{ + bool ret = false; + + if (range[1] != 0 && ioctl(fd, BLKDISCARD, range) != 0) { + perror("ioctl(BLKDISCARD)"); + goto fail; + } + + ret = true; +fail: + return ret; +} + +static bool dbz(const char *devpath, const char *fname, bool query) +{ + bool ret = false; + int fd = -1, fdr = -1; + unsigned does_zero, blksz, blk, i, flags = O_RDWR; + uint64_t range[2]; + struct stat stdev, stfile; + + if (!query && fname == NULL) + flags |= O_EXCL; + fd = open(devpath, flags); + if (fd < 0) { + perror("open(devnode)"); + goto fail; + } + if (fstat(fd, &stdev) != 0) { + perror("stat(devnode)"); + goto fail; + } + if (!S_ISBLK(stdev.st_mode)) { + fprintf(stderr, "%s is not a block device\n", devpath); + goto fail; + } + + if (query) { + if (ioctl(fd, BLKDISCARDZEROES, &does_zero) != 0) { + perror("ioctl(BLKDISCARDZEROES)"); + goto fail; + } + if (does_zero == 0) { + fprintf(stderr, "Device does NOT return zeroes for discarded blocks.\n"); + goto fail; + } + fprintf(stderr, "Device DOES return zeroes for discarded blocks.\n"); + } else { + if (fname != NULL) { + fdr = open(fname, O_RDWR); + if (fdr < 0) { + perror("open(file)"); + goto fail; + } + if (fstat(fdr, &stfile) != 0) { + perror("stat(file)"); + goto fail; + } + if (!S_ISREG(stfile.st_mode)) { + fprintf(stderr, "%s is not a regular file\n", fname); + goto fail; + } + if (stdev.st_rdev != stfile.st_dev) { + fprintf(stderr, "%s is not the mounted device containing %s\n", devpath, fname); + goto fail; + } + + if (ioctl(fdr, FIGETBSZ, &blksz) != 0) { + perror("ioctl(FIGETBSZ)"); + goto fail; + } + range[0] = 0; + range[1] = 0; + for (i = 0; i < stfile.st_size / blksz; i++) { + blk = i; + if (ioctl(fdr, FIBMAP, &blk) != 0) { + perror("ioctl(FIBMAP)"); + goto fail; + } + if (blk == 0) + continue; + if (blk == (range[0] + range[1]) / blksz) { + range[1] += blksz; + continue; + } + if (!dbz_discard(fd, range)) + goto fail; + range[0] = (uint64_t)blk * blksz; + range[1] = blksz; + } + if (!dbz_discard(fd, range)) + goto fail; + } else { + range[0] = 0; + if (ioctl(fd, BLKGETSIZE64, &range[1]) != 0) { + perror("ioctl(BLKGETSIZE64)"); + goto fail; + } + if (!dbz_discard(fd, range)) + goto fail; + } + } + + ret = true; +fail: + if (fd >= 0) + close(fd); + if (fdr >= 0) + close(fdr); + return ret; +} + +int main(int argc, char **argv) +{ + int ret = EXIT_FAILURE; + bool query = true; + + if (argc < 3 || argc > 4) + goto usage; + + if (strcmp(argv[1], "-q") != 0) { + if (strcmp(argv[1], "-d") != 0) + goto usage; + query = false; + } + if (!dbz(argv[2], argv[3], query)) + goto fail; + ret = EXIT_SUCCESS; +fail: + return ret; +usage: + fprintf(stderr, "%s [ -q | -d ] /dev/mmcblkX [ /mount/point/dir/file.rm ]\n", argv[0]); + goto fail; +} diff --git a/pool/shard002/C/0060342_tftpread.c b/pool/shard002/C/0060342_tftpread.c new file mode 100644 index 0000000000000000000000000000000000000000..2b5ca8c06ce53b47c7865fb65a74e1e21da96c9c --- /dev/null +++ b/pool/shard002/C/0060342_tftpread.c @@ -0,0 +1,113 @@ +/* + * Copyright © 2012 Bart Massey + * [This program is licensed under the "MIT License"] + * Please see the file COPYING in the source + * distribution of this software for license terms. + */ + + +/* TFTP client read program. */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +static unsigned char msgbuf[516]; + +static int format_rrq(char *filename) { + char *modestr = "octet"; + msgbuf[0] = 0; + msgbuf[1] = 1; + strcpy((char *)msgbuf + 2, filename); + strcpy((char *)msgbuf + 2 + strlen(filename) + 1, modestr); + return 2 + strlen(filename) + 1 + strlen(modestr) + 1; +} + +static int process_response(int msglen, int blocknum) { + /* XXX should check msglen in case of corrupt packet */ + unsigned short opcode = (msgbuf[0] << 8) | msgbuf[1]; + switch (opcode) { + case 5 /* error */: + fprintf(stderr, "error: %s\n", msgbuf + 4); + exit(1); + case 3 /* data */: { + int actualblock = (msgbuf[2] << 8) | msgbuf[3]; + if (actualblock != blocknum) { + fprintf(stderr, "received unexpected block %d\n", actualblock); + return -1; + } + int r = fwrite(msgbuf + 4, 1, msglen - 4, stdout); + assert(r == msglen - 4); + return msglen - 4; } + } + fprintf(stderr, "unknown opcode 0x%04x received, giving up\n", opcode); + exit(1); +} + +void format_ack(int blocknum) { + msgbuf[0] = 0; + msgbuf[1] = 4; + msgbuf[2] = (blocknum >> 8) & 0xff; + msgbuf[3] = blocknum & 0xff; +} + +int main(int argc, char **argv) { + assert(argc == 3); + + /* XXX Should try for raw IP address first. */ + struct hostent *h = gethostbyname(argv[1]); + if (!h) { + herror("bad destination"); + exit(1); + } + assert(h->h_addrtype == AF_INET); + + int s = socket(AF_INET, SOCK_DGRAM, 0); + assert(s != -1); + + struct sockaddr_in sin; + sin.sin_family = AF_INET; + sin.sin_port = htons(69); + /* XXX Should try all the addresses in the list. */ + sin.sin_addr.s_addr = *(uint32_t *)h->h_addr; + + int size = format_rrq(argv[2]); + int r = sendto(s, msgbuf, size, 0, + (const struct sockaddr *)&sin, (socklen_t)sizeof(sin)); + assert(r == size); + + struct sockaddr_in ssin; + socklen_t ssaddrlen = sizeof(ssin); + r = recvfrom(s, (void *)msgbuf, sizeof(msgbuf), 0, + (struct sockaddr *)&ssin, &ssaddrlen); + assert(r >= 0); + + int blocknum = 1; + while (1) { + int transferred = process_response(r, blocknum); + if (transferred == -1) + continue; + format_ack(blocknum); + r = sendto(s, msgbuf, size, 0, + (const struct sockaddr *)&ssin, (socklen_t)sizeof(ssin)); + if (transferred < 512) { +#ifdef DEBUG + fprintf(stderr, "processing last %d bytes\n", transferred); +#endif + break; + } + ssaddrlen = sizeof(ssin); + r = recvfrom(s, (void *)msgbuf, sizeof(msgbuf), 0, + (struct sockaddr *)&ssin, &ssaddrlen); + assert(r >= 0); + blocknum++; + } + + return 0; +} diff --git a/pool/shard002/C/0060348_linked_list.c b/pool/shard002/C/0060348_linked_list.c new file mode 100644 index 0000000000000000000000000000000000000000..7b2dd845484702eb21efc6d866112643e3cdd756 --- /dev/null +++ b/pool/shard002/C/0060348_linked_list.c @@ -0,0 +1,126 @@ +/******************************************************************************* + * This file is part of libutils. + * + * libutils 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. + * + * libutils 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 libutils; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + ******************************************************************************/ + + +#include "utils/linked_list.h" + +linked_list_t *linked_list_create(size_t elem_size) + { + linked_list_t *list; + if(elem_size==0) + return NULL; + list=malloc(sizeof(linked_list_t)); + if(list==NULL) + return NULL; + list->elem_size=elem_size; + list->head=NULL; + list->size=0; + return list; + } + +int linked_list_add_head(linked_list_t *list, void *e) + { + struct list_node *node; + if(list==NULL || e==NULL) + return 1; + node=malloc(sizeof(linked_node_t)+list->elem_size); + if(node==NULL) + return 2; + node->prev=NULL; + node->next=list->head; + list->head->prev=node; + list->head=node; + list->size++; + return 0; + } + +int linked_list_add_tail(linked_list_t *list, void *e) + { + struct list_node *node; + if(list==NULL || e==NULL) + return 1; + node=malloc(sizeof(linked_node_t)+list->elem_size); + if(node==NULL) + return 2; + node->prev=NULL; + node->next=list->head; + list->head->prev=node; + list->head=node; + list->size++; + return 0; + } + +int linked_list_it_has_next(iterator_t *i) + { + struct linked_list_it *it=(struct linked_list_it*)i; + if(it==NULL || it->cur==NULL) + return 0; + return it->cur->next!=NULL; + } +void *linked_list_it_next(iterator_t *i) + { + struct linked_list_it *it=(struct linked_list_it*)i; + void *e; + if(it==NULL) + return NULL; + if(it->cur) + it->cur=it->cur->next; + return it->cur->data; + } +int linked_list_it_remove(iterator_t *i) + { + struct linked_list_it *it=(struct linked_list_it*)i; + linked_node_t *node; + if(it==NULL || it->cur==NULL) + return 1; + node=it->cur->prev; + node->next=it->cur->next; + it->cur->next->prev=node; + it->list->size--; + return 0; + } + +int linked_list_it_reset(iterator_t *i) + { + struct linked_list_it *it=(struct linked_list_it*)i; + linked_node_t *node; + if(it==NULL) + return 1; + it->cur=it->list->head; + return 0; + } + +iterator_t *linked_list_iterator(linked_list_t *list) + { + struct linked_list_it *it; + if(list==NULL) + return NULL; + + it=malloc(sizeof(struct linked_list_it)); + + it->it.has_next=&linked_list_it_has_next; + it->it.next=&linked_list_it_next; + it->it.reset=&linked_list_it_reset; + it->it.remove=&linked_list_it_remove; + it->it.dispose=(void (*)(iterator_t *))&free; + + it->list=list; + it->cur=list->head; + + return (iterator_t*)it; + } diff --git a/pool/shard002/C/0060356_msjava.c b/pool/shard002/C/0060356_msjava.c new file mode 100644 index 0000000000000000000000000000000000000000..5bd49ec0bb981f2b5166f24cee21c6b87cee0aa9 --- /dev/null +++ b/pool/shard002/C/0060356_msjava.c @@ -0,0 +1,75 @@ +/* +mediastreamer2 library - modular sound and video processing and streaming +Copyright (C) 2010 Belledonne Communications SARL + +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 "mediastreamer2/msjava.h" +#include "mediastreamer2/mscommon.h" + +static JavaVM *ms2_vm=NULL; + +#ifndef WIN32 +#include + +static pthread_key_t jnienv_key; + +void _android_key_cleanup(void *data){ + ms_message("Thread end, detaching jvm from current thread"); + JNIEnv* env=(JNIEnv*)pthread_getspecific(jnienv_key); + if (env != NULL) { + (*ms2_vm)->DetachCurrentThread(ms2_vm); + pthread_setspecific(jnienv_key,NULL); + } +} +#endif + + + +void ms_set_jvm(JavaVM *vm){ + ms2_vm=vm; +#ifndef WIN32 + pthread_key_create(&jnienv_key,_android_key_cleanup); +#endif +} + +JavaVM *ms_get_jvm(void){ + return ms2_vm; +} + +JNIEnv *ms_get_jni_env(void){ + JNIEnv *env=NULL; + if (ms2_vm==NULL){ + ms_fatal("Calling ms_get_jni_env() while no jvm has been set using ms_set_jvm()."); + }else{ +#ifndef WIN32 + env=(JNIEnv*)pthread_getspecific(jnienv_key); + if (env==NULL){ + if ((*ms2_vm)->AttachCurrentThread(ms2_vm,&env,NULL)!=0){ + ms_fatal("AttachCurrentThread() failed !"); + return NULL; + } + pthread_setspecific(jnienv_key,env); + } +#else + ms_fatal("ms_get_jni_env() not implemented on windows."); +#endif + } + return env; +} + + + diff --git a/pool/shard002/C/0060357_iptool.c b/pool/shard002/C/0060357_iptool.c new file mode 100644 index 0000000000000000000000000000000000000000..909e7b006ffb1232fac35baba5fd27a011acc3f2 --- /dev/null +++ b/pool/shard002/C/0060357_iptool.c @@ -0,0 +1,58 @@ +/* C binding for IP Tool. + * + * Implementation of the C iptool library. + * This will be compiled into a .o which can + * then be linked to any C program. + * + * Wrappers handle freeing of the Strings from + * Rust for the user. + * + * Author: + * Tim Monfette + */ + +#include +#include +#include "iptool.h" + +// Wrapper for valid_ipv4 +void valid_ipv4_c(char* userInput, char* buf) { + char* result = valid_ipv4(userInput); + strcpy(buf, result); // copy string from Rust mem to C + free_string(result); // free string on Rust mem side +} + +// Wrapper for ipv4_ipv6 +void ipv4_ipv6_c(char* userInput, char* buf) { + char* result = ipv4_ipv6(userInput); + strcpy(buf, result); + free_string(result); +} + +// Wrapper for ipv4_bin +void ipv4_bin_c(char* userInput, char* buf) { + char* result = ipv4_bin(userInput); + strcpy(buf, result); + free_string(result); +} + +// Wrapper for valid_ipv6 +void valid_ipv6_c(char* userInput, char* buf) { + char* result = valid_ipv6(userInput); + strcpy(buf, result); + free_string(result); +} + +// Wrapper for ipv6_ipv4 +void ipv6_ipv4_c(char* userInput, char* buf) { + char* result = ipv6_ipv4(userInput); + strcpy(buf, result); + free_string(result); +} + +// Wrapper for ipv6_bin +void ipv6_bin_c(char* userInput, char* buf) { + char* result = ipv6_bin(userInput); + strcpy(buf, result); + free_string(result); +} diff --git a/pool/shard002/C/0060362_MsNetworkCapability.c b/pool/shard002/C/0060362_MsNetworkCapability.c new file mode 100644 index 0000000000000000000000000000000000000000..bda91e876a21af334414038b4cc947fde7fa6700 --- /dev/null +++ b/pool/shard002/C/0060362_MsNetworkCapability.c @@ -0,0 +1,102 @@ +/* + * Copyright (c) 2015, EURECOM (www.eurecom.fr) + * 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 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. + * + * The views and conclusions contained in the software and documentation are those + * of the authors and should not be interpreted as representing official policies, + * either expressed or implied, of the FreeBSD Project. + */ +#include +#include +#include + + +#include "TLVEncoder.h" +#include "TLVDecoder.h" +#include "MsNetworkCapability.h" + +int decode_ms_network_capability(MsNetworkCapability *msnetworkcapability, uint8_t iei, uint8_t *buffer, uint32_t len) +{ + int decoded = 0; + uint8_t ielen = 0; + int decode_result; + + if (iei > 0) { + CHECK_IEI_DECODER(iei, *buffer); + decoded++; + } + + ielen = *(buffer + decoded); + decoded++; + CHECK_LENGTH_DECODER(len - decoded, ielen); + + if ((decode_result = decode_octet_string(&msnetworkcapability->msnetworkcapabilityvalue, ielen, buffer + decoded, len - decoded)) < 0) + return decode_result; + else + decoded += decode_result; + +#if defined (NAS_DEBUG) + dump_ms_network_capability_xml(msnetworkcapability, iei); +#endif + return decoded; +} +int encode_ms_network_capability(MsNetworkCapability *msnetworkcapability, uint8_t iei, uint8_t *buffer, uint32_t len) +{ + uint8_t *lenPtr; + uint32_t encoded = 0; + int encode_result; + /* Checking IEI and pointer */ + CHECK_PDU_POINTER_AND_LENGTH_ENCODER(buffer, MS_NETWORK_CAPABILITY_MINIMUM_LENGTH, len); +#if defined (NAS_DEBUG) + dump_ms_network_capability_xml(msnetworkcapability, iei); +#endif + + if (iei > 0) { + *buffer = iei; + encoded++; + } + + lenPtr = (buffer + encoded); + encoded ++; + + if ((encode_result = encode_octet_string(&msnetworkcapability->msnetworkcapabilityvalue, buffer + encoded, len - encoded)) < 0) + return encode_result; + else + encoded += encode_result; + + *lenPtr = encoded - 1 - ((iei > 0) ? 1 : 0); + return encoded; +} + +void dump_ms_network_capability_xml(MsNetworkCapability *msnetworkcapability, uint8_t iei) +{ + printf("\n"); + + if (iei > 0) + /* Don't display IEI if = 0 */ + printf(" 0x%X\n", iei); + + printf("%s",dump_octet_string_xml(&msnetworkcapability->msnetworkcapabilityvalue)); + printf("\n"); +} + diff --git a/pool/shard002/C/0060363_HPMmap.c b/pool/shard002/C/0060363_HPMmap.c new file mode 100644 index 0000000000000000000000000000000000000000..091a53311dfcdf022e2348967e491ce3d8d23cf4 --- /dev/null +++ b/pool/shard002/C/0060363_HPMmap.c @@ -0,0 +1,215 @@ +/** + * This file is part of Hercules. + * http://herc.ws - http://github.com/HerculesWS/Hercules + * + * Copyright (C) 2013-2015 Hercules Dev Team + * + * Hercules 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 . + */ +#define HERCULES_CORE + +#include "HPMmap.h" + +#include "common/HPM.h" +#include "common/cbasetypes.h" + +#include "common/HPMi.h" +#include "common/conf.h" +#include "common/console.h" +#include "common/core.h" +#include "common/db.h" +#include "common/des.h" +#include "common/ers.h" +#include "common/grfio.h" +#include "common/md5calc.h" +#include "common/memmgr.h" +#include "common/mutex.h" +#include "common/mapindex.h" +#include "common/mmo.h" +#include "common/nullpo.h" +#include "common/random.h" +#include "common/showmsg.h" +#include "common/socket.h" +#include "common/spinlock.h" +#include "common/sql.h" +#include "common/strlib.h" +#include "common/sysinfo.h" +#include "common/timer.h" +#include "common/utils.h" +#include "map/achievement.h" +#include "map/atcommand.h" +#include "map/battle.h" +#include "map/battleground.h" +#include "map/buyingstore.h" +#include "map/channel.h" +#include "map/chat.h" +#include "map/chrif.h" +#include "map/clan.h" +#include "map/clif.h" +#include "map/date.h" +#include "map/duel.h" +#include "map/elemental.h" +#include "map/guild.h" +#include "map/homunculus.h" +#include "map/instance.h" +#include "map/intif.h" +#include "map/irc-bot.h" +#include "map/itemdb.h" +#include "map/log.h" +#include "map/mail.h" +#include "map/map.h" +#include "map/mapreg.h" +#include "map/mercenary.h" +#include "map/mob.h" +#include "map/npc.h" +#include "map/packets_struct.h" +#include "map/party.h" +#include "map/path.h" +#include "map/pc.h" +#include "map/pc_groups.h" +#include "map/pet.h" +#include "map/quest.h" +#include "map/rodex.h" +#include "map/script.h" +#include "map/searchstore.h" +#include "map/skill.h" +#include "map/status.h" +#include "map/storage.h" +#include "map/trade.h" +#include "map/unit.h" +#include "map/vending.h" + +// HPMDataCheck comes after all the other includes +#include "common/HPMDataCheck.h" + +#include +#include + +struct HPM_atcommand_list { + //tracking currently not enabled + // - requires modifying how plugins calls atcommand creation + // - needs load/unload during runtime support + //unsigned int pID;/* plugin id */ + char name[ATCOMMAND_LENGTH]; + AtCommandFunc func; +}; + +static struct HPM_atcommand_list *atcommand_list = NULL; +static unsigned int atcommand_list_items = 0; + +/** + * HPM plugin data store validator sub-handler (map-server) + * + * @see HPM_interface::data_store_validate + */ +bool HPM_map_data_store_validate(enum HPluginDataTypes type, struct hplugin_data_store **storeptr, bool initialize) +{ + switch (type) { + case HPDT_MSD: + case HPDT_NPCD: + case HPDT_MAP: + case HPDT_PARTY: + case HPDT_GUILD: + case HPDT_INSTANCE: + case HPDT_MOBDB: + case HPDT_MOBDATA: + case HPDT_ITEMDATA: + case HPDT_BGDATA: + case HPDT_AUTOTRADE_VEND: + case HPDT_CLAN: + // Initialized by the caller. + return true; + default: + break; + } + return false; +} + +void HPM_map_plugin_load_sub(struct hplugin *plugin) +{ + plugin->hpi->sql_handle = map->mysql_handle; + plugin->hpi->addCommand = atcommand->create; + plugin->hpi->addScript = script->addScript; + plugin->hpi->addPCGPermission = HPM_map_add_group_permission; +} + +bool HPM_map_add_atcommand(char *name, AtCommandFunc func) +{ + unsigned int i = 0; + + for(i = 0; i < atcommand_list_items; i++) { + if( !strcmpi(atcommand_list[i].name,name) ) { + ShowDebug("HPM_map_add_atcommand: duplicate command '%s', skipping...\n", name); + return false; + } + } + + i = atcommand_list_items; + + RECREATE(atcommand_list, struct HPM_atcommand_list , ++atcommand_list_items); + + safestrncpy(atcommand_list[i].name, name, sizeof(atcommand_list[i].name)); + atcommand_list[i].func = func; + + return true; +} + +void HPM_map_atcommands(void) +{ + unsigned int i; + + for(i = 0; i < atcommand_list_items; i++) { + atcommand->add(atcommand_list[i].name,atcommand_list[i].func,true); + } +} + +/** + * Adds a new group permission to the HPM-provided list + **/ +void HPM_map_add_group_permission(unsigned int pluginID, char *name, unsigned int *mask) +{ + unsigned char index = pcg->HPMpermissions_count; + + RECREATE(pcg->HPMpermissions, struct pc_groups_new_permission, ++pcg->HPMpermissions_count); + + pcg->HPMpermissions[index].pID = pluginID; + pcg->HPMpermissions[index].name = aStrdup(name); + pcg->HPMpermissions[index].mask = mask; +} + +void HPM_map_do_init(void) +{ + HPM->load_sub = HPM_map_plugin_load_sub; + HPM->data_store_validate_sub = HPM_map_data_store_validate; + HPM->datacheck_init(HPMDataCheck, HPMDataCheckLen, HPMDataCheckVer); + HPM_shared_symbols(SERVER_TYPE_MAP); +} + +void HPM_map_do_final(void) +{ + if (atcommand_list) + aFree(atcommand_list); + /** + * why is pcg->HPM being cleared here? because PCG's do_final is not final, + * is used on reload, and would thus cause plugin-provided permissions to go away + **/ + if (pcg->HPMpermissions) { + unsigned char i; + for (i = 0; i < pcg->HPMpermissions_count; i++) { + aFree(pcg->HPMpermissions[i].name); + } + aFree(pcg->HPMpermissions); + } + HPM->datacheck_final(); +} diff --git a/pool/shard002/C/0060370_digest_auth_example.c b/pool/shard002/C/0060370_digest_auth_example.c new file mode 100644 index 0000000000000000000000000000000000000000..98db4acf9be93d76a41342f1ab0f1a4232be5cc7 --- /dev/null +++ b/pool/shard002/C/0060370_digest_auth_example.c @@ -0,0 +1,140 @@ +/* + This file is part of libmicrohttpd + (C) 2010 Christian Grothoff (and other contributing authors) + + 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 +*/ +/** + * @file digest_auth_example.c + * @brief minimal example for how to use digest auth with libmicrohttpd + * @author Amr Ali + */ + +#include "platform.h" +#include +#include + +#define PAGE "libmicrohttpd demoAccess granted" + +#define DENIED "libmicrohttpd demoAccess denied" + +#define OPAQUE "11733b200778ce33060f31c9af70a870ba96ddd4" + +static int +ahc_echo (void *cls, + struct MHD_Connection *connection, + const char *url, + const char *method, + const char *version, + const char *upload_data, size_t *upload_data_size, void **ptr) +{ + struct MHD_Response *response; + char *username; + const char *password = "testpass"; + const char *realm = "test@example.com"; + int ret; + + username = MHD_digest_auth_get_username(connection); + if (username == NULL) + { + response = MHD_create_response_from_buffer(strlen (DENIED), + DENIED, + MHD_RESPMEM_PERSISTENT); + ret = MHD_queue_auth_fail_response(connection, realm, + OPAQUE, + response, + MHD_NO); + MHD_destroy_response(response); + return ret; + } + ret = MHD_digest_auth_check(connection, realm, + username, + password, + 300); + free(username); + if ( (ret == MHD_INVALID_NONCE) || + (ret == MHD_NO) ) + { + response = MHD_create_response_from_buffer(strlen (DENIED), + DENIED, + MHD_RESPMEM_PERSISTENT); + if (NULL == response) + return MHD_NO; + ret = MHD_queue_auth_fail_response(connection, realm, + OPAQUE, + response, + (ret == MHD_INVALID_NONCE) ? MHD_YES : MHD_NO); + MHD_destroy_response(response); + return ret; + } + response = MHD_create_response_from_buffer(strlen(PAGE), PAGE, + MHD_RESPMEM_PERSISTENT); + ret = MHD_queue_response(connection, MHD_HTTP_OK, response); + MHD_destroy_response(response); + return ret; +} + +int +main (int argc, char *const *argv) +{ + int fd; + char rnd[8]; + size_t len; + size_t off; + struct MHD_Daemon *d; + + if (argc != 2) + { + printf ("%s PORT\n", argv[0]); + return 1; + } + fd = open("/dev/urandom", O_RDONLY); + if (-1 == fd) + { + fprintf (stderr, "Failed to open `%s': %s\n", + "/dev/urandom", + strerror (errno)); + return 1; + } + off = 0; + while (off < 8) + { + len = read(fd, rnd, 8); + if (len == -1) + { + fprintf (stderr, "Failed to read `%s': %s\n", + "/dev/urandom", + strerror (errno)); + (void) close (fd); + return 1; + } + off += len; + } + (void) close(fd); + d = MHD_start_daemon (MHD_USE_THREAD_PER_CONNECTION | MHD_USE_DEBUG, + atoi (argv[1]), + NULL, NULL, &ahc_echo, PAGE, + MHD_OPTION_DIGEST_AUTH_RANDOM, sizeof(rnd), rnd, + MHD_OPTION_NONCE_NC_SIZE, 300, + MHD_OPTION_CONNECTION_TIMEOUT, (unsigned int) 120, + MHD_OPTION_END); + if (d == NULL) + return 1; + (void) getc (stdin); + MHD_stop_daemon (d); + return 0; +} + +/* end of digest_auth_example.c */ diff --git a/pool/shard002/C/0060400_buffer_putallnf.c b/pool/shard002/C/0060400_buffer_putallnf.c new file mode 100644 index 0000000000000000000000000000000000000000..d7a290912bc52c1b852185c8aaddbe4c75c6cb3d --- /dev/null +++ b/pool/shard002/C/0060400_buffer_putallnf.c @@ -0,0 +1,15 @@ +/* ISC license. */ + +#include +#include + +int buffer_putallnoflush (buffer *b, char const *s, size_t len) +{ + ssize_t r = buffer_putnoflush(b, s, len) ; + if (r < len) + { + buffer_unput(b, r) ; + return (errno = ENOBUFS, 0) ; + } + return 1 ; +} diff --git a/pool/shard002/C/0060405_gpd-pocket-fan.c b/pool/shard002/C/0060405_gpd-pocket-fan.c new file mode 100644 index 0000000000000000000000000000000000000000..b471b86c28fe8d2e15aca3766de871e2dfececad --- /dev/null +++ b/pool/shard002/C/0060405_gpd-pocket-fan.c @@ -0,0 +1,229 @@ +// SPDX-License-Identifier: GPL-2.0+ +/* + * GPD Pocket fan controller driver + * + * Copyright (C) 2017 Hans de Goede + */ + +#include +#include +#include +#include +#include +#include +#include +#include + +#define MAX_SPEED 3 + +#define TEMP_LIMIT0_DEFAULT 55000 +#define TEMP_LIMIT1_DEFAULT 60000 +#define TEMP_LIMIT2_DEFAULT 65000 + +#define HYSTERESIS_DEFAULT 3000 + +#define SPEED_ON_AC_DEFAULT 2 + +static int temp_limits[3] = { + TEMP_LIMIT0_DEFAULT, TEMP_LIMIT1_DEFAULT, TEMP_LIMIT2_DEFAULT, +}; +module_param_array(temp_limits, int, NULL, 0444); +MODULE_PARM_DESC(temp_limits, + "Millicelsius values above which the fan speed increases"); + +static int hysteresis = HYSTERESIS_DEFAULT; +module_param(hysteresis, int, 0444); +MODULE_PARM_DESC(hysteresis, + "Hysteresis in millicelsius before lowering the fan speed"); + +static int speed_on_ac = SPEED_ON_AC_DEFAULT; +module_param(speed_on_ac, int, 0444); +MODULE_PARM_DESC(speed_on_ac, + "minimum fan speed to allow when system is powered by AC"); + +struct gpd_pocket_fan_data { + struct device *dev; + struct thermal_zone_device *dts0; + struct thermal_zone_device *dts1; + struct gpio_desc *gpio0; + struct gpio_desc *gpio1; + struct delayed_work work; + int last_speed; +}; + +static void gpd_pocket_fan_set_speed(struct gpd_pocket_fan_data *fan, int speed) +{ + if (speed == fan->last_speed) + return; + + gpiod_direction_output(fan->gpio0, !!(speed & 1)); + gpiod_direction_output(fan->gpio1, !!(speed & 2)); + + fan->last_speed = speed; +} + +static int gpd_pocket_fan_min_speed(void) +{ + if (power_supply_is_system_supplied()) + return speed_on_ac; + else + return 0; +} + +static void gpd_pocket_fan_worker(struct work_struct *work) +{ + struct gpd_pocket_fan_data *fan = + container_of(work, struct gpd_pocket_fan_data, work.work); + int t0, t1, temp, speed, min_speed, i; + + if (thermal_zone_get_temp(fan->dts0, &t0) || + thermal_zone_get_temp(fan->dts1, &t1)) { + dev_warn(fan->dev, "Error getting temperature\n"); + speed = MAX_SPEED; + goto set_speed; + } + + temp = max(t0, t1); + + speed = fan->last_speed; + min_speed = gpd_pocket_fan_min_speed(); + + /* Determine minimum speed */ + for (i = min_speed; i < ARRAY_SIZE(temp_limits); i++) { + if (temp < temp_limits[i]) + break; + } + if (speed < i) + speed = i; + + /* Use hysteresis before lowering speed again */ + for (i = min_speed; i < ARRAY_SIZE(temp_limits); i++) { + if (temp <= (temp_limits[i] - hysteresis)) + break; + } + if (speed > i) + speed = i; + + if (fan->last_speed <= 0 && speed) + speed = MAX_SPEED; /* kick start motor */ + +set_speed: + gpd_pocket_fan_set_speed(fan, speed); + + /* When mostly idle (low temp/speed), slow down the poll interval. */ + queue_delayed_work(system_wq, &fan->work, + msecs_to_jiffies(4000 / (speed + 1))); +} + +static void gpd_pocket_fan_force_update(struct gpd_pocket_fan_data *fan) +{ + fan->last_speed = -1; + mod_delayed_work(system_wq, &fan->work, 0); +} + +static int gpd_pocket_fan_probe(struct platform_device *pdev) +{ + struct gpd_pocket_fan_data *fan; + int i; + + for (i = 0; i < ARRAY_SIZE(temp_limits); i++) { + if (temp_limits[i] < 20000 || temp_limits[i] > 90000) { + dev_err(&pdev->dev, "Invalid temp-limit %d (must be between 40000 and 70000)\n", + temp_limits[i]); + temp_limits[0] = TEMP_LIMIT0_DEFAULT; + temp_limits[1] = TEMP_LIMIT1_DEFAULT; + temp_limits[2] = TEMP_LIMIT2_DEFAULT; + break; + } + } + if (hysteresis < 1000 || hysteresis > 10000) { + dev_err(&pdev->dev, "Invalid hysteresis %d (must be between 1000 and 10000)\n", + hysteresis); + hysteresis = HYSTERESIS_DEFAULT; + } + if (speed_on_ac < 0 || speed_on_ac > MAX_SPEED) { + dev_err(&pdev->dev, "Invalid speed_on_ac %d (must be between 0 and 3)\n", + speed_on_ac); + speed_on_ac = SPEED_ON_AC_DEFAULT; + } + + fan = devm_kzalloc(&pdev->dev, sizeof(*fan), GFP_KERNEL); + if (!fan) + return -ENOMEM; + + fan->dev = &pdev->dev; + INIT_DELAYED_WORK(&fan->work, gpd_pocket_fan_worker); + + /* Note this returns a "weak" reference which we don't need to free */ + fan->dts0 = thermal_zone_get_zone_by_name("soc_dts0"); + if (IS_ERR(fan->dts0)) + return -EPROBE_DEFER; + + fan->dts1 = thermal_zone_get_zone_by_name("soc_dts1"); + if (IS_ERR(fan->dts1)) + return -EPROBE_DEFER; + + fan->gpio0 = devm_gpiod_get_index(fan->dev, NULL, 0, GPIOD_ASIS); + if (IS_ERR(fan->gpio0)) + return PTR_ERR(fan->gpio0); + + fan->gpio1 = devm_gpiod_get_index(fan->dev, NULL, 1, GPIOD_ASIS); + if (IS_ERR(fan->gpio1)) + return PTR_ERR(fan->gpio1); + + gpd_pocket_fan_force_update(fan); + + platform_set_drvdata(pdev, fan); + return 0; +} + +static int gpd_pocket_fan_remove(struct platform_device *pdev) +{ + struct gpd_pocket_fan_data *fan = platform_get_drvdata(pdev); + + cancel_delayed_work_sync(&fan->work); + return 0; +} + +#ifdef CONFIG_PM_SLEEP +static int gpd_pocket_fan_suspend(struct device *dev) +{ + struct gpd_pocket_fan_data *fan = dev_get_drvdata(dev); + + cancel_delayed_work_sync(&fan->work); + gpd_pocket_fan_set_speed(fan, gpd_pocket_fan_min_speed()); + return 0; +} + +static int gpd_pocket_fan_resume(struct device *dev) +{ + struct gpd_pocket_fan_data *fan = dev_get_drvdata(dev); + + gpd_pocket_fan_force_update(fan); + return 0; +} +#endif +static SIMPLE_DEV_PM_OPS(gpd_pocket_fan_pm_ops, + gpd_pocket_fan_suspend, + gpd_pocket_fan_resume); + +static struct acpi_device_id gpd_pocket_fan_acpi_match[] = { + { "FAN02501" }, + {}, +}; +MODULE_DEVICE_TABLE(acpi, gpd_pocket_fan_acpi_match); + +static struct platform_driver gpd_pocket_fan_driver = { + .probe = gpd_pocket_fan_probe, + .remove = gpd_pocket_fan_remove, + .driver = { + .name = "gpd_pocket_fan", + .acpi_match_table = gpd_pocket_fan_acpi_match, + .pm = &gpd_pocket_fan_pm_ops, + }, +}; + +module_platform_driver(gpd_pocket_fan_driver); +MODULE_AUTHOR("Hans de Goede +#include +#include +#if !NACL_ANDROID +#include +#endif + +#include "native_client/src/include/nacl_macros.h" +#include "native_client/src/shared/platform/nacl_check.h" +#include "native_client/src/trusted/service_runtime/linux/android_compat.h" +#include "native_client/src/trusted/service_runtime/nacl_config.h" +#include "native_client/src/trusted/service_runtime/sel_main.h" +#include "native_client/src/trusted/fault_injection/test_injection.h" +#include "native_client/tests/thread_capture/thread_capture_test_injection.h" + +uintptr_t g_nacl_syscall_thread_capture_fault_addr; + +void NaClSegVHandler(int signum, siginfo_t *info, void *other) { + uintptr_t faulting_pc; + ucontext_t *ucp; + + UNREFERENCED_PARAMETER(info); + ucp = (ucontext_t *) other; +#if NACL_LINUX +# if NACL_ARCH(NACL_BUILD_ARCH) == NACL_x86 +# if NACL_BUILD_SUBARCH == 32 + faulting_pc = ucp->uc_mcontext.gregs[REG_EIP]; +# elif NACL_BUILD_SUBARCH == 64 + faulting_pc = ucp->uc_mcontext.gregs[REG_RIP]; +# else +# error "128-bit version of x86?!?" +# endif +# elif NACL_ARCH(NACL_BUILD_ARCH) == NACL_arm + faulting_pc = ucp->uc_mcontext.arm_pc; +# else +# error "how do i get the PC on this cpu architecture?" +# endif +#elif NACL_OSX +# if NACL_ARCH(NACL_BUILD_ARCH) == NACL_x86 +# if NACL_BUILD_SUBARCH == 32 + /* typeof(ucp->uc_mcontext) is struct __darwin_mcontext32 *. */ + faulting_pc = ucp->uc_mcontext->__ss.__eip; +# else + faulting_pc = ucp->uc_mcontext->__ss.__rip; +# endif +# else +# error "fix this for non-x86 OSX" +# endif +#else +# error "signals on Windows?!?" +#endif + + /* + * Normally printf is unsafe in signal handlers, but we should only + * get here due to hitting an explicit hlt instruction and we + * shouldn't be in the middle of an I/O routine. + */ + printf("signal %d\n", signum); + printf("faulting_pc 0x%"NACL_PRIxPTR"\n", faulting_pc); + printf("NaClSyscallThreadCaptureFault 0x%"NACL_PRIxPTR"\n", + g_nacl_syscall_thread_capture_fault_addr); + + CHECK(signum == SIGSEGV); + CHECK(g_nacl_syscall_thread_capture_fault_addr == faulting_pc); + exit(0); +} + +static char g_nacl_altstack[SIGSTKSZ + 4096]; + +void NaClSetSignalHandler(void) { + struct sigaction action; + stack_t stack; + + stack.ss_sp = g_nacl_altstack; + stack.ss_flags = 0; + stack.ss_size = NACL_ARRAY_SIZE(g_nacl_altstack); + sigaltstack(&stack, (stack_t *) NULL); + + memset(&action, 0, sizeof action); + action.sa_sigaction = NaClSegVHandler; + sigfillset(&action.sa_mask); + action.sa_flags = SA_ONSTACK | SA_SIGINFO; + + CHECK(0 == sigaction(SIGSEGV, &action, (struct sigaction *) NULL)); +} + +static struct NaClTestInjectionTable const g_test_injection_functions = { + NaClInjectThreadCaptureSyscall, /* ChangeTrampolines */ + NaClSetSignalHandler, /* BeforeMainThreadLaunches */ +}; + +int main(int argc, char **argv) { + NaClTestInjectionSetInjectionTable(&g_test_injection_functions); + (void) NaClSelLdrMain(argc, argv); + return 1; /* fail! */ +} diff --git a/pool/shard002/C/0060410_dpkg_deb.c b/pool/shard002/C/0060410_dpkg_deb.c new file mode 100644 index 0000000000000000000000000000000000000000..3c540a711ff955bf1a687890531009ea47049e31 --- /dev/null +++ b/pool/shard002/C/0060410_dpkg_deb.c @@ -0,0 +1,101 @@ +/* vi: set sw=4 ts=4: */ +/* + * dpkg-deb packs, unpacks and provides information about Debian archives. + * + * Licensed under GPLv2, see file LICENSE in this tarball for details. + */ +#include +#include +#include +#include + +#include "unarchive.h" +#include "busybox.h" + +#define DPKG_DEB_OPT_CONTENTS 1 +#define DPKG_DEB_OPT_CONTROL 2 +#define DPKG_DEB_OPT_FIELD 4 +#define DPKG_DEB_OPT_EXTRACT 8 +#define DPKG_DEB_OPT_EXTRACT_VERBOSE 16 + +int dpkg_deb_main(int argc, char **argv) +{ + archive_handle_t *ar_archive; + archive_handle_t *tar_archive; + llist_t *control_tar_llist = NULL; + unsigned long opt; + char *extract_dir = NULL; + short argcount = 1; + + /* Setup the tar archive handle */ + tar_archive = init_handle(); + + /* Setup an ar archive handle that refers to the gzip sub archive */ + ar_archive = init_handle(); + ar_archive->sub_archive = tar_archive; + ar_archive->filter = filter_accept_list_reassign; + +#ifdef CONFIG_FEATURE_DEB_TAR_GZ + llist_add_to(&(ar_archive->accept), "data.tar.gz"); + llist_add_to(&control_tar_llist, "control.tar.gz"); +#endif + +#ifdef CONFIG_FEATURE_DEB_TAR_BZ2 + llist_add_to(&(ar_archive->accept), "data.tar.bz2"); + llist_add_to(&control_tar_llist, "control.tar.bz2"); +#endif + + bb_opt_complementally = "?c--efXx:e--cfXx:f--ceXx:X--cefx:x--cefX"; + opt = bb_getopt_ulflags(argc, argv, "cefXx"); + + if (opt & DPKG_DEB_OPT_CONTENTS) { + tar_archive->action_header = header_verbose_list; + } + if (opt & DPKG_DEB_OPT_CONTROL) { + ar_archive->accept = control_tar_llist; + tar_archive->action_data = data_extract_all; + if (optind + 1 == argc) { + extract_dir = "./DEBIAN"; + } else { + argcount++; + } + } + if (opt & DPKG_DEB_OPT_FIELD) { + /* Print the entire control file + * it should accept a second argument which specifies a + * specific field to print */ + ar_archive->accept = control_tar_llist; + llist_add_to(&(tar_archive->accept), "./control"); + tar_archive->filter = filter_accept_list; + tar_archive->action_data = data_extract_to_stdout; + } + if (opt & DPKG_DEB_OPT_EXTRACT) { + tar_archive->action_header = header_list; + } + if (opt & (DPKG_DEB_OPT_EXTRACT_VERBOSE | DPKG_DEB_OPT_EXTRACT)) { + tar_archive->action_data = data_extract_all; + argcount = 2; + } + + if ((optind + argcount) != argc) { + bb_show_usage(); + } + + tar_archive->src_fd = ar_archive->src_fd = bb_xopen(argv[optind++], O_RDONLY); + + /* Workout where to extract the files */ + /* 2nd argument is a dir name */ + if (argv[optind]) { + extract_dir = argv[optind]; + } + if (extract_dir) { + mkdir(extract_dir, 0777); /* bb_make_directory(extract_dir, 0777, 0) */ + bb_xchdir(extract_dir); + } + unpack_ar_archive(ar_archive); + + /* Cleanup */ + close (ar_archive->src_fd); + + return(EXIT_SUCCESS); +} diff --git a/pool/shard002/C/0060418_northbridge.c b/pool/shard002/C/0060418_northbridge.c new file mode 100644 index 0000000000000000000000000000000000000000..4e5f37802b8968d3d994c4557102788fea304c57 --- /dev/null +++ b/pool/shard002/C/0060418_northbridge.c @@ -0,0 +1,210 @@ +/* + * This file is part of the coreboot project. + * + * Copyright (C) 2007-2009 coresystems GmbH + * Copyright (C) 2015 Damien Zammit + * + * 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 +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +static void mch_domain_read_resources(device_t dev) +{ + u8 index; + u64 tom, touud; + u32 tomk, tseg_sizek, tolud, usable_tomk; + u32 pcie_config_base, pcie_config_size; + u32 uma_sizek = 0; + + const u32 top32memk = 4 * (GiB / KiB); + index = 3; + + /* 1024KiB TSEG */ + tseg_sizek = 1024; + + pci_domain_read_resources(dev); + + /* Top of Upper Usable DRAM, including remap */ + touud = pci_read_config16(dev, D0F0_TOUUD); + touud <<= 20; + + /* Top of Lower Usable DRAM */ + tolud = pci_read_config16(dev, D0F0_TOLUD) & 0xfff0; + tolud <<= 16; + + /* Top of Memory - does not account for any UMA */ + tom = pci_read_config16(dev, D0F0_TOM) & 0x01ff; + tom <<= 26; + + printk(BIOS_DEBUG, "TOUUD 0x%llx TOLUD 0x%08x TOM 0x%llx\n", + touud, tolud, tom); + + tomk = tolud >> 10; + + /* Graphics memory comes next */ + const u16 ggc = pci_read_config16(dev, D0F0_GGC); + printk(BIOS_DEBUG, "IGD decoded, subtracting "); + + /* Graphics memory */ + const u32 gms_sizek = decode_igd_memory_size((ggc >> 4) & 0xf); + printk(BIOS_DEBUG, "%uM UMA", gms_sizek >> 10); + + /* GTT Graphics Stolen Memory Size (GGMS) */ + const u32 gsm_sizek = decode_igd_gtt_size((ggc >> 8) & 0xf); + printk(BIOS_DEBUG, " and %uM GTT\n", gsm_sizek >> 10); + + uma_sizek = gms_sizek + gsm_sizek + tseg_sizek; + usable_tomk = tomk - uma_sizek; + + printk(BIOS_INFO, "Available memory below 4GB: %uM\n", usable_tomk >> 10); + + /* Report the memory regions */ + ram_resource(dev, index++, 0, 0xa0000 >> 10); + ram_resource(dev, index++, 1*MiB >> 10, (usable_tomk - (1*MiB >> 10))); + + /* + * If >= 4GB installed then memory from TOLUD to 4GB + * is remapped above TOM, TOUUD will account for both + */ + touud >>= 10; /* Convert to KB */ + if (touud > top32memk) { + ram_resource(dev, index++, top32memk, touud - top32memk); + printk(BIOS_INFO, "Available memory above 4GB: %lluM\n", + (touud - top32memk) >> 10); + } + + printk(BIOS_DEBUG, "Adding UMA memory area base=0x%08x " + "size=0x%08x\n", usable_tomk << 10, uma_sizek << 10); + fixed_mem_resource(dev, index++, usable_tomk, uma_sizek, + IORESOURCE_RESERVE); + + /* Reserve high memory where the NB BARs are up to 4GiB */ + fixed_mem_resource(dev, index++, DEFAULT_HECIBAR >> 10, + top32memk - (DEFAULT_HECIBAR >> 10), + IORESOURCE_RESERVE); + + if (decode_pciebar(&pcie_config_base, &pcie_config_size)) { + printk(BIOS_DEBUG, "Adding PCIe config bar base=0x%08x " + "size=0x%x\n", pcie_config_base, pcie_config_size); + fixed_mem_resource(dev, index++, pcie_config_base >> 10, + pcie_config_size >> 10, IORESOURCE_RESERVE); + } +} + +static void mch_domain_set_resources(device_t dev) +{ + struct resource *res; + + for (res = dev->resource_list; res; res = res->next) + report_resource_stored(dev, res, ""); + + assign_resources(dev->link_list); +} + +static void mch_domain_init(device_t dev) +{ + u32 reg32; + + /* Enable SERR */ + reg32 = pci_read_config32(dev, PCI_COMMAND); + reg32 |= PCI_COMMAND_SERR; + pci_write_config32(dev, PCI_COMMAND, reg32); +} + +static struct device_operations pci_domain_ops = { + .read_resources = mch_domain_read_resources, + .set_resources = mch_domain_set_resources, + .init = mch_domain_init, + .scan_bus = pci_domain_scan_bus, + .ops_pci_bus = pci_bus_default_ops, + .write_acpi_tables = northbridge_write_acpi_tables, + .acpi_fill_ssdt_generator = generate_cpu_entries, +}; + + +static void cpu_bus_init(device_t dev) +{ + initialize_cpus(dev->link_list); +} + +static struct device_operations cpu_bus_ops = { + .read_resources = DEVICE_NOOP, + .set_resources = DEVICE_NOOP, + .enable_resources = DEVICE_NOOP, + .init = cpu_bus_init, +}; + + +static void enable_dev(device_t dev) +{ + /* Set the operations if it is a special bus type */ + if (dev->path.type == DEVICE_PATH_DOMAIN) + dev->ops = &pci_domain_ops; + else if (dev->path.type == DEVICE_PATH_CPU_CLUSTER) + dev->ops = &cpu_bus_ops; +} + +static void x4x_init(void *const chip_info) +{ + int dev, fn, bit_base; + + struct device *const d0f0 = dev_find_slot(0, 0); + + /* Hide internal functions based on devicetree info. */ + for (dev = 3; dev > 0; --dev) { + switch (dev) { + case 3: /* ME */ + fn = 3; + bit_base = 6; + break; + case 2: /* IGD */ + fn = 1; + bit_base = 3; + break; + case 1: /* PEG */ + fn = 0; + bit_base = 1; + break; + } + for (; fn >= 0; --fn) { + const struct device *const d = + dev_find_slot(0, PCI_DEVFN(dev, fn)); + if (!d || d->enabled) + continue; + const u32 deven = pci_read_config32(d0f0, D0F0_DEVEN); + pci_write_config32(d0f0, D0F0_DEVEN, + deven & ~(1 << (bit_base + fn))); + } + } + + const u32 deven = pci_read_config32(d0f0, D0F0_DEVEN); + if (!(deven & (0xf << 6))) + pci_write_config32(d0f0, D0F0_DEVEN, deven & ~(1 << 14)); +} + +struct chip_operations northbridge_intel_x4x_ops = { + CHIP_NAME("Intel 4-Series Northbridge") + .enable_dev = enable_dev, + .init = x4x_init, +}; diff --git a/pool/shard002/C/0060438_onepole.c b/pool/shard002/C/0060438_onepole.c new file mode 100644 index 0000000000000000000000000000000000000000..91fa6aee1ed50015c2514f255d41778d0c9844d5 --- /dev/null +++ b/pool/shard002/C/0060438_onepole.c @@ -0,0 +1,72 @@ +//One pole filter, with normalized peak gain +// +// 1 +//H(z) = ---------- +// 1 - r z^-1 +// +//for stability, |r| < 1 +//peak gain = 1/(1-r) for r > 0 +// = 1/(1+r) for r < 0 +#include +#include + +#include "gen.h" + +struct onepole_history_s { + double y1; +}; +typedef struct onepole_history_s onepole_history_t[1]; +typedef struct onepole_history_s *onepole_history_ptr; + +void onepole_init(gen_ptr g) +{ +} + +void onepole_clear(gen_ptr g) +{ +} + +void *onepole_note_on() +{ + onepole_history_ptr p = malloc(sizeof(onepole_history_t)); + p->y1 = 0.0; + return p; +} + +void onepole_note_free(void *data) +{ + free(data); +} + +double onepole_tick(gen_t g, gen_data_ptr gd, double *value) +{ + onepole_history_ptr h = (onepole_history_ptr) gd->data; + double y; + double r = double_clip(value[1], -1.0, 1.0); + double a; + + if (r > 0.0) { + a = 1.0 - r; + } else { + a = 1.0 + r; + } + y = a * value[0] + r * h->y1; + h->y1 = y; + return y; +} + +char *onepole_port_list[] = { "input", "pole" }; + +struct gen_info_s onepole_info = { + "onepole", + "One Pole Filter", + onepole_init, + onepole_clear, + onepole_note_on, + onepole_note_free, + onepole_tick, + 2, + onepole_port_list, + 0, + NULL, +}; diff --git a/pool/shard002/C/0060471_bchip.c b/pool/shard002/C/0060471_bchip.c new file mode 100644 index 0000000000000000000000000000000000000000..07aaf330e17c943e28b6108ff3ac4c90208d10e4 --- /dev/null +++ b/pool/shard002/C/0060471_bchip.c @@ -0,0 +1,187 @@ +/* + * arch/mips/brcmstb/brcm97400a0/bchip.c + * + * Copyright (C) 2004-2006 Broadcom 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. + * + * 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. + * + * + * Board Specific routines for Broadcom eval boards + * + * when who what + * ---- --- ---- + * 06-09-2006 RYH Full implementation of 7400a0 RAC + */ + +#include +#include +#include +#include +#include +#include + + +#if 1 +/* + * THT 2/09/06: Initializes the core address space, so that RAC __AND__ the flash will work. + * We must call this very early, unless the CFE has already done it, even though we don't enable RAC + * Failing to do so will result in a bus error when accessing the flash around 0x01a4_0000 offset. + */ +static int gRAC_init_called; +static __init int RAC_init(void) +{ + volatile unsigned long cba; + + if (gRAC_init_called) + return 1; + + gRAC_init_called = 1; + cba = __read_32bit_c0_register($22, 6); + printk("======> Before RAC_init:$22s5=%08x, $22s6(CBA)=%08x \n", __read_32bit_c0_register($22, 5), cba); + if (cba == 0x11f0000c) { + printk("@B1F0_001C=%08x, @B1F0_0004=%08x, @B1F0_0000=%08x, @B1F0_0008=%08x\n", + *((volatile unsigned long*) 0xB1F0001C), + *((volatile unsigned long*) 0xB1F00004), + *((volatile unsigned long*) 0xB1F00000), + *((volatile unsigned long*) 0xB1F00008) + ); + } + else { + printk("Invalid value for CBA. Please update your bootloader\n"); + //BUG(); _RAC_init will straighten things out. + } + +#if 0 + // PR 29586: don't touch LLMB or RAC settings + _RAC_init(); +#endif + + return 0; +} + +core_initcall(RAC_init); + +#endif + + +extern unsigned int par_val2; +extern void bcm_inv_rac_all(void); + +#define RAC_CONFIGURATION0_REGISTER 0x00000000 +#define RAC_CONFIGURATION1_REGISTER 0x00000008 +#define RAC_ADDRESS_RANGE_REGISTER 0x00000004 + +#define DEFAULT_RAC_CONFIGURATION 0x00087000 /* WRV = '10'b, PGMSZ = '111'b */ + +#define DEV_RD(x) (*((volatile uint32_t *)(x))) +#define DEV_WR(x, y) do { *((volatile uint32_t *)(x)) = (y); } while(0) + +extern unsigned long rac_config0, rac_config1, rac_address_range; + +int rac_setting(int value) +{ + unsigned long rac_value; + char msg[256]; + unsigned long cba=__read_32bit_c0_register($22, 6); + + if (!gRAC_init_called) { + RAC_init(); + } + cba &= 0xFFFC0000; + + rac_config0 = cba + 0xA0000000 + RAC_CONFIGURATION0_REGISTER; + rac_config1 = cba + 0xA0000000 + RAC_CONFIGURATION1_REGISTER; + rac_address_range = cba + 0xA0000000 + RAC_ADDRESS_RANGE_REGISTER; + + printk("CBA = %08x VALUE = %d PAR_VAL2 = %08x\n", cba, value, par_val2); + printk("RAC0 = %08x RAC1 = %x RAC_RANGE = %08x\n", rac_config0, rac_config1, rac_address_range); + + sprintf(msg, "before init RAC 0x%08x 0x%08x 0x%08x\n", + DEV_RD(rac_config0), DEV_RD(rac_config1), + DEV_RD(rac_address_range)); + uart_puts(msg); + + + switch(value) { + case 0: /* RAC disabled, PF_D='0'b, PF_I='0'b, RAC_D='0'b, RAC_I='0'b */ + rac_value = 0x00000000; + break; + + case 1: /* I-RAC enabled, C_INV='1'b, PF_D='0'b, PF_I='1'b, RAC_D='0'b, RAC_I='1'b */ + bcm_inv_rac_all(); + rac_value = 0x00000015; + break; + + case 2: /* D-RAC enabled, C_INV='1'b, PF_D='1'b, PF_I='0'b, RAC_D='1'b, RAC_I='0'b */ + bcm_inv_rac_all(); + rac_value = 0x0000001A; + break; + + case 3: /* I/D-RAC enabled, PF_D='1'b, PF_I='1'b, RAC_D='1'b, RAC_I='1'b */ + bcm_inv_rac_all(); + rac_value = 0x0000000F; + break; + + case 11: /* I/D-RAC enabled, C_INV='1'b, PF_D='1'b, PF_I='1'b, RAC_D='1'b, RAC_I='1'b */ + bcm_inv_rac_all(); + rac_value = 0x0000001F; + break; + case 0xff: /* leave existing RAC setting intact */ + bcm_inv_rac_all(); + rac_value = 0; + break; + + default: /* unspecified value, set to default */ + bcm_inv_rac_all(); + rac_value = 0x0000001F; + sprintf(msg, "Invalid input for 7401a0 RAC mode setting. Default setting(RAC disabled) applied.\n"); + uart_puts(msg); + break; + } + + if(value != 0xff) + { + rac_value |= DEFAULT_RAC_CONFIGURATION; + printk("RAC_VALUE = %08x\n", rac_value); + + DEV_WR(rac_config0, (DEV_RD(rac_config0) & ~0x1f) | rac_value); + DEV_WR(rac_config1, (DEV_RD(rac_config1) & ~0x1f) | rac_value); + DEV_WR(rac_address_range, par_val2); + + // clear WRV (space reservation by way - set to unreserved) + // set DPF (directional prefetching) + DEV_WR(rac_config0, (DEV_RD(rac_config0) & ~(3 << 18)) | (1 << 6)); + + sprintf(msg, "after init RAC 0x%08x 0x%08x 0x%08x\n", + DEV_RD(rac_config0), DEV_RD(rac_config1), + DEV_RD(rac_address_range)); + + uart_puts(msg); + } else { + /* PR 29586: 7400b0 Linux should not initialize RAC */ + printk("******* RAC initialization is performed by CFE on this platform\n"); + } + + printk("******* $22s0=%08x, $22s5=%08x, $22s6=%08x\n", + __read_32bit_c0_register($22, 0), + __read_32bit_c0_register($22, 5), + __read_32bit_c0_register($22, 6)); + + + return 0; +} + + + diff --git a/pool/shard002/C/0060473_main.c b/pool/shard002/C/0060473_main.c new file mode 100644 index 0000000000000000000000000000000000000000..ced75258f8833389faad92f18db6ea7be2803bf5 --- /dev/null +++ b/pool/shard002/C/0060473_main.c @@ -0,0 +1,182 @@ +/* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 8 -*- + * vim: set et ts=8 sw=8: + * + * Copyright (C) 2008 Novell, Inc. + * + * Authors: Vincent Untz + * + * 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. + * + * The code is originally based on gnome-clock-applet-mechanism-main.c, which + * is under the same license and with the following copyright: + * + * Copyright (C) 2007 David Zeuthen + * + */ + +#ifdef HAVE_CONFIG_H +# include "config.h" +#endif + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +#include "cups-pk-helper-mechanism.h" + +#define CPH_SERVICE "org.opensuse.CupsPkHelper.Mechanism" +#define CPH_PATH "/" + +/* Time after which we exit if there's no activity (in seconds) */ +#define INACTIVITY_EXIT 30 + +typedef struct +{ + CphMechanism *mechanism; + GMainLoop *loop; + unsigned int timeout_id; + gboolean name_acquired; +} cph_main; + +static gboolean +quit_loop (gpointer user_data) +{ + cph_main *data = (cph_main *) user_data; + + g_main_loop_quit (data->loop); + + data->timeout_id = 0; + + return FALSE; +} + +static void +reset_timeout (cph_main *data) +{ + if (data->timeout_id > 0) + g_source_remove (data->timeout_id); + + data->timeout_id = g_timeout_add_seconds (INACTIVITY_EXIT, + quit_loop, data); +} + +static void +mechanism_got_called (CphMechanism *mechanism, + gpointer user_data) +{ + cph_main *data = (cph_main *) user_data; + + reset_timeout (data); +} + +static void +on_bus_acquired (GDBusConnection *connection, + const gchar *name, + gpointer user_data) +{ + cph_main *data = (cph_main *) user_data; + GError *error = NULL; + + if (!cph_mechanism_register (data->mechanism, + connection, CPH_PATH, + &error)) { + if (error) + g_printerr ("Could not register mechanism object: %s\n", error->message); + else + g_printerr ("Could not register mechanism object\n"); + + g_error_free (error); + g_main_loop_quit (data->loop); + + return; + } +} + +static void +on_name_acquired (GDBusConnection *connection, + const gchar *name, + gpointer user_data) +{ + cph_main *data = (cph_main *) user_data; + + data->name_acquired = TRUE; +} + +static void +on_name_lost (GDBusConnection *connection, + const gchar *name, + gpointer user_data) +{ + cph_main *data = (cph_main *) user_data; + + if (connection == NULL) + g_printerr ("Cannot connect to the bus\n"); + else if (!data->name_acquired) + g_printerr ("Cannot acquire %s on the bus\n", CPH_SERVICE); + + g_main_loop_quit (data->loop); +} + +int +main (int argc, char **argv) +{ + cph_main data; + guint owner_id; + + g_type_init (); + + memset (&data, 0, sizeof (data)); + + data.mechanism = cph_mechanism_new (); + + if (data.mechanism == NULL) { + g_printerr ("Could not create mechanism object\n"); + return 1; + } + + data.loop = g_main_loop_new (NULL, FALSE); + + reset_timeout (&data); + + g_signal_connect (data.mechanism, "called", + G_CALLBACK (mechanism_got_called), &data); + + owner_id = g_bus_own_name (G_BUS_TYPE_SYSTEM, + CPH_SERVICE, + G_BUS_NAME_OWNER_FLAGS_NONE, + on_bus_acquired, + on_name_acquired, + on_name_lost, + &data, + NULL); + + g_main_loop_run (data.loop); + + g_object_unref (data.mechanism); + g_bus_unown_name (owner_id); + g_main_loop_unref (data.loop); + + return 0; +} diff --git a/pool/shard002/C/0060477_run.c b/pool/shard002/C/0060477_run.c new file mode 100644 index 0000000000000000000000000000000000000000..342c2a551dc8ff59c5d2c81cc08ca09ae61de677 --- /dev/null +++ b/pool/shard002/C/0060477_run.c @@ -0,0 +1,24 @@ +#include "run.h" +#include "dbg.h" + +void +run_app(gchar *cmd) +{ + GError *error = NULL; + + ENTER; + if (!cmd) + RET(); + + if (!g_spawn_command_line_async(cmd, &error)) + { + GtkWidget *dialog = gtk_message_dialog_new(NULL, 0, + GTK_MESSAGE_ERROR, + GTK_BUTTONS_CLOSE, + "%s", error->message); + gtk_dialog_run(GTK_DIALOG(dialog)); + gtk_widget_destroy(dialog); + g_error_free(error); + } + RET(); +} diff --git a/pool/shard002/C/0060486_main.c b/pool/shard002/C/0060486_main.c new file mode 100644 index 0000000000000000000000000000000000000000..540306a662428d9b2022fd4264dabebdb0d94813 --- /dev/null +++ b/pool/shard002/C/0060486_main.c @@ -0,0 +1,254 @@ +/** + ****************************************************************************** + * @file USB_Host/AUDIO_Standalone/Src/main.c + * @author MCD Application Team + * @version V1.0.1 + * @date 26-February-2014 + * @brief USB host Audio class demo main file + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2014 STMicroelectronics

+ * + * Licensed under MCD-ST Liberty SW License Agreement V2, (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.st.com/software_license_agreement_liberty_v2 + * + * 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. + * + ****************************************************************************** + */ + +/* Includes ------------------------------------------------------------------*/ +#include "main.h" + +/* Private typedef -----------------------------------------------------------*/ +USBH_HandleTypeDef hUSBHost; +AUDIO_ApplicationTypeDef Appli_state = APPLICATION_IDLE; + +/* Private define ------------------------------------------------------------*/ +/* Private macro -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private function prototypes -----------------------------------------------*/ +static void SystemClock_Config(void); +static void USBH_UserProcess(USBH_HandleTypeDef *phost, uint8_t id); +static void Audio_InitApplication(void); + +/* Private functions ---------------------------------------------------------*/ + +/** + * @brief Main program + * @param None + * @retval None + */ +int main(void) +{ + /* STM32F4xx HAL library initialization: + - Configure the Flash prefetch, instruction and Data caches + - Configure the Systick to generate an interrupt each 1 msec + - Set NVIC Group Priority to 4 + - Global MSP (MCU Support Package) initialization + */ + HAL_Init(); + + /* Configure the system clock to 168 Mhz */ + SystemClock_Config(); + + /* Init Audio Application */ + Audio_InitApplication(); + + /* Init Host Library */ + USBH_Init(&hUSBHost, USBH_UserProcess, 0); + + /* Add Supported Class */ + USBH_RegisterClass(&hUSBHost, USBH_AUDIO_CLASS); + + /* Start Host Process */ + USBH_Start(&hUSBHost); + + /* Run Application (Blocking mode) */ + while (1) + { + /* USB Host Background task */ + USBH_Process(&hUSBHost); + + /* AUDIO Menu Process */ + AUDIO_MenuProcess(); + } +} + +/** + * @brief Audio application Init. + * @param None + * @retval None + */ +static void Audio_InitApplication(void) +{ + /* Configure KEY Button */ + BSP_PB_Init(BUTTON_KEY, BUTTON_MODE_EXTI); + + /* Configure Joystick in EXTI mode */ + BSP_JOY_Init(JOY_MODE_EXTI); + + /* Configure the LEDs */ + BSP_LED_Init(LED1); + BSP_LED_Init(LED2); + BSP_LED_Init(LED3); + BSP_LED_Init(LED4); + + /* Initialize the LCD */ + BSP_LCD_Init(); + + /* Initialize the LCD Log module */ + LCD_LOG_Init(); + +#ifdef USE_USB_HS + LCD_LOG_SetHeader((uint8_t *)" USB OTG HS Audio Host"); +#else + LCD_LOG_SetHeader((uint8_t *)" USB OTG FS Audio Host"); +#endif + + LCD_UsrLog("USB Host library started.\n"); + + /* Start Audio Interface */ + USBH_UsrLog("Starting Audio Demo"); + AUDIO_MenuInit(); + + /* Initialize the microSD */ + if(SD_StorageInit() == 0) + { + SD_StorageParse(); + } +} + +/** + * @brief User Process + * @param phost: Host Handle + * @param id: Host Library user message ID + * @retval None + */ +static void USBH_UserProcess(USBH_HandleTypeDef *phost, uint8_t id) +{ + switch(id) + { + case HOST_USER_SELECT_CONFIGURATION: + break; + + case HOST_USER_DISCONNECTION: + Appli_state = APPLICATION_DISCONNECT; + + break; + + case HOST_USER_CLASS_ACTIVE: + Appli_state = APPLICATION_READY; + break; + + case HOST_USER_CONNECTION: + Appli_state = APPLICATION_START; + break; + + default: + break; + } +} + +/** + * @brief Toggles LEDs to shows user input state. + * @param None + * @retval None + */ +void Toggle_Leds(void) +{ + static uint32_t ticks; + + if(ticks++ == 100) + { + BSP_LED_Toggle(LED1); + BSP_LED_Toggle(LED2); + BSP_LED_Toggle(LED3); + BSP_LED_Toggle(LED4); + ticks = 0; + } +} + +/** + * @brief System Clock Configuration + * The system Clock is configured as follow : + * System Clock source = PLL (HSE) + * SYSCLK(Hz) = 168000000 + * HCLK(Hz) = 168000000 + * AHB Prescaler = 1 + * APB1 Prescaler = 4 + * APB2 Prescaler = 2 + * HSE Frequency(Hz) = 25000000 + * PLL_M = 25 + * PLL_N = 336 + * PLL_P = 2 + * PLL_Q = 7 + * VDD(V) = 3.3 + * Main regulator output voltage = Scale1 mode + * Flash Latency(WS) = 5 + * @param None + * @retval None + */ +static void SystemClock_Config(void) +{ + RCC_ClkInitTypeDef RCC_ClkInitStruct; + RCC_OscInitTypeDef RCC_OscInitStruct; + + /* Enable Power Control clock */ + __PWR_CLK_ENABLE(); + + /* The voltage scaling allows optimizing the power consumption when the device is + clocked below the maximum system frequency, to update the voltage scaling value + regarding system frequency refer to product datasheet. */ + __HAL_PWR_VOLTAGESCALING_CONFIG(PWR_REGULATOR_VOLTAGE_SCALE1); + + /* Enable HSE Oscillator and activate PLL with HSE as source */ + RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSE; + RCC_OscInitStruct.HSEState = RCC_HSE_ON; + RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON; + RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSE; + RCC_OscInitStruct.PLL.PLLM = 25; + RCC_OscInitStruct.PLL.PLLN = 336; + RCC_OscInitStruct.PLL.PLLP = RCC_PLLP_DIV2; + RCC_OscInitStruct.PLL.PLLQ = 7; + HAL_RCC_OscConfig(&RCC_OscInitStruct); + + /* Select PLL as system clock source and configure the HCLK, PCLK1 and PCLK2 + clocks dividers */ + RCC_ClkInitStruct.ClockType = (RCC_CLOCKTYPE_SYSCLK | RCC_CLOCKTYPE_HCLK | RCC_CLOCKTYPE_PCLK1 | RCC_CLOCKTYPE_PCLK2); + RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK; + RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1; + RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV4; + RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV2; + HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_5); +} + +#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) */ + + /* Infinite loop */ + while (1) + { + } +} +#endif + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/pool/shard002/C/0060488_gp2ap002a00f.c b/pool/shard002/C/0060488_gp2ap002a00f.c new file mode 100644 index 0000000000000000000000000000000000000000..0ac176d66a6f006c0bb76d0b4a442cae3ee36811 --- /dev/null +++ b/pool/shard002/C/0060488_gp2ap002a00f.c @@ -0,0 +1,286 @@ +/* + * Copyright (C) 2011 Sony Ericsson Mobile Communications Inc. + * + * Author: Courtney Cavin + * Prepared for up-stream by: Oskar Andero + * + * 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 + +struct gp2a_data { + struct input_dev *input; + const struct gp2a_platform_data *pdata; + struct i2c_client *i2c_client; +}; + +enum gp2a_addr { + GP2A_ADDR_PROX = 0x0, + GP2A_ADDR_GAIN = 0x1, + GP2A_ADDR_HYS = 0x2, + GP2A_ADDR_CYCLE = 0x3, + GP2A_ADDR_OPMOD = 0x4, + GP2A_ADDR_CON = 0x6 +}; + +enum gp2a_controls { + /* Software Shutdown control: 0 = shutdown, 1 = normal operation */ + GP2A_CTRL_SSD = 0x01 +}; + +static int gp2a_report(struct gp2a_data *dt) +{ + int vo = gpio_get_value(dt->pdata->vout_gpio); + + input_report_switch(dt->input, SW_FRONT_PROXIMITY, !vo); + input_sync(dt->input); + + return 0; +} + +static irqreturn_t gp2a_irq(int irq, void *handle) +{ + struct gp2a_data *dt = handle; + + gp2a_report(dt); + + return IRQ_HANDLED; +} + +static int gp2a_enable(struct gp2a_data *dt) +{ + return i2c_smbus_write_byte_data(dt->i2c_client, GP2A_ADDR_OPMOD, + GP2A_CTRL_SSD); +} + +static int gp2a_disable(struct gp2a_data *dt) +{ + return i2c_smbus_write_byte_data(dt->i2c_client, GP2A_ADDR_OPMOD, + 0x00); +} + +static int gp2a_device_open(struct input_dev *dev) +{ + struct gp2a_data *dt = input_get_drvdata(dev); + int error; + + error = gp2a_enable(dt); + if (error < 0) { + dev_err(&dt->i2c_client->dev, + "unable to activate, err %d\n", error); + return error; + } + + gp2a_report(dt); + + return 0; +} + +static void gp2a_device_close(struct input_dev *dev) +{ + struct gp2a_data *dt = input_get_drvdata(dev); + int error; + + error = gp2a_disable(dt); + if (error < 0) + dev_err(&dt->i2c_client->dev, + "unable to deactivate, err %d\n", error); +} + +static int gp2a_initialize(struct gp2a_data *dt) +{ + int error; + + error = i2c_smbus_write_byte_data(dt->i2c_client, GP2A_ADDR_GAIN, + 0x08); + if (error < 0) + return error; + + error = i2c_smbus_write_byte_data(dt->i2c_client, GP2A_ADDR_HYS, + 0xc2); + if (error < 0) + return error; + + error = i2c_smbus_write_byte_data(dt->i2c_client, GP2A_ADDR_CYCLE, + 0x04); + if (error < 0) + return error; + + error = gp2a_disable(dt); + + return error; +} + +static int gp2a_probe(struct i2c_client *client, + const struct i2c_device_id *id) +{ + const struct gp2a_platform_data *pdata = dev_get_platdata(&client->dev); + struct gp2a_data *dt; + int error; + + if (!pdata) + return -EINVAL; + + if (pdata->hw_setup) { + error = pdata->hw_setup(client); + if (error < 0) + return error; + } + + error = gpio_request_one(pdata->vout_gpio, GPIOF_IN, GP2A_I2C_NAME); + if (error) + goto err_hw_shutdown; + + dt = kzalloc(sizeof(struct gp2a_data), GFP_KERNEL); + if (!dt) { + error = -ENOMEM; + goto err_free_gpio; + } + + dt->pdata = pdata; + dt->i2c_client = client; + + error = gp2a_initialize(dt); + if (error < 0) + goto err_free_mem; + + dt->input = input_allocate_device(); + if (!dt->input) { + error = -ENOMEM; + goto err_free_mem; + } + + input_set_drvdata(dt->input, dt); + + dt->input->open = gp2a_device_open; + dt->input->close = gp2a_device_close; + dt->input->name = GP2A_I2C_NAME; + dt->input->id.bustype = BUS_I2C; + dt->input->dev.parent = &client->dev; + + input_set_capability(dt->input, EV_SW, SW_FRONT_PROXIMITY); + + error = request_threaded_irq(client->irq, NULL, gp2a_irq, + IRQF_TRIGGER_RISING | IRQF_TRIGGER_FALLING | + IRQF_ONESHOT, + GP2A_I2C_NAME, dt); + if (error) { + dev_err(&client->dev, "irq request failed\n"); + goto err_free_input_dev; + } + + error = input_register_device(dt->input); + if (error) { + dev_err(&client->dev, "device registration failed\n"); + goto err_free_irq; + } + + device_init_wakeup(&client->dev, pdata->wakeup); + i2c_set_clientdata(client, dt); + + return 0; + +err_free_irq: + free_irq(client->irq, dt); +err_free_input_dev: + input_free_device(dt->input); +err_free_mem: + kfree(dt); +err_free_gpio: + gpio_free(pdata->vout_gpio); +err_hw_shutdown: + if (pdata->hw_shutdown) + pdata->hw_shutdown(client); + return error; +} + +static int gp2a_remove(struct i2c_client *client) +{ + struct gp2a_data *dt = i2c_get_clientdata(client); + const struct gp2a_platform_data *pdata = dt->pdata; + + device_init_wakeup(&client->dev, false); + + free_irq(client->irq, dt); + + input_unregister_device(dt->input); + kfree(dt); + + gpio_free(pdata->vout_gpio); + + if (pdata->hw_shutdown) + pdata->hw_shutdown(client); + + return 0; +} + +static int __maybe_unused gp2a_suspend(struct device *dev) +{ + struct i2c_client *client = to_i2c_client(dev); + struct gp2a_data *dt = i2c_get_clientdata(client); + int retval = 0; + + if (device_may_wakeup(&client->dev)) { + enable_irq_wake(client->irq); + } else { + mutex_lock(&dt->input->mutex); + if (dt->input->users) + retval = gp2a_disable(dt); + mutex_unlock(&dt->input->mutex); + } + + return retval; +} + +static int __maybe_unused gp2a_resume(struct device *dev) +{ + struct i2c_client *client = to_i2c_client(dev); + struct gp2a_data *dt = i2c_get_clientdata(client); + int retval = 0; + + if (device_may_wakeup(&client->dev)) { + disable_irq_wake(client->irq); + } else { + mutex_lock(&dt->input->mutex); + if (dt->input->users) + retval = gp2a_enable(dt); + mutex_unlock(&dt->input->mutex); + } + + return retval; +} + +static SIMPLE_DEV_PM_OPS(gp2a_pm, gp2a_suspend, gp2a_resume); + +static const struct i2c_device_id gp2a_i2c_id[] = { + { GP2A_I2C_NAME, 0 }, + { } +}; + +static struct i2c_driver gp2a_i2c_driver = { + .driver = { + .name = GP2A_I2C_NAME, + .owner = THIS_MODULE, + .pm = &gp2a_pm, + }, + .probe = gp2a_probe, + .remove = gp2a_remove, + .id_table = gp2a_i2c_id, +}; + +module_i2c_driver(gp2a_i2c_driver); + +MODULE_AUTHOR("Courtney Cavin "); +MODULE_DESCRIPTION("Sharp GP2AP002A00F I2C Proximity/Opto sensor driver"); +MODULE_LICENSE("GPL v2"); diff --git a/pool/shard002/C/0060491_rtc.c b/pool/shard002/C/0060491_rtc.c new file mode 100644 index 0000000000000000000000000000000000000000..64ba2a4325487ea3851bf1ba860e33aaa228532d --- /dev/null +++ b/pool/shard002/C/0060491_rtc.c @@ -0,0 +1,138 @@ +/*! \file kernel/rtc/rtc.c + \brief Real Time Clock programming + + RTC chip keeps the date and time while your computer is turned off. + However IO access to RTC slow, so Ace kernel uses RTC to get current date and + time only once. After that PIT should up date it. +*/ + +#include +#include +#include + +void InitMC146818(); +UINT32 GetLocalTimeFromMC146818(SYSTEM_TIME_PTR pSystemTime); +UINT32 SetLocalTimeToMC146818(SYSTEM_TIME_PTR pSystemTime); +static void TimeAdd(SYSTEM_TIME_PTR pTime1, SYSTEM_TIME_PTR pTime2); +static void TicksToTime(UINT32 ticks, SYSTEM_TIME_PTR pTime); + +/*! boot_time - filled by RTC chips during booting.*/ +static SYSTEM_TIME boot_time; + +int InitRtc() +{ + memset( &boot_time, 0, sizeof(SYSTEM_TIME) ); +#if ARCH == i386 + InitMC146818(); + return GetLocalTimeFromMC146818(&boot_time); +#else + return 1; +#endif +} + +/*! gets boot time of the system + \param pTime - time structure to fill the boot time + \return 0 on success + 1 on failure +*/ +UINT32 GetBootTime(SYSTEM_TIME_PTR pTime) +{ + memmove(pTime, &boot_time, sizeof(SYSTEM_TIME) ); + return 0; +} +/*! gets the current system time + \param pTime - time structure to fill with the local time + \return 0 on success + 1 on failure +*/ +UINT32 GetLocalTime(SYSTEM_TIME_PTR pTime) +{ + SYSTEM_TIME pElapsedTime; + + memmove(pTime, &boot_time, sizeof(SYSTEM_TIME) ); + + //convert the elapsed ticks to time format + TicksToTime(ElapsedSeconds, &pElapsedTime); + + //add the elapsed time to boot_time + TimeAdd( pTime, &pElapsedTime); + + return 0; +} +/*! sets the system time + \param pTime - time structure to set + \return 0 on success + 1 on failure +*/ +UINT32 SetLocalTime(SYSTEM_TIME_PTR pTime) +{ +#if ARCH == i386 + return SetLocalTimeToMC146818(pTime); +#endif +} + +/*! converts the ticks into time structure. +*/ +static void TicksToTime(UINT32 ticks, SYSTEM_TIME_PTR pTime) +{ + memset(pTime, 0, sizeof(SYSTEM_TIME) ); + pTime->second = ticks % 60; + pTime->minute = (ticks % (60*60)) / 60; + pTime->hour = (ticks % (24*60*60)) / (60*60); + pTime->day = ticks / (24*60*60); +} +/*! adds the pTime1 to pTime2 and stores the result in pTime1 +*/ +static void TimeAdd(SYSTEM_TIME_PTR pTime1, SYSTEM_TIME_PTR pTime2) +{ + pTime1->second += pTime2->second; + if ( pTime1->second % 60 ) + { + pTime1->minute += 1; + pTime1->second %= 60; + } + pTime1->minute += pTime2->minute; + if ( pTime1->minute % 60 ) + { + pTime1->hour += 1; + pTime1->minute %= 60; + } + pTime1->hour += pTime2->hour; + if ( pTime1->hour % 24 ) + { + pTime1->day += 1; + pTime1->hour %= 24; + } +} + +/*! converts bcd to binary and bcd to binary*/ +inline BYTE BcdToBinary(BYTE BcdValue) +{ + return ((((BcdValue >> 4) & 0x0F) * 10) + (BcdValue & 0x0F)); +} +/*! converts bcd to binary and bcd to binary*/ +inline BYTE BinaryToBcd(BYTE BinaryValue) +{ + return (((BinaryValue / 10) << 4) | (BinaryValue % 10)); +} + +void BinaryTimeToBcdTime(SYSTEM_TIME_PTR pTime) +{ + pTime->day = BinaryToBcd(pTime->day); + pTime->month = BinaryToBcd(pTime->month); + pTime->year = BinaryToBcd(pTime->year); + pTime->day_of_week = BinaryToBcd(pTime->day_of_week); + pTime->minute = BinaryToBcd(pTime->minute); + pTime->second = BinaryToBcd(pTime->second); + pTime->hour = BinaryToBcd(pTime->hour); +} +void BcdTimeToBinaryTime(SYSTEM_TIME_PTR pTime) +{ + pTime->day = BcdToBinary(pTime->day); + pTime->month = BcdToBinary(pTime->month); + pTime->year = BcdToBinary(pTime->year); + pTime->day_of_week = BcdToBinary(pTime->day_of_week); + pTime->minute = BcdToBinary(pTime->minute); + pTime->second = BcdToBinary(pTime->second); + pTime->hour = BcdToBinary(pTime->hour); +} diff --git a/pool/shard002/C/0060494_dwarf_funcs.c b/pool/shard002/C/0060494_dwarf_funcs.c new file mode 100644 index 0000000000000000000000000000000000000000..069d108e9c9392f11422743ccf66c9c0553131d1 --- /dev/null +++ b/pool/shard002/C/0060494_dwarf_funcs.c @@ -0,0 +1,134 @@ +/* + + Copyright (C) 2000-2005 Silicon Graphics, Inc. All Rights Reserved. + Portions Copyright (C) 2009-2010 David Anderson. All Rights Reserved. + + This program is free software; you can redistribute it and/or modify it + under the terms of version 2.1 of the GNU Lesser General Public License + as published by the Free Software Foundation. + + This program is distributed in the hope that it would be useful, but + WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + + Further, this software is distributed without any warranty that it is + free of the rightful claim of any third person regarding infringement + or the like. Any license provided herein, whether implied or + otherwise, applies only to this software file. Patent licenses, if + any, provided herein do not apply to combinations of this program with + other software, or any other product whatsoever. + + You should have received a copy of the GNU Lesser General Public + License along with this program; if not, write the Free Software + Foundation, Inc., 51 Franklin Street - Fifth Floor, Boston MA 02110-1301, + USA. + + Contact information: Silicon Graphics, Inc., 1500 Crittenden Lane, + Mountain View, CA 94043, or: + + http://www.sgi.com + + For further information regarding this notice, see: + + http://oss.sgi.com/projects/GenInfo/NoticeExplan + +*/ + + + +#include "config.h" +#include "dwarf_incl.h" +#include +#include "dwarf_funcs.h" +#include "dwarf_global.h" + +int +dwarf_get_funcs(Dwarf_Debug dbg, + Dwarf_Func ** funcs, + Dwarf_Signed * ret_func_count, Dwarf_Error * error) +{ + int res = _dwarf_load_section(dbg, &dbg->de_debug_funcnames,error); + if (res != DW_DLV_OK) { + return res; + } + if (!dbg->de_debug_funcnames.dss_size) { + return (DW_DLV_NO_ENTRY); + } + + + return _dwarf_internal_get_pubnames_like_data(dbg, + dbg->de_debug_funcnames.dss_data, + dbg->de_debug_funcnames.dss_size, + (Dwarf_Global **) funcs, /* Type punning for sections with identical format. */ + ret_func_count, + error, + DW_DLA_FUNC_CONTEXT, + DW_DLA_FUNC, + DW_DLE_DEBUG_FUNCNAMES_LENGTH_BAD, + DW_DLE_DEBUG_FUNCNAMES_VERSION_ERROR); +} + +/* Deallocating fully requires deallocating the list + and all entries. But some internal data is + not exposed, so we need a function with internal knowledge. +*/ + +void +dwarf_funcs_dealloc(Dwarf_Debug dbg, Dwarf_Func * dwgl, + Dwarf_Signed count) +{ + _dwarf_internal_globals_dealloc(dbg, (Dwarf_Global *) dwgl, + count, + DW_DLA_FUNC_CONTEXT, + DW_DLA_FUNC, DW_DLA_LIST); + return; +} + + + +int +dwarf_funcname(Dwarf_Func func_in, char **ret_name, Dwarf_Error * error) +{ + Dwarf_Global func = (Dwarf_Global) func_in; + + if (func == NULL) { + _dwarf_error(NULL, error, DW_DLE_FUNC_NULL); + return (DW_DLV_ERROR); + } + + *ret_name = (char *) (func->gl_name); + return DW_DLV_OK; +} + +int +dwarf_func_die_offset(Dwarf_Func func_in, + Dwarf_Off * return_offset, Dwarf_Error * error) +{ + Dwarf_Global func = (Dwarf_Global) func_in; + + return dwarf_global_die_offset(func, return_offset, error); +} + + +int +dwarf_func_cu_offset(Dwarf_Func func_in, + Dwarf_Off * return_offset, Dwarf_Error * error) +{ + Dwarf_Global func = (Dwarf_Global) func_in; + + return dwarf_global_cu_offset(func, return_offset, error); +} + + +int +dwarf_func_name_offsets(Dwarf_Func func_in, + char **ret_func_name, + Dwarf_Off * die_offset, + Dwarf_Off * cu_die_offset, Dwarf_Error * error) +{ + Dwarf_Global func = (Dwarf_Global) func_in; + + return dwarf_global_name_offsets(func, + ret_func_name, + die_offset, cu_die_offset, error); +} diff --git a/pool/shard002/C/0060515_udp_io.c b/pool/shard002/C/0060515_udp_io.c new file mode 100644 index 0000000000000000000000000000000000000000..a32af9bd2088fdf8595cc70cb65ee8c90b387f3a --- /dev/null +++ b/pool/shard002/C/0060515_udp_io.c @@ -0,0 +1,179 @@ +/* vi: set sw=4 ts=4: */ +/* + * Utility routines. + * + * Copyright (C) 2007 Denys Vlasenko + * + * Licensed under GPLv2, see file LICENSE in this source tree. + */ +#include "libbb.h" + +/* + * This asks kernel to let us know dst addr/port of incoming packets + * We don't check for errors here. Not supported == won't be used + */ +void FAST_FUNC +socket_want_pktinfo(int fd UNUSED_PARAM) +{ +#ifdef IP_PKTINFO + setsockopt_1(fd, IPPROTO_IP, IP_PKTINFO); +#endif +#if ENABLE_FEATURE_IPV6 && defined(IPV6_PKTINFO) + setsockopt_1(fd, IPPROTO_IPV6, IPV6_PKTINFO); +#endif +} + + +ssize_t FAST_FUNC +send_to_from(int fd, void *buf, size_t len, int flags, + const struct sockaddr *to, + const struct sockaddr *from, + socklen_t tolen) +{ +#ifndef IP_PKTINFO + (void)from; /* suppress "unused from" warning */ + return sendto(fd, buf, len, flags, to, tolen); +#else + struct iovec iov[1]; + struct msghdr msg; + union { + char cmsg[CMSG_SPACE(sizeof(struct in_pktinfo))]; +# if ENABLE_FEATURE_IPV6 && defined(IPV6_PKTINFO) + char cmsg6[CMSG_SPACE(sizeof(struct in6_pktinfo))]; +# endif + } u; + struct cmsghdr* cmsgptr; + + if (from->sa_family != AF_INET +# if ENABLE_FEATURE_IPV6 + && from->sa_family != AF_INET6 +# endif + ) { + /* ANY local address */ + return sendto(fd, buf, len, flags, to, tolen); + } + + /* man recvmsg and man cmsg is needed to make sense of code below */ + + iov[0].iov_base = buf; + iov[0].iov_len = len; + + memset(&u, 0, sizeof(u)); + + memset(&msg, 0, sizeof(msg)); + msg.msg_name = (void *)(struct sockaddr *)to; /* or compiler will annoy us */ + msg.msg_namelen = tolen; + msg.msg_iov = iov; + msg.msg_iovlen = 1; + msg.msg_control = &u; + msg.msg_controllen = sizeof(u); + msg.msg_flags = flags; + + cmsgptr = CMSG_FIRSTHDR(&msg); + if (to->sa_family == AF_INET && from->sa_family == AF_INET) { + struct in_pktinfo *pktptr; + cmsgptr->cmsg_level = IPPROTO_IP; + cmsgptr->cmsg_type = IP_PKTINFO; + cmsgptr->cmsg_len = CMSG_LEN(sizeof(struct in_pktinfo)); + pktptr = (struct in_pktinfo *)(CMSG_DATA(cmsgptr)); + /*pktptr->ipi_ifindex = 0; -- already done by memset(u...) */ + /* In general, CMSG_DATA() can be unaligned, but in this case + * we know for sure it is sufficiently aligned: + * CMSG_FIRSTHDR simply returns &u above, + * and CMSG_DATA returns &u + size_t + int + int. + * Thus direct assignment is ok: + */ + pktptr->ipi_spec_dst = ((struct sockaddr_in*)from)->sin_addr; + } +# if ENABLE_FEATURE_IPV6 && defined(IPV6_PKTINFO) + else if (to->sa_family == AF_INET6 && from->sa_family == AF_INET6) { + struct in6_pktinfo *pktptr; + cmsgptr->cmsg_level = IPPROTO_IPV6; + cmsgptr->cmsg_type = IPV6_PKTINFO; + cmsgptr->cmsg_len = CMSG_LEN(sizeof(struct in6_pktinfo)); + pktptr = (struct in6_pktinfo *)(CMSG_DATA(cmsgptr)); + /* pktptr->ipi6_ifindex = 0; -- already done by memset(u...) */ + pktptr->ipi6_addr = ((struct sockaddr_in6*)from)->sin6_addr; + } +# endif + msg.msg_controllen = cmsgptr->cmsg_len; + + return sendmsg(fd, &msg, flags); +#endif +} + +/* NB: this will never set port# in 'to'! + * _Only_ IP/IPv6 address part of 'to' is _maybe_ modified. + * Typical usage is to preinit 'to' with "default" value + * before calling recv_from_to(). */ +ssize_t FAST_FUNC +recv_from_to(int fd, void *buf, size_t len, int flags, + struct sockaddr *from, struct sockaddr *to, + socklen_t sa_size) +{ +#ifndef IP_PKTINFO + (void)to; /* suppress "unused to" warning */ + return recvfrom(fd, buf, len, flags, from, &sa_size); +#else + /* man recvmsg and man cmsg is needed to make sense of code below */ + struct iovec iov[1]; + union { + char cmsg[CMSG_SPACE(sizeof(struct in_pktinfo))]; +# if ENABLE_FEATURE_IPV6 && defined(IPV6_PKTINFO) + char cmsg6[CMSG_SPACE(sizeof(struct in6_pktinfo))]; +# endif + } u; + struct cmsghdr *cmsgptr; + struct msghdr msg; + ssize_t recv_length; + + iov[0].iov_base = buf; + iov[0].iov_len = len; + + memset(&msg, 0, sizeof(msg)); + msg.msg_name = (struct sockaddr *)from; + msg.msg_namelen = sa_size; + msg.msg_iov = iov; + msg.msg_iovlen = 1; + msg.msg_control = &u; + msg.msg_controllen = sizeof(u); + + recv_length = recvmsg(fd, &msg, flags); + if (recv_length < 0) + return recv_length; + +# define to4 ((struct sockaddr_in*)to) +# define to6 ((struct sockaddr_in6*)to) + /* Here we try to retrieve destination IP and memorize it */ + for (cmsgptr = CMSG_FIRSTHDR(&msg); + cmsgptr != NULL; + cmsgptr = CMSG_NXTHDR(&msg, cmsgptr) + ) { + if (cmsgptr->cmsg_level == IPPROTO_IP + && cmsgptr->cmsg_type == IP_PKTINFO + ) { + const int IPI_ADDR_OFF = offsetof(struct in_pktinfo, ipi_addr); + to->sa_family = AF_INET; + /*# define pktinfo(cmsgptr) ( (struct in_pktinfo*)(CMSG_DATA(cmsgptr)) )*/ + /*to4->sin_addr = pktinfo(cmsgptr)->ipi_addr; - may be unaligned */ + memcpy(&to4->sin_addr, (char*)(CMSG_DATA(cmsgptr)) + IPI_ADDR_OFF, sizeof(to4->sin_addr)); + /*to4->sin_port = 123; - this data is not supplied by kernel */ + break; + } +# if ENABLE_FEATURE_IPV6 && defined(IPV6_PKTINFO) + if (cmsgptr->cmsg_level == IPPROTO_IPV6 + && cmsgptr->cmsg_type == IPV6_PKTINFO + ) { + const int IPI6_ADDR_OFF = offsetof(struct in6_pktinfo, ipi6_addr); + to->sa_family = AF_INET6; + /*# define pktinfo(cmsgptr) ( (struct in6_pktinfo*)(CMSG_DATA(cmsgptr)) )*/ + /*to6->sin6_addr = pktinfo(cmsgptr)->ipi6_addr; - may be unaligned */ + memcpy(&to6->sin6_addr, (char*)(CMSG_DATA(cmsgptr)) + IPI6_ADDR_OFF, sizeof(to6->sin6_addr)); + /*to6->sin6_port = 123; */ + break; + } +# endif + } + return recv_length; +#endif +} diff --git a/pool/shard002/C/0060529_nlfit.c b/pool/shard002/C/0060529_nlfit.c new file mode 100644 index 0000000000000000000000000000000000000000..925f65541f01ab9f926abf81dd6fbb8f4c3c5f9e --- /dev/null +++ b/pool/shard002/C/0060529_nlfit.c @@ -0,0 +1,113 @@ +#include +#include +#include +#include +#include +#include +#include + +#include "expfit.c" + +/* number of data points to fit */ +#define N 40 + +int +main (void) +{ + const gsl_multifit_fdfsolver_type *T = gsl_multifit_fdfsolver_lmsder; + gsl_multifit_fdfsolver *s; + int status, info; + size_t i; + const size_t n = N; + const size_t p = 3; + + gsl_matrix *covar = gsl_matrix_alloc (p, p); + double y[N], weights[N]; + struct data d = { n, y }; + gsl_multifit_function_fdf f; + double x_init[3] = { 1.0, 0.0, 0.0 }; + gsl_vector_view x = gsl_vector_view_array (x_init, p); + gsl_vector_view w = gsl_vector_view_array(weights, n); + const gsl_rng_type * type; + gsl_rng * r; + gsl_vector *res_f; + double chi, chi0; + + const double xtol = 1e-8; + const double gtol = 1e-8; + const double ftol = 0.0; + + gsl_rng_env_setup(); + + type = gsl_rng_default; + r = gsl_rng_alloc (type); + + f.f = &expb_f; + f.df = &expb_df; /* set to NULL for finite-difference Jacobian */ + f.n = n; + f.p = p; + f.params = &d; + + /* This is the data to be fitted */ + + for (i = 0; i < n; i++) + { + double t = i; + double yi = 1.0 + 5 * exp (-0.1 * t); + double si = 0.1 * yi; + double dy = gsl_ran_gaussian(r, si); + + weights[i] = 1.0 / (si * si); + y[i] = yi + dy; + printf ("data: %zu %g %g\n", i, y[i], si); + }; + + s = gsl_multifit_fdfsolver_alloc (T, n, p); + + /* initialize solver with starting point and weights */ + gsl_multifit_fdfsolver_wset (s, &f, &x.vector, &w.vector); + + /* compute initial residual norm */ + res_f = gsl_multifit_fdfsolver_residual(s); + chi0 = gsl_blas_dnrm2(res_f); + + /* solve the system with a maximum of 20 iterations */ + status = gsl_multifit_fdfsolver_driver(s, 20, xtol, gtol, ftol, &info); + + gsl_multifit_fdfsolver_covar (s, 0.0, covar); + + /* compute final residual norm */ + chi = gsl_blas_dnrm2(res_f); + +#define FIT(i) gsl_vector_get(s->x, i) +#define ERR(i) sqrt(gsl_matrix_get(covar,i,i)) + + fprintf(stderr, "summary from method '%s'\n", + gsl_multifit_fdfsolver_name(s)); + fprintf(stderr, "number of iterations: %zu\n", + gsl_multifit_fdfsolver_niter(s)); + fprintf(stderr, "function evaluations: %zu\n", f.nevalf); + fprintf(stderr, "Jacobian evaluations: %zu\n", f.nevaldf); + fprintf(stderr, "reason for stopping: %s\n", + (info == 1) ? "small step size" : "small gradient"); + fprintf(stderr, "initial |f(x)| = %g\n", chi0); + fprintf(stderr, "final |f(x)| = %g\n", chi); + + { + double dof = n - p; + double c = GSL_MAX_DBL(1, chi / sqrt(dof)); + + fprintf(stderr, "chisq/dof = %g\n", pow(chi, 2.0) / dof); + + fprintf (stderr, "A = %.5f +/- %.5f\n", FIT(0), c*ERR(0)); + fprintf (stderr, "lambda = %.5f +/- %.5f\n", FIT(1), c*ERR(1)); + fprintf (stderr, "b = %.5f +/- %.5f\n", FIT(2), c*ERR(2)); + } + + fprintf (stderr, "status = %s\n", gsl_strerror (status)); + + gsl_multifit_fdfsolver_free (s); + gsl_matrix_free (covar); + gsl_rng_free (r); + return 0; +} diff --git a/pool/shard002/C/0060536_http_error.c b/pool/shard002/C/0060536_http_error.c new file mode 100644 index 0000000000000000000000000000000000000000..0c6ea4ca90beac0557b12169e7140e100764f447 --- /dev/null +++ b/pool/shard002/C/0060536_http_error.c @@ -0,0 +1,44 @@ +#include "lib_acl.h" +#include "lib_protocol.h" +#include "http_service.h" + +static char reply_error_fmt[] = "HTTP/1.1 %d %s\r\n" + "Accept-Ranges: bytes\r\n" + "Server: dict_http/1.0.0 (Unix)\r\n" + "Content-type: text/html\r\n" + "Connection: close\r\n\r\n"; + +static void free_buf(void *arg) +{ + ACL_VSTRING *s = (ACL_VSTRING*) arg; + + acl_vstring_free(s); +} + +void http_error_reply(ACL_VSTREAM *client, int status, const char *msg) +{ + static __thread ACL_VSTRING *__buf = NULL; + const ACL_VSTRING *str; + const char *ptr; + struct iovec iov[2]; + + if (__buf == NULL) { + __buf = acl_vstring_alloc(256); + acl_pthread_atexit_add(__buf, free_buf); + } + + ptr = http_tmpl_title(status); + str = http_tmpl_get(status); + + if (msg == NULL || *msg == 0) + msg = acl_vstring_str(str); + + acl_vstring_sprintf(__buf, reply_error_fmt, status, ptr); + + iov[0].iov_base = acl_vstring_str(__buf); + iov[0].iov_len = ACL_VSTRING_LEN(__buf); + iov[1].iov_base = (char*) msg; + iov[1].iov_len = strlen(msg); + + acl_vstream_writevn(client, iov, 2); +} diff --git a/pool/shard002/C/0060543_emit-one.c b/pool/shard002/C/0060543_emit-one.c new file mode 100644 index 0000000000000000000000000000000000000000..6cbd9cea72b963ee3e2081f36b53be8b1618b585 --- /dev/null +++ b/pool/shard002/C/0060543_emit-one.c @@ -0,0 +1,23 @@ +#include + +int div(int numerator, int denominator) +{ + return numerator / denominator; +} + +void div_test() +{ + int i = 0; + for (i = 0; i < 2; ++i) + assert(div(2 * i, i) == 2); +} + +int do_nothing() +{ + unsigned int i = 0; + + int k = 100; + int j = k + 1; + + return j; +} diff --git a/pool/shard002/C/0060564_trap.c b/pool/shard002/C/0060564_trap.c new file mode 100644 index 0000000000000000000000000000000000000000..bedcd44c2c1545c6d241a7f9535a38ea6200c76b --- /dev/null +++ b/pool/shard002/C/0060564_trap.c @@ -0,0 +1,221 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#define TICK_NUM 100 + +static void print_ticks() { + cprintf("%d ticks\n",TICK_NUM); + #ifdef DEBUG_GRADE + cprintf("End of Test.\n"); + panic("EOT: kernel seems ok."); + #endif +} + +/* * + * Interrupt descriptor table: + * + * Must be built at run time because shifted function addresses can't + * be represented in relocation records. + * */ +static struct gatedesc idt[256] = {{0}}; + +static struct pseudodesc idt_pd = { + sizeof(idt) - 1, (uintptr_t)idt +}; + +/* idt_init - initialize IDT to each of the entry points in kern/trap/vectors.S */ +void +idt_init(void) { + /* LAB1 YOUR CODE : STEP 2 */ + /* (1) Where are the entry addrs of each Interrupt Service Routine (ISR)? + * All ISR's entry addrs are stored in __vectors. where is uintptr_t __vectors[] ? + * __vectors[] is in kern/trap/vector.S which is produced by tools/vector.c + * (try "make" command in lab1, then you will find vector.S in kern/trap DIR) + * You can use "extern uintptr_t __vectors[];" to define this extern variable which will be used later. + * (2) Now you should setup the entries of ISR in Interrupt Description Table (IDT). + * Can you see idt[256] in this file? Yes, it's IDT! you can use SETGATE macro to setup each item of IDT + * (3) After setup the contents of IDT, you will let CPU know where is the IDT by using 'lidt' instruction. + * You don't know the meaning of this instruction? just google it! and check the libs/x86.h to know more. + * Notice: the argument of lidt is idt_pd. try to find it! + */ + + extern uintptr_t __vectors[]; + for (int i = 0; i < sizeof(idt) / sizeof(struct gatedesc); i++) { + SETGATE(idt[i], 0, GD_KTEXT, __vectors[i], DPL_KERNEL); + } + // from user to kernel + SETGATE(idt[T_SWITCH_TOK], 0, GD_KTEXT, __vectors[T_SWITCH_TOK], DPL_USER); + + // load the IDT + lidt(&idt_pd); +} + +static const char * +trapname(int trapno) { + static const char * const excnames[] = { + "Divide error", + "Debug", + "Non-Maskable Interrupt", + "Breakpoint", + "Overflow", + "BOUND Range Exceeded", + "Invalid Opcode", + "Device Not Available", + "Double Fault", + "Coprocessor Segment Overrun", + "Invalid TSS", + "Segment Not Present", + "Stack Fault", + "General Protection", + "Page Fault", + "(unknown trap)", + "x87 FPU Floating-Point Error", + "Alignment Check", + "Machine-Check", + "SIMD Floating-Point Exception" + }; + + if (trapno < sizeof(excnames)/sizeof(const char * const)) { + return excnames[trapno]; + } + if (trapno >= IRQ_OFFSET && trapno < IRQ_OFFSET + 16) { + return "Hardware Interrupt"; + } + return "(unknown trap)"; +} + +/* trap_in_kernel - test if trap happened in kernel */ +bool +trap_in_kernel(struct trapframe *tf) { + return (tf->tf_cs == (uint16_t)KERNEL_CS); +} + +static const char *IA32flags[] = { + "CF", NULL, "PF", NULL, "AF", NULL, "ZF", "SF", + "TF", "IF", "DF", "OF", NULL, NULL, "NT", NULL, + "RF", "VM", "AC", "VIF", "VIP", "ID", NULL, NULL, +}; + +void +print_trapframe(struct trapframe *tf) { + cprintf("trapframe at %p\n", tf); + print_regs(&tf->tf_regs); + cprintf(" ds 0x----%04x\n", tf->tf_ds); + cprintf(" es 0x----%04x\n", tf->tf_es); + cprintf(" fs 0x----%04x\n", tf->tf_fs); + cprintf(" gs 0x----%04x\n", tf->tf_gs); + cprintf(" trap 0x%08x %s\n", tf->tf_trapno, trapname(tf->tf_trapno)); + cprintf(" err 0x%08x\n", tf->tf_err); + cprintf(" eip 0x%08x\n", tf->tf_eip); + cprintf(" cs 0x----%04x\n", tf->tf_cs); + cprintf(" flag 0x%08x ", tf->tf_eflags); + + int i, j; + for (i = 0, j = 1; i < sizeof(IA32flags) / sizeof(IA32flags[0]); i ++, j <<= 1) { + if ((tf->tf_eflags & j) && IA32flags[i] != NULL) { + cprintf("%s,", IA32flags[i]); + } + } + cprintf("IOPL=%d\n", (tf->tf_eflags & FL_IOPL_MASK) >> 12); + + if (!trap_in_kernel(tf)) { + cprintf(" esp 0x%08x\n", tf->tf_esp); + cprintf(" ss 0x----%04x\n", tf->tf_ss); + } +} + +void +print_regs(struct pushregs *regs) { + cprintf(" edi 0x%08x\n", regs->reg_edi); + cprintf(" esi 0x%08x\n", regs->reg_esi); + cprintf(" ebp 0x%08x\n", regs->reg_ebp); + cprintf(" oesp 0x%08x\n", regs->reg_oesp); + cprintf(" ebx 0x%08x\n", regs->reg_ebx); + cprintf(" edx 0x%08x\n", regs->reg_edx); + cprintf(" ecx 0x%08x\n", regs->reg_ecx); + cprintf(" eax 0x%08x\n", regs->reg_eax); +} + + +/* trap_dispatch - dispatch based on what type of trap occurred */ +static void +trap_dispatch(struct trapframe *tf) { + cprintf("trap dispatch, trapframe:%d", tf); + + char c; + struct trapframe k_u, *u_k; + + switch (tf->tf_trapno) { + case IRQ_OFFSET + IRQ_TIMER: + /* LAB1 YOUR CODE : STEP 3 */ + /* handle the timer interrupt */ + /* (1) After a timer interrupt, you should record this event using a global variable (increase it), such as ticks in kern/driver/clock.c + * (2) Every TICK_NUM cycle, you can print some info using a funciton, such as print_ticks(). + * (3) Too Simple? Yes, I think so! + */ + ticks++; + if (ticks == TICK_NUM) { + print_ticks(); + ticks = 0; + } + break; + case IRQ_OFFSET + IRQ_COM1: + c = cons_getc(); + cprintf("serial [%03d] %c\n", c, c); + break; + case IRQ_OFFSET + IRQ_KBD: + c = cons_getc(); + cprintf("kbd [%03d] %c\n", c, c); + break; + case T_SWITCH_TOU: + if (tf->tf_cs != USER_CS) { + k_u = *tf; + k_u.tf_cs = USER_CS; + k_u.tf_ds = k_u.tf_es = k_u.tf_ss = USER_DS; + k_u.tf_esp = (uint32_t)tf + sizeof(struct trapframe) - 8; + k_u.tf_eflags |= FL_IOPL_MASK; + *((uint32_t *)tf - 1) = (uint32_t)&k_u; + } + break; + case T_SWITCH_TOK: + if (tf->tf_cs != KERNEL_CS) { + tf->tf_cs = KERNEL_CS; + tf->tf_ds = tf->tf_es = KERNEL_DS; + tf->tf_eflags &= ~FL_IOPL_MASK; + u_k = (struct trapframe *)(tf->tf_esp - (sizeof(struct trapframe) - 8)); + memmove(u_k, tf, sizeof(struct trapframe) - 8); + *((uint32_t *)tf - 1) = (uint32_t)u_k; + } + break; + case IRQ_OFFSET + IRQ_IDE1: + case IRQ_OFFSET + IRQ_IDE2: + /* do nothing */ + break; + default: + // in kernel, it must be a mistake + if ((tf->tf_cs & 3) == 0) { + print_trapframe(tf); + panic("unexpected trap in kernel.\n"); + } + } +} + +/* * + * trap - handles or dispatches an exception/interrupt. if and when trap() returns, + * the code in kern/trap/trapentry.S restores the old CPU state saved in the + * trapframe and then uses the iret instruction to return from the exception. + * */ +void +trap(struct trapframe *tf) { + // dispatch based on what type of trap occurred + trap_dispatch(tf); +} + diff --git a/pool/shard002/C/0060566_vmexit_ept.c b/pool/shard002/C/0060566_vmexit_ept.c new file mode 100644 index 0000000000000000000000000000000000000000..ffff477dd5ea0f63d52f5136cd7b4bbef3e7a6f4 --- /dev/null +++ b/pool/shard002/C/0060566_vmexit_ept.c @@ -0,0 +1,88 @@ +/* + * Copyright (c) 2013 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. + */ + +#include "vmm_defs.h" +#include "guest_cpu.h" +#include "vmm_events_data.h" +#include "vmcs_api.h" +#include "hw_utils.h" +#include "emulator_if.h" +#include "vmm_callback.h" +#include "file_codes.h" +#define VMM_DEADLOOP() VMM_DEADLOOP_LOG(VMEXIT_EPT_C) +#define VMM_ASSERT(__condition) VMM_ASSERT_LOG(VMEXIT_EPT_C, __condition) +#ifdef JLMDEBUG +#include "jlmdebug.h" +#endif + +#pragma warning (push) +#pragma warning (disable : 4100) // disable non-referenced formal parameters +VMEXIT_HANDLING_STATUS vmexit_mtf(GUEST_CPU_HANDLE gcpu) +{ + if (!report_uvmm_event(UVMM_EVENT_MTF_VMEXIT, (VMM_IDENTIFICATION_DATA)gcpu, + (const GUEST_VCPU*)guest_vcpu(gcpu), NULL)) { + VMM_LOG(mask_uvmm, level_trace, "Report MTF VMExit failed.\n"); + } + return VMEXIT_HANDLED; +} +#pragma warning (pop) + +BOOLEAN ept_violation_vmexit(GUEST_CPU_HANDLE gcpu, void *pv); + + +VMEXIT_HANDLING_STATUS vmexit_ept_violation(GUEST_CPU_HANDLE gcpu) +{ + EVENT_GCPU_EPT_VIOLATION_DATA data; + VMCS_OBJECT* vmcs = gcpu_get_vmcs(gcpu); + + + //vmm_memset(&data, 0, sizeof(data)); + data.qualification.Uint64 = vmcs_read(vmcs, VMCS_EXIT_INFO_QUALIFICATION); + data.guest_linear_address = vmcs_read(vmcs, VMCS_EXIT_INFO_GUEST_LINEAR_ADDRESS); + data.guest_physical_address = vmcs_read(vmcs, VMCS_EXIT_INFO_GUEST_PHYSICAL_ADDRESS); + data.processed = FALSE; + + ept_violation_vmexit( gcpu, &data ); + + if (!data.processed) { + VMM_LOG(mask_anonymous, level_trace,"Unsupported ept violation in \n"); + PRINT_GCPU_IDENTITY(gcpu); + VMM_LOG(mask_anonymous, level_trace," Running %s emulator\n", emulator_is_running_as_guest() ? "inside" : "outside"); + //vmexit_handler_default(gcpu); + VMM_DEADLOOP(); + } + return VMEXIT_HANDLED; +} + +VMEXIT_HANDLING_STATUS vmexit_ept_misconfiguration(GUEST_CPU_HANDLE gcpu) +{ + EVENT_GCPU_EPT_MISCONFIGURATION_DATA data; + VMCS_OBJECT* vmcs = gcpu_get_vmcs(gcpu); + data.guest_physical_address = vmcs_read(vmcs, VMCS_EXIT_INFO_GUEST_PHYSICAL_ADDRESS); + data.processed = FALSE; + + event_raise( EVENT_GCPU_EPT_MISCONFIGURATION, gcpu, &data ); + + VMM_ASSERT(data.processed); + + if ( ! data.processed) { + VMM_LOG(mask_anonymous, level_trace,"Unsupported ept misconfiguration in \n"); + PRINT_GCPU_IDENTITY(gcpu); + VMM_LOG(mask_anonymous, level_trace," Running %s emulator\n", emulator_is_running_as_guest() ? "inside" : "outside"); + //vmexit_handler_default(gcpu); + VMM_DEADLOOP(); + } + return VMEXIT_HANDLED; +} + diff --git a/pool/shard002/C/0060577_mbox.c b/pool/shard002/C/0060577_mbox.c new file mode 100644 index 0000000000000000000000000000000000000000..fdd82e03cb860379774627d8650957a1078e2f0e --- /dev/null +++ b/pool/shard002/C/0060577_mbox.c @@ -0,0 +1,44 @@ +#include +#include +#include +#include + +#define MAILBOX_FULL 0x80000000 +#define MAILBOX_EMPTY 0x40000000 + +//volatile mailbox_t* gmailbox = (mailbox_t*) MBOX_BASE; + +#define gmailbox ((mailbox_t*) MBOX_BASE) + +uint32_t mbox_read(uint8_t chan) +{ + uint32_t data = 0; + while (1) { + while (gmailbox->status & MAILBOX_EMPTY) { + kprint("status: %x\n\r", gmailbox->status); + memory_barier() ; + } + data = gmailbox->read; + +#ifdef MBOX_DEBUG + kprint("Recived: %x", data); +#endif + if (((uint8_t) data & 0xf) == chan) { + return (data & ~0xf); + } + } +} + +void mbox_write(uint8_t chan, uint32_t data) +{ + while (gmailbox->status & MAILBOX_FULL) ; + + gmailbox->write = (data & ~0xf) | (uint32_t) (chan & 0xf); +} + +void mbox_flush(void) { + while (!(gmailbox->status & MAILBOX_EMPTY)) { + usleep(20); + } +} + diff --git a/pool/shard002/C/0060589_Ex_1.3_fahr2celheading.c b/pool/shard002/C/0060589_Ex_1.3_fahr2celheading.c new file mode 100644 index 0000000000000000000000000000000000000000..ae262dcef13366ee7b581e9275a9345700162c4f --- /dev/null +++ b/pool/shard002/C/0060589_Ex_1.3_fahr2celheading.c @@ -0,0 +1,27 @@ +/* Temperature Conversion Program, Fahrenheit to Celsius */ + +#include + +/* print Fahrenheit-Celsius table for fahr = 0,20 ... 300 */ + +int main() +{ + printf("A program print Fahrenheit-Celsius"\n); + int lower,upper,step; + int celsius,fahr; + + lower = 0; + upper = 300; + step = 20; + + fahr = lower; + + while( fahr <= upper) + { + celsius = 5 * (fahr - 32) / 9; + printf("%d\t%d\n",fahr,celsius); + fahr = fahr + step; + } + + return 0; +} diff --git a/pool/shard002/C/0060599_descriptors.c b/pool/shard002/C/0060599_descriptors.c new file mode 100644 index 0000000000000000000000000000000000000000..5e965865e566c81bf165fea6af753af99fe82d0c --- /dev/null +++ b/pool/shard002/C/0060599_descriptors.c @@ -0,0 +1,370 @@ +/** + * + * Phantom OS + * + * Copyright (C) 2005-2010 Dmitry Zavalishin, dz@dz.ru + * + * IDT/GDT/LDT code + * +**/ + +#define DEBUG_MSG_PREFIX "i386desc" +#include +#define debug_level_flow 0 +#define debug_level_error 10 +#define debug_level_info 10 + +#include +#include + +#include +#include +#include +#include +#include +#include +//#include +#include + +#include +#include + +#include +#include +#include +#include +#include + +#include +#include + +#include "../misc.h" + + + + + +struct real_descriptor gdt[GDTSZ]; +struct real_descriptor ldt[LDTSZ]; +struct real_gate idt[IDTSZ]; + +//struct i386_tss tss; +struct i386_tss cpu_tss[MAX_CPUS]; +struct vm86tss tss_vm86; + +#define main_tss (cpu_tss[0]) + + +// used from direct VESA driver +void set_descriptor_limit( struct real_descriptor *d, unsigned limit ) +{ + if (limit > 0xfffff) + { + if( (limit+1) & 0xFFF ) printf("warning - big limit not aligned to page"); + limit >>= 12; + //limit = 1 + ((limit-1)/PAGE_SIZE); + d->granularity |= SZ_G; + } + else + d->granularity &= ~SZ_G; + + //limit--; // ia32 wants it that way + + d->limit_low = limit & 0xffff; + d->limit_high = limit >> 16; + +} + + + +void phantom_load_gdt() +{ + struct region_descriptor rd; + + rd.rd_limit = sizeof(gdt) - 1; + rd.rd_base = kvtolin(&gdt); + + asm volatile("lgdt %0" : : "m" ((&rd)->rd_limit)); + + // Now Intel wants us to reload segments + + asm volatile("ljmp %0,$1f ;\ + 1: \ + " : : "i" (KERNEL_CS)); + + + asm volatile("movw %w0,%%ds" : : "r" (KERNEL_DS)); + asm volatile("movw %w0,%%es" : : "r" (KERNEL_DS)); + asm volatile("movw %w0,%%ss" : : "r" (KERNEL_DS)); + + asm volatile("movw %w0,%%fs" : : "r" (0)); + asm volatile("movw %w0,%%gs" : : "r" (0)); + + // and activate the LDT + wrldt(MAIN_LDT); + +} + + +void phantom_load_main_tss() +{ + // get it ready for reuse - we are called on exit from VM86 mode too + gdt[MAIN_TSS / 8].access &= ~ACC_TSS_BUSY; + gdt[VM86_TSS / 8].access &= ~ACC_TSS_BUSY; + + // now load TSS + asm volatile("ltr %0" : : "rm" ((u_int16_t)MAIN_TSS) ); +} + + +#define IS_SIZE (1024*16) +static char intr_stack[IS_SIZE]; + +static char cpu_intr_stack[MAX_CPUS][IS_SIZE]; + +void phantom_init_descriptors(void) +{ + main_tss.ss0 = KERNEL_DS; + + //main_tss.esp0 = get_esp(); // why? + main_tss.esp0 = (int) (intr_stack+IS_SIZE-4); + + main_tss.io_bit_map_offset = sizeof(main_tss); + + //tss_vm86.tss.ss0 = KERNEL_DS_16; // WHY!!!? + tss_vm86.tss.ss0 = KERNEL_DS; + //main_tss.esp0 = get_esp(); // why? + tss_vm86.tss.io_bit_map_offset = sizeof(tss_vm86); + + + make_descriptor(gdt, MAIN_TSS, kvtolin(&main_tss), sizeof(main_tss)-1, + ACC_PL_K | ACC_TSS | ACC_P, 0 ); + + make_descriptor(gdt, VM86_TSS, kvtolin(&tss_vm86), sizeof(tss_vm86)-1, + ACC_PL_K | ACC_TSS | ACC_P, 0 ); + + make_descriptor(gdt, KERNEL_CS, kvtolin(0), 0xFFFFFFFF, + ACC_PL_K | ACC_CODE_R, SZ_32 ); + make_descriptor(gdt, KERNEL_DS, kvtolin(0), 0xFFFFFFFF, + ACC_PL_K | ACC_DATA_W, SZ_32 ); + + make_descriptor(gdt, USER_CS, kvtolin(0), 0xFFFFFFFF, + ACC_PL_U | ACC_CODE_R, SZ_32 ); + make_descriptor(gdt, USER_DS, kvtolin(0), 0xFFFFFFFF, + ACC_PL_U | ACC_DATA_W, SZ_32 ); + + make_descriptor(gdt, KERNEL_CS_16, kvtolin(0), 0xFFFF, + ACC_PL_K | ACC_CODE_R, SZ_32 ); + make_descriptor(gdt, KERNEL_DS_16, kvtolin(0), 0xFFFF, + ACC_PL_K | ACC_DATA_W, SZ_32 ); + + + make_descriptor(gdt, MAIN_LDT, kvtolin(&ldt), LDTSZ * sizeof(struct real_descriptor) - 1, + ACC_P | ACC_PL_K | ACC_LDT, 0 ); + + +// ----------------------------------------------------------------------- +// Now LDT +// ----------------------------------------------------------------------- + + /* Initialize the master LDT descriptor in the GDT. */ + make_descriptor(gdt, MAIN_LDT, + kvtolin(&ldt), sizeof(ldt)-1, + ACC_PL_K|ACC_LDT, 0); + + /* Initialize the LDT descriptors. */ + fill_ldt_gate(USER_LDT_SCALL, + (int)&syscall, KERNEL_CS, + ACC_PL_U|ACC_CALL_GATE, 0); +/* +#define VM_MIN_ADDRESS 0 +#define VM_MAX_ADDRESS 0 + fill_ldt_descriptor(USER_LDT_CS, + VM_MIN_ADDRESS, VM_MAX_ADDRESS-VM_MIN_ADDRESS, + // XXX LINEAR_... + ACC_PL_U|ACC_CODE_R, SZ_32); + + fill_ldt_descriptor(USER_LDT_DS, + VM_MIN_ADDRESS, VM_MAX_ADDRESS-VM_MIN_ADDRESS, + ACC_PL_U|ACC_DATA_W, SZ_32); +*/ + + + int i; + for( i = 0; i < MAX_CPUS; i++ ) + { + cpu_tss[i].ss0 = KERNEL_DS; + + cpu_tss[i].esp0 = (int) (cpu_intr_stack[i]+IS_SIZE-4); + + cpu_tss[i].io_bit_map_offset = sizeof(cpu_tss[0]); + + make_descriptor(gdt, (CPU_TSS+i*8), kvtolin(&(cpu_tss[i])), sizeof(struct i386_tss)-1, + ACC_PL_K | ACC_TSS | ACC_P, 0 ); + + } + + phantom_load_gdt(); + phantom_load_main_tss(); +} + + + +void phantom_load_cpu_tss(int ncpu) +{ + // get it ready for reuse - we are called on exit from VM86 mode too + //gdt[MAIN_TSS / 8].access &= ~ACC_TSS_BUSY; + + // now load TSS + asm volatile("ltr %0" : : "rm" ((u_int16_t)(CPU_TSS+ncpu*8)) ); +} + + + + + + +extern int syscall(void); + + +errno_t get_uldt_cs_ds( + linaddr_t cs_base, u_int16_t *ocs, size_t cs_limit, + linaddr_t ds_base, u_int16_t *ods, size_t ds_limit + ) +{ + SHOW_FLOW( 3, "User CS %p 0x%x bytes, DS %p 0x%x bytes", cs_base, cs_limit, ds_base, ds_limit ); + +#if 0 + if( (segsToUse >> 3) + 1 >= LDTSZ ) + return ENOMEM; + + u_int16_t cs = segsToUse | 0x7; + segsToUse += 0x08; + u_int16_t ds = segsToUse | 0x7; + segsToUse += 0x08; +#else + u_int16_t cs = alloc_ldt_selector(); + u_int16_t ds = alloc_ldt_selector(); + if( (cs == NULL_SELECTOR) || (ds == NULL_SELECTOR) ) + return ENOMEM; + + ds |= SELECTOR_USER; + cs |= SELECTOR_USER; +#endif + + //fill_ldt_descriptor(cs, cs_base, 1 + (cs_limit-1)/PAGE_SIZE, ACC_PL_U|ACC_CODE_R, SZ_32|SZ_G); + //fill_ldt_descriptor(ds, ds_base, 1 + (ds_limit-1)/PAGE_SIZE, ACC_PL_U|ACC_DATA_W, SZ_32|SZ_G); + + fill_ldt_descriptor(cs, cs_base, cs_limit-1, ACC_PL_U|ACC_CODE_R, SZ_32); + fill_ldt_descriptor(ds, ds_base, ds_limit-1, ACC_PL_U|ACC_DATA_W, SZ_32); + +#if 0 + struct real_descriptor *dsd = get_descriptor(ldt,ds); + printf( + "ds 0x%x: lim low %x, base low %x, base med %x, acc %x, lim hi %x, gran %x, base hi %x (g must be %x)\ndump:\n", + ds, + + dsd->limit_low, + dsd->base_low, + dsd->base_med, + dsd->access, + dsd->limit_high, + dsd->granularity, + dsd->base_high, + SZ_32|SZ_G + ); + hexdump( dsd, sizeof(*dsd), 0, 0 ); +#endif + + *ocs = cs; + *ods = ds; + + return 0; +} + +errno_t get_uldt_sel( u_int16_t *osel, linaddr_t sel_base, size_t sel_limit, int code, int is32 ) +{ +#if 0 + if( (segsToUse >> 3) >= LDTSZ ) + return ENOMEM; + + u_int16_t s = segsToUse | 0x7; + + segsToUse += 0x8; +#else + u_int16_t s = alloc_ldt_selector(); + if( s == NULL_SELECTOR ) + return ENOMEM; + + s |= SELECTOR_USER; +#endif + + fill_ldt_descriptor(s, sel_base, sel_limit-1, ACC_PL_U | ( code ? ACC_CODE_R : ACC_DATA_W ), is32 ? SZ_32 : 0 ); + + *osel = s; + + return 0; +} + +#define USE_LDT_PHYSALLOC 1 + + + + +#if USE_LDT_PHYSALLOC +static map_elem_t ldt_mapbuf[MAP_SIZE_ELEM(LDTSZ)]; +static physalloc_t ldt_map; +#else +static int segsToUse = 0x10; +#endif + +static void init_ldt_alloc(void) +{ + phantom_phys_alloc_init_static( &ldt_map, LDTSZ, ldt_mapbuf ); + phantom_phys_free_region( &ldt_map, LDT_RESERVED, LDTSZ-LDT_RESERVED-1 ); // -1 = error in phantom_phys_free_region? + ldt_map.allocable_size = LDTSZ-LDT_RESERVED-1; + ldt_map.n_used_pages = 0; +} + +INIT_ME(init_ldt_alloc, 0, 0) + + +selector_id alloc_ldt_selector(void) +{ + //STAT_INC_CNT(STAT_CNT_LDT_ALLOC); +#if USE_LDT_PHYSALLOC + physalloc_item_t ret; + errno_t rc = phantom_phys_alloc_page( &ldt_map, &ret ); + if( rc ) + return NULL_SELECTOR; + u_int16_t s = (((u_int16_t)ret) << 3) | SELECTOR_LDT; + SHOW_FLOW( 3, "alloc ldt sel %x", s ); + return s; +#else + + if( (segsToUse >> 3) >= LDTSZ ) + return NULL_SELECTOR; + + u_int16_t s = segsToUse | SELECTOR_LDT; + + segsToUse += 0x8; + + return s; +#endif +} + +void free_ldt_selector(selector_id sel) +{ + assert(SELECTOR_IS_LDT(sel)); + //STAT_INC_CNT(STAT_CNT_LDT_FREE); + + fill_ldt_descriptor(sel, 0, 0, 0, 0 ); + +#if USE_LDT_PHYSALLOC + SHOW_FLOW( 3, "free ldt sel %x", sel ); + phantom_phys_free_page( &ldt_map, sel>>3 ); +#else + SHOW_ERROR( 0, "unimpl free ldt sel %x", sel ); +#endif +} + diff --git a/pool/shard002/C/0060607_nm-setting-team.c b/pool/shard002/C/0060607_nm-setting-team.c new file mode 100644 index 0000000000000000000000000000000000000000..f5dcdc9442db3a0b76da46bd225e30c77ad24e73 --- /dev/null +++ b/pool/shard002/C/0060607_nm-setting-team.c @@ -0,0 +1,255 @@ +/* -*- Mode: C; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- */ +/* + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the + * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + * Boston, MA 02110-1301 USA. + * + * Copyright 2013 Jiri Pirko + */ + +#include "nm-default.h" + +#include +#include +#include + +#include "nm-setting-team.h" +#include "nm-param-spec-specialized.h" +#include "nm-utils.h" +#include "nm-utils-private.h" +#include "nm-dbus-glib-types.h" +#include "nm-setting-private.h" + +/** + * SECTION:nm-setting-team + * @short_description: Describes connection properties for teams + * @include: nm-setting-team.h + * + * The #NMSettingTeam object is a #NMSetting subclass that describes properties + * necessary for team connections. + * + * Since: 0.9.10 + **/ + +/** + * nm_setting_team_error_quark: + * + * Registers an error quark for #NMSettingTeam if necessary. + * + * Returns: the error quark used for #NMSettingTeam errors. + * + * Since: 0.9.10 + **/ +GQuark +nm_setting_team_error_quark (void) +{ + static GQuark quark; + + if (G_UNLIKELY (!quark)) + quark = g_quark_from_static_string ("nm-setting-team-error-quark"); + return quark; +} + + +G_DEFINE_TYPE_WITH_CODE (NMSettingTeam, nm_setting_team, NM_TYPE_SETTING, + _nm_register_setting (NM_SETTING_TEAM_SETTING_NAME, + g_define_type_id, + 1, + NM_SETTING_TEAM_ERROR)) +NM_SETTING_REGISTER_TYPE (NM_TYPE_SETTING_TEAM) + +#define NM_SETTING_TEAM_GET_PRIVATE(o) (G_TYPE_INSTANCE_GET_PRIVATE ((o), NM_TYPE_SETTING_TEAM, NMSettingTeamPrivate)) + +typedef struct { + char *interface_name; + char *config; +} NMSettingTeamPrivate; + +enum { + PROP_0, + PROP_INTERFACE_NAME, + PROP_CONFIG, + LAST_PROP +}; + +/** + * nm_setting_team_new: + * + * Creates a new #NMSettingTeam object with default values. + * + * Returns: (transfer full): the new empty #NMSettingTeam object + * + * Since: 0.9.10 + **/ +NMSetting * +nm_setting_team_new (void) +{ + return (NMSetting *) g_object_new (NM_TYPE_SETTING_TEAM, NULL); +} + +/** + * nm_setting_team_get_interface_name: + * @setting: the #NMSettingTeam + * + * Returns: the #NMSettingTeam:interface-name property of the setting + * + * Since: 0.9.10 + **/ +const char * +nm_setting_team_get_interface_name (NMSettingTeam *setting) +{ + g_return_val_if_fail (NM_IS_SETTING_TEAM (setting), NULL); + + return NM_SETTING_TEAM_GET_PRIVATE (setting)->interface_name; +} + +/** + * nm_setting_team_get_config: + * @setting: the #NMSettingTeam + * + * Returns: the #NMSettingTeam:config property of the setting + * + * Since: 0.9.10 + **/ +const char * +nm_setting_team_get_config (NMSettingTeam *setting) +{ + g_return_val_if_fail (NM_IS_SETTING_TEAM (setting), NULL); + + return NM_SETTING_TEAM_GET_PRIVATE (setting)->config; +} + +static gboolean +verify (NMSetting *setting, GSList *all_settings, GError **error) +{ + NMSettingTeamPrivate *priv = NM_SETTING_TEAM_GET_PRIVATE (setting); + + return _nm_setting_verify_deprecated_virtual_iface_name ( + priv->interface_name, FALSE, + NM_SETTING_TEAM_SETTING_NAME, NM_SETTING_TEAM_INTERFACE_NAME, + NM_SETTING_TEAM_ERROR, + NM_SETTING_TEAM_ERROR_INVALID_PROPERTY, + NM_SETTING_TEAM_ERROR_MISSING_PROPERTY, + all_settings, error); +} + +static const char * +get_virtual_iface_name (NMSetting *setting) +{ + NMSettingTeam *self = NM_SETTING_TEAM (setting); + + return nm_setting_team_get_interface_name (self); +} + +static void +nm_setting_team_init (NMSettingTeam *setting) +{ +} + +static void +finalize (GObject *object) +{ + NMSettingTeamPrivate *priv = NM_SETTING_TEAM_GET_PRIVATE (object); + + g_free (priv->interface_name); + g_free (priv->config); + + G_OBJECT_CLASS (nm_setting_team_parent_class)->finalize (object); +} + +static void +set_property (GObject *object, guint prop_id, + const GValue *value, GParamSpec *pspec) +{ + NMSettingTeamPrivate *priv = NM_SETTING_TEAM_GET_PRIVATE (object); + + switch (prop_id) { + case PROP_INTERFACE_NAME: + g_free (priv->interface_name); + priv->interface_name = g_value_dup_string (value); + break; + case PROP_CONFIG: + g_free (priv->config); + priv->config = g_value_dup_string (value); + break; + default: + G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec); + break; + } +} + +static void +get_property (GObject *object, guint prop_id, + GValue *value, GParamSpec *pspec) +{ + NMSettingTeam *setting = NM_SETTING_TEAM (object); + + switch (prop_id) { + case PROP_INTERFACE_NAME: + g_value_set_string (value, nm_setting_team_get_interface_name (setting)); + break; + case PROP_CONFIG: + g_value_set_string (value, nm_setting_team_get_config (setting)); + break; + default: + G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec); + break; + } +} + +static void +nm_setting_team_class_init (NMSettingTeamClass *setting_class) +{ + GObjectClass *object_class = G_OBJECT_CLASS (setting_class); + NMSettingClass *parent_class = NM_SETTING_CLASS (setting_class); + + g_type_class_add_private (setting_class, sizeof (NMSettingTeamPrivate)); + + /* virtual methods */ + object_class->set_property = set_property; + object_class->get_property = get_property; + object_class->finalize = finalize; + parent_class->verify = verify; + parent_class->get_virtual_iface_name = get_virtual_iface_name; + + /* Properties */ + /** + * NMSettingTeam:interface-name: + * + * The name of the virtual in-kernel team network interface + **/ + g_object_class_install_property + (object_class, PROP_INTERFACE_NAME, + g_param_spec_string (NM_SETTING_TEAM_INTERFACE_NAME, "", "", + NULL, + G_PARAM_READWRITE | + NM_SETTING_PARAM_INFERRABLE | + G_PARAM_STATIC_STRINGS)); + + /** + * NMSettingTeam:config: + * + * The JSON configuration for the team network interface. The property + * should contain raw JSON configuration data suitable for teamd, because + * the value is passed directly to teamd. If not specified, the default + * configuration is used. See man teamd.conf for the format details. + **/ + g_object_class_install_property + (object_class, PROP_CONFIG, + g_param_spec_string (NM_SETTING_TEAM_CONFIG, "", "", + NULL, + G_PARAM_READWRITE | + NM_SETTING_PARAM_INFERRABLE | + G_PARAM_STATIC_STRINGS)); +} diff --git a/pool/shard002/C/0060611_tester.c b/pool/shard002/C/0060611_tester.c new file mode 100644 index 0000000000000000000000000000000000000000..4e52260e78a36c5c38eb3db74690259f8830e660 --- /dev/null +++ b/pool/shard002/C/0060611_tester.c @@ -0,0 +1,166 @@ + +/** +*** +**/ + +#include +#include +#include +#include +#include + +#include "mz.hpp" +#include "pe.hpp" + +#ifdef _MSC_VER +# define bzero(ptr, size) memset((ptr), 0, (size)) +#endif /* _MSC_VER */ + +#ifdef _MSC_VER +# pragma warning(push) +# pragma warning(disable: 4003) // not enough actual parameters for macro 'GET_PREFIX' +#endif /* _MSC_VER */ + +#include "yad.h" +#include "yad.c" + +#ifdef _MSC_VER +#pragma warning(pop) +#endif /* _MSC_VER */ + +#ifdef LOGGING +# define log printf +#else +# define log +#endif /* LOGGING */ + +#define IMAGE_SIZEOF_SHORT_NAME 8 +typedef struct _IMAGE_SECTION_HEADER { + uint8_t Name[IMAGE_SIZEOF_SHORT_NAME]; + union { + uint32_t PhysicalAddress; + uint32_t VirtualSize; + } Misc; + uint32_t VirtualAddress; + uint32_t SizeOfRawData; + uint32_t PointerToRawData; + uint32_t PointerToRelocations; + uint32_t PointerToLinenumbers; + uint16_t NumberOfRelocations; + uint16_t NumberOfLinenumbers; + uint32_t Characteristics; +} IMAGE_SECTION_HEADER; + +uint32_t rva_to_offset(PE_HEADER *pe, uint32_t rva) +{ + int i; + IMAGE_SECTION_HEADER *shdr = (IMAGE_SECTION_HEADER*)((char*)pe + sizeof(PE_HEADER)); + for (i = 0; i < pe->pe_numofobjects; i++) { + if (rva >= shdr[i].VirtualAddress && rva < shdr[i].VirtualAddress + shdr[i].Misc.VirtualSize) + return rva - shdr[i].VirtualAddress + shdr[i].PointerToRawData; + } + return 0; +} + +void process_buffer(uint8_t *buffer) { + MZ_HEADER *mz; + PE_HEADER *pe; + uint8_t *opcode; + yad_t diza; + int retval, i; + + mz = (MZ_HEADER*)buffer; + //assert(mz->mz_id == MZ_ID); + if (mz->mz_id != MZ_ID) return; /* skip old formats */ + if (mz->mz_neptr == 0) return; /* skip ms-dos, ne-files */ + pe = (PE_HEADER*)&buffer[mz->mz_neptr]; + assert(pe->pe_id == PE_ID); + + if (pe->pe_entrypointrva == 0) return; + log(" \xfe EP: %08X\n", pe->pe_entrypointrva); + printf("%d %d\n", pe->pe_ntheadersize + 0x18, sizeof(PE_HEADER)); + opcode = (char*)buffer + rva_to_offset(pe, pe->pe_entrypointrva); + for (retval = 0;;) { + retval = yad(opcode, &diza); + if (retval == 0) { + printf(" \xfe abort at %p\n", opcode); + printf(" \xfe bytes: %02X %02X %02X %02X %02X %02X %02X %02X\n\n", + *(opcode + 0), *(opcode + 1), *(opcode + 2), *(opcode + 3), + *(opcode + 4), *(opcode + 5), *(opcode + 6), *(opcode + 7)); + break; + } +#ifdef LOGGING + log((" \xfe ")); + for (i = 0; i < retval; ++i) { + log("%02X ", *(opcode + i)); + } + log(("\n")); +#endif /* LOGGING */ + if (diza.opcode == 0xc3 || diza.opcode == 0xc2) { /* ret/retn */ + break; + } + opcode += retval; + if (opcode > (buffer + pe->pe_imagesize - 16)) break; + } +} + +void process_file(const char *fname) { + FILE *fp; + printf("\xfe processing '%s'... \n", fname); + fp = fopen(fname, "rb"); + if (fp != NULL) { + uint8_t *buffer; + size_t filelen; + filelen = filelength(fileno(fp)); + buffer = (uint8_t *)malloc(filelen); + if (buffer != NULL) { + fread(buffer, 1, filelen, fp); + process_buffer(buffer); + free(buffer); + } + fclose(fp); + } +} + +void process_dir(const char *dir, char **fmask, size_t count) { + intptr_t fh; + char path[260]; + struct _finddata_t wfd; + + _snprintf(path, sizeof(path), "%s\\*.*", dir); + memset(&wfd, 0, sizeof(wfd)); + fh = _findfirst(path, &wfd); + if (fh > 0) { + do { + if (wfd.attrib & _A_SUBDIR) { + if (strcmp(wfd.name, ".") && strcmp(wfd.name, "..")) { + _snprintf(path, sizeof(path), "%s\\%s", dir, wfd.name); + process_dir(path, fmask, count); + } + } else { + const char *p = &wfd.name[strlen(wfd.name) - 1]; + for (; p > wfd.name && *p != '.'; --p) ; + if (p > wfd.name && *p == '.') { + size_t i = 0; + for (; i < count; ++i) { + if (!stricmp(p, fmask[i])) { + _snprintf(path, sizeof(path), "%s\\%s", dir, wfd.name); + process_file(path); + break; + } + } + } + } + } while (!_findnext(fh, &wfd)); + _findclose(fh); + } +} + +int main(int argc, char **argv) { + char *fmask[] = { ".exe", ".dll", ".drv", ".sys" }; + process_file(argv[1]); +// process_dir("C:\\WINDOWS\\system32", fmask, sizeof(fmask) / sizeof(fmask[0])); + return EXIT_SUCCESS; +} + +/* [EOF] */ diff --git a/pool/shard002/C/0060624_buddy.c b/pool/shard002/C/0060624_buddy.c new file mode 100644 index 0000000000000000000000000000000000000000..749aecf7c6cea0967392dd9f83f9532f440467fd --- /dev/null +++ b/pool/shard002/C/0060624_buddy.c @@ -0,0 +1,273 @@ +/* Copyright (c) 2007, Sandia National Laboratories */ + +#include +#include +#include +#include + + +/** + * Each free block has one of these structures at its head. The link member + * provides linkage for the mp->avail[order] free list, where order is the + * size of the free block. + */ +struct block { + struct list_head link; + unsigned long order; +}; + + +/** + * Converts a block address to its block index in the specified buddy allocator. + * A block's index is used to find the block's tag bit, mp->tag_bits[block_id]. + */ +static unsigned long +block_to_id(struct buddy_mempool *mp, struct block *block) +{ + unsigned long block_id = + ((unsigned long)block - mp->base_addr) >> mp->min_order; + BUG_ON(block_id >= mp->num_blocks); + return block_id; +} + + +/** + * Marks a block as free by setting its tag bit to one. + */ +static void +mark_available(struct buddy_mempool *mp, struct block *block) +{ + __set_bit(block_to_id(mp, block), mp->tag_bits); +} + + +/** + * Marks a block as allocated by setting its tag bit to zero. + */ +static void +mark_allocated(struct buddy_mempool *mp, struct block *block) +{ + __clear_bit(block_to_id(mp, block), mp->tag_bits); +} + + +/** + * Returns true if block is free, false if it is allocated. + */ +static int +is_available(struct buddy_mempool *mp, struct block *block) +{ + return test_bit(block_to_id(mp, block), mp->tag_bits); +} + + +/** + * Returns the address of the block's buddy block. + */ +static void * +find_buddy(struct buddy_mempool *mp, struct block *block, unsigned long order) +{ + unsigned long _block; + unsigned long _buddy; + + BUG_ON((unsigned long)block < mp->base_addr); + + /* Fixup block address to be zero-relative */ + _block = (unsigned long)block - mp->base_addr; + + /* Calculate buddy in zero-relative space */ + _buddy = _block ^ (1UL << order); + + /* Return the buddy's address */ + return (void *)(_buddy + mp->base_addr); +} + + +/** + * Initializes a buddy system memory allocator object. + * + * Arguments: + * [IN] base_addr: Base address of the memory pool. + * [IN] pool_order: Size of the memory pool (2^pool_order bytes). + * [IN] min_order: Minimum allocatable block size (2^min_order bytes). + * + * Returns: + * Success: Pointer to an initialized buddy system memory allocator. + * Failure: NULL + * + * NOTE: The min_order argument is provided as an optimization. Since one tag + * bit is required for each minimum-sized block, large memory pools that + * allow order 0 allocations will use large amounts of memory. Specifying + * a min_order of 5 (32 bytes), for example, reduces the number of tag + * bits by 32x. + */ +struct buddy_mempool * +buddy_init( + unsigned long base_addr, + unsigned long pool_order, + unsigned long min_order +) +{ + struct buddy_mempool *mp; + unsigned long i; + + /* Smallest block size must be big enough to hold a block structure */ + if ((1UL << min_order) < sizeof(struct block)) + min_order = ilog2( roundup_pow_of_two(sizeof(struct block)) ); + + /* The minimum block order must be smaller than the pool order */ + if (min_order > pool_order) + return NULL; + + mp = alloc_bootmem(sizeof(struct buddy_mempool)); + + mp->base_addr = base_addr; + mp->pool_order = pool_order; + mp->min_order = min_order; + + /* Allocate a list for every order up to the maximum allowed order */ + mp->avail = alloc_bootmem((pool_order + 1) * sizeof(struct list_head)); + + /* Initially all lists are empty */ + for (i = 0; i <= pool_order; i++) + INIT_LIST_HEAD(&mp->avail[i]); + + /* Allocate a bitmap with 1 bit per minimum-sized block */ + mp->num_blocks = (1UL << pool_order) / (1UL << min_order); + mp->tag_bits = alloc_bootmem( + BITS_TO_LONGS(mp->num_blocks) * sizeof(long) + ); + + /* Initially mark all minimum-sized blocks as allocated */ + bitmap_zero(mp->tag_bits, mp->num_blocks); + + return mp; +} + + +/** + * Allocates a block of memory of the requested size (2^order bytes). + * + * Arguments: + * [IN] mp: Buddy system memory allocator object. + * [IN] order: Block size to allocate (2^order bytes). + * + * Returns: + * Success: Pointer to the start of the allocated memory block. + * Failure: NULL + */ +void * +buddy_alloc(struct buddy_mempool *mp, unsigned long order) +{ + unsigned long j; + struct list_head *list; + struct block *block; + struct block *buddy_block; + + BUG_ON(mp == NULL); + BUG_ON(order > mp->pool_order); + + /* Fixup requested order to be at least the minimum supported */ + if (order < mp->min_order) + order = mp->min_order; + + for (j = order; j <= mp->pool_order; j++) { + + /* Try to allocate the first block in the order j list */ + list = &mp->avail[j]; + if (list_empty(list)) + continue; + block = list_entry(list->next, struct block, link); + list_del(&block->link); + mark_allocated(mp, block); + + /* Trim if a higher order block than necessary was allocated */ + while (j > order) { + --j; + buddy_block = (struct block *)((unsigned long)block + (1UL << j)); + buddy_block->order = j; + mark_available(mp, buddy_block); + list_add(&buddy_block->link, &mp->avail[j]); + } + + return block; + } + + return NULL; +} + + +/** + * Returns a block of memory to the buddy system memory allocator. + */ +void +buddy_free( + //! Buddy system memory allocator object. + struct buddy_mempool * mp, + //! Address of memory block to free. + const void * addr, + //! Size of the memory block (2^order bytes). + unsigned long order +) +{ + BUG_ON(mp == NULL); + BUG_ON(order > mp->pool_order); + + /* Fixup requested order to be at least the minimum supported */ + if (order < mp->min_order) + order = mp->min_order; + + /* Overlay block structure on the memory block being freed */ + struct block * block = (struct block *) addr; + BUG_ON(is_available(mp, block)); + + /* Coalesce as much as possible with adjacent free buddy blocks */ + while (order < mp->pool_order) { + /* Determine our buddy block's address */ + struct block * buddy = find_buddy(mp, block, order); + + /* Make sure buddy is available and has the same size as us */ + if (!is_available(mp, buddy)) + break; + if (is_available(mp, buddy) && (buddy->order != order)) + break; + + /* OK, we're good to go... buddy merge! */ + list_del(&buddy->link); + if (buddy < block) + block = buddy; + ++order; + block->order = order; + } + + /* Add the (possibly coalesced) block to the appropriate free list */ + block->order = order; + mark_available(mp, block); + list_add(&block->link, &mp->avail[order]); +} + + +/** + * Dumps the state of a buddy system memory allocator object to the console. + */ +void +buddy_dump_mempool(struct buddy_mempool *mp) +{ + unsigned long i; + unsigned long num_blocks; + struct list_head *entry; + + printk(KERN_DEBUG "DUMP OF BUDDY MEMORY POOL:\n"); + + for (i = mp->min_order; i <= mp->pool_order; i++) { + + /* Count the number of memory blocks in the list */ + num_blocks = 0; + list_for_each(entry, &mp->avail[i]) + ++num_blocks; + + printk(KERN_DEBUG " order %2lu: %lu free blocks\n", i, num_blocks); + } +} + + diff --git a/pool/shard002/C/0060641_marker.c b/pool/shard002/C/0060641_marker.c new file mode 100644 index 0000000000000000000000000000000000000000..b3beeae1d69707423ff05524dc19eb49fc6bafef --- /dev/null +++ b/pool/shard002/C/0060641_marker.c @@ -0,0 +1,158 @@ +/* + * AR2/marker.c + * ARToolKit5 + * + * This file is part of ARToolKit. + * + * ARToolKit 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. + * + * ARToolKit 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 ARToolKit. If not, see . + * + * As a special exception, the copyright holders of this library give you + * permission to link this library with independent modules to produce an + * executable, regardless of the license terms of these independent modules, and to + * copy and distribute the resulting executable under terms of your choice, + * provided that you also meet, for each linked independent module, the terms and + * conditions of the license of that module. An independent module is a module + * which is neither derived from nor based on this library. If you modify this + * library, you may extend this exception to your version of the library, but you + * are not obligated to do so. If you do not wish to do so, delete this exception + * statement from your version. + * + * Copyright 2015 Daqri, LLC. + * Copyright 2006-2015 ARToolworks, Inc. + * + * Author(s): Hirokazu Kato, Philip Lamb + * + */ + +#include +#include +#include +#include +#include + +static char *get_buff( char *buf, int n, FILE *fp ); + +int ar2FreeMarkerSet( AR2MarkerSetT **markerSet ) +{ + if( *markerSet == NULL ) return -1; + + free( (*markerSet)->marker ); + free( *markerSet ); + *markerSet = NULL; + + return 0; +} + +AR2MarkerSetT *ar2ReadMarkerSet( char *filename, char *ext, ARPattHandle *pattHandle ) +{ + //COVHI10394 + FILE *fp = NULL; + AR2MarkerSetT *markerSet = NULL; + char buf[256], buf1[256]/*, buf2[256]*/; + int i, j; + + char namebuf[512]; + sprintf(namebuf, "%s.%s", filename, ext); + if( (fp=fopen(namebuf, "r")) == NULL ) return NULL; + + arMalloc( markerSet, AR2MarkerSetT, 1 ); + + if( get_buff(buf, 256, fp) == NULL ) { + free( markerSet ); + markerSet = NULL; + goto ar2ReadMarkerSet_EXIT; + } + if( sscanf(buf, "%d", &(markerSet->num)) != 1 ) { + free( markerSet ); + markerSet = NULL; + goto ar2ReadMarkerSet_EXIT; + } + if( markerSet->num <= 0 ) { + free(markerSet); + markerSet = NULL; + goto ar2ReadMarkerSet_EXIT; + } + + arMalloc( markerSet->marker, AR2MarkerT, markerSet->num ); + + for( i = 0; i < markerSet->num; i++ ) { + if( get_buff(buf, 256, fp) == NULL ) { + free( markerSet->marker ); + free( markerSet ); + markerSet = NULL; + goto ar2ReadMarkerSet_EXIT; + } + if( sscanf(buf, "%s", buf1) != 1 ) { + free( markerSet->marker ); + free( markerSet ); + markerSet = NULL; + goto ar2ReadMarkerSet_EXIT; + } + //ar2UtilDivideExt(buf1, buf, buf2); + if( (markerSet->marker[i].pattId = arPattLoad(pattHandle, buf1)) < 0 ) { + free( markerSet->marker ); + free( markerSet ); + markerSet = NULL; + goto ar2ReadMarkerSet_EXIT; + } + + if( get_buff(buf, 256, fp) == NULL ) { + free( markerSet->marker ); + free( markerSet ); + markerSet = NULL; + goto ar2ReadMarkerSet_EXIT; + } + if( sscanf(buf, "%f", &(markerSet->marker[i].width)) != 1 ) { + free( markerSet->marker ); + free( markerSet ); + markerSet = NULL; + goto ar2ReadMarkerSet_EXIT; + } + + for( j = 0; j < 3; j++ ) { + if( get_buff(buf, 256, fp) == NULL ) { + free( markerSet->marker ); + free( markerSet ); + markerSet = NULL; + goto ar2ReadMarkerSet_EXIT; + } + if( sscanf(buf, "%f %f %f %f", + &(markerSet->marker[i].transI2M[j][0]), + &(markerSet->marker[i].transI2M[j][1]), + &(markerSet->marker[i].transI2M[j][2]), + &(markerSet->marker[i].transI2M[j][3])) != 4 ) { + free( markerSet->marker ); + free( markerSet ); + markerSet = NULL; + goto ar2ReadMarkerSet_EXIT; + } + } + } + + ar2ReadMarkerSet_EXIT: + fclose(fp); + return markerSet; +} + +static char *get_buff( char *buf, int n, FILE *fp ) +{ + char *ret; + + for(;;) { + ret = fgets( buf, n, fp ); + if( ret == NULL ) return(NULL); + if( buf[0] != '\n' && buf[0] != '#' ) return(ret); + } +} + diff --git a/pool/shard002/C/0060643_sem01.c b/pool/shard002/C/0060643_sem01.c new file mode 100644 index 0000000000000000000000000000000000000000..d6fb8fb01dc0fe729546ce0169b34f5b16fa729b --- /dev/null +++ b/pool/shard002/C/0060643_sem01.c @@ -0,0 +1,170 @@ +/* + * + * 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 + */ + +/* + * FILE : sem01.c + * DESCRIPTION : Creates a semaphore and two processes. The processes + * each go through a loop where they semdown, delay for a + * random amount of time, and semup, so they will almost + * always be fighting for control of the semaphore. + * HISTORY: + * 01/15/2001 Paul Larson (plars@us.ibm.com) + * -written + * 11/09/2001 Manoj Iyer (manjo@ausin.ibm.com) + * Modified. + * - Removed compiler warnings. + * added exit to the end of function main() + * + */ + +#include +#include +#include +#include +#include +#include +#include +#include + +union semun { + int val; + struct semid_ds *buf; + unsigned short *array; +}; + +int verbose = 0; +int loops = 100; +int errors = 0; + +int semup(int semid) +{ + struct sembuf semops; + semops.sem_num = 0; + semops.sem_op = 1; + semops.sem_flg = SEM_UNDO; + if (semop(semid, &semops, 1) == -1) { + perror("semup"); + errors++; + return 1; + } + return 0; +} + +int semdown(int semid) +{ + struct sembuf semops; + semops.sem_num = 0; + semops.sem_op = -1; + semops.sem_flg = SEM_UNDO; + if (semop(semid, &semops, 1) == -1) { + perror("semdown"); + errors++; + return 1; + } + return 0; +} + +void delayloop() +{ + int delay; + delay = 1 + ((100.0 * rand()) / RAND_MAX); + if (verbose) + printf("in delay function for %d microseconds\n", delay); + usleep(delay); +} + +void mainloop(int semid) +{ + int i; + for (i = 0; i < loops; i++) { + if (semdown(semid)) { + printf("semdown failed\n"); + } + if (verbose) + printf("sem is down\n"); + delayloop(); + if (semup(semid)) { + printf("semup failed\n"); + } + if (verbose) + printf("sem is up\n"); + } +} + +int main(int argc, char *argv[]) +{ + int semid, opt; + union semun semunion; + extern char *optarg; + pid_t pid; + int chstat; + + while ((opt = getopt(argc, argv, "l:vh")) != EOF) { + switch ((char)opt) { + case 'l': + loops = atoi(optarg); + break; + case 'v': + verbose = 1; + break; + case 'h': + default: + printf("Usage: -l loops [-v]\n"); + exit(1); + } + } + + /* set up the semaphore */ + if ((semid = semget((key_t) 9142, 1, 0666 | IPC_CREAT)) < 0) { + printf("error in semget()\n"); + exit(-1); + } + semunion.val = 1; + if (semctl(semid, 0, SETVAL, semunion) == -1) { + printf("error in semctl\n"); + } + + if ((pid = fork()) < 0) { + printf("fork error\n"); + exit(-1); + } + if (pid) { + /* parent */ + srand(pid); + mainloop(semid); + waitpid(pid, &chstat, 0); + if (!WIFEXITED(chstat)) { + printf("child exited with status\n"); + exit(-1); + } + if (semctl(semid, 0, IPC_RMID, semunion) == -1) { + printf("error in semctl\n"); + } + if (errors) { + printf("FAIL: there were %d errors\n", errors); + } else { + printf("PASS: error count is 0\n"); + } + exit(errors); + } else { + /* child */ + mainloop(semid); + } + exit(0); +} diff --git a/pool/shard002/C/0060645_bitmap.c b/pool/shard002/C/0060645_bitmap.c new file mode 100644 index 0000000000000000000000000000000000000000..e650917a4faed56a0cf0bc995d8b81737f93dba8 --- /dev/null +++ b/pool/shard002/C/0060645_bitmap.c @@ -0,0 +1,66 @@ +#include +#include +#include +#include + +#include "bitmap.h" +#include "debug_config.h" + +#if DEBUG_BITMAP +/* + * This macro definition is a GNU extension to the C Standard. It lets us pass + * a variable number of arguments and does some special magic for those cases + * when only a string is passed. For a more detailed explanation, see the gcc + * manual here: http://gcc.gnu.org/onlinedocs/gcc-3.4.6/gcc/Variadic-Macros.html#Variadic-Macros + */ +#define DBG_PRINTF(format, ...) fprintf(stderr, format, ## __VA_ARGS__) +#else +#define DBG_PRINTF(format, ...) +#endif + +/* + * bitmap_load + */ +int bitmap_load (bitmap_t *bitmap, const char *filename) +{ + int size; + + memset(bitmap, 0, sizeof (bitmap_t)); + + int fd = open (filename, O_RDONLY); + if (fd == -1) + { + perror ("open "); + return -1; + } + + read(fd, &bitmap->width, sizeof(short int)); + read(fd, &bitmap->height, sizeof(short int)); + size = bitmap->width * bitmap->height * sizeof(short int); + bitmap->bitmap = malloc(size); + + if (bitmap->bitmap == NULL) + { + close(fd); + return -1; + } + + read(fd, bitmap->bitmap, size); + close(fd); + + DBG_PRINTF("Loaded %s %d %d\n", filename, bitmap->width, bitmap->height); + + return 0; +} + + +/* + * bitmap_free + */ +void bitmap_free (bitmap_t *bitmap) +{ + if (bitmap->bitmap) { + free (bitmap->bitmap); + } + memset(bitmap, 0, sizeof(bitmap_t)); +} diff --git a/pool/shard002/C/0060656_gcmodule.c b/pool/shard002/C/0060656_gcmodule.c new file mode 100644 index 0000000000000000000000000000000000000000..350730f07e1db47d9c5bd3f63505d547398fea6e --- /dev/null +++ b/pool/shard002/C/0060656_gcmodule.c @@ -0,0 +1,76 @@ +#include "Python.h" + +#define AS_GC(o) ((PyGC_Head *)(o)-1) + +#define FROM_GC(g) ((PyObject *)(((PyGC_Head *)g)+1)) + +struct gc_generation { + PyGC_Head head; + int threshold; + int count; +}; + +#define NUM_GENERATIONS 3 +#define GEN_HEAD(n) (&generations[n].head) + +static struct gc_generation generations[NUM_GENERATIONS] = { + {{{GEN_HEAD(0), GEN_HEAD(0), 0}}, 700, 0}, + {{{GEN_HEAD(1), GEN_HEAD(1), 0}}, 10, 0}, + {{{GEN_HEAD(2), GEN_HEAD(2), 0}}, 10, 0}, +}; + +PyGC_Head *_PyGC_generation0 = GEN_HEAD(0); + +#define GC_UNTRACKED _PyGC_REFS_UNTRACKED + +#undef PyObject_GC_Track +#undef PyObject_GC_UnTrack +#undef PyObject_GC_Del +#undef _PyObject_GC_Malloc + +void +PyObject_GC_Track(void *op) +{ + _PyObject_GC_TRACK(op); +} + +PyObject * +_PyObject_GC_Malloc(size_t basicsize) +{ + LOG("> _PyObject_GC_Malloc\n"); { + PyObject *op; + PyGC_Head *g = PyObject_MALLOC(sizeof(PyGC_Head) + basicsize); + + if (g == NULL) + return NULL; /* NO MEM */ + g->gc.gc_refs = GC_UNTRACKED; + generations[0].count++; /* number of allocated GC objects */ + + /* actual collection elides */ + + + op = FROM_GC(g); + LOG("< _PyObject_GC_Malloc\n"); + return op; +}} + +PyObject * +_PyObject_GC_New(PyTypeObject *tp) +{ + LOG("> _PyObject_GC_New\n"); { + PyObject *op = _PyObject_GC_Malloc(_PyObject_SIZE(tp)); + if (op != NULL) + op = PyObject_INIT(op, tp); + LOG("< _PyObject_GC_New\n"); + return op; +}} + +PyVarObject * +_PyObject_GC_NewVar(PyTypeObject *tp, int nitems) +{ + const size_t size = _PyObject_VAR_SIZE(tp, nitems); + PyVarObject *op = (PyVarObject *) _PyObject_GC_Malloc(size); + if (op != NULL) + op = PyObject_INIT_VAR(op, tp, nitems); + return op; +} diff --git a/pool/shard002/C/0060662_datatypes.c b/pool/shard002/C/0060662_datatypes.c new file mode 100644 index 0000000000000000000000000000000000000000..4086785f084a75190a5d1e7a32779df002009d1e --- /dev/null +++ b/pool/shard002/C/0060662_datatypes.c @@ -0,0 +1,147 @@ +/* +Copyright (C) 2002-2009, Parrot Foundation. +License: Artistic 2.0, see README and LICENSE for details + +=head1 NAME + +src/datatypes.c - Parrot and native data types functions + +=head1 DESCRIPTION + +The functions in this file are used in .ops files to access the C +and C string constants for Parrot and native data types defined in +F. + +=head2 Functions + +=over 4 + +=cut + +*/ + +#include "parrot/parrot.h" + +/* HEADERIZER HFILE: include/parrot/datatypes.h */ + +/* + +=item C + +Return datatype C for C type_name. + +=cut + +*/ + +PARROT_EXPORT +PARROT_WARN_UNUSED_RESULT +INTVAL +Parrot_dt_get_datatype_enum(PARROT_INTERP, ARGIN(STRING *type_name)) +{ + ASSERT_ARGS(Parrot_dt_get_datatype_enum) + char *type; + int flags = 0; + int i; + + if (STRING_IS_NULL(type_name) || STRING_IS_EMPTY(type_name)) + return enum_type_undef; + + if ('&' == Parrot_str_indexed(interp, type_name, Parrot_str_length(interp, type_name) - 1)) { + type_name = Parrot_str_substr(interp, type_name, 0, + Parrot_str_length(interp, type_name) - 1); + flags |= enum_type_ref_flag; + } + + type = Parrot_str_to_cstring(interp, type_name); + + for (i = enum_first_type; i < enum_last_type; ++i) { + if (STREQ(data_types[i - enum_first_type].name, type)) { + Parrot_str_free_cstring(type); + return i | flags; + } + } + + Parrot_str_free_cstring(type); + + return enum_type_undef; +} + +/* + +=item C + +Return datatype name for C. + +=cut + +*/ + +PARROT_EXPORT +PARROT_WARN_UNUSED_RESULT +PARROT_CANNOT_RETURN_NULL +STRING * +Parrot_dt_get_datatype_name(PARROT_INTERP, INTVAL type) +{ + ASSERT_ARGS(Parrot_dt_get_datatype_name) + const char *s; + STRING *str; + + const int is_ref = type & enum_type_ref_flag; + + type &= ~enum_type_ref_flag; + + s = (type < enum_first_type || type >= enum_last_type) + ? "illegal" + : data_types[type - enum_first_type].name; + + str = Parrot_str_new_init(interp, s, strlen(s), + Parrot_default_encoding_ptr, PObj_external_FLAG); + + return is_ref ? Parrot_str_concat(interp, str, Parrot_str_new(interp, "&", 0)) : str; +} + +/* + +=item C + +Only used to generate Infinity and NaN constants in our corresponding +header file. + +=cut + +*/ + +#ifndef PARROT_HAS_INF_NAN + +PARROT_EXPORT +FLOATVAL +Parrot_dt_divide_floatval_by_zero(SHIM_INTERP, FLOATVAL num) +{ + ASSERT_ARGS(Parrot_dt_divide_floatval_by_zero) + const FLOATVAL zero = 0.0; + return num / zero; +} + +#endif + + +/* + +=back + +=head1 SEE ALSO + +F. + +=cut + +*/ + + +/* + * Local variables: + * c-file-style: "parrot" + * End: + * vim: expandtab shiftwidth=4 cinoptions='\:2=2' : + */ diff --git a/pool/shard002/C/0060685_item.c b/pool/shard002/C/0060685_item.c new file mode 100644 index 0000000000000000000000000000000000000000..35d06497a5cc1c3f02cda3a84d0ce7e46aa3c6e1 --- /dev/null +++ b/pool/shard002/C/0060685_item.c @@ -0,0 +1,157 @@ + + +#include +#include +#include +#include + +#include + + +static inline struct config_item * to_item(struct list_head * entry) +{ + return container_of(entry,struct config_item,ci_entry); +} + +/* Evil kernel */ +static void config_item_release(struct kref *kref); + +void config_item_init(struct config_item * item) +{ + kref_init(&item->ci_kref); + INIT_LIST_HEAD(&item->ci_entry); +} + +int config_item_set_name(struct config_item * item, const char * fmt, ...) +{ + int error = 0; + int limit = CONFIGFS_ITEM_NAME_LEN; + int need; + va_list args; + char * name; + + /* + * First, try the static array + */ + va_start(args,fmt); + need = vsnprintf(item->ci_namebuf,limit,fmt,args); + va_end(args); + if (need < limit) + name = item->ci_namebuf; + else { + /* + * Need more space? Allocate it and try again + */ + limit = need + 1; + name = kmalloc(limit,GFP_KERNEL); + if (!name) { + error = -ENOMEM; + goto Done; + } + va_start(args,fmt); + need = vsnprintf(name,limit,fmt,args); + va_end(args); + + /* Still? Give up. */ + if (need >= limit) { + kfree(name); + error = -EFAULT; + goto Done; + } + } + + /* Free the old name, if necessary. */ + if (item->ci_name && item->ci_name != item->ci_namebuf) + kfree(item->ci_name); + + /* Now, set the new name */ + item->ci_name = name; + Done: + return error; +} + +EXPORT_SYMBOL(config_item_set_name); + +void config_item_init_type_name(struct config_item *item, + const char *name, + struct config_item_type *type) +{ + config_item_set_name(item, name); + item->ci_type = type; + config_item_init(item); +} +EXPORT_SYMBOL(config_item_init_type_name); + +void config_group_init_type_name(struct config_group *group, const char *name, + struct config_item_type *type) +{ + config_item_set_name(&group->cg_item, name); + group->cg_item.ci_type = type; + config_group_init(group); +} +EXPORT_SYMBOL(config_group_init_type_name); + +struct config_item * config_item_get(struct config_item * item) +{ + if (item) + kref_get(&item->ci_kref); + return item; +} + +static void config_item_cleanup(struct config_item * item) +{ + struct config_item_type * t = item->ci_type; + struct config_group * s = item->ci_group; + struct config_item * parent = item->ci_parent; + + pr_debug("config_item %s: cleaning up\n",config_item_name(item)); + if (item->ci_name != item->ci_namebuf) + kfree(item->ci_name); + item->ci_name = NULL; + if (t && t->ct_item_ops && t->ct_item_ops->release) + t->ct_item_ops->release(item); + if (s) + config_group_put(s); + if (parent) + config_item_put(parent); +} + +static void config_item_release(struct kref *kref) +{ + config_item_cleanup(container_of(kref, struct config_item, ci_kref)); +} + +void config_item_put(struct config_item * item) +{ + if (item) + kref_put(&item->ci_kref, config_item_release); +} + +void config_group_init(struct config_group *group) +{ + config_item_init(&group->cg_item); + INIT_LIST_HEAD(&group->cg_children); +} + +struct config_item *config_group_find_item(struct config_group *group, + const char *name) +{ + struct list_head * entry; + struct config_item * ret = NULL; + + list_for_each(entry,&group->cg_children) { + struct config_item * item = to_item(entry); + if (config_item_name(item) && + !strcmp(config_item_name(item), name)) { + ret = config_item_get(item); + break; + } + } + return ret; +} + +EXPORT_SYMBOL(config_item_init); +EXPORT_SYMBOL(config_group_init); +EXPORT_SYMBOL(config_item_get); +EXPORT_SYMBOL(config_item_put); +EXPORT_SYMBOL(config_group_find_item); diff --git a/pool/shard002/C/0060702_basename.c b/pool/shard002/C/0060702_basename.c new file mode 100644 index 0000000000000000000000000000000000000000..d441247416ef27b456e7b0527071513aef6f0294 --- /dev/null +++ b/pool/shard002/C/0060702_basename.c @@ -0,0 +1,61 @@ +/* vi: set sw=4 ts=4: */ +/* + * Mini basename implementation for busybox + * + * Copyright (C) 1999-2004 by Erik Andersen + * + * Licensed under GPLv2 or later, see file LICENSE in this source tree. + */ + +/* Mar 16, 2003 Manuel Novoa III (mjn3@codepoet.org) + * + * Changes: + * 1) Now checks for too many args. Need at least one and at most two. + * 2) Don't check for options, as per SUSv3. + * 3) Save some space by using strcmp(). Calling strncmp() here was silly. + */ + +/* BB_AUDIT SUSv3 compliant */ +/* http://www.opengroup.org/onlinepubs/007904975/utilities/basename.html */ + +//kbuild:lib-$(CONFIG_BASENAME) += basename.o + +//config:config BASENAME +//config: bool "basename" +//config: default y +//config: help +//config: basename is used to strip the directory and suffix from filenames, +//config: leaving just the filename itself. Enable this option if you wish +//config: to enable the 'basename' utility. + +#include "libbb.h" + +/* This is a NOFORK applet. Be very careful! */ + +int basename_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE; +int basename_main(int argc, char **argv) +{ + size_t m, n; + char *s; + + if ((unsigned)(argc-2) >= 2) { + bb_show_usage(); + } + + /* It should strip slash: /abc/def/ -> def */ + s = bb_get_last_path_component_strip(*++argv); + + m = strlen(s); + if (*++argv) { + n = strlen(*argv); + if ((m > n) && (strcmp(s+m-n, *argv) == 0)) { + m -= n; + /*s[m] = '\0'; - redundant */ + } + } + + /* puts(s) will do, but we can do without stdio this way: */ + s[m++] = '\n'; + /* NB: != is correct here: */ + return full_write(STDOUT_FILENO, s, m) != (ssize_t)m; +} diff --git a/pool/shard002/C/0060718_gsl_sf_debye_1.c b/pool/shard002/C/0060718_gsl_sf_debye_1.c new file mode 100644 index 0000000000000000000000000000000000000000..1eff6a965d711926871d3f603c437cc42548017b --- /dev/null +++ b/pool/shard002/C/0060718_gsl_sf_debye_1.c @@ -0,0 +1,14 @@ +#include "stdlib.h" +#include "stdio.h" +#include "/home/lillian/work/install_fpdebug/valgrind-3.7.0/fpdebug/fpdebug.h" +#include +int main(int argc, const char * argv[]) { +unsigned long int hexdouble; +double a; +sscanf(argv[1], "%lX", &hexdouble); +a = *(double*)(&hexdouble); +double result = gsl_sf_debye_1(a); +//printf("%.15f\n", result); +VALGRIND_PRINT_ERROR("result", &result); +return 0; +} \ No newline at end of file diff --git a/pool/shard002/C/0060721_util64.c b/pool/shard002/C/0060721_util64.c new file mode 100644 index 0000000000000000000000000000000000000000..1cf62b66d010e74d983e458d9db815eee401f814 --- /dev/null +++ b/pool/shard002/C/0060721_util64.c @@ -0,0 +1,148 @@ +//***************************************************************************** +// +// Copyright (C) 2014 Texas Instruments Incorporated - http://www.ti.com/ +// +// +// 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 Texas Instruments Incorporated nor the names of +// its contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +//***************************************************************************** + +#include "util64.h" + +#define NSEC_VAL_FOR_1SEC 1000000000 /* Move this to a common file */ + +void util_u32_nsec_add(u32 nsec_1, u32 nsec_2, struct u64_time *result) +{ + /* 1 sec overflow check: v1 nsec + v2 nsec > 1000000000 nanoseconds */ + if(nsec_1 + nsec_2 >= NSEC_VAL_FOR_1SEC) { + result->nsec = nsec_1 + nsec_2; + result->nsec -= NSEC_VAL_FOR_1SEC; + result->secs = 1; /* Carry flag */ + } else { + /* Simple 32bits addition without any carry flag / overflow */ + result->nsec = nsec_1 + nsec_2; + result->secs = 0; + } + + return; +} + +void util_u64_time_add(const struct u64_time *time_1, + const struct u64_time *time_2, + struct u64_time *result) +{ + util_u32_nsec_add(time_1->nsec, time_2->nsec, result); + + result->secs += time_1->secs + time_2->secs; + + return; +} + +void util_u32_data_add(u32 data_1, u32 data_2, struct u64_val *result) +{ + /* 32bit overflow check: v1 + v2 > 0xFFFFFFFF => v1 > 0xFFFFFFFF - v2 */ + if(data_1 > ~data_2) { + /* exceeds by => v1 + v2 - (0xFFFFFFFF + 1) = v1 - (~v2 + 1) */ + result->lo_32 = data_1 - ~data_2 - 1; + result->hi_32 = 1; /* Carry flag */ + } else { + /* Simple 32bits addition without any carry flag and overflow */ + result->lo_32 = data_1 + data_2; + result->hi_32 = 0; + } + + return; +} + +void util_u64_data_add(struct u64_val *value1, struct u64_val *value2, + struct u64_val *result) +{ + util_u32_data_add(value1->lo_32, value2->lo_32, result); + + result->hi_32 += value1->hi_32 + value2->hi_32; + + return; +} + +void util_u32_nsec_sub(u32 from_nsec, u32 this_nsec, + struct u64_time *result) +{ + if(from_nsec < this_nsec) { + result->nsec = NSEC_VAL_FOR_1SEC + from_nsec; + result->nsec -= this_nsec; + result->secs = 0xFFFFFFFF; + } else { + result->nsec = from_nsec - this_nsec; + result->secs = 0; + } + + return; +} + +void util_u64_time_sub(struct u64_time *from, + struct u64_time *this, + struct u64_time *outp) +{ + util_u32_nsec_sub(from->nsec, this->nsec, outp); + + if(from->secs < this->secs + (0xFFFFFFFF == outp->secs)? 1 : 0) + outp->secs = 0xFFFFFFFF; + else + outp->secs += from->secs - this->secs; + + return; +} + +/* Returns: 1 for val1 > val2; 0 for val1 = val2; -1 for val1 < val2 */ +i32 util_u32_data_cmp(u32 val1, u32 val2) +{ + i32 rv = -1; + + if(val1 == val2) + rv = 0; + else if(val1 > val2) + rv = 1; + + return rv; +} + +/* Returns: 1 for val1 > val2; 0 for val1 = val2; -1 for val1 < val2 */ +i32 util_u64_data_cmp(struct u64_val *u64_val1, + struct u64_val *u64_val2) +{ + i32 rv = -1; + + if(u64_val1->hi_32 == u64_val2->hi_32) + rv = util_u32_data_cmp(u64_val1->lo_32, u64_val2->lo_32); + else if(u64_val1->hi_32 > u64_val2->hi_32) + rv = 1; + + return rv; +} +/* TBD: u64 sub */ diff --git a/pool/shard002/C/0060727_io.c b/pool/shard002/C/0060727_io.c new file mode 100644 index 0000000000000000000000000000000000000000..a2a1c4ec2a78229893be6ec3242ab21ee9652ab1 --- /dev/null +++ b/pool/shard002/C/0060727_io.c @@ -0,0 +1,167 @@ +/* + * This file is part of wl1271 + * + * Copyright (C) 2008-2010 Nokia Corporation + * + * Contact: Luciano Coelho + * + * 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 "wlcore.h" +#include "debug.h" +#include "wl12xx_80211.h" +#include "io.h" +#include "tx.h" + +bool wl1271_set_block_size(struct wl1271 *wl) +{ + if (wl->if_ops->set_block_size) { + wl->if_ops->set_block_size(wl->dev, WL12XX_BUS_BLOCK_SIZE); + return true; + } + + return false; +} + +void wlcore_disable_interrupts(struct wl1271 *wl) +{ + disable_irq(wl->irq); +} +EXPORT_SYMBOL_GPL(wlcore_disable_interrupts); + +void wlcore_disable_interrupts_nosync(struct wl1271 *wl) +{ + disable_irq_nosync(wl->irq); +} +EXPORT_SYMBOL_GPL(wlcore_disable_interrupts_nosync); + +void wlcore_enable_interrupts(struct wl1271 *wl) +{ + enable_irq(wl->irq); +} +EXPORT_SYMBOL_GPL(wlcore_enable_interrupts); + +void wlcore_synchronize_interrupts(struct wl1271 *wl) +{ + synchronize_irq(wl->irq); +} +EXPORT_SYMBOL_GPL(wlcore_synchronize_interrupts); + +int wlcore_translate_addr(struct wl1271 *wl, int addr) +{ + struct wlcore_partition_set *part = &wl->curr_part; + + /* + * To translate, first check to which window of addresses the + * particular address belongs. Then subtract the starting address + * of that window from the address. Then, add offset of the + * translated region. + * + * The translated regions occur next to each other in physical device + * memory, so just add the sizes of the preceding address regions to + * get the offset to the new region. + */ + if ((addr >= part->mem.start) && + (addr < part->mem.start + part->mem.size)) + return addr - part->mem.start; + else if ((addr >= part->reg.start) && + (addr < part->reg.start + part->reg.size)) + return addr - part->reg.start + part->mem.size; + else if ((addr >= part->mem2.start) && + (addr < part->mem2.start + part->mem2.size)) + return addr - part->mem2.start + part->mem.size + + part->reg.size; + else if ((addr >= part->mem3.start) && + (addr < part->mem3.start + part->mem3.size)) + return addr - part->mem3.start + part->mem.size + + part->reg.size + part->mem2.size; + + WARN(1, "HW address 0x%x out of range", addr); + return 0; +} +EXPORT_SYMBOL_GPL(wlcore_translate_addr); + + +int wlcore_set_partition(struct wl1271 *wl, + const struct wlcore_partition_set *p) +{ + int ret; + + /* copy partition info */ + memcpy(&wl->curr_part, p, sizeof(*p)); + + wl1271_debug(DEBUG_IO, "mem_start %08X mem_size %08X", + p->mem.start, p->mem.size); + wl1271_debug(DEBUG_IO, "reg_start %08X reg_size %08X", + p->reg.start, p->reg.size); + wl1271_debug(DEBUG_IO, "mem2_start %08X mem2_size %08X", + p->mem2.start, p->mem2.size); + wl1271_debug(DEBUG_IO, "mem3_start %08X mem3_size %08X", + p->mem3.start, p->mem3.size); + + ret = wlcore_raw_write32(wl, HW_PART0_START_ADDR, p->mem.start); + if (ret < 0) + goto out; + + ret = wlcore_raw_write32(wl, HW_PART0_SIZE_ADDR, p->mem.size); + if (ret < 0) + goto out; + + ret = wlcore_raw_write32(wl, HW_PART1_START_ADDR, p->reg.start); + if (ret < 0) + goto out; + + ret = wlcore_raw_write32(wl, HW_PART1_SIZE_ADDR, p->reg.size); + if (ret < 0) + goto out; + + ret = wlcore_raw_write32(wl, HW_PART2_START_ADDR, p->mem2.start); + if (ret < 0) + goto out; + + ret = wlcore_raw_write32(wl, HW_PART2_SIZE_ADDR, p->mem2.size); + if (ret < 0) + goto out; + + /* + * We don't need the size of the last partition, as it is + * automatically calculated based on the total memory size and + * the sizes of the previous partitions. + */ + ret = wlcore_raw_write32(wl, HW_PART3_START_ADDR, p->mem3.start); + +out: + return ret; +} +EXPORT_SYMBOL_GPL(wlcore_set_partition); + +void wl1271_io_reset(struct wl1271 *wl) +{ + if (wl->if_ops->reset) + wl->if_ops->reset(wl->dev); +} + +void wl1271_io_init(struct wl1271 *wl) +{ + if (wl->if_ops->init) + wl->if_ops->init(wl->dev); +} diff --git a/pool/shard002/C/0060735_gawkmisc.c b/pool/shard002/C/0060735_gawkmisc.c new file mode 100644 index 0000000000000000000000000000000000000000..08551da587e1e4b66c474dcd34495d74dc07b202 --- /dev/null +++ b/pool/shard002/C/0060735_gawkmisc.c @@ -0,0 +1,248 @@ +/* gawkmisc.c --- miscellaneous gawk routines that are OS specific. + + Copyright (C) 1986, 1988, 1989, 1991 - 1998, 2001 - 2004 the Free Software Foundation, Inc. + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 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. */ + +char quote = '\''; +char *defpath = DEFPATH; +char envsep = ':'; + +#ifndef INVALID_HANDLE +/* FIXME: is this value for INVALID_HANDLE correct? */ +#define INVALID_HANDLE -1 +#endif + +/* gawk_name --- pull out the "gawk" part from how the OS called us */ + +char * +gawk_name(filespec) +const char *filespec; +{ + char *p; + + /* "path/name" -> "name" */ + p = strrchr(filespec, '/'); + return (p == NULL ? (char *) filespec : p + 1); +} + +/* os_arg_fixup --- fixup the command line */ + +void +os_arg_fixup(argcp, argvp) +int *argcp; +char ***argvp; +{ + /* no-op */ + return; +} + +/* os_devopen --- open special per-OS devices */ + +int +os_devopen(name, flag) +const char *name; +int flag; +{ + /* no-op */ + return INVALID_HANDLE; +} + +/* optimal_bufsize --- determine optimal buffer size */ + +/* + * Enhance this for debugging purposes, as follows: + * + * Always stat the file, stat buffer is used by higher-level code. + * + * if (AWKBUFSIZE == "exact") + * return the file size + * else if (AWKBUFSIZE == a number) + * always return that number + * else + * if the size is < default_blocksize + * return the size + * else + * return default_blocksize + * end if + * endif + * + * Hair comes in an effort to only deal with AWKBUFSIZE + * once, the first time this routine is called, instead of + * every time. Performance, dontyaknow. + */ + +size_t +optimal_bufsize(fd, stb) +int fd; +struct stat *stb; +{ + char *val; + static size_t env_val = 0; + static short first = TRUE; + static short exact = FALSE; + + /* force all members to zero in case OS doesn't use all of them. */ + memset(stb, '\0', sizeof(struct stat)); + + /* always stat, in case stb is used by higher level code. */ + if (fstat(fd, stb) == -1) + fatal("can't stat fd %d (%s)", fd, strerror(errno)); + + if (first) { + first = FALSE; + + if ((val = getenv("AWKBUFSIZE")) != NULL) { + if (strcmp(val, "exact") == 0) + exact = TRUE; + else if (isdigit(*val)) { + for (; *val && isdigit(*val); val++) + env_val = (env_val * 10) + *val - '0'; + + return env_val; + } + } + } else if (! exact && env_val > 0) + return env_val; + /* else + fall through */ + + /* + * System V.n, n < 4, doesn't have the file system block size in the + * stat structure. So we have to make some sort of reasonable + * guess. We use stdio's BUFSIZ, since that is what it was + * meant for in the first place. + */ +#ifdef HAVE_ST_BLKSIZE +#define DEFBLKSIZE (stb->st_blksize > 0 ? stb->st_blksize : BUFSIZ) +#else +#define DEFBLKSIZE BUFSIZ +#endif + + if (S_ISREG(stb->st_mode) /* regular file */ + && 0 < stb->st_size /* non-zero size */ + && (stb->st_size < DEFBLKSIZE /* small file */ + || exact)) /* or debugging */ + return stb->st_size; /* use file size */ + + return DEFBLKSIZE; +} + +/* ispath --- return true if path has directory components */ + +int +ispath(file) +const char *file; +{ + return (strchr(file, '/') != NULL); +} + +/* isdirpunct --- return true if char is a directory separator */ + +int +isdirpunct(c) +int c; +{ + return (c == '/'); +} + +/* os_close_on_exec --- set close on exec flag, print warning if fails */ + +void +os_close_on_exec(fd, name, what, dir) +int fd; +const char *name, *what, *dir; +{ + if (fd <= 2) /* sanity */ + return; + + if (fcntl(fd, F_SETFD, 1) < 0) + warning(_("%s %s `%s': could not set close-on-exec: (fcntl: %s)"), + what, dir, name, strerror(errno)); +} + +/* os_isdir --- is this an fd on a directory? */ + +#if ! defined(S_ISDIR) && defined(S_IFDIR) +#define S_ISDIR(m) (((m) & S_IFMT) == S_IFDIR) +#endif + +int +os_isdir(fd) +int fd; +{ + struct stat sbuf; + + return (fstat(fd, &sbuf) == 0 && S_ISDIR(sbuf.st_mode)); +} + +/* os_is_setuid --- true if running setuid root */ + +int +os_is_setuid() +{ + long uid, euid; + + uid = getuid(); + euid = geteuid(); + + return (euid == 0 && euid != uid); +} + +/* os_setbinmode --- set binary mode on file */ + +int +os_setbinmode(fd, mode) +int fd, mode; +{ +#ifdef __CYGWIN__ + setmode (fd, mode); +#endif + return 0; +} + +/* os_restore_mode --- restore the original mode of the console device */ + +void +os_restore_mode (fd) +int fd; +{ + /* no-op */ + return; +} + +#ifdef __CYGWIN__ +#include +#include + +extern int _fmode; +void +cygwin_premain0 (int argc, char **argv, void *myself) +{ + static struct __cygwin_perfile pf[] = + { + {"", O_RDONLY | O_TEXT}, + /*{"", O_WRONLY | O_BINARY},*/ + {NULL, 0} + }; + cygwin_internal (CW_PERFILE, pf); +} + +void +cygwin_premain2 (int argc, char **argv, void *myself) +{ + setmode (fileno (stdin), O_TEXT); +} +#endif diff --git a/pool/shard002/C/0060736_string.c b/pool/shard002/C/0060736_string.c new file mode 100644 index 0000000000000000000000000000000000000000..2eef6101dbceb77965d5224422eec0b8f76b31e4 --- /dev/null +++ b/pool/shard002/C/0060736_string.c @@ -0,0 +1,51 @@ +/* + * Copyright 2015-2018 Jerome Pasquier + * + * This file is part of rainbrurph. + * + * rainbrurph 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. + * + * rainbrurph 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 rainbrurph. If not, see . + * + */ + +#include "string.h" + +#include // For strlen and strncopy + +//#define NULL 0 +#include // For free(), malloc() + +string_t* string_create(char native[]) +{ + string_t* this= malloc(sizeof(string_t)); + this->length = strlen(native); + this->native = malloc(this->length+1); + if (this->native) + { + strncpy(this->native, native, this->length+1); + } + else + { + free(this->native); + free(this); + this=NULL; + } + return this; +} + +void string_free(string_t** str) +{ + free((*str)->native); + free((*str)); + *str=NULL; +} diff --git a/pool/shard002/C/0060749_bli_trsm_blk_var2b.c b/pool/shard002/C/0060749_bli_trsm_blk_var2b.c new file mode 100644 index 0000000000000000000000000000000000000000..634d84fd3bb72efd56ef712ce0bc59bfc045a920 --- /dev/null +++ b/pool/shard002/C/0060749_bli_trsm_blk_var2b.c @@ -0,0 +1,152 @@ +/* + + BLIS + An object-based framework for developing high-performance BLAS-like + libraries. + + Copyright (C) 2014, The University of Texas at Austin + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are + met: + - Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + - Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + - Neither the name of The University of Texas at Austin nor the names + of its contributors may be used to endorse or promote products + derived from this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +*/ + +#include "blis.h" + +void bli_trsm_blk_var2b( obj_t* a, + obj_t* b, + obj_t* c, + cntx_t* cntx, + trsm_t* cntl, + thrinfo_t* thread ) +{ + obj_t a_pack_s; + obj_t b1_pack_s, c1_pack_s; + + obj_t b1, c1; + obj_t* a_pack = NULL; + obj_t* b1_pack = NULL; + obj_t* c1_pack = NULL; + + dim_t i; + dim_t b_alg; + + // Prune any zero region that exists along the partitioning dimension. + bli_trsm_prune_unref_mparts_n( a, b, c ); + + // Initialize pack objects for A that are passed into packm_init(). + if( bli_thread_am_ochief( thread ) ) { + bli_obj_init_pack( &a_pack_s ); + + // Initialize object for packing A. + bli_packm_init( a, &a_pack_s, + cntx, bli_cntl_sub_packm_a( cntl ) ); + + // Scale C by beta (if instructed). + bli_scalm_int( &BLIS_ONE, + c, + cntx, bli_cntl_sub_scalm( cntl ) ); + } + a_pack = bli_thread_obroadcast( thread, &a_pack_s ); + + // Initialize pack objects for B and C that are passed into packm_init(). + if( bli_thread_am_ichief( thread ) ) { + bli_obj_init_pack( &b1_pack_s ); + bli_obj_init_pack( &c1_pack_s ); + } + b1_pack = bli_thread_ibroadcast( thread, &b1_pack_s ); + c1_pack = bli_thread_ibroadcast( thread, &c1_pack_s ); + + // Pack A (if instructed). + bli_packm_int( a, a_pack, + cntx, bli_cntl_sub_packm_a( cntl ), + bli_thrinfo_sub_opackm( thread ) ); + + dim_t my_start, my_end; + bli_thread_get_range_r2l( thread, b, + ( bli_obj_root_is_triangular( *b ) ? + bli_cntx_get_bmult( BLIS_MR, cntx ) : + bli_cntx_get_bmult( BLIS_NR, cntx ) ), + &my_start, &my_end ); + + // Partition along the n dimension. + for ( i = my_start; i < my_end; i += b_alg ) + { + // Determine the current algorithmic blocksize. + b_alg = bli_determine_blocksize_b( i, my_end, b, + bli_cntl_bszid( cntl ), cntx ); + + // Acquire partitions for B1 and C1. + bli_acquire_mpart_r2l( BLIS_SUBPART1, + i, b_alg, b, &b1 ); + bli_acquire_mpart_r2l( BLIS_SUBPART1, + i, b_alg, c, &c1 ); + + // Initialize objects for packing A1 and B1. + if( bli_thread_am_ichief( thread ) ) { + bli_packm_init( &b1, b1_pack, + cntx, bli_cntl_sub_packm_b( cntl ) ); + bli_packm_init( &c1, c1_pack, + cntx, bli_cntl_sub_packm_c( cntl ) ); + } + bli_thread_ibarrier( thread ); + + // Pack B1 (if instructed). + bli_packm_int( &b1, b1_pack, + cntx, bli_cntl_sub_packm_b( cntl ), + bli_thrinfo_sub_ipackm( thread ) ); + + // Pack C1 (if instructed). + bli_packm_int( &c1, c1_pack, + cntx, bli_cntl_sub_packm_c( cntl ), + bli_thrinfo_sub_ipackm( thread ) ); + + // Perform trsm subproblem. + bli_trsm_int( &BLIS_ONE, + a_pack, + b1_pack, + &BLIS_ONE, + c1_pack, + cntx, + bli_cntl_sub_trsm( cntl ), + bli_thrinfo_sub_self( thread ) ); + bli_thread_ibarrier( thread ); + + // Unpack C1 (if C1 was packed). + bli_unpackm_int( c1_pack, &c1, + cntx, bli_cntl_sub_unpackm_c( cntl ), + bli_thrinfo_sub_ipackm( thread ) ); + } + + // If any packing buffers were acquired within packm, release them back + // to the memory manager. + bli_thread_obarrier( thread ); + if( bli_thread_am_ochief( thread ) ) + bli_packm_release( a_pack, bli_cntl_sub_packm_a( cntl ) ); + if( bli_thread_am_ichief( thread ) ) { + bli_packm_release( b1_pack, bli_cntl_sub_packm_b( cntl ) ); + bli_packm_release( c1_pack, bli_cntl_sub_packm_c( cntl ) ); + } +} + diff --git a/pool/shard002/C/0060759_loginlog.c b/pool/shard002/C/0060759_loginlog.c new file mode 100644 index 0000000000000000000000000000000000000000..cb97da83bc1fff5ce8d0d22b6e8bbe44e57c0c90 --- /dev/null +++ b/pool/shard002/C/0060759_loginlog.c @@ -0,0 +1,217 @@ +/*-------------------------------------------------------------------------| +| _________ | +| \_ ___ \_______ ____ ____ __ __ ______ | +| / \ \/\_ __ \/ \ / \| | \/ ___/ | +| \ \____| | \( ( ) ) | \ | /\___ \ | +| \______ /|__| \____/|___| /____//____ > | +| \/ \/ \/ | +|--------------------------------------------------------------------------| +| Copyright (C) <2014> | +| | +| Copyright Portions to eAthena, jAthena and Hercules 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 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 . | +| | +|----- Descrição: ---------------------------------------------------------| +| | +|--------------------------------------------------------------------------| +| | +|----- ToDo: --------------------------------------------------------------| +| | +|-------------------------------------------------------------------------*/ + +#include "loginlog.h" + +#include +#include // exit + +#include "../common/cbasetypes.h" +#include "../common/mmo.h" +#include "../common/socket.h" +#include "../common/sql.h" +#include "../common/strlib.h" + +// global sql settings (in ipban_sql.c) +static char global_db_hostname[32] = "127.0.0.1"; +static uint16 global_db_port = 3306; +static char global_db_username[32] = "ragnarok"; +static char global_db_password[32] = "ragnarok"; +static char global_db_database[32] = "ragnarok"; +static char global_codepage[32] = ""; +// local sql settings +static char log_db_hostname[32] = ""; +static uint16 log_db_port = 0; +static char log_db_username[32] = ""; +static char log_db_password[32] = ""; +static char log_db_database[32] = ""; +static char log_codepage[32] = ""; +static char log_login_db[256] = "loginlog"; + +static Sql* sql_handle = NULL; +static bool enabled = false; + + +// Returns the number of failed login attempts by the ip in the last minutes. +unsigned long loginlog_failedattempts(uint32 ip, unsigned int minutes) +{ + unsigned long failures = 0; + + if( !enabled ) + return 0; + + if( SQL_ERROR == SQL->Query(sql_handle, "SELECT count(*) FROM `%s` WHERE `ip` = '%s' AND `rcode` = '1' AND `time` > NOW() - INTERVAL %d MINUTE", + log_login_db, ip2str(ip,NULL), minutes) )// how many times failed account? in one ip. + Sql_ShowDebug(sql_handle); + + if( SQL_SUCCESS == SQL->NextRow(sql_handle) ) + { + char* data; + SQL->GetData(sql_handle, 0, &data, NULL); + failures = strtoul(data, NULL, 10); + SQL->FreeResult(sql_handle); + } + return failures; +} + + +/*============================================= + * Records an event in the login log + *---------------------------------------------*/ +void login_log(uint32 ip, const char* username, int rcode, const char* message) +{ + char esc_username[NAME_LENGTH*2+1]; + char esc_message[255*2+1]; + int retcode; + + if( !enabled ) + return; + + SQL->EscapeStringLen(sql_handle, esc_username, username, strnlen(username, NAME_LENGTH)); + SQL->EscapeStringLen(sql_handle, esc_message, message, strnlen(message, 255)); + + retcode = SQL->Query(sql_handle, + "INSERT INTO `%s`(`time`,`ip`,`user`,`rcode`,`log`) VALUES (NOW(), '%s', '%s', '%d', '%s')", + log_login_db, ip2str(ip,NULL), esc_username, rcode, esc_message); + + if( retcode != SQL_SUCCESS ) + Sql_ShowDebug(sql_handle); +} + +bool loginlog_init(void) +{ + const char* username; + const char* password; + const char* hostname; + uint16 port; + const char* database; + const char* codepage; + + if( log_db_hostname[0] != '\0' ) + {// local settings + username = log_db_username; + password = log_db_password; + hostname = log_db_hostname; + port = log_db_port; + database = log_db_database; + codepage = log_codepage; + } + else + {// global settings + username = global_db_username; + password = global_db_password; + hostname = global_db_hostname; + port = global_db_port; + database = global_db_database; + codepage = global_codepage; + } + + sql_handle = SQL->Malloc(); + + if( SQL_ERROR == SQL->Connect(sql_handle, username, password, hostname, port, database) ) + { + Sql_ShowDebug(sql_handle); + SQL->Free(sql_handle); + exit(EXIT_FAILURE); + } + + if( codepage[0] != '\0' && SQL_ERROR == SQL->SetEncoding(sql_handle, codepage) ) + Sql_ShowDebug(sql_handle); + + enabled = true; + + return true; +} + +bool loginlog_final(void) +{ + SQL->Free(sql_handle); + sql_handle = NULL; + return true; +} + +bool loginlog_config_read(const char* key, const char* value) +{ + const char* signature; + + signature = "sql."; + if( strncmpi(key, signature, strlen(signature)) == 0 ) + { + key += strlen(signature); + if( strcasecmp(key, "db_hostname") == 0 ) + safestrncpy(global_db_hostname, value, sizeof(global_db_hostname)); + else + if( strcasecmp(key, "db_port") == 0 ) + global_db_port = (uint16)strtoul(value, NULL, 10); + else + if( strcasecmp(key, "db_username") == 0 ) + safestrncpy(global_db_username, value, sizeof(global_db_username)); + else + if( strcasecmp(key, "db_password") == 0 ) + safestrncpy(global_db_password, value, sizeof(global_db_password)); + else + if( strcasecmp(key, "db_database") == 0 ) + safestrncpy(global_db_database, value, sizeof(global_db_database)); + else + if( strcasecmp(key, "codepage") == 0 ) + safestrncpy(global_codepage, value, sizeof(global_codepage)); + else + return false;// not found + return true; + } + + if( strcasecmp(key, "log_db_ip") == 0 ) + safestrncpy(log_db_hostname, value, sizeof(log_db_hostname)); + else + if( strcasecmp(key, "log_db_port") == 0 ) + log_db_port = (uint16)strtoul(value, NULL, 10); + else + if( strcasecmp(key, "log_db_id") == 0 ) + safestrncpy(log_db_username, value, sizeof(log_db_username)); + else + if( strcasecmp(key, "log_db_pw") == 0 ) + safestrncpy(log_db_password, value, sizeof(log_db_password)); + else + if( strcasecmp(key, "log_db_db") == 0 ) + safestrncpy(log_db_database, value, sizeof(log_db_database)); + else + if( strcasecmp(key, "log_codepage") == 0 ) + safestrncpy(log_codepage, value, sizeof(log_codepage)); + else + if( strcasecmp(key, "log_login_db") == 0 ) + safestrncpy(log_login_db, value, sizeof(log_login_db)); + else + return false; + + return true; +} diff --git a/pool/shard002/C/0060771_tool_player.c b/pool/shard002/C/0060771_tool_player.c new file mode 100644 index 0000000000000000000000000000000000000000..56dc172cc97edb447693f601034d3921e969b342 --- /dev/null +++ b/pool/shard002/C/0060771_tool_player.c @@ -0,0 +1,205 @@ +/* + * Copyright 2004-2006 Freescale Semiconductor, Inc. All rights reserved. + */ + +/* + * The code contained herein is licensed under the GNU General Public + * License. You may obtain a copy of the GNU General Public License + * Version 2 or later at the following locations: + * + * http://www.opensource.org/licenses/gpl-license.html + * http://www.gnu.org/copyleft/gpl.html + */ + +#include +#include +#include +#include +#include +#include +#include "dbmx31-ctrls.h" + +#define BUF_SIZE 4096 + +unsigned short get_audio_bits(FILE * file) +{ + unsigned short ret; + fseek(file, 34, SEEK_SET); + fread(&ret, 2, 1, file); + return ret; +} + +unsigned short get_audio_channels(FILE * file) +{ + unsigned short ret; + fseek(file, 22, SEEK_SET); + fread(&ret, 2, 1, file); + return ret; +} + +int get_audio_frq(FILE * file) +{ + int ret; + fseek(file, 24, SEEK_SET); + fread(&ret, 4, 1, file); + return ret; +} + +int set_audio_config(int fd_audio, FILE * file) +{ + int tmp, format, frequency, channels; + + tmp = format = (int)get_audio_bits(file); + ioctl(fd_audio, SNDCTL_DSP_SETFMT, &format); + if (tmp != format) + return -1; + + tmp = frequency = get_audio_frq(file); + ioctl(fd_audio, SOUND_PCM_WRITE_RATE, &frequency); + if (tmp != frequency) + return -1; + + tmp = channels = get_audio_channels(file); + ioctl(fd_audio, SNDCTL_DSP_CHANNELS, &channels); + if (tmp != channels) + return -1; + + printf("Configuration : %d %d %d\n", format, frequency, channels); + return 0; +} + +int play_file(int fd_audio, FILE * file) +{ + int err = 0; + int n, nleft, nwritten; + char buf[BUF_SIZE], *p; + + // On passe l'entete WAV + fseek(file, 44, SEEK_SET); + + // Lecture de l'échantillon + while ((n = fread(buf, 1, sizeof(buf), file)) > 0) { + nleft = n; + p = buf; + + // On envoie l'échantillon... + while (nleft) { + if ((nwritten = write(fd_audio, p, nleft)) < 0) { + perror("/dev/sound/dsp0 write error"); + err++; + } else + printf("%d/%d written.\n", nwritten, nleft); + + nleft -= nwritten; + p += nwritten; + } + } + + /* Flush output */ + write(fd_audio, NULL, 0); + + return err; +} + +#define ARG_DEV 1 +#define ARG_SSI 2 +#define ARG_FILE 3 +#define ARG_LOOPS 4 + +int main(int ac, char *av[]) +{ + FILE *fd_file; + int fd_audio, fd_audio2; + int i, loop, ssi_index; + int err = 0; + char rep[32]; + int flag; +/* unsigned int reg, val; + dbmx_cfg cfg;*/ + + printf("Hi... \n"); + + if (ac == 1) { + printf + ("main [nb_loops]\n Plays the file to /dev/dspX (uncompressed data)\n"); + printf("device : 0 for stdac; 1 for codec ... \n"); + printf("ssi_nb : 1 for SSI1 ... \n"); + return 0; + } + + /* Open driver in WR mode for stdac, R/W for codec */ + flag = (atoi(av[ARG_DEV]) == 0 ? O_WRONLY : O_RDWR); + + ssi_index = atoi(av[ARG_SSI]); + if ((fd_audio = open("/dev/sound/dsp", flag)) < 0) { + printf("Error opening dsp"); + err++; + goto _err_drv_open1; + } + + if (ssi_index == 2) { + fd_audio2 = fd_audio; + if ((fd_audio = open("/dev/sound/dsp1", O_WRONLY)) < 0) { + printf("Error opening dsp1"); + err++; + goto _err_drv_open2; + } + } + + if (ac == 5) + loop = atoi(av[ARG_LOOPS]); + else + loop = 1; + + if ((fd_file = fopen(av[ARG_FILE], "r")) <= 0) { + err++; + goto _err_file_not_found; + } + +/* printf("Want to configure the HW (y/n) ?\n"); scanf("%s", rep); + while ( rep[0] != 'n' ) + { + printf("R/W reg val (n 0 0 to exit)\n"); + scanf("%s %x %x", rep, ®, &val); + cfg.reg = reg; cfg.val = val; + if ( rep[0] == 'R' ) printf("Read returned = %x\n", ioctl(fd_audio, SNDCTL_DBMX_HW_SSI_CFG_R, &cfg)); + if ( rep[0] == 'W' ) printf("Write returned = %x\n", ioctl(fd_audio, SNDCTL_DBMX_HW_SSI_CFG_W, &cfg)); + }*/ + + if (set_audio_config(fd_audio, fd_file) < 0) { + printf("Bad format for file 1. "); + printf("Do you want to continue ? (y/n) : "); + scanf("%s", rep); + err++; + if (rep[0] != 'y') + goto _err_fmt; + } + // read the file many times if desired + for (i = 0; i < loop; i++) { + err += play_file(fd_audio, fd_file); + } + + /* Flush output */ + write(fd_audio, NULL, 0); + + printf("************** Closing the device\n"); + fclose(fd_file); + close(fd_audio); + close(fd_audio2); + + if (err) + goto _end_err; + printf("All tests passed with success\n"); + return 0; + + _err_fmt: + fclose(fd_file); + _err_file_not_found: + close(fd_audio2); + _err_drv_open2: + close(fd_audio); + _err_drv_open1: + _end_err: + printf("Encountered %d errors\n", err); + return err; +} diff --git a/pool/shard002/C/0060773_gpio.c b/pool/shard002/C/0060773_gpio.c new file mode 100644 index 0000000000000000000000000000000000000000..6627e42dd0d63e070f6f16b8279167b587144773 --- /dev/null +++ b/pool/shard002/C/0060773_gpio.c @@ -0,0 +1,168 @@ +/* + * This file is part of the Soletta Project + * + * Copyright (C) 2015 Intel Corporation. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "sol-flow/gpio.h" +#include "sol-flow-internal.h" + +#include "sol-flow.h" +#include "sol-gpio.h" +#include "sol-util-internal.h" + +#include +#include + +struct gpio_data { + struct sol_gpio *gpio; +}; + +static void +gpio_close(struct sol_flow_node *node, void *data) +{ + struct gpio_data *mdata = data; + + sol_gpio_close(mdata->gpio); +} + +/* GPIO READER ********************************************************************/ +static void +gpio_reader_event(void *data, struct sol_gpio *gpio, bool value) +{ + struct sol_flow_node *node = data; + + sol_flow_send_boolean_packet(node, + SOL_FLOW_NODE_TYPE_GPIO_READER__OUT__OUT, value); +} + +static int +gpio_reader_open(struct sol_flow_node *node, void *data, const struct sol_flow_node_options *options) +{ + uint32_t pin; + struct gpio_data *mdata = data; + const struct sol_flow_node_type_gpio_reader_options *opts = + (const struct sol_flow_node_type_gpio_reader_options *)options; + struct sol_gpio_config gpio_conf = { 0 }; + static const enum sol_gpio_edge mode_lut[] = { + [0 + 2 * 0] = SOL_GPIO_EDGE_NONE, + [1 + 2 * 0] = SOL_GPIO_EDGE_RISING, + [0 + 2 * 1] = SOL_GPIO_EDGE_FALLING, + [1 + 2 * 1] = SOL_GPIO_EDGE_BOTH + }; + + SOL_FLOW_NODE_OPTIONS_SUB_API_CHECK(options, SOL_FLOW_NODE_TYPE_GPIO_READER_OPTIONS_API_VERSION, -EINVAL); + + SOL_SET_API_VERSION(gpio_conf.api_version = SOL_GPIO_CONFIG_API_VERSION; ) + gpio_conf.dir = SOL_GPIO_DIR_IN; + gpio_conf.active_low = opts->active_low; + gpio_conf.in.trigger_mode = mode_lut[opts->edge_rising + 2 * opts->edge_falling]; + gpio_conf.in.cb = gpio_reader_event; + gpio_conf.in.user_data = node; + gpio_conf.in.poll_timeout = opts->poll_timeout; + + if (gpio_conf.in.trigger_mode == SOL_GPIO_EDGE_NONE) { + SOL_WRN("gpio reader #%s: either edge_rising or edge_falling need to be" + " set for the node to generate events.", opts->pin); + return -EINVAL; + } + + if (streq(opts->pull, "up")) + gpio_conf.drive_mode = SOL_GPIO_DRIVE_PULL_UP; + else if (streq(opts->pull, "down")) + gpio_conf.drive_mode = SOL_GPIO_DRIVE_PULL_DOWN; + + mdata->gpio = NULL; + if (!opts->pin || *opts->pin == '\0') { + SOL_WRN("gpio: Option 'pin' cannot be neither 'null' nor empty."); + return -EINVAL; + } + + if (opts->raw) { + if (!sscanf(opts->pin, "%" SCNu32, &pin)) { + SOL_WRN("gpio (%s): 'raw' option was set, but 'pin' value=%s couldn't be parsed as " + "integer.", opts->pin, opts->pin); + } else { + mdata->gpio = sol_gpio_open(pin, &gpio_conf); + } + } else { + mdata->gpio = sol_gpio_open_by_label(opts->pin, &gpio_conf); + } + + if (!mdata->gpio) { + SOL_WRN("Could not open gpio #%s", opts->pin); + return -EIO; + } + + return 0; +} + +/* GPIO WRITER *******************************************************************/ + +static int +gpio_writer_process(struct sol_flow_node *node, void *data, uint16_t port, uint16_t conn_id, const struct sol_flow_packet *packet) +{ + bool value; + struct gpio_data *mdata = data; + int r = sol_flow_packet_get_boolean(packet, &value); + + SOL_INT_CHECK(r, < 0, r); + if (!sol_gpio_write(mdata->gpio, value)) { + return -EIO; + } + return 0; +} + +static int +gpio_writer_open(struct sol_flow_node *node, void *data, const struct sol_flow_node_options *options) +{ + uint32_t pin; + struct gpio_data *mdata = data; + const struct sol_flow_node_type_gpio_writer_options *opts = + (const struct sol_flow_node_type_gpio_writer_options *)options; + struct sol_gpio_config gpio_conf = { 0 }; + + SOL_FLOW_NODE_OPTIONS_SUB_API_CHECK(options, SOL_FLOW_NODE_TYPE_GPIO_WRITER_OPTIONS_API_VERSION, -EINVAL); + + SOL_SET_API_VERSION(gpio_conf.api_version = SOL_GPIO_CONFIG_API_VERSION; ) + gpio_conf.dir = SOL_GPIO_DIR_OUT; + gpio_conf.active_low = opts->active_low; + + mdata->gpio = NULL; + if (!opts->pin || *opts->pin == '\0') { + SOL_WRN("gpio: Option 'pin' cannot be neither 'null' nor empty."); + return -EINVAL; + } + + if (opts->raw) { + if (!sscanf(opts->pin, "%" SCNu32, &pin)) { + SOL_WRN("gpio (%s): 'raw' option was set, but 'pin' value=%s couldn't be parsed as " + "integer.", opts->pin, opts->pin); + } else { + mdata->gpio = sol_gpio_open(pin, &gpio_conf); + } + } else { + mdata->gpio = sol_gpio_open_by_label(opts->pin, &gpio_conf); + } + + if (!mdata->gpio) { + SOL_WRN("Could not open gpio #%s", opts->pin); + return -EIO; + } + + return 0; +} + +#include "gpio-gen.c" diff --git a/pool/shard002/C/0060778_sc_sntp.c b/pool/shard002/C/0060778_sc_sntp.c new file mode 100644 index 0000000000000000000000000000000000000000..1cd3886cc6a3b51f2fe5f59a918b0358124bd219 --- /dev/null +++ b/pool/shard002/C/0060778_sc_sntp.c @@ -0,0 +1,102 @@ +/* + * Copyright (C) 2016 Luminița Lăzărescu + * 2017 Freie Universität Berlin + * + * This file is subject to the terms and conditions of the GNU Lesser + * General Public License v2.1. See the file LICENSE in the top level + * directory for more details. + */ + +/** + * @ingroup sys_shell_commands + * @{ + * + * @file + * @brief Prints the real time offset from the system time + * + * @author Luminița Lăzărescu + * @author Martine Lenders + */ + +#include +#include + +#include "net/sntp.h" +#include "net/ntp_packet.h" +#include "net/af.h" +#include "net/ipv6/addr.h" +#include "timex.h" + +#define _DEFAULT_TIMEOUT (500000LU) + +static void _usage(char *cmd) +{ + printf("Usage: %s [%%] []\n", cmd); + printf("default: timeout = %lu\n", _DEFAULT_TIMEOUT); +} + +int _ntpdate(int argc, char **argv) +{ + uint32_t timeout = _DEFAULT_TIMEOUT; + + if (argc < 2) { + _usage(argv[0]); + return 1; + } + sock_udp_ep_t server = { .port = NTP_PORT, .family = AF_INET6 }; + ipv6_addr_t *addr = (ipv6_addr_t *)&server.addr; + + char *iface = ipv6_addr_split_iface(argv[1]); + kernel_pid_t src_iface = iface ? atoi(iface) : KERNEL_PID_UNDEF; + + if (ipv6_addr_from_str(addr, argv[1]) == NULL) { + puts("error: malformed address"); + return 1; + } + + if (ipv6_addr_is_link_local(addr) || (src_iface != KERNEL_PID_UNDEF)) { + size_t ifnum = gnrc_netif_numof(); + + if (src_iface == KERNEL_PID_UNDEF) { + if (ifnum == 1) { + src_iface = gnrc_netif_iter(NULL)->pid; + } + else { + puts("error: link local target needs interface parameter (use \"
%\")\n"); + return 1; + } + } + else { + if (gnrc_netif_get_by_pid(src_iface) == NULL) { + printf("error: %"PRIkernel_pid" is not a valid interface.\n", src_iface); + return 1; + } + } + server.netif = src_iface; + } + + if (argc > 2) { + timeout = atoi(argv[2]); + } + if (sntp_sync(&server, timeout) < 0) { + puts("Error in synchronization"); + return 1; + } +#if defined(MODULE_NEWLIB) || defined(MODULE_PICOLIBC) + struct tm *tm; + time_t time = (time_t)(sntp_get_unix_usec() / US_PER_SEC); + + tm = gmtime(&time); + printf("%04i-%02i-%02i %02i:%02i:%02i UTC (%i us)\n", + tm->tm_year + 1900, tm->tm_mon + 1, tm->tm_mday, + tm->tm_hour, tm->tm_min, tm->tm_sec, + (int)sntp_get_offset()); +#else + uint64_t time = sntp_get_unix_usec(); + printf("%" PRIu32 ".%" PRIu32 " (%i us)\n", + (uint32_t)(time / US_PER_SEC), + (uint32_t)(time / US_PER_SEC), + (int)sntp_get_offset()); +#endif + return 0; +} diff --git a/pool/shard002/C/0060789_gtkmacintegration-module.c b/pool/shard002/C/0060789_gtkmacintegration-module.c new file mode 100644 index 0000000000000000000000000000000000000000..de7d2f1d4dab0e748d846c8cdd08d67de7284828 --- /dev/null +++ b/pool/shard002/C/0060789_gtkmacintegration-module.c @@ -0,0 +1,24 @@ +#include + +void gtkmacintegration_register_classes (PyObject *d); + +extern PyMethodDef gtkmacintegration_functions[]; + +DL_EXPORT(void) +init_gtkmacintegration (void) +{ + PyObject *m, *d; + + init_pygobject (); + + m = Py_InitModule ("gtkmacintegration._gtkmacintegration", + gtkmacintegration_functions); + d = PyModule_GetDict (m); + + gtkmacintegration_register_classes (d); + + if (PyErr_Occurred ()) { + PyErr_Print(); + Py_FatalError ("can't initialize module gtkmacintegration:"); + } +} diff --git a/pool/shard002/C/0060793_sh_pci.c b/pool/shard002/C/0060793_sh_pci.c new file mode 100644 index 0000000000000000000000000000000000000000..fdec71b9e861bc0f277f25fcf7f60bfd96dbe327 --- /dev/null +++ b/pool/shard002/C/0060793_sh_pci.c @@ -0,0 +1,186 @@ +/* + * SuperH on-chip PCIC emulation. + * + * Copyright (c) 2008 Takashi YOSHII + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL + * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +#include "sysbus.h" +#include "sh.h" +#include "pci.h" +#include "pci_host.h" +#include "bswap.h" +#include "exec-memory.h" + +typedef struct SHPCIState { + SysBusDevice busdev; + PCIBus *bus; + PCIDevice *dev; + qemu_irq irq[4]; + MemoryRegion memconfig_p4; + MemoryRegion memconfig_a7; + MemoryRegion isa; + uint32_t par; + uint32_t mbr; + uint32_t iobr; +} SHPCIState; + +static void sh_pci_reg_write (void *p, hwaddr addr, uint64_t val, + unsigned size) +{ + SHPCIState *pcic = p; + switch(addr) { + case 0 ... 0xfc: + cpu_to_le32w((uint32_t*)(pcic->dev->config + addr), val); + break; + case 0x1c0: + pcic->par = val; + break; + case 0x1c4: + pcic->mbr = val & 0xff000001; + break; + case 0x1c8: + if ((val & 0xfffc0000) != (pcic->iobr & 0xfffc0000)) { + memory_region_del_subregion(get_system_memory(), &pcic->isa); + pcic->iobr = val & 0xfffc0001; + memory_region_add_subregion(get_system_memory(), + pcic->iobr & 0xfffc0000, &pcic->isa); + } + break; + case 0x220: + pci_data_write(pcic->bus, pcic->par, val, 4); + break; + } +} + +static uint64_t sh_pci_reg_read (void *p, hwaddr addr, + unsigned size) +{ + SHPCIState *pcic = p; + switch(addr) { + case 0 ... 0xfc: + return le32_to_cpup((uint32_t*)(pcic->dev->config + addr)); + case 0x1c0: + return pcic->par; + case 0x1c4: + return pcic->mbr; + case 0x1c8: + return pcic->iobr; + case 0x220: + return pci_data_read(pcic->bus, pcic->par, 4); + } + return 0; +} + +static const MemoryRegionOps sh_pci_reg_ops = { + .read = sh_pci_reg_read, + .write = sh_pci_reg_write, + .endianness = DEVICE_NATIVE_ENDIAN, + .valid = { + .min_access_size = 4, + .max_access_size = 4, + }, +}; + +static int sh_pci_map_irq(PCIDevice *d, int irq_num) +{ + return (d->devfn >> 3); +} + +static void sh_pci_set_irq(void *opaque, int irq_num, int level) +{ + qemu_irq *pic = opaque; + + qemu_set_irq(pic[irq_num], level); +} + +static int sh_pci_device_init(SysBusDevice *dev) +{ + SHPCIState *s; + int i; + + s = FROM_SYSBUS(SHPCIState, dev); + for (i = 0; i < 4; i++) { + sysbus_init_irq(dev, &s->irq[i]); + } + s->bus = pci_register_bus(&s->busdev.qdev, "pci", + sh_pci_set_irq, sh_pci_map_irq, + s->irq, + get_system_memory(), + get_system_io(), + PCI_DEVFN(0, 0), 4); + memory_region_init_io(&s->memconfig_p4, &sh_pci_reg_ops, s, + "sh_pci", 0x224); + memory_region_init_alias(&s->memconfig_a7, "sh_pci.2", &s->memconfig_p4, + 0, 0x224); + isa_mmio_setup(&s->isa, 0x40000); + sysbus_init_mmio(dev, &s->memconfig_p4); + sysbus_init_mmio(dev, &s->memconfig_a7); + s->iobr = 0xfe240000; + memory_region_add_subregion(get_system_memory(), s->iobr, &s->isa); + + s->dev = pci_create_simple(s->bus, PCI_DEVFN(0, 0), "sh_pci_host"); + return 0; +} + +static int sh_pci_host_init(PCIDevice *d) +{ + pci_set_word(d->config + PCI_COMMAND, PCI_COMMAND_WAIT); + pci_set_word(d->config + PCI_STATUS, PCI_STATUS_CAP_LIST | + PCI_STATUS_FAST_BACK | PCI_STATUS_DEVSEL_MEDIUM); + return 0; +} + +static void sh_pci_host_class_init(ObjectClass *klass, void *data) +{ + PCIDeviceClass *k = PCI_DEVICE_CLASS(klass); + + k->init = sh_pci_host_init; + k->vendor_id = PCI_VENDOR_ID_HITACHI; + k->device_id = PCI_DEVICE_ID_HITACHI_SH7751R; +} + +static TypeInfo sh_pci_host_info = { + .name = "sh_pci_host", + .parent = TYPE_PCI_DEVICE, + .instance_size = sizeof(PCIDevice), + .class_init = sh_pci_host_class_init, +}; + +static void sh_pci_device_class_init(ObjectClass *klass, void *data) +{ + SysBusDeviceClass *sdc = SYS_BUS_DEVICE_CLASS(klass); + + sdc->init = sh_pci_device_init; +} + +static TypeInfo sh_pci_device_info = { + .name = "sh_pci", + .parent = TYPE_SYS_BUS_DEVICE, + .instance_size = sizeof(SHPCIState), + .class_init = sh_pci_device_class_init, +}; + +static void sh_pci_register_types(void) +{ + type_register_static(&sh_pci_device_info); + type_register_static(&sh_pci_host_info); +} + +type_init(sh_pci_register_types) diff --git a/pool/shard002/C/0060799_hitechnic-superpro-exp2.c b/pool/shard002/C/0060799_hitechnic-superpro-exp2.c new file mode 100644 index 0000000000000000000000000000000000000000..c1c446c830ae0e27c40195583702db99c7daa5b3 --- /dev/null +++ b/pool/shard002/C/0060799_hitechnic-superpro-exp2.c @@ -0,0 +1,37 @@ +#pragma config(Sensor, S1, HTSPB, sensorI2CCustom9V) +//*!!Code automatically generated by 'ROBOTC' configuration wizard !!*// + +/* HiTechnic Experimenter's Kit for the SuperPro + +Experiment - 2 Six LEDs and a Potentiometer + +This program reads the analog value of a potentiometer and outputs a +digital value to one of six LEDs. + +*/ + +#include "drivers/hitechnic-superpro.h" + +task main() { + int inputdata; + ubyte outputdata; + int bit; + + // Set all digital IOs as outputs as output + HTSPBsetupIO(HTSPB, 0xFF); + + while(true) { + // Read a 10bit wide analogue value from A0 + inputdata = HTSPBreadADC(HTSPB, 0, 10); + + nxtDisplayTextLine(1, "A0: %d", inputdata); + + // Set the output bit based on the analogue input value + bit = (inputdata/128); + if (bit > 5) bit = 5; + nxtDisplayTextLine(2, "Bit: %d", bit); + outputdata = 1 << bit; + HTSPBwriteIO(HTSPB, outputdata); + wait1Msec(50); + } +} diff --git a/pool/shard002/C/0060804_user_main.c b/pool/shard002/C/0060804_user_main.c new file mode 100644 index 0000000000000000000000000000000000000000..14bc61599bf2d776bc6a4219d93db5f4c328cb80 --- /dev/null +++ b/pool/shard002/C/0060804_user_main.c @@ -0,0 +1,257 @@ +/* main.c -- MQTT client example +* +* Copyright (c) 2014-2015, Tuan PM +* 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 Redis nor the names of its contributors may be used +* to endorse or promote products derived from this software without +* specific prior written permission. +* +* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE +* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +* POSSIBILITY OF SUCH DAMAGE. +*/ +#include "ets_sys.h" +#include "json/json.h" +#include "json/jsonparse.h" +#include "driver/uart.h" +#include "osapi.h" +#include "mqtt.h" +#include "wifi.h" +#include "config.h" +#include "debug.h" +#include "gpio.h" +#include "string.h" +#include "user_interface.h" + +static volatile os_timer_t send_timer; +#define MAXTIMINGS 10000 +#define BREAKTIME 20 +#define MAC2STR(a) (a)[0], (a)[1], (a)[2], (a)[3], (a)[4], (a)[5] +#define MACSTR "%02x:%02x:%02x:%02x:%02x:%02x" + +static volatile float lastHum, lastTemp; +static volatile os_timer_t some_timer; +static char hwaddr[6]; + +MQTT_Client mqttClient; + +void wifiConnectCb(uint8_t status) +{ + if(status == STATION_GOT_IP){ + char *channel = DOMOTICKS_CHANNEL; + MQTT_Connect(&mqttClient); + MQTT_Subscribe(&mqttClient, channel); + } +} +void mqttConnectedCb(uint32_t *args) +{ + MQTT_Client* client = (MQTT_Client*)args; + INFO("MQTT: Connected\r\n"); + +} + +void mqttDisconnectedCb(uint32_t *args) +{ + MQTT_Client* client = (MQTT_Client*)args; + INFO("MQTT: Disconnected\r\n"); +} + +void mqttPublishedCb(uint32_t *args) +{ + MQTT_Client* client = (MQTT_Client*)args; + client-> + INFO("MQTT: Published\r\n"); +} + +void mqttDataCb(uint32_t *args, const char* topic, uint32_t topic_len, const char *data, uint32_t data_len) +{ + char topicBuf[64], dataBuf[64]; + struct jsonparse_state json_struct; + memset(&json_struct, NULL, sizeof(struct jsonparse_state)); + + MQTT_Client* client = (MQTT_Client*)args; + + os_memcpy(topicBuf, topic, topic_len); + topicBuf[topic_len] = 0; + + os_memcpy(dataBuf, data, data_len); + dataBuf[data_len] = 0; + + if(os_strstr(topicBuf, DOMOTICKS_UUID) != NULL){ + // This message is for me! + INFO("MQTT topic: %s, data: %s \r\n", topicBuf, dataBuf); + jsonparse_setup(&json_struct, dataBuf, data_len); + while(jsonparse_next(&json_struct)){ + + } + } + + + /* Echo back to /echo channel*/ + MQTT_Publish(client, "/echo", dataBuf, data_len, 0, 0); +} + +void sendData(void *arg){ + char msg[64]; + os_sprintf(msg, "Humidity: %d & Temperature : %d\0", lastHum, lastTemp); + + MQTT_Publish(&mqttClient, DOMOTICKS_CHANNEL, msg, os_strlen(msg), 0, 0); +} + +void ICACHE_FLASH_ATTR readDHT(void *arg) +{ + + int counter = 0; + int laststate = 1; + int i = 0; + int j = 0; + int checksum = 0; + //int bitidx = 0; + //int bits[250]; + + int data[100]; + os_printf("\r\nDTH11 reading ...\r\n"); + data[0] = data[1] = data[2] = data[3] = data[4] = 0; + + GPIO_OUTPUT_SET(2, 1); + os_delay_us(250000); + GPIO_OUTPUT_SET(2, 0); + os_delay_us(20000); + //os_intr_lock(); + GPIO_OUTPUT_SET(2, 1); + os_delay_us(40); + GPIO_DIS_OUTPUT(2); + PIN_PULLUP_EN(PERIPHS_IO_MUX_GPIO2_U); + + + // wait for pin to drop? + while (GPIO_INPUT_GET(2) == 1 && i<100000) { + os_delay_us(1); + i++; + } + + if(i==100000){ + return; + } + + // read data! + + for (i = 0; i < MAXTIMINGS; i++) { + counter = 0; + while ( GPIO_INPUT_GET(2) == laststate) { + counter++; + os_delay_us(1); + if (counter == 255) + break; + } + laststate = GPIO_INPUT_GET(2); + if (counter == 255) break; + + //bits[bitidx++] = counter; + + if ((i > 3) && (i%2 == 0)) { + // shove each bit into the storage bytes + data[j/8] <<= 1; + if (counter > BREAKTIME) + data[j/8] |= 1; + j++; + } + } + + //os_intr_unlock(); + + /*for (i=3; i BREAKTIME); + }*/ + + float temp_p, hum_p; + if (j >= 39) { + checksum = (data[0] + data[1] + data[2] + data[3]) & 0xFF; + if (data[4] == checksum) { + /* yay! checksum is valid */ + lastHum = (float)data[0]; + lastTemp = (float)data[2]; + /* DHT22 Stuff... */ + /*hum_p = data[0] * 256 + data[1]; + hum_p /= 10; + + temp_p = (data[2] & 0x7F)* 256 + data[3]; + temp_p /= 10.0; + if (data[2] & 0x80) + temp_p *= -1;*/ + + // End DHT22 Stuff + //sendReading(temp_p, hum_p); + /* lastHum = hum_p; + lastTemp = temp_p;*/ + + char msg[64]; + MQTT_Publish(&mqttClient, DOMOTICKS_CHANNEL, msg, os_strlen(msg), 0, 0); + /*os_printf("Hum : %d, Temp : %d", data[0], data[2]); + os_printf("Hum : %d, Temp : %d", lastHum, lastTemp);*/ + } + } +} + + + +void user_init(void) +{ + lastHum = 0; + lastTemp=0; + uart_init(BIT_RATE_115200, BIT_RATE_115200); + os_delay_us(1000000); + + //Set GPIO2 to output mode + PIN_FUNC_SELECT(PERIPHS_IO_MUX_GPIO2_U, FUNC_GPIO2); + PIN_PULLUP_EN(PERIPHS_IO_MUX_GPIO2_U); + + CFG_Load(); + + MQTT_InitConnection(&mqttClient, sysCfg.mqtt_host, sysCfg.mqtt_port, SEC_NONSSL); + MQTT_InitClient(&mqttClient, sysCfg.device_id, sysCfg.mqtt_user, sysCfg.mqtt_pass, sysCfg.mqtt_keepalive); + MQTT_OnConnected(&mqttClient, mqttConnectedCb); + MQTT_OnDisconnected(&mqttClient, mqttDisconnectedCb); + MQTT_OnPublished(&mqttClient, mqttPublishedCb); + //MQTT_OnData(&mqttClient, mqttDataCb); + + WIFI_Connect(sysCfg.sta_ssid, sysCfg.sta_pwd, wifiConnectCb); + + INFO("\r\nSystem started ...\r\n"); + + //Set GPIO2 to output mode + /*PIN_FUNC_SELECT(PERIPHS_IO_MUX_GPIO2_U, FUNC_GPIO2); + PIN_PULLUP_EN(PERIPHS_IO_MUX_GPIO2_U); + */ + + os_timer_disarm(&some_timer); + //Setup timer + os_timer_setfn(&some_timer, (os_timer_func_t *)readDHT, NULL); + //os_timer_disarm(&send_timer); + //os_timer_setfn(&send_timer, (os_timer_func_t *)sendData, NULL); + //Arm the timer + //&some_timer is the pointer + //1000 is the fire time in ms + //0 for once and 1 for repeating + + os_timer_arm(&some_timer, 10000, 1); + //os_timer_arm(&send_timer, 15000, 1); +} diff --git a/pool/shard002/C/0060807_nautest.c b/pool/shard002/C/0060807_nautest.c new file mode 100644 index 0000000000000000000000000000000000000000..701b545beeadf820294ba7b60dbb8d6bd3a4828b --- /dev/null +++ b/pool/shard002/C/0060807_nautest.c @@ -0,0 +1,119 @@ +/* Test for basic nauty functions (but not nauty itself) */ + +#include "nauty.h" + +int +main(int argc, char *argv[]) +{ + int i,j,bad; + setword w; + + printf("NAUTYVERSION=%s NAUTYVERSIONID=%d\n", + NAUTYVERSION,NAUTYVERSIONID); + printf("MAXN=%d MAXM=%d WORDSIZE=%d NAUTY_INFINITY=%d\n", + MAXN,MAXM,WORDSIZE,NAUTY_INFINITY); + printf("sizes: short=%d int=%d long=%d double=%d\n", + (int)sizeof(short),(int)sizeof(int),(int)sizeof(long), + (int)sizeof(double)); + printf("sizes: boolean=%d setword=%d shortish=%d\n", + (int)sizeof(boolean),(int)sizeof(setword), + (int)sizeof(shortish)); +#ifdef SETWORD_LONGLONG + printf("sizeof(long long)=%d\n",sizeof(long long)); +#endif + + printf("defined:"); +#ifdef __STDC__ + printf(" __STDC__"); +#endif +#ifdef BIGNAUTY + printf(" BIGNAUTY"); +#endif +#ifdef SYS_UNIX + printf(" SYS_UNIX"); +#endif +#ifdef SYS_CRAY + printf(" SYS_CRAY"); +#endif +#ifdef SETWORD_SHORT + printf(" SETWORD_SHORT"); +#endif +#ifdef SETWORD_INT + printf(" SETWORD_INT"); +#endif +#ifdef SETWORD_LONG + printf(" SETWORD_LONG"); +#endif +#ifdef SETWORD_LONGLONG + printf(" SETWORD_LONGLONG"); +#endif + printf("\n"); + + bad = 0; + + if (8*sizeof(setword) != WORDSIZE) + { + printf("\n ***** NOTE: WORDSIZE mismatch *****\n\n"); + ++bad; + } + + for (i = 0; i < WORDSIZE; ++i) + { + w = ALLMASK(i); + if (POPCOUNT(w) != i) + { + printf("\n ***** POPCOUNT(ALLMASK) error %d *****\n\n",i); + ++bad; + } + } + + for (i = 0; i < WORDSIZE; ++i) + { + w = BITMASK(i); + if (POPCOUNT(w) != WORDSIZE-i-1) + { + printf("\n ***** POPCOUNT(BITMASK) error %d *****\n\n",i); + ++bad; + } + } + + for (i = 0; i < WORDSIZE; ++i) + if (POPCOUNT(ALLMASK(i)) != i) + { + printf("\n ***** POPCOUNT(ALLMASK) error %d *****\n\n",i); + ++bad; + } + + for (i = 0; i < WORDSIZE; ++i) + if (FIRSTBIT(BITT[i]) != i) + { + printf("\n ***** FIRSTBIT(BITT) error %d *****\n\n",i); + ++bad; + } + + for (i = 0; i < WORDSIZE; ++i) + if (POPCOUNT(BITT[i]) != 1) + { + printf("\n ***** POPCOUNT(BITT) error %d *****\n\n",i); + ++bad; + } + + for (i = 0; i < WORDSIZE; ++i) + { + w = 0; + for (j = 1; j <= WORDSIZE; ++j) + { + w |= BITT[(j*97+i)%WORDSIZE]; + if (POPCOUNT(w) != j) + { + printf("\n ***** POPCOUNT(w) error %d %d *****\n\n",i,j); + ++bad; + } + } + } + + if (!bad) printf("\nNo errors found\n"); + else printf("\nXXXXXXX %d errors found XXXXXXX\n",bad); + + exit(0); +} diff --git a/pool/shard002/C/0060811_keypad-zeus.c b/pool/shard002/C/0060811_keypad-zeus.c new file mode 100644 index 0000000000000000000000000000000000000000..68504574c0cd86ccba5e3af7a35e4a4bd4896fd1 --- /dev/null +++ b/pool/shard002/C/0060811_keypad-zeus.c @@ -0,0 +1,155 @@ +#include +#include +#include +#include +#include "keypad-zeus.h" + +static struct gpio_event_input_info keypad_gpio_info = { + .info.func = gpio_event_input_func, + .flags = 0, + .type = EV_KEY, + .keymap = keypad_zeus_gpio_map, + .keymap_size = ARRAY_SIZE(keypad_zeus_gpio_map), + .debounce_time.tv.nsec = 10 * NSEC_PER_MSEC, +}; + +static struct gpio_event_input_info switch_gpio_info = { + .info.func = gpio_event_input_func, + .info.no_suspend = 1, + .flags = 0, + .type = EV_SW, + .keymap = switch_zeus_gpio_map, + .keymap_size = ARRAY_SIZE(switch_zeus_gpio_map), +}; + +static struct gpio_event_input_info lidswitch_gpio_info = { + .info.func = gpio_event_input_func, + .info.no_suspend = 1, + .flags = GPIOEDF_ACTIVE_HIGH, + .type = EV_MSC, + .keymap = lidswitch_zeus_gpio_map, + .keymap_size = ARRAY_SIZE(lidswitch_zeus_gpio_map), +}; +#if defined(CONFIG_PHF_TESTER) + +static struct gpio_event_input_info phf_gpio_info = { + .info.func = gpio_event_input_func, + .flags = 0, + .type = EV_KEY, + .keymap = phf_gpio_map, + .keymap_size = ARRAY_SIZE(phf_gpio_map), +}; + +#endif + +static struct gpio_event_info *keypad_info[] = { + &keypad_gpio_info.info, + &switch_gpio_info.info, + &lidswitch_gpio_info.info, +#if defined(CONFIG_PHF_TESTER) + &phf_gpio_info.info, +#endif + +}; + +static int keypad_power(const struct gpio_event_platform_data *pdata, bool on) +{ + int i; + int gpio; + int mgp; + int rc; + + if (!on) { + for (i = 0; i < ARRAY_SIZE(keypad_zeus_gpio_map); ++i) { + gpio = keypad_zeus_gpio_map[i].gpio; + + mgp = GPIO_CFG(gpio, + 0, + GPIO_CFG_INPUT, + GPIO_CFG_PULL_DOWN, + GPIO_CFG_2MA); + rc = gpio_tlmm_config(mgp, GPIO_CFG_DISABLE); + if (rc) + pr_err("%s: gpio_tlmm_config (gpio=%d), failed\n", + __func__, keypad_zeus_gpio_map[i].gpio); + } + } else { + for (i = 0; i < ARRAY_SIZE(keypad_zeus_gpio_map); ++i) { + gpio = keypad_zeus_gpio_map[i].gpio; + mgp = GPIO_CFG(gpio, + 0, + GPIO_CFG_INPUT, + GPIO_CFG_PULL_UP, + GPIO_CFG_2MA); + rc = gpio_tlmm_config(mgp, GPIO_CFG_ENABLE); + if (rc) + pr_err("%s: gpio_tlmm_config (gpio=%d), failed\n", + __func__, keypad_zeus_gpio_map[i].gpio); + } + } + + return 0; +} + +static struct gpio_event_platform_data keypad_data = { + .name = "keypad-zeus", + .info = keypad_info, + .info_count = ARRAY_SIZE(keypad_info), + .power = keypad_power, +}; + +struct platform_device keypad_device_zeus = { + .name = GPIO_EVENT_DEV_NAME, + .id = -1, + .dev = { + .platform_data = &keypad_data, + }, +}; + +static int __init keypad_device_init(void) +{ + int i; + int rc; + int gpio; + int mgp; + + keypad_power(&keypad_data,1); + + for (i = 0; i < ARRAY_SIZE(switch_zeus_gpio_map); ++i) { + gpio = switch_zeus_gpio_map[i].gpio; + mgp = GPIO_CFG(gpio, + 0, + GPIO_CFG_INPUT, + GPIO_CFG_NO_PULL, + GPIO_CFG_2MA); + rc = gpio_tlmm_config(mgp, GPIO_CFG_ENABLE); + if (rc) + pr_err("%s: gpio_tlmm_config (gpio=%d), failed\n", + __func__, switch_zeus_gpio_map[i].gpio); + } + +#ifdef CONFIG_PHF_TESTER + for (i = 0; i < ARRAY_SIZE(phf_gpio_map); ++i) { + gpio = phf_gpio_map[i].gpio; + mgp = GPIO_CFG(gpio, + 0, + GPIO_CFG_INPUT, + GPIO_CFG_PULL_UP, + GPIO_CFG_2MA); + rc = gpio_tlmm_config(mgp, GPIO_CFG_ENABLE); + if (rc) + pr_err("%s: gpio_tlmm_config (gpio=%d), failed\n", + __func__, phf_gpio_map[i].gpio); + } +#endif + + return platform_device_register(&keypad_device_zeus); +} + +static void __exit keypad_device_exit(void) +{ + platform_device_unregister(&keypad_device_zeus); +} + +module_init(keypad_device_init); +module_exit(keypad_device_exit); diff --git a/pool/shard002/C/0060835_channel-mixer.c b/pool/shard002/C/0060835_channel-mixer.c new file mode 100644 index 0000000000000000000000000000000000000000..272680fd9bfa3a3e07c3d6194d94e7d8f69acdb1 --- /dev/null +++ b/pool/shard002/C/0060835_channel-mixer.c @@ -0,0 +1,273 @@ +/* This file is an image processing operation for GEGL + * + * GEGL 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. + * + * GEGL 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 GEGL; if not, see . + * + * This operation is a port of the GIMP channel-mixer plugin: + * + * Copyright (C) 2002 Martin Guldahl + * + * The porting to GEGL was done by Barak Itkin + * + * Copyright (C) 2013 Barak Itkin + */ + +#include "config.h" +#include +#include + +#ifdef GEGL_PROPERTIES + +property_boolean (preserve_luminosity, _("Preserve luminosity"), FALSE) + +/* Red channel */ +property_double (rr_gain, _("Red in Red channel"), 1.0) + description(_("Set the red amount for the red channel")) + value_range (-2.0, 2.0) + +property_double (rg_gain, _("Green in Red channel"), 0.0) + description(_("Set the green amount for the red channel")) + value_range (-2.0, 2.0) + +property_double (rb_gain, _("Blue in Red channel"), 0.0) + description(_("Set the blue amount for the red channel")) + value_range (-2.0, 2.0) + +/* Green channel */ +property_double (gr_gain, _("Red in Green channel"), 0.0) + description(_("Set the red amount for the green channel")) + value_range (-2.0, 2.0) + +property_double (gg_gain, _("Green for Green channel"), 1.0) + description(_("Set the green amount for the green channel")) + value_range (-2.0, 2.0) + +property_double (gb_gain, _("Blue in Green channel"), 0.0) + description(_("Set the blue amount for the green channel")) + value_range (-2.0, 2.0) + +/* Blue channel */ +property_double (br_gain, _("Red in Blue channel"), 0.0) + description(_("Set the red amount for the blue channel")) + value_range (-2.0, 2.0) + +property_double (bg_gain, _("Green in Blue channel"), 0.0) + description(_("Set the green amount for the blue channel")) + value_range (-2.0, 2.0) + +property_double (bb_gain, _("Blue in Blue channel"), 1.0) + description(_("Set the blue amount for the blue channel")) + value_range (-2.0, 2.0) + + +#else + +#define GEGL_OP_POINT_FILTER +#define GEGL_OP_C_SOURCE channel-mixer.c + +#include "gegl-op.h" + +typedef enum +{ + CM_RED_CHANNEL, + CM_GREEN_CHANNEL, + CM_BLUE_CHANNEL +} CmModeType; + +typedef struct +{ + gdouble red_gain; + gdouble green_gain; + gdouble blue_gain; +} CmChannelType; + +typedef struct +{ + CmChannelType red; + CmChannelType green; + CmChannelType blue; + + gboolean preserve_luminosity; + gboolean has_alpha; +} CmParamsType; + +static void prepare (GeglOperation *operation) +{ + const Babl *input_format = gegl_operation_get_source_format (operation, "input"); + GeglProperties *o = GEGL_PROPERTIES (operation); + CmParamsType *mix; + const Babl *format; + + if (o->user_data == NULL) + o->user_data = g_slice_new0 (CmParamsType); + + mix = (CmParamsType*) o->user_data; + + mix->preserve_luminosity = o->preserve_luminosity; + + mix->red.red_gain = o->rr_gain; + mix->red.green_gain = o->rg_gain; + mix->red.blue_gain = o->rb_gain; + + mix->green.red_gain = o->gr_gain; + mix->green.green_gain = o->gg_gain; + mix->green.blue_gain = o->gb_gain; + + mix->blue.red_gain = o->br_gain; + mix->blue.green_gain = o->bg_gain; + mix->blue.blue_gain = o->bb_gain; + + if (input_format == NULL || babl_format_has_alpha (input_format)) + { + mix->has_alpha = TRUE; + format = babl_format ("R'G'B'A float"); + } + else + { + mix->has_alpha = FALSE; + format = babl_format ("R'G'B' float"); + } + + gegl_operation_set_format (operation, "input", format); + gegl_operation_set_format (operation, "output", format); +} + +static void finalize (GObject *object) +{ + GeglOperation *op = (void*) object; + GeglProperties *o = GEGL_PROPERTIES (op); + + if (o->user_data) + { + g_slice_free (CmParamsType, o->user_data); + o->user_data = NULL; + } + + G_OBJECT_CLASS (gegl_op_parent_class)->finalize (object); +} + +static gdouble +cm_calculate_norm (CmParamsType *mix, + CmChannelType *ch) +{ + gdouble sum = ch->red_gain + ch->green_gain + ch->blue_gain; + + if (sum == 0.0 || ! mix->preserve_luminosity) + return 1.0; + + return fabs (1 / sum); +} + +static inline gfloat +cm_mix_pixel (CmChannelType *ch, + gfloat r, + gfloat g, + gfloat b, + gdouble norm) +{ + gdouble c = ch->red_gain * r + ch->green_gain * g + ch->blue_gain * b; + + c *= norm; + + return (gfloat) MIN(1, MAX(0, c)); +} + +static inline void +cm_process_pixel (CmParamsType *mix, + const gfloat *s, + gfloat *d, + const gdouble red_norm, + const gdouble green_norm, + const gdouble blue_norm) +{ + + d[0] = cm_mix_pixel (&mix->red, s[0], s[1], s[2], red_norm); + d[1] = cm_mix_pixel (&mix->green, s[0], s[1], s[2], green_norm); + d[2] = cm_mix_pixel (&mix->blue, s[0], s[1], s[2], blue_norm); +} + +static gboolean +process (GeglOperation *op, + void *in_buf, + void *out_buf, + glong samples, + const GeglRectangle *roi, + gint level) +{ + GeglProperties *o = GEGL_PROPERTIES (op); + CmParamsType *mix = (CmParamsType*) o->user_data; + + gdouble red_norm, green_norm, blue_norm; + gfloat *in, *out; + + g_assert (mix != NULL); + + red_norm = cm_calculate_norm (mix, &mix->red); + green_norm = cm_calculate_norm (mix, &mix->green); + blue_norm = cm_calculate_norm (mix, &mix->blue); + + in = in_buf; + out = out_buf; + + if (mix->has_alpha) + { + while (samples--) + { + cm_process_pixel (mix, in, out, + red_norm, green_norm, blue_norm); + out[3] = in[3]; + + in += 4; + out += 4; + } + } + else + { + while (samples--) + { + cm_process_pixel (mix, in, out, + red_norm, green_norm, blue_norm); + in += 3; + out += 3; + } + } + + return TRUE; +} + +static void +gegl_op_class_init (GeglOpClass *klass) +{ + GeglOperationClass *operation_class; + GeglOperationPointFilterClass *point_filter_class; + + operation_class = GEGL_OPERATION_CLASS (klass); + point_filter_class = GEGL_OPERATION_POINT_FILTER_CLASS (klass); + + point_filter_class->process = process; + operation_class->prepare = prepare; + G_OBJECT_CLASS (klass)->finalize = finalize; + + operation_class->opencl_support = TRUE; + + gegl_operation_class_set_keys (operation_class, + "name", "gegl:channel-mixer", + "categories", "color", + "title", _("Channel Mixer"), + "license", "GPL3+", + "description", _("Remix colors; by defining relative contributions from source components."), + NULL); +} + +#endif + diff --git a/pool/shard002/C/0060837_testmav.c b/pool/shard002/C/0060837_testmav.c new file mode 100644 index 0000000000000000000000000000000000000000..63311025065c7664c1326148910f6eb16b0094fd --- /dev/null +++ b/pool/shard002/C/0060837_testmav.c @@ -0,0 +1,239 @@ +/* + simple MAVLink testsuite for C + */ +#include +#include +#include +#include +#include +#include + +#define MAVLINK_USE_CONVENIENCE_FUNCTIONS +#define MAVLINK_USE_MESSAGE_INFO +#define MAVLINK_COMM_NUM_BUFFERS 2 + +// this trick allows us to make mavlink_message_t as small as possible +// for this dialect, which saves some memory +#include +#define MAVLINK_MAX_PAYLOAD_LEN MAVLINK_MAX_DIALECT_PAYLOAD_SIZE + +#include +static mavlink_system_t mavlink_system = {42,11,}; + +#define MAVLINK_ASSERT(x) assert(x) +static void comm_send_ch(mavlink_channel_t chan, uint8_t c); + +static mavlink_message_t last_msg; + +#include +#include + +static unsigned chan_counts[MAVLINK_COMM_NUM_BUFFERS]; + +#ifndef MAVLINK_HAVE_EXPECTED_MESSAGE_LENGTH +static const uint8_t message_lengths[] = MAVLINK_MESSAGE_LENGTHS; +#define mavlink_expected_message_length(msg) message_lengths[(msg)->msgid] +#endif + +#ifndef MAVLINK_HAVE_GET_MESSAGE_INFO +static const mavlink_message_info_t message_info[] = MAVLINK_MESSAGE_INFO; +#define mavlink_get_message_info(msg) &message_info[(msg)->msgid] +#endif + +static unsigned error_count; + + +static void print_one_field(mavlink_message_t *msg, const mavlink_field_info_t *f, int idx) +{ +#define PRINT_FORMAT(f, def) (f->print_format?f->print_format:def) + switch (f->type) { + case MAVLINK_TYPE_CHAR: + printf(PRINT_FORMAT(f, "%c"), _MAV_RETURN_char(msg, f->wire_offset+idx*1)); + break; + case MAVLINK_TYPE_UINT8_T: + printf(PRINT_FORMAT(f, "%u"), _MAV_RETURN_uint8_t(msg, f->wire_offset+idx*1)); + break; + case MAVLINK_TYPE_INT8_T: + printf(PRINT_FORMAT(f, "%d"), _MAV_RETURN_int8_t(msg, f->wire_offset+idx*1)); + break; + case MAVLINK_TYPE_UINT16_T: + printf(PRINT_FORMAT(f, "%u"), _MAV_RETURN_uint16_t(msg, f->wire_offset+idx*2)); + break; + case MAVLINK_TYPE_INT16_T: + printf(PRINT_FORMAT(f, "%d"), _MAV_RETURN_int16_t(msg, f->wire_offset+idx*2)); + break; + case MAVLINK_TYPE_UINT32_T: + printf(PRINT_FORMAT(f, "%lu"), (unsigned long)_MAV_RETURN_uint32_t(msg, f->wire_offset+idx*4)); + break; + case MAVLINK_TYPE_INT32_T: + printf(PRINT_FORMAT(f, "%ld"), (long)_MAV_RETURN_int32_t(msg, f->wire_offset+idx*4)); + break; + case MAVLINK_TYPE_UINT64_T: + printf(PRINT_FORMAT(f, "%llu"), (unsigned long long)_MAV_RETURN_uint64_t(msg, f->wire_offset+idx*8)); + break; + case MAVLINK_TYPE_INT64_T: + printf(PRINT_FORMAT(f, "%lld"), (long long)_MAV_RETURN_int64_t(msg, f->wire_offset+idx*8)); + break; + case MAVLINK_TYPE_FLOAT: + printf(PRINT_FORMAT(f, "%f"), (double)_MAV_RETURN_float(msg, f->wire_offset+idx*4)); + break; + case MAVLINK_TYPE_DOUBLE: + printf(PRINT_FORMAT(f, "%f"), _MAV_RETURN_double(msg, f->wire_offset+idx*8)); + break; + } +} + +static void print_field(mavlink_message_t *msg, const mavlink_field_info_t *f) +{ + printf("%s: ", f->name); + if (f->array_length == 0) { + print_one_field(msg, f, 0); + printf(" "); + } else { + unsigned i; + /* print an array */ + if (f->type == MAVLINK_TYPE_CHAR) { + printf("'%.*s'", f->array_length, + f->wire_offset+(const char *)_MAV_PAYLOAD(msg)); + + } else { + printf("[ "); + for (i=0; iarray_length; i++) { + print_one_field(msg, f, i); + if (i < f->array_length) { + printf(", "); + } + } + printf("]"); + } + } + printf(" "); +} + +static void print_message(mavlink_message_t *msg) +{ + const mavlink_message_info_t *m = mavlink_get_message_info(msg); + if (m == NULL) { + printf("ERROR: no message info for %u\n", msg->msgid); + error_count++; + return; + } + const mavlink_field_info_t *f = m->fields; + unsigned i; + printf("%s { ", m->name); + for (i=0; inum_fields; i++) { + print_field(msg, &f[i]); + } + printf("}\n"); +} + +#ifdef MAVLINK_SIGNING_FLAG_SIGN_OUTGOING +static mavlink_signing_t signing_in[MAVLINK_COMM_NUM_BUFFERS]; +static mavlink_signing_streams_t signing_streams_in; +#endif + +static void comm_send_ch(mavlink_channel_t chan, uint8_t c) +{ + mavlink_status_t status; + memset(&status, 0, sizeof(status)); +#ifdef MAVLINK_SIGNING_FLAG_SIGN_OUTGOING + status.signing = &signing_in[chan]; + status.signing_streams = &signing_streams_in; +#endif + if (mavlink_parse_char(chan, c, &last_msg, &status)) { + print_message(&last_msg); + chan_counts[chan]++; + /* channel 0 gets 3 messages per message, because of + the channel defaults for _pack() and _encode() */ + if (chan == MAVLINK_COMM_0 && status.current_rx_seq != (uint8_t)(chan_counts[chan]*3)) { + printf("Channel 0 sequence mismatch error at packet %u (rx_seq=%u)\n", + chan_counts[chan], status.current_rx_seq); + error_count++; + } else if (chan > MAVLINK_COMM_0 && status.current_rx_seq != (uint8_t)chan_counts[chan]) { + printf("Channel %u sequence mismatch error at packet %u (rx_seq=%u)\n", + (unsigned)chan, chan_counts[chan], status.current_rx_seq); + error_count++; + } + // we only check the lengtth for MAVLink1. In MAVLink2 packets are zero trimmed + if (mavlink_expected_message_length(&last_msg) > last_msg.len && last_msg.magic == 254) { + printf("Incorrect message length %u for message %u - expected %u\n", + (unsigned)last_msg.len, (unsigned)last_msg.msgid, + mavlink_expected_message_length(&last_msg)); + error_count++; + } + } + if (status.packet_rx_drop_count != 0) { + printf("Parse error at packet %u\n", chan_counts[chan]); + error_count++; + } +} + +int main(void) +{ + mavlink_channel_t chan; + + mavlink_test_all(11, 10, &last_msg); + for (chan=MAVLINK_COMM_0; chan<=MAVLINK_COMM_1; chan++) { + printf("Received %u messages on channel %u OK\n", + chan_counts[chan], (unsigned)chan); + } + if (error_count != 0) { + printf("Error count %u\n", error_count); + exit(1); + } + printf("No errors detected\n"); + +#ifdef MAVLINK_SIGNING_FLAG_SIGN_OUTGOING + mavlink_status_t *status; + + printf("Testing signing\n"); + mavlink_signing_t signing; + mavlink_signing_streams_t signing_streams; + memset(&signing, 0, sizeof(signing)); + memset(&signing_streams, 0, sizeof(signing_streams)); + signing.flags = MAVLINK_SIGNING_FLAG_SIGN_OUTGOING; + signing.link_id = 0; + signing.timestamp = 1; + memset(signing.secret_key, 42, sizeof(signing.secret_key)); + + status = mavlink_get_channel_status(MAVLINK_COMM_1); + status->signing = &signing; + status->signing_streams = &signing_streams; + + mavlink_test_all(11, 10, &last_msg); + for (chan=MAVLINK_COMM_0; chan<=MAVLINK_COMM_1; chan++) { + printf("Received %u messages on channel %u OK\n", + chan_counts[chan], (unsigned)chan); + } + if (error_count != 0) { + printf("Error count %u\n", error_count); + exit(1); + } + printf("No errors detected\n"); +#endif + +#ifdef MAVLINK_STATUS_FLAG_OUT_MAVLINK1 + status = mavlink_get_channel_status(MAVLINK_COMM_0); + status->flags |= MAVLINK_STATUS_FLAG_OUT_MAVLINK1; + status->signing = NULL; + status = mavlink_get_channel_status(MAVLINK_COMM_1); + status->flags |= MAVLINK_STATUS_FLAG_OUT_MAVLINK1; + status->signing = NULL; + printf("Testing sending as MAVLink1\n"); + + mavlink_test_all(11, 10, &last_msg); + for (chan=MAVLINK_COMM_0; chan<=MAVLINK_COMM_1; chan++) { + printf("Received %u messages on channel %u OK\n", + chan_counts[chan], (unsigned)chan); + } + if (error_count != 0) { + printf("Error count %u\n", error_count); + exit(1); + } + printf("No errors detected\n"); +#endif + + + return 0; +} + diff --git a/pool/shard002/C/0060840_sol-blob.c b/pool/shard002/C/0060840_sol-blob.c new file mode 100644 index 0000000000000000000000000000000000000000..0051b304aca3d648f8a714591a9022e3454bec2d --- /dev/null +++ b/pool/shard002/C/0060840_sol-blob.c @@ -0,0 +1,190 @@ +/* + * This file is part of the Soletta Project + * + * Copyright (C) 2015 Intel Corporation. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include + +#define SOL_LOG_DOMAIN &_sol_blob_log_domain +#include "sol-log-internal.h" +#include "sol-macros.h" +#include "sol-util-internal.h" +#include "sol-types.h" + +SOL_LOG_INTERNAL_DECLARE_STATIC(_sol_blob_log_domain, "blob"); + +#ifndef SOL_NO_API_VERSION +#define SOL_BLOB_CHECK_API_VERSION(blob, ...) \ + if ((blob)->type->api_version != SOL_BLOB_TYPE_API_VERSION) { \ + SOL_WRN("" # blob \ + "(%p)->type->api_version(%hu) != " \ + "SOL_BLOB_TYPE_API_VERSION(%hu)", \ + (blob), (blob)->type->api_version, \ + SOL_BLOB_TYPE_API_VERSION); \ + return __VA_ARGS__; \ + } +#else +#define SOL_BLOB_CHECK_API_VERSION(blob, ...) +#endif + +#define SOL_BLOB_CHECK(blob, ...) \ + do { \ + if (!(blob)) { \ + SOL_WRN("" # blob " == NULL"); \ + return __VA_ARGS__; \ + } \ + if (!(blob)->type) { \ + SOL_WRN("" # blob "(%p)->type == NULL", \ + (blob)); \ + return __VA_ARGS__; \ + } \ + SOL_BLOB_CHECK_API_VERSION((blob), __VA_ARGS__) \ + if ((blob)->refcnt == 0) { \ + SOL_WRN("" # blob "(%p)->refcnt == 0", \ + (blob)); \ + return __VA_ARGS__; \ + } \ + } while (0) + +int sol_blob_init(void); +void sol_blob_shutdown(void); + +int +sol_blob_init(void) +{ + sol_log_domain_init_level(SOL_LOG_DOMAIN); + return 0; +} + +void +sol_blob_shutdown(void) +{ +} + +SOL_API struct sol_blob * +sol_blob_new(const struct sol_blob_type *type, struct sol_blob *parent, const void *mem, size_t size) +{ + struct sol_blob *blob; + + SOL_NULL_CHECK(type, NULL); +#ifndef SOL_NO_API_VERSION + SOL_INT_CHECK(type->api_version, != SOL_BLOB_TYPE_API_VERSION, NULL); +#endif + + blob = calloc(1, sizeof(struct sol_blob)); + SOL_NULL_CHECK(blob, NULL); + if (sol_blob_setup(blob, type, mem, size) < 0) { + free(blob); + return NULL; + } + + if (parent) + sol_blob_set_parent(blob, parent); + + return blob; +} + +SOL_API int +sol_blob_setup(struct sol_blob *blob, const struct sol_blob_type *type, const void *mem, size_t size) +{ + SOL_NULL_CHECK(blob, -EINVAL); + SOL_NULL_CHECK(type, -EINVAL); +#ifndef SOL_NO_API_VERSION + SOL_INT_CHECK(type->api_version, != SOL_BLOB_TYPE_API_VERSION, -EINVAL); +#endif + + blob->type = type; + blob->mem = (void *)mem; + blob->size = size; + blob->refcnt = 1; + return 0; +} + +SOL_API struct sol_blob * +sol_blob_ref(struct sol_blob *blob) +{ + SOL_BLOB_CHECK(blob, NULL); + errno = ENOMEM; + SOL_INT_CHECK(blob->refcnt, == UINT16_MAX, NULL); + errno = 0; + blob->refcnt++; + return blob; +} + +SOL_API void +sol_blob_unref(struct sol_blob *blob) +{ + SOL_BLOB_CHECK(blob); + blob->refcnt--; + if (blob->refcnt > 0) + return; + + if (blob->parent) + sol_blob_unref(blob->parent); + + if (blob->type->free) + blob->type->free(blob); + else + free(blob); +} + +SOL_API void +sol_blob_set_parent(struct sol_blob *blob, struct sol_blob *parent) +{ + SOL_BLOB_CHECK(blob); + + if (parent) { + SOL_BLOB_CHECK(parent); + sol_blob_ref(parent); + } + + if (blob->parent) + sol_blob_unref(blob->parent); + + blob->parent = parent; +} + + +static void +blob_free(struct sol_blob *blob) +{ + free(blob->mem); + free(blob); +} + +static void +blob_no_free(struct sol_blob *blob) +{ +} + +SOL_API const struct sol_blob_type SOL_BLOB_TYPE_DEFAULT = { + SOL_SET_API_VERSION(.api_version = SOL_BLOB_TYPE_API_VERSION, ) + SOL_SET_API_VERSION(.sub_api = 0, ) + .free = blob_free, +}; + +SOL_API const struct sol_blob_type SOL_BLOB_TYPE_NO_FREE_DATA = { + SOL_SET_API_VERSION(.api_version = SOL_BLOB_TYPE_API_VERSION, ) + SOL_SET_API_VERSION(.sub_api = 0, ) + .free = NULL, +}; + +SOL_API const struct sol_blob_type SOL_BLOB_TYPE_NO_FREE = { + SOL_SET_API_VERSION(.api_version = SOL_BLOB_TYPE_API_VERSION, ) + SOL_SET_API_VERSION(.sub_api = 0, ) + .free = blob_no_free, +}; diff --git a/pool/shard002/C/0060852_sysdep.c b/pool/shard002/C/0060852_sysdep.c new file mode 100644 index 0000000000000000000000000000000000000000..802520d78a88751ded13c9acefa4d5a15adf3580 --- /dev/null +++ b/pool/shard002/C/0060852_sysdep.c @@ -0,0 +1,101 @@ +/******************************************************************* +** s y s d e p . c +** Forth Inspired Command Language +** Author: John Sadler (john_sadler@alum.mit.edu) +** Created: 16 Oct 1997 +** Implementations of FICL external interface functions... +** +*******************************************************************/ + +/* $FreeBSD: soc2013/dpl/head/sys/boot/ficl/sparc64/sysdep.c 97005 2002-05-19 23:20:56Z jake $ */ + +#ifdef TESTMAIN +#include +#include +#else +#include +#endif +#include "ficl.h" + +/* +******************* FreeBSD P O R T B E G I N S H E R E ******************** Michael Smith +*/ + +#if PORTABLE_LONGMULDIV == 0 +DPUNS ficlLongMul(FICL_UNS x, FICL_UNS y) +{ + DPUNS q; + u_int64_t qx; + + qx = (u_int64_t)x * (u_int64_t) y; + + q.hi = (u_int32_t)( qx >> 32 ); + q.lo = (u_int32_t)( qx & 0xFFFFFFFFL); + + return q; +} + +UNSQR ficlLongDiv(DPUNS q, FICL_UNS y) +{ + UNSQR result; + u_int64_t qx, qh; + + qh = q.hi; + qx = (qh << 32) | q.lo; + + result.quot = qx / y; + result.rem = qx % y; + + return result; +} +#endif + +void ficlTextOut(FICL_VM *pVM, char *msg, int fNewline) +{ + IGNORE(pVM); + + while(*msg != 0) + putchar(*(msg++)); + if (fNewline) + putchar('\n'); + + return; +} + +void *ficlMalloc (size_t size) +{ + return malloc(size); +} + +void *ficlRealloc (void *p, size_t size) +{ + return realloc(p, size); +} + +void ficlFree (void *p) +{ + free(p); +} + + +/* +** Stub function for dictionary access control - does nothing +** by default, user can redefine to guarantee exclusive dict +** access to a single thread for updates. All dict update code +** is guaranteed to be bracketed as follows: +** ficlLockDictionary(TRUE); +** +** ficlLockDictionary(FALSE); +** +** Returns zero if successful, nonzero if unable to acquire lock +** befor timeout (optional - could also block forever) +*/ +#if FICL_MULTITHREAD +int ficlLockDictionary(short fLock) +{ + IGNORE(fLock); + return 0; +} +#endif /* FICL_MULTITHREAD */ + + diff --git a/pool/shard002/C/0060853_BLE_custom.c b/pool/shard002/C/0060853_BLE_custom.c new file mode 100644 index 0000000000000000000000000000000000000000..cc8531e671790172787ff13600f14146a2d24885 --- /dev/null +++ b/pool/shard002/C/0060853_BLE_custom.c @@ -0,0 +1,359 @@ +/***************************************************************************//** +* \file CYBLE_custom.c +* \version 3.10 +* +* \brief +* Contains the source code for the Custom Service. +* +******************************************************************************** +* \copyright +* Copyright 2014-2016, Cypress Semiconductor Corporation. All rights reserved. +* You may use this file only in accordance with the license, terms, conditions, +* disclaimers, and limitations in the end user license agreement accompanying +* the software package with which this file was provided. +*******************************************************************************/ + + +#include "BLE_eventHandler.h" + +#ifdef CYBLE_CUSTOM_SERVER + +/* If any custom service with custom characterisctis is defined in the +* customizer's GUI their handles will be present in this array. +*/ +/* This array contains attribute handles for the defined Custom Services and their characteristics and descriptors. + The array index definitions are located in the CYBLE_custom.h file. */ +const CYBLE_CUSTOMS_T cyBle_customs[0x01u] = { + + /* UART_SERVICE service */ + { + 0x000Eu, /* Handle of the UART_SERVICE service */ + { + + /* UART_CHAR characteristic */ + { + 0x0010u, /* Handle of the UART_CHAR characteristic */ + + /* Array of Descriptors handles */ + { + 0x0011u, /* Handle of the Characteristic User Description descriptor */ + 0x0012u, /* Handle of the Client Characteristic Configuration descriptor */ + }, + }, + }, + }, +}; + + +#endif /* (CYBLE_CUSTOM_SERVER) */ + +#ifdef CYBLE_CUSTOM_CLIENT + + +static uint16 cyBle_customDisServIndex; +static uint16 cyBle_customDisCharIndex; + +#endif /* (CYBLE_CUSTOM_CLIENT) */ + + +/****************************************************************************** +* Function Name: CyBle_CustomInit +***************************************************************************//** +* +* This function initializes Custom Service. +* +* \return +* None +* +******************************************************************************/ +void CyBle_CustomInit(void) +{ + +#ifdef CYBLE_CUSTOM_CLIENT + + uint16 locServIndex; + uint16 locCharIndex; + uint16 locDescIndex; + + for(locServIndex = 0u; locServIndex < CYBLE_CUSTOMC_SERVICE_COUNT; locServIndex++) + { + if(cyBle_serverInfo[CYBLE_SRVI_CUSTOMS + locServIndex].range.startHandle == CYBLE_GATT_INVALID_ATTR_HANDLE_VALUE) + { + for(locCharIndex = 0u; locCharIndex < cyBle_customCServ[locServIndex].charCount; locCharIndex++) + { + cyBle_customCServ[locServIndex].customServChar[locCharIndex]. + customServCharHandle = 0u; + + for(locDescIndex = 0u; locDescIndex < + cyBle_customCServ[locServIndex].customServChar[locCharIndex].descCount; + locDescIndex++) + { + cyBle_customCServ[locServIndex].customServChar[locCharIndex]. + customServCharDesc[locDescIndex].descHandle = 0u; + } + } + } + } + +#endif /* (CYBLE_CUSTOM_CLIENT) */ +} + + +#ifdef CYBLE_CUSTOM_CLIENT + + +/****************************************************************************** +* Function Name: CyBle_CustomcDiscoverServiceEventHandler +***************************************************************************//** +* +* This function is called on receiving a Read By Group Response event or +* Read response with 128-bit service uuid. +* +* \param *discServInfo: The pointer to a service information structure. +* +* \return +* None +* +******************************************************************************/ +void CyBle_CustomcDiscoverServiceEventHandler(const CYBLE_DISC_SRVC128_INFO_T *discServInfo) +{ + uint16 j; + uint8 flag = 0u; + + /* Services with 128 bit UUID have discServInfo->uuid equal to 0 and address to + 128 uuid is stored in cyBle_customCServ.uuid128 + */ + for(j = 0u; (j < CYBLE_CUSTOMC_SERVICE_COUNT) && (flag == 0u); j++) + { + if(cyBle_customCServ[j].uuidFormat == CYBLE_GATT_128_BIT_UUID_FORMAT) + { + if(memcmp(cyBle_customCServ[j].uuid, &discServInfo->uuid.uuid128, CYBLE_GATT_128_BIT_UUID_SIZE) == 0u) + { + if(cyBle_serverInfo[j + (uint16)CYBLE_SRVI_CUSTOMS].range.startHandle == + CYBLE_GATT_INVALID_ATTR_HANDLE_VALUE) + { + cyBle_serverInfo[j + (uint16)CYBLE_SRVI_CUSTOMS].range = discServInfo->range; + cyBle_disCount++; + flag = 1u; + } + } + } + } +} + + +/****************************************************************************** +* Function Name: CyBle_CustomcDiscoverCharacteristicsEventHandler +***************************************************************************//** +* +* This function is called on receiving a CYBLE_EVT_GATTC_READ_BY_TYPE_RSP +* event. Based on the service index, an appropriate data structure is populated +* using the data received as part of the callback. +* +* \param *discCharInfo: The pointer to a characteristic information structure. +* \param discoveryService: The index of the service instance. +* +* \return +* None +* +******************************************************************************/ +void CyBle_CustomcDiscoverCharacteristicsEventHandler(uint16 discoveryService, const CYBLE_DISC_CHAR_INFO_T *discCharInfo) +{ + uint16 locCharIndex; + static CYBLE_GATT_DB_ATTR_HANDLE_T *customsLastEndHandle = NULL; + static uint16 discoveryLastServ = 0u; + uint8 locReqHandle = 0u; + + /* Update last characteristic endHandle to declaration handle of this characteristic */ + if(customsLastEndHandle != NULL) + { + if(discoveryLastServ == discoveryService) + { + *customsLastEndHandle = discCharInfo->charDeclHandle - 1u; + } + customsLastEndHandle = NULL; + } + + for(locCharIndex = 0u; (locCharIndex < cyBle_customCServ[discoveryService].charCount) && (locReqHandle == 0u); + locCharIndex++) + { + uint8 flag = 0u; + + /* Support 128 bit uuid */ + if((discCharInfo->uuidFormat == CYBLE_GATT_128_BIT_UUID_FORMAT) && + (cyBle_customCServ[discoveryService].customServChar[locCharIndex].uuidFormat == + CYBLE_GATT_128_BIT_UUID_FORMAT)) + { + if(memcmp(cyBle_customCServ[discoveryService].customServChar[locCharIndex].uuid, + &discCharInfo->uuid.uuid128, CYBLE_GATT_128_BIT_UUID_SIZE) == 0u) + { + flag = 1u; + } + } + + /* And support 16 bit uuid */ + if((discCharInfo->uuidFormat == CYBLE_GATT_16_BIT_UUID_FORMAT) && + (cyBle_customCServ[discoveryService].customServChar[locCharIndex].uuidFormat == + CYBLE_GATT_16_BIT_UUID_FORMAT)) + { + if(memcmp(cyBle_customCServ[discoveryService].customServChar[locCharIndex].uuid, + &discCharInfo->uuid.uuid16, CYBLE_GATT_16_BIT_UUID_SIZE) == 0u) + { + flag = 1u; + } + } + + if((flag == 1u) && + (cyBle_customCServ[discoveryService].customServChar[locCharIndex].customServCharHandle + == CYBLE_GATT_INVALID_ATTR_HANDLE_VALUE)) + { + cyBle_customCServ[discoveryService].customServChar[locCharIndex].customServCharHandle = + discCharInfo->valueHandle; + cyBle_customCServ[discoveryService].customServChar[locCharIndex].properties = + discCharInfo->properties; + /* Init pointer to characteristic endHandle */ + customsLastEndHandle = &cyBle_customCServ[discoveryService].customServChar[locCharIndex]. + customServCharEndHandle; + /* Init service index of discovered characteristic */ + discoveryLastServ = discoveryService; + locReqHandle = 1u; + } + } + + /* Init characteristic endHandle to Service endHandle. + Characteristic endHandle will be updated to the declaration + Handler of the following characteristic, + in the following characteristic discovery procedure. */ + if(customsLastEndHandle != NULL) + { + *customsLastEndHandle = cyBle_serverInfo[cyBle_disCount].range.endHandle; + } +} + + +/****************************************************************************** +* Function Name: CyBle_GetCustomCharRange +***************************************************************************//** +* +* Returns a possible range of the current characteristic descriptor +* which is pointed by custom service and char index. +* +* \param incrementIndex: Not zero value indicates that service and characteristic index +* should be incremented. +* \return +* CYBLE_GATT_ATTR_HANDLE_RANGE_T range: the block of start and end handles. +* +******************************************************************************/ +CYBLE_GATT_ATTR_HANDLE_RANGE_T CyBle_CustomcGetCharRange(uint8 incrementIndex) +{ + CYBLE_GATT_ATTR_HANDLE_RANGE_T charRange = {CYBLE_GATT_INVALID_ATTR_HANDLE_VALUE, CYBLE_GATT_INVALID_ATTR_HANDLE_VALUE}; + + do{ + if(incrementIndex != CYBLE_DISCOVERY_INIT) + { + if((cyBle_customDisCharIndex + 1u) < cyBle_customCServ[cyBle_customDisServIndex].charCount) + { + cyBle_customDisCharIndex++; + } + else + { + if((cyBle_customDisServIndex + 1u) < CYBLE_CUSTOMC_SERVICE_COUNT) + { + cyBle_customDisServIndex++; /* Discover descriptors for next custom service */ + /* Set characteristic index to first characteristic of custom service */ + cyBle_customDisCharIndex = 0u; + } + else /* Increment general discovery index when custom characteristic discovery is done. */ + { + cyBle_disCount++; + cyBle_customDisCharIndex++; + } + } + } + else /* Increment indexes in the following loop */ + { + cyBle_customDisServIndex = 0u; + cyBle_customDisCharIndex = 0u; + incrementIndex = 1u; + } + /* Read characteristic range */ + if(cyBle_customDisCharIndex < (cyBle_customCServ[cyBle_customDisServIndex].charCount)) + { + charRange.startHandle = cyBle_customCServ[cyBle_customDisServIndex]. + customServChar[cyBle_customDisCharIndex].customServCharHandle + 1u; + charRange.endHandle = cyBle_customCServ[cyBle_customDisServIndex]. + customServChar[cyBle_customDisCharIndex].customServCharEndHandle; + } + }while(((charRange.startHandle <= cyBle_gattcDiscoveryRange.startHandle) || + (charRange.startHandle > cyBle_gattcDiscoveryRange.endHandle) || + (charRange.endHandle < cyBle_gattcDiscoveryRange.startHandle) || + (charRange.startHandle > charRange.endHandle)) && + (cyBle_customDisCharIndex < cyBle_customCServ[cyBle_customDisServIndex].charCount)); + + return(charRange); +} + + +/****************************************************************************** +* Function Name: CyBle_CustomcDiscoverCharDescriptorsEventHandler +***************************************************************************//** +* +* This function is called on receiving a CYBLE_EVT_GATTC_FIND_INFO_RSP event. +* Based on the descriptor UUID, an appropriate data structure is populated using +* the data received as part of the callback. +* +* \param *discDescrInfo: The pointer to a descriptor information structure. +* +* \return +* None +* +******************************************************************************/ +void CyBle_CustomcDiscoverCharDescriptorsEventHandler(const CYBLE_DISC_DESCR_INFO_T *discDescrInfo) +{ + uint8 locDescIndex; + uint8 locReqHandle = 0u; + + for(locDescIndex = 0u; (locDescIndex < cyBle_customCServ[cyBle_customDisServIndex]. + customServChar[cyBle_customDisCharIndex].descCount) && (locReqHandle == 0u); locDescIndex++) + { + uint8 flag = 0u; + + if((discDescrInfo->uuidFormat == CYBLE_GATT_128_BIT_UUID_FORMAT) && + (cyBle_customCServ[cyBle_customDisServIndex].customServChar[cyBle_customDisCharIndex]. + customServCharDesc[locDescIndex].uuidFormat == CYBLE_GATT_128_BIT_UUID_FORMAT)) + { + if(memcmp(cyBle_customCServ[cyBle_customDisServIndex]. + customServChar[cyBle_customDisCharIndex].customServCharDesc[locDescIndex].uuid, + &discDescrInfo->uuid.uuid128, CYBLE_GATT_128_BIT_UUID_SIZE) == 0u) + { + flag = 1u; + } + } + + if((discDescrInfo->uuidFormat == CYBLE_GATT_16_BIT_UUID_FORMAT) && + (cyBle_customCServ[cyBle_customDisServIndex].customServChar[cyBle_customDisCharIndex]. + customServCharDesc[locDescIndex].uuidFormat == CYBLE_GATT_16_BIT_UUID_FORMAT)) + { + if(memcmp(cyBle_customCServ[cyBle_customDisServIndex]. + customServChar[cyBle_customDisCharIndex].customServCharDesc[locDescIndex].uuid, + &discDescrInfo->uuid.uuid16, CYBLE_GATT_16_BIT_UUID_SIZE) == 0u) + { + flag = 1u; + } + } + + if((flag == 1u) && + (cyBle_customCServ[cyBle_customDisServIndex].customServChar[cyBle_customDisCharIndex]. + customServCharDesc[locDescIndex].descHandle == CYBLE_GATT_INVALID_ATTR_HANDLE_VALUE)) + { + cyBle_customCServ[cyBle_customDisServIndex].customServChar[cyBle_customDisCharIndex]. + customServCharDesc[locDescIndex].descHandle = discDescrInfo->descrHandle; + locReqHandle = 1u; + } + } +} + +#endif /* (CYBLE_CUSTOM_CLIENT) */ + + +/* [] END OF FILE */ diff --git a/pool/shard002/C/0060861_idevicedate.c b/pool/shard002/C/0060861_idevicedate.c new file mode 100644 index 0000000000000000000000000000000000000000..a9d78c1ff1c38e37cd2878d24782789f1faa8fb1 --- /dev/null +++ b/pool/shard002/C/0060861_idevicedate.c @@ -0,0 +1,245 @@ +/* + * idevicedate.c + * Simple utility to get and set the clock on a device + * + * Copyright (c) 2011 Martin Szulecki 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 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 + */ + +#ifdef HAVE_CONFIG_H +#include +#endif + +#define TOOL_NAME "idevicedate" + +#include +#include +#include +#include +#if HAVE_LANGINFO_CODESET +#include +#endif +#ifndef WIN32 +#include +#endif + +#include +#include + +#ifdef _DATE_FMT +#define DATE_FMT_LANGINFO nl_langinfo (_DATE_FMT) +#else +#define DATE_FMT_LANGINFO "%a %b %e %H:%M:%S %Z %Y" +#endif + +static void print_usage(int argc, char **argv) +{ + char *name = NULL; + + name = strrchr(argv[0], '/'); + printf("Usage: %s [OPTIONS]\n", (name ? name + 1: argv[0])); + printf("\n"); + printf("Display the current date or set it on a device.\n"); + printf("\n"); + printf("NOTE: Setting the time on iOS 6 and later is only supported\n"); + printf(" in the setup wizard screens before device activation.\n"); + printf("\n"); + printf("OPTIONS:\n"); + printf(" -u, --udid UDID\ttarget specific device by UDID\n"); + printf(" -n, --network\t\tconnect to network device\n"); + printf(" -s, --set TIMESTAMP\tset UTC time described by TIMESTAMP\n"); + printf(" -c, --sync\t\tset time of device to current system time\n"); + printf(" -d, --debug\t\tenable communication debugging\n"); + printf(" -h, --help\t\tprints usage information\n"); + printf(" -v, --version\t\tprints version information\n"); + printf("\n"); + printf("Homepage: <" PACKAGE_URL ">\n"); + printf("Bug Reports: <" PACKAGE_BUGREPORT ">\n"); +} + +int main(int argc, char *argv[]) +{ + lockdownd_client_t client = NULL; + lockdownd_error_t ldret = LOCKDOWN_E_UNKNOWN_ERROR; + idevice_t device = NULL; + idevice_error_t ret = IDEVICE_E_UNKNOWN_ERROR; + int i; + const char* udid = NULL; + int use_network = 0; + time_t setdate = 0; + plist_t node = NULL; + int node_type = -1; + uint64_t datetime = 0; + time_t rawtime; + struct tm * tmp; + char buffer[80]; + int result = 0; + +#ifndef WIN32 + signal(SIGPIPE, SIG_IGN); +#endif + /* parse cmdline args */ + for (i = 1; i < argc; i++) { + if (!strcmp(argv[i], "-d") || !strcmp(argv[i], "--debug")) { + idevice_set_debug_level(1); + continue; + } + else if (!strcmp(argv[i], "-u") || !strcmp(argv[i], "--udid")) { + i++; + if (!argv[i] || !*argv[i]) { + print_usage(argc, argv); + return 0; + } + udid = argv[i]; + continue; + } + else if (!strcmp(argv[i], "-n") || !strcmp(argv[i], "--network")) { + use_network = 1; + continue; + } + else if (!strcmp(argv[i], "-s") || !strcmp(argv[i], "--set")) { + i++; + if (!argv[i] || (strlen(argv[i]) <= 1)) { + print_usage(argc, argv); + return 0; + } + setdate = atoi(argv[i]); + if (setdate == 0) { + printf("ERROR: Invalid timestamp value.\n"); + print_usage(argc, argv); + return 0; + } + continue; + } + else if (!strcmp(argv[i], "-c") || !strcmp(argv[i], "--sync")) { + i++; + /* get current time */ + setdate = time(NULL); + /* convert it to local time which sets timezone/daylight variables */ + tmp = localtime(&setdate); + /* recalculate to make it UTC */ + setdate = mktime(tmp); + continue; + } + else if (!strcmp(argv[i], "-h") || !strcmp(argv[i], "--help")) { + print_usage(argc, argv); + return 0; + } + else if (!strcmp(argv[i], "-v") || !strcmp(argv[i], "--version")) { + printf("%s %s\n", TOOL_NAME, PACKAGE_VERSION); + return 0; + } + else { + print_usage(argc, argv); + return 0; + } + } + + ret = idevice_new_with_options(&device, udid, (use_network) ? IDEVICE_LOOKUP_NETWORK : IDEVICE_LOOKUP_USBMUX); + if (ret != IDEVICE_E_SUCCESS) { + if (udid) { + printf("No device found with udid %s.\n", udid); + } else { + printf("No device found.\n"); + } + return -1; + } + + if (LOCKDOWN_E_SUCCESS != (ldret = lockdownd_client_new_with_handshake(device, &client, TOOL_NAME))) { + fprintf(stderr, "ERROR: Could not connect to lockdownd, error code %d\n", ldret); + result = -1; + goto cleanup; + } + + if(lockdownd_get_value(client, NULL, "TimeIntervalSince1970", &node) != LOCKDOWN_E_SUCCESS) { + fprintf(stderr, "ERROR: Unable to retrieve 'TimeIntervalSince1970' node from device.\n"); + result = -1; + goto cleanup; + } + + if (node == NULL) { + fprintf(stderr, "ERROR: Empty node for 'TimeIntervalSince1970' received.\n"); + result = -1; + goto cleanup; + } + + node_type = plist_get_node_type(node); + + /* get or set? */ + if (setdate == 0) { + /* get time value from device */ + switch (node_type) { + case PLIST_UINT: + plist_get_uint_val(node, &datetime); + break; + case PLIST_REAL: + { + double rv = 0; + plist_get_real_val(node, &rv); + datetime = rv; + } + break; + default: + fprintf(stderr, "ERROR: Unexpected node type for 'TimeIntervalSince1970'\n"); + break; + } + plist_free(node); + node = NULL; + + /* date/time calculations */ + rawtime = (time_t)datetime; + tmp = localtime(&rawtime); + + /* finally we format and print the current date */ + strftime(buffer, 80, DATE_FMT_LANGINFO, tmp); + puts(buffer); + } else { + datetime = setdate; + + plist_free(node); + node = NULL; + + switch (node_type) { + case PLIST_UINT: + node = plist_new_uint(datetime); + break; + case PLIST_REAL: + node = plist_new_real((double)datetime); + break; + default: + fprintf(stderr, "ERROR: Unexpected node type for 'TimeIntervalSince1970'\n"); + break; + } + + if(lockdownd_set_value(client, NULL, "TimeIntervalSince1970", node) == LOCKDOWN_E_SUCCESS) { + tmp = localtime(&setdate); + strftime(buffer, 80, DATE_FMT_LANGINFO, tmp); + puts(buffer); + } else { + printf("ERROR: Failed to set date on device.\n"); + } + node = NULL; + } + +cleanup: + if (client) + lockdownd_client_free(client); + + if (device) + idevice_free(device); + + return result; +} diff --git a/pool/shard002/C/0060864_meson-gx-socinfo.c b/pool/shard002/C/0060864_meson-gx-socinfo.c new file mode 100644 index 0000000000000000000000000000000000000000..1ae339f5eadbd17d716f814d65d824852c954848 --- /dev/null +++ b/pool/shard002/C/0060864_meson-gx-socinfo.c @@ -0,0 +1,189 @@ +/* + * Copyright (c) 2017 BayLibre, SAS + * Author: Neil Armstrong + * + * SPDX-License-Identifier: GPL-2.0+ + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#define AO_SEC_SD_CFG8 0xe0 +#define AO_SEC_SOCINFO_OFFSET AO_SEC_SD_CFG8 + +#define SOCINFO_MAJOR GENMASK(31, 24) +#define SOCINFO_PACK GENMASK(23, 16) +#define SOCINFO_MINOR GENMASK(15, 8) +#define SOCINFO_MISC GENMASK(7, 0) + +static const struct meson_gx_soc_id { + const char *name; + unsigned int id; +} soc_ids[] = { + { "GXBB", 0x1f }, + { "GXTVBB", 0x20 }, + { "GXL", 0x21 }, + { "GXM", 0x22 }, + { "TXL", 0x23 }, + { "TXLX", 0x24 }, + { "AXG", 0x25 }, + { "GXLX", 0x26 }, + { "TXHD", 0x27 }, +}; + +static const struct meson_gx_package_id { + const char *name; + unsigned int major_id; + unsigned int pack_id; + unsigned int pack_mask; +} soc_packages[] = { + { "S905", 0x1f, 0, 0x20 }, /* pack_id != 0x20 */ + { "S905H", 0x1f, 0x3, 0xf }, /* pack_id & 0xf == 0x3 */ + { "S905M", 0x1f, 0x20, 0xf0 }, /* pack_id == 0x20 */ + { "S905D", 0x21, 0, 0xf0 }, + { "S905X", 0x21, 0x80, 0xf0 }, + { "S905W", 0x21, 0xa0, 0xf0 }, + { "S905L", 0x21, 0xc0, 0xf0 }, + { "S905M2", 0x21, 0xe0, 0xf0 }, + { "S912", 0x22, 0, 0x0 }, /* Only S912 is known for GXM */ + { "962X", 0x24, 0x10, 0xf0 }, + { "962E", 0x24, 0x20, 0xf0 }, + { "A113X", 0x25, 0x37, 0xff }, + { "A113D", 0x25, 0x22, 0xff }, +}; + +static inline unsigned int socinfo_to_major(u32 socinfo) +{ + return FIELD_GET(SOCINFO_MAJOR, socinfo); +} + +static inline unsigned int socinfo_to_minor(u32 socinfo) +{ + return FIELD_GET(SOCINFO_MINOR, socinfo); +} + +static inline unsigned int socinfo_to_pack(u32 socinfo) +{ + return FIELD_GET(SOCINFO_PACK, socinfo); +} + +static inline unsigned int socinfo_to_misc(u32 socinfo) +{ + return FIELD_GET(SOCINFO_MISC, socinfo); +} + +static const char *socinfo_to_package_id(u32 socinfo) +{ + unsigned int pack = socinfo_to_pack(socinfo); + unsigned int major = socinfo_to_major(socinfo); + int i; + + for (i = 0 ; i < ARRAY_SIZE(soc_packages) ; ++i) { + if (soc_packages[i].major_id == major && + soc_packages[i].pack_id == + (pack & soc_packages[i].pack_mask)) + return soc_packages[i].name; + } + + return "Unknown"; +} + +static const char *socinfo_to_soc_id(u32 socinfo) +{ + unsigned int id = socinfo_to_major(socinfo); + int i; + + for (i = 0 ; i < ARRAY_SIZE(soc_ids) ; ++i) { + if (soc_ids[i].id == id) + return soc_ids[i].name; + } + + return "Unknown"; +} + +static int __init meson_gx_socinfo_init(void) +{ + struct soc_device_attribute *soc_dev_attr; + struct soc_device *soc_dev; + struct device_node *np; + struct regmap *regmap; + unsigned int socinfo; + struct device *dev; + int ret; + + /* look up for chipid node */ + np = of_find_compatible_node(NULL, NULL, "amlogic,meson-gx-ao-secure"); + if (!np) + return -ENODEV; + + /* check if interface is enabled */ + if (!of_device_is_available(np)) + return -ENODEV; + + /* check if chip-id is available */ + if (!of_property_read_bool(np, "amlogic,has-chip-id")) + return -ENODEV; + + /* node should be a syscon */ + regmap = syscon_node_to_regmap(np); + of_node_put(np); + if (IS_ERR(regmap)) { + pr_err("%s: failed to get regmap\n", __func__); + return -ENODEV; + } + + ret = regmap_read(regmap, AO_SEC_SOCINFO_OFFSET, &socinfo); + if (ret < 0) + return ret; + + if (!socinfo) { + pr_err("%s: invalid chipid value\n", __func__); + return -EINVAL; + } + + soc_dev_attr = kzalloc(sizeof(*soc_dev_attr), GFP_KERNEL); + if (!soc_dev_attr) + return -ENODEV; + + soc_dev_attr->family = "Amlogic Meson"; + + np = of_find_node_by_path("/"); + of_property_read_string(np, "model", &soc_dev_attr->machine); + of_node_put(np); + + soc_dev_attr->revision = kasprintf(GFP_KERNEL, "%x:%x - %x:%x", + socinfo_to_major(socinfo), + socinfo_to_minor(socinfo), + socinfo_to_pack(socinfo), + socinfo_to_misc(socinfo)); + soc_dev_attr->soc_id = kasprintf(GFP_KERNEL, "%s (%s)", + socinfo_to_soc_id(socinfo), + socinfo_to_package_id(socinfo)); + + soc_dev = soc_device_register(soc_dev_attr); + if (IS_ERR(soc_dev)) { + kfree(soc_dev_attr->revision); + kfree_const(soc_dev_attr->soc_id); + kfree(soc_dev_attr); + return PTR_ERR(soc_dev); + } + dev = soc_device_to_device(soc_dev); + + dev_info(dev, "Amlogic Meson %s Revision %x:%x (%x:%x) Detected\n", + soc_dev_attr->soc_id, + socinfo_to_major(socinfo), + socinfo_to_minor(socinfo), + socinfo_to_pack(socinfo), + socinfo_to_misc(socinfo)); + + return 0; +} +device_initcall(meson_gx_socinfo_init); diff --git a/pool/shard002/C/0060870_gunzip.c b/pool/shard002/C/0060870_gunzip.c new file mode 100644 index 0000000000000000000000000000000000000000..026d143a8a38c3dfd614fdf2eea29af904308233 --- /dev/null +++ b/pool/shard002/C/0060870_gunzip.c @@ -0,0 +1,116 @@ +/* Extended Module Player + * Copyright (C) 1996-2016 Claudio Matsuoka and Hipolito Carraro Jr + * + * This file is part of the Extended Module Player and is distributed + * under the terms of the GNU Lesser General Public License. See COPYING.LIB + * for more information. + */ + +#include +#include "common.h" +#include "inflate.h" +#include "depacker.h" +#include "crc32.h" + +/* See RFC1952 for further information */ + +/* The flag byte is divided into individual bits as follows: + + bit 0 FTEXT + bit 1 FHCRC + bit 2 FEXTRA + bit 3 FNAME + bit 4 FCOMMENT + bit 5 reserved + bit 6 reserved + bit 7 reserved +*/ + +#define FLAG_FTEXT (1 << 0) +#define FLAG_FHCRC (1 << 1) +#define FLAG_FEXTRA (1 << 2) +#define FLAG_FNAME (1 << 3) +#define FLAG_FCOMMENT (1 << 4) + +struct member { + uint8 id1; + uint8 id2; + uint8 cm; + uint8 flg; + uint32 mtime; + uint8 xfl; + uint8 os; +}; + +static int test_gzip(unsigned char *b) +{ + return b[0] == 31 && b[1] == 139; +} + +static int decrunch_gzip(FILE *in, FILE *out) +{ + struct member member; + int val, c; + uint32 crc; + + crc32_init_A(); + + member.id1 = read8(in, NULL); + member.id2 = read8(in, NULL); + member.cm = read8(in, NULL); + member.flg = read8(in, NULL); + member.mtime = read32l(in, NULL); + member.xfl = read8(in, NULL); + member.os = read8(in, NULL); + + if (member.cm != 0x08) { + return -1; + } + + if (member.flg & FLAG_FEXTRA) { + int xlen = read16l(in, NULL); + if (fseek(in, xlen, SEEK_CUR) < 0) { + return -1; + } + } + + if (member.flg & FLAG_FNAME) { + do { + c = read8(in, NULL); + } while (c != 0); + } + + if (member.flg & FLAG_FCOMMENT) { + do { + c = read8(in, NULL); + } while (c != 0); + } + + if (member.flg & FLAG_FHCRC) { + read16l(in, NULL); + } + + val = inflate(in, out, &crc, 1); + if (val != 0) { + return -1; + } + + /* Check CRC32 */ + val = read32l(in, NULL); + if (val != crc) { + return -1; + } + + /* Check file size */ + val = read32l(in, NULL); + if (val != ftell(out)) { + return -1; + } + + return 0; +} + +struct depacker gzip_depacker = { + test_gzip, + decrunch_gzip +}; diff --git a/pool/shard002/C/0060871_mod_osc_common.c b/pool/shard002/C/0060871_mod_osc_common.c new file mode 100644 index 0000000000000000000000000000000000000000..73050c774f0b15cc893d8dfd42871a1ec8416903 --- /dev/null +++ b/pool/shard002/C/0060871_mod_osc_common.c @@ -0,0 +1,128 @@ +/* + * Copyright (c) 2015 Hanspeter Portner (dev@open-music-kontrollers.ch) + * + * This is free software: you can redistribute it and/or modify + * it under the terms of the Artistic License 2.0 as published by + * The Perl Foundation. + * + * This source 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 + * Artistic License 2.0 for more details. + * + * You should have received a copy of the Artistic License 2.0 + * along the source as a COPYING file. If not, obtain it from + * http://www.perlfoundation.org/artistic_license_2_0. + */ + +#include +#include + +#include +#include + +osc_data_t * +mod_osc_encode(lua_State *L, int pos, osc_data_t *buf, osc_data_t *end) +{ + osc_data_t *ptr = buf; + + const char *path = luaL_checkstring(L, pos++); + const char *fmt = luaL_checkstring(L, pos++); + + ptr = osc_set_path(ptr, end, path); + ptr = osc_set_fmt(ptr, end, fmt); + + for(const char *type = fmt; *type; type++) + switch(*type) + { + case OSC_INT32: + { + int32_t i = luaL_checkinteger(L, pos++); + ptr = osc_set_int32(ptr, end, i); + break; + } + case OSC_FLOAT: + { + float f = luaL_checknumber(L, pos++); + ptr = osc_set_float(ptr, end, f); + break; + } + case OSC_STRING: + { + const char *s = luaL_checkstring(L, pos++); + ptr = osc_set_string(ptr, end, s); + break; + } + case OSC_BLOB: + { + mod_blob_t *tb = luaL_checkudata(L, pos++, "mod_blob_t"); + ptr = osc_set_blob(ptr, end, tb->size, tb->buf); + break; + } + + case OSC_TIMETAG: + { + osc_time_t t = luaL_checknumber(L, pos++); + ptr = osc_set_timetag(ptr, end, t); + break; + } + case OSC_INT64: + { + int64_t h = luaL_checknumber(L, pos++); + ptr = osc_set_int64(ptr, end, h); + break; + } + case OSC_DOUBLE: + { + double d = luaL_checknumber(L, pos++); + ptr = osc_set_double(ptr, end, d); + break; + } + + case OSC_NIL: + case OSC_BANG: + case OSC_TRUE: + case OSC_FALSE: + break; + + case OSC_SYMBOL: + { + const char *S = luaL_checkstring(L, pos++); + ptr = osc_set_symbol(ptr, end, S); + break; + } + case OSC_CHAR: + { + char c = luaL_checkinteger(L, pos++); + ptr = osc_set_char(ptr, end, c); + break; + } + case OSC_MIDI: + { + uint8_t *m; + if((ptr = osc_set_midi_inline(ptr, end, &m))) + { + if(lua_istable(L, pos)) + { + lua_rawgeti(L, pos, 4); + lua_rawgeti(L, pos, 3); + lua_rawgeti(L, pos, 2); + lua_rawgeti(L, pos, 1); + m[0] = luaL_checkinteger(L, -1); + m[1] = luaL_checkinteger(L, -2); + m[2] = luaL_checkinteger(L, -3); + m[3] = luaL_checkinteger(L, -4); + lua_pop(L, 4); + } + else + { + memset(m, 0, 4); + } + } + pos++; + break; + } + } + + return ptr; +} diff --git a/pool/shard002/C/0060872_simple.c b/pool/shard002/C/0060872_simple.c new file mode 100644 index 0000000000000000000000000000000000000000..ba33acdc37a3b665f6db2b442b5dcee15c8d57a5 --- /dev/null +++ b/pool/shard002/C/0060872_simple.c @@ -0,0 +1,33 @@ + +#include +#include + +/* usage: ./simple fontfile.ttf string */ +int main(int argc, char **argv) +{ + int rtl = 0; /* are we rendering right to left? probably not */ + int pointsize = 12; /* point size in points */ + int dpi = 96; /* work with this many dots per inch */ + + char *pError; /* location of faulty utf-8 */ + gr_font *font = NULL; + size_t numCodePoints = 0; + gr_segment * seg = NULL; + const gr_slot *s; + gr_face *face = gr_make_file_face(argv[1], 0); /*<1>*/ + if (!face) return 1; + font = gr_make_font(pointsize * dpi / 72.0f, face); /*<2>*/ + if (!font) return 2; + numCodePoints = gr_count_unicode_characters(gr_utf8, argv[2], NULL, + (const void **)(&pError)); /*<3>*/ + if (pError) return 3; + seg = gr_make_seg(font, face, 0, 0, gr_utf8, argv[2], numCodePoints, rtl); /*<4>*/ + if (!seg) return 3; + + for (s = gr_seg_first_slot(seg); s; s = gr_slot_next_in_segment(s)) /*<5>*/ + printf("%d(%f,%f) ", gr_slot_gid(s), gr_slot_origin_X(s), gr_slot_origin_Y(s)); + gr_seg_destroy(seg); + gr_font_destroy(font); + gr_face_destroy(face); + return 0; +} diff --git a/pool/shard002/C/0060885_fclaw2d_map_brick.c b/pool/shard002/C/0060885_fclaw2d_map_brick.c new file mode 100644 index 0000000000000000000000000000000000000000..1561bb6868b075f1084ff4a2d4beb3a967097855 --- /dev/null +++ b/pool/shard002/C/0060885_fclaw2d_map_brick.c @@ -0,0 +1,136 @@ +/* Cartesian grid, tranformed to Ax + b */ + +#include + +#include +#include +#include + +static int +fclaw2d_map_query_brick (fclaw2d_map_context_t * cont, int query_identifier) +{ + switch (query_identifier) + { + case FCLAW2D_MAP_QUERY_IS_USED: + return 1; + case FCLAW2D_MAP_QUERY_IS_SCALEDSHIFT: + return 1; + case FCLAW2D_MAP_QUERY_IS_AFFINE: + return 1; + case FCLAW2D_MAP_QUERY_IS_NONLINEAR: + return 0; + case FCLAW2D_MAP_QUERY_IS_GRAPH: + return 0; + case FCLAW2D_MAP_QUERY_IS_PLANAR: + return 1; + case FCLAW2D_MAP_QUERY_IS_ALIGNED: + return 0; + case FCLAW2D_MAP_QUERY_IS_FLAT: + return 1; + case FCLAW2D_MAP_QUERY_IS_DISK: + return 0; + case FCLAW2D_MAP_QUERY_IS_SPHERE: + return 0; + case FCLAW2D_MAP_QUERY_IS_PILLOWDISK: + return 0; + case FCLAW2D_MAP_QUERY_IS_SQUAREDDISK: + return 0; + case FCLAW2D_MAP_QUERY_IS_PILLOWSPHERE: + return 0; + case FCLAW2D_MAP_QUERY_IS_CUBEDSPHERE: + return 0; + case FCLAW2D_MAP_QUERY_IS_FIVEPATCH: + return 0; + case FCLAW2D_MAP_QUERY_IS_CART: + return 1; + case FCLAW2D_MAP_QUERY_IS_BRICK: + return 1; + default: + printf("\n"); + printf("fclaw2d_map_query_brick (fclaw2d_map_brick.h) : "\ + "Query id not identified; Maybe the query is not up to "\ + "date?\nSee fclaw2d_map_brick.c.\n"); + printf("Requested query id : %d\n",query_identifier); + SC_ABORT_NOT_REACHED (); + } + return 0; +} + +void +FCLAW2D_MAP_BRICK_GET_DIM(fclaw2d_map_context_t **cont, + int *mi, int* mj) +{ + fclaw2d_block_ll_t *bv = (fclaw2d_block_ll_t *) (*cont)->brick->user_data; + *mi = bv->mi; + *mj = bv->mj; +} + + +static void +fclaw2d_map_c2m_brick(fclaw2d_map_context_t * cont, int blockno, + double xc, double yc, + double *xp, double *yp, double *zp) +{ + /* Map the brick coordinates to global [0,1] coordinates. */ + fclaw2d_block_ll_t *bv = (fclaw2d_block_ll_t *) cont->user_data; + *xp = (double) (bv->xv[blockno] + xc)/bv->mi; + *yp = (double) (bv->yv[blockno] + yc)/bv->mj; + *zp = 0; +} + +void fclaw2d_map_destroy_brick(fclaw2d_map_context_t *cont) +{ + fclaw2d_block_ll_t *bv = (fclaw2d_block_ll_t *) cont->user_data; + FCLAW_FREE(bv->xv); + FCLAW_FREE(bv->yv); + + FCLAW_FREE (cont->user_data); + FCLAW_FREE (cont); +} + + +fclaw2d_map_context_t* fclaw2d_map_new_brick(p4est_connectivity_t *conn, + int mi, + int mj) +{ + fclaw2d_map_context_t *cont; + fclaw2d_block_ll_t *bv; + int i,nb,vnum; + + cont = FCLAW_ALLOC_ZERO (fclaw2d_map_context_t, 1); + cont->query = fclaw2d_map_query_brick; + cont->mapc2m = fclaw2d_map_c2m_brick; + cont->destroy = fclaw2d_map_destroy_brick; + + nb = (int) conn->num_trees; + bv = FCLAW_ALLOC_ZERO(fclaw2d_block_ll_t,1); + + /* We don't store this in user_double[], since that only has limited + storage (16 doubles) */ + bv->xv = FCLAW_ALLOC_ZERO(double,nb); + bv->yv = FCLAW_ALLOC_ZERO(double,nb); + + bv->nb = nb; /* These integer values could also be stored in user_int[] data */ + bv->mi = mi; + bv->mj = mj; + + for (i = 0; i < nb; i++) + { + vnum = conn->tree_to_vertex[4 * i]; + /* (x,y) coordinates of lower-left corner */ + bv->xv[i] = conn->vertices[3*vnum]; + bv->yv[i] = conn->vertices[3*vnum+1]; + } + cont->user_data = (void*) bv; + + /* Write data for Matlab plotting */ + FILE *fid; + fid = fopen("brick.dat","w"); + fprintf(fid,"%8d %8d\n",mi, mj); + for(i = 0; i < nb; i++) + { + fprintf(fid,"%12g %12g\n",bv->xv[i], bv->yv[i]); + } + fclose(fid); + return cont; +} diff --git a/pool/shard002/C/0060889_i10nm_base.c b/pool/shard002/C/0060889_i10nm_base.c new file mode 100644 index 0000000000000000000000000000000000000000..c334fb7c63df5ec3ba4ced0ade673763b0d48277 --- /dev/null +++ b/pool/shard002/C/0060889_i10nm_base.c @@ -0,0 +1,275 @@ +// SPDX-License-Identifier: GPL-2.0 +/* + * Driver for Intel(R) 10nm server memory controller. + * Copyright (c) 2019, Intel Corporation. + * + */ + +#include +#include +#include +#include +#include "edac_module.h" +#include "skx_common.h" + +#define I10NM_REVISION "v0.0.3" +#define EDAC_MOD_STR "i10nm_edac" + +/* Debug macros */ +#define i10nm_printk(level, fmt, arg...) \ + edac_printk(level, "i10nm", fmt, ##arg) + +#define I10NM_GET_SCK_BAR(d, reg) \ + pci_read_config_dword((d)->uracu, 0xd0, &(reg)) +#define I10NM_GET_IMC_BAR(d, i, reg) \ + pci_read_config_dword((d)->uracu, 0xd8 + (i) * 4, &(reg)) +#define I10NM_GET_DIMMMTR(m, i, j) \ + (*(u32 *)((m)->mbase + 0x2080c + (i) * 0x4000 + (j) * 4)) +#define I10NM_GET_MCDDRTCFG(m, i, j) \ + (*(u32 *)((m)->mbase + 0x20970 + (i) * 0x4000 + (j) * 4)) + +#define I10NM_GET_SCK_MMIO_BASE(reg) (GET_BITFIELD(reg, 0, 28) << 23) +#define I10NM_GET_IMC_MMIO_OFFSET(reg) (GET_BITFIELD(reg, 0, 10) << 12) +#define I10NM_GET_IMC_MMIO_SIZE(reg) ((GET_BITFIELD(reg, 13, 23) - \ + GET_BITFIELD(reg, 0, 10) + 1) << 12) + +static struct list_head *i10nm_edac_list; + +static struct pci_dev *pci_get_dev_wrapper(int dom, unsigned int bus, + unsigned int dev, unsigned int fun) +{ + struct pci_dev *pdev; + + pdev = pci_get_domain_bus_and_slot(dom, bus, PCI_DEVFN(dev, fun)); + if (!pdev) { + edac_dbg(2, "No device %02x:%02x.%x\n", + bus, dev, fun); + return NULL; + } + + if (unlikely(pci_enable_device(pdev) < 0)) { + edac_dbg(2, "Failed to enable device %02x:%02x.%x\n", + bus, dev, fun); + return NULL; + } + + pci_dev_get(pdev); + + return pdev; +} + +static int i10nm_get_all_munits(void) +{ + struct pci_dev *mdev; + void __iomem *mbase; + unsigned long size; + struct skx_dev *d; + int i, j = 0; + u32 reg, off; + u64 base; + + list_for_each_entry(d, i10nm_edac_list, list) { + d->util_all = pci_get_dev_wrapper(d->seg, d->bus[1], 29, 1); + if (!d->util_all) + return -ENODEV; + + d->uracu = pci_get_dev_wrapper(d->seg, d->bus[0], 0, 1); + if (!d->uracu) + return -ENODEV; + + if (I10NM_GET_SCK_BAR(d, reg)) { + i10nm_printk(KERN_ERR, "Failed to socket bar\n"); + return -ENODEV; + } + + base = I10NM_GET_SCK_MMIO_BASE(reg); + edac_dbg(2, "socket%d mmio base 0x%llx (reg 0x%x)\n", + j++, base, reg); + + for (i = 0; i < I10NM_NUM_IMC; i++) { + mdev = pci_get_dev_wrapper(d->seg, d->bus[0], + 12 + i, 0); + if (i == 0 && !mdev) { + i10nm_printk(KERN_ERR, "No IMC found\n"); + return -ENODEV; + } + if (!mdev) + continue; + + d->imc[i].mdev = mdev; + + if (I10NM_GET_IMC_BAR(d, i, reg)) { + i10nm_printk(KERN_ERR, "Failed to get mc bar\n"); + return -ENODEV; + } + + off = I10NM_GET_IMC_MMIO_OFFSET(reg); + size = I10NM_GET_IMC_MMIO_SIZE(reg); + edac_dbg(2, "mc%d mmio base 0x%llx size 0x%lx (reg 0x%x)\n", + i, base + off, size, reg); + + mbase = ioremap(base + off, size); + if (!mbase) { + i10nm_printk(KERN_ERR, "Failed to ioremap 0x%llx\n", + base + off); + return -ENODEV; + } + + d->imc[i].mbase = mbase; + } + } + + return 0; +} + +static const struct x86_cpu_id i10nm_cpuids[] = { + { X86_VENDOR_INTEL, 6, INTEL_FAM6_ATOM_TREMONT_X, 0, 0 }, + { } +}; +MODULE_DEVICE_TABLE(x86cpu, i10nm_cpuids); + +static bool i10nm_check_ecc(struct skx_imc *imc, int chan) +{ + u32 mcmtr; + + mcmtr = *(u32 *)(imc->mbase + 0x20ef8 + chan * 0x4000); + edac_dbg(1, "ch%d mcmtr reg %x\n", chan, mcmtr); + + return !!GET_BITFIELD(mcmtr, 2, 2); +} + +static int i10nm_get_dimm_config(struct mem_ctl_info *mci) +{ + struct skx_pvt *pvt = mci->pvt_info; + struct skx_imc *imc = pvt->imc; + struct dimm_info *dimm; + u32 mtr, mcddrtcfg; + int i, j, ndimms; + + for (i = 0; i < I10NM_NUM_CHANNELS; i++) { + if (!imc->mbase) + continue; + + ndimms = 0; + for (j = 0; j < I10NM_NUM_DIMMS; j++) { + dimm = EDAC_DIMM_PTR(mci->layers, mci->dimms, + mci->n_layers, i, j, 0); + mtr = I10NM_GET_DIMMMTR(imc, i, j); + mcddrtcfg = I10NM_GET_MCDDRTCFG(imc, i, j); + edac_dbg(1, "dimmmtr 0x%x mcddrtcfg 0x%x (mc%d ch%d dimm%d)\n", + mtr, mcddrtcfg, imc->mc, i, j); + + if (IS_DIMM_PRESENT(mtr)) + ndimms += skx_get_dimm_info(mtr, 0, dimm, + imc, i, j); + else if (IS_NVDIMM_PRESENT(mcddrtcfg, j)) + ndimms += skx_get_nvdimm_info(dimm, imc, i, j, + EDAC_MOD_STR); + } + if (ndimms && !i10nm_check_ecc(imc, 0)) { + i10nm_printk(KERN_ERR, "ECC is disabled on imc %d\n", + imc->mc); + return -ENODEV; + } + } + + return 0; +} + +static struct notifier_block i10nm_mce_dec = { + .notifier_call = skx_mce_check_error, + .priority = MCE_PRIO_EDAC, +}; + +static int __init i10nm_init(void) +{ + u8 mc = 0, src_id = 0, node_id = 0; + const struct x86_cpu_id *id; + const char *owner; + struct skx_dev *d; + int rc, i, off[3] = {0xd0, 0xc8, 0xcc}; + u64 tolm, tohm; + + edac_dbg(2, "\n"); + + owner = edac_get_owner(); + if (owner && strncmp(owner, EDAC_MOD_STR, sizeof(EDAC_MOD_STR))) + return -EBUSY; + + id = x86_match_cpu(i10nm_cpuids); + if (!id) + return -ENODEV; + + rc = skx_get_hi_lo(0x09a2, off, &tolm, &tohm); + if (rc) + return rc; + + rc = skx_get_all_bus_mappings(0x3452, 0xcc, I10NM, &i10nm_edac_list); + if (rc < 0) + goto fail; + if (rc == 0) { + i10nm_printk(KERN_ERR, "No memory controllers found\n"); + return -ENODEV; + } + + rc = i10nm_get_all_munits(); + if (rc < 0) + goto fail; + + list_for_each_entry(d, i10nm_edac_list, list) { + rc = skx_get_src_id(d, &src_id); + if (rc < 0) + goto fail; + + rc = skx_get_node_id(d, &node_id); + if (rc < 0) + goto fail; + + edac_dbg(2, "src_id = %d node_id = %d\n", src_id, node_id); + for (i = 0; i < I10NM_NUM_IMC; i++) { + if (!d->imc[i].mdev) + continue; + + d->imc[i].mc = mc++; + d->imc[i].lmc = i; + d->imc[i].src_id = src_id; + d->imc[i].node_id = node_id; + + rc = skx_register_mci(&d->imc[i], d->imc[i].mdev, + "Intel_10nm Socket", EDAC_MOD_STR, + i10nm_get_dimm_config); + if (rc < 0) + goto fail; + } + } + + rc = skx_adxl_get(); + if (rc) + goto fail; + + opstate_init(); + mce_register_decode_chain(&i10nm_mce_dec); + setup_skx_debug("i10nm_test"); + + i10nm_printk(KERN_INFO, "%s\n", I10NM_REVISION); + + return 0; +fail: + skx_remove(); + return rc; +} + +static void __exit i10nm_exit(void) +{ + edac_dbg(2, "\n"); + teardown_skx_debug(); + mce_unregister_decode_chain(&i10nm_mce_dec); + skx_adxl_put(); + skx_remove(); +} + +module_init(i10nm_init); +module_exit(i10nm_exit); + +MODULE_LICENSE("GPL v2"); +MODULE_DESCRIPTION("MC Driver for Intel 10nm server processors"); diff --git a/pool/shard002/C/0060893_curl_crtl_init.c b/pool/shard002/C/0060893_curl_crtl_init.c new file mode 100644 index 0000000000000000000000000000000000000000..9f7cf66c7ac6649219c197b79cbac6aa6e263067 --- /dev/null +++ b/pool/shard002/C/0060893_curl_crtl_init.c @@ -0,0 +1,310 @@ +/* File: curl_crtl_init.c + * + * This file makes sure that the DECC Unix settings are correct for + * the mode the program is run in. + * + * The CRTL has not been initialized at the time that these routines + * are called, so many routines can not be called. + * + * This is a module that provides a LIB$INITIALIZE routine that + * will turn on some CRTL features that are not enabled by default. + * + * The CRTL features can also be turned on via logical names, but that + * impacts all programs and some aren't ready, willing, or able to handle + * those settings. + * + * On VMS versions that are too old to use the feature setting API, this + * module falls back to using logical names. + * + * Copyright 2013, John Malmberg + * + * 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. + * + */ + +/* Unix headers */ +#include +#include + +/* VMS specific headers */ +#include +#include +#include + +#pragma member_alignment save +#pragma nomember_alignment longword +#pragma message save +#pragma message disable misalgndmem +struct itmlst_3 { + unsigned short int buflen; + unsigned short int itmcode; + void *bufadr; + unsigned short int *retlen; +}; +#pragma message restore +#pragma member_alignment restore + +#ifdef __VAX +#define ENABLE "ENABLE" +#define DISABLE "DISABLE" +#else + +#define ENABLE TRUE +#define DISABLE 0 +int decc$feature_get_index (const char *name); +int decc$feature_set_value (int index, int mode, int value); +#endif + +int SYS$TRNLNM( + const unsigned long * attr, + const struct dsc$descriptor_s * table_dsc, + struct dsc$descriptor_s * name_dsc, + const unsigned char * acmode, + const struct itmlst_3 * item_list); +int SYS$CRELNM( + const unsigned long * attr, + const struct dsc$descriptor_s * table_dsc, + const struct dsc$descriptor_s * name_dsc, + const unsigned char * acmode, + const struct itmlst_3 * item_list); + + +/* Take all the fun out of simply looking up a logical name */ +static int sys_trnlnm + (const char * logname, + char * value, + int value_len) +{ + const $DESCRIPTOR(table_dsc, "LNM$FILE_DEV"); + const unsigned long attr = LNM$M_CASE_BLIND; + struct dsc$descriptor_s name_dsc; + int status; + unsigned short result; + struct itmlst_3 itlst[2]; + + itlst[0].buflen = value_len; + itlst[0].itmcode = LNM$_STRING; + itlst[0].bufadr = value; + itlst[0].retlen = &result; + + itlst[1].buflen = 0; + itlst[1].itmcode = 0; + + name_dsc.dsc$w_length = strlen(logname); + name_dsc.dsc$a_pointer = (char *)logname; + name_dsc.dsc$b_dtype = DSC$K_DTYPE_T; + name_dsc.dsc$b_class = DSC$K_CLASS_S; + + status = SYS$TRNLNM(&attr, &table_dsc, &name_dsc, 0, itlst); + + if ($VMS_STATUS_SUCCESS(status)) { + + /* Null terminate and return the string */ + /*--------------------------------------*/ + value[result] = '\0'; + } + + return status; +} + +/* How to simply create a logical name */ +static int sys_crelnm + (const char * logname, + const char * value) +{ + int ret_val; + const char * proc_table = "LNM$PROCESS_TABLE"; + struct dsc$descriptor_s proc_table_dsc; + struct dsc$descriptor_s logname_dsc; + struct itmlst_3 item_list[2]; + + proc_table_dsc.dsc$a_pointer = (char *) proc_table; + proc_table_dsc.dsc$w_length = strlen(proc_table); + proc_table_dsc.dsc$b_dtype = DSC$K_DTYPE_T; + proc_table_dsc.dsc$b_class = DSC$K_CLASS_S; + + logname_dsc.dsc$a_pointer = (char *) logname; + logname_dsc.dsc$w_length = strlen(logname); + logname_dsc.dsc$b_dtype = DSC$K_DTYPE_T; + logname_dsc.dsc$b_class = DSC$K_CLASS_S; + + item_list[0].buflen = strlen(value); + item_list[0].itmcode = LNM$_STRING; + item_list[0].bufadr = (char *)value; + item_list[0].retlen = NULL; + + item_list[1].buflen = 0; + item_list[1].itmcode = 0; + + ret_val = SYS$CRELNM(NULL, &proc_table_dsc, &logname_dsc, NULL, item_list); + + return ret_val; +} + + + /* Start of DECC RTL Feature handling */ + +/* +** Sets default value for a feature +*/ +#ifdef __VAX +static void set_feature_default(const char *name, const char *value) +{ + sys_crelnm(name, value); +} +#else +static void set_feature_default(const char *name, int value) +{ + int index; + + index = decc$feature_get_index(name); + + if (index > 0) + decc$feature_set_value (index, 0, value); +} +#endif + +static void set_features(void) +{ + int status; + char unix_shell_name[255]; + int use_unix_settings = 1; + + status = sys_trnlnm("GNV$UNIX_SHELL", + unix_shell_name, sizeof unix_shell_name -1); + if (!$VMS_STATUS_SUCCESS(status)) { + use_unix_settings = 0; + } + + /* ACCESS should check ACLs or it is lying. */ + set_feature_default("DECC$ACL_ACCESS_CHECK", ENABLE); + + /* We always want the new parse style */ + set_feature_default ("DECC$ARGV_PARSE_STYLE" , ENABLE); + + + /* Unless we are in POSIX compliant mode, we want the old POSIX root + * enabled. + */ + set_feature_default("DECC$DISABLE_POSIX_ROOT", DISABLE); + + /* EFS charset, means UTF-8 support */ + /* VTF-7 support is controlled by a feature setting called UTF8 */ + set_feature_default ("DECC$EFS_CHARSET", ENABLE); + set_feature_default ("DECC$EFS_CASE_PRESERVE", ENABLE); + + /* Support timestamps when available */ + set_feature_default ("DECC$EFS_FILE_TIMESTAMPS", ENABLE); + + /* Cache environment variables - performance improvements */ + set_feature_default ("DECC$ENABLE_GETENV_CACHE", ENABLE); + + /* Start out with new file attribute inheritance */ +#ifdef __VAX + set_feature_default ("DECC$EXEC_FILEATTR_INHERITANCE", "2"); +#else + set_feature_default ("DECC$EXEC_FILEATTR_INHERITANCE", 2); +#endif + + /* Don't display trailing dot after files without type */ + set_feature_default ("DECC$READDIR_DROPDOTNOTYPE", ENABLE); + + /* For standard output channels buffer output until terminator */ + /* Gets rid of output logs with single character lines in them. */ + set_feature_default ("DECC$STDIO_CTX_EOL", ENABLE); + + /* Fix mv aa.bb aa */ + set_feature_default ("DECC$RENAME_NO_INHERIT", ENABLE); + + if (use_unix_settings) { + + /* POSIX requires that open files be able to be removed */ + set_feature_default ("DECC$ALLOW_REMOVE_OPEN_FILES", ENABLE); + + /* Default to outputting Unix filenames in VMS routines */ + set_feature_default ("DECC$FILENAME_UNIX_ONLY", ENABLE); + /* FILENAME_UNIX_ONLY Implicitly sets */ + /* decc$disable_to_vms_logname_translation */ + + set_feature_default ("DECC$FILE_PERMISSION_UNIX", ENABLE); + + set_feature_default ("DECC$FILE_SHARING", ENABLE); + + set_feature_default ("DECC$FILE_OWNER_UNIX", ENABLE); + set_feature_default ("DECC$POSIX_SEEK_STREAM_FILE", ENABLE); + + } else { + set_feature_default("DECC$FILENAME_UNIX_REPORT", ENABLE); + } + + /* When reporting Unix filenames, glob the same way */ + set_feature_default ("DECC$GLOB_UNIX_STYLE", ENABLE); + + /* The VMS version numbers on Unix filenames is incompatible with most */ + /* ported packages. */ + set_feature_default("DECC$FILENAME_UNIX_NO_VERSION", ENABLE); + + /* The VMS version numbers on Unix filenames is incompatible with most */ + /* ported packages. */ + set_feature_default("DECC$UNIX_PATH_BEFORE_LOGNAME", ENABLE); + + /* Set strtol to proper behavior */ + set_feature_default("DECC$STRTOL_ERANGE", ENABLE); + + /* Commented here to prevent future bugs: A program or user should */ + /* never ever enable DECC$POSIX_STYLE_UID. */ + /* It will probably break all code that accesses UIDs */ + /* do_not_set_default ("DECC$POSIX_STYLE_UID", TRUE); */ +} + + +/* Some boilerplate to force this to be a proper LIB$INITIALIZE section */ + +#pragma nostandard +#pragma extern_model save +#ifdef __VAX +#pragma extern_model strict_refdef "LIB$INITIALIZE" nowrt, long, nopic +#else +#pragma extern_model strict_refdef "LIB$INITIALIZE" nowrt, long +# if __INITIAL_POINTER_SIZE +# pragma __pointer_size __save +# pragma __pointer_size 32 +# else +# pragma __required_pointer_size __save +# pragma __required_pointer_size 32 +# endif +#endif +/* Set our contribution to the LIB$INITIALIZE array */ +void (* const iniarray[])(void) = {set_features, } ; +#ifndef __VAX +# if __INITIAL_POINTER_SIZE +# pragma __pointer_size __restore +# else +# pragma __required_pointer_size __restore +# endif +#endif + + +/* +** Force a reference to LIB$INITIALIZE to ensure it +** exists in the image. +*/ +int LIB$INITIALIZE(void); +#ifdef __DECC +#pragma extern_model strict_refdef +#endif + int lib_init_ref = (int) LIB$INITIALIZE; +#ifdef __DECC +#pragma extern_model restore +#pragma standard +#endif diff --git a/pool/shard002/C/0060898_gdv.c b/pool/shard002/C/0060898_gdv.c new file mode 100644 index 0000000000000000000000000000000000000000..2ecbb535e7cb75ea4e0fca49a43f6e9a07d776c3 --- /dev/null +++ b/pool/shard002/C/0060898_gdv.c @@ -0,0 +1,203 @@ +/* + * Gremlin Digital Video demuxer + * Copyright (c) 2017 Paul B Mahol + * + * 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 "libavutil/intreadwrite.h" + +#include "avformat.h" +#include "avio.h" +#include "internal.h" + +typedef struct GDVContext { + int is_first_video; + int is_audio; + int audio_size; + int audio_stream_index; + int video_stream_index; + unsigned pal[256]; +} GDVContext; + +static int gdv_read_probe(const AVProbeData *p) +{ + if (AV_RL32(p->buf) == 0x29111994) + return AVPROBE_SCORE_MAX; + + return 0; +} + +static struct { + uint16_t id; + uint16_t width; + uint16_t height; +} FixedSize[] = { + { 0, 320, 200}, + { 1, 640, 200}, + { 2, 320, 167}, + { 3, 320, 180}, + { 4, 320, 400}, + { 5, 320, 170}, + { 6, 160, 85}, + { 7, 160, 83}, + { 8, 160, 90}, + { 9, 280, 128}, + {10, 320, 240}, + {11, 320, 201}, + {16, 640, 400}, + {17, 640, 200}, + {18, 640, 180}, + {19, 640, 167}, + {20, 640, 170}, + {21, 320, 240} +}; + +static int gdv_read_header(AVFormatContext *ctx) +{ + GDVContext *gdv = ctx->priv_data; + AVIOContext *pb = ctx->pb; + AVStream *vst, *ast; + unsigned fps, snd_flags, vid_depth, size_id; + + avio_skip(pb, 4); + size_id = avio_rl16(pb); + + vst = avformat_new_stream(ctx, 0); + if (!vst) + return AVERROR(ENOMEM); + + vst->start_time = 0; + vst->duration = + vst->nb_frames = avio_rl16(pb); + + fps = avio_rl16(pb); + if (!fps) + return AVERROR_INVALIDDATA; + + snd_flags = avio_rl16(pb); + if (snd_flags & 1) { + ast = avformat_new_stream(ctx, 0); + if (!ast) + return AVERROR(ENOMEM); + + ast->start_time = 0; + ast->codecpar->codec_type = AVMEDIA_TYPE_AUDIO; + ast->codecpar->codec_tag = 0; + ast->codecpar->sample_rate = avio_rl16(pb); + ast->codecpar->channels = 1 + !!(snd_flags & 2); + if (snd_flags & 8) { + ast->codecpar->codec_id = AV_CODEC_ID_GREMLIN_DPCM; + } else { + ast->codecpar->codec_id = (snd_flags & 4) ? AV_CODEC_ID_PCM_S16LE : AV_CODEC_ID_PCM_U8; + } + + avpriv_set_pts_info(ast, 64, 1, ast->codecpar->sample_rate); + gdv->audio_size = (ast->codecpar->sample_rate / fps) * + ast->codecpar->channels * (1 + !!(snd_flags & 4)) / (1 + !!(snd_flags & 8)); + gdv->is_audio = 1; + } else { + avio_skip(pb, 2); + } + vid_depth = avio_rl16(pb); + avio_skip(pb, 4); + + vst->codecpar->codec_type = AVMEDIA_TYPE_VIDEO; + vst->codecpar->codec_id = AV_CODEC_ID_GDV; + vst->codecpar->codec_tag = 0; + vst->codecpar->width = avio_rl16(pb); + vst->codecpar->height = avio_rl16(pb); + + if (vst->codecpar->width == 0 || vst->codecpar->height == 0) { + int i; + + for (i = 0; i < FF_ARRAY_ELEMS(FixedSize) - 1; i++) { + if (FixedSize[i].id == size_id) + break; + } + + vst->codecpar->width = FixedSize[i].width; + vst->codecpar->height = FixedSize[i].height; + } + + avpriv_set_pts_info(vst, 64, 1, fps); + + if (vid_depth & 1) { + int i; + + for (i = 0; i < 256; i++) { + unsigned r = avio_r8(pb); + unsigned g = avio_r8(pb); + unsigned b = avio_r8(pb); + gdv->pal[i] = 0xFFU << 24 | r << 18 | g << 10 | b << 2; + } + } + + gdv->is_first_video = 1; + + return 0; +} + +static int gdv_read_packet(AVFormatContext *ctx, AVPacket *pkt) +{ + GDVContext *gdv = ctx->priv_data; + AVIOContext *pb = ctx->pb; + int ret; + + if (avio_feof(pb)) + return pb->error ? pb->error : AVERROR_EOF; + + if (gdv->audio_size && gdv->is_audio) { + ret = av_get_packet(pb, pkt, gdv->audio_size); + if (ret < 0) + return ret; + pkt->stream_index = 1; + gdv->is_audio = 0; + } else { + uint8_t *pal; + + if (avio_rl16(pb) != 0x1305) + return AVERROR_INVALIDDATA; + ret = av_get_packet(pb, pkt, 4 + avio_rl16(pb)); + if (ret < 0) + return ret; + pkt->stream_index = 0; + gdv->is_audio = 1; + + if (gdv->is_first_video) { + pal = av_packet_new_side_data(pkt, AV_PKT_DATA_PALETTE, + AVPALETTE_SIZE); + if (!pal) { + return AVERROR(ENOMEM); + } + memcpy(pal, gdv->pal, AVPALETTE_SIZE); + pkt->flags |= AV_PKT_FLAG_KEY; + gdv->is_first_video = 0; + } + } + + return 0; +} + +AVInputFormat ff_gdv_demuxer = { + .name = "gdv", + .long_name = NULL_IF_CONFIG_SMALL("Gremlin Digital Video"), + .priv_data_size = sizeof(GDVContext), + .read_probe = gdv_read_probe, + .read_header = gdv_read_header, + .read_packet = gdv_read_packet, +}; diff --git a/pool/shard002/C/0060925_report_platform.c b/pool/shard002/C/0060925_report_platform.c new file mode 100644 index 0000000000000000000000000000000000000000..e0c91945fed2bfde12e3f6b8497ad240113af91b --- /dev/null +++ b/pool/shard002/C/0060925_report_platform.c @@ -0,0 +1,251 @@ +/* + * This file is part of the coreboot project. + * + * Copyright (C) 2014 Google Inc. + * Copyright (C) 2015-2018 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 +#include +#include +#include +#include +#include +#include +#include +#include + +#define BIOS_SIGN_ID 0x8B + +static struct { + u32 cpuid; + const char *name; +} cpu_table[] = { + { CPUID_CANNONLAKE_A0, "Cannonlake A0" }, + { CPUID_CANNONLAKE_B0, "Cannonlake B0" }, + { CPUID_CANNONLAKE_C0, "Cannonlake C0" }, + { CPUID_CANNONLAKE_D0, "Cannonlake D0" }, + { CPUID_COFFEELAKE_D0, "Coffeelake D0" }, + { CPUID_WHISKEYLAKE_V0, "Whiskeylake V0" }, + { CPUID_WHISKEYLAKE_W0, "Whiskeylake W0" }, + { CPUID_COFFEELAKE_U0, "Coffeelake U0 (6+2)" }, + { CPUID_COMETLAKE_U_A0, "Cometlake-U A0 (6+2)" }, + { CPUID_COMETLAKE_U_K0_S0, "Cometlake-U K0/S0 (6+2)/(4+2)" }, + { CPUID_COMETLAKE_H_S_6_2_P0, "Cometlake-H/S P0 (6+2)" }, + { CPUID_COMETLAKE_H_S_10_2_P0, "Cometlake-H/S P0 (10+2)" }, +}; + +static struct { + u16 mchid; + const char *name; +} mch_table[] = { + { PCI_DEVICE_ID_INTEL_CNL_ID_U, "Cannonlake-U" }, + { PCI_DEVICE_ID_INTEL_CNL_ID_Y, "Cannonlake-Y" }, + { PCI_DEVICE_ID_INTEL_CFL_ID_U, "Coffeelake U (4+3e)" }, + { PCI_DEVICE_ID_INTEL_WHL_ID_Wx4, "Whiskeylake W (4+2)" }, + { PCI_DEVICE_ID_INTEL_WHL_ID_Wx2, "Whiskeylake W (2+2)" }, + { PCI_DEVICE_ID_INTEL_CFL_ID_H, "Coffeelake-H" }, + { PCI_DEVICE_ID_INTEL_CFL_ID_S, "Coffeelake-S" }, + { PCI_DEVICE_ID_INTEL_CML_ULT, "CometLake-U (4+2)" }, + { PCI_DEVICE_ID_INTEL_CML_ULT_2_2, "CometLake-U (2+2)" }, + { PCI_DEVICE_ID_INTEL_CML_ULT_6_2, "CometLake-U (6+2)" }, + { PCI_DEVICE_ID_INTEL_CML_ULX, "CometLake-ULX (4+2)" }, + { PCI_DEVICE_ID_INTEL_CML_S, "CometLake-S (6+2)" }, + { PCI_DEVICE_ID_INTEL_CML_S_10_2, "CometLake-S (10+2)" }, + { PCI_DEVICE_ID_INTEL_CML_H, "CometLake-H (6+2)" }, + { PCI_DEVICE_ID_INTEL_CML_H_8_2, "CometLake-H (8+2)" }, +}; + +static struct { + u16 lpcid; + const char *name; +} pch_table[] = { + { PCI_DEVICE_ID_INTEL_CNL_BASE_U_LPC, "Cannonlake-U Base" }, + { PCI_DEVICE_ID_INTEL_CNL_U_PREMIUM_LPC, "Cannonlake-U Premium" }, + { PCI_DEVICE_ID_INTEL_CNL_Y_PREMIUM_LPC, "Cannonlake-Y Premium" }, + { PCI_DEVICE_ID_INTEL_CNP_H_LPC_Q370, "Cannonlake-H Q370" }, + { PCI_DEVICE_ID_INTEL_CNP_H_LPC_QM370, "Cannonlake-H QM370" }, + { PCI_DEVICE_ID_INTEL_CMP_SUPER_U_LPC, "Cometlake-U Super" }, + { PCI_DEVICE_ID_INTEL_CMP_PREMIUM_Y_LPC, "Cometlake-Y Premium" }, + { PCI_DEVICE_ID_INTEL_CMP_PREMIUM_U_LPC, "Cometlake-U Premium" }, + { PCI_DEVICE_ID_INTEL_CMP_BASE_U_LPC, "Cometlake-U Base" }, + { PCI_DEVICE_ID_INTEL_CMP_SUPER_Y_LPC, "Cometlake-Y Super" }, +}; + +static struct { + u16 igdid; + const char *name; +} igd_table[] = { + { PCI_DEVICE_ID_INTEL_CNL_GT2_ULX_1, "Cannonlake ULX GT2" }, + { PCI_DEVICE_ID_INTEL_CNL_GT2_ULX_2, "Cannonlake ULX GT1.5" }, + { PCI_DEVICE_ID_INTEL_CNL_GT2_ULX_3, "Cannonlake ULX GT1" }, + { PCI_DEVICE_ID_INTEL_CNL_GT2_ULX_4, "Cannonlake ULX GT0.5" }, + { PCI_DEVICE_ID_INTEL_CNL_GT2_ULT_1, "Cannonlake ULT GT2" }, + { PCI_DEVICE_ID_INTEL_CNL_GT2_ULT_2, "Cannonlake ULT GT1.5" }, + { PCI_DEVICE_ID_INTEL_CNL_GT2_ULT_3, "Cannonlake ULT GT1" }, + { PCI_DEVICE_ID_INTEL_CNL_GT2_ULT_4, "Cannonlake ULT GT0.5" }, + { PCI_DEVICE_ID_INTEL_CFL_GT2_ULT, "Coffeelake ULT GT2" }, + { PCI_DEVICE_ID_INTEL_WHL_GT1_ULT_1, "Whiskeylake ULT GT1" }, + { PCI_DEVICE_ID_INTEL_WHL_GT2_ULT_1, "Whiskeylake ULT GT2" }, + { PCI_DEVICE_ID_INTEL_CFL_H_GT2, "Coffeelake-H GT2" }, + { PCI_DEVICE_ID_INTEL_CFL_S_GT2, "Coffeelake-S GT2" }, + { PCI_DEVICE_ID_INTEL_CML_GT1_ULT_1, "CometLake ULT GT1" }, + { PCI_DEVICE_ID_INTEL_CML_GT1_ULT_2, "CometLake ULT GT1" }, + { PCI_DEVICE_ID_INTEL_CML_GT2_ULT_1, "CometLake ULT GT2" }, + { PCI_DEVICE_ID_INTEL_CML_GT2_ULT_2, "CometLake ULT GT2" }, + { PCI_DEVICE_ID_INTEL_CML_GT1_ULT_3, "CometLake ULT GT1" }, + { PCI_DEVICE_ID_INTEL_CML_GT1_ULT_4, "CometLake ULT GT1" }, + { PCI_DEVICE_ID_INTEL_CML_GT2_ULT_3, "CometLake ULT GT2" }, + { PCI_DEVICE_ID_INTEL_CML_GT2_ULT_4, "CometLake ULT GT2" }, + { PCI_DEVICE_ID_INTEL_CML_GT1_ULX_1, "CometLake ULX GT1" }, + { PCI_DEVICE_ID_INTEL_CML_GT2_ULX_1, "CometLake ULX GT2" }, + { PCI_DEVICE_ID_INTEL_CML_GT1_S_1, "CometLake S GT1" }, + { PCI_DEVICE_ID_INTEL_CML_GT1_S_2, "CometLake S GT1" }, + { PCI_DEVICE_ID_INTEL_CML_GT2_S_1, "CometLake S GT2" }, + { PCI_DEVICE_ID_INTEL_CML_GT2_S_2, "CometLake S GT2" }, + { PCI_DEVICE_ID_INTEL_CML_GT1_H_1, "CometLake H GT1" }, + { PCI_DEVICE_ID_INTEL_CML_GT1_H_2, "CometLake H GT1" }, + { PCI_DEVICE_ID_INTEL_CML_GT2_H_1, "CometLake H GT2" }, + { PCI_DEVICE_ID_INTEL_CML_GT2_H_2, "CometLake H GT2" }, +}; + +static uint8_t get_dev_revision(pci_devfn_t dev) +{ + return pci_read_config8(dev, PCI_REVISION_ID); +} + +static uint16_t get_dev_id(pci_devfn_t dev) +{ + return pci_read_config16(dev, PCI_DEVICE_ID); +} + +static void report_cpu_info(void) +{ + struct cpuid_result cpuidr; + u32 i, index, cpu_id, cpu_feature_flag; + char cpu_string[50], *cpu_name = cpu_string; /* 48 bytes are reported */ + int vt, txt, aes; + msr_t microcode_ver; + static const char *const mode[] = {"NOT ", ""}; + const char *cpu_type = "Unknown"; + u32 p[13]; + + index = 0x80000000; + cpuidr = cpuid(index); + if (cpuidr.eax < 0x80000004) { + strcpy(cpu_string, "Platform info not available"); + } else { + int j=0; + + for (i = 2; i <= 4; i++) { + cpuidr = cpuid(index + i); + p[j++] = cpuidr.eax; + p[j++] = cpuidr.ebx; + p[j++] = cpuidr.ecx; + p[j++] = cpuidr.edx; + } + p[12]=0; + cpu_name = (char *)p; + } + /* Skip leading spaces in CPU name string */ + while (cpu_name[0] == ' ') + cpu_name++; + + microcode_ver.lo = 0; + microcode_ver.hi = 0; + wrmsr(BIOS_SIGN_ID, microcode_ver); + cpu_id = cpu_get_cpuid(); + microcode_ver = rdmsr(BIOS_SIGN_ID); + + /* Look for string to match the name */ + for (i = 0; i < ARRAY_SIZE(cpu_table); i++) { + if (cpu_table[i].cpuid == cpu_id) { + cpu_type = cpu_table[i].name; + break; + } + } + + printk(BIOS_DEBUG, "CPU: %s\n", cpu_name); + printk(BIOS_DEBUG, "CPU: ID %x, %s, ucode: %08x\n", + cpu_id, cpu_type, microcode_ver.hi); + + cpu_feature_flag = cpu_get_feature_flags_ecx(); + aes = (cpu_feature_flag & CPUID_AES) ? 1 : 0; + txt = (cpu_feature_flag & CPUID_SMX) ? 1 : 0; + vt = (cpu_feature_flag & CPUID_VMX) ? 1 : 0; + printk(BIOS_DEBUG, + "CPU: AES %ssupported, TXT %ssupported, VT %ssupported\n", + mode[aes], mode[txt], mode[vt]); +} + +static void report_mch_info(void) +{ + int i; + pci_devfn_t dev = SA_DEV_ROOT; + uint16_t mchid = get_dev_id(dev); + uint8_t mch_revision = get_dev_revision(dev); + const char *mch_type = "Unknown"; + + for (i = 0; i < ARRAY_SIZE(mch_table); i++) { + if (mch_table[i].mchid == mchid) { + mch_type = mch_table[i].name; + break; + } + } + + printk(BIOS_DEBUG, "MCH: device id %04x (rev %02x) is %s\n", + mchid, mch_revision, mch_type); +} + +static void report_pch_info(void) +{ + int i; + pci_devfn_t dev = PCH_DEV_LPC; + uint16_t lpcid = get_dev_id(dev); + const char *pch_type = "Unknown"; + + for (i = 0; i < ARRAY_SIZE(pch_table); i++) { + if (pch_table[i].lpcid == lpcid) { + pch_type = pch_table[i].name; + break; + } + } + printk(BIOS_DEBUG, "PCH: device id %04x (rev %02x) is %s\n", + lpcid, get_dev_revision(dev), pch_type); +} + +static void report_igd_info(void) +{ + int i; + pci_devfn_t dev = SA_DEV_IGD; + uint16_t igdid = get_dev_id(dev); + const char *igd_type = "Unknown"; + + for (i = 0; i < ARRAY_SIZE(igd_table); i++) { + if (igd_table[i].igdid == igdid) { + igd_type = igd_table[i].name; + break; + } + } + printk(BIOS_DEBUG, "IGD: device id %04x (rev %02x) is %s\n", + igdid, get_dev_revision(dev), igd_type); +} + +void report_platform_info(void) +{ + report_cpu_info(); + report_mch_info(); + report_pch_info(); + report_igd_info(); +} diff --git a/pool/shard002/C/0060931_input_raw.c b/pool/shard002/C/0060931_input_raw.c new file mode 100644 index 0000000000000000000000000000000000000000..04c06fed318c026aed59b16138c4b7fe338e447a --- /dev/null +++ b/pool/shard002/C/0060931_input_raw.c @@ -0,0 +1,102 @@ +/* + * Harry - A Tool for Measuring String Similarity + * Copyright (C) 2013-2015 Konrad Rieck (konrad@mlsec.org); + * -- + * 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 without any + * warranty. See the GNU General Public License for more details. + */ + +/** + * @addtogroup input + *
+ * raw: The strings are provided on standard input in raw format. + * + * This input module is designed for efficiently interfacing with other + * analysis environments. The raw format of a string is [len][array], where + * [len] is a 32-bit unsigned integer in host-byte order indicating the + * length of the following byte [array] containing the string data. + @{ + */ + +#include "config.h" +#include "common.h" +#include "harry.h" +#include "util.h" +#include "input.h" +#include "murmur.h" + +/** Static variable */ +static int str_num = 0; + +/** External variables */ +extern config_t cfg; + +/** + * Opens stdin for reading raw strings + * @param name File name (bogus) + * @return 1 on success, 0 otherwise + */ +int input_raw_open(char *name) +{ + if (stdin == NULL) { + error("Could not open for reading"); + return FALSE; + } + + str_num = 0; + return TRUE; +} + +/** + * Reads a block of strings into memory. + * @param strs Array for data + * @param num Length of block + * @return number of strings read into memory + */ +int input_raw_read(hstring_t *strs, int num) +{ + assert(strs && num > 0); + uint32_t len, ret, i = 0, j = 0; + char *str = NULL; + + for (i = 0; i < num; i++) { + ret = fread(&len, sizeof(len), 1, stdin); + if (ret != 1) { + error("Incomplete length field in raw format"); + break; + } + + str = malloc(len * sizeof(char)); + if (!str) { + error("Failed to allocate memory for string"); + break; + } + + ret = fread(str, sizeof(char), len, stdin); + if (ret != len) { + error("Incomplete byte array in raw format"); + break; + } + + strs[j].str.c = str; + strs[j].type = TYPE_BYTE; + strs[j].len = len; + strs[j].src = NULL; + j++; + } + + return j; +} + +/** + * Closes an open directory. + */ +void input_raw_close() +{ + /* Do nothing */ +} + +/** @} */ diff --git a/pool/shard002/C/0060934_test2.c b/pool/shard002/C/0060934_test2.c new file mode 100644 index 0000000000000000000000000000000000000000..d5b4b6e9259f15872ca5ec10ba34b8ba58f778ff --- /dev/null +++ b/pool/shard002/C/0060934_test2.c @@ -0,0 +1,34 @@ +#include "pfs.h" + +int main(int argc, char* argv[]) { + initialize(argc, argv); + //pfs_create("foo.txt", 1); + int fd = pfs_open("pfs_file1", 'w'); + //char *data = "test data123"; + char *data = malloc(1024); + //int cache_hit; + int cache_hit; + //pfs_write(fd, data, strlen(data)+1, 0, &cache_hit); + //sleep(30); + pfs_read(fd, data, 1024, 1025, &cache_hit); + fprintf(stderr, "data:%s\n", data); + sleep(10); + pfs_close(fd); + //cleanup();*/ + /*if (fd == -1) { + + } + fd = pfs_open("foo.txt", 'r'); + fprintf(stderr, "fd: %d\n", fd); + pfs_create("foo.txt", 1); + pfs_create("bar.txt", 1); + pfs_create("foo.txt", 1); + pfs_delete("foo.txt"); + pfs_create("foo.txt", 1);*/ + /*int cache_hit2; + void* data1 = malloc(10*1024); + int fd = pfs_open("pfs_file1", 'r'); + pfs_read(fd, data1, 4*1024, 0, &cache_hit2); + fprintf(stderr, "DATA%.*s\n", 4096, (char*)data1);*/ + return 0; +} diff --git a/pool/shard002/C/0060947_init.c b/pool/shard002/C/0060947_init.c new file mode 100644 index 0000000000000000000000000000000000000000..ae3f773d92091fd0285ffc47961a31dc86acca13 --- /dev/null +++ b/pool/shard002/C/0060947_init.c @@ -0,0 +1,68 @@ +#include +#include +#include +#include "q_incs.h" +#include "init.h" +#include "auxil.h" +extern lua_State *g_L_Q; +extern bool g_halt; + +extern char g_valid_chars_in_url[256]; + +extern char g_q_data_dir[Q_MAX_LEN_FILE_NAME+1]; +extern char g_q_metadata_file[Q_MAX_LEN_FILE_NAME+1]; +extern char g_qc_flags[Q_MAX_LEN_FLAGS+1]; +extern char g_link_flags[Q_MAX_LEN_FLAGS+1]; +extern char g_ld_library_path[Q_MAX_LEN_PATH+1]; + +void +free_globals( + void + ) +{ + if ( g_L_Q != NULL ) { lua_close(g_L_Q); g_L_Q = NULL; } +} + +void +zero_globals( + void + ) +{ + g_halt = false; + + memset(g_q_data_dir, '\0', Q_MAX_LEN_FILE_NAME+1); + memset(g_q_metadata_file, '\0', Q_MAX_LEN_FILE_NAME+1); + memset(g_qc_flags, '\0', Q_MAX_LEN_FLAGS+1); + memset(g_link_flags, '\0', Q_MAX_LEN_FLAGS+1); + memset(g_ld_library_path, '\0', Q_MAX_LEN_PATH+1); + + //------------ + const char *str = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ=/_:."; + /* Note that I added period to allow FileNames to be passed as args */ + /* Not sure if that is good practice */ + memset(g_valid_chars_in_url, '\0', 256); + for ( char *cptr = (char *)str; *cptr != '\0'; cptr++ ) { + g_valid_chars_in_url[(uint8_t)(*cptr)] = true; + } + +} + +int +init_lua( + void + ) +{ + int status = 0; + g_L_Q = luaL_newstate(); if ( g_L_Q == NULL ) { go_BYE(-1); } + luaL_openlibs(g_L_Q); + + status = luaL_dostring(g_L_Q, "Q = require 'Q'; "); + mcr_chk_lua_rslt(status); + if ( ( g_q_metadata_file != NULL ) && ( *g_q_metadata_file != '\0' ) ) { + status = luaL_dostring(g_L_Q, "Q.restore()"); + mcr_chk_lua_rslt(status); + } + +BYE: + return status; +} diff --git a/pool/shard002/C/0060950_CWE121_Stack_Based_Buffer_Overflow__CWE805_char_alloca_ncpy_54e.c b/pool/shard002/C/0060950_CWE121_Stack_Based_Buffer_Overflow__CWE805_char_alloca_ncpy_54e.c new file mode 100644 index 0000000000000000000000000000000000000000..075122ba8f07da230d628a65f5341dd88eeeae5f --- /dev/null +++ b/pool/shard002/C/0060950_CWE121_Stack_Based_Buffer_Overflow__CWE805_char_alloca_ncpy_54e.c @@ -0,0 +1,56 @@ +/* TEMPLATE GENERATED TESTCASE FILE +Filename: CWE121_Stack_Based_Buffer_Overflow__CWE805_char_alloca_ncpy_54e.c +Label Definition File: CWE121_Stack_Based_Buffer_Overflow__CWE805.string.label.xml +Template File: sources-sink-54e.tmpl.c +*/ +/* + * @description + * CWE: 121 Stack Based Buffer Overflow + * BadSource: Set data pointer to the bad buffer + * GoodSource: Set data pointer to the good buffer + * Sink: ncpy + * BadSink : Copy string to data using strncpy + * Flow Variant: 54 Data flow: data passed as an argument from one function through three others to a fifth; all five functions are in different source files + * + * */ + +#include "std_testcase.h" + +#include + +/* all the sinks are the same, we just want to know where the hit originated if a tool flags one */ + +#ifndef OMITBAD + +void CWE121_Stack_Based_Buffer_Overflow__CWE805_char_alloca_ncpy_54e_badSink(char * data) +{ + { + char source[100]; + memset(source, 'C', 100-1); /* fill with 'C's */ + source[100-1] = '\0'; /* null terminate */ + /* POTENTIAL FLAW: Possible buffer overflow if the size of data is less than the length of source */ + strncpy(data, source, 100-1); + data[100-1] = '\0'; /* Ensure the destination buffer is null terminated */ + printLine(data); + } +} + +#endif /* OMITBAD */ + +#ifndef OMITGOOD + +/* goodG2B uses the GoodSource with the BadSink */ +void CWE121_Stack_Based_Buffer_Overflow__CWE805_char_alloca_ncpy_54e_goodG2BSink(char * data) +{ + { + char source[100]; + memset(source, 'C', 100-1); /* fill with 'C's */ + source[100-1] = '\0'; /* null terminate */ + /* POTENTIAL FLAW: Possible buffer overflow if the size of data is less than the length of source */ + strncpy(data, source, 100-1); + data[100-1] = '\0'; /* Ensure the destination buffer is null terminated */ + printLine(data); + } +} + +#endif /* OMITGOOD */ diff --git a/pool/shard002/C/0060953_perf_event_agent.c b/pool/shard002/C/0060953_perf_event_agent.c new file mode 100644 index 0000000000000000000000000000000000000000..4ff31fbeb7f1a30268212952d1054cc4cf6098db --- /dev/null +++ b/pool/shard002/C/0060953_perf_event_agent.c @@ -0,0 +1,205 @@ +/* + * self.c - example of a simple self monitoring task + * + * Copyright (c) 2009 Google, Inc + * Contributed by Stephane Eranian + * + * Based on: + * Copyright (c) 2002-2007 Hewlett-Packard Development Company, L.P. + * Contributed by Stephane Eranian + * + * 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. + * + * This file is part of libpfm, a performance monitoring support library for + * applications on Linux. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include "perf_util.h" + +#include "jvmti.h" +#include "jni.h" + + +/*static const char *gen_events[]={ + "PERF_COUNT_HW_CPU_CYCLES", + "PERF_COUNT_HW_INSTRUCTIONS", + NULL +};*/ + +static perf_event_desc_t* perfevent_fds = NULL; +static int perfevent_num_fds = 0; +static char* perfevent_events = NULL; + + +void perfevent_initialize(char*events) { + int i, ret; + perfevent_events = strdup(events); + + /* + * Initialize pfm library (required before we can use it) + */ + ret = pfm_initialize(); + if (ret != PFM_SUCCESS) + errx(1, "Cannot initialize library: %s", pfm_strerror(ret)); + + ret = perf_setup_list_events(events, &perfevent_fds, &perfevent_num_fds); + if (ret || !perfevent_num_fds) + errx(1, "cannot setup events"); + + perfevent_fds[0].fd = -1; + for(i=0; i < perfevent_num_fds; i++) { + /* request timing information necessary for scaling */ + perfevent_fds[i].hw.read_format = PERF_FORMAT_SCALE; + + perfevent_fds[i].hw.disabled = (i == 0); /* do not start now */ + perfevent_fds[i].hw.inherit = 1; /* pass on to child threads */ + + /* each event is in an independent group (multiplexing likely) */ + perfevent_fds[i].fd = perf_event_open(&perfevent_fds[i].hw, 0, -1, perfevent_fds[0].fd, 0); + if (perfevent_fds[i].fd == -1) + err(1, "cannot open event %d", i); + } +} +void perfevent_enable() { + int ret; + /* + * start counting now + */ + ret = ioctl(perfevent_fds[0].fd, PERF_EVENT_IOC_ENABLE, 0); + if (ret) + err(1, "ioctl(enable) failed"); +} +void perfevent_disable() { + int ret; + /* + * stop counting + */ + ret = ioctl(perfevent_fds[0].fd, PERF_EVENT_IOC_DISABLE, 0); + if (ret) + err(1, "ioctl(disable) failed"); +} +void perfevent_reset() { + int i, ret; + /* + * stop counting + */ + for(i=0; i < perfevent_num_fds; i++) { + ret = ioctl(perfevent_fds[i].fd, PERF_EVENT_IOC_RESET, 0); + if (ret) + err(1, "ioctl(reset) failed"); + } +} + +void perfevent_read() { + int i, ret; + uint64_t values[3]; + /* + * now read the results. We use pfp_event_count because + * libpfm guarantees that counters for the events always + * come first. + */ + memset(values, 0, sizeof(values)); + + fprintf(stderr, "============================ Tabulate Statistics ============================\n"); + for (i=0; i < perfevent_num_fds; i++) { + fprintf(stderr, "%s ", perfevent_fds[i].name); + } + fprintf(stderr, "\n"); + for (i=0; i < perfevent_num_fds; i++) { + uint64_t val; + double ratio; + + ret = read(perfevent_fds[i].fd, values, sizeof(values)); + if (ret < sizeof(values)) { + if (ret == -1) + err(1, "cannot read results: %s", strerror(errno)); + else + warnx("could not read event%d", i); + } + /* + * scaling is systematic because we may be sharing the PMU and + * thus may be multiplexed + */ + val = perf_scale(values); + ratio = perf_scale_ratio(values); + + if (ratio == 1.0) + fprintf(stderr, "%lld ", (long long int) val); + else + if (ratio == 0.0) + fprintf(stderr, "NO_VALUE "); + else + fprintf(stderr, "%lld-SCALED-%.2f%% ", (long long int) val, ratio*100.0); + } + fprintf(stderr, "\n=============================================================================\n"); +} +void perfevent_cleanup() { + int i; + for (i=0; i < perfevent_num_fds; i++) { + close(perfevent_fds[i].fd); + } + free(perfevent_fds); + perfevent_fds = NULL; + perfevent_num_fds = 0; +} + +/* JVMTI Functions */ +JNIEXPORT jint JNICALL +Agent_OnLoad(JavaVM *vm, char *options, void *reserved) { + perfevent_initialize(options); + return JNI_OK; +} +JNIEXPORT void JNICALL +Agent_OnUnload(JavaVM *vm) { + perfevent_cleanup(); +} + +/* JNI Functions */ +JNIEXPORT void JNICALL Java_probe_PerfEventProbe_begin + (JNIEnv *env, jobject o, jstring benchmark, jint iteration, jboolean warmup) { + perfevent_enable(); +} +JNIEXPORT void JNICALL Java_probe_PerfEventProbe_end + (JNIEnv *env, jobject o, jstring benchmark, jint iteration, jboolean warmup) { + perfevent_disable(); +} +JNIEXPORT void JNICALL Java_probe_PerfEventProbe_report + (JNIEnv *env, jobject o, jstring benchmark, jint iteration, jboolean warmup) { + perfevent_read(); + perfevent_reset(); +} +JNIEXPORT void JNICALL Java_probe_PerfEventProbe_reinitialize + (JNIEnv *env, jobject o) { + perfevent_cleanup(); + perfevent_initialize(perfevent_events); +} diff --git a/pool/shard002/C/0060956_label.c b/pool/shard002/C/0060956_label.c new file mode 100644 index 0000000000000000000000000000000000000000..dea15871f61af48494cd1e3569e69f1565c139bb --- /dev/null +++ b/pool/shard002/C/0060956_label.c @@ -0,0 +1,100 @@ +/* SPDX-License-Identifier: LGPL-2.1-or-later */ + +#include +#include +#include + +#include "btrfs-util.h" +#include "fs-util.h" +#include "label.h" +#include "macro.h" +#include "selinux-util.h" +#include "smack-util.h" + +int label_fix_container(const char *path, const char *inside_path, LabelFixFlags flags) { + int r, q; + + r = mac_selinux_fix_container(path, inside_path, flags); + q = mac_smack_fix_container(path, inside_path, flags); + + if (r < 0) + return r; + if (q < 0) + return q; + + return 0; +} + +int symlink_label(const char *old_path, const char *new_path) { + int r; + + assert(old_path); + assert(new_path); + + r = mac_selinux_create_file_prepare(new_path, S_IFLNK); + if (r < 0) + return r; + + r = RET_NERRNO(symlink(old_path, new_path)); + mac_selinux_create_file_clear(); + + if (r < 0) + return r; + + return mac_smack_fix(new_path, 0); +} + +int symlink_atomic_label(const char *from, const char *to) { + int r; + + assert(from); + assert(to); + + r = mac_selinux_create_file_prepare(to, S_IFLNK); + if (r < 0) + return r; + + r = symlink_atomic(from, to); + mac_selinux_create_file_clear(); + + if (r < 0) + return r; + + return mac_smack_fix(to, 0); +} + +int mknod_label(const char *pathname, mode_t mode, dev_t dev) { + int r; + + assert(pathname); + + r = mac_selinux_create_file_prepare(pathname, mode); + if (r < 0) + return r; + + r = RET_NERRNO(mknod(pathname, mode, dev)); + mac_selinux_create_file_clear(); + + if (r < 0) + return r; + + return mac_smack_fix(pathname, 0); +} + +int btrfs_subvol_make_label(const char *path) { + int r; + + assert(path); + + r = mac_selinux_create_file_prepare(path, S_IFDIR); + if (r < 0) + return r; + + r = btrfs_subvol_make(path); + mac_selinux_create_file_clear(); + + if (r < 0) + return r; + + return mac_smack_fix(path, 0); +} diff --git a/pool/shard002/C/0060960_sf_sincos.c b/pool/shard002/C/0060960_sf_sincos.c new file mode 100644 index 0000000000000000000000000000000000000000..e192b4b449488fe8a67fb45421f8401e53b20476 --- /dev/null +++ b/pool/shard002/C/0060960_sf_sincos.c @@ -0,0 +1,39 @@ + +/* @(#)z_sinf.c 1.0 98/08/13 */ +/****************************************************************** + * Sine + * + * Input: + * x - floating point value + * + * Output: + * sine of x + * + * Description: + * This routine returns the sine of x. + * + *****************************************************************/ + +#include "fdlibm.h" +#include "zmath.h" + +void +_DEFUN (sincosf, (x, sinx, cosx), + float x _AND + float *sinx _AND + float *cosx) +{ + *sinx = sin (x); + *cosx = cos (x); +} + +#ifdef _DOUBLE_IS_32BITS + +void +sincos (double x, double *sinx, double *cosx) +{ + *sinx = (double) sinf ((float) x); + *cosx = (double) cosf ((float) x); +} + +#endif /* defined(_DOUBLE_IS_32BITS) */ diff --git a/pool/shard002/C/0060966_caiaq-midi.c b/pool/shard002/C/0060966_caiaq-midi.c new file mode 100644 index 0000000000000000000000000000000000000000..793ca20ce349c502732c7f160e0401dff9f13f47 --- /dev/null +++ b/pool/shard002/C/0060966_caiaq-midi.c @@ -0,0 +1,177 @@ +/* + * Copyright (c) 2006,2007 Daniel Mack + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +*/ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "caiaq-device.h" +#include "caiaq-midi.h" + + +static int snd_usb_caiaq_midi_input_open(struct snd_rawmidi_substream *substream) +{ + return 0; +} + +static int snd_usb_caiaq_midi_input_close(struct snd_rawmidi_substream *substream) +{ + return 0; +} + +static void snd_usb_caiaq_midi_input_trigger(struct snd_rawmidi_substream *substream, int up) +{ + struct snd_usb_caiaqdev *dev = substream->rmidi->private_data; + + if (!dev) + return; + + dev->midi_receive_substream = up ? substream : NULL; +} + + +static int snd_usb_caiaq_midi_output_open(struct snd_rawmidi_substream *substream) +{ + return 0; +} + +static int snd_usb_caiaq_midi_output_close(struct snd_rawmidi_substream *substream) +{ + return 0; +} + +static void snd_usb_caiaq_midi_send(struct snd_usb_caiaqdev *dev, + struct snd_rawmidi_substream *substream) +{ + int len, ret; + + dev->midi_out_buf[0] = EP1_CMD_MIDI_WRITE; + dev->midi_out_buf[1] = 0; /* port */ + len = snd_rawmidi_transmit_peek(substream, dev->midi_out_buf+3, EP1_BUFSIZE-3); + + if (len <= 0) + return; + + dev->midi_out_buf[2] = len; + dev->midi_out_urb.transfer_buffer_length = len+3; + + ret = usb_submit_urb(&dev->midi_out_urb, GFP_ATOMIC); + if (ret < 0) + log("snd_usb_caiaq_midi_send(%p): usb_submit_urb() failed, %d\n", + substream, ret); +} + +static void snd_usb_caiaq_midi_output_trigger(struct snd_rawmidi_substream *substream, int up) +{ + struct snd_usb_caiaqdev *dev = substream->rmidi->private_data; + + if (dev->midi_out_substream != NULL) + return; + + if (!up) { + dev->midi_out_substream = NULL; + return; + } + + dev->midi_out_substream = substream; + snd_usb_caiaq_midi_send(dev, substream); +} + + +static struct snd_rawmidi_ops snd_usb_caiaq_midi_output = +{ + .open = snd_usb_caiaq_midi_output_open, + .close = snd_usb_caiaq_midi_output_close, + .trigger = snd_usb_caiaq_midi_output_trigger, +}; + +static struct snd_rawmidi_ops snd_usb_caiaq_midi_input = +{ + .open = snd_usb_caiaq_midi_input_open, + .close = snd_usb_caiaq_midi_input_close, + .trigger = snd_usb_caiaq_midi_input_trigger, +}; + +void snd_usb_caiaq_midi_handle_input(struct snd_usb_caiaqdev *dev, + int port, const char *buf, int len) +{ + if (!dev->midi_receive_substream) + return; + + snd_rawmidi_receive(dev->midi_receive_substream, buf, len); +} + +int __devinit snd_usb_caiaq_midi_init(struct snd_usb_caiaqdev *device) +{ + int ret; + struct snd_rawmidi *rmidi; + + ret = snd_rawmidi_new(device->chip.card, device->product_name, 0, + device->spec.num_midi_out, + device->spec.num_midi_in, + &rmidi); + + if (ret < 0) + return ret; + + strcpy(rmidi->name, device->product_name); + + rmidi->info_flags = SNDRV_RAWMIDI_INFO_DUPLEX; + rmidi->private_data = device; + + if (device->spec.num_midi_out > 0) { + rmidi->info_flags |= SNDRV_RAWMIDI_INFO_OUTPUT; + snd_rawmidi_set_ops(rmidi, SNDRV_RAWMIDI_STREAM_OUTPUT, + &snd_usb_caiaq_midi_output); + } + + if (device->spec.num_midi_in > 0) { + rmidi->info_flags |= SNDRV_RAWMIDI_INFO_INPUT; + snd_rawmidi_set_ops(rmidi, SNDRV_RAWMIDI_STREAM_INPUT, + &snd_usb_caiaq_midi_input); + } + + device->rmidi = rmidi; + + return 0; +} + +void snd_usb_caiaq_midi_output_done(struct urb* urb) +{ + struct snd_usb_caiaqdev *dev = urb->context; + char *buf = urb->transfer_buffer; + + if (urb->status != 0) + return; + + if (!dev->midi_out_substream) + return; + + snd_rawmidi_transmit_ack(dev->midi_out_substream, buf[2]); + dev->midi_out_substream = NULL; + snd_usb_caiaq_midi_send(dev, dev->midi_out_substream); +} + diff --git a/pool/shard002/C/0060982_str_add.c b/pool/shard002/C/0060982_str_add.c new file mode 100644 index 0000000000000000000000000000000000000000..56202de5ae7eaf5b2fa8637666c21fec6458ae29 --- /dev/null +++ b/pool/shard002/C/0060982_str_add.c @@ -0,0 +1,19 @@ +#include +#include "wich.h" +#include "refcounting.h" + +int main(int ____c, char *____v[]) +{ + setup_error_handlers(); + ENTER(); + STRING(hello); + STRING(world); + hello = String_new("hello"); + REF((void *)hello); + world = String_new("world"); + REF((void *)world); + print_string(String_add(hello,world)); + EXIT(); + return 0; +} + diff --git a/pool/shard002/C/0060988_server_demo.c b/pool/shard002/C/0060988_server_demo.c new file mode 100644 index 0000000000000000000000000000000000000000..34dffb541a7ad151e7a8f1d242f7597edb04f21b --- /dev/null +++ b/pool/shard002/C/0060988_server_demo.c @@ -0,0 +1,34 @@ +#include +#include + +static void process_request(int fd) +{ + char str[20]; + char s[20]; + int len, i, j; + read(fd, str, 20); + len = strlen(str); + + for(i = 0, j = len; j >= 0; j++, i++) + s[j] = str[i]; + + write(fd, s, len); +} + +int main(void) +{ + int sock, fd; + + sock = make_server_socket(30000); + if (-1 == sock) + exit(1); + + while(1) { + fd = accept(sock, NULL, NULL); + if (-1 == fd) + break; + + process_request(fd); + close(fd); + } +} \ No newline at end of file diff --git a/pool/shard002/C/0060989_dirname.c b/pool/shard002/C/0060989_dirname.c new file mode 100644 index 0000000000000000000000000000000000000000..53d0bdc7d9ddd844fc62d46d18c6fccbd288ddcf --- /dev/null +++ b/pool/shard002/C/0060989_dirname.c @@ -0,0 +1,114 @@ +/* dirname -- strip suffix from file name + + Copyright (C) 1990-1997, 1999-2002, 2004-2009 Free Software Foundation, Inc. + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . */ + +/* Written by David MacKenzie and Jim Meyering. */ + +#include +#include +#include +#include + +#include "system.h" +#include "long-options.h" +#include "error.h" +#include "quote.h" + +/* The official name of this program (e.g., no `g' prefix). */ +#define PROGRAM_NAME "dirname" + +#define AUTHORS \ + proper_name ("David MacKenzie"), \ + proper_name ("Jim Meyering") + +void +usage (int status) +{ + if (status != EXIT_SUCCESS) + fprintf (stderr, _("Try `%s --help' for more information.\n"), + program_name); + else + { + printf (_("\ +Usage: %s NAME\n\ + or: %s OPTION\n\ +"), + program_name, program_name); + fputs (_("\ +Print NAME with its trailing /component removed; if NAME contains no /'s,\n\ +output `.' (meaning the current directory).\n\ +\n\ +"), stdout); + fputs (HELP_OPTION_DESCRIPTION, stdout); + fputs (VERSION_OPTION_DESCRIPTION, stdout); + printf (_("\ +\n\ +Examples:\n\ + %s /usr/bin/sort Output \"/usr/bin\".\n\ + %s stdio.h Output \".\".\n\ +"), + program_name, program_name); + emit_bug_reporting_address (); + } + exit (status); +} + +int +main (int argc, char **argv) +{ + static char const dot = '.'; + char const *result; + size_t len; + + initialize_main (&argc, &argv); + set_program_name (argv[0]); + setlocale (LC_ALL, ""); + bindtextdomain (PACKAGE, LOCALEDIR); + textdomain (PACKAGE); + + atexit (close_stdout); + + parse_long_options (argc, argv, PROGRAM_NAME, PACKAGE_NAME, Version, + usage, AUTHORS, (char const *) NULL); + if (getopt_long (argc, argv, "+", NULL, NULL) != -1) + usage (EXIT_FAILURE); + + if (argc < optind + 1) + { + error (0, 0, _("missing operand")); + usage (EXIT_FAILURE); + } + + if (optind + 1 < argc) + { + error (0, 0, _("extra operand %s"), quote (argv[optind + 1])); + usage (EXIT_FAILURE); + } + + result = argv[optind]; + len = dir_len (result); + + if (! len) + { + result = ˙ + len = 1; + } + + fwrite (result, 1, len, stdout); + putchar ('\n'); + + exit (EXIT_SUCCESS); +} diff --git a/pool/shard002/C/0061027_intr.c b/pool/shard002/C/0061027_intr.c new file mode 100644 index 0000000000000000000000000000000000000000..b6499070c0c6d20d1c582633dbc2ca665e1c49d0 --- /dev/null +++ b/pool/shard002/C/0061027_intr.c @@ -0,0 +1,168 @@ +/* + * intr.c: Interrupt handling for SVM. + * Copyright (c) 2005, AMD Inc. + * Copyright (c) 2004, Intel Corporation. + * + * This program is free software; you can redistribute it and/or modify it + * under the terms and conditions of the GNU General Public License, + * version 2, as published by the Free Software Foundation. + * + * This program is distributed in the hope it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + * + * You should have received a copy of the GNU General Public License along with + * this program; if not, write to the Free Software Foundation, Inc., 59 Temple + * Place - Suite 330, Boston, MA 02111-1307 USA. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +static void svm_inject_nmi(struct vcpu *v) +{ + struct vmcb_struct *vmcb = v->arch.hvm_svm.vmcb; + eventinj_t event; + + event.bytes = 0; + event.fields.v = 1; + event.fields.type = X86_EVENTTYPE_NMI; + event.fields.vector = 2; + + ASSERT(vmcb->eventinj.fields.v == 0); + vmcb->eventinj = event; + + /* + * SVM does not virtualise the NMI mask, so we emulate it by intercepting + * the next IRET and blocking NMI injection until the intercept triggers. + */ + vmcb->general1_intercepts |= GENERAL1_INTERCEPT_IRET; +} + +static void svm_inject_extint(struct vcpu *v, int vector) +{ + struct vmcb_struct *vmcb = v->arch.hvm_svm.vmcb; + eventinj_t event; + + event.bytes = 0; + event.fields.v = 1; + event.fields.type = X86_EVENTTYPE_EXT_INTR; + event.fields.vector = vector; + + ASSERT(vmcb->eventinj.fields.v == 0); + vmcb->eventinj = event; +} + +static void enable_intr_window(struct vcpu *v, struct hvm_intack intack) +{ + struct vmcb_struct *vmcb = v->arch.hvm_svm.vmcb; + vintr_t intr; + + ASSERT(intack.source != hvm_intsrc_none); + + HVMTRACE_3D(INTR_WINDOW, intack.vector, intack.source, + vmcb->eventinj.fields.v?vmcb->eventinj.fields.vector:-1); + + /* + * Create a dummy virtual interrupt to intercept as soon as the + * guest can accept the real interrupt. + * + * TODO: Better NMI handling. We need a way to skip a MOV SS interrupt + * shadow. This is hard to do without hardware support. We should also + * track 'NMI blocking' from NMI injection until IRET. This can be done + * quite easily in software by intercepting the unblocking IRET. + */ + intr = vmcb->vintr; + intr.fields.irq = 1; + intr.fields.vector = 0; + intr.fields.prio = intack.vector >> 4; + intr.fields.ign_tpr = (intack.source != hvm_intsrc_lapic); + vmcb->vintr = intr; + vmcb->general1_intercepts |= GENERAL1_INTERCEPT_VINTR; +} + +asmlinkage void svm_intr_assist(void) +{ + struct vcpu *v = current; + struct vmcb_struct *vmcb = v->arch.hvm_svm.vmcb; + struct hvm_intack intack; + + /* Crank the handle on interrupt state. */ + pt_update_irq(v); + hvm_dirq_assist(v); + + do { + intack = hvm_vcpu_has_pending_irq(v); + if ( likely(intack.source == hvm_intsrc_none) ) + return; + + /* + * Pending IRQs must be delayed if: + * 1. An event is already pending. This is despite the fact that SVM + * provides a VINTR delivery method quite separate from the EVENTINJ + * mechanism. The event delivery can arbitrarily delay the injection + * of the vintr (for example, if the exception is handled via an + * interrupt gate, hence zeroing RFLAGS.IF). In the meantime: + * - the vTPR could be modified upwards, so we need to wait until + * the exception is delivered before we can safely decide that an + * interrupt is deliverable; and + * - the guest might look at the APIC/PIC state, so we ought not to + * have cleared the interrupt out of the IRR. + * 2. The IRQ is masked. + */ + if ( unlikely(vmcb->eventinj.fields.v) || + hvm_interrupt_blocked(v, intack) ) + { + enable_intr_window(v, intack); + return; + } + + intack = hvm_vcpu_ack_pending_irq(v, intack); + } while ( intack.source == hvm_intsrc_none ); + + if ( intack.source == hvm_intsrc_nmi ) + { + svm_inject_nmi(v); + } + else + { + HVMTRACE_2D(INJ_VIRQ, intack.vector, /*fake=*/ 0); + svm_inject_extint(v, intack.vector); + pt_intr_post(v, intack); + } + + /* Is there another IRQ to queue up behind this one? */ + intack = hvm_vcpu_has_pending_irq(v); + if ( unlikely(intack.source != hvm_intsrc_none) ) + enable_intr_window(v, intack); +} + +/* + * Local variables: + * mode: C + * c-set-style: "BSD" + * c-basic-offset: 4 + * tab-width: 4 + * indent-tabs-mode: nil + * End: + */ diff --git a/pool/shard002/C/0061029_hypervisor.c b/pool/shard002/C/0061029_hypervisor.c new file mode 100644 index 0000000000000000000000000000000000000000..fa112e1c2c1f460e8a67826f6eb97b31c03f7164 --- /dev/null +++ b/pool/shard002/C/0061029_hypervisor.c @@ -0,0 +1,81 @@ +/* + * Common hypervisor code + * + * Copyright (C) 2008, VMware, Inc. + * Author : Alok N Kataria + * + * 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., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + */ + +#include +#include +#include + +/* + * Hypervisor detect order. This is specified explicitly here because + * some hypervisors might implement compatibility modes for other + * hypervisors and therefore need to be detected in specific sequence. + */ +static const __initconst struct hypervisor_x86 * const hypervisors[] = +{ + &x86_hyper_vmware, + &x86_hyper_ms_hyperv, +<<<<<<< HEAD +#ifdef CONFIG_XEN_PVHVM + &x86_hyper_xen_hvm, +#endif +======= +>>>>>>> 296c66da8a02d52243f45b80521febece5ed498a +}; + +const struct hypervisor_x86 *x86_hyper; +EXPORT_SYMBOL(x86_hyper); + +static inline void __init +detect_hypervisor_vendor(void) +{ + const struct hypervisor_x86 *h, * const *p; + + for (p = hypervisors; p < hypervisors + ARRAY_SIZE(hypervisors); p++) { + h = *p; + if (h->detect()) { + x86_hyper = h; + printk(KERN_INFO "Hypervisor detected: %s\n", h->name); + break; + } + } +} + +void __cpuinit init_hypervisor(struct cpuinfo_x86 *c) +{ + if (x86_hyper && x86_hyper->set_cpu_features) + x86_hyper->set_cpu_features(c); +} + +void __init init_hypervisor_platform(void) +{ + + detect_hypervisor_vendor(); + + if (!x86_hyper) + return; + + init_hypervisor(&boot_cpu_data); + + if (x86_hyper->init_platform) + x86_hyper->init_platform(); +} diff --git a/pool/shard002/C/0061030_FLA_Copyt_t.c b/pool/shard002/C/0061030_FLA_Copyt_t.c new file mode 100644 index 0000000000000000000000000000000000000000..4a04b4a8c5f41d0f6b1bbfedfa252936d7c9c346 --- /dev/null +++ b/pool/shard002/C/0061030_FLA_Copyt_t.c @@ -0,0 +1,48 @@ +/* + + Copyright (C) 2014, The University of Texas at Austin + + This file is part of libflame and is available under the 3-Clause + BSD license, which can be found in the LICENSE file at the top-level + directory, or at http://opensource.org/licenses/BSD-3-Clause + +*/ + +#include "FLAME.h" + +FLA_Error FLA_Copyt_t( FLA_Obj A, FLA_Obj B, fla_copyt_t* cntl ) +{ + FLA_Error r_val = FLA_SUCCESS; + + if ( FLA_Cntl_variant( cntl ) == FLA_SUBPROBLEM ) + { + r_val = FLA_Copyt_t_task( A, B, cntl ); + } + else if ( FLA_Cntl_variant( cntl ) == FLA_BLOCKED_VARIANT1 ) + { + r_val = FLA_Copyt_t_blk_var1( A, B, cntl ); + } +#ifdef FLA_ENABLE_NON_CRITICAL_CODE + else if ( FLA_Cntl_variant( cntl ) == FLA_BLOCKED_VARIANT2 ) + { + r_val = FLA_Copyt_t_blk_var2( A, B, cntl ); + } +#endif + else if ( FLA_Cntl_variant( cntl ) == FLA_BLOCKED_VARIANT3 ) + { + r_val = FLA_Copyt_t_blk_var3( A, B, cntl ); + } +#ifdef FLA_ENABLE_NON_CRITICAL_CODE + else if ( FLA_Cntl_variant( cntl ) == FLA_BLOCKED_VARIANT4 ) + { + r_val = FLA_Copyt_t_blk_var4( A, B, cntl ); + } +#endif + else + { + r_val = FLA_Check_error_code( FLA_NOT_YET_IMPLEMENTED ); + } + + return r_val; +} + diff --git a/pool/shard002/C/0061032_memchr.c b/pool/shard002/C/0061032_memchr.c new file mode 100644 index 0000000000000000000000000000000000000000..f6708fd9174af8886aa7b7221bb08b81e59ced8c --- /dev/null +++ b/pool/shard002/C/0061032_memchr.c @@ -0,0 +1,162 @@ +/* Copyright (C) 1991-2017 Free Software Foundation, Inc. + This file is part of the GNU C Library. + Based on strlen implementation by Torbjorn Granlund (tege@sics.se), + with help from Dan Sahlin (dan@sics.se) and + commentary by Jim Blandy (jimb@ai.mit.edu); + adaptation to memchr suggested by Dick Karpinski (dick@cca.ucsf.edu), + and implemented by Roland McGrath (roland@ai.mit.edu). + + 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 + . */ + +#ifndef _LIBC +# include +#endif + +#include + +#include + +#include + +#undef __memchr +#ifdef _LIBC +# undef memchr +#endif + +#ifndef weak_alias +# define __memchr memchr +#endif + +#ifndef MEMCHR +# define MEMCHR __memchr +#endif + +/* Search no more than N bytes of S for C. */ +void * +MEMCHR (void const *s, int c_in, size_t n) +{ + /* On 32-bit hardware, choosing longword to be a 32-bit unsigned + long instead of a 64-bit uintmax_t tends to give better + performance. On 64-bit hardware, unsigned long is generally 64 + bits already. Change this typedef to experiment with + performance. */ + typedef unsigned long int longword; + + const unsigned char *char_ptr; + const longword *longword_ptr; + longword repeated_one; + longword repeated_c; + unsigned char c; + + c = (unsigned char) c_in; + + /* Handle the first few bytes by reading one byte at a time. + Do this until CHAR_PTR is aligned on a longword boundary. */ + for (char_ptr = (const unsigned char *) s; + n > 0 && (size_t) char_ptr % sizeof (longword) != 0; + --n, ++char_ptr) + if (*char_ptr == c) + return (void *) char_ptr; + + longword_ptr = (const longword *) char_ptr; + + /* All these elucidatory comments refer to 4-byte longwords, + but the theory applies equally well to any size longwords. */ + + /* Compute auxiliary longword values: + repeated_one is a value which has a 1 in every byte. + repeated_c has c in every byte. */ + repeated_one = 0x01010101; + repeated_c = c | (c << 8); + repeated_c |= repeated_c << 16; + if (0xffffffffU < (longword) -1) + { + repeated_one |= repeated_one << 31 << 1; + repeated_c |= repeated_c << 31 << 1; + if (8 < sizeof (longword)) + { + size_t i; + + for (i = 64; i < sizeof (longword) * 8; i *= 2) + { + repeated_one |= repeated_one << i; + repeated_c |= repeated_c << i; + } + } + } + + /* Instead of the traditional loop which tests each byte, we will test a + longword at a time. The tricky part is testing if *any of the four* + bytes in the longword in question are equal to c. We first use an xor + with repeated_c. This reduces the task to testing whether *any of the + four* bytes in longword1 is zero. + + We compute tmp = + ((longword1 - repeated_one) & ~longword1) & (repeated_one << 7). + That is, we perform the following operations: + 1. Subtract repeated_one. + 2. & ~longword1. + 3. & a mask consisting of 0x80 in every byte. + Consider what happens in each byte: + - If a byte of longword1 is zero, step 1 and 2 transform it into 0xff, + and step 3 transforms it into 0x80. A carry can also be propagated + to more significant bytes. + - If a byte of longword1 is nonzero, let its lowest 1 bit be at + position k (0 <= k <= 7); so the lowest k bits are 0. After step 1, + the byte ends in a single bit of value 0 and k bits of value 1. + After step 2, the result is just k bits of value 1: 2^k - 1. After + step 3, the result is 0. And no carry is produced. + So, if longword1 has only non-zero bytes, tmp is zero. + Whereas if longword1 has a zero byte, call j the position of the least + significant zero byte. Then the result has a zero at positions 0, ..., + j-1 and a 0x80 at position j. We cannot predict the result at the more + significant bytes (positions j+1..3), but it does not matter since we + already have a non-zero bit at position 8*j+7. + + So, the test whether any byte in longword1 is zero is equivalent to + testing whether tmp is nonzero. */ + + while (n >= sizeof (longword)) + { + longword longword1 = *longword_ptr ^ repeated_c; + + if ((((longword1 - repeated_one) & ~longword1) + & (repeated_one << 7)) != 0) + break; + longword_ptr++; + n -= sizeof (longword); + } + + char_ptr = (const unsigned char *) longword_ptr; + + /* At this point, we know that either n < sizeof (longword), or one of the + sizeof (longword) bytes starting at char_ptr is == c. On little-endian + machines, we could determine the first such byte without any further + memory accesses, just by looking at the tmp result from the last loop + iteration. But this does not work on big-endian machines. Choose code + that works in both cases. */ + + for (; n > 0; --n, ++char_ptr) + { + if (*char_ptr == c) + return (void *) char_ptr; + } + + return NULL; +} +#ifdef weak_alias +weak_alias (__memchr, memchr) +#endif +libc_hidden_builtin_def (memchr) diff --git a/pool/shard002/C/0061035_cpl_nonsig.c b/pool/shard002/C/0061035_cpl_nonsig.c new file mode 100644 index 0000000000000000000000000000000000000000..cdf76b1cdf668618a7927a5c7dcbb0598a340845 --- /dev/null +++ b/pool/shard002/C/0061035_cpl_nonsig.c @@ -0,0 +1,277 @@ +/* + * $Id: cpl_nonsig.c,v 1.8 2004/08/24 08:58:26 janakj Exp $ + * + * Copyright (C) 2001-2003 FhG Fokus + * + * This file is part of ser, a free SIP server. + * + * ser 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 + * + * For a license to use the ser software under conditions + * other than those described here, or to purchase support for this + * software, please contact iptel.org by e-mail at the following addresses: + * info@iptel.org + * + * ser 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 + * + * History: + * ------- + * 2003-06-27: file created (bogdan) + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "../../mem/shm_mem.h" +#include "../../mem/mem.h" +#include "../../dprint.h" +#include "cpl_nonsig.h" +#include "CPL_tree.h" + + +#define MAX_LOG_FILE_NAME 32 +#define MAX_FD 32 + +#define FILE_NAME_SUFIX ".log" +#define FILE_NAME_SUFIX_LEN (sizeof(FILE_NAME_SUFIX)-1) + +#define LOG_SEPARATOR ": " +#define LOG_SEPARATOR_LEN (sizeof(LOG_SEPARATOR)-1) + +#define DEFAULT_LOG_NAME "default_log" +#define DEFAULT_LOG_NAME_LEN (sizeof(DEFAULT_LOG_NAME)-1) + +#define LOG_TERMINATOR "\n" +#define LOG_TERMINATOR_LEN (sizeof(LOG_TERMINATOR)-1) + + +static char file[MAX_LOG_DIR_SIZE+1+MAX_LOG_FILE_NAME+FILE_NAME_SUFIX_LEN+1]; +static char *file_ptr; + + +static inline void write_log( struct cpl_cmd *cmd) +{ + struct iovec wr_vec[5]; + time_t now; + char *time_ptr; + int fd; + int ret; + + /* build file name (cmd->s1 is the user name)*/ + if (cmd->s1.len>MAX_LOG_FILE_NAME) + cmd->s1.len = MAX_LOG_FILE_NAME; + memcpy(file_ptr, cmd->s1.s, cmd->s1.len ); + memcpy(file_ptr+cmd->s1.len,FILE_NAME_SUFIX,FILE_NAME_SUFIX_LEN); + file_ptr[cmd->s1.len+FILE_NAME_SUFIX_LEN] = 0; + + /* get current date+time -> wr_vec[0] */ + time( &now ); + time_ptr = ctime( &now ); + wr_vec[0].iov_base = time_ptr; + wr_vec[0].iov_len = strlen( time_ptr ); + /* ctime_r adds a \n at the end -> overwrite it with space */ + time_ptr[ wr_vec[0].iov_len-1 ] = ' '; + + /* log name (cmd->s2) -> wr_vec[1] */ + if (cmd->s2.s==0 || cmd->s2.len==0) { + wr_vec[1].iov_base = DEFAULT_LOG_NAME; + wr_vec[1].iov_len = DEFAULT_LOG_NAME_LEN; + } else { + wr_vec[1].iov_base = cmd->s2.s; + wr_vec[1].iov_len = cmd->s2.len; + } + + /* log separator -> wr_vec[2] */ + wr_vec[2].iov_base = LOG_SEPARATOR; + wr_vec[2].iov_len = LOG_SEPARATOR_LEN; + + /* log comment (cmd->s3) -> wr_vec[3] */ + wr_vec[3].iov_base = cmd->s3.s; + wr_vec[3].iov_len = cmd->s3.len; + + /* log terminator -> wr_vec[2] */ + wr_vec[4].iov_base = LOG_TERMINATOR; + wr_vec[4].iov_len = LOG_TERMINATOR_LEN; + + /* [create+]open the file */ + fd = open( file, O_CREAT|O_APPEND|O_WRONLY, 0664); + if (fd==-1) { + LOG(L_ERR,"ERROR:cpl_c:write_log: cannot open file [%s] : %s\n", + file, strerror(errno) ); + return; + } + /* get the log */ + DBG("DEBUG:cpl_c:write_log: logging into [%s]... \n",file); + /* I'm really not interested in the return code for write ;-) */ + while ( (ret=writev( fd, wr_vec, 5))==-1 ) { + if (errno==EINTR) + continue; + LOG(L_ERR,"ERROR:cpl_c:write_log: writing to log file [%s] : %s\n", + file, strerror(errno) ); + } + close (fd); + + shm_free( cmd->s1.s ); +} + + + +static inline void send_mail( struct cpl_cmd *cmd) +{ + char *argv[5]; + int pfd[2]; + pid_t pid; + int i; + + if (pipe(pfd) < 0) { + LOG(L_ERR,"ERROR:cpl_c:send_mail: pipe failed: %s\n",strerror(errno)); + return; + } + + /* even if I haven't fork yet, I push the date on the pipe just to get + * rid of one more malloc + copy */ + if (cmd->s3.len && cmd->s3.s) { + if ( (i=write( pfd[1], cmd->s3.s, cmd->s3.len ))!=cmd->s3.len ) { + LOG(L_ERR,"ERROR:cpl_c:send_mail: write returned error %s\n", + strerror(errno)); + goto error; + } + } + + if ( (pid = fork()) < 0) { + LOG(L_ERR,"ERROR:cpl_c:send_mail: fork failed: %s\n",strerror(errno)); + goto error; + } else if (pid==0) { + /* child -> close all descriptors excepting pfd[0] */ + for (i=3; i < MAX_FD; i++) + if (i!=pfd[0]) + close(i); + if (pfd[0] != STDIN_FILENO) { + dup2(pfd[0], STDIN_FILENO); + close(pfd[0]); + } + + /* set the argument vector*/ + argv[0] = "mail"; + argv[1] = "-s"; + if (cmd->s2.s && cmd->s2.len) { + /* put the subject in this format : <"$subject"\0> */ + if ( (argv[2]=(char*)pkg_malloc(1+cmd->s2.len+1+1))==0) { + LOG(L_ERR,"ERROR:cpl_c:send_mail: cannot get pkg memory\n"); + goto child_exit; + } + argv[2][0] = '\"'; + memcpy(argv[2]+1,cmd->s2.s,cmd->s2.len); + argv[2][cmd->s2.len+1] = '\"'; + argv[2][cmd->s2.len+2] = 0; + } else { + argv[2] = "\"[CPL notification]\""; + } + /* put the TO in <$to\0> format*/ + if ( (argv[3]=(char*)pkg_malloc(cmd->s1.len+1))==0) { + LOG(L_ERR,"ERROR:cpl_c:send_mail: cannot get pkg memory\n"); + goto child_exit; + } + memcpy(argv[3],cmd->s1.s,cmd->s1.len); + argv[3][cmd->s1.len] = 0; + /* last element in vector mist be a null pointer */ + argv[4] = (char*)0; + /* just debug */ + for(i=0;i free the shm */ + shm_free( cmd->s1.s ); + + /* set an alarm -> sending the email shouldn't take more than 10 sec */ + alarm(10); + /* run the external mailer */ + DBG("DEBUG:cpl_c:send_mail: new forked process created -> " + "doing execv..\n"); + execv("/usr/bin/mail",argv); + /* if we got here means execv exit with error :-( */ + LOG(L_ERR,"ERROR:cpl_c:send_mail: execv failed! (%s)\n", + strerror(errno)); +child_exit: + _exit(127); + } + + /* parent -> close both ends of pipe */ + close(pfd[0]); + close(pfd[1]); + return; +error: + shm_free( cmd->s1.s ); + close(pfd[0]); + close(pfd[1]); + return; +} + + + + +void cpl_aux_process( int cmd_out, char *log_dir) +{ + struct cpl_cmd cmd; + int len; + + /* this process will ignore SIGCHLD signal */ + if (signal( SIGCHLD, SIG_IGN)==SIG_ERR) { + LOG(L_ERR,"ERROR:cpl_c:cpl_aux_process: cannot set to IGNORE " + "SIGCHLD signal\n"); + } + + /* set the path for logging */ + if (log_dir) { + strcpy( file, log_dir); + file_ptr = file + strlen(log_dir); + *(file_ptr++) = '/'; + } + + while(1) { + /* let's read a command from pipe */ + len = read( cmd_out, &cmd, sizeof(struct cpl_cmd)); + if (len!=sizeof(struct cpl_cmd)) { + if (len>=0) { + LOG(L_ERR,"ERROR:cpl_aux_processes: truncated message" + " read from pipe! -> discarded\n"); + } else if (errno!=EAGAIN) { + LOG(L_ERR,"ERROR:cpl_aux_process: pipe reading failed: " + " : %s\n",strerror(errno)); + } + sleep(1); + continue; + } + + /* process the command*/ + switch (cmd.code) { + case CPL_LOG_CMD: + write_log( &cmd ); + break; + case CPL_MAIL_CMD: + send_mail( &cmd ); + break; + default: + LOG(L_ERR,"ERROR:cpl_aux_process: unknown command (%d) " + "received! -> ignoring\n",cmd.code); + } /* end switch*/ + + } +} + diff --git a/pool/shard002/C/0061054_atmisv71_4.c b/pool/shard002/C/0061054_atmisv71_4.c new file mode 100644 index 0000000000000000000000000000000000000000..31461e8b131314e31d0df20a6d7c4aab8918f743 --- /dev/null +++ b/pool/shard002/C/0061054_atmisv71_4.c @@ -0,0 +1,131 @@ +/** + * @brief Test buildserver, buildclient and buildtms - server + * + * @file atmisv71_4.c + */ +/* ----------------------------------------------------------------------------- + * Enduro/X Middleware Platform for Distributed Transaction Processing + * Copyright (C) 2009-2016, ATR Baltic, Ltd. All Rights Reserved. + * Copyright (C) 2017-2019, Mavimax, Ltd. All Rights Reserved. + * This software is released under one of the following licenses: + * AGPL (with Java and Go exceptions) or Mavimax's license for commercial use. + * See LICENSE file for full text. + * ----------------------------------------------------------------------------- + * AGPL license: + * + * This program is free software; you can redistribute it and/or modify it under + * the terms of the GNU Affero General Public License, version 3 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 Affero General Public License, version 3 + * for more details. + * + * You should have received a copy of the GNU Affero 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 + * + * ----------------------------------------------------------------------------- + * A commercial use license is available from Mavimax, Ltd + * contact@mavimax.com + * ----------------------------------------------------------------------------- + */ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "test71.h" + +#ifdef __cplusplus +extern "C" +{ +#endif + +/*---------------------------Externs------------------------------------*/ +extern int __write_to_tx_file(char *buf); +/*---------------------------Macros-------------------------------------*/ +/*---------------------------Enums--------------------------------------*/ +/*---------------------------Typedefs-----------------------------------*/ +/*---------------------------Globals------------------------------------*/ +/*---------------------------Statics------------------------------------*/ +/*---------------------------Prototypes---------------------------------*/ + +/** + * This will give some echo back... + */ +void ECHOSV (TPSVCINFO *p_svc) +{ + int ret=EXSUCCEED; + char testbuf[1024]; + UBFH *p_ub = (UBFH *)p_svc->data; + + NDRX_LOG(log_debug, "%s got call", __func__); + + /* Allocate some stuff... */ + if (NULL==(p_ub = (UBFH *)tprealloc((char *)p_ub, 4096))) + { + NDRX_LOG(log_error, "TESTERROR: Failed to allocate 1024 bytes: %s", + tpstrerror(tperrno)); + tpreturn (TPFAIL, 0L, NULL, 0L, 0L); + } + + if (EXFAIL==Bget(p_ub, T_STRING_FLD, 0, testbuf, 0)) + { + NDRX_LOG(log_error, "TESTERROR: Failed to get T_STRING_FLD: %s", + Bstrerror(Berror)); + ret=EXFAIL; + goto out; + } + /* echo back the field */ + if (EXFAIL==Bchg(p_ub, T_STRING_2_FLD, 0, testbuf, 0)) + { + NDRX_LOG(log_error, "TESTERROR: Failed to get T_STRING_2_FLD: %s", + Bstrerror(Berror)); + ret=EXFAIL; + goto out; + } + +out: + tpreturn( ret==EXSUCCEED?TPSUCCESS:TPFAIL, + 0L, + (char *)p_ub, + 0L, + 0L); +} + +/** + * Another service func.. + */ +void ECHO2SV (TPSVCINFO *p_svc) +{ + ECHOSV(p_svc); +} + +/** + * Another service func.. + */ +void SERV (TPSVCINFO *p_svc) +{ + ECHOSV(p_svc); +} + +/** + * Dummy / no service + */ +void DUMFUNC (TPSVCINFO *p_svc) +{ + ECHOSV(p_svc); +} + + +#ifdef __cplusplus +} // extern "C" +#endif + +/* vim: set ts=4 sw=4 et smartindent: */ diff --git a/pool/shard002/C/0061071_ioremap.c b/pool/shard002/C/0061071_ioremap.c new file mode 100644 index 0000000000000000000000000000000000000000..0588e93a4be31fc18112251072e1234978803b3b --- /dev/null +++ b/pool/shard002/C/0061071_ioremap.c @@ -0,0 +1,101 @@ +/* + * arch/cris/mm/ioremap.c + * + * Re-map IO memory to kernel address space so that we can access it. + * Needed for memory-mapped I/O devices mapped outside our normal DRAM + * window (that is, all memory-mapped I/O devices). + * + * (C) Copyright 1995 1996 Linus Torvalds + * CRIS-port by Axis Communications AB + */ + +#include +#include +#include +#include + +/* + * Generic mapping function (not visible outside): + */ + +/* + * Remap an arbitrary physical address space into the kernel virtual + * address space. Needed when the kernel wants to access high addresses + * directly. + * + * NOTE! We need to allow non-page-aligned mappings too: we will obviously + * have to convert them into an offset in a page-aligned mapping, but the + * caller shouldn't need to know that small detail. + */ +void __iomem *__ioremap_prot(unsigned long phys_addr, unsigned long size, pgprot_t prot) +{ + void __iomem *addr; + struct vm_struct *area; + unsigned long offset, last_addr; + + /* Don't allow wraparound or zero size */ + last_addr = phys_addr + size - 1; + + if (!size || last_addr < phys_addr) + { + return NULL; + } + + /* + * Mappings have to be page-aligned + */ + offset = phys_addr & ~PAGE_MASK; + phys_addr &= PAGE_MASK; + size = PAGE_ALIGN(last_addr + 1) - phys_addr; + + /* + * Ok, go for it.. + */ + area = get_vm_area(size, VM_IOREMAP); + + if (!area) + { + return NULL; + } + + addr = (void __iomem *)area->addr; + + if (ioremap_page_range((unsigned long)addr, (unsigned long)addr + size, + phys_addr, prot)) + { + vfree((void __force *)addr); + return NULL; + } + + return (void __iomem *) (offset + (char __iomem *)addr); +} + +void __iomem *__ioremap(unsigned long phys_addr, unsigned long size, unsigned long flags) +{ + return __ioremap_prot(phys_addr, size, + __pgprot(_PAGE_PRESENT | __READABLE | + __WRITEABLE | _PAGE_GLOBAL | + _PAGE_KERNEL | flags)); +} + +/** + * ioremap_nocache - map bus memory into CPU space + * @offset: bus address of the memory + * @size: size of the resource to map + * + * Must be freed with iounmap. + */ + +void __iomem *ioremap_nocache(unsigned long phys_addr, unsigned long size) +{ + return __ioremap(phys_addr | MEM_NON_CACHEABLE, size, 0); +} +EXPORT_SYMBOL(ioremap_nocache); + +void iounmap(volatile void __iomem *addr) +{ + if (addr > high_memory) + { + return vfree((void *) (PAGE_MASK & (unsigned long) addr)); + } +} diff --git a/pool/shard002/C/0061081_CWE401_Memory_Leak__int64_t_realloc_34.c b/pool/shard002/C/0061081_CWE401_Memory_Leak__int64_t_realloc_34.c new file mode 100644 index 0000000000000000000000000000000000000000..1965225674470491b67a5537c6e706d5c5b42f45 --- /dev/null +++ b/pool/shard002/C/0061081_CWE401_Memory_Leak__int64_t_realloc_34.c @@ -0,0 +1,121 @@ +/* TEMPLATE GENERATED TESTCASE FILE +Filename: CWE401_Memory_Leak__int64_t_realloc_34.c +Label Definition File: CWE401_Memory_Leak.c.label.xml +Template File: sources-sinks-34.tmpl.c +*/ +/* + * @description + * CWE: 401 Memory Leak + * BadSource: realloc Allocate data using realloc() + * GoodSource: Allocate data on the stack + * Sinks: + * GoodSink: call free() on data + * BadSink : no deallocation of data + * Flow Variant: 34 Data flow: use of a union containing two methods of accessing the same data (within the same function) + * + * */ + +#include "std_testcase.h" + +#include + +typedef union +{ + int64_t * unionFirst; + int64_t * unionSecond; +} CWE401_Memory_Leak__int64_t_realloc_34_unionType; + +#ifndef OMITBAD + +void CWE401_Memory_Leak__int64_t_realloc_34_bad() +{ + int64_t * data; + CWE401_Memory_Leak__int64_t_realloc_34_unionType myUnion; + data = NULL; + /* POTENTIAL FLAW: Allocate memory on the heap */ + data = (int64_t *)realloc(data, 100*sizeof(int64_t)); + /* Initialize and make use of data */ + data[0] = 5LL; + printLongLongLine(data[0]); + myUnion.unionFirst = data; + { + int64_t * data = myUnion.unionSecond; + /* POTENTIAL FLAW: No deallocation */ + ; /* empty statement needed for some flow variants */ + } +} + +#endif /* OMITBAD */ + +#ifndef OMITGOOD + +/* goodG2B() uses the GoodSource with the BadSink */ +static void goodG2B() +{ + int64_t * data; + CWE401_Memory_Leak__int64_t_realloc_34_unionType myUnion; + data = NULL; + /* FIX: Use memory allocated on the stack with ALLOCA */ + data = (int64_t *)ALLOCA(100*sizeof(int64_t)); + /* Initialize and make use of data */ + data[0] = 5LL; + printLongLongLine(data[0]); + myUnion.unionFirst = data; + { + int64_t * data = myUnion.unionSecond; + /* POTENTIAL FLAW: No deallocation */ + ; /* empty statement needed for some flow variants */ + } +} + +/* goodB2G() uses the BadSource with the GoodSink */ +static void goodB2G() +{ + int64_t * data; + CWE401_Memory_Leak__int64_t_realloc_34_unionType myUnion; + data = NULL; + /* POTENTIAL FLAW: Allocate memory on the heap */ + data = (int64_t *)realloc(data, 100*sizeof(int64_t)); + /* Initialize and make use of data */ + data[0] = 5LL; + printLongLongLine(data[0]); + myUnion.unionFirst = data; + { + int64_t * data = myUnion.unionSecond; + /* FIX: Deallocate memory */ + free(data); + } +} + +void CWE401_Memory_Leak__int64_t_realloc_34_good() +{ + goodG2B(); + goodB2G(); +} + +#endif /* OMITGOOD */ + +/* Below is the main(). It is only used when building this testcase on + its own for testing or for building a binary to use in testing binary + analysis tools. It is not used when compiling all the testcases as one + application, which is how source code analysis tools are tested. */ +#ifdef INCLUDEMAIN + +int main(int argc, char * argv[]) +{ + /* seed randomness */ + srand( (unsigned)time(NULL) ); +#ifndef OMITGOOD + printLine("Calling good()..."); + CWE401_Memory_Leak__int64_t_realloc_34_good(); + printLine("Finished good()"); +#endif /* OMITGOOD */ +#ifndef OMITBAD + printLine("Calling bad()..."); + CWE401_Memory_Leak__int64_t_realloc_34_bad(); + printLine("Finished bad()"); +#endif /* OMITBAD */ + return 0; +} + +#endif diff --git a/pool/shard002/C/0061086_btormem.c b/pool/shard002/C/0061086_btormem.c new file mode 100644 index 0000000000000000000000000000000000000000..cc4e9168c31cd64070bedfb7e656e878afdc4e9b --- /dev/null +++ b/pool/shard002/C/0061086_btormem.c @@ -0,0 +1,211 @@ +/* Boolector: Satisfiablity Modulo Theories (SMT) solver. + * + * Copyright (C) 2007 Robert Daniel Brummayer. + * Copyright (C) 2007-2012 Armin Biere. + * + * All rights reserved. + + * This file is part of Boolector. + * See COPYING for more information on using this software. + * This file is part of Boolector. + */ + +#include "btormem.h" +#include "btorexit.h" + +#include +#include +#include +#include +#include + +/*------------------------------------------------------------------------*/ + +#define BTOR_ABORT_MEM(cond,msg) \ +do { \ + if (cond) \ + { \ + fputs ("[btormem] " msg "\n", stdout); \ + exit (BTOR_ERR_EXIT); \ + } \ +} while (0) + + +#define ADJUST() \ +do { \ + if (mm->maxallocated < mm->allocated) \ + mm->maxallocated = mm->allocated; \ +} while (0) + +/*------------------------------------------------------------------------*/ +/* This enables logging of all memory allocations. + */ +#if 0 +#define BTOR_LOG_MEM(FMT,ARGS...) \ +do { \ + fputs ("[btorlogmem] ", stdout); \ + printf (FMT, ##ARGS); \ + fflush (stdout); \ +} while (0) +#else +#define BTOR_LOG_MEM(...) do { } while (0) +#endif + +/*------------------------------------------------------------------------*/ + +BtorMemMgr * +btor_new_mem_mgr (void) +{ + BtorMemMgr *mm = (BtorMemMgr *) malloc (sizeof (BtorMemMgr)); + BTOR_ABORT_MEM (!mm, "out of memory in 'btor_new_mem_mgr'"); + mm->allocated = 0; + mm->maxallocated = 0; + return mm; +} + +void * +btor_malloc (BtorMemMgr * mm, size_t size) +{ + void *result; + if (!size) return 0; + assert (mm); + result = malloc (size); + BTOR_ABORT_MEM (!result, "out of memory in 'btor_malloc'"); + mm->allocated += size; + ADJUST (); + BTOR_LOG_MEM ("%p malloc %10ld\n", result, size); + return result; +} + +void * +btor_realloc (BtorMemMgr * mm, void *p, size_t old_size, size_t new_size) +{ + void *result; + assert (mm); + assert (!p == !old_size); + assert (mm->allocated >= old_size); + BTOR_LOG_MEM ("%p free %10ld (realloc)\n", p, old_size); + result = realloc (p, new_size); + BTOR_ABORT_MEM (!result, "out of memory in 'btor_realloc'"); + mm->allocated -= old_size; + mm->allocated += new_size; + ADJUST (); + BTOR_LOG_MEM ("%p malloc %10ld (realloc)\n", result, new_size); + return result; +} + +void * +btor_calloc (BtorMemMgr * mm, size_t nobj, size_t size) +{ + size_t bytes = nobj * size; + void *result; + assert (mm); + result = calloc (nobj, size); + BTOR_ABORT_MEM (!result, "out of memory in 'btor_calloc'"); + mm->allocated += bytes; + ADJUST (); + BTOR_LOG_MEM ("%p malloc %10ld (calloc)\n", result, bytes); + return result; +} + +void +btor_free (BtorMemMgr * mm, void *p, size_t freed) +{ + assert (mm); + assert (!p == !freed); + assert (mm->allocated >= freed); + mm->allocated -= freed; + BTOR_LOG_MEM ("%p free %10ld\n", p, freed); + free (p); +} + +char * +btor_strdup (BtorMemMgr * mm, const char *str) +{ + char *res; + + if (str) + { + res = btor_malloc (mm, strlen (str) + 1); + ADJUST (); + strcpy (res, str); + } + else + res = 0; + + return res; +} + +void +btor_freestr (BtorMemMgr * mm, char *str) +{ + if (str) + btor_free (mm, str, strlen (str) + 1); +} + +void +btor_delete_mem_mgr (BtorMemMgr * mm) +{ + assert (mm); + assert (getenv ("BTORLEAK") || + getenv ("BTORLEAKMEM") || + !mm->allocated); + free (mm); +} + +size_t +btor_parse_error_message_length (const char * name, + const char * fmt, va_list ap) +{ + size_t bytes = strlen (name) + 20; /* care for ':: \0' and lineno */ + const char * p; + + for (p = fmt; *p; p++) + { + if (*p == '%') + { + p++; + assert (*p); + if (*p == 'c') + { + (void) va_arg (ap, int); + bytes += 1; + } + else if (*p == 'd' || *p == 'u') + { + (void) va_arg (ap, unsigned); + bytes += 12; + } + else + { + assert (*p == 's'); + bytes += strlen (va_arg (ap, const char *)); + } + } + else + bytes++; + } + + return bytes; +} + +char * +btor_parse_error_message (BtorMemMgr * mem, + const char * name, + int lineno, + const char * fmt, + va_list ap, + size_t bytes) +{ + char * res; + char *tmp; + + tmp = btor_malloc (mem, bytes); + sprintf (tmp, "%s:%d: ", name, lineno); + assert (strlen (tmp) + 1 < bytes); + vsprintf (tmp + strlen (tmp), fmt, ap); + res = btor_strdup (mem, tmp); + btor_free (mem, tmp, bytes); + + return res; +} diff --git a/pool/shard002/C/0061091_hlfs_rm_snapshot.c b/pool/shard002/C/0061091_hlfs_rm_snapshot.c new file mode 100644 index 0000000000000000000000000000000000000000..62a149ca6003743ad156408d8075203444193259 --- /dev/null +++ b/pool/shard002/C/0061091_hlfs_rm_snapshot.c @@ -0,0 +1,51 @@ +/* + * Copyright (C) 2012 Harry Wei + * + * 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 "hlfs_ctrl.h" +#include "snapshot.h" +#include "storage_helper.h" +#include "hlfs_log.h" + +int +hlfs_rm_snapshot(const char *uri, const char *ssname) { + //HLOG_DEBUG("enter func %s", __func__); + int ret = 0; + struct snapshot *ss = NULL; + bs_file_t file = NULL; + struct back_storage *storage = init_storage_handler(uri); + if (NULL == storage) { + HLOG_ERROR("storage init error!"); + return -1; + } + if (0 != (ret=load_snapshot_by_name(storage, SNAPSHOT_FILE, &ss, \ + ssname))){ + HLOG_ERROR("snapshot %s is not exist, right???", ssname); + ret = EHLFS_SSNOTEXIST; + goto out; + } + //HLOG_DEBUG("99 before dump ret is %d", ret); + if (0 != (ret=dump_snapshot_delmark(storage, SNAPSHOT_FILE, ss->sname))) { + goto out; + } + //HLOG_DEBUG("99 after dump ret is %d", ret); + + HLOG_INFO("Remove Snapshot Succ - snapshot_name:%s", ssname); +out: + if (NULL != file) { + storage->bs_file_close(storage, file); + } + if (ss != NULL) { + g_free(ss); + } + //HLOG_DEBUG("leave func %s", __func__); + return ret; +} diff --git a/pool/shard002/C/0061092_Common.c b/pool/shard002/C/0061092_Common.c new file mode 100644 index 0000000000000000000000000000000000000000..52fea82142de9e04614a1f09cc3cb13f29b75a4a --- /dev/null +++ b/pool/shard002/C/0061092_Common.c @@ -0,0 +1,87 @@ +#include "Common.h" + +extern int CommonGetRandom(int min, int max) +{ + return min + (int)(rand()*(max-min+1.0)/(1.0+RAND_MAX)); +} + +extern double CommonGetDistance(int ay, int ax, int by, int bx) +{ + return sqrt((ay - by)*(ay - by) + (ax - bx)*(ax - bx)); +} + +/* LOS経路作成 + * @param path 作成したパスを格納する配列 + * @param pathSize パスの要素数 + * @param me パスを作成する始点座標 + * @param to パスを作成する終点座標 +*/ +extern void CommonBuildPathTo(Position *path, int pathSize, Position me, Position to) +{ + int nextCol = me.x; + int nextRow = me.y; + int deltaRow = to.y - me.y; + int deltaCol = to.x - me.x; + int stepCol, stepRow; + int currentStep, fraction; + + // 経路の初期化 + for(currentStep=0; currentStep < pathSize; currentStep++) { + path[ currentStep ].y = -1; + path[ currentStep ].x = -1; + } + currentStep = 0; + + // 進行方向の計算。計算済みの deltaRow と deltaCol の値を使って進行方向を決定する + if( deltaRow < 0 ) stepRow = -1; else stepRow = 1; + if( deltaCol < 0 ) stepCol = -1; else stepCol = 1; + deltaRow = abs( deltaRow * 2 ); + deltaCol = abs( deltaCol * 2 ); + + // ブレゼンハムアルゴリズム + path[ currentStep ].y = nextRow; + path[ currentStep ].x = nextCol; + currentStep++; + if( currentStep >= pathSize ) { + return; + } + // 列軸のほうが長い場合 + if( deltaCol > deltaRow ) { + fraction = deltaRow * 2 - deltaCol; + + while( nextCol != to.x ) + { + if( fraction >= 0 ){ + nextRow = nextRow + stepRow; + fraction = fraction - deltaCol; + } + nextCol = nextCol + stepCol; + fraction = fraction + deltaRow; + path[ currentStep ].y = nextRow; + path[ currentStep ].x = nextCol; + currentStep++; + if( currentStep >= pathSize ) + return; + } + } else { + // 行軸のほうが長い場合 + fraction = deltaCol * 2 - deltaRow; + + while( nextRow != to.y ) + { + if( fraction >= 0 ){ + nextCol = nextCol + stepCol; + fraction = fraction - deltaRow; + } + nextRow = nextRow + stepRow; + fraction = fraction + deltaCol; + path[ currentStep ].y = nextRow; + path[ currentStep ].x = nextCol; + currentStep++; + if( currentStep >= pathSize ) + return; + } + } + return; +} + diff --git a/pool/shard002/C/0061101_pthread_attrgetinheritsched.c b/pool/shard002/C/0061101_pthread_attrgetinheritsched.c new file mode 100644 index 0000000000000000000000000000000000000000..70be7cbd519927681823e300ccf31eceba373498 --- /dev/null +++ b/pool/shard002/C/0061101_pthread_attrgetinheritsched.c @@ -0,0 +1,123 @@ +/**************************************************************************** + * + * 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. + * + ****************************************************************************/ +/**************************************************************************** + * libc/pthread/pthread_attrgetinheritsched.c + * + * Copyright (C) 2007-2009, 2011 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 + +/**************************************************************************** + * Definitions + ****************************************************************************/ + +/**************************************************************************** + * Private Type Declarations + ****************************************************************************/ + +/**************************************************************************** + * Global Variables + ****************************************************************************/ + +/**************************************************************************** + * Private Variables + ****************************************************************************/ + +/**************************************************************************** + * Private Functions + ****************************************************************************/ + +/**************************************************************************** + * Public Functions + ****************************************************************************/ + +/**************************************************************************** + * Function: pthread_attr_getinheritsched + * + * Description: + * Report whether the scheduling info in the pthread + * attributes will be used or if the thread will + * inherit the properties of the parent. + * + * Parameters: + * attr + * inheritsched + * + * Return Value: + * 0 if successful. Otherwise, an error code. + * + * Assumptions: + * + ****************************************************************************/ + +int pthread_attr_getinheritsched(FAR const pthread_attr_t *attr, FAR int *inheritsched) +{ + int ret; + + svdbg("attr=0x%p inheritsched=0x%p\n", attr, inheritsched); + + if (!attr || !inheritsched) { + ret = EINVAL; + } else { + *inheritsched = (int)attr->inheritsched; + ret = OK; + } + + svdbg("Returning %d\n", ret); + return ret; +} diff --git a/pool/shard002/C/0061116_8.c b/pool/shard002/C/0061116_8.c new file mode 100644 index 0000000000000000000000000000000000000000..a770624ac615ab3ec0d1f2240fe7fe68997b6016 --- /dev/null +++ b/pool/shard002/C/0061116_8.c @@ -0,0 +1,74 @@ +#include +#include +#include +#include + +int roll_dice(void); +bool play_game(void); + +int main(void) +{ + int wins = 0, losses = 0; + char play_again; + + srand((unsigned) time(NULL)); + + for (;;) { + if (play_game()) wins++; + else losses++; + + printf("Play again? "); + scanf("%c", &play_again); + if (play_again == 'n') break; + else continue; + } + + printf("Wins: %d Losses: %d\n", wins, losses); + + return 0; +} + +int roll_dice(void) +{ + int x, y; + + x = (rand() % 6) + 1; + y = (rand() % 6) + 1; + + return x + y; +} + +bool play_game(void) +{ + int roll, point; + + roll = roll_dice(); + printf("\nYou rolled: %d\n", roll); + + if (roll == 7 || roll == 11) { + printf("You win!\n\n"); + return true; + } + else if (roll == 2 || roll == 3 || roll == 12) { + printf("You lose!\n\n"); + return false; + } else { + point = roll; + printf("Your point is %d\n", point); + } + + for (;;) { + roll = roll_dice(); + printf ("You rolled: %d\n", roll); + + if (roll == point) { + printf("You win!\n\n"); + return true; + } + + if (roll == 7 || roll == 11) { + printf("You lose!\n\n"); + return false; + } + } +} diff --git a/pool/shard002/C/0061140_cert_extract.c b/pool/shard002/C/0061140_cert_extract.c new file mode 100644 index 0000000000000000000000000000000000000000..095f810f4ff11a184db79c17154e627159eb8468 --- /dev/null +++ b/pool/shard002/C/0061140_cert_extract.c @@ -0,0 +1,183 @@ +//krazy:excludeall=license (program, not a library) +/* +** cert_extract.c -- Extract CA Certs out of Netscape certN.db files +** +** Copyright Ariel Glenn +** Copyright 1998 Ralf S. Engelschall +** +** 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 +** +** +** Originally written and released under the GPL by +** Ariel Glenn from the AcIS R&D group at Columbia +** as the two sources findoffset.c and dblist.c. See under +** http://www.columbia.edu/~ariel/good-certs/ for more details. +** +** Merged into one single program in August 1998 +** by Ralf S. Engelschall for use in the mod_ssl project. +** See under http://www.engelschall.com/sw/mod_ssl/ for more details. +** +*/ + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +#include "openssl/asn1.h" +#include "openssl/x509.h" + +int findoffset(char *dbname); + +int findoffset(char *dbname) +{ + DB *db; + DBT dkey, dvalue; + int result; + int offset = 0; + char *p; + int ptag = 0, pclass, plen; + X509 *mycert; + + if ((db = dbopen(dbname, O_RDONLY, 0, DB_HASH, NULL)) == NULL) { + fprintf(stderr, "Failed to open DB file '%s': %s\n", dbname, strerror(errno)); + exit(1); + } + while ((result = (db->seq(db, &dkey, &dvalue, R_NEXT))) == 0) { + if ((dvalue.size) > 520) { + while (offset < dvalue.size) { + p = (char *)dvalue.data + offset - 1; + ASN1_get_object((unsigned char **)&p, (long *)&plen, &ptag, &pclass, dvalue.size); + if (ptag == V_ASN1_SEQUENCE) { /* ok, it might be a cert then. */ + /* include length of object header junk */ + plen += p - ((char *) dvalue.data + offset - 1); + mycert = NULL; + p = (char *) dvalue.data + offset - 1; + d2i_X509(&mycert, (unsigned char **) &p, plen); + if (mycert == NULL) { /* must be garbage after all */ + offset++; + continue; + } + break; + } + else + offset++; + } + if (offset > 0) + break; /* found it, let's quit */ + } + } + db->close(db); + return (offset); +} + +int main(int argc, char **argv) +{ + char *dbname; + DB *db; + int j; + int offset; + DBT dkey, dvalue; + int result; + char oname[40]; + int fout; + int find; + char *p; + int ptag = 0, pclass, plen; + X509 *mycert; + char *shortname; + char byte1, byte2; + + if (argc != 2) { + fprintf(stderr, "usage: %s /path/to/netscape/cert.db\n", argv[0]); + exit(1); + } + + dbname = argv[1]; + offset = findoffset(dbname); + if (offset == 0) { + fprintf(stderr, "Could not determine cert offset in DB file '%s'\n", dbname); + exit(1); + } + else { + fprintf(stderr, "Ok: certificates are at offset %d\n", offset); + } + + if ((db = dbopen(dbname, O_RDONLY, 0, DB_HASH, NULL)) == NULL) { + fprintf(stderr, "Failed to open DB file '%s': %s\n", dbname, strerror(errno)); + exit(1); + } + if ((find = open("cert.index", O_WRONLY | O_CREAT | O_TRUNC, 0755)) == -1) { + fprintf(stderr, "Failed to open Index file '%s': %s\n", "cert-index", strerror(errno)); + exit(1); + } + j = 0; + byte1 = -1; + byte2 = -1; + while ((result = (db->seq(db, &dkey, &dvalue, R_NEXT))) == 0) { + if (dvalue.size > offset && ((dvalue.size) - offset) > 500) { + p = (char *)dvalue.data + offset - 1; + if (byte1 != -1 && byte2 != -1) + if (byte1 != p[0] || byte2 != p[1]) + continue; + ASN1_get_object((unsigned char **)&p, (long *)&plen, &ptag, &pclass, dvalue.size); + if (ptag == V_ASN1_SEQUENCE) { /* ok, it might be a cert then. */ + if (byte1 == -1 && byte2 == -1) { + byte1 = p[0]; + byte2 = p[1]; + } + /* include length of object header junk */ + plen += p - ((char *) dvalue.data + offset - 1); + mycert = NULL; + p = (char *) dvalue.data + offset - 1; + d2i_X509(&mycert, (unsigned char **) &p, plen); + if (mycert == NULL) { /* must be garbage after all */ + continue; + } + j++; + sprintf(oname, "cert.%02d.der", j); + if ((fout = open(oname, O_WRONLY | O_CREAT | O_TRUNC, 0755)) == -1) { + fprintf(stderr, "could not open %s\n", oname); + continue; + } + write(fout, (char *) dvalue.data + offset - 1, plen); + close(fout); + write(find, oname, strlen(oname)); + write(find, ": ", 2); + shortname = (char *) dvalue.data + offset - 1 + plen; + write(find, shortname, dvalue.size - plen - offset); + write(find, "\n", 1); + fprintf(stderr, "Extracted: %s (", oname); + write(fileno(stderr), shortname, dvalue.size - plen - offset); + fprintf(stderr, ")\n"); + } + else { + /* fprintf(stderr, "Hmmm... ptag is %d, plen is %d\n", ptag, plen); */ + } + } + } + close(find); + db->close(db); + + return (0); +} + diff --git a/pool/shard002/C/0061142_base64.c b/pool/shard002/C/0061142_base64.c new file mode 100644 index 0000000000000000000000000000000000000000..aeba7c1d8a0903ae9939b7ec9eac99e8cdff9153 --- /dev/null +++ b/pool/shard002/C/0061142_base64.c @@ -0,0 +1,85 @@ +/* base64.c + * Base-64 conversion + * + * $Id$ + * + * Wireshark - Network traffic analyzer + * By Gerald Combs + * Copyright 1998 Gerald Combs + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +#include "config.h" + +#include +#include "base64.h" + +/* Decode a base64 string in-place - simple and slow algorithm. + Return length of result. Taken from rproxy/librsync/base64.c by + Andrew Tridgell. */ + +size_t epan_base64_decode(char *s) +{ + static const char b64[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/\r\n"; + int bit_offset, byte_offset, idx, i; + unsigned char *d = (unsigned char *)s; + char *p; + int cr_idx; + + /* we will allow CR and LF - but ignore them */ + cr_idx = (int) (strchr(b64, '\r') - b64); + + i=0; + + while (*s && (p=strchr(b64, *s))) { + idx = (int)(p - b64); + if(idx < cr_idx) { + byte_offset = (i*6)/8; + bit_offset = (i*6)%8; + d[byte_offset] &= ~((1<<(8-bit_offset))-1); + if (bit_offset < 3) { + d[byte_offset] |= (idx << (2-bit_offset)); + } else { + d[byte_offset] |= (idx >> (bit_offset-2)); + d[byte_offset+1] = 0; + d[byte_offset+1] |= (idx << (8-(bit_offset-2))) & 0xFF; + } + i++; + } + s++; + } + + d[i*3/4] = 0; + return i*3/4; +} + +/* Return a tvb that contains the binary representation of a base64 + string */ + +tvbuff_t * +base64_to_tvb(tvbuff_t *parent, const char *base64) +{ + tvbuff_t *tvb; + char *data = g_strdup(base64); + gint len; + + len = (gint) epan_base64_decode(data); + tvb = tvb_new_child_real_data(parent, (const guint8 *)data, len, len); + + tvb_set_free_cb(tvb, g_free); + + return tvb; +} diff --git a/pool/shard002/C/0061154_oauth-account-manager-dialog.c b/pool/shard002/C/0061154_oauth-account-manager-dialog.c new file mode 100644 index 0000000000000000000000000000000000000000..6876c8e611816ab3b851c6bdcb7029502ef81736 --- /dev/null +++ b/pool/shard002/C/0061154_oauth-account-manager-dialog.c @@ -0,0 +1,250 @@ +/* -*- Mode: C; tab-width: 8; indent-tabs-mode: t; c-basic-offset: 8 -*- */ + +/* + * GThumb + * + * Copyright (C) 2010 Free Software Foundation, Inc. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 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 Street #330, Boston, MA 02111-1307, USA. + */ + +#include +#include +#include "oauth-account.h" +#include "oauth-account-manager-dialog.h" + + +#define GET_WIDGET(x) (_gtk_builder_get_widget (self->priv->builder, (x))) + + +enum { + ACCOUNT_DATA_COLUMN, + ACCOUNT_NAME_COLUMN, +}; + + +static gpointer parent_class = NULL; + + +struct _OAuthAccountManagerDialogPrivate { + GtkBuilder *builder; +}; + + +static void +oauth_account_manager_dialog_finalize (GObject *object) +{ + OAuthAccountManagerDialog *self; + + self = OAUTH_ACCOUNT_MANAGER_DIALOG (object); + + _g_object_unref (self->priv->builder); + + G_OBJECT_CLASS (parent_class)->finalize (object); +} + + +static void +oauth_account_manager_dialog_class_init (OAuthAccountManagerDialogClass *klass) +{ + GObjectClass *object_class; + + parent_class = g_type_class_peek_parent (klass); + g_type_class_add_private (klass, sizeof (OAuthAccountManagerDialogPrivate)); + + object_class = (GObjectClass*) klass; + object_class->finalize = oauth_account_manager_dialog_finalize; +} + + +static void +delete_button_clicked_cb (GtkWidget *button, + gpointer user_data) +{ + OAuthAccountManagerDialog *self = user_data; + GtkTreeModel *tree_model; + GtkTreeIter iter; + + if (gtk_tree_selection_get_selected (gtk_tree_view_get_selection (GTK_TREE_VIEW (GET_WIDGET ("account_treeview"))), + &tree_model, + &iter)) + { + gtk_list_store_remove (GTK_LIST_STORE (tree_model), &iter); + } +} + + +static void +text_renderer_edited_cb (GtkCellRendererText *renderer, + char *path, + char *new_text, + gpointer user_data) +{ + OAuthAccountManagerDialog *self = user_data; + GtkTreePath *tree_path; + GtkTreeIter iter; + OAuthAccount *account; + + tree_path = gtk_tree_path_new_from_string (path); + tree_path = gtk_tree_path_new_from_string (path); + if (! gtk_tree_model_get_iter (GTK_TREE_MODEL (GET_WIDGET ("accounts_liststore")), + &iter, + tree_path)) + { + gtk_tree_path_free (tree_path); + return; + } + gtk_tree_path_free (tree_path); + + gtk_tree_model_get (GTK_TREE_MODEL (GET_WIDGET ("accounts_liststore")), &iter, + ACCOUNT_DATA_COLUMN, &account, + -1); + oauth_account_set_username (account, new_text); + + gtk_list_store_set (GTK_LIST_STORE (GET_WIDGET ("accounts_liststore")), &iter, + ACCOUNT_DATA_COLUMN, account, + ACCOUNT_NAME_COLUMN, new_text, + -1); + + g_object_unref (account); +} + + +static void +oauth_account_manager_dialog_init (OAuthAccountManagerDialog *self) +{ + GtkWidget *content; + + self->priv = G_TYPE_INSTANCE_GET_PRIVATE (self, OAUTH_TYPE_ACCOUNT_MANAGER_DIALOG, OAuthAccountManagerDialogPrivate); + self->priv->builder = _gtk_builder_new_from_file ("flicker-account-manager.ui", "flicker"); + + gtk_window_set_resizable (GTK_WINDOW (self), FALSE); + gtk_dialog_set_has_separator (GTK_DIALOG (self), FALSE); + gtk_box_set_spacing (GTK_BOX (gtk_dialog_get_content_area (GTK_DIALOG (self))), 5); + gtk_container_set_border_width (GTK_CONTAINER (self), 5); + + content = _gtk_builder_get_widget (self->priv->builder, "account_manager"); + gtk_container_set_border_width (GTK_CONTAINER (content), 5); + gtk_box_pack_start (GTK_BOX (gtk_dialog_get_content_area (GTK_DIALOG (self))), content, TRUE, TRUE, 0); + + gtk_dialog_add_button (GTK_DIALOG (self), + GTK_STOCK_NEW, + OAUTH_ACCOUNT_MANAGER_RESPONSE_NEW); + gtk_dialog_add_button (GTK_DIALOG (self), + GTK_STOCK_CANCEL, + GTK_RESPONSE_CANCEL); + gtk_dialog_add_button (GTK_DIALOG (self), + GTK_STOCK_OK, + GTK_RESPONSE_OK); + + g_object_set (GET_WIDGET ("account_cellrenderertext"), "editable", TRUE, NULL); + g_signal_connect (GET_WIDGET ("account_cellrenderertext"), + "edited", + G_CALLBACK (text_renderer_edited_cb), + self); + + g_signal_connect (GET_WIDGET ("delete_button"), + "clicked", + G_CALLBACK (delete_button_clicked_cb), + self); +} + + +GType +oauth_account_manager_dialog_get_type (void) +{ + static GType type = 0; + + if (type == 0) { + static const GTypeInfo g_define_type_info = { + sizeof (OAuthAccountManagerDialogClass), + (GBaseInitFunc) NULL, + (GBaseFinalizeFunc) NULL, + (GClassInitFunc) oauth_account_manager_dialog_class_init, + (GClassFinalizeFunc) NULL, + NULL, + sizeof (OAuthAccountManagerDialog), + 0, + (GInstanceInitFunc) oauth_account_manager_dialog_init, + NULL + }; + type = g_type_register_static (GTK_TYPE_DIALOG, + "OAuthAccountManagerDialog", + &g_define_type_info, + 0); + } + + return type; +} + + +static void +oauth_account_manager_dialog_construct (OAuthAccountManagerDialog *self, + GList *accounts) +{ + GtkListStore *list_store; + GtkTreeIter iter; + GList *scan; + + list_store = GTK_LIST_STORE (GET_WIDGET ("accounts_liststore")); + gtk_list_store_clear (list_store); + for (scan = accounts; scan; scan = scan->next) { + OAuthAccount *account = scan->data; + + gtk_list_store_append (list_store, &iter); + gtk_list_store_set (list_store, &iter, + ACCOUNT_DATA_COLUMN, account, + ACCOUNT_NAME_COLUMN, account->username, + -1); + } +} + + +GtkWidget * +oauth_account_manager_dialog_new (GList *accounts) +{ + OAuthAccountManagerDialog *self; + + self = g_object_new (OAUTH_TYPE_ACCOUNT_MANAGER_DIALOG, NULL); + oauth_account_manager_dialog_construct (self, accounts); + + return (GtkWidget *) self; +} + + +GList * +oauth_account_manager_dialog_get_accounts (OAuthAccountManagerDialog *self) +{ + GList *accounts; + GtkTreeModel *tree_model; + GtkTreeIter iter; + + tree_model = (GtkTreeModel *) GET_WIDGET ("accounts_liststore"); + if (! gtk_tree_model_get_iter_first (tree_model, &iter)) + return NULL; + + accounts = NULL; + do { + OAuthAccount *account; + + gtk_tree_model_get (tree_model, &iter, + ACCOUNT_DATA_COLUMN, &account, + -1); + accounts = g_list_prepend (accounts, account); + } + while (gtk_tree_model_iter_next (tree_model, &iter)); + + return g_list_reverse (accounts); +} diff --git a/pool/shard002/C/0061172_q_thread.c b/pool/shard002/C/0061172_q_thread.c new file mode 100644 index 0000000000000000000000000000000000000000..ede085253c7e73ab5db46d653d20e91ef4ecbee5 --- /dev/null +++ b/pool/shard002/C/0061172_q_thread.c @@ -0,0 +1,247 @@ +#include + +#include "os_heap.h" +#include "os_stdlib.h" +#include "os_thread.h" + +#include "q_thread.h" +#include "q_servicelease.h" +#include "q_error.h" +#include "q_log.h" +#include "q_config.h" +#include "q_globals.h" +#include "sysdeps.h" + +static char main_thread_name[] = "main"; + +struct thread_states thread_states; +#if OS_HAS_TSD_USING_THREAD_KEYWORD +__thread struct thread_state1 *tsd_thread_state; +#endif + +static void *os_malloc_aligned_cacheline (os_size_t size) +{ + /* This wastes some space, but we use it only once and it isn't a + huge amount of memory, just a little over a cache line. + Alternatively, we good use valloc() and have it aligned to a page + boundary, but that one isn't part of the O/S abstraction layer + ... */ + const os_address clm1 = CACHE_LINE_SIZE - 1; + os_address ptrA; + void **pptr; + void *ptr; + if ((ptr = os_malloc (size + CACHE_LINE_SIZE + sizeof (void *))) == NULL) + return NULL; + ptrA = ((os_address) ptr + sizeof (void *) + clm1) & ~clm1; + pptr = (void **) ptrA; + pptr[-1] = ptr; + return (void *) ptrA; +} + +static void os_free_aligned (void *ptr) +{ + void **pptr = ptr; + os_free (pptr[-1]); +} + +int thread_states_init (int maxthreads) +{ + int i; + + if (os_mutexInit (&thread_states.lock, &gv.mattr) != os_resultSuccess) + goto err_lock; + thread_states.nthreads = maxthreads; + if ((thread_states.ts = + os_malloc_aligned_cacheline (maxthreads * sizeof (*thread_states.ts))) == NULL) + goto err_tstates; + memset (thread_states.ts, 0, maxthreads * sizeof (*thread_states.ts)); + for (i = 0; i < thread_states.nthreads; i++) + { + thread_states.ts[i].state = THREAD_STATE_ZERO; + thread_states.ts[i].vtime = 1; + thread_states.ts[i].watchdog = 1; + thread_states.ts[i].lb = NULL; + thread_states.ts[i].name = NULL; + } + return 0; + err_tstates: + os_mutexDestroy (&thread_states.lock); + err_lock: + NN_FATAL0 ("thread_states_init: failed to initialize thread state table\n"); + return ERR_UNSPECIFIED; +} + +void thread_states_fini (void) +{ + int i; + for (i = 0; i < thread_states.nthreads; i++) + assert (thread_states.ts[i].state != THREAD_STATE_ALIVE); + os_mutexDestroy (&thread_states.lock); + os_free_aligned (thread_states.ts); + + /* All spawned threads are gone, but the main thread is still alive, + downgraded to an ordinary thread (we're on it right now). We + don't want to lose the ability to log messages, so set ts to a + NULL pointer and rely on lookup_thread_state()'s checks + thread_states.ts. */ + thread_states.ts = NULL; +} + +struct thread_state1 *lookup_thread_state_real (void) +{ + if (thread_states.ts) + { + os_threadId self = os_threadIdSelf (); + int i; + for (i = 0; i < thread_states.nthreads; i++) + if (os_threadEqual (thread_states.ts[i].tid, self)) + return &thread_states.ts[i]; + } + return NULL; +} + +struct thread_context { + struct thread_state1 *self; + void * (*f) (void *arg); + void *arg; +}; + +static void *create_thread_wrapper (struct thread_context *ctxt) +{ + void *ret; + ctxt->self->tid = os_threadIdSelf (); + ret = ctxt->f (ctxt->arg); + logbuf_free (ctxt->self->lb); + os_free (ctxt); + return ret; +} + +static int find_free_slot (const char *name) +{ + int i, cand; + for (i = 0, cand = -1; i < thread_states.nthreads; i++) + { + if (thread_states.ts[i].state != THREAD_STATE_ALIVE) + cand = i; + if (thread_states.ts[i].state == THREAD_STATE_ZERO) + break; + } + if (cand == -1) + NN_FATAL1 ("create_thread: %s: no free slot\n", name ? name : "(anon)"); + return cand; +} + +void upgrade_main_thread (void) +{ + int cand; + struct thread_state1 *ts1; + os_mutexLock (&thread_states.lock); + if ((cand = find_free_slot ("name")) < 0) + abort (); + ts1 = &thread_states.ts[cand]; + if (ts1->state == THREAD_STATE_ZERO) + assert (vtime_asleep_p (ts1->vtime)); + ts1->state = THREAD_STATE_ALIVE; + ts1->tid = os_threadIdSelf (); + ts1->lb = logbuf_new (); + ts1->name = main_thread_name; + os_mutexUnlock (&thread_states.lock); +} + +const struct config_thread_properties_listelem *lookup_thread_properties (const char *name) +{ + const struct config_thread_properties_listelem *e; + for (e = config.thread_properties; e != NULL; e = e->next) + if (strcmp (e->name, name) == 0) + break; + return e; +} + +struct thread_state1 *create_thread (const char *name, void * (*f) (void *arg), void *arg) +{ + struct config_thread_properties_listelem const * const tprops = lookup_thread_properties (name); + int cand; + os_threadAttr tattr; + struct thread_state1 *ts1; + os_threadId tid; + struct thread_context *ctxt; + if ((ctxt = os_malloc (sizeof (*ctxt))) == NULL) + return NULL; + os_mutexLock (&thread_states.lock); + if ((cand = find_free_slot (name)) < 0) + goto fatal; + ts1 = &thread_states.ts[cand]; + if (ts1->state == THREAD_STATE_ZERO) + assert (vtime_asleep_p (ts1->vtime)); + if ((ts1->name = os_strdup (name)) == NULL) + { + NN_FATAL1 ("create_thread: %s: out of memory\n", name); + goto fatal; + } + ts1->lb = logbuf_new (); + ts1->state = THREAD_STATE_ALIVE; + ctxt->self = ts1; + ctxt->f = f; + ctxt->arg = arg; + os_threadAttrInit (&tattr); + if (tprops != NULL) + { + if (!tprops->sched_priority.isdefault) + tattr.schedPriority = tprops->sched_priority.value; + tattr.schedClass = tprops->sched_class; /* explicit default value in the enum */ + if (!tprops->stack_size.isdefault) + tattr.stackSize = (os_uint32) tprops->stack_size.value; + } + TRACE (("create_thread: %s: class %d priority %d stack %u\n", name, (int) tattr.schedClass, tattr.schedPriority, tattr.stackSize)); + + if (os_threadCreate (&tid, name, &tattr, (void * (*) (void *)) create_thread_wrapper, ctxt) != os_resultSuccess) + { + ts1->state = THREAD_STATE_ZERO; + NN_FATAL1 ("create_thread: %s: os_threadCreate failed\n", name); + goto fatal; + } + nn_log (LC_INFO, "started new thread 0x%llx : %s\n", (unsigned long long) os_threadIdToInteger (tid), name); + ts1->extTid = tid; /* overwrite the temporary value with the correct external one */ + os_mutexUnlock (&thread_states.lock); + return ts1; + fatal: + os_mutexUnlock (&thread_states.lock); + os_free (ctxt); + abort (); + return NULL; +} + +static void reap_thread_state (struct thread_state1 *ts1, int sync_with_servicelease) +{ + os_mutexLock (&thread_states.lock); + ts1->state = THREAD_STATE_ZERO; + if (sync_with_servicelease) + nn_servicelease_statechange_barrier (gv.servicelease); + if (ts1->name != main_thread_name) + os_free (ts1->name); + os_mutexUnlock (&thread_states.lock); +} + +int join_thread (struct thread_state1 *ts1, void **retval) +{ + int ret; + assert (ts1->state == THREAD_STATE_ALIVE); + if (os_threadWaitExit (ts1->extTid, retval) == 0) + ret = 0; + else + ret = ERR_UNSPECIFIED; + assert (vtime_asleep_p (ts1->vtime)); + reap_thread_state (ts1, 1); + return ret; +} + +void downgrade_main_thread (void) +{ + struct thread_state1 *ts1 = lookup_thread_state (); + thread_state_asleep (ts1); + logbuf_free (ts1->lb); + /* no need to sync with service lease: already stopped */ + reap_thread_state (ts1, 0); +} + +/* SHA1 not available (unoffical build.) */ diff --git a/pool/shard002/C/0061174_UxCplus.c b/pool/shard002/C/0061174_UxCplus.c new file mode 100644 index 0000000000000000000000000000000000000000..ccf37ed05a55d44e70c923a3b2ff9751d508263d --- /dev/null +++ b/pool/shard002/C/0061174_UxCplus.c @@ -0,0 +1,140 @@ +/*------------------------------------------------------------------------------ + * $Date$ $Revision: 2.7 + *------------------------------------------------------------------------------ + * Copyright (c) 1991, Visual Edge Software Ltd. + * + * ALL RIGHTS RESERVED. Permission to use, copy, modify, and + * distribute this software and its documentation for any purpose + * and without fee is hereby granted, provided that the above + * copyright notice appear in all copies and that both that + * copyright notice and this permission notice appear in supporting + * documentation, and that the name of Visual Edge Software not be + * used in advertising or publicity pertaining to distribution of + * the software without specific, written prior permission. The year + * included in the notice is the year of the creation of the work. + *------------------------------------------------------------------------------ + * This file defines the base class from which interfaces are derived. + *----------------------------------------------------------------------------*/ + +#ifdef __cplusplus + +#ifdef XT_CODE +# include "UxXt.h" +#else /* XT_CODE */ +# include "UxLib.h" +#endif /* XT_CODE */ + +/*------------------------------------------------------------------------------ + * NAME: childSite + * RETURNS: NULL + * DESCRIPTION: Default childSite method for interface base class. + *----------------------------------------------------------------------------*/ +swidget _UxCInterface::childSite (Environment * pEnv) +{ + if (pEnv) { + pEnv->_major = NO_EXCEPTION; + } + return 0; +} + +/*------------------------------------------------------------------------------ + * NAME: UxChildSite + * INPUT: swidget sw + * DESCRIPTION: Gets the designatedChildSite by calling the childSite method. + * If the childSite itself is a component, we recur in it to ensure + * that the child is placed correctly by its rules, and so on. + *----------------------------------------------------------------------------*/ +swidget _UxCInterface::UxChildSite (swidget proposedParent) +{ + _UxCInterface *ppIface; + + if (!proposedParent) { + return NULL; + } + + ppIface = (_UxCInterface *) UxGetContext (proposedParent); + if (ppIface && (ppIface != this)) { + swidget preferredParent = ppIface->childSite(&UxEnv); + if (preferredParent) { + return ppIface->UxChildSite(preferredParent); + } + } + return proposedParent; +} + +/*------------------------------------------------------------------------------ + * Interface methods for geometry. + * These are the default methods for normal generated components; + * they may be overridden for components not made in UIM/X. + *----------------------------------------------------------------------------*/ + +int _UxCInterface::_get_x(Environment*) +{ + Position x; + XtVaGetValues(UxRealWidget(UxThis), XmNx, &x, NULL); + return x; +} + +void _UxCInterface::_set_x(Environment*, int x) +{ + XtVaSetValues(UxRealWidget(UxThis), XmNx, x, NULL); +} + +int _UxCInterface::_get_y(Environment*) +{ + Position y; + XtVaGetValues(UxRealWidget(UxThis), XmNy, &y, NULL); + return y; +} + +void _UxCInterface::_set_y(Environment*, int y) +{ + XtVaSetValues(UxRealWidget(UxThis), XmNy, y, NULL); +} + +int _UxCInterface::_get_width(Environment*) +{ + Dimension width; + XtVaGetValues(UxRealWidget(UxThis), XmNwidth, &width, NULL); + return width; +} + +void _UxCInterface::_set_width(Environment*, int width) +{ + XtVaSetValues(UxRealWidget(UxThis), XmNwidth, width, NULL); +} + +int _UxCInterface::_get_height(Environment*) +{ + Dimension height; + XtVaGetValues(UxRealWidget(UxThis), XmNheight, &height, NULL); + return height; +} + +void _UxCInterface::_set_height(Environment*, int height) +{ + XtVaSetValues(UxRealWidget(UxThis), XmNheight, height, NULL); +} + + +/*------------------------------------------------------------------------------ + * NAME: UxManage + * DESCRIPTION: Manage this interface + * This method is called after the interface is constructed and initialized, + * unless the interface was defined to be created unmanaged. + * Its makes the interface visible. + *----------------------------------------------------------------------------*/ +void _UxCInterface::UxManage(Environment*) +{ + Widget w = UxGetWidget(UxThis); + Widget rw = UxRealWidget(UxThis); + + if (w && XtIsComposite(XtParent(w))) { + XtManageChild(w); + } + if (rw && XtIsSubclass(rw, shellWidgetClass)) { + XtPopup(rw, XtGrabNone); + } +} + +#endif /* __cplusplus */ diff --git a/pool/shard002/C/0061178_vms.c b/pool/shard002/C/0061178_vms.c new file mode 100644 index 0000000000000000000000000000000000000000..12d0415d03a37a8f394eab15f64e8c919a0477b8 --- /dev/null +++ b/pool/shard002/C/0061178_vms.c @@ -0,0 +1,227 @@ +/* +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +% % +% % +% % +% V V M M SSSSS % +% V V MM MM SS % +% V V M M M SSS % +% V V M M SS % +% V M M SSSSS % +% % +% % +% VMS Utility Methods for ImageMagick % +% % +% % +% Software Design % +% John Cristy % +% October 1994 % +% % +% % +% Copyright 1999 E. I. du Pont de Nemours and Company % +% % +% Permission is hereby granted, free of charge, to any person obtaining a % +% copy of this software and associated documentation files ("ImageMagick"), % +% to deal in ImageMagick without restriction, including without limitation % +% the rights to use, copy, modify, merge, publish, distribute, sublicense, % +% and/or sell copies of ImageMagick, and to permit persons to whom the % +% ImageMagick 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 ImageMagick. % +% % +% 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 % +% E. I. du Pont de Nemours and Company 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 ImageMagick or the use or other % +% dealings in ImageMagick. % +% % +% Except as contained in this notice, the name of the E. I. du Pont de % +% Nemours and Company shall not be used in advertising or otherwise to % +% promote the sale, use or other dealings in ImageMagick without prior % +% written authorization from the E. I. du Pont de Nemours and Company. % +% % +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +% +% The directory methods are strongly based on similar methods written +% by Rich Salz. +% +*/ + +#if defined(vms) && !defined(_AXP_) +/* + Include declarations. +*/ +#include "magick.h" +#include "defines.h" +#include "vms.h" + +#if !defined(__VMS_VER) || (__VMS_VER < 70000000) +/* +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +% % +% % +% % +% c l o s e d i r % +% % +% % +% % +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +% +% Method closedir closes the named directory stream and frees the DIR +% structure. +% +% The format of the closedir method is: +% +% +% A description of each parameter follows: +% +% o entry: Specifies a pointer to a DIR structure. +% +% +*/ +void closedir(DIR *directory) +{ + assert(directory != (DIR *) NULL); + free(directory->pattern); + free((char *) directory); +} + +/* +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +% % +% % +% % +% o p e n e d i r % +% % +% % +% % +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +% +% Method opendir opens the directory named by filename and associates +% a directory stream with it. +% +% The format of the opendir method is: +% +% opendir(entry) +% +% A description of each parameter follows: +% +% o entry: Specifies a pointer to a DIR structure. +% +% +*/ +DIR *opendir(char *name) +{ + DIR + *directory; + + /* + Allocate memory for handle and the pattern. + */ + directory=(DIR *) AllocateMemory(sizeof(*directory)); + if (directory == (DIR *) NULL) + { + errno=ENOMEM; + return((DIR *) NULL); + } + if (strcmp(".",name) == 0) + name=""; + directory->pattern=AllocateMemory((unsigned int) (strlen(name) + +sizeof("*.*")+1)); + if (directory->pattern == (char *) NULL) + { + FreeMemory((char *) directory); + errno=ENOMEM; + return(NULL); + } + /* + Initialize descriptor. + */ + (void) sprintf(directory->pattern,"%.1024s*.*",name); + directory->context=0; + directory->pat.dsc$a_pointer=directory->pattern; + directory->pat.dsc$w_length=strlen(directory->pattern); + directory->pat.dsc$b_dtype=DSC$K_DTYPE_T; + directory->pat.dsc$b_class=DSC$K_CLASS_S; + return(directory); +} + +/* +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +% % +% % +% % +% r e a d d i r % +% % +% % +% % +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +% +% Method readdir returns a pointer to a structure representing the +% directory entry at the current position in the directory stream to +% which entry refers. +% +% The format of the readdir +% +% readdir(entry) +% +% A description of each parameter follows: +% +% o entry: Specifies a pointer to a DIR structure. +% +% +*/ +struct dirent *readdir(DIR *directory) +{ + char + buffer[sizeof(directory->entry.d_name)]; + + int + status; + + register char + *p; + + register int + i; + + struct dsc$descriptor_s + result; + + /* + Initialize the result descriptor. + */ + result.dsc$a_pointer=buffer; + result.dsc$w_length=sizeof(buffer)-2; + result.dsc$b_dtype=DSC$K_DTYPE_T; + result.dsc$b_class=DSC$K_CLASS_S; + status=lib$find_file(&directory->pat,&result,&directory->context); + if ((status == RMS$_NMF) || (directory->context == 0L)) + return((struct dirent *) NULL); + /* + Lowercase all filenames. + */ + buffer[sizeof(buffer)-1]='\0'; + for (p=buffer; *p; p++) + if (isupper(*p)) + *p=tolower(*p); + /* + Skip any directory component and just copy the name. + */ + p=buffer; + while (!isspace(*p)) + p++; + *p='\0'; + p=strchr(buffer,']'); + if (p) + (void) strcpy(directory->entry.d_name,p+1); + else + (void) strcpy(directory->entry.d_name,buffer); + directory->entry.d_namlen=strlen(directory->entry.d_name); + return(&directory->entry); +} +#endif +#endif diff --git a/pool/shard002/C/0061184_OSAL_Parser.c b/pool/shard002/C/0061184_OSAL_Parser.c new file mode 100644 index 0000000000000000000000000000000000000000..6f3c4bf23f8c0e4212d8718c9d1683570c33c2c4 --- /dev/null +++ b/pool/shard002/C/0061184_OSAL_Parser.c @@ -0,0 +1,104 @@ +#include "OSAL_Parser.h" + + +#ifndef __OSAL_PARSER_MASK__ +int OSAL_Script_FetchParser_Data(char *main_name, char *sub_name, int value[], int count) +{ + script_item_u val; + script_item_value_type_e type; + int ret = -1; + + if(count == 1) { + type = script_get_item(main_name, sub_name, &val); + if(SCIRPT_ITEM_VALUE_TYPE_INT == type) { + ret = 0; + *value = val.val; + __inf("%s.%s=%d\n", main_name, sub_name, *value); + } else { + ret = -1; + __inf("fetch script data %s.%s fail\n", main_name, sub_name); + } + } else if(count == sizeof(disp_gpio_set_t)/sizeof(int)) { + type = script_get_item(main_name, sub_name, &val); + if(SCIRPT_ITEM_VALUE_TYPE_PIO == type) { + disp_gpio_set_t *gpio_info = (disp_gpio_set_t *)value; + + ret = 0; + gpio_info->gpio = val.gpio.gpio; + gpio_info->mul_sel = val.gpio.mul_sel; + gpio_info->pull = val.gpio.pull; + gpio_info->drv_level = val.gpio.drv_level; + gpio_info->data = val.gpio.data; + memcpy(gpio_info->gpio_name, sub_name, strlen(sub_name)+1); + __inf("%s.%s gpio=%d,mul_sel=%d,data:%d\n",main_name, sub_name, gpio_info->gpio, gpio_info->mul_sel, gpio_info->data); + } else { + ret = -1; + __inf("fetch script data %s.%s fail\n", main_name, sub_name); + } + } else { + type = script_get_item(main_name, sub_name, &val); + if(SCIRPT_ITEM_VALUE_TYPE_STR == type) { + memcpy((void*)value, (void*)val.str, strlen(val.str)+1); + __inf("%s.%s=%s\n",main_name, sub_name, val.str); + } else { + ret = -1; + __inf("fetch script data %s.%s fail\n", main_name, sub_name); + } + } + + return ret; +} + +/* returns: 0:invalid, 1: int; 2:str, 3: gpio */ +int OSAL_Script_FetchParser_Data_Ex(char *main_name, char *sub_name, int value[], int count) +{ + script_item_u val; + script_item_value_type_e type; + int ret = -1; + + type = script_get_item(main_name, sub_name, &val); + if(SCIRPT_ITEM_VALUE_TYPE_INT == type) { + ret = 0; + *value = val.val; + __inf("%s.%s=%d\n", main_name, sub_name, *value); + } else if(SCIRPT_ITEM_VALUE_TYPE_PIO == type) { + disp_gpio_set_t *gpio_info = (disp_gpio_set_t *)value; + + ret = 0; + gpio_info->gpio = val.gpio.gpio; + gpio_info->mul_sel = val.gpio.mul_sel; + gpio_info->pull = val.gpio.pull; + gpio_info->drv_level = val.gpio.drv_level; + gpio_info->data = val.gpio.data; + memcpy(gpio_info->gpio_name, sub_name, strlen(sub_name)+1); + __inf("%s.%s gpio=%d,mul_sel=%d,data:%d\n",main_name, sub_name, gpio_info->gpio, gpio_info->mul_sel, gpio_info->data); + } else if(SCIRPT_ITEM_VALUE_TYPE_STR == type) { + memcpy((void*)value, (void*)val.str, strlen(val.str)+1); + __inf("%s.%s=%s\n",main_name, sub_name, val.str); + } else { + ret = -1; + __inf("fetch script data %s.%s fail\n", main_name, sub_name); + } + + return type; +} + +#else + +int OSAL_Script_FetchParser_Data(char *main_name, char *sub_name, int value[], int count) +{ + return 0; +} + +/* returns: 0:invalid, 1: int; 2:str, 3: gpio */ +int OSAL_Script_FetchParser_Data_Ex(char *main_name, char *sub_name, int value[], int count) +{ + return 0; +} + +int OSAL_sw_get_ic_ver(void) +{ + return 0; +} + +#endif diff --git a/pool/shard002/C/0061196_json.c b/pool/shard002/C/0061196_json.c new file mode 100644 index 0000000000000000000000000000000000000000..2492171ef25cafe4e1b9ed2c331de79596127b0c --- /dev/null +++ b/pool/shard002/C/0061196_json.c @@ -0,0 +1,208 @@ +/****************************************************************************** + * Copyright 2008-2014 by Aerospike. All rights reserved. + * THIS IS UNPUBLISHED PROPRIETARY SOURCE CODE. THE COPYRIGHT NOTICE + * ABOVE DOES NOT EVIDENCE ANY ACTUAL OR INTENDED PUBLICATION. + ******************************************************************************/ + +#include +#include + +#include "json.h" + +#include +#include +#include +#include + + +#define LOG(msg, ...) \ + // { printf("%s:%d - ", __FILE__, __LINE__); printf(msg, ##__VA_ARGS__ ); printf("\n"); } + + +as_list * as_json_array_to_list(json_t * a) { + + int size = (int)json_array_size(a); + as_list * l = (as_list *)as_arraylist_new(size,0); + + for (int i = 0; i < json_array_size(a); i++) { + as_val * v = as_json_to_val(json_array_get(a,i)); + as_list_append(l, v); + } + + return l; +} + +as_map * as_json_object_to_map(json_t * o) { + + int n = (int)json_object_size(o); + as_map * m = (as_map *)as_hashmap_new(n); + const char * k = NULL; + json_t * v = NULL; + + json_object_foreach(o, k, v) { + as_val * key = (as_val *) as_string_new(strdup(k),true); + as_val * val = as_json_to_val(v); + as_map_set(m, key, val); + + } + + return m; +} + +as_string * as_json_string_to_string(json_t * s) { + const char * str = json_string_value(s); + return as_string_new(strdup(str),true); +} + +as_integer * as_json_number_to_integer(json_t * n) { + return as_integer_new((int64_t) json_integer_value(n)); +} + +as_boolean * as_json_boolean_to_boolean(json_t * n) { + return as_boolean_new(json_is_true(n)); +} + +as_val * as_json_to_val(json_t * j) { + if ( json_is_array(j) ) return (as_val *) as_json_array_to_list(j); + if ( json_is_object(j) ) return (as_val *) as_json_object_to_map(j); + if ( json_is_boolean(j) ) return (as_val *) as_json_boolean_to_boolean(j); + if ( json_is_string(j) ) return (as_val *) as_json_string_to_string(j); + if ( json_is_integer(j) ) return (as_val *) as_json_number_to_integer(j); + if ( json_is_real(j) ) return (as_val *) as_double_new((double)json_real_value(j)); + return (as_val *) NULL;//&as_nil; +} + +as_val * as_json_arg(char const * arg) { + + as_val * val = NULL; + json_t * root = NULL; + json_error_t error; + + root = json_loads(arg, 0, &error); + + if ( !root ) { + // Let asql deal with base type. JSON only to pass nested types + return NULL; + } + else { + val = as_json_to_val(root); + json_decref(root); + } + + return val; +} + +/** + * as_linkedlist had been removed. + */ +/* +as_list * as_json_arglist(int argc, char ** argv) { + if ( argc == 0 || argv == NULL ) return NULL;//cons(NULL,NULL); + return (as_list *)as_linkedlist_new(as_json_arg(argv[0]), (as_linkedlist *)as_json_arglist(argc-1, argv+1)); +} +*/ + +int as_json_print(const as_val * val) { + if ( !val ) { + printf("null"); + return 1; + } + switch( val->type ) { + case AS_NIL: { + printf("null"); + break; + } + case AS_BOOLEAN: { + printf("%s", as_boolean_tobool((as_boolean *) val) ? "true" : "false"); + break; + } + case AS_INTEGER: { + printf("%" PRId64, as_integer_toint((as_integer *) val)); + break; + } + case AS_DOUBLE: { + printf("%.16g", as_double_get((as_double*)val)); + break; + } + case AS_STRING: { + printf("\"%s\"", as_string_tostring((as_string *) val)); + break; + } + case AS_LIST: { + as_iterator * i = (as_iterator *)as_list_iterator_new((as_list *) val); + bool delim = false; + printf("["); + while ( as_iterator_has_next(i) ) { + if ( delim ) printf(","); + printf(" "); + as_json_print(as_iterator_next(i)); + delim = true; + } + printf(" "); + printf("]"); + break; + } + case AS_MAP: { + as_iterator * i = (as_iterator *)as_map_iterator_new((as_map *) val); + bool delim = false; + printf("{"); + while ( as_iterator_has_next(i) ) { + as_pair * kv = (as_pair *) as_iterator_next(i); + if ( delim ) printf(","); + printf(" "); + as_json_print(as_pair_1(kv)); + printf(": "); + as_json_print(as_pair_2(kv)); + delim = true; + } + printf(" "); + printf("}"); + break; + } + default: { + printf("~~<%d>", val->type); + } + } + return 0; +} + +int record_to_json(int nbins, as_bin * bins) { + printf("{"); + for (int i = 0; i < nbins; i++, bins++) { + as_bin* bin = bins; + printf("\"%s\": ", bins->name); + as_val* val = (as_val*)bin->valuep; + + switch (val->type) { + case AS_INTEGER: { + as_integer* v = as_integer_fromval(val); + printf("%"PRId64"", v->value); + break; + } + case AS_DOUBLE: { + as_double* v = as_double_fromval(val); + printf("%.16g", v->value); + break; + } + case AS_STRING: { + as_string* v = as_string_fromval(val); + printf("\"%s\"", v->value); + break; + } + case AS_LIST: + case AS_MAP: { + as_json_print(val); + break; + } + default: { + printf("<%d>",(int)val->type); + break; + } + } + if ( i < nbins-1 ) { + printf(", "); + } + } + printf("}"); + return 0; +} diff --git a/pool/shard002/C/0061207_batch-p.c b/pool/shard002/C/0061207_batch-p.c new file mode 100644 index 0000000000000000000000000000000000000000..a4b53d9b7598e40561a44062a32df645151b7565 --- /dev/null +++ b/pool/shard002/C/0061207_batch-p.c @@ -0,0 +1,151 @@ +#include +#include +#include +#include +#include "vmax.h" +#include +#include +#include +#include "comm.h" +#include +#include + +char f1[JOBS_AT_A_TIME][256]; +char f2[JOBS_AT_A_TIME][256]; +long _start_ = 0; + +static FILE *out = NULL; +static FILE *err = NULL; + +void process_alarm(int sig) +{ + fprintf(stderr, "time out. terminate now.\n"); + stop_now = 1; + signal(SIGALRM, process_alarm); /* maybe unnecessary, but won't hurt */ +} + +void leave(int sig) +{ + fprintf(stderr, "received SIGINT. Save and exit.\n"); + if (out) { + fflush(out); + fclose(out); + } + if (err) { + fflush(err); + fclose(err); + } + exit(1); +} + +int main(int argc, char* argv[]) +{ + signal(SIGALRM, process_alarm); + signal(SIGINT, leave); + + int verbose = 0; + int clean_start = 0; + int mc = 1; + char host[256] = "localhost"; + + /* time stats */ + struct timeval begin, end; + double time_total = 0; + + char c; + int k; + while ((c = getopt (argc, argv, "vcm:h:")) != -1) { + switch(c) { + case 'v' : + verbose = 1; + break; + case 'c' : + clean_start = 1; + break; + case 'h' : + k = sscanf(optarg, "%s", host); + if (k != 1) { + fprintf(stderr, "Usage: %s [-v] [-c] [-m maxconn] [-h host] output\n", argv[0]); + return 1; + } + break; + case 'm' : + k = sscanf(optarg, "%d", &mc); + if (k != 1) { + fprintf(stderr, "Usage: %s [-v] [-c] [-m maxconn] [-h host] output\n", argv[0]); + return 1; + } + break; + default : + fprintf(stderr, "Usage: %s [-v] [-c] [-m maxconn] [-h host] output\n", argv[0]); + return 1; + } + } + + if (optind != argc - 1) { + fprintf(stderr, "Usage: %s [-v] [-c] [-m maxconn] [-h host] output\n", argv[0]); + return 1; + } + + char* output = argv[optind]; + + char mode[3] = ""; + if (clean_start) strcat(mode, "w"); + else strcat(mode, "a"); + + out = fopen(output, mode); + if (out == NULL) { + fprintf(stderr, "cannot open file %s for write\n", output); + return 1; + } + + char err_filename[256] = ""; + strcat(err_filename, output); + strcat(err_filename, ".err"); + err = fopen(err_filename, mode); + if (err == NULL) { + fprintf(stderr, "cannot open file %s for write\n", err_filename); + return 1; + } + + int lines; + int progress = 0; + do { + lines = refill(host, (char**)f1, (char**)f2); + //printf("read %d lines\n", lines); + int i; + for (i = 0; i < lines; i ++) { + + Graph *g = read_graph(f1[i]); + Graph *g2 = read_graph(f2[i]); + if (g == NULL || g2 == NULL) { + fprintf(err, "%s:%s:skipped\n", f1[i], f2[i]); + if (g) destruct(g); + if (g2) destruct(g2); + continue; + } + + if (verbose) fprintf(stdout, "%s:%s\n", f1[i], f2[i]); + gettimeofday(&begin, NULL); + alarm(MCS_TIMEOUT); + int best_l = max(g, g2, mc, 0, 0); + alarm(0); + gettimeofday(&end, NULL); + time_total += (end.tv_sec - begin.tv_sec + + (end.tv_usec - begin.tv_usec) * 0.000001); + + destruct(g); + destruct(g2); + + fprintf(out, "%s:%s:%d\n", f1[i], f2[i], best_l); + } + fflush(out); + fflush(err); + progress += i; + printf("finished %d lines\n", progress); + } while (lines == JOBS_AT_A_TIME); + + fprintf(err, "Total time: %f\n", time_total); + fclose(out); fclose(err); + return 0; +} diff --git a/pool/shard002/C/0061209_mtr_clnt.c b/pool/shard002/C/0061209_mtr_clnt.c new file mode 100644 index 0000000000000000000000000000000000000000..04d0104f8269807506c780e07215ce1f44f11ff9 --- /dev/null +++ b/pool/shard002/C/0061209_mtr_clnt.c @@ -0,0 +1,25 @@ +#include +#include +#include +#include +#include +#include "../log/log.h" +#include "../comm/comm.h" +#include "../mtr_if/mtr_if.h" +#include "../bin/i2c_zmq/mtr_srv.h" + +//Client interface to server +mtrStatus_t SendCommand(void *req, mtrID_t mtrID, cmdID_t cmd, uint32_t *data){ + int i; + mtrCmdReq_t mtrCmdReq; + mtrCmdRep_t mtrCmdRep; + mtrStatus_t ret; + + mtrCmdReq.mtrID=(uint8_t)mtrID; + mtrCmdReq.cmdID = (uint8_t)cmd; + mtrCmdReq.data = *data; + zmq_send (req, &mtrCmdReq, sizeof(mtrCmdReq_t), 0); + zmq_recv (req, &mtrCmdRep, sizeof(mtrCmdRep_t), 0); + *data = mtrCmdRep.data; + return 1; +} diff --git a/pool/shard002/C/0061211_common.c b/pool/shard002/C/0061211_common.c new file mode 100644 index 0000000000000000000000000000000000000000..d2cefbe10b27cc7383e727d0b9882b482c0f375e --- /dev/null +++ b/pool/shard002/C/0061211_common.c @@ -0,0 +1,57 @@ + +/* Common code for wrappers. + + Copyright (C) 2008 Free Software Foundation, Inc. + + Written by FlÃvio Cruz + + 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., 675 Mass Ave, Cambridge, MA 02139, USA. */ + +inline static void +_set_routine (const unsigned what, void *fun) +{ + assert (what < _NUMBER_OF_ROUTINES); + + if (routines[what] != NULL) + { + fprintf (stderr, "Warning: redefining routine %s\n", + routine_to_str (what)); + } + + routines[what] = fun; +} + +inline static void +_get_module_info (void) +{ + int i; + for (i = 0; i != _NUMBER_OF_ROUTINES; ++i) + { + if (routines[i] != NULL) + { + printf ("Routine #%d (%s): set to address %x\n", i, + routine_to_str (i), (vm_size_t) routines[i]); + } + } +} + +#define COMMON_FUNCTIONS(module) \ + void get_ ## module ## _info(void) { \ + _get_module_info(); \ + } \ + void set_ ## module ## _routine(const unsigned what, void *fun) { \ + _set_routine(what, fun); \ + } + diff --git a/pool/shard002/C/0061213_hung_task.c b/pool/shard002/C/0061213_hung_task.c new file mode 100644 index 0000000000000000000000000000000000000000..79464a611f3d6efaff1d349720a4da86b2bc240b --- /dev/null +++ b/pool/shard002/C/0061213_hung_task.c @@ -0,0 +1,236 @@ +/* + * Detect Hung Task + * + * kernel/hung_task.c - kernel thread for detecting tasks stuck in D state + * + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +/* + * The number of tasks checked: + */ +unsigned long __read_mostly sysctl_hung_task_check_count = PID_MAX_LIMIT; + +/* + * Limit number of tasks checked in a batch. + * + * This value controls the preemptibility of khungtaskd since preemption + * is disabled during the critical section. It also controls the size of + * the RCU grace period. So it needs to be upper-bound. + */ +#define HUNG_TASK_BATCHING 1024 + +/* + * Zero means infinite timeout - no checking done: + */ +unsigned long __read_mostly sysctl_hung_task_timeout_secs = CONFIG_DEFAULT_HUNG_TASK_TIMEOUT; + +unsigned long __read_mostly sysctl_hung_task_warnings = 10; + +static int __read_mostly did_panic; + +static struct task_struct *watchdog_task; + +/* + * Should we panic (and reboot, if panic_timeout= is set) when a + * hung task is detected: + */ +unsigned int __read_mostly sysctl_hung_task_panic = + CONFIG_BOOTPARAM_HUNG_TASK_PANIC_VALUE; + +static int __init hung_task_panic_setup(char *str) +{ + sysctl_hung_task_panic = simple_strtoul(str, NULL, 0); + + return 1; +} +__setup("hung_task_panic=", hung_task_panic_setup); + +static int +hung_task_panic(struct notifier_block *this, unsigned long event, void *ptr) +{ + did_panic = 1; + + return NOTIFY_DONE; +} + +static struct notifier_block panic_block = { + .notifier_call = hung_task_panic, +}; + +static void check_hung_task(struct task_struct *t, unsigned long timeout) +{ + unsigned long switch_count = t->nvcsw + t->nivcsw; + + /* + * Ensure the task is not frozen. + * Also, skip vfork and any other user process that freezer should skip. + */ + if (unlikely(t->flags & (PF_FROZEN | PF_FREEZER_SKIP))) + return; + + /* + * When a freshly created task is scheduled once, changes its state to + * TASK_UNINTERRUPTIBLE without having ever been switched out once, it + * musn't be checked. + */ + if (unlikely(!switch_count)) + return; + + if (switch_count != t->last_switch_count) { + t->last_switch_count = switch_count; + return; + } + if (!sysctl_hung_task_warnings) + return; + sysctl_hung_task_warnings--; + + /* + * Ok, the task did not get scheduled for more than 2 minutes, + * complain: + */ + pr_err("INFO: task %s:%d blocked for more than %ld seconds.\n", + t->comm, t->pid, timeout); + pr_err(" %s %s %.*s\n", + print_tainted(), init_utsname()->release, + (int)strcspn(init_utsname()->version, " "), + init_utsname()->version); + pr_err("\"echo 0 > /proc/sys/kernel/hung_task_timeout_secs\"" + " disables this message.\n"); + sched_show_task(t); + debug_show_held_locks(t); + + touch_nmi_watchdog(); + + if (sysctl_hung_task_panic) { + trigger_all_cpu_backtrace(); + panic("hung_task: blocked tasks"); + } +} + +/* + * To avoid extending the RCU grace period for an unbounded amount of time, + * periodically exit the critical section and enter a new one. + * + * For preemptible RCU it is sufficient to call rcu_read_unlock in order + * to exit the grace period. For classic RCU, a reschedule is required. + */ +static bool rcu_lock_break(struct task_struct *g, struct task_struct *t) +{ + bool can_cont; + + get_task_struct(g); + get_task_struct(t); + rcu_read_unlock(); + cond_resched(); + rcu_read_lock(); + can_cont = pid_alive(g) && pid_alive(t); + put_task_struct(t); + put_task_struct(g); + + return can_cont; +} + +/* + * Check whether a TASK_UNINTERRUPTIBLE does not get woken up for + * a really long time (120 seconds). If that happens, print out + * a warning. + */ +static void check_hung_uninterruptible_tasks(unsigned long timeout) +{ + int max_count = sysctl_hung_task_check_count; + int batch_count = HUNG_TASK_BATCHING; + struct task_struct *g, *t; + + /* + * If the system crashed already then all bets are off, + * do not report extra hung tasks: + */ + if (test_taint(TAINT_DIE) || did_panic) + return; + + rcu_read_lock(); + do_each_thread(g, t) { + if (!max_count--) + goto unlock; + if (!--batch_count) { + batch_count = HUNG_TASK_BATCHING; + if (!rcu_lock_break(g, t)) + goto unlock; + } + /* use "==" to skip the TASK_KILLABLE tasks waiting on NFS */ + if (t->state == TASK_UNINTERRUPTIBLE) + check_hung_task(t, timeout); + } while_each_thread(g, t); + unlock: + rcu_read_unlock(); +} + +static unsigned long timeout_jiffies(unsigned long timeout) +{ + /* timeout of 0 will disable the watchdog */ + return timeout ? timeout * HZ : MAX_SCHEDULE_TIMEOUT; +} + +/* + * Process updating of timeout sysctl + */ +int proc_dohung_task_timeout_secs(struct ctl_table *table, int write, + void __user *buffer, + size_t *lenp, loff_t *ppos) +{ + int ret; + + ret = proc_doulongvec_minmax(table, write, buffer, lenp, ppos); + + if (ret || !write) + goto out; + + wake_up_process(watchdog_task); + + out: + return ret; +} + +/* + * kthread which checks for tasks stuck in D state + */ +static int watchdog(void *dummy) +{ + set_user_nice(current, 0); + + for ( ; ; ) { + unsigned long timeout = sysctl_hung_task_timeout_secs; + + while (schedule_timeout_interruptible(timeout_jiffies(timeout))) { + kgr_task_safe(current); + timeout = sysctl_hung_task_timeout_secs; + } + + check_hung_uninterruptible_tasks(timeout); + } + + return 0; +} + +static int __init hung_task_init(void) +{ + atomic_notifier_chain_register(&panic_notifier_list, &panic_block); + watchdog_task = kthread_run(watchdog, NULL, "khungtaskd"); + + return 0; +} + +module_init(hung_task_init); diff --git a/pool/shard002/C/0061215_request_key_auth.c b/pool/shard002/C/0061215_request_key_auth.c new file mode 100644 index 0000000000000000000000000000000000000000..c7afc9217d8529cf1277c59fa92e9d5c85865621 --- /dev/null +++ b/pool/shard002/C/0061215_request_key_auth.c @@ -0,0 +1,231 @@ +/* Request key authorisation token key definition. + * + * Copyright (C) 2005 Red Hat, Inc. All Rights Reserved. + * Written by David Howells (dhowells@redhat.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. + * + * See Documentation/security/keys-request-key.txt + */ + +#include +#include +#include +#include +#include +#include +#include "internal.h" + +static int request_key_auth_instantiate(struct key *, const void *, size_t); +static void request_key_auth_describe(const struct key *, struct seq_file *); +static void request_key_auth_revoke(struct key *); +static void request_key_auth_destroy(struct key *); +static long request_key_auth_read(const struct key *, char __user *, size_t); + +struct key_type key_type_request_key_auth = { + .name = ".request_key_auth", + .def_datalen = sizeof(struct request_key_auth), + .instantiate = request_key_auth_instantiate, + .describe = request_key_auth_describe, + .revoke = request_key_auth_revoke, + .destroy = request_key_auth_destroy, + .read = request_key_auth_read, +}; + +static int request_key_auth_instantiate(struct key *key, + const void *data, + size_t datalen) +{ + key->payload.data = (struct request_key_auth *) data; + return 0; +} + +static void request_key_auth_describe(const struct key *key, + struct seq_file *m) +{ + struct request_key_auth *rka = key->payload.data; + + seq_puts(m, "key:"); + seq_puts(m, key->description); + if (key_is_instantiated(key)) + seq_printf(m, " pid:%d ci:%zu", rka->pid, rka->callout_len); +} + +static long request_key_auth_read(const struct key *key, + char __user *buffer, size_t buflen) +{ + struct request_key_auth *rka = key->payload.data; + size_t datalen; + long ret; + + datalen = rka->callout_len; + ret = datalen; + + + if (buffer && buflen > 0) { + if (buflen > datalen) + buflen = datalen; + + if (copy_to_user(buffer, rka->callout_info, buflen) != 0) + ret = -EFAULT; + } + + return ret; +} + +static void request_key_auth_revoke(struct key *key) +{ + struct request_key_auth *rka = key->payload.data; + + kenter("{%d}", key->serial); + + if (rka->cred) { + put_cred(rka->cred); + rka->cred = NULL; + } +} + +static void request_key_auth_destroy(struct key *key) +{ + struct request_key_auth *rka = key->payload.data; + + kenter("{%d}", key->serial); + + if (rka->cred) { + put_cred(rka->cred); + rka->cred = NULL; + } + + key_put(rka->target_key); + key_put(rka->dest_keyring); + kfree(rka->callout_info); + kfree(rka); +} + +struct key *request_key_auth_new(struct key *target, const void *callout_info, + size_t callout_len, struct key *dest_keyring) +{ + struct request_key_auth *rka, *irka; + const struct cred *cred = current->cred; + struct key *authkey = NULL; + char desc[20]; + int ret; + + kenter("%d,", target->serial); + + + rka = kmalloc(sizeof(*rka), GFP_KERNEL); + if (!rka) { + kleave(" = -ENOMEM"); + return ERR_PTR(-ENOMEM); + } + rka->callout_info = kmalloc(callout_len, GFP_KERNEL); + if (!rka->callout_info) { + kleave(" = -ENOMEM"); + kfree(rka); + return ERR_PTR(-ENOMEM); + } + + if (cred->request_key_auth) { + + down_read(&cred->request_key_auth->sem); + + if (test_bit(KEY_FLAG_REVOKED, &cred->request_key_auth->flags)) + goto auth_key_revoked; + + irka = cred->request_key_auth->payload.data; + rka->cred = get_cred(irka->cred); + rka->pid = irka->pid; + + up_read(&cred->request_key_auth->sem); + } + else { + + rka->cred = get_cred(cred); + rka->pid = current->pid; + } + + rka->target_key = key_get(target); + rka->dest_keyring = key_get(dest_keyring); + memcpy(rka->callout_info, callout_info, callout_len); + rka->callout_len = callout_len; + + + sprintf(desc, "%x", target->serial); + + authkey = key_alloc(&key_type_request_key_auth, desc, + cred->fsuid, cred->fsgid, cred, + KEY_POS_VIEW | KEY_POS_READ | KEY_POS_SEARCH | + KEY_USR_VIEW, KEY_ALLOC_NOT_IN_QUOTA); + if (IS_ERR(authkey)) { + ret = PTR_ERR(authkey); + goto error_alloc; + } + + + ret = key_instantiate_and_link(authkey, rka, 0, NULL, NULL); + if (ret < 0) + goto error_inst; + + kleave(" = {%d,%d}", authkey->serial, atomic_read(&authkey->usage)); + return authkey; + +auth_key_revoked: + up_read(&cred->request_key_auth->sem); + kfree(rka->callout_info); + kfree(rka); + kleave("= -EKEYREVOKED"); + return ERR_PTR(-EKEYREVOKED); + +error_inst: + key_revoke(authkey); + key_put(authkey); +error_alloc: + key_put(rka->target_key); + key_put(rka->dest_keyring); + kfree(rka->callout_info); + kfree(rka); + kleave("= %d", ret); + return ERR_PTR(ret); +} + +static int key_get_instantiation_authkey_match(const struct key *key, + const void *_id) +{ + struct request_key_auth *rka = key->payload.data; + key_serial_t id = (key_serial_t)(unsigned long) _id; + + return rka->target_key->serial == id; +} + +struct key *key_get_instantiation_authkey(key_serial_t target_id) +{ + const struct cred *cred = current_cred(); + struct key *authkey; + key_ref_t authkey_ref; + + authkey_ref = search_process_keyrings( + &key_type_request_key_auth, + (void *) (unsigned long) target_id, + key_get_instantiation_authkey_match, + cred); + + if (IS_ERR(authkey_ref)) { + authkey = ERR_CAST(authkey_ref); + if (authkey == ERR_PTR(-EAGAIN)) + authkey = ERR_PTR(-ENOKEY); + goto error; + } + + authkey = key_ref_to_ptr(authkey_ref); + if (test_bit(KEY_FLAG_REVOKED, &authkey->flags)) { + key_put(authkey); + authkey = ERR_PTR(-EKEYREVOKED); + } + +error: + return authkey; +} diff --git a/pool/shard002/C/0061218_infra.c b/pool/shard002/C/0061218_infra.c new file mode 100644 index 0000000000000000000000000000000000000000..50433d9233d97f6013396ee6bfcfd9a6c054470d --- /dev/null +++ b/pool/shard002/C/0061218_infra.c @@ -0,0 +1,93 @@ +/* + * infra.c + * + * Copyright (c) 2015 Bernie Gach + * see the LICENCE file + */ +#include"infra.h" +void infra_init(void) +{ + /*set clock to uart0 module*/ + SIM_SCGC4|=SIM_SCGC4_UART0_MASK; + + //PTC6 as receiver and PTD7 as transmitter + portC->PCR[6].mux=0x00; + portD->PCR[7].mux=0x00; + portD->PCR[7].mux=0x02; + SIM_SOPT5|= SIM_SOPT5_UART0RXSRC(0x01); + PTC->PDDR.bit_reg.bit6=in; + PTD->PDDR.bit_reg.bit7=out; +} + +void uart0_init (UART_MemMapPtr uartch, int sysclk, int baud) +{ + uint16_t ubd, temp, brfa; + /* Make sure that the transmitter and receiver are disabled while we + * change settings. + */ + UART_C2_REG(uartch) &= ~(UART_C2_TE_MASK | UART_C2_RE_MASK ); + /* Configure the UART for 8-bit mode, no parity */ + /* We need all default settings, so entire register is cleared */ + UART_C1_REG(uartch) = 0; + /* Calculate baud settings */ + ubd = (uint16_t)((sysclk*2000)/(baud * 16)); + /* Save off the current value of the UARTx_BDH except for the SBR */ + temp = UART_BDH_REG(uartch) & ~(UART_BDH_SBR(0x1F)); + UART_BDH_REG(uartch) = temp | UART_BDH_SBR(((ubd & 0x1F00) >> 8)); + UART_BDL_REG(uartch) = (uint8_t)(ubd & UART_BDL_SBR_MASK); + /* Determine if a fractional divider is needed to get closer to the baud rate */ + brfa = (((sysclk*32000)/(baud * 16)) - (ubd * 32)); + /* Save off the current value of the UARTx_C4 register except for the BRFA */ + temp = UART_C4_REG(uartch) & ~(UART_C4_BRFA(0x1F)); + UART_C4_REG(uartch) = temp | UART_C4_BRFA(brfa); + /* Enable receiver and transmitter */ + UART_C2_REG(uartch) |= (UART_C2_TE_MASK | UART_C2_RE_MASK ); + UART_S1_REG(uartch) &= ~UART_S1_TDRE_MASK; + /*infrared enable and set transmitter narrow pulse*/ + UART0_IR|= UART_IR_IREN_MASK; + UART0_IR|= UART_IR_TNP(0x00); + +} + + +void infra_transmit(uint8_t ch) +{ + /* Wait until space is available in the FIFO */ + while(!(UART_S1_REG(UART0_BASE_PTR) & UART_S1_TDRE_MASK)); + + /* Send the character */ + UART_D_REG(UART0_BASE_PTR) = (uint8_t)ch; + +} + +/*send a string*/ +void infra_transmit_string(uint8_t *s) +{ + while(*s!='\0') + { + infra_transmit(*s++); + } +} + + + +uint8_t infra_read(void) +{ + /* Wait until character has been received */ + while (!(UART_S1_REG(UART0_BASE_PTR) & UART_S1_RDRF_MASK)); + + /* Return the 8-bit data from the receiver */ + return (uint8_t)UART_D_REG(UART0_BASE_PTR); +} + + + + + +/*check if there is data to read*/ +uint16_t data_present(void) +{ + return (((uint16_t)(UART_S1_REG(UART0_BASE_PTR) & UART_S1_RDRF_MASK)) == UART_S1_RDRF_MASK); + +} + diff --git a/pool/shard002/C/0061237_statistics_folder.c b/pool/shard002/C/0061237_statistics_folder.c new file mode 100644 index 0000000000000000000000000000000000000000..62bb6cf8ecad503509e40840ed2d0e0d82d7a018 --- /dev/null +++ b/pool/shard002/C/0061237_statistics_folder.c @@ -0,0 +1,240 @@ +/* $APPASERVER_HOME/src_appaserver/statistics_folder.c */ +/* ---------------------------------------------------------------- */ +/* */ +/* Freely available software: see Appaserver.org */ +/* ---------------------------------------------------------------- */ + +/* Includes */ +/* -------- */ +#include +#include +#include +#include "timlib.h" +#include "list.h" +#include "form.h" +#include "folder.h" +#include "related_folder.h" +#include "appaserver.h" +#include "operation_list.h" +#include "document.h" +#include "application.h" +#include "dictionary.h" +#include "query.h" +#include "query_attribute_statistics_list.h" +#include "appaserver_library.h" +#include "appaserver_error.h" +#include "environ.h" +#include "appaserver_parameter_file.h" +#include "decode_html_post.h" +#include "role.h" +#include "dictionary_appaserver.h" +#include "lookup_before_drop_down.h" + +/* Constants */ +/* --------- */ + +/* Prototypes */ +/* ---------- */ + +int main( int argc, char **argv ) +{ + char *login_name, *application_name, *session, *folder_name; + DOCUMENT *document; + char decoded_dictionary_string[ MAX_INPUT_LINE ]; + char *dictionary_string; + DICTIONARY *original_post_dictionary; + FOLDER *folder; + QUERY_ATTRIBUTE_STATISTICS_LIST *query_attribute_statistics_list; + APPASERVER_PARAMETER_FILE *appaserver_parameter_file; + char *sys_string; + char *where_clause; + ROLE *role; + char *role_name; + DICTIONARY_APPASERVER *dictionary_appaserver; + QUERY *query; + LOOKUP_BEFORE_DROP_DOWN *lookup_before_drop_down; + + application_name = environ_get_application_name( argv[ 0 ] ); + + appaserver_error_starting_argv_append_file( + argc, + argv, + application_name ); + + if ( argc != 7 ) + { + fprintf( stderr, +"Usage: %s login_name ignored session folder role dictionary\n", + argv[ 0 ] ); + exit ( 1 ); + } + + login_name = argv[ 1 ]; + session = argv[ 3 ]; + folder_name = argv[ 4 ]; + role_name = argv[ 5 ]; + dictionary_string = argv[ 6 ]; + + decode_html_post( decoded_dictionary_string, + dictionary_string ); + + original_post_dictionary = + dictionary_index_string2dictionary( + decoded_dictionary_string ); + + if ( ! ( dictionary_appaserver = + dictionary_appaserver_new( + original_post_dictionary, + (char *)0 /* application_name */, + (LIST *)0 /* attribute_list */, + (LIST *)0 /* operation_name_list */ ) ) ) + { + fprintf( stderr, + "ERROR in %s/%s()/%d: exiting early.\n", + __FILE__, + __FUNCTION__, + __LINE__ ); + exit( 1 ); + } + + appaserver_parameter_file = appaserver_parameter_file_new(); + + folder = folder_new_folder( application_name, + session, + folder_name ); + + role = role_new_role( application_name, + role_name ); + + folder_load( &folder->insert_rows_number, + &folder->lookup_email_output, + &folder->row_level_non_owner_forbid, + &folder->row_level_non_owner_view_only, + &folder->populate_drop_down_process, + &folder->post_change_process, + &folder->folder_form, + &folder->notepad, + &folder->html_help_file_anchor, + &folder->post_change_javascript, + &folder->lookup_before_drop_down, + &folder->data_directory, + &folder->index_directory, + &folder->no_initial_capital, + &folder->subschema_name, + &folder->create_view_statement, + application_name, + session, + folder->folder_name, + role_get_override_row_restrictions( + role->override_row_restrictions_yn ), + role_name, + (LIST *)0 /* mto1_related_folder_list */ ); + + folder->mto1_isa_related_folder_list = + related_folder_get_mto1_related_folder_list( + list_new_list(), + application_name, + session, + folder_name, + (char *)0 /* role_name */, + 1 /* isa_flag */, + related_folder_recursive_all, + role_get_override_row_restrictions( + role->override_row_restrictions_yn ), + (LIST *)0 /* root_primary_attribute_name_list */, + 0 /* recursive_level */ ); + + folder->attribute_list = + attribute_get_attribute_list( + folder->application_name, + folder->folder_name, + (char *)0 /* attribute_name */, + folder->mto1_isa_related_folder_list, + (char *)0 /* role_name */ ); + + lookup_before_drop_down = + lookup_before_drop_down_new( + application_name, + dictionary_appaserver-> + lookup_before_drop_down_dictionary, + "lookup" /* state */ ); + + lookup_before_drop_down->lookup_before_drop_down_state = + lookup_before_drop_down_get_state( + lookup_before_drop_down-> + lookup_before_drop_down_folder_list, + dictionary_appaserver-> + lookup_before_drop_down_dictionary, + dictionary_appaserver->preprompt_dictionary, + folder->lookup_before_drop_down ); + + query = + query_simple_new( + dictionary_appaserver->query_dictionary, + application_name, + login_name, + folder_name ); + + where_clause = query->query_output->where_clause; + + document = document_new( "", application_name ); + document->output_content_type = 1; + + document_output_head( + document->application_name, + document->title, + document->output_content_type, + appaserver_parameter_file->appaserver_mount_point, + document->javascript_module_list, + document->stylesheet_filename, + application_relative_source_directory( + application_name ), + 0 /* not with_dynarch_menu */ ); + + document_output_body( + document->application_name, + document->onload_control_string ); + + query_attribute_statistics_list = + query_attribute_statistics_list_new( + folder->application_name, + query->query_output->from_clause ); + + query_attribute_statistics_list->list = + query_attribute_statistics_list_get_list( + folder->attribute_list ); + + sys_string = + query_attribute_statistics_list_get_build_each_temp_file_sys_string( + query_attribute_statistics_list->application_name, + query_attribute_statistics_list->folder_name, + query_attribute_statistics_list->list, + where_clause ); + + if ( !sys_string ) + { + printf( +"

There are no number attributes or dates in this folder to perform statistics on.\n" ); + document_close(); + return 0; + } + + if ( system( sys_string ) ){} + + query_attribute_statistics_list_populate_list( + query_attribute_statistics_list->list ); + + query_attribute_statistics_list_output_table( + query_attribute_statistics_list->folder_name, + where_clause, + query_attribute_statistics_list->list, + application_name ); + + query_attribute_statistics_remove_temp_file( + query_attribute_statistics_list->list ); + + document_close(); + + return 0; +} + diff --git a/pool/shard002/C/0061243_server.c b/pool/shard002/C/0061243_server.c new file mode 100644 index 0000000000000000000000000000000000000000..44a501c5856253cbfabe9dd2fe269e4ba449a1f5 --- /dev/null +++ b/pool/shard002/C/0061243_server.c @@ -0,0 +1,145 @@ +/* + * + * OBEX Server + * + * Copyright (C) 2007-2010 Nokia Corporation + * Copyright (C) 2007-2010 Marcel Holtmann + * + * + * 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 + * + */ + +#ifdef HAVE_CONFIG_H +#include +#endif + +#include +#include +#include +#include +#include +#include +#include + +#include + +#include + +#include "log.h" +#include "obex.h" +#include "obex-priv.h" +#include "server.h" +#include "service.h" +#include "transport.h" + +static GSList *servers = NULL; + +static void obex_server_free(struct obex_server *server) +{ + g_free(server->folder); + g_free(server->capability); + g_free(server); +} + +int obex_server_init(uint16_t service, const char *folder, + gboolean secure, gboolean auto_accept, + gboolean symlinks, const char *capability) +{ + GSList *drivers; + GSList *transports; + GSList *l; + + drivers = obex_service_driver_list(service); + if (drivers == NULL) { + DBG("No service driver registered"); + return -EINVAL; + } + + transports = obex_transport_driver_list(); + if (transports == NULL) { + DBG("No transport driver registered"); + return -EINVAL; + } + + for (l = transports; l; l = l->next) { + struct obex_transport_driver *transport = l->data; + struct obex_server *server; + int err; + + if (transport->service != 0 && + (transport->service & service) == FALSE) + continue; + + server = g_new0(struct obex_server, 1); + server->transport = transport; + server->drivers = drivers; + server->folder = g_strdup(folder); + server->auto_accept = auto_accept; + server->symlinks = symlinks; + server->capability = g_strdup(capability); + server->secure = secure; + + server->transport_data = transport->start(server, &err); + if (server->transport_data == NULL) { + DBG("Unable to start %s transport: %s (%d)", + transport->name, strerror(err), err); + obex_server_free(server); + continue; + } + + servers = g_slist_prepend(servers, server); + } + + return 0; +} + +void obex_server_exit(void) +{ + GSList *l; + + for (l = servers; l; l = l->next) { + struct obex_server *server = l->data; + + server->transport->stop(server->transport_data); + obex_server_free(server); + } + + g_slist_free(servers); + + return; +} + +struct obex_service_driver *obex_server_find_driver( + struct obex_server *server, + uint8_t channel) +{ + GSList *l; + + for (l = server->drivers; l; l = l->next) { + struct obex_service_driver *driver = l->data; + + if (driver->channel == channel) + return driver; + } + + return NULL; +} + +int obex_server_new_connection(struct obex_server *server, GIOChannel *io, + uint16_t tx_mtu, uint16_t rx_mtu) +{ + return obex_session_start(io, tx_mtu, rx_mtu, server); +} diff --git a/pool/shard002/C/0061248_pr43177.c b/pool/shard002/C/0061248_pr43177.c new file mode 100644 index 0000000000000000000000000000000000000000..cd0ae03b3d96665e2d15fb938cb8d3cd105ee581 --- /dev/null +++ b/pool/shard002/C/0061248_pr43177.c @@ -0,0 +1,36 @@ +/* { dg-do run } */ +/* { dg-options "-g" } */ + +void __attribute__((noinline)) +bar (long x) +{ + asm volatile ("" : : "r" (x) : "memory"); +} + +long __attribute__((noinline)) +foo (long x) +{ + long l = x + 3; + bar (l);/* { dg-final { gdb-test .+1 "l" "10" } } */ + bar (l);/* { dg-final { gdb-test . "x" "7" } } */ + return l; +} + +long __attribute__((noinline)) +baz (int x) +{ + long l = x + 3; + bar (l);/* { dg-final { gdb-test .+1 "l" "10" } } */ + bar (l);/* { dg-final { gdb-test . "x" "7" } } */ + return l; +} + +int +main (void) +{ + int i; + asm volatile ("" : "=r" (i) : "0" (7)); + foo (i); + baz (i); + return 0; +} diff --git a/pool/shard002/C/0061251_ip_vs_est.c b/pool/shard002/C/0061251_ip_vs_est.c new file mode 100644 index 0000000000000000000000000000000000000000..3a762ac994d6d707e67f101f72b34d4472182d10 --- /dev/null +++ b/pool/shard002/C/0061251_ip_vs_est.c @@ -0,0 +1,200 @@ +/* + * ip_vs_est.c Simple rate estimator for IPVS + * + * Version: $Id: ip_vs_est.c,v 1.1.1.1 2004/06/19 05:03:02 ashieh Exp $ + * + * Authors: Wensong Zhang + * + * 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. + * + * Changes: + * + */ +#include +#include + +#include + +/* + This code is to estimate rate in a shorter interval (such as 8 + seconds) for virtual services and real servers. For measure rate in a + long interval, it is easy to implement a user level daemon which + periodically reads those statistical counters and measure rate. + + Currently, the measurement is activated by slow timer handler. Hope + this measurement will not introduce too much load. + + We measure rate during the last 8 seconds every 2 seconds: + + avgrate = avgrate*(1-W) + rate*W + + where W = 2^(-2) + + NOTES. + + * The stored value for average bps is scaled by 2^5, so that maximal + rate is ~2.15Gbits/s, average pps and cps are scaled by 2^10. + + * A lot code is taken from net/sched/estimator.c + */ + + +struct ip_vs_estimator +{ + struct ip_vs_estimator *next; + struct ip_vs_stats *stats; + + u32 last_conns; + u32 last_inpkts; + u32 last_outpkts; + u64 last_inbytes; + u64 last_outbytes; + + u32 cps; + u32 inpps; + u32 outpps; + u32 inbps; + u32 outbps; +}; + + +static struct ip_vs_estimator *est_list = NULL; +static rwlock_t est_lock = RW_LOCK_UNLOCKED; +static struct timer_list est_timer; + +static void estimation_timer(unsigned long arg) +{ + struct ip_vs_estimator *e; + struct ip_vs_stats *s; + u32 n_conns; + u32 n_inpkts, n_outpkts; + u64 n_inbytes, n_outbytes; + u32 rate; + + read_lock(&est_lock); + for (e = est_list; e; e = e->next) { + s = e->stats; + + spin_lock(&s->lock); + n_conns = s->conns; + n_inpkts = s->inpkts; + n_outpkts = s->outpkts; + n_inbytes = s->inbytes; + n_outbytes = s->outbytes; + + /* scaled by 2^10, but divided 2 seconds */ + rate = (n_conns - e->last_conns)<<9; + e->last_conns = n_conns; + e->cps += ((long)rate - (long)e->cps)>>2; + s->cps = (e->cps+0x1FF)>>10; + + rate = (n_inpkts - e->last_inpkts)<<9; + e->last_inpkts = n_inpkts; + e->inpps += ((long)rate - (long)e->inpps)>>2; + s->inpps = (e->inpps+0x1FF)>>10; + + rate = (n_outpkts - e->last_outpkts)<<9; + e->last_outpkts = n_outpkts; + e->outpps += ((long)rate - (long)e->outpps)>>2; + s->outpps = (e->outpps+0x1FF)>>10; + + rate = (n_inbytes - e->last_inbytes)<<4; + e->last_inbytes = n_inbytes; + e->inbps += ((long)rate - (long)e->inbps)>>2; + s->inbps = (e->inbps+0xF)>>5; + + rate = (n_outbytes - e->last_outbytes)<<4; + e->last_outbytes = n_outbytes; + e->outbps += ((long)rate - (long)e->outbps)>>2; + s->outbps = (e->outbps+0xF)>>5; + spin_unlock(&s->lock); + } + read_unlock(&est_lock); + mod_timer(&est_timer, jiffies + 2*HZ); +} + +int ip_vs_new_estimator(struct ip_vs_stats *stats) +{ + struct ip_vs_estimator *est; + + est = kmalloc(sizeof(*est), GFP_KERNEL); + if (est == NULL) + return -ENOMEM; + + memset(est, 0, sizeof(*est)); + est->stats = stats; + est->last_conns = stats->conns; + est->cps = stats->cps<<10; + + est->last_inpkts = stats->inpkts; + est->inpps = stats->inpps<<10; + + est->last_outpkts = stats->outpkts; + est->outpps = stats->outpps<<10; + + est->last_inbytes = stats->inbytes; + est->inbps = stats->inbps<<5; + + est->last_outbytes = stats->outbytes; + est->outbps = stats->outbps<<5; + + est->next = est_list; + if (est->next == NULL) { + init_timer(&est_timer); + est_timer.expires = jiffies + 2*HZ; + est_timer.function = estimation_timer; + add_timer(&est_timer); + } + write_lock_bh(&est_lock); + est_list = est; + write_unlock_bh(&est_lock); + return 0; +} + +void ip_vs_kill_estimator(struct ip_vs_stats *stats) +{ + struct ip_vs_estimator *est, **pest; + int killed = 0; + + write_lock_bh(&est_lock); + pest = &est_list; + while ((est=*pest) != NULL) { + if (est->stats != stats) { + pest = &est->next; + continue; + } + *pest = est->next; + kfree(est); + killed++; + } + if (killed && est_list == NULL) + del_timer_sync(&est_timer); + write_unlock_bh(&est_lock); +} + +void ip_vs_zero_estimator(struct ip_vs_stats *stats) +{ + struct ip_vs_estimator *e; + + write_lock_bh(&est_lock); + for (e = est_list; e; e = e->next) { + if (e->stats != stats) + continue; + + /* set counters zero */ + e->last_conns = 0; + e->last_inpkts = 0; + e->last_outpkts = 0; + e->last_inbytes = 0; + e->last_outbytes = 0; + e->cps = 0; + e->inpps = 0; + e->outpps = 0; + e->inbps = 0; + e->outbps = 0; + } + write_unlock_bh(&est_lock); +} diff --git a/pool/shard002/C/0061261_sd.c b/pool/shard002/C/0061261_sd.c new file mode 100644 index 0000000000000000000000000000000000000000..22c9540757713a6cde69137cbec3fba316d4bd6a --- /dev/null +++ b/pool/shard002/C/0061261_sd.c @@ -0,0 +1,314 @@ +/** + ****************************************************************************** + * @file BSP/Src/sd.c + * @author MCD Application Team + * @version V1.0.1 + * @date 09-October-2015 + * @brief This example code shows how to use the SD Driver + ****************************************************************************** + * @attention + * + *

© 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 "main.h" + +/** @addtogroup STM32F4xx_HAL_Examples + * @{ + */ + +/** @addtogroup BSP + * @{ + */ + +/* Private typedef -----------------------------------------------------------*/ +/* Private define ------------------------------------------------------------*/ +#define BLOCK_START_ADDR 0 /* Block start address */ +#define BLOCKSIZE 512 /* Block Size in Bytes */ +#define NUM_OF_BLOCKS 5 /* Total number of blocks */ +#define BUFFER_WORDS_SIZE ((BLOCKSIZE * NUM_OF_BLOCKS) >> 2) /* Total data size in bytes */ +/* Private macro -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +uint32_t aTxBuffer[BUFFER_WORDS_SIZE]; +uint32_t aRxBuffer[BUFFER_WORDS_SIZE]; +/* Private function prototypes -----------------------------------------------*/ +void SD_main_test(void); +void SD_Detection(void); +static void SD_SetHint(void); +static void Fill_Buffer(uint32_t *pBuffer, uint32_t uwBufferLenght, uint32_t uwOffset); +static uint8_t Buffercmp(uint32_t* pBuffer1, uint32_t* pBuffer2, uint16_t BufferLength); + +/* Private functions ---------------------------------------------------------*/ + +/** + * @brief SD Demo polling detection + * @param None + * @retval None + */ +void SD_demo (void) +{ + SD_main_test(); + + while (1) + { + SD_Detection(); + + if(CheckForUserInput() > 0) + { + BSP_SD_DeInit(); + return; + } + } +} + + +/** + * @brief SD Demo exti detection + * @param None + * @retval None + */ +void SD_exti_demo (void) +{ + + SD_main_test(); + + if(BSP_SD_IsDetected() != SD_PRESENT) + { + BSP_SD_Init(); + BSP_LCD_SetTextColor(LCD_COLOR_RED); + BSP_LCD_DisplayStringAt(20, BSP_LCD_GetYSize()-30, (uint8_t *)"SD Not Connected", LEFT_MODE); + } + else + { + BSP_LCD_SetTextColor(LCD_COLOR_GREEN); + BSP_LCD_DisplayStringAt(20, BSP_LCD_GetYSize()-30, (uint8_t *)"SD Connected ", LEFT_MODE); + } + + BSP_SD_ITConfig(); + + while (1) + { + if (exti2_received == 1) + { + exti2_received = 0; + SD_Detection(); + } + + if(CheckForUserInput() > 0) + { + BSP_SD_DeInit(); + return; + } + } +} + +/** + * @brief SD_Detection checks detection and writes msg on display + * @param None + * @retval None + */ +void SD_Detection(void) +{ + static uint8_t prev_status = 2; + + /* Check if the SD card is plugged in the slot */ + if(BSP_SD_IsDetected() != SD_PRESENT) + { + if(prev_status != SD_NOT_PRESENT) + { + //BSP_SD_Init(); + prev_status = SD_NOT_PRESENT; + BSP_LCD_SetTextColor(LCD_COLOR_RED); + BSP_LCD_DisplayStringAt(20, BSP_LCD_GetYSize()-30, (uint8_t *)"SD Not Connected", LEFT_MODE); + } + } + else if (prev_status != SD_PRESENT) + { + prev_status = SD_PRESENT; + BSP_LCD_SetTextColor(LCD_COLOR_GREEN); + BSP_LCD_DisplayStringAt(20, BSP_LCD_GetYSize()-30, (uint8_t *)"SD Connected ", LEFT_MODE); + } +} + +/** + * @brief Main part of SD Demo Test + * @param None + * @retval None + */ +void SD_main_test (void) +{ + uint8_t SD_state = SD_OK; + + SD_SetHint(); + SD_state = BSP_SD_Init(); + + if(SD_state != SD_OK) + { + if(SD_state == MSD_ERROR_SD_NOT_PRESENT) + { + BSP_LCD_DisplayStringAt(20, 100, (uint8_t *)"SD shall be inserted before running test", LEFT_MODE); + } + else + { + BSP_LCD_DisplayStringAt(20, 100, (uint8_t *)"SD Initialization : FAIL.", LEFT_MODE); + } + BSP_LCD_DisplayStringAt(20, 115, (uint8_t *)"SD Test Aborted.", LEFT_MODE); + } + else + { + BSP_LCD_DisplayStringAt(20, 100, (uint8_t *)"SD Initialization : OK.", LEFT_MODE); + + SD_state = BSP_SD_Erase(BLOCK_START_ADDR, (BLOCKSIZE * NUM_OF_BLOCKS)); + + if(SD_state != SD_OK) + { + BSP_LCD_DisplayStringAt(20, 115, (uint8_t *)"SD ERASE : FAILED.", LEFT_MODE); + BSP_LCD_DisplayStringAt(20, 130, (uint8_t *)"SD Test Aborted.", LEFT_MODE); + } + else + { + BSP_LCD_DisplayStringAt(20, 115, (uint8_t *)"SD ERASE : OK.", LEFT_MODE); + + /* Fill the buffer to write */ + Fill_Buffer(aTxBuffer, BUFFER_WORDS_SIZE, 0x22FF); + SD_state = BSP_SD_WriteBlocks(aTxBuffer, BLOCK_START_ADDR, BLOCKSIZE, NUM_OF_BLOCKS); + + if(SD_state != SD_OK) + { + BSP_LCD_DisplayStringAt(20, 130, (uint8_t *)"SD WRITE : FAILED.", LEFT_MODE); + BSP_LCD_DisplayStringAt(20, 145, (uint8_t *)"SD Test Aborted.", LEFT_MODE); + } + else + { + BSP_LCD_DisplayStringAt(20, 130, (uint8_t *)"SD WRITE : OK.", LEFT_MODE); + SD_state = BSP_SD_ReadBlocks(aRxBuffer, BLOCK_START_ADDR, BLOCKSIZE, NUM_OF_BLOCKS); + if(SD_state != SD_OK) + { + BSP_LCD_DisplayStringAt(20, 145, (uint8_t *)"SD READ : FAILED.", LEFT_MODE); + BSP_LCD_DisplayStringAt(20, 160, (uint8_t *)"SD Test Aborted.", LEFT_MODE); + } + else + { + BSP_LCD_DisplayStringAt(20, 145, (uint8_t *)"SD READ : OK.", LEFT_MODE); + if(Buffercmp(aTxBuffer, aRxBuffer, BUFFER_WORDS_SIZE) > 0) + { + BSP_LCD_DisplayStringAt(20, 160, (uint8_t *)"SD COMPARE : FAILED.", LEFT_MODE); + BSP_LCD_DisplayStringAt(20, 175, (uint8_t *)"SD Test Aborted.", LEFT_MODE); + } + else + { + BSP_LCD_DisplayStringAt(20, 160, (uint8_t *)"SD Test : OK.", LEFT_MODE); + BSP_LCD_DisplayStringAt(20, 175, (uint8_t *)"SD can be removed.", LEFT_MODE); + } + } + } + } + } +} + + + +/** + * @brief Display SD Demo Hint + * @param None + * @retval None + */ +static void SD_SetHint(void) +{ + /* Clear the LCD */ + BSP_LCD_Clear(LCD_COLOR_WHITE); + + /* Set LCD Demo description */ + BSP_LCD_SetTextColor(LCD_COLOR_BLUE); + BSP_LCD_FillRect(0, 0, BSP_LCD_GetXSize(), 80); + BSP_LCD_SetTextColor(LCD_COLOR_WHITE); + BSP_LCD_SetBackColor(LCD_COLOR_BLUE); + BSP_LCD_SetFont(&Font24); + BSP_LCD_DisplayStringAt(0, 0, (uint8_t *)"SD", CENTER_MODE); + BSP_LCD_SetFont(&Font12); + BSP_LCD_DisplayStringAt(0, 30, (uint8_t *)"This example shows how to write", CENTER_MODE); + BSP_LCD_DisplayStringAt(0, 45, (uint8_t *)"and read data on the microSD and also", CENTER_MODE); + BSP_LCD_DisplayStringAt(0, 60, (uint8_t *)"how to detect the presence of the card", CENTER_MODE); + + /* Set the LCD Text Color */ + BSP_LCD_SetTextColor(LCD_COLOR_BLUE); + BSP_LCD_DrawRect(10, 90, BSP_LCD_GetXSize() - 20, BSP_LCD_GetYSize()- 100); + BSP_LCD_DrawRect(11, 91, BSP_LCD_GetXSize() - 22, BSP_LCD_GetYSize()- 102); + + BSP_LCD_SetTextColor(LCD_COLOR_BLACK); + BSP_LCD_SetBackColor(LCD_COLOR_WHITE); + } + +/** + * @brief Fills buffer with user predefined data. + * @param pBuffer: pointer on the buffer to fill + * @param uwBufferLenght: size of the buffer to fill + * @param uwOffset: first value to fill on the buffer + * @retval None + */ +static void Fill_Buffer(uint32_t *pBuffer, uint32_t uwBufferLenght, uint32_t uwOffset) +{ + uint32_t tmpIndex = 0; + + /* Put in global buffer different values */ + for (tmpIndex = 0; tmpIndex < uwBufferLenght; tmpIndex++ ) + { + pBuffer[tmpIndex] = tmpIndex + uwOffset; + } +} + +/** + * @brief Compares two buffers. + * @param pBuffer1, pBuffer2: buffers to be compared. + * @param BufferLength: buffer's length + * @retval 1: pBuffer identical to pBuffer1 + * 0: pBuffer differs from pBuffer1 + */ +static uint8_t Buffercmp(uint32_t* pBuffer1, uint32_t* pBuffer2, uint16_t BufferLength) +{ + while (BufferLength--) + { + if (*pBuffer1 != *pBuffer2) + { + return 1; + } + + pBuffer1++; + pBuffer2++; + } + + return 0; +} +/** + * @} + */ + +/** + * @} + */ +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/pool/shard002/C/0061267_rwgif.c b/pool/shard002/C/0061267_rwgif.c new file mode 100644 index 0000000000000000000000000000000000000000..181699c1151fd724b1a6df20be75cb8a46c02973 --- /dev/null +++ b/pool/shard002/C/0061267_rwgif.c @@ -0,0 +1,161 @@ +/* -*- c -*- */ + +/* + * rwgif.c + * + * rwimg + * + * Copyright (C) 2006 Xavier Martin + * + * 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., 675 Mass Ave, Cambridge, MA 02139, USA. + */ + +#include +#include +#include + +#include +#include + +typedef struct +{ + GifFileType *file; + int width; + int height; + unsigned char *rgb; +} gif_data_t; + +void* +open_gif_file (const char *filename, int *width, int *height) +{ + int interlace_offset[] = { 0, 4, 2, 1 }; + int interlace_jump[] = { 8, 8, 4, 2 }; + GifColorType *colormap; + GifRecordType record_type; + GifRowType *buffer = NULL; + + int i, j; + int color_index; + unsigned char *ptr = NULL; + + gif_data_t *data = (gif_data_t*)malloc(sizeof(gif_data_t)); + + assert(data != 0); + + int error; + data->file = DGifOpenFileName(filename, &error); + + assert(data->file !=0); + + do + { + assert(DGifGetRecordType(data->file, &record_type) != GIF_ERROR) ; + + switch (record_type) + { + case IMAGE_DESC_RECORD_TYPE: + assert(DGifGetImageDesc(data->file) != GIF_ERROR); + + *width = data->file->Image.Width; + *height = data->file->Image.Height; + data->width = *width; + data->height = *height; + + buffer = malloc(*height * sizeof(GifRowType *)); + assert(buffer != NULL); + + for (i = 0; i < *height; i++) + { + buffer[i] = malloc(*width * sizeof(GifPixelType)); + assert(buffer[i] != NULL); + } + + if (data->file->Image.Interlace) + { + for (i = 0; i < 4; i++) + for (j = interlace_offset[i]; j < *height; + j += interlace_jump[i]) + DGifGetLine(data->file, buffer[j], *width); + } + else + { + for (i = 0; i < *height; i++) + DGifGetLine(data->file, buffer[i], *width); + } + break; + case EXTENSION_RECORD_TYPE: + { + /* Skip extension blocks */ + int ext_code; + GifByteType *ext; + assert(DGifGetExtension(data->file, &ext_code, &ext) != GIF_ERROR); + + while (ext != NULL) + { + assert(DGifGetExtensionNext(data->file, &ext) != GIF_ERROR); + } + } + break; + case TERMINATE_RECORD_TYPE: + break; + default: + fprintf(stderr, "unknown record type in GIF file\n"); + break; + } + } while (record_type != TERMINATE_RECORD_TYPE); + + + colormap = (data->file->Image.ColorMap ? data->file->Image.ColorMap->Colors + : data->file->SColorMap->Colors); + + data->rgb = (unsigned char*)malloc( (data->width* data->height * 3) ); + assert(data->rgb != NULL); + + ptr = data->rgb; + + for (j = 0; j < *height; j++) + { + for (i = 0; i < *width; i++) + { + color_index = (int) buffer[j][i]; + *ptr++ = (unsigned char) colormap[color_index].Red; + *ptr++ = (unsigned char) colormap[color_index].Green; + *ptr++ = (unsigned char) colormap[color_index].Blue; + } + free(buffer[j]); + } + free(buffer); + + assert(DGifCloseFile(data->file, &error) == GIF_OK); + + return data; +} + +void +gif_read_lines (void *_data, unsigned char *lines, int num_lines) +{ + gif_data_t *data = (gif_data_t*)_data; + + memcpy(lines, data->rgb, data->width * num_lines * 3); +} + +void +gif_free_data (void *_data) +{ + gif_data_t *data = (gif_data_t*)_data; + + free(data->rgb); + free(data); +} diff --git a/pool/shard002/C/0061273_graph.c b/pool/shard002/C/0061273_graph.c new file mode 100644 index 0000000000000000000000000000000000000000..ee0f36a5b51ba5c8c8921ebf93f5072823b7de3a --- /dev/null +++ b/pool/shard002/C/0061273_graph.c @@ -0,0 +1,204 @@ +#include "graph.h" + +void graphGen(graph* g) +{ + + LONG_T *startVertex, *endVertex; + WEIGHT_T *weights; + LONG_T i, j, u, v; + WEIGHT_T w; + LONG_T estNumEdges, numEdges, edgeNum; + int *stream1, *stream2; + FILE* outfp; + + /*----------------------------------------------*/ + /* initialize SPRNG */ + /*----------------------------------------------*/ + + stream1 = init_sprng(SPRNG_CMRG, 0, 1, SPRNG_SEED1, SPRNG_DEFAULT); + stream2 = init_sprng(SPRNG_CMRG, 0, 1, SPRNG_SEED2, SPRNG_DEFAULT); + + /*------------------------------------------------------*/ + /* generate edges as per the */ + /* graph model and user options */ + /*------------------------------------------------------*/ + + if ((STORE_IN_MEMORY == 0) && (SORT_EDGELISTS == 0)) { + fprintf(stderr, "Generating edges on the fly\n"); + outfp = fopen(OUTFILE, "w"); + fprintf(outfp, "c FILE : %s\n", OUTFILE); + fprintf(outfp, "c No. of vertices : %ld\n", n); + if (GRAPH_MODEL == 1) + fprintf(outfp, "c No. of edges : %ld\n", m); + else + fprintf(outfp, " \n"); + fprintf(outfp, "c Max. weight : %ld\n", MAX_WEIGHT); + fprintf(outfp, "c Min. weight : %ld\n", MIN_WEIGHT); + fprintf(outfp, "c A directed arc from u to v of weight w\n"); + fprintf(outfp, "c is represented below as ' a u v w '\n"); + fprintf(stderr, "Generating Edges ... "); + + /* Erdos-Renyi */ + if (GRAPH_MODEL == 0) { + + /* Write the no. of edges later */ + fprintf(outfp, " \n"); + numEdges = 0; + + for (i=0; i sprng(stream1)) { + w = MIN_WEIGHT + (WEIGHT_T) \ + (MAX_WEIGHT - MIN_WEIGHT) * sprng(stream2); + /* Create edge */ + fprintf(outfp, "a %ld %ld %ld\n", i+1, j+1, w); + numEdges++; + } + + } + } + + m = numEdges; + fclose(outfp); + fprintf(stderr, "done\n"); + updateEdgeVal(OUTFILE, numEdges); + + } else { + + fprintf(outfp, "p sp %ld %ld\n", n, m); + numEdges = 0; + + for (i=0; i sprng(stream1)) { + + startVertex[edgeNum] = i; + endVertex[edgeNum] = j; + edgeNum++; + + } + } + + } + + numEdges = edgeNum; + + } else { + + startVertex = (LONG_T *) malloc(m * sizeof(LONG_T)); + endVertex = (LONG_T *) malloc(m * sizeof(LONG_T)); + + for (i=0; istart = startVertex; + g->end = endVertex; + g->w = weights; + g->n = n; + g->m = numEdges; +} diff --git a/pool/shard002/C/0061288_2005.c b/pool/shard002/C/0061288_2005.c new file mode 100644 index 0000000000000000000000000000000000000000..93610261a36ea9ce352626fee69119e44ce9dc85 --- /dev/null +++ b/pool/shard002/C/0061288_2005.c @@ -0,0 +1,33 @@ +#include +#include + +int MONTH[12] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; +int IsLeapYear(int year); +int DayRank(int year, int month, int date); + +int main() +{ + int year, month, date; + int days = 0; + while (scanf("%d/%d/%d", &year, &month, &date) != EOF) { + days = DayRank(year, month, date); + printf("%d\n", days); + } + return 0; +} + +int IsLeapYear(int year) +{ + return ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)); +} + +int DayRank(int year, int month, int date) +{ + int days = 0, i; + int flag = IsLeapYear(year); + if (flag) MONTH[1] = 29; + else MONTH[1] = 28; + for (i = 0; i < month - 1; ++i) days += MONTH[i]; + days += date; + return days; +} diff --git a/pool/shard002/C/0061292_ioctl.c b/pool/shard002/C/0061292_ioctl.c new file mode 100644 index 0000000000000000000000000000000000000000..912c0460bfc4b67b6d96676c9a0f5e4c765d64d0 --- /dev/null +++ b/pool/shard002/C/0061292_ioctl.c @@ -0,0 +1,67 @@ +/* + * ioctl.c + * + * Copyright (C) 1995, 1996 by Volker Lendecke + * Copyright (C) 1997 by Volker Lendecke + * + * Please add a note about your changes to smbfs in the ChangeLog file. + */ + +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +#include + +#include "proto.h" + +int +smb_ioctl(struct inode *inode, struct file *filp, + unsigned int cmd, unsigned long arg) +{ + struct smb_sb_info *server = server_from_inode(inode); + struct smb_conn_opt opt; + int result = -EINVAL; + + switch (cmd) { + uid16_t uid16; + uid_t uid32; + case SMB_IOC_GETMOUNTUID: + SET_UID(uid16, server->mnt->mounted_uid); + result = put_user(uid16, (uid16_t *) arg); + break; + case SMB_IOC_GETMOUNTUID32: + SET_UID(uid32, server->mnt->mounted_uid); + result = put_user(uid32, (uid_t *) arg); + break; + + case SMB_IOC_NEWCONN: + /* arg is smb_conn_opt, or NULL if no connection was made */ + if (!arg) { + result = 0; + smb_lock_server(server); + server->state = CONN_RETRIED; + printk(KERN_ERR "Connection attempt failed! [%d]\n", + server->conn_error); + smbiod_flush(server); + smb_unlock_server(server); + break; + } + + result = -EFAULT; + if (!copy_from_user(&opt, (void *)arg, sizeof(opt))) + result = smb_newconn(server, &opt); + break; + default: + break; + } + + return result; +} diff --git a/pool/shard002/C/0061322_scrobbler.c b/pool/shard002/C/0061322_scrobbler.c new file mode 100644 index 0000000000000000000000000000000000000000..7d9c65814ddd76d6798710248c121fb7de40dc1a --- /dev/null +++ b/pool/shard002/C/0061322_scrobbler.c @@ -0,0 +1,302 @@ +/*************************************************************************** + * __________ __ ___. + * Open \______ \ ____ ____ | | _\_ |__ _______ ___ + * Source | _// _ \_/ ___\| |/ /| __ \ / _ \ \/ / + * Jukebox | | ( <_> ) \___| < | \_\ ( <_> > < < + * Firmware |____|_ /\____/ \___ >__|_ \|___ /\____/__/\_ \ + * \/ \/ \/ \/ \/ + * $Id$ + * + * Copyright (C) 2006-2008 Robert Keevil + * + * 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 software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + ****************************************************************************/ +/* +Audioscrobbler spec at: +http://www.audioscrobbler.net/wiki/Portable_Player_Logging +*/ + +#include +#include +#include "file.h" +#include "logf.h" +#include "metadata.h" +#include "kernel.h" +#include "audio.h" +#include "core_alloc.h" +#include "settings.h" +#include "ata_idle_notify.h" +#include "filefuncs.h" +#include "appevents.h" + +#if CONFIG_RTC +#include "time.h" +#include "timefuncs.h" +#endif + +#include "scrobbler.h" + +#define SCROBBLER_VERSION "1.1" + +/* increment this on any code change that effects output */ +#define SCROBBLER_REVISION " $Revision$" + +#define SCROBBLER_MAX_CACHE 32 +/* longest entry I've had is 323, add a safety margin */ +#define SCROBBLER_CACHE_LEN 512 + +static bool scrobbler_initialised = false; +static int scrobbler_cache = 0; +static int cache_pos = 0; +static bool pending = false; +#if CONFIG_RTC +static time_t timestamp; +#define BASE_FILENAME ".scrobbler.log" +#define HDR_STR_TIMELESS +#define get_timestamp() ((long)timestamp) +#define record_timestamp() ((void)(timestamp = mktime(get_time()))) +#else /* !CONFIG_RTC */ +#define HDR_STR_TIMELESS " Timeless" +#define BASE_FILENAME ".scrobbler-timeless.log" +#define get_timestamp() (0l) +#define record_timestamp() ({}) +#endif /* CONFIG_RTC */ + +static void get_scrobbler_filename(char *path, size_t size) +{ + int used; +/* Get location of USB mass storage area */ +#ifdef APPLICATION +#if (CONFIG_PLATFORM & PLATFORM_MAEMO) + used = snprintf(path, size, "/home/user/MyDocs/%s", BASE_FILENAME); +#elif (CONFIG_PLATFORM & PLATFORM_ANDROID) + used = snprintf(path, size, "/sdcard/rockbox/%s", BASE_FILENAME); +#elif defined (SAMSUNG_YPR0) + used = snprintf(path, size, "%s/%s", HOME_DIR, BASE_FILENAME); +#else /* SDL/unknown RaaA build */ + used = snprintf(path, size, "%s/%s", ROCKBOX_DIR, BASE_FILENAME); +#endif /* (CONFIG_PLATFORM & PLATFORM_MAEMO) */ + +#else + used = snprintf(path, size, "/%s", BASE_FILENAME); +#endif + + if (used >= (int)size) + { + logf("SCROBBLER: not enough buffer space for log file"); + memset(path, 0, size); + } +} + +static void write_cache(void) +{ + int i; + int fd; + + char scrobbler_file[MAX_PATH]; + get_scrobbler_filename(scrobbler_file, MAX_PATH); + + /* If the file doesn't exist, create it. + Check at each write since file may be deleted at any time */ + if(!file_exists(scrobbler_file)) + { + fd = open(scrobbler_file, O_RDWR | O_CREAT, 0666); + if(fd >= 0) + { + fdprintf(fd, "#AUDIOSCROBBLER/" SCROBBLER_VERSION "\n" + "#TZ/UNKNOWN\n" "#CLIENT/Rockbox " + TARGET_NAME SCROBBLER_REVISION + HDR_STR_TIMELESS "\n"); + + close(fd); + } + else + { + logf("SCROBBLER: cannot create log file"); + } + } + + /* write the cache entries */ + fd = open(scrobbler_file, O_WRONLY | O_APPEND); + if(fd >= 0) + { + logf("SCROBBLER: writing %d entries", cache_pos); + /* copy data to temporary storage in case data moves during I/O */ + char temp_buf[SCROBBLER_CACHE_LEN]; + for ( i=0; i < cache_pos; i++ ) + { + logf("SCROBBLER: write %d", i); + char* scrobbler_buf = core_get_data(scrobbler_cache); + ssize_t len = strlcpy(temp_buf, scrobbler_buf+(SCROBBLER_CACHE_LEN*i), + sizeof(temp_buf)); + if (write(fd, temp_buf, len) != len) + break; + } + close(fd); + } + else + { + logf("SCROBBLER: error writing file"); + } + + /* clear even if unsuccessful - don't want to overflow the buffer */ + cache_pos = 0; +} + +static void scrobbler_flush_callback(void) +{ + if (scrobbler_initialised && cache_pos) + write_cache(); +} + +static void add_to_cache(const struct mp3entry *id) +{ + if ( cache_pos >= SCROBBLER_MAX_CACHE ) + write_cache(); + + char rating = 'S'; /* Skipped */ + char* scrobbler_buf = core_get_data(scrobbler_cache); + + logf("SCROBBLER: add_to_cache[%d]", cache_pos); + + if (id->elapsed > id->length / 2) + rating = 'L'; /* Listened */ + + char tracknum[11] = { "" }; + + if (id->tracknum > 0) + snprintf(tracknum, sizeof (tracknum), "%d", id->tracknum); + + int ret = snprintf(scrobbler_buf+(SCROBBLER_CACHE_LEN*cache_pos), + SCROBBLER_CACHE_LEN, + "%s\t%s\t%s\t%s\t%d\t%c\t%ld\t%s\n", + id->artist, + id->album ?: "", + id->title, + tracknum, + (int)(id->length / 1000), + rating, + get_timestamp(), + id->mb_track_id ?: ""); + + if ( ret >= SCROBBLER_CACHE_LEN ) + { + logf("SCROBBLER: entry too long:"); + logf("SCROBBLER: %s", id->path); + } + else + { + cache_pos++; + register_storage_idle_func(scrobbler_flush_callback); + } + +} + +static void scrobbler_change_event(unsigned short id, void *ev_data) +{ + (void)id; + struct mp3entry *id3 = ((struct track_event *)ev_data)->id3; + + /* check if track was resumed > %50 played + check for blank artist or track name */ + if (id3->elapsed > id3->length / 2 || !id3->artist || !id3->title) + { + pending = false; + logf("SCROBBLER: skipping file %s", id3->path); + } + else + { + logf("SCROBBLER: add pending"); + record_timestamp(); + pending = true; + } +} + +static void scrobbler_finish_event(unsigned short id, void *data) +{ + (void)id; + struct track_event *te = (struct track_event *)data; + + /* add entry using the currently ending track */ + if (pending && (te->flags & TEF_CURRENT) +#if CONFIG_CODEC == SWCODEC + && !(te->flags & TEF_REWIND) +#endif + ) + { + pending = false; + add_to_cache(te->id3); + } +} + +int scrobbler_init(void) +{ + if (scrobbler_initialised) + return 1; + + scrobbler_cache = core_alloc("scrobbler", + SCROBBLER_MAX_CACHE*SCROBBLER_CACHE_LEN); + + if (scrobbler_cache <= 0) + { + logf("SCROOBLER: OOM"); + return -1; + } + + cache_pos = 0; + pending = false; + + scrobbler_initialised = true; + + add_event(PLAYBACK_EVENT_TRACK_CHANGE, scrobbler_change_event); + add_event(PLAYBACK_EVENT_TRACK_FINISH, scrobbler_finish_event); + + return 1; +} + +static void scrobbler_flush_cache(void) +{ + /* Add any pending entries to the cache */ + if (pending) + { + pending = false; + if (audio_status()) + add_to_cache(audio_current_track()); + } + + /* Write the cache to disk if needed */ + if (cache_pos) + write_cache(); +} + +void scrobbler_shutdown(bool poweroff) +{ + if (!scrobbler_initialised) + return; + + remove_event(PLAYBACK_EVENT_TRACK_CHANGE, scrobbler_change_event); + remove_event(PLAYBACK_EVENT_TRACK_FINISH, scrobbler_finish_event); + + scrobbler_flush_cache(); + + if (!poweroff) + { + /* get rid of the buffer */ + core_free(scrobbler_cache); + scrobbler_cache = 0; + } + + scrobbler_initialised = false; +} + +bool scrobbler_is_enabled(void) +{ + return scrobbler_initialised; +} diff --git a/pool/shard002/C/0061332_certificate.c b/pool/shard002/C/0061332_certificate.c new file mode 100644 index 0000000000000000000000000000000000000000..7346c564986455ca357a1fb477b78548740afc37 --- /dev/null +++ b/pool/shard002/C/0061332_certificate.c @@ -0,0 +1,318 @@ +/** @file + * + @brief Certificate: Handle sending a certificate request to the website + and receiving its response. + + @author + Tolu Alabi, Zach Butler, Martin Dluhos, Chase Felker, Radhika Krishnar + + @date + Created February 21, 2012
+ Last revised: May 6, 2012 + +*/ + +#include "certificate.h" + +//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ +// Helpers +//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ + +/** + * @brief Tell the curl functions where to write the data they receive from a network + * + * @remark wrfu is shorthand for Write Function. + * + * @param ptr a pointer to the location where the data will be stored + * @param size FIXME + * @param nmemb the size of the data written + * @param stream FIXME + * + * @return FIXME + */ +static size_t wrfu (void *ptr, size_t size, size_t nmemb, void *stream) +{ + (void) stream; + (void) ptr; + return size * nmemb; +} + +/** + * @brief Combines curl cleanup calls. + * @param curl_handle ___. FIXME + */ +static void curl_cleanup(CURL* curl_handle) +{ + curl_easy_cleanup(curl_handle); + curl_global_cleanup(); +} + +/** + * @brief Changes fingerprint (hex characters) to upper case. + * @param fingerprint pointer to the string to be changed into upper case. + */ +static void to_upper_case(char* fingerprint) +{ + int i=0; + while(fingerprint[i]) + { + if( (fingerprint[i] != ':') && + (fingerprint[i] >= 'a') && + (fingerprint[i] <= 'f')) + fingerprint[i] -= 32; + i++; + } +} + +/** + * @brief converts the PEM certificate to its corresponding SHA1 fingerprint + * + * @param cert array of certificates to be converted. + * @param fingerprints pointer to the array to which @c get_fingerprint_from_cert writes the SHA1 fingerprints + * @param num_of_certs size of the @c cert array + */ +static void get_fingerprint_from_cert (char** cert, char** fingerprints, int num_of_certs) +{ + ssize_t len; + BIO* bio_buffer; + X509* decoded_certificate; + const EVP_MD* digest; + unsigned char md[EVP_MAX_MD_SIZE]; + unsigned int n; + char errmsg[1024]; + unsigned err; + int pos; + + //initialize OpenSSL + //this allows us to access error messages + SSL_load_error_strings(); + + //this initializes the library for ssl (algorithms) + SSL_library_init(); + + //temporary value to store parts of the fingerprint + char* temp = malloc(sizeof(char) * 4); + + int i; + for(i=0; iurl); + curl_easy_setopt(curl, CURLOPT_PORT, host_to_verify->port); + curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, wrfu); + + curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0L); + curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0L); + + curl_easy_setopt(curl, CURLOPT_VERBOSE, 0L); + curl_easy_setopt(curl, CURLOPT_CERTINFO, 1L); + + //res is 0 if curl_easy_perform succeeds. + res = curl_easy_perform(curl); + + //Initialize ci and determine number of certificates. + if(!res) { + struct curl_certinfo *ci = NULL; + res = curl_easy_getinfo(curl, CURLINFO_CERTINFO, &ci); + number_of_certs = ci->num_of_certs; + + //allocate memory for the array to store the retrieved certificates + char** certificates; + certificates = (char**)calloc(number_of_certs, sizeof *certificates); + + int i; + if((!res) && ci) + { + for(i=0; icertinfo[i]; slist; slist = slist->next) + if(!strncmp(slist->data, "Cert:", 5)) + { + certificates[i] = slist->data+5; + //printf("%s\n", certificates[i]); + } + } + + //retrieve the fingerprints from these certificates + get_fingerprint_from_cert(certificates, fingerprints, number_of_certs); + + //Cleanup curl + curl_cleanup(curl); + + return number_of_certs; + } + else + { + fprintf(stderr, "Could not retrieve certificate from server\n"); + curl_cleanup(curl); + return 0; + } //If the certificate cannot be retrieved from the server, return 0 + } + else + { + fprintf(stderr, "Could not establish a connection with the server\n"); + curl_cleanup(curl); + return 0; + } //If curl could not establish a connection with server, return 0 + } + else + { + fprintf(stderr, "Could not initialize CURL\n"); + curl_cleanup(curl); + return 0; + } //if curl could not be initialized, return 0 +} +// request_certificate + + +/** + * @brief Verifies that the fingerprint from the website matches the fingerprint from the user. + * + * @return 1 if fingerprints match, 0 otherwise. + */ +int +verify_certificate (const char *fingerprint_from_client, char **fingerprints_from_website, int num_of_website_certs) +{ + //variable to store the result of the fingerprint comparison + int result_of_comparison = 0; + + //this variable is used to store the fingerprint from the client + //in order for the fingerprint to be changed to uppercase + char* client_fingerprint = malloc(sizeof(char) * FPT_LENGTH); + strcpy(client_fingerprint, fingerprint_from_client); + to_upper_case(client_fingerprint); + + int i; + for(i=0; i< num_of_website_certs; i++) + { + to_upper_case(fingerprints_from_website[i]); + if(strcmp(client_fingerprint, fingerprints_from_website[i]) == 0) + { + result_of_comparison = 1; + break; + } + } + + free(client_fingerprint); + return result_of_comparison; +} // verify_certificate + + +/** + * @brief Verifies that a fingerprint has the correct format. + * + * @return 1 if the fingerprint is correctly formatted, 0 otherwise. + */ +int +verify_fingerprint_format (char *fingerprint) +{ + /* Length of SHA-1 fingerprint */ + int fpt_length = 59; + int i; + + /* Check the length of the fingerprint. */ + if (strlen (fingerprint) != fpt_length) + return 0; + + /* Check three characters at a time until reaching the last colon. There are +* 19 sequences of two hex and one colon characters. +*/ + for (i = 0; i < fpt_length-2; i++) + { + /* Check if the first two characters are hex and the third a colon. */ + if (isxdigit (fingerprint[i])) + i++; + else + return 0; + + if (isxdigit (fingerprint[i])) + i++; + else + return 0; + + if (! (fingerprint[i] == ':') ) + return 0; + + } + + /* Check the last two characters. */ + if (isxdigit (fingerprint[i])) + i++; + else + return 0; + + if (isxdigit (fingerprint[i])) + return 1; + else + return 0; +} // verify_fingerprint_format diff --git a/pool/shard002/C/0061341_config.c b/pool/shard002/C/0061341_config.c new file mode 100644 index 0000000000000000000000000000000000000000..bef1208c1c70cc917ae95d535b019832d0a87aa6 --- /dev/null +++ b/pool/shard002/C/0061341_config.c @@ -0,0 +1,112 @@ +/** + * @file + * @copyright 1998-2004 Jonathan Brown + * @license https://www.gnu.org/licenses/gpl-3.0.html + * @homepage https://github.com/bluedroplet/emergence + */ + +#ifdef LINUX +#define _GNU_SOURCE +#define _REENTRANT +#endif + +#include +#include + + +#include "../../common/types.h" +#include "../../common/stringbuf.h" +#include "../../common/user.h" +#include "parse.h" +#include "cvar.h" +#include "../console.h" + +#ifdef EMCLIENT +#include "../control.h" +#endif + +#ifdef LINUX +#include "../entry.h" +#endif + +#ifdef WIN32 +#include "../nfcl/win32/entry.h" +#endif + +int exec_config_file(char *filename) +{ + if(!filename) + return 0; + + if(!*filename) + return 0; + + FILE *file = fopen(filename, "r"); + + if(!file) + { + console_print("Could not execute file \""); + console_print(filename); + console_print("\"\n"); + return 0; + } + + console_print("Executing \""); + console_print(filename); + console_print("\"\n"); + + + struct string_t *s = new_string(); + + char c; + + do + { + c = fgetc(file); + + while(c != EOF && c != '\n') + { + string_cat_char(s, c); + c = fgetc(file); + } + + parse_command(s->text); + + string_clear(s); + + } while(c != EOF); + + fclose(file); + + free_string(s); + + return 1; +} + + +void write_config_file() +{ + struct string_t *string = new_string_string(emergence_home_dir); +#ifdef EMCLIENT + string_cat_text(string, "/client.config"); +#else + string_cat_text(string, "/server.config"); +#endif + + FILE *file = fopen(string->text, "w"); + + free_string(string); + + if(!file) + return; + + fputs("// do not put commands other than bind in this file\n\n", file); + + dump_cvars(file); + + #ifdef EMCLIENT + dump_bindings(file); + #endif + + fclose(file); +} diff --git a/pool/shard002/C/0061348_measure_rectangles.debug.c b/pool/shard002/C/0061348_measure_rectangles.debug.c new file mode 100644 index 0000000000000000000000000000000000000000..c1805bb939dac936a05b0f808e66216899442e1a --- /dev/null +++ b/pool/shard002/C/0061348_measure_rectangles.debug.c @@ -0,0 +1,140 @@ +/*********************************************************************** + * Copyright (C) 2002,2003,2004,2005,2006,2007,2008 Carsten Urbach + * + * This file is part of tmLQCD. + * + * tmLQCD 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. + * + * tmLQCD 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 tmLQCD. If not, see . + ***********************************************************************/ + +/******************************************************************* + * + * Here the 1x2 rectangles are implemented + * for renormalization group improved gauge + * actions like the DBW2 or the Iwasaki + * gauge action. + * + * 1/3 \sum_{\mu\leq\nu;\mu,nu=1}^4 Tr U^{1x2} + * + * author: Carsten Urbach + * + * + *******************************************************************/ + +#ifdef HAVE_CONFIG_H +#include "tmlqcd_config.h" +#endif +#include +#include +#include +#ifdef TM_USE_MPI +#include +#endif +#include "global.h" +#include "sse.h" +#include "su3.h" +#include "su3adj.h" +#include "geometry_eo.h" +#include "measure_rectangles.h" + + +double measure_rectangles() { + int i, j, k, mu, nu; + int x, y, z, t; + static su3 pr1, pr2, tmp; + su3 *v = NULL , *w = NULL; + static double ga, ac, gas; + static double ks, kc, tr, ts, tt; + kc=0.0; ks=0.0; + double d = 0.; + FILE * debugfile; + char filename[100]; + + sprintf(filename,"debug_mr.s"); +#ifdef PARALLELT + sprintf(filename,"debug_mr.pt.%d", g_proc_id); +#endif +#ifdef PARALLELXT + sprintf(filename,"debug_mr.pxt.%d", g_proc_id); +#endif + debugfile = fopen(filename,"w"); + + for(x = 0; x < LX; x++) { + for(y = 0; y < LY; y++) { + for(z = 0; z < LZ; z++) { + for(t = 0; t < T; t++) { + i = g_ipt[t][x][y][z]; + + for (mu = 0; mu < 4; mu++) { + d = 0.; + for (nu = 0; nu < 4; nu++) { + if(nu != mu) { + /* + ^ + | + ^ + | + -> + */ + j = g_iup[i][mu]; + k = g_iup[j][nu]; + v = &g_gauge_field[i][mu]; + w = &g_gauge_field[j][nu]; + _su3_times_su3(tmp, *v, *w); + v = &g_gauge_field[k][nu]; + _su3_times_su3(pr1, tmp, *v); + /* + -> + ^ + | + ^ + | + */ + j = g_iup[i][nu]; + k = g_iup[j][nu]; + v = &g_gauge_field[i][nu]; + w = &g_gauge_field[j][nu]; + _su3_times_su3(tmp, *v, *w); + v = &g_gauge_field[k][mu]; + _su3_times_su3(pr2, tmp, *v); + + /* Trace it */ + _trace_su3_times_su3d(ac,pr1,pr2); + d += ac; + /* printf("i mu nu: %d %d %d, ac = %e\n", i, mu, nu, ac); */ + /* Kahan summation */ + tr=ac+kc; + ts=tr+ks; + tt=ts-ks; + ks=ts; + kc=tr-tt; + } + } + fprintf(debugfile,"%d %d %d %d %d %e\n", + g_proc_coords[0]*T+t, g_proc_coords[1]*LX+x, y, z, mu, d); + } + + } + } + } + } +/* fprintf(debugfile,"###\n"); */ + fclose(debugfile); + ga=(kc+ks)/3.0; +#ifdef TM_USE_MPI + MPI_Allreduce(&ga, &gas, 1, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD); + return gas; +#else + return ga; +#endif +} diff --git a/pool/shard002/C/0061351_debug.c b/pool/shard002/C/0061351_debug.c new file mode 100644 index 0000000000000000000000000000000000000000..7ce6e581ec518258cc000e7707fa3db3508a72b6 --- /dev/null +++ b/pool/shard002/C/0061351_debug.c @@ -0,0 +1,187 @@ +/** + * \file debug.c + * \author Alexander Winiger (alexander.winiger@hslu.ch) + * \date 13.11.2015 + * \brief Debug output helper + * + */ + +#if !defined(USE_KINETIS_SDK) +/******************************************************************************* + * INCLUDE FILES + ******************************************************************************/ +#include +#include +#include +#include "board.h" +#include "debug.h" +#include "print_scan.h" + +/******************************************************************************* + * PRIVATE FUNCTION PROTOTYPES (STATIC) + ******************************************************************************/ +static int debug_putc( int ch, void* stream ); + +/******************************************************************************* + * PRIVATE VARIABLES (STATIC) + ******************************************************************************/ +static Uart_t *dbg_stdio; + +/******************************************************************************* + * MODULE FUNCTIONS (PUBLIC) + ******************************************************************************/ +uint8_t DbgConsole_Init( Uart_t *stdio ) +{ + dbg_stdio = stdio; + + return ERR_OK; +} + +#pragma weak _write +int _write( int handle, char *buffer, int size ) +{ + if ( buffer == 0 ) { + /* return -1 if error */ + return -1; + } + + /* This function only writes to "standard out" and "standard err",*/ + /* for all other file handles it returns failure.*/ + if ( (handle != 1) && (handle != 2) ) { + return -1; + } + + /* Do nothing if the debug uart is not initialized.*/ + if ( dbg_stdio == NULL ) { + return -1; + } + + /* Send data.*/ + UartPutBuffer(dbg_stdio, (uint8_t *) buffer, size); + return size; +} + +#pragma weak _read +int _read( int handle, char *buffer, int size ) +{ + /* This function only reads from "standard in", for all other file*/ + /* handles it returns failure.*/ + if ( handle != 0 ) { + return -1; + } + + /* Do nothing if the debug uart is not initialized.*/ + if ( dbg_stdio == NULL ) { + return -1; + } + + /* Receive data.*/ + UartGetBuffer(dbg_stdio, (uint8_t *) buffer, size, (void*) NULL); + + return size; +} + +/*************Code for debug_printf/scanf/assert*******************************/ +int debug_printf( const char *fmt_s, ... ) +{ + va_list ap; + int result; + /* Do nothing if the debug uart is not initialized.*/ + if ( dbg_stdio == NULL ) { + return -1; + } + va_start(ap, fmt_s); + result = _doprint(NULL, debug_putc, -1, (char *) fmt_s, ap); + va_end(ap); + + return result; +} + +int debug_putchar( int ch ) +{ + /* Do nothing if the debug uart is not initialized.*/ + if ( dbg_stdio == NULL ) { + return -1; + } + debug_putc(ch, NULL); + + return 1; +} + +int debug_scanf( const char *fmt_ptr, ... ) +{ + char temp_buf[IO_MAXLINE]; + va_list ap; + uint32_t i; + char result; + + /* Do nothing if the debug uart is not initialized.*/ + if ( dbg_stdio == NULL ) { + return -1; + } + va_start(ap, fmt_ptr); + temp_buf[0] = '\0'; + + for ( i = 0; i < IO_MAXLINE; i++ ) { + temp_buf[i] = result = debug_getchar(); + + if ( (result == '\r') || (result == '\n') ) { + /* End of Line */ + if ( i == 0 ) { + i = (uint32_t) - 1; + } else { + break; + } + } + + temp_buf[i + 1] = '\0'; + } + + result = scan_prv(temp_buf, (char *) fmt_ptr, ap); + va_end(ap); + + return result; +} + +int debug_getchar( void ) +{ + unsigned char c; + + /* Do nothing if the debug uart is not initialized.*/ + if ( dbg_stdio == NULL ) { + return -1; + } + UartGetBuffer(dbg_stdio, &c, 1, (void*) NULL); + + return c; +} + +/******************************************************************************* + * PRIVATE FUNCTIONS (STATIC) + ******************************************************************************/ +static int debug_putc( int ch, void* stream ) +{ + const unsigned char c = (unsigned char) ch; + /* Do nothing if the debug uart is not initialized.*/ + if ( dbg_stdio == NULL ) { + return -1; + } +#if defined(USE_CUSTOM_UART_HAL) + UartPutBuffer(dbg_stdio, (uint8_t *) &c, 1); +#else + UartPutChar(dbg_stdio, c); +#endif + + return 0; + +} + +void debug_assert( const char* file, int line ) +{ + asm volatile("bkpt"); +} /* end debug_assert */ + +#endif /* USE_KINETIS_SDK */ +/******************************************************************************* + * END OF CODE + ******************************************************************************/ diff --git a/pool/shard002/C/0061358_mapistore_test.c b/pool/shard002/C/0061358_mapistore_test.c new file mode 100644 index 0000000000000000000000000000000000000000..3471bf84d088b8ccbcaca4a094bb9632062f4769 --- /dev/null +++ b/pool/shard002/C/0061358_mapistore_test.c @@ -0,0 +1,118 @@ +/* + OpenChange Storage Abstraction Layer library test tool + + OpenChange Project + + Copyright (C) Julien Kerihuel 2009 + + 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 "mapiproxy/libmapistore/mapistore.h" +#include "mapiproxy/libmapistore/mapistore_errors.h" +#include +#include +#include + +/** + \file mapistore_test.c + + \brief Test mapistore implementation + */ + + +int main(int argc, const char *argv[]) +{ + TALLOC_CTX *mem_ctx; + int retval; + struct mapistore_context *mstore_ctx; + struct loadparm_context *lp_ctx; + poptContext pc; + int opt; + const char *opt_debug = NULL; + uint32_t context_id = 0; + uint32_t context_id2 = 0; + uint32_t context_id3 = 0; + void *root_folder; + + enum { OPT_DEBUG=1000 }; + + struct poptOption long_options[] = { + POPT_AUTOHELP + { "debuglevel", 'd', POPT_ARG_STRING, NULL, OPT_DEBUG, "set the debug level", NULL }, + { NULL, 0, 0, NULL, 0, NULL, NULL } + }; + + mem_ctx = talloc_named(NULL, 0, "mapistore_test"); + lp_ctx = loadparm_init_global(true); + oc_log_init_stdout(); + + pc = poptGetContext("mapistore_test", argc, argv, long_options, 0); + while ((opt = poptGetNextOpt(pc)) != -1) { + switch (opt) { + case OPT_DEBUG: + opt_debug = poptGetOptArg(pc); + break; + } + } + + poptFreeContext(pc); + + if (opt_debug) { + lpcfg_set_cmdline(lp_ctx, "log level", opt_debug); + } + + retval = mapistore_set_mapping_path("/tmp"); + if (retval != MAPISTORE_SUCCESS) { + OC_DEBUG(0, "%s\n", mapistore_errstr(retval)); + exit (1); + } + + mstore_ctx = mapistore_init(mem_ctx, lp_ctx, NULL); + if (!mstore_ctx) { + exit (1); + } + + retval = mapistore_add_context(mstore_ctx, "openchange", "sqlite:///tmp/test.db", -1, &context_id, &root_folder); + if (retval != MAPISTORE_SUCCESS) { + OC_DEBUG(0, "%s\n", mapistore_errstr(retval)); + exit (1); + } + + retval = mapistore_add_context(mstore_ctx, "openchange", "sqlite:///tmp/test2.db", -1, &context_id2, &root_folder); + if (retval != MAPISTORE_SUCCESS) { + OC_DEBUG(0, "%s\n", mapistore_errstr(retval)); + exit (1); + } + + OC_DEBUG(0, "Context ID: [1] = %d and [2] = %d\n", context_id, context_id2); + + retval = mapistore_add_context(mstore_ctx, "openchange", "fsocpf:///tmp/fsocpf", -1, &context_id3, &root_folder); + if (retval != MAPISTORE_SUCCESS) { + OC_DEBUG(0, "%s\n", mapistore_errstr(retval)); + exit (1); + } + + retval = mapistore_del_context(mstore_ctx, context_id); + retval = mapistore_del_context(mstore_ctx, context_id2); + retval = mapistore_del_context(mstore_ctx, context_id3); + + retval = mapistore_release(mstore_ctx); + if (retval != MAPISTORE_SUCCESS) { + OC_DEBUG(0, "%s\n", mapistore_errstr(retval)); + exit(1); + } + + return 0; +} diff --git a/pool/shard002/C/0061365_pbsD_holdjob.c b/pool/shard002/C/0061365_pbsD_holdjob.c new file mode 100644 index 0000000000000000000000000000000000000000..8629e0efbb48013e6c062147a41c89229923a1e5 --- /dev/null +++ b/pool/shard002/C/0061365_pbsD_holdjob.c @@ -0,0 +1,88 @@ +/* + * Copyright (C) 1994-2016 Altair Engineering, Inc. + * For more information, contact Altair at www.altair.com. + * + * This file is part of the PBS Professional ("PBS Pro") software. + * + * Open Source License Information: + * + * PBS Pro is free software. You can redistribute it and/or modify it under the + * terms of the GNU Affero General Public License as published by the Free + * Software Foundation, either version 3 of the License, or (at your option) any + * later version. + * + * PBS Pro 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 Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License along + * with this program. If not, see . + * + * Commercial License Information: + * + * The PBS Pro software is licensed under the terms of the GNU Affero General + * Public License agreement ("AGPL"), except where a separate commercial license + * agreement for PBS Pro version 14 or later has been executed in writing with Altair. + * + * Altair’s dual-license business model allows companies, individuals, and + * organizations to create proprietary derivative works of PBS Pro and distribute + * them - whether embedded or bundled with other software - under a commercial + * license agreement. + * + * Use of Altair’s trademarks, including but not limited to "PBS™", + * "PBS Professional®", and "PBS Pro™" and Altair’s logos is subject to Altair's + * trademark licensing policies. + * + */ +/* pbs_holdjob.c + + Send the Hold Job request to the server -- + really just an instance of the "manager" request. + */ + +#include /* the master config generated by configure */ + +#include +#include "libpbs.h" + + +/** + * @brief + * - Send the Hold Job request to the server -- + * really just an instance of the "manager" request. + * + * @param[in] c - connection handler + * @param[in] jobid - job identifier + * @param[in] holdtype - value for holdtype + * @param[in] extend - string to encode req + * + * @return int + * @retval 0 success + * @retval !0 error + * + */ + + +int +pbs_holdjob(int c, char *jobid, char *holdtype, char *extend) +{ + struct attropl aopl; + + if ((jobid == (char *)0) || (*jobid == '\0')) + return (pbs_errno = PBSE_IVALREQ); + + aopl.name = ATTR_h; + aopl.resource = (char *)NULL; + if ((holdtype == (char *)NULL) || (*holdtype == '\0')) + aopl.value = "u"; + else + aopl.value = holdtype; + aopl.op = SET; + aopl.next = (struct attropl *)NULL; + return PBSD_manager(c, PBS_BATCH_HoldJob, + MGR_CMD_SET, + MGR_OBJ_JOB, + jobid, + &aopl, + extend); +} diff --git a/pool/shard002/C/0061366_clock.c b/pool/shard002/C/0061366_clock.c new file mode 100644 index 0000000000000000000000000000000000000000..ec74288417b2ac7dc91d7ac35fde7f2dda48aba1 --- /dev/null +++ b/pool/shard002/C/0061366_clock.c @@ -0,0 +1,166 @@ +/* $Id$ */ + +/* + * Copyright (c) 2009 Nicholas Marriott + * + * Permission to use, copy, modify, and distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF MIND, USE, DATA OR PROFITS, WHETHER + * IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING + * OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + */ + +#include + +#include +#include + +#include "tmux.h" + +const char clock_table[14][5][5] = { + { { 1,1,1,1,1 }, /* 0 */ + { 1,0,0,0,1 }, + { 1,0,0,0,1 }, + { 1,0,0,0,1 }, + { 1,1,1,1,1 } }, + { { 0,0,0,0,1 }, /* 1 */ + { 0,0,0,0,1 }, + { 0,0,0,0,1 }, + { 0,0,0,0,1 }, + { 0,0,0,0,1 } }, + { { 1,1,1,1,1 }, /* 2 */ + { 0,0,0,0,1 }, + { 1,1,1,1,1 }, + { 1,0,0,0,0 }, + { 1,1,1,1,1 } }, + { { 1,1,1,1,1 }, /* 3 */ + { 0,0,0,0,1 }, + { 1,1,1,1,1 }, + { 0,0,0,0,1 }, + { 1,1,1,1,1 } }, + { { 1,0,0,0,1 }, /* 4 */ + { 1,0,0,0,1 }, + { 1,1,1,1,1 }, + { 0,0,0,0,1 }, + { 0,0,0,0,1 } }, + { { 1,1,1,1,1 }, /* 5 */ + { 1,0,0,0,0 }, + { 1,1,1,1,1 }, + { 0,0,0,0,1 }, + { 1,1,1,1,1 } }, + { { 1,1,1,1,1 }, /* 6 */ + { 1,0,0,0,0 }, + { 1,1,1,1,1 }, + { 1,0,0,0,1 }, + { 1,1,1,1,1 } }, + { { 1,1,1,1,1 }, /* 7 */ + { 0,0,0,0,1 }, + { 0,0,0,0,1 }, + { 0,0,0,0,1 }, + { 0,0,0,0,1 } }, + { { 1,1,1,1,1 }, /* 8 */ + { 1,0,0,0,1 }, + { 1,1,1,1,1 }, + { 1,0,0,0,1 }, + { 1,1,1,1,1 } }, + { { 1,1,1,1,1 }, /* 9 */ + { 1,0,0,0,1 }, + { 1,1,1,1,1 }, + { 0,0,0,0,1 }, + { 1,1,1,1,1 } }, + { { 0,0,0,0,0 }, /* : */ + { 0,0,1,0,0 }, + { 0,0,0,0,0 }, + { 0,0,1,0,0 }, + { 0,0,0,0,0 } }, + { { 1,1,1,1,1 }, /* A */ + { 1,0,0,0,1 }, + { 1,1,1,1,1 }, + { 1,0,0,0,1 }, + { 1,0,0,0,1 } }, + { { 1,1,1,1,1 }, /* P */ + { 1,0,0,0,1 }, + { 1,1,1,1,1 }, + { 1,0,0,0,0 }, + { 1,0,0,0,0 } }, + { { 1,0,0,0,1 }, /* M */ + { 1,1,0,1,1 }, + { 1,0,1,0,1 }, + { 1,0,0,0,1 }, + { 1,0,0,0,1 } }, +}; + +void +clock_draw(struct screen_write_ctx *ctx, int colour, int style) +{ + struct screen *s = ctx->s; + struct grid_cell gc; + char tim[64], *ptr; + time_t t; + struct tm *tm; + u_int i, j, x, y, idx; + + t = time(NULL); + tm = localtime(&t); + if (style == 0) { + strftime(tim, sizeof tim, "%l:%M ", localtime(&t)); + if (tm->tm_hour >= 12) + strlcat(tim, "PM", sizeof tim); + else + strlcat(tim, "AM", sizeof tim); + } else + strftime(tim, sizeof tim, "%H:%M", tm); + + + screen_write_clearscreen(ctx); + + if (screen_size_x(s) < 6 * strlen(tim) || screen_size_y(s) < 6) { + if (screen_size_x(s) >= strlen(tim) && screen_size_y(s) != 0) { + x = (screen_size_x(s) / 2) - (strlen(tim) / 2); + y = screen_size_y(s) / 2; + screen_write_cursormove(ctx, x, y); + + memcpy(&gc, &grid_default_cell, sizeof gc); + colour_set_fg(&gc, colour); + screen_write_puts(ctx, &gc, "%s", tim); + } + return; + } + + x = (screen_size_x(s) / 2) - 3 * strlen(tim); + y = (screen_size_y(s) / 2) - 3; + + memcpy(&gc, &grid_default_cell, sizeof gc); + colour_set_bg(&gc, colour); + for (ptr = tim; *ptr != '\0'; ptr++) { + if (*ptr >= '0' && *ptr <= '9') + idx = *ptr - '0'; + else if (*ptr == ':') + idx = 10; + else if (*ptr == 'A') + idx = 11; + else if (*ptr == 'P') + idx = 12; + else if (*ptr == 'M') + idx = 13; + else { + x += 6; + continue; + } + + for (j = 0; j < 5; j++) { + for (i = 0; i < 5; i++) { + screen_write_cursormove(ctx, x + i, y + j); + if (clock_table[idx][j][i]) + screen_write_putc(ctx, &gc, ' '); + } + } + x += 6; + } +} diff --git a/pool/shard002/C/0061372_main.c b/pool/shard002/C/0061372_main.c new file mode 100644 index 0000000000000000000000000000000000000000..a0c8660c44a8d3e9e7575be03e96535bd3b1354c --- /dev/null +++ b/pool/shard002/C/0061372_main.c @@ -0,0 +1,225 @@ +#include +#include +#include +#include +#include "packer.h" +#include "datapack.h" + +#ifndef MIN + #define MIN(x, y) ((x) < (y) ? (x) : (y)) +#endif + +const int SERVER_PORT = 8492; + + +void process_connection(int conn); + + +int main(int argc, char *argv[]) +{ + int listener, conn; + struct sockaddr_in servaddr; + WSADATA wsaData; + + WSAStartup(MAKEWORD(1, 1), &wsaData); + + if ( (listener = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0 ) { + fprintf(stderr, "Could not create listening socket: %i", WSAGetLastError()); + return -1; + } + + memset(&servaddr, 0, sizeof(servaddr)); + servaddr.sin_family = AF_INET; + servaddr.sin_port = htons(SERVER_PORT); + servaddr.sin_addr.s_addr = inet_addr("127.0.0.1"); + + if ( bind(listener, (struct sockaddr *) &servaddr, sizeof(servaddr)) < 0 ) { + fprintf(stderr, "Could not bind listening socket."); + return -1; + } + + if ( listen(listener, 1) < 0) { + fprintf(stderr, "Call to listen failed."); + return -1; + } + + system("start http://127.0.0.1:8492"); + + while(1) { + if ( (conn = accept(listener, NULL, NULL)) < 0 ) { + fprintf(stderr, "Error calling accept()"); + return -1; + } + + process_connection(conn); + } + + WSACleanup(); + + return 0; +} + +void WriteLine(int conn, const char *line, size_t len) +{ + size_t rc; + + if(len == 0) + len = strlen(line); + + while(len > 0) { + rc = send(conn, line, len, 0); + if(rc < 0) { + fprintf(stderr, "Failed to write data to socket.\n"); + return; + } + len -= rc; + line += rc; + } +} + +void ReadLine(int conn, char *buf, ssize_t max) +{ + int rc = 0; + max--; // Leave room for a NULL terminator + + while(max > 0) { + if ( (rc = recv(conn, buf, 1, 0)) == 1 ) { + printf("%c", *buf); + if ( *buf == '\n' ) { + *(buf+1) = 0; + return; + } + + buf++; + max--; + } + else if ( rc == 0 ) + { + *buf = 0; + return; + } + else { + fprintf(stderr, "Error reading request: %i.\n", rc); + *buf = 0; + return; + } + } +} + +bool ReadData(int conn, char *buf, ssize_t max) +{ + int rc = 0; + + while(max > 0) { + if ( (rc = recv(conn, buf, max, 0)) > 0 ) { + buf += rc; + max -= rc; + } + else if ( rc == 0 ) + { + return false; + } + else { + fprintf(stderr, "Error reading request: %i.\n", rc); + return false; + } + } + + return true; +} + +void process_connection(int conn) +{ + ssize_t len; + FILE *fp; + char buf[1024]; + char filename[256] = {0}; + bool GET = true; + int content_length = 0; + struct DATAPACK datapack; + + strcpy(filename, "/index.html"); + + + // Wait until the request has finished sending + while(1) { + ReadLine(conn, buf, 1024); + if(buf[0] == '\r' && buf[1] == '\n') + break; + + // TODO: These functions are unsafe. + if(sscanf(buf, "GET %s HTTP", filename) == 1) + GET = true; + + if(sscanf(buf, "POST %s HTTP", filename) == 1) + GET = false; + + sscanf(buf, "Content-Length: %i\r\n", &content_length); + } + + if(!strcmp(filename, "/save") && !GET) + { + fp = fopen("todo.json", "wb"); + + while(content_length > 0) { + if(!ReadData(conn, buf, MIN(content_length, 1024))) + break; + + fwrite(buf, 1, MIN(content_length, 1024), fp); + + content_length -= 1024; + } + + shutdown(conn, SD_SEND); + closesocket(conn); + fclose(fp); + return; + } + + if(filename[1] == 0) + strcpy(filename, "/index.html"); + + printf("Sending: '%s'\n", filename+1); + + datapack = find_datapack(datapacks, filename+1); + + if(datapack.name != NULL) + { + WriteLine(conn, datapack.data, datapack.len); + } + else + { + if ( (fp = fopen(filename+1, "rb")) == NULL ) { + fprintf(stderr, "Unable to open '%s' for reading.\n\n", filename); + + if(!strcmp(filename, "/todo.json")) + { + WriteLine(conn, "\n", 1); + + shutdown(conn, SD_SEND); + } + + closesocket(conn); + return; + } + + + // Send the file + WriteLine(conn, "HTTP/1.0 200 OK\r\nServer: PGBWebServ v01.\r\nContent-Type: text/html\r\n\r\n", 0); + while(1) { + len = fread(buf, 1, 1024, fp); + printf("Sending %u bytes.\n", (unsigned int)len); + WriteLine(conn, buf, len); + + if(len < 1024) + break; + } + } + + shutdown(conn, SD_SEND); + closesocket(conn); + + + fclose(fp); +} + diff --git a/pool/shard002/C/0061391_gdbstub.c b/pool/shard002/C/0061391_gdbstub.c new file mode 100644 index 0000000000000000000000000000000000000000..7fb076c2e9b096bd95dd7b6c5cea1a6e2e19f5fe --- /dev/null +++ b/pool/shard002/C/0061391_gdbstub.c @@ -0,0 +1,57 @@ +/* + * MicroBlaze gdb server stub + * + * Copyright (c) 2003-2005 Fabrice Bellard + * Copyright (c) 2013 SUSE LINUX Products GmbH + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, see . + */ +#include "qemu/osdep.h" +#include "qemu-common.h" +#include "cpu.h" +#include "exec/gdbstub.h" + +int mb_cpu_gdb_read_register(CPUState *cs, uint8_t *mem_buf, int n) +{ + MicroBlazeCPU *cpu = MICROBLAZE_CPU(cs); + CPUMBState *env = &cpu->env; + + if (n < 32) { + return gdb_get_reg32(mem_buf, env->regs[n]); + } else { + return gdb_get_reg32(mem_buf, env->sregs[n - 32]); + } + return 0; +} + +int mb_cpu_gdb_write_register(CPUState *cs, uint8_t *mem_buf, int n) +{ + MicroBlazeCPU *cpu = MICROBLAZE_CPU(cs); + CPUClass *cc = CPU_GET_CLASS(cs); + CPUMBState *env = &cpu->env; + uint32_t tmp; + + if (n > cc->gdb_num_core_regs) { + return 0; + } + + tmp = ldl_p(mem_buf); + + if (n < 32) { + env->regs[n] = tmp; + } else { + env->sregs[n - 32] = tmp; + } + return 4; +} diff --git a/pool/shard002/C/0061399_rx_xn297.c b/pool/shard002/C/0061399_rx_xn297.c new file mode 100644 index 0000000000000000000000000000000000000000..8a2b2bf1dcdf4bc7965441b30568586a8c0bd56e --- /dev/null +++ b/pool/shard002/C/0061399_rx_xn297.c @@ -0,0 +1,89 @@ +/* + * This file is part of Cleanflight. + * + * Cleanflight 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. + * + * Cleanflight 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 Cleanflight. If not, see . + */ + +// This file borrows heavily from project Deviation, +// see http://deviationtx.com + +#include +#include + +#include "drivers/rx_nrf24l01.h" +#include "common/maths.h" + + +static const uint8_t xn297_data_scramble[30] = { + 0xbc, 0xe5, 0x66, 0x0d, 0xae, 0x8c, 0x88, 0x12, + 0x69, 0xee, 0x1f, 0xc7, 0x62, 0x97, 0xd5, 0x0b, + 0x79, 0xca, 0xcc, 0x1b, 0x5d, 0x19, 0x10, 0x24, + 0xd3, 0xdc, 0x3f, 0x8e, 0xc5, 0x2f +}; + +static const uint16_t xn297_crc_xorout[26] = { + 0x9BA7, 0x8BBB, 0x85E1, 0x3E8C, 0x451E, 0x18E6, 0x6B24, 0xE7AB, + 0x3828, 0x814B, 0xD461, 0xF494, 0x2503, 0x691D, 0xFE8B, 0x9BA7, + 0x8B17, 0x2920, 0x8B5F, 0x61B1, 0xD391, 0x7401, 0x2138, 0x129F, + 0xB3A0, 0x2988 +}; + +static uint8_t bitReverse(uint8_t bIn) +{ + uint8_t bOut = 0; + for (int ii = 0; ii < 8; ++ii) { + bOut = (bOut << 1) | (bIn & 1); + bIn >>= 1; + } + return bOut; +} + + +#define RX_TX_ADDR_LEN 5 + +uint16_t XN297_UnscramblePayload(uint8_t *data, int len, const uint8_t *rxAddr) +{ + uint16_t crc = 0xb5d2; + if (rxAddr) { + for (int ii = 0; ii < RX_TX_ADDR_LEN; ++ii) { + crc = crc16_ccitt(crc, rxAddr[RX_TX_ADDR_LEN - 1 - ii]); + } + } + for (int ii = 0; ii < len; ++ii) { + crc = crc16_ccitt(crc, data[ii]); + data[ii] = bitReverse(data[ii] ^ xn297_data_scramble[ii]); + } + crc ^= xn297_crc_xorout[len]; + return crc; +} + +uint8_t XN297_WritePayload(uint8_t *data, int len, const uint8_t *rxAddr) +{ + uint8_t packet[NRF24L01_MAX_PAYLOAD_SIZE]; + uint16_t crc = 0xb5d2; + for (int ii = 0; ii < RX_TX_ADDR_LEN; ++ii) { + packet[ii] = rxAddr[RX_TX_ADDR_LEN - 1 - ii]; + crc = crc16_ccitt(crc, packet[ii]); + } + for (int ii = 0; ii < len; ++ii) { + const uint8_t bOut = bitReverse(data[ii]); + packet[ii + RX_TX_ADDR_LEN] = bOut ^ xn297_data_scramble[ii]; + crc = crc16_ccitt(crc, packet[ii + RX_TX_ADDR_LEN]); + } + crc ^= xn297_crc_xorout[len]; + packet[RX_TX_ADDR_LEN + len] = crc >> 8; + packet[RX_TX_ADDR_LEN + len + 1] = crc & 0xff; + return NRF24L01_WritePayload(packet, RX_TX_ADDR_LEN + len + 2); +} + diff --git a/pool/shard002/C/0061408_midi.c b/pool/shard002/C/0061408_midi.c new file mode 100644 index 0000000000000000000000000000000000000000..4cf4e2330c44867077d6597da4571854ae697162 --- /dev/null +++ b/pool/shard002/C/0061408_midi.c @@ -0,0 +1,331 @@ +/**************************************************************************** + + Copyright Echo Digital Audio Corporation (c) 1998 - 2004 + All rights reserved + www.echoaudio.com + + This file is part of Echo Digital Audio's generic driver library. + + Echo Digital Audio's generic driver 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. + + 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. + + ************************************************************************* + + Translation from C++ and adaptation for use in ALSA-Driver + were made by Giuliano Pochini + +****************************************************************************/ + + +/* + + */ + +/* */ +static int enable_midi_input(struct echoaudio *chip, char enable) +{ + DE_MID(("enable_midi_input(%d)\n", enable)); + + if (wait_handshake(chip)) + return -EIO; + + if (enable) { + chip->mtc_state = MIDI_IN_STATE_NORMAL; + chip->comm_page->flags |= + cpu_to_le32(DSP_FLAG_MIDI_INPUT); + } else + chip->comm_page->flags &= + ~cpu_to_le32(DSP_FLAG_MIDI_INPUT); + + clear_handshake(chip); + return send_vector(chip, DSP_VC_UPDATE_FLAGS); +} + + + +/* + */ +static int write_midi(struct echoaudio *chip, u8 *data, int bytes) +{ + if (snd_BUG_ON(bytes <= 0 || bytes >= MIDI_OUT_BUFFER_SIZE)) + return -EINVAL; + + if (wait_handshake(chip)) + return -EIO; + + /* */ + if (! (get_dsp_register(chip, CHI32_STATUS_REG) & CHI32_STATUS_REG_HF4)) + return 0; + + chip->comm_page->midi_output[0] = bytes; + memcpy(&chip->comm_page->midi_output[1], data, bytes); + chip->comm_page->midi_out_free_count = 0; + clear_handshake(chip); + send_vector(chip, DSP_VC_MIDI_WRITE); + DE_MID(("write_midi: %d\n", bytes)); + return bytes; +} + + + +/* + + + + + + */ +static inline int mtc_process_data(struct echoaudio *chip, short midi_byte) +{ + switch (chip->mtc_state) { + case MIDI_IN_STATE_NORMAL: + if (midi_byte == 0xF1) + chip->mtc_state = MIDI_IN_STATE_TS_HIGH; + break; + case MIDI_IN_STATE_TS_HIGH: + chip->mtc_state = MIDI_IN_STATE_TS_LOW; + return MIDI_IN_SKIP_DATA; + break; + case MIDI_IN_STATE_TS_LOW: + chip->mtc_state = MIDI_IN_STATE_F1_DATA; + return MIDI_IN_SKIP_DATA; + break; + case MIDI_IN_STATE_F1_DATA: + chip->mtc_state = MIDI_IN_STATE_NORMAL; + break; + } + return 0; +} + + + +/* + */ +static int midi_service_irq(struct echoaudio *chip) +{ + short int count, midi_byte, i, received; + + /* */ + count = le16_to_cpu(chip->comm_page->midi_input[0]); + + if (snd_BUG_ON(count >= MIDI_IN_BUFFER_SIZE)) + return 0; + + /* */ + i = 1; + received = 0; + for (i = 1; i <= count; i++) { + /* */ + midi_byte = le16_to_cpu(chip->comm_page->midi_input[i]); + + /* + + + + + */ + if (mtc_process_data(chip, midi_byte) == MIDI_IN_SKIP_DATA) + continue; + + chip->midi_buffer[received++] = (u8)midi_byte; + } + + return received; +} + + + + +/* + + */ + +static int snd_echo_midi_input_open(struct snd_rawmidi_substream *substream) +{ + struct echoaudio *chip = substream->rmidi->private_data; + + chip->midi_in = substream; + DE_MID(("rawmidi_iopen\n")); + return 0; +} + + + +static void snd_echo_midi_input_trigger(struct snd_rawmidi_substream *substream, + int up) +{ + struct echoaudio *chip = substream->rmidi->private_data; + + if (up != chip->midi_input_enabled) { + spin_lock_irq(&chip->lock); + enable_midi_input(chip, up); + spin_unlock_irq(&chip->lock); + chip->midi_input_enabled = up; + } +} + + + +static int snd_echo_midi_input_close(struct snd_rawmidi_substream *substream) +{ + struct echoaudio *chip = substream->rmidi->private_data; + + chip->midi_in = NULL; + DE_MID(("rawmidi_iclose\n")); + return 0; +} + + + +static int snd_echo_midi_output_open(struct snd_rawmidi_substream *substream) +{ + struct echoaudio *chip = substream->rmidi->private_data; + + chip->tinuse = 0; + chip->midi_full = 0; + chip->midi_out = substream; + DE_MID(("rawmidi_oopen\n")); + return 0; +} + + + +static void snd_echo_midi_output_write(unsigned long data) +{ + struct echoaudio *chip = (struct echoaudio *)data; + unsigned long flags; + int bytes, sent, time; + unsigned char buf[MIDI_OUT_BUFFER_SIZE - 1]; + + DE_MID(("snd_echo_midi_output_write\n")); + /* + */ + sent = bytes = 0; + spin_lock_irqsave(&chip->lock, flags); + chip->midi_full = 0; + if (!snd_rawmidi_transmit_empty(chip->midi_out)) { + bytes = snd_rawmidi_transmit_peek(chip->midi_out, buf, + MIDI_OUT_BUFFER_SIZE - 1); + DE_MID(("Try to send %d bytes...\n", bytes)); + sent = write_midi(chip, buf, bytes); + if (sent < 0) { + snd_printk(KERN_ERR "write_midi() error %d\n", sent); + /* */ + sent = 9000; + chip->midi_full = 1; + } else if (sent > 0) { + DE_MID(("%d bytes sent\n", sent)); + snd_rawmidi_transmit_ack(chip->midi_out, sent); + } else { + /* + */ + DE_MID(("Full\n")); + sent = 32; + chip->midi_full = 1; + } + } + + /* */ + if (!snd_rawmidi_transmit_empty(chip->midi_out) && chip->tinuse) { + /* + */ + time = (sent << 3) / 25 + 1; /* */ + mod_timer(&chip->timer, jiffies + (time * HZ + 999) / 1000); + DE_MID(("Timer armed(%d)\n", ((time * HZ + 999) / 1000))); + } + spin_unlock_irqrestore(&chip->lock, flags); +} + + + +static void snd_echo_midi_output_trigger(struct snd_rawmidi_substream *substream, + int up) +{ + struct echoaudio *chip = substream->rmidi->private_data; + + DE_MID(("snd_echo_midi_output_trigger(%d)\n", up)); + spin_lock_irq(&chip->lock); + if (up) { + if (!chip->tinuse) { + init_timer(&chip->timer); + chip->timer.function = snd_echo_midi_output_write; + chip->timer.data = (unsigned long)chip; + chip->tinuse = 1; + } + } else { + if (chip->tinuse) { + chip->tinuse = 0; + spin_unlock_irq(&chip->lock); + del_timer_sync(&chip->timer); + DE_MID(("Timer removed\n")); + return; + } + } + spin_unlock_irq(&chip->lock); + + if (up && !chip->midi_full) + snd_echo_midi_output_write((unsigned long)chip); +} + + + +static int snd_echo_midi_output_close(struct snd_rawmidi_substream *substream) +{ + struct echoaudio *chip = substream->rmidi->private_data; + + chip->midi_out = NULL; + DE_MID(("rawmidi_oclose\n")); + return 0; +} + + + +static struct snd_rawmidi_ops snd_echo_midi_input = { + .open = snd_echo_midi_input_open, + .close = snd_echo_midi_input_close, + .trigger = snd_echo_midi_input_trigger, +}; + +static struct snd_rawmidi_ops snd_echo_midi_output = { + .open = snd_echo_midi_output_open, + .close = snd_echo_midi_output_close, + .trigger = snd_echo_midi_output_trigger, +}; + + + +/* */ +static int __devinit snd_echo_midi_create(struct snd_card *card, + struct echoaudio *chip) +{ + int err; + + if ((err = snd_rawmidi_new(card, card->shortname, 0, 1, 1, + &chip->rmidi)) < 0) + return err; + + strcpy(chip->rmidi->name, card->shortname); + chip->rmidi->private_data = chip; + + snd_rawmidi_set_ops(chip->rmidi, SNDRV_RAWMIDI_STREAM_INPUT, + &snd_echo_midi_input); + snd_rawmidi_set_ops(chip->rmidi, SNDRV_RAWMIDI_STREAM_OUTPUT, + &snd_echo_midi_output); + + chip->rmidi->info_flags |= SNDRV_RAWMIDI_INFO_OUTPUT | + SNDRV_RAWMIDI_INFO_INPUT | SNDRV_RAWMIDI_INFO_DUPLEX; + DE_INIT(("MIDI ok\n")); + return 0; +} diff --git a/pool/shard002/C/0061410_tt_socket_addr_native.c b/pool/shard002/C/0061410_tt_socket_addr_native.c new file mode 100644 index 0000000000000000000000000000000000000000..a99d61b2e8d7bc20bc561906a0cfb5321671b31d --- /dev/null +++ b/pool/shard002/C/0061410_tt_socket_addr_native.c @@ -0,0 +1,275 @@ +/* Copyright (C) 2017 haniu (niuhao.cn@gmail.com) + * + * 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. + */ + +//////////////////////////////////////////////////////////// +// import header files +//////////////////////////////////////////////////////////// + +#include + +#include + +#include +#include + +#include + +//////////////////////////////////////////////////////////// +// internal macro +//////////////////////////////////////////////////////////// + +#define TT_ASSERT_SA TT_ASSERT + +//////////////////////////////////////////////////////////// +// internal type +//////////////////////////////////////////////////////////// + +//////////////////////////////////////////////////////////// +// extern declaration +//////////////////////////////////////////////////////////// + +//////////////////////////////////////////////////////////// +// global variant +//////////////////////////////////////////////////////////// + +//////////////////////////////////////////////////////////// +// interface declaration +//////////////////////////////////////////////////////////// + +//////////////////////////////////////////////////////////// +// interface implementation +//////////////////////////////////////////////////////////// + +void tt_sktaddr_init_ntv(IN tt_sktaddr_ntv_t *addr, IN tt_net_family_t family) +{ + tt_memset(addr, 0, sizeof(tt_sktaddr_ntv_t)); + if (family == TT_NET_AF_INET) { + addr->ss_family = AF_INET; + } else { + TT_ASSERT_SA(family == TT_NET_AF_INET6); + addr->ss_family = AF_INET6; + } +} + +tt_net_family_t tt_sktaddr_get_family_ntv(IN tt_sktaddr_ntv_t *addr) +{ + if (addr->ss_family == AF_INET) { + return TT_NET_AF_INET; + } else { + TT_ASSERT_SA(addr->ss_family == AF_INET6); + return TT_NET_AF_INET6; + } +} + +void tt_sktaddr_set_ip_n_ntv(IN tt_sktaddr_ntv_t *addr, IN tt_sktaddr_ip_t *na) +{ + if (addr->ss_family == AF_INET) { + if (na == TT_IP_ANY) { + ((struct sockaddr_in *)addr)->sin_addr.s_addr = INADDR_ANY; + } else { + ((struct sockaddr_in *)addr)->sin_addr.s_addr = na->a32.__u32; + } + } else { + TT_ASSERT_SA(addr->ss_family == AF_INET6); + if (na == TT_IP_ANY) { + ((struct sockaddr_in6 *)addr)->sin6_addr = in6addr_any; + } else { + tt_memcpy(((struct sockaddr_in6 *)addr)->sin6_addr.s6_addr, + na->a128.__u8, + 16); + } + } +} + +void tt_sktaddr_get_ip_n_ntv(IN tt_sktaddr_ntv_t *addr, OUT tt_sktaddr_ip_t *na) +{ + tt_memset(na, 0, sizeof(tt_sktaddr_ip_t)); + if (addr->ss_family == AF_INET) { + na->a32.__u32 = ((struct sockaddr_in *)addr)->sin_addr.s_addr; + } else { + TT_ASSERT_SA(addr->ss_family == AF_INET6); + tt_memcpy(na->a128.__u8, + ((struct sockaddr_in6 *)addr)->sin6_addr.s6_addr, + 16); + } +} + +tt_result_t tt_sktaddr_ip_n2p_ntv(IN tt_net_family_t family, + IN tt_sktaddr_ip_t *na, + OUT tt_char_t *buf, + IN tt_u32_t buf_len) +{ + if (family == TT_NET_AF_INET) { + struct in_addr n; + + n.s_addr = na->a32.__u32; + if (inet_ntop(AF_INET, &n, buf, buf_len) != NULL) { + return TT_SUCCESS; + } else { + TT_ERROR_NTV("invalid n addr"); + return TT_FAIL; + } + } else { + struct in6_addr n; + + TT_ASSERT_SA(family == TT_NET_AF_INET6); + + tt_memcpy(n.s6_addr, na->a128.__u8, 16); + if (inet_ntop(AF_INET6, &n, buf, buf_len) != NULL) { + return TT_SUCCESS; + } else { + TT_ERROR_NTV("invalid n addr"); + return TT_FAIL; + } + } +} + +tt_result_t tt_sktaddr_ip_p2n_ntv(IN tt_net_family_t family, + IN const tt_char_t *buf, + OUT tt_sktaddr_ip_t *na) +{ + if (family == TT_NET_AF_INET) { + int ret; + struct in_addr n; + + ret = inet_pton(AF_INET, buf, &n); + if (ret == 1) { + na->a32.__u32 = n.s_addr; + return TT_SUCCESS; + } else if (ret == 0) { + TT_ERROR("invalid format: %s", buf); + return TT_FAIL; + } else { + TT_ERROR_NTV("invalid p address: %s", buf); + return TT_FAIL; + } + } else { + int ret; + struct in6_addr n; + + TT_ASSERT_SA(family == TT_NET_AF_INET6); + + ret = inet_pton(AF_INET6, buf, &n); + if (ret == 1) { + tt_memcpy(na->a128.__u8, n.s6_addr, 16); + return TT_SUCCESS; + } else if (ret == 0) { + TT_ERROR("invalid format: %s", buf); + return TT_FAIL; + } else { + TT_ERROR_NTV("invalid p address: %s", buf); + return TT_FAIL; + } + } +} + +void tt_sktaddr_set_port_ntv(IN tt_sktaddr_ntv_t *addr, IN tt_u16_t port) +{ + if (addr->ss_family == AF_INET) { + ((struct sockaddr_in *)addr)->sin_port = htons(port); + } else { + TT_ASSERT_SA(addr->ss_family == AF_INET6); + ((struct sockaddr_in6 *)addr)->sin6_port = htons(port); + } +} + +tt_u16_t tt_sktaddr_get_port_ntv(IN tt_sktaddr_ntv_t *addr) +{ + if (addr->ss_family == AF_INET) { + return ntohs(((struct sockaddr_in *)addr)->sin_port); + } else { + TT_ASSERT_SA(addr->ss_family == AF_INET6); + return ntohs(((struct sockaddr_in6 *)addr)->sin6_port); + } +} + +void tt_sktaddr_set_scope_ntv(IN tt_sktaddr_ntv_t *addr, IN tt_u32_t scope_id) +{ + if (addr->ss_family != AF_INET6) { + TT_WARN("can no set scope id to ipv4 addr"); + return; + } + + ((struct sockaddr_in6 *)addr)->sin6_scope_id = scope_id; +} + +tt_u32_t tt_sktaddr_get_scope_ntv(IN tt_sktaddr_ntv_t *addr) +{ + return ((struct sockaddr_in6 *)addr)->sin6_scope_id; +} + +void tt_sktaddr_set_scope_p_ntv(IN tt_sktaddr_ntv_t *addr, + IN tt_char_t *scope_name) +{ + tt_u32_t scope_id; + + if (addr->ss_family != AF_INET6) { + TT_WARN("can no set scope id to ipv4 addr"); + return; + } + + scope_id = if_nametoindex(scope_name); + if (scope_id == 0) { + TT_ERROR("invalid scope name: %s", scope_name); + return; + } + + ((struct sockaddr_in6 *)addr)->sin6_scope_id = scope_id; +} + +void tt_sktaddr_map4to6_ntv(IN tt_sktaddr_ntv_t *in4, OUT tt_sktaddr_ntv_t *in6) +{ + struct sockaddr_in *i4 = (struct sockaddr_in *)in4; + struct sockaddr_in6 *i6 = (struct sockaddr_in6 *)in6; + unsigned char *uc6 = i6->sin6_addr.s6_addr; + + // save ipv4 value as in4 and in6 may be same pointer + uint32_t __s_addr = i4->sin_addr.s_addr; + uint16_t __sin_port = i4->sin_port; + // now change change in6 + tt_memset(i6, 0, sizeof(struct sockaddr_in6)); + + i6->sin6_family = AF_INET6; + + *((uint32_t *)&uc6[0]) = 0; + *((uint32_t *)&uc6[4]) = 0; + *((uint16_t *)&uc6[8]) = 0; + *((uint16_t *)&uc6[10]) = 0xFFFF; + *((uint32_t *)&uc6[12]) = __s_addr; + + i6->sin6_port = __sin_port; + + // i6->sin6_flowinfo = 0; + // i6->sin6_scope_id = 0; +} + +tt_bool_t tt_sktaddr_ipv4mapped_ntv(IN tt_sktaddr_ntv_t *addr) +{ + unsigned char *uc6 = ((struct sockaddr_in6 *)addr)->sin6_addr.s6_addr; + + if (addr->ss_family != AF_INET6) { + return TT_FALSE; + } + + if ((*((uint32_t *)&uc6[0]) != 0) || (*((uint32_t *)&uc6[4]) != 0) || + (*((uint16_t *)&uc6[8]) != 0) || (*((uint16_t *)&uc6[10]) != 0xFFFF)) { + return TT_FALSE; + } + + return TT_TRUE; +} diff --git a/pool/shard002/C/0061415_board-kmini-gpio-i2c.c b/pool/shard002/C/0061415_board-kmini-gpio-i2c.c new file mode 100644 index 0000000000000000000000000000000000000000..c0bdd7ccb0f18eef9596a654b28c478ad5771cdc --- /dev/null +++ b/pool/shard002/C/0061415_board-kmini-gpio-i2c.c @@ -0,0 +1,88 @@ +/* + * Copyright (c) 2013 Samsung Electronics Co., Ltd. + * + * 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. + * + * 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 "board-universal222ap.h" + +#define GPIO_KMINI_GPIO_I2C_SCL EXYNOS4_GPM4(5) +#define GPIO_KMINI_GPIO_I2C_SDA EXYNOS4_GPM4(4) + +/* I2C21 */ +static struct i2c_gpio_platform_data gpio_i2c_data21 = { + .scl_pin = GPIO_KMINI_GPIO_I2C_SCL, + .sda_pin = GPIO_KMINI_GPIO_I2C_SDA, + .udelay = 2, +}; + +static struct platform_device s3c_device_i2c21 = { + .name = "i2c-gpio", + .id = 21, + .dev.platform_data = &gpio_i2c_data21, +}; + +/* I2C21 */ +static struct i2c_board_info i2c_device21_emul[] __initdata = { + { + I2C_BOARD_INFO("ktd2026", 0x30), + }, + { + I2C_BOARD_INFO("mc96fr116c", 0xA0 >> 1), + }, +}; + +static struct platform_device *kmini_i2c21_devices[] __initdata = { + &s3c_device_i2c21, +}; + +int board_universal_ss222ap_add_platdata_gpio_i2c(int index, + void *platform_data) +{ + if (ARRAY_SIZE(i2c_device21_emul) <= index) + return -EINVAL; + + i2c_device21_emul[index].platform_data = platform_data; + + return 0; +} + +void board_universal_ss222ap_init_gpio_i2c(void) +{ + s3c_gpio_cfgpin(gpio_i2c_data21.scl_pin, S3C_GPIO_INPUT); + s3c_gpio_setpull(gpio_i2c_data21.scl_pin, S3C_GPIO_PULL_NONE); + s5p_gpio_set_drvstr(gpio_i2c_data21.scl_pin, S5P_GPIO_DRVSTR_LV1); + + s3c_gpio_cfgpin(gpio_i2c_data21.sda_pin, S3C_GPIO_INPUT); + s3c_gpio_setpull(gpio_i2c_data21.sda_pin, S3C_GPIO_PULL_NONE); + s5p_gpio_set_drvstr(gpio_i2c_data21.sda_pin, S5P_GPIO_DRVSTR_LV1); + + i2c_register_board_info(21, i2c_device21_emul, + ARRAY_SIZE(i2c_device21_emul)); + + platform_add_devices(kmini_i2c21_devices, + ARRAY_SIZE(kmini_i2c21_devices)); +} + diff --git a/pool/shard002/C/0061416_mi_unique.c b/pool/shard002/C/0061416_mi_unique.c new file mode 100644 index 0000000000000000000000000000000000000000..635f6c18247b58d3a18a478861e1ee9595280c18 --- /dev/null +++ b/pool/shard002/C/0061416_mi_unique.c @@ -0,0 +1,232 @@ +/* Copyright (C) 2000-2006 MySQL AB + + 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ + +/* Functions to check if a row is unique */ + +#include "myisamdef.h" +#include + +my_bool mi_check_unique(MI_INFO *info, MI_UNIQUEDEF *def, byte *record, + ha_checksum unique_hash, my_off_t disk_pos) +{ + my_off_t lastpos=info->lastpos; + MI_KEYDEF *key= &info->s->keyinfo[def->key]; + uchar *key_buff=info->lastkey2; + DBUG_ENTER("mi_check_unique"); + + mi_unique_store(record+key->seg->start, unique_hash); + _mi_make_key(info,def->key,key_buff,record,0); + + /* The above changed info->lastkey2. Inform mi_rnext_same(). */ + info->update&= ~HA_STATE_RNEXT_SAME; + + if (_mi_search(info,info->s->keyinfo+def->key,key_buff,MI_UNIQUE_HASH_LENGTH, + SEARCH_FIND,info->s->state.key_root[def->key])) + { + info->page_changed=1; /* Can't optimize read next */ + info->lastpos= lastpos; + DBUG_RETURN(0); /* No matching rows */ + } + + for (;;) + { + if (info->lastpos != disk_pos && + !(*info->s->compare_unique)(info,def,record,info->lastpos)) + { + my_errno=HA_ERR_FOUND_DUPP_UNIQUE; + info->errkey= (int) def->key; + info->dupp_key_pos= info->lastpos; + info->page_changed=1; /* Can't optimize read next */ + info->lastpos=lastpos; + DBUG_PRINT("info",("Found duplicate")); + DBUG_RETURN(1); /* Found identical */ + } + if (_mi_search_next(info,info->s->keyinfo+def->key, info->lastkey, + MI_UNIQUE_HASH_LENGTH, SEARCH_BIGGER, + info->s->state.key_root[def->key]) || + bcmp((char*) info->lastkey, (char*) key_buff, MI_UNIQUE_HASH_LENGTH)) + { + info->page_changed=1; /* Can't optimize read next */ + info->lastpos=lastpos; + DBUG_RETURN(0); /* end of tree */ + } + } +} + + +/* + Calculate a hash for a row + + TODO + Add support for bit fields +*/ + +ha_checksum mi_unique_hash(MI_UNIQUEDEF *def, const byte *record) +{ + const byte *pos, *end; + ha_checksum crc= 0; + ulong seed1=0, seed2= 4; + HA_KEYSEG *keyseg; + + for (keyseg=def->seg ; keyseg < def->end ; keyseg++) + { + enum ha_base_keytype type=(enum ha_base_keytype) keyseg->type; + uint length=keyseg->length; + + if (keyseg->null_bit) + { + if (record[keyseg->null_pos] & keyseg->null_bit) + { + /* + Change crc in a way different from an empty string or 0. + (This is an optimisation; The code will work even if this isn't + done) + */ + crc=((crc << 8) + 511+ + (crc >> (8*sizeof(ha_checksum)-8))); + continue; + } + } + pos= record+keyseg->start; + if (keyseg->flag & HA_VAR_LENGTH_PART) + { + uint pack_length= keyseg->bit_start; + uint tmp_length= (pack_length == 1 ? (uint) *(uchar*) pos : + uint2korr(pos)); + pos+= pack_length; /* Skip VARCHAR length */ + set_if_smaller(length,tmp_length); + } + else if (keyseg->flag & HA_BLOB_PART) + { + uint tmp_length=_mi_calc_blob_length(keyseg->bit_start,pos); + memcpy_fixed((byte*) &pos,pos+keyseg->bit_start,sizeof(char*)); + if (!length || length > tmp_length) + length=tmp_length; /* The whole blob */ + } + end= pos+length; + if (type == HA_KEYTYPE_TEXT || type == HA_KEYTYPE_VARTEXT1 || + type == HA_KEYTYPE_VARTEXT2) + { + keyseg->charset->coll->hash_sort(keyseg->charset, + (const uchar*) pos, length, &seed1, + &seed2); + crc^= seed1; + } + else + while (pos != end) + crc=((crc << 8) + + (((uchar) *(uchar*) pos++))) + + (crc >> (8*sizeof(ha_checksum)-8)); + } + return crc; +} + + +/* + compare unique key for two rows + + TODO + Add support for bit fields + + RETURN + 0 if both rows have equal unique value + # Rows are different +*/ + +int mi_unique_comp(MI_UNIQUEDEF *def, const byte *a, const byte *b, + my_bool null_are_equal) +{ + const byte *pos_a, *pos_b, *end; + HA_KEYSEG *keyseg; + + for (keyseg=def->seg ; keyseg < def->end ; keyseg++) + { + enum ha_base_keytype type=(enum ha_base_keytype) keyseg->type; + uint a_length, b_length; + a_length= b_length= keyseg->length; + + /* If part is NULL it's regarded as different */ + if (keyseg->null_bit) + { + uint tmp; + if ((tmp=(a[keyseg->null_pos] & keyseg->null_bit)) != + (uint) (b[keyseg->null_pos] & keyseg->null_bit)) + return 1; + if (tmp) + { + if (!null_are_equal) + return 1; + continue; + } + } + pos_a= a+keyseg->start; + pos_b= b+keyseg->start; + if (keyseg->flag & HA_VAR_LENGTH_PART) + { + uint pack_length= keyseg->bit_start; + if (pack_length == 1) + { + a_length= (uint) *(uchar*) pos_a++; + b_length= (uint) *(uchar*) pos_b++; + } + else + { + a_length= uint2korr(pos_a); + b_length= uint2korr(pos_b); + pos_a+= 2; /* Skip VARCHAR length */ + pos_b+= 2; + } + set_if_smaller(a_length, keyseg->length); /* Safety */ + set_if_smaller(b_length, keyseg->length); /* safety */ + } + else if (keyseg->flag & HA_BLOB_PART) + { + /* Only compare 'length' characters if length != 0 */ + a_length= _mi_calc_blob_length(keyseg->bit_start,pos_a); + b_length= _mi_calc_blob_length(keyseg->bit_start,pos_b); + /* Check that a and b are of equal length */ + if (keyseg->length) + { + /* + This is used in some cases when we are not interested in comparing + the whole length of the blob. + */ + set_if_smaller(a_length, keyseg->length); + set_if_smaller(b_length, keyseg->length); + } + memcpy_fixed((byte*) &pos_a,pos_a+keyseg->bit_start,sizeof(char*)); + memcpy_fixed((byte*) &pos_b,pos_b+keyseg->bit_start,sizeof(char*)); + } + if (type == HA_KEYTYPE_TEXT || type == HA_KEYTYPE_VARTEXT1 || + type == HA_KEYTYPE_VARTEXT2) + { + if (mi_compare_text(keyseg->charset, (uchar *) pos_a, a_length, + (uchar *) pos_b, b_length, 0, 1)) + return 1; + } + else + { + if (a_length != b_length) + return 1; + end= pos_a+a_length; + while (pos_a != end) + { + if (*pos_a++ != *pos_b++) + return 1; + } + } + } + return 0; +} diff --git a/pool/shard002/C/0061417_topsplit.c b/pool/shard002/C/0061417_topsplit.c new file mode 100644 index 0000000000000000000000000000000000000000..a1f78f8b0f1aa788c9a6f3623b1b7abc155c3fe4 --- /dev/null +++ b/pool/shard002/C/0061417_topsplit.c @@ -0,0 +1,83 @@ +#include +#include + +#include "../topsig-global.h" + +static struct { + int headersize; + int maxnamelen; + int sig_width; + size_t sig_record_size; + size_t sig_offset; +} cfg; + +void readSigHeader(FILE *fp) +{ + char sig_method[64]; + cfg.headersize = fileRead32(fp); // header-size + int version = fileRead32(fp); // version + cfg.maxnamelen = fileRead32(fp); // maxnamelen + cfg.sig_width = fileRead32(fp); // sig_width + fileRead32(fp); // sig_density + if (version >= 2) { + fileRead32(fp); // sig_seed + } + fread(sig_method, 1, 64, fp); // sig_method + + cfg.sig_offset = cfg.maxnamelen + 1; + cfg.sig_offset += 8 * 4; // 8 32-bit ints + cfg.sig_record_size = cfg.sig_offset + cfg.sig_width / 8; +} + +int main(int argc, char **argv) +{ + if (argc < 5) { + fprintf(stderr, "usage: {input sigfile} {# of sigs per file} {output sigfile format string, printf format}\n"); + return 0; + } + FILE *fi; + if ((fi = fopen(argv[1], "rb"))) { + int sigcount = atoi(argv[2]); + readSigHeader(fi); + rewind(fi); + unsigned char *fileheader_buffer = malloc(cfg.headersize); + fread(fileheader_buffer, 1, cfg.headersize, fi); + + int sigfile_num = 0; + + unsigned char *sigheader_buffer = malloc(cfg.sig_offset); + unsigned char *sig_buffer = malloc(cfg.sig_width / 8); + int eof = 0; + for (;;) { + char fname[256]; + sprintf(fname, argv[3], sigfile_num); + FILE *fo = fopen(fname, "wb"); + fwrite(fileheader_buffer, 1, cfg.headersize, fo); + + int sigs_copied = 0; + for (;;) { + if (fread(sigheader_buffer, 1, cfg.sig_offset, fi) == 0) { + eof = 1; + break; + } + fwrite(sigheader_buffer, 1, cfg.sig_offset, fo); + fread(sig_buffer, 1, cfg.sig_width / 8, fi); + fwrite(sig_buffer, 1, cfg.sig_width / 8, fo); + + sigs_copied++; + if (sigs_copied >= sigcount) break; + } + fclose(fo); + } + + free(fileheader_buffer); + free(sigheader_buffer); + free(sig_buffer); + + fclose(fi); + } else { + fprintf(stderr, "Unable to open input file\n"); + } + + return 0; +} diff --git a/pool/shard002/C/0061424_if_indextoname.c b/pool/shard002/C/0061424_if_indextoname.c new file mode 100644 index 0000000000000000000000000000000000000000..4b16433a4ee6525514fb748031181aeea2b99545 --- /dev/null +++ b/pool/shard002/C/0061424_if_indextoname.c @@ -0,0 +1,88 @@ +/* $KAME: if_indextoname.c,v 1.7 2000/11/08 03:09:30 itojun Exp $ */ + +/*- + * Copyright (c) 1997, 2000 + * Berkeley Software 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: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * THIS SOFTWARE IS PROVIDED BY Berkeley Software Design, 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 Berkeley Software Design, Inc. 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. + * + * BSDI Id: if_indextoname.c,v 2.3 2000/04/17 22:38:05 dab Exp + */ + +#include +__FBSDID("$FreeBSD$"); + +#include +#include +#include +#include +#include +#include +#include +#include + +/* + * From RFC 2533: + * + * The second function maps an interface index into its corresponding + * name. + * + * #include + * + * char *if_indextoname(unsigned int ifindex, char *ifname); + * + * The ifname argument must point to a buffer of at least IF_NAMESIZE + * bytes into which the interface name corresponding to the specified + * index is returned. (IF_NAMESIZE is also defined in and + * its value includes a terminating null byte at the end of the + * interface name.) This pointer is also the return value of the + * function. If there is no interface corresponding to the specified + * index, NULL is returned, and errno is set to ENXIO, if there was a + * system error (such as running out of memory), if_indextoname returns + * NULL and errno would be set to the proper value (e.g., ENOMEM). + */ + +char * +if_indextoname(unsigned int ifindex, char *ifname) +{ + struct ifaddrs *ifaddrs, *ifa; + int error = 0; + + if (getifaddrs(&ifaddrs) < 0) + return(NULL); /* getifaddrs properly set errno */ + + for (ifa = ifaddrs; ifa != NULL; ifa = ifa->ifa_next) { + if (ifa->ifa_addr && + ifa->ifa_addr->sa_family == AF_LINK && + ifindex == LLINDEX((struct sockaddr_dl*)ifa->ifa_addr)) + break; + } + + if (ifa == NULL) { + error = ENXIO; + ifname = NULL; + } + else + strncpy(ifname, ifa->ifa_name, IFNAMSIZ); + + freeifaddrs(ifaddrs); + + errno = error; + return(ifname); +} diff --git a/pool/shard002/C/0061431_globus_io_file_test.c b/pool/shard002/C/0061431_globus_io_file_test.c new file mode 100644 index 0000000000000000000000000000000000000000..dcec5f0cd46b6fcf3ec5b314de96d0e921b01ae3 --- /dev/null +++ b/pool/shard002/C/0061431_globus_io_file_test.c @@ -0,0 +1,147 @@ +/* + * Copyright 1999-2006 University of Chicago + * + * 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 "globus_io.h" +#ifndef TARGET_ARCH_WIN32 +#include +#endif + +#include "globus_preload.h" + +/* + * Function: main + * + * Description: + * + * Parameters: + * + * Returns: + */ +int +main(int argc, char **argv) +{ + int rc; + globus_result_t result; + globus_object_t * error = NULL; + char * errstring; + globus_io_handle_t handle; + globus_io_handle_t stdout_handle; + globus_size_t bytes; + globus_byte_t buf[1024]; + const char * path = getenv("DATA_FILE"); + + LTDL_SET_PRELOADED_SYMBOLS(); + if (path == NULL && argc < 2) + { + fprintf(stderr, "# Usage: %s DATA_FILE\n", argv[0]); + exit(99); + } + else if (path == NULL) + { + path = argv[1]; + } + rc = globus_module_activate(GLOBUS_COMMON_MODULE); + if (rc != GLOBUS_SUCCESS) + { + fprintf(stderr, "# Error activating GLOBUS_COMMON_MODULE\n"); + exit(99); + } + rc = globus_module_activate(GLOBUS_IO_MODULE); + if (rc != GLOBUS_SUCCESS) + { + fprintf(stderr, "# Error activating GLOBUS_COMMON_MODULE\n"); + exit(99); + } + result = globus_io_file_open(path, + O_RDONLY, + 0600, + GLOBUS_NULL, + &handle); + + if(result != GLOBUS_SUCCESS) + { + error = globus_error_get(result); + errstring = globus_object_printable_to_string(error); + printf("test failed to open %s: %s\n", path, errstring); + goto done; + } + +#ifndef TARGET_ARCH_WIN32 + result = globus_io_file_posix_convert( + fileno(stdout), + GLOBUS_NULL, + &stdout_handle); +#else + result = globus_io_file_windows_convert( + GetStdHandle(STD_OUTPUT_HANDLE), + GLOBUS_NULL, + &stdout_handle); +#endif + if(result != GLOBUS_SUCCESS) + { + error = globus_error_get(result); + errstring = globus_object_printable_to_string(error); + printf("test failed to convert stdout to io handle: %s\n", + errstring); + goto done; + } + + do + { + result = globus_io_read(&handle, + buf, + sizeof(buf), + sizeof(buf), + &bytes); + if(result == GLOBUS_SUCCESS || + ((error = globus_error_get(result)) && + (globus_object_type_match(globus_object_get_type(error), + GLOBUS_IO_ERROR_TYPE_EOF)))) + { + globus_size_t nbytes2; + + globus_io_write(&stdout_handle, + buf, + bytes, + &nbytes2); + } + else + { + errstring = globus_object_printable_to_string(error); + printf("test failed to read /etc/group: %s\n", + errstring); + goto done; + + } + } + while(result == GLOBUS_SUCCESS); + + done: + + if(error) + { + globus_object_free(error); + } + + globus_io_close(&handle); + globus_io_close(&stdout_handle); + + globus_module_deactivate(GLOBUS_IO_MODULE); + globus_module_deactivate(GLOBUS_COMMON_MODULE); + + return 0; +} +/* main() */ diff --git a/pool/shard002/C/0061432_legacy.c b/pool/shard002/C/0061432_legacy.c new file mode 100644 index 0000000000000000000000000000000000000000..5565d7016b754d340c4f82aceec44f781b964d63 --- /dev/null +++ b/pool/shard002/C/0061432_legacy.c @@ -0,0 +1,56 @@ +/* + * legacy.c - traditional, old school PCI bus probing + */ +#include +#include +#include "pci.h" + +/* + * Discover remaining PCI buses in case there are peer host bridges. + * We use the number of last PCI bus provided by the PCI BIOS. + */ +static void __devinit pcibios_fixup_peer_bridges(void) +{ + int n, devfn; + + if (pcibios_last_bus <= 0 || pcibios_last_bus >= 0xff) + return; + DBG("PCI: Peer bridge fixup\n"); + + for (n=0; n <= pcibios_last_bus; n++) { + u32 l; + if (pci_find_bus(0, n)) + continue; + for (devfn = 0; devfn < 256; devfn += 8) { + if (!raw_pci_ops->read(0, n, devfn, PCI_VENDOR_ID, 2, &l) && + l != 0x0000 && l != 0xffff) { + DBG("Found device at %02x:%02x [%04x]\n", n, devfn, l); + printk(KERN_INFO "PCI: Discovered peer bus %02x\n", n); + pci_scan_bus_with_sysdata(n); + break; + } + } + } +} + +static int __init pci_legacy_init(void) +{ + if (!raw_pci_ops) { + printk("PCI: System does not support PCI\n"); + return 0; + } + + if (pcibios_scanned++) + return 0; + + printk("PCI: Probing PCI hardware\n"); + pci_root_bus = pcibios_scan_root(0); + if (pci_root_bus) + pci_bus_add_devices(pci_root_bus); + + pcibios_fixup_peer_bridges(); + + return 0; +} + +subsys_initcall(pci_legacy_init); diff --git a/pool/shard002/C/0061435_CWE78_OS_Command_Injection__wchar_t_file_w32_execv_63b.c b/pool/shard002/C/0061435_CWE78_OS_Command_Injection__wchar_t_file_w32_execv_63b.c new file mode 100644 index 0000000000000000000000000000000000000000..67533877761bf30ce23ea1adbfb9bc8d8d0b4ee2 --- /dev/null +++ b/pool/shard002/C/0061435_CWE78_OS_Command_Injection__wchar_t_file_w32_execv_63b.c @@ -0,0 +1,74 @@ +/* TEMPLATE GENERATED TESTCASE FILE +Filename: CWE78_OS_Command_Injection__wchar_t_file_w32_execv_63b.c +Label Definition File: CWE78_OS_Command_Injection.strings.label.xml +Template File: sources-sink-63b.tmpl.c +*/ +/* + * @description + * CWE: 78 OS Command Injection + * BadSource: file Read input from a file + * GoodSource: Fixed string + * Sinks: w32_execv + * BadSink : execute command with wexecv + * Flow Variant: 63 Data flow: pointer to data passed from one function to another 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"ls" +#define COMMAND_ARG2 L"-la" +#define COMMAND_ARG3 data +#endif + +#ifdef _WIN32 +#define FILENAME "C:\\temp\\file.txt" +#else +#define FILENAME "/tmp/file.txt" +#endif + +#include +#define EXECV _wexecv + +#ifndef OMITBAD + +void CWE78_OS_Command_Injection__wchar_t_file_w32_execv_63b_badSink(wchar_t * * dataPtr) +{ + wchar_t * data = *dataPtr; + { + wchar_t *args[] = {COMMAND_INT_PATH, COMMAND_ARG1, COMMAND_ARG2, COMMAND_ARG3, NULL}; + /* wexecv - specify the path where the command is located */ + /* POTENTIAL FLAW: Execute command without validating input possibly leading to command injection */ + EXECV(COMMAND_INT_PATH, args); + } +} + +#endif /* OMITBAD */ + +#ifndef OMITGOOD + +/* goodG2B uses the GoodSource with the BadSink */ +void CWE78_OS_Command_Injection__wchar_t_file_w32_execv_63b_goodG2BSink(wchar_t * * dataPtr) +{ + wchar_t * data = *dataPtr; + { + wchar_t *args[] = {COMMAND_INT_PATH, COMMAND_ARG1, COMMAND_ARG2, COMMAND_ARG3, NULL}; + /* wexecv - specify the path where the command is located */ + /* POTENTIAL FLAW: Execute command without validating input possibly leading to command injection */ + EXECV(COMMAND_INT_PATH, args); + } +} + +#endif /* OMITGOOD */ diff --git a/pool/shard002/C/0061444_SQLConnect.c b/pool/shard002/C/0061444_SQLConnect.c new file mode 100644 index 0000000000000000000000000000000000000000..427e75b869ebf1d46c9beac1fe08db6e3b15bfbc --- /dev/null +++ b/pool/shard002/C/0061444_SQLConnect.c @@ -0,0 +1,204 @@ +/******************************************************************************* + * + * Copyright (c) 2000 Easysoft Ltd + * + * The contents of this file are subject to the Easysoft Public License + * Version 1.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.easysoft.org/EPL.html + * + * Software distributed under the License is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for + * the specific language governing rights and limitations under the License. + * + * The Original Code was created by Easysoft Limited and its successors. + * + * Contributor(s): Tom Fosdick (Easysoft) + * + ******************************************************************************* + * + * $Id: SQLConnect.c,v 1.4 2004/08/02 21:21:16 dbox Exp $ + * + * $Log: SQLConnect.c,v $ + * Revision 1.4 2004/08/02 21:21:16 dbox + * tinkered w reading odbc.ini procedure + * + * Revision 1.3 2002/06/26 21:02:23 dbox + * changed trace functions, setenv DEBUG 2 traces through SQLxxx functions + * setenv DEBUG 3 traces through OCIxxx functions + * + * + * VS: ---------------------------------------------------------------------- + * + * Revision 1.2 2002/05/14 23:01:05 dbox + * added a bunch of error checking and some 'constructors' for the + * environment handles + * + * Revision 1.1.1.1 2002/02/11 19:48:06 dbox + * second try, importing code into directories + * + * Revision 1.14 2000/07/10 08:24:35 tom + * tweaks for less tolerant compilers + * + * Revision 1.13 2000/07/07 07:59:55 tom + * Heavier tracing + * + * Revision 1.12 2000/06/06 10:24:35 tom + * Tidy up for possible release 0.0.3 + * + * Revision 1.10 2000/05/08 16:21:00 tom + * General tidyness mods and clean up + * + * Revision 1.9 2000/05/04 14:56:31 tom + * diagnostics now cleared down (almost) properly + * local functions renamed to make clashes less likely + * + * Revision 1.8 2000/05/03 16:00:02 tom + * initial tracing implementation + * + * Revision 1.7 2000/05/02 14:29:01 tom + * initial thread safety measures + * + * Revision 1.6 2000/04/28 08:39:45 tom + * Tidy up + * + * Revision 1.5 2000/04/26 15:28:13 tom + * Changed to account for new handle definitions + * + * Revision 1.4 2000/04/26 10:14:50 tom + * Changes due to libclntsh no longer being dlopened + * + * Revision 1.3 2000/04/20 10:50:31 nick + * Add to CVS and tidy up + * + * Revision 1.2 2000/04/19 15:24:19 tom + * First functional checkin + * + * Revision 1.1 2000/04/13 11:44:22 tom + * Added files + * + ******************************************************************************/ + +#include "common.h" + +static char const rcsid[] = "$RCSfile: SQLConnect.c,v $ $Revision: 1.4 $"; + +SQLRETURN SQL_API SQLConnect(SQLHDBC ConnectionHandle, + SQLCHAR * ServerName, + SQLSMALLINT NameLength1, + SQLCHAR * UserName, + SQLSMALLINT NameLength2, + SQLCHAR * Authentication, SQLSMALLINT NameLength3) +{ + hDbc_T *dbc = (hDbc_T *) ConnectionHandle; + SQLRETURN status = SQL_SUCCESS; + SQLCHAR trace_opt[4]; + SQLSMALLINT ret; + assert(IS_VALID(dbc)); + + if (!dbc || HANDLE_TYPE(dbc) != SQL_HANDLE_DBC) { + return SQL_INVALID_HANDLE; + } + ood_clear_diag((hgeneric *) dbc); + + if (!ServerName || NameLength1 == 0) { + ood_post_diag((hgeneric *) dbc, ERROR_ORIGIN_HY000, 0, "", + "A DSN is required", + __LINE__, 0, "", ERROR_STATE_HY000, + __FILE__, __LINE__); + } + + THREAD_MUTEX_LOCK(dbc); + if (NameLength1 > 0) { + memcpy(dbc->DSN, ServerName, NameLength1); + dbc->DSN[NameLength1] = '\0'; + } else { + strcpy(dbc->DSN, (const char *)ServerName); + } + + /* + * Now see if we can get the DB + */ + ret = SQLGetPrivateProfileString(dbc->DSN, "DB", + "", dbc->DB, 128, "ODBC.INI"); + if (!ret) + ret = SQLGetPrivateProfileString(dbc->DSN, "Database", + "", dbc->DB, 128, "ODBC.INI"); + + /* + * For UID and PWD the defaults in the odbc.ini are overridden + * by the connection string. + */ + if (NameLength2 > 0) { + memcpy(dbc->UID, UserName, NameLength2); + dbc->UID[NameLength2] = '\0'; + } else if (NameLength2 == SQL_NTS && UserName && *UserName) { + strcpy(dbc->UID, (const char *)UserName); + } else { + ret = SQLGetPrivateProfileString(dbc->DSN, "USER", + "", dbc->UID, 32, "ODBC.INI"); + if (!ret) + ret = SQLGetPrivateProfileString(dbc->DSN, "USERNAME", + "", dbc->UID, 32, + "ODBC.INI"); + if (!ret) + ret = SQLGetPrivateProfileString(dbc->DSN, "UID", + "", dbc->UID, 32, + "ODBC.INI"); + + } + + if (NameLength3 > 0) { + memcpy(dbc->PWD, Authentication, NameLength3); + dbc->PWD[NameLength3] = '\0'; + } else if (NameLength3 == SQL_NTS && Authentication && *Authentication) { + strcpy(dbc->PWD, (const char *)Authentication); + } else { + ret = SQLGetPrivateProfileString(dbc->DSN, "PASSWORD", + "", dbc->PWD, 64, "ODBC.INI"); + if (!ret) + ret = SQLGetPrivateProfileString(dbc->DSN, "PWD", + "", dbc->PWD, 64, + "ODBC.INI"); + if (!ret) + ret = SQLGetPrivateProfileString(dbc->DSN, "PASSWD", + "", dbc->PWD, 64, + "ODBC.INI"); + } + + if (ENABLE_TRACE) { + /* + * Get the tracing options + */ + SQLGetPrivateProfileString(dbc->DSN, "Trace", + "No", trace_opt, 4, "ODBC.INI"); + if (*trace_opt == 'Y' || *trace_opt == 'y') { + dbc->trace = SQL_OPT_TRACE_ON; + } else if (*trace_opt == 'N' || *trace_opt == 'n') { + dbc->trace = SQL_OPT_TRACE_OFF; + } + + SQLGetPrivateProfileString(dbc->DSN, "TraceFile", + TRACEFILE_DEFAULT, dbc->tracefile, + FILENAME_MAX, "ODBC.INI"); + + } + + /* + * We now have all the information we need to be able to + * do a connect :- so go for it... + */ + status = ood_driver_connect(dbc); + THREAD_MUTEX_UNLOCK(dbc); + if (ENABLE_TRACE) { + ood_log_message(dbc, __FILE__, __LINE__, TRACE_FUNCTION_ENTRY, + (SQLHANDLE) dbc, 0, "ssss", + NULL, "New Connection", + "DSN", dbc->DSN, + "DB", dbc->DB, "USER", dbc->UID); + ood_log_message(dbc, __FILE__, __LINE__, TRACE_FUNCTION_EXIT, + (SQLHANDLE) NULL, status, ""); + } + return (status); +} diff --git a/pool/shard002/C/0061476_cli-utils.c b/pool/shard002/C/0061476_cli-utils.c new file mode 100644 index 0000000000000000000000000000000000000000..60f7553dca270a74d5f73cb84d347152590fc9e1 --- /dev/null +++ b/pool/shard002/C/0061476_cli-utils.c @@ -0,0 +1,278 @@ +/* CLI utilities. + + Copyright (C) 2011-2013 Free Software Foundation, Inc. + + This file is part of GDB. + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . */ + +#include "defs.h" +#include "cli/cli-utils.h" +#include "gdb_string.h" +#include "value.h" +#include "gdb_assert.h" + +#include + +/* *PP is a string denoting a number. Get the number of the. Advance + *PP after the string and any trailing whitespace. + + Currently the string can either be a number, or "$" followed by the + name of a convenience variable, or ("$" or "$$") followed by digits. + + TRAILER is a character which can be found after the number; most + commonly this is `-'. If you don't want a trailer, use \0. */ + +static int +get_number_trailer (char **pp, int trailer) +{ + int retval = 0; /* default */ + char *p = *pp; + + if (*p == '$') + { + struct value *val = value_from_history_ref (p, &p); + + if (val) /* Value history reference */ + { + if (TYPE_CODE (value_type (val)) == TYPE_CODE_INT) + retval = value_as_long (val); + else + { + printf_filtered (_("History value must have integer type.")); + retval = 0; + } + } + else /* Convenience variable */ + { + /* Internal variable. Make a copy of the name, so we can + null-terminate it to pass to lookup_internalvar(). */ + char *varname; + char *start = ++p; + LONGEST val; + + while (isalnum (*p) || *p == '_') + p++; + varname = (char *) alloca (p - start + 1); + strncpy (varname, start, p - start); + varname[p - start] = '\0'; + if (get_internalvar_integer (lookup_internalvar (varname), &val)) + retval = (int) val; + else + { + printf_filtered (_("Convenience variable must " + "have integer value.\n")); + retval = 0; + } + } + } + else + { + if (*p == '-') + ++p; + while (*p >= '0' && *p <= '9') + ++p; + if (p == *pp) + /* There is no number here. (e.g. "cond a == b"). */ + { + /* Skip non-numeric token. */ + while (*p && !isspace((int) *p)) + ++p; + /* Return zero, which caller must interpret as error. */ + retval = 0; + } + else + retval = atoi (*pp); + } + if (!(isspace (*p) || *p == '\0' || *p == trailer)) + { + /* Trailing junk: return 0 and let caller print error msg. */ + while (!(isspace (*p) || *p == '\0' || *p == trailer)) + ++p; + retval = 0; + } + p = skip_spaces (p); + *pp = p; + return retval; +} + +/* See documentation in cli-utils.h. */ + +int +get_number (char **pp) +{ + return get_number_trailer (pp, '\0'); +} + +/* See documentation in cli-utils.h. */ + +void +init_number_or_range (struct get_number_or_range_state *state, + char *string) +{ + memset (state, 0, sizeof (*state)); + state->string = string; +} + +/* See documentation in cli-utils.h. */ + +int +get_number_or_range (struct get_number_or_range_state *state) +{ + if (*state->string != '-') + { + /* Default case: state->string is pointing either to a solo + number, or to the first number of a range. */ + state->last_retval = get_number_trailer (&state->string, '-'); + if (*state->string == '-') + { + char **temp; + + /* This is the start of a range ( - ). + Skip the '-', parse and remember the second number, + and also remember the end of the final token. */ + + temp = &state->end_ptr; + state->end_ptr = skip_spaces (state->string + 1); + state->end_value = get_number (temp); + if (state->end_value < state->last_retval) + { + error (_("inverted range")); + } + else if (state->end_value == state->last_retval) + { + /* Degenerate range (number1 == number2). Advance the + token pointer so that the range will be treated as a + single number. */ + state->string = state->end_ptr; + } + else + state->in_range = 1; + } + } + else if (! state->in_range) + error (_("negative value")); + else + { + /* state->string points to the '-' that betokens a range. All + number-parsing has already been done. Return the next + integer value (one greater than the saved previous value). + Do not advance the token pointer until the end of range + is reached. */ + + if (++state->last_retval == state->end_value) + { + /* End of range reached; advance token pointer. */ + state->string = state->end_ptr; + state->in_range = 0; + } + } + state->finished = *state->string == '\0'; + return state->last_retval; +} + +/* Accept a number and a string-form list of numbers such as is + accepted by get_number_or_range. Return TRUE if the number is + in the list. + + By definition, an empty list includes all numbers. This is to + be interpreted as typing a command such as "delete break" with + no arguments. */ + +int +number_is_in_list (char *list, int number) +{ + struct get_number_or_range_state state; + + if (list == NULL || *list == '\0') + return 1; + + init_number_or_range (&state, list); + while (!state.finished) + { + int gotnum = get_number_or_range (&state); + + if (gotnum == 0) + error (_("Args must be numbers or '$' variables.")); + if (gotnum == number) + return 1; + } + return 0; +} + +/* See documentation in cli-utils.h. */ + +const char * +skip_to_space_const (const char *chp) +{ + if (chp == NULL) + return NULL; + while (*chp && !isspace (*chp)) + chp++; + return chp; +} + +/* See documentation in cli-utils.h. */ + +char * +remove_trailing_whitespace (const char *start, char *s) +{ + while (s > start && isspace (*(s - 1))) + --s; + + return s; +} + +/* See documentation in cli-utils.h. */ + +char * +extract_arg (char **arg) +{ + char *result, *copy; + + if (!*arg) + return NULL; + + /* Find the start of the argument. */ + *arg = skip_spaces (*arg); + if (!**arg) + return NULL; + result = *arg; + + /* Find the end of the argument. */ + *arg = skip_to_space (*arg + 1); + + if (result == *arg) + return NULL; + + copy = xmalloc (*arg - result + 1); + memcpy (copy, result, *arg - result); + copy[*arg - result] = '\0'; + + return copy; +} + +/* See documentation in cli-utils.h. */ + +int +check_for_argument (char **str, char *arg, int arg_len) +{ + if (strncmp (*str, arg, arg_len) == 0 + && ((*str)[arg_len] == '\0' || isspace ((*str)[arg_len]))) + { + *str += arg_len; + return 1; + } + return 0; +} diff --git a/pool/shard002/C/0061481_init.c b/pool/shard002/C/0061481_init.c new file mode 100644 index 0000000000000000000000000000000000000000..fce188ed3914d1392e5f0b406d4f963451ce4fef --- /dev/null +++ b/pool/shard002/C/0061481_init.c @@ -0,0 +1,144 @@ +/* + * COPYRIGHT (c) 1989-2012. + * 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. + */ + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +#include +#include + +const char rtems_test_name[] = "PSXCANCEL 1"; + +/* forward declarations to avoid warnings */ +void *POSIX_Init(void *argument); +rtems_timer_service_routine Cancel_duringISR_TSR( + rtems_id ignored_id, + void *ignored_address +); +rtems_timer_service_routine SetState_duringISR_TSR( + rtems_id ignored_id, + void *ignored_address +); +rtems_timer_service_routine SetType_duringISR_TSR( + rtems_id ignored_id, + void *ignored_address +); +void doit( + rtems_timer_service_routine (*TSR)(rtems_id, void *), + const char *method +); + +volatile int TSR_occurred; +volatile int TSR_status; + +rtems_id timer_id; + +rtems_timer_service_routine Cancel_duringISR_TSR( + rtems_id ignored_id, + void *ignored_address +) +{ + TSR_status = pthread_cancel( pthread_self() ); + TSR_occurred = 1; +} + +rtems_timer_service_routine SetState_duringISR_TSR( + rtems_id ignored_id, + void *ignored_address +) +{ + int oldstate; + + TSR_status = pthread_setcancelstate( 0, &oldstate ); + TSR_occurred = 1; +} + +rtems_timer_service_routine SetType_duringISR_TSR( + rtems_id ignored_id, + void *ignored_address +) +{ + int oldtype; + + TSR_status = pthread_setcanceltype( 0, &oldtype ); + TSR_occurred = 1; +} + +void doit( + rtems_timer_service_routine (*TSR)(rtems_id, void *), + const char *method +) +{ + rtems_interval start; + rtems_interval end; + rtems_status_code status; + + printf( "Init: schedule %s from a TSR\n", method ); + + TSR_occurred = 0; + TSR_status = 0; + + status = rtems_timer_fire_after( timer_id, 10, TSR, NULL ); + rtems_test_assert( !status ); + + start = rtems_clock_get_ticks_since_boot(); + do { + end = rtems_clock_get_ticks_since_boot(); + } while ( !TSR_occurred && ((end - start) <= 800)); + + if ( !TSR_occurred ) { + printf( "%s did not occur\n", method ); + rtems_test_exit(0); + } + if ( TSR_status != EPROTO ) { + printf( "%s returned %s\n", method, strerror(TSR_status) ); + rtems_test_exit(0); + } + printf( "%s - from ISR returns EPROTO - OK\n", method ); + +} + +void *POSIX_Init( + void *argument +) +{ + rtems_status_code status; + + TEST_BEGIN(); + + status = rtems_timer_create( + rtems_build_name( 'T', 'M', '1', ' ' ), + &timer_id + ); + rtems_test_assert( !status ); + + doit( Cancel_duringISR_TSR, "pthread_cancel" ); + doit( SetState_duringISR_TSR, "pthread_setcancelstate" ); + doit( SetType_duringISR_TSR, "pthread_setcanceltype" ); + + TEST_END(); + rtems_test_exit(0); + return NULL; /* just so the compiler thinks we returned something */ +} + +/* configuration information */ + +#define CONFIGURE_APPLICATION_NEEDS_CONSOLE_DRIVER +#define CONFIGURE_APPLICATION_NEEDS_CLOCK_DRIVER + +#define CONFIGURE_MAXIMUM_TIMERS 1 + +#define CONFIGURE_INITIAL_EXTENSIONS RTEMS_TEST_INITIAL_EXTENSION + +#define CONFIGURE_MAXIMUM_POSIX_THREADS 1 +#define CONFIGURE_POSIX_INIT_THREAD_TABLE + +#define CONFIGURE_INIT +#include diff --git a/pool/shard002/C/0061491_seahorse-pkcs11-source.c b/pool/shard002/C/0061491_seahorse-pkcs11-source.c new file mode 100644 index 0000000000000000000000000000000000000000..0a5d99f1bde91ac8f19f0453c15c2df0d4045122 --- /dev/null +++ b/pool/shard002/C/0061491_seahorse-pkcs11-source.c @@ -0,0 +1,224 @@ +/* + * Seahorse + * + * Copyright (C) 2006 Stefan Walter + * + * 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 "config.h" + +#include +#include +#include + +#include + +#include "seahorse-operation.h" +#include "seahorse-util.h" +#include "seahorse-secure-memory.h" +#include "seahorse-passphrase.h" + +#include "seahorse-pkcs11.h" +#include "seahorse-pkcs11-certificate.h" +#include "seahorse-pkcs11-object.h" +#include "seahorse-pkcs11-operations.h" +#include "seahorse-pkcs11-source.h" + +#include "common/seahorse-registry.h" + +enum { + PROP_0, + PROP_SLOT, + PROP_SOURCE_TAG, + PROP_SOURCE_LOCATION, + PROP_FLAGS +}; + +struct _SeahorsePkcs11SourcePrivate { + GP11Slot *slot; +}; + +static void seahorse_source_iface (SeahorseSourceIface *iface); + +G_DEFINE_TYPE_EXTENDED (SeahorsePkcs11Source, seahorse_pkcs11_source, G_TYPE_OBJECT, 0, + G_IMPLEMENT_INTERFACE (SEAHORSE_TYPE_SOURCE, seahorse_source_iface)); + +/* ----------------------------------------------------------------------------- + * OBJECT + */ + +static void +seahorse_pkcs11_source_init (SeahorsePkcs11Source *self) +{ + self->pv = (G_TYPE_INSTANCE_GET_PRIVATE (self, SEAHORSE_TYPE_PKCS11_SOURCE, SeahorsePkcs11SourcePrivate)); +} + +static GObject* +seahorse_pkcs11_source_constructor (GType type, guint n_props, GObjectConstructParam* props) +{ + GObject* obj = G_OBJECT_CLASS (seahorse_pkcs11_source_parent_class)->constructor (type, n_props, props); + SeahorsePkcs11Source *self = NULL; + + if (obj) { + self = SEAHORSE_PKCS11_SOURCE (obj); + g_return_val_if_fail (self->pv->slot, NULL); + } + + return obj; +} + +static void +seahorse_pkcs11_source_get_property (GObject *object, guint prop_id, GValue *value, + GParamSpec *pspec) +{ + SeahorsePkcs11Source *self = SEAHORSE_PKCS11_SOURCE (object); + + switch (prop_id) { + case PROP_SLOT: + g_value_set_object (value, self->pv->slot); + break; + case PROP_SOURCE_TAG: + g_value_set_uint (value, SEAHORSE_PKCS11_TYPE); + break; + case PROP_SOURCE_LOCATION: + g_value_set_enum (value, SEAHORSE_LOCATION_LOCAL); + break; + case PROP_FLAGS: + g_value_set_uint (value, 0); + break; + } +} + +static void +seahorse_pkcs11_source_set_property (GObject *object, guint prop_id, const GValue *value, + GParamSpec *pspec) +{ + SeahorsePkcs11Source *self = SEAHORSE_PKCS11_SOURCE (object); + + switch (prop_id) { + case PROP_SLOT: + g_return_if_fail (!self->pv->slot); + self->pv->slot = g_value_get_object (value); + g_return_if_fail (self->pv->slot); + g_object_ref (self->pv->slot); + break; + }; +} + +static SeahorseOperation* +seahorse_pkcs11_source_load (SeahorseSource *src) +{ + return seahorse_pkcs11_refresher_new (SEAHORSE_PKCS11_SOURCE (src)); +} + +static void +seahorse_pkcs11_source_dispose (GObject *obj) +{ + SeahorsePkcs11Source *self = SEAHORSE_PKCS11_SOURCE (obj); + + /* The keyring object */ + if (self->pv->slot) + g_object_unref (self->pv->slot); + self->pv->slot = NULL; + + G_OBJECT_CLASS (seahorse_pkcs11_source_parent_class)->dispose (obj); +} + +static void +seahorse_pkcs11_source_finalize (GObject *obj) +{ + SeahorsePkcs11Source *self = SEAHORSE_PKCS11_SOURCE (obj); + + g_assert (self->pv->slot == NULL); + + G_OBJECT_CLASS (seahorse_pkcs11_source_parent_class)->finalize (obj); +} + +static void +seahorse_pkcs11_source_class_init (SeahorsePkcs11SourceClass *klass) +{ + GObjectClass *gobject_class; + + seahorse_pkcs11_source_parent_class = g_type_class_peek_parent (klass); + g_type_class_add_private (klass, sizeof (SeahorsePkcs11SourcePrivate)); + + gobject_class = G_OBJECT_CLASS (klass); + gobject_class->constructor = seahorse_pkcs11_source_constructor; + gobject_class->dispose = seahorse_pkcs11_source_dispose; + gobject_class->finalize = seahorse_pkcs11_source_finalize; + gobject_class->set_property = seahorse_pkcs11_source_set_property; + gobject_class->get_property = seahorse_pkcs11_source_get_property; + + g_object_class_install_property (gobject_class, PROP_SLOT, + g_param_spec_object ("slot", "Slot", "Pkcs#11 SLOT", + GP11_TYPE_SLOT, G_PARAM_READWRITE | G_PARAM_CONSTRUCT_ONLY)); + + g_object_class_install_property (gobject_class, PROP_FLAGS, + g_param_spec_uint ("flags", "Flags", "Object Source flags.", + 0, G_MAXUINT, 0, G_PARAM_READABLE)); + + g_object_class_override_property (gobject_class, PROP_SOURCE_TAG, "source-tag"); + g_object_class_override_property (gobject_class, PROP_SOURCE_LOCATION, "source-location"); + + seahorse_registry_register_type (NULL, SEAHORSE_TYPE_PKCS11_SOURCE, "source", "local", SEAHORSE_PKCS11_TYPE_STR, NULL); +} + +static void +seahorse_source_iface (SeahorseSourceIface *iface) +{ + iface->load = seahorse_pkcs11_source_load; +} + +/* -------------------------------------------------------------------------- + * PUBLIC + */ + +SeahorsePkcs11Source* +seahorse_pkcs11_source_new (GP11Slot *slot) +{ + return g_object_new (SEAHORSE_TYPE_PKCS11_SOURCE, "slot", slot, NULL); +} + +GP11Slot* +seahorse_pkcs11_source_get_slot (SeahorsePkcs11Source *self) +{ + g_return_val_if_fail (SEAHORSE_IS_PKCS11_SOURCE (self), NULL); + return self->pv->slot; +} + +void +seahorse_pkcs11_source_receive_object (SeahorsePkcs11Source *self, GP11Object *obj) +{ + GQuark id = seahorse_pkcs11_object_cannonical_id (obj); + SeahorsePkcs11Certificate *cert; + SeahorseObject *prev; + + g_return_if_fail (SEAHORSE_IS_PKCS11_SOURCE (self)); + + /* TODO: This will need to change once we get other kinds of objects */ + + prev = seahorse_context_get_object (NULL, SEAHORSE_SOURCE (self), id); + if (prev) { + seahorse_object_refresh (prev); + g_object_unref (obj); + return; + } + + cert = seahorse_pkcs11_certificate_new (obj); + g_object_set (cert, "source", self, NULL); + seahorse_context_add_object (NULL, SEAHORSE_OBJECT (cert)); +} diff --git a/pool/shard002/C/0061493_reverse_alternate_levels.c b/pool/shard002/C/0061493_reverse_alternate_levels.c new file mode 100644 index 0000000000000000000000000000000000000000..b7c3438c14b5cde9664c33c01b4432e1fe939149 --- /dev/null +++ b/pool/shard002/C/0061493_reverse_alternate_levels.c @@ -0,0 +1,93 @@ +/* reverse the alternate levels in a binary tree */ + +#include +#include +#define MAX 100 + +struct treenode { + struct treenode *left; + struct treenode *right; + char data; +}; + +struct treenode * newNode(char c) { + struct treenode *node = (struct treenode *) malloc(sizeof(struct treenode)); + node->left = NULL; + node->right = NULL; + node->data = c; + return node; +} + +void inorder(struct treenode *root) { + if(root) { + inorder(root->left); + printf("%c ", root->data); + inorder(root->right); + } +} + +void store_inorder(struct treenode *root, char a[], int *index, int level) { + if(root) { + store_inorder(root->left, a, index, level+1); + if(level%2 != 0) { + a[(*index)++] = root->data; + } + store_inorder(root->right, a, index, level+1); + } +} + +void reverse(char a[], int start, int end) { + + while(startleft, a, index, level+1); + if(level%2 != 0) { + root->data = a[(*index)++]; + } + store_back_inorder(root->right, a, index, level+1); + } +} + +void reverse_alternate(struct treenode *root) { + char a[MAX]; + int index = 0; + store_inorder(root, a, &index, 0); + reverse(a, 0, index-1); + index = 0; + store_back_inorder(root, a, &index, 0); +} + +void main() { + struct treenode *root = newNode('a'); + root->left = newNode('b'); + root->right = newNode('c'); + root->left->left = newNode('d'); + root->left->right = newNode('e'); + root->right->left = newNode('f'); + root->right->right = newNode('g'); + root->left->left->left = newNode('h'); + root->left->left->right = newNode('i'); + root->left->right->left = newNode('j'); + root->left->right->right = newNode('k'); + root->right->left->left = newNode('l'); + root->right->left->right = newNode('m'); + root->right->right->left = newNode('n'); + root->right->right->right = newNode('o'); + + inorder(root); + printf("\n"); + reverse_alternate(root); + inorder(root); +} diff --git a/pool/shard002/C/0061496_tlp_degrmode.c b/pool/shard002/C/0061496_tlp_degrmode.c new file mode 100644 index 0000000000000000000000000000000000000000..6ae975d3ecd0682ac0641500e854807e4cef7d20 --- /dev/null +++ b/pool/shard002/C/0061496_tlp_degrmode.c @@ -0,0 +1,238 @@ +/* + * tlp-degrmode.c + * + * TALPA Filesystem Interceptor + * + * Copyright (C) 2004-2011 Sophos Limited, Oxford, England. + * + * This program is free software; you can redistribute it and/or modify it under the terms of the + * GNU General Public License Version 2 as published by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without + * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along with this program; if not, + * write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + * + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "tlp-test.h" + + +#include "common/bool.h" +#define TALPA_SUBSYS "degrmodetest" +#include "common/talpa.h" + +#include "components/services/linux_personality_impl/linux_personality.h" +#include "components/services/linux_filesystem_impl/linux_fileinfo.h" +#include "components/services/linux_filesystem_impl/linux_filesysteminfo.h" +#include "components/core/intercept_filters_impl/degraded_mode/degraded_mode.h" +#include "components/core/intercept_processing_impl/evaluation_report_impl.h" +#include "components/services/configurator_impl/procfs_configurator.h" +#include "components/services/linux_filesystem_impl/linux_systemroot.h" +#include "app_ctrl/iportability_app_ctrl.h" + +static ISystemRoot* systemRoot(void); +static LinuxSystemRoot* mSystemRoot; + +/* + * Singleton Object. + */ +static IPortabilityApplicationControl GL_talpa_linux = + { + NULL, + systemRoot, + NULL, + NULL, + NULL + }; + +const IPortabilityApplicationControl* TALPA_Portability(void) +{ + return &GL_talpa_linux; +} + +static ISystemRoot* systemRoot(void) +{ + return &mSystemRoot->i_ISystemRoot; +} + +DegradedModeProcessor *degrmode; +EvaluationReportImpl *erep; +static ProcfsConfigurator* mConfig; + +#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,36) +long talpa_ioctl(struct file *file, unsigned int cmd, unsigned long parm) +#else +int talpa_ioctl(struct inode *inode, struct file *file, unsigned int cmd, unsigned long parm) +#endif +{ + int ret = -ENOTTY; + + LinuxPersonality *pers; + + struct talpa_file tf; + LinuxFileInfo *fi; + + pers = newLinuxPersonality(); + + erep->mExternallyVetted = false; + erep->i_IEvaluationReport.setRecommendedAction(erep, EIA_Next); + + switch ( cmd ) + { + case TALPA_TEST_DEGRMODE_TIMEOUTS: + erep->mTimeouts = parm; + ret = 0; + break; + case TALPA_TEST_FILEINFO: + ret = copy_from_user(&tf, (void *)parm, sizeof(struct talpa_file)); + if ( !ret ) + { + fi = newLinuxFileInfo(tf.operation, tf.name, tf.flags, 0); + if ( fi ) + { + degrmode->i_IInterceptFilter.examineFile(degrmode, &erep->i_IEvaluationReport, &pers->i_IPersonality, &fi->i_IFileInfo, NULL); + fi->delete(fi); + ret = erep->i_IEvaluationReport.recommendedAction(erep); + } + else + { + err("Failed to create IFileInfo!"); + ret = -EINVAL; + } + } + else + { + err("copy_from_user!"); + } + break; + } + + pers->delete(pers); + + return ret; +} + +struct file_operations talpa_fops = +{ + owner: THIS_MODULE, +#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,36) + unlocked_ioctl: talpa_ioctl +#else + ioctl: talpa_ioctl +#endif +}; + +static int __init talpa_test_init(void) +{ + int ret; + + mSystemRoot = newLinuxSystemRoot(); + if (mSystemRoot == 0) + { + err("Failed to create system root"); + return -ENOMEM; + } + + mConfig = newProcfsConfigurator(); + if ( !mConfig ) + { + err("Failed to allocate configurator"); + mSystemRoot->delete(mSystemRoot); + return -ENOMEM; + } + + degrmode = newDegradedModeProcessor(); + + if ( !degrmode ) + { + mConfig->delete(mConfig); + mSystemRoot->delete(mSystemRoot); + err("Failed to create degraded mode processor!"); + return 1; + } + + erep = newEvaluationReportImpl(0); + + if ( !erep ) + { + err("Failed to create evaluation report!"); + mConfig->delete(mConfig); + degrmode->delete(degrmode); + mSystemRoot->delete(mSystemRoot); + return 1; + } + + ret = mConfig->i_IConfigurator.attach(mConfig, ECG_InterceptFilter, °rmode->i_IConfigurable); + + if ( ret ) + { + err("Failed to attach configuration!"); + erep->delete(erep); + degrmode->delete(degrmode); + mConfig->delete(mConfig); + mSystemRoot->delete(mSystemRoot); + return ret; + } + + ret = register_chrdev(TALPA_MAJOR, TALPA_DEVICE, &talpa_fops); + + if ( ret ) + { + err("Failed to register TALPA Test character device!"); + mConfig->i_IConfigurator.detach(mConfig, °rmode->i_IConfigurable); + erep->delete(erep); + degrmode->delete(degrmode); + mConfig->delete(mConfig); + mSystemRoot->delete(mSystemRoot); + return ret; + } + + return 0; +} + +static void __exit talpa_test_exit(void) +{ + int ret; + + mConfig->i_IConfigurator.detach(mConfig, °rmode->i_IConfigurable); + mConfig->delete(mConfig); + erep->delete(erep); + degrmode->delete(degrmode); + mSystemRoot->delete(mSystemRoot); + + ret = talpa_unregister_chrdev(TALPA_MAJOR, TALPA_DEVICE); + + if ( ret ) + { + err("Hmmmmmm... very strange things are happening!"); + } +} + +/* + * + * Module information. + * + */ +MODULE_AUTHOR("Sophos Limited"); +MODULE_DESCRIPTION("TALPA Filesystem Interceptor Test Module"); +MODULE_LICENSE("GPL"); + +module_init(talpa_test_init); +module_exit(talpa_test_exit); + diff --git a/pool/shard002/C/0061504_common.c b/pool/shard002/C/0061504_common.c new file mode 100644 index 0000000000000000000000000000000000000000..ead60b434f5324e27b7a6f5fb59ac474ea271c34 --- /dev/null +++ b/pool/shard002/C/0061504_common.c @@ -0,0 +1,132 @@ +/* + * common.c + * Misc functions used in idevicerestore + * + * Copyright (c) 2010 Joshua Hill. 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 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +#include +#include + +#include "common.h" + +int idevicerestore_debug = 0; + +int write_file(const char* filename, const void* data, size_t size) { + size_t bytes = 0; + FILE* file = NULL; + + debug("Writing data to %s\n", filename); + file = fopen(filename, "wb"); + if (file == NULL) { + error("read_file: Unable to open file %s\n", filename); + return -1; + } + + bytes = fwrite(data, 1, size, file); + fclose(file); + + if (bytes != size) { + error("ERROR: Unable to write entire file: %s: %d of %d\n", filename, (int)bytes, (int)size); + return -1; + } + + return size; +} + +int read_file(const char* filename, void** data, size_t* size) { + size_t bytes = 0; + size_t length = 0; + FILE* file = NULL; + char* buffer = NULL; + debug("Reading data from %s\n", filename); + + *size = 0; + *data = NULL; + + file = fopen(filename, "rb"); + if (file == NULL) { + error("read_file: File %s not found\n", filename); + return -1; + } + + fseek(file, 0, SEEK_END); + length = ftell(file); + rewind(file); + + buffer = (char*) malloc(length); + if (buffer == NULL) { + error("ERROR: Out of memory\n"); + fclose(file); + return -1; + } + bytes = fread(buffer, 1, length, file); + fclose(file); + + if (bytes != length) { + error("ERROR: Unable to read entire file\n"); + free(buffer); + return -1; + } + + *size = length; + *data = buffer; + return 0; +} + +void debug_plist(plist_t plist) { + int size = 0; + char* data = NULL; + plist_to_xml(plist, &data, &size); + info("%s", data); + free(data); +} + +void print_progress_bar(double progress) { + int i = 0; + if(progress < 0) return; + if(progress > 100) progress = 100; + info("\r["); + for(i = 0; i < 50; i++) { + if(i < progress / 2) info("="); + else info(" "); + } + info("] %5.1f%%", progress); + if(progress == 100) info("\n"); + fflush(stdout); +} + +#define GET_RAND(min, max) ((rand() % (max - min)) + min) + +char *generate_guid() +{ + char *guid = (char *) malloc(sizeof(char) * 37); + const char *chars = "ABCDEF0123456789"; + srand(time(NULL)); + int i = 0; + + for (i = 0; i < 36; i++) { + if (i == 8 || i == 13 || i == 18 || i == 23) { + guid[i] = '-'; + continue; + } else { + guid[i] = chars[GET_RAND(0, 16)]; + } + } + guid[36] = '\0'; + return guid; +} diff --git a/pool/shard002/C/0061521_unknown_payload.c b/pool/shard002/C/0061521_unknown_payload.c new file mode 100644 index 0000000000000000000000000000000000000000..df126b50b26673f96fb5e45f9449c05b0b92268f --- /dev/null +++ b/pool/shard002/C/0061521_unknown_payload.c @@ -0,0 +1,208 @@ +/** + * @file unknown_payload.c + * + * @brief Implementation of unknown_payload_t. + * + */ + +/* + * Copyright (C) 2005-2006 Martin Willi + * Copyright (C) 2005 Jan Hutter + * Hochschule fuer Technik Rapperswil + * + * 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. See . + * + * 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 "unknown_payload.h" + + + +typedef struct private_unknown_payload_t private_unknown_payload_t; + +/** + * Private data of an unknown_payload_t object. + */ +struct private_unknown_payload_t { + + /** + * Public unknown_payload_t interface. + */ + unknown_payload_t public; + + /** + * Next payload type. + */ + u_int8_t next_payload; + + /** + * Critical flag. + */ + bool critical; + + /** + * Length of this payload. + */ + u_int16_t payload_length; + + /** + * The contained data. + */ + chunk_t data; +}; + +/** + * Encoding rules to parse an payload which is not further specified. + * + * The defined offsets are the positions in a object of type + * private_unknown_payload_t. + * + */ +encoding_rule_t unknown_payload_encodings[] = { + /* 1 Byte next payload type, stored in the field next_payload */ + { U_INT_8, offsetof(private_unknown_payload_t, next_payload)}, + /* the critical bit */ + { FLAG, offsetof(private_unknown_payload_t, critical) }, + /* 7 Bit reserved bits, nowhere stored */ + { RESERVED_BIT, 0 }, + { RESERVED_BIT, 0 }, + { RESERVED_BIT, 0 }, + { RESERVED_BIT, 0 }, + { RESERVED_BIT, 0 }, + { RESERVED_BIT, 0 }, + { RESERVED_BIT, 0 }, + /* Length of the whole payload*/ + { PAYLOAD_LENGTH, offsetof(private_unknown_payload_t, payload_length)}, + /* some unknown data bytes, length is defined in PAYLOAD_LENGTH */ + { UNKNOWN_DATA, offsetof(private_unknown_payload_t, data) } +}; + +/* + 1 2 3 + 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + ! Next Payload !C! RESERVED ! Payload Length ! + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + ! ! + ~ Data of any type ~ + ! ! + +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ +*/ + +/** + * Implementation of payload_t.verify. + */ +static status_t verify(private_unknown_payload_t *this) +{ + /* can't do any checks, so we assume its good */ + return SUCCESS; +} + +/** + * Implementation of payload_t.get_encoding_rules. + */ +static void get_encoding_rules(private_unknown_payload_t *this, encoding_rule_t **rules, size_t *rule_count) +{ + *rules = unknown_payload_encodings; + *rule_count = sizeof(unknown_payload_encodings) / sizeof(encoding_rule_t); +} + +/** + * Implementation of payload_t.get_type. + */ +static payload_type_t get_payload_type(private_unknown_payload_t *this) +{ + return UNKNOWN_PAYLOAD; +} + +/** + * Implementation of payload_t.get_next_type. + */ +static payload_type_t get_next_type(private_unknown_payload_t *this) +{ + return (this->next_payload); +} + +/** + * Implementation of payload_t.set_next_type. + */ +static void set_next_type(private_unknown_payload_t *this,payload_type_t type) +{ + this->next_payload = type; +} + +/** + * Implementation of payload_t.get_length. + */ +static size_t get_length(private_unknown_payload_t *this) +{ + return this->payload_length; +} + +/** + * Implementation of unknown_payload_t.get_data. + */ +static bool is_critical(private_unknown_payload_t *this) +{ + return this->critical; +} + +/** + * Implementation of unknown_payload_t.get_data. + */ +static chunk_t get_data (private_unknown_payload_t *this) +{ + return (this->data); +} + +/** + * Implementation of payload_t.destroy and unknown_payload_t.destroy. + */ +static void destroy(private_unknown_payload_t *this) +{ + if (this->data.ptr != NULL) + { + chunk_free(&(this->data)); + } + + free(this); +} + +/* + * Described in header + */ +unknown_payload_t *unknown_payload_create() +{ + private_unknown_payload_t *this = malloc_thing(private_unknown_payload_t); + + /* interface functions */ + this->public.payload_interface.verify = (status_t (*) (payload_t *))verify; + this->public.payload_interface.get_encoding_rules = (void (*) (payload_t *, encoding_rule_t **, size_t *) ) get_encoding_rules; + this->public.payload_interface.get_length = (size_t (*) (payload_t *)) get_length; + this->public.payload_interface.get_next_type = (payload_type_t (*) (payload_t *)) get_next_type; + this->public.payload_interface.set_next_type = (void (*) (payload_t *,payload_type_t)) set_next_type; + this->public.payload_interface.get_type = (payload_type_t (*) (payload_t *)) get_payload_type; + this->public.payload_interface.destroy = (void (*) (payload_t *))destroy; + + /* public functions */ + this->public.destroy = (void (*) (unknown_payload_t *)) destroy; + this->public.is_critical = (bool (*) (unknown_payload_t *)) is_critical; + this->public.get_data = (chunk_t (*) (unknown_payload_t *)) get_data; + + /* private variables */ + this->critical = FALSE; + this->next_payload = NO_PAYLOAD; + this->payload_length = UNKNOWN_PAYLOAD_HEADER_LENGTH; + this->data = CHUNK_INITIALIZER; + + return (&(this->public)); +} diff --git a/pool/shard002/C/0061526_01_task01.c b/pool/shard002/C/0061526_01_task01.c new file mode 100644 index 0000000000000000000000000000000000000000..7258f5135806b50abec9d43aa2e21bf7680cd7fa --- /dev/null +++ b/pool/shard002/C/0061526_01_task01.c @@ -0,0 +1,13 @@ +#include +#include + +int main() +{ +int a,b,c; +scanf("%d", &a); +b=a*a; +c=a*a*a; +printf("\n %d", b); +printf("\n %d", c); +return 0; +} diff --git a/pool/shard002/C/0061531_webredir.c b/pool/shard002/C/0061531_webredir.c new file mode 100644 index 0000000000000000000000000000000000000000..13c3b41e563ab8999db535b151528adbace9176d --- /dev/null +++ b/pool/shard002/C/0061531_webredir.c @@ -0,0 +1,201 @@ +/* + * webredir UnrealIRCd module + * (C) Copyright 2019 i and the UnrealIRCd team + * + * This module will 301-redirect any clients issuing GET's/POST's during pre-connect stage. + * + * 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 1, 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., 675 Mass Ave, Cambridge, MA 02139, USA. + */ + +#include "unrealircd.h" + +CMD_FUNC(webredir); + +ModuleHeader MOD_HEADER + = { + "webredir", + "1.0", + "Do 301 redirect for HEAD/GET/POST/PUT commands", + "UnrealIRCd Team", + "unrealircd-6", + }; + +struct { + char *url; +} cfg; + +static int nowebredir = 1; + +static void free_config(void); +static void init_config(void); +int webredir_config_posttest(int *errs); +int webredir_config_test(ConfigFile *, ConfigEntry *, int, int *); +int webredir_config_run(ConfigFile *, ConfigEntry *, int); + +MOD_TEST() +{ + HookAdd(modinfo->handle, HOOKTYPE_CONFIGTEST, 0, webredir_config_test); + HookAdd(modinfo->handle, HOOKTYPE_CONFIGPOSTTEST, 0, webredir_config_posttest); + return MOD_SUCCESS; +} + +MOD_INIT() +{ + MARK_AS_OFFICIAL_MODULE(modinfo); + init_config(); + CommandAdd(modinfo->handle, "HEAD", webredir, MAXPARA, CMD_UNREGISTERED); + CommandAdd(modinfo->handle, "GET", webredir, MAXPARA, CMD_UNREGISTERED); + CommandAdd(modinfo->handle, "POST", webredir, MAXPARA, CMD_UNREGISTERED); + CommandAdd(modinfo->handle, "PUT", webredir, MAXPARA, CMD_UNREGISTERED); + HookAdd(modinfo->handle, HOOKTYPE_CONFIGRUN, 0, webredir_config_run); + return MOD_SUCCESS; +} + +MOD_LOAD() +{ + if (SHOWCONNECTINFO) + { + config_warn("I'm disabling set::options::show-connect-info for you " + "as this setting is incompatible with the webredir module."); + SHOWCONNECTINFO = 0; + } + return MOD_SUCCESS; +} + +MOD_UNLOAD() +{ + free_config(); + return MOD_SUCCESS; +} + +static void init_config(void) +{ + memset(&cfg, 0, sizeof(cfg)); +} + +static void free_config(void) +{ + safe_free(cfg.url); + + memset(&cfg, 0, sizeof(cfg)); /* needed! */ +} + +int webredir_config_posttest(int *errs) +{ + int errors = 0; + + if (nowebredir) + { + config_error("set::webredir is missing!"); + errors++; + } + + *errs = errors; + return errors ? -1 : 1; +} + +int webredir_config_test(ConfigFile *cf, ConfigEntry *ce, int type, int *errs) +{ + int errors = 0; + int has_url = 0; + ConfigEntry *cep; + + if (type != CONFIG_SET) + return 0; + + /* We are only interrested in set::webredir... */ + if (!ce || !ce->name || strcmp(ce->name, "webredir")) + return 0; + + nowebredir = 0; + for (cep = ce->items; cep; cep = cep->next) + { + if (!cep->value) + { + config_error("%s:%i: set::webredir::%s with no value", + cep->file->filename, cep->line_number, cep->name); + errors++; + } + else if (!strcmp(cep->name, "url")) + { + if (!*cep->value || strchr(cep->value, ' ')) + { + config_error("%s:%i: set::webredir::%s with empty value", + cep->file->filename, cep->line_number, cep->name); + errors++; + } + if (!strstr(cep->value, "://") || !strcmp(cep->value, "https://...")) + { + config_error("%s:%i: set::webredir::url needs to be a valid URL", + cep->file->filename, cep->line_number); + errors++; + } + if (has_url) + { + config_warn_duplicate(cep->file->filename, + cep->line_number, "set::webredir::url"); + continue; + } + has_url = 1; + } + else + { + config_error("%s:%i: unknown directive set::webredir::%s", + cep->file->filename, cep->line_number, cep->name); + errors++; + } + } + + if (!has_url) + { + config_error_missing(ce->file->filename, ce->line_number, + "set::webredir::url"); + errors++; + } + + *errs = errors; + return errors ? -1 : 1; +} + +int webredir_config_run(ConfigFile *cf, ConfigEntry *ce, int type) +{ + ConfigEntry *cep; + + if (type != CONFIG_SET) + return 0; + + /* We are only interrested in set::webredir... */ + if (!ce || !ce->name || strcmp(ce->name, "webredir")) + return 0; + + for (cep = ce->items; cep; cep = cep->next) + { + if (!strcmp(cep->name, "url")) + { + safe_strdup(cfg.url, cep->value); + } + } + return 1; +} + +CMD_FUNC(webredir) +{ + if (!MyConnect(client)) + return; + + sendto_one(client, NULL, "HTTP/1.1 301 Moved Permanently"); + sendto_one(client, NULL, "Location: %s\r\n\r\n", cfg.url); + dead_socket(client, "Connection closed"); +} diff --git a/pool/shard002/C/0061546_logind-action.c b/pool/shard002/C/0061546_logind-action.c new file mode 100644 index 0000000000000000000000000000000000000000..852ea9f9491d36e75b49db41153f45975a2908da --- /dev/null +++ b/pool/shard002/C/0061546_logind-action.c @@ -0,0 +1,179 @@ +/* SPDX-License-Identifier: LGPL-2.1+ */ +/*** + This file is part of systemd. + + Copyright 2012 Lennart Poettering + + systemd 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. + + systemd 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 systemd; If not, see . +***/ + +#include + +#include "alloc-util.h" +#include "bus-error.h" +#include "bus-util.h" +#include "conf-parser.h" +#include "format-util.h" +#include "logind-action.h" +#include "process-util.h" +#include "sleep-config.h" +#include "special.h" +#include "string-table.h" +#include "terminal-util.h" +#include "user-util.h" + +int manager_handle_action( + Manager *m, + InhibitWhat inhibit_key, + HandleAction handle, + bool ignore_inhibited, + bool is_edge) { + + static const char * const message_table[_HANDLE_ACTION_MAX] = { + [HANDLE_POWEROFF] = "Powering Off...", + [HANDLE_REBOOT] = "Rebooting...", + [HANDLE_HALT] = "Halting...", + [HANDLE_KEXEC] = "Rebooting via kexec...", + [HANDLE_SUSPEND] = "Suspending...", + [HANDLE_HIBERNATE] = "Hibernating...", + [HANDLE_HYBRID_SLEEP] = "Hibernating and suspending..." + }; + + static const char * const target_table[_HANDLE_ACTION_MAX] = { + [HANDLE_POWEROFF] = SPECIAL_POWEROFF_TARGET, + [HANDLE_REBOOT] = SPECIAL_REBOOT_TARGET, + [HANDLE_HALT] = SPECIAL_HALT_TARGET, + [HANDLE_KEXEC] = SPECIAL_KEXEC_TARGET, + [HANDLE_SUSPEND] = SPECIAL_SUSPEND_TARGET, + [HANDLE_HIBERNATE] = SPECIAL_HIBERNATE_TARGET, + [HANDLE_HYBRID_SLEEP] = SPECIAL_HYBRID_SLEEP_TARGET + }; + + _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL; + InhibitWhat inhibit_operation; + Inhibitor *offending = NULL; + bool supported; + int r; + + assert(m); + + /* If the key handling is turned off, don't do anything */ + if (handle == HANDLE_IGNORE) { + log_debug("Refusing operation, as it is turned off."); + return 0; + } + + if (inhibit_key == INHIBIT_HANDLE_LID_SWITCH) { + /* If the last system suspend or startup is too close, + * let's not suspend for now, to give USB docking + * stations some time to settle so that we can + * properly watch its displays. */ + if (m->lid_switch_ignore_event_source) { + log_debug("Ignoring lid switch request, system startup or resume too close."); + return 0; + } + } + + /* If the key handling is inhibited, don't do anything */ + if (inhibit_key > 0) { + if (manager_is_inhibited(m, inhibit_key, INHIBIT_BLOCK, NULL, true, false, 0, NULL)) { + log_debug("Refusing operation, %s is inhibited.", inhibit_what_to_string(inhibit_key)); + return 0; + } + } + + /* Locking is handled differently from the rest. */ + if (handle == HANDLE_LOCK) { + + if (!is_edge) + return 0; + + log_info("Locking sessions..."); + session_send_lock_all(m, true); + return 1; + } + + if (handle == HANDLE_SUSPEND) + supported = can_sleep("suspend") > 0; + else if (handle == HANDLE_HIBERNATE) + supported = can_sleep("hibernate") > 0; + else if (handle == HANDLE_HYBRID_SLEEP) + supported = can_sleep("hybrid-sleep") > 0; + else if (handle == HANDLE_KEXEC) + supported = access(KEXEC, X_OK) >= 0; + else + supported = true; + + if (!supported) { + log_warning("Requested operation not supported, ignoring."); + return -EOPNOTSUPP; + } + + if (m->action_what) { + log_debug("Action already in progress, ignoring."); + return -EALREADY; + } + + inhibit_operation = IN_SET(handle, HANDLE_SUSPEND, HANDLE_HIBERNATE, HANDLE_HYBRID_SLEEP) ? INHIBIT_SLEEP : INHIBIT_SHUTDOWN; + + /* If the actual operation is inhibited, warn and fail */ + if (!ignore_inhibited && + manager_is_inhibited(m, inhibit_operation, INHIBIT_BLOCK, NULL, false, false, 0, &offending)) { + _cleanup_free_ char *comm = NULL, *u = NULL; + + get_process_comm(offending->pid, &comm); + u = uid_to_name(offending->uid); + + /* If this is just a recheck of the lid switch then don't warn about anything */ + if (!is_edge) { + log_debug("Refusing operation, %s is inhibited by UID "UID_FMT"/%s, PID "PID_FMT"/%s.", + inhibit_what_to_string(inhibit_operation), + offending->uid, strna(u), + offending->pid, strna(comm)); + return 0; + } + + log_error("Refusing operation, %s is inhibited by UID "UID_FMT"/%s, PID "PID_FMT"/%s.", + inhibit_what_to_string(inhibit_operation), + offending->uid, strna(u), + offending->pid, strna(comm)); + + return -EPERM; + } + + log_info("%s", message_table[handle]); + + r = bus_manager_shutdown_or_sleep_now_or_later(m, target_table[handle], inhibit_operation, &error); + if (r < 0) { + log_error("Failed to execute operation: %s", bus_error_message(&error, r)); + return r; + } + + return 1; +} + +static const char* const handle_action_table[_HANDLE_ACTION_MAX] = { + [HANDLE_IGNORE] = "ignore", + [HANDLE_POWEROFF] = "poweroff", + [HANDLE_REBOOT] = "reboot", + [HANDLE_HALT] = "halt", + [HANDLE_KEXEC] = "kexec", + [HANDLE_SUSPEND] = "suspend", + [HANDLE_HIBERNATE] = "hibernate", + [HANDLE_HYBRID_SLEEP] = "hybrid-sleep", + [HANDLE_LOCK] = "lock" +}; + +DEFINE_STRING_TABLE_LOOKUP(handle_action, HandleAction); +DEFINE_CONFIG_PARSE_ENUM(config_parse_handle_action, handle_action, HandleAction, "Failed to parse handle action setting"); diff --git a/pool/shard002/C/0061553_main.c b/pool/shard002/C/0061553_main.c new file mode 100644 index 0000000000000000000000000000000000000000..5680be8a1a4ec7d01f1bbc38993b1af306d13afd --- /dev/null +++ b/pool/shard002/C/0061553_main.c @@ -0,0 +1,162 @@ +/** + * @file src/main.c + * + * @brief Main program functions. + */ + +#include +#include +#include +#include +#include + +#include "assert.h" +#include "data.h" +#include "error.h" +#include "lists.h" +#include "config.h" +#include "capacitance.h" +#include "sor.h" + +char *a_configfile=NULL; + +/** + * @brief Interrupt handler. + */ +void main_interrupt(int num) +{ + error("\nInterrupt. Will finish this net and save state. Use '-r' to restore."); + + a_interrupt=1; + + signal(SIGINT, SIG_DFL); +} + +/** + * @brief Print syntax. + */ +void main_syntax() +{ + printf("NELMA, Numerical ElectroMagnetics. Capacitance calculator version %s\n", VERSION); + printf("Copyright (c) 2006 Tomaz Solc\n\n"); + + printf("SYNTAX: nelma-cap [ -s STANDOFF ]\n"); + printf(" [ -n ITERATIONS ]\n"); + printf(" [ -w SOR_OMEGA ]\n"); + printf(" [ -e MAX_ERROR_%% ]\n"); + printf(" [ -d ]\n"); + printf(" [ -v VERBOSITY ]\n"); + printf(" [ -r ]\n"); + printf(" config_file.em\n\n"); + + printf("Bug reports to \n"); + + return; +} + +/** + * @brief Print header. + */ +void main_header(int argc, char **argv) +{ + int n; + time_t t; + + t=time(NULL); + + printf("* Created by NELMA capacitance calculator, version %s\n", VERSION); + printf("* %s", ctime(&t)); + printf("*\n"); + printf("* Command line:"); + + for(n=0;n +#include + + +// code to be emulated +#define SPARC_CODE "\x86\x00\x40\x02" // add %g1, %g2, %g3; +//#define SPARC_CODE "\xbb\x70\x00\x00" // illegal code + +// memory address where emulation starts +#define ADDRESS 0x10000 + +static void hook_block(uc_engine *uc, uint64_t address, uint32_t size, void *user_data) +{ + printf(">>> Tracing basic block at 0x%"PRIx64 ", block size = 0x%x\n", address, size); +} + +static void hook_code(uc_engine *uc, uint64_t address, uint32_t size, void *user_data) +{ + printf(">>> Tracing instruction at 0x%"PRIx64 ", instruction size = 0x%x\n", address, size); +} + +static void test_sparc(void) +{ + uc_engine *uc; + uc_err err; + uc_hook trace1, trace2; + + int g1 = 0x1230; // G1 register + int g2 = 0x6789; // G2 register + int g3 = 0x5555; // G3 register + + printf("Emulate SPARC code\n"); + + // Initialize emulator in Sparc mode + err = uc_open(UC_ARCH_SPARC, UC_MODE_SPARC32|UC_MODE_BIG_ENDIAN, &uc); + if (err) { + printf("Failed on uc_open() with error returned: %u (%s)\n", + err, uc_strerror(err)); + return; + } + + // map 2MB memory for this emulation + uc_mem_map(uc, ADDRESS, 2 * 1024 * 1024, UC_PROT_ALL); + + // write machine code to be emulated to memory + uc_mem_write(uc, ADDRESS, SPARC_CODE, sizeof(SPARC_CODE) - 1); + + // initialize machine registers + uc_reg_write(uc, UC_SPARC_REG_G1, &g1); + uc_reg_write(uc, UC_SPARC_REG_G2, &g2); + uc_reg_write(uc, UC_SPARC_REG_G3, &g3); + + // tracing all basic blocks with customized callback + uc_hook_add(uc, &trace1, UC_HOOK_BLOCK, hook_block, NULL, 1, 0); + + // tracing all instructions with customized callback + uc_hook_add(uc, &trace2, UC_HOOK_CODE, hook_code, NULL, 1, 0); + + // emulate machine code in infinite time (last param = 0), or when + // finishing all the code. + err = uc_emu_start(uc, ADDRESS, ADDRESS + sizeof(SPARC_CODE) - 1, 0, 0); + if (err) { + printf("Failed on uc_emu_start() with error returned: %u (%s)\n", + err, uc_strerror(err)); + } + + // now print out some registers + printf(">>> Emulation done. Below is the CPU context\n"); + + uc_reg_read(uc, UC_SPARC_REG_G3, &g3); + printf(">>> G3 = 0x%x\n", g3); + + uc_close(uc); +} + +int main(int argc, char **argv, char **envp) +{ + // dynamically load shared library +#ifdef DYNLOAD + if (!uc_dyn_load(NULL, 0)) { + printf("Error dynamically loading shared library.\n"); + printf("Please check that unicorn.dll/unicorn.so is available as well as\n"); + printf("any other dependent dll/so files.\n"); + printf("The easiest way is to place them in the same directory as this app.\n"); + return 1; + } +#endif + + test_sparc(); + + // dynamically free shared library +#ifdef DYNLOAD + uc_dyn_free(); +#endif + + return 0; +} diff --git a/pool/shard002/C/0061592_readAll.c b/pool/shard002/C/0061592_readAll.c new file mode 100644 index 0000000000000000000000000000000000000000..92e6b9412993c951c9eeb1e9a9a4f11b10b8747b --- /dev/null +++ b/pool/shard002/C/0061592_readAll.c @@ -0,0 +1,109 @@ +/** + * @file readAll.c + * @author Salvatore Barone + * @date 19 06 2017 + * + * @copyright + * Copyright 2017 Salvatore Barone + * + * This file is part of Zynq7000DriverPack + * + * Zynq7000DriverPack 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 any later version. + * + * Zynq7000DriverPack 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. + * + * @example readAll.c + * Il file readAll.c contiene un programma di test/debug che è possibile eseguire in un sistema operativo + * Linux. L'esempio costituisce un programma user-space che non fa altro che leggere tutti i registri di + * un device, senza mediazione di altri driver, usando il device-file /dev/mem. + */ + +#include +#include +#include +#include +#include +#include + +void howto(void) { + printf("Uso:\n"); + printf("noDriver -a -o \n"); + printf("-a : indirizzo fisico del device GPIO\n"); + printf("\t-o : offsett dell'ultimo registro letto\n"); +} + +int parse_args(int argc, char **argv, uint32_t *gpio_address, uint32_t *max_offset) { + int par; + + while((par = getopt(argc, argv, "a:o:")) != -1) { + switch (par) { + case 'a' : + *gpio_address = strtoul(optarg, NULL, 0); + break; + case 'o' : + *max_offset = strtoul(optarg, NULL, 0); + break; + default : + printf("%c: parametro sconosciuto.\n", par); + howto(); + return -1; + } + } + return 0; +} + +int main(int argc, char** argv) { + uint32_t gpio_addr = 0; + uint32_t max_offset = 16; + + if (parse_args(argc, argv, &gpio_addr, &max_offset) == -1) + return -1; + + if (gpio_addr == 0) { + printf("è necessario specificare l'indirizzo di memoria del device.\n"); + howto(); + return -1; + } + + int descriptor = open ("/dev/mem", O_RDWR); + if (descriptor < 1) { + perror(argv[0]); + return -1; + } + + uint32_t page_size = sysconf(_SC_PAGESIZE); // dimensione della pagina + uint32_t page_mask = ~(page_size-1); // maschera di conversione indirizzo -> indirizzo pagina + uint32_t page_addr = gpio_addr & page_mask; // indirizzo della "pagina fisica" a cui è mappato il device + uint32_t offset = gpio_addr - page_addr; // offset del device rispetto all'indirizzo della pagina + // conversione dell'indirizzo fisico in indirizzo virtuale + void* vrt_page_addr = mmap(NULL, page_size, PROT_READ | PROT_WRITE, MAP_SHARED, descriptor, page_addr); + + if (vrt_page_addr == MAP_FAILED) { + printf("Mapping indirizzo fisico - indirizzo virtuale FALLITO!\n"); + return -1; + } + + void* vrt_gpio_addr = vrt_page_addr + offset; // indirizzo virtuale del device gpio + + printf("base address : %08X\n", (uint32_t) vrt_gpio_addr); + uint32_t read_value = 0; + uint32_t i; + for (i=0; i<=max_offset; i+=4) { + read_value = *((uint32_t*)(vrt_gpio_addr+i)); + printf("\toffset : %08X => %08X\n", i, read_value); + } + + munmap(vrt_page_addr, page_size); + close(descriptor); + + return 0; +} + diff --git a/pool/shard002/C/0061602_stdtr.c b/pool/shard002/C/0061602_stdtr.c new file mode 100644 index 0000000000000000000000000000000000000000..abcc4062fb2940434bfd3861fb22f2ba30923418 --- /dev/null +++ b/pool/shard002/C/0061602_stdtr.c @@ -0,0 +1,207 @@ +/* stdtr.c + * + * Student's t distribution + * + * + * + * SYNOPSIS: + * + * double t, stdtr(); + * short k; + * + * y = stdtr( k, t ); + * + * + * DESCRIPTION: + * + * Computes the integral from minus infinity to t of the Student + * t distribution with integer k > 0 degrees of freedom: + * + * t + * - + * | | + * - | 2 -(k+1)/2 + * | ( (k+1)/2 ) | ( x ) + * ---------------------- | ( 1 + --- ) dx + * - | ( k ) + * sqrt( k pi ) | ( k/2 ) | + * | | + * - + * -inf. + * + * Relation to incomplete beta integral: + * + * 1 - stdtr(k,t) = 0.5 * incbet( k/2, 1/2, z ) + * where + * z = k/(k + t**2). + * + * For t < -2, this is the method of computation. For higher t, + * a direct method is derived from integration by parts. + * Since the function is symmetric about t=0, the area under the + * right tail of the density is found by calling the function + * with -t instead of t. + * + * ACCURACY: + * + * Tested at random 1 <= k <= 25. The "domain" refers to t. + * Relative error: + * arithmetic domain # trials peak rms + * IEEE -100,-2 50000 5.9e-15 1.4e-15 + * IEEE -2,100 500000 2.7e-15 4.9e-17 + */ + +/* stdtri.c + * + * Functional inverse of Student's t distribution + * + * + * + * SYNOPSIS: + * + * double p, t, stdtri(); + * int k; + * + * t = stdtri( k, p ); + * + * + * DESCRIPTION: + * + * Given probability p, finds the argument t such that stdtr(k,t) + * is equal to p. + * + * ACCURACY: + * + * Tested at random 1 <= k <= 100. The "domain" refers to p: + * Relative error: + * arithmetic domain # trials peak rms + * IEEE .001,.999 25000 5.7e-15 8.0e-16 + * IEEE 10^-6,.001 25000 2.0e-12 2.9e-14 + */ + + +/* + * Cephes Math Library Release 2.3: March, 1995 + * Copyright 1984, 1987, 1995 by Stephen L. Moshier + */ + +#include "mconf.h" +#include + +extern double MACHEP; + +double stdtr(k, t) +int k; +double t; +{ + double x, rk, z, f, tz, p, xsqk; + int j; + + if (k <= 0) { + mtherr("stdtr", DOMAIN); + return (OWL_NAN); + } + + if (t == 0) + return (0.5); + + if (t < -2.0) { + rk = k; + z = rk / (rk + t * t); + p = 0.5 * incbet(0.5 * rk, 0.5, z); + return (p); + } + + /* compute integral from -t to + t */ + + if (t < 0) + x = -t; + else + x = t; + + rk = k; /* degrees of freedom */ + z = 1.0 + (x * x) / rk; + + /* test if k is odd or even */ + if ((k & 1) != 0) { + + /* computation for odd k */ + + xsqk = x / sqrt(rk); + p = atan(xsqk); + if (k > 1) { + f = 1.0; + tz = 1.0; + j = 3; + while ((j <= (k - 2)) && ((tz / f) > MACHEP)) { + tz *= (j - 1) / (z * j); + f += tz; + j += 2; + } + p += f * xsqk / z; + } + p *= 2.0 / OWL_PI; + } + + + else { + + /* computation for even k */ + + f = 1.0; + tz = 1.0; + j = 2; + + while ((j <= (k - 2)) && ((tz / f) > MACHEP)) { + tz *= (j - 1) / (z * j); + f += tz; + j += 2; + } + p = f * x / sqrt(z * rk); + } + + /* common exit */ + + + if (t < 0) + p = -p; /* note destruction of relative accuracy */ + + p = 0.5 + 0.5 * p; + return (p); +} + +double stdtri(k, p) +int k; +double p; +{ + double t, rk, z; + int rflg; + + if (k <= 0 || p <= 0.0 || p >= 1.0) { + mtherr("stdtri", DOMAIN); + return (OWL_NAN); + } + + rk = k; + + if (p > 0.25 && p < 0.75) { + if (p == 0.5) + return (0.0); + z = 1.0 - 2.0 * p; + z = incbi(0.5, 0.5 * rk, fabs(z)); + t = sqrt(rk * z / (1.0 - z)); + if (p < 0.5) + t = -t; + return (t); + } + rflg = -1; + if (p >= 0.5) { + p = 1.0 - p; + rflg = 1; + } + z = incbi(0.5 * rk, 0.5, 2.0 * p); + + if (DBL_MAX * z < rk) + return (rflg * OWL_POSINF); + t = sqrt(rk / z - rk); + return (rflg * t); +} diff --git a/pool/shard002/C/0061635_roverp5p_lcd.c b/pool/shard002/C/0061635_roverp5p_lcd.c new file mode 100644 index 0000000000000000000000000000000000000000..fd20732f1475c366dba3f2839d01b795789356e1 --- /dev/null +++ b/pool/shard002/C/0061635_roverp5p_lcd.c @@ -0,0 +1,292 @@ +/* + * LCD controls for roverp5p + * + * Copyright ? 2004 Andrew Zabolotny + * + * 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. + * + * + * 2003 Andrew Zabolotny Original code for Axim X5 + * 2004 Konstantine A. Beklemishev Copied from aximx5_lcd.c and adapted to Rover P5+ + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include "../drivers/soc/mq11xx.h" + +#if 0 +# define debug(s, args...) printk (KERN_INFO s, ##args) +#else +# define debug(s, args...) +#endif +#define debug_func(s, args...) debug ("%s: " s, __FUNCTION__, ##args) + +static int roverp5p_lcd_set_power (struct lcd_device *ld, int state) +{ + struct mediaq11xx_base *mq_base = class_get_devdata (&ld->class_dev); + int lcdfp_state = mq_base->get_power (mq_base, MEDIAQ_11XX_FP_DEVICE_ID) ? 1 : 0; + int fpctl_state = mq_base->get_power (mq_base, MEDIAQ_11XX_FB_DEVICE_ID) ? 1 : 0; + + int new_lcdfp_state = (state < 1) ? 1 : 0; + int new_fpctl_state = (state < 4) ? 1 : 0; + + debug_func ("state:%d\n", state); + + if (new_lcdfp_state != lcdfp_state) + mq_base->set_power (mq_base, MEDIAQ_11XX_FP_DEVICE_ID, new_lcdfp_state); + if (new_fpctl_state != fpctl_state) + mq_base->set_power (mq_base, MEDIAQ_11XX_FB_DEVICE_ID, new_fpctl_state); + + if (new_lcdfp_state) + /* MediaQ GPIO 1 seems connected to flat-panel power */ + mq_base->set_GPIO (mq_base, 1, MQ_GPIO_OUT1); + else + /* Output '0' to MQ1132 GPIO 1 */ + mq_base->set_GPIO (mq_base, 1, MQ_GPIO_OUT0); + + return 0; +} + +static int roverp5p_lcd_get_power (struct lcd_device *ld) +{ + struct mediaq11xx_base *mq_base = class_get_devdata (&ld->class_dev); + int lcdfp_state = mq_base->get_power (mq_base, MEDIAQ_11XX_FP_DEVICE_ID); + int fpctl_state = mq_base->get_power (mq_base, MEDIAQ_11XX_FB_DEVICE_ID); + + debug_func ("\n"); + + if (lcdfp_state == 0) { + if (fpctl_state == 0) + return 4; + else + return 2; + } + return 0; +} + +/* This routine is generic for any MediaQ 1100/1132 chips */ +static int +roverp5p_lcd_set_contrast (struct lcd_device *ld, int contrast) +{ + struct mediaq11xx_base *mq_base = class_get_devdata (&ld->class_dev); + u32 x; + + debug_func ("contrast:%d\n", contrast); + + /* Well... this is kind of tricky but here's how it works: + * On 24-bit TFT panels the R,G,B channels are output via + * the FD0..FD23 MQ1132' outputs. There are separate enable + * bits for these pins in FP07R, which we will use. + * Basically we just mask out (setting them to '1') + * the lowest 1..8 bits of every color component thus + * effectively reducing the number of bits for them. + */ + if (contrast > 7) + contrast = 7; + contrast = 7 ^ contrast; + + x = (1 << contrast) - 1; + + mq_base->regs->FP.pin_output_data |= 0x00ffffff; + mq_base->regs->FP.pin_output_select_1 = + (mq_base->regs->FP.pin_output_select_1 & 0xff000000) | + x | (x << 8) | (x << 16); + + return 0; +} + +static int +roverp5p_lcd_get_contrast (struct lcd_device *ld) +{ + struct mediaq11xx_base *mq_base = class_get_devdata (&ld->class_dev); + u32 c, x; + + debug_func ("\n"); + + x = (mq_base->regs->FP.pin_output_select_1 & 0x7f); + for (c = 7; x; x >>= 1, c--) + ; + return c; +} + +/*---* Backlight *---*/ + +static int +roverp5p_backlight_set_power (struct backlight_device *bd, int state) +{ + struct mediaq11xx_base *mq_base = class_get_devdata (&bd->class_dev); + + debug_func ("state:%d\n", state); + + /* Turn off backlight power */ + if (state == 0) { + mq_base->set_GPIO (mq_base, 64, MQ_GPIO_IN | MQ_GPIO_OUT1); + if (PWM_PWDUTY0 & 0x3ff) + CKEN |= CKEN0_PWM0; + else + CKEN &= ~CKEN0_PWM0; + } else { + CKEN &= ~CKEN0_PWM0; + mq_base->set_GPIO (mq_base, 64, MQ_GPIO_IN | MQ_GPIO_OUT0); + } + return 0; +} + +static int +roverp5p_backlight_get_power (struct backlight_device *bd) +{ + struct mediaq11xx_base *mq_base = class_get_devdata (&bd->class_dev); + + debug_func ("\n"); + + return mq_base->get_GPIO (mq_base, 64) ? 0 : 4; +} + +static int +roverp5p_backlight_set_brightness (struct backlight_device *bd, int brightness) +{ + debug_func ("brightness:%d\n", brightness); + + if (brightness > 0x3ff) + brightness = 0x3ff; + + /* LCD brightness on Dell Axim is driven by PWM0. + * We'll set the pre-scaler to 8, and the period to 1024, this + * means the backlight refresh rate will be 3686400/(8*1024) = + * 450 Hz which is quite enough. + */ + PWM_CTRL0 = 7; /* pre-scaler */ + PWM_PWDUTY0 = brightness; /* duty cycle */ + PWM_PERVAL0 = 0x3ff; /* period */ + + if (brightness) + CKEN |= CKEN0_PWM0; + else + CKEN &= ~CKEN0_PWM0; + + return 0; +} + +static int +roverp5p_backlight_get_brightness (struct backlight_device *bd) +{ + u32 x, y; + + debug_func ("\n"); + + x = PWM_PWDUTY0 & 0x3ff; + y = PWM_PERVAL0 & 0x3ff; + // To avoid division, we'll approximate y to nearest 2^n-1. + // PocketPC is using 0xfe as PERVAL0 and we're using 0x3ff. + x <<= (10 - fls (y)); + return x; +} + +/*-------------------// Flat panel driver for SoC device //------------------*/ + +static struct lcd_ops mq11xx_fb0_lcd = { + .get_power = roverp5p_lcd_get_power, + .set_power = roverp5p_lcd_set_power, + .max_contrast = 7, + .get_contrast = roverp5p_lcd_get_contrast, + .set_contrast = roverp5p_lcd_set_contrast, +}; + +static struct backlight_properties mq11xx_fb0_bl = { + .owner = THIS_MODULE, + .get_power = roverp5p_backlight_get_power, + .set_power = roverp5p_backlight_set_power, + .max_brightness = 0x3ff, + .get_brightness = roverp5p_backlight_get_brightness, + .set_brightness = roverp5p_backlight_set_brightness, +}; + +static struct lcd_device *mqfb_lcd_device; +static struct backlight_device *mqfb_backlight_device; + +static int roverp5p_fp_probe (struct device *dev) +{ + struct mediaq11xx_base *mq_base = + (struct mediaq11xx_base *)dev->platform_data; + + mqfb_backlight_device = backlight_device_register ("mq11xx_fb0", + mq_base, &mq11xx_fb0_bl); + if (IS_ERR (mqfb_backlight_device)) + return PTR_ERR (mqfb_backlight_device); + mqfb_lcd_device = lcd_device_register ("mq11xx_fb0", mq_base, + &mq11xx_fb0_lcd); + if (IS_ERR (mqfb_lcd_device)) { + backlight_device_unregister (mqfb_backlight_device); + return PTR_ERR (mqfb_lcd_device); + } + + return 0; +} + +static int roverp5p_fp_remove (struct device *dev) +{ + debug_func ("\n"); + + backlight_device_unregister (mqfb_backlight_device); + lcd_device_unregister (mqfb_lcd_device); + + return 0; +} + +static int roverp5p_fp_suspend (struct device *dev, u32 state, u32 level) +{ + debug_func ("\n"); + return 0; +} + +static int roverp5p_fp_resume (struct device *dev, u32 level) +{ + debug_func ("\n"); + return 0; +} + +static platform_device_id roverp5p_fp_device_ids[] = { MEDIAQ_11XX_FP_DEVICE_ID, 0 }; + +struct device_driver roverp5p_fp_device_driver = { + .name = "mq11xx_lcd", + .probe = roverp5p_fp_probe, + .remove = roverp5p_fp_remove, + .suspend = roverp5p_fp_suspend, + .resume = roverp5p_fp_resume +}; + +static int __init +roverp5p_fp_init(void) +{ + debug_func ("\n"); + return driver_register (&roverp5p_fp_device_driver); +} + +static void __exit +roverp5p_fp_exit(void) +{ + debug_func ("\n"); + driver_unregister (&roverp5p_fp_device_driver); +} + +module_init(roverp5p_fp_init); +module_exit(roverp5p_fp_exit); + +MODULE_AUTHOR("Konstantine A. Bekelmishev "); +MODULE_DESCRIPTION("LCD driver for Rover P5+"); +MODULE_LICENSE("GPL"); diff --git a/pool/shard002/C/0061638_networkd-address-label.c b/pool/shard002/C/0061638_networkd-address-label.c new file mode 100644 index 0000000000000000000000000000000000000000..4c5544273946291317657fc9b0154e19053526b2 --- /dev/null +++ b/pool/shard002/C/0061638_networkd-address-label.c @@ -0,0 +1,202 @@ +/* SPDX-License-Identifier: LGPL-2.1+ */ + +#include +#include + +#include "alloc-util.h" +#include "conf-parser.h" +#include "networkd-address-label.h" +#include "netlink-util.h" +#include "networkd-manager.h" +#include "parse-util.h" +#include "socket-util.h" + +int address_label_new(AddressLabel **ret) { + _cleanup_(address_label_freep) AddressLabel *addrlabel = NULL; + + addrlabel = new0(AddressLabel, 1); + if (!addrlabel) + return -ENOMEM; + + *ret = TAKE_PTR(addrlabel); + + return 0; +} + +void address_label_free(AddressLabel *label) { + if (!label) + return; + + if (label->network) { + LIST_REMOVE(labels, label->network->address_labels, label); + assert(label->network->n_address_labels > 0); + label->network->n_address_labels--; + + if (label->section) { + hashmap_remove(label->network->address_labels_by_section, label->section); + network_config_section_free(label->section); + } + } + + free(label); +} + +static int address_label_new_static(Network *network, const char *filename, unsigned section_line, AddressLabel **ret) { + _cleanup_(network_config_section_freep) NetworkConfigSection *n = NULL; + _cleanup_(address_label_freep) AddressLabel *label = NULL; + int r; + + assert(network); + assert(ret); + assert(!!filename == (section_line > 0)); + + r = network_config_section_new(filename, section_line, &n); + if (r < 0) + return r; + + label = hashmap_get(network->address_labels_by_section, n); + if (label) { + *ret = TAKE_PTR(label); + + return 0; + } + + r = address_label_new(&label); + if (r < 0) + return r; + + label->section = TAKE_PTR(n); + + r = hashmap_put(network->address_labels_by_section, label->section, label); + if (r < 0) + return r; + + label->network = network; + LIST_APPEND(labels, network->address_labels, label); + network->n_address_labels++; + + *ret = TAKE_PTR(label); + + return 0; +} + +int address_label_configure( + AddressLabel *label, + Link *link, + sd_netlink_message_handler_t callback, + bool update) { + + _cleanup_(sd_netlink_message_unrefp) sd_netlink_message *req = NULL; + int r; + + assert(label); + assert(link); + assert(link->ifindex > 0); + assert(link->manager); + assert(link->manager->rtnl); + + r = sd_rtnl_message_new_addrlabel(link->manager->rtnl, &req, RTM_NEWADDRLABEL, + link->ifindex, AF_INET6); + if (r < 0) + return log_error_errno(r, "Could not allocate RTM_NEWADDR message: %m"); + + r = sd_rtnl_message_addrlabel_set_prefixlen(req, label->prefixlen); + if (r < 0) + return log_error_errno(r, "Could not set prefixlen: %m"); + + r = sd_netlink_message_append_u32(req, IFAL_LABEL, label->label); + if (r < 0) + return log_error_errno(r, "Could not append IFAL_LABEL attribute: %m"); + + r = sd_netlink_message_append_in6_addr(req, IFA_ADDRESS, &label->in_addr.in6); + if (r < 0) + return log_error_errno(r, "Could not append IFA_ADDRESS attribute: %m"); + + r = sd_netlink_call_async(link->manager->rtnl, req, callback, link, 0, NULL); + if (r < 0) + return log_error_errno(r, "Could not send rtnetlink message: %m"); + + link_ref(link); + + return 0; +} + +int config_parse_address_label_prefix(const char *unit, + const char *filename, + unsigned line, + const char *section, + unsigned section_line, + const char *lvalue, + int ltype, + const char *rvalue, + void *data, + void *userdata) { + + _cleanup_(address_label_freep) AddressLabel *n = NULL; + Network *network = userdata; + int r; + + assert(filename); + assert(section); + assert(lvalue); + assert(rvalue); + assert(data); + + r = address_label_new_static(network, filename, section_line, &n); + if (r < 0) + return r; + + r = in_addr_prefix_from_string(rvalue, AF_INET6, &n->in_addr, &n->prefixlen); + if (r < 0) { + log_syntax(unit, LOG_ERR, filename, line, r, "Address label is invalid, ignoring assignment: %s", rvalue); + return 0; + } + + n = NULL; + + return 0; +} + +int config_parse_address_label( + const char *unit, + const char *filename, + unsigned line, + const char *section, + unsigned section_line, + const char *lvalue, + int ltype, + const char *rvalue, + void *data, + void *userdata) { + + _cleanup_(address_label_freep) AddressLabel *n = NULL; + Network *network = userdata; + uint32_t k; + int r; + + assert(filename); + assert(section); + assert(lvalue); + assert(rvalue); + assert(data); + + r = address_label_new_static(network, filename, section_line, &n); + if (r < 0) + return r; + + r = safe_atou32(rvalue, &k); + if (r < 0) { + log_syntax(unit, LOG_ERR, filename, line, r, "Failed to parse address label, ignoring: %s", rvalue); + return 0; + } + + if (k == 0xffffffffUL) { + log_syntax(unit, LOG_ERR, filename, line, r, "Address label is invalid, ignoring: %s", rvalue); + return 0; + } + + n->label = k; + n = NULL; + + return 0; +} diff --git a/pool/shard002/C/0061648_pxe.c b/pool/shard002/C/0061648_pxe.c new file mode 100644 index 0000000000000000000000000000000000000000..0c9fb06a2e05e6e2016e12af71584ea17ec0129a --- /dev/null +++ b/pool/shard002/C/0061648_pxe.c @@ -0,0 +1,175 @@ +/* + * Copyright 2013-2014 Intel Corporation - All Rights Reserved + */ + +#include +#include +#include "efi.h" +#include "net.h" +#include "fs/pxe/pxe.h" + +const struct url_scheme url_schemes[] = { + { "tftp", tftp_open, 0 }, + { "http", http_open, O_DIRECTORY }, + { "ftp", ftp_open, O_DIRECTORY }, + { NULL, NULL, 0 }, +}; + +/** + * Network stack-specific initialization + */ +void net_core_init(void) +{ + http_bake_cookies(); +} + +void pxe_init_isr(void) {} +void gpxe_init(void) {} +void pxe_idle_init(void) {} + +int reset_pxe(void) +{ + return 0; +} + +#define DNS_MAX_SERVERS 4 /* Max no of DNS servers */ +uint32_t dns_server[DNS_MAX_SERVERS] = {0, }; + +__export uint32_t dns_resolv(const char *name) +{ + /* + * Return failure on an empty input... this can happen during + * some types of URL parsing, and this is the easiest place to + * check for it. + */ + if (!name || !*name) + return 0; + + return 0; +} + +int pxe_init(bool quiet) +{ + EFI_HANDLE *handles; + EFI_STATUS status; + UINTN nr_handles; + + status = LibLocateHandle(ByProtocol, &PxeBaseCodeProtocol, + NULL, &nr_handles, &handles); + if (status != EFI_SUCCESS) { + if (!quiet) + Print(L"No PXE Base Code Protocol\n"); + return -1; + } + + return 0; +} + +#define EDHCP_BUF_LEN 8192 + +struct embedded_dhcp_options { + uint32_t magic[4]; + uint32_t bdhcp_len; + uint32_t adhcp_len; + uint32_t buffer_size; + uint32_t reserved; + uint8_t dhcp_data[EDHCP_BUF_LEN]; +} __attribute__((aligned(16))); + +struct embedded_dhcp_options embedded_dhcp_options = +{ + .magic[0] = 0x2a171ead, + .magic[1] = 0x0600e65e, + .magic[2] = 0x4025a4e4, + .magic[3] = 0x42388fc8, + .bdhcp_len = 0, + .adhcp_len = 0, + .buffer_size = EDHCP_BUF_LEN, +}; + +void net_parse_dhcp(void) +{ + EFI_PXE_BASE_CODE_MODE *mode; + EFI_PXE_BASE_CODE *bc; + unsigned int pkt_len = sizeof(EFI_PXE_BASE_CODE_PACKET); + EFI_STATUS status; + EFI_HANDLE *handles = NULL; + UINTN nr_handles = 0; + uint8_t hardlen; + uint32_t ip; + char dst[256]; + + status = LibLocateHandle(ByProtocol, &PxeBaseCodeProtocol, + NULL, &nr_handles, &handles); + if (status != EFI_SUCCESS) + return; + + /* Probably want to use IPv4 protocol to decide which handle to use */ + status = uefi_call_wrapper(BS->HandleProtocol, 3, handles[0], + &PxeBaseCodeProtocol, (void **)&bc); + if (status != EFI_SUCCESS) { + Print(L"Failed to lookup PxeBaseCodeProtocol\n"); + } + + mode = bc->Mode; + + /* + * Parse any "before" hardcoded options + */ + parse_dhcp_options(embedded_dhcp_options.dhcp_data, + embedded_dhcp_options.bdhcp_len, 0); + + /* + * Get the DHCP client identifiers (query info 1) + */ + Print(L"Getting cached packet "); + parse_dhcp(&mode->DhcpDiscover.Dhcpv4, pkt_len); + /* + * We don't use flags from the request packet, so + * this is a good time to initialize DHCPMagic... + * Initialize it to 1 meaning we will accept options found; + * in earlier versions of PXELINUX bit 0 was used to indicate + * we have found option 208 with the appropriate magic number; + * we no longer require that, but MAY want to re-introduce + * it in the future for vendor encapsulated options. + */ + *(char *)&DHCPMagic = 1; + + /* + * Get the BOOTP/DHCP packet that brought us file (and an IP + * address). This lives in the DHCPACK packet (query info 2) + */ + parse_dhcp(&mode->DhcpAck.Dhcpv4, pkt_len); + /* + * Save away MAC address (assume this is in query info 2. If this + * turns out to be problematic it might be better getting it from + * the query info 1 packet + */ + hardlen = mode->DhcpAck.Dhcpv4.BootpHwAddrLen; + MAC_len = hardlen > 16 ? 0 : hardlen; + MAC_type = mode->DhcpAck.Dhcpv4.BootpHwType; + memcpy(MAC, mode->DhcpAck.Dhcpv4.BootpHwAddr, MAC_len); + + /* + * Get the boot file and other info. This lives in the CACHED_REPLY + * packet (query info 3) + */ + parse_dhcp(&mode->PxeReply.Dhcpv4, pkt_len); + Print(L"\n"); + + /* + * Parse any "after" hardcoded options + */ + parse_dhcp_options(embedded_dhcp_options.dhcp_data + + embedded_dhcp_options.bdhcp_len, + embedded_dhcp_options.adhcp_len, 0); + + ip = IPInfo.myip; + sprintf(dst, "%u.%u.%u.%u", + ((const uint8_t *)&ip)[0], + ((const uint8_t *)&ip)[1], + ((const uint8_t *)&ip)[2], + ((const uint8_t *)&ip)[3]); + + Print(L"My IP is %a\n", dst); +} diff --git a/pool/shard002/C/0061649_slarrr.c b/pool/shard002/C/0061649_slarrr.c new file mode 100644 index 0000000000000000000000000000000000000000..4db671de136fbff06f9d5e3acd99ddca1f6a3513 --- /dev/null +++ b/pool/shard002/C/0061649_slarrr.c @@ -0,0 +1,162 @@ +#include "clapack.h" + +/* Subroutine */ int slarrr_(integer *n, real *d__, real *e, integer *info) +{ + /* System generated locals */ + integer i__1; + real r__1; + + /* Builtin functions */ + double sqrt(doublereal); + + /* Local variables */ + integer i__; + real eps, tmp, tmp2, rmin, offdig; + extern doublereal slamch_(char *); + real safmin; + logical yesrel; + real smlnum, offdig2; + + +/* -- LAPACK auxiliary routine (version 3.1) -- */ +/* Univ. of Tennessee, Univ. of California Berkeley and NAG Ltd.. */ +/* November 2006 */ + +/* .. Scalar Arguments .. */ +/* .. */ +/* .. Array Arguments .. */ +/* .. */ + + +/* Purpose */ +/* ======= */ + +/* Perform tests to decide whether the symmetric tridiagonal matrix T */ +/* warrants expensive computations which guarantee high relative accuracy */ +/* in the eigenvalues. */ + +/* Arguments */ +/* ========= */ + +/* N (input) INTEGER */ +/* The order of the matrix. N > 0. */ + +/* D (input) REAL array, dimension (N) */ +/* The N diagonal elements of the tridiagonal matrix T. */ + +/* E (input/output) REAL array, dimension (N) */ +/* On entry, the first (N-1) entries contain the subdiagonal */ +/* elements of the tridiagonal matrix T; E(N) is set to ZERO. */ + +/* INFO (output) INTEGER */ +/* INFO = 0(default) : the matrix warrants computations preserving */ +/* relative accuracy. */ +/* INFO = 1 : the matrix warrants computations guaranteeing */ +/* only absolute accuracy. */ + +/* Further Details */ +/* =============== */ + +/* Based on contributions by */ +/* Beresford Parlett, University of California, Berkeley, USA */ +/* Jim Demmel, University of California, Berkeley, USA */ +/* Inderjit Dhillon, University of Texas, Austin, USA */ +/* Osni Marques, LBNL/NERSC, USA */ +/* Christof Voemel, University of California, Berkeley, USA */ + +/* ===================================================================== */ + +/* .. Parameters .. */ +/* .. */ +/* .. Local Scalars .. */ +/* .. */ +/* .. External Functions .. */ +/* .. */ +/* .. Intrinsic Functions .. */ +/* .. */ +/* .. Executable Statements .. */ + +/* As a default, do NOT go for relative-accuracy preserving computations. */ + /* Parameter adjustments */ + --e; + --d__; + + /* Function Body */ + *info = 1; + safmin = slamch_("Safe minimum"); + eps = slamch_("Precision"); + smlnum = safmin / eps; + rmin = sqrt(smlnum); +/* Tests for relative accuracy */ + +/* Test for scaled diagonal dominance */ +/* Scale the diagonal entries to one and check whether the sum of the */ +/* off-diagonals is less than one */ + +/* The sdd relative error bounds have a 1/(1- 2*x) factor in them, */ +/* x = max(OFFDIG + OFFDIG2), so when x is close to 1/2, no relative */ +/* accuracy is promised. In the notation of the code fragment below, */ +/* 1/(1 - (OFFDIG + OFFDIG2)) is the condition number. */ +/* We don't think it is worth going into "sdd mode" unless the relative */ +/* condition number is reasonable, not 1/macheps. */ +/* The threshold should be compatible with other thresholds used in the */ +/* code. We set OFFDIG + OFFDIG2 <= .999 =: RELCOND, it corresponds */ +/* to losing at most 3 decimal digits: 1 / (1 - (OFFDIG + OFFDIG2)) <= 1000 */ +/* instead of the current OFFDIG + OFFDIG2 < 1 */ + + yesrel = TRUE_; + offdig = 0.f; + tmp = sqrt((dabs(d__[1]))); + if (tmp < rmin) { + yesrel = FALSE_; + } + if (! yesrel) { + goto L11; + } + i__1 = *n; + for (i__ = 2; i__ <= i__1; ++i__) { + tmp2 = sqrt((r__1 = d__[i__], dabs(r__1))); + if (tmp2 < rmin) { + yesrel = FALSE_; + } + if (! yesrel) { + goto L11; + } + offdig2 = (r__1 = e[i__ - 1], dabs(r__1)) / (tmp * tmp2); + if (offdig + offdig2 >= .999f) { + yesrel = FALSE_; + } + if (! yesrel) { + goto L11; + } + tmp = tmp2; + offdig = offdig2; +/* L10: */ + } +L11: + if (yesrel) { + *info = 0; + return 0; + } else { + } + + +/* *** MORE TO BE IMPLEMENTED *** */ + + +/* Test if the lower bidiagonal matrix L from T = L D L^T */ +/* (zero shift facto) is well conditioned */ + + +/* Test if the upper bidiagonal matrix U from T = U D U^T */ +/* (zero shift facto) is well conditioned. */ +/* In this case, the matrix needs to be flipped and, at the end */ +/* of the eigenvector computation, the flip needs to be applied */ +/* to the computed eigenvectors (and the support) */ + + + return 0; + +/* END OF SLARRR */ + +} /* slarrr_ */ diff --git a/pool/shard002/C/0061654_packet-credssp-template.c b/pool/shard002/C/0061654_packet-credssp-template.c new file mode 100644 index 0000000000000000000000000000000000000000..28bb9e4c3e7ffb47bc193b2094a9c8867620f23f --- /dev/null +++ b/pool/shard002/C/0061654_packet-credssp-template.c @@ -0,0 +1,176 @@ +/* packet-credssp.c + * Routines for CredSSP (Credential Security Support Provider) packet dissection + * Graeme Lunt 2011 + * + * Wireshark - Network traffic analyzer + * By Gerald Combs + * Copyright 1998 Gerald Combs + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +#include "config.h" + +#include +#include +#include +#include + +#include "packet-ber.h" +#include "packet-credssp.h" + + +#define PNAME "Credential Security Support Provider" +#define PSNAME "CredSSP" +#define PFNAME "credssp" + +#define TS_PASSWORD_CREDS 1 +#define TS_SMARTCARD_CREDS 2 +static gint creds_type; + +static gint exported_pdu_tap = -1; + +/* Initialize the protocol and registered fields */ +static int proto_credssp = -1; + +/* List of dissectors to call for negoToken data */ +static heur_dissector_list_t credssp_heur_subdissector_list; + +static int hf_credssp_TSPasswordCreds = -1; /* TSPasswordCreds */ +static int hf_credssp_TSSmartCardCreds = -1; /* TSSmartCardCreds */ +static int hf_credssp_TSCredentials = -1; /* TSCredentials */ +#include "packet-credssp-hf.c" + +/* Initialize the subtree pointers */ +static gint ett_credssp = -1; +#include "packet-credssp-ett.c" + +#include "packet-credssp-fn.c" + +/* +* Dissect CredSSP PDUs +*/ +static int +dissect_credssp(tvbuff_t *tvb, packet_info *pinfo, proto_tree *parent_tree, void *data) +{ + proto_item *item=NULL; + proto_tree *tree=NULL; + + if(parent_tree){ + item = proto_tree_add_item(parent_tree, proto_credssp, tvb, 0, -1, ENC_NA); + tree = proto_item_add_subtree(item, ett_credssp); + } + col_set_str(pinfo->cinfo, COL_PROTOCOL, "CredSSP"); + col_clear(pinfo->cinfo, COL_INFO); + + creds_type = -1; + return dissect_TSRequest_PDU(tvb, pinfo, tree, data); +} + +static gboolean +dissect_credssp_heur(tvbuff_t *tvb, packet_info *pinfo, proto_tree *parent_tree, void *data _U_) +{ + asn1_ctx_t asn1_ctx; + int offset = 0; + gint8 ber_class; + gboolean pc; + gint32 tag; + guint32 length; + gint8 ver; + + asn1_ctx_init(&asn1_ctx, ASN1_ENC_BER, TRUE, pinfo); + + /* Look for SEQUENCE, CONTEXT 0, and INTEGER 2 */ + if(tvb_captured_length(tvb) > 7) { + offset = get_ber_identifier(tvb, offset, &ber_class, &pc, &tag); + if((ber_class == BER_CLASS_UNI) && (tag == BER_UNI_TAG_SEQUENCE) && (pc == TRUE)) { + offset = get_ber_length(tvb, offset, NULL, NULL); + offset = get_ber_identifier(tvb, offset, &ber_class, &pc, &tag); + if((ber_class == BER_CLASS_CON) && (tag == 0)) { + offset = get_ber_length(tvb, offset, NULL, NULL); + offset = get_ber_identifier(tvb, offset, &ber_class, &pc, &tag); + if((ber_class == BER_CLASS_UNI) && (tag == BER_UNI_TAG_INTEGER)) { + offset = get_ber_length(tvb, offset, &length, NULL); + ver = tvb_get_guint8(tvb, offset); + if((length == 1) && ((ver == 2) || (ver == 3))) { + if (have_tap_listener(exported_pdu_tap)) { + exp_pdu_data_t *exp_pdu_data = export_pdu_create_common_tags(pinfo, "credssp", EXP_PDU_TAG_PROTO_NAME); + + exp_pdu_data->tvb_captured_length = tvb_captured_length(tvb); + exp_pdu_data->tvb_reported_length = tvb_reported_length(tvb); + exp_pdu_data->pdu_tvb = tvb; + + tap_queue_packet(exported_pdu_tap, pinfo, exp_pdu_data); + } + dissect_credssp(tvb, pinfo, parent_tree, NULL); + return TRUE; + } + } + } + } + } + return FALSE; +} + + +/*--- proto_register_credssp -------------------------------------------*/ +void proto_register_credssp(void) { + + /* List of fields */ + static hf_register_info hf[] = + { + { &hf_credssp_TSPasswordCreds, + { "TSPasswordCreds", "credssp.TSPasswordCreds", + FT_NONE, BASE_NONE, NULL, 0, + NULL, HFILL }}, + { &hf_credssp_TSSmartCardCreds, + { "TSSmartCardCreds", "credssp.TSSmartCardCreds", + FT_NONE, BASE_NONE, NULL, 0, + NULL, HFILL }}, + { &hf_credssp_TSCredentials, + { "TSCredentials", "credssp.TSCredentials", + FT_NONE, BASE_NONE, NULL, 0, + NULL, HFILL }}, +#include "packet-credssp-hfarr.c" + }; + + /* List of subtrees */ + static gint *ett[] = { + &ett_credssp, +#include "packet-credssp-ettarr.c" + }; + + + /* Register protocol */ + proto_credssp = proto_register_protocol(PNAME, PSNAME, PFNAME); + register_dissector("credssp", dissect_credssp, proto_credssp); + + /* Register fields and subtrees */ + proto_register_field_array(proto_credssp, hf, array_length(hf)); + proto_register_subtree_array(ett, array_length(ett)); + + /* heuristic dissectors for any premable e.g. CredSSP before RDP */ + credssp_heur_subdissector_list = register_heur_dissector_list("credssp", proto_credssp); + +} + + +/*--- proto_reg_handoff_credssp --- */ +void proto_reg_handoff_credssp(void) { + + heur_dissector_add("ssl", dissect_credssp_heur, "CredSSP over SSL", "credssp_ssl", proto_credssp, HEURISTIC_ENABLE); + exported_pdu_tap = find_tap_id(EXPORT_PDU_TAP_NAME_LAYER_7); +} + diff --git a/pool/shard002/C/0061655_join3.c b/pool/shard002/C/0061655_join3.c new file mode 100644 index 0000000000000000000000000000000000000000..14122e7468592c9f658b4bca5a7e45767f1ab3bf --- /dev/null +++ b/pool/shard002/C/0061655_join3.c @@ -0,0 +1,75 @@ +/* + * Test for pthread_join() returning return value from threads. + * + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2005 Pthreads-win32 contributors + * + * Contact Email: rpj@callisto.canberra.edu.au + * + * The current list of contributors is contained + * in the file CONTRIBUTORS included with the source + * code distribution. The list can also be seen at the + * following World Wide Web location: + * http://sources.redhat.com/pthreads-win32/contributors.html + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library in the file COPYING.LIB; + * if not, write to the Free Software Foundation, Inc., + * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA + * + * -------------------------------------------------------------------------- + * + * Depends on API functions: pthread_create(). + */ + +#include "test.h" + +void * +func(void * arg) +{ + sched_yield(); + return arg; +} + +int +main(int argc, char * argv[]) +{ + pthread_t id[4]; + int i; + intptr_t result = 0; + + /* Create a few threads and then exit. */ + for (i = 0; i < 4; i++) + { + assert(pthread_create(&id[i], NULL, func, UINT2PTR(i)) == 0); + } + + /* + * Let threads exit before we join them. + * We should still retrieve the exit code for the threads. + */ + Sleep(1000); + + for (i = 0; i < 4; i++) + { + assert(pthread_join(id[i], (void **) &result) == 0); + assert((int) result == i); + } + + /* Success. */ + return 0; +} diff --git a/pool/shard002/C/0061670_parser.c b/pool/shard002/C/0061670_parser.c new file mode 100644 index 0000000000000000000000000000000000000000..1a94d5597fc210a487d66238a0b31df56e9992d6 --- /dev/null +++ b/pool/shard002/C/0061670_parser.c @@ -0,0 +1,81 @@ +/* + * balde: A microframework for C based on GLib and bad intentions. + * Copyright (C) 2013-2017 Rafael G. Martins + * + * This program can be distributed under the terms of the LGPL-2 License. + * See the file COPYING. + */ + +#ifdef HAVE_CONFIG_H +#include +#endif /* HAVE_CONFIG_H */ + +#include +#include "parser.h" + + +void +balde_unescape_single_quoted_strings(gchar** str) +{ + GRegex *re_escaped_str = g_regex_new("\\\\'", 0, 0, NULL); + gchar *escaped_str = g_regex_replace_literal(re_escaped_str, *str, -1, 0, + "'", 0, NULL); + g_free(*str); + *str = escaped_str; + g_regex_unref(re_escaped_str); +} + + +void +balde_template_free_blocks(GList *blocks) +{ + balde_template_block_t *block; + balde_template_import_block_t *imblock; + balde_template_include_block_t *iblock; + balde_template_if_block_t *ifblock; + balde_template_content_block_t *cblock; + balde_template_print_var_block_t *vblock; + balde_template_print_fn_call_block_t *fblock; + balde_template_fn_arg_t *arg; + for(GList *tmp = blocks; tmp != NULL; tmp = g_list_next(tmp)) { + block = tmp->data; + switch(block->type) { + case BALDE_TEMPLATE_IMPORT_BLOCK: + imblock = block->block; + g_free(imblock->import); + break; + case BALDE_TEMPLATE_INCLUDE_BLOCK: + iblock = block->block; + g_free(iblock->include); + break; + case BALDE_TEMPLATE_IF_BLOCK: + ifblock = block->block; + g_free(ifblock->if_var); + break; + case BALDE_TEMPLATE_ELSE_BLOCK: + case BALDE_TEMPLATE_IF_END_BLOCK: + break; + case BALDE_TEMPLATE_CONTENT_BLOCK: + cblock = block->block; + g_free(cblock->content); + break; + case BALDE_TEMPLATE_PRINT_VAR_BLOCK: + vblock = block->block; + g_free(vblock->variable); + break; + case BALDE_TEMPLATE_PRINT_FN_CALL_BLOCK: + fblock = block->block; + g_free(fblock->name); + for(GSList *tmp2 = fblock->args; tmp2 != NULL; tmp2 = g_slist_next(tmp2)) { + arg = tmp2->data; + g_free(arg->content); + g_free(arg); + } + g_slist_free(fblock->args); + break; + } + g_free(block->block); + g_free(block); + } + g_list_free(blocks); +} diff --git a/pool/shard002/C/0061676_nv44.c b/pool/shard002/C/0061676_nv44.c new file mode 100644 index 0000000000000000000000000000000000000000..cc56271db5643695add777bad34059c27d7f9b49 --- /dev/null +++ b/pool/shard002/C/0061676_nv44.c @@ -0,0 +1,54 @@ +/* + * 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 "priv.h" + +void +nv44_mc_init(struct nvkm_mc *mc) +{ + struct nvkm_device *device = mc->subdev.device; + u32 tmp = nvkm_rd32(device, 0x10020c); + + nvkm_wr32(device, 0x000200, 0xffffffff); /* everything enabled */ + + nvkm_wr32(device, 0x001700, tmp); + nvkm_wr32(device, 0x001704, 0); + nvkm_wr32(device, 0x001708, 0); + nvkm_wr32(device, 0x00170c, tmp); +} + +static const struct nvkm_mc_func +nv44_mc = { + .init = nv44_mc_init, + .intr = nv17_mc_intr, + .intr_unarm = nv04_mc_intr_unarm, + .intr_rearm = nv04_mc_intr_rearm, + .intr_mask = nv04_mc_intr_mask, + .reset = nv17_mc_reset, +}; + +int +nv44_mc_new(struct nvkm_device *device, int index, struct nvkm_mc **pmc) +{ + return nvkm_mc_new_(&nv44_mc, device, index, pmc); +} diff --git a/pool/shard002/C/0061683_dump_tlb.c b/pool/shard002/C/0061683_dump_tlb.c new file mode 100644 index 0000000000000000000000000000000000000000..594df1a05ecc62847724c3e6fb69596ea1d27307 --- /dev/null +++ b/pool/shard002/C/0061683_dump_tlb.c @@ -0,0 +1,216 @@ +/* + * Dump R4x00 TLB for debugging purposes. + * + * Copyright (C) 1994, 1995 by Waldorf Electronics, written by Ralf Baechle. + * Copyright (C) 1999 by Silicon Graphics, Inc. + */ +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +static inline const char *msk2str(unsigned int mask) +{ + switch (mask) { + case PM_4K: return "4kb"; + case PM_16K: return "16kb"; + case PM_64K: return "64kb"; + case PM_256K: return "256kb"; +#ifndef CONFIG_CPU_VR41XX + case PM_1M: return "1Mb"; + case PM_4M: return "4Mb"; + case PM_16M: return "16Mb"; + case PM_64M: return "64Mb"; + case PM_256M: return "256Mb"; +#endif + } + + return "unknown"; +} + +#define BARRIER() \ + __asm__ __volatile__( \ + ".set\tnoreorder\n\t" \ + "nop;nop;nop;nop;nop;nop;nop\n\t" \ + ".set\treorder"); + +void dump_tlb(int first, int last) +{ + unsigned long s_entryhi, entryhi, entrylo0, entrylo1, asid; + unsigned int s_index, pagemask, c0, c1, i; + + s_entryhi = read_c0_entryhi(); + s_index = read_c0_index(); + asid = s_entryhi & 0xff; + + for (i = first; i <= last; i++) { + write_c0_index(i); + BARRIER(); + tlb_read(); + BARRIER(); + pagemask = read_c0_pagemask(); + entryhi = read_c0_entryhi(); + entrylo0 = read_c0_entrylo0(); + entrylo1 = read_c0_entrylo1(); + + /* Unused entries have a virtual address of CKSEG0. */ + if ((entryhi & ~0x1ffffUL) != CKSEG0 + && (entryhi & 0xff) == asid) { + /* + * Only print entries in use + */ + printk("Index: %2d pgmask=%s ", i, msk2str(pagemask)); + + c0 = (entrylo0 >> 3) & 7; + c1 = (entrylo1 >> 3) & 7; + + printk("va=%011lx asid=%02lx\n", + (entryhi & ~0x1fffUL), + entryhi & 0xff); + printk("\t[pa=%011lx c=%d d=%d v=%d g=%ld] ", + (entrylo0 << 6) & PAGE_MASK, c0, + (entrylo0 & 4) ? 1 : 0, + (entrylo0 & 2) ? 1 : 0, + (entrylo0 & 1)); + printk("[pa=%011lx c=%d d=%d v=%d g=%ld]\n", + (entrylo1 << 6) & PAGE_MASK, c1, + (entrylo1 & 4) ? 1 : 0, + (entrylo1 & 2) ? 1 : 0, + (entrylo1 & 1)); + } + } + printk("\n"); + + write_c0_entryhi(s_entryhi); + write_c0_index(s_index); +} + +void dump_tlb_all(void) +{ + dump_tlb(0, current_cpu_data.tlbsize - 1); +} + +void dump_tlb_wired(void) +{ + int wired; + + wired = read_c0_wired(); + printk("Wired: %d", wired); + dump_tlb(0, read_c0_wired()); +} + +void dump_tlb_addr(unsigned long addr) +{ + unsigned int flags, oldpid; + int index; + + local_irq_save(flags); + oldpid = read_c0_entryhi() & 0xff; + BARRIER(); + write_c0_entryhi((addr & PAGE_MASK) | oldpid); + BARRIER(); + tlb_probe(); + BARRIER(); + index = read_c0_index(); + write_c0_entryhi(oldpid); + local_irq_restore(flags); + + if (index < 0) { + printk("No entry for address 0x%08lx in TLB\n", addr); + return; + } + + printk("Entry %d maps address 0x%08lx\n", index, addr); + dump_tlb(index, index); +} + +void dump_tlb_nonwired(void) +{ + dump_tlb(read_c0_wired(), current_cpu_data.tlbsize - 1); +} + +void dump_list_process(struct task_struct *t, void *address) +{ + pgd_t *page_dir, *pgd; + pud_t *pud; + pmd_t *pmd; + pte_t *pte, page; + unsigned long addr, val; + + addr = (unsigned long) address; + + printk("Addr == %08lx\n", addr); + printk("tasks->mm.pgd == %08lx\n", (unsigned long) t->mm->pgd); + + page_dir = pgd_offset(t->mm, 0UL); + printk("page_dir == %016lx\n", (unsigned long) page_dir); + + pgd = pgd_offset(t->mm, addr); + printk("pgd == %016lx\n", (unsigned long) pgd); + + pud = pud_offset(pgd, addr); + printk("pud == %016lx\n", (unsigned long) pud); + + pmd = pmd_offset(pud, addr); + printk("pmd == %016lx\n", (unsigned long) pmd); + + pte = pte_offset(pmd, addr); + printk("pte == %016lx\n", (unsigned long) pte); + + page = *pte; + printk("page == %08lx\n", pte_val(page)); + + val = pte_val(page); + if (val & _PAGE_PRESENT) printk("present "); + if (val & _PAGE_READ) printk("read "); + if (val & _PAGE_WRITE) printk("write "); + if (val & _PAGE_ACCESSED) printk("accessed "); + if (val & _PAGE_MODIFIED) printk("modified "); + if (val & _PAGE_R4KBUG) printk("r4kbug "); + if (val & _PAGE_GLOBAL) printk("global "); + if (val & _PAGE_VALID) printk("valid "); + printk("\n"); +} + +void dump_list_current(void *address) +{ + dump_list_process(current, address); +} + +unsigned long vtop(void *address) +{ + pgd_t *pgd; + pud_t *pud; + pmd_t *pmd; + pte_t *pte; + unsigned long addr, paddr; + + addr = (unsigned long) address; + pgd = pgd_offset(current->mm, addr); + pud = pud_offset(pgd, addr); + pmd = pmd_offset(pud, addr); + pte = pte_offset(pmd, addr); + paddr = (CKSEG1 | (unsigned int) pte_val(*pte)) & PAGE_MASK; + paddr |= (addr & ~PAGE_MASK); + + return paddr; +} + +void dump16(unsigned long *p) +{ + int i; + + for (i = 0; i < 8; i++) { + printk("*%08lx == %08lx, ", (unsigned long)p, *p); + p++; + printk("*%08lx == %08lx\n", (unsigned long)p, *p); + p++; + } +} diff --git a/pool/shard002/C/0061684_compress.c b/pool/shard002/C/0061684_compress.c new file mode 100644 index 0000000000000000000000000000000000000000..3fdccaea6865b9b0c73c7b43bbb6a37a7e7de793 --- /dev/null +++ b/pool/shard002/C/0061684_compress.c @@ -0,0 +1,68 @@ +/* compress.c -- compress a memory buffer + * Copyright (C) 1995-2002 Jean-loup Gailly. + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +/* @(#) $Id: compress.c 700 2006-02-25 22:49:40Z pepsiman $ */ + +#include "zlib.h" + +/* =========================================================================== + Compresses the source buffer into the destination buffer. The level + parameter has the same meaning as in deflateInit. sourceLen is the byte + length of the source buffer. Upon entry, destLen is the total size of the + destination buffer, which must be at least 0.1% larger than sourceLen plus + 12 bytes. Upon exit, destLen is the actual size of the compressed buffer. + + compress2 returns Z_OK if success, Z_MEM_ERROR if there was not enough + memory, Z_BUF_ERROR if there was not enough room in the output buffer, + Z_STREAM_ERROR if the level parameter is invalid. +*/ +int ZEXPORT compress2 (dest, destLen, source, sourceLen, level) + Bytef *dest; + uLongf *destLen; + const Bytef *source; + uLong sourceLen; + int level; +{ + z_stream stream; + int err; + + stream.next_in = (Bytef*)source; + stream.avail_in = (uInt)sourceLen; +#ifdef MAXSEG_64K + /* Check for source > 64K on 16-bit machine: */ + if ((uLong)stream.avail_in != sourceLen) return Z_BUF_ERROR; +#endif + stream.next_out = dest; + stream.avail_out = (uInt)*destLen; + if ((uLong)stream.avail_out != *destLen) return Z_BUF_ERROR; + + stream.zalloc = (alloc_func)0; + stream.zfree = (free_func)0; + stream.opaque = (voidpf)0; + + err = deflateInit(&stream, level); + if (err != Z_OK) return err; + + err = deflate(&stream, Z_FINISH); + if (err != Z_STREAM_END) { + deflateEnd(&stream); + return err == Z_OK ? Z_BUF_ERROR : err; + } + *destLen = stream.total_out; + + err = deflateEnd(&stream); + return err; +} + +/* =========================================================================== + */ +int ZEXPORT compress (dest, destLen, source, sourceLen) + Bytef *dest; + uLongf *destLen; + const Bytef *source; + uLong sourceLen; +{ + return compress2(dest, destLen, source, sourceLen, Z_DEFAULT_COMPRESSION); +} diff --git a/pool/shard002/C/0061696_sss_storage_server.c b/pool/shard002/C/0061696_sss_storage_server.c new file mode 100644 index 0000000000000000000000000000000000000000..6e2db0db3b0c23535b1fd522cb7585a3bb6856ba --- /dev/null +++ b/pool/shard002/C/0061696_sss_storage_server.c @@ -0,0 +1,134 @@ +/**************************************************************************** + * + * Copyright 2018 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. + * + ****************************************************************************/ + +/// +/// This sample provides the way to create cloud sample +#include +#include +#include +#include +#include +#include +#include +#include "cacommon.h" +#include "cacommonutil.h" +#include "ocstack.h" +#include "ocpayload.h" +#include "logger.h" +#include "mbedtls/ssl_ciphersuites.h" + +#include "sss_storage_server.h" + +#include "utils/things_malloc.h" +#include "logging/things_logger.h" + +#include "mbedtls/sss_storage.h" + +#define SSSFILE "/sss/00014280" + +int g_secureStorageType; + +int getSecureStorageType(void) +{ + return g_secureStorageType; +} + +void setSecureStorageType(int type) +{ + g_secureStorageType = type; +} + +//#define LOGSECURE(data) printf("%s:%d|%s() SSS[%s] data:%d\n",__FILE__,__LINE__,__func__,getSecureStorageType() == 0 ? "PERSISTENT" : "MEMORY", data) +#define LOGSECURE(data) + +/** Persistent storage open handler.*/ +FILE *secure_fopen(const char *path, const char *mode) +{ + LOGSECURE(0); + if (getSecureStorageType() == 0) + return sss_open(path, mode); + + return sss_open_mem(path, mode); +} + +/** Persistent storage read handler.*/ +size_t secure_fread(void *ptr, size_t size, size_t nmemb, FILE *stream) +{ + LOGSECURE(nmemb); + size_t count = 0; + + if (getSecureStorageType() == 0) { + count = sss_read(ptr, size, nmemb, stream); + LOGSECURE(count); + return count; + } + count = sss_read_mem(ptr, size, nmemb, stream); + LOGSECURE(count); + return count; +} + +/** Persistent storage write handler.*/ +size_t secure_fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream) +{ + LOGSECURE(nmemb); + if (getSecureStorageType() == 0) + return sss_write(ptr, size, nmemb, stream); + + return sss_write_mem(ptr, size, nmemb, stream); +} + +void secure_sync(void) +{ + LOGSECURE(0); + sss_sync(); +} + +/** Persistent storage close handler.*/ +int secure_fclose(FILE *fp) +{ + return sss_close(fp); +} +/** Persistent storage unlink handler.*/ +int secure_funlink(const char *path) +{ + return sss_unlink(path); +} + +/** Persistent secure_remove handler.*/ +extern int secure_remove(const char *path) +{ + char *fullpath; + int ret = -1; + + fullpath = get_fullpath(SSSFILE); + + usleep(500 * 1000); + + if (fullpath) { + ret = unlink(fullpath); + if (ret < 0) { + printf("unlink fail [%d]", ret); + } + free(fullpath); + printf("File [%s] Clear Success", SSSFILE); + } else { + printf("delete fail"); + } + + return ret; +} diff --git a/pool/shard002/C/0061697_addnbrs.c b/pool/shard002/C/0061697_addnbrs.c new file mode 100644 index 0000000000000000000000000000000000000000..d8ec3637c2423bc794c423f0662c02b0d51b4e31 --- /dev/null +++ b/pool/shard002/C/0061697_addnbrs.c @@ -0,0 +1,59 @@ +/* +** addnbrs.c for Bistromathique in /home/schmou_a/Bistromathique sans warnings +** +** Made by adrien schmouker +** Login +** +** Started on Sun Nov 9 20:23:51 2014 adrien schmouker +** Last update Sun Nov 9 20:23:52 2014 adrien schmouker +*/ + +#include +#include "calc.h" + +t_nb *init_add_nbs(t_nb *nb1, t_nb *nb2) +{ + t_nb *nnb2; + int i; + + if (nb1 == NULL || nb2 == NULL) + return (NULL); + nnb2 = malloc(sizeof(t_nb)); + if (nnb2 == NULL) + return (NULL); + nnb2->nb = malloc(nb1->len + 1); + nnb2->len = nb1->len; + nnb2->sign = nb2->sign; + nb1->nb = my_revnbr(nb1->nb, nb1->len); + nb2->nb = my_revnbr(nb2->nb, nb2->len); + i = -1; + while (++i < nb2->len) + nnb2->nb[i] = nb2->nb[i]; + i--; + while (++i < nnb2->len) + nnb2->nb[i] = 0; + nnb2->nb[i] = 255; + nb2 = nnb2; + return (nnb2); +} + +void my_test_nbrs(t_nb *nb1, t_nb *nb2) +{ + int i; + + i = -1; + while (nb1->nb[++i] != '\0') + { + nb1->nb[i] -= 48; + nb2->nb[i] -= 48; + } +} + +void my_disp_test(t_nb *nb) +{ + int i; + + i = -1; + while (++i < nb->len) + my_putchar(nb->nb[i] + 48); +} diff --git a/pool/shard002/C/0061705_convert.c b/pool/shard002/C/0061705_convert.c new file mode 100644 index 0000000000000000000000000000000000000000..c34d5f20b10f940cea04c92d1c9508510519d484 --- /dev/null +++ b/pool/shard002/C/0061705_convert.c @@ -0,0 +1,228 @@ +#include +#include +#include +#include +#include + +#include "romfuns.h" +struct romboot_s support_socs[]={ + { + .cpu="m1", + .write=m1_write, + }, + { + .cpu="m2", + .write=m1_write, + }, + { + .cpu="m3", + .write=m3_write, + .write_ex=m3_write_ex, + }, + { + .cpu="a3", + .write=a3_write, + }, + { + .cpu="m6", + .write=m6_write, + .write_ex=m6_write_ex, + }, + { + .cpu="m6tv", + .write=m6_write, + .write_ex=m6_write_ex, + }, + { + .cpu="m8", + .write=m8_write, + .write_ex=m8_write_ex, + }, + { + .cpu=NULL, + .write=NULL, + } +}; +#define MAX_SOCS (sizeof(support_socs)/sizeof(support_socs[0])) +static struct option longopts[] = +{ + { "spl", 1, NULL, 's' }, + { "input", 1, NULL, 'i' }, + { "output", 1, NULL, 'o' }, + { "soc", 1, NULL, 'c' }, + { "help", 1, NULL, 'h' }, + /*{ "M1", 0, &cpu, 0 }, + { "M2", 0, &cpu, 1 }, + { "A3", 0, &cpu, 2 },*/ + [MAX_SOCS-1+5]= + { 0, 0, 0, 0 }, +}; + + +#define for_each_soc(entry) for(entry=&support_socs[0]; \ + entry->cpu;entry++) +static void printUsage(char * program) +{ + struct romboot_s *entry; + fprintf(stdout ,"%s usage:\t%s -i input <-s spl> -o output <-soc |-\n" + ,program,program); + fprintf(stdout,"\t available cpuid: "); + for_each_soc(entry) + { + fprintf(stdout,"%s ",entry->cpu); + } + fprintf(stdout,"\n"); +} +#define ERROR_DUPLICATE_PARAMETER -1 +int main(int argc,char * argv[]) +{ + + FILE * fp_in=NULL; + FILE * fp_out=NULL; + FILE * fp_spl=NULL; + char * spl_file=NULL; + char * in_file=NULL; + char * out_file=NULL; + struct romboot_s *entry; + int cpu = -1; + int ret=1; + int i=0; + int c; + for_each_soc(entry) + { + longopts[i+5].name=entry->cpu; + longopts[i+5].has_arg=0; + longopts[i+5].flag=&cpu; + longopts[i+5].val=i; + i++; + } + entry=NULL; + + while ((c = getopt_long(argc, argv, ":s:i:o:c:h:", longopts, NULL)) != -1) + { + switch(c) + { + case 's': + if(spl_file) + { + ret=ERROR_DUPLICATE_PARAMETER; + goto exit_prog; + } + spl_file=optarg; + if(fp_in&&strcmp(in_file,spl_file)==0) + { + fp_spl=fp_in; + }else{ + fp_spl=fopen(optarg,"rb"); + } + + break; + case 'i': + if(in_file) + { + ret=ERROR_DUPLICATE_PARAMETER-1; + goto exit_prog; + } + in_file=optarg; + if(fp_spl&&strcmp(in_file,spl_file)==0) + { + fp_in=fp_spl; + }else{ + fp_in=fopen(optarg,"rb"); + } + + + break; + case 'o': + if(out_file) + { + ret=ERROR_DUPLICATE_PARAMETER-2; + goto exit_prog; + } + out_file=optarg; + fp_out=fopen(optarg,"wb"); + break; + case 'c': + if(cpu!=-1) + { + ret=ERROR_DUPLICATE_PARAMETER-3; + goto exit_prog; + } + if(!optarg) + goto exit_prog; + for_each_soc(entry) + { + if(strcasecmp(entry->cpu,optarg)==0) + break; + } + if(entry->cpu==NULL) + entry=NULL; + break; + case 'h': + printUsage(argv[0]); + goto exit_prog; + } + } + ret=ERROR_DUPLICATE_PARAMETER-4; + if(cpu==-1 && entry==NULL) + { + goto exit_prog; + } +// printf("%d,%d,%d,%d\n",(cpu<-1),(-1>(int)(MAX_SOCS-2)),cpu,MAX_SOCS-2); + if(cpu<-1||cpu>(int)(MAX_SOCS-2)) + goto exit_prog; + + if(entry==NULL) + entry=&support_socs[cpu]; + + if(fp_spl==NULL && fp_in==NULL) + { + + goto exit_prog; + } + if(fp_spl==NULL || fp_in==NULL) + { + if(fp_spl) + fp_in=fp_spl; + else + fp_spl=fp_in; + + } + + if(fp_out==NULL) + { + goto exit_prog; + } + + ret=entry->write(fp_spl,fp_in,fp_out); + +/* + +*/ + if(ret) + fprintf(stderr,"File I/O error\n"); +exit_prog: +// printf("%d\n",ret); + if(fp_spl) + { + fclose(fp_spl); + }else{ + fprintf(stderr,"File open error %s",spl_file?spl_file:in_file); + } + if(fp_in) + { + if(fp_in!=fp_spl) + fclose(fp_in); + }else{ + fprintf(stderr,"File open error A %s",in_file?in_file:spl_file); + } + if(fp_out) + { + fclose(fp_out); + }else{ + fprintf(stderr,"File open error %s",out_file); + } + if(ret) + printUsage(argv[0]); + return ret; +} diff --git a/pool/shard002/C/0061708_exception.c b/pool/shard002/C/0061708_exception.c new file mode 100644 index 0000000000000000000000000000000000000000..b872a55a8ac6377618b9323b4e8a2d6cf94e7332 --- /dev/null +++ b/pool/shard002/C/0061708_exception.c @@ -0,0 +1,210 @@ +/* + * This file is part of the libpayload project. + * + * Copyright 2013 Google Inc. + * + * 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 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. + */ + +#include +#include +#include +#include +#include +#include +#include +#include + +uint8_t exception_stack[0x200] __attribute__((aligned(16))); + +static const char *exception_names[NUM_EXC_VIDS] = { + [EXC_VID_CUR_SP_EL0_SYNC] = "_sync_sp_el0", + [EXC_VID_CUR_SP_EL0_IRQ] = "_irq_sp_el0", + [EXC_VID_CUR_SP_EL0_FIRQ] = "_fiq_sp_el0", + [EXC_VID_CUR_SP_EL0_SERR] = "_serror_sp_el0", + [EXC_VID_CUR_SP_ELX_SYNC] = "_sync_sp_el3", + [EXC_VID_CUR_SP_ELX_IRQ] = "_irq_sp_el3", + [EXC_VID_CUR_SP_ELX_FIQ] = "_fiq_sp_el3", + [EXC_VID_CUR_SP_ELX_SERR] = "_serror_sp_el3", + [EXC_VID_LOW64_SYNC] = "_sync_elx_64", + [EXC_VID_LOW64_IRQ] = "_irq_elx_64", + [EXC_VID_LOW64_FIQ] = "_fiq_elx_64", + [EXC_VID_LOW64_SERR] = "_serror_elx_64", + [EXC_VID_LOW32_SYNC] = "_sync_elx_32", + [EXC_VID_LOW32_IRQ] = "_irq_elx_32", + [EXC_VID_LOW32_FIQ] = "_fiq_elx_32", + [EXC_VID_LOW32_SERR] = "_serror_elx_32" +}; + +static void print_regs(struct exc_state *exc_state) +{ + int i; + struct elx_state *elx = &exc_state->elx; + struct regs *regs = &exc_state->regs; + + uint64_t elx_esr = raw_read_esr_current(); + uint64_t elx_far = raw_read_far_current(); + + printk(BIOS_DEBUG, "ELR = 0x%016llx\n", elx->elr); + printk(BIOS_DEBUG, "ESR = 0x%016llx\n", elx_esr); + printk(BIOS_DEBUG, "SPSR = 0x%08llx\n", elx->spsr); + printk(BIOS_DEBUG, "FAR = 0x%016llx\n", elx_far); + printk(BIOS_DEBUG, "SP = 0x%016llx\n", regs->sp); + for (i = X0_INDEX; i < XMAX_INDEX; i++) + printk(BIOS_DEBUG, "X%02d = 0x%016llx\n", i, regs->x[i]); +} + + +static struct exception_handler *handlers[NUM_EXC_VIDS]; + + +int exception_handler_register(uint64_t vid, struct exception_handler *h) +{ + if (vid >= NUM_EXC_VIDS) + return -1; + + /* Just place at head of queue. */ + h->next = handlers[vid]; + store_release(&handlers[vid], h); + + return 0; +} + +int exception_handler_unregister(uint64_t vid, struct exception_handler *h) +{ + struct exception_handler *cur; + struct exception_handler **prev; + + if (vid >= NUM_EXC_VIDS) + return -1; + + prev = &handlers[vid]; + + for (cur = handlers[vid]; cur != NULL; cur = cur->next) { + if (cur != h) + continue; + /* Update previous pointer. */ + store_release(prev, cur->next); + return 0; + } + + /* Not found */ + return -1; +} + +static void print_exception_info(struct exc_state *state, uint64_t idx) +{ + if (idx < NUM_EXC_VIDS) + printk(BIOS_DEBUG, "exception %s\n", exception_names[idx]); + + print_regs(state); +} + +static void print_exception_and_die(struct exc_state *state, uint64_t idx) +{ + print_exception_info(state, idx); + die("exception death"); +} + + +static int handle_exception(struct exc_state *state, uint64_t idx) +{ + int ret = EXC_RET_ABORT; + + struct exception_handler *h; + + for (h = handlers[idx]; h != NULL; h = h->next) { + int hret; + + hret = h->handler(state, idx); + + if (hret > ret) + ret = hret; + } + + return ret; +} + +void exc_dispatch(struct exc_state *state, uint64_t idx) +{ + int ret; + + if (idx >= NUM_EXC_VIDS) { + printk(BIOS_DEBUG, "Bad exception index %x.\n", (int)idx); + print_exception_and_die(state, idx); + } + + ret = handle_exception(state, idx); + + if (ret == EXC_RET_ABORT) + print_exception_and_die(state, idx); + + if (ret == EXC_RET_IGNORED || ret == EXC_RET_HANDLED_DUMP_STATE) + print_exception_info(state, idx); + + exc_exit(&state->regs); +} + +static int test_exception_handler(struct exc_state *state, uint64_t vector_id) +{ + /* Update instruction pointer to next instrution. */ + state->elx.elr += sizeof(uint32_t); + raw_write_elr_current(state->elx.elr); + return EXC_RET_HANDLED; +} + +static uint64_t test_exception(void) +{ + struct exception_handler sync_elx; + struct exception_handler sync_el0; + unsigned long long *a = (void *)0xffffffff00000000ULL; + + sync_elx.handler = &test_exception_handler; + sync_el0.handler = &test_exception_handler; + + exception_handler_register(EXC_VID_CUR_SP_ELX_SYNC, &sync_elx); + exception_handler_register(EXC_VID_CUR_SP_EL0_SYNC, &sync_el0); + + force_read(*a); + + exception_handler_unregister(EXC_VID_CUR_SP_ELX_SYNC, &sync_elx); + exception_handler_unregister(EXC_VID_CUR_SP_EL0_SYNC, &sync_el0); + + return 0; +} + +void exception_init(void) +{ + /* Load the exception table and initialize SP_EL3. */ + exception_init_asm(exception_stack + ARRAY_SIZE(exception_stack)); + + printk(BIOS_DEBUG, "ARM64: Exception handlers installed.\n"); + + /* Only spend time testing on debug builds that are trying to detect more errors. */ + if (IS_ENABLED(CONFIG_FATAL_ASSERTS)) { + printk(BIOS_DEBUG, "ARM64: Testing exception\n"); + test_exception(); + printk(BIOS_DEBUG, "ARM64: Done test exception\n"); + } +} diff --git a/pool/shard002/C/0061714_slave.c b/pool/shard002/C/0061714_slave.c new file mode 100644 index 0000000000000000000000000000000000000000..f59fbbdc461c6927b5812a29137649cb09de713a --- /dev/null +++ b/pool/shard002/C/0061714_slave.c @@ -0,0 +1,156 @@ +/* + * Copyright (c) 2013 - 2014, Freescale Semiconductor, 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: + * + * o Redistributions of source code must retain the above copyright notice, this list + * of conditions and the following disclaimer. + * + * o 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. + * + * o Neither the name of Freescale Semiconductor, Inc. nor the names of its + * contributors may be used to endorse or promote products derived from this + * software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR + * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include +#include "fsl_spi_slave_driver.h" +#include "fsl_clock_manager.h" +#include "fsl_debug_console.h" +#include "board.h" +#include + +/******************************************************************************* + * Definitions + ******************************************************************************/ +#define SPI_SLAVE_INSTANCE (0) /*! User change define to choose SPI instance */ +#define TRANSFER_SIZE (64) +#define SLAVE_TRANSFER_TIMEOUT (OSA_WAIT_FOREVER) /*! Transfer timeout of slave - 5s */ + +/******************************************************************************* + * Prototypes + ******************************************************************************/ + +/******************************************************************************* + * Variables + ******************************************************************************/ + +/*! + * @brief Buffer for storing data received by the SPI slave driver. + */ +uint8_t s_spiSinkBuffer[TRANSFER_SIZE] = {0}; + +/*! + * @brief Buffer that supplies data to be transmitted with the SPI slave driver. + */ +uint8_t s_spiSourceBuffer[TRANSFER_SIZE] = {0}; + +/******************************************************************************* + * Code + ******************************************************************************/ + +int main (void) +{ + uint32_t j; + spi_status_t spiResult; + spi_slave_state_t spiSlaveState; + + // Create slaveUserConfig + spi_slave_user_config_t slaveUserConfig = + { + #if FSL_FEATURE_SPI_16BIT_TRANSFERS + .bitCount = kSpi8BitMode, + #endif + .direction = kSpiMsbFirst, + .polarity = kSpiClockPolarity_ActiveHigh, + .phase = kSpiClockPhase_FirstEdge + }; + + // init the hardware, this also sets up up the SPI pins for each specific SoC + hardware_init(); + + OSA_Init(); + + dbg_uart_init(); + + printf("\r\nSPI board to board blocking example"); + printf("\r\nThis example run on instance 0 "); + printf("\r\nBe sure master's SPI0 and slave's SPI0 are connected "); + + //USER CONFIGURABLE OPTION FOR SPI INSTANCE (if applicable) + + // Configure SPI pin + configure_spi_pins(SPI_SLAVE_INSTANCE); + + SPI_DRV_SlaveInit(SPI_SLAVE_INSTANCE, &spiSlaveState, &slaveUserConfig); + + while(1) + { + printf("\r\nSlave example is running..."); + + // Reset the sink buffer + for (j = 0; j < TRANSFER_SIZE; j++) + { + s_spiSinkBuffer[j] = 0; + } + + // Receive data from master + printf("\r\nSPI is waiting to receive data \r\n"); + + spiResult = SPI_DRV_SlaveTransferBlocking(SPI_SLAVE_INSTANCE, + NULL, + s_spiSinkBuffer, + TRANSFER_SIZE, OSA_WAIT_FOREVER); + if (spiResult != kStatus_SPI_Success) + { + printf("\r\nERROR: slave receives error "); + return -1; + } + + for (j = 0; j < TRANSFER_SIZE; j++) + { + s_spiSourceBuffer[j] = s_spiSinkBuffer[j]; + } + // Send back datat to master + spiResult = SPI_DRV_SlaveTransferBlocking(SPI_SLAVE_INSTANCE, + s_spiSourceBuffer, + NULL, + TRANSFER_SIZE, OSA_WAIT_FOREVER); + if (spiResult != kStatus_SPI_Success) + { + printf("\r\nERROR: slave sends error "); + return -1; + } + + // Print out receive buffer + printf("\r\nSlave receive:"); + for (j = 0; j < TRANSFER_SIZE; j++) + { + if (j%16 == 0) + { + printf("\r\n "); + } + printf(" %02X", s_spiSinkBuffer[j]); + } + } +} + +/******************************************************************************* + * EOF + ******************************************************************************/ + diff --git a/pool/shard002/C/0061720_bst_126_m256_padding.c b/pool/shard002/C/0061720_bst_126_m256_padding.c new file mode 100644 index 0000000000000000000000000000000000000000..98cb30136b726ba13da72406dc9e63d0be11abdc --- /dev/null +++ b/pool/shard002/C/0061720_bst_126_m256_padding.c @@ -0,0 +1,145 @@ +#include +#include +#include + + +/* + * Disclaimer: The indices differ from the high-level pseudo-code description + * found in the book [1]. + * + * Here, e[i,j] is the expected value for the tree containing keys i to j-1, + * since the first key is p_0 and not p_1 as in the book. w[.,.] and root[.,.] + * are defined similarly. + * + */ + +/* + * This is an extension of bst_117. It implements the padding semantics that + * enable proper alignment of vectors. + * + */ + +#define STRIDE (n+1) +#define IDX(i,j) ((n+1)*(n+2)/2 - (n-(i)+1)*(n-(i)+2)/2 + (j) - (i)) + +typedef struct { + double* e; + double* w; + int* r; + size_t n; + size_t e_sz; +} segments_t; + +inline size_t compute_size( size_t n ) { + size_t m = (n+1)%4; + size_t k = (3-m)*(3-m+1)/2; + size_t rempad = 6 - k; + return (n+1)*(n+2)/2 + ((n+1)/4)*6 + rempad; +} + +void* bst_alloc_126_m256_padding( size_t n ) { + segments_t* mem = (segments_t*) malloc( sizeof(segments_t) ); + mem->e_sz = compute_size( n ); + // XXX: for testing: calloc + mem->e = (double*) calloc(1, mem->e_sz * sizeof(double) ); + mem->w = (double*) calloc(1, mem->e_sz * sizeof(double) ); + mem->r = (int*) calloc(1, mem->e_sz * sizeof(int) ); + mem->n = n; + memset( mem->r, -1, mem->e_sz * sizeof(int) ); + return mem; +} + +double bst_compute_126_m256_padding( void*_bst_obj, double* p, double* q, size_t nn ) { + segments_t* mem = (segments_t*) _bst_obj; + int n, i, r, l_end, j; + double t, e_tmp; + double* e = mem->e, *w = mem->w; + int* root = mem->r; + // initialization + // mem->n = nn; + n = nn; // subtractions with n potentially negative. say hello to all the bugs + + int idx1, idx2, idx3, pad, pad_r; + + idx1 = ((int) mem->e_sz) - 1; + // the conventio is that iteration i, idx1 points to the first element of line i+1 + e[idx1++] = q[n]; + + // pad contains the padding for row i+1 + // for row n it's always 3 + pad = 3; + for (i = n-1; i >= 0; --i) { + idx1 -= 2*(n-i)+1 + pad; + idx2 = idx1 + 1; + e[idx1] = q[i]; + w[idx1] = q[i]; + for (j = i+1; j < n+1; ++j,++idx2) { + e[idx2] = INFINITY; + w[idx2] = w[idx2-1] + p[j-1] + q[j]; + } + // idx2 now points to the beginning of the next line. + idx2 += pad; // padding of line i+1 + + idx3 = idx1; + pad_r = pad; // padding of line r + for (r = i; r < n; ++r) { + pad_r = (pad_r+1)&3; // padding of line r+1 + // idx2 = IDX(r+1, r+1); + idx1 = idx3; + l_end = idx2 + (n-r); + e_tmp = e[idx1++]; + for( ; idx2 < l_end; ++idx2 ) { + // printf("idx1: %d, idx2: %d\n", idx1, idx2); + t = e_tmp + e[idx2] + w[idx1]; + if (t < e[idx1]) { + e[idx1] = t; + root[idx1] = r; + } + idx1++; + } + idx2 += pad_r; + idx3++; + } + pad = (pad-1)&3; + // pad is 3,2,1,0,3,2,1,0, etc. + } + + // the index of the last item of the first row is ((n/4)+1)*4-1, due to the padding + // if n is even, the total number of entries in the first + // row of the table is odd, so we need padding + return e[ ((n/4)+1)*4 - 1 ]; +} + +size_t bst_get_root_126_m256_padding( void* _bst_obj, size_t i, size_t j ) +{ + // [i,j], in table: [i-1, j]+1 + segments_t *mem = _bst_obj; + size_t n = mem->n; + int *root = mem->r; + return (size_t) root[(i-1)*(n+1)+j]+1; +} + +void bst_free_126_m256_padding( void* _mem ) { + segments_t* mem = (segments_t*) _mem; + + /* + size_t n = mem->n; + for (size_t i=0; i<=n; ++i) { + for (size_t j=0; j<=n; ++j) { + printf(" %.3lf", mem->e[i*(n+1)+j]); + } + printf("\n"); + } + */ + + free( mem->e ); + free( mem->w ); + free( mem->r ); + free( mem ); +} + +size_t bst_flops_126_m256_padding( size_t n ) { + double n3 = n*n*n; + double n2 = n*n; + return (size_t) ( n3/3.0 + 2*n2 + 5.0*n/3 ); +} diff --git a/pool/shard002/C/0061734_CWE121_Stack_Based_Buffer_Overflow__CWE805_wchar_t_alloca_memcpy_12.c b/pool/shard002/C/0061734_CWE121_Stack_Based_Buffer_Overflow__CWE805_wchar_t_alloca_memcpy_12.c new file mode 100644 index 0000000000000000000000000000000000000000..267f14e4f28425ae25537789e6a2aa344eb1db93 --- /dev/null +++ b/pool/shard002/C/0061734_CWE121_Stack_Based_Buffer_Overflow__CWE805_wchar_t_alloca_memcpy_12.c @@ -0,0 +1,118 @@ +/* TEMPLATE GENERATED TESTCASE FILE +Filename: CWE121_Stack_Based_Buffer_Overflow__CWE805_wchar_t_alloca_memcpy_12.c +Label Definition File: CWE121_Stack_Based_Buffer_Overflow__CWE805.string.label.xml +Template File: sources-sink-12.tmpl.c +*/ +/* + * @description + * CWE: 121 Stack Based Buffer Overflow + * BadSource: Set data pointer to the bad buffer + * GoodSource: Set data pointer to the good buffer + * Sink: memcpy + * BadSink : Copy string to data using memcpy + * Flow Variant: 12 Control flow: if(globalReturnsTrueOrFalse()) + * + * */ + +#include "std_testcase.h" + +#include + +#ifndef OMITBAD + +void CWE121_Stack_Based_Buffer_Overflow__CWE805_wchar_t_alloca_memcpy_12_bad() +{ + wchar_t * data; + wchar_t * dataBadBuffer = (wchar_t *)ALLOCA(50*sizeof(wchar_t)); + wchar_t * dataGoodBuffer = (wchar_t *)ALLOCA(100*sizeof(wchar_t)); + if(globalReturnsTrueOrFalse()) + { + /* FLAW: Set a pointer to a "small" buffer. This buffer will be used in the sinks as a destination + * buffer in various memory copying functions using a "large" source buffer. */ + data = dataBadBuffer; + data[0] = L'\0'; /* null terminate */ + } + else + { + /* FIX: Set a pointer to a "large" buffer, thus avoiding buffer overflows in the sinks. */ + data = dataGoodBuffer; + data[0] = L'\0'; /* null terminate */ + } + { + wchar_t source[100]; + wmemset(source, L'C', 100-1); /* fill with L'C's */ + source[100-1] = L'\0'; /* null terminate */ + /* POTENTIAL FLAW: Possible buffer overflow if the size of data is less than the length of source */ + memcpy(data, source, 100*sizeof(wchar_t)); + data[100-1] = L'\0'; /* Ensure the destination buffer is null terminated */ + printWLine(data); + } +} + +#endif /* OMITBAD */ + +#ifndef OMITGOOD + +/* goodG2B() - use goodsource and badsink by changing the "if" so that + * both branches use the GoodSource */ +static void goodG2B() +{ + wchar_t * data; + wchar_t * dataBadBuffer = (wchar_t *)ALLOCA(50*sizeof(wchar_t)); + wchar_t * dataGoodBuffer = (wchar_t *)ALLOCA(100*sizeof(wchar_t)); + if(globalReturnsTrueOrFalse()) + { + /* FIX: Set a pointer to a "large" buffer, thus avoiding buffer overflows in the sinks. */ + data = dataGoodBuffer; + data[0] = L'\0'; /* null terminate */ + } + else + { + /* FIX: Set a pointer to a "large" buffer, thus avoiding buffer overflows in the sinks. */ + data = dataGoodBuffer; + data[0] = L'\0'; /* null terminate */ + } + { + wchar_t source[100]; + wmemset(source, L'C', 100-1); /* fill with L'C's */ + source[100-1] = L'\0'; /* null terminate */ + /* POTENTIAL FLAW: Possible buffer overflow if the size of data is less than the length of source */ + memcpy(data, source, 100*sizeof(wchar_t)); + data[100-1] = L'\0'; /* Ensure the destination buffer is null terminated */ + printWLine(data); + } +} + +void CWE121_Stack_Based_Buffer_Overflow__CWE805_wchar_t_alloca_memcpy_12_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()..."); + CWE121_Stack_Based_Buffer_Overflow__CWE805_wchar_t_alloca_memcpy_12_good(); + printLine("Finished good()"); +#endif /* OMITGOOD */ +#ifndef OMITBAD + printLine("Calling bad()..."); + CWE121_Stack_Based_Buffer_Overflow__CWE805_wchar_t_alloca_memcpy_12_bad(); + printLine("Finished bad()"); +#endif /* OMITBAD */ + return 0; +} + +#endif diff --git a/pool/shard002/C/0061736_pcap-can-linux.c b/pool/shard002/C/0061736_pcap-can-linux.c new file mode 100644 index 0000000000000000000000000000000000000000..f6a3925ec065cfc4084c741f1c3e9a3a93aaedf5 --- /dev/null +++ b/pool/shard002/C/0061736_pcap-can-linux.c @@ -0,0 +1,311 @@ +/* + * Copyright (c) 2009 Felix Obenhuber + * 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 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. + * + * SocketCan sniffing API implementation for Linux platform + * By Felix Obenhuber + * + */ + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +#include "pcap-int.h" +#include "pcap-can-linux.h" + +#ifdef NEED_STRERROR_H +#include "strerror.h" +#endif + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +/* not yet defined anywhere */ +#ifndef PF_CAN +#define PF_CAN 29 +#endif +#ifndef AF_CAN +#define AF_CAN PF_CAN +#endif + +/* forward declaration */ +static int can_activate(pcap_t *); +static int can_read_linux(pcap_t *, int , pcap_handler , u_char *); +static int can_inject_linux(pcap_t *, const void *, size_t); +static int can_setfilter_linux(pcap_t *, struct bpf_program *); +static int can_setdirection_linux(pcap_t *, pcap_direction_t); +static int can_stats_linux(pcap_t *, struct pcap_stat *); + +int +can_findalldevs(pcap_if_t **devlistp, char *errbuf) +{ + /* + * There are no platform-specific devices since each device + * exists as a regular network interface. + * + * XXX - true? + */ + return 0; +} + +pcap_t * +can_create(const char *device, char *ebuf, int *is_ours) +{ + const char *cp; + char *cpend; + long devnum; + pcap_t* p; + + /* Does this look like a CANbus device? */ + cp = strrchr(device, '/'); + if (cp == NULL) + cp = device; + /* Does it begin with "can" or "vcan"? */ + if (strncmp(cp, "can", 3) == 0) { + /* Begins with "can" */ + cp += 3; /* skip past "can" */ + } else if (strncmp(cp, "vcan", 4) == 0) { + /* Begins with "vcan" */ + cp += 4; + } else { + /* Nope, doesn't begin with "can" or "vcan" */ + *is_ours = 0; + return NULL; + } + /* Yes - is "can" or "vcan" followed by a number from 0? */ + devnum = strtol(cp, &cpend, 10); + if (cpend == cp || *cpend != '\0') { + /* Not followed by a number. */ + *is_ours = 0; + return NULL; + } + if (devnum < 0) { + /* Followed by a non-valid number. */ + *is_ours = 0; + return NULL; + } + + /* OK, it's probably ours. */ + *is_ours = 1; + + p = pcap_create_common(device, ebuf); + if (p == NULL) + return (NULL); + + p->activate_op = can_activate; + return (p); +} + + +static int +can_activate(pcap_t* handle) +{ + struct sockaddr_can addr; + struct ifreq ifr; + + /* Initialize some components of the pcap structure. */ + handle->bufsize = 24; + handle->offset = 8; + handle->linktype = DLT_CAN_SOCKETCAN; + handle->read_op = can_read_linux; + handle->inject_op = can_inject_linux; + handle->setfilter_op = can_setfilter_linux; + handle->setdirection_op = can_setdirection_linux; + handle->set_datalink_op = NULL; + handle->getnonblock_op = pcap_getnonblock_fd; + handle->setnonblock_op = pcap_setnonblock_fd; + handle->stats_op = can_stats_linux; + + /* Create socket */ + handle->fd = socket(PF_CAN, SOCK_RAW, CAN_RAW); + if (handle->fd < 0) + { + snprintf(handle->errbuf, PCAP_ERRBUF_SIZE, "Can't create raw socket %d:%s", + errno, strerror(errno)); + return PCAP_ERROR; + } + + /* get interface index */ + memset(&ifr, 0, sizeof(ifr)); + strncpy(ifr.ifr_name, handle->opt.source, sizeof(ifr.ifr_name)); + if (ioctl(handle->fd, SIOCGIFINDEX, &ifr) < 0) + { + snprintf(handle->errbuf, PCAP_ERRBUF_SIZE, + "Unable to get interface index: %s", + pcap_strerror(errno)); + pcap_cleanup_live_common(handle); + return PCAP_ERROR; + } + handle->md.ifindex = ifr.ifr_ifindex; + + /* allocate butter */ + handle->buffer = malloc(handle->bufsize); + if (!handle->buffer) + { + snprintf(handle->errbuf, PCAP_ERRBUF_SIZE, "Can't allocate dump buffer: %s", + pcap_strerror(errno)); + pcap_cleanup_live_common(handle); + return PCAP_ERROR; + } + + /* Bind to the socket */ + addr.can_family = AF_CAN; + addr.can_ifindex = handle->md.ifindex; + if( bind( handle->fd, (struct sockaddr*)&addr, sizeof(addr) ) < 0 ) + { + snprintf(handle->errbuf, PCAP_ERRBUF_SIZE, "Can't attach to device %d %d:%s", + handle->md.ifindex, errno, strerror(errno)); + pcap_cleanup_live_common(handle); + return PCAP_ERROR; + } + + if (handle->opt.rfmon) + { + /* Monitor mode doesn't apply to CAN devices. */ + pcap_cleanup_live_common(handle); + return PCAP_ERROR; + } + + handle->selectable_fd = handle->fd; + return 0; + +} + + +static int +can_read_linux(pcap_t *handle, int max_packets, pcap_handler callback, u_char *user) +{ + struct msghdr msg; + struct pcap_pkthdr pkth; + struct iovec iv; + struct can_frame* cf; + + iv.iov_base = &handle->buffer[handle->offset]; + iv.iov_len = handle->snapshot; + + memset(&msg, 0, sizeof(msg)); + msg.msg_iov = &iv; + msg.msg_iovlen = 1; + msg.msg_control = handle->buffer; + msg.msg_controllen = handle->offset; + + do + { + pkth.caplen = recvmsg(handle->fd, &msg, 0); + if (handle->break_loop) + { + handle->break_loop = 0; + return -2; + } + } while ((pkth.caplen == -1) && (errno == EINTR)); + + if (pkth.caplen < 0) + { + snprintf(handle->errbuf, PCAP_ERRBUF_SIZE, "Can't receive packet %d:%s", + errno, strerror(errno)); + return -1; + } + + /* adjust capture len according to frame len */ + cf = (struct can_frame*)&handle->buffer[8]; + pkth.caplen -= 8 - cf->can_dlc; + pkth.len = pkth.caplen; + + cf->can_id = htonl( cf->can_id ); + + if( -1 == gettimeofday(&pkth.ts, NULL) ) + { + snprintf(handle->errbuf, PCAP_ERRBUF_SIZE, "Can't get time of day %d:%s", + errno, strerror(errno)); + return -1; + } + + callback(user, &pkth, &handle->buffer[8]); + + return 1; +} + + +static int +can_inject_linux(pcap_t *handle, const void *buf, size_t size) +{ + /* not yet implemented */ + snprintf(handle->errbuf, PCAP_ERRBUF_SIZE, "inject not supported on " + "can devices"); + return (-1); +} + + +static int +can_stats_linux(pcap_t *handle, struct pcap_stat *stats) +{ + /* not yet implemented */ + stats->ps_recv = 0; /* number of packets received */ + stats->ps_drop = 0; /* number of packets dropped */ + stats->ps_ifdrop = 0; /* drops by interface -- only supported on some platforms */ + return 0; +} + + +static int +can_setfilter_linux(pcap_t *p, struct bpf_program *fp) +{ + /* not yet implemented */ + return 0; +} + + +static int +can_setdirection_linux(pcap_t *p, pcap_direction_t d) +{ + /* no support for PCAP_D_OUT */ + if (d == PCAP_D_OUT) + { + snprintf(p->errbuf, sizeof(p->errbuf), + "Setting direction to PCAP_D_OUT is not supported on can"); + return -1; + } + + p->direction = d; + + return 0; +} + + +/* eof */ diff --git a/pool/shard002/C/0061747_PhysCellIdCDMA2000.c b/pool/shard002/C/0061747_PhysCellIdCDMA2000.c new file mode 100644 index 0000000000000000000000000000000000000000..91f7c8659f4f1898190775633e5845ec52b32731 --- /dev/null +++ b/pool/shard002/C/0061747_PhysCellIdCDMA2000.c @@ -0,0 +1,165 @@ +/* + * Generated by asn1c-0.9.24 (http://lionet.info/asn1c) + * From ASN.1 module "EUTRA-RRC-Definitions" + * found in "fixed_grammar.asn" + * `asn1c -gen-PER` + */ + +#include "PhysCellIdCDMA2000.h" + +int +PhysCellIdCDMA2000_constraint(asn_TYPE_descriptor_t *td, const void *sptr, + asn_app_constraint_failed_f *ctfailcb, void *app_key) { + long value; + + if(!sptr) { + _ASN_CTFAIL(app_key, td, sptr, + "%s: value not given (%s:%d)", + td->name, __FILE__, __LINE__); + return -1; + } + + value = *(const long *)sptr; + + if((value >= 0 && value <= 511)) { + /* Constraint check succeeded */ + return 0; + } else { + _ASN_CTFAIL(app_key, td, sptr, + "%s: constraint failed (%s:%d)", + td->name, __FILE__, __LINE__); + return -1; + } +} + +/* + * This type is implemented using NativeInteger, + * so here we adjust the DEF accordingly. + */ +static void +PhysCellIdCDMA2000_1_inherit_TYPE_descriptor(asn_TYPE_descriptor_t *td) { + td->free_struct = asn_DEF_NativeInteger.free_struct; + td->print_struct = asn_DEF_NativeInteger.print_struct; + td->ber_decoder = asn_DEF_NativeInteger.ber_decoder; + td->der_encoder = asn_DEF_NativeInteger.der_encoder; + td->xer_decoder = asn_DEF_NativeInteger.xer_decoder; + td->xer_encoder = asn_DEF_NativeInteger.xer_encoder; + td->uper_decoder = asn_DEF_NativeInteger.uper_decoder; + td->uper_encoder = asn_DEF_NativeInteger.uper_encoder; + td->aper_decoder = asn_DEF_NativeInteger.aper_decoder; + td->aper_encoder = asn_DEF_NativeInteger.aper_encoder; + if(!td->per_constraints) + td->per_constraints = asn_DEF_NativeInteger.per_constraints; + td->elements = asn_DEF_NativeInteger.elements; + td->elements_count = asn_DEF_NativeInteger.elements_count; + td->specifics = asn_DEF_NativeInteger.specifics; +} + +void +PhysCellIdCDMA2000_free(asn_TYPE_descriptor_t *td, + void *struct_ptr, int contents_only) { + PhysCellIdCDMA2000_1_inherit_TYPE_descriptor(td); + td->free_struct(td, struct_ptr, contents_only); +} + +int +PhysCellIdCDMA2000_print(asn_TYPE_descriptor_t *td, const void *struct_ptr, + int ilevel, asn_app_consume_bytes_f *cb, void *app_key) { + PhysCellIdCDMA2000_1_inherit_TYPE_descriptor(td); + return td->print_struct(td, struct_ptr, ilevel, cb, app_key); +} + +asn_dec_rval_t +PhysCellIdCDMA2000_decode_ber(asn_codec_ctx_t *opt_codec_ctx, asn_TYPE_descriptor_t *td, + void **structure, const void *bufptr, size_t size, int tag_mode) { + PhysCellIdCDMA2000_1_inherit_TYPE_descriptor(td); + return td->ber_decoder(opt_codec_ctx, td, structure, bufptr, size, tag_mode); +} + +asn_enc_rval_t +PhysCellIdCDMA2000_encode_der(asn_TYPE_descriptor_t *td, + void *structure, int tag_mode, ber_tlv_tag_t tag, + asn_app_consume_bytes_f *cb, void *app_key) { + PhysCellIdCDMA2000_1_inherit_TYPE_descriptor(td); + return td->der_encoder(td, structure, tag_mode, tag, cb, app_key); +} + +asn_dec_rval_t +PhysCellIdCDMA2000_decode_xer(asn_codec_ctx_t *opt_codec_ctx, asn_TYPE_descriptor_t *td, + void **structure, const char *opt_mname, const void *bufptr, size_t size) { + PhysCellIdCDMA2000_1_inherit_TYPE_descriptor(td); + return td->xer_decoder(opt_codec_ctx, td, structure, opt_mname, bufptr, size); +} + +asn_enc_rval_t +PhysCellIdCDMA2000_encode_xer(asn_TYPE_descriptor_t *td, void *structure, + int ilevel, enum xer_encoder_flags_e flags, + asn_app_consume_bytes_f *cb, void *app_key) { + PhysCellIdCDMA2000_1_inherit_TYPE_descriptor(td); + return td->xer_encoder(td, structure, ilevel, flags, cb, app_key); +} + +asn_dec_rval_t +PhysCellIdCDMA2000_decode_uper(asn_codec_ctx_t *opt_codec_ctx, asn_TYPE_descriptor_t *td, + asn_per_constraints_t *constraints, void **structure, asn_per_data_t *per_data) { + PhysCellIdCDMA2000_1_inherit_TYPE_descriptor(td); + return td->uper_decoder(opt_codec_ctx, td, constraints, structure, per_data); +} + +asn_enc_rval_t +PhysCellIdCDMA2000_encode_uper(asn_TYPE_descriptor_t *td, + asn_per_constraints_t *constraints, + void *structure, asn_per_outp_t *per_out) { + PhysCellIdCDMA2000_1_inherit_TYPE_descriptor(td); + return td->uper_encoder(td, constraints, structure, per_out); +} + +asn_enc_rval_t +PhysCellIdCDMA2000_encode_aper(asn_TYPE_descriptor_t *td, + asn_per_constraints_t *constraints, + void *structure, asn_per_outp_t *per_out) { + PhysCellIdCDMA2000_1_inherit_TYPE_descriptor(td); + return td->aper_encoder(td, constraints, structure, per_out); +} + +asn_dec_rval_t +PhysCellIdCDMA2000_decode_aper(asn_codec_ctx_t *opt_codec_ctx, asn_TYPE_descriptor_t *td, + asn_per_constraints_t *constraints, void **structure, asn_per_data_t *per_data) { + PhysCellIdCDMA2000_1_inherit_TYPE_descriptor(td); + return td->aper_decoder(opt_codec_ctx, td, constraints, structure, per_data); +} + +static asn_per_constraints_t asn_PER_type_PhysCellIdCDMA2000_constr_1 GCC_NOTUSED = { + { APC_CONSTRAINED, 9, 9, 0, 511 } /* (0..511) */, + { APC_UNCONSTRAINED, -1, -1, 0, 0 }, + 0, 0 /* No PER value map */ +}; +static ber_tlv_tag_t asn_DEF_PhysCellIdCDMA2000_tags_1[] = { + (ASN_TAG_CLASS_UNIVERSAL | (2 << 2)) +}; +asn_TYPE_descriptor_t asn_DEF_PhysCellIdCDMA2000 = { + "PhysCellIdCDMA2000", + "PhysCellIdCDMA2000", + PhysCellIdCDMA2000_free, + PhysCellIdCDMA2000_print, + PhysCellIdCDMA2000_constraint, + PhysCellIdCDMA2000_decode_ber, + PhysCellIdCDMA2000_encode_der, + PhysCellIdCDMA2000_decode_xer, + PhysCellIdCDMA2000_encode_xer, + PhysCellIdCDMA2000_decode_uper, + PhysCellIdCDMA2000_encode_uper, + PhysCellIdCDMA2000_decode_aper, + PhysCellIdCDMA2000_encode_aper, + 0, /* Use generic outmost tag fetcher */ + asn_DEF_PhysCellIdCDMA2000_tags_1, + sizeof(asn_DEF_PhysCellIdCDMA2000_tags_1) + /sizeof(asn_DEF_PhysCellIdCDMA2000_tags_1[0]), /* 1 */ + asn_DEF_PhysCellIdCDMA2000_tags_1, /* Same as above */ + sizeof(asn_DEF_PhysCellIdCDMA2000_tags_1) + /sizeof(asn_DEF_PhysCellIdCDMA2000_tags_1[0]), /* 1 */ + &asn_PER_type_PhysCellIdCDMA2000_constr_1, + 0, 0, /* No members */ + 0 /* No specifics */ +}; + diff --git a/pool/shard002/C/0061761_EventUtil.c b/pool/shard002/C/0061761_EventUtil.c new file mode 100644 index 0000000000000000000000000000000000000000..3127efc8445dbc98f1267ef620afa9353298006e --- /dev/null +++ b/pool/shard002/C/0061761_EventUtil.c @@ -0,0 +1,232 @@ +/* + +Copyright (c) 1993, Oracle and/or its affiliates. All rights reserved. + +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 (including the next +paragraph) 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. + +*/ +/******************************************************** + +Copyright 1988 by Hewlett-Packard Company +Copyright 1987, 1988, 1989 by Digital Equipment Corporation, Maynard, Massachusetts + +Permission to use, copy, modify, and distribute this software +and its documentation for any purpose and without fee is hereby +granted, provided that the above copyright notice appear in all +copies and that both that copyright notice and this permission +notice appear in supporting documentation, and that the names of +Hewlett-Packard or Digital not be used in advertising or +publicity pertaining to distribution of the software without specific, +written prior permission. + +DIGITAL DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING +ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL +DIGITAL BE LIABLE FOR ANY SPECIAL, 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. + +********************************************************/ + +/* + +Copyright 1987, 1988, 1989, 1998 The Open Group + +Permission to use, copy, modify, distribute, and sell this software and its +documentation for any purpose is hereby granted without fee, provided that +the above copyright notice appear in all copies and that both that +copyright notice and this permission notice appear in supporting +documentation. + +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 +OPEN GROUP 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 of The Open Group shall not be +used in advertising or otherwise to promote the sale, use or other dealings +in this Software without prior written authorization from The Open Group. + +*/ + +#ifdef HAVE_CONFIG_H +#include +#endif +#include "IntrinsicI.h" +#include "PassivGraI.h" +#include "StringDefs.h" +#include "EventI.h" + +static XContext perWidgetInputContext = 0; + +void _XtFreePerWidgetInput( + Widget w, + XtPerWidgetInput pwi) +{ + LOCK_PROCESS; + XDeleteContext(XtDisplay(w), + (Window)w, + perWidgetInputContext); + + XtFree((char *)pwi); + UNLOCK_PROCESS; +} + +/* + * This routine gets the passive list associated with the widget + * from the context manager. + */ +XtPerWidgetInput _XtGetPerWidgetInput( + Widget widget, + _XtBoolean create) +{ + XtPerWidgetInput pwi = NULL; + Display *dpy = widget->core.screen->display; + + LOCK_PROCESS; + if (! perWidgetInputContext) + perWidgetInputContext = XUniqueContext(); + + if (XFindContext(dpy, + (Window)(((intptr_t)widget)&0xffffffff), + perWidgetInputContext, + (XPointer *)&pwi) && + create) + { + pwi = (XtPerWidgetInput) + __XtMalloc((unsigned) sizeof(XtPerWidgetInputRec)); + + pwi->focusKid = NULL; + pwi->queryEventDescendant = NULL; + pwi->focalPoint = XtUnrelated; + pwi->keyList = + pwi->ptrList = NULL; + + pwi->haveFocus = + pwi->map_handler_added = + pwi->realize_handler_added = + pwi->active_handler_added = FALSE; + + XtAddCallback(widget, XtNdestroyCallback, + _XtDestroyServerGrabs, (XtPointer)pwi); + + (void) XSaveContext(dpy, + (Window)(((intptr_t)widget)&0xffffffff), + perWidgetInputContext, + (char *) pwi); + } + UNLOCK_PROCESS; + return pwi; +} + + +void _XtFillAncestorList( + Widget **listPtr, + int *maxElemsPtr, + int *numElemsPtr, + Widget start, + Widget breakWidget) +{ +#define CACHESIZE 16 + Cardinal i; + Widget w; + Widget *trace = *listPtr; + + /* First time in, allocate the ancestor list */ + if (trace == NULL) + { + trace = (Widget *) __XtMalloc(CACHESIZE * sizeof(Widget)); + *maxElemsPtr = CACHESIZE; + } + /* First fill in the ancestor list */ + + trace[0] = start; + + for (i = 1, w = XtParent(start); + w != NULL && !XtIsShell(trace[i-1]) && trace[i-1] != breakWidget; + w = XtParent(w), i++) { + if (i == (Cardinal) *maxElemsPtr) { + /* This should rarely happen, but if it does it'll probably + happen again, so grow the ancestor list */ + *maxElemsPtr += CACHESIZE; + trace = (Widget *) XtRealloc((char*)trace, + sizeof(Widget) * (*maxElemsPtr)); + } + trace[i] = w; + } + *listPtr = trace; + *numElemsPtr = i; +#undef CACHESIZE +} + + +Widget _XtFindRemapWidget( + XEvent *event, + Widget widget, + EventMask mask, + XtPerDisplayInput pdi) +{ + Widget dspWidget = widget; + + if (!pdi->traceDepth || !(widget == pdi->trace[0])) + { + _XtFillAncestorList(&pdi->trace, &pdi->traceMax, + &pdi->traceDepth, widget, NULL); + pdi->focusWidget = NULL; /* invalidate the focus + cache */ + } + if (mask & (KeyPressMask | KeyReleaseMask)) + dspWidget = _XtProcessKeyboardEvent((XKeyEvent*)event, widget, pdi); + else if (mask &(ButtonPressMask | ButtonReleaseMask)) + dspWidget = _XtProcessPointerEvent((XButtonEvent*)event, widget,pdi); + + return dspWidget; +} + +void _XtUngrabBadGrabs( + XEvent *event, + Widget widget, + EventMask mask, + XtPerDisplayInput pdi) +{ + XKeyEvent * ke = (XKeyEvent *) event; + + if (mask & (KeyPressMask | KeyReleaseMask)) + { + if (IsServerGrab(pdi->keyboard.grabType) && + !_XtOnGrabList(pdi->keyboard.grab.widget, + pdi->grabList)) + XtUngrabKeyboard(widget, ke->time); + + } + else + { + if (IsServerGrab(pdi->pointer.grabType) && + !_XtOnGrabList(pdi->pointer.grab.widget, + pdi->grabList)) + XtUngrabPointer(widget, ke->time); + } +} diff --git a/pool/shard002/C/0061764_dw9714.c b/pool/shard002/C/0061764_dw9714.c new file mode 100644 index 0000000000000000000000000000000000000000..790cc86dee904d76876607a4c1b47363bdb3a3c4 --- /dev/null +++ b/pool/shard002/C/0061764_dw9714.c @@ -0,0 +1,195 @@ +/* Copyright (c) 2011-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. + */ + +#include "hisi_vcm.h" +#include "vcm_driver.h" + +#define VCM_ID_CODE 0x9714 + +int dw9714_get_otp_af(struct hisi_vcm_ctrl_t *vcm_ctrl, void *data) +{ + struct vcm_cfg_data *cdata = (struct vcm_cfg_data *)data; + struct hisi_sd_req_sd vcm_req_sd = {0}; + char sd_name[DEV_NAME_SIZE]={0}; + struct hisi_sensor_ctrl_t *s_ctrl; + int rc = 0; + + cam_debug("%s enter.", __func__); + + snprintf(sd_name, sizeof(sd_name), "hisi_sensor_%d", vcm_ctrl->index); + vcm_req_sd.name = sd_name; + v4l2_subdev_notify(&vcm_ctrl->hisi_sd.sd, HISI_SD_NOTIFY_GET_SD, &vcm_req_sd); + + s_ctrl = container_of(container_of(vcm_req_sd.subdev, struct hisi_sd_subdev, sd), + struct hisi_sensor_ctrl_t, hisi_sd); + + if (s_ctrl->sensor->sensor_otp.af_otp.af_otp_succeed) { + cam_info("%s succeed to get otp af.", __func__); + memcpy(&cdata->cfg.af_otp, &s_ctrl->sensor->sensor_otp.af_otp, + sizeof(struct hisi_sensor_af_otp)); + rc = 0; + } else { + cam_err("%s failed to get otp af.", __func__); + memset(&cdata->cfg.af_otp, 0, sizeof(struct hisi_sensor_af_otp)); + rc = -1; + } + return rc; +} + +int dw9714_ioctl(struct hisi_vcm_ctrl_t *vcm_ctrl, void *data) +{ + struct vcm_cfg_data cdata; + long rc = 0; + + cam_debug("%s enter.\n", __func__); + + if (copy_from_user(&cdata, (void *)data, sizeof(struct vcm_cfg_data))) + return -EFAULT; + + switch (cdata.cfgtype) { + case CFG_VCM_SET_CFG: + break; + case CFG_VCM_GET_OTP_AF: + rc = dw9714_get_otp_af(vcm_ctrl, data); + break; + default: + rc = -EFAULT; + break; + } + + return rc; +} + +int dw9714_i2c_read(struct hisi_vcm_ctrl_t *vcm_ctrl, void *data) +{ + struct vcm_cfg_data *cdata = (struct vcm_cfg_data *)data; + //struct vcm_i2c_reg reg; + int rc = -1; + + cam_info("%s: address=0x%x\n", __func__, cdata->cfg.reg.address); + //todo ... + cdata->cfg.reg.value = VCM_ID_CODE; + return rc; +} + +int dw9714_i2c_write(struct hisi_vcm_ctrl_t *vcm_ctrl, void *data) +{ + struct vcm_cfg_data *cdata = (struct vcm_cfg_data *)data; + int rc = 0; + + cam_debug("%s enter.\n", __func__); + + cam_debug("%s: address=0x%x, value=0x%x\n", __func__, + cdata->cfg.reg.address, cdata->cfg.reg.value); + + rc = isp_write_vcm(vcm_ctrl->vcm->vcm_info->slave_address, + (u16)cdata->cfg.reg.address, + (u16)cdata->cfg.reg.value, + vcm_ctrl->vcm->vcm_info->data_type); + + return rc; +} + +static struct hisi_vcm_fn_t dw9714_func_tbl = { + /* vcm function table */ + .vcm_config = hisi_vcm_config, + .vcm_i2c_read = dw9714_i2c_read, + .vcm_i2c_write = dw9714_i2c_write, + .vcm_ioctl = dw9714_ioctl, +}; + +static int32_t dw9714_vcm_probe(struct platform_device *pdev) +{ + int32_t rc = 0; + struct hisi_vcm_t *vcm = NULL; + cam_debug("%s enter.\n", __func__); + vcm = (struct hisi_vcm_t*)kmalloc(sizeof(struct hisi_vcm_t), + GFP_KERNEL); + if (NULL == vcm) { + return -ENOMEM; + } + + vcm->func_tbl = &dw9714_func_tbl; + + if (pdev->dev.of_node) { + rc = hisi_vcm_get_dt_data(pdev, vcm); + if (rc < 0) { + cam_err("%s failed line %d\n", __func__, __LINE__); + kfree(vcm); + vcm = NULL; + return rc; + } + } else { + cam_err("%s dw9714 of_node is NULL.\n", __func__); + kfree(vcm); + vcm = NULL; + return rc; + } + + rc = hisi_vcm_add(vcm); + if (rc < 0) { + cam_err("%s fail to add vcm into vcm array.\n", __func__); + kfree(vcm); + vcm = NULL; + return rc; + } + if (!dev_get_drvdata(&pdev->dev)) { + dev_set_drvdata(&pdev->dev, (void *)vcm); + } + return rc; +} + +static const struct of_device_id hisi_dw9714_dt_match[] = { + {.compatible = "hisi,dw9714"}, + {} +}; +MODULE_DEVICE_TABLE(of, hisi_dw9714_dt_match); +static struct platform_driver dw9714_platform_driver = { + .driver = { + .name = "dw9714", + .owner = THIS_MODULE, + .of_match_table = hisi_dw9714_dt_match, + }, +}; + +static int32_t dw9714_platform_probe(struct platform_device *pdev) +{ + int32_t rc = 0; + const struct of_device_id *match; + match = of_match_device(hisi_dw9714_dt_match, &pdev->dev); + cam_info("%s compatible=%s.\n", __func__, match->compatible); + rc = dw9714_vcm_probe(pdev); + return rc; +} + +static int __init dw9714_module_init(void) +{ + int rc = 0; + cam_debug("%s:%d\n", __func__, __LINE__); + + rc = platform_driver_probe(&dw9714_platform_driver, + dw9714_platform_probe); + if (rc < 0) { + cam_err("%s platform_driver_probe error.\n", __func__); + } + return rc; +} + +static void __exit dw9714_module_exit(void) +{ + platform_driver_unregister(&dw9714_platform_driver); +} + +MODULE_AUTHOR("HISI"); +module_init(dw9714_module_init); +module_exit(dw9714_module_exit); +MODULE_LICENSE("GPL"); diff --git a/pool/shard002/C/0061776_rt_scene.c b/pool/shard002/C/0061776_rt_scene.c new file mode 100644 index 0000000000000000000000000000000000000000..a99e49def7c39f769751e0c806b29697cbf39fcc --- /dev/null +++ b/pool/shard002/C/0061776_rt_scene.c @@ -0,0 +1,87 @@ +/* ************************************************************************** */ +/* */ +/* ::: :::::::: */ +/* rt_scene.c :+: :+: :+: */ +/* +:+ +:+ +:+ */ +/* By: qfremeau +#+ +:+ +#+ */ +/* +#+#+#+#+#+ +#+ */ +/* Created: 2016/11/24 22:26:38 by qfremeau #+# #+# */ +/* Updated: 2017/01/07 16:53:07 by qfremeau ### ########.fr */ +/* */ +/* ************************************************************************** */ + +#include "rtv1.h" + +t_scene *new_scene(t_cam *cam, t_obj **obj, t_skybox *skybox) +{ + t_scene *s; + + s = malloc(sizeof(t_scene)); + s->cam = cam; + s->obj = obj; + s->skybox = skybox; + return (s); +} + +t_scene *init_scene(t_rt *rt) +{ + t_scene *scene; + t_obj **obj; + t_skybox *skybox; + t_cam *cam; + t_vec3 *temp; + t_vec3 *cam_lookfrom; + t_vec3 *cam_lookat; + t_vec3 *cam_vup; + double focus; + double aperture; + int obj_nb; + + cam_lookfrom = v3_new_vec(13.0, 2.0, 3.0); + cam_lookat = v3_new_vec(0.0, 0.0, 0.0); + cam_vup = v3_new_vec(0.0, -1.0, 0.0); + temp = v3_sub_vec(*cam_lookfrom, *cam_lookat); + focus = v3_lenght_double(*temp); + aperture = 0.0; + v3_free(temp); + cam = init_camera(cam_lookfrom, cam_lookat, cam_vup, 60.0, \ + (double)rt->r_view->w / (double)rt->r_view->h, aperture, focus); + + obj_nb = 3; + obj = (t_obj**)malloc(obj_nb * sizeof(t_obj*)); + obj[0] = new_object((void*)new_sphere(v3_new_vec(0, -1000, 0), 1000), \ + OBJ_SPHERE, new_material(v3_new_vec(0.9, 0.0, 0.0), 0.0), \ + MAT_LAMBERT); + obj[1] = new_object((void*)new_sphere(v3_new_vec(0, 2, 0), 2), \ + OBJ_SPHERE, new_material(v3_new_vec(0.1, 0.8, 1.0), 0.2), \ + MAT_LAMBERT); + //obj[1] = new_object((void*)new_sphere(v3_new_vec(2, 2, 0), 2), \ + OBJ_PLANE_XY, new_material(v3_new_vec(0.5, 0.5, 1.0), 0.0), \ + MAT_LAMBERT); + obj[2] = new_object((void*)new_sphere(v3_new_vec(-1, 7, -1), 2), \ + OBJ_SPHERE, new_material(v3_new_vec(4, 4, 4), NULL_PARAM), \ + MAT_DIFF_LIGHT); + /*obj[0] = new_object(v3_new_vec(0.0, 0.0, 0.0), 0.2, OBJ_SPHERE, \ + v3_new_vec(1.0, 0.1, 0.1), MAT_LAMBERT, NULL_PARAM); + obj[1] = new_object(v3_new_vec(0.0, -100.5, -1.0), 100.0, OBJ_SPHERE, \ + v3_new_vec(0.9, 0.9, 0.9), MAT_LAMBERT, NULL_PARAM); + obj[2] = new_object(v3_new_vec(1.0, 0.0, -1.0), 0.5, OBJ_SPHERE, \ + v3_new_vec(0.7, 0.7, 0.7), MAT_METAL, 0.0); + obj[3] = new_object(v3_new_vec(-1.0, 0.0, -1.0), 0.5, OBJ_SPHERE, \ + v3_new_vec(0.8, 0.8, 0.2), MAT_METAL, 0.5); + obj[4] = new_object(v3_new_vec(0.0, 0.0, 1.0), 0.5, OBJ_SPHERE, \ + v3_new_vec(0.1, 0.1, 0.8), MAT_LAMBERT, NULL_PARAM); + obj[5] = new_object(v3_new_vec(0.0, 0.0, -3.0), 2.0, OBJ_SPHERE, \ + v3_new_vec(0.1, 0.1, 0.1), MAT_LAMBERT, NULL_PARAM); + obj[6] = new_object(v3_new_vec(150.0, 120.0, 150.0), 100.0, OBJ_SPHERE, \ + v3_new_vec(0.9, 0.5, 0.3), MAT_DIFF_LIGHT, NULL_PARAM); + obj[6] = new_object(v3_new_vec(0.0, 1.5, 0.0), 0.5, OBJ_SPHERE, \ + v3_new_vec(0.8, 0.8, 0.8), MAT_DIFF_LIGHT, NULL_PARAM);*/ + + skybox = new_skybox(v3_new_vec(0.5, 0.4, 0.1), \ + v3_new_vec(0.6, 1.0, 1.0), SKYBX_GRADIENT); + + scene = new_scene(cam, obj, skybox); + scene->obj_nb = obj_nb; + return (scene); +} diff --git a/pool/shard002/C/0061792_max7359_keypad.c b/pool/shard002/C/0061792_max7359_keypad.c new file mode 100644 index 0000000000000000000000000000000000000000..307235df952d4ec70afdde01e12658e82312aabf --- /dev/null +++ b/pool/shard002/C/0061792_max7359_keypad.c @@ -0,0 +1,323 @@ +/* + * max7359_keypad.c - MAX7359 Key Switch Controller Driver + * + * Copyright (C) 2009 Samsung Electronics + * Kim Kyuwon + * + * Based on pxa27x_keypad.c + * + * 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. + * + * Datasheet: http://www.maxim-ic.com/quick_view2.cfm/qv_pk/5456 + */ + +#include +#include +#include +#include +#include +#include +#include + +#define MAX7359_MAX_KEY_ROWS 8 +#define MAX7359_MAX_KEY_COLS 8 +#define MAX7359_MAX_KEY_NUM (MAX7359_MAX_KEY_ROWS * MAX7359_MAX_KEY_COLS) +#define MAX7359_ROW_SHIFT 3 + +/* + + */ +#define MAX7359_REG_KEYFIFO 0x00 +#define MAX7359_REG_CONFIG 0x01 +#define MAX7359_REG_DEBOUNCE 0x02 +#define MAX7359_REG_INTERRUPT 0x03 +#define MAX7359_REG_PORTS 0x04 +#define MAX7359_REG_KEYREP 0x05 +#define MAX7359_REG_SLEEP 0x06 + +/* + + */ +#define MAX7359_CFG_SLEEP (1 << 7) +#define MAX7359_CFG_INTERRUPT (1 << 5) +#define MAX7359_CFG_KEY_RELEASE (1 << 3) +#define MAX7359_CFG_WAKEUP (1 << 1) +#define MAX7359_CFG_TIMEOUT (1 << 0) + +/* + + */ +#define MAX7359_AUTOSLEEP_8192 0x01 +#define MAX7359_AUTOSLEEP_4096 0x02 +#define MAX7359_AUTOSLEEP_2048 0x03 +#define MAX7359_AUTOSLEEP_1024 0x04 +#define MAX7359_AUTOSLEEP_512 0x05 +#define MAX7359_AUTOSLEEP_256 0x06 + +struct max7359_keypad { + /* */ + unsigned short keycodes[MAX7359_MAX_KEY_NUM]; + + struct input_dev *input_dev; + struct i2c_client *client; +}; + +static int max7359_write_reg(struct i2c_client *client, u8 reg, u8 val) +{ + int ret = i2c_smbus_write_byte_data(client, reg, val); + + if (ret < 0) + dev_err(&client->dev, "%s: reg 0x%x, val 0x%x, err %d\n", + __func__, reg, val, ret); + return ret; +} + +static int max7359_read_reg(struct i2c_client *client, int reg) +{ + int ret = i2c_smbus_read_byte_data(client, reg); + + if (ret < 0) + dev_err(&client->dev, "%s: reg 0x%x, err %d\n", + __func__, reg, ret); + return ret; +} + +static void max7359_build_keycode(struct max7359_keypad *keypad, + const struct matrix_keymap_data *keymap_data) +{ + struct input_dev *input_dev = keypad->input_dev; + int i; + + for (i = 0; i < keymap_data->keymap_size; i++) { + unsigned int key = keymap_data->keymap[i]; + unsigned int row = KEY_ROW(key); + unsigned int col = KEY_COL(key); + unsigned int scancode = MATRIX_SCAN_CODE(row, col, + MAX7359_ROW_SHIFT); + unsigned short keycode = KEY_VAL(key); + + keypad->keycodes[scancode] = keycode; + __set_bit(keycode, input_dev->keybit); + } + __clear_bit(KEY_RESERVED, input_dev->keybit); +} + +/* */ +static irqreturn_t max7359_interrupt(int irq, void *dev_id) +{ + struct max7359_keypad *keypad = dev_id; + struct input_dev *input_dev = keypad->input_dev; + int val, row, col, release, code; + + val = max7359_read_reg(keypad->client, MAX7359_REG_KEYFIFO); + row = val & 0x7; + col = (val >> 3) & 0x7; + release = val & 0x40; + + code = MATRIX_SCAN_CODE(row, col, MAX7359_ROW_SHIFT); + + dev_dbg(&keypad->client->dev, + "key[%d:%d] %s\n", row, col, release ? "release" : "press"); + + input_event(input_dev, EV_MSC, MSC_SCAN, code); + input_report_key(input_dev, keypad->keycodes[code], !release); + input_sync(input_dev); + + return IRQ_HANDLED; +} + +/* + + + + */ +static inline void max7359_fall_deepsleep(struct i2c_client *client) +{ + max7359_write_reg(client, MAX7359_REG_SLEEP, MAX7359_AUTOSLEEP_8192); +} + +/* + + + */ +static inline void max7359_take_catnap(struct i2c_client *client) +{ + max7359_write_reg(client, MAX7359_REG_SLEEP, MAX7359_AUTOSLEEP_256); +} + +static int max7359_open(struct input_dev *dev) +{ + struct max7359_keypad *keypad = input_get_drvdata(dev); + + max7359_take_catnap(keypad->client); + + return 0; +} + +static void max7359_close(struct input_dev *dev) +{ + struct max7359_keypad *keypad = input_get_drvdata(dev); + + max7359_fall_deepsleep(keypad->client); +} + +static void max7359_initialize(struct i2c_client *client) +{ + max7359_write_reg(client, MAX7359_REG_CONFIG, + MAX7359_CFG_INTERRUPT | /* */ + MAX7359_CFG_KEY_RELEASE | /* */ + MAX7359_CFG_WAKEUP); /* */ + + /* */ + max7359_write_reg(client, MAX7359_REG_DEBOUNCE, 0x1F); + + /* */ + max7359_write_reg(client, MAX7359_REG_INTERRUPT, 0x01); + + max7359_fall_deepsleep(client); +} + +static int __devinit max7359_probe(struct i2c_client *client, + const struct i2c_device_id *id) +{ + const struct matrix_keymap_data *keymap_data = client->dev.platform_data; + struct max7359_keypad *keypad; + struct input_dev *input_dev; + int ret; + int error; + + if (!client->irq) { + dev_err(&client->dev, "The irq number should not be zero\n"); + return -EINVAL; + } + + /* */ + ret = max7359_read_reg(client, MAX7359_REG_KEYFIFO); + if (ret < 0) { + dev_err(&client->dev, "failed to detect device\n"); + return -ENODEV; + } + + dev_dbg(&client->dev, "keys FIFO is 0x%02x\n", ret); + + keypad = kzalloc(sizeof(struct max7359_keypad), GFP_KERNEL); + input_dev = input_allocate_device(); + if (!keypad || !input_dev) { + dev_err(&client->dev, "failed to allocate memory\n"); + error = -ENOMEM; + goto failed_free_mem; + } + + keypad->client = client; + keypad->input_dev = input_dev; + + input_dev->name = client->name; + input_dev->id.bustype = BUS_I2C; + input_dev->open = max7359_open; + input_dev->close = max7359_close; + input_dev->dev.parent = &client->dev; + + input_dev->evbit[0] = BIT_MASK(EV_KEY) | BIT_MASK(EV_REP); + input_dev->keycodesize = sizeof(keypad->keycodes[0]); + input_dev->keycodemax = ARRAY_SIZE(keypad->keycodes); + input_dev->keycode = keypad->keycodes; + + input_set_capability(input_dev, EV_MSC, MSC_SCAN); + input_set_drvdata(input_dev, keypad); + + max7359_build_keycode(keypad, keymap_data); + + error = request_threaded_irq(client->irq, NULL, max7359_interrupt, + IRQF_TRIGGER_LOW | IRQF_ONESHOT, + client->name, keypad); + if (error) { + dev_err(&client->dev, "failed to register interrupt\n"); + goto failed_free_mem; + } + + /* */ + error = input_register_device(input_dev); + if (error) { + dev_err(&client->dev, "failed to register input device\n"); + goto failed_free_irq; + } + + /* */ + max7359_initialize(client); + + i2c_set_clientdata(client, keypad); + device_init_wakeup(&client->dev, 1); + + return 0; + +failed_free_irq: + free_irq(client->irq, keypad); +failed_free_mem: + input_free_device(input_dev); + kfree(keypad); + return error; +} + +static int __devexit max7359_remove(struct i2c_client *client) +{ + struct max7359_keypad *keypad = i2c_get_clientdata(client); + + free_irq(client->irq, keypad); + input_unregister_device(keypad->input_dev); + kfree(keypad); + + return 0; +} + +#ifdef CONFIG_PM +static int max7359_suspend(struct device *dev) +{ + struct i2c_client *client = to_i2c_client(dev); + + max7359_fall_deepsleep(client); + + if (device_may_wakeup(&client->dev)) + enable_irq_wake(client->irq); + + return 0; +} + +static int max7359_resume(struct device *dev) +{ + struct i2c_client *client = to_i2c_client(dev); + + if (device_may_wakeup(&client->dev)) + disable_irq_wake(client->irq); + + /* */ + max7359_take_catnap(client); + + return 0; +} +#endif + +static SIMPLE_DEV_PM_OPS(max7359_pm, max7359_suspend, max7359_resume); + +static const struct i2c_device_id max7359_ids[] = { + { "max7359", 0 }, + { } +}; +MODULE_DEVICE_TABLE(i2c, max7359_ids); + +static struct i2c_driver max7359_i2c_driver = { + .driver = { + .name = "max7359", + .pm = &max7359_pm, + }, + .probe = max7359_probe, + .remove = __devexit_p(max7359_remove), + .id_table = max7359_ids, +}; + +module_i2c_driver(max7359_i2c_driver); + +MODULE_AUTHOR("Kim Kyuwon "); +MODULE_DESCRIPTION("MAX7359 Key Switch Controller Driver"); +MODULE_LICENSE("GPL v2"); diff --git a/pool/shard002/C/0061797_gridify-4.c b/pool/shard002/C/0061797_gridify-4.c new file mode 100644 index 0000000000000000000000000000000000000000..c3fbdbf55d4afa6eaa3b031adc567d86f9feb28d --- /dev/null +++ b/pool/shard002/C/0061797_gridify-4.c @@ -0,0 +1,45 @@ +#define THE_LOOP \ + for (i = j + 1; i < n; i += 3) \ + a[i] = i + +void __attribute__((noinline, noclone)) +foo (int j, int n, int *a) +{ +#pragma omp parallel + { + #pragma omp single + { + int i; +#pragma omp target +#pragma omp teams +#pragma omp distribute parallel for shared(a) firstprivate(n) private(i) firstprivate(j) + THE_LOOP; + } + } +} + +void __attribute__((noinline, noclone)) +bar (int j, int n, int *a) +{ + int i; + THE_LOOP; +} + +int main (int argc, char **argv) +{ + int n = 32; + int *a = __builtin_malloc (sizeof (int) * n); + int *ref = __builtin_malloc (sizeof (int) * n); + int i, j = 4; + + __builtin_memset (a, 0, sizeof (int) * n); + __builtin_memset (ref, 0, sizeof (int) * n); + bar (j, n, ref); + foo (j, n, a); + for (i = 0; i < n; i ++) + { + if (a[i] != ref[i]) + __builtin_abort (); + } + return 0; +} diff --git a/pool/shard002/C/0061810_processor.c b/pool/shard002/C/0061810_processor.c new file mode 100644 index 0000000000000000000000000000000000000000..f3c0ebe262c8679bcfd9ccc6aad26e7d0a9d9972 --- /dev/null +++ b/pool/shard002/C/0061810_processor.c @@ -0,0 +1,213 @@ +/* + * Copyright IBM Corp. 2008 + * Author(s): Martin Schwidefsky (schwidefsky@de.ibm.com) + */ + +#define KMSG_COMPONENT "cpu" +#define pr_fmt(fmt) KMSG_COMPONENT ": " fmt + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +struct cpu_info +{ + unsigned int cpu_mhz_dynamic; + unsigned int cpu_mhz_static; + struct cpuid cpu_id; +}; + +static DEFINE_PER_CPU(struct cpu_info, cpu_info); + +static bool machine_has_cpu_mhz; + +void __init cpu_detect_mhz_feature(void) +{ + if (test_facility(34) && __ecag(ECAG_CPU_ATTRIBUTE, 0) != -1UL) + { + machine_has_cpu_mhz = 1; + } +} + +static void update_cpu_mhz(void *arg) +{ + unsigned long mhz; + struct cpu_info *c; + + mhz = __ecag(ECAG_CPU_ATTRIBUTE, 0); + c = this_cpu_ptr(&cpu_info); + c->cpu_mhz_dynamic = mhz >> 32; + c->cpu_mhz_static = mhz & 0xffffffff; +} + +void s390_update_cpu_mhz(void) +{ + s390_adjust_jiffies(); + + if (machine_has_cpu_mhz) + { + on_each_cpu(update_cpu_mhz, NULL, 0); + } +} + +void notrace cpu_relax(void) +{ + if (!smp_cpu_mtid && MACHINE_HAS_DIAG44) + { + diag_stat_inc(DIAG_STAT_X044); + asm volatile("diag 0,0,0x44"); + } + + barrier(); +} +EXPORT_SYMBOL(cpu_relax); + +/* + * cpu_init - initializes state that is per-CPU. + */ +void cpu_init(void) +{ + struct cpuid *id = this_cpu_ptr(&cpu_info.cpu_id); + + get_cpu_id(id); + + if (machine_has_cpu_mhz) + { + update_cpu_mhz(NULL); + } + + atomic_inc(&init_mm.mm_count); + current->active_mm = &init_mm; + BUG_ON(current->mm); + enter_lazy_tlb(&init_mm, current); +} + +/* + * cpu_have_feature - Test CPU features on module initialization + */ +int cpu_have_feature(unsigned int num) +{ + return elf_hwcap & (1UL << num); +} +EXPORT_SYMBOL(cpu_have_feature); + +static void show_cpu_summary(struct seq_file *m, void *v) +{ + static const char *hwcap_str[] = + { + "esan3", "zarch", "stfle", "msa", "ldisp", "eimm", "dfp", + "edat", "etf3eh", "highgprs", "te", "vx" + }; + static const char *const int_hwcap_str[] = + { + "sie" + }; + int i, cpu; + + seq_printf(m, "vendor_id : IBM/S390\n" + "# processors : %i\n" + "bogomips per cpu: %lu.%02lu\n", + num_online_cpus(), loops_per_jiffy / (500000 / HZ), + (loops_per_jiffy / (5000 / HZ)) % 100); + seq_printf(m, "max thread id : %d\n", smp_cpu_mtid); + seq_puts(m, "features\t: "); + + for (i = 0; i < ARRAY_SIZE(hwcap_str); i++) + if (hwcap_str[i] && (elf_hwcap & (1UL << i))) + { + seq_printf(m, "%s ", hwcap_str[i]); + } + + for (i = 0; i < ARRAY_SIZE(int_hwcap_str); i++) + if (int_hwcap_str[i] && (int_hwcap & (1UL << i))) + { + seq_printf(m, "%s ", int_hwcap_str[i]); + } + + seq_puts(m, "\n"); + show_cacheinfo(m); + for_each_online_cpu(cpu) + { + struct cpuid *id = &per_cpu(cpu_info.cpu_id, cpu); + + seq_printf(m, "processor %d: " + "version = %02X, " + "identification = %06X, " + "machine = %04X\n", + cpu, id->version, id->ident, id->machine); + } +} + +static void show_cpu_mhz(struct seq_file *m, unsigned long n) +{ + struct cpu_info *c = per_cpu_ptr(&cpu_info, n); + + seq_printf(m, "cpu MHz dynamic : %d\n", c->cpu_mhz_dynamic); + seq_printf(m, "cpu MHz static : %d\n", c->cpu_mhz_static); +} + +/* + * show_cpuinfo - Get information on one CPU for use by procfs. + */ +static int show_cpuinfo(struct seq_file *m, void *v) +{ + unsigned long n = (unsigned long) v - 1; + + if (!n) + { + show_cpu_summary(m, v); + } + + if (!machine_has_cpu_mhz) + { + return 0; + } + + seq_printf(m, "\ncpu number : %ld\n", n); + show_cpu_mhz(m, n); + return 0; +} + +static inline void *c_update(loff_t *pos) +{ + if (*pos) + { + *pos = cpumask_next(*pos - 1, cpu_online_mask); + } + + return *pos < nr_cpu_ids ? (void *)*pos + 1 : NULL; +} + +static void *c_start(struct seq_file *m, loff_t *pos) +{ + get_online_cpus(); + return c_update(pos); +} + +static void *c_next(struct seq_file *m, void *v, loff_t *pos) +{ + ++*pos; + return c_update(pos); +} + +static void c_stop(struct seq_file *m, void *v) +{ + put_online_cpus(); +} + +const struct seq_operations cpuinfo_op = +{ + .start = c_start, + .next = c_next, + .stop = c_stop, + .show = show_cpuinfo, +}; diff --git a/pool/shard002/C/0061821_findLambdaMax.c b/pool/shard002/C/0061821_findLambdaMax.c new file mode 100644 index 0000000000000000000000000000000000000000..92266bcc658f9bd3ad98bdf8a7b5326d8430ef07 --- /dev/null +++ b/pool/shard002/C/0061821_findLambdaMax.c @@ -0,0 +1,40 @@ +#include "mex.h" +#include +#include +#include +#include "altra.h" + + +/* + * ------------------------------------------------------------------- + * Function and parameter + * ------------------------------------------------------------------- + * + * findLambdaMax compute + * + * the lambda_{max} that achieves a zero solution for + * + * min 1/2 \|x-v\|^2 + \lambda_{\max} * \sum w_i \|x_{G_i}\|, + * + * where x is of dimension n, + * w_i >=0, and G_i's follow the tree structure + * + * The file is implemented in the following in Matlab: + * + * lambdaMax=findLambdaMax(v, n, ind,nodes); + */ + +void mexFunction (int nlhs, mxArray* plhs[], int nrhs, const mxArray* prhs[]){ + double* v = mxGetPr(prhs[0]); + int n = (int) mxGetScalar(prhs[1]); + double* ind = mxGetPr(prhs[2]); + int nodes = (int) mxGetScalar(prhs[3]); + + double *lambdaMax; + + /* set up output arguments */ + plhs[0] = mxCreateDoubleMatrix(1,1,mxREAL); + + lambdaMax = mxGetPr(plhs[0]); + findLambdaMax(lambdaMax,v,n,ind,nodes); +} \ No newline at end of file diff --git a/pool/shard002/C/0061827_dequant.c b/pool/shard002/C/0061827_dequant.c new file mode 100644 index 0000000000000000000000000000000000000000..65c340a1ce90a6daabaa3b69cd1a2d2aeb65e264 --- /dev/null +++ b/pool/shard002/C/0061827_dequant.c @@ -0,0 +1,215 @@ +/****************************************************************************** + * + * Copyright (C) 2014 The Android Open Source Project + * Copyright 2003 - 2004 Open Interface North America, Inc. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ******************************************************************************/ + +/********************************************************************************** + $Revision: #1 $ +***********************************************************************************/ + +/** + @file + + Dequantizer for SBC decoder; reconstructs quantized representation of subband samples. + + @ingroup codec_internal + */ + +/** +@addtogroup codec_internal +@{ +*/ + +/** + This function is a fixed-point approximation of a modification of the following + dequantization operation defined in the spec, as inferred from section 12.6.4: + + @code + dequant = 2^(scale_factor+1) * ((raw * 2.0 + 1.0) / ((2^bits) - 1) - 1) + + 2 <= bits <= 16 + 0 <= raw < (2^bits)-1 (the -1 is because quantized values with all 1's are forbidden) + + -65535 < dequant < 65535 + @endcode + + The code below computes the dequantized value divided by a scaling constant + equal to about 1.38. This constant is chosen to ensure that the entry in the + dequant_long_scaled table for 16 bits is as accurate as possible, since it has + the least relative precision available to it due to its small magnitude. + + This routine outputs in Q16.15 format. + + The helper array dequant_long is defined as follows: + + @code + dequant_long_long[bits] = round(2^31 * 1/((2^bits - 1) / 1.38...) for 2 <= bits <= 16 + @endcode + + + Additionally, the table entries have the following property: + + @code + dequant_long_scaled[bits] <= 2^31 / ((2^bits - 1)) for 2 <= bits <= 16 + @endcode + + Therefore + + @code + d = 2 * raw + 1 1 <= d <= 2^bits - 2 + + d' = d * dequant_long[bits] + + d * dequant_long_scaled[bits] <= (2^bits - 2) * (2^31 / (2^bits - 1)) + d * dequant_long_scaled[bits] <= 2^31 * (2^bits - 2)/(2^bits - 1) < 2^31 + @endcode + + Therefore, d' doesn't overflow a signed 32-bit value. + + @code + + d' =~ 2^31 * (raw * 2.0 + 1.0) / (2^bits - 1) / 1.38... + + result = d' - 2^31/1.38... =~ 2^31 * ((raw * 2.0 + 1.0) / (2^bits - 1) - 1) / 1.38... + + result is therefore a scaled approximation to dequant. It remains only to + turn 2^31 into 2^(scale_factor+1). Since we're aiming for Q16.15 format, + this is achieved by shifting right by (15-scale_factor): + + (2^31 * x) >> (15-scale_factor) =~ 2^(31-15+scale_factor) * x = 2^15 * 2^(1+scale_factor) * x + @endcode + + */ + +#include "bt_target.h" +#include + +#if (defined(SBC_DEC_INCLUDED) && SBC_DEC_INCLUDED == TRUE) + +#ifndef SBC_DEQUANT_LONG_SCALED_OFFSET +#define SBC_DEQUANT_LONG_SCALED_OFFSET 1555931970 +#endif + +#ifndef SBC_DEQUANT_LONG_UNSCALED_OFFSET +#define SBC_DEQUANT_LONG_UNSCALED_OFFSET 2147483648 +#endif + +#ifndef SBC_DEQUANT_SCALING_FACTOR +#define SBC_DEQUANT_SCALING_FACTOR 1.38019122262781f +#endif + +const OI_UINT32 dequant_long_scaled[17]; +const OI_UINT32 dequant_long_unscaled[17]; + +/** Scales x by y bits to the right, adding a rounding factor. + */ +#ifndef SCALE +#define SCALE(x, y) (((x) + (1 <<((y)-1))) >> (y)) +#endif + +#ifdef DEBUG_DEQUANTIZATION + +#include + +INLINE float dequant_float(OI_UINT32 raw, OI_UINT scale_factor, OI_UINT bits) +{ + float result = (1 << (scale_factor + 1)) * ((raw * 2.0f + 1.0f) / ((1 << bits) - 1.0f) - 1.0f); + + result /= SBC_DEQUANT_SCALING_FACTOR; + + /* Unless the encoder screwed up, all correct dequantized values should + * satisfy this inequality. Non-compliant encoders which generate quantized + * values with all 1-bits set can, theoretically, trigger this assert. This + * is unlikely, however, and only an issue in debug mode. + */ + OI_ASSERT(fabs(result) < 32768 * 1.6); + + return result; +} + +#endif + + +INLINE OI_INT32 OI_SBC_Dequant(OI_UINT32 raw, OI_UINT scale_factor, OI_UINT bits) +{ + OI_UINT32 d; + OI_INT32 result; + + OI_ASSERT(scale_factor <= 15); + OI_ASSERT(bits <= 16); + + if (bits <= 1) { + return 0; + } + + d = (raw * 2) + 1; + d *= dequant_long_scaled[bits]; + result = d - SBC_DEQUANT_LONG_SCALED_OFFSET; + +#ifdef DEBUG_DEQUANTIZATION + { + OI_INT32 integerized_float_result; + float float_result; + + float_result = dequant_float(raw, scale_factor, bits); + integerized_float_result = (OI_INT32)floor(0.5f + float_result * (1 << 15)); + + /* This detects overflow */ + OI_ASSERT(((result >= 0) && (integerized_float_result >= 0)) || + ((result <= 0) && (integerized_float_result <= 0))); + } +#endif + return result >> (15 - scale_factor); +} + +/* This version of Dequant does not incorporate the scaling factor of 1.38. It + * is intended for use with implementations of the filterbank which are + * hard-coded into a DSP. Output is Q16.4 format, so that after joint stereo + * processing (which leaves the most significant bit equal to the sign bit if + * the encoder is conformant) the result will fit a 24 bit fixed point signed + * value.*/ + +INLINE OI_INT32 OI_SBC_Dequant_Unscaled(OI_UINT32 raw, OI_UINT scale_factor, OI_UINT bits) +{ + OI_UINT32 d; + OI_INT32 result; + + OI_ASSERT(scale_factor <= 15); + OI_ASSERT(bits <= 16); + + + if (bits <= 1) { + return 0; + } + if (bits == 16) { + result = (raw << 16) + raw - 0x7fff7fff; + return SCALE(result, 24 - scale_factor); + } + + + d = (raw * 2) + 1; + d *= dequant_long_unscaled[bits]; + result = d - 0x80000000; + + return SCALE(result, 24 - scale_factor); +} + +/** +@} +*/ + +#endif /* #if (defined(SBC_DEC_INCLUDED) && SBC_DEC_INCLUDED == TRUE) */ diff --git a/pool/shard002/C/0061830_ffmetaenc.c b/pool/shard002/C/0061830_ffmetaenc.c new file mode 100644 index 0000000000000000000000000000000000000000..800fb1887c6f981eeca29bf3b27220faf88b4d85 --- /dev/null +++ b/pool/shard002/C/0061830_ffmetaenc.c @@ -0,0 +1,98 @@ +/* + * Metadata muxer + * Copyright (c) 2010 Anton Khirnov + * + * 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 "avformat.h" +#include "ffmeta.h" +#include "libavutil/dict.h" + + +static void write_escape_str(AVIOContext *s, const uint8_t *str) +{ + const uint8_t *p = str; + + while (*p) { + if (*p == '#' || *p == ';' || *p == '=' || *p == '\\' || *p == '\n') + avio_w8(s, '\\'); + avio_w8(s, *p); + p++; + } +} + +static void write_tags(AVIOContext *s, AVDictionary *m) +{ + AVDictionaryEntry *t = NULL; + while ((t = av_dict_get(m, "", t, AV_DICT_IGNORE_SUFFIX))) { + write_escape_str(s, t->key); + avio_w8(s, '='); + write_escape_str(s, t->value); + avio_w8(s, '\n'); + } +} + +static int write_header(AVFormatContext *s) +{ + avio_write(s->pb, ID_STRING, sizeof(ID_STRING) - 1); + avio_w8(s->pb, '1'); // version + avio_w8(s->pb, '\n'); + return 0; +} + +static int write_trailer(AVFormatContext *s) +{ + int i; + + write_tags(s->pb, s->metadata); + + for (i = 0; i < s->nb_streams; i++) { + avio_write(s->pb, ID_STREAM, sizeof(ID_STREAM) - 1); + avio_w8(s->pb, '\n'); + write_tags(s->pb, s->streams[i]->metadata); + } + + for (i = 0; i < s->nb_chapters; i++) { + AVChapter *ch = s->chapters[i]; + avio_write(s->pb, ID_CHAPTER, sizeof(ID_CHAPTER) - 1); + avio_w8(s->pb, '\n'); + avio_printf(s->pb, "TIMEBASE=%d/%d\n", ch->time_base.num, ch->time_base.den); + avio_printf(s->pb, "START=%"PRId64"\n", ch->start); + avio_printf(s->pb, "END=%"PRId64"\n", ch->end); + write_tags(s->pb, ch->metadata); + } + + return 0; +} + +static int write_packet(AVFormatContext *s, AVPacket *pkt) +{ + return 0; +} + +AVOutputFormat ff_ffmetadata_muxer = { + .name = "ffmetadata", + .long_name = NULL_IF_CONFIG_SMALL("FFmpeg metadata in text"), + .extensions = "ffmeta", + .write_header = write_header, + .write_packet = write_packet, + .write_trailer = write_trailer, + .flags = AVFMT_NOTIMESTAMPS | AVFMT_NOSTREAMS, +}; diff --git a/pool/shard002/C/0061836_pawns.c b/pool/shard002/C/0061836_pawns.c new file mode 100644 index 0000000000000000000000000000000000000000..9bf7eec3bb7c4c65f62119a0308dba6e38a9bf5e --- /dev/null +++ b/pool/shard002/C/0061836_pawns.c @@ -0,0 +1,75 @@ +#include "pieces/walks/pawns/pawns.h" +#include "pieces/walks/pawns/en_passant.h" +#include "solving/move_generator.h" +#include "solving/move_effect_journal.h" +#include "debugging/trace.h" + +#include "debugging/assert.h" + +void pawns_generate_ep_capture_move(square sq_arrival_singlestep) +{ + TraceFunctionEntry(__func__); + TraceSquare(sq_arrival_singlestep); + TraceFunctionParamListEnd(); + + if (get_walk_of_piece_on_square(curr_generation->departure)!=Orphan /* orphans cannot capture ep */ + && en_passant_is_capture_possible_to(trait[nbply],sq_arrival_singlestep)) + { + square const sq_capture = en_passant_find_capturee(); + if (sq_capture!=initsquare) + push_special_move(offset_en_passant_capture+sq_capture); + } + + TraceFunctionExit(__func__); + TraceFunctionResultEnd(); +} + +/* generates move of a pawn of side camp on departure capturing a piece on + * arrival + */ +void pawns_generate_capture_move(numvec dir) +{ + TraceFunctionEntry(__func__); + TraceFunctionParamListEnd(); + + curr_generation->arrival = curr_generation->departure+dir; + + if (piece_belongs_to_opponent(curr_generation->arrival)) + push_move(); + else + pawns_generate_ep_capture_move(curr_generation->arrival); + + TraceFunctionExit(__func__); + TraceFunctionResultEnd(); +} + +/* generates moves of a pawn in direction dir where steps single steps are + * possible. + */ +void pawns_generate_nocapture_moves(numvec dir, int steps) +{ + TraceFunctionEntry(__func__); + TraceFunctionParam("%d",dir); + TraceFunctionParam("%d",steps); + TraceFunctionParamListEnd(); + + curr_generation->arrival = curr_generation->departure+dir; + + if (is_square_empty(curr_generation->arrival)) + { + push_move(); + curr_generation->arrival += dir; + + while (--steps>0) + if (is_square_empty(curr_generation->arrival)) + { + push_special_move(pawn_multistep); + curr_generation->arrival += dir; + } + else + break; + } + + TraceFunctionExit(__func__); + TraceFunctionResultEnd(); +} diff --git a/pool/shard002/C/0061851_mu_trig_trgfile.c b/pool/shard002/C/0061851_mu_trig_trgfile.c new file mode 100644 index 0000000000000000000000000000000000000000..4b3e52c84dd8b18f3343837795715e7e8f0314c9 --- /dev/null +++ b/pool/shard002/C/0061851_mu_trig_trgfile.c @@ -0,0 +1,59 @@ +/**************************************************************** + * * + * Copyright 2010 Fidelity Information Services, 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_string.h" +#include "cli.h" +#include +#include "mu_gv_stack_init.h" +#include "trigger_trgfile_protos.h" +#include "mu_trig_trgfile.h" +#include "mupip_exit.h" + +GBLREF boolean_t skip_dbtriggers; /* see gbldefs.c for description of this global */ +GBLREF IN_PARMS *cli_lex_in_ptr; +GBLREF boolean_t is_replicator; +GBLREF int tprestart_state; + +void mu_trig_trgfile(char *trigger_filename, int trigger_filename_len, boolean_t noprompt) +{ + IN_PARMS *cli_lex_in_ptr_save = NULL; + boolean_t trigger_error; + + error_def(ERR_MUNOACTION); + + is_replicator = TRUE; + /* Since ^#t global is the ONLY global that is touched by MUPIP TRIGGERS and we currently dont support triggers + * on ^#t global, it is safe to set skip_dbtriggers to TRUE for this process. This is in fact needed so we + * skip cdb_sc_triggermod processing in t_end and tp_tend as otherwise that could cause unnecessary restarts in + * journal recovery and update process which at least the former is not designed to handle. + */ + skip_dbtriggers = TRUE; + mu_gv_stack_init(); + if (NULL != cli_lex_in_ptr) + { + cli_lex_in_ptr_save = (IN_PARMS *)malloc(SIZEOF(IN_PARMS) + cli_lex_in_ptr->buflen); + cli_lex_in_ptr_save->argc = cli_lex_in_ptr->argc; + cli_lex_in_ptr_save->argv = cli_lex_in_ptr->argv; + cli_lex_in_ptr_save->tp = cli_lex_in_ptr_save->in_str + (cli_lex_in_ptr->tp - cli_lex_in_ptr->in_str); + cli_lex_in_ptr_save->buflen = cli_lex_in_ptr->buflen; + memcpy(cli_lex_in_ptr_save->in_str, cli_lex_in_ptr->in_str, cli_lex_in_ptr->buflen); + } else + cli_lex_in_ptr_save = NULL; + trigger_error = trigger_trgfile_tpwrap(trigger_filename, trigger_filename_len, noprompt); + if (NULL != cli_lex_in_ptr) + free(cli_lex_in_ptr); + cli_lex_in_ptr = cli_lex_in_ptr_save; + if (trigger_error) + mupip_exit(ERR_MUNOACTION); +} diff --git a/pool/shard002/C/0061859_up_buttons.c b/pool/shard002/C/0061859_up_buttons.c new file mode 100644 index 0000000000000000000000000000000000000000..e7aa92e7b981bee8ad9558f3c93574320a94c04d --- /dev/null +++ b/pool/shard002/C/0061859_up_buttons.c @@ -0,0 +1,172 @@ +/**************************************************************************** + * configs/stm3220g-eval/src/board_buttons.c + * + * Copyright (C) 2012, 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 "stm3220g-internal.h" + +#ifdef CONFIG_ARCH_BUTTONS + +/**************************************************************************** + * Definitions + ****************************************************************************/ + +/**************************************************************************** + * Private Data + ****************************************************************************/ + +/**************************************************************************** + * Private Functions + ****************************************************************************/ + +/* Pin configuration for each STM3210E-EVAL button. This array is indexed by + * the BUTTON_* and JOYSTICK_* definitions in board.h + */ + +static const uint16_t g_buttons[NUM_BUTTONS] = +{ + GPIO_BTN_WAKEUP, GPIO_BTN_TAMPER, GPIO_BTN_USER +}; + +/**************************************************************************** + * Public Functions + ****************************************************************************/ + +/**************************************************************************** + * Name: board_button_initialize + * + * Description: + * board_button_initialize() must be called to initialize button resources. After + * that, board_buttons() may be called to collect the current state of all + * buttons or board_button_irq() may be called to register button interrupt + * handlers. + * + ****************************************************************************/ + +void board_button_initialize(void) +{ + int i; + + /* Configure the GPIO pins as inputs. NOTE that EXTI interrupts are + * configured for all pins. + */ + + for (i = 0; i < NUM_BUTTONS; i++) + { + stm32_configgpio(g_buttons[i]); + } +} + +/**************************************************************************** + * Name: board_buttons + ****************************************************************************/ + +uint8_t board_buttons(void) +{ + uint8_t ret = 0; + int i; + + /* Check that state of each key */ + + for (i = 0; i < NUM_BUTTONS; i++) + { + /* A LOW value means that the key is pressed for most keys. The exception + * is the WAKEUP button. + */ + + bool released = stm32_gpioread(g_buttons[i]); + if (i == BUTTON_WAKEUP) + { + released = !released; + } + + /* Accumulate the set of depressed (not released) keys */ + + if (!released) + { + ret |= (1 << i); + } + } + + return ret; +} + +/************************************************************************************ + * Button support. + * + * Description: + * board_button_initialize() must be called to initialize button resources. After + * that, board_buttons() may be called to collect the current state of all + * buttons or board_button_irq() may be called to register button interrupt + * handlers. + * + * After board_button_initialize() has been called, board_buttons() may be called to + * collect the state of all buttons. board_buttons() returns an 8-bit bit set + * with each bit associated with a button. See the BUTTON_*_BIT + * definitions in board.h for the meaning of each bit. + * + * board_button_irq() may be called to register an interrupt handler that will + * be called when a button is depressed or released. The ID value is a + * button enumeration value that uniquely identifies a button resource. See the + * BUTTON_* definitions in board.h for the meaning of enumeration + * value. The previous interrupt handler address is returned (so that it may + * restored, if so desired). + * + ************************************************************************************/ + +#ifdef CONFIG_ARCH_IRQBUTTONS +xcpt_t board_button_irq(int id, xcpt_t irqhandler) +{ + xcpt_t oldhandler = NULL; + + /* The following should be atomic */ + + if (id >= MIN_IRQBUTTON && id <= MAX_IRQBUTTON) + { + oldhandler = stm32_gpiosetevent(g_buttons[id], true, true, true, irqhandler); + } + return oldhandler; +} +#endif +#endif /* CONFIG_ARCH_BUTTONS */ diff --git a/pool/shard002/C/0061874_atarimouse.c b/pool/shard002/C/0061874_atarimouse.c new file mode 100644 index 0000000000000000000000000000000000000000..f13c6be783887c13ac8eaa067247ad034f0c5ae0 --- /dev/null +++ b/pool/shard002/C/0061874_atarimouse.c @@ -0,0 +1,168 @@ +/* + * Atari mouse driver for Linux/m68k + * + * Copyright (c) 2005 Michael Schmitz + * + * Based on: + * Amiga mouse driver for Linux/m68k + * + * Copyright (c) 2000-2002 Vojtech Pavlik + * + */ +/* + * The low level init and interrupt stuff is handled in arch/mm68k/atari/atakeyb.c + * (the keyboard ACIA also handles the mouse and joystick data, and the keyboard + * interrupt is shared with the MIDI ACIA so MIDI data also get handled there). + * This driver only deals with handing key events off to the input layer. + * + * Largely based on the old: + * + * Atari Mouse Driver for Linux + * by Robert de Vries (robert@and.nl) 19Jul93 + * + * 16 Nov 1994 Andreas Schwab + * Compatibility with busmouse + * Support for three button mouse (shamelessly stolen from MiNT) + * third button wired to one of the joystick directions on joystick 1 + * + * 1996/02/11 Andreas Schwab + * Module support + * Allow multiple open's + * + * Converted to use new generic busmouse code. 5 Apr 1998 + * Russell King + */ + + +/* + * 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 + +MODULE_AUTHOR("Michael Schmitz "); +MODULE_DESCRIPTION("Atari mouse driver"); +MODULE_LICENSE("GPL"); + +static int mouse_threshold[2] = {2, 2}; +module_param_array(mouse_threshold, int, NULL, 0); + +#ifdef FIXED_ATARI_JOYSTICK + extern int atari_mouse_buttons; +#endif + +static struct input_dev *atamouse_dev; + +static void atamouse_interrupt(char *buf) +{ + int buttons, dx, dy; + + buttons = (buf[0] & 1) | ((buf[0] & 2) << 1); +#ifdef FIXED_ATARI_JOYSTICK + buttons |= atari_mouse_buttons & 2; + atari_mouse_buttons = buttons; +#endif + + /* only relative events get here */ + dx = buf[1]; + dy = buf[2]; + + input_report_rel(atamouse_dev, REL_X, dx); + input_report_rel(atamouse_dev, REL_Y, dy); + + input_report_key(atamouse_dev, BTN_LEFT, buttons & 0x4); + input_report_key(atamouse_dev, BTN_MIDDLE, buttons & 0x2); + input_report_key(atamouse_dev, BTN_RIGHT, buttons & 0x1); + + input_sync(atamouse_dev); + + return; +} + +static int atamouse_open(struct input_dev *dev) +{ +#ifdef FIXED_ATARI_JOYSTICK + atari_mouse_buttons = 0; +#endif + ikbd_mouse_y0_top(); + ikbd_mouse_thresh(mouse_threshold[0], mouse_threshold[1]); + ikbd_mouse_rel_pos(); + atari_input_mouse_interrupt_hook = atamouse_interrupt; + + return 0; +} + +static void atamouse_close(struct input_dev *dev) +{ + ikbd_mouse_disable(); + atari_input_mouse_interrupt_hook = NULL; +} + +static int __init atamouse_init(void) +{ + int error; + + if (!MACH_IS_ATARI || !ATARIHW_PRESENT(ST_MFP)) + { + return -ENODEV; + } + + error = atari_keyb_init(); + + if (error) + { + return error; + } + + atamouse_dev = input_allocate_device(); + + if (!atamouse_dev) + { + return -ENOMEM; + } + + atamouse_dev->name = "Atari mouse"; + atamouse_dev->phys = "atamouse/input0"; + atamouse_dev->id.bustype = BUS_HOST; + atamouse_dev->id.vendor = 0x0001; + atamouse_dev->id.product = 0x0002; + atamouse_dev->id.version = 0x0100; + + atamouse_dev->evbit[0] = BIT_MASK(EV_KEY) | BIT_MASK(EV_REL); + atamouse_dev->relbit[0] = BIT_MASK(REL_X) | BIT_MASK(REL_Y); + atamouse_dev->keybit[BIT_WORD(BTN_LEFT)] = BIT_MASK(BTN_LEFT) | + BIT_MASK(BTN_MIDDLE) | BIT_MASK(BTN_RIGHT); + + atamouse_dev->open = atamouse_open; + atamouse_dev->close = atamouse_close; + + error = input_register_device(atamouse_dev); + + if (error) + { + input_free_device(atamouse_dev); + return error; + } + + return 0; +} + +static void __exit atamouse_exit(void) +{ + input_unregister_device(atamouse_dev); +} + +module_init(atamouse_init); +module_exit(atamouse_exit); diff --git a/pool/shard002/C/0061877_konami.c b/pool/shard002/C/0061877_konami.c new file mode 100644 index 0000000000000000000000000000000000000000..1b317f349ce2b2306bf1adc4d98ebfa2e8ec1eaa --- /dev/null +++ b/pool/shard002/C/0061877_konami.c @@ -0,0 +1,67 @@ +/*************************************************************************** + + The Konami_1 CPU is a 6809 with opcodes scrambled. Here is how to + descramble them. + +***************************************************************************/ + +#include "driver.h" + + +UINT8 *konami1_decrypted; + +UINT8 konami1_decodebyte( UINT8 opcode, unsigned short address ) +{ +/* +> +> CPU_D7 = (EPROM_D7 & ~ADDRESS_1) | (~EPROM_D7 & ADDRESS_1) > +> CPU_D6 = EPROM_D6 +> +> CPU_D5 = (EPROM_D5 & ADDRESS_1) | (~EPROM_D5 & ~ADDRESS_1) > +> CPU_D4 = EPROM_D4 +> +> CPU_D3 = (EPROM_D3 & ~ADDRESS_3) | (~EPROM_D3 & ADDRESS_3) > +> CPU_D2 = EPROM_D2 +> +> CPU_D1 = (EPROM_D1 & ADDRESS_3) | (~EPROM_D1 & ~ADDRESS_3) > +> CPU_D0 = EPROM_D0 +> +*/ + UINT8 xormask; + + + xormask = 0; + if (address & 0x02) xormask |= 0x80; + else xormask |= 0x20; + if (address & 0x08) xormask |= 0x08; + else xormask |= 0x02; + + return opcode ^ xormask; +} + + + +static void decode(int cpu) +{ + UINT8 *rom = memory_region(REGION_CPU1+cpu); + int size = memory_region_length(REGION_CPU1+cpu); + int A; + + konami1_decrypted = auto_malloc(size); + memory_set_decrypted_region(cpu, 0x0000, 0xffff, konami1_decrypted); + + for (A = 0;A < size;A++) + { + konami1_decrypted[A] = konami1_decodebyte(rom[A],A); + } +} + +void konami1_decode(void) +{ + decode(0); +} + +void konami1_decode_cpu2(void) +{ + decode(1); +} diff --git a/pool/shard002/C/0061888_j-log-files.c b/pool/shard002/C/0061888_j-log-files.c new file mode 100644 index 0000000000000000000000000000000000000000..4983c151033e5fea90ef29c31193d1f785c299c8 --- /dev/null +++ b/pool/shard002/C/0061888_j-log-files.c @@ -0,0 +1,122 @@ +/* + * + * j-chkmail - Mail Server Filter for sendmail + * + * Copyright (c) 2001-2017 - Jose-Marcio Martins da Cruz + * + * Auteur : Jose Marcio Martins da Cruz + * jose.marcio.mc@gmail.org + * + * Historique : + * Creation : Tue Jan 17 14:47:25 CET 2006 + * + * This program is free software, but with restricted license : + * + * - j-chkmail is distributed only to registered users + * - j-chkmail license is available only non-commercial applications, + * this means, you can use j-chkmail if you make no profit with it. + * - redistribution of j-chkmail in any way : binary, source in any + * media, is forbidden + * + * 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. + * + * More details about j-chkmail license can be found at j-chkmail + * web site : http://foss.jose-marcio.org + */ + + +#include +#include +#include +#include + + +/****************************************************************************** + * * + * * + ******************************************************************************/ +static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; + +static LOG_T logt = LOG_INITIALIZER; + +/****************************************************************************** + * * + * * + ******************************************************************************/ +bool +log_attached_files_reopen() +{ + bool res = TRUE; + + MUTEX_LOCK(&mutex); + + if (!log_ready(&logt)) + { + char path[1024]; + char *wkdir = cf_get_str(CF_WORKDIR); + char *logname = cf_get_str(CF_XFILES_LOG_FILE); + + ADJUST_LOG_NAME(path, logname, wkdir, "none:"); + + res = log_open(&logt, path); + } else + res = log_reopen(&logt); + + MUTEX_UNLOCK(&mutex); + + return res; +} + +/****************************************************************************** + * * + * * + ******************************************************************************/ +bool +log_attached_files(id, ip, files) + char *id; + char *ip; + attachment_T *files; +{ + attachment_T *p; + time_t t = time(NULL); + int r; + + char ipbuf[SZ_IP]; + + bool res = TRUE; + + if (id == NULL) + id = "00000000.000"; + + if (!log_ready(&logt) && !log_attached_files_reopen()) + return FALSE; + + snprintf(ipbuf, sizeof (ipbuf), "%s", STRNULL(ip, "0.0.0.0")); + + MUTEX_LOCK(&mutex); + + if (log_ready(&logt)) + { + p = files; + while (p != NULL) + { + char *serror = "???"; + + if ((p->name == NULL) || (strlen(p->name) == 0)) + continue; + + serror = STRBOOL(p->xfile, "XXX", "---"); + log_printf(&logt, "%10ld %-12s ADDR=(%s) CLASS=(%s) MIME=(%s) %s\n", + (long) t, id, ipbuf, serror, + STRNULL(p->mimetype, "mime-unknown"), p->name); + p = p->next; + } + } + +fin: + MUTEX_UNLOCK(&mutex); + + return res; +} diff --git a/pool/shard002/C/0061890_fputwc.c b/pool/shard002/C/0061890_fputwc.c new file mode 100644 index 0000000000000000000000000000000000000000..56c9b399ca90861474ff6871df14be808b95a43c --- /dev/null +++ b/pool/shard002/C/0061890_fputwc.c @@ -0,0 +1,113 @@ +/* + Copyright (c) 2010 - 2012, 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 that accompanies this + distribution. The full text of the license may be found at + http://opensource.org/licenses/bsd-license. + + THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS, + WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED. + + * Copyright (c)2001 Citrus Project, + * 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 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. + * + * $Citrus$ + +NetBSD: fputwc.c,v 1.4 2005/06/12 05:21:27 lukem Exp +*/ +#include +#include + +#include +#include +#include +#include +#include +#include "reentrant.h" +#include "local.h" +#include "fvwrite.h" + +wint_t +__fputwc_unlock(wchar_t wc, FILE *fp) +{ + struct wchar_io_data *wcio; + mbstate_t *st; + size_t size; + char buf[MB_LEN_MAX]; + struct __suio uio; + struct __siov iov; + + _DIAGASSERT(fp != NULL); + if(fp == NULL) { + errno = EINVAL; + return (WEOF); + } + + /* LINTED we don't play with buf */ + iov.iov_base = (void *)buf; + uio.uio_iov = &iov; + uio.uio_iovcnt = 1; + + _SET_ORIENTATION(fp, 1); + wcio = WCIO_GET(fp); + if (wcio == 0) { + errno = ENOMEM; + return WEOF; + } + + wcio->wcio_ungetwc_inbuf = 0; + st = &wcio->wcio_mbstate_out; + + size = wcrtomb(buf, wc, st); + if (size == (size_t)-1) { + return WEOF; + } + + _DIAGASSERT(size != 0); + + uio.uio_resid = (int)(iov.iov_len = size); + if (__sfvwrite(fp, &uio)) { + return WEOF; + } + + return (wint_t)wc; +} + +wint_t +fputwc(wchar_t wc, FILE *fp) +{ + wint_t r; + + _DIAGASSERT(fp != NULL); + if(fp == NULL) { + errno = EINVAL; + return (WEOF); + } + + FLOCKFILE(fp); + r = __fputwc_unlock(wc, fp); + FUNLOCKFILE(fp); + + return (r); +} diff --git a/pool/shard002/C/0061891_acpi_tables.c b/pool/shard002/C/0061891_acpi_tables.c new file mode 100644 index 0000000000000000000000000000000000000000..c0d086229fec8b45e25c9260ab34d3d84004e5ff --- /dev/null +++ b/pool/shard002/C/0061891_acpi_tables.c @@ -0,0 +1,71 @@ +/* + * This file is part of the coreboot project. + * + * Written by Stefan Reinauer . + * ACPI FADT, FACS, and DSDT table support added by + * + * Copyright (C) 2004 Stefan Reinauer + * Copyright (C) 2005 Nick Barker + * Copyright (C) 2007 Rudolf Marek + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; version 2 of the License. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ + +#include +#include +#include +#include +#include +#include +#include +#include "southbridge/via/vt8237r/vt8237r.h" +#include "southbridge/via/k8t890/k8t890.h" +#include "northbridge/amd/amdk8/acpi.h" +#include +#include + +void get_bus_conf(void) +{ + /* FIXME: implement this. */ +} + +unsigned long acpi_fill_madt(unsigned long current) +{ + unsigned int gsi_base = 0x18; + + /* Create all subtables for processors. */ + current = acpi_create_madt_lapics(current); + + /* Write SB IOAPIC. */ + current += acpi_create_madt_ioapic((acpi_madt_ioapic_t *) current, + VT8237R_APIC_ID, IO_APIC_ADDR, 0); + + /* Write NB IOAPIC. */ + current += acpi_create_madt_ioapic((acpi_madt_ioapic_t *) current, + K8T890_APIC_ID, K8T890_APIC_BASE, gsi_base); + + /* IRQ9 ACPI active low. */ + current += acpi_create_madt_irqoverride((acpi_madt_irqoverride_t *) + current, 0, 9, 9, MP_IRQ_TRIGGER_LEVEL | MP_IRQ_POLARITY_LOW); + + /* IRQ0 -> APIC IRQ2. */ + current += acpi_create_madt_irqoverride((acpi_madt_irqoverride_t *) + current, 0, 0, 2, 0x0); + + /* Create all subtables for processors. */ + current = acpi_create_madt_lapic_nmis(current, + MP_IRQ_TRIGGER_EDGE | MP_IRQ_POLARITY_HIGH, 1); + + return current; +} diff --git a/pool/shard002/C/0061905_utilities.c b/pool/shard002/C/0061905_utilities.c new file mode 100644 index 0000000000000000000000000000000000000000..4e82c31640da75583a9be86ac71d2a13d21a1a26 --- /dev/null +++ b/pool/shard002/C/0061905_utilities.c @@ -0,0 +1,110 @@ +/* + * Copyright (c) 1980, 1986, 1993 + * 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. + * 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. + */ + +#if 0 +#ifndef lint +static const char sccsid[] = "@(#)utilities.c 8.6 (Berkeley) 5/19/95"; +#endif /* not lint */ +#endif +#include +__FBSDID("$FreeBSD$"); + +#include +#include +#include + +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "fsck.h" + + +char * +blockcheck(char *origname) +{ + struct stat stblock; + char *newname, *cp; + struct fstab *fsinfo; + int retried = 0, len; + static char device[MAXPATHLEN]; + + newname = origname; + if (stat(newname, &stblock) < 0) { + cp = strrchr(newname, '/'); + if (cp == 0) { + (void)snprintf(device, sizeof(device), "%s%s", + _PATH_DEV, newname); + newname = device; + } + } +retry: + if (stat(newname, &stblock) < 0) { + printf("Can't stat %s: %s\n", newname, strerror(errno)); + return (origname); + } + switch(stblock.st_mode & S_IFMT) { + case S_IFCHR: + case S_IFBLK: + return(newname); + case S_IFDIR: + if (retried) + break; + + len = strlen(origname) - 1; + if (len > 0 && origname[len] == '/') + /* remove trailing slash */ + origname[len] = '\0'; + if ((fsinfo = getfsfile(origname)) == NULL) { + printf( + "Can't resolve %s to character special device.\n", + origname); + return (origname); + } + newname = fsinfo->fs_spec; + retried++; + goto retry; + } + /* + * Not a block or character device, just return name and + * let the user decide whether to use it. + */ + return (origname); +} + diff --git a/pool/shard002/C/0061906_passage_file.c b/pool/shard002/C/0061906_passage_file.c new file mode 100644 index 0000000000000000000000000000000000000000..497fbd332b7f6c8ae4122838a6c3f47490e6bdae --- /dev/null +++ b/pool/shard002/C/0061906_passage_file.c @@ -0,0 +1,71 @@ +//******************************************************************************************** +//* +//* This file is part of Egoboo. +//* +//* Egoboo 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. +//* +//* Egoboo 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 Egoboo. If not, see . +//* +//******************************************************************************************** + +/// @file file_formats/passage_file.c +/// @brief A scanner for the passage file for a given module ( /modules/*.mod/basicdat/passages.txt ) +/// @details + +#include "passage_file.h" + +#include "mpd_file.h" + +#include "egoboo_fileutil.h" + +//-------------------------------------------------------------------------------------------- +passage_t * passage_init( passage_t * ppass ) +{ + if ( NULL == ppass ) return ppass; + + memset( ppass, 0, sizeof( *ppass ) ); + + ppass->music = NO_MUSIC; // Set no song as default + + return ppass; +} + +//-------------------------------------------------------------------------------------------- +bool_t scan_passage_file( vfs_FILE * fileread, passage_t * ppass ) +{ + /// @details ZZ@> This function reads the passage file + + bool_t found; + + if ( NULL == fileread || NULL == ppass ) return bfalse; + + passage_init( ppass ); + + found = bfalse; + if ( goto_colon( NULL, fileread, btrue ) ) + { + ppass->area.left = fget_int( fileread ); + ppass->area.top = fget_int( fileread ); + ppass->area.right = fget_int( fileread ); + ppass->area.bottom = fget_int( fileread ); + + ppass->open = fget_bool( fileread ); + + ppass->mask = MPDFX_IMPASS | MPDFX_WALL; + if ( fget_bool( fileread ) ) ppass->mask = MPDFX_IMPASS; + if ( fget_bool( fileread ) ) ppass->mask = MPDFX_SLIPPY; + + found = btrue; + } + + return found; +} \ No newline at end of file diff --git a/pool/shard002/C/0061917_main.c b/pool/shard002/C/0061917_main.c new file mode 100644 index 0000000000000000000000000000000000000000..2f06ab44e2466e31fe54ec64cf803689b697c6dd --- /dev/null +++ b/pool/shard002/C/0061917_main.c @@ -0,0 +1,363 @@ +/** + ****************************************************************************** + * @file RCC/RCC_ClockConfig/Src/main.c + * @author MCD Application Team + * @version V1.2.3 + * @date 09-October-2015 + * @brief This example describes how to use the RCC HAL API to configure the + * system clock (SYSCLK) and modify the clock settings on run time. + ****************************************************************************** + * @attention + * + *

© 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 "main.h" + +/** @addtogroup STM32F4xx_HAL_Examples + * @{ + */ + +/** @addtogroup RCC_ClockConfig + * @{ + */ + +/* Private typedef -----------------------------------------------------------*/ +/* Private define ------------------------------------------------------------*/ +/* Private macro -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +static RCC_ClkInitTypeDef RCC_ClkInitStruct; +static RCC_OscInitTypeDef RCC_OscInitStruct; + +/* Private function prototypes -----------------------------------------------*/ +static void SystemClockHSI_Config(void); +static void SystemClockHSE_Config(void); +static void Error_Handler(void); + +/* Private functions ---------------------------------------------------------*/ + +/** + * @brief Main program + * @param None + * @retval None + */ +int main(void) +{ + /* STM32F4xx HAL library initialization: + - Configure the Flash prefetch, instruction and Data caches + - Configure the Systick to generate an interrupt each 1 msec + - Set NVIC Group Priority to 4 + - Global MSP (MCU Support Package) initialization + */ + HAL_Init(); + + /* Configure LED3 and LED4 */ + BSP_LED_Init(LED3); + BSP_LED_Init(LED4); + + /* Initialize User button, will be used to trigger an interrupt each time it's pressed. + In the ISR the PLL source will be changed from HSE to HSI, and vice versa. */ + BSP_PB_Init(BUTTON_KEY, BUTTON_MODE_EXTI); + + /* Enable Power Control clock */ + __HAL_RCC_PWR_CLK_ENABLE(); + + /* The voltage scaling allows optimizing the power consumption when the device is + clocked below the maximum system frequency, to update the voltage scaling value + regarding system frequency refer to product datasheet. */ + __HAL_PWR_VOLTAGESCALING_CONFIG(PWR_REGULATOR_VOLTAGE_SCALE1); + + /* Enable HSE oscillator and configure the PLL to reach the max system frequency (180MHz) + when using HSE oscillator as PLL clock source. */ + RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSE; + RCC_OscInitStruct.HSEState = RCC_HSE_ON; + RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON; + RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSE; + RCC_OscInitStruct.PLL.PLLM = 8; + RCC_OscInitStruct.PLL.PLLN = 360; + RCC_OscInitStruct.PLL.PLLP = RCC_PLLP_DIV2; + RCC_OscInitStruct.PLL.PLLQ = 7; + if(HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK) + { + /* Initialization Error */ + Error_Handler(); + } + + /* Activate the Over Drive feature (available only for STM32F42xxx/43xxx devices)*/ + if(HAL_PWREx_EnableOverDrive() != HAL_OK) + { + /* Initialization Error */ + Error_Handler(); + } + + /* Select PLL as system clock source and configure the HCLK, PCLK1 and PCLK2 clocks dividers. + The SysTick 1 msec interrupt is required for the HAL process (Timeout management); by default + the configuration is done using the HAL_Init() API, and when the system clock configuration + is updated the SysTick configuration will be adjusted by the HAL_RCC_ClockConfig() API. */ + RCC_ClkInitStruct.ClockType = (RCC_CLOCKTYPE_SYSCLK | RCC_CLOCKTYPE_HCLK | RCC_CLOCKTYPE_PCLK1 | RCC_CLOCKTYPE_PCLK2); + RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK; + RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1; + RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV4; + RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV2; + if(HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_5) != HAL_OK) + { + /* Initialization Error */ + Error_Handler(); + } + + /* Output SYSCLK divided by 2 on MCO2 pin(PC9) */ + HAL_RCC_MCOConfig(RCC_MCO2, RCC_MCO2SOURCE_SYSCLK, RCC_MCODIV_2); + + /* Toggle LED3 and LED4 in an infinite loop */ + while (1) + { + /* Toggle LED3 */ + BSP_LED_Toggle(LED3); + HAL_Delay(1000); + /* Toggle LED4 */ + BSP_LED_Toggle(LED4); + HAL_Delay(100); + } +} + +/** + * @brief EXTI line detection callbacks. + * @param GPIO_Pin: Specifies the pins connected EXTI line + * @retval None + */ +void HAL_GPIO_EXTI_Callback(uint16_t GPIO_Pin) +{ + if(GPIO_Pin == KEY_BUTTON_PIN) + { + if(__HAL_RCC_GET_PLL_OSCSOURCE() == RCC_PLLCFGR_PLLSRC_HSI) + { + /* Set SYSCLK frequency to 180 MHz, coming from the PLL which is clocked by the HSE */ + SystemClockHSE_Config(); + } + else /* PLL source is HSE oscillator */ + { + /* Set SYSCLK frequency to 180 MHz, coming from the PLL which is clocked by the HSI */ + SystemClockHSI_Config(); + } + } +} + +/** + * @brief Switch the PLL source from HSI to HSE, and select the PLL as SYSCLK + * source. + * The system Clock is configured as follow : + * System Clock source = PLL (HSE) + * SYSCLK(Hz) = 180000000 + * HCLK(Hz) = 180000000 + * AHB Prescaler = 1 + * APB1 Prescaler = 4 + * APB2 Prescaler = 2 + * HSE Frequency(Hz) = 8000000 + * PLL_M = 8 + * PLL_N = 360 + * PLL_P = 2 + * PLL_Q = 7 + * VDD(V) = 3.3 + * Main regulator output voltage = Scale1 mode + * Flash Latency(WS) = 5 + * @param None + * @retval None + */ +void SystemClockHSE_Config(void) +{ + /* -1- Select HSI as system clock source to allow modification of the PLL configuration */ + RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_SYSCLK; + RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_HSI; + if(HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_1) != HAL_OK) + { + Error_Handler(); + } + + /* -2- Enable HSE Oscillator, select it as PLL source and finally activate the PLL */ + RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSE; + RCC_OscInitStruct.HSEState = RCC_HSE_ON; + RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON; + RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSE; + RCC_OscInitStruct.PLL.PLLM = 8; + RCC_OscInitStruct.PLL.PLLN = 360; + RCC_OscInitStruct.PLL.PLLP = RCC_PLLP_DIV2; + RCC_OscInitStruct.PLL.PLLQ = 7; + if(HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK) + { + /* Initialization Error */ + Error_Handler(); + } + + /* -3- Activate the Over Drive feature to reach 180 MHz as system clock frequency + (this feature is only available for STM32F42xxx/43xxx devices) */ + if(HAL_PWREx_EnableOverDrive() != HAL_OK) + { + /* Initialization Error */ + Error_Handler(); + } + + /* -4- Select the PLL as system clock source and configure the HCLK, PCLK1 and PCLK2 clocks dividers */ + RCC_ClkInitStruct.ClockType = (RCC_CLOCKTYPE_SYSCLK | RCC_CLOCKTYPE_HCLK | RCC_CLOCKTYPE_PCLK1 | RCC_CLOCKTYPE_PCLK2); + RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK; + RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1; + RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV4; + RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV2; + if(HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_5) != HAL_OK) + { + Error_Handler(); + } + + /* -5- Optional: Disable HSI Oscillator (if the HSI is no more needed by the application)*/ + RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSI; + RCC_OscInitStruct.HSIState = RCC_HSI_OFF; + RCC_OscInitStruct.PLL.PLLState = RCC_PLL_NONE; + if(HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK) + { + /* Initialization Error */ + Error_Handler(); + } +} + +/** + * @brief Switch the PLL source from HSI to HSE, and select the PLL as SYSCLK + * source. + * The system Clock is configured as follow : + * System Clock source = PLL (HSI) + * SYSCLK(Hz) = 180000000 + * HCLK(Hz) = 180000000 + * AHB Prescaler = 1 + * APB1 Prescaler = 4 + * APB2 Prescaler = 2 + * HSI Frequency(Hz) = 16000000 + * PLL_M = 16 + * PLL_N = 360 + * PLL_P = 2 + * VDD(V) = 3.3 + * Main regulator output voltage = Scale1 mode + * Flash Latency(WS) = 5 + * @param None + * @retval None + */ +void SystemClockHSI_Config(void) +{ + /* -1- Select HSE as system clock source to allow modification of the PLL configuration */ + RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_SYSCLK; + RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_HSE; + if(HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_1) != HAL_OK) + { + Error_Handler(); + } + + /* -2- Enable HSI Oscillator, select it as PLL source and finally activate the PLL */ + RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSI; + RCC_OscInitStruct.HSIState = RCC_HSI_ON; + RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON; + RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSI; + RCC_OscInitStruct.PLL.PLLM = 16; + RCC_OscInitStruct.PLL.PLLN = 360; + RCC_OscInitStruct.PLL.PLLP = RCC_PLLP_DIV2; + RCC_OscInitStruct.HSICalibrationValue = 0x10; + if(HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK) + { + /* Initialization Error */ + Error_Handler(); + } + + /* -3- Activate the Over Drive feature to reach 180 MHz as system clock frequency + (this feature is only available for STM32F42xxx/43xxx devices) */ + if(HAL_PWREx_EnableOverDrive() != HAL_OK) + { + /* Initialization Error */ + Error_Handler(); + } + + /* -4- Select the PLL as system clock source and configure the HCLK, PCLK1 and PCLK2 clocks dividers */ + RCC_ClkInitStruct.ClockType = (RCC_CLOCKTYPE_SYSCLK | RCC_CLOCKTYPE_HCLK | RCC_CLOCKTYPE_PCLK1 | RCC_CLOCKTYPE_PCLK2); + RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK; + RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1; + RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV4; + RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV2; + if(HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_5) != HAL_OK) + { + Error_Handler(); + } + + /* -5- Optional: Disable HSE Oscillator (if the HSE is no more needed by the application) */ + RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSE; + RCC_OscInitStruct.HSEState = RCC_HSE_OFF; + RCC_OscInitStruct.PLL.PLLState = RCC_PLL_NONE; + if(HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK) + { + /* Initialization Error */ + Error_Handler(); + } +} + +/** + * @brief This function is executed in case of error occurrence. + * @param None + * @retval None + */ +static void Error_Handler(void) +{ + /* Turn LED4 on */ + BSP_LED_On(LED4); + while(1) + { + } +} + +#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) */ + + /* Infinite loop */ + while (1) + { + } +} +#endif + +/** + * @} + */ + +/** + * @} + */ + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/pool/shard002/C/0061921_container_read.c b/pool/shard002/C/0061921_container_read.c new file mode 100644 index 0000000000000000000000000000000000000000..33f4d368463b15a26b7e1e803a33f23b284d5929 --- /dev/null +++ b/pool/shard002/C/0061921_container_read.c @@ -0,0 +1,89 @@ +/* + * + * (c) 2005 Laurent Vivier + * + */ + +#include +#include +#include + +#include "libcontainer.h" +#include "container.h" + +extern void error(char *x) __attribute__ ((noreturn)); + +static unsigned long seek_block(stream_FILE *_file) +{ + container_FILE *file = (container_FILE*)_file; + struct emile_container *container = file->container; + ssize_t current; + int i; + unsigned long offset = file->offset; + int block_size = file->device->get_blocksize(file->device->data); + + for (i = 0, current = 0; + container->blocks[i].offset != 0; i++) + { + int extent_size = block_size * + container->blocks[i].count; + + if ( (current <= offset) && (offset < current + extent_size) ) + { + return container->blocks[i].offset + + (offset - current) / block_size; + } + + current += extent_size; + } + + return 0; +} + +size_t container_read(stream_FILE *_file, void *ptr, size_t size) +{ + container_FILE *file = (container_FILE*)_file; + int err; + ssize_t read = 0; + int part; + int block_size = file->device->get_blocksize(file->device->data); + + while (size != 0) + { + unsigned long block_nb; + int block_offset; + + if (file->offset >= file->container->size) + return read; + + block_nb = seek_block(_file); + block_offset = file->offset % block_size; + + if (block_nb == 0) + error("BUG in libcontainer !!!"); + + if (block_nb != file->current_block) + { + err = file->device->read_sector( + file->device->data, + block_nb, + file->buffer, + block_size); + if (err == -1) + return -1; + file->current_block = block_nb; + } + + part = block_size - block_offset; + if (part > size) + part = size; + memcpy(ptr, file->buffer + block_offset, part); + + size -= part; + ptr = (char*)ptr + part; + file->offset += part; + read += part; + } + + return read; +} diff --git a/pool/shard002/C/0061925_cc-qr-code.c b/pool/shard002/C/0061925_cc-qr-code.c new file mode 100644 index 0000000000000000000000000000000000000000..b803011bca95a715f7f8361e3cbdeb34cf6070b6 --- /dev/null +++ b/pool/shard002/C/0061925_cc-qr-code.c @@ -0,0 +1,197 @@ +/* -*- mode: c; c-basic-offset: 2; indent-tabs-mode: nil; -*- */ +/* cc-qr-code.c + * + * Copyright 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 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 . + * + * Author(s): + * Mohammed Sadiq + * + * SPDX-License-Identifier: GPL-3.0-or-later + */ + +#undef G_LOG_DOMAIN +#define G_LOG_DOMAIN "cc-qr-code" + +#ifdef HAVE_CONFIG_H +# include "config.h" +#endif + +#include "cc-qr-code.h" +#include "qrcodegen.c" + +/** + * SECTION: cc-qr_code + * @title: CcQrCode + * @short_description: A Simple QR Code wrapper around libqrencode + * @include: "cc-qr-code.h" + * + * Generate a QR image from a given text. + */ + +struct _CcQrCode +{ + GObject parent_instance; + + gchar *text; + cairo_surface_t *surface; + gint size; + gint scale; +}; + +G_DEFINE_TYPE (CcQrCode, cc_qr_code, G_TYPE_OBJECT) + + +static void +cc_qr_code_finalize (GObject *object) +{ + CcQrCode *self = (CcQrCode *)object; + + g_clear_pointer (&self->surface, cairo_surface_destroy); + g_clear_pointer (&self->text, g_free); + + G_OBJECT_CLASS (cc_qr_code_parent_class)->finalize (object); +} + +static void +cc_qr_code_class_init (CcQrCodeClass *klass) +{ + GObjectClass *object_class = G_OBJECT_CLASS (klass); + + object_class->finalize = cc_qr_code_finalize; +} + +static void +cc_qr_code_init (CcQrCode *self) +{ +} + +CcQrCode * +cc_qr_code_new (void) +{ + return g_object_new (CC_TYPE_QR_CODE, NULL); +} + +gboolean +cc_qr_code_set_text (CcQrCode *self, + const gchar *text) +{ + g_return_val_if_fail (CC_IS_QR_CODE (self), FALSE); + g_return_val_if_fail (!text || *text, FALSE); + + if (g_strcmp0 (text, self->text) == 0) + return FALSE; + + /* Clear cairo surface that is cached */ + g_clear_pointer (&self->surface, cairo_surface_destroy); + g_free (self->text); + self->text = g_strdup (text); + + return TRUE; +} + +static void +cc_cairo_fill_pixel (cairo_t *cr, + int x, + int y, + int padding, + int scale) +{ + cairo_rectangle (cr, + x * scale + padding, + y * scale + padding, + scale, scale); + cairo_fill (cr); +} + +cairo_surface_t * +cc_qr_code_get_surface (CcQrCode *self, + gint size, + gint scale) +{ + uint8_t qr_code[qrcodegen_BUFFER_LEN_FOR_VERSION (qrcodegen_VERSION_MAX)]; + uint8_t temp_buf[qrcodegen_BUFFER_LEN_FOR_VERSION (qrcodegen_VERSION_MAX)]; + cairo_t *cr; + gint pixel_size, padding, qr_size; + gboolean success = FALSE; + + g_return_val_if_fail (CC_IS_QR_CODE (self), NULL); + g_return_val_if_fail (size > 0, NULL); + g_return_val_if_fail (scale > 0, NULL); + + if (!self->text || !*self->text) + { + g_warn_if_reached (); + cc_qr_code_set_text (self, "invalid text"); + } + + if (self->surface && + self->size == size && + self->scale == scale) + return self->surface; + + self->size = size; + self->scale = scale; + g_clear_pointer (&self->surface, cairo_surface_destroy); + + success = qrcodegen_encodeText (self->text, + temp_buf, + qr_code, + qrcodegen_Ecc_LOW, + qrcodegen_VERSION_MIN, + qrcodegen_VERSION_MAX, + qrcodegen_Mask_AUTO, + FALSE); + + if (!success) + return NULL; + + self->surface = cairo_image_surface_create (CAIRO_FORMAT_RGB24, size * scale, size * scale); + cairo_surface_set_device_scale (self->surface, scale, scale); + cr = cairo_create (self->surface); + cairo_set_antialias (cr, CAIRO_ANTIALIAS_NONE); + + /* Draw white background */ + cairo_set_source_rgba (cr, 1, 1, 1, 1); + cairo_rectangle (cr, 0, 0, size * scale, size * scale); + cairo_fill (cr); + + qr_size = qrcodegen_getSize(qr_code); + pixel_size = MAX (1, size / (qr_size)); + padding = (size - qr_size * pixel_size) / 2; + + /* If subpixel size is big and margin is pretty small, + * increase the margin */ + if (pixel_size > 4 && padding < 12) + { + pixel_size--; + padding = (size - qr_size * pixel_size) / 2; + } + + /* Now draw the black QR code pixels */ + cairo_set_source_rgba (cr, 0, 0, 0, 1); + for (int row = 0; row < qr_size; row++) + { + for (int column = 0; column < qr_size; column++) + { + if (qrcodegen_getModule (qr_code, row, column)) + cc_cairo_fill_pixel (cr, column, row, padding, pixel_size); + } + } + + cairo_destroy (cr); + + return self->surface; +} diff --git a/pool/shard002/C/0061944_twi.c b/pool/shard002/C/0061944_twi.c new file mode 100644 index 0000000000000000000000000000000000000000..3241a3eb30b1ea37490f57c4b4156c853bae0341 --- /dev/null +++ b/pool/shard002/C/0061944_twi.c @@ -0,0 +1,253 @@ +/* this is not much more than a shell; it does not do anything useful yet */ + +/* TWI (I2C) driver for Blackfin + * + * Copyright (c) 2008 Kallisti Labs, Los Gatos, CA, USA + * written by Allan Hessenflow + * + * 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. + */ + + +#include +#include + +#include +#include "twi.h" + + +#ifndef N_BFIN_TWI +#define N_BFIN_TWI 1 +#endif + +#define BFIN_REG16(base, offset) \ + (*((uint16_t volatile *) ((char *)(base) + (offset)))) + + +static struct { + void *base; + rtems_id irqSem; + rtems_id mutex; + bfin_twi_callback_t callback; + void *callbackArg; + bfin_twi_request_t volatile *req; + uint8_t volatile *dataPtr; + int volatile count; + bool volatile masterActive; + rtems_status_code volatile masterResult; + bool volatile slaveActive; +} twi[N_BFIN_TWI]; + + +rtems_status_code bfin_twi_init(int channel, bfin_twi_config_t *config) { + rtems_status_code result; + void *base; + + if (channel < 0 || channel >= N_BFIN_TWI) + return RTEMS_INVALID_NUMBER; + + base = config->base; + twi[channel].base = base; + + result = rtems_semaphore_create(rtems_build_name('t','w','i','s'), + 0, + RTEMS_FIFO | + RTEMS_SIMPLE_BINARY_SEMAPHORE | + RTEMS_NO_INHERIT_PRIORITY | + RTEMS_NO_PRIORITY_CEILING | + RTEMS_LOCAL, + 0, + &twi[channel].irqSem); + result = rtems_semaphore_create(rtems_build_name('t','w','i','m'), + 1, + RTEMS_PRIORITY | + RTEMS_SIMPLE_BINARY_SEMAPHORE | + RTEMS_INHERIT_PRIORITY | + RTEMS_NO_PRIORITY_CEILING | + RTEMS_LOCAL, + 0, + &twi[channel].mutex); + BFIN_REG16(base, TWI_CONTROL_OFFSET) = + (uint16_t) (((config->sclk +9999999) / 10000000) << + TWI_CONTROL_PRESCALE_SHIFT) | + TWI_CONTROL_TWI_ENA; + BFIN_REG16(base, TWI_CLKDIV_OFFSET) = config->fast ? + ((8 << TWI_CLKDIV_CLKHI_SHIFT) | + (17 << TWI_CLKDIV_CLKLOW_SHIFT)) : + ((33 << TWI_CLKDIV_CLKHI_SHIFT) | + (67 << TWI_CLKDIV_CLKLOW_SHIFT)); + BFIN_REG16(base, TWI_SLAVE_CTL_OFFSET) = 0; + BFIN_REG16(base, TWI_MASTER_CTL_OFFSET) = config->fast ? + TWI_MASTER_CTL_FAST : + 0; + BFIN_REG16(base, TWI_SLAVE_ADDR_OFFSET) = (uint16_t) config->slave_address << + TWI_SLAVE_ADDR_SADDR_SHIFT; + BFIN_REG16(base, TWI_MASTER_STAT_OFFSET) = TWI_MASTER_STAT_BUFWRERR | + TWI_MASTER_STAT_BUFRDERR | + TWI_MASTER_STAT_DNAK | + TWI_MASTER_STAT_ANAK | + TWI_MASTER_STAT_LOSTARB; + BFIN_REG16(base, TWI_FIFO_CTL_OFFSET) = TWI_FIFO_CTL_XMTFLUSH | + TWI_FIFO_CTL_RCVFLUSH; + BFIN_REG16(base, TWI_FIFO_CTL_OFFSET) = 0; + BFIN_REG16(base, TWI_INT_STAT_OFFSET) = TWI_INT_STAT_RCVSERV | + TWI_INT_STAT_XMTSERV | + TWI_INT_STAT_MERR | + TWI_INT_STAT_MCOMP | + TWI_INT_STAT_SOVF | + TWI_INT_STAT_SERR | + TWI_INT_STAT_SCOMP | + TWI_INT_STAT_SINIT; + BFIN_REG16(base, TWI_INT_MASK_OFFSET) = TWI_INT_MASK_RCVSERVM | + TWI_INT_MASK_XMTSERVM; + + return result; +} + +rtems_status_code bfin_twi_register_callback(int channel, + bfin_twi_callback_t callback, + void *arg) { + void *base; + int level; + + if (channel < 0 || channel >= N_BFIN_TWI) + return RTEMS_INVALID_NUMBER; + + base = twi[channel].base; + if (callback == NULL) + BFIN_REG16(base, TWI_SLAVE_CTL_OFFSET) = 0; + rtems_interrupt_disable(level); + twi[channel].callback = callback; + twi[channel].callbackArg = arg; + rtems_interrupt_enable(level); + if (callback != NULL) + BFIN_REG16(base, TWI_SLAVE_CTL_OFFSET) = TWI_SLAVE_CTL_GEN | + TWI_SLAVE_CTL_SEN; + + return RTEMS_SUCCESSFUL; +} + +void bfin_twi_isr(int source) { + void *base; + int i; + uint16_t r; + uint16_t stat; + + for (i = 0; i < N_BFIN_TWI; i++) { + base = twi[i].base; + if (base) { + stat = BFIN_REG16(base, TWI_INT_STAT_OFFSET); + if (stat) { + BFIN_REG16(base, TWI_INT_STAT_OFFSET) = stat; + if ((stat & TWI_INT_STAT_SINIT) && !twi[i].slaveActive) { + twi[i].slaveActive = true; + r = BFIN_REG16(base, TWI_FIFO_CTL_OFFSET); + BFIN_REG16(base, TWI_FIFO_CTL_OFFSET) = r | TWI_FIFO_CTL_XMTFLUSH; + BFIN_REG16(base, TWI_FIFO_CTL_OFFSET) = r; + r = BFIN_REG16(base, TWI_SLAVE_CTL_OFFSET); + BFIN_REG16(base, TWI_SLAVE_CTL_OFFSET) = r | TWI_SLAVE_CTL_STDVAL; + } + if (twi[i].slaveActive) { + + + if (stat & (TWI_INT_STAT_SCOMP | TWI_INT_STAT_SERR)) { + + + r = BFIN_REG16(base, TWI_SLAVE_CTL_OFFSET); + BFIN_REG16(base, TWI_SLAVE_CTL_OFFSET) = r & ~TWI_SLAVE_CTL_STDVAL; + twi[i].slaveActive = false; + + + } + } + if (twi[i].masterActive && !twi[i].slaveActive) { + + + if (stat & (TWI_INT_STAT_MCOMP | TWI_INT_STAT_MERR)) { + if (!(stat & TWI_INT_STAT_MERR)) { + + + rtems_semaphore_release(twi[i].irqSem); + + + } else + rtems_semaphore_release(twi[i].irqSem); + } + } + } + } + } +} + +rtems_status_code bfin_twi_request(int channel, uint8_t address, + bfin_twi_request_t *request, + rtems_interval timeout) { + rtems_status_code result; + void *base; + rtems_interrupt_level level; + uint16_t r; + uint16_t masterMode; + + if (channel < 0 || channel >= N_BFIN_TWI) + return RTEMS_INVALID_NUMBER; + result = rtems_semaphore_obtain(twi[channel].mutex, + RTEMS_WAIT, RTEMS_NO_TIMEOUT); + if (result == RTEMS_SUCCESSFUL) { + base = twi[channel].base; + twi[channel].req = request; + + if (request->write) { + twi[channel].dataPtr = request->data; + twi[channel].count = request->count; + } else + twi[channel].count = 0; + + BFIN_REG16(base, TWI_MASTER_ADDR_OFFSET) = (uint16_t) address << + TWI_MASTER_ADDR_MADDR_SHIFT; + masterMode = BFIN_REG16(base, TWI_MASTER_CTL_OFFSET); + masterMode |= (request->count << TWI_MASTER_CTL_DCNT_SHIFT); + if (request->next) + masterMode |= TWI_MASTER_CTL_RSTART; + if (!request->write) + masterMode |= TWI_MASTER_CTL_MDIR; + masterMode |= TWI_MASTER_CTL_MEN; + rtems_interrupt_disable(level); + if (!twi[channel].slaveActive) { + r = BFIN_REG16(base, TWI_FIFO_CTL_OFFSET); + BFIN_REG16(base, TWI_FIFO_CTL_OFFSET) = r | TWI_FIFO_CTL_XMTFLUSH; + BFIN_REG16(base, TWI_FIFO_CTL_OFFSET) = r; + if (request->write) { + while (twi[channel].count && + (BFIN_REG16(base, TWI_FIFO_STAT_OFFSET) & + TWI_FIFO_STAT_XMTSTAT_MASK) != + TWI_FIFO_STAT_XMTSTAT_FULL) { + BFIN_REG16(base, TWI_XMT_DATA8_OFFSET) = + (uint16_t) *twi[channel].dataPtr++; + twi[channel].count--; + } + } + twi[channel].masterActive = true; + BFIN_REG16(base, TWI_MASTER_CTL_OFFSET) = masterMode; + } else { + twi[channel].masterActive = false; + twi[channel].masterResult = -1; /* BISON (code should be equiv to lost arbitration) */ + } + rtems_interrupt_enable(level); + while (result == RTEMS_SUCCESSFUL && twi[channel].masterActive) + result = rtems_semaphore_obtain(twi[channel].irqSem, + RTEMS_WAIT, timeout); + if (result == RTEMS_SUCCESSFUL) + result = twi[channel].masterResult; + else { + /* BISON abort */ + + + + } + rtems_semaphore_release(twi[channel].mutex); + } + return result; +} + diff --git a/pool/shard002/C/0061953_ecc_test.c b/pool/shard002/C/0061953_ecc_test.c new file mode 100644 index 0000000000000000000000000000000000000000..02f1f91ff571944e06c33d91b634f17a0457bce4 --- /dev/null +++ b/pool/shard002/C/0061953_ecc_test.c @@ -0,0 +1,89 @@ +#include "test.h" + +int ecc_tests (void) +{ + unsigned char buf[4][4096]; + unsigned long x, y, z; + int stat, stat2; + ecc_key usera, userb; + + DO(ecc_test ()); + + /* make up two keys */ + DO(ecc_make_key (&test_yarrow, find_prng ("yarrow"), 24, &usera)); + DO(ecc_make_key (&test_yarrow, find_prng ("yarrow"), 24, &userb)); + + /* make the shared secret */ + x = 4096; + DO(ecc_shared_secret (&usera, &userb, buf[0], &x)); + + y = 4096; + DO(ecc_shared_secret (&userb, &usera, buf[1], &y)); + + if (y != x) { + printf ("ecc Shared keys are not same size."); + return 1; + } + + if (memcmp (buf[0], buf[1], x)) { + printf ("ecc Shared keys not same contents."); + return 1; + } + + /* now export userb */ + y = 4096; + DO(ecc_export (buf[1], &y, PK_PUBLIC, &userb)); + ecc_free (&userb); + + /* import and make the shared secret again */ + DO(ecc_import (buf[1], y, &userb)); + + z = 4096; + DO(ecc_shared_secret (&usera, &userb, buf[2], &z)); + + if (z != x) { + printf ("failed. Size don't match?"); + return 1; + } + if (memcmp (buf[0], buf[2], x)) { + printf ("Failed. Content didn't match."); + return 1; + } + ecc_free (&usera); + ecc_free (&userb); + +/* test encrypt_key */ + ecc_make_key (&test_yarrow, find_prng ("yarrow"), 20, &usera); + for (x = 0; x < 32; x++) { + buf[0][x] = x; + } + y = sizeof (buf[1]); + DO(ecc_encrypt_key (buf[0], 32, buf[1], &y, &test_yarrow, find_prng ("yarrow"), find_hash ("sha256"), &usera)); + zeromem (buf[0], sizeof (buf[0])); + x = sizeof (buf[0]); + DO(ecc_decrypt_key (buf[1], y, buf[0], &x, &usera)); + if (x != 32) { + printf ("Failed (length)"); + return 1; + } + for (x = 0; x < 32; x++) + if (buf[0][x] != x) { + printf ("Failed (contents)"); + return 1; + } +/* test sign_hash */ + for (x = 0; x < 16; x++) { + buf[0][x] = x; + } + x = sizeof (buf[1]); + DO(ecc_sign_hash (buf[0], 16, buf[1], &x, &test_yarrow, find_prng ("yarrow"), &usera)); + DO(ecc_verify_hash (buf[1], x, buf[0], 16, &stat, &usera)); + buf[0][0] ^= 1; + DO(ecc_verify_hash (buf[1], x, buf[0], 16, &stat2, &usera)); + if (!(stat == 1 && stat2 == 0)) { + printf("ecc_verify_hash failed"); + return 1; + } + ecc_free (&usera); + return 0; +} diff --git a/pool/shard002/C/0061957_pi_integration_mpi.c b/pool/shard002/C/0061957_pi_integration_mpi.c new file mode 100644 index 0000000000000000000000000000000000000000..32905619a85e31a83d0c18ab49b3f8c2c031bf8a --- /dev/null +++ b/pool/shard002/C/0061957_pi_integration_mpi.c @@ -0,0 +1,48 @@ +#include +#include +#include + +int main (int argc, char *argv[]) +{ + int i,num_steps,ThisInitial,ThisSteps; + int ThisTask,NTask; + double x, local_sum=0.0, sum, step, pi; + double t_start, t_end; + + MPI_Init(&argc, &argv); + MPI_Comm_rank(MPI_COMM_WORLD,&ThisTask); + MPI_Comm_size(MPI_COMM_WORLD,&NTask); + + num_steps=500000000; + x=0; + sum = 0.0; + step = 1.0/(double) num_steps; + t_start = MPI_Wtime(); + + + /* how many steps per task- last task picks up the slack */ + ThisSteps=num_steps/NTask; + ThisInitial=ThisTask*ThisSteps; + if(ThisTask==NTask-1) + { + ThisSteps+=num_steps%NTask; + } + + for (i=ThisInitial; i < ThisInitial+ThisSteps; i++) + { + x = (i+0.5)*step; + local_sum = local_sum + 4.0/(1.0+x*x); + } + + MPI_Reduce(&local_sum,&sum,1,MPI_DOUBLE,MPI_SUM,0,MPI_COMM_WORLD); + + t_end = MPI_Wtime(); + if(ThisTask==0) + { + pi = step * sum; + printf("Value of pi = %g\n",pi); + printf("Expended wall clock time = %.20f\n", t_end - t_start); + } + MPI_Finalize(); + return EXIT_SUCCESS; +} diff --git a/pool/shard002/C/0061960_udf.c b/pool/shard002/C/0061960_udf.c new file mode 100644 index 0000000000000000000000000000000000000000..fa5dccee7077905e08df91df5b947aaa44370d8d --- /dev/null +++ b/pool/shard002/C/0061960_udf.c @@ -0,0 +1,179 @@ +/* + * volume_id - reads filesystem label and uuid + * + * Copyright (C) 2004 Kay Sievers + * + * 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 + */ + +//kbuild:lib-$(CONFIG_FEATURE_VOLUMEID_UDF) += udf.o + +//config:config FEATURE_VOLUMEID_UDF +//config: bool "udf filesystem" +//config: default y +//config: depends on VOLUMEID + +#include "volume_id_internal.h" + +struct volume_descriptor { + struct descriptor_tag { + uint16_t id; + uint16_t version; + uint8_t checksum; + uint8_t reserved; + uint16_t serial; + uint16_t crc; + uint16_t crc_len; + uint32_t location; + } PACKED tag; + union { + struct anchor_descriptor { + uint32_t length; + uint32_t location; + } PACKED anchor; + struct primary_descriptor { + uint32_t seq_num; + uint32_t desc_num; + struct dstring { + uint8_t clen; + uint8_t c[31]; + } PACKED ident; + } PACKED primary; + } PACKED type; +} PACKED; + +struct volume_structure_descriptor { + uint8_t type; + uint8_t id[5]; + uint8_t version; +} PACKED; + +#define UDF_VSD_OFFSET 0x8000 + +int FAST_FUNC volume_id_probe_udf(struct volume_id *id /*,uint64_t off*/) +{ +#define off ((uint64_t)0) + struct volume_descriptor *vd; + struct volume_structure_descriptor *vsd; + unsigned bs; + unsigned b; + unsigned type; + unsigned count; + unsigned loc; + unsigned clen; + + dbg("probing at offset 0x%llx", (unsigned long long) off); + + vsd = volume_id_get_buffer(id, off + UDF_VSD_OFFSET, 0x200); + if (vsd == NULL) + return -1; + + if (memcmp(vsd->id, "NSR02", 5) == 0) + goto blocksize; + if (memcmp(vsd->id, "NSR03", 5) == 0) + goto blocksize; + if (memcmp(vsd->id, "BEA01", 5) == 0) + goto blocksize; + if (memcmp(vsd->id, "BOOT2", 5) == 0) + goto blocksize; + if (memcmp(vsd->id, "CD001", 5) == 0) + goto blocksize; + if (memcmp(vsd->id, "CDW02", 5) == 0) + goto blocksize; + if (memcmp(vsd->id, "TEA03", 5) == 0) + goto blocksize; + return -1; + +blocksize: + /* search the next VSD to get the logical block size of the volume */ + for (bs = 0x800; bs < 0x8000; bs += 0x800) { + vsd = volume_id_get_buffer(id, off + UDF_VSD_OFFSET + bs, 0x800); + if (vsd == NULL) + return -1; + dbg("test for blocksize: 0x%x", bs); + if (vsd->id[0] != '\0') + goto nsr; + } + return -1; + +nsr: + /* search the list of VSDs for a NSR descriptor */ + for (b = 0; b < 64; b++) { + vsd = volume_id_get_buffer(id, off + UDF_VSD_OFFSET + (b * bs), 0x800); + if (vsd == NULL) + return -1; + + dbg("vsd: %c%c%c%c%c", + vsd->id[0], vsd->id[1], vsd->id[2], vsd->id[3], vsd->id[4]); + + if (vsd->id[0] == '\0') + return -1; + if (memcmp(vsd->id, "NSR02", 5) == 0) + goto anchor; + if (memcmp(vsd->id, "NSR03", 5) == 0) + goto anchor; + } + return -1; + +anchor: + /* read anchor volume descriptor */ + vd = volume_id_get_buffer(id, off + (256 * bs), 0x200); + if (vd == NULL) + return -1; + + type = le16_to_cpu(vd->tag.id); + if (type != 2) /* TAG_ID_AVDP */ + goto found; + + /* get descriptor list address and block count */ + count = le32_to_cpu(vd->type.anchor.length) / bs; + loc = le32_to_cpu(vd->type.anchor.location); + dbg("0x%x descriptors starting at logical secor 0x%x", count, loc); + + /* pick the primary descriptor from the list */ + for (b = 0; b < count; b++) { + vd = volume_id_get_buffer(id, off + ((loc + b) * bs), 0x200); + if (vd == NULL) + return -1; + + type = le16_to_cpu(vd->tag.id); + dbg("descriptor type %i", type); + + /* check validity */ + if (type == 0) + goto found; + if (le32_to_cpu(vd->tag.location) != loc + b) + goto found; + + if (type == 1) /* TAG_ID_PVD */ + goto pvd; + } + goto found; + + pvd: +// volume_id_set_label_raw(id, &(vd->type.primary.ident.clen), 32); + + clen = vd->type.primary.ident.clen; + dbg("label string charsize=%i bit", clen); + if (clen == 8) + volume_id_set_label_string(id, vd->type.primary.ident.c, 31); + else if (clen == 16) + volume_id_set_label_unicode16(id, vd->type.primary.ident.c, BE, 31); + + found: +// volume_id_set_usage(id, VOLUME_ID_FILESYSTEM); + IF_FEATURE_BLKID_TYPE(id->type = "udf";) + return 0; +} diff --git a/pool/shard002/C/0061964_test-expm1f.c b/pool/shard002/C/0061964_test-expm1f.c new file mode 100644 index 0000000000000000000000000000000000000000..016deb88c0b5617236fdbf8a8bfc56495fdf0237 --- /dev/null +++ b/pool/shard002/C/0061964_test-expm1f.c @@ -0,0 +1,49 @@ +/* Test of expm1f() function. + Copyright (C) 2010-2013 Free Software Foundation, Inc. + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . */ + +/* Written by Bruno Haible , 2010-2011. */ + +#include + +#include + +#include "signature.h" +SIGNATURE_CHECK (expm1f, float, (float)); + +#include + +#include "macros.h" + +#define DOUBLE float +#define L_(literal) literal##f +#define MANT_DIG FLT_MANT_DIG +#define MIN_EXP FLT_MIN_EXP +#define EXPM1 expm1f +#define RANDOM randomf +#include "test-expm1.h" + +int +main () +{ + /* A particular value. */ + x = 0.6f; + y = expm1f (x); + ASSERT (y >= 0.8221187f && y <= 0.8221189f); + + test_function (); + + return 0; +} diff --git a/pool/shard002/C/0061965_MP+PPO714.c b/pool/shard002/C/0061965_MP+PPO714.c new file mode 100644 index 0000000000000000000000000000000000000000..2dc49b469c38f974261db2be18bf3e9b91a18cef --- /dev/null +++ b/pool/shard002/C/0061965_MP+PPO714.c @@ -0,0 +1,64 @@ +/* Copyright (C) 2018 Magnus Lång and Tuan Phong Ngo + * This benchmark is part of SWSC */ + +#include +#include +#include +#include + +atomic_int vars[3]; +atomic_int atom_1_r1_1; +atomic_int atom_1_r8_1; + +void *t0(void *arg){ +label_1:; + atomic_store_explicit(&vars[0], 2, memory_order_seq_cst); + + atomic_store_explicit(&vars[1], 1, memory_order_seq_cst); + return NULL; +} + +void *t1(void *arg){ +label_2:; + int v2_r1 = atomic_load_explicit(&vars[1], memory_order_seq_cst); + int v3_r3 = v2_r1 ^ v2_r1; + int v4_r3 = v3_r3 + 1; + atomic_store_explicit(&vars[2], v4_r3, memory_order_seq_cst); + int v6_r5 = atomic_load_explicit(&vars[2], memory_order_seq_cst); + int v7_cmpeq = (v6_r5 == v6_r5); + if (v7_cmpeq) goto lbl_LC00; else goto lbl_LC00; +lbl_LC00:; + atomic_store_explicit(&vars[0], 1, memory_order_seq_cst); + int v9_r8 = atomic_load_explicit(&vars[0], memory_order_seq_cst); + int v16 = (v2_r1 == 1); + atomic_store_explicit(&atom_1_r1_1, v16, memory_order_seq_cst); + int v17 = (v9_r8 == 1); + atomic_store_explicit(&atom_1_r8_1, v17, memory_order_seq_cst); + return NULL; +} + +int main(int argc, char *argv[]){ + pthread_t thr0; + pthread_t thr1; + + atomic_init(&vars[2], 0); + atomic_init(&vars[1], 0); + atomic_init(&vars[0], 0); + atomic_init(&atom_1_r1_1, 0); + atomic_init(&atom_1_r8_1, 0); + + pthread_create(&thr0, NULL, t0, NULL); + pthread_create(&thr1, NULL, t1, NULL); + + pthread_join(thr0, NULL); + pthread_join(thr1, NULL); + + int v10 = atomic_load_explicit(&vars[0], memory_order_seq_cst); + int v11 = (v10 == 2); + int v12 = atomic_load_explicit(&atom_1_r1_1, memory_order_seq_cst); + int v13 = atomic_load_explicit(&atom_1_r8_1, memory_order_seq_cst); + int v14_conj = v12 & v13; + int v15_conj = v11 & v14_conj; + if (v15_conj == 1) assert(0); + return 0; +} diff --git a/pool/shard002/C/0061970_befslabel.c b/pool/shard002/C/0061970_befslabel.c new file mode 100644 index 0000000000000000000000000000000000000000..7be96fafd2a6e48b30a646a18897ed0fc0808b15 --- /dev/null +++ b/pool/shard002/C/0061970_befslabel.c @@ -0,0 +1,91 @@ +/* befslabel.c - User interface + + Copyright (C) 1993 Werner Almesberger + Copyright (C) 1998 Roman Hodek + Copyright (C) 2007 Red Hat, Inc. + Copyright (C) 2008-2014 Daniel Baumann + Copyright (C) 2015 Andreas Bombe + Copyright (C) 2016 Luis de Bethencourt + + 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 . + + The complete text of the GNU General Public License + can be found in /usr/share/common-licenses/GPL-3 file. +*/ + +#include "version.h" + +#include +#include +#include +#include +#include +#include +#include + +#include "befs.h" +#include "common.h" +#include "io.h" + +int rw = 0, verbose = 0, write_immed = 0; + +static void usage(int error) +{ + FILE *f = error ? stderr : stdout; + int status = error ? 1 : 0; + + fprintf(f, "usage: fatlabel device [label]\n"); + exit(status); +} + +int main(int argc, char *argv[]) +{ + rw = 0; + + char *device = NULL; + char label[B_OS_NAME_LENGTH] = { 0 }; + + if (argc < 2 || argc > 3) + usage(1); + + if (!strcmp(argv[1], "-h") || !strcmp(argv[1], "--help")) + usage(0); + else if (!strcmp(argv[1], "-V") || !strcmp(argv[1], "--version")) { + printf("befslabel " VERSION " (" VERSION_DATE ")\n"); + exit(0); + } + + device = argv[1]; + if (argc == 3) { + strncpy(label, argv[2], B_OS_NAME_LENGTH); + if (strlen(argv[2]) > B_OS_NAME_LENGTH - 1) { + fprintf(stderr, + "befslabel: labels can be no longer than %d characters\n", + B_OS_NAME_LENGTH); + exit(1); + } + rw = 1; + } + + fs_open(device, rw); + if (!rw) { + fs_read(SECTOR_SIZE, B_OS_NAME_LENGTH, label); + fprintf(stdout, "%s\n", label); + exit(0); + } + + fs_write(SECTOR_SIZE, B_OS_NAME_LENGTH, label, verbose, write_immed); + fs_close(rw); + return 0; +} diff --git a/pool/shard002/C/0061971_utt_test_main.c b/pool/shard002/C/0061971_utt_test_main.c new file mode 100644 index 0000000000000000000000000000000000000000..535b964a132035c01abb24ba11e8756670827c0d --- /dev/null +++ b/pool/shard002/C/0061971_utt_test_main.c @@ -0,0 +1,152 @@ +/*************************************************************************/ +/* */ +/* Language Technologies Institute */ +/* Carnegie Mellon University */ +/* Copyright (c) 1999 */ +/* All Rights Reserved. */ +/* */ +/* Permission is hereby granted, free of charge, to use and distribute */ +/* this software and its documentation without restriction, including */ +/* without limitation the rights to use, copy, modify, merge, publish, */ +/* distribute, sublicense, and/or sell copies of this work, and to */ +/* permit persons to whom this work is furnished to do so, subject to */ +/* the following conditions: */ +/* 1. The code must retain the above copyright notice, this list of */ +/* conditions and the following disclaimer. */ +/* 2. Any modifications must be clearly marked as such. */ +/* 3. Original authors' names are not deleted. */ +/* 4. The authors' names are not used to endorse or promote products */ +/* derived from this software without specific prior written */ +/* permission. */ +/* */ +/* CARNEGIE MELLON UNIVERSITY AND THE CONTRIBUTORS TO THIS WORK */ +/* DISCLAIM ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING */ +/* ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT */ +/* SHALL CARNEGIE MELLON UNIVERSITY NOR THE CONTRIBUTORS BE LIABLE */ +/* FOR ANY SPECIAL, 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. */ +/* */ +/*************************************************************************/ +/* Author: Alan W Black (awb@cs.cmu.edu) */ +/* Date: April 2000 */ +/*************************************************************************/ +/* */ +/* Read some data, build an utt, look up words and extract some feats */ +/* Actually doing osmething here */ +/* */ +/* */ +/*************************************************************************/ +#include +#include "cst_hrg.h" +#include "cst_tokenstream.h" +#include "cst_lexicon.h" + +extern cst_lexicon cmu_lex; +void cmu_lex_init(); + +static int bbb_relation_load(cst_relation *r,const char *filename); +static int WordSylSeg(cst_utterance *u); + +int main(int argc, char **argv) +{ + cst_utterance *u; + cst_relation *r; + cst_item *item=0; + int i; + + cmu_lex_init(); + + u = new_utterance(); + r = utt_relation_create(u,"Word"); + + bbb_relation_load(r,"ttt.txt"); + + WordSylSeg(u); + + for (i=0,item=item_next(relation_head(utt_relation(u,"Segment"))); + item; item=item_next(item),i++) + { + printf("Segment %s %s %s %s\n", + ffeature_string(item,"name"), + ffeature_string(item,"n.name"), + ffeature_string(item,"p.name"), + ffeature_string(item,"R:SylStructure.parent.name") +/* ffeature_string(item,"R:SylStructure.parent.R:Word.n.name"), */ +/* item_feat_float(item,"duration")); */ + ); + } + + delete_utterance(u); + + return 0; +} + +static int WordSylSeg(cst_utterance *u) +{ + cst_item *word; + cst_relation *sylstructure,*seg; + cst_val *phones; + const cst_val *p; + cst_item *ssword,*segitem; + + sylstructure = utt_relation_create(u,"SylStructure"); + seg = utt_relation_create(u,"Segment"); + + for (word=relation_head(utt_relation(u,"Word")); + word; word=item_next(word)) + { + printf("word: %s\n",item_feat_string(word,"name")); + ssword = relation_append(sylstructure,word); + phones = lex_lookup((cst_lexicon *)&cmu_lex,item_feat_string(word,"name"),NULL,NULL); + for (p=phones; p; p=val_cdr(p)) + { + segitem = relation_append(seg,NULL); + item_set(segitem,"name",val_car(p)); + printf("seg: %s\n",item_feat_string(segitem,"name")); + item_add_daughter(ssword,segitem); + } + delete_val_list(phones); + } + + return TRUE; + +} + +static int bbb_relation_load(cst_relation *r,const char *filename) +{ + const char *token; + cst_item *item; + cst_tokenstream *fd; + + fd = ts_open(filename, + cst_ts_default_whitespacesymbols, + cst_ts_default_singlecharsymbols, + cst_ts_default_prepunctuationsymbols, + cst_ts_default_postpunctuationsymbols); + if (fd == 0) + return 0; + + while (!ts_eof(fd)) + { + token = ts_get(fd); + if (cst_streq(token,"")) + continue; + item = relation_append(r,NULL); + item_set_string(item,"name",token); + item_set_string(item,"whitespace",fd->whitespace); + item_set_string(item,"prepunctuation",fd->prepunctuation); + item_set_string(item,"punc",fd->postpunctuation); + item_set_int(item,"file_pos",fd->file_pos); + item_set_int(item,"line_number",fd->line_number); + } + + ts_close(fd); + + return 1; +} + + + diff --git a/pool/shard002/C/0061979_dns.c b/pool/shard002/C/0061979_dns.c new file mode 100644 index 0000000000000000000000000000000000000000..ff9ddffc9d0a1f15e7febf808c5606f69ab48a3d --- /dev/null +++ b/pool/shard002/C/0061979_dns.c @@ -0,0 +1,206 @@ +/* + * DNS support driver + * + * Copyright (c) 2008 Pieter Voorthuijsen + * Copyright (c) 2009 Robin Getz + * + * This is a simple DNS implementation for U-Boot. It will use the first IP + * in the DNS response as NetServerIP. This can then be used for any other + * network related activities. + * + * The packet handling is partly based on TADNS, original copyrights + * follow below. + * + */ + +/* + * Copyright (c) 2004-2005 Sergey Lyubka + * + * "THE BEER-WARE LICENSE" (Revision 42): + * Sergey Lyubka wrote this file. As long as you retain this notice you + * can do whatever you want with this stuff. If we meet some day, and you think + * this stuff is worth it, you can buy me a beer in return. + */ + +#include +#include +#include +#include + +#include "dns.h" + +char *NetDNSResolve; /* The host to resolve */ +char *NetDNSenvvar; /* The envvar to store the answer in */ + +static int DnsOurPort; + +static void +DnsSend(void) +{ + struct header *header; + int n, name_len; + uchar *p, *pkt; + const char *s; + const char *name; + enum dns_query_type qtype = DNS_A_RECORD; + + name = NetDNSResolve; + pkt = p = (uchar *)(NetTxPacket + NetEthHdrSize() + IP_UDP_HDR_SIZE); + + /* Prepare DNS packet header */ + header = (struct header *) pkt; + header->tid = 1; + header->flags = htons(0x100); /* standard query */ + header->nqueries = htons(1); /* Just one query */ + header->nanswers = 0; + header->nauth = 0; + header->nother = 0; + + /* Encode DNS name */ + name_len = strlen(name); + p = (uchar *) &header->data; /* For encoding host name into packet */ + + do { + s = strchr(name, '.'); + if (!s) + s = name + name_len; + + n = s - name; /* Chunk length */ + *p++ = n; /* Copy length */ + memcpy(p, name, n); /* Copy chunk */ + p += n; + + if (*s == '.') + n++; + + name += n; + name_len -= n; + } while (*s != '\0'); + + *p++ = 0; /* Mark end of host name */ + *p++ = 0; /* Some servers require double null */ + *p++ = (unsigned char) qtype; /* Query Type */ + + *p++ = 0; + *p++ = 1; /* Class: inet, 0x0001 */ + + n = p - pkt; /* Total packet length */ + debug("Packet size %d\n", n); + + DnsOurPort = random_port(); + + NetSendUDPPacket(NetServerEther, NetOurDNSIP, DNS_SERVICE_PORT, + DnsOurPort, n); + debug("DNS packet sent\n"); +} + +static void +DnsTimeout(void) +{ + puts("Timeout\n"); + net_set_state(NETLOOP_FAIL); +} + +static void +DnsHandler(uchar *pkt, unsigned dest, IPaddr_t sip, unsigned src, unsigned len) +{ + struct header *header; + const unsigned char *p, *e, *s; + u16 type, i; + int found, stop, dlen; + char IPStr[22]; + IPaddr_t IPAddress; + + + debug("%s\n", __func__); + if (dest != DnsOurPort) + return; + + for (i = 0; i < len; i += 4) + debug("0x%p - 0x%.2x 0x%.2x 0x%.2x 0x%.2x\n", + pkt+i, pkt[i], pkt[i+1], pkt[i+2], pkt[i+3]); + + /* We sent one query. We want to have a single answer: */ + header = (struct header *) pkt; + if (ntohs(header->nqueries) != 1) + return; + + /* Received 0 answers */ + if (header->nanswers == 0) { + puts("DNS: host not found\n"); + net_set_state(NETLOOP_SUCCESS); + return; + } + + /* Skip host name */ + s = &header->data[0]; + e = pkt + len; + for (p = s; p < e && *p != '\0'; p++) + continue; + + /* We sent query class 1, query type 1 */ + if (&p[5] > e || get_unaligned_be16(p+1) != DNS_A_RECORD) { + puts("DNS: response was not an A record\n"); + net_set_state(NETLOOP_SUCCESS); + return; + } + + /* Go to the first answer section */ + p += 5; + + /* Loop through the answers, we want A type answer */ + for (found = stop = 0; !stop && &p[12] < e; ) { + + /* Skip possible name in CNAME answer */ + if (*p != 0xc0) { + while (*p && &p[12] < e) + p++; + p--; + } + debug("Name (Offset in header): %d\n", p[1]); + + type = get_unaligned_be16(p+2); + debug("type = %d\n", type); + if (type == DNS_CNAME_RECORD) { + /* CNAME answer. shift to the next section */ + debug("Found canonical name\n"); + dlen = get_unaligned_be16(p+10); + debug("dlen = %d\n", dlen); + p += 12 + dlen; + } else if (type == DNS_A_RECORD) { + debug("Found A-record\n"); + found = stop = 1; + } else { + debug("Unknown type\n"); + stop = 1; + } + } + + if (found && &p[12] < e) { + + dlen = get_unaligned_be16(p+10); + p += 12; + memcpy(&IPAddress, p, 4); + + if (p + dlen <= e) { + ip_to_string(IPAddress, IPStr); + printf("%s\n", IPStr); + if (NetDNSenvvar) + setenv(NetDNSenvvar, IPStr); + } else + puts("server responded with invalid IP number\n"); + } + + net_set_state(NETLOOP_SUCCESS); +} + +void +DnsStart(void) +{ + debug("%s\n", __func__); + + NetSetTimeout(DNS_TIMEOUT, DnsTimeout); + net_set_udp_handler(DnsHandler); + + DnsSend(); +} diff --git a/pool/shard002/C/0061986_rockchip-hdmi-card.c b/pool/shard002/C/0061986_rockchip-hdmi-card.c new file mode 100644 index 0000000000000000000000000000000000000000..3a3f8e21a6cd520328cb545247e66e28ec3b515b --- /dev/null +++ b/pool/shard002/C/0061986_rockchip-hdmi-card.c @@ -0,0 +1,179 @@ +/* + * rockchip-hdmi-card.c + * + * 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 "rk29_pcm.h" +#include "rk29_i2s.h" + +#ifdef HDMI_DEBUG +#define DBG(format, ...) \ + printk(KERN_INFO "HDMI Card: " format "\n", ## __VA_ARGS__) +#else +#define DBG(format, ...) +#endif + +#define DRV_NAME "rockchip-hdmi-audio" + +static int rockchip_hdmi_dai_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 *cpu_dai = rtd->cpu_dai; + unsigned int pll_out = 0; + int div_bclk,div_mclk; + int ret; + struct clk *general_pll; + + DBG("Enter::%s----%d\n",__FUNCTION__,__LINE__); + { + /* set cpu DAI configuration */ + #if defined (CONFIG_SND_RK29_CODEC_SOC_SLAVE) + DBG("Set cpu_dai master\n"); + ret = snd_soc_dai_set_fmt(cpu_dai, SND_SOC_DAIFMT_I2S | + SND_SOC_DAIFMT_NB_NF | SND_SOC_DAIFMT_CBM_CFM); + #endif + #if defined (CONFIG_SND_RK29_CODEC_SOC_MASTER) + ret = snd_soc_dai_set_fmt(cpu_dai, SND_SOC_DAIFMT_I2S | + SND_SOC_DAIFMT_NB_NF | SND_SOC_DAIFMT_CBS_CFS); + DBG("Set cpu_dai slave\n"); + #endif + if (ret < 0) + return ret; + } + + switch(params_rate(params)) { + case 8000: + case 16000: + case 24000: + case 32000: + case 48000: + case 96000: + pll_out = 12288000; + break; + case 11025: + case 22050: + case 44100: + case 88200: + pll_out = 11289600; + break; + case 176400: + pll_out = 11289600*2; + break; + case 192000: + pll_out = 12288000*2; + break; + default: + DBG("Enter:%s, %d, Error rate=%d\n",__FUNCTION__,__LINE__,params_rate(params)); + return -EINVAL; + break; + } + DBG("Enter:%s, %d, rate=%d\n",__FUNCTION__,__LINE__,params_rate(params)); + #if defined (CONFIG_SND_RK29_CODEC_SOC_MASTER) + snd_soc_dai_set_sysclk(cpu_dai, 0, pll_out, 0); + #endif + + #if defined (CONFIG_SND_RK29_CODEC_SOC_SLAVE) + + div_bclk = 63; + div_mclk = pll_out/(params_rate(params)*64) - 1; + +// DBG("func is%s,gpll=%ld,pll_out=%ld,div_mclk=%ld\n", +// __FUNCTION__,clk_get_rate(general_pll),pll_out,div_mclk); + snd_soc_dai_set_sysclk(cpu_dai, 0, pll_out, 0); + snd_soc_dai_set_clkdiv(cpu_dai, ROCKCHIP_DIV_BCLK,div_bclk); + snd_soc_dai_set_clkdiv(cpu_dai, ROCKCHIP_DIV_MCLK, div_mclk); +// DBG("Enter:%s, %d, LRCK=%d\n",__FUNCTION__,__LINE__,(pll_out/4)/params_rate(params)); + #endif + return 0; +} + +static struct snd_soc_ops rockchip_hdmi_dai_ops = { + .hw_params = rockchip_hdmi_dai_hw_params, +}; + +static struct snd_soc_dai_link rockchip_hdmi_dai = { + .name = "HDMI", + .stream_name = "HDMI", + .cpu_dai_name = "rk29_i2s.0", + .platform_name = "rockchip-audio", + .codec_name = "rockchip-hdmi-codec", + .codec_dai_name = "hdmi-audio-codec", + .ops = &rockchip_hdmi_dai_ops, +}; + +static struct snd_soc_card snd_soc_rockchip_hdmi = { + .name = "ROCKCHIP HDMI", + .dai_link = &rockchip_hdmi_dai, + .num_links = 1, +}; + +static __devinit int rockchip_hdmi_probe(struct platform_device *pdev) +{ + struct snd_soc_card *card = &snd_soc_rockchip_hdmi; + int ret; + + DBG("%s", __FUNCTION__); + + card->dev = &pdev->dev; + + ret = snd_soc_register_card(card); + if (ret) { + dev_err(&pdev->dev, "snd_soc_register_card failed (%d)\n", ret); + card->dev = NULL; + return ret; + } + return 0; +} + +static int __devexit rockchip_hdmi_remove(struct platform_device *pdev) +{ + struct snd_soc_card *card = platform_get_drvdata(pdev); + + snd_soc_unregister_card(card); + card->dev = NULL; + return 0; +} + +static struct platform_driver rockchip_hdmi_driver = { + .driver = { + .name = "rockchip-hdmi-audio", + .owner = THIS_MODULE, + }, + .probe = rockchip_hdmi_probe, + .remove = __devexit_p(rockchip_hdmi_remove), +}; + +static int __init rockchip_hdmi_init(void) +{ + return platform_driver_register(&rockchip_hdmi_driver); +} +module_init(rockchip_hdmi_init); + +static void __exit rockchip_hdmi_exit(void) +{ + platform_driver_unregister(&rockchip_hdmi_driver); +} +module_exit(rockchip_hdmi_exit); + +MODULE_DESCRIPTION("Rockchip HDMI machine ASoC driver"); +MODULE_LICENSE("GPL"); +MODULE_ALIAS("platform:" DRV_NAME); diff --git a/pool/shard002/C/0061997_clearenv.c b/pool/shard002/C/0061997_clearenv.c new file mode 100644 index 0000000000000000000000000000000000000000..0abbec30207a63e38006b62947dd10a57bf37892 --- /dev/null +++ b/pool/shard002/C/0061997_clearenv.c @@ -0,0 +1,21 @@ +#define _GNU_SOURCE +#include +#include + +static void dummy(char *old, char *new) {} +weak_alias(dummy, __env_rm_add); + +int clearenv() +{ +#ifdef __wasilibc_unmodified_upstream // Lazy environment variable init. +#else +// This specialized header is included within the function body to arranges for +// the environment variables to be lazily initialized. It redefined `__environ`, +// so don't remove or reorder it with respect to other code. +#include "wasi/libc-environ-compat.h" +#endif + char **e = __environ; + __environ = 0; + if (e) while (*e) __env_rm_add(*e++, 0); + return 0; +} diff --git a/pool/shard002/C/0061998_fmap.c b/pool/shard002/C/0061998_fmap.c new file mode 100644 index 0000000000000000000000000000000000000000..490cadb4264b99c0e01999e4b844c7ba6d953ce2 --- /dev/null +++ b/pool/shard002/C/0061998_fmap.c @@ -0,0 +1,157 @@ +/* + * This file is part of the coreboot project. + * + * Copyright (C) 2012 The ChromiumOS Authors. 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; 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 "fmap.h" + +static int is_fmap_signature_valid(const struct fmap *fmap) +{ + const char reversed_sig[] = FMAP_REVERSED_SIGNATURE; + const char *p2 = reversed_sig + sizeof(FMAP_REVERSED_SIGNATURE) - 2; + const char *p1 = (char *)fmap; + + while (p2 >= reversed_sig) + if (*p1++ != *p2--) { + printk(BIOS_ERR, "No FMAP found at %p.\n", fmap); + return 1; + } + + printk(BIOS_DEBUG, "FMAP: Found \"%s\" version %d.%d at %p.\n", + fmap->name, fmap->ver_major, fmap->ver_minor, fmap); + printk(BIOS_DEBUG, "FMAP: base = %llx size = %x #areas = %d\n", + (unsigned long long)fmap->base, fmap->size, fmap->nareas); + + return 0; +} + +/* Find FMAP data structure in ROM. + * See http://code.google.com/p/flashmap/ for more information on FMAP. + */ +const struct fmap *fmap_find(void) +{ + /* FIXME: Get rid of the hard codes. The "easy" way would be to + * do a binary search, but since ROM accesses are slow, we don't + * want to spend a lot of time looking for the FMAP. An elegant + * solution would be to store a pointer to the FMAP in the CBFS + * master header; that would require some more changes to cbfstool + * and possibly cros_bundle_firmware. + */ + const struct fmap *fmap; + struct cbfs_media media; + size_t size; + + if (init_default_cbfs_media(&media)) { + printk(BIOS_ERR, "failed to init default cbfs media\n"); + return NULL; + } + + media.open(&media); + fmap = media.map(&media, CONFIG_FLASHMAP_OFFSET, sizeof(*fmap)); + + if (fmap == CBFS_MEDIA_INVALID_MAP_ADDRESS) { + printk(BIOS_ERR, "failed to map FMAP header\n"); + media.close(&media); + return NULL; + } + + if (is_fmap_signature_valid(fmap)) { + media.unmap(&media, fmap); + media.close(&media); + return NULL; + } + + size = sizeof(*fmap) + sizeof(struct fmap_area) * fmap->nareas; + media.unmap(&media, fmap); + fmap = media.map(&media, CONFIG_FLASHMAP_OFFSET, size); + + if (fmap == CBFS_MEDIA_INVALID_MAP_ADDRESS) { + printk(BIOS_ERR, "failed to map FMAP (size=%zu)\n", size); + media.unmap(&media, fmap); + media.close(&media); + return NULL; + } + + media.close(&media); + return fmap; +} + +const struct fmap_area *find_fmap_area(const struct fmap *fmap, + const char name[]) +{ + const struct fmap_area *area = NULL; + + if (fmap) { + int i; + for (i = 0; i < fmap->nareas; i++) { + if (!strcmp((const char *)fmap->areas[i].name, name)) { + area = &fmap->areas[i]; + break; + } + } + } + + if (area) { + printk(BIOS_DEBUG, "FMAP: area %s found\n", name); + printk(BIOS_DEBUG, "FMAP: offset: %x\n", area->offset); + printk(BIOS_DEBUG, "FMAP: size: %d bytes\n", area->size); + } else { + printk(BIOS_DEBUG, "FMAP: area %s not found\n", name); + } + + return area; +} + +int find_fmap_entry(const char name[], void **pointer) +{ + MAYBE_STATIC const struct fmap *fmap = NULL; + const struct fmap_area *area; + void *base = NULL; + + if (!fmap) + fmap = fmap_find(); + + area = find_fmap_area(fmap, name); + + if (!area) + return -1; + + /* Right now cros_bundle_firmware does not write a valid + * base address into the FMAP. Hence, if base is 0, assume + * 4GB-8MB as base address. + */ + if (fmap->base) { + base = (void *)(unsigned long)fmap->base; + printk(BIOS_DEBUG, "FMAP: %s base at %p\n", name, base); + } else { +#if CONFIG_ARCH_X86 + base = (void *)(0 - CONFIG_ROM_SIZE); + printk(BIOS_WARNING, "FMAP: No valid base address, using" + " 0x%p\n", base); +#endif + } + + *pointer = (void*) ((uintptr_t)base + area->offset); + printk(BIOS_DEBUG, "FMAP: %s at %p (offset %x)\n", + name, *pointer, area->offset); + return area->size; +} diff --git a/pool/shard002/C/0062004_mpxxdtyy-i2s.c b/pool/shard002/C/0062004_mpxxdtyy-i2s.c new file mode 100644 index 0000000000000000000000000000000000000000..e65d8d3c6d0f83976be2b509b9a7e826160f5fea --- /dev/null +++ b/pool/shard002/C/0062004_mpxxdtyy-i2s.c @@ -0,0 +1,146 @@ +/* + * Copyright (c) 2018 STMicroelectronics + * + * SPDX-License-Identifier: Apache-2.0 + */ + +#define DT_DRV_COMPAT st_mpxxdtyy + +#include "mpxxdtyy.h" +#include + +#define LOG_LEVEL CONFIG_AUDIO_DMIC_LOG_LEVEL +#include +LOG_MODULE_DECLARE(mpxxdtyy); + +#if DT_ANY_INST_ON_BUS_STATUS_OKAY(i2s) + +#define NUM_RX_BLOCKS 4 +#define PDM_BLOCK_MAX_SIZE_BYTES 512 + +K_MEM_SLAB_DEFINE(rx_pdm_i2s_mslab, PDM_BLOCK_MAX_SIZE_BYTES, NUM_RX_BLOCKS, 1); + +int mpxxdtyy_i2s_read(const struct device *dev, uint8_t stream, void **buffer, + size_t *size, int32_t timeout) +{ + int ret; + const struct mpxxdtyy_config *config = dev->config; + struct mpxxdtyy_data *const data = dev->data; + void *pdm_block, *pcm_block; + size_t pdm_size; + TPDMFilter_InitStruct *pdm_filter = &data->pdm_filter[0]; + + ret = i2s_read(config->comm_master, &pdm_block, &pdm_size); + if (ret != 0) { + LOG_ERR("read failed (%d)", ret); + return ret; + } + + ret = k_mem_slab_alloc(data->pcm_mem_slab, + &pcm_block, K_NO_WAIT); + if (ret < 0) { + return ret; + } + + sw_filter_lib_run(pdm_filter, pdm_block, pcm_block, pdm_size, + data->pcm_mem_size); + k_mem_slab_free(&rx_pdm_i2s_mslab, &pdm_block); + + *buffer = pcm_block; + *size = data->pcm_mem_size; + + return 0; +} + +int mpxxdtyy_i2s_trigger(const struct device *dev, enum dmic_trigger cmd) +{ + int ret; + const struct mpxxdtyy_config *config = dev->config; + struct mpxxdtyy_data *const data = dev->data; + enum i2s_trigger_cmd i2s_cmd; + enum dmic_state tmp_state; + + switch (cmd) { + case DMIC_TRIGGER_START: + if (data->state == DMIC_STATE_CONFIGURED) { + tmp_state = DMIC_STATE_ACTIVE; + i2s_cmd = I2S_TRIGGER_START; + } else { + return 0; + } + break; + case DMIC_TRIGGER_STOP: + if (data->state == DMIC_STATE_ACTIVE) { + tmp_state = DMIC_STATE_CONFIGURED; + i2s_cmd = I2S_TRIGGER_STOP; + } else { + return 0; + } + break; + default: + return -EINVAL; + } + + ret = i2s_trigger(config->comm_master, I2S_DIR_RX, i2s_cmd); + if (ret != 0) { + LOG_ERR("trigger failed with %d error", ret); + return ret; + } + + data->state = tmp_state; + return 0; +} + +int mpxxdtyy_i2s_configure(const struct device *dev, struct dmic_cfg *cfg) +{ + int ret; + const struct mpxxdtyy_config *config = dev->config; + struct mpxxdtyy_data *const data = dev->data; + uint8_t chan_size = cfg->streams->pcm_width; + uint32_t audio_freq = cfg->streams->pcm_rate; + uint16_t factor; + + /* PCM buffer size */ + data->pcm_mem_slab = cfg->streams->mem_slab; + data->pcm_mem_size = cfg->streams->block_size; + + /* check requested min pdm frequency */ + if (cfg->io.min_pdm_clk_freq < MPXXDTYY_MIN_PDM_FREQ || + cfg->io.min_pdm_clk_freq > cfg->io.max_pdm_clk_freq) { + return -EINVAL; + } + + /* check requested max pdm frequency */ + if (cfg->io.max_pdm_clk_freq > MPXXDTYY_MAX_PDM_FREQ || + cfg->io.max_pdm_clk_freq < cfg->io.min_pdm_clk_freq) { + return -EINVAL; + } + + factor = sw_filter_lib_init(dev, cfg); + if (factor == 0U) { + return -EINVAL; + } + + /* configure I2S channels */ + struct i2s_config i2s_cfg; + + i2s_cfg.word_size = chan_size; + i2s_cfg.channels = cfg->channel.req_num_chan; + i2s_cfg.format = I2S_FMT_DATA_FORMAT_LEFT_JUSTIFIED | + I2S_FMT_BIT_CLK_INV; + i2s_cfg.options = I2S_OPT_FRAME_CLK_MASTER | I2S_OPT_BIT_CLK_MASTER; + i2s_cfg.frame_clk_freq = audio_freq * factor / chan_size; + i2s_cfg.block_size = data->pcm_mem_size * (factor / chan_size); + i2s_cfg.mem_slab = &rx_pdm_i2s_mslab; + i2s_cfg.timeout = 2000; + + ret = i2s_configure(config->comm_master, I2S_DIR_RX, &i2s_cfg); + if (ret != 0) { + LOG_ERR("I2S device configuration error"); + return ret; + } + + data->state = DMIC_STATE_CONFIGURED; + return 0; +} +#endif /* DT_ANY_INST_ON_BUS_STATUS_OKAY(i2s) */ diff --git a/pool/shard002/C/0062018_xt_CONNSECMARK.c b/pool/shard002/C/0062018_xt_CONNSECMARK.c new file mode 100644 index 0000000000000000000000000000000000000000..35b6e945076a3ea6b0413c77dd4d980bf6a05842 --- /dev/null +++ b/pool/shard002/C/0062018_xt_CONNSECMARK.c @@ -0,0 +1,143 @@ +/* + * This module is used to copy security markings from packets + * to connections, and restore security markings from connections + * back to packets. This would normally be performed in conjunction + * with the SECMARK target and state match. + * + * Based somewhat on CONNMARK: + * Copyright (C) 2002,2004 MARA Systems AB + * by Henrik Nordstrom + * + * (C) 2006,2008 Red Hat, Inc., James Morris + * + * 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. + * + */ +#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt +#include +#include +#include +#include +#include +#include + +MODULE_LICENSE("GPL"); +MODULE_AUTHOR("James Morris "); +MODULE_DESCRIPTION("Xtables: target for copying between connection and security mark"); +MODULE_ALIAS("ipt_CONNSECMARK"); +MODULE_ALIAS("ip6t_CONNSECMARK"); + +/* + + + */ +static void secmark_save(const struct sk_buff *skb) +{ + if (skb->secmark) { + struct nf_conn *ct; + enum ip_conntrack_info ctinfo; + + ct = nf_ct_get(skb, &ctinfo); + if (ct && !ct->secmark) { + ct->secmark = skb->secmark; + nf_conntrack_event_cache(IPCT_SECMARK, ct); + } + } +} + +/* + + + */ +static void secmark_restore(struct sk_buff *skb) +{ + if (!skb->secmark) { + const struct nf_conn *ct; + enum ip_conntrack_info ctinfo; + + ct = nf_ct_get(skb, &ctinfo); + if (ct && ct->secmark) + skb->secmark = ct->secmark; + } +} + +static unsigned int +connsecmark_tg(struct sk_buff *skb, const struct xt_action_param *par) +{ + const struct xt_connsecmark_target_info *info = par->targinfo; + + switch (info->mode) { + case CONNSECMARK_SAVE: + secmark_save(skb); + break; + + case CONNSECMARK_RESTORE: + secmark_restore(skb); + break; + + default: + BUG(); + } + + return XT_CONTINUE; +} + +static int connsecmark_tg_check(const struct xt_tgchk_param *par) +{ + const struct xt_connsecmark_target_info *info = par->targinfo; + int ret; + + if (strcmp(par->table, "mangle") != 0 && + strcmp(par->table, "security") != 0) { + pr_info("target only valid in the \'mangle\' " + "or \'security\' tables, not \'%s\'.\n", par->table); + return -EINVAL; + } + + switch (info->mode) { + case CONNSECMARK_SAVE: + case CONNSECMARK_RESTORE: + break; + + default: + pr_info("invalid mode: %hu\n", info->mode); + return -EINVAL; + } + + ret = nf_ct_l3proto_try_module_get(par->family); + if (ret < 0) + pr_info("cannot load conntrack support for proto=%u\n", + par->family); + return ret; +} + +static void connsecmark_tg_destroy(const struct xt_tgdtor_param *par) +{ + nf_ct_l3proto_module_put(par->family); +} + +static struct xt_target connsecmark_tg_reg __read_mostly = { + .name = "CONNSECMARK", + .revision = 0, + .family = NFPROTO_UNSPEC, + .checkentry = connsecmark_tg_check, + .destroy = connsecmark_tg_destroy, + .target = connsecmark_tg, + .targetsize = sizeof(struct xt_connsecmark_target_info), + .me = THIS_MODULE, +}; + +static int __init connsecmark_tg_init(void) +{ + return xt_register_target(&connsecmark_tg_reg); +} + +static void __exit connsecmark_tg_exit(void) +{ + xt_unregister_target(&connsecmark_tg_reg); +} + +module_init(connsecmark_tg_init); +module_exit(connsecmark_tg_exit); diff --git a/pool/shard002/C/0062023_SetWMProps.c b/pool/shard002/C/0062023_SetWMProps.c new file mode 100644 index 0000000000000000000000000000000000000000..c2a2b90f2184e5bc2eb38d22dd6809234e79e9b2 --- /dev/null +++ b/pool/shard002/C/0062023_SetWMProps.c @@ -0,0 +1,80 @@ +#include "nxlib.h" +#include +#include + +void +XSetWMName(Display * display, Window w, XTextProperty * name) +{ + GR_WM_PROPERTIES props; + + if (!name || !name->value) + return; + + props.flags = GR_WM_FLAGS_TITLE; + props.title = name->value; + GrSetWMProperties(w, &props); +} + +/* Not used */ +void +XSetWMIconName(Display * display, Window w, XTextProperty * name) +{ +} + +/* Not used */ +void +XSetWMNormalHints(Display * display, Window w, XSizeHints * hints) +{ +} + +/* Not used */ +int +XSetWMHints(Display * display, Window w, XWMHints * hints) +{ + return 1; +} + +/* Not used */ +void +XSetWMClassHints(Display * display, Window w, XClassHint * hints) +{ +} + +void +XSetWMProperties(Display * display, Window w, XTextProperty * window_name, + XTextProperty * icon_name, char **argv, int argc, + XSizeHints * normal_hints, XWMHints * wm_hints, XClassHint *class_hints) +{ + if (window_name) + XSetWMName(display, w, window_name); + if (icon_name) + XSetWMIconName(display, w, icon_name); + if (normal_hints) + XSetWMNormalHints(display, w, normal_hints); + if (wm_hints) + XSetWMHints(display, w, wm_hints); + if (class_hints) + XSetWMClassHints(display, w, class_hints); +} + +void +XmbSetWMProperties(Display *dpy, Window w, _Xconst char *windowName, + _Xconst char *iconName, char **argv, int argc, XSizeHints * sizeHints, + XWMHints * wmHints, XClassHint * classHints) +{ + XTextProperty wname, iname; + XTextProperty *wprop = NULL; + XTextProperty *iprop = NULL; + + /* fake up XTextProperty struct members for XSetWMName*/ + if (windowName) { + wname.value = (unsigned char *)windowName; + wprop = &wname; + } + if (iconName) { + iname.value = (unsigned char *)iconName; + iprop = &iname; + } + XSetWMProperties(dpy, w, wprop, iprop, argv, argc, sizeHints, wmHints, + classHints); +} diff --git a/pool/shard002/C/0062026_socketio.c b/pool/shard002/C/0062026_socketio.c new file mode 100644 index 0000000000000000000000000000000000000000..f110db6712b441f5d32e99ed9e0621458e73e89e --- /dev/null +++ b/pool/shard002/C/0062026_socketio.c @@ -0,0 +1,183 @@ +/* @(#)$Id: socketio.c,v 1.7 1998/06/23 23:35:08 seks Exp $ */ + +/* Undernet Channel Service (X) + * Copyright (C) 1995-2002 Robin Thellend + * + * 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 + * + * The author can be contact by email at + * + * Please note that this software is unsupported and mostly + * obsolete. It was replaced by GNUworld/CMaster. See + * http://gnuworld.sourceforge.net/ for more information. + */ + +/* These routines were first developed for the telnet3d project. + * Special thanks to Danny Mitchell (wildthang@irc) for his help. + */ + + +#include "h.h" + +#ifdef DOHTTP +#include + +extern void chat_close(http_socket *, char *); + +int readfrom_http(http_socket * client) +{ + void http_log(char *fmt,...); + char buf[1024]; + int length; + + if ((length = read(client->fd, buf, 1023)) <= 0) + { + if (errno == EWOULDBLOCK || errno == EAGAIN) + { + return 0; + } + else + { + if (client->status == HTTP_CHAT) + chat_close(client, "read error"); + close(client->fd); + client->fd = -1; + client->status = HTTP_ERROR; + return -1; + } + } + buf[length] = '\0'; +#ifdef DEBUG + printf("AA: |%s|\n", buf); +#endif + + if (copy_to_buffer(&client->inbuf, buf, length) >= 4096) + { + http_log("ERROR: Recv'd more than 4K from client! (flood?)"); + if (client->status == HTTP_CHAT) + chat_close(client, "Input packet too big"); + client->status = HTTP_ERROR; + close(client->fd); + client->fd = -1; + return -1; + } + + if (find_char_in_buffer(&client->inbuf, '\n', 1023)) + { + while (find_char_in_buffer(&client->inbuf, '\n', 1023) && + client->status != HTTP_PIPE && + client->status != HTTP_ENDING && + client->status != HTTP_ERROR) + { + copy_from_buffer(&client->inbuf, buf, '\n', 1023); + parse_http(client, buf); + } + /* Check for STUPID MSIE! who doesn't send a \n after post data + ** so check for a = in the first 10 chars, assume *ugh* it's post data + */ + if (find_char_in_buffer(&client->inbuf, '=', 10)) + { + if (client->status != HTTP_PIPE && + client->status != HTTP_ENDING && + client->status != HTTP_ERROR) + { +#ifdef DEBUG + printf("SEND\n"); +#endif + copy_from_buffer(&client->inbuf, buf, '\0', 1023); + parse_http(client, buf); + } + } + } + else if (length > 200) + { + if (client->status == HTTP_CHAT) + chat_close(client, "line too long"); + client->status = HTTP_ERROR; + close(client->fd); + client->fd = -1; + return -1; + } + return 1; +} + +int flush_http_buffer(http_socket * client) +{ + http_file_pipe *fpipe; + char buf[1024]; + int length; + int count; + + if (client == NULL || client->outbuf == NULL) + return -1; + + while ((count = look_in_buffer(&client->outbuf, buf, '\0', 1023)) > 0) + { + if ((length = write(client->fd, buf, count)) <= 0) + { + if ((errno == EWOULDBLOCK || errno == EAGAIN) && length != 0) + { + return 0; + } + else + { + if (client->status == HTTP_PIPE) + { + for (fpipe = FilePipes; fpipe != NULL; fpipe = fpipe->next) + { + if (fpipe->hsock == client) + { + close(fpipe->fd); + destroy_file_pipe(fpipe); + break; + } + } + } + if (client->status == HTTP_CHAT) + chat_close(client, "write error"); + close(client->fd); + client->fd = -1; + client->status = HTTP_ERROR; + return -1; + } + } + else + { + skip_char_in_buffer(&client->outbuf, length); + HTTPTTLSENTBYTES += length; + } + } + + return 0; +} + +/* sendto_client() by SeKs + * args (struct buffer_block **block, char *format, args...) + * adds 'args' according to 'format' to the client's output + * buffer. + */ +long sendto_http(http_socket * sck, char *format,...) +{ + va_list args; + char string[1024]; + + va_start(args, format); + vsprintf(string, format, args); + va_end(args); + + return copy_to_buffer(&sck->outbuf, string, strlen(string)); +} + +#endif /* DOHTTP */ diff --git a/pool/shard002/C/0062029_winMain.c b/pool/shard002/C/0062029_winMain.c new file mode 100644 index 0000000000000000000000000000000000000000..99e9b311c8fc30ab5b0514a69827741f359c3d1a --- /dev/null +++ b/pool/shard002/C/0062029_winMain.c @@ -0,0 +1,388 @@ +/* + * winMain.c -- + * + * Main entry point for wish and other Tk-based applications. + * + * Copyright (c) 1995-1997 Sun Microsystems, Inc. + * Copyright (c) 1998-1999 by Scriptics Corporation. + * + * See the file "license.terms" for information on usage and redistribution + * of this file, and for a DISCLAIMER OF ALL WARRANTIES. + * + * RCS: @(#) $Id$ + */ + +#include +#define WIN32_LEAN_AND_MEAN +#include +#undef WIN32_LEAN_AND_MEAN +#include +#include + +#include "tkInt.h" + +/* + * The following declarations refer to internal Tk routines. These + * interfaces are available for use, but are not supported. + */ + + +/* + * Forward declarations for procedures defined later in this file: + */ + +static void setargv _ANSI_ARGS_((int *argcPtr, char ***argvPtr)); +static void WishPanic _ANSI_ARGS_(TCL_VARARGS(CONST char *,format)); + +#ifdef TK_TEST +extern int Tktest_Init(Tcl_Interp *interp); +#endif /* TK_TEST */ + +static BOOL consoleRequired = TRUE; + +/* + * The following #if block allows you to change the AppInit + * function by using a #define of TCL_LOCAL_APPINIT instead + * of rewriting this entire file. The #if checks for that + * #define and uses Tcl_AppInit if it doesn't exist. + */ + +#ifndef TK_LOCAL_APPINIT +#define TK_LOCAL_APPINIT Tcl_AppInit +#endif +extern int TK_LOCAL_APPINIT _ANSI_ARGS_((Tcl_Interp *interp)); + +/* + * The following #if block allows you to change how Tcl finds the startup + * script, prime the library or encoding paths, fiddle with the argv, + * etc., without needing to rewrite Tk_Main() + */ + +#ifdef TK_LOCAL_MAIN_HOOK +extern int TK_LOCAL_MAIN_HOOK _ANSI_ARGS_((int *argc, char ***argv)); +#endif + + +/* + *---------------------------------------------------------------------- + * + * WinMain -- + * + * Main entry point from Windows. + * + * Results: + * Returns false if initialization fails, otherwise it never + * returns. + * + * Side effects: + * Just about anything, since from here we call arbitrary Tcl code. + * + *---------------------------------------------------------------------- + */ + +int APIENTRY +WinMain(hInstance, hPrevInstance, lpszCmdLine, nCmdShow) + HINSTANCE hInstance; + HINSTANCE hPrevInstance; + LPSTR lpszCmdLine; + int nCmdShow; +{ + char **argv; + int argc; + char buffer[MAX_PATH+1]; + char *p; + + Tcl_SetPanicProc(WishPanic); + + /* + * Create the console channels and install them as the standard + * channels. All I/O will be discarded until Tk_CreateConsoleWindow is + * called to attach the console to a text widget. + */ + + consoleRequired = TRUE; + + /* + * Set up the default locale to be standard "C" locale so parsing + * is performed correctly. + */ + + setlocale(LC_ALL, "C"); + setargv(&argc, &argv); + + /* + * Replace argv[0] with full pathname of executable, and forward + * slashes substituted for backslashes. + */ + + GetModuleFileName(NULL, buffer, sizeof(buffer)); + argv[0] = buffer; + for (p = buffer; *p != '\0'; p++) { + if (*p == '\\') { + *p = '/'; + } + } + +#ifdef TK_LOCAL_MAIN_HOOK + TK_LOCAL_MAIN_HOOK(&argc, &argv); +#endif + + Tk_Main(argc, argv, TK_LOCAL_APPINIT); + return 1; +} + + +/* + *---------------------------------------------------------------------- + * + * Tcl_AppInit -- + * + * This procedure performs application-specific initialization. + * Most applications, especially those that incorporate additional + * packages, will have their own version of this procedure. + * + * Results: + * Returns a standard Tcl completion code, and leaves an error + * message in the interp's result if an error occurs. + * + * Side effects: + * Depends on the startup script. + * + *---------------------------------------------------------------------- + */ + +int +Tcl_AppInit(interp) + Tcl_Interp *interp; /* Interpreter for application. */ +{ + if (Tcl_Init(interp) == TCL_ERROR) { + goto error; + } + if (Tk_Init(interp) == TCL_ERROR) { + goto error; + } + Tcl_StaticPackage(interp, "Tk", Tk_Init, Tk_SafeInit); + + /* + * Initialize the console only if we are running as an interactive + * application. + */ + + if (consoleRequired) { + if (Tk_CreateConsoleWindow(interp) == TCL_ERROR) { + goto error; + } + } + +#ifdef TK_TEST + if (Tktest_Init(interp) == TCL_ERROR) { + goto error; + } + Tcl_StaticPackage(interp, "Tktest", Tktest_Init, + (Tcl_PackageInitProc *) NULL); +#endif /* TK_TEST */ + + Tcl_SetVar(interp, "tcl_rcFileName", "~/wishrc.tcl", TCL_GLOBAL_ONLY); + return TCL_OK; + +error: + MessageBeep(MB_ICONEXCLAMATION); + MessageBox(NULL, Tcl_GetStringResult(interp), "Error in Wish", + MB_ICONSTOP | MB_OK | MB_TASKMODAL | MB_SETFOREGROUND); + ExitProcess(1); + /* we won't reach this, but we need the return */ + return TCL_ERROR; +} + +/* + *---------------------------------------------------------------------- + * + * WishPanic -- + * + * Display a message and exit. + * + * Results: + * None. + * + * Side effects: + * Exits the program. + * + *---------------------------------------------------------------------- + */ + +void +WishPanic TCL_VARARGS_DEF(CONST char *,arg1) +{ + va_list argList; + char buf[1024]; + CONST char *format; + + format = TCL_VARARGS_START(CONST char *,arg1,argList); + vsprintf(buf, format, argList); + + MessageBeep(MB_ICONEXCLAMATION); + MessageBox(NULL, buf, "Fatal Error in Wish", + MB_ICONSTOP | MB_OK | MB_TASKMODAL | MB_SETFOREGROUND); +#ifdef _MSC_VER + DebugBreak(); +#endif + ExitProcess(1); +} +/* + *------------------------------------------------------------------------- + * + * setargv -- + * + * Parse the Windows command line string into argc/argv. Done here + * because we don't trust the builtin argument parser in crt0. + * Windows applications are responsible for breaking their command + * line into arguments. + * + * 2N backslashes + quote -> N backslashes + begin quoted string + * 2N + 1 backslashes + quote -> literal + * N backslashes + non-quote -> literal + * quote + quote in a quoted string -> single quote + * quote + quote not in quoted string -> empty string + * quote -> begin quoted string + * + * Results: + * Fills argcPtr with the number of arguments and argvPtr with the + * array of arguments. + * + * Side effects: + * Memory allocated. + * + *-------------------------------------------------------------------------- + */ + +static void +setargv(argcPtr, argvPtr) + int *argcPtr; /* Filled with number of argument strings. */ + char ***argvPtr; /* Filled with argument strings (malloc'd). */ +{ + char *cmdLine, *p, *arg, *argSpace; + char **argv; + int argc, size, inquote, copy, slashes; + + cmdLine = GetCommandLine(); /* INTL: BUG */ + + /* + * Precompute an overly pessimistic guess at the number of arguments + * in the command line by counting non-space spans. + */ + + size = 2; + for (p = cmdLine; *p != '\0'; p++) { + if ((*p == ' ') || (*p == '\t')) { /* INTL: ISO space. */ + size++; + while ((*p == ' ') || (*p == '\t')) { /* INTL: ISO space. */ + p++; + } + if (*p == '\0') { + break; + } + } + } + argSpace = (char *) Tcl_Alloc( + (unsigned) (size * sizeof(char *) + strlen(cmdLine) + 1)); + argv = (char **) argSpace; + argSpace += size * sizeof(char *); + size--; + + p = cmdLine; + for (argc = 0; argc < size; argc++) { + argv[argc] = arg = argSpace; + while ((*p == ' ') || (*p == '\t')) { /* INTL: ISO space. */ + p++; + } + if (*p == '\0') { + break; + } + + inquote = 0; + slashes = 0; + while (1) { + copy = 1; + while (*p == '\\') { + slashes++; + p++; + } + if (*p == '"') { + if ((slashes & 1) == 0) { + copy = 0; + if ((inquote) && (p[1] == '"')) { + p++; + copy = 1; + } else { + inquote = !inquote; + } + } + slashes >>= 1; + } + + while (slashes) { + *arg = '\\'; + arg++; + slashes--; + } + + if ((*p == '\0') + || (!inquote && ((*p == ' ') || (*p == '\t')))) { /* INTL: ISO space. */ + break; + } + if (copy != 0) { + *arg = *p; + arg++; + } + p++; + } + *arg = '\0'; + argSpace = arg + 1; + } + argv[argc] = NULL; + + *argcPtr = argc; + *argvPtr = argv; +} + +#if !defined(__GNUC__) || defined(TK_TEST) +/* + *---------------------------------------------------------------------- + * + * main -- + * + * Main entry point from the console. + * + * Results: + * None: Tk_Main never returns here, so this procedure never + * returns either. + * + * Side effects: + * Whatever the applications does. + * + *---------------------------------------------------------------------- + */ + +int main(int argc, char **argv) +{ + Tcl_SetPanicProc(WishPanic); + + /* + * Set up the default locale to be standard "C" locale so parsing + * is performed correctly. + */ + + setlocale(LC_ALL, "C"); + + /* + * Create the console channels and install them as the standard + * channels. All I/O will be discarded until Tk_CreateConsoleWindow is + * called to attach the console to a text widget. + */ + + consoleRequired = FALSE; + + Tk_Main(argc, argv, Tcl_AppInit); + return 0; +} +#endif /* !__GNUC__ || TK_TEST */ diff --git a/pool/shard002/C/0062039_writeprob.c b/pool/shard002/C/0062039_writeprob.c new file mode 100644 index 0000000000000000000000000000000000000000..9f74bb92139558ac297c5c42b2d15203aa70380e --- /dev/null +++ b/pool/shard002/C/0062039_writeprob.c @@ -0,0 +1,110 @@ +/* + Write out a problem in SDPA format. +*/ + +#include +#include +#include "declarations.h" + +int write_prob(fname, n, k, C, a, constraints) const char *fname; +int n; +int k; +struct blockmatrix C; +double *a; +struct constraintmatrix *constraints; +{ + FILE *fid; + int i; + int j; + int blk; + struct sparseblock *p; + + /* + * Open up the file for output. + */ + fid = fopen(fname, "w"); + + if (fid == (FILE *)NULL) { + printf("Couldn't open problem file for writing! \n"); + + exit(11); + }; + + /* + * Write out the basic problem size info. + */ + fprintf(fid, "%d \n", k); + fprintf(fid, "%d \n", C.nblocks); + for (i = 1; i <= C.nblocks; i++) { + switch (C.blocks[i].blockcategory) { + case DIAG: + fprintf(fid, "%d ", -C.blocks[i].blocksize); + break; + case MATRIX: + fprintf(fid, "%d ", C.blocks[i].blocksize); + break; + default: + printf("Illegal block type!\n"); + exit(12); + }; + }; + + fprintf(fid, "\n"); + + /* + * Write out the a vector. (c in SDPA terminology) + */ + for (i = 1; i <= k; i++) fprintf(fid, "%.18e ", a[i]); + fprintf(fid, "\n"); + + /* + * Write out the C matrix (F0 in SDPA) + */ + + for (blk = 1; blk <= C.nblocks; blk++) { + switch (C.blocks[blk].blockcategory) { + case DIAG: + for (i = 1; i <= C.blocks[blk].blocksize; i++) { + if (C.blocks[blk].data.vec[i] != 0.0) + fprintf(fid, "0 %d %d %d %.18e \n", blk, i, i, + C.blocks[blk].data.vec[i]); + }; + break; + case MATRIX: + for (i = 1; i <= C.blocks[blk].blocksize; i++) + for (j = i; j <= C.blocks[blk].blocksize; j++) { + if (C.blocks[blk].data.mat[ijtok(i, j, C.blocks[blk].blocksize)] != + 0.0) + fprintf( + fid, "0 %d %d %d %.18e \n", blk, i, j, + C.blocks[blk].data.mat[ijtok(i, j, C.blocks[blk].blocksize)]); + }; + break; + default: + printf("Illegal block type!\n"); + exit(12); + }; + }; + + /* + * Now, start writing out the A_i (F_k in SDPA notation) + */ + + for (i = 1; i <= k; i++) { + p = constraints[i].blocks; + while (p != NULL) { + for (j = 1; j <= p->numentries; j++) { + fprintf(fid, "%d %d %d %d %.18e \n", i, p->blocknum, p->iindices[j], + p->jindices[j], p->entries[j]); + }; + p = p->next; + }; + }; + + /* + * Close up the file and get out. + */ + + fclose(fid); + return (0); +} diff --git a/pool/shard002/C/0062040_mpu6050_trigger.c b/pool/shard002/C/0062040_mpu6050_trigger.c new file mode 100644 index 0000000000000000000000000000000000000000..bc67728f0c702dd026ccdda83b315fab9e000928 --- /dev/null +++ b/pool/shard002/C/0062040_mpu6050_trigger.c @@ -0,0 +1,146 @@ +/* + * Copyright (c) 2016 Intel Corporation + * + * SPDX-License-Identifier: Apache-2.0 + */ + +#include +#include +#include +#include +#include + +#include "mpu6050.h" + +#define LOG_LEVEL CONFIG_SENSOR_LOG_LEVEL +#include +LOG_MODULE_DECLARE(MPU6050); + +int mpu6050_trigger_set(struct device *dev, + const struct sensor_trigger *trig, + sensor_trigger_handler_t handler) +{ + struct mpu6050_data *drv_data = dev->driver_data; + + if (trig->type != SENSOR_TRIG_DATA_READY) { + return -ENOTSUP; + } + + gpio_pin_disable_callback(drv_data->gpio, CONFIG_MPU6050_GPIO_PIN_NUM); + + drv_data->data_ready_handler = handler; + if (handler == NULL) { + return 0; + } + + drv_data->data_ready_trigger = *trig; + + gpio_pin_enable_callback(drv_data->gpio, CONFIG_MPU6050_GPIO_PIN_NUM); + + return 0; +} + +static void mpu6050_gpio_callback(struct device *dev, + struct gpio_callback *cb, u32_t pins) +{ + struct mpu6050_data *drv_data = + CONTAINER_OF(cb, struct mpu6050_data, gpio_cb); + + ARG_UNUSED(pins); + + gpio_pin_disable_callback(dev, CONFIG_MPU6050_GPIO_PIN_NUM); + +#if defined(CONFIG_MPU6050_TRIGGER_OWN_THREAD) + k_sem_give(&drv_data->gpio_sem); +#elif defined(CONFIG_MPU6050_TRIGGER_GLOBAL_THREAD) + k_work_submit(&drv_data->work); +#endif +} + +static void mpu6050_thread_cb(void *arg) +{ + struct device *dev = arg; + struct mpu6050_data *drv_data = dev->driver_data; + + if (drv_data->data_ready_handler != NULL) { + drv_data->data_ready_handler(dev, + &drv_data->data_ready_trigger); + } + + gpio_pin_enable_callback(drv_data->gpio, CONFIG_MPU6050_GPIO_PIN_NUM); +} + +#ifdef CONFIG_MPU6050_TRIGGER_OWN_THREAD +static void mpu6050_thread(int dev_ptr, int unused) +{ + struct device *dev = INT_TO_POINTER(dev_ptr); + struct mpu6050_data *drv_data = dev->driver_data; + + ARG_UNUSED(unused); + + while (1) { + k_sem_take(&drv_data->gpio_sem, K_FOREVER); + mpu6050_thread_cb(dev); + } +} +#endif + +#ifdef CONFIG_MPU6050_TRIGGER_GLOBAL_THREAD +static void mpu6050_work_cb(struct k_work *work) +{ + struct mpu6050_data *drv_data = + CONTAINER_OF(work, struct mpu6050_data, work); + + mpu6050_thread_cb(drv_data->dev); +} +#endif + +int mpu6050_init_interrupt(struct device *dev) +{ + struct mpu6050_data *drv_data = dev->driver_data; + + /* setup data ready gpio interrupt */ + drv_data->gpio = device_get_binding(CONFIG_MPU6050_GPIO_DEV_NAME); + if (drv_data->gpio == NULL) { + LOG_ERR("Failed to get pointer to %s device", + CONFIG_MPU6050_GPIO_DEV_NAME); + return -EINVAL; + } + + gpio_pin_configure(drv_data->gpio, CONFIG_MPU6050_GPIO_PIN_NUM, + GPIO_DIR_IN | GPIO_INT | GPIO_INT_EDGE | + GPIO_INT_ACTIVE_HIGH | GPIO_INT_DEBOUNCE); + + gpio_init_callback(&drv_data->gpio_cb, + mpu6050_gpio_callback, + BIT(CONFIG_MPU6050_GPIO_PIN_NUM)); + + if (gpio_add_callback(drv_data->gpio, &drv_data->gpio_cb) < 0) { + LOG_ERR("Failed to set gpio callback"); + return -EIO; + } + + /* enable data ready interrupt */ + if (i2c_reg_write_byte(drv_data->i2c, CONFIG_MPU6050_I2C_ADDR, + MPU6050_REG_INT_EN, MPU6050_DRDY_EN) < 0) { + LOG_ERR("Failed to enable data ready interrupt."); + return -EIO; + } + +#if defined(CONFIG_MPU6050_TRIGGER_OWN_THREAD) + k_sem_init(&drv_data->gpio_sem, 0, UINT_MAX); + + k_thread_create(&drv_data->thread, drv_data->thread_stack, + CONFIG_MPU6050_THREAD_STACK_SIZE, + (k_thread_entry_t)mpu6050_thread, dev, + 0, NULL, K_PRIO_COOP(CONFIG_MPU6050_THREAD_PRIORITY), + 0, 0); +#elif defined(CONFIG_MPU6050_TRIGGER_GLOBAL_THREAD) + drv_data->work.handler = mpu6050_work_cb; + drv_data->dev = dev; +#endif + + gpio_pin_enable_callback(drv_data->gpio, CONFIG_MPU6050_GPIO_PIN_NUM); + + return 0; +} diff --git a/pool/shard002/C/0062053_wcnss_prealloc.c b/pool/shard002/C/0062053_wcnss_prealloc.c new file mode 100644 index 0000000000000000000000000000000000000000..7dd96135066ba8507ebeefe4bcc0ea5853aee4fd --- /dev/null +++ b/pool/shard002/C/0062053_wcnss_prealloc.c @@ -0,0 +1,76 @@ +#include +#include +#include +#include + +struct wcnss_prealloc wcnss_allocs[] = { + {0, 8 * 1024, NULL}, + {0, 8 * 1024, NULL}, + {0, 8 * 1024, NULL}, + {0, 8 * 1024, NULL}, + {0, 32 * 1024, NULL}, + {0, 32 * 1024, NULL}, + {0, 32 * 1024, NULL}, + {0, 32 * 1024, NULL}, + {0, 32 * 1024, NULL}, + {0, 32 * 1024, NULL}, + {0, 32 * 1024, NULL}, + {0, 64 * 1024, NULL}, + {0, 64 * 1024, NULL}, + {0, 128 * 1024, NULL}, +}; + +void wcnss_prealloc_init (void) +{ + int i = 0; + + for (i = 0; i < ARRAY_SIZE(wcnss_allocs); i++) { + wcnss_allocs[i].occupied = 0; + wcnss_allocs[i].ptr = kmalloc (wcnss_allocs[i].size, GFP_KERNEL); + } +} + +void wcnss_prealloc_deinit (void) +{ + int i = 0; + + for (i = 0; i < ARRAY_SIZE(wcnss_allocs); i++) { + kfree(wcnss_allocs[i].ptr); + } +} + +void * wcnss_prealloc (unsigned int size) +{ + int i = 0; + + for (i = 0; i < ARRAY_SIZE(wcnss_allocs); i++) { + if (wcnss_allocs[i].occupied) continue;; + if (wcnss_allocs[i].size > size) { + /* we found the slot */ + //printk(KERN_INFO"%s : prealloc index%d %d -> %d\n", __func__, + // i, size, wcnss_allocs[i].size); + wcnss_allocs[i].occupied = 1; + return wcnss_allocs[i].ptr; + } + } + printk (KERN_INFO"%s : prealloc failed\n", __func__); + + return NULL; +} +EXPORT_SYMBOL(wcnss_prealloc); + +int wcnss_prefree (void * ptr) +{ + int i = 0; + + for (i = 0; i < ARRAY_SIZE(wcnss_allocs); i++) { + if (wcnss_allocs[i].ptr == ptr) { + //printk(KERN_INFO"%s : free index%d\n", __func__, i); + wcnss_allocs[i].occupied = 0; + return 1; + } + } + + return 0; +} +EXPORT_SYMBOL(wcnss_prefree); diff --git a/pool/shard002/C/0062055_ftwinfnt.c b/pool/shard002/C/0062055_ftwinfnt.c new file mode 100644 index 0000000000000000000000000000000000000000..8e337fbe5307045ccad77eba7ed8734acefae4f0 --- /dev/null +++ b/pool/shard002/C/0062055_ftwinfnt.c @@ -0,0 +1,53 @@ +/***************************************************************************/ +/* */ +/* ftwinfnt.c */ +/* */ +/* FreeType API for accessing Windows FNT specific info (body). */ +/* */ +/* Copyright 2003, 2004, 2014 by */ +/* David Turner, Robert Wilhelm, and Werner Lemberg. */ +/* */ +/* This file is part of the FreeType project, and may only be used, */ +/* modified, and distributed under the terms of the FreeType project */ +/* license, LICENSE.TXT. By continuing to use, modify, or distribute */ +/* this file you indicate that you have read the license and */ +/* understand and accept it fully. */ +/* */ +/***************************************************************************/ + + +#include +#include FT_INTERNAL_DEBUG_H +#include FT_WINFONTS_H +#include FT_INTERNAL_OBJECTS_H +#include FT_SERVICE_WINFNT_H + + + /* documentation is in ftwinfnt.h */ + + FT_EXPORT_DEF( FT_Error ) + FT_Get_WinFNT_Header( FT_Face face, + FT_WinFNT_HeaderRec *header ) + { + FT_Service_WinFnt service; + FT_Error error; + + + if ( !face ) + return FT_THROW( Invalid_Face_Handle ); + + if ( !header ) + return FT_THROW( Invalid_Argument ); + + FT_FACE_LOOKUP_SERVICE( face, service, WINFNT ); + + if ( service ) + error = service->get_header( face, header ); + else + error = FT_THROW( Invalid_Argument ); + + return error; + } + + +/* END */ diff --git a/pool/shard002/C/0062059_CWE415_Double_Free__malloc_free_int64_t_45.c b/pool/shard002/C/0062059_CWE415_Double_Free__malloc_free_int64_t_45.c new file mode 100644 index 0000000000000000000000000000000000000000..471ae84108844a9798c96ec9521565e23ccc0c19 --- /dev/null +++ b/pool/shard002/C/0062059_CWE415_Double_Free__malloc_free_int64_t_45.c @@ -0,0 +1,125 @@ +/* TEMPLATE GENERATED TESTCASE FILE +Filename: CWE415_Double_Free__malloc_free_int64_t_45.c +Label Definition File: CWE415_Double_Free__malloc_free.label.xml +Template File: sources-sinks-45.tmpl.c +*/ +/* + * @description + * CWE: 415 Double Free + * BadSource: Allocate data using malloc() and Deallocate data using free() + * GoodSource: Allocate data using malloc() + * Sinks: + * GoodSink: do nothing + * BadSink : Deallocate data using free() + * Flow Variant: 45 Data flow: data passed as a static global variable from one function to another in the same source file + * + * */ + +#include "std_testcase.h" + +#include + +static int64_t * CWE415_Double_Free__malloc_free_int64_t_45_badData; +static int64_t * CWE415_Double_Free__malloc_free_int64_t_45_goodG2BData; +static int64_t * CWE415_Double_Free__malloc_free_int64_t_45_goodB2GData; + +#ifndef OMITBAD + +static void badSink() +{ + int64_t * data = CWE415_Double_Free__malloc_free_int64_t_45_badData; + /* POTENTIAL FLAW: Possibly freeing memory twice */ + free(data); +} + +void CWE415_Double_Free__malloc_free_int64_t_45_bad() +{ + int64_t * data; + /* Initialize data */ + data = NULL; + data = (int64_t *)malloc(100*sizeof(int64_t)); + if (data == NULL) {exit(-1);} + /* POTENTIAL FLAW: Free data in the source - the bad sink frees data as well */ + free(data); + CWE415_Double_Free__malloc_free_int64_t_45_badData = data; + badSink(); +} + +#endif /* OMITBAD */ + +#ifndef OMITGOOD + +/* goodG2B() uses the GoodSource with the BadSink */ +static void goodG2BSink() +{ + int64_t * data = CWE415_Double_Free__malloc_free_int64_t_45_goodG2BData; + /* POTENTIAL FLAW: Possibly freeing memory twice */ + free(data); +} + +static void goodG2B() +{ + int64_t * data; + /* Initialize data */ + data = NULL; + data = (int64_t *)malloc(100*sizeof(int64_t)); + if (data == NULL) {exit(-1);} + /* FIX: Do NOT free data in the source - the bad sink frees data */ + CWE415_Double_Free__malloc_free_int64_t_45_goodG2BData = data; + goodG2BSink(); +} + +/* goodB2G() uses the BadSource with the GoodSink */ +static void goodB2GSink() +{ + int64_t * data = CWE415_Double_Free__malloc_free_int64_t_45_goodB2GData; + /* do nothing */ + /* FIX: Don't attempt to free the memory */ + ; /* empty statement needed for some flow variants */ +} + +static void goodB2G() +{ + int64_t * data; + /* Initialize data */ + data = NULL; + data = (int64_t *)malloc(100*sizeof(int64_t)); + if (data == NULL) {exit(-1);} + /* POTENTIAL FLAW: Free data in the source - the bad sink frees data as well */ + free(data); + CWE415_Double_Free__malloc_free_int64_t_45_goodB2GData = data; + goodB2GSink(); +} + +void CWE415_Double_Free__malloc_free_int64_t_45_good() +{ + goodG2B(); + goodB2G(); +} + +#endif /* OMITGOOD */ + +/* Below is the main(). It is only used when building this testcase on + its own for testing or for building a binary to use in testing binary + analysis tools. It is not used when compiling all the testcases as one + application, which is how source code analysis tools are tested. */ +#ifdef INCLUDEMAIN + +int main(int argc, char * argv[]) +{ + /* seed randomness */ + srand( (unsigned)time(NULL) ); +#ifndef OMITGOOD + printLine("Calling good()..."); + CWE415_Double_Free__malloc_free_int64_t_45_good(); + printLine("Finished good()"); +#endif /* OMITGOOD */ +#ifndef OMITBAD + printLine("Calling bad()..."); + CWE415_Double_Free__malloc_free_int64_t_45_bad(); + printLine("Finished bad()"); +#endif /* OMITBAD */ + return 0; +} + +#endif diff --git a/pool/shard002/C/0062061_vacuum.c b/pool/shard002/C/0062061_vacuum.c new file mode 100644 index 0000000000000000000000000000000000000000..e34a4e9737dfad57041b336c49767e3ce4b9f6f3 --- /dev/null +++ b/pool/shard002/C/0062061_vacuum.c @@ -0,0 +1,262 @@ +/* +** 2003 April 6 +** +** The author disclaims copyright to this source code. In place of +** a legal notice, here is a blessing: +** +** May you do good and not evil. +** May you find forgiveness for yourself and forgive others. +** May you share freely, never taking more than you give. +** +************************************************************************* +** This file contains code used to implement the VACUUM command. +** +** Most of the code in this file may be omitted by defining the +** SQLITE_OMIT_VACUUM macro. +** +** $Id: vacuum.c,v 1.69 2007/03/27 16:19:52 danielk1977 Exp $ +*/ +#include "sqliteInt.h" +#include "vdbeInt.h" +#include "os.h" + +#if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH) +/* +** Execute zSql on database db. Return an error code. +*/ +static int execSql(sqlite3 *db, const char *zSql){ + sqlite3_stmt *pStmt; + if( SQLITE_OK!=sqlite3_prepare(db, zSql, -1, &pStmt, 0) ){ + return sqlite3_errcode(db); + } + while( SQLITE_ROW==sqlite3_step(pStmt) ){} + return sqlite3_finalize(pStmt); +} + +/* +** Execute zSql on database db. The statement returns exactly +** one column. Execute this as SQL on the same database. +*/ +static int execExecSql(sqlite3 *db, const char *zSql){ + sqlite3_stmt *pStmt; + int rc; + + rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0); + if( rc!=SQLITE_OK ) return rc; + + while( SQLITE_ROW==sqlite3_step(pStmt) ){ + rc = execSql(db, (char*)sqlite3_column_text(pStmt, 0)); + if( rc!=SQLITE_OK ){ + sqlite3_finalize(pStmt); + return rc; + } + } + + return sqlite3_finalize(pStmt); +} + +/* +** The non-standard VACUUM command is used to clean up the database, +** collapse free space, etc. It is modelled after the VACUUM command +** in PostgreSQL. +** +** In version 1.0.x of SQLite, the VACUUM command would call +** gdbm_reorganize() on all the database tables. But beginning +** with 2.0.0, SQLite no longer uses GDBM so this command has +** become a no-op. +*/ +void sqlite3Vacuum(Parse *pParse){ + Vdbe *v = sqlite3GetVdbe(pParse); + if( v ){ + sqlite3VdbeAddOp(v, OP_Vacuum, 0, 0); + } + return; +} + +/* +** This routine implements the OP_Vacuum opcode of the VDBE. +*/ +int sqlite3RunVacuum(char **pzErrMsg, sqlite3 *db){ + int rc = SQLITE_OK; /* Return code from service routines */ + Btree *pMain; /* The database being vacuumed */ + Btree *pTemp; /* The temporary database we vacuum into */ + char *zSql = 0; /* SQL statements */ + int saved_flags; /* Saved value of the db->flags */ + Db *pDb = 0; /* Database to detach at end of vacuum */ + + /* Save the current value of the write-schema flag before setting it. */ + saved_flags = db->flags; + db->flags |= SQLITE_WriteSchema | SQLITE_IgnoreChecks; + + if( !db->autoCommit ){ + sqlite3SetString(pzErrMsg, "cannot VACUUM from within a transaction", + (char*)0); + rc = SQLITE_ERROR; + goto end_of_vacuum; + } + pMain = db->aDb[0].pBt; + + /* Attach the temporary database as 'vacuum_db'. The synchronous pragma + ** can be set to 'off' for this file, as it is not recovered if a crash + ** occurs anyway. The integrity of the database is maintained by a + ** (possibly synchronous) transaction opened on the main database before + ** sqlite3BtreeCopyFile() is called. + ** + ** An optimisation would be to use a non-journaled pager. + */ + zSql = "ATTACH '' AS vacuum_db;"; + rc = execSql(db, zSql); + if( rc!=SQLITE_OK ) goto end_of_vacuum; + pDb = &db->aDb[db->nDb-1]; + assert( strcmp(db->aDb[db->nDb-1].zName,"vacuum_db")==0 ); + pTemp = db->aDb[db->nDb-1].pBt; + sqlite3BtreeSetPageSize(pTemp, sqlite3BtreeGetPageSize(pMain), + sqlite3BtreeGetReserve(pMain)); + if( sqlite3MallocFailed() ){ + rc = SQLITE_NOMEM; + goto end_of_vacuum; + } + assert( sqlite3BtreeGetPageSize(pTemp)==sqlite3BtreeGetPageSize(pMain) ); + rc = execSql(db, "PRAGMA vacuum_db.synchronous=OFF"); + if( rc!=SQLITE_OK ){ + goto end_of_vacuum; + } + +#ifndef SQLITE_OMIT_AUTOVACUUM + sqlite3BtreeSetAutoVacuum(pTemp, sqlite3BtreeGetAutoVacuum(pMain)); +#endif + + /* Begin a transaction */ + rc = execSql(db, "BEGIN EXCLUSIVE;"); + if( rc!=SQLITE_OK ) goto end_of_vacuum; + + /* Query the schema of the main database. Create a mirror schema + ** in the temporary database. + */ + rc = execExecSql(db, + "SELECT 'CREATE TABLE vacuum_db.' || substr(sql,14,100000000) " + " FROM sqlite_master WHERE type='table' AND name!='sqlite_sequence'" + " AND rootpage>0" + ); + if( rc!=SQLITE_OK ) goto end_of_vacuum; + rc = execExecSql(db, + "SELECT 'CREATE INDEX vacuum_db.' || substr(sql,14,100000000)" + " FROM sqlite_master WHERE sql LIKE 'CREATE INDEX %' "); + if( rc!=SQLITE_OK ) goto end_of_vacuum; + rc = execExecSql(db, + "SELECT 'CREATE UNIQUE INDEX vacuum_db.' || substr(sql,21,100000000) " + " FROM sqlite_master WHERE sql LIKE 'CREATE UNIQUE INDEX %'"); + if( rc!=SQLITE_OK ) goto end_of_vacuum; + + /* Loop through the tables in the main database. For each, do + ** an "INSERT INTO vacuum_db.xxx SELECT * FROM xxx;" to copy + ** the contents to the temporary database. + */ + rc = execExecSql(db, + "SELECT 'INSERT INTO vacuum_db.' || quote(name) " + "|| ' SELECT * FROM ' || quote(name) || ';'" + "FROM sqlite_master " + "WHERE type = 'table' AND name!='sqlite_sequence' " + " AND rootpage>0" + + ); + if( rc!=SQLITE_OK ) goto end_of_vacuum; + + /* Copy over the sequence table + */ + rc = execExecSql(db, + "SELECT 'DELETE FROM vacuum_db.' || quote(name) || ';' " + "FROM vacuum_db.sqlite_master WHERE name='sqlite_sequence' " + ); + if( rc!=SQLITE_OK ) goto end_of_vacuum; + rc = execExecSql(db, + "SELECT 'INSERT INTO vacuum_db.' || quote(name) " + "|| ' SELECT * FROM ' || quote(name) || ';' " + "FROM vacuum_db.sqlite_master WHERE name=='sqlite_sequence';" + ); + if( rc!=SQLITE_OK ) goto end_of_vacuum; + + + /* Copy the triggers, views, and virtual tables from the main database + ** over to the temporary database. None of these objects has any + ** associated storage, so all we have to do is copy their entries + ** from the SQLITE_MASTER table. + */ + rc = execSql(db, + "INSERT INTO vacuum_db.sqlite_master " + " SELECT type, name, tbl_name, rootpage, sql" + " FROM sqlite_master" + " WHERE type='view' OR type='trigger'" + " OR (type='table' AND rootpage=0)" + ); + if( rc ) goto end_of_vacuum; + + /* At this point, unless the main db was completely empty, there is now a + ** transaction open on the vacuum database, but not on the main database. + ** Open a btree level transaction on the main database. This allows a + ** call to sqlite3BtreeCopyFile(). The main database btree level + ** transaction is then committed, so the SQL level never knows it was + ** opened for writing. This way, the SQL transaction used to create the + ** temporary database never needs to be committed. + */ + if( rc==SQLITE_OK ){ + u32 meta; + int i; + + /* This array determines which meta meta values are preserved in the + ** vacuum. Even entries are the meta value number and odd entries + ** are an increment to apply to the meta value after the vacuum. + ** The increment is used to increase the schema cookie so that other + ** connections to the same database will know to reread the schema. + */ + static const unsigned char aCopy[] = { + 1, 1, /* Add one to the old schema cookie */ + 3, 0, /* Preserve the default page cache size */ + 5, 0, /* Preserve the default text encoding */ + 6, 0, /* Preserve the user version */ + }; + + assert( 1==sqlite3BtreeIsInTrans(pTemp) ); + assert( 1==sqlite3BtreeIsInTrans(pMain) ); + + /* Copy Btree meta values */ + for(i=0; iflags */ + db->flags = saved_flags; + + /* Currently there is an SQL level transaction open on the vacuum + ** database. No locks are held on any other files (since the main file + ** was committed at the btree level). So it safe to end the transaction + ** by manually setting the autoCommit flag to true and detaching the + ** vacuum database. The vacuum_db journal file is deleted when the pager + ** is closed by the DETACH. + */ + db->autoCommit = 1; + + if( pDb ){ + sqlite3MallocDisallow(); + sqlite3BtreeClose(pDb->pBt); + sqlite3MallocAllow(); + pDb->pBt = 0; + pDb->pSchema = 0; + } + + sqlite3ResetInternalSchema(db, 0); + + return rc; +} +#endif /* SQLITE_OMIT_VACUUM && SQLITE_OMIT_ATTACH */ diff --git a/pool/shard002/C/0062066_tcp_iw_kern.c b/pool/shard002/C/0062066_tcp_iw_kern.c new file mode 100644 index 0000000000000000000000000000000000000000..d1444557358e70ca088b6c2a46d4e2269abf01a4 --- /dev/null +++ b/pool/shard002/C/0062066_tcp_iw_kern.c @@ -0,0 +1,83 @@ +/* Copyright (c) 2017 Facebook + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of version 2 of the GNU General Public + * License as published by the Free Software Foundation. + * + * BPF program to set initial congestion window and initial receive + * window to 40 packets and send and receive buffers to 1.5MB. This + * would usually be done after doing appropriate checks that indicate + * the hosts are far enough away (i.e. large RTT). + * + * Use "bpftool cgroup attach $cg sock_ops $prog" to load this BPF program. + */ + +#include +#include +#include +#include +#include +#include +#include + +#define DEBUG 1 + +SEC("sockops") +int bpf_iw(struct bpf_sock_ops *skops) +{ + int bufsize = 1500000; + int rwnd_init = 40; + int iw = 40; + int rv = 0; + int op; + + /* For testing purposes, only execute rest of BPF program + * if neither port numberis 55601 + */ + if (bpf_ntohl(skops->remote_port) != 55601 && + skops->local_port != 55601) { + skops->reply = -1; + return 1; + } + + op = (int) skops->op; + +#ifdef DEBUG + bpf_printk("BPF command: %d\n", op); +#endif + + /* Usually there would be a check to insure the hosts are far + * from each other so it makes sense to increase buffer sizes + */ + switch (op) { + case BPF_SOCK_OPS_RWND_INIT: + rv = rwnd_init; + break; + case BPF_SOCK_OPS_TCP_CONNECT_CB: + /* Set sndbuf and rcvbuf of active connections */ + rv = bpf_setsockopt(skops, SOL_SOCKET, SO_SNDBUF, &bufsize, + sizeof(bufsize)); + rv += bpf_setsockopt(skops, SOL_SOCKET, SO_RCVBUF, + &bufsize, sizeof(bufsize)); + break; + case BPF_SOCK_OPS_ACTIVE_ESTABLISHED_CB: + rv = bpf_setsockopt(skops, SOL_TCP, TCP_BPF_IW, &iw, + sizeof(iw)); + break; + case BPF_SOCK_OPS_PASSIVE_ESTABLISHED_CB: + /* Set sndbuf and rcvbuf of passive connections */ + rv = bpf_setsockopt(skops, SOL_SOCKET, SO_SNDBUF, &bufsize, + sizeof(bufsize)); + rv += bpf_setsockopt(skops, SOL_SOCKET, SO_RCVBUF, + &bufsize, sizeof(bufsize)); + break; + default: + rv = -1; + } +#ifdef DEBUG + bpf_printk("Returning %d\n", rv); +#endif + skops->reply = rv; + return 1; +} +char _license[] SEC("license") = "GPL"; diff --git a/pool/shard002/C/0062068_composite-test.c b/pool/shard002/C/0062068_composite-test.c new file mode 100644 index 0000000000000000000000000000000000000000..5401abfdf6151f093d7c0278dc154913b0414715 --- /dev/null +++ b/pool/shard002/C/0062068_composite-test.c @@ -0,0 +1,192 @@ +#include +#include +#include +#include "pixman.h" +#include "gtk-utils.h" + +#define WIDTH 60 +#define HEIGHT 60 + +typedef struct { + const char *name; + pixman_op_t op; +} operator_t; + +static const operator_t operators[] = { + { "CLEAR", PIXMAN_OP_CLEAR }, + { "SRC", PIXMAN_OP_SRC }, + { "DST", PIXMAN_OP_DST }, + { "OVER", PIXMAN_OP_OVER }, + { "OVER_REVERSE", PIXMAN_OP_OVER_REVERSE }, + { "IN", PIXMAN_OP_IN }, + { "IN_REVERSE", PIXMAN_OP_IN_REVERSE }, + { "OUT", PIXMAN_OP_OUT }, + { "OUT_REVERSE", PIXMAN_OP_OUT_REVERSE }, + { "ATOP", PIXMAN_OP_ATOP }, + { "ATOP_REVERSE", PIXMAN_OP_ATOP_REVERSE }, + { "XOR", PIXMAN_OP_XOR }, + { "ADD", PIXMAN_OP_ADD }, + { "SATURATE", PIXMAN_OP_SATURATE }, + + { "MULTIPLY", PIXMAN_OP_MULTIPLY }, + { "SCREEN", PIXMAN_OP_SCREEN }, + { "OVERLAY", PIXMAN_OP_OVERLAY }, + { "DARKEN", PIXMAN_OP_DARKEN }, + { "LIGHTEN", PIXMAN_OP_LIGHTEN }, + { "COLOR_DODGE", PIXMAN_OP_COLOR_DODGE }, + { "COLOR_BURN", PIXMAN_OP_COLOR_BURN }, + { "HARD_LIGHT", PIXMAN_OP_HARD_LIGHT }, + { "SOFT_LIGHT", PIXMAN_OP_SOFT_LIGHT }, + { "DIFFERENCE", PIXMAN_OP_DIFFERENCE }, + { "EXCLUSION", PIXMAN_OP_EXCLUSION }, + { "HSL_HUE", PIXMAN_OP_HSL_HUE }, + { "HSL_SATURATION", PIXMAN_OP_HSL_SATURATION }, + { "HSL_COLOR", PIXMAN_OP_HSL_COLOR }, + { "HSL_LUMINOSITY", PIXMAN_OP_HSL_LUMINOSITY }, +}; + +static uint32_t +reader (const void *src, int size) +{ + switch (size) + { + case 1: + return *(uint8_t *)src; + case 2: + return *(uint16_t *)src; + case 4: + return *(uint32_t *)src; + default: + g_assert_not_reached(); + } +} + +static void +writer (void *src, uint32_t value, int size) +{ + switch (size) + { + case 1: + *(uint8_t *)src = value; + break; + + case 2: + *(uint16_t *)src = value; + break; + + case 4: + *(uint32_t *)src = value; + break; + + default: + break; + } +} + +int +main (int argc, char **argv) +{ +#define d2f pixman_double_to_fixed + + GtkWidget *window, *swindow; + GtkWidget *table; + uint32_t *dest = malloc (WIDTH * HEIGHT * 4); + uint32_t *src = malloc (WIDTH * HEIGHT * 4); + pixman_image_t *src_img; + pixman_image_t *dest_img; + pixman_point_fixed_t p1 = { -10 << 0, 0 }; + pixman_point_fixed_t p2 = { WIDTH << 16, (HEIGHT - 10) << 16 }; + uint16_t full = 0xcfff; + uint16_t low = 0x5000; + uint16_t alpha = 0xffff; + pixman_gradient_stop_t stops[6] = + { + { d2f (0.0), { full, low, low, alpha } }, + { d2f (0.25), { full, full, low, alpha } }, + { d2f (0.4), { low, full, low, alpha } }, + { d2f (0.5), { low, full, full, alpha } }, + { d2f (0.8), { low, low, full, alpha } }, + { d2f (1.0), { full, low, full, alpha } }, + }; + + + int i; + + gtk_init (&argc, &argv); + + window = gtk_window_new (GTK_WINDOW_TOPLEVEL); + + gtk_window_set_default_size (GTK_WINDOW (window), 800, 600); + + g_signal_connect (window, "delete-event", + G_CALLBACK (gtk_main_quit), + NULL); + table = gtk_table_new (G_N_ELEMENTS (operators) / 6, 6, TRUE); + + src_img = pixman_image_create_linear_gradient (&p1, &p2, stops, + sizeof (stops) / sizeof (stops[0])); + + pixman_image_set_repeat (src_img, PIXMAN_REPEAT_PAD); + + dest_img = pixman_image_create_bits (PIXMAN_a8r8g8b8, + WIDTH, HEIGHT, + dest, + WIDTH * 4); + pixman_image_set_accessors (dest_img, reader, writer); + + for (i = 0; i < G_N_ELEMENTS (operators); ++i) + { + GtkWidget *image; + GdkPixbuf *pixbuf; + GtkWidget *vbox; + GtkWidget *label; + int j, k; + + vbox = gtk_vbox_new (FALSE, 0); + + label = gtk_label_new (operators[i].name); + gtk_box_pack_start (GTK_BOX (vbox), label, FALSE, FALSE, 6); + gtk_widget_show (label); + + for (j = 0; j < HEIGHT; ++j) + { + for (k = 0; k < WIDTH; ++k) + dest[j * WIDTH + k] = 0x7f6f6f00; + } + pixman_image_composite (operators[i].op, src_img, NULL, dest_img, + 0, 0, 0, 0, 0, 0, WIDTH, HEIGHT); + pixbuf = pixbuf_from_argb32 (pixman_image_get_data (dest_img), TRUE, + WIDTH, HEIGHT, WIDTH * 4); + image = gtk_image_new_from_pixbuf (pixbuf); + gtk_box_pack_start (GTK_BOX (vbox), image, FALSE, FALSE, 0); + gtk_widget_show (image); + + gtk_table_attach_defaults (GTK_TABLE (table), vbox, + i % 6, (i % 6) + 1, i / 6, (i / 6) + 1); + gtk_widget_show (vbox); + + g_object_unref (pixbuf); + } + + pixman_image_unref (src_img); + free (src); + pixman_image_unref (dest_img); + free (dest); + + swindow = gtk_scrolled_window_new (NULL, NULL); + gtk_scrolled_window_set_policy (GTK_SCROLLED_WINDOW (swindow), + GTK_POLICY_AUTOMATIC, + GTK_POLICY_AUTOMATIC); + + gtk_scrolled_window_add_with_viewport (GTK_SCROLLED_WINDOW (swindow), table); + gtk_widget_show (table); + + gtk_container_add (GTK_CONTAINER (window), swindow); + gtk_widget_show (swindow); + + gtk_widget_show (window); + + gtk_main (); + + return 0; +} diff --git a/pool/shard002/C/0062069_exnames.c b/pool/shard002/C/0062069_exnames.c new file mode 100644 index 0000000000000000000000000000000000000000..639f0bd3f6d86dd25c77c9df9b626be8edbef058 --- /dev/null +++ b/pool/shard002/C/0062069_exnames.c @@ -0,0 +1,447 @@ + +/****************************************************************************** + * + * Module Name: exnames - interpreter/scanner name load/execute + * + *****************************************************************************/ + +/* + * Copyright (C) 2000 - 2005, 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 +#include + +#define _COMPONENT ACPI_EXECUTER + ACPI_MODULE_NAME ("exnames") + +/* Local prototypes */ + +static char * +acpi_ex_allocate_name_string ( + u32 prefix_count, + u32 num_name_segs); + +static acpi_status +acpi_ex_name_segment ( + u8 **in_aml_address, + char *name_string); + + +/******************************************************************************* + * + * FUNCTION: acpi_ex_allocate_name_string + * + * PARAMETERS: prefix_count - Count of parent levels. Special cases: + * (-1)==root, 0==none + * num_name_segs - count of 4-character name segments + * + * RETURN: A pointer to the allocated string segment. This segment must + * be deleted by the caller. + * + * DESCRIPTION: Allocate a buffer for a name string. Ensure allocated name + * string is long enough, and set up prefix if any. + * + ******************************************************************************/ + +static char * +acpi_ex_allocate_name_string ( + u32 prefix_count, + u32 num_name_segs) +{ + char *temp_ptr; + char *name_string; + u32 size_needed; + + ACPI_FUNCTION_TRACE ("ex_allocate_name_string"); + + + /* + * Allow room for all \ and ^ prefixes, all segments and a multi_name_prefix. + * Also, one byte for the null terminator. + * This may actually be somewhat longer than needed. + */ + if (prefix_count == ACPI_UINT32_MAX) { + /* Special case for root */ + + size_needed = 1 + (ACPI_NAME_SIZE * num_name_segs) + 2 + 1; + } + else { + size_needed = prefix_count + (ACPI_NAME_SIZE * num_name_segs) + 2 + 1; + } + + /* + * Allocate a buffer for the name. + * This buffer must be deleted by the caller! + */ + name_string = ACPI_MEM_ALLOCATE (size_needed); + if (!name_string) { + ACPI_REPORT_ERROR (( + "ex_allocate_name_string: Could not allocate size %d\n", size_needed)); + return_PTR (NULL); + } + + temp_ptr = name_string; + + /* Set up Root or Parent prefixes if needed */ + + if (prefix_count == ACPI_UINT32_MAX) { + *temp_ptr++ = AML_ROOT_PREFIX; + } + else { + while (prefix_count--) { + *temp_ptr++ = AML_PARENT_PREFIX; + } + } + + + /* Set up Dual or Multi prefixes if needed */ + + if (num_name_segs > 2) { + /* Set up multi prefixes */ + + *temp_ptr++ = AML_MULTI_NAME_PREFIX_OP; + *temp_ptr++ = (char) num_name_segs; + } + else if (2 == num_name_segs) { + /* Set up dual prefixes */ + + *temp_ptr++ = AML_DUAL_NAME_PREFIX; + } + + /* + * Terminate string following prefixes. acpi_ex_name_segment() will + * append the segment(s) + */ + *temp_ptr = 0; + + return_PTR (name_string); +} + +/******************************************************************************* + * + * FUNCTION: acpi_ex_name_segment + * + * PARAMETERS: in_aml_address - Pointer to the name in the AML code + * name_string - Where to return the name. The name is appended + * to any existing string to form a namepath + * + * RETURN: Status + * + * DESCRIPTION: Extract an ACPI name (4 bytes) from the AML byte stream + * + ******************************************************************************/ + +static acpi_status +acpi_ex_name_segment ( + u8 **in_aml_address, + char *name_string) +{ + char *aml_address = (void *) *in_aml_address; + acpi_status status = AE_OK; + u32 index; + char char_buf[5]; + + + ACPI_FUNCTION_TRACE ("ex_name_segment"); + + + /* + * If first character is a digit, then we know that we aren't looking at a + * valid name segment + */ + char_buf[0] = *aml_address; + + if ('0' <= char_buf[0] && char_buf[0] <= '9') { + ACPI_DEBUG_PRINT ((ACPI_DB_ERROR, "leading digit: %c\n", char_buf[0])); + return_ACPI_STATUS (AE_CTRL_PENDING); + } + + ACPI_DEBUG_PRINT ((ACPI_DB_LOAD, "Bytes from stream:\n")); + + for (index = 0; + (index < ACPI_NAME_SIZE) && (acpi_ut_valid_acpi_character (*aml_address)); + index++) { + char_buf[index] = *aml_address++; + ACPI_DEBUG_PRINT ((ACPI_DB_LOAD, "%c\n", char_buf[index])); + } + + + /* Valid name segment */ + + if (index == 4) { + /* Found 4 valid characters */ + + char_buf[4] = '\0'; + + if (name_string) { + ACPI_STRCAT (name_string, char_buf); + ACPI_DEBUG_PRINT ((ACPI_DB_NAMES, + "Appended to - %s \n", name_string)); + } + else { + ACPI_DEBUG_PRINT ((ACPI_DB_NAMES, + "No Name string - %s \n", char_buf)); + } + } + else if (index == 0) { + /* + * First character was not a valid name character, + * so we are looking at something other than a name. + */ + ACPI_DEBUG_PRINT ((ACPI_DB_INFO, + "Leading character is not alpha: %02Xh (not a name)\n", + char_buf[0])); + status = AE_CTRL_PENDING; + } + else { + /* + * Segment started with one or more valid characters, but fewer than + * the required 4 + */ + status = AE_AML_BAD_NAME; + ACPI_DEBUG_PRINT ((ACPI_DB_ERROR, + "Bad character %02x in name, at %p\n", + *aml_address, aml_address)); + } + + *in_aml_address = (u8 *) aml_address; + return_ACPI_STATUS (status); +} + + +/******************************************************************************* + * + * FUNCTION: acpi_ex_get_name_string + * + * PARAMETERS: data_type - Object type to be associated with this + * name + * in_aml_address - Pointer to the namestring in the AML code + * out_name_string - Where the namestring is returned + * out_name_length - Length of the returned string + * + * RETURN: Status, namestring and length + * + * DESCRIPTION: Extract a full namepath from the AML byte stream, + * including any prefixes. + * + ******************************************************************************/ + +acpi_status +acpi_ex_get_name_string ( + acpi_object_type data_type, + u8 *in_aml_address, + char **out_name_string, + u32 *out_name_length) +{ + acpi_status status = AE_OK; + u8 *aml_address = in_aml_address; + char *name_string = NULL; + u32 num_segments; + u32 prefix_count = 0; + u8 has_prefix = FALSE; + + + ACPI_FUNCTION_TRACE_PTR ("ex_get_name_string", aml_address); + + + if (ACPI_TYPE_LOCAL_REGION_FIELD == data_type || + ACPI_TYPE_LOCAL_BANK_FIELD == data_type || + ACPI_TYPE_LOCAL_INDEX_FIELD == data_type) { + /* Disallow prefixes for types associated with field_unit names */ + + name_string = acpi_ex_allocate_name_string (0, 1); + if (!name_string) { + status = AE_NO_MEMORY; + } + else { + status = acpi_ex_name_segment (&aml_address, name_string); + } + } + else { + /* + * data_type is not a field name. + * Examine first character of name for root or parent prefix operators + */ + switch (*aml_address) { + case AML_ROOT_PREFIX: + + ACPI_DEBUG_PRINT ((ACPI_DB_LOAD, "root_prefix(\\) at %p\n", + aml_address)); + + /* + * Remember that we have a root_prefix -- + * see comment in acpi_ex_allocate_name_string() + */ + aml_address++; + prefix_count = ACPI_UINT32_MAX; + has_prefix = TRUE; + break; + + + case AML_PARENT_PREFIX: + + /* Increment past possibly multiple parent prefixes */ + + do { + ACPI_DEBUG_PRINT ((ACPI_DB_LOAD, "parent_prefix (^) at %p\n", + aml_address)); + + aml_address++; + prefix_count++; + + } while (*aml_address == AML_PARENT_PREFIX); + + has_prefix = TRUE; + break; + + + default: + + /* Not a prefix character */ + + break; + } + + /* Examine first character of name for name segment prefix operator */ + + switch (*aml_address) { + case AML_DUAL_NAME_PREFIX: + + ACPI_DEBUG_PRINT ((ACPI_DB_LOAD, "dual_name_prefix at %p\n", + aml_address)); + + aml_address++; + name_string = acpi_ex_allocate_name_string (prefix_count, 2); + if (!name_string) { + status = AE_NO_MEMORY; + break; + } + + /* Indicate that we processed a prefix */ + + has_prefix = TRUE; + + status = acpi_ex_name_segment (&aml_address, name_string); + if (ACPI_SUCCESS (status)) { + status = acpi_ex_name_segment (&aml_address, name_string); + } + break; + + + case AML_MULTI_NAME_PREFIX_OP: + + ACPI_DEBUG_PRINT ((ACPI_DB_LOAD, "multi_name_prefix at %p\n", + aml_address)); + + /* Fetch count of segments remaining in name path */ + + aml_address++; + num_segments = *aml_address; + + name_string = acpi_ex_allocate_name_string (prefix_count, num_segments); + if (!name_string) { + status = AE_NO_MEMORY; + break; + } + + /* Indicate that we processed a prefix */ + + aml_address++; + has_prefix = TRUE; + + while (num_segments && + (status = acpi_ex_name_segment (&aml_address, name_string)) == + AE_OK) { + num_segments--; + } + + break; + + + case 0: + + /* null_name valid as of 8-12-98 ASL/AML Grammar Update */ + + if (prefix_count == ACPI_UINT32_MAX) { + ACPI_DEBUG_PRINT ((ACPI_DB_EXEC, + "name_seg is \"\\\" followed by NULL\n")); + } + + /* Consume the NULL byte */ + + aml_address++; + name_string = acpi_ex_allocate_name_string (prefix_count, 0); + if (!name_string) { + status = AE_NO_MEMORY; + break; + } + + break; + + + default: + + /* Name segment string */ + + name_string = acpi_ex_allocate_name_string (prefix_count, 1); + if (!name_string) { + status = AE_NO_MEMORY; + break; + } + + status = acpi_ex_name_segment (&aml_address, name_string); + break; + } + } + + if (AE_CTRL_PENDING == status && has_prefix) { + /* Ran out of segments after processing a prefix */ + + ACPI_REPORT_ERROR ( + ("ex_do_name: Malformed Name at %p\n", name_string)); + status = AE_AML_BAD_NAME; + } + + *out_name_string = name_string; + *out_name_length = (u32) (aml_address - in_aml_address); + + return_ACPI_STATUS (status); +} + + diff --git a/pool/shard002/C/0062087_sl_utils_print.c b/pool/shard002/C/0062087_sl_utils_print.c new file mode 100644 index 0000000000000000000000000000000000000000..386b8469b478195f881909f21ff75da4cf22ca95 --- /dev/null +++ b/pool/shard002/C/0062087_sl_utils_print.c @@ -0,0 +1,298 @@ +/* + * This file is part of the Sofia-SIP package + * + * Copyright (C) 2005 Nokia Corporation. + * + * Contact: Pekka Pessi + * + * 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 + * + */ + +/**@ingroup sl_utils + * + * @CFILE sl_utils_print.c + * @brief Implementation of SIP library utility print functions. + * + * @author Pekka Pessi + * + * @date Created: Thu Oct 5 15:38:39 2000 ppessi + */ + +#include "config.h" + +#include +#include +#include +#include + +#include +#include "sofia-sip/sl_utils.h" + +/**Print a SIP message. + * + * The function sl_message_log() prints shorthand information identifying + * the SIP message to the given output @a stream. The shorthand information + * include the method and URL by default. If @a details is nonzero, topmost + * @Via, @CSeq, @To and @From is included, too. + * + * @param stream output stream (if @c NULL, @c stdout is used). + * @param prefix string printed before the first line. + * @param sip message to be logged. + * @param details flag specifying if detailed output is desired. + */ +void sl_message_log(FILE *stream, + char const *prefix, sip_t const *sip, int details) +{ + sip_cseq_t const *cs = sip->sip_cseq; + + if (stream == NULL) + stream = stdout; + + assert(cs); + + if (sip->sip_request) { + fprintf(stream, + "%s%s "URL_FORMAT_STRING" (CSeq %d %s)\n", + prefix, + sip->sip_request->rq_method_name, + URL_PRINT_ARGS(sip->sip_request->rq_url), + cs->cs_seq, + cs->cs_method_name); + + if (!details) + return; + + if (sip->sip_via) { + fputs(prefix, stream); + sl_via_print(stream, "Via: %s\n", sip->sip_via); + } + } + else { + fprintf(stream, + "%s%03u %s (CSeq %d %s)\n", + prefix, + sip->sip_status->st_status, + sip->sip_status->st_phrase, + cs->cs_seq, + cs->cs_method_name); + if (!details) + return; + } + + if (sip->sip_from) + sl_from_print(stream, "\tFrom: %s\n", sip->sip_from); + + if (sip->sip_to) + sl_to_print(stream, "\tTo: %s\n", sip->sip_to); +} + +/** Print @From header. + * + * The function sl_from_print() prints the contents of @a from header to + * the output @a stream. The @a fmt specifies the output format, where %s + * is replaced with header contents. If @a fmt is @c NULL, only the header + * contents are printed. + * + * @param stream output stream + * @param fmt output format + * @param from header object + * + * @return + * The function sl_from_print() returns number of bytes printed, + * or -1 upon an error. + */ +issize_t sl_from_print(FILE *stream, char const *fmt, sip_from_t const *from) +{ + sip_addr_t a[1]; + + if (from == NULL) + return -1; + + memcpy(a, from, sizeof a); + a->a_params = NULL; + if (!a->a_display) a->a_display = ""; + + return sl_header_print(stream, fmt, (sip_header_t *)a); +} + +/** Print @To header. + * + * The function sl_to_print() prints the contents of @a to header to + * the output @a stream. The @a fmt specifies the output format, where %s + * is replaced with header contents. If @a fmt is @c NULL, only the header + * contents are printed. + * + * @param stream output stream + * @param fmt output format + * @param to header object + * + * @return + * The function sl_to_print() returns number of bytes printed, + * or -1 upon an error. + */ +issize_t sl_to_print(FILE *stream, char const *fmt, sip_to_t const *to) +{ + return sl_from_print(stream, fmt, (sip_from_t const *)to); +} + +/** Print @Contact header. + * + * The function sl_contact_print() prints the contents of @a contact + * header to the output @a stream. The @a fmt specifies the output format, + * where %s is replaced with header contents. If @a fmt is @c NULL, only the + * header contents are printed. + * + * @param stream output stream + * @param fmt output format + * @param contact header object + * + * @return + * The function sl_contact_print() returns number of bytes printed, + * or -1 upon an error. +*/ +issize_t sl_contact_print(FILE *stream, char const *fmt, + sip_contact_t const *m) +{ + return sl_from_print(stream, fmt, (sip_from_t const *)m); +} + +/** Print @Allow header(s). + * + * The function sl_allow_print() prints the contents of @a allow header to + * the output @a stream. The @a fmt specifies the output format, where %s + * is replaced with header contents. If @a fmt is @c NULL, only the header + * contents are printed. + * + * @param stream output stream + * @param fmt output format + * @param allow header object + * + * @return + * The function sl_allow_print() returns number of bytes printed, + * or -1 upon an error. +*/ +issize_t sl_allow_print(FILE *stream, + char const *fmt, + sip_allow_t const *allow) +{ + return sl_header_print(stream, fmt, (sip_header_t *)allow); +} + + +/** Print message payload. + * + * The function sl_payload_print() prints the contents of @a payload + * object to the output @a stream. The @a fmt specifies the output format, + * where %s is replaced with header contents. If @a fmt is @c NULL, only the + * header contents are printed. + * + * @param stream output stream + * @param prefix prefix appended to each payload line + * @param pl payload object + * + * @return + * The function sl_payload_print() returns number of bytes printed, + * or -1 upon an error. +*/ +issize_t sl_payload_print(FILE *stream, char const *prefix, sip_payload_t const *pl) +{ + char *s = pl->pl_data, *end = pl->pl_data + pl->pl_len; + size_t n, total = 0, crlf = 1; + + while (s < end && *s != '\0') { + n = su_strncspn(s, end - s, "\r\n"); + crlf = su_strnspn(s + n, end - s - n, "\r\n"); + if (prefix) + fputs(prefix, stream), total += strlen(prefix); + if (fwrite(s, 1, n + crlf, stream) < n + crlf) + return (issize_t)-1; + s += n + crlf; + total += n + crlf; + } + if (crlf == 0) + fputs("\n", stream), total++; + + return (issize_t)total; +} + +/** Print @Via header. + * + * The function sl_via_print() prints the contents of @a via header to + * the output @a stream. The @a fmt specifies the output format, where %s + * is replaced with header contents. If @a fmt is @c NULL, only the header + * contents are printed. + * + * @param stream output stream + * @param fmt output format + * @param v header object + * + * @return + * The function sl_via_print() returns number of bytes printed, + * or -1 upon an error. + */ +issize_t sl_via_print(FILE *stream, char const *fmt, sip_via_t const *v) +{ + char s[1024]; + + sip_header_field_e(s, sizeof(s), (sip_header_t const *)v, 0); + s[sizeof(s) - 1] = '\0'; + + if (fmt && strcmp(fmt, "%s")) + return fprintf(stream, fmt, s); + if (fputs(s, stream) >= 0) + return (issize_t)strlen(s); + return -1; +} + +/** Print a header. + * + * Prints the contents of an header to the output @a stream. The @a fmt + * specifies the output format, where %s is replaced with header contents. + * If @a fmt is @c NULL, only the header contents are printed. + * + * @param stream output stream + * @param fmt output format + * @param v header object + * + * @return + * Number of bytes logged, or -1 upon an error. + */ +issize_t sl_header_print(FILE *stream, char const *fmt, sip_header_t const *h) +{ + char *s, b[1024]; + issize_t len; + + len = sip_header_field_e(s = b, sizeof b, h, 0); + if (len == -1) + return len; + + if ((size_t)len >= sizeof b) { + s = malloc(len + 1); if (!s) return -1; + sip_header_field_e(s, len + 1, h, 0); + } + s[len] = '\0'; + + if (fmt != NULL && strcmp(fmt, "%s") != 0) + len = fprintf(stream, fmt, s); + else if (fputs(s, stream) < 0) + len = -1; + + if (s != b) + free(s); + + return len; +} diff --git a/pool/shard002/C/0062097_cgc32-am33lin.c b/pool/shard002/C/0062097_cgc32-am33lin.c new file mode 100644 index 0000000000000000000000000000000000000000..16048958d3c01589622900be76487093e4195546 --- /dev/null +++ b/pool/shard002/C/0062097_cgc32-am33lin.c @@ -0,0 +1,106 @@ +/* Matsushita AM33/2.0 support for 32-bit GNU/Linux CGC + Copyright 2003, 2005, 2007 + Free Software Foundation, Inc. + + This file is part of BFD, the Binary File Descriptor library. + + 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., 51 Franklin Street - Fifth Floor, Boston, + MA 02110-1301, USA. */ + +#include "sysdep.h" +#include "bfd.h" +#include "cgc-bfd.h" +#include "cgc/mn10300.h" + +#define cgc_symbol_leading_char 0 + +#define TARGET_LITTLE_SYM bfd_cgc32_am33lin_vec +#define TARGET_LITTLE_NAME "cgc32-am33lin" +#define CGC_ARCH bfd_arch_mn10300 +#define CGC_MACHINE_CODE EM_MN10300 +#define CGC_MACHINE_ALT1 EM_CYGNUS_MN10300 +#define CGC_MAXPAGESIZE 0x1000 + +/* Rename global functions. */ +#define _bfd_mn10300_cgc_merge_private_bfd_data _bfd_am33_cgc_merge_private_bfd_data +#define _bfd_mn10300_cgc_object_p _bfd_am33_cgc_object_p +#define _bfd_mn10300_cgc_final_write_processing _bfd_am33_cgc_final_write_processing + +/* Support for core dump NOTE sections. */ +static bfd_boolean +cgc32_am33lin_grok_prstatus (bfd *abfd, Cgc_Internal_Note *note) +{ + int offset; + unsigned int size; + + switch (note->descsz) + { + default: + return FALSE; + + case 184: + case 188: /* Linux/am33 */ + /* pr_cursig */ + cgc_tdata (abfd)->core->signal = bfd_get_16 (abfd, note->descdata + 12); + + /* pr_pid */ + cgc_tdata (abfd)->core->lwpid = bfd_get_32 (abfd, note->descdata + 24); + + /* pr_reg */ + offset = 72; + size = 112; + + break; + } + + /* Make a ".reg/999" section. */ + return _bfd_cgccore_make_pseudosection (abfd, ".reg", size, + note->descpos + offset); +} + +static bfd_boolean +cgc32_am33lin_grok_psinfo (bfd *abfd, Cgc_Internal_Note *note) +{ + switch (note->descsz) + { + default: + return FALSE; + + case 124: /* Linux/am33 cgc_prpsinfo */ + cgc_tdata (abfd)->core->program + = _bfd_cgccore_strndup (abfd, note->descdata + 28, 16); + cgc_tdata (abfd)->core->command + = _bfd_cgccore_strndup (abfd, note->descdata + 44, 80); + } + + /* Note that for some reason, a spurious space is tacked + onto the end of the args in some (at least one anyway) + implementations, so strip it off if it exists. */ + + { + char *command = cgc_tdata (abfd)->core->command; + int n = strlen (command); + + if (0 < n && command[n - 1] == ' ') + command[n - 1] = '\0'; + } + + return TRUE; +} + +#define cgc_backend_grok_prstatus cgc32_am33lin_grok_prstatus +#define cgc_backend_grok_psinfo cgc32_am33lin_grok_psinfo + +#include "cgc-m10300.c" diff --git a/pool/shard002/C/0062113_button.c b/pool/shard002/C/0062113_button.c new file mode 100644 index 0000000000000000000000000000000000000000..827590f498281919ed4565120591f5b529ba8384 --- /dev/null +++ b/pool/shard002/C/0062113_button.c @@ -0,0 +1,243 @@ +/* + * File : button.c + * This file is part of RT-Thread RTOS + * COPYRIGHT (C) 2006 - 2009, RT-Thread Development 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 + * 2009-10-16 Bernard first version + */ +#include +#include +#include + +static void _rtgui_button_constructor(rtgui_button_t *button) +{ + /* init widget and set event handler */ + RTGUI_WIDGET(button)->flag |= RTGUI_WIDGET_FLAG_FOCUSABLE; + rtgui_widget_set_event_handler(RTGUI_WIDGET(button), rtgui_button_event_handler); + + /* un-press button */ + button->flag = 0; + + /* set flag and on_button event handler */ + button->pressed_image = RT_NULL; + button->unpressed_image = RT_NULL; + button->on_button = RT_NULL; + + /* set gc */ + RTGUI_WIDGET_FOREGROUND(RTGUI_WIDGET(button)) = default_foreground; + RTGUI_WIDGET_BACKGROUND(RTGUI_WIDGET(button)) = RTGUI_RGB(212, 208, 200); + RTGUI_WIDGET_TEXTALIGN(RTGUI_WIDGET(button)) = RTGUI_ALIGN_CENTER_HORIZONTAL | RTGUI_ALIGN_CENTER_VERTICAL; +} + +static void _rtgui_button_destructor(rtgui_button_t *button) +{ + if (button->pressed_image != RT_NULL) + { + rtgui_image_destroy(button->pressed_image); + button->pressed_image = RT_NULL; + } + + if (button->unpressed_image != RT_NULL) + { + rtgui_image_destroy(button->unpressed_image); + button->unpressed_image = RT_NULL; + } +} + +DEFINE_CLASS_TYPE(button, "button", + RTGUI_LABEL_TYPE, + _rtgui_button_constructor, + _rtgui_button_destructor, + sizeof(struct rtgui_button)); + +rt_bool_t rtgui_button_event_handler(struct rtgui_widget* widget, struct rtgui_event* event) +{ + struct rtgui_button* btn; + + RT_ASSERT(widget != RT_NULL); + + btn = (struct rtgui_button*) widget; + switch (event->type) + { + case RTGUI_EVENT_PAINT: +#ifndef RTGUI_USING_SMALL_SIZE + if (widget->on_draw != RT_NULL ) widget->on_draw(widget, event); + else +#endif + rtgui_theme_draw_button(btn); + break; + + case RTGUI_EVENT_KBD: + { + struct rtgui_event_kbd* ekbd = (struct rtgui_event_kbd*) event; + + if (RTGUI_WIDGET_IS_HIDE(widget)) return RT_FALSE; + if ((ekbd->key == RTGUIK_RETURN) || (ekbd->key == RTGUIK_SPACE)) + { + if (RTGUI_KBD_IS_DOWN(ekbd)) + { + btn->flag |= RTGUI_BUTTON_FLAG_PRESS; + } + else + { + btn->flag &= ~RTGUI_BUTTON_FLAG_PRESS; + } + + /* draw button */ + rtgui_theme_draw_button(btn); + + if ((btn->flag & RTGUI_BUTTON_FLAG_PRESS) && (btn->on_button != RT_NULL)) + { + /* call on button handler */ + btn->on_button(widget, event); + } + } + } + break; + + case RTGUI_EVENT_MOUSE_BUTTON: + if (RTGUI_WIDGET_IS_HIDE(widget)) return RT_FALSE; + { + struct rtgui_event_mouse* emouse = (struct rtgui_event_mouse*)event; + + if (btn->flag & RTGUI_BUTTON_TYPE_PUSH) + { + /* it's a push button */ + if (emouse->button & RTGUI_MOUSE_BUTTON_UP) + { + if (btn->flag & RTGUI_BUTTON_FLAG_PRESS) + { + btn->flag &= ~RTGUI_BUTTON_FLAG_PRESS; + } + else + { + btn->flag |= RTGUI_BUTTON_FLAG_PRESS; + } + + /* draw button */ +#ifndef RTGUI_USING_SMALL_SIZE + if (widget->on_draw != RT_NULL ) widget->on_draw(widget, event); + else +#endif + rtgui_theme_draw_button(btn); + + if (btn->on_button != RT_NULL) + { + /* call on button handler */ + btn->on_button(widget, event); + } + +#ifndef RTGUI_USING_SMALL_SIZE + /* invokes call back */ + if (widget->on_mouseclick != RT_NULL && + emouse->button & RTGUI_MOUSE_BUTTON_UP) + return widget->on_mouseclick(widget, event); +#endif + } + } + else + { + if (emouse->button & RTGUI_MOUSE_BUTTON_LEFT) + { + /* it's a normal button */ + if (emouse->button & RTGUI_MOUSE_BUTTON_DOWN) + { + btn->flag |= RTGUI_BUTTON_FLAG_PRESS; + } + else + { + btn->flag &= ~RTGUI_BUTTON_FLAG_PRESS; + } + + /* draw button */ +#ifndef RTGUI_USING_SMALL_SIZE + if (widget->on_draw != RT_NULL ) widget->on_draw(widget, event); + else +#endif + rtgui_theme_draw_button(btn); + +#ifndef RTGUI_USING_SMALL_SIZE + /* invokes call back */ + if (widget->on_mouseclick != RT_NULL && + emouse->button & RTGUI_MOUSE_BUTTON_UP) + return widget->on_mouseclick(widget, event); +#endif + + if (!(btn->flag & RTGUI_BUTTON_FLAG_PRESS) && (btn->on_button != RT_NULL)) + { + /* call on button handler */ + btn->on_button(widget, event); + } + } + + } + + return RT_TRUE; + } + } + + return RT_FALSE; +} + +rtgui_button_t* rtgui_button_create(const char* text) +{ + struct rtgui_button* btn; + + btn = (struct rtgui_button*) rtgui_widget_create (RTGUI_BUTTON_TYPE); + if (btn != RT_NULL) + { + rtgui_rect_t rect; + + /* set default rect */ + rtgui_font_get_metrics(rtgui_font_default(), text, &rect); + rect.x2 += (RTGUI_BORDER_DEFAULT_WIDTH << 1); + rect.y2 += (RTGUI_BORDER_DEFAULT_WIDTH << 1); + rtgui_widget_set_rect(RTGUI_WIDGET(btn), &rect); + rtgui_label_set_text(RTGUI_LABEL(btn), text); + } + + return btn; +} + +rtgui_button_t* rtgui_pushbutton_create(const char* text) +{ + rtgui_button_t* btn; + + btn = rtgui_button_create(text); + if (btn != RT_NULL) btn->flag |= RTGUI_BUTTON_TYPE_PUSH; + + return btn; +} + +void rtgui_button_destroy(rtgui_button_t* btn) +{ + rtgui_widget_destroy(RTGUI_WIDGET(btn)); +} + +void rtgui_button_set_pressed_image(rtgui_button_t* btn, rtgui_image_t* image) +{ + RT_ASSERT(btn != RT_NULL); + + btn->pressed_image = image; +} + +void rtgui_button_set_unpressed_image(rtgui_button_t* btn, rtgui_image_t* image) +{ + RT_ASSERT(btn != RT_NULL); + + btn->unpressed_image = image; +} + +void rtgui_button_set_onbutton(rtgui_button_t* btn, rtgui_onbutton_func_t func) +{ + RT_ASSERT(btn != RT_NULL); + + btn->on_button = func; +} + diff --git a/pool/shard002/C/0062114_urlhist.c b/pool/shard002/C/0062114_urlhist.c new file mode 100644 index 0000000000000000000000000000000000000000..e15e312111d535d6492a17df3f0ebb1aba4a6b8f --- /dev/null +++ b/pool/shard002/C/0062114_urlhist.c @@ -0,0 +1,129 @@ +/* + * Copyright 2006 Jacek Caban for CodeWeavers + * + * 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 "ieframe.h" + +#include + +static HRESULT WINAPI UrlHistoryStg_QueryInterface(IUrlHistoryStg2 *iface, REFIID riid, void **ppv) +{ + *ppv = NULL; + + if(IsEqualGUID(&IID_IUnknown, riid)) { + TRACE("(IID_IUnknown %p)\n", ppv); + *ppv = iface; + }else if(IsEqualGUID(&IID_IUrlHistoryStg, riid)) { + TRACE("(IID_IUrlHistoryStg %p)\n", ppv); + *ppv = iface; + }else if(IsEqualGUID(&IID_IUrlHistoryStg2, riid)) { + TRACE("(IID_IUrlHistoryStg2 %p)\n", ppv); + *ppv = iface; + } + + if(*ppv) { + IUnknown_AddRef((IUnknown*)*ppv); + return S_OK; + } + + WARN("(%s %p)\n", debugstr_guid(riid), ppv); + return E_NOINTERFACE; +} + +static ULONG WINAPI UrlHistoryStg_AddRef(IUrlHistoryStg2 *iface) +{ + lock_module(); + return 2; +} + +static ULONG WINAPI UrlHistoryStg_Release(IUrlHistoryStg2 *iface) +{ + unlock_module(); + return 1; +} + +static HRESULT WINAPI UrlHistoryStg_AddUrl(IUrlHistoryStg2 *iface, LPCOLESTR lpcsUrl, + LPCOLESTR pocsTitle, DWORD dwFlags) +{ + FIXME("(%s %s %08x)\n", debugstr_w(lpcsUrl), debugstr_w(pocsTitle), dwFlags); + return E_NOTIMPL; +} + +static HRESULT WINAPI UrlHistoryStg_DeleteUrl(IUrlHistoryStg2 *iface, LPCOLESTR lpcsUrl, + DWORD dwFlags) +{ + FIXME("(%s %08x)\n", debugstr_w(lpcsUrl), dwFlags); + return E_NOTIMPL; +} + +static HRESULT WINAPI UrlHistoryStg_QueryUrl(IUrlHistoryStg2 *iface, LPCOLESTR lpcsUrl, + DWORD dwFlags, LPSTATURL lpSTATURL) +{ + FIXME("(%s %08x %p)\n", debugstr_w(lpcsUrl), dwFlags, lpSTATURL); + return E_NOTIMPL; +} + +static HRESULT WINAPI UrlHistoryStg_BindToObject(IUrlHistoryStg2 *iface, LPCOLESTR lpcsUrl, + REFIID riid, void **ppv) +{ + FIXME("(%s %s %p)\n", debugstr_w(lpcsUrl), debugstr_guid(riid), ppv); + return E_NOTIMPL; +} + +static HRESULT WINAPI UrlHistoryStg_EnumUrls(IUrlHistoryStg2 *iface, IEnumSTATURL **ppEnum) +{ + FIXME("(%p)\n", ppEnum); + return E_NOTIMPL; +} + +static HRESULT WINAPI UrlHistoryStg_AddUrlAndNotify(IUrlHistoryStg2 *iface, LPCOLESTR pocsUrl, + LPCOLESTR pocsTitle, DWORD dwFlags, BOOL fWriteHistory, IOleCommandTarget *poctNotify, + IUnknown *punkISFolder) +{ + FIXME("(%s %s %08x %x %p %p)\n", debugstr_w(pocsUrl), debugstr_w(pocsTitle), + dwFlags, fWriteHistory, poctNotify, punkISFolder); + return E_NOTIMPL; +} + +static HRESULT WINAPI UrlHistoryStg_ClearHistory(IUrlHistoryStg2 *iface) +{ + FIXME("()\n"); + return E_NOTIMPL; +} + +static const IUrlHistoryStg2Vtbl UrlHistoryStg2Vtbl = { + UrlHistoryStg_QueryInterface, + UrlHistoryStg_AddRef, + UrlHistoryStg_Release, + UrlHistoryStg_AddUrl, + UrlHistoryStg_DeleteUrl, + UrlHistoryStg_QueryUrl, + UrlHistoryStg_BindToObject, + UrlHistoryStg_EnumUrls, + UrlHistoryStg_AddUrlAndNotify, + UrlHistoryStg_ClearHistory +}; + +static IUrlHistoryStg2 UrlHistoryStg2 = { &UrlHistoryStg2Vtbl }; + +HRESULT WINAPI CUrlHistory_Create(IClassFactory *iface, IUnknown *pOuter, REFIID riid, void **ppv) +{ + if(pOuter) + return CLASS_E_NOAGGREGATION; + + return IUrlHistoryStg2_QueryInterface(&UrlHistoryStg2, riid, ppv); +} diff --git a/pool/shard002/C/0062115_sched_affinity.c b/pool/shard002/C/0062115_sched_affinity.c new file mode 100644 index 0000000000000000000000000000000000000000..9f51048c1b16079ab18ea9a6d8a2ac89c95cc924 --- /dev/null +++ b/pool/shard002/C/0062115_sched_affinity.c @@ -0,0 +1,69 @@ +/*!The Treasure Box Library + * + * 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) 2009-2020, TBOOX Open Source Group. + * + * @author ruki + * @file sched_affinity.c + * @ingroup platform + * + */ + +/* ////////////////////////////////////////////////////////////////////////////////////// + * includes + */ +#include "../sched.h" +#include +#include + +/* ////////////////////////////////////////////////////////////////////////////////////// + * implementation + */ +tb_bool_t tb_sched_setaffinity(tb_size_t pid, tb_cpuset_ref_t cpuset) +{ + // check + tb_assert_and_check_return_val(cpuset, tb_false); + + // set cpu affinity + tb_int_t i; + cpu_set_t cpu_set; + CPU_ZERO(&cpu_set); + for (i = 0; i < TB_CPUSET_SIZE; i++) + { + if (TB_CPUSET_ISSET(i, cpuset) && i < CPU_SETSIZE) + CPU_SET(i, &cpu_set); + } + return sched_setaffinity((pid_t)pid, sizeof(cpu_set_t), &cpu_set) == 0; +} +tb_bool_t tb_sched_getaffinity(tb_size_t pid, tb_cpuset_ref_t cpuset) +{ + // check + tb_assert_and_check_return_val(cpuset, tb_false); + + // get cpu affinity + cpu_set_t cpu_set; + CPU_ZERO(&cpu_set); + if (sched_getaffinity((pid_t)pid, sizeof(cpu_set_t), &cpu_set) != 0) + return tb_false; + + // save cpuset + tb_int_t i; + TB_CPUSET_ZERO(cpuset); + for (i = 0; i < CPU_SETSIZE; i++) + { + if (CPU_ISSET(i, &cpu_set) && i < TB_CPUSET_SIZE) + TB_CPUSET_SET(i, cpuset); + } + return tb_true; +} diff --git a/pool/shard002/C/0062118_mpc83xx_gpio.c b/pool/shard002/C/0062118_mpc83xx_gpio.c new file mode 100644 index 0000000000000000000000000000000000000000..92b6e0cb76da3942199ff2a15a58068c4dba7f10 --- /dev/null +++ b/pool/shard002/C/0062118_mpc83xx_gpio.c @@ -0,0 +1,183 @@ +/* + * Freescale MPC83xx GPIO handling. + * + * SPDX-License-Identifier: GPL-2.0+ + */ + +#include +#include +#include +#include + +#ifndef CONFIG_MPC83XX_GPIO_0_INIT_DIRECTION +#define CONFIG_MPC83XX_GPIO_0_INIT_DIRECTION 0 +#endif +#ifndef CONFIG_MPC83XX_GPIO_1_INIT_DIRECTION +#define CONFIG_MPC83XX_GPIO_1_INIT_DIRECTION 0 +#endif +#ifndef CONFIG_MPC83XX_GPIO_0_INIT_OPEN_DRAIN +#define CONFIG_MPC83XX_GPIO_0_INIT_OPEN_DRAIN 0 +#endif +#ifndef CONFIG_MPC83XX_GPIO_1_INIT_OPEN_DRAIN +#define CONFIG_MPC83XX_GPIO_1_INIT_OPEN_DRAIN 0 +#endif +#ifndef CONFIG_MPC83XX_GPIO_0_INIT_VALUE +#define CONFIG_MPC83XX_GPIO_0_INIT_VALUE 0 +#endif +#ifndef CONFIG_MPC83XX_GPIO_1_INIT_VALUE +#define CONFIG_MPC83XX_GPIO_1_INIT_VALUE 0 +#endif + +static unsigned int gpio_output_value[MPC83XX_GPIO_CTRLRS]; + +/* + * Generic_GPIO primitives. + */ + +int gpio_request(unsigned gpio, const char *label) +{ + if (gpio >= MAX_NUM_GPIOS) + return -1; + + return 0; +} + +int gpio_free(unsigned gpio) +{ + /* Do not set to input */ + return 0; +} + +/* set GPIO pin 'gpio' as an input */ +int gpio_direction_input(unsigned gpio) +{ + immap_t *im = (immap_t *)CONFIG_SYS_IMMR; + unsigned int ctrlr; + unsigned int line; + unsigned int line_mask; + + /* 32-bits per controller */ + ctrlr = gpio >> 5; + line = gpio & (0x1F); + + /* Big endian */ + line_mask = 1 << (31 - line); + + clrbits_be32(&im->gpio[ctrlr].dir, line_mask); + + return 0; +} + +/* set GPIO pin 'gpio' as an output, with polarity 'value' */ +int gpio_direction_output(unsigned gpio, int value) +{ + immap_t *im = (immap_t *)CONFIG_SYS_IMMR; + unsigned int ctrlr; + unsigned int line; + unsigned int line_mask; + + if (value != 0 && value != 1) { + printf("Error: Value parameter must be 0 or 1.\n"); + return -1; + } + + gpio_set_value(gpio, value); + + /* 32-bits per controller */ + ctrlr = gpio >> 5; + line = gpio & (0x1F); + + /* Big endian */ + line_mask = 1 << (31 - line); + + /* Make the line output */ + setbits_be32(&im->gpio[ctrlr].dir, line_mask); + + return 0; +} + +/* read GPIO IN value of pin 'gpio' */ +int gpio_get_value(unsigned gpio) +{ + immap_t *im = (immap_t *)CONFIG_SYS_IMMR; + unsigned int ctrlr; + unsigned int line; + unsigned int line_mask; + + /* 32-bits per controller */ + ctrlr = gpio >> 5; + line = gpio & (0x1F); + + /* Big endian */ + line_mask = 1 << (31 - line); + + /* Read the value and mask off the bit */ + return (in_be32(&im->gpio[ctrlr].dat) & line_mask) != 0; +} + +/* write GPIO OUT value to pin 'gpio' */ +int gpio_set_value(unsigned gpio, int value) +{ + immap_t *im = (immap_t *)CONFIG_SYS_IMMR; + unsigned int ctrlr; + unsigned int line; + unsigned int line_mask; + + if (value != 0 && value != 1) { + printf("Error: Value parameter must be 0 or 1.\n"); + return -1; + } + + /* 32-bits per controller */ + ctrlr = gpio >> 5; + line = gpio & (0x1F); + + /* Big endian */ + line_mask = 1 << (31 - line); + + /* Update the local output buffer soft copy */ + gpio_output_value[ctrlr] = + (gpio_output_value[ctrlr] & ~line_mask) | \ + (value ? line_mask : 0); + + /* Write the output */ + out_be32(&im->gpio[ctrlr].dat, gpio_output_value[ctrlr]); + + return 0; +} + +/* Configure GPIO registers early */ +void mpc83xx_gpio_init_f(void) +{ + immap_t *im = (immap_t *)CONFIG_SYS_IMMR; + +#if MPC83XX_GPIO_CTRLRS >= 1 + out_be32(&im->gpio[0].dir, CONFIG_MPC83XX_GPIO_0_INIT_DIRECTION); + out_be32(&im->gpio[0].odr, CONFIG_MPC83XX_GPIO_0_INIT_OPEN_DRAIN); + out_be32(&im->gpio[0].dat, CONFIG_MPC83XX_GPIO_0_INIT_VALUE); + out_be32(&im->gpio[0].ier, 0xFFFFFFFF); /* Clear all events */ + out_be32(&im->gpio[0].imr, 0); + out_be32(&im->gpio[0].icr, 0); +#endif + +#if MPC83XX_GPIO_CTRLRS >= 2 + out_be32(&im->gpio[1].dir, CONFIG_MPC83XX_GPIO_1_INIT_DIRECTION); + out_be32(&im->gpio[1].odr, CONFIG_MPC83XX_GPIO_1_INIT_OPEN_DRAIN); + out_be32(&im->gpio[1].dat, CONFIG_MPC83XX_GPIO_1_INIT_VALUE); + out_be32(&im->gpio[1].ier, 0xFFFFFFFF); /* Clear all events */ + out_be32(&im->gpio[1].imr, 0); + out_be32(&im->gpio[1].icr, 0); +#endif +} + +/* Initialize GPIO soft-copies */ +void mpc83xx_gpio_init_r(void) +{ +#if MPC83XX_GPIO_CTRLRS >= 1 + gpio_output_value[0] = CONFIG_MPC83XX_GPIO_0_INIT_VALUE; +#endif + +#if MPC83XX_GPIO_CTRLRS >= 2 + gpio_output_value[1] = CONFIG_MPC83XX_GPIO_1_INIT_VALUE; +#endif +} diff --git a/pool/shard002/C/0062123_thread_reaper.c b/pool/shard002/C/0062123_thread_reaper.c new file mode 100644 index 0000000000000000000000000000000000000000..ae81912cb11cf75298c064a025e61efb25dadbf3 --- /dev/null +++ b/pool/shard002/C/0062123_thread_reaper.c @@ -0,0 +1,103 @@ +/* + * This file is part of BitFiend. + * Copyright (C) 2017 Eduard Permyakov + * + * BitFiend 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. + * + * BitFiend 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 "thread_reaper.h" +#include "log.h" +#include "torrent.h" +#include "peer_connection.h" + +#include +#include + +static void reap_periodic_cleanup(void *arg) +{ + free(arg); +} + +static void *reap_periodic(void *arg) +{ + reaper_arg_t *rarg = (reaper_arg_t*)arg; + pthread_cleanup_push(reap_periodic_cleanup, arg);{ + + while(true) { + + pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL); + sleep(rarg->reap_interval); + pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, NULL); + + /* Reap unassociated peers */ + pthread_mutex_lock(rarg->unassoc_peer_lock); + + const list_iter_t *iter = list_iter_first(rarg->unassoc_peers); + while(iter) { + pthread_t thread = *(pthread_t*)list_iter_get_value(iter); + iter = list_iter_next(iter); + + void *ret; + if(pthread_tryjoin_np(thread, &ret) == 0){ + + list_remove(rarg->unassoc_peers, (unsigned char*)&thread); + log_printf(LOG_LEVEL_INFO, "Reaped exited unassociated peer thread\n"); + } + } + pthread_mutex_unlock(rarg->unassoc_peer_lock); + + /* Reap associateed peers */ + pthread_mutex_lock(rarg->torrents_lock); + const unsigned char *entry; + FOREACH_ENTRY(entry, rarg->torrents){ + torrent_t *torrent = *(torrent_t**)entry; + + pthread_mutex_lock(&torrent->sh_lock); + + const list_iter_t *iter = list_iter_first(torrent->sh.peer_connections); + while(iter){ + peer_conn_t *conn = *(peer_conn_t**)list_iter_get_value(iter); + iter = list_iter_next(iter); + + void *ret; + if(pthread_tryjoin_np(conn->thread, &ret) == 0) { + + list_remove(torrent->sh.peer_connections, (unsigned char*)&conn); + log_printf(LOG_LEVEL_INFO, "Reaped exited peer thread\n"); + } + } + pthread_mutex_unlock(&torrent->sh_lock); + + } + pthread_mutex_unlock(rarg->torrents_lock); + } + + }pthread_cleanup_pop(0); + +} + +int thread_reaper_create(pthread_t *thread, reaper_arg_t *arg) +{ + if(pthread_create(thread, NULL, reap_periodic, arg)) + goto fail_create_thread; + + return 0; + +fail_create_thread: + log_printf(LOG_LEVEL_ERROR, "Failed to create reaper thread\n"); + return -1; + +} + diff --git a/pool/shard002/C/0062126_writev.c b/pool/shard002/C/0062126_writev.c new file mode 100644 index 0000000000000000000000000000000000000000..a1e572248a85596f035f32d9e4b76f71e694ce39 --- /dev/null +++ b/pool/shard002/C/0062126_writev.c @@ -0,0 +1,50 @@ +/* + * JFFS2 -- Journalling Flash File System, Version 2. + * + * Copyright (C) 2001, 2002 Red Hat, Inc. + * + * Created by David Woodhouse + * + * For licensing information, see the file 'LICENCE' in this directory. + * + * $Id: writev.c,v 1.5 2004/07/13 08:58:25 dwmw2 Exp $ + * + */ + +#include +#include +#include "nodelist.h" + +/* This ought to be in core MTD code. All registered MTD devices + without writev should have this put in place. Bug the MTD + maintainer */ +static inline int mtd_fake_writev(struct mtd_info *mtd, const struct kvec *vecs, + unsigned long count, loff_t to, size_t *retlen) +{ + unsigned long i; + size_t totlen = 0, thislen; + int ret = 0; + + for (i=0; iwrite(mtd, to, vecs[i].iov_len, &thislen, vecs[i].iov_base); + totlen += thislen; + if (ret || thislen != vecs[i].iov_len) + break; + to += vecs[i].iov_len; + } + if (retlen) + *retlen = totlen; + return ret; +} + +int jffs2_flash_direct_writev(struct jffs2_sb_info *c, const struct kvec *vecs, + unsigned long count, loff_t to, size_t *retlen) +{ + if (c->mtd->writev) + return c->mtd->writev(c->mtd, vecs, count, to, retlen); + else + return mtd_fake_writev(c->mtd, vecs, count, to, retlen); +} + diff --git a/pool/shard002/C/0062127_osc_object.c b/pool/shard002/C/0062127_osc_object.c new file mode 100644 index 0000000000000000000000000000000000000000..9d474fcdd9a74b965f7a7bdd511e0596276ee981 --- /dev/null +++ b/pool/shard002/C/0062127_osc_object.c @@ -0,0 +1,269 @@ +/* + * GPL HEADER START + * + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License version 2 only, + * 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 version 2 for more details (a copy is included + * in the LICENSE file that accompanied this code). + * + * You should have received a copy of the GNU General Public License + * version 2 along with this program; If not, see + * http://www.sun.com/software/products/lustre/docs/GPLv2.pdf + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + * + * GPL HEADER END + */ +/* + * Copyright (c) 2008, 2010, Oracle and/or its affiliates. All rights reserved. + * Use is subject to license terms. + * + * Copyright (c) 2011, 2015, Intel Corporation. + */ +/* + * This file is part of Lustre, http://www.lustre.org/ + * Lustre is a trademark of Sun Microsystems, Inc. + * + * Implementation of cl_object for OSC layer. + * + * Author: Nikita Danilov + */ + +#define DEBUG_SUBSYSTEM S_OSC + +#include "osc_cl_internal.h" + +/** \addtogroup osc + * @{ + */ + +/***************************************************************************** + * + * Type conversions. + * + */ + +static struct lu_object *osc2lu(struct osc_object *osc) +{ + return &osc->oo_cl.co_lu; +} + +static struct osc_object *lu2osc(const struct lu_object *obj) +{ + LINVRNT(osc_is_object(obj)); + return container_of0(obj, struct osc_object, oo_cl.co_lu); +} + +/***************************************************************************** + * + * Object operations. + * + */ + +static int osc_object_init(const struct lu_env *env, struct lu_object *obj, + const struct lu_object_conf *conf) +{ + struct osc_object *osc = lu2osc(obj); + const struct cl_object_conf *cconf = lu2cl_conf(conf); + int i; + + osc->oo_oinfo = cconf->u.coc_oinfo; + spin_lock_init(&osc->oo_seatbelt); + for (i = 0; i < CRT_NR; ++i) + INIT_LIST_HEAD(&osc->oo_inflight[i]); + + INIT_LIST_HEAD(&osc->oo_ready_item); + INIT_LIST_HEAD(&osc->oo_hp_ready_item); + INIT_LIST_HEAD(&osc->oo_write_item); + INIT_LIST_HEAD(&osc->oo_read_item); + + osc->oo_root.rb_node = NULL; + INIT_LIST_HEAD(&osc->oo_hp_exts); + INIT_LIST_HEAD(&osc->oo_urgent_exts); + INIT_LIST_HEAD(&osc->oo_rpc_exts); + INIT_LIST_HEAD(&osc->oo_reading_exts); + atomic_set(&osc->oo_nr_reads, 0); + atomic_set(&osc->oo_nr_writes, 0); + spin_lock_init(&osc->oo_lock); + + cl_object_page_init(lu2cl(obj), sizeof(struct osc_page)); + + return 0; +} + +static void osc_object_free(const struct lu_env *env, struct lu_object *obj) +{ + struct osc_object *osc = lu2osc(obj); + int i; + + for (i = 0; i < CRT_NR; ++i) + LASSERT(list_empty(&osc->oo_inflight[i])); + + LASSERT(list_empty(&osc->oo_ready_item)); + LASSERT(list_empty(&osc->oo_hp_ready_item)); + LASSERT(list_empty(&osc->oo_write_item)); + LASSERT(list_empty(&osc->oo_read_item)); + + LASSERT(!osc->oo_root.rb_node); + LASSERT(list_empty(&osc->oo_hp_exts)); + LASSERT(list_empty(&osc->oo_urgent_exts)); + LASSERT(list_empty(&osc->oo_rpc_exts)); + LASSERT(list_empty(&osc->oo_reading_exts)); + LASSERT(atomic_read(&osc->oo_nr_reads) == 0); + LASSERT(atomic_read(&osc->oo_nr_writes) == 0); + + lu_object_fini(obj); + kmem_cache_free(osc_object_kmem, osc); +} + +int osc_lvb_print(const struct lu_env *env, void *cookie, + lu_printer_t p, const struct ost_lvb *lvb) +{ + return (*p)(env, cookie, "size: %llu mtime: %llu atime: %llu ctime: %llu blocks: %llu", + lvb->lvb_size, lvb->lvb_mtime, lvb->lvb_atime, + lvb->lvb_ctime, lvb->lvb_blocks); +} + +static int osc_object_print(const struct lu_env *env, void *cookie, + lu_printer_t p, const struct lu_object *obj) +{ + struct osc_object *osc = lu2osc(obj); + struct lov_oinfo *oinfo = osc->oo_oinfo; + struct osc_async_rc *ar = &oinfo->loi_ar; + + (*p)(env, cookie, "id: " DOSTID " idx: %d gen: %d kms_valid: %u kms %llu rc: %d force_sync: %d min_xid: %llu ", + POSTID(&oinfo->loi_oi), oinfo->loi_ost_idx, + oinfo->loi_ost_gen, oinfo->loi_kms_valid, oinfo->loi_kms, + ar->ar_rc, ar->ar_force_sync, ar->ar_min_xid); + osc_lvb_print(env, cookie, p, &oinfo->loi_lvb); + return 0; +} + +static int osc_attr_get(const struct lu_env *env, struct cl_object *obj, + struct cl_attr *attr) +{ + struct lov_oinfo *oinfo = cl2osc(obj)->oo_oinfo; + + cl_lvb2attr(attr, &oinfo->loi_lvb); + attr->cat_kms = oinfo->loi_kms_valid ? oinfo->loi_kms : 0; + return 0; +} + +static int osc_attr_set(const struct lu_env *env, struct cl_object *obj, + const struct cl_attr *attr, unsigned valid) +{ + struct lov_oinfo *oinfo = cl2osc(obj)->oo_oinfo; + struct ost_lvb *lvb = &oinfo->loi_lvb; + + if (valid & CAT_SIZE) + lvb->lvb_size = attr->cat_size; + if (valid & CAT_MTIME) + lvb->lvb_mtime = attr->cat_mtime; + if (valid & CAT_ATIME) + lvb->lvb_atime = attr->cat_atime; + if (valid & CAT_CTIME) + lvb->lvb_ctime = attr->cat_ctime; + if (valid & CAT_BLOCKS) + lvb->lvb_blocks = attr->cat_blocks; + if (valid & CAT_KMS) { + CDEBUG(D_CACHE, "set kms from %llu to %llu\n", + oinfo->loi_kms, (__u64)attr->cat_kms); + loi_kms_set(oinfo, attr->cat_kms); + } + return 0; +} + +static int osc_object_glimpse(const struct lu_env *env, + const struct cl_object *obj, struct ost_lvb *lvb) +{ + struct lov_oinfo *oinfo = cl2osc(obj)->oo_oinfo; + + lvb->lvb_size = oinfo->loi_kms; + lvb->lvb_blocks = oinfo->loi_lvb.lvb_blocks; + return 0; +} + +void osc_object_set_contended(struct osc_object *obj) +{ + obj->oo_contention_time = cfs_time_current(); + /* mb(); */ + obj->oo_contended = 1; +} + +void osc_object_clear_contended(struct osc_object *obj) +{ + obj->oo_contended = 0; +} + +int osc_object_is_contended(struct osc_object *obj) +{ + struct osc_device *dev = lu2osc_dev(obj->oo_cl.co_lu.lo_dev); + int osc_contention_time = dev->od_contention_time; + unsigned long cur_time = cfs_time_current(); + unsigned long retry_time; + + if (OBD_FAIL_CHECK(OBD_FAIL_OSC_OBJECT_CONTENTION)) + return 1; + + if (!obj->oo_contended) + return 0; + + /* + * I like copy-paste. the code is copied from + * ll_file_is_contended. + */ + retry_time = cfs_time_add(obj->oo_contention_time, + cfs_time_seconds(osc_contention_time)); + if (cfs_time_after(cur_time, retry_time)) { + osc_object_clear_contended(obj); + return 0; + } + return 1; +} + +static const struct cl_object_operations osc_ops = { + .coo_page_init = osc_page_init, + .coo_lock_init = osc_lock_init, + .coo_io_init = osc_io_init, + .coo_attr_get = osc_attr_get, + .coo_attr_set = osc_attr_set, + .coo_glimpse = osc_object_glimpse +}; + +static const struct lu_object_operations osc_lu_obj_ops = { + .loo_object_init = osc_object_init, + .loo_object_delete = NULL, + .loo_object_release = NULL, + .loo_object_free = osc_object_free, + .loo_object_print = osc_object_print, + .loo_object_invariant = NULL +}; + +struct lu_object *osc_object_alloc(const struct lu_env *env, + const struct lu_object_header *unused, + struct lu_device *dev) +{ + struct osc_object *osc; + struct lu_object *obj; + + osc = kmem_cache_zalloc(osc_object_kmem, GFP_NOFS); + if (osc) { + obj = osc2lu(osc); + lu_object_init(obj, NULL, dev); + osc->oo_cl.co_ops = &osc_ops; + obj->lo_ops = &osc_lu_obj_ops; + } else + obj = NULL; + return obj; +} + +/** @} osc */ diff --git a/pool/shard002/C/0062128_compass.c b/pool/shard002/C/0062128_compass.c new file mode 100644 index 0000000000000000000000000000000000000000..9a1738342894f8e64cce54697ea1d32a6a57b362 --- /dev/null +++ b/pool/shard002/C/0062128_compass.c @@ -0,0 +1,214 @@ +/* repeatedly convolve with a rotating mask + * + * 23/10/13 + * - from vips_conv() + */ + +/* + + This file is part of VIPS. + + VIPS is free software; you can redistribute it and/or modify + it under the terms of the GNU Lesser General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA + 02110-1301 USA + + */ + +/* + + These files are distributed with VIPS - http://www.vips.ecs.soton.ac.uk + + */ + +#ifdef HAVE_CONFIG_H +#include +#endif /*HAVE_CONFIG_H*/ +#include + +#include + +#include + +#include "pconvolution.h" + +typedef struct { + VipsConvolution parent_instance; + + int times; + VipsAngle45 angle; + VipsCombine combine; + VipsPrecision precision; + int layers; + int cluster; +} VipsCompass; + +typedef VipsConvolutionClass VipsCompassClass; + +G_DEFINE_TYPE( VipsCompass, vips_compass, VIPS_TYPE_CONVOLUTION ); + +static int +vips_compass_build( VipsObject *object ) +{ + VipsConvolution *convolution = (VipsConvolution *) object; + VipsCompass *compass = (VipsCompass *) object; + VipsImage **masks; + VipsImage *mask; + VipsImage **images; + int i; + VipsImage **abs; + VipsImage **combine; + VipsImage *x; + + g_object_set( compass, "out", vips_image_new(), NULL ); + + if( VIPS_OBJECT_CLASS( vips_compass_parent_class )->build( object ) ) + return( -1 ); + + masks = (VipsImage **) + vips_object_local_array( object, compass->times ); + images = (VipsImage **) + vips_object_local_array( object, compass->times ); + abs = (VipsImage **) + vips_object_local_array( object, compass->times ); + combine = (VipsImage **) + vips_object_local_array( object, compass->times ); + + mask = convolution->M; + for( i = 0; i < compass->times; i++ ) { + if( vips_conv( convolution->in, &images[i], mask, + "precision", compass->precision, + "layers", compass->layers, + "cluster", compass->cluster, + NULL ) ) + return( -1 ); + if( vips_rot45( mask, &masks[i], + "angle", compass->angle, + NULL ) ) + return( -1 ); + + mask = masks[i]; + } + + for( i = 0; i < compass->times; i++ ) + if( vips_abs( images[i], &abs[i], NULL ) ) + return( -1 ); + + switch( compass->combine ) { + case VIPS_COMBINE_MAX: + if( vips_bandrank( abs, &combine[0], compass->times, + "index", compass->times - 1, + NULL ) ) + return( -1 ); + x = combine[0]; + break; + + case VIPS_COMBINE_SUM: + x = abs[0]; + for( i = 1; i < compass->times; i++ ) { + if( vips_add( x, abs[i], &combine[i], NULL ) ) + return( -1 ); + x = combine[i]; + } + break; + + default: + g_assert( 0 ); + } + + if( vips_image_write( x, convolution->out ) ) + return( -1 ); + + return( 0 ); +} + +static void +vips_compass_class_init( VipsCompassClass *class ) +{ + GObjectClass *gobject_class = G_OBJECT_CLASS( class ); + VipsObjectClass *object_class = (VipsObjectClass *) class; + + gobject_class->set_property = vips_object_set_property; + gobject_class->get_property = vips_object_get_property; + + object_class->nickname = "compass"; + object_class->description = _( "convolve with rotaing mask" ); + object_class->build = vips_compass_build; + + VIPS_ARG_INT( class, "times", 101, + _( "Times" ), + _( "Rotate and convolve this many times" ), + VIPS_ARGUMENT_OPTIONAL_INPUT, + G_STRUCT_OFFSET( VipsCompass, times ), + 1, 1000, 2 ); + + VIPS_ARG_ENUM( class, "angle", 103, + _( "Angle" ), + _( "Rotate mask by this much between convolutions" ), + VIPS_ARGUMENT_OPTIONAL_INPUT, + G_STRUCT_OFFSET( VipsCompass, angle ), + VIPS_TYPE_ANGLE45, VIPS_ANGLE45_90 ); + + VIPS_ARG_ENUM( class, "combine", 104, + _( "Combine" ), + _( "Combine convolution results like this" ), + VIPS_ARGUMENT_OPTIONAL_INPUT, + G_STRUCT_OFFSET( VipsCompass, combine ), + VIPS_TYPE_COMBINE, VIPS_COMBINE_MAX ); + + VIPS_ARG_ENUM( class, "precision", 203, + _( "Precision" ), + _( "Convolve with this precision" ), + VIPS_ARGUMENT_OPTIONAL_INPUT, + G_STRUCT_OFFSET( VipsCompass, precision ), + VIPS_TYPE_PRECISION, VIPS_PRECISION_INTEGER ); + + VIPS_ARG_INT( class, "layers", 204, + _( "Layers" ), + _( "Use this many layers in approximation" ), + VIPS_ARGUMENT_OPTIONAL_INPUT, + G_STRUCT_OFFSET( VipsCompass, layers ), + 1, 1000, 5 ); + + VIPS_ARG_INT( class, "cluster", 205, + _( "Cluster" ), + _( "Cluster lines closer than this in approximation" ), + VIPS_ARGUMENT_OPTIONAL_INPUT, + G_STRUCT_OFFSET( VipsCompass, cluster ), + 1, 100, 1 ); + +} + +static void +vips_compass_init( VipsCompass *compass ) +{ + compass->times = 2; + compass->angle = VIPS_ANGLE45_90; + compass->combine = VIPS_COMBINE_MAX; + compass->precision = VIPS_PRECISION_INTEGER; + compass->layers = 5; + compass->cluster = 1; +} + +int +vips_compass( VipsImage *in, VipsImage **out, VipsImage *mask, ... ) +{ + va_list ap; + int result; + + va_start( ap, mask ); + result = vips_call_split( "compass", ap, in, out, mask ); + va_end( ap ); + + return( result ); +} diff --git a/pool/shard002/C/0062135_ac_80211_json_directsequencecontrol.c b/pool/shard002/C/0062135_ac_80211_json_directsequencecontrol.c new file mode 100644 index 0000000000000000000000000000000000000000..08691d313eb41bbf57bd932cf20e60aca7a96c0a --- /dev/null +++ b/pool/shard002/C/0062135_ac_80211_json_directsequencecontrol.c @@ -0,0 +1,88 @@ +#include "ac.h" +#include "ac_json.h" + +/* +IEEE80211DirectSequenceControl: { + CurrentChan: [int], + CurrentCCA: [int], + EnergyDetectThreshold: [int] +} +*/ + +/* */ +static void* ac_json_80211_directsequencecontrol_createmessageelement(struct json_object* jsonparent, uint16_t radioid) { + struct json_object* jsonitem; + struct capwap_80211_directsequencecontrol_element* directsequencecontrol; + + directsequencecontrol = (struct capwap_80211_directsequencecontrol_element*)capwap_alloc(sizeof(struct capwap_80211_directsequencecontrol_element)); + memset(directsequencecontrol, 0, sizeof(struct capwap_80211_directsequencecontrol_element)); + directsequencecontrol->radioid = radioid; + + /* */ + jsonitem = compat_json_object_object_get(jsonparent, "CurrentChan"); + if (jsonitem && (json_object_get_type(jsonitem) == json_type_int)) { + directsequencecontrol->currentchannel = (uint8_t)json_object_get_int(jsonitem); + } else { + capwap_free(directsequencecontrol); + return NULL; + } + + jsonitem = compat_json_object_object_get(jsonparent, "CurrentCCA"); + if (jsonitem && (json_object_get_type(jsonitem) == json_type_int)) { + directsequencecontrol->currentcca = (uint8_t)json_object_get_int(jsonitem); + } else { + capwap_free(directsequencecontrol); + return NULL; + } + + jsonitem = compat_json_object_object_get(jsonparent, "EnergyDetectThreshold"); + if (jsonitem && (json_object_get_type(jsonitem) == json_type_int)) { + directsequencecontrol->enerydetectthreshold = (uint32_t)json_object_get_int(jsonitem); + } else { + capwap_free(directsequencecontrol); + return NULL; + } + + return directsequencecontrol; +} + +/* */ +static int ac_json_80211_directsequencecontrol_addmessageelement(struct ac_json_ieee80211_wtpradio* wtpradio, void* data, int overwrite) { + struct capwap_80211_directsequencecontrol_element* directsequencecontrol = (struct capwap_80211_directsequencecontrol_element*)data; + struct ac_json_ieee80211_item* item = &wtpradio->items[directsequencecontrol->radioid - 1]; + const struct capwap_message_elements_ops *ops = capwap_get_message_element_ops(CAPWAP_ELEMENT_80211_DIRECTSEQUENCECONTROL); + + if (item->directsequencecontrol) { + if (!overwrite) { + return 0; + } + + ops->free(item->directsequencecontrol); + } + + item->valid = 1; + item->directsequencecontrol = (struct capwap_80211_directsequencecontrol_element*)ops->clone(directsequencecontrol); + + return 1; +} + +/* */ +static void ac_json_80211_directsequencecontrol_createjson(struct json_object* jsonparent, void* data) { + struct json_object* jsonitem; + struct capwap_80211_directsequencecontrol_element* directsequencecontrol = (struct capwap_80211_directsequencecontrol_element*)data; + + jsonitem = json_object_new_object(); + json_object_object_add(jsonitem, "CurrentChan", json_object_new_int((int)directsequencecontrol->currentchannel)); + json_object_object_add(jsonitem, "CurrentCCA", json_object_new_int((int)directsequencecontrol->currentcca)); + json_object_object_add(jsonitem, "EnergyDetectThreshold", json_object_new_int((int)directsequencecontrol->enerydetectthreshold)); + json_object_object_add(jsonparent, "IEEE80211DirectSequenceControl", jsonitem); +} + +/* */ +struct ac_json_ieee80211_ops ac_json_80211_directsequencecontrol_ops = { + .type = CAPWAP_ELEMENT_80211_DIRECTSEQUENCECONTROL, + .json_type = "IEEE80211DirectSequenceControl", + .create = ac_json_80211_directsequencecontrol_createmessageelement, + .add_message_element = ac_json_80211_directsequencecontrol_addmessageelement, + .create_json = ac_json_80211_directsequencecontrol_createjson +}; diff --git a/pool/shard002/C/0062153_mxms.c b/pool/shard002/C/0062153_mxms.c new file mode 100644 index 0000000000000000000000000000000000000000..839ca1edc132e9c1db915522c3b573f549821574 --- /dev/null +++ b/pool/shard002/C/0062153_mxms.c @@ -0,0 +1,193 @@ +/* + * 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 +#include "mxms.h" + +#define ROM16(x) le16_to_cpu(*(u16 *)&(x)) +#define ROM32(x) le32_to_cpu(*(u32 *)&(x)) + +static u8 * +mxms_data(struct nouveau_mxm *mxm) +{ + return mxm->mxms; + +} + +u16 +mxms_version(struct nouveau_mxm *mxm) +{ + u8 *mxms = mxms_data(mxm); + u16 version = (mxms[4] << 8) | mxms[5]; + switch (version ) { + case 0x0200: + case 0x0201: + case 0x0300: + return version; + default: + break; + } + + nv_debug(mxm, "unknown version %d.%d\n", mxms[4], mxms[5]); + return 0x0000; +} + +u16 +mxms_headerlen(struct nouveau_mxm *mxm) +{ + return 8; +} + +u16 +mxms_structlen(struct nouveau_mxm *mxm) +{ + return *(u16 *)&mxms_data(mxm)[6]; +} + +bool +mxms_checksum(struct nouveau_mxm *mxm) +{ + u16 size = mxms_headerlen(mxm) + mxms_structlen(mxm); + u8 *mxms = mxms_data(mxm), sum = 0; + while (size--) + sum += *mxms++; + if (sum) { + nv_debug(mxm, "checksum invalid\n"); + return false; + } + return true; +} + +bool +mxms_valid(struct nouveau_mxm *mxm) +{ + u8 *mxms = mxms_data(mxm); + if (*(u32 *)mxms != 0x5f4d584d) { + nv_debug(mxm, "signature invalid\n"); + return false; + } + + if (!mxms_version(mxm) || !mxms_checksum(mxm)) + return false; + + return true; +} + +bool +mxms_foreach(struct nouveau_mxm *mxm, u8 types, + bool (*exec)(struct nouveau_mxm *, u8 *, void *), void *info) +{ + u8 *mxms = mxms_data(mxm); + u8 *desc = mxms + mxms_headerlen(mxm); + u8 *fini = desc + mxms_structlen(mxm) - 1; + while (desc < fini) { + u8 type = desc[0] & 0x0f; + u8 headerlen = 0; + u8 recordlen = 0; + u8 entries = 0; + + switch (type) { + case 0: /* Output Device Structure */ + if (mxms_version(mxm) >= 0x0300) + headerlen = 8; + else + headerlen = 6; + break; + case 1: /* System Cooling Capability Structure */ + case 2: /* Thermal Structure */ + case 3: /* Input Power Structure */ + headerlen = 4; + break; + case 4: /* GPIO Device Structure */ + headerlen = 4; + recordlen = 2; + entries = (ROM32(desc[0]) & 0x01f00000) >> 20; + break; + case 5: /* Vendor Specific Structure */ + headerlen = 8; + break; + case 6: /* Backlight Control Structure */ + if (mxms_version(mxm) >= 0x0300) { + headerlen = 4; + recordlen = 8; + entries = (desc[1] & 0xf0) >> 4; + } else { + headerlen = 8; + } + break; + case 7: /* Fan Control Structure */ + headerlen = 8; + recordlen = 4; + entries = desc[1] & 0x07; + break; + default: + nv_debug(mxm, "unknown descriptor type %d\n", type); + return false; + } + + if (nv_subdev(mxm)->debug >= NV_DBG_DEBUG && (exec == NULL)) { + static const char * mxms_desc_name[] = { + "ODS", "SCCS", "TS", "IPS", + "GSD", "VSS", "BCS", "FCS", + }; + u8 *dump = desc; + int i, j; + + nv_debug(mxm, "%4s: ", mxms_desc_name[type]); + for (j = headerlen - 1; j >= 0; j--) + printk("%02x", dump[j]); + printk("\n"); + dump += headerlen; + + for (i = 0; i < entries; i++, dump += recordlen) { + nv_debug(mxm, " "); + for (j = recordlen - 1; j >= 0; j--) + printk("%02x", dump[j]); + printk("\n"); + } + } + + if (types & (1 << type)) { + if (!exec(mxm, desc, info)) + return false; + } + + desc += headerlen + (entries * recordlen); + } + + return true; +} + +void +mxms_output_device(struct nouveau_mxm *mxm, u8 *pdata, struct mxms_odev *desc) +{ + u64 data = ROM32(pdata[0]); + if (mxms_version(mxm) >= 0x0300) + data |= (u64)ROM16(pdata[4]) << 32; + + desc->outp_type = (data & 0x00000000000000f0ULL) >> 4; + desc->ddc_port = (data & 0x0000000000000f00ULL) >> 8; + desc->conn_type = (data & 0x000000000001f000ULL) >> 12; + desc->dig_conn = (data & 0x0000000000780000ULL) >> 19; +} diff --git a/pool/shard002/C/0062157_library.c b/pool/shard002/C/0062157_library.c new file mode 100644 index 0000000000000000000000000000000000000000..c05522eb2b4fc889b7002c88a3ff5682933d9e92 --- /dev/null +++ b/pool/shard002/C/0062157_library.c @@ -0,0 +1,189 @@ +/* + * Copyright (C) 2015~2015 by CSSlayer + * wengxt@gmail.com + * + * This library is free software; you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation; either version 2 of the + * License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; see the file COPYING. If not, + * see . + */ + +#include "utils.h" +#include "library.h" +#include "stringutils.h" +#include +#include +#include +#include +#include +#include +#include +#include + +struct _FcitxLibrary +{ + char* path; + char* errorString; + void* handle; +}; + +FCITX_EXPORT_API +FcitxLibrary* fcitx_library_new(const char* path) +{ + FcitxLibrary* lib = fcitx_utils_new(FcitxLibrary); + if (path) { + lib->path = fcitx_utils_strdup(path); + } else { + lib->path = NULL; + } + return lib; +} + +FCITX_EXPORT_API +void fcitx_library_free(FcitxLibrary* lib) +{ + if (!lib) { + return; + } + free(lib->errorString); + free(lib->path); + free(lib); +} + +FCITX_EXPORT_API +bool fcitx_library_load(FcitxLibrary* lib, uint32_t hint) +{ + int flag = 0; + if (hint & FLLH_ResolveAllSymbolsHint) { + flag |= RTLD_NOW; + } else { + flag |= RTLD_LAZY; + } + + if (hint & FLLH_PreventUnloadHint) { + flag |= RTLD_NODELETE; + } + + if (hint & FLLH_ExportExternalSymbolsHint) { + flag |= RTLD_GLOBAL; + } + + lib->handle = dlopen(lib->path, flag); + if (!lib->handle) { + fcitx_utils_string_swap(&lib->errorString, dlerror()); + return false; + } + + return true; +} + +FCITX_EXPORT_API +bool fcitx_library_unload(FcitxLibrary* lib) +{ + if (!lib->handle) { + return false; + } + + if (dlclose(lib->handle)) { + fcitx_utils_string_swap(&lib->errorString, dlerror()); + return false; + } + + lib->handle = NULL; + return true; +} + +FCITX_EXPORT_API +bool fcitx_library_find_data(FcitxLibrary* lib, const char* slug, const char* magic, size_t lenOfMagic, FcitxLibraryDataParser parser, void* arg) +{ + if (lib->handle) { + void* data = fcitx_library_resolve(lib, slug); + if (!data) { + return false; + } + + if (memcmp(data, magic, lenOfMagic) != 0) { + return false; + } + + data += lenOfMagic; + if (parser) { + parser(data, arg); + } + return true; + } + + int fd = open(lib->path, O_RDONLY); + if (fd < 0) { + fcitx_utils_string_swap(&lib->errorString, strerror(errno)); + return false; + } + + void* needfree = NULL; + bool result = false; + do { + struct stat statbuf; + int statresult = fstat(fd, &statbuf); + if (statresult < 0) { + fcitx_utils_string_swap(&lib->errorString, strerror(errno)); + break; + } + void* needunmap = NULL; + void* data = needunmap = mmap(0, statbuf.st_size, PROT_READ, MAP_PRIVATE, fd, 0); + if (!data) { + data = malloc(statbuf.st_size); + needfree = data; + if (!data) { + break; + } + if (read(fd, data, statbuf.st_size) != statbuf.st_size) { + break; + } + } + char* pos = fcitx_utils_backward_search(data, (size_t) statbuf.st_size, magic, lenOfMagic, 0); + pos += lenOfMagic; + + if (parser) { + parser(pos, arg); + } + result = true; + if (needunmap) { + munmap(needunmap, statbuf.st_size); + } + } while(0); + + close(fd); + free(needfree); + + return result; +} + +FCITX_EXPORT_API +void* fcitx_library_resolve(FcitxLibrary* lib, const char* symbol) +{ + if (!lib->handle) { + return NULL; + } + + void* result = dlsym(lib->handle, symbol); + if (!result) { + fcitx_utils_string_swap(&lib->errorString, dlerror()); + } + return result; +} + +FCITX_EXPORT_API +const char* fcitx_library_error(FcitxLibrary* lib) +{ + return lib->errorString; +} + diff --git a/pool/shard002/C/0062162_udp.c b/pool/shard002/C/0062162_udp.c new file mode 100644 index 0000000000000000000000000000000000000000..17289d6cd5da3d10060de471e0facf4252c991c6 --- /dev/null +++ b/pool/shard002/C/0062162_udp.c @@ -0,0 +1,56 @@ +/* + * This source code is a part of coLinux source package. + * + * Dan Aloni , 2003 (c) + * Service support by Jaroslaw Kowalski , 2004 (c) + * + * The code is licensed under the GPL. See the COPYING file at + * the root directory. + * + */ + +#include +#include +#include +#include + +#include +#include +#include + +int co_udp_socket_connect(const char *addr, unsigned short int port) +{ + struct sockaddr_in server; + int ret, sock; + WSADATA wsaData; + + WSAStartup(MAKEWORD(2,2), &wsaData); + + sock = socket(AF_INET, SOCK_DGRAM, 0); + if (sock == -1) { + printf("unable to create socket %x\n", sock); + return -1; + } + + co_bzero((char *)&server, sizeof(server)); + server.sin_family = AF_INET; + server.sin_addr.s_addr = inet_addr(addr); + server.sin_port = htons(port); + + ret = connect(sock, (struct sockaddr *)&server, sizeof(server)); + if (ret) + return -1; + + return sock; +} + +int co_udp_socket_send(int sock, const char *buffer, uintptr_t size) +{ + return send(sock, buffer, size, 0); +} + +void co_udp_socket_close(int sock) +{ + closesocket(sock); +} + diff --git a/pool/shard002/C/0062177_owtest_utils.c b/pool/shard002/C/0062177_owtest_utils.c new file mode 100644 index 0000000000000000000000000000000000000000..889f8f414eb61cc6f9d40d05e1dd9e26610a1983 --- /dev/null +++ b/pool/shard002/C/0062177_owtest_utils.c @@ -0,0 +1,296 @@ +/* + * File: owtest_utils.h + * + * Author: Erik Reid + * GÉANT + * + * Description: shared test methods/structs + */ +#include + +#include +#include +#include +#include +#include + +#include +#include + +#include + +#include "./owtest_utils.h" + + +/* + * Function: tmpFile + * + * Description: creates a temporary file + * + * In Args: + * + * Out Args: + * + * Scope: + * Returns: a pointer to a FILE + * Side Effect: + */ +FILE *tmpFile(void) { + char *filename = (char *) malloc(sizeof TMPNAME_FMT); + FILE *fp = NULL; + + strcpy(filename, TMPNAME_FMT); + int fd = mkstemp(filename); + if (fd < 0) { + printf("mkstemp error: %m\n"); + goto tmp_file_error; + } + + fp = fdopen(fd, "w+b"); + if (!fp) { + printf("fdopen error: %m\n"); + goto tmp_file_error; + } + + if(unlink(filename)) { + printf("unlink error: %m\n"); + goto tmp_file_error; + } + + free(filename); + return fp; + +tmp_file_error: + if (fp) { + fclose(fp); + } + free(filename); + exit(1); +} + +/* + * Function: tmpSessionDataFile + * + * Description: creates a temporary file & writes the input + * binary data to it (input should be a hex string) + * + * In Args: string of hex characters + * + * Out Args: + * + * Scope: + * Returns: a pointer to a FILE + * Side Effect: + */ +FILE *tmpSessionDataFile(const char *hex) { + size_t nbytes = strlen(hex)/2; + uint8_t *bytes = (uint8_t *) malloc(nbytes); + FILE *fp = NULL; + + if(!I2HexDecode(hex, bytes, nbytes)) { + printf("I2HexDecode error\n"); + goto tmp_file_error; + } + + fp = tmpFile(); + if(fwrite(bytes, 1, nbytes, fp) != nbytes) { + printf("error writing test data\n"); + goto tmp_file_error; + } + + rewind(fp); + free(bytes); + return fp; + +tmp_file_error: + if (fp) { + fclose(fp); + } + free(bytes); + exit(1); +} + + +/* + * Function: rmdir_recursive + * + * Description: simple version of 'rm -r' + * + * In Args: directory name + * + * Out Args: + * + * Scope: + * Returns: + * Side Effect: simple: doesn't really recover from or report errors + */ +void rmdir_recursive(const char *dir_name) { + DIR *d = opendir(dir_name); + if (!d) { + fprintf(stderr, "can't open directory: %s\n", dir_name); + perror("opendir error"); + return; + } + + struct dirent *e; + while((e=readdir(d))) { + if(!strcmp(e->d_name, ".") || !strcmp(e->d_name, "..")) { + continue; + } + + char name[PATH_MAX]; + struct stat statbuf; + + sprintf(name, "%s/%s", dir_name, e->d_name); + if(!stat(name, &statbuf)) { + if (S_ISDIR(statbuf.st_mode)) { + rmdir_recursive(name); + } else { + if(unlink(name)) { + fprintf(stderr, "couldn't unlink file: %s\n", name); + perror("unlink error"); + } + } + } + } + + closedir(d); + if(rmdir(dir_name)) { + fprintf(stderr, "couldn't rmdir: %s\n", dir_name); + perror("rmdir error"); + } +} + + + + + +/* + * Function: tmpContext + * + * Description: creates an OWPContext instance that can be used + * for testing + * + * In Args: argv passed to main + * + * Out Args: + * + * Scope: + * Returns: a new OWPContext + * Side Effect: I2ErrLogImmediate is static, so effectively global + * ... i.e. this is a convenience function that just + * makes test code a bit easier to read, but should be + * called only once (per process) + */ +OWPContext tmpContext(char **argv) { + char *progname; + progname = (progname = strrchr(argv[0], '/')) ? progname+1 : *argv; + + static I2LogImmediateAttr ia; + ia.line_info = I2NAME | I2MSG | I2LINE | I2FILE; + ia.fp = stderr; + I2ErrHandle eh = I2ErrOpen(progname, I2ErrLogImmediate, &ia, NULL, NULL); + if (!eh) { + printf("I2ErrOpen failed\n"); + exit(1); + } + + OWPContext ctx = OWPContextCreate(eh); + if(!ctx) { + printf("OWPContextCreate returned NULL\n"); + exit(1); + } + return ctx; +} + + + +/* + * Function: run_server + * + * Description: starts a server that listens and accepts connections + * on a unix socket + * + * In Args: pointer to a struct _server_params, socket_path and + * client_proc must be initialized + * + * Out Args: + * + * Scope: + * Returns: NULL when an error occurs or the server ends + * Side Effect: + */ +void *run_server(struct _server_params *server_params) { + int fd; + + struct sockaddr_un addr; + memset(&addr, 0, sizeof addr); + addr.sun_family = AF_UNIX; + strncpy( + addr.sun_path, + server_params->socket_path, + sizeof addr.sun_path - 1); + + fd = socket(AF_UNIX, SOCK_STREAM, 0); + if (fd < 0) { + perror("error creating server socket"); + return NULL; + } + + if(bind(fd, (struct sockaddr *) &addr, sizeof addr) == -1) { + close(fd); + perror("bind error"); + return NULL; + } + + if (listen(fd, 1) == -1) { + close(fd); + perror("listen error"); + return NULL; + } + + int keep_serving = 1; + while(keep_serving) { + int cfd = accept(fd, NULL, NULL); + if (cfd == -1) { + close(fd); + perror("accept error"); + return NULL; + } + + keep_serving = server_params->client_proc(cfd, server_params->test_context); + + close(cfd); + } + + close(fd); + return NULL; +} + +/* + * Function: count_occurrences + * + * Description: count the number of occurrences of needle in haystack + * + * In Args: needle: string to search for + * haystack: string in which to search + * + * Out Args: + * + * Scope: + * Returns: number of occurences found + * Side Effect: + */ +int count_occurrences(const char *haystack, const char *needle) { + int num = 0; + while(1) { + char *match = strstr(haystack, needle); + if (!match || strlen(match) < strlen(needle)) { + return num; + } + haystack = &match[strlen(needle)]; + num++; + } +} + + diff --git a/pool/shard002/C/0062190_ehci-omap.c b/pool/shard002/C/0062190_ehci-omap.c new file mode 100644 index 0000000000000000000000000000000000000000..3c58f9e656c6d1a2dbe5a2bd103dfbe623a96eb2 --- /dev/null +++ b/pool/shard002/C/0062190_ehci-omap.c @@ -0,0 +1,274 @@ +/* + * (C) Copyright 2011 Ilya Yanok, Emcraft Systems + * (C) Copyright 2004-2008 + * Texas Instruments, + * + * Derived from Beagle Board code by + * Sunil Kumar + * Shashi Ranjan + * + * + * SPDX-License-Identifier: GPL-2.0+ + */ + +#include +#include +#include +#include +#include +#include +#include +#include + +#include "ehci.h" + +static struct omap_uhh *const uhh = (struct omap_uhh *)OMAP_UHH_BASE; +static struct omap_usbtll *const usbtll = (struct omap_usbtll *)OMAP_USBTLL_BASE; +static struct omap_ehci *const ehci = (struct omap_ehci *)OMAP_EHCI_BASE; + +static int omap_uhh_reset(void) +{ +/* + * Soft resetting the UHH module causes instability issues on + * all OMAPs so we just avoid it. + * + * See OMAP36xx Errata + * i571: USB host EHCI may stall when entering smart-standby mode + * i660: USBHOST Configured In Smart-Idle Can Lead To a Deadlock + * + * On OMAP4/5, soft-resetting the UHH module will put it into + * Smart-Idle mode and lead to a deadlock. + * + * On OMAP3, this doesn't seem to be the case but still instabilities + * are observed on beagle (3530 ES1.0) if soft-reset is used. + * e.g. NFS root failures with Linux kernel. + */ + return 0; +} + +static int omap_ehci_tll_reset(void) +{ + unsigned long init = get_timer(0); + + /* perform TLL soft reset, and wait until reset is complete */ + writel(OMAP_USBTLL_SYSCONFIG_SOFTRESET, &usbtll->sysc); + + /* Wait for TLL reset to complete */ + while (!(readl(&usbtll->syss) & OMAP_USBTLL_SYSSTATUS_RESETDONE)) + if (get_timer(init) > CONFIG_SYS_HZ) { + debug("OMAP EHCI error: timeout resetting TLL\n"); + return -EL3RST; + } + + return 0; +} + +static void omap_usbhs_hsic_init(int port) +{ + unsigned int reg; + + /* Enable channels now */ + reg = readl(&usbtll->channel_conf + port); + + setbits_le32(®, (OMAP_TLL_CHANNEL_CONF_CHANMODE_TRANSPARENT_UTMI + | OMAP_TLL_CHANNEL_CONF_ULPINOBITSTUFF + | OMAP_TLL_CHANNEL_CONF_DRVVBUS + | OMAP_TLL_CHANNEL_CONF_CHRGVBUS + | OMAP_TLL_CHANNEL_CONF_CHANEN)); + + writel(reg, &usbtll->channel_conf + port); +} + +#ifdef CONFIG_USB_ULPI +static void omap_ehci_soft_phy_reset(int port) +{ + struct ulpi_viewport ulpi_vp; + + ulpi_vp.viewport_addr = (u32)&ehci->insreg05_utmi_ulpi; + ulpi_vp.port_num = port; + + ulpi_reset(&ulpi_vp); +} +#else +static void omap_ehci_soft_phy_reset(int port) +{ + return; +} +#endif + +inline int __board_usb_init(void) +{ + return 0; +} +int board_usb_init(void) __attribute__((weak, alias("__board_usb_init"))); + +#if defined(CONFIG_OMAP_EHCI_PHY1_RESET_GPIO) || \ + defined(CONFIG_OMAP_EHCI_PHY2_RESET_GPIO) || \ + defined(CONFIG_OMAP_EHCI_PHY3_RESET_GPIO) +/* controls PHY(s) reset signal(s) */ +static inline void omap_ehci_phy_reset(int on, int delay) +{ + /* + * Refer ISSUE1: + * Hold the PHY in RESET for enough time till + * PHY is settled and ready + */ + if (delay && !on) + udelay(delay); +#ifdef CONFIG_OMAP_EHCI_PHY1_RESET_GPIO + gpio_request(CONFIG_OMAP_EHCI_PHY1_RESET_GPIO, "USB PHY1 reset"); + gpio_direction_output(CONFIG_OMAP_EHCI_PHY1_RESET_GPIO, !on); +#endif +#ifdef CONFIG_OMAP_EHCI_PHY2_RESET_GPIO + gpio_request(CONFIG_OMAP_EHCI_PHY2_RESET_GPIO, "USB PHY2 reset"); + gpio_direction_output(CONFIG_OMAP_EHCI_PHY2_RESET_GPIO, !on); +#endif +#ifdef CONFIG_OMAP_EHCI_PHY3_RESET_GPIO + gpio_request(CONFIG_OMAP_EHCI_PHY3_RESET_GPIO, "USB PHY3 reset"); + gpio_direction_output(CONFIG_OMAP_EHCI_PHY3_RESET_GPIO, !on); +#endif + + /* Hold the PHY in RESET for enough time till DIR is high */ + /* Refer: ISSUE1 */ + if (delay && on) + udelay(delay); +} +#else +#define omap_ehci_phy_reset(on, delay) do {} while (0) +#endif + +/* Reset is needed otherwise the kernel-driver will throw an error. */ +int omap_ehci_hcd_stop(void) +{ + debug("Resetting OMAP EHCI\n"); + omap_ehci_phy_reset(1, 0); + + if (omap_uhh_reset() < 0) + return -1; + + if (omap_ehci_tll_reset() < 0) + return -1; + + return 0; +} + +/* + * Initialize the OMAP EHCI controller and PHY. + * Based on "drivers/usb/host/ehci-omap.c" from Linux 3.1 + * See there for additional Copyrights. + */ +int omap_ehci_hcd_init(struct omap_usbhs_board_data *usbhs_pdata, + struct ehci_hccr **hccr, struct ehci_hcor **hcor) +{ + int ret; + unsigned int i, reg = 0, rev = 0; + + debug("Initializing OMAP EHCI\n"); + + ret = board_usb_init(); + if (ret < 0) + return ret; + + /* Put the PHY in RESET */ + omap_ehci_phy_reset(1, 10); + + ret = omap_uhh_reset(); + if (ret < 0) + return ret; + + ret = omap_ehci_tll_reset(); + if (ret) + return ret; + + writel(OMAP_USBTLL_SYSCONFIG_ENAWAKEUP | + OMAP_USBTLL_SYSCONFIG_SIDLEMODE | + OMAP_USBTLL_SYSCONFIG_CACTIVITY, &usbtll->sysc); + + /* Put UHH in NoIdle/NoStandby mode */ + writel(OMAP_UHH_SYSCONFIG_VAL, &uhh->sysc); + + /* setup ULPI bypass and burst configurations */ + clrsetbits_le32(®, OMAP_UHH_HOSTCONFIG_INCRX_ALIGN_EN, + (OMAP_UHH_HOSTCONFIG_INCR4_BURST_EN | + OMAP_UHH_HOSTCONFIG_INCR8_BURST_EN | + OMAP_UHH_HOSTCONFIG_INCR16_BURST_EN)); + + rev = readl(&uhh->rev); + if (rev == OMAP_USBHS_REV1) { + if (is_ehci_phy_mode(usbhs_pdata->port_mode[0])) + clrbits_le32(®, OMAP_UHH_HOSTCONFIG_ULPI_P1_BYPASS); + else + setbits_le32(®, OMAP_UHH_HOSTCONFIG_ULPI_P1_BYPASS); + + if (is_ehci_phy_mode(usbhs_pdata->port_mode[1])) + clrbits_le32(®, OMAP_UHH_HOSTCONFIG_ULPI_P2_BYPASS); + else + setbits_le32(®, OMAP_UHH_HOSTCONFIG_ULPI_P2_BYPASS); + + if (is_ehci_phy_mode(usbhs_pdata->port_mode[2])) + clrbits_le32(®, OMAP_UHH_HOSTCONFIG_ULPI_P3_BYPASS); + else + setbits_le32(®, OMAP_UHH_HOSTCONFIG_ULPI_P3_BYPASS); + } else if (rev == OMAP_USBHS_REV2) { + + clrsetbits_le32(®, (OMAP_P1_MODE_CLEAR | OMAP_P2_MODE_CLEAR), + OMAP4_UHH_HOSTCONFIG_APP_START_CLK); + + /* Clear port mode fields for PHY mode */ + + if (is_ehci_hsic_mode(usbhs_pdata->port_mode[0])) + setbits_le32(®, OMAP_P1_MODE_HSIC); + + if (is_ehci_hsic_mode(usbhs_pdata->port_mode[1])) + setbits_le32(®, OMAP_P2_MODE_HSIC); + + } else if (rev == OMAP_USBHS_REV2_1) { + + clrsetbits_le32(®, + (OMAP_P1_MODE_CLEAR | + OMAP_P2_MODE_CLEAR | + OMAP_P3_MODE_CLEAR), + OMAP4_UHH_HOSTCONFIG_APP_START_CLK); + + /* Clear port mode fields for PHY mode */ + + if (is_ehci_hsic_mode(usbhs_pdata->port_mode[0])) + setbits_le32(®, OMAP_P1_MODE_HSIC); + + if (is_ehci_hsic_mode(usbhs_pdata->port_mode[1])) + setbits_le32(®, OMAP_P2_MODE_HSIC); + + if (is_ehci_hsic_mode(usbhs_pdata->port_mode[2])) + setbits_le32(®, OMAP_P3_MODE_HSIC); + } + + debug("OMAP UHH_REVISION 0x%x\n", rev); + writel(reg, &uhh->hostconfig); + + for (i = 0; i < OMAP_HS_USB_PORTS; i++) + if (is_ehci_hsic_mode(usbhs_pdata->port_mode[i])) + omap_usbhs_hsic_init(i); + + omap_ehci_phy_reset(0, 10); + + /* + * An undocumented "feature" in the OMAP3 EHCI controller, + * causes suspended ports to be taken out of suspend when + * the USBCMD.Run/Stop bit is cleared (for example when + * we do ehci_bus_suspend). + * This breaks suspend-resume if the root-hub is allowed + * to suspend. Writing 1 to this undocumented register bit + * disables this feature and restores normal behavior. + */ + writel(EHCI_INSNREG04_DISABLE_UNSUSPEND, &ehci->insreg04); + + for (i = 0; i < OMAP_HS_USB_PORTS; i++) + if (is_ehci_phy_mode(usbhs_pdata->port_mode[i])) + omap_ehci_soft_phy_reset(i); + + *hccr = (struct ehci_hccr *)(OMAP_EHCI_BASE); + *hcor = (struct ehci_hcor *)(OMAP_EHCI_BASE + 0x10); + + debug("OMAP EHCI init done\n"); + return 0; +} diff --git a/pool/shard002/C/0062193_irq_pyxis.c b/pool/shard002/C/0062193_irq_pyxis.c new file mode 100644 index 0000000000000000000000000000000000000000..990d467dfa7c732cade97decd3e8e14db2d89940 --- /dev/null +++ b/pool/shard002/C/0062193_irq_pyxis.c @@ -0,0 +1,110 @@ +/* + + + + + + */ + +#include +#include +#include + +#include +#include + +#include "proto.h" +#include "irq_impl.h" + + +/* */ +static unsigned long cached_irq_mask; + +static inline void +pyxis_update_irq_hw(unsigned long mask) +{ + *(vulp)PYXIS_INT_MASK = mask; + mb(); + *(vulp)PYXIS_INT_MASK; +} + +static inline void +pyxis_enable_irq(struct irq_data *d) +{ + pyxis_update_irq_hw(cached_irq_mask |= 1UL << (d->irq - 16)); +} + +static void +pyxis_disable_irq(struct irq_data *d) +{ + pyxis_update_irq_hw(cached_irq_mask &= ~(1UL << (d->irq - 16))); +} + +static void +pyxis_mask_and_ack_irq(struct irq_data *d) +{ + unsigned long bit = 1UL << (d->irq - 16); + unsigned long mask = cached_irq_mask &= ~bit; + + /* */ + *(vulp)PYXIS_INT_MASK = mask; + wmb(); + /* */ + *(vulp)PYXIS_INT_REQ = bit; + mb(); + /* */ + *(vulp)PYXIS_INT_MASK; +} + +static struct irq_chip pyxis_irq_type = { + .name = "PYXIS", + .irq_mask_ack = pyxis_mask_and_ack_irq, + .irq_mask = pyxis_disable_irq, + .irq_unmask = pyxis_enable_irq, +}; + +void +pyxis_device_interrupt(unsigned long vector) +{ + unsigned long pld; + unsigned int i; + + /* */ + pld = *(vulp)PYXIS_INT_REQ; + pld &= cached_irq_mask; + + /* + + + */ + while (pld) { + i = ffz(~pld); + pld &= pld - 1; /* */ + if (i == 7) + isa_device_interrupt(vector); + else + handle_irq(16+i); + } +} + +void __init +init_pyxis_irqs(unsigned long ignore_mask) +{ + long i; + + *(vulp)PYXIS_INT_MASK = 0; /* */ + *(vulp)PYXIS_INT_REQ = -1; /* */ + mb(); + + /* */ + *(vuip) CIA_IACK_SC; + + for (i = 16; i < 48; ++i) { + if ((ignore_mask >> i) & 1) + continue; + irq_set_chip_and_handler(i, &pyxis_irq_type, handle_level_irq); + irq_set_status_flags(i, IRQ_LEVEL); + } + + setup_irq(16+7, &isa_cascade_irqaction); +} diff --git a/pool/shard002/C/0062196_flash.c b/pool/shard002/C/0062196_flash.c new file mode 100644 index 0000000000000000000000000000000000000000..1ca604386f8892a7899ec2081025abfe87a8efb4 --- /dev/null +++ b/pool/shard002/C/0062196_flash.c @@ -0,0 +1,43 @@ +/* + * This file is part of Cleanflight and Betaflight. + * + * Cleanflight and Betaflight are free software. You can redistribute + * this software and/or modify this software 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. + * + * Cleanflight and Betaflight are distributed in the hope that they + * will be useful, but WITHOUT ANY WARRANTY; without even the implied + * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * See the GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this software. + * + * If not, see . + */ + +#include +#include + +#include "platform.h" + +#ifdef USE_FLASHFS + +#include "drivers/bus_spi.h" +#include "drivers/io.h" + +#include "pg/pg.h" +#include "pg/pg_ids.h" + +#include "flash.h" + +PG_REGISTER_WITH_RESET_FN(flashConfig_t, flashConfig, PG_FLASH_CONFIG, 0); + +void pgResetFn_flashConfig(flashConfig_t *flashConfig) +{ + flashConfig->csTag = IO_TAG(FLASH_CS_PIN); + flashConfig->spiDevice = SPI_DEV_TO_CFG(spiDeviceByInstance(FLASH_SPI_INSTANCE)); +} +#endif diff --git a/pool/shard002/C/0062203_image_chksum.c b/pool/shard002/C/0062203_image_chksum.c new file mode 100644 index 0000000000000000000000000000000000000000..df2ac4ceecee010e67c4881558e7ada15726fea7 --- /dev/null +++ b/pool/shard002/C/0062203_image_chksum.c @@ -0,0 +1,209 @@ +/* + * Checksum fixer for Withings WS-30 firmware images + * (Freescale Kinetis K20 MCU) + * + * CRC code directly stolen from http://www.barrgroup.com/Embedded-Systems/How-To/CRC-Calculation-C-Code + */ + +#include +#include +#include +#include +#include +#include + +#define POLYNOMIAL 0x04C11DB7 +#define INITIAL_REMAINDER 0xFFFFFFFF +#define FINAL_XOR_VALUE 0xFFFFFFFF + +#define WIDTH (8 * sizeof(unsigned int)) +#define TOPBIT (1 << (WIDTH - 1)) +#define REFLECT_DATA(X) ((unsigned char) reflect((X), 8)) +#define REFLECT_REMAINDER(X) ((unsigned int) reflect((X), WIDTH)) + +struct fw_header { + unsigned int total_size; + unsigned int gold; + unsigned int version; + unsigned int kinetis_address; + unsigned int kinetis_size; + unsigned int kinetis_crc; + unsigned int wifi_address; + unsigned int wifi_size; + unsigned int bluetooth_address; + unsigned int bluetooth_size; +}; + +unsigned long reflect ( unsigned long data, unsigned char nBits) +{ + unsigned long reflection = 0x00000000; + unsigned char bit; + + /* + * Reflect the data about the center bit. + */ + for (bit = 0; bit < nBits; ++bit) + { + /* + * If the LSB bit is set, set the reflection of it. + */ + if (data & 0x01) + { + reflection |= (1 << ((nBits - 1) - bit)); + } + + data = (data >> 1); + } + + return (reflection); + +} /* reflect() */ + + +unsigned int crcSlow ( unsigned char *message, int nBytes ) +{ + unsigned int remainder = INITIAL_REMAINDER; + int byte; + unsigned char bit; + + + /* + * Perform modulo-2 division, a byte at a time. + */ + for (byte = 0; byte < nBytes; ++byte) + { + /* + * Bring the next byte into the remainder. + */ + remainder ^= (REFLECT_DATA(message[byte]) << (WIDTH - 8)); + + /* + * Perform modulo-2 division, a bit at a time. + */ + for (bit = 8; bit > 0; --bit) + { + /* + * Try to divide the current data bit. + */ + if (remainder & TOPBIT) + { + remainder = (remainder << 1) ^ POLYNOMIAL; + } + else + { + remainder = (remainder << 1); + } + } + } + + /* + * The final remainder is the CRC result. + */ + return (REFLECT_REMAINDER(remainder) ^ FINAL_XOR_VALUE); + +} /* crcSlow() */ + +void error ( char *msg ) +{ + perror(msg); + exit(EXIT_FAILURE); +} + +int main ( int argc, char **argv ) +{ + int fdin, fdout, ret, offset; + unsigned int image_size, image_crc, kinetis_crc; + unsigned char *buf; + struct fw_header *header; + + if ( argc != 2 && argc != 3 ) + { + printf("Usage: %s [outfile]\n", argv[0]); + return -1; + } + + fdin = open(argv[1], O_RDONLY); + if ( fdin < 0 ) + error("open"); + + ret = read(fdin, &image_size, 4); + if ( ret < 0 ) + error("error"); + + printf("Image is %u bytes\n", image_size); + + lseek(fdin, 0, SEEK_SET); + + buf = malloc(image_size); + if ( buf == NULL ) + error("malloc"); + + offset = 0; + while ( (ret = read(fdin, buf + offset, image_size - offset)) != 0 ) + { + if ( ret < 0 ) + error("read"); + offset += ret; + //printf("Read in %d bytes (%d/%d)\n", ret, offset, image_size); + } + + header = (struct fw_header *)buf; + + printf("Found WS-30 firmware image:\n"); + printf(" Total size: %u\n", header->total_size); + printf(" Gold: 0x%08x\n", header->gold); + printf(" Version: %u\n", header->version); + printf(" Kinetis address: 0x%x\n", header->kinetis_address); + printf(" Kinetis size: %u\n", header->kinetis_size); + printf(" Kinetis CRC: 0x%08x\n", header->kinetis_crc); + printf(" WiFi address: 0x%x\n", header->wifi_address); + printf(" WiFi size: %u\n", header->wifi_size); + printf(" Bluetooth address: 0x%x\n", header->bluetooth_address); + printf(" Bluetooth size: %u\n", header->bluetooth_size); + printf(" Image CRC: 0x%08x\n", *(unsigned int *)(buf + header->total_size - 4)); + + image_crc = crcSlow(buf, header->total_size - 4); + printf("\nCalculated image CRC: 0x%08x\n", image_crc); + + kinetis_crc = crcSlow(buf + header->kinetis_address, header->kinetis_size); + printf("Calculated Kinetis CRC: 0x%08x\n", kinetis_crc); + + close(fdin); + + if ( ! argv[2] ) + return 0; + + if ( header->kinetis_crc != kinetis_crc ) + { + header->kinetis_crc = kinetis_crc; + printf("\nPatched Kinetis CRC, recalculating image CRC...\n"); + + image_crc = crcSlow(buf, header->total_size - 4); + printf("Calculated image CRC: 0x%08x\n", image_crc); + } + + fdout = creat(argv[2], 0666); + if ( fdout < 0 ) + error("open"); + + if ( *(unsigned int *)(buf + header->total_size - 4) != image_crc ) + { + *(unsigned int *)(buf + header->total_size - 4) = image_crc; + printf("Patched image CRC\n"); + } + + ret = write(fdout, buf, header->total_size); + if ( ret < 0 ) + error("write"); + else if ( ret != header->total_size ) + { + printf("Didn't write out the entire file, try again.\n"); + return -1; + } + + printf("\nWrote %d bytes to %s\n", ret, argv[2]); + + close(fdout); + + return 0; +} diff --git a/pool/shard002/C/0062222_main.c b/pool/shard002/C/0062222_main.c new file mode 100644 index 0000000000000000000000000000000000000000..b4565bdd73b880bb1c88935060d7a46c8bfaa6c6 --- /dev/null +++ b/pool/shard002/C/0062222_main.c @@ -0,0 +1,155 @@ + +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 4; tab-width: 4 -*- */ +/* + * main.c + * Copyright (C) skottie 2011 + * + * guitar-tuner 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. + * + * guitar-tuner 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 . + */ +/* Frequencies of strings */ +#define NOTE_E 369.23 +#define NOTE_A 440 +#define NOTE_D 587.33 +#define NOTE_G 783.99 +#define NOTE_B 987.77 +#define NOTE_e 1187.23 + +#include +#include +#include + + +#include + + + +/* For testing propose use the local (not installed) ui file */ +/* #define UI_FILE PACKAGE_DATA_DIR"/guitar_tuner/ui/guitar_tuner.ui" */ +#define UI_FILE "src/guitar_tuner.ui" + +/* Signal handlers */ +/* Note: These may not be declared static because signal autoconnection + * only works with non-static methods + */ + +/* Called when the window is closed */ +void +destroy (GtkWidget *widget, gpointer data) +{ + gtk_main_quit (); +} + +static GtkWidget* +create_window (void) +{ + GtkWidget *window; + GtkBuilder *builder; + GError* error = NULL; + + /* Load UI from file */ + builder = gtk_builder_new (); + if (!gtk_builder_add_from_file (builder, UI_FILE, &error)) + { + g_warning ("Couldn't load builder file: %s", error->message); + g_error_free (error); + } + + /* Auto-connect signal handlers */ + gtk_builder_connect_signals (builder, NULL); + + /* Get the window object from the ui file */ + window = GTK_WIDGET (gtk_builder_get_object (builder, "window")); + g_object_unref (builder); + + return window; +} + +#define LENGTH 500 /* Length of playing in ms */ + +static gboolean +pipeline_stop (GstElement* pipeline) +{ + gst_element_set_state (pipeline, GST_STATE_PAUSED); + g_object_unref (pipeline); + + return FALSE; +} + +static void +play_sound (gdouble frequency) +{ + GstElement *source, *sink; + GstElement *pipeline; + + pipeline = gst_pipeline_new ("note"); + source = gst_element_factory_make ("audiotestsrc", + "source"); + sink = gst_element_factory_make ("autoaudiosink", + "output"); + + /* set frequency */ + g_object_set (source, "freq", frequency, NULL); + + gst_bin_add_many (GST_BIN (pipeline), source, sink, NULL); + gst_element_link (source, sink); + + gst_element_set_state (pipeline, GST_STATE_PLAYING); + + /* stop it after 500ms */ + g_timeout_add (LENGTH, (GSourceFunc) pipeline_stop, pipeline); +} + +void +on_button_clicked (GtkButton *button, gpointer user_data) +{ + + GtkWidget* label = gtk_bin_get_child (GTK_BIN (button)); + const gchar* text = gtk_label_get_label (GTK_LABEL (label)); + + if (g_str_equal (text, _("E"))) + play_sound (NOTE_E); + else if (g_str_equal (text, _("A"))) + play_sound (NOTE_A); + else if (g_str_equal (text, _("G"))) + play_sound (NOTE_G); + else if (g_str_equal (text, _("D"))) + play_sound (NOTE_D); + else if (g_str_equal (text, ("B"))) + play_sound (NOTE_B); + else if (g_str_equal (text, _("e"))) + play_sound (NOTE_e); +} + + +int +main (int argc, char *argv[]) +{ + GtkWidget *window; + + +#ifdef ENABLE_NLS + bindtextdomain (GETTEXT_PACKAGE, PACKAGE_LOCALE_DIR); + bind_textdomain_codeset (GETTEXT_PACKAGE, "UTF-8"); + textdomain (GETTEXT_PACKAGE); +#endif + + gst_init (&argc, &argv); + gtk_init (&argc, &argv); + + window = create_window (); + gtk_widget_show (window); + + gtk_main (); + return 0; +} diff --git a/pool/shard002/C/0062231_test_yk_utilities.c b/pool/shard002/C/0062231_test_yk_utilities.c new file mode 100644 index 0000000000000000000000000000000000000000..be14d781f6f2c8026ca1559cd33aad274bccfa41 --- /dev/null +++ b/pool/shard002/C/0062231_test_yk_utilities.c @@ -0,0 +1,112 @@ +/* -*- mode:C; c-file-style: "bsd" -*- */ +/* + * Copyright (c) 2012-2015 Yubico AB + * 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. + * + * 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 +#include +#include +#include +#include + +#include +#include +#include + +struct versions { + int major; + int minor; + int build; + bool support; +} supported[] = { + {0,8,0,false}, + {0,9,9,true}, + {1,2,9,true}, + {1,3,1,true}, + {1,4,5,false}, + {2,0,2,true}, + {2,1,1,true}, + {2,2,3,true}, + {2,3,0,true}, + {2,4,5,true}, + {2,5,2,true}, + {2,6,0,false}, + {3,0,1,true}, + {3,2,8,true}, + {3,3,0,true}, + {3,4,3,true}, + {3,5,1,false}, + {4,0,1,true}, + {4,1,2,true}, + {4,1,10,true}, + {4,2,1,true}, + {4,3,7,true}, + {4,4,5,false}, + {5,0,0,false}, +}; + +static YK_STATUS * _test_init_st(int major, int minor, int build) +{ + YK_STATUS *st = ykds_alloc(); + struct status_st *t; + + t = (struct status_st *) st; + + /* connected key details */ + t->versionMajor = major; + t->versionMinor = minor; + t->versionBuild = build; + + return st; +} + +static void _test_yk_firmware(void) +{ + size_t i; + for(i = 0; i < sizeof(supported) / sizeof(struct versions); i++) { + int rc; + YK_STATUS *st = _test_init_st(supported[i].major, supported[i].minor, supported[i].build); + printf("testing: %d.%d.%d\n", supported[i].major, supported[i].minor, supported[i].build); + rc = yk_check_firmware_version2(st); + if(supported[i].support == true) { + assert(rc == 1); + } else { + assert(yk_errno == YK_EFIRMWARE); + assert(rc == 0); + } + ykds_free(st); + } +} + +int main(void) +{ + _test_yk_firmware(); + + return 0; +} + diff --git a/pool/shard002/C/0062240_calc.c b/pool/shard002/C/0062240_calc.c new file mode 100644 index 0000000000000000000000000000000000000000..df7221ad21310b0b46623fce3f5a8fc3dcfc9bde --- /dev/null +++ b/pool/shard002/C/0062240_calc.c @@ -0,0 +1,42 @@ +/* +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 3 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, see . +*/ +///////////////////////////////////////////////////////////////////////////// +// Nome: calc.c +// Propósito: Rotinas para facilitar cálculo de m e u +// Author: Kenneth Camargo +// Modified by: +// Criado: 2009-02-12 +// Copyright: (c) Kenneth Camargo +// Licença: GPL +///////////////////////////////////////////////////////////////////////////// + +#include +#include "calc.h" + +#define calclog(n) ((double)(log((double)n)/log((double)2.0))) + +double +ppos(double m, double u) +{ + double r = m / u; + return calclog(r); +} + +double +npos(double m, double u) +{ + double r = (1 - m) / (1 - u); + return calclog(r); +} + diff --git a/pool/shard002/C/0062244_render.c b/pool/shard002/C/0062244_render.c new file mode 100644 index 0000000000000000000000000000000000000000..c87146b76a962ccfe63a3f71862cc72121782fe1 --- /dev/null +++ b/pool/shard002/C/0062244_render.c @@ -0,0 +1,162 @@ +/*****************************************************\ + RENDER.C + By: Jesse McClure (c) 2015 + See slider.c or COPYING for license information +\*****************************************************/ + +#include "slider.h" + +typedef struct PDF { + PopplerDocument *doc; + int npage; +} PDF; + +static PDF *_pdf = NULL; +static Window _fade_win = None; +static int _n = 0, _fade_steps; + +int render_set_fader(Window win, int steps) { + _fade_win = win; + _fade_steps = steps; + return 0; +} + +PopplerDocument *render_get_pdf_ptr() { + return _pdf[0].doc; +} + +int render_page(int pg, Window win, bool fixed) { + render_pdf_page(0, pg, win, fixed); + //notes_draw(pg); + return 0; +} + +int render_pdf_page(int pdf, int pg, Window win, bool fixed) { + if (pg >= _pdf[pdf].npage) return 1; + cairo_t *ctx; + cairo_surface_t *s, *img; + double pdfw, pdfh, scx, scy; + int ig; + unsigned int uig, ww, wh; + /* get page size and scale to window */ + PopplerPage *page = poppler_document_get_page(_pdf[pdf].doc, pg); + poppler_page_get_size(page, &pdfw, &pdfh); + XGetGeometry(dpy, win, (Window *) &ig, &ig, &ig, &ww, &wh, &uig, &uig); + scx = ww / pdfw; scy = wh / pdfh; + //if (pdf == 0) { _ww = ww; _wh = wh; } + if (fixed) { /* adjust window size for fixed aspect ratio */ + scx = (scx < scy ? (scy=scx) : scy); + ww = scx * pdfw + 0.5; wh = scy * pdfh + 0.5; + XResizeWindow(dpy, win, ww, wh); + } + /* create background pixmap and render page to it */ + Pixmap pix = XCreatePixmap(dpy, win, ww, wh, DefaultDepth(dpy,scr)); + s = cairo_xlib_surface_create(dpy, pix, DefaultVisual(dpy,scr), ww, wh); + ctx = cairo_create(s); + cairo_surface_destroy(s); + cairo_scale(ctx, scx, scy); + cairo_set_source_rgb(ctx, 1, 1, 1); + cairo_paint(ctx); + poppler_page_render(page, ctx); + cairo_destroy(ctx); + /* if this is the fader window, fade in */ + if (win == _fade_win) { + /* hide cursor for fade transitions */ +#ifdef module_cursor + bool pre = cursor_visible(query); + cursor_visible(false); +#endif + /* get image, set up context, and render page */ + img = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, ww, wh); + ctx = cairo_create(img); + cairo_scale(ctx, scx, scy); + cairo_set_source_rgb(ctx, 1, 1, 1); + cairo_paint(ctx); + poppler_page_render(page, ctx); + cairo_destroy(ctx); + /* get window surface, reset context to draw img to window */ + s = cairo_xlib_surface_create(dpy, win, DefaultVisual(dpy,scr), ww, wh); + ctx = cairo_create(s); + cairo_surface_destroy(s); + cairo_set_source_surface(ctx, img, 0, 0); // memory leak?! + /* fade in */ + for (ig = _fade_steps; ig; --ig) { + cairo_paint_with_alpha(ctx, 1 / (float) ig); // memory leak?! + //XFlush(dpy); + usleep(200); + } + /* clean up */ + cairo_destroy(ctx); + cairo_surface_destroy(img); +#ifdef module_cursor + cursor_visible(pre); +#endif + } + g_object_unref(page); + /* set the pixmap to be the window background */ + XSetWindowBackgroundPixmap(dpy, win, pix); + XFreePixmap(dpy, pix); + XClearWindow(dpy, win); +#ifdef module_cursor + if (pdf == 0) cursor_draw(-1, -1); +#endif + return 0; +} + +int render_init(char *fname) { + char *path = realpath(fname, NULL); + if (!path) return 1; + char *uri = malloc(strlen(path) + 8); + sprintf(uri, "file://%s", path); + free(path); +_pdf = realloc(_pdf, (_n + 1) * sizeof(PDF)); + _pdf[_n].doc = poppler_document_new_from_file(uri, NULL, NULL); + _pdf[_n].npage = poppler_document_get_n_pages(_pdf[_n].doc); +++_n; + free(uri); + return 0; +} + +int render_free() { + if (_pdf) free(_pdf); + return 0; +} + +Window *render_create_sorter(Window win) { + int i; + PopplerPage *page; + double pdfw, pdfh, scale; + cairo_surface_t *pix_s; + cairo_t *pix_c; + + XSetWindowAttributes wa; + wa.backing_store = Always; + wa.event_mask = ButtonPress | ExposureMask | PointerMotionMask; + Window *wins = malloc((_pdf[0].npage + 1) * sizeof(Window)); + Pixmap pix; + int ww, wh; + for (i = 0; i < _pdf[0].npage; ++i) { + page = poppler_document_get_page(_pdf[0].doc, i); + poppler_page_get_size(page, &pdfw, &pdfh); + scale = get_d(presH) / (6 * pdfh); + ww = scale * pdfw; wh = scale * pdfh; + wins[i] = XCreateWindow(dpy, win, 0, 0, ww, wh, 1, DefaultDepth(dpy,scr), + InputOutput, DefaultVisual(dpy,scr), CWBackingStore | CWEventMask, &wa); + XDefineCursor(dpy, wins[i], XCreateFontCursor(dpy, 68)); + pix = XCreatePixmap(dpy, wins[i], ww, wh, DefaultDepth(dpy,scr)); + pix_s = cairo_xlib_surface_create(dpy, pix, DefaultVisual(dpy,scr), ww, wh); + pix_c = cairo_create(pix_s); + cairo_surface_destroy(pix_s); + cairo_set_source_rgb(pix_c, 1, 1, 1); + cairo_paint(pix_c); + cairo_scale(pix_c, scale, scale); + poppler_page_render(page, pix_c); + cairo_destroy(pix_c); + XSetWindowBackgroundPixmap(dpy, wins[i], pix); + XFreePixmap(dpy, pix); + g_object_unref(page); + } + wins[_pdf[0].npage] = None; + return wins; +} + diff --git a/pool/shard002/C/0062252_choom.c b/pool/shard002/C/0062252_choom.c new file mode 100644 index 0000000000000000000000000000000000000000..6895aef4332af2aa488c4e8ea69620d41e72a9c6 --- /dev/null +++ b/pool/shard002/C/0062252_choom.c @@ -0,0 +1,159 @@ +/* + * choom - Change OOM score setting + * + * Copyright (C) 2018 Karel Zak + * + * 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 would 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 "nls.h" +#include "c.h" +#include "path.h" +#include "strutils.h" +#include "closestream.h" + +static void __attribute__((__noreturn__)) usage(void) +{ + FILE *out = stdout; + fputs(USAGE_HEADER, out); + fprintf(out, + _(" %1$s [options] -p pid\n" + " %1$s [options] -n number -p pid\n" + " %1$s [options] -n number command [args...]]\n"), + program_invocation_short_name); + + fputs(USAGE_SEPARATOR, out); + fputs(_("Display and adjust OOM-killer score.\n"), out); + + fputs(USAGE_OPTIONS, out); + fputs(_(" -n, --adjust specify the adjust score value\n"), out); + fputs(_(" -p, --pid process ID\n"), out); + fputs(USAGE_SEPARATOR, out); + printf(USAGE_HELP_OPTIONS(24)); + printf(USAGE_MAN_TAIL("choom(1)")); + exit(EXIT_SUCCESS); +} + +static int get_score(struct path_cxt *pc) +{ + int ret; + + if (ul_path_read_s32(pc, &ret, "oom_score") != 0) + err(EXIT_FAILURE, _("failed to read OOM score value")); + + return ret; +} + +static int get_score_adj(struct path_cxt *pc) +{ + int ret; + + if (ul_path_read_s32(pc, &ret, "oom_score_adj") != 0) + err(EXIT_FAILURE, _("failed to read OOM score adjust value")); + + return ret; +} + +static int set_score_adj(struct path_cxt *pc, int adj) +{ + return ul_path_write_u64(pc, adj, "oom_score_adj"); +} + +int main(int argc, char **argv) +{ + pid_t pid = 0; + int c, adj = 0, has_adj = 0; + struct path_cxt *pc = NULL; + + static const struct option longopts[] = { + { "adjust", required_argument, NULL, 'n' }, + { "pid", required_argument, NULL, 'p' }, + { "help", no_argument, NULL, 'h' }, + { "version", no_argument, NULL, 'V' }, + { NULL, 0, NULL, 0 } + }; + + setlocale(LC_ALL, ""); + bindtextdomain(PACKAGE, LOCALEDIR); + textdomain(PACKAGE); + atexit(close_stdout); + + while ((c = getopt_long(argc, argv, "hn:p:V", longopts, NULL)) != -1) { + switch (c) { + case 'p': + pid = strtos32_or_err(optarg, _("invalid PID argument")); + break; + case 'n': + adj = strtos32_or_err(optarg, _("invalid adjust argument")); + has_adj = 1; + break; + case 'V': + printf(UTIL_LINUX_VERSION); + return EXIT_SUCCESS; + case 'h': + usage(); + default: + errtryhelp(EXIT_FAILURE); + } + } + + if (optind < argc && pid) { + warnx(_("invalid argument: %s"), argv[optind]); + errtryhelp(EXIT_FAILURE); + } + if (!pid && argc - optind < 1) { + warnx(_("no PID or COMMAND specified")); + errtryhelp(EXIT_FAILURE); + } + if (optind < argc && !has_adj) { + warnx(_("no OOM score adjust value specified")); + errtryhelp(EXIT_FAILURE); + } + + pc = ul_new_path("/proc/%d", (int) (pid ? pid : getpid())); + + /* Show */ + if (!has_adj) { + printf(_("pid %d's current OOM score: %d\n"), pid, get_score(pc)); + printf(_("pid %d's current OOM score adjust value: %d\n"), pid, get_score_adj(pc)); + + /* Change */ + } else if (pid) { + int old = get_score_adj(pc); + + if (set_score_adj(pc, adj)) + err(EXIT_FAILURE, _("failed to set score adjust value")); + + printf(_("pid %d's OOM score adjust value changed from %d to %d\n"), pid, old, adj); + + /* Start new process */ + } else { + if (set_score_adj(pc, adj)) + err(EXIT_FAILURE, _("failed to set score adjust value")); + ul_unref_path(pc); + argv += optind; + execvp(argv[0], argv); + errexec(argv[0]); + } + + ul_unref_path(pc); + return EXIT_SUCCESS; +} diff --git a/pool/shard002/C/0062253_clk-periph-gate.c b/pool/shard002/C/0062253_clk-periph-gate.c new file mode 100644 index 0000000000000000000000000000000000000000..762f73d9ffe177126c201c0a613d219c911efcaa --- /dev/null +++ b/pool/shard002/C/0062253_clk-periph-gate.c @@ -0,0 +1,192 @@ +/* + * Copyright (c) 2012, NVIDIA CORPORATION. All rights reserved. + * + * This program is free software; you can redistribute it and/or modify it + * under the terms and conditions of the GNU General Public License, + * version 2, as published by the Free Software Foundation. + * + * This program is distributed in the hope 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 "clk.h" + +static DEFINE_SPINLOCK(periph_ref_lock); + +/* Macros to assist peripheral gate clock */ +#define read_enb(gate) \ + readl_relaxed(gate->clk_base + (gate->regs->enb_reg)) +#define write_enb_set(val, gate) \ + writel_relaxed(val, gate->clk_base + (gate->regs->enb_set_reg)) +#define write_enb_clr(val, gate) \ + writel_relaxed(val, gate->clk_base + (gate->regs->enb_clr_reg)) + +#define read_rst(gate) \ + readl_relaxed(gate->clk_base + (gate->regs->rst_reg)) +#define write_rst_clr(val, gate) \ + writel_relaxed(val, gate->clk_base + (gate->regs->rst_clr_reg)) + +#define periph_clk_to_bit(gate) (1 << (gate->clk_num % 32)) + +#define LVL2_CLK_GATE_OVRE 0x554 + +/* Peripheral gate clock ops */ +static int clk_periph_is_enabled(struct clk_hw *hw) +{ + struct tegra_clk_periph_gate *gate = to_clk_periph_gate(hw); + int state = 1; + + if (!(read_enb(gate) & periph_clk_to_bit(gate))) + { + state = 0; + } + + if (!(gate->flags & TEGRA_PERIPH_NO_RESET)) + if (read_rst(gate) & periph_clk_to_bit(gate)) + { + state = 0; + } + + return state; +} + +static int clk_periph_enable(struct clk_hw *hw) +{ + struct tegra_clk_periph_gate *gate = to_clk_periph_gate(hw); + unsigned long flags = 0; + + spin_lock_irqsave(&periph_ref_lock, flags); + + gate->enable_refcnt[gate->clk_num]++; + + if (gate->enable_refcnt[gate->clk_num] > 1) + { + spin_unlock_irqrestore(&periph_ref_lock, flags); + return 0; + } + + write_enb_set(periph_clk_to_bit(gate), gate); + udelay(2); + + if (!(gate->flags & TEGRA_PERIPH_NO_RESET) && + !(gate->flags & TEGRA_PERIPH_MANUAL_RESET)) + { + if (read_rst(gate) & periph_clk_to_bit(gate)) + { + udelay(5); /* reset propogation delay */ + write_rst_clr(periph_clk_to_bit(gate), gate); + } + } + + if (gate->flags & TEGRA_PERIPH_WAR_1005168) + { + writel_relaxed(0, gate->clk_base + LVL2_CLK_GATE_OVRE); + writel_relaxed(BIT(22), gate->clk_base + LVL2_CLK_GATE_OVRE); + udelay(1); + writel_relaxed(0, gate->clk_base + LVL2_CLK_GATE_OVRE); + } + + spin_unlock_irqrestore(&periph_ref_lock, flags); + + return 0; +} + +static void clk_periph_disable(struct clk_hw *hw) +{ + struct tegra_clk_periph_gate *gate = to_clk_periph_gate(hw); + unsigned long flags = 0; + + spin_lock_irqsave(&periph_ref_lock, flags); + + gate->enable_refcnt[gate->clk_num]--; + + if (gate->enable_refcnt[gate->clk_num] > 0) + { + spin_unlock_irqrestore(&periph_ref_lock, flags); + return; + } + + /* + * If peripheral is in the APB bus then read the APB bus to + * flush the write operation in apb bus. This will avoid the + * peripheral access after disabling clock + */ + if (gate->flags & TEGRA_PERIPH_ON_APB) + { + tegra_read_chipid(); + } + + write_enb_clr(periph_clk_to_bit(gate), gate); + + spin_unlock_irqrestore(&periph_ref_lock, flags); +} + +const struct clk_ops tegra_clk_periph_gate_ops = +{ + .is_enabled = clk_periph_is_enabled, + .enable = clk_periph_enable, + .disable = clk_periph_disable, +}; + +struct clk *tegra_clk_register_periph_gate(const char *name, + const char *parent_name, u8 gate_flags, void __iomem *clk_base, + unsigned long flags, int clk_num, int *enable_refcnt) +{ + struct tegra_clk_periph_gate *gate; + struct clk *clk; + struct clk_init_data init; + const struct tegra_clk_periph_regs *pregs; + + pregs = get_reg_bank(clk_num); + + if (!pregs) + { + return ERR_PTR(-EINVAL); + } + + gate = kzalloc(sizeof(*gate), GFP_KERNEL); + + if (!gate) + { + pr_err("%s: could not allocate periph gate clk\n", __func__); + return ERR_PTR(-ENOMEM); + } + + init.name = name; + init.flags = flags; + init.parent_names = parent_name ? &parent_name : NULL; + init.num_parents = parent_name ? 1 : 0; + init.ops = &tegra_clk_periph_gate_ops; + + gate->magic = TEGRA_CLK_PERIPH_GATE_MAGIC; + gate->clk_base = clk_base; + gate->clk_num = clk_num; + gate->flags = gate_flags; + gate->enable_refcnt = enable_refcnt; + gate->regs = pregs; + + /* Data in .init is copied by clk_register(), so stack variable OK */ + gate->hw.init = &init; + + clk = clk_register(NULL, &gate->hw); + + if (IS_ERR(clk)) + { + kfree(gate); + } + + return clk; +} diff --git a/pool/shard002/C/0062259_dlassq.c b/pool/shard002/C/0062259_dlassq.c new file mode 100644 index 0000000000000000000000000000000000000000..9fadcebd01bf14c8047cb27188d8756a25560c4c --- /dev/null +++ b/pool/shard002/C/0062259_dlassq.c @@ -0,0 +1,116 @@ +/* dlassq.f -- translated by f2c (version 19941215). + You must link the resulting object file with the libraries: + -lf2c -lm (in that order) +*/ + +#include "f2c.h" + +/* Subroutine */ int dlassq_(n, x, incx, scale, sumsq) +integer *n; +doublereal *x; +integer *incx; +doublereal *scale, *sumsq; +{ + /* System generated locals */ + integer i__1, i__2; + doublereal d__1; + + /* Local variables */ + static doublereal absxi; + static integer ix; + + +/* -- LAPACK auxiliary routine (version 1.1) -- */ +/* Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., */ +/* Courant Institute, Argonne National Lab, and Rice University */ +/* October 31, 1992 */ + +/* .. Scalar Arguments .. */ +/* .. */ +/* .. Array Arguments .. */ +/* .. */ + +/* Purpose */ +/* ======= */ + +/* DLASSQ returns the values scl and smsq such that */ + +/* ( scl**2 )*smsq = x( 1 )**2 +...+ x( n )**2 + ( scale**2 )*sumsq, +*/ + +/* where x( i ) = X( 1 + ( i - 1 )*INCX ). The value of sumsq is */ +/* assumed to be non-negative and scl returns the value */ + +/* scl = max( scale, abs( x( i ) ) ). */ + +/* scale and sumsq must be supplied in SCALE and SUMSQ and */ +/* scl and smsq are overwritten on SCALE and SUMSQ respectively. */ + +/* The routine makes only one pass through the vector x. */ + +/* Arguments */ +/* ========= */ + +/* N (input) INTEGER */ +/* The number of elements to be used from the vector X. */ + +/* X (input) DOUBLE PRECISION */ +/* The vector for which a scaled sum of squares is computed. */ +/* x( i ) = X( 1 + ( i - 1 )*INCX ), 1 <= i <= n. */ + +/* INCX (input) INTEGER */ +/* The increment between successive values of the vector X. */ +/* INCX > 0. */ + +/* SCALE (input/output) DOUBLE PRECISION */ +/* On entry, the value scale in the equation above. */ +/* On exit, SCALE is overwritten with scl , the scaling factor +*/ +/* for the sum of squares. */ + +/* SUMSQ (input/output) DOUBLE PRECISION */ +/* On entry, the value sumsq in the equation above. */ +/* On exit, SUMSQ is overwritten with smsq , the basic sum of */ +/* squares from which scl has been factored out. */ + +/* ===================================================================== +*/ + +/* .. Parameters .. */ +/* .. */ +/* .. Local Scalars .. */ +/* .. */ +/* .. Intrinsic Functions .. */ +/* .. */ +/* .. Executable Statements .. */ + + /* Parameter adjustments */ + --x; + + /* Function Body */ + if (*n > 0) { + i__1 = (*n - 1) * *incx + 1; + i__2 = *incx; + for (ix = 1; i__2 < 0 ? ix >= i__1 : ix <= i__1; ix += i__2) { + if (x[ix] != 0.) { + absxi = (d__1 = x[ix], abs(d__1)); + if (*scale < absxi) { +/* Computing 2nd power */ + d__1 = *scale / absxi; + *sumsq = *sumsq * (d__1 * d__1) + 1; + *scale = absxi; + } else { +/* Computing 2nd power */ + d__1 = absxi / *scale; + *sumsq += d__1 * d__1; + } + } +/* L10: */ + } + } + return 0; + +/* End of DLASSQ */ + +} /* dlassq_ */ + diff --git a/pool/shard002/C/0062267_hdmi_sii9022.c b/pool/shard002/C/0062267_hdmi_sii9022.c new file mode 100644 index 0000000000000000000000000000000000000000..40395ee3d234602db20535d71d18d7ce82ec163a --- /dev/null +++ b/pool/shard002/C/0062267_hdmi_sii9022.c @@ -0,0 +1,233 @@ + + +#include +#include +#include "msm_fb.h" + +#define DEVICE_NAME "sii9022" +#define SII9022_DEVICE_ID 0xB0 + +struct sii9022_i2c_addr_data{ + u8 addr; + u8 data; +}; + + +static u8 video_mode_data[] = { + 0x00, + 0xF9, 0x1C, 0x70, 0x17, 0x72, 0x06, 0xEE, 0x02, +}; + +static u8 avi_io_format[] = { + 0x09, + 0x00, 0x00, +}; + + +static struct sii9022_i2c_addr_data regset0[] = { + { 0x60, 0x04 }, + { 0x63, 0x00 }, + { 0x1E, 0x00 }, +}; + +static u8 video_infoframe[] = { + 0x0C, + 0xF0, 0x00, 0x68, 0x00, 0x04, 0x00, 0x19, 0x00, + 0xE9, 0x02, 0x04, 0x01, 0x04, 0x06, +}; + + +static struct sii9022_i2c_addr_data regset1[] = { + { 0x26, 0x90 }, + { 0x20, 0x90 }, + { 0x1F, 0x80 }, + { 0x26, 0x80 }, + { 0x24, 0x02 }, + { 0x25, 0x0B }, + { 0xBC, 0x02 }, + { 0xBD, 0x24 }, + { 0xBE, 0x02 }, +}; + + +static u8 misc_infoframe[] = { + 0xBF, + 0xC2, 0x84, 0x01, 0x0A, 0x6F, 0x02, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, +}; + + +static struct sii9022_i2c_addr_data regset2[] = { + { 0x1A, 0x01 }, + { 0x3D, 0x00 }, +}; + +static int send_i2c_data(struct i2c_client *client, + struct sii9022_i2c_addr_data *regset, + int size) +{ + int i; + int rc = 0; + + for (i = 0; i < size; i++) { + rc = i2c_smbus_write_byte_data( + client, + regset[i].addr, regset[i].data); + if (rc) + break; + } + return rc; +} + +static int hdmi_sii_enable(struct i2c_client *client) +{ + int rc; + int retries = 10; + int count; + + rc = i2c_smbus_write_byte_data(client, 0xC7, 0x00); + if (rc) + goto enable_exit; + + do { + msleep(1); + rc = i2c_smbus_read_byte_data(client, 0x1B); + } while ((rc != SII9022_DEVICE_ID) && retries--); + + if (rc != SII9022_DEVICE_ID) + return -ENODEV; + + rc = i2c_smbus_write_byte_data(client, 0x1A, 0x11); + if (rc) + goto enable_exit; + + count = ARRAY_SIZE(video_mode_data); + rc = i2c_master_send(client, video_mode_data, count); + if (rc != count) { + rc = -EIO; + goto enable_exit; + } + + rc = i2c_smbus_write_byte_data(client, 0x08, 0x20); + if (rc) + goto enable_exit; + count = ARRAY_SIZE(avi_io_format); + rc = i2c_master_send(client, avi_io_format, count); + if (rc != count) { + rc = -EIO; + goto enable_exit; + } + + rc = send_i2c_data(client, regset0, ARRAY_SIZE(regset0)); + if (rc) + goto enable_exit; + + count = ARRAY_SIZE(video_infoframe); + rc = i2c_master_send(client, video_infoframe, count); + if (rc != count) { + rc = -EIO; + goto enable_exit; + } + + rc = send_i2c_data(client, regset1, ARRAY_SIZE(regset1)); + if (rc) + goto enable_exit; + + count = ARRAY_SIZE(misc_infoframe); + rc = i2c_master_send(client, misc_infoframe, count); + if (rc != count) { + rc = -EIO; + goto enable_exit; + } + + rc = send_i2c_data(client, regset2, ARRAY_SIZE(regset2)); + if (rc) + goto enable_exit; + + return 0; +enable_exit: + printk(KERN_ERR "%s: exited rc=%d\n", __func__, rc); + return rc; +} + +static const struct i2c_device_id hmdi_sii_id[] = { + { DEVICE_NAME, 0 }, + { } +}; + +static int hdmi_sii_probe(struct i2c_client *client, + const struct i2c_device_id *id) +{ + int rc; + + if (!i2c_check_functionality(client->adapter, + I2C_FUNC_SMBUS_BYTE | I2C_FUNC_I2C)) + return -ENODEV; + rc = hdmi_sii_enable(client); + return rc; +} + + +static struct i2c_driver hdmi_sii_i2c_driver = { + .driver = { + .name = DEVICE_NAME, + .owner = THIS_MODULE, + }, + .probe = hdmi_sii_probe, + .remove = __exit_p(hdmi_sii_remove), + .id_table = hmdi_sii_id, +}; + +static int __init hdmi_sii_init(void) +{ + int ret; + struct msm_panel_info pinfo; + + if (msm_fb_detect_client("hdmi_sii9022")) + return 0; + + pinfo.xres = 1280; + pinfo.yres = 720; + pinfo.type = HDMI_PANEL; + pinfo.pdest = DISPLAY_1; + pinfo.wait_cycle = 0; + pinfo.bpp = 18; + pinfo.fb_num = 2; + pinfo.clk_rate = 74250000; + + pinfo.lcdc.h_back_porch = 124; + pinfo.lcdc.h_front_porch = 110; + pinfo.lcdc.h_pulse_width = 136; + pinfo.lcdc.v_back_porch = 19; + pinfo.lcdc.v_front_porch = 5; + pinfo.lcdc.v_pulse_width = 6; + pinfo.lcdc.border_clr = 0; + pinfo.lcdc.underflow_clr = 0xff; + pinfo.lcdc.hsync_skew = 0; + + ret = lcdc_device_register(&pinfo); + if (ret) { + printk(KERN_ERR "%s: failed to register device\n", __func__); + goto init_exit; + } + + ret = i2c_add_driver(&hdmi_sii_i2c_driver); + if (ret) + printk(KERN_ERR "%s: failed to add i2c driver\n", __func__); + +init_exit: + return ret; +} + +static void __exit hdmi_sii_exit(void) +{ + i2c_del_driver(&hdmi_sii_i2c_driver); +} + +module_init(hdmi_sii_init); +module_exit(hdmi_sii_exit); +MODULE_LICENSE("GPL v2"); +MODULE_VERSION("0.1"); +MODULE_AUTHOR("Qualcomm Innovation Center, Inc."); +MODULE_DESCRIPTION("SiI9022 HDMI driver"); +MODULE_ALIAS("platform:hdmi-sii9022"); diff --git a/pool/shard002/C/0062268_disable.c b/pool/shard002/C/0062268_disable.c new file mode 100644 index 0000000000000000000000000000000000000000..65517c49d4918196f972d698d88d341966255af0 --- /dev/null +++ b/pool/shard002/C/0062268_disable.c @@ -0,0 +1,13 @@ +#include "sway/commands.h" +#include "sway/config.h" + +struct cmd_results *output_cmd_disable(int argc, char **argv) { + if (!config->handler_context.output_config) { + return cmd_results_new(CMD_FAILURE, "output", "Missing output config"); + } + config->handler_context.output_config->enabled = 0; + + config->handler_context.leftovers.argc = argc; + config->handler_context.leftovers.argv = argv; + return NULL; +} diff --git a/pool/shard002/C/0062271_packet-klm.c b/pool/shard002/C/0062271_packet-klm.c new file mode 100644 index 0000000000000000000000000000000000000000..9fd64ba2aebe04c3be3838a0b65e60a888069e6e --- /dev/null +++ b/pool/shard002/C/0062271_packet-klm.c @@ -0,0 +1,267 @@ +/* packet-klm.c 2001 Ronnie Sahlberg + * Routines for klm dissection + * + * $Id: packet-klm.c 45017 2012-09-20 02:03:38Z morriss $ + * + * Wireshark - Network traffic analyzer + * By Gerald Combs + * Copyright 1998 Gerald Combs + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ + +#include "config.h" + +#if defined(LEAN_ONCRPC) +# error LEAN_ONCRPC: Should not be build +#endif + +#include "packet-rpc.h" +#include "packet-nfs.h" +#include "packet-klm.h" + +static int proto_klm = -1; +static int hf_klm_procedure_v1 = -1; +static int hf_klm_exclusive = -1; +static int hf_klm_lock = -1; +static int hf_klm_servername = -1; +static int hf_klm_pid = -1; +static int hf_klm_offset = -1; +static int hf_klm_len = -1; +static int hf_klm_stats = -1; +static int hf_klm_holder = -1; +static int hf_klm_block = -1; + +static gint ett_klm = -1; +static gint ett_klm_lock = -1; +static gint ett_klm_holder = -1; + +static const value_string names_klm_stats[] = +{ +#define KLM_GRANTED 0 + { KLM_GRANTED, "KLM_GRANTED" }, +#define KLM_DENIED 1 + { KLM_DENIED, "KLM_DENIED" }, +#define KLM_DENIED_NOLOCKS 2 + { KLM_DENIED_NOLOCKS, "KLM_DENIED_NOLOCKS" }, +#define KLM_WORKING 3 + { KLM_WORKING, "KLM_WORKING" }, + { 0, NULL } +}; + +static int +dissect_holder(tvbuff_t *tvb, proto_tree *tree, int offset) +{ + proto_item* lock_item = NULL; + proto_tree* lock_tree = NULL; + + lock_item = proto_tree_add_item(tree, hf_klm_holder, tvb, + offset, -1, ENC_NA); + + lock_tree = proto_item_add_subtree(lock_item, ett_klm_holder); + + offset = dissect_rpc_bool( tvb, lock_tree, + hf_klm_exclusive, offset); + + offset = dissect_rpc_uint32(tvb, lock_tree, + hf_klm_pid, offset); + + offset = dissect_rpc_uint32(tvb, lock_tree, + hf_klm_offset, offset); + + offset = dissect_rpc_uint32(tvb, lock_tree, + hf_klm_len, offset); + + return offset; +} + +static int +dissect_lock(tvbuff_t *tvb, packet_info* pinfo, proto_tree *tree, int offset) +{ + proto_item* lock_item = NULL; + proto_tree* lock_tree = NULL; + + lock_item = proto_tree_add_item(tree, hf_klm_lock, tvb, + offset, -1, ENC_NA); + + lock_tree = proto_item_add_subtree(lock_item, ett_klm_lock); + + offset = dissect_rpc_string(tvb, lock_tree, + hf_klm_servername, offset, NULL); + + offset = dissect_nfs_fh3(tvb, offset, pinfo, lock_tree,"fh", NULL); + + offset = dissect_rpc_uint32(tvb, lock_tree, + hf_klm_pid, offset); + + offset = dissect_rpc_uint32(tvb, lock_tree, + hf_klm_offset, offset); + + offset = dissect_rpc_uint32(tvb, lock_tree, + hf_klm_len, offset); + + return offset; +} + +static int +dissect_klm_unlock_call(tvbuff_t *tvb, int offset, packet_info *pinfo, proto_tree *tree) +{ + offset = dissect_lock(tvb, pinfo, tree, offset); + + return offset; +} + +static int +dissect_klm_stat_reply(tvbuff_t *tvb, int offset, packet_info *pinfo _U_, proto_tree *tree) +{ + + offset = dissect_rpc_uint32(tvb, tree, + hf_klm_stats, offset); + + return offset; +} + +static int +dissect_klm_lock_call(tvbuff_t *tvb, int offset, packet_info *pinfo, proto_tree *tree) +{ + offset = dissect_rpc_bool( tvb, tree, + hf_klm_block, offset); + + offset = dissect_rpc_bool( tvb, tree, + hf_klm_exclusive, offset); + + offset = dissect_lock(tvb, pinfo, tree, offset); + + return offset; +} + +static int +dissect_klm_test_reply(tvbuff_t *tvb, int offset, packet_info *pinfo _U_, proto_tree *tree) +{ + gint32 stats; + + stats = tvb_get_ntohl(tvb, offset); + + offset = dissect_rpc_uint32(tvb, tree, + hf_klm_stats, offset); + + if (stats == KLM_DENIED) { + offset = dissect_holder(tvb, tree, offset); + } + + return offset; +} + +static int +dissect_klm_test_call(tvbuff_t *tvb, int offset, packet_info *pinfo, proto_tree *tree) +{ + offset = dissect_rpc_bool( tvb, tree, + hf_klm_exclusive, offset); + + offset = dissect_lock(tvb, pinfo, tree, offset); + + return offset; +} + + +/* proc number, "proc name", dissect_request, dissect_reply */ +/* NULL as function pointer means: type of arguments is "void". */ +static const vsff klm1_proc[] = { + { KLMPROC_TEST, "TEST", + dissect_klm_test_call, dissect_klm_test_reply }, + { KLMPROC_LOCK, "LOCK", + dissect_klm_lock_call, dissect_klm_stat_reply }, + { KLMPROC_CANCEL, "CANCEL", + dissect_klm_lock_call, dissect_klm_stat_reply }, + { KLMPROC_UNLOCK, "UNLOCK", + dissect_klm_unlock_call, dissect_klm_stat_reply }, + { 0, NULL, NULL, NULL } +}; +static const value_string klm1_proc_vals[] = { + { KLMPROC_TEST, "TEST" }, + { KLMPROC_LOCK, "LOCK" }, + { KLMPROC_CANCEL, "CANCEL" }, + { KLMPROC_UNLOCK, "UNLOCK" }, + { 0, NULL} +}; + +void +proto_register_klm(void) +{ + static struct true_false_string tfs_exclusive = { "Exclusive", "Not exclusive" }; + static struct true_false_string tfs_block = { "Block", "Do not block" }; + + static hf_register_info hf[] = { + { &hf_klm_procedure_v1, { + "V1 Procedure", "klm.procedure_v1", FT_UINT32, BASE_DEC, + VALS(klm1_proc_vals), 0, NULL, HFILL }}, + { &hf_klm_exclusive, { + "exclusive", "klm.exclusive", FT_BOOLEAN, BASE_NONE, + TFS(&tfs_exclusive), 0x0, "Exclusive lock", HFILL }}, + + { &hf_klm_lock, { + "lock", "klm.lock", FT_NONE, BASE_NONE, + NULL, 0, "KLM lock structure", HFILL }}, + + { &hf_klm_servername, { + "server name", "klm.servername", FT_STRING, BASE_NONE, + NULL, 0, NULL, HFILL }}, + + { &hf_klm_pid, { + "pid", "klm.pid", FT_UINT32, BASE_DEC, + NULL, 0, "ProcessID", HFILL }}, + + { &hf_klm_offset, { + "offset", "klm.offset", FT_UINT32, BASE_DEC, + NULL, 0, "File offset", HFILL }}, + + { &hf_klm_len, { + "length", "klm.len", FT_UINT32, BASE_DEC, + NULL, 0, "Length of lock region", HFILL }}, + + { &hf_klm_stats, { + "stats", "klm.stats", FT_UINT32, BASE_DEC, + VALS(names_klm_stats), 0, NULL, HFILL }}, + + { &hf_klm_holder, { + "holder", "klm.holder", FT_NONE, BASE_NONE, + NULL, 0, "KLM lock holder", HFILL }}, + + { &hf_klm_block, { + "block", "klm.block", FT_BOOLEAN, BASE_NONE, + TFS(&tfs_block), 0x0, NULL, HFILL }}, + + }; + + static gint *ett[] = { + &ett_klm, + &ett_klm_lock, + &ett_klm_holder, + }; + + proto_klm = proto_register_protocol("Kernel Lock Manager", + "KLM", "klm"); + proto_register_field_array(proto_klm, hf, array_length(hf)); + proto_register_subtree_array(ett, array_length(ett)); +} + +void +proto_reg_handoff_klm(void) +{ + /* Register the protocol as RPC */ + rpc_init_prog(proto_klm, KLM_PROGRAM, ett_klm); + /* Register the procedure tables */ + rpc_init_proc_table(KLM_PROGRAM, 1, klm1_proc, hf_klm_procedure_v1); +} diff --git a/pool/shard002/C/0062281_kexec.c b/pool/shard002/C/0062281_kexec.c new file mode 100644 index 0000000000000000000000000000000000000000..53cbd53d8740537d86b7fe5ab13e19dfcdcecd75 --- /dev/null +++ b/pool/shard002/C/0062281_kexec.c @@ -0,0 +1,73 @@ +/* + * Copyright 2006 Michael Ellerman, IBM 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; either version + * 2 of the License, or (at your option) any later version. + */ + +#include +#include +#include +#include +#include +#include + +#include "pseries.h" +#include "xics.h" +#include "plpar_wrappers.h" + +static void pseries_kexec_cpu_down(int crash_shutdown, int secondary) +{ + /* Don't risk a hypervisor call if we're crashing */ + if (firmware_has_feature(FW_FEATURE_SPLPAR) && !crash_shutdown) { + unsigned long addr; + + addr = __pa(get_slb_shadow()); + if (unregister_slb_shadow(hard_smp_processor_id(), addr)) + printk("SLB shadow buffer deregistration of " + "cpu %u (hw_cpu_id %d) failed\n", + smp_processor_id(), + hard_smp_processor_id()); + + addr = __pa(get_lppaca()); + if (unregister_vpa(hard_smp_processor_id(), addr)) { + printk("VPA deregistration of cpu %u (hw_cpu_id %d) " + "failed\n", smp_processor_id(), + hard_smp_processor_id()); + } + } +} + +static void pseries_kexec_cpu_down_mpic(int crash_shutdown, int secondary) +{ + pseries_kexec_cpu_down(crash_shutdown, secondary); + mpic_teardown_this_cpu(secondary); +} + +void __init setup_kexec_cpu_down_mpic(void) +{ + ppc_md.kexec_cpu_down = pseries_kexec_cpu_down_mpic; +} + +static void pseries_kexec_cpu_down_xics(int crash_shutdown, int secondary) +{ + pseries_kexec_cpu_down(crash_shutdown, secondary); + xics_kexec_teardown_cpu(secondary); +} + +void __init setup_kexec_cpu_down_xics(void) +{ + ppc_md.kexec_cpu_down = pseries_kexec_cpu_down_xics; +} + +static int __init pseries_kexec_setup(void) +{ + ppc_md.machine_kexec = default_machine_kexec; + ppc_md.machine_kexec_prepare = default_machine_kexec_prepare; + ppc_md.machine_crash_shutdown = default_machine_crash_shutdown; + + return 0; +} +machine_device_initcall(pseries, pseries_kexec_setup); diff --git a/pool/shard002/C/0062284_share.c b/pool/shard002/C/0062284_share.c new file mode 100644 index 0000000000000000000000000000000000000000..13d591ec1b46400b52c0f67edcfd56bdc84e35df --- /dev/null +++ b/pool/shard002/C/0062284_share.c @@ -0,0 +1,156 @@ +/* + Unix SMB/CIFS implementation. + + Modular shares configuration system + + Copyright (C) Simo Sorce 2006 + + 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 "includes.h" +#include "param/share.h" +#include "param/param.h" + +const char *share_string_option(struct share_config *scfg, const char *opt_name, const char *defval) +{ + return scfg->ctx->ops->string_option(scfg, opt_name, defval); +} + +int share_int_option(struct share_config *scfg, const char *opt_name, int defval) +{ + return scfg->ctx->ops->int_option(scfg, opt_name, defval); +} + +bool share_bool_option(struct share_config *scfg, const char *opt_name, bool defval) +{ + return scfg->ctx->ops->bool_option(scfg, opt_name, defval); +} + +const char **share_string_list_option(TALLOC_CTX *mem_ctx, struct share_config *scfg, const char *opt_name) +{ + return scfg->ctx->ops->string_list_option(mem_ctx, scfg, opt_name); +} + +NTSTATUS share_list_all(TALLOC_CTX *mem_ctx, struct share_context *sctx, int *count, const char ***names) +{ + return sctx->ops->list_all(mem_ctx, sctx, count, names); +} + +NTSTATUS share_get_config(TALLOC_CTX *mem_ctx, struct share_context *sctx, const char *name, struct share_config **scfg) +{ + return sctx->ops->get_config(mem_ctx, sctx, name, scfg); +} + +NTSTATUS share_create(struct share_context *sctx, const char *name, struct share_info *info, int count) +{ + if (sctx->ops->create) { + return sctx->ops->create(sctx, name, info, count); + } + return NT_STATUS_NOT_IMPLEMENTED; +} + +NTSTATUS share_set(struct share_context *sctx, const char *name, struct share_info *info, int count) +{ + if (sctx->ops->set) { + return sctx->ops->set(sctx, name, info, count); + } + return NT_STATUS_NOT_IMPLEMENTED; +} + +NTSTATUS share_remove(struct share_context *sctx, const char *name) +{ + if (sctx->ops->remove) { + return sctx->ops->remove(sctx, name); + } + return NT_STATUS_NOT_IMPLEMENTED; +} + +/* List of currently available share backends */ +static struct share_ops **backends = NULL; + +static const struct share_ops *share_backend_by_name(const char *name) +{ + int i; + + for (i = 0; backends && backends[i]; i++) { + if (strcmp(backends[i]->name, name) == 0) { + return backends[i]; + } + } + + return NULL; +} + +/* + Register the share backend +*/ +NTSTATUS share_register(const struct share_ops *ops) +{ + int i; + + if (share_backend_by_name(ops->name) != NULL) { + DEBUG(0,("SHARE backend [%s] already registered\n", ops->name)); + return NT_STATUS_OBJECT_NAME_COLLISION; + } + + i = 0; + while (backends && backends[i]) { + i++; + } + + backends = realloc_p(backends, struct share_ops *, i + 2); + if (!backends) { + smb_panic("out of memory in share_register"); + } + + backends[i] = (struct share_ops *)smb_xmemdup(ops, sizeof(*ops)); + backends[i]->name = smb_xstrdup(ops->name); + + backends[i + 1] = NULL; + + DEBUG(3, ("SHARE backend [%s] registered.\n", ops->name)); + + return NT_STATUS_OK; +} + +NTSTATUS share_get_context_by_name(TALLOC_CTX *mem_ctx, const char *backend_name, + struct tevent_context *event_ctx, + struct loadparm_context *lp_ctx, + struct share_context **ctx) +{ + const struct share_ops *ops; + + ops = share_backend_by_name(backend_name); + if (!ops) { + DEBUG(0, ("share_init_connection: share backend [%s] not found!\n", backend_name)); + return NT_STATUS_INTERNAL_ERROR; + } + + return ops->init(mem_ctx, ops, event_ctx, lp_ctx, ctx); +} + +/* + initialise the SHARE subsystem +*/ +NTSTATUS share_init(void) +{ + extern NTSTATUS share_ldb_init(void); + extern NTSTATUS share_classic_init(void); + init_module_fn static_init[] = { STATIC_share_MODULES }; + + run_init_functions(static_init); + + return NT_STATUS_OK; +} diff --git a/pool/shard002/C/0062304_stacktrace.c b/pool/shard002/C/0062304_stacktrace.c new file mode 100644 index 0000000000000000000000000000000000000000..5d9746749f70a2b38d3ac3d32bd22219285e4293 --- /dev/null +++ b/pool/shard002/C/0062304_stacktrace.c @@ -0,0 +1,139 @@ +#include +#include +#include + +#include + +#if defined(CONFIG_FRAME_POINTER) && !defined(CONFIG_ARM_UNWIND) +/* + * Unwind the current stack frame and store the new register values in the + * structure passed as argument. Unwinding is equivalent to a function return, + * hence the new PC value rather than LR should be used for backtrace. + * + * With framepointer enabled, a simple function prologue looks like this: + * mov ip, sp + * stmdb sp!, {fp, ip, lr, pc} + * sub fp, ip, #4 + * + * A simple function epilogue looks like this: + * ldm sp, {fp, sp, pc} + * + * Note that with framepointer enabled, even the leaf functions have the same + * prologue and epilogue, therefore we can ignore the LR value in this case. + */ +int notrace unwind_frame(struct stackframe *frame) +{ + unsigned long high, low; + unsigned long fp = frame->fp; + + /* only go to a higher address on the stack */ + low = frame->sp; + high = ALIGN(low, THREAD_SIZE); + + /* check current frame pointer is within bounds */ + if (fp < (low + 12) || fp + 4 >= high) + return -EINVAL; + + /* restore the registers from the stack frame */ + frame->fp = *(unsigned long *)(fp - 12); + frame->sp = *(unsigned long *)(fp - 8); + frame->pc = *(unsigned long *)(fp - 4); + + return 0; +} +#endif + +void notrace walk_stackframe(struct stackframe *frame, + int (*fn)(struct stackframe *, void *), void *data) +{ + while (1) { + int ret; + + if (fn(frame, data)) + break; + ret = unwind_frame(frame); + if (ret < 0) + break; + } +} +EXPORT_SYMBOL(walk_stackframe); + +#ifdef CONFIG_STACKTRACE +struct stack_trace_data { + struct stack_trace *trace; + unsigned int no_sched_functions; + unsigned int skip; +}; + +static int save_trace(struct stackframe *frame, void *d) +{ + struct stack_trace_data *data = d; + struct stack_trace *trace = data->trace; + unsigned long addr = frame->pc; + + if (data->no_sched_functions && in_sched_functions(addr)) + return 0; + if (data->skip) { + data->skip--; + return 0; + } + + trace->entries[trace->nr_entries++] = addr; + + return trace->nr_entries >= trace->max_entries; +} + +void save_stack_trace_tsk(struct task_struct *tsk, struct stack_trace *trace) +{ + struct stack_trace_data data; + struct stackframe frame; + + data.trace = trace; + data.skip = trace->skip; + + if (tsk != current) { +#ifdef CONFIG_SMP + /* + * What guarantees do we have here that 'tsk' is not + * running on another CPU? For now, ignore it as we + * can't guarantee we won't explode. + */ + #ifdef CONFIG_MACH_MOT + if (cpu_online(1)) { + printk(KERN_INFO "save_stack_trace_tsk() called from unsafe SMP context\n"); + return; + } + #else + BUG(); + #endif + if (trace->nr_entries < trace->max_entries) + trace->entries[trace->nr_entries++] = ULONG_MAX; + return; +#else + data.no_sched_functions = 1; + frame.fp = thread_saved_fp(tsk); + frame.sp = thread_saved_sp(tsk); + frame.lr = 0; /* recovered from the stack */ + frame.pc = thread_saved_pc(tsk); +#endif + } else { + register unsigned long current_sp asm ("sp"); + + data.no_sched_functions = 0; + frame.fp = (unsigned long)__builtin_frame_address(0); + frame.sp = current_sp; + frame.lr = (unsigned long)__builtin_return_address(0); + frame.pc = (unsigned long)save_stack_trace_tsk; + } + + walk_stackframe(&frame, save_trace, &data); + if (trace->nr_entries < trace->max_entries) + trace->entries[trace->nr_entries++] = ULONG_MAX; +} + +void save_stack_trace(struct stack_trace *trace) +{ + save_stack_trace_tsk(current, trace); +} +EXPORT_SYMBOL_GPL(save_stack_trace); +#endif diff --git a/pool/shard002/C/0062316_user_sleepmode_task.c b/pool/shard002/C/0062316_user_sleepmode_task.c new file mode 100644 index 0000000000000000000000000000000000000000..09312351f7fbb29a91d0d07ad58f085c352b0323 --- /dev/null +++ b/pool/shard002/C/0062316_user_sleepmode_task.c @@ -0,0 +1,301 @@ +/** + **************************************************************************************** + * + * @file user_sleepmode_task.c + * + * @brief Sleep mode project source code. + * + * Copyright (C) 2016. Dialog Semiconductor Ltd, unpublished work. This computer + * program includes Confidential, Proprietary Information and is a Trade Secret of + * Dialog Semiconductor Ltd. All use, disclosure, and/or reproduction is prohibited + * unless authorized in writing. All Rights Reserved. + * + * and contributors. + * + **************************************************************************************** + */ + +/** + **************************************************************************************** + * @addtogroup APP + * @{ + **************************************************************************************** + */ + +/* + * INCLUDE FILES + **************************************************************************************** + */ + +#include "user_sleepmode_task.h" +#include "wkupct_quadec.h" +#include "gpio.h" +#include "pwm.h" +#include "adc.h" +#include "custs1_task.h" +#include "user_custs1_def.h" +#include "user_sleepmode.h" +#include "user_periph_setup.h" + +/* + * DEFINES + **************************************************************************************** + */ + +#define APP_PWM_ON (1000) +#define APP_PWM_HIGH (500) +#define APP_PWM_LOW (200) +#define APP_NOTES_NUM (26) + +/* + * GLOBAL VARIABLE DEFINITIONS + **************************************************************************************** + */ + +struct app_proj_env_tag app_sleep_env __attribute__((section("retention_mem_area0"), zero_init)); //@RETENTION MEMORY + +const uint16_t notes[APP_NOTES_NUM] = +{ + 1046, 987, 767, 932, 328, 880, 830, 609, 783, 991, 739, 989, 698, 456, 659, 255, 622, + 254, 587, 554, 365, 523, 251, 493, 466, 440 +}; + +/* + * LOCAL FUNCTIONS DECLARATION + **************************************************************************************** + */ + +/** + **************************************************************************************** + * @brief Timer callback function. Update PWM settings. + * @return void + **************************************************************************************** + */ +static void user_app_pwm_callback_function(void); + +/** + **************************************************************************************** + * @brief Enable PWM timer. + * @return void + **************************************************************************************** + */ +static void user_app_enable_pwm(void); + +/** + **************************************************************************************** + * @brief Disable PWM timer. + * @return void + **************************************************************************************** + */ +static void user_app_disable_pwm(void); + +/** + **************************************************************************************** + * @brief Set button event configuration. + * @param[in] next_event Next event number + * @return void + **************************************************************************************** + */ +static void user_app_set_button_event(uint8_t next_event); + +/** + **************************************************************************************** + * @brief Disable button action. + * @return void + **************************************************************************************** + */ +static void user_app_disable_button(void); + +/** + **************************************************************************************** + * @brief Callback function for button action. Update button state charactersitc. + * @return void + **************************************************************************************** + */ +static void user_app_button_press_cb(void); + +/** + **************************************************************************************** + * @brief Read ADC val and update ADC_VAL2 characteristic. + * @return void + **************************************************************************************** +*/ +static void user_app_get_adc_val(void); + +/* + * FUNCTION DEFINITIONS + **************************************************************************************** + */ + +static void user_app_pwm_callback_function(void) +{ + static uint8_t change_delay = 0; + static uint8_t notes_idx = 0; + + if (change_delay == 10) + { + change_delay = 0; + timer0_set_pwm_on_counter(0xFFFF); + timer0_set_pwm_high_counter(notes[notes_idx] / 3 * 2); + timer0_set_pwm_low_counter(notes[notes_idx] / 3); + notes_idx = ++notes_idx % (APP_NOTES_NUM - 1); + } + change_delay++; +} + +static void user_app_enable_pwm(void) +{ + if(!app_sleep_env.custs1_pwm_enabled) + { + app_sleep_env.custs1_pwm_enabled = 1; + + // Disable sleep mode + arch_force_active_mode(); + + // Enable TIMER clock + set_tmr_enable(CLK_PER_REG_TMR_ENABLED); + // Set clock division + set_tmr_div(CLK_PER_REG_TMR_DIV_8); + // Init timer 0 + timer0_init(TIM0_CLK_FAST, PWM_MODE_ONE, TIM0_CLK_NO_DIV); + // Set timing parameters + timer0_set(APP_PWM_ON, APP_PWM_HIGH, APP_PWM_LOW); + // Register IRQ callback + timer0_register_callback(user_app_pwm_callback_function); + // Enable IRQ + timer0_enable_irq(); + // Start timer + timer0_start(); + } +} + +static void user_app_disable_pwm(void) +{ + if(app_sleep_env.custs1_pwm_enabled) + { + app_sleep_env.custs1_pwm_enabled = 0; + + arch_restore_sleep_mode(); + + timer0_stop(); + set_tmr_enable(CLK_PER_REG_TMR_DISABLED); + } +} + +static void user_app_set_button_event(uint8_t next_event) +{ + + wkupct_register_callback(user_app_button_press_cb); + + wkupct_enable_irq(WKUPCT_PIN_SELECT(GPIO_BUTTON_PORT, GPIO_BUTTON_PIN), + WKUPCT_PIN_POLARITY(GPIO_BUTTON_PORT, GPIO_BUTTON_PIN, next_event), // polarity + 1, // 1 event + 10); // debouncing time = 10 ms + +} + +static void user_app_disable_button(void) +{ + wkupct_disable_irq(); +} + +static void user_app_button_press_cb(void) +{ + uint8_t next_btn_event = 0; + + // Read button state + if(GPIO_GetPinStatus(GPIO_BUTTON_PORT, GPIO_BUTTON_PIN)) + { + app_sleep_env.custs1_btn_state = CUSTS1_BTN_STATE_RELEASED; + next_btn_event = WKUPCT_PIN_POLARITY_LOW; + } + else + { + app_sleep_env.custs1_btn_state = CUSTS1_BTN_STATE_PRESSED; + next_btn_event = WKUPCT_PIN_POLARITY_HIGH; + } + + // Update button characterstic + struct custs1_val_ntf_req *req = KE_MSG_ALLOC_DYN(CUSTS1_VAL_NTF_REQ, + TASK_CUSTS1, + TASK_APP, + custs1_val_ntf_req, + DEF_CUST1_BUTTON_STATE_CHAR_LEN); + + req->conhdl = app_env->conhdl; + req->handle = CUST1_IDX_BUTTON_STATE_VAL; + req->length = DEF_CUST1_BUTTON_STATE_CHAR_LEN; + req->value[0] = app_sleep_env.custs1_btn_state; + + ke_msg_send(req); + + // Configure next button event + user_app_set_button_event(next_btn_event); +} + +static void user_app_get_adc_val(void) +{ + if (app_sleep_env.custs1_adcval2_enabled) + { + uint16_t adc_sample; + + adc_calibrate(); + adc_sample = (uint16_t)adc_get_vbat_sample(false); + + struct custs1_val_set_req *req = KE_MSG_ALLOC_DYN(CUSTS1_VAL_SET_REQ, + TASK_CUSTS1, + TASK_APP, + custs1_val_set_req, + DEF_CUST1_ADC_VAL_2_CHAR_LEN); + + req->conhdl = app_env->conhdl; + req->handle = CUST1_IDX_ADC_VAL_2_VAL; + req->length = DEF_CUST1_ADC_VAL_2_CHAR_LEN; + memcpy(req->value, &adc_sample, DEF_CUST1_ADC_VAL_1_CHAR_LEN); + + ke_msg_send(req); + } +} + +void user_app_enable_periphs(void) +{ + // Update button state characteristic + user_app_button_press_cb(); + // Get initial ADC value if enabled + user_app_get_adc_val(); +} + +void user_app_disable_periphs(void) +{ + user_app_disable_pwm(); + user_app_disable_button(); +} + +void user_custs1_ctrl_wr_ind_handler(ke_msg_id_t const msgid, + struct custs1_val_write_ind const *param, + ke_task_id_t const dest_id, + ke_task_id_t const src_id) +{ + if(param->handle == CUST1_IDX_CONTROL_POINT_VAL) + { + if(param->value[0] == CUSTS1_CP_CMD_PWM_ENABLE) + { + user_app_enable_pwm(); + } + else if(param->value[0] == CUSTS1_CP_CMD_PWM_DISABLE) + { + user_app_disable_pwm(); + } + else if(param->value[0] == CUSTS1_CP_CMD_ADC_VAL_2_ENABLE) + { + app_sleep_env.custs1_adcval2_enabled = 1; + user_app_get_adc_val(); + } + else if(param->value[0] == CUSTS1_CP_CMD_ADC_VAL_2_DISABLE) + { + app_sleep_env.custs1_adcval2_enabled = 0; + } + } +} + +/// @} APP diff --git a/pool/shard002/C/0062317_secutil.c b/pool/shard002/C/0062317_secutil.c new file mode 100644 index 0000000000000000000000000000000000000000..1cd9d586596d904f8b2cde597565087ab27a15d0 --- /dev/null +++ b/pool/shard002/C/0062317_secutil.c @@ -0,0 +1,133 @@ +/* + * Part of Very Secure FTPd + * Licence: GPL v2 + * Author: Chris Evans + * secutil.c + */ + +#include "secutil.h" +#include "str.h" +#include "sysutil.h" +#include "sysstr.h" +#include "utility.h" +#include "sysdeputil.h" + +void +vsf_secutil_change_credentials(const struct mystr* p_user_str, + const struct mystr* p_dir_str, + const struct mystr* p_ext_dir_str, + unsigned int caps, unsigned int options) +{ + struct vsf_sysutil_user* p_user; + if (!vsf_sysutil_running_as_root()) + { + bug("vsf_secutil_change_credentials: not running as root"); + } + p_user = str_getpwnam(p_user_str); + if (p_user == 0) + { + die2("cannot locate user entry:", str_getbuf(p_user_str)); + } + { + struct mystr dir_str = INIT_MYSTR; + /* Work out where the chroot() jail is */ + if (p_dir_str == 0 || str_isempty(p_dir_str)) + { + str_alloc_text(&dir_str, vsf_sysutil_user_get_homedir(p_user)); + } + else + { + str_copy(&dir_str, p_dir_str); + } + /* Sort out supplementary groups before the chroot(). We need to access + * /etc/groups + */ + if (options & VSF_SECUTIL_OPTION_USE_GROUPS) + { + vsf_sysutil_initgroups(p_user); + } + else + { + vsf_sysutil_clear_supp_groups(); + } + /* Always do the chdir() regardless of whether we are chroot()'ing */ + { + /* Do chdir() with the target effective IDs to cater for NFS mounted + * home directories. + */ + int saved_euid = 0; + int saved_egid = 0; + int retval; + if (options & VSF_SECUTIL_OPTION_CHANGE_EUID) + { + saved_euid = vsf_sysutil_geteuid(); + saved_egid = vsf_sysutil_getegid(); + vsf_sysutil_setegid(p_user); + vsf_sysutil_seteuid(p_user); + } + retval = str_chdir(&dir_str); + if (retval != 0) + { + die2("cannot change directory:", str_getbuf(&dir_str)); + } + if (p_ext_dir_str && !str_isempty(p_ext_dir_str)) + { + retval = str_chdir(p_ext_dir_str); + /* Failure on the extra directory is OK as long as we're not in + * chroot() mode + */ + if (retval != 0 && !(options & VSF_SECUTIL_OPTION_CHROOT)) + { + retval = 0; + } + } + if (retval != 0) + { + die2("cannot change directory:", str_getbuf(p_ext_dir_str)); + } + if (options & VSF_SECUTIL_OPTION_CHANGE_EUID) + { + vsf_sysutil_seteuid_numeric(saved_euid); + vsf_sysutil_setegid_numeric(saved_egid); + } + /* Do the chroot() if required */ + if (options & VSF_SECUTIL_OPTION_CHROOT) + { + vsf_sysutil_chroot("."); + } + } + str_free(&dir_str); + } + if (options & VSF_SECUTIL_OPTION_NO_FDS) + { + vsf_sysutil_set_no_fds(); + } + /* Handle capabilities */ + if (caps) + { + if (!vsf_sysdep_has_capabilities()) + { + /* Need privilege but OS has no capabilities - have to keep root */ + return; + } + if (!vsf_sysdep_has_capabilities_as_non_root()) + { + vsf_sysdep_adopt_capabilities(caps); + return; + } + vsf_sysdep_keep_capabilities(); + } + /* Set group id */ + vsf_sysutil_setgid(p_user); + /* Finally set user id */ + vsf_sysutil_setuid(p_user); + if (caps) + { + vsf_sysdep_adopt_capabilities(caps); + } + if (options & VSF_SECUTIL_OPTION_NO_PROCS) + { + vsf_sysutil_set_no_procs(); + } +} + diff --git a/pool/shard002/C/0062347_dm-message.c b/pool/shard002/C/0062347_dm-message.c new file mode 100644 index 0000000000000000000000000000000000000000..0bc3afec558be88e7e04dd028882cab4753b957f --- /dev/null +++ b/pool/shard002/C/0062347_dm-message.c @@ -0,0 +1,180 @@ +/* + * Copyright (C) 2007,2008 Red Hat Inc. All rights reserved. + * + * Module Author: Heinz Mauelshagen + * + * This file is released under the GPL. + * + * device-mapper message parser. + * + */ + +#include "dm.h" +#include "dm-message.h" +#include + +#define DM_MSG_PREFIX "dm_message" + +/* Basename of a path. */ +static inline char * +basename(char *s) +{ + char *p = strrchr(s, '/'); + + return p ? p + 1 : s; +} + +/* Get an argument depending on type. */ +static void +message_arguments(struct dm_msg *msg, int argc, char **argv) +{ + + if (argc) { + int i; + struct dm_message_argument *args = msg->spec->args; + + for (i = 0; i < args->num_args; i++) { + int r; + unsigned long **ptr = args->ptr; + enum dm_message_argument_type type = args->types[i]; + + switch (type) { + case dm_msg_base_t: + ((char **) ptr)[i] = basename(argv[i]); + break; + + case dm_msg_str_t: + ((char **) ptr)[i] = argv[i]; + break; + + case dm_msg_int_t: + r = sscanf(argv[i], "%d", ((int **) ptr)[i]); + goto check; + + case dm_msg_uint_t: + r = sscanf(argv[i], "%u", + ((unsigned **) ptr)[i]); + goto check; + + case dm_msg_uint64_t: + r = sscanf(argv[i], "%llu", + ((unsigned long long **) ptr)[i]); + + check: + if (r != 1) { + set_bit(dm_msg_ret_undef, &msg->ret); + set_bit(dm_msg_ret_arg, &msg->ret); + } + } + } + } +} + +/* Parse message options. */ +static void +message_options_parse(struct dm_msg *msg, int argc, char **argv) +{ + int hit = 0; + unsigned long *action; + size_t l1 = strlen(*argv), l_hit = 0; + struct dm_message_option *o = msg->spec->options; + char **option, **option_end = o->options + o->num_options; + + for (option = o->options, action = o->actions; + option < option_end; option++, action++) { + size_t l2 = strlen(*option); + + if (!strnicmp(*argv, *option, min(l1, l2))) { + hit++; + l_hit = l2; + set_bit(*action, &msg->action); + } + } + + /* Assume error. */ + msg->ret = 0; + set_bit(dm_msg_ret_option, &msg->ret); + if (!hit || l1 > l_hit) + set_bit(dm_msg_ret_undef, &msg->ret); /* Undefined option. */ + else if (hit > 1) + set_bit(dm_msg_ret_ambiguous, &msg->ret); /* Ambiguous option.*/ + else { + clear_bit(dm_msg_ret_option, &msg->ret); /* Option OK. */ + message_arguments(msg, --argc, ++argv); + } +} + +static inline void +print_ret(const char *caller, unsigned long ret) +{ + struct { + unsigned long err; + const char *err_str; + } static err_msg[] = { + { dm_msg_ret_ambiguous, "message ambiguous" }, + { dm_msg_ret_inval, "message invalid" }, + { dm_msg_ret_undef, "message undefined" }, + { dm_msg_ret_arg, "message argument" }, + { dm_msg_ret_argcount, "message argument count" }, + { dm_msg_ret_option, "option" }, + }, *e = ARRAY_END(err_msg); + + while (e-- > err_msg) { + if (test_bit(e->err, &ret)) + DMERR("%s %s", caller, e->err_str); + } +} + +/* Parse a message action. */ +int +dm_message_parse(const char *caller, struct dm_msg *msg, void *context, + int argc, char **argv) +{ + int hit = 0; + size_t l1 = strlen(*argv), l_hit = 0; + struct dm_msg_spec *s, *s_hit = NULL, + *s_end = msg->specs + msg->num_specs; + + if (argc < 2) + return -EINVAL; + + for (s = msg->specs; s < s_end; s++) { + size_t l2 = strlen(s->cmd); + + if (!strnicmp(*argv, s->cmd, min(l1, l2))) { + hit++; + l_hit = l2; + s_hit = s; + } + } + + msg->ret = 0; + if (!hit || l1 > l_hit) /* No hit or message string too long. */ + set_bit(dm_msg_ret_undef, &msg->ret); + else if (hit > 1) /* Ambiguous message. */ + set_bit(dm_msg_ret_ambiguous, &msg->ret); + else if (argc - 2 != s_hit->args->num_args) { + set_bit(dm_msg_ret_undef, &msg->ret); + set_bit(dm_msg_ret_argcount, &msg->ret); + } + + if (msg->ret) + goto bad; + + msg->action = 0; + msg->spec = s_hit; + set_bit(s_hit->action, &msg->action); + message_options_parse(msg, --argc, ++argv); + + if (!msg->ret) + return msg->spec->f(msg, context); + + bad: + print_ret(caller, msg->ret); + return -EINVAL; +} +EXPORT_SYMBOL(dm_message_parse); + +MODULE_DESCRIPTION(DM_NAME " device-mapper target message parser"); +MODULE_AUTHOR("Heinz Mauelshagen "); +MODULE_LICENSE("GPL"); diff --git a/pool/shard002/C/0062365_keepalive_timeout.c b/pool/shard002/C/0062365_keepalive_timeout.c new file mode 100644 index 0000000000000000000000000000000000000000..ceefe5db8e32acafae35f5aeb0c5dbc55a564cb4 --- /dev/null +++ b/pool/shard002/C/0062365_keepalive_timeout.c @@ -0,0 +1,248 @@ +/* + * + * Copyright 2017, Google Inc. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following disclaimer + * in the documentation and/or other materials provided with the + * distribution. + * * Neither the name of Google Inc. nor the names of its + * contributors may be used to endorse or promote products derived from + * this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + */ + +#include "test/core/end2end/end2end_tests.h" + +#include +#include + +#include +#include +#include +#include +#include +#include "src/core/ext/transport/chttp2/transport/frame_ping.h" +#include "src/core/lib/channel/channel_args.h" +#include "src/core/lib/iomgr/exec_ctx.h" +#include "src/core/lib/support/env.h" +#include "test/core/end2end/cq_verifier.h" + +static void *tag(intptr_t t) { return (void *)t; } + +static grpc_end2end_test_fixture begin_test(grpc_end2end_test_config config, + const char *test_name, + grpc_channel_args *client_args, + grpc_channel_args *server_args) { + grpc_end2end_test_fixture f; + gpr_log(GPR_INFO, "%s/%s", test_name, config.name); + f = config.create_fixture(client_args, server_args); + config.init_server(&f, server_args); + config.init_client(&f, client_args); + return f; +} + +static gpr_timespec n_seconds_from_now(int n) { + return grpc_timeout_seconds_to_deadline(n); +} + +static gpr_timespec five_seconds_from_now(void) { + return n_seconds_from_now(5); +} + +static void drain_cq(grpc_completion_queue *cq) { + grpc_event ev; + do { + ev = grpc_completion_queue_next(cq, five_seconds_from_now(), NULL); + } while (ev.type != GRPC_QUEUE_SHUTDOWN); +} + +static void shutdown_server(grpc_end2end_test_fixture *f) { + if (!f->server) return; + + grpc_server_shutdown_and_notify(f->server, f->shutdown_cq, tag(1000)); + GPR_ASSERT(grpc_completion_queue_pluck(f->shutdown_cq, tag(1000), + five_seconds_from_now(), NULL) + .type == GRPC_OP_COMPLETE); + grpc_server_destroy(f->server); + f->server = NULL; +} + +static void shutdown_client(grpc_end2end_test_fixture *f) { + if (!f->client) return; + grpc_channel_destroy(f->client); + f->client = NULL; +} + +static void end_test(grpc_end2end_test_fixture *f) { + shutdown_server(f); + shutdown_client(f); + + grpc_completion_queue_shutdown(f->cq); + drain_cq(f->cq); + grpc_completion_queue_destroy(f->cq); + grpc_completion_queue_destroy(f->shutdown_cq); +} + +/* Client sends a request, server replies with a payload, then waits for the + keepalive watchdog timeouts before returning status. */ +static void test_keepalive_timeout(grpc_end2end_test_config config) { + grpc_call *c; + grpc_call *s; + grpc_slice response_payload_slice = + grpc_slice_from_copied_string("hello world"); + grpc_byte_buffer *response_payload = + grpc_raw_byte_buffer_create(&response_payload_slice, 1); + + grpc_arg keepalive_args[] = {{.type = GRPC_ARG_INTEGER, + .key = GRPC_ARG_KEEPALIVE_TIME_MS, + .value.integer = 1500}, + {.type = GRPC_ARG_INTEGER, + .key = GRPC_ARG_KEEPALIVE_TIMEOUT_MS, + .value.integer = 0}, + {.type = GRPC_ARG_INTEGER, + .key = GRPC_ARG_HTTP2_BDP_PROBE, + .value.integer = 1}}; + + grpc_channel_args *client_args = NULL; + client_args = grpc_channel_args_copy_and_add(client_args, keepalive_args, 2); + + grpc_end2end_test_fixture f = + begin_test(config, "keepalive_timeout", client_args, NULL); + cq_verifier *cqv = cq_verifier_create(f.cq); + grpc_op ops[6]; + grpc_op *op; + grpc_metadata_array initial_metadata_recv; + grpc_metadata_array trailing_metadata_recv; + grpc_metadata_array request_metadata_recv; + grpc_byte_buffer *response_payload_recv = NULL; + grpc_call_details call_details; + grpc_status_code status; + grpc_call_error error; + grpc_slice details; + + /* Disable ping ack to trigger the keepalive timeout */ + grpc_set_disable_ping_ack(true); + + gpr_timespec deadline = five_seconds_from_now(); + c = grpc_channel_create_call( + f.client, NULL, GRPC_PROPAGATE_DEFAULTS, f.cq, + grpc_slice_from_static_string("/foo"), + get_host_override_slice("foo.test.google.fr:1234", config), deadline, + NULL); + GPR_ASSERT(c); + + grpc_metadata_array_init(&initial_metadata_recv); + grpc_metadata_array_init(&trailing_metadata_recv); + grpc_metadata_array_init(&request_metadata_recv); + grpc_call_details_init(&call_details); + + memset(ops, 0, sizeof(ops)); + op = ops; + op->op = GRPC_OP_SEND_INITIAL_METADATA; + op->data.send_initial_metadata.count = 0; + op++; + op->op = GRPC_OP_SEND_CLOSE_FROM_CLIENT; + op++; + op->op = GRPC_OP_RECV_INITIAL_METADATA; + op->data.recv_initial_metadata.recv_initial_metadata = &initial_metadata_recv; + op++; + op->op = GRPC_OP_RECV_MESSAGE; + op->data.recv_message.recv_message = &response_payload_recv; + op++; + error = grpc_call_start_batch(c, ops, (size_t)(op - ops), tag(1), NULL); + GPR_ASSERT(GRPC_CALL_OK == error); + + GPR_ASSERT(GRPC_CALL_OK == grpc_server_request_call( + f.server, &s, &call_details, + &request_metadata_recv, f.cq, f.cq, tag(101))); + CQ_EXPECT_COMPLETION(cqv, tag(101), 1); + cq_verify(cqv); + + memset(ops, 0, sizeof(ops)); + op = ops; + op->op = GRPC_OP_SEND_INITIAL_METADATA; + op->data.send_initial_metadata.count = 0; + op++; + op->op = GRPC_OP_SEND_MESSAGE; + op->data.send_message.send_message = response_payload; + op++; + error = grpc_call_start_batch(s, ops, (size_t)(op - ops), tag(102), NULL); + GPR_ASSERT(GRPC_CALL_OK == error); + + CQ_EXPECT_COMPLETION(cqv, tag(102), 1); + CQ_EXPECT_COMPLETION(cqv, tag(1), 1); + cq_verify(cqv); + + memset(ops, 0, sizeof(ops)); + op = ops; + op->op = GRPC_OP_RECV_STATUS_ON_CLIENT; + op->data.recv_status_on_client.trailing_metadata = &trailing_metadata_recv; + op->data.recv_status_on_client.status = &status; + op->data.recv_status_on_client.status_details = &details; + op++; + error = grpc_call_start_batch(c, ops, (size_t)(op - ops), tag(3), NULL); + GPR_ASSERT(GRPC_CALL_OK == error); + + CQ_EXPECT_COMPLETION(cqv, tag(3), 1); + cq_verify(cqv); + + char *details_str = grpc_slice_to_c_string(details); + char *method_str = grpc_slice_to_c_string(call_details.method); + GPR_ASSERT(status == GRPC_STATUS_UNAVAILABLE); + GPR_ASSERT(0 == grpc_slice_str_cmp(details, "keepalive watchdog timeout")); + GPR_ASSERT(0 == grpc_slice_str_cmp(call_details.method, "/foo")); + validate_host_override_string("foo.test.google.fr:1234", call_details.host, + config); + + gpr_free(details_str); + gpr_free(method_str); + + grpc_slice_unref(details); + grpc_metadata_array_destroy(&initial_metadata_recv); + grpc_metadata_array_destroy(&trailing_metadata_recv); + grpc_metadata_array_destroy(&request_metadata_recv); + grpc_call_details_destroy(&call_details); + + grpc_call_unref(c); + grpc_call_unref(s); + + cq_verifier_destroy(cqv); + + grpc_byte_buffer_destroy(response_payload); + grpc_byte_buffer_destroy(response_payload_recv); + + if (client_args != NULL) { + grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT; + grpc_channel_args_destroy(&exec_ctx, client_args); + grpc_exec_ctx_finish(&exec_ctx); + } + + end_test(&f); + config.tear_down_data(&f); +} + +void keepalive_timeout(grpc_end2end_test_config config) { + test_keepalive_timeout(config); +} + +void keepalive_timeout_pre_init(void) {} diff --git a/pool/shard002/C/0062387_gui-menu-url.c b/pool/shard002/C/0062387_gui-menu-url.c new file mode 100644 index 0000000000000000000000000000000000000000..a738df912f15a0c068f93424b8f78af868e04d6e --- /dev/null +++ b/pool/shard002/C/0062387_gui-menu-url.c @@ -0,0 +1,140 @@ +/* + gui-menu-url.c : irssi + + Copyright (C) 2002 Timo Sirainen + + 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 "module.h" +#include "misc.h" +#include "special-vars.h" +#include "servers.h" +#include "channels.h" + +#include "gui-menu.h" +#include "gui-url.h" + +enum { + ACTION_COMMAND = ACTION_CUSTOM, + ACTION_HTTPURL, + ACTION_FTPURL, + ACTION_MAILTOURL +}; + +static MenuItem http_items[] = { + { ACTION_HTTPURL, "Open" }, + { ACTION_SEPARATOR }, + { ACTION_COMMAND, "Open with _Galeon", GALEON_OPEN }, + { ACTION_COMMAND, "Open with _Mozilla", MOZILLA_OPEN } +}; + +static MenuItem ftp_items[] = { + { ACTION_FTPURL, "Open" }, + { ACTION_SEPARATOR }, + { ACTION_COMMAND, "Open with _Galeon", GALEON_OPEN }, + { ACTION_COMMAND, "Open with _lftp", LFTP_OPEN } +}; + +static MenuItem mail_items[] = { + { ACTION_MAILTOURL, "Send mail" }, + { ACTION_SEPARATOR }, + { ACTION_COMMAND, "Send mail with _mutt", MUTT_SEND } +}; + +static MenuItem irc_items[] = { + { ACTION_COMMAND, "Connect", "connect $0" } +}; + +static void menu_callback(void *user_data, const char *cmd, int action) +{ + GObject *obj = user_data; + const char *url; + + url = g_object_get_data(obj, "url"); + + switch (action) { + case ACTION_COMMAND: + eval_special_string(cmd, url, NULL, NULL); + break; + case ACTION_HTTPURL: + signal_emit("url open", 2, url, "http"); + break; + case ACTION_FTPURL: + signal_emit("url open", 2, url, "ftp"); + break; + case ACTION_MAILTOURL: + signal_emit("url open", 2, url, "mailto"); + break; + } +} + +static gboolean event_menu_destroy(GtkWidget *widget) +{ + g_free(g_object_get_data(G_OBJECT(widget), "url")); + return FALSE; +} + +void gui_menu_url_popup(const char *url, int button) +{ + MenuItem *items; + GtkWidget *menu; + char *new_url; + int nitems; + + g_return_if_fail(url != NULL); + + /* fix the urls to contain proto:// */ + new_url = NULL; + if (strncmp(url, "www.", 4) == 0) + url = new_url = g_strconcat("http://", url, NULL); + else if (strncmp(url, "ftp.", 4) == 0) + url = new_url = g_strconcat("ftp://", url, NULL); + + if (strncmp(url, "http://", 7) == 0 || + strncmp(url, "https://", 8) == 0) { + items = http_items; + nitems = G_N_ELEMENTS(http_items); + } else if (strncmp(url, "ftp://", 6) == 0) { + items = ftp_items; + nitems = G_N_ELEMENTS(ftp_items); + } else if (strncmp(url, "mailto:", 7) == 0) { + items = mail_items; + nitems = G_N_ELEMENTS(mail_items); + } else if (strncmp(url, "irc://", 6) == 0) { + items = irc_items; + nitems = G_N_ELEMENTS(irc_items); + } else { + /* unknown url protocol */ + return; + } + + if (new_url == NULL) + new_url = g_strdup(url); + + /* create the menu */ + menu = gtk_menu_new(); + + g_signal_connect(G_OBJECT(menu), "destroy", + G_CALLBACK(event_menu_destroy), NULL); + g_signal_connect(G_OBJECT(menu), "selection_done", + G_CALLBACK(gtk_widget_destroy), NULL); + + g_object_set_data(G_OBJECT(menu), "url", new_url); + gui_menu_fill(menu, items, nitems, menu_callback, menu); + + gtk_widget_show_all(menu); + gtk_menu_popup(GTK_MENU(menu), NULL, NULL, NULL, NULL, button, 0); +} diff --git a/pool/shard002/C/0062393_ditto.c b/pool/shard002/C/0062393_ditto.c new file mode 100644 index 0000000000000000000000000000000000000000..a63f11d1f13432d2dcc18900e17ec58ea43439ec --- /dev/null +++ b/pool/shard002/C/0062393_ditto.c @@ -0,0 +1,146 @@ +/**************************************************************************** + * Copyright (c) 1998-2001,2005 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: Thomas E. Dickey 1998 + * + * $Id$ + * + * The program illustrates how to set up multiple screens from a single + * program. Invoke the program by specifying another terminal on the same + * machine by specifying its device, e.g., + * ditto /dev/ttyp1 + */ +#include +#include +#include + +typedef struct { + FILE *input; + FILE *output; + SCREEN *screen; +} DITTO; + +static void +failed(const char *s) +{ + perror(s); + ExitProgram(EXIT_FAILURE); +} + +static void +usage(void) +{ + fprintf(stderr, "usage: ditto [terminal1 ...]\n"); + ExitProgram(EXIT_FAILURE); +} + +static FILE * +open_tty(char *path) +{ + FILE *fp; + struct stat sb; + + if (stat(path, &sb) < 0) + failed(path); + if ((sb.st_mode & S_IFMT) != S_IFCHR) { + errno = ENOTTY; + failed(path); + } + fp = fopen(path, "a+"); + if (fp == 0) + failed(path); + printf("opened %s\n", path); + return fp; +} + +int +main(int argc GCC_UNUSED, + char *argv[]GCC_UNUSED) +{ + int j; + int active_tty = 0; + DITTO *data; + + if (argc <= 1) + usage(); + + if ((data = (DITTO *) calloc((unsigned) argc, sizeof(DITTO))) == 0) + failed("calloc data"); + + data[0].input = stdin; + data[0].output = stdout; + for (j = 1; j < argc; j++) { + data[j].input = + data[j].output = open_tty(argv[j]); + } + + /* + * If we got this far, we have open connection(s) to the terminal(s). + * Set up the screens. + */ + for (j = 0; j < argc; j++) { + active_tty++; + data[j].screen = newterm((char *) 0, /* assume $TERM is the same */ + data[j].output, + data[j].input); + if (data[j].screen == 0) + failed("newterm"); + cbreak(); + noecho(); + scrollok(stdscr, TRUE); + } + + /* + * Loop, reading characters from any of the inputs and writing to all + * of the screens. + */ + for (;;) { + int ch; + set_term(data[0].screen); + ch = getch(); + if (ch == ERR) + continue; + if (ch == 4) + break; + for (j = 0; j < argc; j++) { + set_term(data[j].screen); + addch(UChar(ch)); + refresh(); + } + } + + /* + * Cleanup and exit + */ + for (j = argc - 1; j >= 0; j--) { + set_term(data[j].screen); + endwin(); + } + ExitProgram(EXIT_SUCCESS); +} diff --git a/pool/shard002/C/0062403_lproc_fld.c b/pool/shard002/C/0062403_lproc_fld.c new file mode 100644 index 0000000000000000000000000000000000000000..da312816666c6b0bc4bdd296513ec35cf8596218 --- /dev/null +++ b/pool/shard002/C/0062403_lproc_fld.c @@ -0,0 +1,159 @@ +/* + * GPL HEADER START + * + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License version 2 only, + * 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 version 2 for more details (a copy is included + * in the LICENSE file that accompanied this code). + * + * You should have received a copy of the GNU General Public License + * version 2 along with this program; If not, see + * http://www.sun.com/software/products/lustre/docs/GPLv2.pdf + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + * + * GPL HEADER END + */ +/* + * Copyright (c) 2007, 2010, Oracle and/or its affiliates. All rights reserved. + * Use is subject to license terms. + * + * Copyright (c) 2012, 2015, Intel Corporation. + */ +/* + * This file is part of Lustre, http://www.lustre.org/ + * Lustre is a trademark of Sun Microsystems, Inc. + * + * lustre/fld/lproc_fld.c + * + * FLD (FIDs Location Database) + * + * Author: Yury Umanets + * Di Wang + */ + +#define DEBUG_SUBSYSTEM S_FLD + +#include "../../include/linux/libcfs/libcfs.h" +#include + +#include "../include/obd.h" +#include "../include/obd_class.h" +#include "../include/obd_support.h" +#include "../include/lustre_req_layout.h" +#include "../include/lustre_fld.h" +#include "../include/lustre_fid.h" +#include "fld_internal.h" + +static int +fld_debugfs_targets_seq_show(struct seq_file *m, void *unused) +{ + struct lu_client_fld *fld = (struct lu_client_fld *)m->private; + struct lu_fld_target *target; + + spin_lock(&fld->lcf_lock); + list_for_each_entry(target, + &fld->lcf_targets, ft_chain) + seq_printf(m, "%s\n", fld_target_name(target)); + spin_unlock(&fld->lcf_lock); + + return 0; +} + +static int +fld_debugfs_hash_seq_show(struct seq_file *m, void *unused) +{ + struct lu_client_fld *fld = (struct lu_client_fld *)m->private; + + spin_lock(&fld->lcf_lock); + seq_printf(m, "%s\n", fld->lcf_hash->fh_name); + spin_unlock(&fld->lcf_lock); + + return 0; +} + +static ssize_t +fld_debugfs_hash_seq_write(struct file *file, + const char __user *buffer, + size_t count, loff_t *off) +{ + struct lu_client_fld *fld; + struct lu_fld_hash *hash = NULL; + char fh_name[8]; + int i; + + if (count > sizeof(fh_name)) + return -ENAMETOOLONG; + + if (copy_from_user(fh_name, buffer, count) != 0) + return -EFAULT; + + fld = ((struct seq_file *)file->private_data)->private; + + for (i = 0; fld_hash[i].fh_name; i++) { + if (count != strlen(fld_hash[i].fh_name)) + continue; + + if (!strncmp(fld_hash[i].fh_name, fh_name, count)) { + hash = &fld_hash[i]; + break; + } + } + + if (hash) { + spin_lock(&fld->lcf_lock); + fld->lcf_hash = hash; + spin_unlock(&fld->lcf_lock); + + CDEBUG(D_INFO, "%s: Changed hash to \"%s\"\n", + fld->lcf_name, hash->fh_name); + } + + return count; +} + +static ssize_t +fld_debugfs_cache_flush_write(struct file *file, const char __user *buffer, + size_t count, loff_t *pos) +{ + struct lu_client_fld *fld = file->private_data; + + fld_cache_flush(fld->lcf_cache); + + CDEBUG(D_INFO, "%s: Lookup cache is flushed\n", fld->lcf_name); + + return count; +} + +static int +fld_debugfs_cache_flush_release(struct inode *inode, struct file *file) +{ + file->private_data = NULL; + return 0; +} + +static struct file_operations fld_debugfs_cache_flush_fops = { + .owner = THIS_MODULE, + .open = simple_open, + .write = fld_debugfs_cache_flush_write, + .release = fld_debugfs_cache_flush_release, +}; + +LPROC_SEQ_FOPS_RO(fld_debugfs_targets); +LPROC_SEQ_FOPS(fld_debugfs_hash); + +struct lprocfs_vars fld_client_debugfs_list[] = { + { "targets", &fld_debugfs_targets_fops }, + { "hash", &fld_debugfs_hash_fops }, + { "cache_flush", &fld_debugfs_cache_flush_fops }, + { NULL } +}; diff --git a/pool/shard002/C/0062409_get_amode.c b/pool/shard002/C/0062409_get_amode.c new file mode 100644 index 0000000000000000000000000000000000000000..3ff5077ae225f2c8e63f34fbcac72b9b8f9946ce --- /dev/null +++ b/pool/shard002/C/0062409_get_amode.c @@ -0,0 +1,55 @@ +/* -*- Mode: C; c-basic-offset:4 ; indent-tabs-mode:nil ; -*- */ +/* + * + * 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_get_amode = PMPI_File_get_amode +#elif defined(HAVE_PRAGMA_HP_SEC_DEF) +#pragma _HP_SECONDARY_DEF PMPI_File_get_amode MPI_File_get_amode +#elif defined(HAVE_PRAGMA_CRI_DUP) +#pragma _CRI duplicate MPI_File_get_amode as PMPI_File_get_amode +/* end of weak pragmas */ +#elif defined(HAVE_WEAK_ATTRIBUTE) +int MPI_File_get_amode(MPI_File fh, int *amode) __attribute__((weak,alias("PMPI_File_get_amode"))); +#endif + +/* Include mapping from MPI->PMPI */ +#define MPIO_BUILD_PROFILING +#include "mpioprof.h" +#endif + +/*@ + MPI_File_get_amode - Returns the file access mode + +Input Parameters: +. fh - file handle (handle) + +Output Parameters: +. amode - access mode (integer) + +.N fortran +@*/ +int MPI_File_get_amode(MPI_File fh, int *amode) +{ + int error_code=MPI_SUCCESS; + static char myname[] = "MPI_FILE_GET_AMODE"; + ADIO_File adio_fh; + + adio_fh = MPIO_File_resolve(fh); + + /* --BEGIN ERROR HANDLING-- */ + MPIO_CHECK_FILE_HANDLE(adio_fh, myname, error_code); + /* --END ERROR HANDLING-- */ + + *amode = adio_fh->access_mode; + +fn_exit: + return error_code; +} diff --git a/pool/shard002/C/0062413_simple_decoder.c b/pool/shard002/C/0062413_simple_decoder.c new file mode 100644 index 0000000000000000000000000000000000000000..bb4207167acf133f620cd6372124700ad70e8c67 --- /dev/null +++ b/pool/shard002/C/0062413_simple_decoder.c @@ -0,0 +1,40 @@ +/////////////////////////////////////////////////////////////////////////////// +// +/// \file simple_decoder.c +/// \brief Properties decoder for simple filters +// +// Author: Lasse Collin +// +// This file has been put into the public domain. +// You can do whatever you want with this file. +// +/////////////////////////////////////////////////////////////////////////////// + +#include "simple_decoder.h" + + +extern lzma_ret +lzma_simple_props_decode(void **options, const lzma_allocator *allocator, + const uint8_t *props, size_t props_size) +{ + if (props_size == 0) + return LZMA_OK; + + if (props_size != 4) { + return LZMA_OPTIONS_ERROR; + } + lzma_options_bcj *opt = lzma_alloc( + sizeof(lzma_options_bcj), allocator); + if (opt == NULL) + return LZMA_MEM_ERROR; + + opt->start_offset = unaligned_read32le(props); + + // Don't leave an options structure allocated if start_offset is zero. + if (opt->start_offset == 0) + lzma_free(opt, allocator); + else + *options = opt; + + return LZMA_OK; +} diff --git a/pool/shard002/C/0062423_timer_stm32.c b/pool/shard002/C/0062423_timer_stm32.c new file mode 100644 index 0000000000000000000000000000000000000000..437be52c63b6557010bd60b685032abe39ae4a05 --- /dev/null +++ b/pool/shard002/C/0062423_timer_stm32.c @@ -0,0 +1,139 @@ +/* Port of CanFestival to STM32F103 using libopencm3 + +*/ + +/* +This file is part of CanFestival, a library implementing CanOpen Stack. + +Copyright (C): Edouard TISSERANT and Francis DUPIN +STM32F103 Port: Ken Sarkies, November 2012 +Based on AVR Port: Andreas GLAUSER and Peter CHRISTEN + +See COPYING file for copyrights details. + +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 +*/ + +/* STM32 implementation of the CANopen timer driver, uses Timer 3 (16 bit) */ + +/* Includes for the Canfestival driver */ +#include +#include +#include +#include +#include + +TIMEVAL timerAlarm = 0; + +/************************** Module variables **********************************/ +/* Store the last timer value to calculate the elapsed time */ +static TIMEVAL last_time_set = TIMEVAL_MAX; + +/****************************************************************************** +Initializes the timer, turn on the interrupt and put the interrupt time to zero +INPUT void +OUTPUT void + +The timer is set to roll over at 0.5 second from an 8us clock, and the output +compare 1 is used to trigger an alarm. This is set progressively by the +CanFestival stack. +******************************************************************************/ +void initTimer(void) +{ +/* Set alarm back to zero */ + timerAlarm = 0; +/* Enable TIM3 clock. */ + rcc_peripheral_enable_clock(&RCC_APB1ENR, RCC_APB1ENR_TIM3EN); +/* Enable TIM3 interrupt. */ + nvic_enable_irq(NVIC_TIM3_IRQ); + timer_reset(TIM3); + timer_set_mode(TIM3, TIM_CR1_CKD_CK_INT, + TIM_CR1_CMS_EDGE, TIM_CR1_DIR_UP); +/* Set prescaler to give 8us clock */ + timer_set_prescaler(TIM3, 576); +/* Set the period as 0.5 second */ + timer_set_period(TIM3, TIMEVAL_MAX); +/* Disable physical pin outputs. */ + timer_disable_oc_output(TIM3, TIM_OC1 | TIM_OC2 | TIM_OC3 | TIM_OC4); +/* Configure global mode of output channel 1, disabling the output. */ + timer_disable_oc_clear(TIM3, TIM_OC1); + timer_disable_oc_preload(TIM3, TIM_OC1); + timer_set_oc_slow_mode(TIM3, TIM_OC1); + timer_set_oc_mode(TIM3, TIM_OC1, TIM_OCM_FROZEN); +/* Set the initial compare value for OC1. */ + timer_set_oc_value(TIM3, TIM_OC1, timerAlarm); +/* Continous counting mode. */ + timer_continuous_mode(TIM3); +/* ARR reload disable. */ + timer_disable_preload(TIM3); +/* Counter enable. */ + timer_enable_counter(TIM3); +/* Enable compare match interrupt. */ + timer_enable_irq(TIM3, TIM_DIER_CC1IE); +} + +/****************************************************************************** +Set the timer for the next alarm. +INPUT value TIMEVAL (unsigned long) 0...TIMEVAL_MAX +OUTPUT void +******************************************************************************/ +void setTimer(TIMEVAL value) +{ +/* Add the desired time to the timer interrupt time for the next alarm */ +/* NOTE: This is computing (timerAlarm + value) % TIMEVAL_MAX, but so that it can +handle possible (timerAlarm + value) beyond the integer range of TIMEVAL */ +/* Just make certain that value is in range */ + if (value > TIMEVAL_MAX) value = TIMEVAL_MAX; + if (timerAlarm < TIMEVAL_MAX - value) + timerAlarm += value; + else + timerAlarm -= TIMEVAL_MAX - value; + timer_set_oc_value(TIM3, TIM_OC1, (unsigned long) timerAlarm); +} + +/****************************************************************************** +Return the elapsed time to tell the Stack how much time is spent since last call. +INPUT void +OUTPUT value TIMEVAL (unsigned long) the elapsed time +******************************************************************************/ +TIMEVAL getElapsedTime(void) +{ + TIMEVAL timer = timer_get_counter(TIM3); /* Read the value of the running timer */ + if (timer > last_time_set) /* In case the timer value is higher than the last time. */ + return (timer - last_time_set); /* Calculate the time difference */ + else if (timer < last_time_set) /* Timer has cycled around */ + return (timer + (TIMEVAL_MAX - last_time_set)); /* Calculate the time difference */ + else + return TIMEVAL_MAX; /* timer has gone around a full cycle.*/ +} + +/****************************************************************************** +Interruptserviceroutine Timer 3 Compare 1 for the CAN timer +Pull in the timer counter value to represent the last time an alarm was set. +******************************************************************************/ +void tim3_isr(void) +{ +/* Clear interrrupt flag. */ + if (timer_get_flag(TIM3, TIM_SR_CC1IF)) + { + timer_clear_flag(TIM3, TIM_SR_CC1IF); +/* Reread to force the previous write before leaving (a side-effect of hardware pipelining)*/ + timer_get_flag(TIM3, TIM_SR_CC1IF); + last_time_set = timer_get_counter(TIM3); +/* Call the time handler of the stack to adapt the elapsed time */ + TimeDispatch(); + } +} + diff --git a/pool/shard002/C/0062434_EplApiProcessImageSetup.c b/pool/shard002/C/0062434_EplApiProcessImageSetup.c new file mode 100644 index 0000000000000000000000000000000000000000..218f05e563a747628e44c11880e5629dd487e647 --- /dev/null +++ b/pool/shard002/C/0062434_EplApiProcessImageSetup.c @@ -0,0 +1,337 @@ +/**************************************************************************** + + (c) SYSTEC electronic GmbH, D-08468 Heinsdorfergrund, Am Windrad 2 + www.systec-electronic.com + + Project: openPOWERLINK + + Description: source file for setting up the process image + + 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. Neither the name of SYSTEC electronic GmbH nor the names of its + contributors may be used to endorse or promote products derived + from this software without prior written permission. For written + permission, please contact info@systec-electronic.com. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + COPYRIGHT HOLDERS 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. + + Severability Clause: + + If a provision of this License is or becomes illegal, invalid or + unenforceable in any jurisdiction, that shall not affect: + 1. the validity or enforceability in that jurisdiction of any other + provision of this License; or + 2. the validity or enforceability in other jurisdictions of that or + any other provision of this License. + + ------------------------------------------------------------------------- + + $RCSfile$ + + $Author$ + + $Revision$ $Date$ + + $State$ + + Build Environment: + GCC V3.4 + + ------------------------------------------------------------------------- + + Revision History: + + 2006/10/10 d.k.: start of the implementation, version 1.00 + +****************************************************************************/ + +#include "Epl.h" + + +/***************************************************************************/ +/* */ +/* */ +/* G L O B A L D E F I N I T I O N S */ +/* */ +/* */ +/***************************************************************************/ + +//--------------------------------------------------------------------------- +// const defines +//--------------------------------------------------------------------------- + +#define EPLAPI_PI_SUBINDEX_COUNT 252 + +//--------------------------------------------------------------------------- +// local types +//--------------------------------------------------------------------------- + +//--------------------------------------------------------------------------- +// modul globale vars +//--------------------------------------------------------------------------- + +//--------------------------------------------------------------------------- +// local function prototypes +//--------------------------------------------------------------------------- + + +/***************************************************************************/ +/* */ +/* */ +/* C L A S S EplApi */ +/* */ +/* */ +/***************************************************************************/ +// +// Description: +// +// +/***************************************************************************/ + + +//=========================================================================// +// // +// P R I V A T E D E F I N I T I O N S // +// // +//=========================================================================// + +//--------------------------------------------------------------------------- +// const defines +//--------------------------------------------------------------------------- + +//--------------------------------------------------------------------------- +// local types +//--------------------------------------------------------------------------- + +//--------------------------------------------------------------------------- +// local vars +//--------------------------------------------------------------------------- + +//--------------------------------------------------------------------------- +// local function prototypes +//--------------------------------------------------------------------------- + +static tEplKernel EplApiProcessImageLinkRange( + unsigned int uiObjIndexStart_p, + unsigned int uiObjIndexEnd_p, + unsigned int uiOffsetPI_p, + BOOL fOutputPI_p, + tEplObdSize EntrySize_p, + unsigned int uiSubindexCountPerIndex_p); + + +//=========================================================================// +// // +// P U B L I C F U N C T I O N S // +// // +//=========================================================================// + + +//--------------------------------------------------------------------------- +// +// Function: EplApiProcessImageSetup() +// +// Description: sets up static process image +// +// Parameters: (none) +// +// Returns: tEplKernel = error code +// +// +// State: +// +//--------------------------------------------------------------------------- + +tEplKernel PUBLIC EplApiProcessImageSetup(void) +{ +tEplKernel Ret = kEplSuccessful; + + Ret = EplApiProcessImageLinkRange(0xA000, 0xA00F, 0, FALSE, 1, EPLAPI_PI_SUBINDEX_COUNT); + if (Ret != kEplSuccessful) + { + goto Exit; + } + + Ret = EplApiProcessImageLinkRange(0xA040, 0xA04F, 0, FALSE, 1, EPLAPI_PI_SUBINDEX_COUNT); + if (Ret != kEplSuccessful) + { + goto Exit; + } + + Ret = EplApiProcessImageLinkRange(0xA0C0, 0xA0C7, 0, FALSE, 2, EPLAPI_PI_SUBINDEX_COUNT); + if (Ret != kEplSuccessful) + { + goto Exit; + } + + Ret = EplApiProcessImageLinkRange(0xA100, 0xA107, 0, FALSE, 2, EPLAPI_PI_SUBINDEX_COUNT); + if (Ret != kEplSuccessful) + { + goto Exit; + } + + Ret = EplApiProcessImageLinkRange(0xA1C0, 0xA1C3, 0, FALSE, 4, EPLAPI_PI_SUBINDEX_COUNT); + if (Ret != kEplSuccessful) + { + goto Exit; + } + + Ret = EplApiProcessImageLinkRange(0xA200, 0xA203, 0, FALSE, 4, EPLAPI_PI_SUBINDEX_COUNT); + if (Ret != kEplSuccessful) + { + goto Exit; + } + + Ret = EplApiProcessImageLinkRange(0xA400, 0xA401, 0, FALSE, 8, EPLAPI_PI_SUBINDEX_COUNT); + if (Ret != kEplSuccessful) + { + goto Exit; + } + + Ret = EplApiProcessImageLinkRange(0xA440, 0xA441, 0, FALSE, 8, EPLAPI_PI_SUBINDEX_COUNT); + if (Ret != kEplSuccessful) + { + goto Exit; + } + + Ret = EplApiProcessImageLinkRange(0xA480, 0xA48F, 0, TRUE, 1, EPLAPI_PI_SUBINDEX_COUNT); + if (Ret != kEplSuccessful) + { + goto Exit; + } + + Ret = EplApiProcessImageLinkRange(0xA4C0, 0xA4CF, 0, TRUE, 1, EPLAPI_PI_SUBINDEX_COUNT); + if (Ret != kEplSuccessful) + { + goto Exit; + } + + Ret = EplApiProcessImageLinkRange(0xA540, 0xA547, 0, TRUE, 2, EPLAPI_PI_SUBINDEX_COUNT); + if (Ret != kEplSuccessful) + { + goto Exit; + } + + Ret = EplApiProcessImageLinkRange(0xA580, 0xA587, 0, TRUE, 2, EPLAPI_PI_SUBINDEX_COUNT); + if (Ret != kEplSuccessful) + { + goto Exit; + } + + Ret = EplApiProcessImageLinkRange(0xA640, 0xA643, 0, TRUE, 4, EPLAPI_PI_SUBINDEX_COUNT); + if (Ret != kEplSuccessful) + { + goto Exit; + } + + Ret = EplApiProcessImageLinkRange(0xA680, 0xA683, 0, TRUE, 4, EPLAPI_PI_SUBINDEX_COUNT); + if (Ret != kEplSuccessful) + { + goto Exit; + } + + Ret = EplApiProcessImageLinkRange(0xA880, 0xA881, 0, TRUE, 8, EPLAPI_PI_SUBINDEX_COUNT); + if (Ret != kEplSuccessful) + { + goto Exit; + } + + Ret = EplApiProcessImageLinkRange(0xA8C0, 0xA8C1, 0, TRUE, 8, EPLAPI_PI_SUBINDEX_COUNT); + if (Ret != kEplSuccessful) + { + goto Exit; + } + +Exit: + return Ret; +} + + + +//=========================================================================// +// // +// P R I V A T E F U N C T I O N S // +// // +//=========================================================================// + +//--------------------------------------------------------------------------- +// +// Function: EplApiProcessImageSetup() +// +// Description: sets up static process image +// +// Parameters: (none) +// +// Returns: tEplKernel = error code +// +// +// State: +// +//--------------------------------------------------------------------------- + +static tEplKernel EplApiProcessImageLinkRange( + unsigned int uiObjIndexStart_p, + unsigned int uiObjIndexEnd_p, + unsigned int uiOffsetPI_p, + BOOL fOutputPI_p, + tEplObdSize EntrySize_p, + unsigned int uiSubindexCountPerIndex_p) +{ +tEplKernel Ret = kEplSuccessful; +unsigned int uiVarEntries; + + for (; uiObjIndexStart_p <= uiObjIndexEnd_p; + uiObjIndexStart_p++, uiOffsetPI_p += EntrySize_p * uiSubindexCountPerIndex_p) + { + uiVarEntries = uiSubindexCountPerIndex_p; + Ret = EplApiProcessImageLinkObject( + uiObjIndexStart_p, + 1, + uiOffsetPI_p, + fOutputPI_p, + EntrySize_p, + &uiVarEntries); + if (((Ret == kEplSuccessful) && (uiVarEntries < uiSubindexCountPerIndex_p)) + || (Ret == kEplApiPISizeExceeded)) + { + Ret = kEplSuccessful; + break; + } + if (Ret != kEplSuccessful) + { + TRACE("EplApiProcessImageLinkObject returned: %xh for index %xh\n", Ret, uiObjIndexStart_p); + goto Exit; + } + } + +Exit: + return Ret; +} + + + +// EOF + diff --git a/pool/shard002/C/0062437_vmapiImageLockQueryDm.c b/pool/shard002/C/0062437_vmapiImageLockQueryDm.c new file mode 100644 index 0000000000000000000000000000000000000000..1902fd11bd6bfd049c0f5dd741fe2f3a7d443bff --- /dev/null +++ b/pool/shard002/C/0062437_vmapiImageLockQueryDm.c @@ -0,0 +1,80 @@ +/** + * Copyright 2017 IBM 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. + */ +#include "smSocket.h" +#include "vmapiImage.h" +#include "smapiTableParser.h" +#include +#include +#include + +#define PARSER_TABLE_NAME Image_Lock_Query_DM_Layout +#define OUTPUT_STRUCTURE_NAME vmApiImageLockQueryDmOutput + +/** + * Image_Lock_Query_DM SMAPI interface + */ +int smImage_Lock_Query_DM(struct _vmApiInternalContext* vmapiContextP, + char * userid, int passwordLength, char * password, + char * targetIdentifier, vmApiImageLockQueryDmOutput ** outData) { + const char * const functionName = "Image_Lock_Query_DM"; + tableParserParms parserParms; + int tempSize; + char * cursor; + int rc; + + int inputSize = 4 + 4 + strlen(functionName) + 4 + strlen(userid) + 4 + + passwordLength + 4 + strlen(targetIdentifier); + char * inputP = 0; + + // Build SMAPI input parameter buffer + if (0 == (inputP = malloc(inputSize))) + return MEMORY_ERROR; + cursor = inputP; + PUT_INT(inputSize - 4, cursor); + + tempSize = strlen(functionName); + PUT_INT(tempSize, cursor); + memcpy(cursor, functionName, tempSize); + cursor += tempSize; + + tempSize = strlen(userid); // UserId 1..8 or 0..8 chars + PUT_INT(tempSize, cursor); + if (tempSize > 0) { + memcpy(cursor, userid, tempSize); + cursor += tempSize; + } + + tempSize = passwordLength; // Password 1..200 or 0..200 chars + PUT_INT(tempSize, cursor); + if (tempSize > 0) { + memcpy(cursor, password, tempSize); + cursor += tempSize; + } + + tempSize = strlen(targetIdentifier); // Target identifier 1..8 + PUT_INT(tempSize, cursor); + memcpy(cursor, targetIdentifier, tempSize); + cursor += tempSize; + + + // This routine will send SMAPI the input, delete the input storage + // and call the table parser to set the output in outData + rc = getAndParseSmapiBuffer(vmapiContextP, &inputP, inputSize, + PARSER_TABLE_NAME, // Integer table + TO_STRING(PARSER_TABLE_NAME), // String name of the table + (char * *) outData); + return rc; +} diff --git a/pool/shard002/C/0062474_modem_example.c b/pool/shard002/C/0062474_modem_example.c new file mode 100644 index 0000000000000000000000000000000000000000..072f7fd7fe3980c33b3d98e4673907078688c6e6 --- /dev/null +++ b/pool/shard002/C/0062474_modem_example.c @@ -0,0 +1,112 @@ +// This example demonstates the digital modulator/demodulator +// (modem) object. Data symbols are modulated into complex +// samples which are then demodulated without noise or phase +// offsets. The user may select the modulation scheme via +// the command-line interface. + +#include +#include +#include +#include "liquid.h" + +#define OUTPUT_FILENAME "modem_example.m" + +// print usage/help message +void usage() +{ + printf("modem_example [options]\n"); + printf(" h : print help\n"); + printf(" v/q : verbose/quiet\n"); + printf(" m : modulation scheme (qam16 default)\n"); + liquid_print_modulation_schemes(); +} + + +int main(int argc, char*argv[]) +{ + // create mod/demod objects + modulation_scheme ms = LIQUID_MODEM_QAM16; + int verbose = 1; + + int dopt; + while ((dopt = getopt(argc,argv,"hvqm:")) != EOF) { + switch (dopt) { + case 'h': usage(); return 0; + case 'v': verbose = 1; break; + case 'q': verbose = 0; break; + case 'm': + ms = liquid_getopt_str2mod(optarg); + if (ms == LIQUID_MODEM_UNKNOWN) { + fprintf(stderr,"error: %s, unknown/unsupported modulation scheme '%s'\n", argv[0], optarg); + return 1; + } + break; + default: + exit(1); + } + } + + // create the modem objects + modemcf mod = modemcf_create(ms); + modemcf demod = modemcf_create(ms); + + // ensure bits/symbol matches modem description (only + // applicable to certain specific modems) + unsigned int bps = modemcf_get_bps(mod); + + modemcf_print(mod); + + // open output file + FILE*fid = fopen(OUTPUT_FILENAME,"w"); + fprintf(fid,"%% %s : auto-generated file\n", OUTPUT_FILENAME); + fprintf(fid,"clear all;\n"); + fprintf(fid,"close all;\n\n"); + fprintf(fid,"m = %u;\n", bps); + fprintf(fid,"M = %u;\n", 1< +#include +#include +#include +#include +#include +#include +#include +#include +#include "mb_sysconf.h" + +#define DUMP_ACPI_TABLES 0 + +#if DUMP_ACPI_TABLES == 1 +static void dump_mem(u32 start, u32 end) +{ + + u32 i; + print_debug("dump_mem:"); + for (i = start; i < end; i++) { + if ((i & 0xf) == 0) { + printk(BIOS_DEBUG, "\n%08x:", i); + } + printk(BIOS_DEBUG, " %02x", (u8)*((u8 *)i)); + } + print_debug("\n"); +} +#endif + +extern const unsigned char AmlCode[]; +extern const unsigned char AmlCode_ssdt[]; + +#if CONFIG_ACPI_SSDTX_NUM >= 1 +extern const unsigned char AmlCode_ssdt2[]; +extern const unsigned char AmlCode_ssdt3[]; +extern const unsigned char AmlCode_ssdt4[]; +extern const unsigned char AmlCode_ssdt5[]; +#endif + +unsigned long acpi_fill_mcfg(unsigned long current) +{ + /* Just a dummy */ + return current; +} + +unsigned long acpi_fill_madt(unsigned long current) +{ + /* create all subtables for processors */ + current = acpi_create_madt_lapics(current); + + /* Write SB700 IOAPIC, only one */ + current += acpi_create_madt_ioapic((acpi_madt_ioapic_t *) current, 2, + IO_APIC_ADDR, 0); + + current += acpi_create_madt_irqoverride((acpi_madt_irqoverride_t *) + current, 0, 0, 2, 0); + current += acpi_create_madt_irqoverride((acpi_madt_irqoverride_t *) + current, 0, 9, 9, 0xF); + /* 0: mean bus 0--->ISA */ + /* 0: PIC 0 */ + /* 2: APIC 2 */ + /* 5 mean: 0101 --> Edige-triggered, Active high */ + + /* create all subtables for processors */ + /* current = acpi_create_madt_lapic_nmis(current, 5, 1); */ + /* 1: LINT1 connect to NMI */ + + return current; +} + +unsigned long write_acpi_tables(unsigned long start) +{ + unsigned long current; + acpi_rsdp_t *rsdp; + acpi_rsdt_t *rsdt; + acpi_hpet_t *hpet; + acpi_madt_t *madt; + acpi_srat_t *srat; + acpi_slit_t *slit; + acpi_fadt_t *fadt; + acpi_facs_t *facs; + acpi_header_t *dsdt; + acpi_header_t *ssdt; +#if CONFIG_ACPI_SSDTX_NUM >= 1 + acpi_header_t *ssdtx; + void *p; + int i; +#endif + + get_bus_conf(); /* it will get sblk, pci1234, hcdn, and sbdn */ + + /* Align ACPI tables to 16 bytes */ + start = (start + 0x0f) & -0x10; + current = start; + + printk(BIOS_INFO, "ACPI: Writing ACPI tables at %lx...\n", start); + + /* We need at least an RSDP and an RSDT Table */ + rsdp = (acpi_rsdp_t *) current; + current += sizeof(acpi_rsdp_t); + rsdt = (acpi_rsdt_t *) current; + current += sizeof(acpi_rsdt_t); + + /* clear all table memory */ + memset((void *)start, 0, current - start); + + acpi_write_rsdp(rsdp, rsdt, NULL); + acpi_write_rsdt(rsdt); + + /* DSDT */ + current = ( current + 0x07) & -0x08; + printk(BIOS_DEBUG, "ACPI: * DSDT at %lx\n", current); + dsdt = (acpi_header_t *)current; // it will used by fadt + memcpy(dsdt, &AmlCode, sizeof(acpi_header_t)); + current += dsdt->length; + memcpy(dsdt, &AmlCode, dsdt->length); + printk(BIOS_DEBUG, "ACPI: * DSDT @ %p Length %x\n",dsdt,dsdt->length); + + /* FACS */ // it needs 64 bit alignment + current = ( current + 0x07) & -0x08; + printk(BIOS_DEBUG, "ACPI: * FACS at %lx\n", current); + facs = (acpi_facs_t *) current; // it will be used by fadt + current += sizeof(acpi_facs_t); + acpi_create_facs(facs); + + /* FADT */ + current = ( current + 0x07) & -0x08; + printk(BIOS_DEBUG, "ACPI: * FADT at %lx\n", current); + fadt = (acpi_fadt_t *) current; + current += sizeof(acpi_fadt_t); + + acpi_create_fadt(fadt, facs, dsdt); + acpi_add_table(rsdp, fadt); + + /* + * We explicitly add these tables later on: + */ + current = ( current + 0x07) & -0x08; + printk(BIOS_DEBUG, "ACPI: * HPET at %lx\n", current); + hpet = (acpi_hpet_t *) current; + current += sizeof(acpi_hpet_t); + acpi_create_hpet(hpet); + acpi_add_table(rsdp, hpet); + + /* If we want to use HPET Timers Linux wants an MADT */ + current = ( current + 0x07) & -0x08; + printk(BIOS_DEBUG, "ACPI: * MADT at %lx\n",current); + madt = (acpi_madt_t *) current; + acpi_create_madt(madt); + current += madt->header.length; + acpi_add_table(rsdp, madt); + + /* SRAT */ + current = ( current + 0x07) & -0x08; + printk(BIOS_DEBUG, "ACPI: * SRAT at %lx\n", current); + srat = (acpi_srat_t *) current; + acpi_create_srat(srat); + current += srat->header.length; + acpi_add_table(rsdp, srat); + + /* SLIT */ + current = ( current + 0x07) & -0x08; + printk(BIOS_DEBUG, "ACPI: * SLIT at %lx\n", current); + slit = (acpi_slit_t *) current; + acpi_create_slit(slit); + current += slit->header.length; + acpi_add_table(rsdp, slit); + + /* SSDT */ + current = ( current + 0x0f) & -0x10; + printk(BIOS_DEBUG, "ACPI: * SSDT at %lx\n", current); + ssdt = (acpi_header_t *)current; + memcpy(ssdt, &AmlCode_ssdt, sizeof(acpi_header_t)); + current += ssdt->length; + memcpy(ssdt, &AmlCode_ssdt, ssdt->length); + //Here you need to set value in pci1234, sblk and sbdn in get_bus_conf.c + update_ssdt((void*)ssdt); + /* recalculate checksum */ + ssdt->checksum = 0; + ssdt->checksum = acpi_checksum((unsigned char *)ssdt,ssdt->length); + acpi_add_table(rsdp,ssdt); + + printk(BIOS_DEBUG, "ACPI: * SSDT for PState at %lx\n", current); + current = acpi_add_ssdt_pstates(rsdp, current); + +#if CONFIG_ACPI_SSDTX_NUM >= 1 + + /* same htio, but different position? We may have to copy, + change HCIN, and recalculate the checknum and add_table */ + + for(i=1;ilength; + memcpy(ssdtx, p, ssdtx->length); + update_ssdtx((void *)ssdtx, i); + ssdtx->checksum = 0; + ssdtx->checksum = acpi_checksum((u8 *)ssdtx, ssdtx->length); + acpi_add_table(rsdp, ssdtx); + } +#endif + +#if DUMP_ACPI_TABLES == 1 + printk(BIOS_DEBUG, "rsdp\n"); + dump_mem(rsdp, ((void *)rsdp) + sizeof(acpi_rsdp_t)); + + printk(BIOS_DEBUG, "rsdt\n"); + dump_mem(rsdt, ((void *)rsdt) + sizeof(acpi_rsdt_t)); + + printk(BIOS_DEBUG, "madt\n"); + dump_mem(madt, ((void *)madt) + madt->header.length); + + printk(BIOS_DEBUG, "srat\n"); + dump_mem(srat, ((void *)srat) + srat->header.length); + + printk(BIOS_DEBUG, "slit\n"); + dump_mem(slit, ((void *)slit) + slit->header.length); + + printk(BIOS_DEBUG, "ssdt\n"); + dump_mem(ssdt, ((void *)ssdt) + ssdt->length); + + printk(BIOS_DEBUG, "fadt\n"); + dump_mem(fadt, ((void *)fadt) + fadt->header.length); +#endif + + printk(BIOS_INFO, "ACPI: done.\n"); + return current; +} diff --git a/pool/shard002/C/0062492_bipartite_match.c b/pool/shard002/C/0062492_bipartite_match.c new file mode 100644 index 0000000000000000000000000000000000000000..381627ec3d800a8fc7f97275dd4df0280509a389 --- /dev/null +++ b/pool/shard002/C/0062492_bipartite_match.c @@ -0,0 +1,180 @@ +/*------------------------------------------------------------------------- + * + * bipartite_match.c + * Hopcroft-Karp maximum cardinality algorithm for bipartite graphs + * + * This implementation is based on pseudocode found at: + * + * http://en.wikipedia.org/w/index.php?title=Hopcroft%E2%80%93Karp_algorithm&oldid=593898016 + * + * Copyright (c) 2015-2016, PostgreSQL Global Development Group + * + * IDENTIFICATION + * src/backend/lib/bipartite_match.c + * + *------------------------------------------------------------------------- + */ +#include "postgres.h" + +#include + +#include "lib/bipartite_match.h" +#include "miscadmin.h" + +/* + * The distances computed in hk_breadth_search can easily be seen to never + * exceed u_size. Since we restrict u_size to be less than SHRT_MAX, we + * can therefore use SHRT_MAX as the "infinity" distance needed as a marker. + */ +#define HK_INFINITY SHRT_MAX + +static bool hk_breadth_search(BipartiteMatchState *state); +static bool hk_depth_search(BipartiteMatchState *state, int u); + +/* + * Given the size of U and V, where each is indexed 1..size, and an adjacency + * list, perform the matching and return the resulting state. + */ +BipartiteMatchState * +BipartiteMatch(int u_size, int v_size, short **adjacency) +{ + BipartiteMatchState *state = palloc(sizeof(BipartiteMatchState)); + + if (u_size < 0 || u_size >= SHRT_MAX || + v_size < 0 || v_size >= SHRT_MAX) + elog(ERROR, "invalid set size for BipartiteMatch"); + + state->u_size = u_size; + state->v_size = v_size; + state->adjacency = adjacency; + state->matching = 0; + state->pair_uv = (short *) palloc0((u_size + 1) * sizeof(short)); + state->pair_vu = (short *) palloc0((v_size + 1) * sizeof(short)); + state->distance = (short *) palloc((u_size + 1) * sizeof(short)); + state->queue = (short *) palloc((u_size + 2) * sizeof(short)); + + while (hk_breadth_search(state)) + { + int u; + + for (u = 1; u <= u_size; u++) + { + if (state->pair_uv[u] == 0) + if (hk_depth_search(state, u)) + state->matching++; + } + + CHECK_FOR_INTERRUPTS(); /* just in case */ + } + + return state; +} + +/* + * Free a state returned by BipartiteMatch, except for the original adjacency + * list, which is owned by the caller. This only frees memory, so it's optional. + */ +void +BipartiteMatchFree(BipartiteMatchState *state) +{ + /* adjacency matrix is treated as owned by the caller */ + pfree(state->pair_uv); + pfree(state->pair_vu); + pfree(state->distance); + pfree(state->queue); + pfree(state); +} + +/* + * Perform the breadth-first search step of H-K matching. + * Returns true if successful. + */ +static bool +hk_breadth_search(BipartiteMatchState *state) +{ + int usize = state->u_size; + short *queue = state->queue; + short *distance = state->distance; + int qhead = 0; /* we never enqueue any node more than once */ + int qtail = 0; /* so don't have to worry about wrapping */ + int u; + + distance[0] = HK_INFINITY; + + for (u = 1; u <= usize; u++) + { + if (state->pair_uv[u] == 0) + { + distance[u] = 0; + queue[qhead++] = u; + } + else + distance[u] = HK_INFINITY; + } + + while (qtail < qhead) + { + u = queue[qtail++]; + + if (distance[u] < distance[0]) + { + short *u_adj = state->adjacency[u]; + int i = u_adj ? u_adj[0] : 0; + + for (; i > 0; i--) + { + int u_next = state->pair_vu[u_adj[i]]; + + if (distance[u_next] == HK_INFINITY) + { + distance[u_next] = 1 + distance[u]; + Assert(qhead < usize + 2); + queue[qhead++] = u_next; + } + } + } + } + + return (distance[0] != HK_INFINITY); +} + +/* + * Perform the depth-first search step of H-K matching. + * Returns true if successful. + */ +static bool +hk_depth_search(BipartiteMatchState *state, int u) +{ + short *distance = state->distance; + short *pair_uv = state->pair_uv; + short *pair_vu = state->pair_vu; + short *u_adj = state->adjacency[u]; + int i = u_adj ? u_adj[0] : 0; + short nextdist; + + if (u == 0) + return true; + if (distance[u] == HK_INFINITY) + return false; + nextdist = distance[u] + 1; + + check_stack_depth(); + + for (; i > 0; i--) + { + int v = u_adj[i]; + + if (distance[pair_vu[v]] == nextdist) + { + if (hk_depth_search(state, pair_vu[v])) + { + pair_vu[v] = u; + pair_uv[u] = v; + return true; + } + } + } + + distance[u] = HK_INFINITY; + return false; +} diff --git a/pool/shard002/C/0062496_os_info.c b/pool/shard002/C/0062496_os_info.c new file mode 100644 index 0000000000000000000000000000000000000000..fe284addad0c6b3d1984b9968ebd94389b59fc30 --- /dev/null +++ b/pool/shard002/C/0062496_os_info.c @@ -0,0 +1,319 @@ +/* $Id$ */ +/* + * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com) + * Copyright (C) 2003-2008 Benny Prijono + * + * 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 + +/* + * FYI these links contain useful infos about predefined macros across + * platforms: + * - http://predef.sourceforge.net/preos.html + */ + +#if defined(PJ_HAS_SYS_UTSNAME_H) && PJ_HAS_SYS_UTSNAME_H != 0 +/* For uname() */ +# include +# include +# define PJ_HAS_UNAME 1 +#endif + +#if defined(PJ_HAS_LIMITS_H) && PJ_HAS_LIMITS_H != 0 +/* Include to get to get various glibc macros. + * See http://predef.sourceforge.net/prelib.html + */ +# include +#endif + +#if defined(_MSC_VER) +/* For all Windows including mobile */ +# include +#endif + +#if defined(PJ_DARWINOS) && PJ_DARWINOS != 0 +# include "TargetConditionals.h" +#endif + +#ifndef PJ_SYS_INFO_BUFFER_SIZE +# define PJ_SYS_INFO_BUFFER_SIZE 64 +#endif + + +#if defined(PJ_DARWINOS) && PJ_DARWINOS != 0 && TARGET_OS_IPHONE + void pj_iphone_os_get_sys_info(pj_sys_info *si, pj_str_t *si_buffer); +#endif + +#if defined(PJ_SYMBIAN) && PJ_SYMBIAN != 0 + PJ_BEGIN_DECL + unsigned pj_symbianos_get_model_info(char *buf, unsigned buf_size); + unsigned pj_symbianos_get_platform_info(char *buf, unsigned buf_size); + void pj_symbianos_get_sdk_info(pj_str_t *name, pj_uint32_t *ver); + PJ_END_DECL +#endif + + +static char *ver_info(pj_uint32_t ver, char *buf) +{ + int len; + + if (ver == 0) { + *buf = '\0'; + return buf; + } + + sprintf(buf, "-%u.%u", + (ver & 0xFF000000) >> 24, + (ver & 0x00FF0000) >> 16); + len = strlen(buf); + + if (ver & 0xFFFF) { + sprintf(buf+len, ".%u", (ver & 0xFF00) >> 8); + len = strlen(buf); + + if (ver & 0x00FF) { + sprintf(buf+len, ".%u", (ver & 0xFF)); + } + } + + return buf; +} + +static pj_uint32_t parse_version(char *str) +{ + char *tok; + int i, maxtok; + pj_uint32_t version = 0; + + while (*str && !pj_isdigit(*str)) + str++; + + maxtok = 4; + for (tok = strtok(str, ".-"), i=0; tok && i= len+1) { \ + si.field.ptr = si_buffer + PJ_SYS_INFO_BUFFER_SIZE - left; \ + si.field.slen = len; \ + pj_memcpy(si.field.ptr, str, len+1); \ + left -= (len+1); \ + } \ + } while (0) + + /* + * Machine and OS info. + */ +#if defined(PJ_HAS_UNAME) && PJ_HAS_UNAME + #if defined(PJ_DARWINOS) && PJ_DARWINOS != 0 && TARGET_OS_IPHONE && \ + (!defined TARGET_IPHONE_SIMULATOR || TARGET_IPHONE_SIMULATOR == 0) + { + pj_str_t buf = {si_buffer + PJ_SYS_INFO_BUFFER_SIZE - left, left}; + pj_str_t machine = {"arm", 3}; + pj_str_t sdk_name = {"iOS-SDK", 7}; + char tmp[PJ_SYS_INFO_BUFFER_SIZE]; + + pj_iphone_os_get_sys_info(&si, &buf); + left -= si.os_name.slen + 1; + + si.os_ver = parse_version(si.machine.ptr); + + si.machine = machine; + si.sdk_name = sdk_name; + + #ifdef PJ_SDK_NAME + pj_memcpy(tmp, PJ_SDK_NAME, pj_ansi_strlen(PJ_SDK_NAME) + 1); + si.sdk_ver = parse_version(tmp); + #endif + } + #else + { + struct utsname u; + + /* Successful uname() returns zero on Linux and positive value + * on OpenSolaris. + */ + if (uname(&u) == -1) + goto get_sdk_info; + + ALLOC_CP_STR(u.machine, machine); + ALLOC_CP_STR(u.sysname, os_name); + + si.os_ver = parse_version(u.release); + } + #endif +#elif defined(_MSC_VER) + { + OSVERSIONINFO ovi; + + ovi.dwOSVersionInfoSize = sizeof(ovi); + + if (GetVersionEx(&ovi) == FALSE) + goto get_sdk_info; + + si.os_ver = (ovi.dwMajorVersion << 24) | + (ovi.dwMinorVersion << 16); + #if defined(PJ_WIN32_WINCE) && PJ_WIN32_WINCE + si.os_name = pj_str("wince"); + #else + si.os_name = pj_str("win32"); + #endif + } + + { + SYSTEM_INFO wsi; + + GetSystemInfo(&wsi); + switch (wsi.wProcessorArchitecture) { + #if defined(PJ_WIN32_WINCE) && PJ_WIN32_WINCE + case PROCESSOR_ARCHITECTURE_ARM: + si.machine = pj_str("arm"); + break; + case PROCESSOR_ARCHITECTURE_SHX: + si.machine = pj_str("shx"); + break; + #else + case PROCESSOR_ARCHITECTURE_AMD64: + si.machine = pj_str("x86_64"); + break; + case PROCESSOR_ARCHITECTURE_IA64: + si.machine = pj_str("ia64"); + break; + case PROCESSOR_ARCHITECTURE_INTEL: + si.machine = pj_str("i386"); + break; + #endif /* PJ_WIN32_WINCE */ + } + } +#elif defined(PJ_SYMBIAN) && PJ_SYMBIAN != 0 + { + pj_symbianos_get_model_info(si_buffer, sizeof(si_buffer)); + ALLOC_CP_STR(si_buffer, machine); + + char *p = si_buffer + sizeof(si_buffer) - left; + unsigned plen; + plen = pj_symbianos_get_platform_info(p, left); + if (plen) { + /* Output format will be "Series60vX.X" */ + si.os_name = pj_str("S60"); + si.os_ver = parse_version(p+9); + } else { + si.os_name = pj_str("Unknown"); + } + } +#endif + + /* + * SDK info. + */ +get_sdk_info: + +#if defined(__GLIBC__) + si.sdk_ver = (__GLIBC__ << 24) | + (__GLIBC_MINOR__ << 16); + si.sdk_name = pj_str("glibc"); +#elif defined(__GNU_LIBRARY__) + si.sdk_ver = (__GNU_LIBRARY__ << 24) | + (__GNU_LIBRARY_MINOR__ << 16); + si.sdk_name = pj_str("libc"); +#elif defined(__UCLIBC__) + si.sdk_ver = (__UCLIBC_MAJOR__ << 24) | + (__UCLIBC_MINOR__ << 16); + si.sdk_name = pj_str("uclibc"); +#elif defined(_WIN32_WCE) && _WIN32_WCE + /* Old window mobile declares _WIN32_WCE as decimal (e.g. 300, 420, etc.), + * but then it was changed to use hex, e.g. 0x420, etc. See + * http://social.msdn.microsoft.com/forums/en-US/vssmartdevicesnative/thread/8a97c59f-5a1c-4bc6-99e6-427f065ff439/ + */ + #if _WIN32_WCE <= 500 + si.sdk_ver = ( (_WIN32_WCE / 100) << 24) | + ( ((_WIN32_WCE % 100) / 10) << 16) | + ( (_WIN32_WCE % 10) << 8); + #else + si.sdk_ver = ( ((_WIN32_WCE & 0xFF00) >> 8) << 24) | + ( ((_WIN32_WCE & 0x00F0) >> 4) << 16) | + ( ((_WIN32_WCE & 0x000F) >> 0) << 8); + #endif + si.sdk_name = pj_str("cesdk"); +#elif defined(_MSC_VER) + /* No SDK info is easily obtainable for Visual C, so lets just use + * _MSC_VER. The _MSC_VER macro reports the major and minor versions + * of the compiler. For example, 1310 for Microsoft Visual C++ .NET 2003. + * 1310 represents version 13 and a 1.0 point release. + * The Visual C++ 2005 compiler version is 1400. + */ + si.sdk_ver = ((_MSC_VER / 100) << 24) | + (((_MSC_VER % 100) / 10) << 16) | + ((_MSC_VER % 10) << 8); + si.sdk_name = pj_str("msvc"); +#elif defined(PJ_SYMBIAN) && PJ_SYMBIAN != 0 + pj_symbianos_get_sdk_info(&si.sdk_name, &si.sdk_ver); +#endif + + /* + * Build the info string. + */ + { + char tmp[PJ_SYS_INFO_BUFFER_SIZE]; + char os_ver[20], sdk_ver[20]; + int cnt; + + cnt = pj_ansi_snprintf(tmp, sizeof(tmp), + "%s%s%s%s%s%s%s", + si.os_name.ptr, + ver_info(si.os_ver, os_ver), + (si.machine.slen ? "/" : ""), + si.machine.ptr, + (si.sdk_name.slen ? "/" : ""), + si.sdk_name.ptr, + ver_info(si.sdk_ver, sdk_ver)); + if (cnt > 0 && cnt < (int)sizeof(tmp)) { + ALLOC_CP_STR(tmp, info); + } + } + + si_initialized = PJ_TRUE; + return &si; +} diff --git a/pool/shard002/C/0062512_msm_show_resume_irq.c b/pool/shard002/C/0062512_msm_show_resume_irq.c new file mode 100644 index 0000000000000000000000000000000000000000..217a430403f81b3482620feedfac0414a6b3d86e --- /dev/null +++ b/pool/shard002/C/0062512_msm_show_resume_irq.c @@ -0,0 +1,77 @@ +/* Copyright (c) 2011, Code Aurora Forum. 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. + * + * 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 +#include + +/****************************************************************************** + * Debug Definitions + *****************************************************************************/ + +enum { + MSM_SHOW_IRQ_DEBUG_RESUME = BIT(0), +}; + +static int msm_show_resume_irq_mask = MSM_SHOW_IRQ_DEBUG_RESUME; +module_param_named( + debug_mask, msm_show_resume_irq_mask, int, S_IRUGO | S_IWUSR | S_IWGRP +); + +static int msm_show_resume_irq_resume(struct sys_device *dev) +{ + if (msm_show_resume_irq_mask & MSM_SHOW_IRQ_DEBUG_RESUME) { + gic_show_resume_irq(0); + msm_gpio_show_resume_irq(); + pm8058_show_resume_irq(); + } + return 0; +} + +static struct sysdev_class msm_show_resume_irq_sysclass = { + .name = "msm_show_resume_irq", + .resume = msm_show_resume_irq_resume, +}; + +static struct sys_device msm_show_resume_irq_device = { + .cls = &msm_show_resume_irq_sysclass, +}; + +static int __init msm_show_resume_irq_init(void) +{ + int ret = -ENODEV; + + ret = sysdev_class_register(&msm_show_resume_irq_sysclass); + if (ret == 0) + ret = sysdev_register(&msm_show_resume_irq_device); + return ret; +} + +static void __exit msm_show_resume_irq_exit(void) +{ + sysdev_unregister(&msm_show_resume_irq_device); + sysdev_class_unregister(&msm_show_resume_irq_sysclass); +} + +module_init(msm_show_resume_irq_init); +module_exit(msm_show_resume_irq_exit); diff --git a/pool/shard002/C/0062513_testwifi.c b/pool/shard002/C/0062513_testwifi.c new file mode 100644 index 0000000000000000000000000000000000000000..01f17d8c4d301701a4c6cdbd3332e77f53429eab --- /dev/null +++ b/pool/shard002/C/0062513_testwifi.c @@ -0,0 +1,194 @@ +/** + * Tester program for 'thing'. + * + * This program sends commands through the wifi link in order to move the + * servos. See its command line options for usage. + * + * Copyright (C) 2015 Paolo Scaramuzza + */ +#include +#include +#include +#include +#include +#include // requires libbsd-dev +#include +#include +#include +#include + +#include "include/board.h" // use the same header as the firmware + +#define BOARD_IP "192.168.4.1" +#define BOARD_PORT 333 + +const char* USAGE_STR = "Usage: %s [options] [value]\n\n" + "Options:\n" + " -a\tSet the angle value\n" + " -c\tSet maximum current\n" + " -h\tDisplay this help text\n" + " -m\tChange operating mode (A, H or F)\n" + " -n\tSet servo number\n" + " -s\tSet rotation speed\n"; + +void parseCmdLine(int argc, char *argv[],int* m_ptr, int*n_ptr, int* a_ptr, + int* s_ptr, int* c_ptr) +{ + int opt; + while ((opt = getopt(argc, argv, "ha:c:m:n:s:")) != -1) { + const char* errstr; + switch (opt) + { + case 'a': + *a_ptr = strtonum(optarg, 0, 180, &errstr); + if (errstr != NULL) { + fprintf(stderr, "Could not parse the angle. Reason: %s\n", + errstr); + exit(EXIT_FAILURE); + } + break; + case 'c': + *c_ptr = strtonum(optarg, 0, 255, &errstr); + if (errstr != NULL) { + fprintf(stderr, "Could not parse the current. Reason: %s\n", + errstr); + exit(EXIT_FAILURE); + } + break; + case 'h': + printf(USAGE_STR, argv[0]); + exit(0); + break; + case 'm': + if (*optarg == 'F') + *m_ptr = WIFI_MODE_FOLLOW; + else if (*optarg == 'A') + *m_ptr = WIFI_MODE_ANGLE; + else if (*optarg == 'H') + *m_ptr = WIFI_MODE_HOLD; + else { + fprintf(stderr, "Invalid mode: %s. Expected F, A or H\n", + optarg); + exit(EXIT_FAILURE); + } + break; + case 'n': + *n_ptr = strtonum(optarg, 0, 5, &errstr); + if (errstr != NULL) { + fprintf(stderr, "Could not parse the servo number." + " Reason: %s\n", errstr); + exit(EXIT_FAILURE); + } + break; + case 's': + *s_ptr = strtonum(optarg, 0, 255, &errstr); + if (errstr != NULL) { + fprintf(stderr, "Could not parse the speed. Reason: %s\n", + errstr); + exit(EXIT_FAILURE); + } + break; + default: + fprintf(stderr, USAGE_STR, argv[0]); + exit(EXIT_FAILURE); + } + } +} + +int main(int argc, char *argv[]) +{ + int mode = -1; + int servo_number = -1; + int angle = -1; + int speed = -1; + int current = -1; + + if (argc == 1) { + printf("Nothing to do.\n"); + fprintf(stderr, USAGE_STR, argv[0]); + return 0; + } + + parseCmdLine(argc, argv, &mode, &servo_number, &angle, &speed, ¤t); + + // check command line options + if (((angle != -1) || (speed != -1) || (current != -1)) + && (servo_number == -1)) { + fprintf(stderr, "Please provide a servo to move\n"); + exit(EXIT_FAILURE); + } + + // We can open the connection now + int socket_desc = socket(AF_INET , SOCK_STREAM , 0); + if (socket_desc == -1) { + fprintf(stderr, "Could not create socket.\n"); + exit(EXIT_FAILURE); + } + + struct sockaddr_in board; + board.sin_addr.s_addr = inet_addr(BOARD_IP); + board.sin_family = AF_INET; + board.sin_port = htons(BOARD_PORT); + + if (connect(socket_desc, (struct sockaddr *)&board , sizeof(board)) < 0) + { + fprintf(stderr, "Error connecting to target board\n"); + exit(EXIT_FAILURE); + } + struct timeval tv; + tv.tv_sec = 1; + tv.tv_usec = 0; + setsockopt(socket_desc, SOL_SOCKET, SO_RCVTIMEO, (char *)&tv, + sizeof(struct timeval)); + + union wifiCommand_le cmd; + union wifiCommand answer; + + if (mode != -1) { // change mode first + cmd.field.command = WIFI_SET_MODE; + cmd.field.data = mode; + int retval = -1; + while (retval < 0) { + send(socket_desc , &cmd, sizeof(cmd), 0); + retval = read(socket_desc, &answer, sizeof(answer)); + } + } + + if (angle != -1) { + cmd.field.command = WIFI_SET_ANGLE; + cmd.field.servo = servo_number; + cmd.field.data = angle; + + int retval = -1; + while (retval < 0) { + send(socket_desc , &cmd, sizeof(cmd), 0); + retval = read(socket_desc, &answer, sizeof(answer)); + } + } + + if (current != -1) { + cmd.field.command = WIFI_SET_CURRENT; + cmd.field.servo = servo_number; + cmd.field.data = current; + + int retval = -1; + while (retval < 0) { + send(socket_desc , &cmd, sizeof(cmd), 0); + retval = read(socket_desc, &answer, sizeof(answer)); + } + } + + if (speed != -1) { + cmd.field.command = WIFI_SET_SPEED; + cmd.field.servo = servo_number; + cmd.field.data = speed; + + int retval = -1; + while (retval < 0) { + send(socket_desc , &cmd, sizeof(cmd), 0); + retval = read(socket_desc, &answer, sizeof(answer)); + } + } + + return 0; +} diff --git a/pool/shard002/C/0062528_rap_server.c b/pool/shard002/C/0062528_rap_server.c new file mode 100644 index 0000000000000000000000000000000000000000..fc2d3aa611d288d6124f345d19b09111932bfc90 --- /dev/null +++ b/pool/shard002/C/0062528_rap_server.c @@ -0,0 +1,96 @@ +/* + Unix SMB/CIFS implementation. + RAP handlers + + Copyright (C) Volker Lendecke 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 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 "includes.h" +#include "param/share.h" +#include "../librpc/gen_ndr/rap.h" +#include "libcli/raw/interfaces.h" +#include "librpc/gen_ndr/srvsvc.h" +#include "librpc/gen_ndr/dcerpc.h" +#include "rpc_server/common/common.h" +#include "rpc_server/common/share.h" +#include "param/param.h" +#include "ntvfs/ipc/ipc.h" +#include "ntvfs/ipc/proto.h" + +/* At this moment these are just dummy functions, but you might get the + * idea. */ + +NTSTATUS rap_netshareenum(TALLOC_CTX *mem_ctx, + struct tevent_context *event_ctx, + struct loadparm_context *lp_ctx, + struct rap_NetShareEnum *r) +{ + NTSTATUS nterr; + const char **snames; + struct share_context *sctx; + struct share_config *scfg; + int i, j, count; + + r->out.status = 0; + r->out.available = 0; + r->out.info = NULL; + + nterr = share_get_context_by_name(mem_ctx, lpcfg_share_backend(lp_ctx), event_ctx, lp_ctx, &sctx); + if (!NT_STATUS_IS_OK(nterr)) { + return nterr; + } + + nterr = share_list_all(mem_ctx, sctx, &count, &snames); + if (!NT_STATUS_IS_OK(nterr)) { + return nterr; + } + + r->out.available = count; + r->out.info = talloc_array(mem_ctx, + union rap_share_info, r->out.available); + + for (i = 0, j = 0; i < r->out.available; i++) { + size_t sname_len; + + if (!NT_STATUS_IS_OK(share_get_config(mem_ctx, sctx, snames[i], &scfg))) { + DEBUG(3, ("WARNING: Service [%s] disappeared after enumeration!\n", snames[i])); + continue; + } + /* Make sure we have NUL-termination */ + sname_len = MIN(strlen(snames[i]), + sizeof(r->out.info[j].info1.share_name)); + strlcpy((char *)r->out.info[j].info1.share_name, + snames[i], + sname_len); + r->out.info[i].info1.reserved1 = 0; + r->out.info[i].info1.share_type = dcesrv_common_get_share_type(mem_ctx, NULL, scfg); + r->out.info[i].info1.comment = share_string_option(mem_ctx, scfg, SHARE_COMMENT, ""); + talloc_free(scfg); + j++; + } + r->out.available = j; + + return NT_STATUS_OK; +} + +NTSTATUS rap_netserverenum2(TALLOC_CTX *mem_ctx, + struct loadparm_context *lp_ctx, + struct rap_NetServerEnum2 *r) +{ + r->out.status = 0; + r->out.available = 0; + return NT_STATUS_OK; +} diff --git a/pool/shard002/C/0062546_iu091_eeprom.c b/pool/shard002/C/0062546_iu091_eeprom.c new file mode 100644 index 0000000000000000000000000000000000000000..a192830ac50fd09e447ee816f5aec2db71c264e8 --- /dev/null +++ b/pool/shard002/C/0062546_iu091_eeprom.c @@ -0,0 +1,220 @@ +/* Copyright (c) 2012, Code Aurora Forum. 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. + * + */ +/***********************************************************************/ +/* Modified by */ +/* (C) NEC CASIO Mobile Communications, Ltd. 2013 */ +/***********************************************************************/ + +#include +#include "msm_camera_eeprom.h" +#include "msm_camera_i2c.h" + + +#define IU091_EEPROM_BANK_SEL_REG 0x34C9 + + + DEFINE_MUTEX(iu091_eeprom_mutex); +static struct msm_eeprom_ctrl_t iu091_eeprom_t; + +static const struct i2c_device_id iu091_eeprom_i2c_id[] = { + {"iu091_eeprom", (kernel_ulong_t)&iu091_eeprom_t}, + { } +}; + +static struct i2c_driver iu091_eeprom_i2c_driver = { + .id_table = iu091_eeprom_i2c_id, + .probe = msm_eeprom_i2c_probe, + .remove = __exit_p(iu091_eeprom_i2c_remove), + .driver = { + .name = "iu091_eeprom", + }, +}; + +static int __init iu091_eeprom_i2c_add_driver(void) +{ + int rc = 0; + rc = i2c_add_driver(iu091_eeprom_t.i2c_driver); + return rc; +} + + +void iu091_set_dev_addr(struct msm_eeprom_ctrl_t *eclient, + uint32_t *reg_addr) { + uint32_t eprom_addr = *reg_addr; + msm_camera_i2c_write(&eclient->i2c_client, IU091_EEPROM_BANK_SEL_REG, + (eprom_addr & 0xFF) >> 3, MSM_CAMERA_I2C_BYTE_DATA); +} + + +static struct v4l2_subdev_core_ops iu091_eeprom_subdev_core_ops = { + .ioctl = msm_eeprom_subdev_ioctl, +}; + +static struct v4l2_subdev_ops iu091_eeprom_subdev_ops = { + .core = &iu091_eeprom_subdev_core_ops, +}; + + + + + + +uint8_t iu091_otp_data_1[8]; +uint8_t iu091_otp_data_2[6]; +uint8_t iu091_otp_data_3[90]; +uint16_t iu091_calibration_data_1[4]; +uint16_t iu091_calibration_data_2[3]; + + +static struct msm_camera_eeprom_info_t iu091_calib_supp_info = { + + + + + + {TRUE, sizeof(iu091_calibration_data_1), 0, 1}, + {TRUE, sizeof(iu091_calibration_data_2), 1, 1024}, + {FALSE, 0, 0, 1}, + + + {FALSE, 0, 0, 1}, + + +}; + +static struct msm_camera_eeprom_read_t iu091_eeprom_read_tbl[] = { + + + + {0x350E, &iu091_otp_data_1[0], 2, 0}, + {0x3510, &iu091_otp_data_1[2], 6, 0}, + {0x3508, &iu091_otp_data_2[0], 6, 0}, + {0x3518, &iu091_otp_data_3[0], 8, 0}, + {0x3520, &iu091_otp_data_3[8], 8, 0}, + {0x3528, &iu091_otp_data_3[16], 8, 0}, + {0x3530, &iu091_otp_data_3[24], 8, 0}, + {0x3538, &iu091_otp_data_3[32], 8, 0}, + {0x3540, &iu091_otp_data_3[40], 8, 0}, + {0x3548, &iu091_otp_data_3[48], 8, 0}, + {0x3550, &iu091_otp_data_3[56], 8, 0}, + {0x3558, &iu091_otp_data_3[64], 8, 0}, + {0x3560, &iu091_otp_data_3[72], 8, 0}, + {0x3568, &iu091_otp_data_3[80], 8, 0}, + {0x3570, &iu091_otp_data_3[88], 2, 0}, + +}; + + +static struct msm_camera_eeprom_data_t iu091_eeprom_data_tbl[] = { + + + + {&iu091_calibration_data_1, sizeof(iu091_calibration_data_1)}, + {&iu091_calibration_data_2, sizeof(iu091_calibration_data_2)}, + {&iu091_otp_data_3, sizeof(iu091_otp_data_3)}, + +}; + + + + + + + + + + + + + + + + + + + + + + +static void iu091_format_data_1(void) +{ + iu091_calibration_data_1[0] = (uint16_t)(iu091_otp_data_1[0] << 8) | + iu091_otp_data_1[1]; + iu091_calibration_data_1[1] = (uint16_t)(iu091_otp_data_1[2] << 8) | + iu091_otp_data_1[3]; + iu091_calibration_data_1[2] = (uint16_t)(iu091_otp_data_1[4] << 8) | + iu091_otp_data_1[5]; + iu091_calibration_data_1[3] = (uint16_t)(iu091_otp_data_1[6] << 8) | + iu091_otp_data_1[7]; +} + +static void iu091_format_data_2(void) +{ + iu091_calibration_data_2[0] = (uint16_t)(iu091_otp_data_2[0] << 8) | + iu091_otp_data_2[1]; + iu091_calibration_data_2[1] = (uint16_t)(iu091_otp_data_2[2] << 8) | + iu091_otp_data_2[3]; + iu091_calibration_data_2[2] = (uint16_t)(iu091_otp_data_2[4] << 8) | + iu091_otp_data_2[5]; +} + + + +void iu091_format_calibrationdata(void) +{ + + + + iu091_format_data_1(); + iu091_format_data_2(); + +} +static struct msm_eeprom_ctrl_t iu091_eeprom_t = { + .i2c_driver = &iu091_eeprom_i2c_driver, + + + .i2c_addr = 0x34, + + .eeprom_v4l2_subdev_ops = &iu091_eeprom_subdev_ops, + + .i2c_client = { + + + .addr_type = MSM_CAMERA_I2C_WORD_ADDR, + + }, + + .eeprom_mutex = &iu091_eeprom_mutex, + + .func_tbl = { + .eeprom_init = NULL, + .eeprom_release = NULL, + .eeprom_get_info = msm_camera_eeprom_get_info, + .eeprom_get_data = msm_camera_eeprom_get_data, + + + .eeprom_set_dev_addr = iu091_set_dev_addr, + + .eeprom_format_data = iu091_format_calibrationdata, + }, + .info = &iu091_calib_supp_info, + .info_size = sizeof(struct msm_camera_eeprom_info_t), + .read_tbl = iu091_eeprom_read_tbl, + .read_tbl_size = ARRAY_SIZE(iu091_eeprom_read_tbl), + .data_tbl = iu091_eeprom_data_tbl, + .data_tbl_size = ARRAY_SIZE(iu091_eeprom_data_tbl), +}; + +subsys_initcall(iu091_eeprom_i2c_add_driver); +MODULE_DESCRIPTION("iu091 EEPROM"); +MODULE_LICENSE("GPL v2"); diff --git a/pool/shard002/C/0062547_xen_apic.c b/pool/shard002/C/0062547_xen_apic.c new file mode 100644 index 0000000000000000000000000000000000000000..a95878227262db2f531f31845566888dd7b2068c --- /dev/null +++ b/pool/shard002/C/0062547_xen_apic.c @@ -0,0 +1,95 @@ +/* + * Xen basic APIC support + * + * Copyright (c) 2012 Citrix + * + * Authors: + * Wei Liu + * + * This work is licensed under the terms of the GNU GPL version 2 or + * later. See the COPYING file in the top-level directory. + */ +#include "hw/i386/apic_internal.h" +#include "hw/pci/msi.h" +#include "hw/xen/xen.h" + +static uint64_t xen_apic_mem_read(void *opaque, hwaddr addr, + unsigned size) +{ + return ~(uint64_t)0; +} + +static void xen_apic_mem_write(void *opaque, hwaddr addr, + uint64_t data, unsigned size) +{ + if (size != sizeof(uint32_t)) { + fprintf(stderr, "Xen: APIC write data size = %d, invalid\n", size); + return; + } + + xen_hvm_inject_msi(addr, data); +} + +static const MemoryRegionOps xen_apic_io_ops = { + .read = xen_apic_mem_read, + .write = xen_apic_mem_write, + .endianness = DEVICE_NATIVE_ENDIAN, +}; + +static void xen_apic_init(APICCommonState *s) +{ + memory_region_init_io(&s->io_memory, &xen_apic_io_ops, s, "xen-apic-msi", + APIC_SPACE_SIZE); + +#if defined(CONFIG_XEN_CTRL_INTERFACE_VERSION) \ + && CONFIG_XEN_CTRL_INTERFACE_VERSION >= 420 + msi_supported = true; +#endif +} + +static void xen_apic_set_base(APICCommonState *s, uint64_t val) +{ +} + +static void xen_apic_set_tpr(APICCommonState *s, uint8_t val) +{ +} + +static uint8_t xen_apic_get_tpr(APICCommonState *s) +{ + return 0; +} + +static void xen_apic_vapic_base_update(APICCommonState *s) +{ +} + +static void xen_apic_external_nmi(APICCommonState *s) +{ +} + +static void xen_apic_class_init(ObjectClass *klass, void *data) +{ + APICCommonClass *k = APIC_COMMON_CLASS(klass); + + k->init = xen_apic_init; + k->set_base = xen_apic_set_base; + k->set_tpr = xen_apic_set_tpr; + k->get_tpr = xen_apic_get_tpr; + k->vapic_base_update = xen_apic_vapic_base_update; + k->external_nmi = xen_apic_external_nmi; +} + +static const TypeInfo xen_apic_info = { + .name = "xen-apic", + .parent = TYPE_APIC_COMMON, + .instance_size = sizeof(APICCommonState), + .class_init = xen_apic_class_init, +}; + +static void xen_apic_register_types(void) +{ + type_register_static(&xen_apic_info); +} + +type_init(xen_apic_register_types) diff --git a/pool/shard002/C/0062549_main.c b/pool/shard002/C/0062549_main.c new file mode 100644 index 0000000000000000000000000000000000000000..1f27d36a7a856e1d4443165f616ed0cd3d0ec71c --- /dev/null +++ b/pool/shard002/C/0062549_main.c @@ -0,0 +1,104 @@ +/* + ChibiOS - Copyright (C) 2006..2018 Giovanni Di Sirio + + 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 "ch.h" + +#if !defined(SYSTEM_CLOCK) +#define SYSTEM_CLOCK 8000000U +#endif + +/* + * @brief System Timer handler. + */ +CH_IRQ_HANDLER(SysTick_Handler) { + + CH_IRQ_PROLOGUE(); + + chSysLockFromISR(); + chSysTimerHandlerI(); + chSysUnlockFromISR(); + + CH_IRQ_EPILOGUE(); +} + +static uint32_t seconds_counter; +static uint32_t minutes_counter; + +/* + * Seconds counter thread. + */ +static THD_WORKING_AREA(waThread1, 128); +static THD_FUNCTION(Thread1, arg) { + + (void)arg; + + while (true) { + chThdSleepMilliseconds(1000); + seconds_counter++; + } +} + +/* + * Minutes counter thread. + */ +static THD_WORKING_AREA(waThread2, 128); +static THD_FUNCTION(Thread2, arg) { + + (void)arg; + + while (true) { + chThdSleepSeconds(60); + minutes_counter++; + } +} + +/* + * Threads static table, one entry per thread. The number of entries must + * match NIL_CFG_NUM_THREADS. + */ +THD_TABLE_BEGIN +THD_TABLE_ENTRY(waThread1, "counter1", Thread1, NULL) +THD_TABLE_ENTRY(waThread2, "counter2", Thread2, NULL) +THD_TABLE_END + +/* + * Application entry point. + */ +int main(void) { + + /* + * Hardware initialization, in this simple demo just the systick timer is + * initialized. + */ + SysTick->LOAD = SYSTEM_CLOCK / CH_CFG_ST_FREQUENCY - (systime_t)1; + SysTick->VAL = (uint32_t)0; + SysTick->CTRL = SysTick_CTRL_CLKSOURCE_Msk | SysTick_CTRL_ENABLE_Msk | + SysTick_CTRL_TICKINT_Msk; + + /* + * System initializations. + * - Kernel initialization, the main() function becomes a thread and the + * RTOS is active. + */ + chSysInit(); + + /* This is now the idle thread loop, you may perform here a low priority + task but you must never try to sleep or wait in this loop. Note that + this tasks runs at the lowest priority level so any instruction added + here will be executed after all other tasks have been started.*/ + while (true) { + } +} diff --git a/pool/shard002/C/0062557_zip.c b/pool/shard002/C/0062557_zip.c new file mode 100644 index 0000000000000000000000000000000000000000..5fe8e91b1f9dd062ba930b7b85e71e92387e145b --- /dev/null +++ b/pool/shard002/C/0062557_zip.c @@ -0,0 +1,117 @@ +/* zip.c -- compress files to the gzip or pkzip format + * Copyright (C) 1992-1993 Jean-loup Gailly + * This is free software; you can redistribute it and/or modify it under the + * terms of the GNU General Public License, see the file COPYING. + */ + +#ifdef RCSID +static char rcsid[] = "$Id: zip.c,v 1.1.1.1 2006/09/14 01:59:08 root Exp $"; +#endif + +#include +#include + +#include "tailor.h" +#include "gzip.h" +#include "crypt.h" + +#ifdef HAVE_UNISTD_H +# include +#endif +#ifndef NO_FCNTL_H +# include +#endif + +local ulg crc; /* crc on uncompressed file data */ +long header_bytes; /* number of bytes in gzip header */ + +/* =========================================================================== + * Deflate in to out. + * IN assertions: the input and output buffers are cleared. + * The variables time_stamp and save_orig_name are initialized. + */ +int zip(in, out) + int in, out; /* input and output file descriptors */ +{ + uch flags = 0; /* general purpose bit flags */ + ush attr = 0; /* ascii/binary flag */ + ush deflate_flags = 0; /* pkzip -es, -en or -ex equivalent */ + + ifd = in; + ofd = out; + outcnt = 0; + + /* Write the header to the gzip file. See algorithm.doc for the format */ + + method = DEFLATED; + put_byte(GZIP_MAGIC[0]); /* magic header */ + put_byte(GZIP_MAGIC[1]); + put_byte(DEFLATED); /* compression method */ + + if (save_orig_name) { + flags |= ORIG_NAME; + } + put_byte(flags); /* general flags */ + put_long(time_stamp); + + /* Write deflated file to zip file */ + crc = updcrc(0, 0); + + bi_init(out); + ct_init(&attr, &method); + lm_init(level, &deflate_flags); + + put_byte((uch)deflate_flags); /* extra flags */ + put_byte(OS_CODE); /* OS identifier */ + + if (save_orig_name) { + char *p = basename(ifname); /* Don't save the directory part. */ + do { + put_char(*p); + } while (*p++); + } + header_bytes = (long)outcnt; + + (void)deflate(); + +#if !defined(NO_SIZE_CHECK) && !defined(RECORD_IO) + /* Check input size (but not in VMS -- variable record lengths mess it up) + * and not on MSDOS -- diet in TSR mode reports an incorrect file size) + */ + if (ifile_size != -1L && isize != (ulg)ifile_size) { + Trace((stderr, " actual=%ld, read=%ld ", ifile_size, isize)); + fprintf(stderr, "%s: %s: file size changed while zipping\n", + progname, ifname); + } +#endif + + /* Write the crc and uncompressed size */ + put_long(crc); + put_long(isize); + header_bytes += 2*sizeof(long); + + flush_outbuf(); + return OK; +} + + +/* =========================================================================== + * Read a new buffer from the current input file, perform end-of-line + * translation, and update the crc and input file size. + * IN assertion: size >= 2 (for end-of-line translation) + */ +int file_read(buf, size) + char *buf; + unsigned size; +{ + unsigned len; + + Assert(insize == 0, "inbuf not empty"); + + len = read(ifd, buf, size); + if (len == (unsigned)(-1) || len == 0) return (int)len; + + crc = updcrc((uch*)buf, len); + isize += (ulg)len; + return (int)len; +} diff --git a/pool/shard002/C/0062560_hal_tick.c b/pool/shard002/C/0062560_hal_tick.c new file mode 100644 index 0000000000000000000000000000000000000000..a0c2063cb32c2acd7cd6abc660b7530b33ef34b1 --- /dev/null +++ b/pool/shard002/C/0062560_hal_tick.c @@ -0,0 +1,138 @@ +/** + ****************************************************************************** + * @file hal_tick.c + * @author MCD Application Team + * @brief Initialization of HAL tick + ****************************************************************************** + * @attention + * + *

© COPYRIGHT 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. + * + ****************************************************************************** + */ +#include "hal_tick.h" + +// 0=NO, 1=PB6 toggles at each tick +#define DEBUG_TICK 0 + +TIM_HandleTypeDef TimMasterHandle; +uint32_t PreviousVal = 0; + +void us_ticker_irq_handler(void); + +void timer_irq_handler(void) { + // Channel 1 for mbed timeout + if (__HAL_TIM_GET_ITSTATUS(&TimMasterHandle, TIM_IT_CC1) == SET) { + us_ticker_irq_handler(); + } + + // Channel 2 for HAL tick + if (__HAL_TIM_GET_ITSTATUS(&TimMasterHandle, TIM_IT_CC2) == SET) { + __HAL_TIM_CLEAR_IT(&TimMasterHandle, TIM_IT_CC2); + uint32_t val = __HAL_TIM_GetCounter(&TimMasterHandle); + if ((val - PreviousVal) >= HAL_TICK_DELAY) { + // Increment HAL variable + HAL_IncTick(); + // Prepare next interrupt + __HAL_TIM_SetCompare(&TimMasterHandle, TIM_CHANNEL_2, val + HAL_TICK_DELAY); + PreviousVal = val; +#if DEBUG_TICK > 0 + HAL_GPIO_TogglePin(GPIOB, GPIO_PIN_6); +#endif + } + } +} + +// Reconfigure the HAL tick using a standard timer instead of systick. +HAL_StatusTypeDef HAL_InitTick(uint32_t TickPriority) { + RCC_ClkInitTypeDef RCC_ClkInitStruct; + uint32_t PclkFreq; + + // Get clock configuration + // Note: PclkFreq contains here the Latency (not used after) + HAL_RCC_GetClockConfig(&RCC_ClkInitStruct, &PclkFreq); + + // Get TIM5 clock value + PclkFreq = HAL_RCC_GetPCLK1Freq(); + + // Enable timer clock + TIM_MST_RCC; + + // Reset timer + TIM_MST_RESET_ON; + TIM_MST_RESET_OFF; + + // Configure time base + TimMasterHandle.Instance = TIM_MST; + TimMasterHandle.Init.Period = 0xFFFFFFFF; + + // TIMxCLK = PCLKx when the APB prescaler = 1 else TIMxCLK = 2 * PCLKx + if (RCC_ClkInitStruct.APB1CLKDivider == RCC_HCLK_DIV1) + TimMasterHandle.Init.Prescaler = (uint16_t)((PclkFreq) / 1000000) - 1; // 1 us tick + else + TimMasterHandle.Init.Prescaler = (uint16_t)((PclkFreq * 2) / 1000000) - 1; // 1 us tick + + TimMasterHandle.Init.ClockDivision = 0; + TimMasterHandle.Init.CounterMode = TIM_COUNTERMODE_UP; + TimMasterHandle.Init.RepetitionCounter = 0; + HAL_TIM_OC_Init(&TimMasterHandle); + + NVIC_SetVector(TIM_MST_IRQ, (uint32_t)timer_irq_handler); + NVIC_EnableIRQ(TIM_MST_IRQ); + + // Channel 1 for mbed timeout + HAL_TIM_OC_Start(&TimMasterHandle, TIM_CHANNEL_1); + + // Channel 2 for HAL tick + HAL_TIM_OC_Start(&TimMasterHandle, TIM_CHANNEL_2); + PreviousVal = __HAL_TIM_GetCounter(&TimMasterHandle); + __HAL_TIM_SetCompare(&TimMasterHandle, TIM_CHANNEL_2, PreviousVal + HAL_TICK_DELAY); + __HAL_TIM_ENABLE_IT(&TimMasterHandle, TIM_IT_CC2); + +#if DEBUG_TICK > 0 + __GPIOB_CLK_ENABLE(); + GPIO_InitTypeDef GPIO_InitStruct; + GPIO_InitStruct.Pin = GPIO_PIN_6; + GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP; + GPIO_InitStruct.Pull = GPIO_PULLUP; + GPIO_InitStruct.Speed = GPIO_SPEED_FAST; + HAL_GPIO_Init(GPIOB, &GPIO_InitStruct); +#endif + + return HAL_OK; +} + +/** + * @} + */ + +/** + * @} + */ + +/** + * @} + */ +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/pool/shard002/C/0062563_C811_WriteJoinPriority.c b/pool/shard002/C/0062563_C811_WriteJoinPriority.c new file mode 100644 index 0000000000000000000000000000000000000000..7f8933816a2682fab4bb0f9b839320b3e412e19c --- /dev/null +++ b/pool/shard002/C/0062563_C811_WriteJoinPriority.c @@ -0,0 +1,71 @@ +/* +* Copyright (C) 2013 Nivis LLC. +* Email: opensource@nivis.com +* Website: http://www.nivis.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, version 3 of the License. +* +* Redistribution and use in source and binary forms must retain this +* copyright notice. + +* 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 "C811_WriteJoinPriority.h" + +uint8_t Compose_C811_WriteJoinPriority_Req ( C811_WriteJoinPriority_Req* request, + ComposerContext* context, + BinaryStream* toStream ) +{ + context->cmdId = CMDID_C811_WriteJoinPriority; + STREAM_WRITE_UINT8(toStream, request->JoinPriority); + + return RCS_N00_Success; // success +} + +uint8_t Parse_C811_WriteJoinPriority_Req ( C811_WriteJoinPriority_Req* request, + ParserContext* context, + BinaryStream* fromStream ) +{ +#if defined(_DEBUG) +// if (fromStream->remainingBytes > C811_ReqSize) +// return RCS_E01_Undefined1; // too many bytes +#endif + + STREAM_READ_UINT8(fromStream, &request->JoinPriority); + + return RCS_N00_Success; // success +} + +uint8_t Compose_C811_WriteJoinPriority_Resp ( C811_WriteJoinPriority_Resp* response, + ComposerContext* context, + BinaryStream* toStream ) +{ + context->cmdId = CMDID_C811_WriteJoinPriority; + STREAM_WRITE_UINT8(toStream, response->JoinPriority); + + return RCS_N00_Success; // success +} + +uint8_t Parse_C811_WriteJoinPriority_Resp ( C811_WriteJoinPriority_Resp* response, + ParserContext* context, + BinaryStream* fromStream ) +{ +#if defined(_DEBUG) +// if (fromStream->remainingBytes > C811_RespSize) +// return RCS_E01_Undefined1; // too many bytes +#endif + + STREAM_READ_UINT8(fromStream, &response->JoinPriority); + + return RCS_N00_Success; // success +} diff --git a/pool/shard002/C/0062572_connection.c b/pool/shard002/C/0062572_connection.c new file mode 100644 index 0000000000000000000000000000000000000000..77cef9b27426feae11d6083aa90f5f0015234b62 --- /dev/null +++ b/pool/shard002/C/0062572_connection.c @@ -0,0 +1,283 @@ +/* + Copyright 2016,暗夜幽灵 + + 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 . +*/ + +#ifdef WINDOWS + #include +#endif //WINDOWS + +#ifndef WINDOWS + #include +#endif //! WINDOWS + +#include +#include +#include "../common/common.h" +#include "connection.h" + +#ifndef WINDOWS + typedef int SOCKET; + #define closesocket close + #define INVALID_SOCKET (-1) + #define SOCKET_ERROR (-1) +#endif //! WINDOWS + +static map_t address_map; +static pthread_mutex_t adress_map_lock; +static list_t conn_list; +static pthread_mutex_t conn_list_lock; +static SOCKET conn_socket; +static bool runflag = false; +static size_t pkg_size; +static size_t max_pkg_size; +static u32 max_retry; +static u32 heartbeat; + +static pthread_t recv_thread; +static pthread_t heartbeat_thread; + +static void set_checksum(ppkg_t p_pkg); +static bool checksum(ppkg_t p_pkg); +static void send_reply(struct sockaddr_in* p_addr, + ppkg_t p_pkg, + bool resend); + +static void* recv_thread_func(void* arg); +static void* heartbeat_thread_func(void* arg); + +static void reply_recv(struct sockaddr_in* addr, char* addr_str, + ppkg_t p_pkg); +static void resend_recv(struct sockaddr_in* addr, char* addr_str, + ppkg_t p_pkg); +static void accept_recv(struct sockaddr_in* addr, char* addr_str, + ppkg_t p_pkg); +static void connect_recv(struct sockaddr_in* addr, char* addr_str, + ppkg_t p_pkg); +static void data_recv(struct sockaddr_in* addr, char* addr_str, + ppkg_t p_pkg); +static void heartbeat_recv(struct sockaddr_in* addr, char* addr_str, + ppkg_t p_pkg); + +bool connection_init(u32 port, size_t _pkg_size, + size_t _max_pkg_size, u32 _heartbeat, u32 _max_retry) +{ + void* retval; + + #ifdef WINDOWS + WSADATA wsaData; + #endif //WINDOWS + struct sockaddr_in addr; + + #ifdef WINDOWS + + if(WSAStartup(MAKEWORD(2, 2), &wsaData) != 0) { + return false; + } + + #endif //WINDOWS + + if(runflag) { + return true; + } + + map_init(address_map); + list_init(conn_list); + address_map_lock = PTHREAD_MUTEX_INITIALIZER; + conn_list_lock = PTHREAD_MUTEX_INITIALIZER; + pkg_size = _pkg_size; + max_pkg_size = _max_pkg_size; + heartbeat = _heartbeat; + max_retry = _max_retry; + + //Set address + memset(&addr, 0, sizeof(addr)); + addr.sin_family = AF_INET; + addr.sin_addr.s_addr = htonl(INADDR_ANY); + addr.sin_port = htons(port); + + //Create socket + conn_socket = socket(AF_INET, SOCK_DGRAM, 0); + + if(conn_socket == INVALID_SOCKET) { + #ifdef WINDOWS + WSACleanup(); + #endif //WINDOWS + return false; + } + + //Bind socket + if(bind(conn_socket, (struct sockaddr*)&addr, sizeof(addr)) + == SOCKET_ERROR) { + closesocket(conn_socket); + #ifdef WINDOWS + WSACleanup(); + #endif //WINDOWS + return false; + } + + //Create threads + runflag = true; + + //Receive thread + if(pthread_create(&recv_thread, NULL, recv_thread_func, NULL) != 0) { + runflag = false; + closesocket(conn_socket); + #ifdef WINDOWS + WSACleanup(); + #endif //WINDOWS + return false; + } + + //Heartbeat thread + if(pthread_create(&heartbeat_thread, NULL, heartbeat_thread_func, + NULL) != 0) { + runflag = false; + closesocket(conn_socket); + pthread_join(recv_thread, &retval); + #ifdef WINDOWS + WSACleanup(); + #endif //WINDOWS + return false; + } + + return true; +} + +void connection_destroy() +{ + void* retval; + + runflag = false; + closesocket(conn_socket); + pthread_join(recv_thread, &retval); + pthread_join(heartbeat_thread, &retval); + #ifdef WINDOWS + WSACleanup(); + #endif //WINDOWS + return; +} + +pconnection_t create_connection(char* address); +pconnection_t listen_connection(); +void close_connection(pconnection_t p_conn); +size_t send_data(); +size_t recv_data(); + +void set_checksum(ppkg_t p_pkg) +{ + u8 sum; + size_t counted; + + p_pkg->data.head.checksum = 0; + + for(counted = 0; counted < p_pkg->data.head.size; counted++) { + sum += p_pkg->buf[counted]; + } + + p_pkg->data.head.checksum = 0 - sum; + + return; +} + +bool checksum(ppkg_t p_pkg) +{ + u8 sum; + size_t counted; + + for(counted = 0; counted < p_pkg->data.head.size; counted++) { + sum += p_pkg->buf[counted]; + } + + if(sum == 0) { + return true; + + } else { + return false; + } +} + +void* recv_thread_func(void* arg) +{ + u8* buf; + ppkg_t p_pkg; + struct sockaddr_in addr; + char addr_buf[32]; + pconnection_t p_conn; + + p_pkg = (ppkg_t)buf; + buf = malloc(max_pkg_size); + + while(runflag) { + //Receive package + if(recvfrom(conn_socket, buf, max_pkg_size, 0 + , (struct sockaddr*)&addr, sizeof(addr)) <= 0) { + continue; + } + + //Dispatch package + //Get address + sprintf(addr_buf, "%s:%hu", inet_ntoa(addr.sin_addr), addr.sin_port); + + if(p_pkg->data.head.type == PKG_TYPE_REPLY) { + reply_recv(&addr, addr_buf, p_pkg); + + } else if(p_pkg->head.type == PKG_TYPE_RESEND) { + resend_recv(&addr, addr_buf, p_pkg); + + } else { + //Checksum + if(!checksum(p_pkg)) { + send_reply(&addr, p_pkg, true); + } + + switch(p_pkg->data.head.type) { + case PKG_TYPE_CONNECT: + connect_recv(&addr, addr_buf, p_pkg); + break; + + case PKG_TYPE_ACCEPT: + accept_recv(&addr, addr_buf, p_pkg); + break; + + case PKG_TYPE_HEARTBEAT: + heartbeat_recv(&addr, addr_buf, p_pkg); + break; + + case PKG_TYPE_DATA: + data_recv(&addr, addr_buf, p_pkg); + break; + } + } + } + + free(buf); + UNREFERENCED_PARAMETER(arg); + return NULL; +} + +void reply_recv(struct sockaddr_in* addr, char* addr_str, + ppkg_t p_pkg); +void resend_recv(struct sockaddr_in* addr, char* addr_str, + ppkg_t p_pkg); +void accept_recv(struct sockaddr_in* addr, char* addr_str, + ppkg_t p_pkg); +void connect_recv(struct sockaddr_in* addr, char* addr_str, + ppkg_t p_pkg); +void data_recv(struct sockaddr_in* addr, char* addr_str, + ppkg_t p_pkg); +void heartbeat_recv(struct sockaddr_in* addr, char* addr_str, + ppkg_t p_pkg); + diff --git a/pool/shard002/C/0062590_radius.c b/pool/shard002/C/0062590_radius.c new file mode 100644 index 0000000000000000000000000000000000000000..625dc4108a2b7a2813ab476bf029a22f0f5d66d2 --- /dev/null +++ b/pool/shard002/C/0062590_radius.c @@ -0,0 +1,81 @@ +/* + * radius.c + * + * Copyright (C) 2012-15 - ntop.org + * + * nDPI is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * nDPI is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with nDPI. If not, see . + * + */ + + +#include "ndpi_api.h" + +#ifdef NDPI_PROTOCOL_RADIUS + +struct radius_header { + u_int8_t code; + u_int8_t packet_id; + u_int16_t len; +}; + +static void ndpi_check_radius(struct ndpi_detection_module_struct *ndpi_struct, struct ndpi_flow_struct *flow) +{ + struct ndpi_packet_struct *packet = &flow->packet; + // const u_int8_t *packet_payload = packet->payload; + u_int32_t payload_len = packet->payload_packet_len; + + if(packet->udp != NULL) { + struct radius_header *h = (struct radius_header*)packet->payload; + u_int len = ntohs(h->len); + + if((payload_len > sizeof(struct radius_header)) + && (h->code > 0) + && (h->code <= 5) + && (len == payload_len)) { + NDPI_LOG(NDPI_PROTOCOL_RADIUS, ndpi_struct, NDPI_LOG_DEBUG, "Found radius.\n"); + ndpi_set_detected_protocol(ndpi_struct, flow, NDPI_PROTOCOL_RADIUS, NDPI_PROTOCOL_UNKNOWN); + + return; + } + + NDPI_ADD_PROTOCOL_TO_BITMASK(flow->excluded_protocol_bitmask, NDPI_PROTOCOL_RADIUS); + return; + } +} + +void ndpi_search_radius(struct ndpi_detection_module_struct *ndpi_struct, struct ndpi_flow_struct *flow) +{ + struct ndpi_packet_struct *packet = &flow->packet; + + NDPI_LOG(NDPI_PROTOCOL_RADIUS, ndpi_struct, NDPI_LOG_DEBUG, "radius detection...\n"); + + /* skip marked packets */ + if(packet->detected_protocol_stack[0] != NDPI_PROTOCOL_RADIUS) + ndpi_check_radius(ndpi_struct, flow); +} + + +void init_radius_dissector(struct ndpi_detection_module_struct *ndpi_struct, u_int32_t *id, NDPI_PROTOCOL_BITMASK *detection_bitmask) +{ + ndpi_set_bitmask_protocol_detection("Radius", ndpi_struct, detection_bitmask, *id, + NDPI_PROTOCOL_RADIUS, + ndpi_search_radius, + NDPI_SELECTION_BITMASK_PROTOCOL_UDP_WITH_PAYLOAD, + SAVE_DETECTION_BITMASK_AS_UNKNOWN, + ADD_TO_DETECTION_BITMASK); + + *id += 1; +} + +#endif diff --git a/pool/shard002/C/0062597_setup-fb-24bpp.c b/pool/shard002/C/0062597_setup-fb-24bpp.c new file mode 100644 index 0000000000000000000000000000000000000000..f992a1289c4146921088f58d8f16eb04e12678c5 --- /dev/null +++ b/pool/shard002/C/0062597_setup-fb-24bpp.c @@ -0,0 +1,62 @@ +/* + * linux/arch/arm/mach-s5pc100/setup-fb-24bpp.c + * + * Copyright 2009 Samsung Electronics + * + * Base S5PC100 setup information for 24bpp LCD framebuffer + * + * 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 + +#define DISR_OFFSET 0x7008 + +<<<<<<< HEAD +static void s5pc100_fb_setgpios(unsigned int base, unsigned int nr) +{ + s3c_gpio_cfgrange_nopull(base, nr, S3C_GPIO_SFN(2)); +} + +void s5pc100_fb_gpio_setup_24bpp(void) +{ + s5pc100_fb_setgpios(S5PC100_GPF0(0), 8); + s5pc100_fb_setgpios(S5PC100_GPF1(0), 8); + s5pc100_fb_setgpios(S5PC100_GPF2(0), 8); + s5pc100_fb_setgpios(S5PC100_GPF3(0), 4); +======= +void s5pc100_fb_gpio_setup_24bpp(void) +{ + unsigned int gpio = 0; + + for (gpio = S5PC100_GPF0(0); gpio <= S5PC100_GPF0(7); gpio++) { + s3c_gpio_cfgpin(gpio, S3C_GPIO_SFN(2)); + s3c_gpio_setpull(gpio, S3C_GPIO_PULL_NONE); + } + + for (gpio = S5PC100_GPF1(0); gpio <= S5PC100_GPF1(7); gpio++) { + s3c_gpio_cfgpin(gpio, S3C_GPIO_SFN(2)); + s3c_gpio_setpull(gpio, S3C_GPIO_PULL_NONE); + } + + for (gpio = S5PC100_GPF2(0); gpio <= S5PC100_GPF2(7); gpio++) { + s3c_gpio_cfgpin(gpio, S3C_GPIO_SFN(2)); + s3c_gpio_setpull(gpio, S3C_GPIO_PULL_NONE); + } + + for (gpio = S5PC100_GPF3(0); gpio <= S5PC100_GPF3(3); gpio++) { + s3c_gpio_cfgpin(gpio, S3C_GPIO_SFN(2)); + s3c_gpio_setpull(gpio, S3C_GPIO_PULL_NONE); + } +>>>>>>> 296c66da8a02d52243f45b80521febece5ed498a +} diff --git a/pool/shard002/C/0062600_dv1394.c b/pool/shard002/C/0062600_dv1394.c new file mode 100644 index 0000000000000000000000000000000000000000..a9bc058dc9e853e8725609219407508ae2a8ced1 --- /dev/null +++ b/pool/shard002/C/0062600_dv1394.c @@ -0,0 +1,238 @@ +/* + * Linux DV1394 interface + * Copyright (c) 2003 Max Krasnyansky + * + * 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 "config.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "libavformat/avformat.h" + +#undef DV1394_DEBUG + +#include "libavformat/dv.h" +#include "dv1394.h" + +struct dv1394_data { + int fd; + int channel; + int format; + + uint8_t *ring; /* Ring buffer */ + int index; /* Current frame index */ + int avail; /* Number of frames available for reading */ + int done; /* Number of completed frames */ + + DVDemuxContext* dv_demux; /* Generic DV muxing/demuxing context */ +}; + +/* + * The trick here is to kludge around well known problem with kernel Ooopsing + * when you try to capture PAL on a device node configure for NTSC. That's + * why we have to configure the device node for PAL, and then read only NTSC + * amount of data. + */ +static int dv1394_reset(struct dv1394_data *dv) +{ + struct dv1394_init init; + + init.channel = dv->channel; + init.api_version = DV1394_API_VERSION; + init.n_frames = DV1394_RING_FRAMES; + init.format = DV1394_PAL; + + if (ioctl(dv->fd, DV1394_INIT, &init) < 0) + return -1; + + dv->avail = dv->done = 0; + return 0; +} + +static int dv1394_start(struct dv1394_data *dv) +{ + /* Tell DV1394 driver to enable receiver */ + if (ioctl(dv->fd, DV1394_START_RECEIVE, 0) < 0) { + av_log(NULL, AV_LOG_ERROR, "Failed to start receiver: %s\n", strerror(errno)); + return -1; + } + return 0; +} + +static int dv1394_read_header(AVFormatContext * context, AVFormatParameters * ap) +{ + struct dv1394_data *dv = context->priv_data; + + dv->dv_demux = dv_init_demux(context); + if (!dv->dv_demux) + goto failed; + + if (ap->standard && !strcasecmp(ap->standard, "pal")) + dv->format = DV1394_PAL; + else + dv->format = DV1394_NTSC; + + if (ap->channel) + dv->channel = ap->channel; + else + dv->channel = DV1394_DEFAULT_CHANNEL; + + /* Open and initialize DV1394 device */ + dv->fd = open(context->filename, O_RDONLY); + if (dv->fd < 0) { + av_log(context, AV_LOG_ERROR, "Failed to open DV interface: %s\n", strerror(errno)); + goto failed; + } + + if (dv1394_reset(dv) < 0) { + av_log(context, AV_LOG_ERROR, "Failed to initialize DV interface: %s\n", strerror(errno)); + goto failed; + } + + dv->ring = mmap(NULL, DV1394_PAL_FRAME_SIZE * DV1394_RING_FRAMES, + PROT_READ, MAP_PRIVATE, dv->fd, 0); + if (dv->ring == MAP_FAILED) { + av_log(context, AV_LOG_ERROR, "Failed to mmap DV ring buffer: %s\n", strerror(errno)); + goto failed; + } + + if (dv1394_start(dv) < 0) + goto failed; + + return 0; + +failed: + close(dv->fd); + return AVERROR(EIO); +} + +static int dv1394_read_packet(AVFormatContext *context, AVPacket *pkt) +{ + struct dv1394_data *dv = context->priv_data; + int size; + + size = dv_get_packet(dv->dv_demux, pkt); + if (size > 0) + return size; + + if (!dv->avail) { + struct dv1394_status s; + struct pollfd p; + + if (dv->done) { + /* Request more frames */ + if (ioctl(dv->fd, DV1394_RECEIVE_FRAMES, dv->done) < 0) { + /* This usually means that ring buffer overflowed. + * We have to reset :(. + */ + + av_log(context, AV_LOG_ERROR, "DV1394: Ring buffer overflow. Reseting ..\n"); + + dv1394_reset(dv); + dv1394_start(dv); + } + dv->done = 0; + } + + /* Wait until more frames are available */ +restart_poll: + p.fd = dv->fd; + p.events = POLLIN | POLLERR | POLLHUP; + if (poll(&p, 1, -1) < 0) { + if (errno == EAGAIN || errno == EINTR) + goto restart_poll; + av_log(context, AV_LOG_ERROR, "Poll failed: %s\n", strerror(errno)); + return AVERROR(EIO); + } + + if (ioctl(dv->fd, DV1394_GET_STATUS, &s) < 0) { + av_log(context, AV_LOG_ERROR, "Failed to get status: %s\n", strerror(errno)); + return AVERROR(EIO); + } +#ifdef DV1394_DEBUG + av_log(context, AV_LOG_DEBUG, "DV1394: status\n" + "\tactive_frame\t%d\n" + "\tfirst_clear_frame\t%d\n" + "\tn_clear_frames\t%d\n" + "\tdropped_frames\t%d\n", + s.active_frame, s.first_clear_frame, + s.n_clear_frames, s.dropped_frames); +#endif + + dv->avail = s.n_clear_frames; + dv->index = s.first_clear_frame; + dv->done = 0; + + if (s.dropped_frames) { + av_log(context, AV_LOG_ERROR, "DV1394: Frame drop detected (%d). Reseting ..\n", + s.dropped_frames); + + dv1394_reset(dv); + dv1394_start(dv); + } + } + +#ifdef DV1394_DEBUG + av_log(context, AV_LOG_DEBUG, "index %d, avail %d, done %d\n", dv->index, dv->avail, + dv->done); +#endif + + size = dv_produce_packet(dv->dv_demux, pkt, + dv->ring + (dv->index * DV1394_PAL_FRAME_SIZE), + DV1394_PAL_FRAME_SIZE, -1); + dv->index = (dv->index + 1) % DV1394_RING_FRAMES; + dv->done++; dv->avail--; + + return size; +} + +static int dv1394_close(AVFormatContext * context) +{ + struct dv1394_data *dv = context->priv_data; + + /* Shutdown DV1394 receiver */ + if (ioctl(dv->fd, DV1394_SHUTDOWN, 0) < 0) + av_log(context, AV_LOG_ERROR, "Failed to shutdown DV1394: %s\n", strerror(errno)); + + /* Unmap ring buffer */ + if (munmap(dv->ring, DV1394_NTSC_FRAME_SIZE * DV1394_RING_FRAMES) < 0) + av_log(context, AV_LOG_ERROR, "Failed to munmap DV1394 ring buffer: %s\n", strerror(errno)); + + close(dv->fd); + av_free(dv->dv_demux); + + return 0; +} + +AVInputFormat ff_dv1394_demuxer = { + .name = "dv1394", + .long_name = NULL_IF_CONFIG_SMALL("DV1394 A/V grab"), + .priv_data_size = sizeof(struct dv1394_data), + .read_header = dv1394_read_header, + .read_packet = dv1394_read_packet, + .read_close = dv1394_close, + .flags = AVFMT_NOFILE +}; diff --git a/pool/shard002/C/0062604_gvcmy_open.c b/pool/shard002/C/0062604_gvcmy_open.c new file mode 100644 index 0000000000000000000000000000000000000000..d2b4a587e10e384c056d1b5a8ff8f6ab526051ef --- /dev/null +++ b/pool/shard002/C/0062604_gvcmy_open.c @@ -0,0 +1,207 @@ +/**************************************************************** + * * + * Copyright 2001, 2003 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" + +#ifdef VMS +# include +# include +# include +#elif defined(UNIX) +# include +# include +# include "parse_file.h" +# include "gtm_stdlib.h" +#endif + +#include "gdsroot.h" +#include "gtm_facility.h" +#include "fileinfo.h" +#include "gdsbt.h" +#include "gdsfhead.h" +#include "hashdef.h" +#include "cmidef.h" +#include "cmmdef.h" +#include "stringpool.h" +#include "gtm_string.h" +#include "iosp.h" +#include "gvcmy_open.h" +#include "gvcmy_close.h" +#include "trans_log_name.h" +#include "gvcmz.h" +#include "copy.h" +#include "error.h" +#include "op.h" + +GBLREF spdesc stringpool; + +#define GTCM_ENVVAR_PFX "GTCM_" +#define GTCM_ENVVAR_PFXLEN (sizeof(GTCM_ENVVAR_PFX) - 1) + +#ifdef VMS +void gvcmy_open(gd_region *reg, struct NAM *nb) +#else +void gvcmy_open(gd_region *reg, parse_blk *pb) +#endif +{ + struct CLB *clb_ptr; + link_info *li; + unsigned char *ptr, *top, *fn, *libuff; + char *trans_name; + bool new = FALSE; + int len; + uint4 status; + cmi_descriptor node; + mstr task1, task2; + unsigned char buff[256], lbuff[MAX_HOST_NAME_LEN + GTCM_ENVVAR_PFXLEN]; + short temp_short; + VMS_ONLY($DESCRIPTOR(task, "GTCMSVR");) + UNIX_ONLY(MSTR_DEF(task, 0, NULL);) + error_def(ERR_INVNETFILNM); + error_def(ERR_BADSRVRNETMSG); + error_def(ERR_NETDBOPNERR); + error_def(ERR_SYSCALL); + + ESTABLISH(gvcmy_open_ch); +#ifdef VMS + if (!nb->nam$b_node) + rts_error(VARLSTCNT(1) ERR_INVNETFILNM); + top = nb->nam$l_esa + nb->nam$b_esl; + fn = nb->nam$l_node + nb->nam$b_node; + node.dsc$b_dtype = task.dsc$b_dtype = 14; + node.dsc$b_class = task.dsc$b_class = 1; + node.dsc$w_length = nb->nam$b_node - 2; + node.dsc$a_pointer = nb->nam$l_node; + task1.addr = "GTCMSVRNAM"; + task1.len = sizeof("GTCMSVRNAM") - 1; + status = trans_log_name(&task1, &task2, (char *)buff); +#elif defined(UNIX) + if (!pb->b_node) + rts_error(VARLSTCNT(1) ERR_INVNETFILNM); + fn = (unsigned char *)pb->l_dir; + top = fn + pb->b_esl - pb->b_node; /* total length except node gives end of string */ + /* + The "task" value for unix comes from a logical of the form GTCM_. This value + has the form of "portnum". If the optional hostname or ip is specified + as part of the value, it will override the node value from the global directory. That + processing is handled down in the CMI layer. + */ + node.addr = pb->l_node; + node.len = pb->b_node - 1; + memcpy(lbuff, GTCM_ENVVAR_PFX, GTCM_ENVVAR_PFXLEN); + memcpy(lbuff + GTCM_ENVVAR_PFXLEN, node.addr, node.len); + task1.addr = (char *)lbuff; + task1.len = node.len + GTCM_ENVVAR_PFXLEN; + lbuff[task1.len] = '\0'; + task2.addr = (char *)buff; + task2.len = 0; + if (NULL != (trans_name = GETENV((const char *)lbuff))) + { + status = SS_NORMAL; + task2.len = strlen(trans_name); + memcpy(task2.addr, trans_name, task2.len); + } else + status = SS_NOLOGNAM; +#else +# error "Undefined platform" +#endif + if (SS_NOLOGNAM != status) + { + if (SS_NORMAL != status) + rts_error(VARLSTCNT(1) status); + VMS_ONLY( + task.dsc$a_pointer = buff; + task.dsc$w_length = task2.len; + ); + UNIX_ONLY( + task.addr = (char *)task2.addr; + task.len = task2.len; + ); + } + clb_ptr = cmu_getclb(&node, &task); + if (!clb_ptr) /* If link not open */ + { + new = TRUE; + clb_ptr = gvcmz_netopen(clb_ptr, &node, &task); + } else + { + assert(((link_info *)clb_ptr->usr)->lnk_active); + len = top - fn + 2 + S_HDRSIZE; + if (len < CM_MINBUFSIZE) + len = CM_MINBUFSIZE; + if (stringpool.top - stringpool.free < len) + stp_gcol(len); + clb_ptr->mbf = stringpool.free; + clb_ptr->mbl = len; + } + li = (link_info *)clb_ptr->usr; + clb_ptr->cbl = top - fn + 2 + S_HDRSIZE; + *clb_ptr->mbf = CMMS_S_INITREG; + ptr = clb_ptr->mbf + 1; + temp_short = top - fn; + CM_PUT_SHORT(ptr, temp_short, li->convert_byteorder); + ptr += sizeof(short); + memcpy(ptr, fn, top - fn); + status = cmi_write(clb_ptr); + if (CMI_ERROR(status)) + { + if (new) + gvcmy_close(clb_ptr); + rts_error(VARLSTCNT(3) ERR_NETDBOPNERR, 0, status); + } + status = cmi_read(clb_ptr); + if (CMI_ERROR(status)) + { + if (new) + gvcmy_close(clb_ptr); + rts_error(VARLSTCNT(3) ERR_NETDBOPNERR, 0, status); + } + if (CMMS_T_REGNUM != *clb_ptr->mbf) + { + if (CMMS_E_ERROR != *clb_ptr->mbf) + { + if (new) + gvcmy_close(clb_ptr); + rts_error(VARLSTCNT(3) ERR_NETDBOPNERR, 0, ERR_BADSRVRNETMSG); + } + gvcmz_errmsg(clb_ptr, new); + } + ptr = clb_ptr->mbf + 1; + reg->cmx_regnum = *ptr++; + reg->null_subs = *ptr++; + CM_GET_SHORT(reg->max_rec_size, ptr, li->convert_byteorder); + ptr += sizeof(short); + if (reg->max_rec_size + CM_BUFFER_OVERHEAD > li->buffer_size) + { + if (li->buffered_count) + { + assert(li->buffer); + libuff = malloc(reg->max_rec_size); + memcpy(libuff, li->buffer, li->buffer_used); + free(li->buffer); + li->buffer = libuff; + } else if (li->buffer) + { + free(li->buffer); + li->buffer = 0; + } + li->buffer_size = reg->max_rec_size + CM_BUFFER_OVERHEAD; + } + CM_GET_SHORT(reg->max_key_size, ptr, li->convert_byteorder); + reg->dyn.addr->cm_blk = clb_ptr; + reg->dyn.addr->acc_meth = dba_cm; + reg->open = TRUE; + clb_ptr->mbl = li->buffer_size; + if (clb_ptr->mbl < CM_MINBUFSIZE) + clb_ptr->mbl = CM_MINBUFSIZE; + REVERT; + return; +} diff --git a/pool/shard002/C/0062611_postform.c b/pool/shard002/C/0062611_postform.c new file mode 100644 index 0000000000000000000000000000000000000000..60a687e35df2f95bc0a02e514fbdb67049d3ecd0 --- /dev/null +++ b/pool/shard002/C/0062611_postform.c @@ -0,0 +1,117 @@ +/* +** @(#) $Id: postform.c,v 1.9 1999/03/01 13:41:55 frystyk Exp $ +** +** Other libwww samples can be found at "http://www.w3.org/Library/Examples" +** +** Copyright (c© 1995-1998 World Wide Web Consortium, (Massachusetts +** Institute of Technology, Institut National de Recherche en +** Informatique et en Automatique, Keio University). All Rights +** Reserved. This program is distributed under the W3C's Software +** Intellectual Property 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 W3C License http://www.w3.org/Consortium/Legal/ for more +** details. +** +** Posts form data to an HTTP server and saves the result in a chunk +*/ + +#include "WWWLib.h" +#include "WWWInit.h" + +PRIVATE HTChunk * result = NULL; + +PRIVATE int printer (const char * fmt, va_list pArgs) +{ + return (vfprintf(stdout, fmt, pArgs)); +} + +PRIVATE int tracer (const char * fmt, va_list pArgs) +{ + return (vfprintf(stderr, fmt, pArgs)); +} + +PRIVATE int terminate_handler (HTRequest * request, HTResponse * response, + void * param, int status) +{ + if (status == HT_LOADED && result && HTChunk_data(result)) { + HTPrint("%s", HTChunk_data(result)); + HTChunk_delete(result); + } + + /* We are done with this request */ + HTRequest_delete(request); + + /* Terminate libwww */ + HTProfile_delete(); + + exit(0); +} + +int main (int argc, char ** argv) +{ + HTRequest * request = NULL; + HTAnchor * anchor = NULL; + HTAssocList * formfields = NULL; + char * uri = NULL; + + /* Create a new premptive client */ + HTProfile_newNoCacheClient("TestApp", "1.0"); + + /* Need our own trace and print functions */ + HTPrint_setCallback(printer); + HTTrace_setCallback(tracer); + + /* Get trace messages */ +#if 0 + HTSetTraceMessageMask("sop"); +#endif + + /* Add our own filter to update the history list */ + HTNet_addAfter(terminate_handler, NULL, NULL, HT_ALL, HT_FILTER_LAST); + + /* Set the timeout for long we are going to wait for a response */ + HTHost_setEventTimeout(20000); + + /* Handle command line args */ + if (argc >= 2) { + int arg; + uri = argv[1]; + for (arg=2; arg 'a=1' 'b=+2+' 'c=3 ...'\n", argv[0]); + } + + return 0; +} diff --git a/pool/shard002/C/0062617_isomorphic-strings.c b/pool/shard002/C/0062617_isomorphic-strings.c new file mode 100644 index 0000000000000000000000000000000000000000..c2af42f3f070def3711fd27ea787762dfe79b6ab --- /dev/null +++ b/pool/shard002/C/0062617_isomorphic-strings.c @@ -0,0 +1,21 @@ +char* normalize(char* s) { + int i = 0; + int m = 1; + int ch[256]; + char* t = NULL; + t = (char *) malloc(strlen(s) * sizeof(char)); + for (i=0; i < 256; i++) + ch[i] = 0; + for (i=0; i < strlen(s); i++) { + if (ch[s[i]] == 0) { + ch[s[i]] = m; + m++; + } + t[i] = ch[s[i]]; + } + return t; +} + +bool isIsomorphic(char* s, char* t) { + return !strcmp(normalize(s), normalize(t)); +} diff --git a/pool/shard002/C/0062622_main.c b/pool/shard002/C/0062622_main.c new file mode 100644 index 0000000000000000000000000000000000000000..aa8e57628f326c99bbe20ae205c766b62e478ea6 --- /dev/null +++ b/pool/shard002/C/0062622_main.c @@ -0,0 +1,152 @@ +/* + * GtkShot - A screen capture programme using GtkLib + * Copyright (C) 2012 flytreeleft @ CrazyDan + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include + +#include +#include +#include +#include +#include + +#include +#include + +#include "utils.h" +#include "xpm.h" + +#include "shot.h" + +#define WAKE_UP_SIGNAL SIGUSR1 +#define LOCK_FILE ("/tmp/gtkshot.lock") + +static GtkShot *shot = NULL; + +static void wake_up(gint signo); +static void exit_clean(gint signo); +static void quit(); +static void save_to_clipboard(); +static void remove_lock_file(); +static gint new_lock_file(); + +int main(int argc, char *argv[]) { +#ifdef ENABLE_NLS + bindtextdomain(GETTEXT_PACKAGE, PACKAGE_LOCALE_DIR); + bind_textdomain_codeset(GETTEXT_PACKAGE, "UTF-8"); + textdomain(GETTEXT_PACKAGE); +#endif + + gint pid = new_lock_file(); + + if (pid > 0) { + if (kill(pid, WAKE_UP_SIGNAL) == 0) { + exit(0); // 进程确已存在,则退出新进程 + } else { // 否则,重新创建锁定文件 + remove_lock_file(); + new_lock_file(); + } + } + signal(WAKE_UP_SIGNAL, wake_up); + signal(SIGINT, exit_clean); + + gtk_init(&argc, &argv); + + shot = gtk_shot_new(); + shot->quit = quit; + shot->dblclick = save_to_clipboard; + + gtk_window_set_title(GTK_WINDOW(shot), GTK_SHOT_NAME); + GdkPixbuf *icon = gdk_pixbuf_new_from_xpm_data(gtkshot_xpm); + gtk_window_set_icon(GTK_WINDOW(shot), icon); + g_object_unref(icon); + + gtk_shot_show(shot, TRUE); + gtk_main(); + + return 0; +} + +void wake_up(gint signo) { + gtk_shot_show(shot, TRUE); + debug("GtkShot has been wake up...\n"); +} + +void exit_clean(gint signo) { + quit(); +} + +void quit() { + debug("GtkShot has exit" \ + ", you will not get shot image any more...\n"); + + remove_lock_file(); + gtk_main_quit(); + exit(0); +} + +void save_to_clipboard() { + if (gtk_shot_has_visible_section(shot)) { + gtk_shot_save_section_to_clipboard(shot); + gtk_shot_hide(shot); + } else { + gtk_shot_quit(shot); + } +} + +void remove_lock_file() { + if (remove(LOCK_FILE) == 0) { + debug("clean lock file [%s] successfully...\n", LOCK_FILE); + } else { + debug("can not remove lock file [%s]: %s" \ + ", please remove it by yourself...\n" + , LOCK_FILE, strerror(errno)); + } +} + +/** + * 创建锁文件,并返回进程PID + * @return (= 0), 进程不存在,新建锁文件; + * (> 0), 进程已存在,且PID为该返回值 + * ,并保留原锁文件; + */ +gint new_lock_file() { + FILE *f = fopen(LOCK_FILE, "r"); + gint pid = 0; + + if (f) { + fscanf(f, "gtk-shot-pid: %d", &pid); + //fread(&pid, sizeof(gint), 1, f); +#ifdef GTK_SHOT_DEBUG + debug("GtkShot exists: pid is %d\n", pid); +#endif + } else if ((f = fopen(LOCK_FILE, "w+"))) { + pid = getpid(); + fprintf(f, "gtk-shot-pid: %d", pid); + //fwrite(&pid, sizeof(gint), 1, f); +#ifdef GTK_SHOT_DEBUG + debug("new GtkShot: pid is %d\n", pid); +#endif + pid = 0; + } else { + debug("no lock file and create lock file failed[%s]: %s\n" + , LOCK_FILE, strerror(errno)); + exit(-1); + } + if (f) fclose(f); + + return pid; +} diff --git a/pool/shard002/C/0062625_linalg.c b/pool/shard002/C/0062625_linalg.c new file mode 100644 index 0000000000000000000000000000000000000000..78e6268e1cd0787d7b8271afb1068d5218579b05 --- /dev/null +++ b/pool/shard002/C/0062625_linalg.c @@ -0,0 +1,49 @@ +/* + linalg.c is part of the RoseWheel project. + Copyright (C) 2011 RoseWheel Team + + 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 "assert_param.h" +#include "linalg.h" + +void matrix_init(matrix_t* matrix, double* data, + size_t size_x, size_t size_y) +{ + matrix->data = data; + matrix->size_x = size_x; + matrix->size_y = size_y; + matrix->data = data; +} + +void vector_init(vector_t* vector, double* data, size_t size) +{ + vector->size = size; + vector->data = data; +} + +void mv_mult(vector_t* result, matrix_t* m, vector_t* v) +{ + assert_param(m->size_x == v->size); + assert_param(m->size_y == result->size); + for (int i = 0; i < m->size_y; i++) + { + result->data[i] = 0; + for (int j = 0; j < m->size_x; j++) + result->data[i] += m->data[i * m->size_x + j] * v->data[j]; + } +} diff --git a/pool/shard002/C/0062647_empty-Seed4-RandomFuns-Type_long-ControlStructures_14-BB2-ForBound_input-Operators_PlusA_MinusA_Lt_Gt_Le_Ge_Eq_Ne.c b/pool/shard002/C/0062647_empty-Seed4-RandomFuns-Type_long-ControlStructures_14-BB2-ForBound_input-Operators_PlusA_MinusA_Lt_Gt_Le_Ge_Eq_Ne.c new file mode 100644 index 0000000000000000000000000000000000000000..7f687cb5d01717d9f2c16cc6e5ec8ba3a5e5e492 --- /dev/null +++ b/pool/shard002/C/0062647_empty-Seed4-RandomFuns-Type_long-ControlStructures_14-BB2-ForBound_input-Operators_PlusA_MinusA_Lt_Gt_Le_Ge_Eq_Ne.c @@ -0,0 +1,120 @@ +/* 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 long input[1] , unsigned long 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 , ...) ; +int main(int argc , char *argv[] ) +{ + unsigned long input[1] ; + unsigned long output[1] ; + int randomFuns_i5 ; + unsigned long 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 = strtoul(argv[randomFuns_i5 + 1], 0, 10); + input[randomFuns_i5] = randomFuns_value6; + randomFuns_i5 ++; + } + RandomFunc(input, output); + if (output[0] == 4242424242UL) { + printf("You win!\n"); + } else { + + } + randomFuns_main_i7 = 0; + while (randomFuns_main_i7 < 1) { + printf("%lu\n", output[randomFuns_main_i7]); + randomFuns_main_i7 ++; + } +} +} +void megaInit(void) +{ + + + { + +} +} +void RandomFunc(unsigned long input[1] , unsigned long output[1] ) +{ + unsigned long state[1] ; + unsigned long local1 ; + char copy11 ; + char copy12 ; + char copy13 ; + unsigned short copy14 ; + + { + state[0UL] = (input[0UL] + 914778474UL) - 981234615UL; + local1 = 0UL; + while (local1 < input[1UL]) { + if (state[0UL] < local1) { + if (state[0UL] != local1) { + state[0UL] += state[0UL]; + copy11 = *((char *)(& state[0UL]) + 1); + *((char *)(& state[0UL]) + 1) = *((char *)(& state[0UL]) + 7); + *((char *)(& state[0UL]) + 7) = copy11; + } else { + copy12 = *((char *)(& state[local1]) + 1); + *((char *)(& state[local1]) + 1) = *((char *)(& state[local1]) + 6); + *((char *)(& state[local1]) + 6) = copy12; + state[0UL] = state[local1] + state[0UL]; + } + } else + if (state[0UL] != local1) { + copy13 = *((char *)(& state[local1]) + 7); + *((char *)(& state[local1]) + 7) = *((char *)(& state[local1]) + 0); + *((char *)(& state[local1]) + 0) = copy13; + state[0UL] = state[local1] + state[local1]; + } else { + copy14 = *((unsigned short *)(& state[local1]) + 3); + *((unsigned short *)(& state[local1]) + 3) = *((unsigned short *)(& state[local1]) + 2); + *((unsigned short *)(& state[local1]) + 2) = copy14; + state[0UL] = state[local1] + state[local1]; + } + local1 ++; + } + output[0UL] = state[0UL] - 699774821UL; +} +} diff --git a/pool/shard002/C/0062653_dup2.c b/pool/shard002/C/0062653_dup2.c new file mode 100644 index 0000000000000000000000000000000000000000..c824cc58e779966d94de49208c0ebb433b4b7962 --- /dev/null +++ b/pool/shard002/C/0062653_dup2.c @@ -0,0 +1,49 @@ +/**************************************************************************/ +/* */ +/* OCaml */ +/* */ +/* Xavier Leroy, projet Cristal, INRIA Rocquencourt */ +/* */ +/* Copyright 1996 Institut National de Recherche en Informatique et */ +/* en Automatique. */ +/* */ +/* All rights reserved. This file is distributed under the terms of */ +/* the GNU Lesser General Public License version 2.1, with the */ +/* special exception on linking described in the file LICENSE. */ +/* */ +/**************************************************************************/ + +#include +#include "unixsupport.h" + +#ifdef HAS_DUP2 + +CAMLprim value unix_dup2(value fd1, value fd2) +{ + if (dup2(Int_val(fd1), Int_val(fd2)) == -1) uerror("dup2", Nothing); + return Val_unit; +} + +#else + +static int do_dup2(int fd1, int fd2) +{ + int fd; + int res; + + fd = dup(fd1); + if (fd == -1) return -1; + if (fd == fd2) return 0; + res = do_dup2(fd1, fd2); + close(fd); + return res; +} + +CAMLprim value unix_dup2(value fd1, value fd2) +{ + close(Int_val(fd2)); + if (do_dup2(Int_val(fd1), Int_val(fd2)) == -1) uerror("dup2", Nothing); + return Val_unit; +} + +#endif diff --git a/pool/shard002/C/0062659_CTString.c b/pool/shard002/C/0062659_CTString.c new file mode 100644 index 0000000000000000000000000000000000000000..2f168dd79bf58dd150c411c47661aafad06a894a --- /dev/null +++ b/pool/shard002/C/0062659_CTString.c @@ -0,0 +1,58 @@ +/* + craftIk - A custom Minecraft server written in C. + Copyright (C) 2012, SI Cyrusian. All Rights Reserved. + Minecraft is a trademark of Mojang AB. + + 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 "CTString.h" +#include "CTObject.h" +#include + + +struct _CTString { + CTObjectHeader *header; + CTShort length; // JString compatible + char *body; +}; + + +CTBOOL CTStringCopy(CTString **cloneString, CTString *sourceString) { + return CTStringInitWithCString(cloneString, sourceString->body, sourceString->length); +} + +CTBOOL CTStringInitWithCString(CTString **newString, char *sourceString, CTShort sourceLength) { + if(newString==NULL) + return NO; + + if(CTAllocate((void **)newString, sizeof(CTString))==NO) + return NO; + + (*newString)->length=(sourceLength<0?(CTShort)strlen(sourceString):sourceLength); + + (*newString)->body=(char *)malloc((*newString)->length); + if((*newString)->body==NULL) { + CTRelease(*newString, NULL); + + return NO; + } + memmove((*newString)->body, sourceString, (*newString)->length); + + return YES; +} + +void CTStringDealloc(void *existingCTStringObject) { + free(((CTString *)existingCTStringObject)->body); +} diff --git a/pool/shard002/C/0062663_hash.c b/pool/shard002/C/0062663_hash.c new file mode 100644 index 0000000000000000000000000000000000000000..66a8baf7f4cdfee7e660cc145bb0535abec25898 --- /dev/null +++ b/pool/shard002/C/0062663_hash.c @@ -0,0 +1,49 @@ +#include "../src/ezlib.h" + + +void my_hash_func (char *key, ezpointer value, ezpointer user_data) { + printf ("%s:%s:%s\n", key, value, user_data); +} + +bool my_list_func (ezpointer value, ezpointer user_data) { + printf ("%s:%s\n", user_data, value); +} + +int main (int argc, char **argv) { + + void *global_ctx; + EZHashTable *hash = NULL; + EZList *keys = NULL; + EZList *values = NULL; + + global_ctx = ez_new0 (void, 0); + + hash = ez_hash_table_new (1); + + ez_hash_table_insert (hash, "1", ez_strdup_ctx (global_ctx, "Jon Doe")); + ez_hash_table_insert (hash, "2", ez_strdup_ctx (global_ctx, "John Stiles")); + ez_hash_table_insert (hash, "3", ez_strdup_ctx (global_ctx, "Richard Miles")); + ez_hash_table_insert (hash, "4", ez_strdup_ctx (global_ctx, "Mary Major")); + + printf ("%s:%s\n", "2", ez_hash_table_lookup (hash, "2")); + printf ("%s:%s\n", "2", ez_hash_table_remove (hash, "2")); + + ez_hash_table_foreach (hash, my_hash_func, "user data"); + + printf ("%d\n", ez_hash_table_size (hash)); + + keys = ez_hash_table_get_keys (hash); + ez_list_foreach (keys, my_list_func, "key"); + ez_list_free (keys); + + values = ez_hash_table_get_values (hash); + ez_list_foreach (values, my_list_func, "value"); + ez_list_free (values); + + ez_hash_table_free (hash); + + ez_free (global_ctx); + + return 0; +} + diff --git a/pool/shard002/C/0062664_nf_nat_rule.c b/pool/shard002/C/0062664_nf_nat_rule.c new file mode 100644 index 0000000000000000000000000000000000000000..ebbd319f62f56741ea2d22da8529cda0586089a0 --- /dev/null +++ b/pool/shard002/C/0062664_nf_nat_rule.c @@ -0,0 +1,215 @@ +/* (C) 1999-2001 Paul `Rusty' Russell + * (C) 2002-2006 Netfilter Core Team + * + * 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. + */ + +/* Everything about the rules for NAT. */ +#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +#define NAT_VALID_HOOKS ((1 << NF_INET_PRE_ROUTING) | \ + (1 << NF_INET_POST_ROUTING) | \ + (1 << NF_INET_LOCAL_OUT) | \ + (1 << NF_INET_LOCAL_IN)) + +static const struct xt_table nat_table = { + .name = "nat", + .valid_hooks = NAT_VALID_HOOKS, + .me = THIS_MODULE, + .af = NFPROTO_IPV4, +}; + +/* Source NAT */ +static unsigned int +ipt_snat_target(struct sk_buff *skb, const struct xt_action_param *par) +{ + struct nf_conn *ct; + enum ip_conntrack_info ctinfo; + const struct nf_nat_multi_range_compat *mr = par->targinfo; + + NF_CT_ASSERT(par->hooknum == NF_INET_POST_ROUTING || + par->hooknum == NF_INET_LOCAL_IN); + + ct = nf_ct_get(skb, &ctinfo); + + /* Connection must be valid and new. */ + NF_CT_ASSERT(ct && (ctinfo == IP_CT_NEW || ctinfo == IP_CT_RELATED || + ctinfo == IP_CT_RELATED + IP_CT_IS_REPLY)); + NF_CT_ASSERT(par->out != NULL); + + return nf_nat_setup_info(ct, &mr->range[0], IP_NAT_MANIP_SRC); +} + +static unsigned int +ipt_dnat_target(struct sk_buff *skb, const struct xt_action_param *par) +{ + struct nf_conn *ct; + enum ip_conntrack_info ctinfo; + const struct nf_nat_multi_range_compat *mr = par->targinfo; + + NF_CT_ASSERT(par->hooknum == NF_INET_PRE_ROUTING || + par->hooknum == NF_INET_LOCAL_OUT); + + ct = nf_ct_get(skb, &ctinfo); + + /* Connection must be valid and new. */ + NF_CT_ASSERT(ct && (ctinfo == IP_CT_NEW || ctinfo == IP_CT_RELATED)); + + return nf_nat_setup_info(ct, &mr->range[0], IP_NAT_MANIP_DST); +} + +static int ipt_snat_checkentry(const struct xt_tgchk_param *par) +{ + const struct nf_nat_multi_range_compat *mr = par->targinfo; + + /* Must be a valid range */ + if (mr->rangesize != 1) { + pr_info("SNAT: multiple ranges no longer supported\n"); + return -EINVAL; + } + return 0; +} + +static int ipt_dnat_checkentry(const struct xt_tgchk_param *par) +{ + const struct nf_nat_multi_range_compat *mr = par->targinfo; + + /* Must be a valid range */ + if (mr->rangesize != 1) { + pr_info("DNAT: multiple ranges no longer supported\n"); + return -EINVAL; + } + return 0; +} + +static unsigned int +alloc_null_binding(struct nf_conn *ct, unsigned int hooknum) +{ + /* Force range to this IP; let proto decide mapping for + per-proto parts (hence not IP_NAT_RANGE_PROTO_SPECIFIED). + Use reply in case it's already been mangled (eg local packet). + */ + __be32 ip + = (HOOK2MANIP(hooknum) == IP_NAT_MANIP_SRC + ? ct->tuplehash[IP_CT_DIR_REPLY].tuple.dst.u3.ip + : ct->tuplehash[IP_CT_DIR_REPLY].tuple.src.u3.ip); + struct nf_nat_range range + = { IP_NAT_RANGE_MAP_IPS, ip, ip, { 0 }, { 0 } }; + + pr_debug("Allocating NULL binding for %p (%pI4)\n", ct, &ip); + return nf_nat_setup_info(ct, &range, HOOK2MANIP(hooknum)); +} + +int nf_nat_rule_find(struct sk_buff *skb, + unsigned int hooknum, + const struct net_device *in, + const struct net_device *out, + struct nf_conn *ct) +{ + struct net *net = nf_ct_net(ct); + int ret; + + ret = ipt_do_table(skb, hooknum, in, out, net->ipv4.nat_table); + + if (ret == NF_ACCEPT) { + if (!nf_nat_initialized(ct, HOOK2MANIP(hooknum))) + /* NUL mapping */ + ret = alloc_null_binding(ct, hooknum); + } + return ret; +} + +static struct xt_target ipt_snat_reg __read_mostly = { + .name = "SNAT", + .target = ipt_snat_target, + .targetsize = sizeof(struct nf_nat_multi_range_compat), + .table = "nat", + .hooks = (1 << NF_INET_POST_ROUTING) | (1 << NF_INET_LOCAL_IN), + .checkentry = ipt_snat_checkentry, + .family = AF_INET, +}; + +static struct xt_target ipt_dnat_reg __read_mostly = { + .name = "DNAT", + .target = ipt_dnat_target, + .targetsize = sizeof(struct nf_nat_multi_range_compat), + .table = "nat", + .hooks = (1 << NF_INET_PRE_ROUTING) | (1 << NF_INET_LOCAL_OUT), + .checkentry = ipt_dnat_checkentry, + .family = AF_INET, +}; + +static int __net_init nf_nat_rule_net_init(struct net *net) +{ + struct ipt_replace *repl; + + repl = ipt_alloc_initial_table(&nat_table); + if (repl == NULL) + return -ENOMEM; + net->ipv4.nat_table = ipt_register_table(net, &nat_table, repl); + kfree(repl); + if (IS_ERR(net->ipv4.nat_table)) + return PTR_ERR(net->ipv4.nat_table); + return 0; +} + +static void __net_exit nf_nat_rule_net_exit(struct net *net) +{ + ipt_unregister_table(net, net->ipv4.nat_table); +} + +static struct pernet_operations nf_nat_rule_net_ops = { + .init = nf_nat_rule_net_init, + .exit = nf_nat_rule_net_exit, +}; + +int __init nf_nat_rule_init(void) +{ + int ret; + + ret = register_pernet_subsys(&nf_nat_rule_net_ops); + if (ret != 0) + goto out; + ret = xt_register_target(&ipt_snat_reg); + if (ret != 0) + goto unregister_table; + + ret = xt_register_target(&ipt_dnat_reg); + if (ret != 0) + goto unregister_snat; + + return ret; + + unregister_snat: + xt_unregister_target(&ipt_snat_reg); + unregister_table: + unregister_pernet_subsys(&nf_nat_rule_net_ops); + out: + return ret; +} + +void nf_nat_rule_cleanup(void) +{ + xt_unregister_target(&ipt_dnat_reg); + xt_unregister_target(&ipt_snat_reg); + unregister_pernet_subsys(&nf_nat_rule_net_ops); +} diff --git a/pool/shard002/C/0062670_veris.c_OpenSER__cases1_stripFullBoth_arr_true-unreach-call.c b/pool/shard002/C/0062670_veris.c_OpenSER__cases1_stripFullBoth_arr_true-unreach-call.c new file mode 100644 index 0000000000000000000000000000000000000000..54b3cd643f6d51da1f36f741082942115f3e56cf --- /dev/null +++ b/pool/shard002/C/0062670_veris.c_OpenSER__cases1_stripFullBoth_arr_true-unreach-call.c @@ -0,0 +1,194 @@ +extern void __VERIFIER_error() __attribute__ ((__noreturn__)); + +void __VERIFIER_assert(int cond) { + if (!(cond)) { + ERROR: __VERIFIER_error(); + } + return; +} +#ifndef _BASE_H +#define _BASE_H + +/* Only #define it if it hasn't already been defined using -D */ +#ifndef BASE_SZ +#define BASE_SZ 2 +#endif + +#ifndef MAX_GETC +#define MAX_GETC 10 +#endif + +#endif + +#ifndef _STUBS_H +#define _STUBS_H + +#define NULL ((void *)0) +#define EOS 0 +#define EOF -1 +#define ERR -1 + +/* I had size_t being an unsigned long before, but that led to the + * infamous "Equality without matching types" error when I used a + * size_t to index into an array. */ +typedef int size_t; +typedef int bool; +#define true 1 +#define false 0 + +#define TYPECAST_MEMCPY 0 + +char *strchr(const char *s, int c); +char *strrchr(const char *s, int c); +char *strstr(const char *haystack, const char *needle); +char *strncpy (char *dest, const char *src, size_t n); +char *strncpy_ptr (char *dest, const char *src, size_t n); +char *strcpy (char *dest, const char *src); +unsigned strlen(const char *s); +int strncmp (const char *s1, const char *s2, size_t n); +int strcmp (const char *s1, const char *s2); +char *strcat(char *dest, const char *src); + +void *memcpy(void *dest, const void *src, size_t n); + +int isascii (int c); +int isspace (int c); + +int getc (/* ignore FILE* arg */); + +/* Extensions to libc's string library */ +char *strrand (char *s); +int istrrand (char *s); +int istrchr(const char *s, int c); +int istrrchr(const char *s, int c); +int istrncmp (const char *s1, int start, const char *s2, size_t n); +int istrstr(const char *haystack, const char *needle); + +/* Hackish duplicate functions to enable us to determine which claims + * are relevant. Oh, the hilarity. */ +char *r_strncpy (char *dest, const char *src, size_t n); +char *r_strcpy (char *dest, const char *src); +char *r_strcat(char *dest, const char *src); +char *r_strncat(char *dest, const char *src, size_t n); +void *r_memcpy(void *dest, const void *src, size_t n); + +#endif + +typedef unsigned int u_int; +typedef unsigned char u_int8_t; + +struct ieee80211_scan_entry { + u_int8_t *se_rsn_ie; /* captured RSN ie */ +}; + +#define IEEE80211_ELEMID_RSN 200 /* fake */ + +/* Size of an array leader[] which is written to buf[] before it is + * overflowed by the ie[] array. */ +#define LEADERSZ 1 + +/* We first write the "leader" to buf[], and then write from the "ie" + * array. buf[] has to be bigger than LEADERSZ by at least 2. */ +#define BUFSZ BASE_SZ + LEADERSZ + 3 + +/* Just has to be big enough to overflow buf[] + * Note that for each byte in ie[], two bytes are written to buf[] in + * encode_ie() */ +#define IESZ BUFSZ - LEADERSZ + +typedef int NSS_STATUS; + +/* Size of overflowed buffer. */ +#define FSTRING_LEN BASE_SZ /* originally 256 */ +typedef char fstring[FSTRING_LEN]; + +/* Size of input buffer. */ +#define INSZ (FSTRING_LEN+2) + +// Destination buffer. +#define BUF BASE_SZ + +// Source buffers. Make each big enough that the size checks in the OK +// versions are necessary to ensure safety. +#define GECOS BASE_SZ + 2 +#define LOGIN BASE_SZ + 2 + +#define EXPRESSION_LENGTH BASE_SZ +#define NEEDLE "EX" +#define NEEDLE_SZ 2 + +/* Enough to fill a buffer of size EXPRESSION_LENGTH, enough to + * contain the needle, and enough to overflow the buffer. */ +#define LINE_LENGTH EXPRESSION_LENGTH + NEEDLE_SZ + 4 + +/* Size of buffer being overflowed. + * Ensure that SUN_PATH_SZ - 1 is non-negative */ +#define SUN_PATH_SZ BASE_SZ + 1/* originally 108 */ + +/* Size of input buffer. */ +#define FILENAME_SZ SUN_PATH_SZ + 2 /* originally 1024 */ + +struct sockaddr_un +{ + char sun_path[SUN_PATH_SZ]; /* Path name. */ +}; + + + +static int parse_expression_list(char *str) +{ + int start=0, i=-1, j=-1; + char str2[EXPRESSION_LENGTH]; + + if (!str) return -1; + + do { + + /* i only changes here --> it's the "current character" */ + i++; + switch(str[i]) { + case EOS: /* word found */ + + /* Skip initial whitespace from start of the word being processed */ + while ((str[start] == ' ') || (str[start] == '\t')) start++; + + /* Skip quote marks */ + if (str[start] == '"') start++; + + /* Set j to point to the end of the current word */ + j = i-1; + + /* Skip over quotes and whitespace at the END of the word */ + while ((0 < j) && ((str[j] == ' ') || (str[j] == '\t'))) j--; + if ((0 < j) && (str[j] == '"')) j--; + + /* If word not empty.... */ + if (start<=j) { + /* valid word */ + if (j-start+1>=EXPRESSION_LENGTH) { + return -1; + } + /* OK */ + r_strncpy(str2, str+start, j-start+1); + str2[j-start+1] = EOS; + } else { + /* parsing error */ + return -1; + } + /* for the next word */ + start = i+1; + } + } while (str[i] != EOS); + + return 0; +} + + +int main () +{ + char A [LINE_LENGTH+1]; + A[LINE_LENGTH] = EOS; + + parse_expression_list (A); + return 0; +} diff --git a/pool/shard002/C/0062672_MOREDETOUR0912.c b/pool/shard002/C/0062672_MOREDETOUR0912.c new file mode 100644 index 0000000000000000000000000000000000000000..3b16ff861dd205bec1ad8c8e6bbc84a933ab8890 --- /dev/null +++ b/pool/shard002/C/0062672_MOREDETOUR0912.c @@ -0,0 +1,85 @@ +/* Copyright (C) 2018 Magnus Lång and Tuan Phong Ngo + * This benchmark is part of SWSC */ + +#include +#include +#include +#include + +atomic_int vars[2]; +atomic_int atom_1_r3_0; +atomic_int atom_1_r6_1; +atomic_int atom_2_r4_3; +atomic_int atom_2_r1_1; + +void *t0(void *arg){ +label_1:; + atomic_store_explicit(&vars[0], 4, memory_order_seq_cst); + + atomic_store_explicit(&vars[1], 1, memory_order_seq_cst); + return NULL; +} + +void *t1(void *arg){ +label_2:; + atomic_store_explicit(&vars[1], 2, memory_order_seq_cst); + int v2_r3 = atomic_load_explicit(&vars[0], memory_order_seq_cst); + atomic_store_explicit(&vars[0], 1, memory_order_seq_cst); + int v4_r6 = atomic_load_explicit(&vars[0], memory_order_seq_cst); + atomic_store_explicit(&vars[0], 3, memory_order_seq_cst); + int v22 = (v2_r3 == 0); + atomic_store_explicit(&atom_1_r3_0, v22, memory_order_seq_cst); + int v23 = (v4_r6 == 1); + atomic_store_explicit(&atom_1_r6_1, v23, memory_order_seq_cst); + return NULL; +} + +void *t2(void *arg){ +label_3:; + int v6_r1 = atomic_load_explicit(&vars[0], memory_order_seq_cst); + atomic_store_explicit(&vars[0], 2, memory_order_seq_cst); + + int v8_r4 = atomic_load_explicit(&vars[0], memory_order_seq_cst); + int v24 = (v8_r4 == 3); + atomic_store_explicit(&atom_2_r4_3, v24, memory_order_seq_cst); + int v25 = (v6_r1 == 1); + atomic_store_explicit(&atom_2_r1_1, v25, memory_order_seq_cst); + return NULL; +} + +int main(int argc, char *argv[]){ + pthread_t thr0; + pthread_t thr1; + pthread_t thr2; + + atomic_init(&vars[0], 0); + atomic_init(&vars[1], 0); + atomic_init(&atom_1_r3_0, 0); + atomic_init(&atom_1_r6_1, 0); + atomic_init(&atom_2_r4_3, 0); + atomic_init(&atom_2_r1_1, 0); + + pthread_create(&thr0, NULL, t0, NULL); + pthread_create(&thr1, NULL, t1, NULL); + pthread_create(&thr2, NULL, t2, NULL); + + pthread_join(thr0, NULL); + pthread_join(thr1, NULL); + pthread_join(thr2, NULL); + + int v9 = atomic_load_explicit(&vars[1], memory_order_seq_cst); + int v10 = (v9 == 2); + int v11 = atomic_load_explicit(&vars[0], memory_order_seq_cst); + int v12 = (v11 == 4); + int v13 = atomic_load_explicit(&atom_1_r3_0, memory_order_seq_cst); + int v14 = atomic_load_explicit(&atom_1_r6_1, memory_order_seq_cst); + int v15 = atomic_load_explicit(&atom_2_r4_3, memory_order_seq_cst); + int v16 = atomic_load_explicit(&atom_2_r1_1, memory_order_seq_cst); + int v17_conj = v15 & v16; + int v18_conj = v14 & v17_conj; + int v19_conj = v13 & v18_conj; + int v20_conj = v12 & v19_conj; + int v21_conj = v10 & v20_conj; + if (v21_conj == 1) assert(0); + return 0; +} diff --git a/pool/shard002/C/0062678_ioperm02.c b/pool/shard002/C/0062678_ioperm02.c new file mode 100644 index 0000000000000000000000000000000000000000..5c2e6cb81765290122628a8af6e4b92f45c3a675 --- /dev/null +++ b/pool/shard002/C/0062678_ioperm02.c @@ -0,0 +1,274 @@ +/* + * Copyright (c) Wipro Technologies Ltd, 2002. All Rights Reserved. + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of version 2 of the GNU General Public License as + * published by the Free Software Foundation. + * + * This program is distributed in the hope that it would be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write the Free Software Foundation, Inc., 59 + * Temple Place - Suite 330, Boston MA 02111-1307, USA. + * + */ +/********************************************************** + * + * TEST IDENTIFIER : ioperm02 + * + * EXECUTED BY : superuser + * + * TEST TITLE : Tests for error conditions + * + * TEST CASE TOTAL : 2 + * + * AUTHOR : Subhab Biwas + * + * SIGNALS + * Uses SIGUSR1 to pause before test if option set. + * (See the parse_opts(3) man page). + * + * DESCRIPTION + * Verify that + * 1) ioperm(2) returns -1 and sets errno to EINVAL for I/O port + * address greater than 0x3ff. + * 2) ioperm(2) returns -1 and sets errno to EPERM if the current + * user is not the super-user. + * + * Setup: + * Setup signal handling. + * Set expected errnos for logging + * Pause for SIGUSR1 if option specified. + * + * Test: + * Loop if the proper options are given. + * Execute system call + * Check return code and error number, if matching, + * Issue PASS message + * Otherwise, + * Issue FAIL message + * Perform testcase specific cleanup (if needed) + * + * Cleanup: + * Print errno log and/or timing stats if options given + * + * USAGE: + * ioperm02 [-c n] [-e] [-i n] [-I x] [-P x] [-t] [-h] [-f] [-p] + * where, -c n : Run n copies concurrently. + * -e : Turn on errno logging. + * -h : Show help screen + * -f : Turn off functional testing + * -i n : Execute test n times. + * -I x : Execute test for x seconds. + * -p : Pause for SIGUSR1 before starting + * -P x : Pause for x seconds between iterations. + * -t : Turn on syscall timing. + * + ****************************************************************/ + +char *TCID = "ioperm02"; /* Test program identifier. */ + +#if defined __i386__ || defined(__x86_64__) + +#include +#include +#include +#include +#include "test.h" +#include "usctest.h" + +#define NUM_BYTES 3 +#define TURN_ON 1 +#define TURN_OFF 0 +#define EXP_RET_VAL -1 +#ifndef IO_BITMAP_BITS +#define IO_BITMAP_BITS 1024 /* set to default value since some H/W may not support 0x10000 even with a 2.6.8 kernel */ +#define IO_BITMAP_BITS_16 65536 +#endif + +static void setup(); +static int setup1(void); +static void cleanup1(); +static void cleanup(); + +static int exp_enos[] = { EINVAL, EPERM, 0 }; + +static char nobody_uid[] = "nobody"; +struct passwd *ltpuser; + +struct test_cases_t { + long from; /* starting port address */ + long num; /* no. of bytes from starting address */ + int turn_on; + char *desc; /* test case description */ + int exp_errno; /* expected error number */ +}; + +int TST_TOTAL = 2; +struct test_cases_t *test_cases; + +int main(int ac, char **av) +{ + int lc, i; + char *msg; /* message returned from parse_opts */ + + /* parse standard options */ + if ((msg = parse_opts(ac, av, NULL, NULL)) != NULL) + tst_brkm(TBROK, NULL, "OPTION PARSING ERROR - %s", msg); + + setup(); + + for (lc = 0; TEST_LOOPING(lc); lc++) { + + Tst_count = 0; + + for (i = 0; i < TST_TOTAL; ++i) { + + if (i == 1) { + /* setup Non super-user for second test */ + if (setup1()) { + /* setup1() failed, skip this test */ + continue; + } + } + + /* Test the system call */ + + TEST(ioperm(test_cases[i].from, + test_cases[i].num, test_cases[i].turn_on)); + + if ((TEST_RETURN == EXP_RET_VAL) && + (TEST_ERRNO == test_cases[i].exp_errno)) { + tst_resm(TPASS, "Expected failure for %s, " + "errno: %d", test_cases[i].desc, + TEST_ERRNO); + } else { + tst_resm(TFAIL, "Unexpected results for %s ; " + "returned %ld (expected %d), errno %d " + "(expected errno %d)", + test_cases[i].desc, + TEST_RETURN, EXP_RET_VAL, + TEST_ERRNO, test_cases[i].exp_errno); + } + + TEST_ERROR_LOG(TEST_ERRNO); + + if (i == 1) { + /* revert back to super user */ + cleanup1(); + } else { + } + } + + } + + /* cleanup and exit */ + cleanup(); + + tst_exit(); + +} + +/* setup1() - set up non-super user for second test case */ +int setup1(void) +{ + /* switch to "nobody" user */ + if (seteuid(ltpuser->pw_uid) == -1) { + tst_resm(TWARN, "Failed to set effective" + "uid to %d", ltpuser->pw_uid); + return 1; + } + return 0; +} + +/* cleanup1() - reset to super user for second test case */ +void cleanup1() +{ + /* reset user as root */ + if (seteuid(0) == -1) { + tst_brkm(TBROK, NULL, "Failed to set uid as root"); + } +} + +/* setup() - performs all ONE TIME setup for this test */ +void setup() +{ + + tst_sig(NOFORK, DEF_HANDLER, cleanup); + + /* Check whether we are root */ + if (geteuid() != 0) { + tst_brkm(TBROK, NULL, "Must be root for this test!"); + } + + /* Check if "nobody" user id exists */ + if ((ltpuser = getpwnam(nobody_uid)) == NULL) { + tst_brkm(TBROK, NULL, "\"nobody\" user id doesn't exist"); + } + + /* + * The value of IO_BITMAP_BITS (include/asm-i386/processor.h) changed + * from kernel 2.6.8 to permit 16-bits (65536) ioperm + * + * Ricky Ng-Adam, rngadam@yahoo.com + * */ + test_cases = + (struct test_cases_t *)malloc(sizeof(struct test_cases_t) * 2); + test_cases[0].num = NUM_BYTES; + test_cases[0].turn_on = TURN_ON; + test_cases[0].desc = "Invalid I/O address"; + test_cases[0].exp_errno = EINVAL; + test_cases[1].num = NUM_BYTES; + test_cases[1].turn_on = TURN_ON; + test_cases[1].desc = "Non super-user"; + test_cases[1].exp_errno = EPERM; + if ((tst_kvercmp(2, 6, 8) < 0) || (tst_kvercmp(2, 6, 9) == 0)) { + /*try invalid ioperm on 1022, 1023, 1024 */ + test_cases[0].from = (IO_BITMAP_BITS - NUM_BYTES) + 1; + + /*try get valid ioperm on 1021, 1022, 1023 */ + test_cases[1].from = IO_BITMAP_BITS - NUM_BYTES; + } else { + /*try invalid ioperm on 65534, 65535, 65536 */ + test_cases[0].from = (IO_BITMAP_BITS_16 - NUM_BYTES) + 1; + + /*try valid ioperm on 65533, 65534, 65535 */ + test_cases[1].from = IO_BITMAP_BITS_16 - NUM_BYTES; + } + + /* Set up the expected error numbers for -e option */ + TEST_EXP_ENOS(exp_enos); + + TEST_PAUSE; + +} + +void cleanup() +{ + + /* + * print timing stats if that option was specified. + * print errno log if that option was specified. + */ + TEST_CLEANUP; + +} + +#else /* __i386__ */ + +#include "test.h" +#include "usctest.h" + +int TST_TOTAL = 0; /* Total number of test cases. */ + +int main() +{ + tst_resm(TPASS, + "LSB v1.3 does not specify ioperm() for this architecture."); + tst_exit(); + tst_exit(); +} + +#endif /* __i386__ */ \ No newline at end of file diff --git a/pool/shard002/C/0062681_fixuns-trunc-1.c b/pool/shard002/C/0062681_fixuns-trunc-1.c new file mode 100644 index 0000000000000000000000000000000000000000..0d0942952497ab6ba2afbc65085ce70c1d71dc3e --- /dev/null +++ b/pool/shard002/C/0062681_fixuns-trunc-1.c @@ -0,0 +1,31 @@ +/* { dg-do run } */ +/* { dg-options "-std=c99" } */ + +unsigned long foo(double d) +{ + return (unsigned long) d; +} + +extern void abort(void); + +int main(void) +{ + double d; + unsigned long l; + +#ifdef __LP64__ + d = 9223372036854775808.7; + l = 1LL << 63; + + if (foo(d) != l) + abort(); +#endif + + d = 122485.2; + l = 122485; + + if (foo(d) != l) + abort(); + + return 0; +} diff --git a/pool/shard002/C/0062689_lavf.c b/pool/shard002/C/0062689_lavf.c new file mode 100644 index 0000000000000000000000000000000000000000..56bfa29ca3d0d80a6543a713307fa60df725f20c --- /dev/null +++ b/pool/shard002/C/0062689_lavf.c @@ -0,0 +1,226 @@ +/***************************************************************************** + * lavf.c: libavformat input + ***************************************************************************** + * Copyright (C) 2009-2010 x264 project + * + * Authors: Mike Gurlitz + * Steven Walters + * + * 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 02111, USA. + * + * This program is also available under a commercial proprietary license. + * For more information, contact us at licensing@x264.com. + *****************************************************************************/ + +#include "input.h" +#define FAIL_IF_ERROR( cond, ... ) FAIL_IF_ERR( cond, "lavf", __VA_ARGS__ ) +#undef DECLARE_ALIGNED +#include +#include + +typedef struct +{ + AVFormatContext *lavf; + int stream_id; + int next_frame; + int vfr_input; + cli_pic_t *first_pic; +} lavf_hnd_t; + +static int read_frame_internal( cli_pic_t *p_pic, lavf_hnd_t *h, int i_frame, video_info_t *info ) +{ + if( h->first_pic && !info ) + { + /* see if the frame we are requesting is the frame we have already read and stored. + * if so, retrieve the pts and image data before freeing it. */ + if( !i_frame ) + { + XCHG( cli_image_t, p_pic->img, h->first_pic->img ); + p_pic->pts = h->first_pic->pts; + XCHG( void*, p_pic->opaque, h->first_pic->opaque ); + } + lavf_input.release_frame( h->first_pic, NULL ); + lavf_input.picture_clean( h->first_pic ); + free( h->first_pic ); + h->first_pic = NULL; + if( !i_frame ) + return 0; + } + + AVCodecContext *c = h->lavf->streams[h->stream_id]->codec; + AVPacket *pkt = p_pic->opaque; + AVFrame frame; + avcodec_get_frame_defaults( &frame ); + + while( i_frame >= h->next_frame ) + { + int finished = 0; + int ret = 0; + do + { + ret = av_read_frame( h->lavf, pkt ); + + if( pkt->stream_index == h->stream_id ) + { + if( ret < 0 ) + pkt->size = 0; + + c->reordered_opaque = pkt->pts; + if( avcodec_decode_video2( c, &frame, &finished, pkt ) < 0 ) + x264_cli_log( "lavf", X264_LOG_WARNING, "video decoding failed on frame %d\n", h->next_frame ); + } + } while( !finished && ret >= 0 ); + + if( !finished ) + return -1; + + h->next_frame++; + } + + memcpy( p_pic->img.stride, frame.linesize, sizeof(p_pic->img.stride) ); + memcpy( p_pic->img.plane, frame.data, sizeof(p_pic->img.plane) ); + p_pic->img.height = c->height; + p_pic->img.csp = c->pix_fmt | X264_CSP_OTHER; + p_pic->img.width = c->width; + + if( info ) + { + info->interlaced = frame.interlaced_frame; + info->tff = frame.top_field_first; + } + + if( h->vfr_input ) + { + p_pic->pts = p_pic->duration = 0; + if( c->has_b_frames && frame.reordered_opaque != AV_NOPTS_VALUE ) + p_pic->pts = frame.reordered_opaque; + else if( pkt->dts != AV_NOPTS_VALUE ) + p_pic->pts = pkt->dts; // for AVI files + else if( info ) + { + h->vfr_input = info->vfr = 0; + return 0; + } + } + + return 0; +} + +static int open_file( char *psz_filename, hnd_t *p_handle, video_info_t *info, cli_input_opt_t *opt ) +{ + lavf_hnd_t *h = calloc( 1, sizeof(lavf_hnd_t) ); + if( !h ) + return -1; + av_register_all(); + if( !strcmp( psz_filename, "-" ) ) + psz_filename = "pipe:"; + + /* if resolution was passed in, parse it and colorspace into parameters. this allows raw video support */ + AVFormatParameters *param = NULL; + if( opt->resolution ) + { + param = calloc( 1, sizeof(AVFormatParameters) ); + if( !param ) + return -1; + sscanf( opt->resolution, "%dx%d", ¶m->width, ¶m->height ); + param->pix_fmt = opt->colorspace ? av_get_pix_fmt( opt->colorspace ) : PIX_FMT_YUV420P; + } + + FAIL_IF_ERROR( av_open_input_file( &h->lavf, psz_filename, NULL, 0, param ), "could not open input file\n" ) + if( param ) + free( param ); + FAIL_IF_ERROR( av_find_stream_info( h->lavf ) < 0, "could not find input stream info\n" ) + + int i = 0; + while( i < h->lavf->nb_streams && h->lavf->streams[i]->codec->codec_type != CODEC_TYPE_VIDEO ) + i++; + FAIL_IF_ERROR( i == h->lavf->nb_streams, "could not find video stream\n" ) + h->stream_id = i; + h->next_frame = 0; + AVCodecContext *c = h->lavf->streams[i]->codec; + info->fps_num = h->lavf->streams[i]->r_frame_rate.num; + info->fps_den = h->lavf->streams[i]->r_frame_rate.den; + info->timebase_num = h->lavf->streams[i]->time_base.num; + info->timebase_den = h->lavf->streams[i]->time_base.den; + /* lavf is thread unsafe as calling av_read_frame invalidates previously read AVPackets */ + info->thread_safe = 0; + h->vfr_input = info->vfr; + FAIL_IF_ERROR( avcodec_open( c, avcodec_find_decoder( c->codec_id ) ), + "could not find decoder for video stream\n" ) + + /* prefetch the first frame and set/confirm flags */ + h->first_pic = malloc( sizeof(cli_pic_t) ); + FAIL_IF_ERROR( !h->first_pic || lavf_input.picture_alloc( h->first_pic, X264_CSP_OTHER, info->width, info->height ), + "malloc failed\n" ) + else if( read_frame_internal( h->first_pic, h, 0, info ) ) + return -1; + + info->width = c->width; + info->height = c->height; + info->csp = h->first_pic->img.csp; + info->num_frames = h->lavf->streams[i]->nb_frames; + info->sar_height = c->sample_aspect_ratio.den; + info->sar_width = c->sample_aspect_ratio.num; + + /* avisynth stores rgb data vertically flipped. */ + if( !strcasecmp( get_filename_extension( psz_filename ), "avs" ) && + (c->pix_fmt == PIX_FMT_BGRA || c->pix_fmt == PIX_FMT_BGR24) ) + info->csp |= X264_CSP_VFLIP; + + *p_handle = h; + + return 0; +} + +static int picture_alloc( cli_pic_t *pic, int csp, int width, int height ) +{ + if( x264_cli_pic_alloc( pic, csp, width, height ) ) + return -1; + pic->img.planes = 4; + pic->opaque = malloc( sizeof(AVPacket) ); + if( !pic->opaque ) + return -1; + av_init_packet( pic->opaque ); + return 0; +} + +static int read_frame( cli_pic_t *pic, hnd_t handle, int i_frame ) +{ + return read_frame_internal( pic, handle, i_frame, NULL ); +} + +static int release_frame( cli_pic_t *pic, hnd_t handle ) +{ + av_free_packet( pic->opaque ); + av_init_packet( pic->opaque ); + return 0; +} + +static void picture_clean( cli_pic_t *pic ) +{ + free( pic->opaque ); + memset( pic, 0, sizeof(cli_pic_t) ); +} + +static int close_file( hnd_t handle ) +{ + lavf_hnd_t *h = handle; + avcodec_close( h->lavf->streams[h->stream_id]->codec ); + av_close_input_file( h->lavf ); + free( h ); + return 0; +} + +const cli_input_t lavf_input = { open_file, picture_alloc, read_frame, release_frame, picture_clean, close_file }; diff --git a/pool/shard002/C/0062692_vect-strided-u16-i4.c b/pool/shard002/C/0062692_vect-strided-u16-i4.c new file mode 100644 index 0000000000000000000000000000000000000000..2e6fb02b81782e8acbe63453a7e848fc9714afa7 --- /dev/null +++ b/pool/shard002/C/0062692_vect-strided-u16-i4.c @@ -0,0 +1,75 @@ +/* { dg-require-effective-target vect_int } */ + +#include +#include "tree-vect.h" + +#define N 128 + +typedef struct { + unsigned short a; + unsigned short b; + unsigned short c; + unsigned short d; +} s; + +volatile int y = 0; + +__attribute__ ((noinline)) int +main1 (s *arr) +{ + int i; + s *ptr = arr; + s res[N]; + unsigned short x, y, z, w; + + for (i = 0; i < N; i++) + { + x = ptr->b - ptr->a; + y = ptr->d - ptr->c; + res[i].c = x + y; + z = ptr->a + ptr->c; + w = ptr->b + ptr->d; + res[i].a = z + w; + res[i].d = x + y; + res[i].b = x + y; + ptr++; + } + + /* check results: */ + for (i = 0; i < N; i++) + { + if (res[i].c != arr[i].b - arr[i].a + arr[i].d - arr[i].c + || res[i].a != arr[i].a + arr[i].c + arr[i].b + arr[i].d + || res[i].d != arr[i].b - arr[i].a + arr[i].d - arr[i].c + || res[i].b != arr[i].b - arr[i].a + arr[i].d - arr[i].c) + abort (); + } + + return 0; +} + +int main (void) +{ + int i; + s arr[N]; + + check_vect (); + + for (i = 0; i < N; i++) + { + arr[i].a = i; + arr[i].b = i * 2; + arr[i].c = 17; + arr[i].d = i+34; + if (y) /* Avoid vectorization. */ + abort (); + } + + main1 (arr); + + return 0; +} + +/* { dg-final { scan-tree-dump-times "vectorized 1 loops" 1 "vect" { target vect_strided4 } } } */ +/* { dg-final { cleanup-tree-dump "vect" } } */ + diff --git a/pool/shard002/C/0062695_ol_notify.c b/pool/shard002/C/0062695_ol_notify.c new file mode 100644 index 0000000000000000000000000000000000000000..fc5b29c9e03878850e0a95d7c2afe109901d6acd --- /dev/null +++ b/pool/shard002/C/0062695_ol_notify.c @@ -0,0 +1,145 @@ +/* -*- mode: C; c-basic-offset: 2; indent-tabs-mode: nil; -*- */ +/* + * Copyright (C) 2009-2011 Tiger Soldier + * + * This file is part of OSD Lyrics. + * + * OSD Lyrics 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. + * + * OSD Lyrics 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 OSD Lyrics. If not, see . + */ +#include +#include "config.h" +#include "ol_notify.h" +#include "ol_intl.h" +#include "ol_utils.h" +#include "ol_debug.h" + +static const char *UNKNOWN_TITLE = N_("Unknown title"); +static const char *UNKNOWN_ARTIST = N_("Unknown artist"); +static const char *INFO_FORMAT = "%s"; +static const char *INFO_FORMAT_ALBUM = "%s\n%s"; +static const int DEFAULT_TIMEOUT = -1; + +static NotifyNotification *notify = NULL; + +static gboolean _init (); +static NotifyNotification *_get_notify (const char *summary, + const char *body, + const char *icon); + +static NotifyNotification * +_get_notify (const char *summary, + const char *body, + const char *icon) +{ + ol_debugf ("summary: %s\n" + "body: %s\n" + "icon: %s\n", + summary, + body, + icon); + if (notify == NULL) + { +#ifdef HAVE_LIBNOTIFY_0_7 + notify = notify_notification_new (summary, + body, + icon); +#else + notify = notify_notification_new (summary, + body, + icon, + NULL); +#endif + } + else + { + notify_notification_update (notify, + summary, + body, + icon); + } + return notify; +} + +static gboolean +_init () +{ + if (!notify_is_initted()) + notify_init (_(PROGRAM_NAME)); + return TRUE; +} + +void +ol_notify_init () +{ + _init (); +} + +void +ol_notify_unload () +{ + if (notify != NULL) + g_object_unref (notify); + notify_uninit (); +} + +void +ol_notify_music_change (OlMetadata *info, const char *icon) +{ + ol_assert (info != NULL); + if (!_init ()) + { + return; + } + char *art = NULL; + const char *title = ol_metadata_get_title (info); + const char *artist = ol_metadata_get_artist (info); + if (title == NULL && artist == NULL) + return; + if (title == NULL) + title = _(UNKNOWN_TITLE); + if (artist == NULL) + artist = _(UNKNOWN_ARTIST); + const char *album = ol_metadata_get_album (info); + char *body = NULL; + if (album == NULL) + { + body = g_markup_printf_escaped (INFO_FORMAT, + artist); + } + else + { + body = g_markup_printf_escaped (INFO_FORMAT_ALBUM, + artist, + album); + } + if (ol_metadata_get_art (info) != NULL) + { + const char *art_uri = ol_metadata_get_art (info); + if (art_uri[0] == '/') + art = g_strdup (art_uri); + else if (g_str_has_prefix (art_uri, "file://")) + art = g_filename_from_uri (art_uri, NULL, NULL); + if (art && !ol_path_is_file (art)) + { + g_free (art); + art = NULL; + } + } + NotifyNotification *music_notify = _get_notify (title, body, art ? art : icon); + notify_notification_set_timeout (music_notify, + DEFAULT_TIMEOUT); + notify_notification_show (music_notify, NULL); + g_free (body); + g_free (art); +} diff --git a/pool/shard002/C/0062696_apf27.c b/pool/shard002/C/0062696_apf27.c new file mode 100644 index 0000000000000000000000000000000000000000..30e720d167a6ce3398473cd8df7fa3867176586e --- /dev/null +++ b/pool/shard002/C/0062696_apf27.c @@ -0,0 +1,256 @@ +/* + * Copyright (C) 2008-2013 Eric Jarrige + * + * based on the files by + * Sascha Hauer, Pengutronix + * + * SPDX-License-Identifier: GPL-2.0+ + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "apf27.h" +#include "crc.h" +#include "fpga.h" + +DECLARE_GLOBAL_DATA_PTR; + +/* + * Fuse bank 1 row 8 is "reserved for future use" and therefore available for + * customer use. The APF27 board uses this fuse to store the board revision: + * 0: initial board revision + * 1: first revision - Presence of the second RAM chip on the board is blown in + * fuse bank 1 row 9 bit 0 - No hardware change + * N: to be defined + */ +static u32 get_board_rev(void) +{ + struct iim_regs *iim = (struct iim_regs *)IMX_IIM_BASE; + + return readl(&iim->bank[1].fuse_regs[8]); +} + +/* + * Fuse bank 1 row 9 is "reserved for future use" and therefore available for + * customer use. The APF27 board revision 1 uses the bit 0 to permanently store + * the presence of the second RAM chip + * 0: AFP27 with 1 RAM of 64 MiB + * 1: AFP27 with 2 RAM chips of 64 MiB each (128MB) + */ +static int get_num_ram_bank(void) +{ + struct iim_regs *iim = (struct iim_regs *)IMX_IIM_BASE; + int nr_dram_banks = 1; + + if ((get_board_rev() > 0) && (CONFIG_NR_DRAM_BANKS > 1)) + nr_dram_banks += readl(&iim->bank[1].fuse_regs[9]) & 0x01; + else + nr_dram_banks = CONFIG_NR_DRAM_POPULATED; + + return nr_dram_banks; +} + +static void apf27_port_init(int port, u32 gpio_dr, u32 ocr1, u32 ocr2, + u32 iconfa1, u32 iconfa2, u32 iconfb1, u32 iconfb2, + u32 icr1, u32 icr2, u32 imr, u32 gpio_dir, u32 gpr, + u32 puen, u32 gius) +{ + struct gpio_port_regs *regs = (struct gpio_port_regs *)IMX_GPIO_BASE; + + writel(gpio_dr, ®s->port[port].gpio_dr); + writel(ocr1, ®s->port[port].ocr1); + writel(ocr2, ®s->port[port].ocr2); + writel(iconfa1, ®s->port[port].iconfa1); + writel(iconfa2, ®s->port[port].iconfa2); + writel(iconfb1, ®s->port[port].iconfb1); + writel(iconfb2, ®s->port[port].iconfb2); + writel(icr1, ®s->port[port].icr1); + writel(icr2, ®s->port[port].icr2); + writel(imr, ®s->port[port].imr); + writel(gpio_dir, ®s->port[port].gpio_dir); + writel(gpr, ®s->port[port].gpr); + writel(puen, ®s->port[port].puen); + writel(gius, ®s->port[port].gius); +} + +#define APF27_PORT_INIT(n) apf27_port_init(PORT##n, ACFG_DR_##n##_VAL, \ + ACFG_OCR1_##n##_VAL, ACFG_OCR2_##n##_VAL, ACFG_ICFA1_##n##_VAL, \ + ACFG_ICFA2_##n##_VAL, ACFG_ICFB1_##n##_VAL, ACFG_ICFB2_##n##_VAL, \ + ACFG_ICR1_##n##_VAL, ACFG_ICR2_##n##_VAL, ACFG_IMR_##n##_VAL, \ + ACFG_DDIR_##n##_VAL, ACFG_GPR_##n##_VAL, ACFG_PUEN_##n##_VAL, \ + ACFG_GIUS_##n##_VAL) + +static void apf27_iomux_init(void) +{ + APF27_PORT_INIT(A); + APF27_PORT_INIT(B); + APF27_PORT_INIT(C); + APF27_PORT_INIT(D); + APF27_PORT_INIT(E); + APF27_PORT_INIT(F); +} + +static int apf27_devices_init(void) +{ + int i; + unsigned int mode[] = { + PC5_PF_I2C2_DATA, + PC6_PF_I2C2_CLK, + PD17_PF_I2C_DATA, + PD18_PF_I2C_CLK, + }; + + for (i = 0; i < ARRAY_SIZE(mode); i++) + imx_gpio_mode(mode[i]); + +#ifdef CONFIG_MXC_UART + mx27_uart1_init_pins(); +#endif + +#ifdef CONFIG_FEC_MXC + mx27_fec_init_pins(); +#endif + +#ifdef CONFIG_MXC_MMC + mx27_sd2_init_pins(); + imx_gpio_mode((GPIO_PORTF | GPIO_OUT | GPIO_PUEN | GPIO_GPIO | 16)); + gpio_request(PC_PWRON, "pc_pwron"); + gpio_set_value(PC_PWRON, 1); +#endif + return 0; +} + +static void apf27_setup_csx(void) +{ + struct weim_regs *weim = (struct weim_regs *)IMX_WEIM_BASE; + + writel(ACFG_CS0U_VAL, &weim->cs0u); + writel(ACFG_CS0L_VAL, &weim->cs0l); + writel(ACFG_CS0A_VAL, &weim->cs0a); + + writel(ACFG_CS1U_VAL, &weim->cs1u); + writel(ACFG_CS1L_VAL, &weim->cs1l); + writel(ACFG_CS1A_VAL, &weim->cs1a); + + writel(ACFG_CS2U_VAL, &weim->cs2u); + writel(ACFG_CS2L_VAL, &weim->cs2l); + writel(ACFG_CS2A_VAL, &weim->cs2a); + + writel(ACFG_CS3U_VAL, &weim->cs3u); + writel(ACFG_CS3L_VAL, &weim->cs3l); + writel(ACFG_CS3A_VAL, &weim->cs3a); + + writel(ACFG_CS4U_VAL, &weim->cs4u); + writel(ACFG_CS4L_VAL, &weim->cs4l); + writel(ACFG_CS4A_VAL, &weim->cs4a); + + writel(ACFG_CS5U_VAL, &weim->cs5u); + writel(ACFG_CS5L_VAL, &weim->cs5l); + writel(ACFG_CS5A_VAL, &weim->cs5a); + + writel(ACFG_EIM_VAL, &weim->eim); +} + +static void apf27_setup_port(void) +{ + struct system_control_regs *system = + (struct system_control_regs *)IMX_SYSTEM_CTL_BASE; + + writel(ACFG_FMCR_VAL, &system->fmcr); +} + +int board_init(void) +{ + gd->bd->bi_boot_params = PHYS_SDRAM_1 + 0x100; + + apf27_setup_csx(); + apf27_setup_port(); + apf27_iomux_init(); + apf27_devices_init(); +#if defined(CONFIG_FPGA) + APF27_init_fpga(); +#endif + + + return 0; +} + +int dram_init(void) +{ + gd->ram_size = get_ram_size((void *)PHYS_SDRAM_1, PHYS_SDRAM_1_SIZE); + if (get_num_ram_bank() > 1) + gd->ram_size += get_ram_size((void *)PHYS_SDRAM_2, + PHYS_SDRAM_2_SIZE); + + return 0; +} + +void dram_init_banksize(void) +{ + gd->bd->bi_dram[0].start = PHYS_SDRAM_1; + gd->bd->bi_dram[0].size = get_ram_size((void *)PHYS_SDRAM_1, + PHYS_SDRAM_1_SIZE); + gd->bd->bi_dram[1].start = PHYS_SDRAM_2; + if (get_num_ram_bank() > 1) + gd->bd->bi_dram[1].size = get_ram_size((void *)PHYS_SDRAM_2, + PHYS_SDRAM_2_SIZE); + else + gd->bd->bi_dram[1].size = 0; +} + +ulong board_get_usable_ram_top(ulong total_size) +{ + ulong ramtop; + + if (get_num_ram_bank() > 1) + ramtop = PHYS_SDRAM_2 + get_ram_size((void *)PHYS_SDRAM_2, + PHYS_SDRAM_2_SIZE); + else + ramtop = PHYS_SDRAM_1 + get_ram_size((void *)PHYS_SDRAM_1, + PHYS_SDRAM_1_SIZE); + + return ramtop; +} + +int checkboard(void) +{ + printf("Board: Armadeus APF27 revision %d\n", get_board_rev()); + return 0; +} + +#ifdef CONFIG_SPL_BUILD +inline void hang(void) +{ + for (;;) + ; +} + +void board_init_f(ulong bootflag) +{ + /* + * copy ourselves from where we are running to where we were + * linked at. Use ulong pointers as all addresses involved + * are 4-byte-aligned. + */ + ulong *start_ptr, *end_ptr, *link_ptr, *run_ptr, *dst; + asm volatile ("ldr %0, =_start" : "=r"(start_ptr)); + asm volatile ("ldr %0, =_end" : "=r"(end_ptr)); + asm volatile ("ldr %0, =board_init_f" : "=r"(link_ptr)); + asm volatile ("adr %0, board_init_f" : "=r"(run_ptr)); + for (dst = start_ptr; dst < end_ptr; dst++) + *dst = *(dst+(run_ptr-link_ptr)); + + /* + * branch to nand_boot's link-time address. + */ + asm volatile("ldr pc, =nand_boot"); +} +#endif /* CONFIG_SPL_BUILD */ diff --git a/pool/shard002/C/0062705_nmbd_browserdb.c b/pool/shard002/C/0062705_nmbd_browserdb.c new file mode 100644 index 0000000000000000000000000000000000000000..cc1ce6c2ab560bcc32d06324c29fe61b14b75913 --- /dev/null +++ b/pool/shard002/C/0062705_nmbd_browserdb.c @@ -0,0 +1,183 @@ +/* + Unix SMB/Netbios implementation. + Version 1.9. + NBT netbios routines and daemon - version 2 + Copyright (C) Andrew Tridgell 1994-1998 + Copyright (C) Luke Kenneth Casson Leighton 1994-1998 + Copyright (C) Jeremy Allison 1994-1998 + Copyright (C) Christopher R. Hertel 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., 675 Mass Ave, Cambridge, MA 02139, USA. + +*/ +/* -------------------------------------------------------------------------- ** + * Modified July 1998 by CRH. + * I converted this module to use the canned doubly-linked lists. I also + * added comments above the functions where possible. + */ + +#include "includes.h" + +/* -------------------------------------------------------------------------- ** + * Variables... + * + * lmb_browserlist - This is our local master browser list. + */ + +ubi_dlNewList( lmb_browserlist ); + + +/* -------------------------------------------------------------------------- ** + * Functions... + */ + +/* ************************************************************************** ** + * Remove and free a browser list entry. + * + * Input: browc - A pointer to the entry to be removed from the list and + * freed. + * Output: none. + * + * ************************************************************************** ** + */ +static void remove_lmb_browser_entry( struct browse_cache_record *browc ) + { + safe_free( (char *)ubi_dlRemThis( lmb_browserlist, browc ) ); + } /* remove_lmb_browser_entry */ + +/* ************************************************************************** ** + * Update a browser death time. + * + * Input: browc - Pointer to the entry to be updated. + * Output: none. + * + * ************************************************************************** ** + */ +void update_browser_death_time( struct browse_cache_record *browc ) + { + /* Allow the new lmb to miss an announce period before we remove it. */ + browc->death_time = time(NULL) + ( (CHECK_TIME_MST_ANNOUNCE + 2) * 60 ); + } /* update_browser_death_time */ + +/* ************************************************************************** ** + * Create a browser entry and add it to the local master browser list. + * + * Input: work_name + * browser_name + * ip + * + * Output: Pointer to the new entry, or NULL if malloc() failed. + * + * ************************************************************************** ** + */ +struct browse_cache_record *create_browser_in_lmb_cache( char *work_name, + char *browser_name, + struct in_addr ip ) + { + struct browse_cache_record *browc; + time_t now = time( NULL ); + + browc = (struct browse_cache_record *)malloc( sizeof( *browc ) ); + + if( NULL == browc ) + { + DEBUG( 0, ("create_browser_in_lmb_cache: malloc fail !\n") ); + return( NULL ); + } + + memset( (char *)browc, '\0', sizeof( *browc ) ); + + /* For a new lmb entry we want to sync with it after one minute. This + will allow it time to send out a local announce and build its + browse list. + */ + browc->sync_time = now + 60; + + /* Allow the new lmb to miss an announce period before we remove it. */ + browc->death_time = now + ( (CHECK_TIME_MST_ANNOUNCE + 2) * 60 ); + + StrnCpy( browc->lmb_name, browser_name, sizeof(browc->lmb_name)-1 ); + StrnCpy( browc->work_group, work_name, sizeof(browc->work_group)-1 ); + strupper( browc->lmb_name ); + strupper( browc->work_group ); + + browc->ip = ip; + + (void)ubi_dlAddTail( lmb_browserlist, browc ); + + if( DEBUGLVL( 3 ) ) + { + Debug1( "nmbd_browserdb:create_browser_in_lmb_cache()\n" ); + Debug1( " Added lmb cache entry for workgroup %s ", browc->work_group ); + Debug1( "name %s IP %s ", browc->lmb_name, inet_ntoa(ip) ); + Debug1( "ttl %d\n", (int)browc->death_time ); + } + + return( browc ); + } /* create_browser_in_lmb_cache */ + +/* ************************************************************************** ** + * Find a browser entry in the local master browser list. + * + * Input: browser_name - The name for which to search. + * + * Output: A pointer to the matching entry, or NULL if no match was found. + * + * ************************************************************************** ** + */ +struct browse_cache_record *find_browser_in_lmb_cache( char *browser_name ) + { + struct browse_cache_record *browc; + + for( browc = (struct browse_cache_record *)ubi_dlFirst( lmb_browserlist ); + browc; + browc = (struct browse_cache_record *)ubi_dlNext( browc ) ) + if( strequal( browser_name, browc->lmb_name ) ) + break; + + return( browc ); + } /* find_browser_in_lmb_cache */ + +/* ************************************************************************** ** + * Expire timed out browsers in the browserlist. + * + * Input: t - Expiration time. Entries with death times less than this + * value will be removed from the list. + * Output: none. + * + * ************************************************************************** ** + */ +void expire_lmb_browsers( time_t t ) + { + struct browse_cache_record *browc; + struct browse_cache_record *nextbrowc; + + for( browc = (struct browse_cache_record *)ubi_dlFirst( lmb_browserlist ); + browc; + browc = nextbrowc ) + { + nextbrowc = (struct browse_cache_record *)ubi_dlNext( browc ); + + if( browc->death_time < t ) + { + if( DEBUGLVL( 3 ) ) + { + Debug1( "nmbd_browserdb:expire_lmb_browsers()\n" ); + Debug1( " Removing timed out lmb entry %s\n", browc->lmb_name ); + } + remove_lmb_browser_entry( browc ); + } + } + } /* expire_lmb_browsers */ diff --git a/pool/shard002/C/0062715_xftimer.c b/pool/shard002/C/0062715_xftimer.c new file mode 100644 index 0000000000000000000000000000000000000000..292ebbb7746d6f99c81a2f43c9a3c8f209ec5818 --- /dev/null +++ b/pool/shard002/C/0062715_xftimer.c @@ -0,0 +1,26 @@ +#include "typedef.h" +#include "xftimer.h" + +void XF_TimerSetTimeout(XF_Timer *timer, uint16 timeoutMS) { + XF_Timer tick = XF_TickGetValue(); + timer->timeout = timeoutMS + tick; + if (timer->timeout < tick) timer->overflow = 1; +} + +uint8 XF_TimerIsTimeout(XF_Timer *timer) { + XF_Timer tick = XF_TickGetValue(); + if (0 == timer->overflow) { + if (timer->timeout < tick) return 1; + } + else { + if (timer->timeout > tick) timer->overflow = 0; + } + return 0; +} + +void XF_TimerDelayMs(uint16 ms) { + XF_Timer t = {0}; + + XF_TimerSetTimeout(&t, ms); + while (!XF_TimerIsTimeout(&t)); +} diff --git a/pool/shard002/C/0062719_cliente.c b/pool/shard002/C/0062719_cliente.c new file mode 100644 index 0000000000000000000000000000000000000000..513a456a085e4d47f8092f9de7667cccec58dc66 --- /dev/null +++ b/pool/shard002/C/0062719_cliente.c @@ -0,0 +1,141 @@ +/* Cliente */ + +/* Arquivo: cliente.c */ + +#include +#include +#include +#include +#include +#include +#include +#include + +#include "minimax.c" + +//#define ip "192.168.1.124" +#define tmb 1024 +#define porta 23 +int main () +{ + + // game + printf("Computer: O, You: X\nPlay (1)st or (2)nd? "); + int board[9] = {0,0,0,0,0,0,0,0,0}; + //computer quadrados are 1, player quadrados are -1. + int player=0; + scanf("%d",&player); + printf("\n"); + unsigned turn; + + char ip[16] = "192.168.0.115"; + char buffer[tmb], bufaux[tmb], *loc; + char comandos[]="/x /mem /disc /time /pros /port /help"; + int tbuf, skt, escolha; + struct sockaddr_in serv; + + system("clear"); + + printf("\n Robotica Inteligente - UFBA\n\n"); + + //printf("\n>> Digite o ip do Servidor ou /x para sair: "); + //gets(ip); + + skt = socket(AF_INET, SOCK_STREAM, 0); + + serv.sin_family = AF_INET; + serv.sin_addr.s_addr = inet_addr(ip); + serv.sin_port = htons (porta); + + memset (&(serv.sin_zero), 0x00, sizeof (serv.sin_zero)); + if(connect (skt, (struct sockaddr *)&serv, sizeof (struct sockaddr)) != 0) + { + puts("\n> Servidor nao Encontrado\n"); + exit(0); + + } + printf(">> A Conexao com o Servidor %s foi estabelecida na porta %d \n\n",ip,porta); + // Recebe ack do serv + tbuf = recv (skt, buffer, tmb, 0); + buffer[tbuf] = 0x00; + printf (">: %s\n",buffer); + + + // switch (cmd[0]) { + // case 'G': + // + // break; + // } + + // Envia ack p/ serv + strcpy(buffer, "Client comunicando OK!!!"); + send(skt, buffer, strlen(buffer), 0 ); + // while(strcmp(buffer,"/x") != 0){ + + desenhar(board); + + for(turn = 0; turn < 9 && vencer(board) == 0; ++turn) { + int move; + if((turn+player) % 2 == 0){ + move = movimentoDoRobo(board); + printf("Movimento do Robo: %d\n",move); + desenhar(board); + // gets(buffer); + // strcpy(bufaux,buffer); + sprintf(buffer,"%d",move); + // itoa(move,buffer,10); + send(skt, buffer, strlen(buffer), 0); + printf("Waiting for response message: \n"); + // Recebe ack do serv + tbuf = recv (skt, buffer, tmb, 0); + buffer[tbuf] = 0x00; + while(strcmp(bufaux,buffer) != 0){ + printf ("Response: %s\n",buffer); + strcpy(bufaux,buffer); + } + + } + else { + movimentoDoJogador(board); + desenhar(board); + } + + } + switch(vencer(board)) { + case 0: + printf("A draw. How droll.\n"); + break; + case 1: + desenhar(board); + printf("You lose.\n"); + break; + case -1: + printf("You win. Inconceivable!\n"); + break; + } + close(skt); + printf (">>A conexao com o servidor foi finalizada!!!\n\n"); + exit(0); +} + +void jogada(){ + // if((turn+player) % 2 == 0) + // movimentoDoRobo(board); + // else { + // desenhar(board); + // movimentoDoJogador(board); + // } + // // } + // switch(vencer(board)) { + // case 0: + // printf("A draw. How droll.\n"); + // break; + // case 1: + // desenhar(board); + // printf("You lose.\n"); + // break; + // case -1: + // printf("You win. Inconceivable!\n"); + // break; + // } +} diff --git a/pool/shard002/C/0062723_lockfile.c b/pool/shard002/C/0062723_lockfile.c new file mode 100644 index 0000000000000000000000000000000000000000..17d6237eaa6430ee568b23f0f594b7f0f7013a7d --- /dev/null +++ b/pool/shard002/C/0062723_lockfile.c @@ -0,0 +1,82 @@ +/* + * Copyright (c) 1998-2001 Sendmail, Inc. and its suppliers. + * All rights reserved. + * Copyright (c) 1983, 1995-1997 Eric P. Allman. All rights reserved. + * Copyright (c) 1988, 1993 + * The Regents of the University of California. All rights reserved. + * + * By using this file, you agree to the terms and conditions set + * forth in the LICENSE file which can be found at the top level of + * the sendmail distribution. + * + */ + +#include + +SM_RCSID("@(#)$Id: lockfile.c,v 8.21 2003/11/10 22:57:38 ca Exp $") + + +/* +** LOCKFILE -- lock a file using flock or (shudder) fcntl locking +** +** Parameters: +** fd -- the file descriptor of the file. +** filename -- the file name (for error messages). [unused] +** ext -- the filename extension. [unused] +** type -- type of the lock. Bits can be: +** LOCK_EX -- exclusive lock. +** LOCK_NB -- non-blocking. +** LOCK_UN -- unlock. +** +** Returns: +** true if the lock was acquired. +** false otherwise. +*/ + +bool +lockfile(fd, filename, ext, type) + int fd; + char *filename; + char *ext; + int type; +{ +#if !HASFLOCK + int action; + struct flock lfd; + + memset(&lfd, '\0', sizeof lfd); + if (bitset(LOCK_UN, type)) + lfd.l_type = F_UNLCK; + else if (bitset(LOCK_EX, type)) + lfd.l_type = F_WRLCK; + else + lfd.l_type = F_RDLCK; + if (bitset(LOCK_NB, type)) + action = F_SETLK; + else + action = F_SETLKW; + + if (fcntl(fd, action, &lfd) >= 0) + return true; + + /* + ** On SunOS, if you are testing using -oQ/tmp/mqueue or + ** -oA/tmp/aliases or anything like that, and /tmp is mounted + ** as type "tmp" (that is, served from swap space), the + ** previous fcntl will fail with "Invalid argument" errors. + ** Since this is fairly common during testing, we will assume + ** that this indicates that the lock is successfully grabbed. + */ + + if (errno == EINVAL) + return true; + +#else /* !HASFLOCK */ + + if (flock(fd, type) >= 0) + return true; + +#endif /* !HASFLOCK */ + + return false; +} diff --git a/pool/shard002/C/0062733_omap_palmas.c b/pool/shard002/C/0062733_omap_palmas.c new file mode 100644 index 0000000000000000000000000000000000000000..0ccb1af0098648af68992dbfda75d795a989c078 --- /dev/null +++ b/pool/shard002/C/0062733_omap_palmas.c @@ -0,0 +1,158 @@ +/** + * OMAP and TWL PMIC specific intializations. + * + * Copyright (C) 2011 Texas Instruments Incorporated. + * Vishwanat BS + * + * 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 "voltage.h" +#include "twl-common.h" +#include "pm.h" + +#define OMAP5_SRI2C_SLAVE_ADDR 0x12 +#define OMAP5_VDD_MPU_SR_VOLT_REG 0x23 +#define OMAP5_VDD_MPU_SR_CMD_REG 0x22 +#define OMAP5_VDD_MM_SR_VOLT_REG 0x2B +#define OMAP5_VDD_MM_SR_CMD_REG 0x2A +#define OMAP5_VDD_CORE_SR_VOLT_REG 0x37 +#define OMAP5_VDD_CORE_SR_CMD_REG 0x36 + +static u8 twl6035_uv_to_vsel(unsigned long uv) +{ + if (uv > 1650000) { + pr_err("%s:OUT OF RANGE! non mapped uv for %ld\n", + __func__, uv); + return 0; + } + + if (uv == 0) + return 0; + + return DIV_ROUND_UP((uv - 500000), 10000) + 6; +} + +static unsigned long twl6035_vsel_to_uv(const u8 vsel) +{ + u8 temp_vsel = vsel; + + if (vsel > 127) { + pr_err("%s:OUT OF RANGE! non mapped vsel %d\n", + __func__, vsel); + return 0; + } + + if (vsel == 0) + return 0; + + if (temp_vsel > 121) + temp_vsel = 121; + + temp_vsel = temp_vsel - 6; + if (temp_vsel < 0) + return 500000; + else + return 500000 + temp_vsel * 10000; +} + +static struct omap_voltdm_pmic twl6035_vcore1_pmic = { + .slew_rate = 220, /* BUG00117 - TI internal ref */ + .step_size = 10000, + .switch_on_time = 549, + .vp_erroroffset = OMAP5_VP_CONFIG_ERROROFFSET, + .vp_vstepmin = OMAP5_VP_VSTEPMIN_VSTEPMIN, + .vp_vstepmax = OMAP5_VP_VSTEPMAX_VSTEPMAX, + .vddmin = 0, + .vddmax = 1650000, + .vp_timeout_us = OMAP5_VP_VLIMITTO_TIMEOUT_US, + .i2c_slave_addr = OMAP5_SRI2C_SLAVE_ADDR, + .volt_reg_addr = OMAP5_VDD_MPU_SR_VOLT_REG, + .cmd_reg_addr = OMAP5_VDD_MPU_SR_CMD_REG, + .i2c_high_speed = false, + .i2c_scll_low = 0x15, + .i2c_scll_high = 0xe, + .i2c_hscll_low = 0x0B, + .i2c_hscll_high = 0x00, + .vsel_to_uv = twl6035_vsel_to_uv, + .uv_to_vsel = twl6035_uv_to_vsel, +}; + +static struct omap_voltdm_pmic twl6035_vcore2_pmic = { + .slew_rate = 220, /* BUG00117 - TI internal ref */ + .step_size = 10000, + .switch_on_time = 549, + .vp_erroroffset = OMAP5_VP_CONFIG_ERROROFFSET, + .vp_vstepmin = OMAP5_VP_VSTEPMIN_VSTEPMIN, + .vp_vstepmax = OMAP5_VP_VSTEPMAX_VSTEPMAX, + .vddmin = 0, + .vddmax = 1650000, + .vp_timeout_us = OMAP5_VP_VLIMITTO_TIMEOUT_US, + .i2c_slave_addr = OMAP5_SRI2C_SLAVE_ADDR, + .volt_reg_addr = OMAP5_VDD_MM_SR_VOLT_REG, + .cmd_reg_addr = OMAP5_VDD_MM_SR_CMD_REG, + .i2c_high_speed = false, + .i2c_scll_low = 0x15, + .i2c_scll_high = 0xe, + .i2c_hscll_low = 0x0B, + .i2c_hscll_high = 0x00, + .vsel_to_uv = twl6035_vsel_to_uv, + .uv_to_vsel = twl6035_uv_to_vsel, +}; + +static struct omap_voltdm_pmic twl6035_vcore3_pmic = { + .slew_rate = 220, /* BUG00117 - TI internal ref */ + .step_size = 10000, + .startup_time = 500, + .shutdown_time = 500, + .switch_on_time = 549, + .vp_erroroffset = OMAP5_VP_CONFIG_ERROROFFSET, + .vp_vstepmin = OMAP5_VP_VSTEPMIN_VSTEPMIN, + .vp_vstepmax = OMAP5_VP_VSTEPMAX_VSTEPMAX, + .vddmin = 0, + .vddmax = 1650000, + .vp_timeout_us = OMAP5_VP_VLIMITTO_TIMEOUT_US, + .i2c_slave_addr = OMAP5_SRI2C_SLAVE_ADDR, + .volt_reg_addr = OMAP5_VDD_CORE_SR_VOLT_REG, + .cmd_reg_addr = OMAP5_VDD_CORE_SR_CMD_REG, + .i2c_high_speed = false, + .i2c_scll_low = 0x15, + .i2c_scll_high = 0xe, + .i2c_hscll_low = 0x0B, + .i2c_hscll_high = 0x00, + .vsel_to_uv = twl6035_vsel_to_uv, + .uv_to_vsel = twl6035_uv_to_vsel, +}; + +static __initdata struct omap_pmic_map omap_twl_map[] = { + { + .name = "mpu", + .cpu = PMIC_CPU_OMAP54XX, + .pmic_data = &twl6035_vcore1_pmic, + }, + { + .name = "core", + .cpu = PMIC_CPU_OMAP54XX, + .pmic_data = &twl6035_vcore3_pmic, + }, + { + .name = "mm", + .cpu = PMIC_CPU_OMAP54XX, + .pmic_data = &twl6035_vcore2_pmic, + + }, + /* Terminator */ + { .name = NULL, .pmic_data = NULL}, +}; + +int __init omap_palmas_init(void) +{ + return omap_pmic_register_data(omap_twl_map); +} diff --git a/pool/shard002/C/0062749_main.c b/pool/shard002/C/0062749_main.c new file mode 100644 index 0000000000000000000000000000000000000000..de0f58d7e82a1a023b6d5c258fb443db26ac8023 --- /dev/null +++ b/pool/shard002/C/0062749_main.c @@ -0,0 +1,63 @@ +#include +#include +#include +#include +#include + +#define MAX_EVENTS 10 + +/* + * Program requires pipe 'pipe1' to exist. It has to have some input first, + * so program can start. Executable simply accept input on stdin and 'pipe1', + * to print it to stdout. + * + * In first TTY: + * $> mkfifo pipe1 + * $> make && ./main + * + * In second TTY: + * $> echo 'something' > pipe1 + */ + +int main(int argc, char **argv) +{ + int p1 = open("pipe1", O_RDONLY); + + int hub = epoll_create1(0); + struct epoll_event ev, events[MAX_EVENTS]; + + /*Set event to be edge-triggered*/ + ev.events = EPOLLIN | EPOLLET; + + ev.data.fd = 0; + epoll_ctl(hub, EPOLL_CTL_ADD, 0, &ev); + ev.data.fd = p1; + epoll_ctl(hub, EPOLL_CTL_ADD, p1, &ev); + + char buff[10]; + for (;;) + { + int n, nfds = epoll_wait(hub, events, MAX_EVENTS, -1); + for (n = 0; n < nfds; ++n) + { + memset(&buff, 0, sizeof(char) * 10); + if (events[n].data.fd == 0) + { + read(0, &buff, 10); + buff[9] = '\0'; + printf("%s", buff); + } + if (events[n].data.fd == p1) + { + read(p1, &buff, 10); + buff[9] = '\0'; + printf("%s", buff); + } + fflush(stdout); + } + } + + close(hub); + close(p1); + return 0; +} diff --git a/pool/shard002/C/0062752_poll.c b/pool/shard002/C/0062752_poll.c new file mode 100644 index 0000000000000000000000000000000000000000..5b863c5806eb24ec1151a6d3f2394251154ee3fb --- /dev/null +++ b/pool/shard002/C/0062752_poll.c @@ -0,0 +1,97 @@ +/* + * sys_poll(struct pollfd __user *ufds, unsigned int nfds, int timeout); + */ +#include +#include +#include +#include "random.h" +#include "sanitise.h" +#include "utils.h" +#include "compat.h" + +static const unsigned long poll_events[] = { + POLLIN, POLLPRI, POLLOUT, POLLERR, + POLLHUP, POLLNVAL, POLLRDBAND, POLLWRNORM, + POLLWRBAND, POLLMSG, POLLREMOVE, POLLRDHUP, + POLLFREE, POLL_BUSY_LOOP, +}; + +static void sanitise_poll(struct syscallrecord *rec) +{ + struct pollfd *pollfd; + unsigned int i; + unsigned int num_fds = rand() % 10; + + pollfd = zmalloc(num_fds * sizeof(struct pollfd)); + + for (i = 0; i < num_fds; i++) { + pollfd[i].fd = get_random_fd(); + pollfd[i].events = set_rand_bitmask(ARRAY_SIZE(poll_events), poll_events); + } + + rec->a1 = (unsigned long) pollfd; + rec->a2 = num_fds; +} + +static void post_poll(struct syscallrecord *rec) +{ + freeptr(&rec->a1); +} + +struct syscallentry syscall_poll = { + .name = "poll", + .num_args = 3, + .arg1name = "ufds", + .arg2name = "nfds", + .arg3name = "timeout_msecs", + .arg3type = ARG_RANGE, + .low3range = 0, + .hi3range = 1, + .flags = NEED_ALARM, + .sanitise = sanitise_poll, + .post = post_poll, +}; + +/* + * SYSCALL_DEFINE5(ppoll, struct pollfd __user *, ufds, unsigned int, nfds, + struct timespec __user *, tsp, const sigset_t __user *, sigmask, size_t, sigsetsize) + */ + +static void sanitise_ppoll(struct syscallrecord *rec) +{ + struct pollfd *fds; + struct timespec *ts; + + sanitise_poll(rec); + + fds = (struct pollfd *) rec->a1; + if (fds == NULL) + return; + + ts = zmalloc(sizeof(struct timespec)); + rec->a3 = (unsigned long) ts; + ts->tv_sec = 1; + ts->tv_nsec = 0; + + rec->a5 = sizeof(sigset_t); +} + +static void post_ppoll(struct syscallrecord *rec) +{ + freeptr(&rec->a1); + freeptr(&rec->a4); +} + +struct syscallentry syscall_ppoll = { + .name = "ppoll", + .num_args = 5, + .arg1name = "ufds", + .arg2name = "nfds", + .arg3name= "tsp", + .arg4name = "sigmask", + .arg4type = ARG_ADDRESS, + .arg5name = "sigsetsize", + .flags = NEED_ALARM, + .sanitise = sanitise_ppoll, + .post = post_ppoll, +}; diff --git a/pool/shard002/C/0062770_ampi_stack.c b/pool/shard002/C/0062770_ampi_stack.c new file mode 100644 index 0000000000000000000000000000000000000000..f435986765bebccfac3039a5fdbe694840b6ae97 --- /dev/null +++ b/pool/shard002/C/0062770_ampi_stack.c @@ -0,0 +1,30 @@ +#include "ampi_stack.h" + +void AMPI_push(ampi_stack *s, double val) { + s->v[s->top] = val; + (s->top)=(s->top)+1; +} + +double AMPI_pop(ampi_stack *s) { + (s->top)=(s->top)-1; + return (s->v[s->top]); +} + +ampi_stack* AMPI_stack_create(size_t size) { + ampi_stack* s = (ampi_stack*) malloc(sizeof(ampi_stack)); + s->top=0; + s->v = (double*) malloc(sizeof(double)*size); + s->size=size; + + return s; +} + +void AMPI_stack_delete(ampi_stack *s) { + free(s->v); + free(s); +} + +void AMPI_stack_reset(ampi_stack *s) { + /* We assume that the stack is always used to full size */ + s->top = s->size; +} diff --git a/pool/shard002/C/0062779_subviewer1dec.c b/pool/shard002/C/0062779_subviewer1dec.c new file mode 100644 index 0000000000000000000000000000000000000000..93db4ebf21acd34e7b9ee632fbebcf2796b1e418 --- /dev/null +++ b/pool/shard002/C/0062779_subviewer1dec.c @@ -0,0 +1,124 @@ +/* + * Copyright (c) 2012 Clément Bœsch + * + * 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 + */ + +/** + * @file + * SubViewer v1 subtitle demuxer + */ + +#include "avformat.h" +#include "internal.h" +#include "subtitles.h" + +typedef struct { + FFDemuxSubtitlesQueue q; +} SubViewer1Context; + +static int subviewer1_probe(AVProbeData *p) +{ + const unsigned char *ptr = p->buf; + + if (strstr(ptr, "******** START SCRIPT ********")) + return AVPROBE_SCORE_EXTENSION; + return 0; +} + +static int subviewer1_read_header(AVFormatContext *s) +{ + int delay = 0; + AVPacket *sub = NULL; + SubViewer1Context *subviewer1 = s->priv_data; + AVStream *st = avformat_new_stream(s, NULL); + + if (!st) + return AVERROR(ENOMEM); + avpriv_set_pts_info(st, 64, 1, 1); + st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE; + st->codec->codec_id = AV_CODEC_ID_SUBVIEWER1; + + while (!avio_feof(s->pb)) { + char line[4096]; + int len = ff_get_line(s->pb, line, sizeof(line)); + int hh, mm, ss; + + if (!len) + break; + + if (!strncmp(line, "[DELAY]", 7)) { + ff_get_line(s->pb, line, sizeof(line)); + sscanf(line, "%d", &delay); + } + + if (sscanf(line, "[%d:%d:%d]", &hh, &mm, &ss) == 3) { + const int64_t pos = avio_tell(s->pb); + int64_t pts_start = hh*3600LL + mm*60LL + ss + delay; + + len = ff_get_line(s->pb, line, sizeof(line)); + line[strcspn(line, "\r\n")] = 0; + if (!*line) { + if (sub) + sub->duration = pts_start - sub->pts; + } else { + sub = ff_subtitles_queue_insert(&subviewer1->q, line, len, 0); + if (!sub) + return AVERROR(ENOMEM); + sub->pos = pos; + sub->pts = pts_start; + sub->duration = -1; + } + } + } + + ff_subtitles_queue_finalize(s, &subviewer1->q); + return 0; +} + +static int subviewer1_read_packet(AVFormatContext *s, AVPacket *pkt) +{ + SubViewer1Context *subviewer1 = s->priv_data; + return ff_subtitles_queue_read_packet(&subviewer1->q, pkt); +} + +static int subviewer1_read_seek(AVFormatContext *s, int stream_index, + int64_t min_ts, int64_t ts, int64_t max_ts, int flags) +{ + SubViewer1Context *subviewer1 = s->priv_data; + return ff_subtitles_queue_seek(&subviewer1->q, s, stream_index, + min_ts, ts, max_ts, flags); +} + +static int subviewer1_read_close(AVFormatContext *s) +{ + SubViewer1Context *subviewer1 = s->priv_data; + ff_subtitles_queue_clean(&subviewer1->q); + return 0; +} + +AVInputFormat ff_subviewer1_demuxer = { + .name = "subviewer1", + .long_name = NULL_IF_CONFIG_SMALL("SubViewer v1 subtitle format"), + .priv_data_size = sizeof(SubViewer1Context), + .read_probe = subviewer1_probe, + .read_header = subviewer1_read_header, + .read_packet = subviewer1_read_packet, + .read_seek2 = subviewer1_read_seek, + .read_close = subviewer1_read_close, + .extensions = "sub", +}; diff --git a/pool/shard002/C/0062780_t-init_set.c b/pool/shard002/C/0062780_t-init_set.c new file mode 100644 index 0000000000000000000000000000000000000000..a0fb3caf360363e735bbeea71dd6592e6c2e0e73 --- /dev/null +++ b/pool/shard002/C/0062780_t-init_set.c @@ -0,0 +1,78 @@ +/* + Copyright (C) 2011 Sebastian Pancratz + + This file is part of FLINT. + + FLINT 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. See . +*/ + +#include +#include +#include +#include "flint.h" +#include "ulong_extras.h" +#include "fmpz.h" + +int +main(void) +{ + int i, result; + FLINT_TEST_INIT(state); + + flint_printf("init_set...."); + fflush(stdout); + + + + /* Small integers */ + for (i = 0; i < 10000 * flint_test_multiplier(); i++) + { + fmpz_t a, b; + + fmpz_init(a); + fmpz_randtest(a, state, FLINT_BITS - 2); + fmpz_init_set(b, a); + + result = fmpz_equal(a, b); + if (!result) + { + flint_printf("FAIL:\n\n"); + flint_printf("a = "), fmpz_print(a), flint_printf("\n"); + flint_printf("b = "), fmpz_print(b), flint_printf("\n"); + abort(); + } + + fmpz_clear(a); + fmpz_clear(b); + } + + /* Large integers */ + for (i = 0; i < 10000 * flint_test_multiplier(); i++) + { + fmpz_t a, b; + + fmpz_init(a); + fmpz_randtest(a, state, 2 * FLINT_BITS); + fmpz_init_set(b, a); + + result = fmpz_equal(a, b); + if (!result) + { + flint_printf("FAIL:\n\n"); + flint_printf("a = "), fmpz_print(a), flint_printf("\n"); + flint_printf("b = "), fmpz_print(b), flint_printf("\n"); + abort(); + } + + fmpz_clear(a); + fmpz_clear(b); + } + + FLINT_TEST_CLEANUP(state); + + flint_printf("PASS\n"); + return 0; +} diff --git a/pool/shard002/C/0062783_tss2_writeauthorizenv.c b/pool/shard002/C/0062783_tss2_writeauthorizenv.c new file mode 100644 index 0000000000000000000000000000000000000000..618a696b0fa74046bfbae02a1505b443bee9aca0 --- /dev/null +++ b/pool/shard002/C/0062783_tss2_writeauthorizenv.c @@ -0,0 +1,60 @@ +/* SPDX-License-Identifier: BSD-3-Clause */ + +#include +#include +#include + +#include "tools/fapi/tss2_template.h" + +/* Context struct used to store passed command line parameters */ +static struct cxt { + char const *nvPath; + char const *policyPath; +} ctx; + +/* Parse command line parameters */ +static bool on_option(char key, char *value) { + switch (key) { + case 'p': + ctx.nvPath = value; + break; + case 'P': + ctx.policyPath = value; + break; + } + return true; +} + +/* Define possible command line parameters */ +static bool tss2_tool_onstart(tpm2_options **opts) { + struct option topts[] = { + {"nvPath" , required_argument, NULL, 'p'}, + {"policyPath" , required_argument, NULL, 'P'} + }; + return (*opts = tpm2_options_new ("p:P:", ARRAY_LEN(topts), topts, + on_option, NULL, 0)) != NULL; +} + +/* Execute specific tool */ +static int tss2_tool_onrun (FAPI_CONTEXT *fctx) { + /* Check availability of required parameters */ + if (!ctx.nvPath) { + fprintf (stderr, "No NV path provided, use --nvPath\n"); + return -1; + } + if (!ctx.policyPath) { + fprintf (stderr, "No policy path provided, use --policyPath\n"); + return -1; + } + + /* Execute FAPI command with passed arguments */ + TSS2_RC r = Fapi_WriteAuthorizeNv(fctx, ctx.nvPath, ctx.policyPath); + if (r != TSS2_RC_SUCCESS){ + LOG_PERR ("Fapi_WriteAuthorizeNv", r); + return 1; + } + + return 0; +} + +TSS2_TOOL_REGISTER("writeauthorizenv", tss2_tool_onstart, tss2_tool_onrun, NULL) diff --git a/pool/shard002/C/0062784_mg5uart_reg.c b/pool/shard002/C/0062784_mg5uart_reg.c new file mode 100644 index 0000000000000000000000000000000000000000..f4509ab0257dfe56c6d536042773dfcac774eb84 --- /dev/null +++ b/pool/shard002/C/0062784_mg5uart_reg.c @@ -0,0 +1,60 @@ +/* + * This file contains a typical set of register access routines which may be + * used with the mg5uart chip if accesses to the chip are as follows: + * + * + registers are accessed as uint32_t 's + * + registers are only u32-aligned (no address gaps) + * + * COPYRIGHT (c) 1989-2001. + * 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. + * + * $Id: mg5uart_reg.c,v 1.4 2009/11/30 05:09:01 ralf Exp $ + */ + +#include + +#ifndef _MG5UART_MULTIPLIER +#define _MG5UART_MULTIPLIER 1 +#define _MG5UART_NAME(_X) _X +#define _MG5UART_TYPE uint32_t +#endif + +#define CALCULATE_REGISTER_ADDRESS( _base, _reg ) \ + (_MG5UART_TYPE *)((_base) + ((_reg) * _MG5UART_MULTIPLIER )) + +/* + * MG5UART Get Register Routine + */ + +uint8_t _MG5UART_NAME(mg5uart_get_register)( + uint32_t ulCtrlPort, + uint8_t ucRegNum +) +{ + _MG5UART_TYPE *port; + + port = CALCULATE_REGISTER_ADDRESS( ulCtrlPort, ucRegNum ); + + return *port; +} + +/* + * MG5UART Set Register Routine + */ + +void _MG5UART_NAME(mg5uart_set_register)( + uint32_t ulCtrlPort, + uint8_t ucRegNum, + uint8_t ucData +) +{ + _MG5UART_TYPE *port; + + port = CALCULATE_REGISTER_ADDRESS( ulCtrlPort, ucRegNum ); + + *port = ucData; +} diff --git a/pool/shard002/C/0062787_mddi_client_s6d04d1.c b/pool/shard002/C/0062787_mddi_client_s6d04d1.c new file mode 100644 index 0000000000000000000000000000000000000000..341d89a4e71c8d5b64ccb63a2e9530ec94fbb707 --- /dev/null +++ b/pool/shard002/C/0062787_mddi_client_s6d04d1.c @@ -0,0 +1,272 @@ +/* + * 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 "mddi_client_eid.h" + +static DECLARE_WAIT_QUEUE_HEAD(s6d04d1_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 *fb_callback; + struct work_struct panel_work; + struct workqueue_struct *fb_wq; + int s6d04d1_got_int; +}; + +static struct cabc_config cabc_config; +static struct platform_device mddi_samsung_cabc = { + .name = "samsung_cabc", + .id = 0, + .dev = { + .platform_data = &cabc_config, + } +}; + +static void s6d04d1_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->fb_callback = callback; + if (panel->s6d04d1_got_int) { + panel->s6d04d1_got_int = 0; + client_data->activate_link(client_data); /* clears interrupt */ + } +} + +static void s6d04d1_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->s6d04d1_got_int) { + panel->s6d04d1_got_int = 0; + client_data->activate_link(client_data); /* clears interrupt */ + } + + if (wait_event_timeout(s6d04d1_vsync_wait, panel->s6d04d1_got_int, + HZ/2) == 0) + printk(KERN_ERR "timeout waiting for VSYNC\n"); + + panel->s6d04d1_got_int = 0; + /* interrupt clears when screen dma starts */ +} + +static int s6d04d1_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; + + ret = bridge_data->uninit(bridge_data, client_data); + if (ret) { + printk(KERN_INFO "mddi s6d04d1 client: non zero return from " + "uninit\n"); + return ret; + } + client_data->suspend(client_data); + return 0; +} + +static int s6d04d1_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; + + client_data->resume(client_data); + ret = bridge_data->init(bridge_data, client_data); + if (ret) + return ret; + return 0; +} + +static int s6d04d1_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; + + if (cabc_config.bl_handle) + cabc_config.bl_handle(&mddi_samsung_cabc, LED_OFF); + + return bridge_data->blank(bridge_data, client_data); +} + +static int s6d04d1_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; + + if (cabc_config.bl_handle) { + mdelay(40); + cabc_config.bl_handle(&mddi_samsung_cabc, LED_FULL); + } + + return bridge_data->unblank(bridge_data, client_data); +} + +irqreturn_t s6d04d1_vsync_interrupt(int irq, void *data) +{ + struct panel_info *panel = data; + + panel->s6d04d1_got_int = 1; + if (panel->fb_callback) { + panel->fb_callback->func(panel->fb_callback); + panel->fb_callback = NULL; + } + wake_up(&s6d04d1_vsync_wait); + + return IRQ_HANDLED; +} + +static int setup_vsync(struct panel_info *panel, int init) +{ + int ret; + int gpio = 97; + 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; + + ret = request_irq(irq, s6d04d1_vsync_interrupt, IRQF_TRIGGER_RISING, + "vsync", panel); + if (ret) + goto err_request_irq_failed; + + printk(KERN_INFO "vsync on gpio %d now %d\n", + gpio, gpio_get_value(gpio)); + return 0; + +uninit: + free_irq(gpio_to_irq(gpio), panel->client_data); +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_s6d04d1_probe(struct platform_device *pdev) +{ + 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; + int ret; + + struct panel_info *panel = kzalloc(sizeof(struct panel_info), + GFP_KERNEL); + + printk(KERN_DEBUG "%s: enter.\n", __func__); + + if (!panel) + return -ENOMEM; + platform_set_drvdata(pdev, panel); + + ret = setup_vsync(panel, 1); + if (ret) { + dev_err(&pdev->dev, "mddi_s6d04d1_setup_vsync failed\n"); + return ret; + } + + cabc_config.pwm_data = panel_data->pwm; + cabc_config.min_level = panel_data->min_level; + if (panel_data->caps & MSMFB_CAP_CABC) { + printk(KERN_INFO "CABC enabled\n"); + cabc_config.client = client_data; + platform_device_register(&mddi_samsung_cabc); + } + + panel->client_data = client_data; + panel->panel_data.suspend = s6d04d1_suspend; + panel->panel_data.resume = s6d04d1_resume; + panel->panel_data.wait_vsync = s6d04d1_wait_vsync; + panel->panel_data.request_vsync = s6d04d1_request_vsync; + panel->panel_data.blank = s6d04d1_blank; + panel->panel_data.unblank = s6d04d1_unblank; + panel->panel_data.fb_data = &bridge_data->fb_data; + panel->panel_data.caps = 0; + + 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); + + return 0; +} + +static int mddi_s6d04d1_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_0101_04d1 = { + .probe = mddi_s6d04d1_probe, + .remove = mddi_s6d04d1_remove, + .driver = { .name = "mddi_c_0101_04d1" }, +}; + +static int __init mddi_client_s6d04d1_init(void) +{ + return platform_driver_register(&mddi_client_0101_04d1); +} + +module_init(mddi_client_s6d04d1_init); + diff --git a/pool/shard002/C/0062795_rsurface.c b/pool/shard002/C/0062795_rsurface.c new file mode 100644 index 0000000000000000000000000000000000000000..75a19822865bfda22f5759347949df7b204b6d41 --- /dev/null +++ b/pool/shard002/C/0062795_rsurface.c @@ -0,0 +1,81 @@ +#include +#include +#include +#include "RStarTree/RStarTree.h" +#include "rsurface.h" + +/* RSurface */ + +struct _RSurface { + RSTREE t; + char * name; +}; + +RSurface * r_surface_open (const char * fname, const char * mode, int size) +{ + RSurface * rt = malloc (sizeof (RSurface)); + rt->t = NULL; + if (!OpenRST (&rt->t, fname, "r")) { + free (rt); + return NULL; + } + rt->name = malloc (sizeof (char)*(strlen (fname) + 1)); + strcpy (rt->name, fname); + return rt; +} + +int r_surface_close (RSurface * rt) +{ + int status = 1; + status = CloseRST (&rt->t); + free (rt->name); + free (rt); + return status; +} + +static boolean Intersects (RSTREE R, + typrect RSTrect, + typrect queryrect, + typrect unused) +{ + int maxdim= NumbOfDim -1; + boolean inter; + int d; + + d= -1; + do { + d++; + inter= RSTrect[d].l <= queryrect[d].h && + RSTrect[d].h >= queryrect[d].l; + } while (inter && d != maxdim); + return inter; +} + +static void ManageQuery (RSTREE R, + typrect rectangle, + refinfo infoptr, + void ** data, + boolean *modify, + boolean *finish) +{ + RSurfaceQuery q = data[0]; + double p[3]; + p[0] = rectangle[0].l; p[1] = rectangle[1].l; + p[2] = infoptr->height; + (*q) (p, data[1]); + *modify = FALSE; + *finish = FALSE; +} + +void r_surface_query_region (RSurface * rt, + double min[2], double max[2], + RSurfaceQuery q, void * user_data) +{ + typrect rect, unused; + rect[0].l = min[0]; rect[0].h = max[0]; + rect[1].l = min[1]; rect[1].h = max[1]; + void * data[2]; + data[0] = q; + data[1] = user_data; + RegionQuery (rt->t, rect, unused, Intersects, Intersects, (QueryManageProc) ManageQuery, data); +} diff --git a/pool/shard002/C/0062798_tsimpleinj.c b/pool/shard002/C/0062798_tsimpleinj.c new file mode 100644 index 0000000000000000000000000000000000000000..a7029cbb8ff70a126dee16828a76d3b4ee30dcf1 --- /dev/null +++ b/pool/shard002/C/0062798_tsimpleinj.c @@ -0,0 +1,165 @@ +/* + * Test program for Linux memory error recovery. + * Requires special injection support. + * + * This is a early primitive version of tinjpage.c, + * but simpler to debug in some cases. + */ +#define _GNU_SOURCE 1 +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#define MADV_POISON 100 + +#define err(x) perror(x),exit(1) + +int count = 20; +int failure = 0; +int total_cases = 0; +sigjmp_buf recover; +int PS; + +void sighandler(int sig, siginfo_t *si, void *arg) +{ + printf("signal %d code %d addr %p\n", sig, si->si_code, si->si_addr); + + if (--count == 0) + exit(1); + + siglongjmp(recover, 1); +} + +void testmem(char *msg, char *page, int write) +{ + printf("%s page %p\n", msg, page); + total_cases++; + if (sigsetjmp(recover,1) == 0) { + if (madvise(page, PS, MADV_POISON) != 0) { + failure++; + perror("madvise"); + } + if (write) + *page = 2; + else + printf("%x\n", *(unsigned char *)page); + } + printf("recovered\n"); +} + +void expecterr(char *msg, int res) +{ + if (res == 0) + printf("no error on %s\n", msg); + else + perror(msg); +} + +int tempfd(void) +{ + static int tmpcount; + int fd; + char buf[30]; + snprintf(buf,30,"/tmp/test%d.XXXXXXXX",tmpcount++); + fd = mkstemp(buf); + if (fd >= 0) + unlink(buf); + return fd; +} + +#define RANDOM_FILE "/etc/profile" + +int main(void) +{ + PS = getpagesize(); + char *page; + + struct sigaction sa = { + .sa_sigaction = sighandler, + .sa_flags = SA_SIGINFO + }; + sigaction(SIGBUS, &sa, NULL); +// sigaction(SIGSEGV, &sa, NULL); + + page = mmap(NULL, PS, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS|MAP_POPULATE, 0, 0); + testmem("dirty", page, 1); + + page = mmap(NULL, PS, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS|MAP_LOCKED, 0, 0); + testmem("mlocked", page, 1); + + int fd = open(RANDOM_FILE, O_RDONLY); + if (fd < 0) err("open " RANDOM_FILE); + page = mmap(NULL, PS, PROT_READ, MAP_SHARED|MAP_POPULATE, fd, 0); + if (page == (char *)-1) err("mmap"); + close(fd); + testmem("clean file", page, 0); + + fd = tempfd(); + if (fd < 0) err("open testfile"); + char *tmp = malloc(PS); + if (!tmp) err("no enough memory"); + memset(tmp, 0xff, PS); + write(fd, tmp, PS); + free(tmp); + page = mmap(NULL, PS, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0); + if (page == (char*)-1) err("mmap"); + *page = 1; + testmem("file dirty", page, 0); + expecterr("msync expect error", msync(page, PS, MS_SYNC)); + expecterr("fsync expect error", fsync(fd)); + close(fd); + + /* hole case still broken in the kernel -- doesn't report error */ + fd = tempfd(); + if (fd < 0) err("open testfile"); + ftruncate(fd, PS); + page = mmap(NULL, PS, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0); + if (page == (char*)-1) err("mmap"); + *page = 1; + testmem("hole file dirty", page, 0); + expecterr("hole msync expect error", msync(page, PS, MS_SYNC)); + expecterr("hole fsync expect error", fsync(fd)); + close(fd); + +#if 0 + const int NPAGES = 10; + int i; + fd = tempfd(); + if (fd < 0) err("open rfp testfile"); + tmp = malloc(PS); + if (!tmp) exit(ENOMEM); + for (i = 0; i < NPAGES; i++) { + memset(tmp, i, PS); + write(fd, tmp, PS); + } + free(tmp); + page = mmap(NULL, PS*NPAGES, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0); + if (page == (char*)-1) err("mmap"); + int k = NPAGES - 1; + for (i = 0; i < NPAGES; i++, k--) { + if (remap_file_pages(page + i*PS, PS, 0, k, 0)) + perror("remap_file_pages"); + } + *page = 1; + testmem("rfp file dirty", page, 0); + expecterr("rfp msync expect error", msync(page, PS, MS_SYNC)); + expecterr("rfp fsync expect error", fsync(fd)); + close(fd); +#endif + + if (failure > 0) { + printf("FAILURE -- %d of %d cases broken!\n", failure, total_cases); + return 1; + } + printf("SUCCESS\n"); + + return 0; +} + + diff --git a/pool/shard002/C/0062803_libxt_pkttype.c b/pool/shard002/C/0062803_libxt_pkttype.c new file mode 100644 index 0000000000000000000000000000000000000000..b72c013388f9ee7f8d8ed2285a58f8447075dbed --- /dev/null +++ b/pool/shard002/C/0062803_libxt_pkttype.c @@ -0,0 +1,135 @@ +/* + * Shared library add-on to iptables to match + * packets by their type (BROADCAST, UNICAST, MULTICAST). + * + * Michal Ludvig + */ +#include +#include +#include +#define __aligned_u64 __u64 __attribute__((aligned(8))) +#include +#include + +enum { + O_PKTTYPE = 0, +}; + +struct pkttypes { + const char *name; + unsigned char pkttype; + unsigned char printhelp; + const char *help; +}; + +static const struct pkttypes supported_types[] = { + {"unicast", PACKET_HOST, 1, "to us"}, + {"broadcast", PACKET_BROADCAST, 1, "to all"}, + {"multicast", PACKET_MULTICAST, 1, "to group"}, +/* + {"otherhost", PACKET_OTHERHOST, 1, "to someone else"}, + {"outgoing", PACKET_OUTGOING, 1, "outgoing of any type"}, +*/ + /* aliases */ + {"bcast", PACKET_BROADCAST, 0, NULL}, + {"mcast", PACKET_MULTICAST, 0, NULL}, + {"host", PACKET_HOST, 0, NULL} +}; + +static void print_types(void) +{ + unsigned int i; + + printf("Valid packet types:\n"); + for (i = 0; i < ARRAY_SIZE(supported_types); ++i) + if(supported_types[i].printhelp == 1) + printf("\t%-14s\t\t%s\n", supported_types[i].name, supported_types[i].help); + printf("\n"); +} + +static void pkttype_help(void) +{ + printf( +"pkttype match options:\n" +"[!] --pkt-type packettype match packet type\n"); + print_types(); +} + +static const struct xt_option_entry pkttype_opts[] = { + {.name = "pkt-type", .id = O_PKTTYPE, .type = XTTYPE_STRING, + .flags = XTOPT_MAND | XTOPT_INVERT}, + XTOPT_TABLEEND, +}; + +static void parse_pkttype(const char *pkttype, struct xt_pkttype_info *info) +{ + unsigned int i; + + for (i = 0; i < ARRAY_SIZE(supported_types); ++i) + if(strcasecmp(pkttype, supported_types[i].name)==0) + { + info->pkttype=supported_types[i].pkttype; + return; + } + + xtables_error(PARAMETER_PROBLEM, "Bad packet type '%s'", pkttype); +} + +static void pkttype_parse(struct xt_option_call *cb) +{ + struct xt_pkttype_info *info = cb->data; + + xtables_option_parse(cb); + parse_pkttype(cb->arg, info); + if (cb->invert) + info->invert = 1; +} + +static void print_pkttype(const struct xt_pkttype_info *info) +{ + unsigned int i; + + for (i = 0; i < ARRAY_SIZE(supported_types); ++i) + if(supported_types[i].pkttype==info->pkttype) + { + printf("%s", supported_types[i].name); + return; + } + + printf("%d", info->pkttype); /* in case we didn't find an entry in named-packtes */ +} + +static void pkttype_print(const void *ip, const struct xt_entry_match *match, + int numeric) +{ + const struct xt_pkttype_info *info = (const void *)match->data; + + printf(" PKTTYPE %s= ", info->invert ? "!" : ""); + print_pkttype(info); +} + +static void pkttype_save(const void *ip, const struct xt_entry_match *match) +{ + const struct xt_pkttype_info *info = (const void *)match->data; + + printf("%s --pkt-type ", info->invert ? " !" : ""); + print_pkttype(info); +} + +static struct xtables_match pkttype_match = { + .family = NFPROTO_UNSPEC, + .name = "pkttype", + .version = XTABLES_VERSION, + .size = XT_ALIGN(sizeof(struct xt_pkttype_info)), + .userspacesize = XT_ALIGN(sizeof(struct xt_pkttype_info)), + .help = pkttype_help, + .print = pkttype_print, + .save = pkttype_save, + .x6_parse = pkttype_parse, + .x6_options = pkttype_opts, +}; + +void _init(void) +{ + xtables_register_match(&pkttype_match); +} diff --git a/pool/shard002/C/0062810_s390-virtio.c b/pool/shard002/C/0062810_s390-virtio.c new file mode 100644 index 0000000000000000000000000000000000000000..c36a8b2336a95317da49bb2cff4a92ced9f939f3 --- /dev/null +++ b/pool/shard002/C/0062810_s390-virtio.c @@ -0,0 +1,262 @@ +/* + * QEMU S390 virtio target + * + * Copyright (c) 2009 Alexander Graf + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, see . + */ + +#include "hw.h" +#include "block.h" +#include "sysemu.h" +#include "net.h" +#include "boards.h" +#include "monitor.h" +#include "loader.h" +#include "elf.h" +#include "hw/virtio.h" +#include "hw/sysbus.h" +#include "kvm.h" + +#include "hw/s390-virtio-bus.h" + +//#define DEBUG_S390 + +#ifdef DEBUG_S390 +#define dprintf(fmt, ...) \ + do { fprintf(stderr, fmt, ## __VA_ARGS__); } while (0) +#else +#define dprintf(fmt, ...) \ + do { } while (0) +#endif + +#define KVM_S390_VIRTIO_NOTIFY 0 +#define KVM_S390_VIRTIO_RESET 1 +#define KVM_S390_VIRTIO_SET_STATUS 2 + +#define KERN_IMAGE_START 0x010000UL +#define KERN_PARM_AREA 0x010480UL +#define INITRD_START 0x800000UL +#define INITRD_PARM_START 0x010408UL +#define INITRD_PARM_SIZE 0x010410UL +#define PARMFILE_START 0x001000UL + +#define MAX_BLK_DEVS 10 + +static VirtIOS390Bus *s390_bus; +static CPUState **ipi_states; + +void irq_info(Monitor *mon); +void pic_info(Monitor *mon); + +void irq_info(Monitor *mon) +{ +} + +void pic_info(Monitor *mon) +{ +} + +CPUState *s390_cpu_addr2state(uint16_t cpu_addr) +{ + if (cpu_addr >= smp_cpus) { + return NULL; + } + + return ipi_states[cpu_addr]; +} + +int s390_virtio_hypercall(CPUState *env) +{ + int r = 0, i; + target_ulong mem = env->regs[2]; + + dprintf("KVM hypercall: %ld\n", env->regs[1]); + switch (env->regs[1]) { + case KVM_S390_VIRTIO_NOTIFY: + if (mem > ram_size) { + VirtIOS390Device *dev = s390_virtio_bus_find_vring(s390_bus, + mem, &i); + if (dev) { + virtio_queue_notify(dev->vdev, i); + } else { + r = -EINVAL; + } + } else { + /* Early printk */ + } + break; + case KVM_S390_VIRTIO_RESET: + { + VirtIOS390Device *dev; + + dev = s390_virtio_bus_find_mem(s390_bus, mem); + virtio_reset(dev->vdev); + s390_virtio_device_sync(dev); + break; + } + case KVM_S390_VIRTIO_SET_STATUS: + { + VirtIOS390Device *dev; + + dev = s390_virtio_bus_find_mem(s390_bus, mem); + if (dev) { + s390_virtio_device_update_status(dev); + } else { + r = -EINVAL; + } + break; + } + default: + r = -EINVAL; + break; + } + + env->regs[2] = r; + return 0; +} + +/* PC hardware initialisation */ +static void s390_init(ram_addr_t ram_size, + const char *boot_device, + const char *kernel_filename, + const char *kernel_cmdline, + const char *initrd_filename, + const char *cpu_model) +{ + CPUState *env = NULL; + ram_addr_t ram_addr; + ram_addr_t kernel_size = 0; + ram_addr_t initrd_offset; + ram_addr_t initrd_size = 0; + int i; + + /* XXX we only work on KVM for now */ + + if (!kvm_enabled()) { + fprintf(stderr, "The S390 target only works with KVM enabled\n"); + exit(1); + } + + /* get a BUS */ + s390_bus = s390_virtio_bus_init(&ram_size); + + /* allocate RAM */ + ram_addr = qemu_ram_alloc(ram_size); + cpu_register_physical_memory(0, ram_size, ram_addr); + + /* init CPUs */ + if (cpu_model == NULL) { + cpu_model = "host"; + } + + ipi_states = qemu_malloc(sizeof(CPUState *) * smp_cpus); + + for (i = 0; i < smp_cpus; i++) { + CPUState *tmp_env; + + tmp_env = cpu_init(cpu_model); + if (!env) { + env = tmp_env; + } + ipi_states[i] = tmp_env; + tmp_env->halted = 1; + tmp_env->exception_index = EXCP_HLT; + } + + env->halted = 0; + env->exception_index = 0; + + if (kernel_filename) { + kernel_size = load_image(kernel_filename, qemu_get_ram_ptr(0)); + + if (lduw_phys(KERN_IMAGE_START) != 0x0dd0) { + fprintf(stderr, "Specified image is not an s390 boot image\n"); + exit(1); + } + + env->psw.addr = KERN_IMAGE_START; + env->psw.mask = 0x0000000180000000ULL; + } + + if (initrd_filename) { + initrd_offset = INITRD_START; + while (kernel_size + 0x100000 > initrd_offset) { + initrd_offset += 0x100000; + } + initrd_size = load_image(initrd_filename, qemu_get_ram_ptr(initrd_offset)); + + stq_phys(INITRD_PARM_START, initrd_offset); + stq_phys(INITRD_PARM_SIZE, initrd_size); + } + + if (kernel_cmdline) { + cpu_physical_memory_rw(KERN_PARM_AREA, (uint8_t *)kernel_cmdline, + strlen(kernel_cmdline), 1); + } + + /* Create VirtIO network adapters */ + for(i = 0; i < nb_nics; i++) { + NICInfo *nd = &nd_table[i]; + DeviceState *dev; + + if (!nd->model) { + nd->model = qemu_strdup("virtio"); + } + + if (strcmp(nd->model, "virtio")) { + fprintf(stderr, "S390 only supports VirtIO nics\n"); + exit(1); + } + + dev = qdev_create((BusState *)s390_bus, "virtio-net-s390"); + qdev_set_nic_properties(dev, nd); + qdev_init_nofail(dev); + } + + /* Create VirtIO disk drives */ + for(i = 0; i < MAX_BLK_DEVS; i++) { + DriveInfo *dinfo; + DeviceState *dev; + + dinfo = drive_get(IF_IDE, 0, i); + if (!dinfo) { + continue; + } + + dev = qdev_create((BusState *)s390_bus, "virtio-blk-s390"); + qdev_prop_set_drive(dev, "drive", dinfo); + qdev_init_nofail(dev); + } +} + +static QEMUMachine s390_machine = { + .name = "s390-virtio", + .alias = "s390", + .desc = "VirtIO based S390 machine", + .init = s390_init, + .no_serial = 1, + .no_parallel = 1, + .use_virtcon = 1, + .no_vga = 1, + .max_cpus = 255, + .is_default = 1, +}; + +static void s390_machine_init(void) +{ + qemu_register_machine(&s390_machine); +} + +machine_init(s390_machine_init); diff --git a/pool/shard002/C/0062831_txx9aclc-ac97.c b/pool/shard002/C/0062831_txx9aclc-ac97.c new file mode 100644 index 0000000000000000000000000000000000000000..b0fa285c7ba298765368ea27abeb6af52139c070 --- /dev/null +++ b/pool/shard002/C/0062831_txx9aclc-ac97.c @@ -0,0 +1,233 @@ +/* + * TXx9 ACLC AC97 driver + * + * Copyright (C) 2009 Atsushi Nemoto + * + * Based on RBTX49xx patch from CELF patch archive. + * (C) Copyright TOSHIBA CORPORATION 2004-2006 + * + * 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 "txx9aclc.h" + +#define AC97_DIR \ + (SND_SOC_DAIDIR_PLAYBACK | SND_SOC_DAIDIR_CAPTURE) + +#define AC97_RATES \ + SNDRV_PCM_RATE_8000_48000 + +#ifdef __BIG_ENDIAN +#define AC97_FMTS SNDRV_PCM_FMTBIT_S16_BE +#else +#define AC97_FMTS SNDRV_PCM_FMTBIT_S16_LE +#endif + +static DECLARE_WAIT_QUEUE_HEAD(ac97_waitq); + +/* REVISIT: How to find txx9aclc_drvdata from snd_ac97? */ +static struct txx9aclc_plat_drvdata *txx9aclc_drvdata; + +static int txx9aclc_regready(struct txx9aclc_plat_drvdata *drvdata) +{ + return __raw_readl(drvdata->base + ACINTSTS) & ACINT_REGACCRDY; +} + +/* AC97 controller reads codec register */ +static unsigned short txx9aclc_ac97_read(struct snd_ac97 *ac97, + unsigned short reg) +{ + struct txx9aclc_plat_drvdata *drvdata = txx9aclc_drvdata; + void __iomem *base = drvdata->base; + u32 dat; + + if (!(__raw_readl(base + ACINTSTS) & ACINT_CODECRDY(ac97->num))) + return 0xffff; + reg |= ac97->num << 7; + dat = (reg << ACREGACC_REG_SHIFT) | ACREGACC_READ; + __raw_writel(dat, base + ACREGACC); + __raw_writel(ACINT_REGACCRDY, base + ACINTEN); + if (!wait_event_timeout(ac97_waitq, txx9aclc_regready(txx9aclc_drvdata), HZ)) { + __raw_writel(ACINT_REGACCRDY, base + ACINTDIS); + printk(KERN_ERR "ac97 read timeout (reg %#x)\n", reg); + dat = 0xffff; + goto done; + } + dat = __raw_readl(base + ACREGACC); + if (((dat >> ACREGACC_REG_SHIFT) & 0xff) != reg) { + printk(KERN_ERR "reg mismatch %x with %x\n", + dat, reg); + dat = 0xffff; + goto done; + } + dat = (dat >> ACREGACC_DAT_SHIFT) & 0xffff; +done: + __raw_writel(ACINT_REGACCRDY, base + ACINTDIS); + return dat; +} + +/* AC97 controller writes to codec register */ +static void txx9aclc_ac97_write(struct snd_ac97 *ac97, unsigned short reg, + unsigned short val) +{ + struct txx9aclc_plat_drvdata *drvdata = txx9aclc_drvdata; + void __iomem *base = drvdata->base; + + __raw_writel(((reg | (ac97->num << 7)) << ACREGACC_REG_SHIFT) | + (val << ACREGACC_DAT_SHIFT), + base + ACREGACC); + __raw_writel(ACINT_REGACCRDY, base + ACINTEN); + if (!wait_event_timeout(ac97_waitq, txx9aclc_regready(txx9aclc_drvdata), HZ)) { + printk(KERN_ERR + "ac97 write timeout (reg %#x)\n", reg); + } + __raw_writel(ACINT_REGACCRDY, base + ACINTDIS); +} + +static void txx9aclc_ac97_cold_reset(struct snd_ac97 *ac97) +{ + struct txx9aclc_plat_drvdata *drvdata = txx9aclc_drvdata; + void __iomem *base = drvdata->base; + u32 ready = ACINT_CODECRDY(ac97->num) | ACINT_REGACCRDY; + + __raw_writel(ACCTL_ENLINK, base + ACCTLDIS); + udelay(1); + __raw_writel(ACCTL_ENLINK, base + ACCTLEN); + /* wait for primary codec ready status */ + __raw_writel(ready, base + ACINTEN); + if (!wait_event_timeout(ac97_waitq, + (__raw_readl(base + ACINTSTS) & ready) == ready, + HZ)) { + dev_err(&ac97->dev, "primary codec is not ready " + "(status %#x)\n", + __raw_readl(base + ACINTSTS)); + } + __raw_writel(ACINT_REGACCRDY, base + ACINTSTS); + __raw_writel(ready, base + ACINTDIS); +} + +/* AC97 controller operations */ +static struct snd_ac97_bus_ops txx9aclc_ac97_ops = { + .read = txx9aclc_ac97_read, + .write = txx9aclc_ac97_write, + .reset = txx9aclc_ac97_cold_reset, +}; + +static irqreturn_t txx9aclc_ac97_irq(int irq, void *dev_id) +{ + struct txx9aclc_plat_drvdata *drvdata = dev_id; + void __iomem *base = drvdata->base; + + __raw_writel(__raw_readl(base + ACINTMSTS), base + ACINTDIS); + wake_up(&ac97_waitq); + return IRQ_HANDLED; +} + +static int txx9aclc_ac97_probe(struct snd_soc_dai *dai) +{ + txx9aclc_drvdata = snd_soc_dai_get_drvdata(dai); + return 0; +} + +static int txx9aclc_ac97_remove(struct snd_soc_dai *dai) +{ + struct txx9aclc_plat_drvdata *drvdata = snd_soc_dai_get_drvdata(dai); + + /* disable AC-link */ + __raw_writel(ACCTL_ENLINK, drvdata->base + ACCTLDIS); + txx9aclc_drvdata = NULL; + return 0; +} + +static struct snd_soc_dai_driver txx9aclc_ac97_dai = { + .bus_control = true, + .probe = txx9aclc_ac97_probe, + .remove = txx9aclc_ac97_remove, + .playback = { + .rates = AC97_RATES, + .formats = AC97_FMTS, + .channels_min = 2, + .channels_max = 2, + }, + .capture = { + .rates = AC97_RATES, + .formats = AC97_FMTS, + .channels_min = 2, + .channels_max = 2, + }, +}; + +static const struct snd_soc_component_driver txx9aclc_ac97_component = { + .name = "txx9aclc-ac97", +}; + +static int txx9aclc_ac97_dev_probe(struct platform_device *pdev) +{ + struct txx9aclc_plat_drvdata *drvdata; + struct resource *r; + int err; + int irq; + + irq = platform_get_irq(pdev, 0); + if (irq < 0) + return irq; + + drvdata = devm_kzalloc(&pdev->dev, sizeof(*drvdata), GFP_KERNEL); + if (!drvdata) + return -ENOMEM; + + r = platform_get_resource(pdev, IORESOURCE_MEM, 0); + drvdata->base = devm_ioremap_resource(&pdev->dev, r); + if (IS_ERR(drvdata->base)) + return PTR_ERR(drvdata->base); + + platform_set_drvdata(pdev, drvdata); + drvdata->physbase = r->start; + if (sizeof(drvdata->physbase) > sizeof(r->start) && + r->start >= TXX9_DIRECTMAP_BASE && + r->start < TXX9_DIRECTMAP_BASE + 0x400000) + drvdata->physbase |= 0xf00000000ull; + err = devm_request_irq(&pdev->dev, irq, txx9aclc_ac97_irq, + 0, dev_name(&pdev->dev), drvdata); + if (err < 0) + return err; + + err = snd_soc_set_ac97_ops(&txx9aclc_ac97_ops); + if (err < 0) + return err; + + return devm_snd_soc_register_component(&pdev->dev, &txx9aclc_ac97_component, + &txx9aclc_ac97_dai, 1); +} + +static int txx9aclc_ac97_dev_remove(struct platform_device *pdev) +{ + snd_soc_set_ac97_ops(NULL); + return 0; +} + +static struct platform_driver txx9aclc_ac97_driver = { + .probe = txx9aclc_ac97_dev_probe, + .remove = txx9aclc_ac97_dev_remove, + .driver = { + .name = "txx9aclc-ac97", + }, +}; + +module_platform_driver(txx9aclc_ac97_driver); + +MODULE_AUTHOR("Atsushi Nemoto "); +MODULE_DESCRIPTION("TXx9 ACLC AC97 driver"); +MODULE_LICENSE("GPL"); +MODULE_ALIAS("platform:txx9aclc-ac97"); diff --git a/pool/shard002/C/0062842_byt_cr_board_configs.c b/pool/shard002/C/0062842_byt_cr_board_configs.c new file mode 100644 index 0000000000000000000000000000000000000000..7a892e0f8b4083f407af0c8608b154758f9f4d3e --- /dev/null +++ b/pool/shard002/C/0062842_byt_cr_board_configs.c @@ -0,0 +1,95 @@ +/* + * byt_cr_board_configs.h - Intel SST Driver for audio engine + * + * Copyright (C) 2014 Intel Corporation + * Authors: Ola Lilja + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * 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. + * + * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + * + * Board-specific hardware-configurations + * + */ + +#include +#include +#include +#include + +#include "byt_cr_board_configs.h" + +static const struct mach_codec_link *mc_link; + +static acpi_status sst_acpi_mach_match(acpi_handle handle, u32 level, + void *context, void **ret) +{ + *(bool *)context = true; + return AE_OK; +} + +static bool acpi_id_exists(const char *id) +{ + bool found = false; + acpi_status status; + + status = acpi_get_devices(id, sst_acpi_mach_match, &found, NULL); + return ACPI_SUCCESS(status) && found; +} + +int set_mc_link(void) +{ + int i; + + for (i = 0; i < ARRAY_SIZE(mach_codec_links); i++) + if (acpi_id_exists(mach_codec_links[i].codec_hid)) { + pr_info("%s: %s-codec found! Registering machine-device %s.\n", + __func__, mach_codec_links[i].codec_hid, + mach_codec_links[i].mach_dev->name); + platform_device_register(mach_codec_links[i].mach_dev); + mc_link = &mach_codec_links[i]; + break; + } + if (i == ARRAY_SIZE(mach_codec_links)) { + pr_err("%s: Unknown or no codec found!\n", __func__); + return -ENOENT; + } + + return 0; +} + +const struct mach_codec_link *get_mc_link(void) +{ + if (!mc_link) + if (set_mc_link()) + return NULL; + + return mc_link; +} + +const struct board_config *get_board_config( + const struct mach_codec_link *mc_link) +{ + const struct dmi_system_id *dmi; + + if (!mc_link) + return NULL; + dmi = dmi_first_match(mc_link->dmi_system_ids); + if (!dmi) { + pr_info("Board is a default %s.\n", mc_link->mach_dev->name); + return mc_link->board_config_default; + } + + pr_info("%s: Board is a %s (%s)\n", __func__, dmi->ident, + mc_link->mach_dev->name); + + return (const struct board_config *)dmi->driver_data; +} diff --git a/pool/shard002/C/0062857_test-skin-archive.c b/pool/shard002/C/0062857_test-skin-archive.c new file mode 100644 index 0000000000000000000000000000000000000000..ff350e84ba1b07e31e1179cca97fa0f9d637cac5 --- /dev/null +++ b/pool/shard002/C/0062857_test-skin-archive.c @@ -0,0 +1,48 @@ +/* vi: set sw=4 ts=4: */ +/* + * test_skin_archive.c + * + * This file is part of ________. + * + * Copyright (C) 2008 - kelvenxu . + * + * 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 + + +int main() +{ + SkinArchive *ar; + gboolean re; + + g_type_init(); + ar = skin_archive_new(); + + g_return_val_if_fail(SKIN_IS_ARCHIVE(ar), -1); + + re = skin_archive_load(ar, "tests/tt.zip"); + if(re) + { + printf("archive Information: \n"); + printf("\tname: %s\n", ar->info->name); + printf("\tauthor: %s\n", ar->info->author); + printf("\temail: %s\n", ar->info->email); + } + + return 0; +} diff --git a/pool/shard002/C/0062865_m_blocknonalpha.c b/pool/shard002/C/0062865_m_blocknonalpha.c new file mode 100644 index 0000000000000000000000000000000000000000..f2f8c3878b08e49a344ae5367f9dbb7480c4f9c2 --- /dev/null +++ b/pool/shard002/C/0062865_m_blocknonalpha.c @@ -0,0 +1,123 @@ +#include "config.h" +#include "struct.h" +#include "common.h" +#include "sys.h" +#include "numeric.h" +#include "msg.h" +#include "channel.h" +#include +#include +#include +#include +#include +#ifdef _WIN32 +#include +#endif +#include +#include "h.h" +#ifdef STRIPBADWORDS +#include "badwords.h" +#endif +#ifdef _WIN32 +#include "version.h" +#endif + +#define DelCmode(x) if (x) CmodeDel(x); x = NULL +#define DelHook(x) if (x) HookDel(x); x = NULL + +Hook *HookPreJoin; /* our /join hook */ +static int m_myjoin(aClient *, aChannel *, char *[]); /* the called function */ +static int alnum_check(const char *s); /* check whether the nick is valid */ +Cmode_t EXTCMODE_BLOCK = 0L; +Cmode *ModeBlock = NULL; + +ModuleHeader MOD_HEADER(m_blocknonalpha) + = { + "m_blocknonalpha", + "$Id: m_blocknonalpha.c,v 1.0 2004/04/04 Certus Exp $", + "prevents nicks with non-alphabetic chars from joining a +y channel", + "3.2-b8-1", + NULL + }; + +DLLFUNC int MOD_INIT(m_blocknonalpha)(ModuleInfo *modinfo) +{ + CmodeInfo req; + ModuleSetOptions(modinfo->handle, MOD_OPT_PERM); /* We are PERM */ + ircd_log(LOG_ERROR, "debug: mod_init called from m_blocknonalpha.c"); + sendto_realops("loading m_blocknonalpha"); + memset(&req, 0, sizeof(req)); + req.paracount = 0; + req.is_ok = extcmode_default_requirehalfop; + req.flag = 'y'; + ModeBlock = CmodeAdd(modinfo->handle, req, &EXTCMODE_BLOCK); + + HookPreJoin = HookAddEx(modinfo->handle, HOOKTYPE_PRE_LOCAL_JOIN, m_myjoin); + return MOD_SUCCESS; +} + +DLLFUNC int MOD_LOAD(m_blocknonalpha)(int module_load) +{ + return MOD_SUCCESS; +} + +DLLFUNC int MOD_UNLOAD(m_blocknonalpha)(int module_unload) +{ + DelCmode(ModeBlock); + DelHook(HookPreJoin); + sendto_realops("[m_blocknonalpha] mod_unload called, this shouldn't have happened."); + return MOD_FAILED; +} + +u_int is_invited(aClient *sptr, aChannel *chptr) +{ + Link *lp; + + for (lp = sptr->user->invited; lp; lp = lp->next) + if (lp->value.chptr == chptr) + return 1; + + return 0; +} + +static int m_myjoin(aClient *sptr, aChannel *chptr, char *parv[]) +{ + if (chptr == NULL) { + return HOOK_CONTINUE; + } else if (is_invited(sptr, chptr)) { + return HOOK_CONTINUE; + } else { + if (chptr->mode.extmode & EXTCMODE_BLOCK) { + if (alnum_check(sptr->name) == 0) { + if (!IsRegNick(sptr) && !IsULine(sptr) && !IsOper(sptr)) { + sendto_one(sptr, ":%s NOTICE %s :*** Your nick contains banned characters. Please register to nickserv" \ + " or use a nick with alphabetic letters for being able to join channel %s.", me.name, sptr->name, chptr->chname); + return HOOK_DENY; + } + } + } + } + return HOOK_CONTINUE; +} + + +/* As the unrealircd dev team changed isalpha(), we have to create our own function */ +int charcheck(int c) { + if ((c == '|') || (c == '\\') || (c == '^') || (c == '-') || (c == '_') || (c == '{') || (c == '}') || (c == '[') || (c == ']')) + return 0; + else + return 1; +} + +/* does the string contain a non-alpha character? return 0 if so */ +extern int alnum_check(const char *s) { + register int c; + + while (c = *s) { + if (!isalnum(c) || !charcheck(c)) { + return 0; + } + s++; + } + return 1; +} \ No newline at end of file diff --git a/pool/shard002/C/0062867_t-powers_mod_bsgs.c b/pool/shard002/C/0062867_t-powers_mod_bsgs.c new file mode 100644 index 0000000000000000000000000000000000000000..2a42eb57cc2806edb5bf8633b045e72c134ada41 --- /dev/null +++ b/pool/shard002/C/0062867_t-powers_mod_bsgs.c @@ -0,0 +1,112 @@ +/* + Copyright (C) 2020 William Hart + + This file is part of FLINT. + + FLINT 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. See . +*/ + +#include +#include +#include +#include "flint.h" +#include "nmod_vec.h" +#include "nmod_poly.h" +#include "ulong_extras.h" + +int +main(void) +{ +#if FLINT_USES_PTHREAD && (FLINT_USES_TLS || FLINT_REENTRANT) + int i, result, max_threads = 5; +#endif + FLINT_TEST_INIT(state); + + flint_printf("powers_mod_bsgs...."); + fflush(stdout); + +#if FLINT_USES_PTHREAD && (FLINT_USES_TLS || FLINT_REENTRANT) + /* Compare with powmod */ + for (i = 0; i < 100 * flint_test_multiplier(); i++) + { + nmod_poly_t f, g, pow; + nmod_poly_struct * res; + mp_limb_t n; + ulong exp; + slong j; + + flint_set_num_threads(n_randint(state, max_threads)); + + n = n_randtest_prime(state, 0); + exp = n_randint(state, 32); + + nmod_poly_init(f, n); + nmod_poly_init(g, n); + nmod_poly_init(pow, n); + + res = (nmod_poly_struct *) flint_malloc(exp*sizeof(nmod_poly_struct)); + + for (j = 0; j < exp; j++) + nmod_poly_init(res + j, n); + + nmod_poly_randtest(f, state, n_randint(state, 50)); + do { + nmod_poly_randtest(g, state, n_randint(state, 50)); + } while (nmod_poly_is_zero(g)); + + nmod_poly_powers_mod_bsgs(res, f, exp, g); + + result = 1; + j = 0; + + if (exp > 0) + { + nmod_poly_one(pow); + result = nmod_poly_equal(res + 0, pow); + } + + for (j = 1 ; j < exp && result; j++) + { + nmod_poly_mulmod(pow, pow, f, g); + result &= nmod_poly_equal(res + j, pow); + } + + j--; + + if (!result) + { + flint_printf("FAIL:\n"); + flint_printf("exp: %wu\n\n", exp); + flint_printf("f:\n"); nmod_poly_print(f), flint_printf("\n\n"); + flint_printf("g:\n"); nmod_poly_print(g), flint_printf("\n\n"); + flint_printf("j: %w\n", j); + flint_printf("pow:\n"); nmod_poly_print(pow), flint_printf("\n\n"); + flint_printf("res[%w]:\n", j); nmod_poly_print(res + j), flint_printf("\n\n"); + fflush(stdout); + flint_abort(); + } + + nmod_poly_clear(f); + nmod_poly_clear(g); + nmod_poly_clear(pow); + + for (j = 0; j < exp; j++) + nmod_poly_clear(res + j); + + flint_free(res); + } + + FLINT_TEST_CLEANUP(state); + + flint_printf("PASS\n"); +#else + FLINT_TEST_CLEANUP(state); + + flint_printf("SKIPPED\n"); +#endif + + return 0; +} diff --git a/pool/shard002/C/0062874_fast_sha256.c b/pool/shard002/C/0062874_fast_sha256.c new file mode 100644 index 0000000000000000000000000000000000000000..b0fb03e4f818608678fceb0c66f7a24d95963bc0 --- /dev/null +++ b/pool/shard002/C/0062874_fast_sha256.c @@ -0,0 +1,165 @@ +/* + * SHA-256 hash implementation and interface functions + * Copyright (c) 2003-2007, Jouni Malinen + * + * Hardware crypto support Copyright 2017 Espressif Systems (Shanghai) PTE LTD + * + * 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. + * + * Alternatively, this software may be distributed under the terms of BSD + * license. + * + * See README and COPYING for more details. + */ + +#include "crypto/includes.h" + +#include "crypto/common.h" +#include "crypto/sha256.h" +#include "crypto/crypto.h" + + +/** + * fast_hmac_sha256_vector - HMAC-SHA256 over data vector (RFC 2104) + * @key: Key for HMAC operations + * @key_len: Length of the key in bytes + * @num_elem: Number of elements in the data vector + * @addr: Pointers to the data areas + * @len: Lengths of the data blocks + * @mac: Buffer for the hash (32 bytes) + */ +void +fast_hmac_sha256_vector(const uint8_t *key, size_t key_len, size_t num_elem, + const uint8_t *addr[], const size_t *len, uint8_t *mac) +{ + uint8_t k_pad[64]; /* padding - key XORd with ipad/opad */ + uint8_t tk[32]; + const uint8_t *_addr[6]; + size_t _len[6], i; + + if (num_elem > 5) { + /* + * Fixed limit on the number of fragments to avoid having to + * allocate memory (which could fail). + */ + return; + } + + /* if key is longer than 64 bytes reset it to key = SHA256(key) */ + if (key_len > 64) { + fast_sha256_vector(1, &key, &key_len, tk); + key = tk; + key_len = 32; + } + + /* the HMAC_SHA256 transform looks like: + * + * SHA256(K XOR opad, SHA256(K XOR ipad, text)) + * + * where K is an n byte key + * ipad is the byte 0x36 repeated 64 times + * opad is the byte 0x5c repeated 64 times + * and text is the data being protected + */ + + /* start out by storing key in ipad */ + os_memset(k_pad, 0, sizeof(k_pad)); + os_memcpy(k_pad, key, key_len); + /* XOR key with ipad values */ + for (i = 0; i < 64; i++) { + k_pad[i] ^= 0x36; + } + + /* perform inner SHA256 */ + _addr[0] = k_pad; + _len[0] = 64; + for (i = 0; i < num_elem; i++) { + _addr[i + 1] = addr[i]; + _len[i + 1] = len[i]; + } + fast_sha256_vector(1 + num_elem, _addr, _len, mac); + + os_memset(k_pad, 0, sizeof(k_pad)); + os_memcpy(k_pad, key, key_len); + /* XOR key with opad values */ + for (i = 0; i < 64; i++) { + k_pad[i] ^= 0x5c; + } + + /* perform outer SHA256 */ + _addr[0] = k_pad; + _len[0] = 64; + _addr[1] = mac; + _len[1] = SHA256_MAC_LEN; + fast_sha256_vector(2, _addr, _len, mac); +} + + +/** + * fast_hmac_sha256 - HMAC-SHA256 over data buffer (RFC 2104) + * @key: Key for HMAC operations + * @key_len: Length of the key in bytes + * @data: Pointers to the data area + * @data_len: Length of the data area + * @mac: Buffer for the hash (20 bytes) + */ +void +fast_hmac_sha256(const uint8_t *key, size_t key_len, const uint8_t *data, + size_t data_len, uint8_t *mac) +{ + fast_hmac_sha256_vector(key, key_len, 1, &data, &data_len, mac); +} + + +/** + * fast_sha256_prf - SHA256-based Pseudo-Random Function (IEEE 802.11r, 8.5.1.5.2) + * @key: Key for PRF + * @key_len: Length of the key in bytes + * @label: A unique label for each purpose of the PRF + * @data: Extra data to bind into the key + * @data_len: Length of the data + * @buf: Buffer for the generated pseudo-random key + * @buf_len: Number of bytes of key to generate + * + * This function is used to derive new, cryptographically separate keys from a + * given key. + */ +void +fast_sha256_prf(const uint8_t *key, size_t key_len, const char *label, + const uint8_t *data, size_t data_len, uint8_t *buf, size_t buf_len) +{ + uint16_t counter = 1; + size_t pos, plen; + uint8_t hash[SHA256_MAC_LEN]; + const uint8_t *addr[4]; + size_t len[4]; + uint8_t counter_le[2], length_le[2]; + + addr[0] = counter_le; + len[0] = 2; + addr[1] = (uint8_t *) label; + len[1] = os_strlen(label); + addr[2] = data; + len[2] = data_len; + addr[3] = length_le; + len[3] = sizeof(length_le); + + WPA_PUT_LE16(length_le, buf_len * 8); + pos = 0; + while (pos < buf_len) { + plen = buf_len - pos; + WPA_PUT_LE16(counter_le, counter); + if (plen >= SHA256_MAC_LEN) { + fast_hmac_sha256_vector(key, key_len, 4, addr, len, + &buf[pos]); + pos += SHA256_MAC_LEN; + } else { + fast_hmac_sha256_vector(key, key_len, 4, addr, len, hash); + os_memcpy(&buf[pos], hash, plen); + break; + } + counter++; + } +} diff --git a/pool/shard002/C/0062914_const.c b/pool/shard002/C/0062914_const.c new file mode 100644 index 0000000000000000000000000000000000000000..265e126e54e2d02071b563fc0bcfd01f3f81f116 --- /dev/null +++ b/pool/shard002/C/0062914_const.c @@ -0,0 +1,17 @@ +#include +enum { pin3=3,pin4,pin5,pin6,pin7,pin8,pin9,pin10,pin11,pin12,pin13 }; +int main() { + const int ledrouge12 = 12; + printf("ledrouge12=%d\n",ledrouge12); + printf("Le démoniaque monsieur pointeur passe ...\n"); + int *ptr12 = &ledrouge12; + *ptr12=666; + printf("et change la valeur\n"); + printf("ledrouge12=%d\n",ledrouge12); + + + + printf("%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d\n", + pin3,pin4,pin5,pin6,pin7,pin8,pin9,pin10,pin11,pin12,pin13); + return 0; +} \ No newline at end of file diff --git a/pool/shard002/C/0062930_halFrameComposerIsrc.c b/pool/shard002/C/0062930_halFrameComposerIsrc.c new file mode 100644 index 0000000000000000000000000000000000000000..4f50c4cc9b81890a5f5c9405f8cd10517286d154 --- /dev/null +++ b/pool/shard002/C/0062930_halFrameComposerIsrc.c @@ -0,0 +1,67 @@ +/* + * @file:halFrameComposerIsrc.c + * + * Created on: Jul 1, 2010 + * Author: klabadi & dlopo + */ +#include "halFrameComposerIsrc.h" +#include "access.h" +#include "hdmi_log.h" + +/* register offset */ +static const IM_UINT8 FC_ISRC1_0 = 0x92; +static const IM_UINT8 FC_ISRC1_1 = 0xA2; +static const IM_UINT8 FC_ISRC1_16 = 0x93; +static const IM_UINT8 FC_ISRC2_0 = 0xB2; +static const IM_UINT8 FC_ISRC2_15 = 0xA3; +/* bit shifts */ +static const IM_UINT8 ISRC_CONT = 0; +static const IM_UINT8 ISRC_VALID = 1; +static const IM_UINT8 ISRC_STATUS = 2; + +void halFrameComposerIsrc_Status(IM_UINT16 baseAddr, IM_UINT8 code) +{ + LOG_TRACE1(code); + access_CoreWrite(code, (baseAddr + FC_ISRC1_0), ISRC_STATUS, 3); +} + +void halFrameComposerIsrc_Valid(IM_UINT16 baseAddr, IM_UINT8 validity) +{ + LOG_TRACE1(validity); + access_CoreWrite((validity ? 1 : 0), (baseAddr + FC_ISRC1_0), ISRC_VALID, 1); +} + +void halFrameComposerIsrc_Cont(IM_UINT16 baseAddr, IM_UINT8 isContinued) +{ + LOG_TRACE1(isContinued); + access_CoreWrite((isContinued ? 1 : 0), (baseAddr + FC_ISRC1_0), ISRC_CONT, + 1); +} + +void halFrameComposerIsrc_Isrc1Codes(IM_UINT16 baseAddr, IM_UINT8 * codes, IM_UINT8 length) +{ + IM_UINT8 c = 0; + LOG_TRACE1(codes[0]); + if (length > (FC_ISRC1_1 - FC_ISRC1_16 + 1)) + { + length = (FC_ISRC1_1 - FC_ISRC1_16 + 1); + LOG_WARNING("ISRC1 Codes Truncated"); + } + + for (c = 0; c < length; c++) + access_CoreWriteByte(codes[c], (baseAddr + FC_ISRC1_1 - c)); +} + +void halFrameComposerIsrc_Isrc2Codes(IM_UINT16 baseAddr, IM_UINT8 * codes, IM_UINT8 length) +{ + IM_UINT8 c = 0; + LOG_TRACE1(codes[0]); + if (length > (FC_ISRC2_0 - FC_ISRC2_15 + 1)) + { + length = (FC_ISRC2_0 - FC_ISRC2_15 + 1); + LOG_WARNING("ISRC2 Codes Truncated"); + } + + for (c = 0; c < length; c++) + access_CoreWriteByte(codes[c], (baseAddr + FC_ISRC2_0 - c)); +} diff --git a/pool/shard002/C/0062935_diadev.c b/pool/shard002/C/0062935_diadev.c new file mode 100644 index 0000000000000000000000000000000000000000..e904bbfd39fd676dbc7832c2a152b3ca752cd1af --- /dev/null +++ b/pool/shard002/C/0062935_diadev.c @@ -0,0 +1,272 @@ + +/* +* Copyright (C) Actility, SA. All Rights Reserved. +* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER +* +* This program is free software; you can redistribute it and/or +* modify it under the terms of the GNU General Public License version +* 2 only, 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 version 2 for more details (a copy is +* included at /legal/license.txt). +* +* You should have received a copy of the GNU General Public License +* version 2 along with this work; if not, write to the Free Software +* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA +* 02110-1301 USA +* +* Please contact Actility, SA., 4, rue Ampere 22300 LANNION FRANCE +* or visit www.actility.com if you need additional +* information or have any questions. +*/ + +/*! @file diadev.c + * + */ +#include /************************************/ +#include /* run in main thread */ +#include /************************************/ +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +#include "rtlbase.h" +#include "rtlimsg.h" +#include "xoapipr.h" +#include "dIa.h" + +#include "cmndefine.h" +#include "cmnstruct.h" +#include "speccproto.h" +#include "cmnproto.h" +#include "specextern.h" + +#include "diadef.h" + + +extern void *MainTbPoll; +extern int TraceLevel; + +extern dia_context_t *DiaCtxt; + + +static void DiaDevOk(t_dia_req *preq, t_dia_rspparam *par); +static void DiaDevError(t_dia_req *preq, t_dia_rspparam *par); +static void DiaDevInstCreate(t_dia_req *preq, t_dia_rspparam *par, ...); +static void DiaDevContCreate(t_dia_req *preq, t_dia_rspparam *par, ...); +static void DiaDevElemCreate(t_dia_req *preq, t_dia_rspparam *par, ...); +static void DiaDevContRetrieve(t_dia_req *preq, t_dia_rspparam *par, ...); +static void DiaDevElemRetrieve(t_dia_req *preq, t_dia_rspparam *par, ...); + +static void DiaDevOk(t_dia_req *preq,t_dia_rspparam *par) +{ + DIA_DEVICE_CONTEXT(); + + RTL_TRDBG(2,"OK DIA DEV '%s'\n",cmn->cmn_ieee); + + cmn->cmn_dia_devok++; + + WDiaUCBRequestOk(DIA_FUNC,preq,cmn); +} + +static void DiaDevError(t_dia_req *preq,t_dia_rspparam *par) +{ + DIA_DEVICE_CONTEXT(); + + RTL_TRDBG(0,"ERROR DIA DEV FAILURE '%s' req='%s' tid=%d code='%s'\n", + cmn->cmn_ieee,preq->rq_name,preq->rq_tid,preq->rq_scode); + + cmn->cmn_dia_devok = 0; + + if (par && par->pr_timeout) // TIMEOUT => RETRY NO + { + WDiaUCBRequestTimeout(DIA_FUNC,preq,cmn); + return; + } + RTL_TRDBG(0,"ERROR DIA DEV DEFINTIVE FAILURE\n"); + + WDiaUCBRequestError(DIA_FUNC,preq,cmn); +} + +static void DiaDevInstCreate(t_dia_req *preq,t_dia_rspparam *par,...) +{ + DIA_LOCAL_VAR(); + parseflags = XOML_PARSE_OBIX; + + DIA_DEVICE_CONTEXT(); + +if (PseudoOng) + sprintf(target,"%s%s/DEV_%s/containers/DESCRIPTOR/contentInstances/latest", + GetHostTarget(),SCL_ROOT_APP,cmn->cmn_ieee); +else + sprintf(target,"%s%s/DEV_%s/containers/DESCRIPTOR/contentInstances", + GetHostTarget(),SCL_ROOT_APP,cmn->cmn_ieee); + + if (par == NULL) + { + // REQUEST +retry : +// SetVar("d_ieee",cmn->cmn_ieee); + WDiaUCBPreLoadTemplate(reqname,preq,target,cmn,xo); + xo = WXoNewTemplate("dev_inst.xml",parseflags); + if (!xo) + return; + WDiaUCBPostLoadTemplate(reqname,preq,target,cmn,xo); +// iCmnSensorSetApplicationListInObj(cmn,xo); + + DIA_CREATE_REQUEST(DiaDevInstCreate); +return; + } + + // RESPONSE + DIA_CREATE_RESPONSE(DiaDevError,DiaDevError,DiaDevOk); +} + +static void DiaDevContCreate(t_dia_req *preq,t_dia_rspparam *par,...) +{ + DIA_LOCAL_VAR(); + DIA_DEVICE_CONTEXT(); + +if (PseudoOng) + sprintf(target,"%s%s/DEV_%s/containers/DESCRIPTOR", + GetHostTarget(),SCL_ROOT_APP,cmn->cmn_ieee); +else + sprintf(target,"%s%s/DEV_%s/containers", + GetHostTarget(),SCL_ROOT_APP,cmn->cmn_ieee); + + if (par == NULL) + { + // REQUEST +retry : +// SetVar("d_ieee",cmn->cmn_ieee); + WDiaUCBPreLoadTemplate(reqname,preq,target,cmn,xo); + xo = WXoNewTemplate("dev_cont.xml",0); + if (!xo) + return; + WDiaUCBPostLoadTemplate(reqname,preq,target,cmn,xo); + + DIA_CREATE_REQUEST(DiaDevContCreate); +return; + } + + // RESPONSE + DIA_CREATE_RESPONSE(DiaDevError,DiaDevError,DiaDevInstCreate); +} + +static void DiaDevElemCreate(t_dia_req *preq,t_dia_rspparam *par,...) +{ + DIA_LOCAL_VAR(); + DIA_DEVICE_CONTEXT(); + +if (PseudoOng) + sprintf(target,"%s%s/DEV_%s",GetHostTarget(),SCL_ROOT_APP,cmn->cmn_ieee); +else + sprintf(target,"%s%s",GetHostTarget(),SCL_ROOT_APP); + + if (par == NULL) + { + // REQUEST +retry : +// SetVar("d_ieee",cmn->cmn_ieee); + WDiaUCBPreLoadTemplate(reqname,preq,target,cmn,xo); + xo = WXoNewTemplate("dev_elem.xml",parseflags); + if (!xo) + return; + WDiaUCBPostLoadTemplate(reqname,preq,target,cmn,xo); + + DIA_CREATE_REQUEST(DiaDevElemCreate); +return; + } + + // RESPONSE + DIA_CREATE_RESPONSE(DiaDevError,DiaDevError,DiaDevContRetrieve); +} + +static void DiaDevContRetrieve(t_dia_req *preq,t_dia_rspparam *par,...) +{ + DIA_LOCAL_VAR(); + DIA_DEVICE_CONTEXT(); + +if (PseudoOng) + sprintf(target,"%s%s/DEV_%s/containers/DESCRIPTOR", + GetHostTarget(),SCL_ROOT_APP,cmn->cmn_ieee); +else + sprintf(target,"%s%s/DEV_%s/containers/DESCRIPTOR", + GetHostTarget(),SCL_ROOT_APP,cmn->cmn_ieee); + + if (par == NULL) + { + // REQUEST +retry : + DIA_RETRIEVE_REQUEST(DiaDevContRetrieve); +return; + } + + // RESPONSE + DIA_RETRIEVE_RESPONSE(DiaDevError,DiaDevContCreate,DiaDevInstCreate); +} + +static void DiaDevElemRetrieve(t_dia_req *preq,t_dia_rspparam *par,...) +{ + DIA_LOCAL_VAR(); + DIA_DEVICE_CONTEXT(); + +if (PseudoOng) + sprintf(target,"%s%s/DEV_%s",GetHostTarget(),SCL_ROOT_APP,cmn->cmn_ieee); +else + sprintf(target,"%s%s/DEV_%s",GetHostTarget(),SCL_ROOT_APP,cmn->cmn_ieee); + + if (par == NULL) + { + // REQUEST +retry : + DIA_RETRIEVE_REQUEST(DiaDevElemRetrieve); +return; + } + + // RESPONSE + DIA_RETRIEVE_RESPONSE(DiaDevError,DiaDevElemCreate,DiaDevContRetrieve); +} + + + +/*! + * + * @brief start DIA macro request for "network-device" M2M application + * @param dev device/sensor number + * @param serial serial number of the device + * @return void + * + */ +void DiaDevStart(int dev,int serial) +{ + t_dia_req req; + + memset (&req,0,sizeof(t_dia_req)); + req.rq_cli = NULL; + req.rq_dev = dev; + req.rq_serial = serial; + req.rq_name = (char *)__func__; + DiaDevElemRetrieve(&req,NULL); +} + + +void CmdDiaDev(t_cli *cli,char *buf) +{ + t_dia_req req; + + memset (&req,0,sizeof(t_dia_req)); + req.rq_cli = cli; +// req.rq_cli = NULL; + DiaDevElemRetrieve(&req,NULL); +} diff --git a/pool/shard002/C/0062937_clifunc.c b/pool/shard002/C/0062937_clifunc.c new file mode 100644 index 0000000000000000000000000000000000000000..d338226e176341ae00df4bd83afbe49e9e702727 --- /dev/null +++ b/pool/shard002/C/0062937_clifunc.c @@ -0,0 +1,105 @@ +/* clifunc.c +*/ + +#include "chatroom.h" + +int +login_cli(int connfd) +{ + char nname[50] = {0}; + printf("please input a nick name: "); + fgets(nname, 50, stdin); + memset(&nname[strlen(nname)-1],0,1); + sendMsg(connfd, nname, strlen(nname)); + return 0; +} + +int +login_cli_cgi(int connfd, WINDOW *wp) +{ + char nname[50] = {0}; + wprintw(wp, "please input a nick name: "); + wrefresh(wp); + wgetnstr(wp, nname, 50); + sendMsg(connfd, nname, strlen(nname)); + return 0; +} + +int +parseNotifyMsg(char *msg, char **infoArray) +{ + char *p; + p = strtok(msg, "|"); + int i = 0; + while(p!=NULL){ + strcpy(infoArray[i], p); + p = strtok(NULL, "|"); + i++; + } + return 0; +} + +void +printUserList(char **userNameList, WINDOW *wnd) +{ + int i; + wclear(wnd); + wprintw(wnd, "current user list:\n"); + for(i=0;isocket, msgbuf, &len)<0){ + wprintw(arg->wnd_output, "Server [%s] closed connection\n", arg->servip); + wrefresh(arg->wnd_output); + break; + } + memset(buf,0x00,sizeof(buf)); + parseAMsg(msgbuf,buf,&msgType); + if(msgType/10==200){ + for(i=0;iwnd_ulist); + } + wprintw(arg->wnd_output, "%s\n", buf); + wrefresh(arg->wnd_output); + } + free2dCharArray(infoArray, NOTIFYINFONUM); + free2dCharArray(userNameList, ORIUSERNUM); + return ((void *)0); +} diff --git a/pool/shard002/C/0062942_pm_domains.c b/pool/shard002/C/0062942_pm_domains.c new file mode 100644 index 0000000000000000000000000000000000000000..a6a5d807cc2bae5a1b2cc4fbbc7c39136fe12e20 --- /dev/null +++ b/pool/shard002/C/0062942_pm_domains.c @@ -0,0 +1,249 @@ +/* + * Exynos Generic power domain support. + * + * Copyright (c) 2012 Samsung Electronics Co., Ltd. + * http://www.samsung.com + * + * Implementation of Exynos specific power domain control which is used in + * conjunction with runtime-pm. Support for both device-tree and non-device-tree + * based power domain support is included. + * + * 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 + +#define MAX_CLK_PER_DOMAIN 4 + +struct exynos_pm_domain_config { + /* Value for LOCAL_PWR_CFG and STATUS fields for each domain */ + u32 local_pwr_cfg; +}; + +/* + * Exynos specific wrapper around the generic power domain + */ +struct exynos_pm_domain { + void __iomem *base; + bool is_off; + struct generic_pm_domain pd; + struct clk *oscclk; + struct clk *clk[MAX_CLK_PER_DOMAIN]; + struct clk *pclk[MAX_CLK_PER_DOMAIN]; + struct clk *asb_clk[MAX_CLK_PER_DOMAIN]; + u32 local_pwr_cfg; +}; + +static int exynos_pd_power(struct generic_pm_domain *domain, bool power_on) +{ + struct exynos_pm_domain *pd; + void __iomem *base; + u32 timeout, pwr; + char *op; + int i; + + pd = container_of(domain, struct exynos_pm_domain, pd); + base = pd->base; + + for (i = 0; i < MAX_CLK_PER_DOMAIN; i++) { + if (IS_ERR(pd->asb_clk[i])) + break; + clk_prepare_enable(pd->asb_clk[i]); + } + + /* Set oscclk before powering off a domain*/ + if (!power_on) { + for (i = 0; i < MAX_CLK_PER_DOMAIN; i++) { + if (IS_ERR(pd->clk[i])) + break; + pd->pclk[i] = clk_get_parent(pd->clk[i]); + if (clk_set_parent(pd->clk[i], pd->oscclk)) + pr_err("%s: error setting oscclk as parent to clock %d\n", + domain->name, i); + } + } + + pwr = power_on ? pd->local_pwr_cfg : 0; + writel_relaxed(pwr, base); + + /* Wait max 1ms */ + timeout = 10; + + while ((readl_relaxed(base + 0x4) & pd->local_pwr_cfg) != pwr) { + if (!timeout) { + op = (power_on) ? "enable" : "disable"; + pr_err("Power domain %s %s failed\n", domain->name, op); + return -ETIMEDOUT; + } + timeout--; + cpu_relax(); + usleep_range(80, 100); + } + + /* Restore clocks after powering on a domain*/ + if (power_on) { + for (i = 0; i < MAX_CLK_PER_DOMAIN; i++) { + if (IS_ERR(pd->clk[i])) + break; + + if (IS_ERR(pd->pclk[i])) + continue; /* Skip on first power up */ + if (clk_set_parent(pd->clk[i], pd->pclk[i])) + pr_err("%s: error setting parent to clock%d\n", + domain->name, i); + } + } + + for (i = 0; i < MAX_CLK_PER_DOMAIN; i++) { + if (IS_ERR(pd->asb_clk[i])) + break; + clk_disable_unprepare(pd->asb_clk[i]); + } + + return 0; +} + +static int exynos_pd_power_on(struct generic_pm_domain *domain) +{ + return exynos_pd_power(domain, true); +} + +static int exynos_pd_power_off(struct generic_pm_domain *domain) +{ + return exynos_pd_power(domain, false); +} + +static const struct exynos_pm_domain_config exynos4210_cfg __initconst = { + .local_pwr_cfg = 0x7, +}; + +static const struct exynos_pm_domain_config exynos5433_cfg __initconst = { + .local_pwr_cfg = 0xf, +}; + +static const struct of_device_id exynos_pm_domain_of_match[] __initconst = { + { + .compatible = "samsung,exynos4210-pd", + .data = &exynos4210_cfg, + }, { + .compatible = "samsung,exynos5433-pd", + .data = &exynos5433_cfg, + }, + { }, +}; + +static __init const char *exynos_get_domain_name(struct device_node *node) +{ + const char *name; + + if (of_property_read_string(node, "label", &name) < 0) + name = strrchr(node->full_name, '/') + 1; + return kstrdup_const(name, GFP_KERNEL); +} + +static __init int exynos4_pm_init_power_domain(void) +{ + struct device_node *np; + const struct of_device_id *match; + + for_each_matching_node_and_match(np, exynos_pm_domain_of_match, &match) { + const struct exynos_pm_domain_config *pm_domain_cfg; + struct exynos_pm_domain *pd; + int on, i; + + pm_domain_cfg = match->data; + + pd = kzalloc(sizeof(*pd), GFP_KERNEL); + if (!pd) { + of_node_put(np); + return -ENOMEM; + } + pd->pd.name = exynos_get_domain_name(np); + if (!pd->pd.name) { + kfree(pd); + of_node_put(np); + return -ENOMEM; + } + + pd->base = of_iomap(np, 0); + if (!pd->base) { + pr_warn("%s: failed to map memory\n", __func__); + kfree_const(pd->pd.name); + kfree(pd); + continue; + } + + pd->pd.power_off = exynos_pd_power_off; + pd->pd.power_on = exynos_pd_power_on; + pd->local_pwr_cfg = pm_domain_cfg->local_pwr_cfg; + + for (i = 0; i < MAX_CLK_PER_DOMAIN; i++) { + char clk_name[8]; + + snprintf(clk_name, sizeof(clk_name), "asb%d", i); + pd->asb_clk[i] = of_clk_get_by_name(np, clk_name); + if (IS_ERR(pd->asb_clk[i])) + break; + } + + pd->oscclk = of_clk_get_by_name(np, "oscclk"); + if (IS_ERR(pd->oscclk)) + goto no_clk; + + for (i = 0; i < MAX_CLK_PER_DOMAIN; i++) { + char clk_name[8]; + + snprintf(clk_name, sizeof(clk_name), "clk%d", i); + pd->clk[i] = of_clk_get_by_name(np, clk_name); + if (IS_ERR(pd->clk[i])) + break; + /* + * Skip setting parent on first power up. + * The parent at this time may not be useful at all. + */ + pd->pclk[i] = ERR_PTR(-EINVAL); + } + + if (IS_ERR(pd->clk[0])) + clk_put(pd->oscclk); + +no_clk: + on = readl_relaxed(pd->base + 0x4) & pd->local_pwr_cfg; + + pm_genpd_init(&pd->pd, NULL, !on); + of_genpd_add_provider_simple(np, &pd->pd); + } + + /* Assign the child power domains to their parents */ + for_each_matching_node(np, exynos_pm_domain_of_match) { + struct of_phandle_args child, parent; + + child.np = np; + child.args_count = 0; + + if (of_parse_phandle_with_args(np, "power-domains", + "#power-domain-cells", 0, + &parent) != 0) + continue; + + if (of_genpd_add_subdomain(&parent, &child)) + pr_warn("%s failed to add subdomain: %s\n", + parent.np->full_name, child.np->full_name); + else + pr_info("%s has as child subdomain: %s.\n", + parent.np->full_name, child.np->full_name); + } + + return 0; +} +core_initcall(exynos4_pm_init_power_domain); diff --git a/pool/shard002/C/0062946_bytepat.c b/pool/shard002/C/0062946_bytepat.c new file mode 100644 index 0000000000000000000000000000000000000000..9d1468308bbe26e62577dcc55b1c8ed0aec58b42 --- /dev/null +++ b/pool/shard002/C/0062946_bytepat.c @@ -0,0 +1,134 @@ +/* radare - LGPL - Copyright 2006-2019 - esteve, pancake */ + +#include +#include +#include + +#define CTXMINB 5 +#define BSIZE (1024*1024) +#define MAX_PATLEN 1024 + +typedef struct _fnditem { + unsigned char str[MAX_PATLEN]; + void* next; +} fnditem; + +static fnditem* init_fi(void) { + fnditem* n; + n = (fnditem*) malloc (sizeof (fnditem)); + if (!n) { + return NULL; + } + n->next = NULL; + return n; +} + +static void fini_fi(fnditem* fi) { + fnditem *fu; + fu = fi; + while (fi->next) { + fu = fi; + fi = fi->next; + free (fu); + fu = NULL; + } + free (fu); +} + +static void add_fi (fnditem* n, unsigned char* blk, int patlen) { + fnditem* p; + for (p = n; p->next != NULL; p = p->next) { + ; + } + p->next = (fnditem*) malloc (sizeof (fnditem)); + p = p->next; + memcpy (p->str, blk, patlen); + p->next = NULL; +} + +static int is_fi_present(fnditem* n, unsigned char* blk , int patlen) { + fnditem* p; + for (p = n; p->next != NULL; p = p->next) { + if (!memcmp (blk, p->str, patlen)) { + return true; + } + } + return false; +} + +R_API int r_search_pattern(RSearch *s, ut64 from, ut64 to) { + ut8 block[BSIZE+MAX_PATLEN], sblk[BSIZE+MAX_PATLEN+1]; + ut64 addr, bact, bytes, intaddr, rb, bproc = 0; + int nr,i, moar=0, pcnt, cnt = 0, k = 0; + int patlen = s->pattern_size; + fnditem* root; + + eprintf ("Searching patterns between 0x%08"PFMT64x" and 0x%08"PFMT64x"\n", from, to); + if (patlen < 1 || patlen > MAX_PATLEN) { + eprintf ("Invalid pattern length (must be > 1 and < %d)\n", MAX_PATLEN); + return false; + } + bact = from; + bytes = to; + //bytes += bact; + root = init_fi (); + pcnt = -1; + +// bact = from +// bytes = to +// bproc = from2 + while (bact < bytes) { + addr = bact; + if (r_print_is_interrupted ()) { + break; + } + + bproc = bact + patlen ; +// read ( fd, sblk, patlen ); +//XXX bytepattern should be used with a read callback + nr = ((bytes - bproc) < BSIZE)?(bytes - bproc):BSIZE; + //XXX radare_read_at(bact, sblk, patlen); + rb = s->iob.read_at (s->iob.io, addr, sblk, nr); + sblk[patlen] = 0; // XXX + + intaddr = bact; + cnt = 0; + while (bproc < bytes) { + // TODO: handle ^C here + nr = ((bytes - bproc) < BSIZE)?(bytes - bproc):BSIZE; + nr += (patlen - (nr % patlen)); // tamany de bloc llegit multiple superior de tamany busqueda + rb = s->iob.read_at (s->iob.io, bproc, block, nr); + if (rb < 1) { + bproc += nr; + break; + } + nr = rb; + addr += nr; + moar = 0; + for (i = 0; i 0) { + eprintf ("\ncount: %d: %d\n", pcnt, moar + 1); + } + bproc += rb; + } + bact += (moar > 0)? patlen: 1; + } + eprintf ("\n"); + fini_fi (root); + return 0; +} diff --git a/pool/shard002/C/0062956_get_matrix.c b/pool/shard002/C/0062956_get_matrix.c new file mode 100644 index 0000000000000000000000000000000000000000..bd8bd3fcc858864b6047c12c53a4f70465b84922 --- /dev/null +++ b/pool/shard002/C/0062956_get_matrix.c @@ -0,0 +1,182 @@ +//------------------------------------------------------------------------------ +// GraphBLAS/Demo/Source/get_matrix.c: get matrix from file, or create random +//------------------------------------------------------------------------------ + +// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2018, All Rights Reserved. +// http://suitesparse.com See GraphBLAS/Doc/License.txt for license. + +//------------------------------------------------------------------------------ + +// Creates a symmetric matrix, either from a file or by creating a random +// matrix. If reading from a file, the file is assumed to be 0-based. + +#define FREE_ALL \ + GrB_free (&A) ; \ + GrB_free (&desc) ; \ + GrB_free (&Mask) ; + +#include "demos.h" + +GrB_Info get_matrix // get a matrix from stdin, or create random one +( + GrB_Matrix *A_output, // matrix to create + int argc, // command-line arguments + char **argv, + bool no_self_edges, // if true, ensure the matrix has no self-edges + bool boolean // if true, file is read as GrB_BOOL, else GrB_FP64 +) +{ + + GrB_Info info ; + GrB_Index nrows = 1, ncols = 1, ntuples = 1, nvals ; + GrB_Matrix A = NULL ; + GrB_Matrix Mask = NULL ; + GrB_Descriptor desc = NULL ; + int kind = 0 ; + + double tic [2], t ; + simple_tic (tic) ; + + if (argc > 2) + { + + //---------------------------------------------------------------------- + // create a random matrix + //---------------------------------------------------------------------- + + kind = strtol (argv [1], NULL, 0) ; + + if (kind == 0) + { + + //------------------------------------------------------------------ + // random pattern + //------------------------------------------------------------------ + + // usage: ./main 0 nrows ncols ntuples method + + int method = 0 ; // 0:setElement, 1:build + + if (argc > 2) nrows = strtol (argv [2], NULL, 0) ; + if (argc > 3) ncols = strtol (argv [3], NULL, 0) ; + if (argc > 4) ntuples = strtol (argv [4], NULL, 0) ; + if (argc > 5) method = strtol (argv [5], NULL, 0) ; + + OK (random_matrix (&A, true, no_self_edges, + nrows, ncols, ntuples, method, false)) ; + + // force completion, just to check timing + GrB_Matrix_nvals (&nvals, A) ; + + t = simple_toc (tic) ; + + // printf format warnings can vary with different compilers, so + // punt and type cast to double + printf ( + "random %.16g by %.16g, nz: %.16g, method %d time %.3f sec\n", + (double) nrows, (double) ncols, (double) nvals, method, t) ; + + fprintf (stderr, + "random %.16g by %.16g, nz: %.16g, method %d time %.3f sec\n", + (double) nrows, (double) ncols, (double) nvals, method, t) ; + + } + else + { + + //------------------------------------------------------------------ + // Wathen matrix + //------------------------------------------------------------------ + + // usage: ./main 1 nx ny method + + int method = 0 ; // 0 to 3 + int64_t nx = 4, ny = 4 ; + if (argc > 2) nx = strtol (argv [2], NULL, 0) ; + if (argc > 3) ny = strtol (argv [3], NULL, 0) ; + if (argc > 4) method = strtol (argv [4], NULL, 0) ; + + OK (wathen (&A, nx, ny, false, method, NULL)) ; + GrB_Matrix_nvals (&nvals, A) ; + GrB_Matrix_nrows (&nrows, A) ; + t = simple_toc (tic) ; + + printf ( + "Wathen: nx %.16g ny %.16g n %.16g nz %.16g method %d," + " time: %.3f sec\n", (double) nx, (double) ny, (double) nrows, + (double) nvals, method, t) ; + + fprintf (stderr, + "Wathen: nx %.16g ny %.16g n %.16g nz %.16g method %d," + " time: %.3f sec\n", (double) nx, (double) ny, (double) nrows, + (double) nvals, method, t) ; + + // remove the self edges from the matrix + if (no_self_edges) + { + // Mask = speye (nrows) ; + OK (GrB_Matrix_new (&Mask, GrB_BOOL, nrows, nrows)) ; + for (int64_t i = 0 ; i < nrows ; i++) + { + // Mask (i,i) = true + OK (GrB_Matrix_setElement (Mask, (bool) true, i, i)) ; + } + // A<~Mask> = A, thus removing the diagonal. GrB_transpose + // does C=A', so setting inp0 to tran does C=A'', and + // thus C=A, without forming any transpose at all. + // Replace is set, so A is cleared first. Otherwise the + // diagonal is not touched by C<~Mask>=A. + OK (GrB_Descriptor_new (&desc)) ; + OK (GrB_Descriptor_set (desc, GrB_INP0, GrB_TRAN)) ; + OK (GrB_Descriptor_set (desc, GrB_MASK, GrB_SCMP)) ; + OK (GrB_Descriptor_set (desc, GrB_OUTP, GrB_REPLACE)) ; + OK (GrB_transpose (A, Mask, NULL, A, desc)) ; + GrB_free (&Mask) ; + GrB_free (&desc) ; + } + } + + } + else + { + + //---------------------------------------------------------------------- + // read a 0-based or 1-based matrix from stdin + //---------------------------------------------------------------------- + + // usage: ./main < file + // ./main 0 < file + // ./main 1 < file + // + // default is 0-based, for the matrices in the Matrix/ folder + + bool one_based = false ; + if (argc > 1) one_based = strtol (argv [1], NULL, 0) ; + + OK (read_matrix (&A, stdin, true, no_self_edges, one_based, boolean, + false)) ; + + OK (GrB_Matrix_nrows (&nrows, A)) ; + OK (GrB_Matrix_ncols (&ncols, A)) ; + OK (GrB_Matrix_nvals (&nvals, A)) ; + + printf ("matrix %.16g by %.16g, %.16g entries, from stdin\n", + (double) nrows, (double) ncols, (double) nvals) ; + + fprintf (stderr, "matrix %.16g by %.16g, %.16g entries, from stdin\n", + (double) nrows, (double) ncols, (double) nvals) ; + + } + + //-------------------------------------------------------------------------- + // print and return result + //-------------------------------------------------------------------------- + + // print a short description of the matrix (about 30 entries) + OK (GxB_Matrix_fprint (A, "from get_matrix:", GxB_SHORT, stdout)) ; + + *A_output = A ; + A = NULL ; + return (GrB_SUCCESS) ; +} + diff --git a/pool/shard002/C/0062962_main.c b/pool/shard002/C/0062962_main.c new file mode 100644 index 0000000000000000000000000000000000000000..4b865e83742ec59d1b9b5e285589e4de72a007b0 --- /dev/null +++ b/pool/shard002/C/0062962_main.c @@ -0,0 +1,64 @@ +/* + * Copyright (C) 2017 Gilles DOFFE + * + * 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 tests + * @{ + * + * @file + * @brief Test for low-level QDEC drivers + * + * This test initializes all declared QDEC devices. + * It displays QDEC counters value each second. + * + * @author Gilles DOFFE + * + * @} + */ + +#include + +#include "periph/qdec.h" +#include "xtimer.h" + +static void handler(void *arg) +{ + qdec_t qdec = (qdec_t)(uintptr_t)arg; + printf("QDEC %u counter overflow : reset counter\n", qdec); + qdec_read_and_reset(QDEC_DEV(qdec)); +} + +int main(void) +{ + unsigned i; + int32_t value; + puts("Welcome into Quadrature Decoder (QDEC) test program."); + puts("This program will count pulses on all available QDEC channels"); + puts("Written for nucleo-f401re, you have to plug signals A and B as follow :"); + puts(" QDEC0 : signal A on PA6 and signal B on PA7"); + puts(" QDEC1 : signal A on PB6 and signal B on PB7"); + puts("Quadrature decoding mode is set to X4 : counting on all edges on both signals"); + + for (i = 0; i < QDEC_NUMOF; i++) { + int32_t error = qdec_init(QDEC_DEV(i), QDEC_X4, handler, (void *)(uintptr_t)i); + if (error) { + fprintf(stderr,"Not supported mode !\n"); + return error; + } + } + + while (1) { + for (i = 0; i < QDEC_NUMOF; i++) { + value = qdec_read_and_reset(QDEC_DEV(i)); + printf("QDEC %lu = %ld\n", (unsigned long int)i, (long int)value); + } + xtimer_sleep(1); + } + + return 0; +} diff --git a/pool/shard002/C/0062963_pop.c b/pool/shard002/C/0062963_pop.c new file mode 100644 index 0000000000000000000000000000000000000000..3c63ffd9b304a961348b53ba6e3dd74e994c1ee5 --- /dev/null +++ b/pool/shard002/C/0062963_pop.c @@ -0,0 +1,121 @@ +/* + * This file is part of Kotaka, a mud library for DGD + * http://github.com/shentino/kotaka + * + * Copyright (C) 2018, 2021 Raymond Jennings + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero 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 Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ +#include +#include +#include +#include + +inherit "/lib/string/object"; +inherit LIB_VERB; + +string *query_parse_methods() +{ + return ({ "raw" }); +} + +string query_help_title() +{ + return "Pop"; +} + +string *query_help_contents() +{ + return ({ "Performs a specifc operation on a property of a given object.", "Does this atomically, and can be useful for numeric properties." }); +} + +void main(object actor, mapping roles) +{ + mixed opvalue, *pinfo, pvalue; + object obj, user; + string args, oname, operatur, pname, *users; + + user = query_user(); + + if (user->query_class() < 2) { + send_out("You do not have sufficient access rights to set object properties.\n"); + return; + } + + args = roles["raw"]; + + if (!args || sscanf(args, "%s %s %s %s", operatur, oname, pname, pvalue) != 4) { + send_out("Usage: pop \n"); + return; + } + + if (!sizeof( ({ operatur }) + & ({ "add", "sub", "mul", "div", "radd", "and", "or", "xor" }) ) + ) { + send_out("Invalid operator.\nPlease use add, sub, mul, div, radd, and, or, or xor.\n"); + return; + } + + obj = parse_object(oname); + + if (!obj) { + send_out(oname + ": No such object.\n"); + return; + } + + pinfo = PROPERTYD->query_property(pname); + + if (!pinfo) { + send_out(pname + ": No such property.\n"); + return; + } + + pvalue = PARSER_VALUE->parse(pvalue); + opvalue = obj->query_property(pname); + + switch(operatur) { + case "add": + obj->set_property(pname, opvalue + pvalue); + break; + + case "and": + obj->set_property(pname, opvalue & pvalue); + break; + + case "div": + obj->set_property(pname, opvalue / pvalue); + break; + + case "mul": + obj->set_property(pname, opvalue * pvalue); + break; + + case "or": + obj->set_property(pname, opvalue | pvalue); + break; + + case "radd": + obj->set_property(pname, pvalue + opvalue); + break; + + case "sub": + obj->set_property(pname, opvalue - pvalue); + break; + + case "xor": + obj->set_property(pname, opvalue ^ pvalue); + } + + send_out("Done.\n"); +} diff --git a/pool/shard002/C/0062965_address_space.c b/pool/shard002/C/0062965_address_space.c new file mode 100644 index 0000000000000000000000000000000000000000..8bd6b5acbecaad1e23e3eeb106a742e0593cf29d --- /dev/null +++ b/pool/shard002/C/0062965_address_space.c @@ -0,0 +1,255 @@ + +#include +#include +#include +#include +#include "assert.h" +#include "bitstring.h" +#include "address_space.h" +#include "utils.h" +#include "version.h" + +void as_print_summary(struct address_space_s *this) { + double alloc = this->bs_len * sizeof(bitstring_t) * this->sample / 1024.0; + char unit = 'k'; + if (alloc > 10000) { + alloc /= 1024.0; + unit = 'M'; + } + printf("Dimension: %d\n", this->bits); + printf("Number of hardlocations: %d\n", this->sample); + printf("Allocated memory for addresses: %.1f %cB\n", alloc, unit); + printf("Allocated bits per bitstring: %ld\n", this->bs_len * 8 * sizeof(bitstring_t)); + printf("Remaining bits per bitstring: %d\n", this->bs_bits_remaining); + printf("Memory efficiency: %.1f%%\n", (100.0 * this->bits) / this->bs_len / 8 / sizeof(bitstring_t)); +} + +void as_print_addresses_hex(struct address_space_s *this) { + unsigned int i; + char buf[1000]; + for (i=0; i < this->sample; i++) { + bs_to_hex(buf, this->addresses[i], this->bs_len); + printf("[%8d] %s\n", i, buf); + } +} + +void as_print_addresses_b64(struct address_space_s *this) { + unsigned int i; + char buf[1000]; + for (i=0; i < this->sample; i++) { + bs_to_b64(buf, this->addresses[i], this->bs_len); + printf("[%8d] %s\n", i, buf); + } +} + +int as_init(struct address_space_s *this, unsigned int bits, unsigned int sample) { + unsigned int i; + + this->bits = bits; + this->sample = sample; + this->verbose = 1; + + this->bs_len = bits / 8 / sizeof(bitstring_t); + if (this->bs_len * 8 * sizeof(bitstring_t) < bits) { + this->bs_len++; + } + this->bs_bits_remaining = this->bs_len * 8 * sizeof(bitstring_t) - bits; + + this->bs_data = (bitstring_t *) malloc(sizeof(bitstring_t) * this->bs_len * this->sample); + if (this->bs_data == NULL) { + return -1; + } + + this->addresses = (bitstring_t **) malloc(sizeof(bitstring_t*) * this->sample); + if (this->addresses == NULL) { + free(this->bs_data); + return -2; + } + for (i=0; isample; i++) { + this->addresses[i] = &this->bs_data[i * this->bs_len]; + } + +#ifdef SDM_ENABLE_OPENCL + this->opencl_opts = (struct opencl_scanner_s *) malloc(sizeof(struct opencl_scanner_s)); + if (this->opencl_opts == NULL) { + free(this->bs_data); + free(this->addresses); + return -3; + } +#endif + + return 0; +} + +int as_init_random(struct address_space_s *this, unsigned int bits, unsigned int sample) { + unsigned int i; + if (as_init(this, bits, sample)) { + return -1; + } + for(i=0; i < this->sample; i++) { + bs_init_random(this->addresses[i], this->bs_len, this->bs_bits_remaining); + } + return 0; +} + +int as_free(struct address_space_s *this) { + free(this->addresses); + free(this->bs_data); +#ifdef SDM_ENABLE_OPENCL + free(this->opencl_opts); +#endif + return 0; +} + +int as_scan_linear(const struct address_space_s *this, const bitstring_t *bs, unsigned int radius, uint8_t *selected) { + unsigned int i, cnt; + cnt = 0; + for(i=0; isample; i++) { + selected[i] = (bs_distance(this->addresses[i], bs, this->bs_len) <= radius); + cnt += selected[i]; + /* + if (bs_distance(this->addresses[i], bs, this->bs_len) <= radius) { + cnt++; + if (selected) { + selected[i] = 1; + } + } else { + if (selected) { + selected[i] = 0; + } + } + */ + } + return cnt; +} + +int as_scan_linear2(const struct address_space_s *this, const bitstring_t *bs, unsigned int radius, unsigned int *selected) { + unsigned int i, cnt; + cnt = 0; + for(i=0; isample; i++) { + if (bs_distance(this->addresses[i], bs, this->bs_len) <= radius) { + selected[cnt++] = i; + } + } + return cnt; +} + +void as_reset_address(struct address_space_s *this, unsigned int index) { + bitstring_t *bs = this->addresses[index]; + bs_init_random(bs, this->bs_len, this->bs_bits_remaining); +} + +int as_save_b64_file(const struct address_space_s *this, char *filename) { + unsigned int i; + char buf[1000]; + FILE *fp = fopen(filename, "w"); + if (fp == NULL) { + return -1; + } + fprintf(fp, "SDM ADDRESS SPACE\n"); + fprintf(fp, "SDM-Version: " SDM_VERSION_STR "\n"); + fprintf(fp, "Format: base64\n"); + fprintf(fp, "Order-of-bytes: %s\n", (is_little_endian() ? "little-endian" : "big-endian")); + fprintf(fp, "Bits-per-Bitstring: %lu\n", this->bs_len * 8 * sizeof(bitstring_t)); + fprintf(fp, "Bits: %d\n", this->bits); + fprintf(fp, "Sample: %d\n", this->sample); + fprintf(fp, "\n"); + for(i=0; isample; i++) { + bs_to_b64(buf, this->addresses[i], this->bs_len); + fprintf(fp, "%s\n", buf); + } + fclose(fp); + return 0; +} + +int as_init_from_b64_file(struct address_space_s *this, char *filename) { + FILE *fp; + char line[2000], *key, *value; + int ret = 0; + unsigned int len, cnt; + unsigned int bits = 0, sample = 0, bits_per_bitstring = 0; + fp = fopen(filename, "r"); + if (fp == NULL) { + return -1; + } + fgets(line, sizeof(line), fp); + if (strcmp(line, "SDM ADDRESS SPACE\n")) { + return -1; + } + while(fgets(line, sizeof(line), fp)) { + len = strlen(line); + if (len <= 1) { + break; + } + assert(line[len-1] == '\n'); + line[len-1] = '\0'; + key = line; + value = strchr(line, ':'); + value[0] = '\0'; + value++; + while(isspace(*value)) value++; + /*printf("!! [%s] \"%s\"\n", key, value);*/ + + if (!strcmp(key, "SDM-Version")) { + /* Check version. */ + if (strcmp(value, SDM_VERSION_STR)) { + ret = -2; + goto exit; + } + } else if (!strcmp(key, "Format")) { + /* Check format. */ + if (strcmp(value, "base64")) { + ret = -3; + goto exit; + } + } else if (!strcmp(key, "Order-of-bytes")) { + /* Check byte order. */ + if (strcmp(value, (is_little_endian() ? "little-endian" : "big-endian"))) { + ret = -4; + goto exit; + } + } else if (!strcmp(key, "Bits-per-Bitstring")) { + /* Check bits per bitstring. */ + bits_per_bitstring = atoi(value); + } else if (!strcmp(key, "Bits")) { + /* Check bits. */ + bits = atoi(value); + } else if (!strcmp(key, "Sample")) { + /* Check sample. */ + sample = atoi(value); + } else { + /* Unknown header. */ + ret = -5; + goto exit; + } + } + if (bits == 0 || sample == 0 || bits_per_bitstring == 0) { + ret = -6; + goto exit; + } + if (bits_per_bitstring % (8 * sizeof(bitstring_t)) != 0) { + ret = -7; + goto exit; + } + if (as_init(this, bits, sample)) { + ret = -8; + goto exit; + } + + /* Read address space (this->bs_data). */ + cnt = 0; + while(fgets(line, sizeof(line), fp)) { + bs_init_b64(this->addresses[cnt], line); + cnt++; + } + if (cnt != sample) { + as_free(this); + ret = -9; + goto exit; + } + +exit: + fclose(fp); + return ret; +} + diff --git a/pool/shard002/C/0062966_riowatchdog.c b/pool/shard002/C/0062966_riowatchdog.c new file mode 100644 index 0000000000000000000000000000000000000000..eb3b037ddc999c34f0643458fbe3bd7acf37d17c --- /dev/null +++ b/pool/shard002/C/0062966_riowatchdog.c @@ -0,0 +1,293 @@ +/* $Id: riowatchdog.c 2 2007-04-05 08:51:12Z tt $ + * riowatchdog.c - driver for hw watchdog inside Super I/O of RIO + * + * Copyright (C) 2001 David S. Miller (davem@redhat.com) + */ + +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include + +#include + +/* RIO uses the NatSemi Super I/O power management logical device + * as its' watchdog. + * + * When the watchdog triggers, it asserts a line to the BBC (Boot Bus + * Controller) of the machine. The BBC can only be configured to + * trigger a power-on reset when the signal is asserted. The BBC + * can be configured to ignore the signal entirely as well. + * + * The only Super I/O device register we care about is at index + * 0x05 (WDTO_INDEX) which is the watchdog time-out in minutes (1-255). + * If set to zero, this disables the watchdog. When set, the system + * must periodically (before watchdog expires) clear (set to zero) and + * re-set the watchdog else it will trigger. + * + * There are two other indexed watchdog registers inside this Super I/O + * logical device, but they are unused. The first, at index 0x06 is + * the watchdog control and can be used to make the watchdog timer re-set + * when the PS/2 mouse or serial lines show activity. The second, at + * index 0x07 is merely a sampling of the line from the watchdog to the + * BBC. + * + * The watchdog device generates no interrupts. + */ + +MODULE_AUTHOR("David S. Miller "); +MODULE_DESCRIPTION("Hardware watchdog driver for Sun RIO"); +MODULE_SUPPORTED_DEVICE("watchdog"); +MODULE_LICENSE("GPL"); + +#define RIOWD_NAME "pmc" +#define RIOWD_MINOR 215 + +static DEFINE_SPINLOCK(riowd_lock); + +static void __iomem *bbc_regs; +static void __iomem *riowd_regs; +#define WDTO_INDEX 0x05 + +static int riowd_timeout = 1; /* in minutes */ +module_param(riowd_timeout, int, 0); +MODULE_PARM_DESC(riowd_timeout, "Watchdog timeout in minutes"); + +#if 0 /* Currently unused. */ +static u8 riowd_readreg(int index) +{ + unsigned long flags; + u8 ret; + + spin_lock_irqsave(&riowd_lock, flags); + writeb(index, riowd_regs + 0); + ret = readb(riowd_regs + 1); + spin_unlock_irqrestore(&riowd_lock, flags); + + return ret; +} +#endif + +static void riowd_writereg(u8 val, int index) +{ + unsigned long flags; + + spin_lock_irqsave(&riowd_lock, flags); + writeb(index, riowd_regs + 0); + writeb(val, riowd_regs + 1); + spin_unlock_irqrestore(&riowd_lock, flags); +} + +static void riowd_pingtimer(void) +{ + riowd_writereg(riowd_timeout, WDTO_INDEX); +} + +static void riowd_stoptimer(void) +{ + u8 val; + + riowd_writereg(0, WDTO_INDEX); + + val = readb(bbc_regs + BBC_WDACTION); + val &= ~BBC_WDACTION_RST; + writeb(val, bbc_regs + BBC_WDACTION); +} + +static void riowd_starttimer(void) +{ + u8 val; + + riowd_writereg(riowd_timeout, WDTO_INDEX); + + val = readb(bbc_regs + BBC_WDACTION); + val |= BBC_WDACTION_RST; + writeb(val, bbc_regs + BBC_WDACTION); +} + +static int riowd_open(struct inode *inode, struct file *filp) +{ + nonseekable_open(inode, filp); + return 0; +} + +static int riowd_release(struct inode *inode, struct file *filp) +{ + return 0; +} + +static int riowd_ioctl(struct inode *inode, struct file *filp, + unsigned int cmd, unsigned long arg) +{ + static struct watchdog_info info = { + WDIOF_SETTIMEOUT, 0, "Natl. Semiconductor PC97317" + }; + void __user *argp = (void __user *)arg; + unsigned int options; + int new_margin; + + switch (cmd) { + case WDIOC_GETSUPPORT: + if (copy_to_user(argp, &info, sizeof(info))) + return -EFAULT; + break; + + case WDIOC_GETSTATUS: + case WDIOC_GETBOOTSTATUS: + if (put_user(0, (int __user *)argp)) + return -EFAULT; + break; + + case WDIOC_KEEPALIVE: + riowd_pingtimer(); + break; + + case WDIOC_SETOPTIONS: + if (copy_from_user(&options, argp, sizeof(options))) + return -EFAULT; + + if (options & WDIOS_DISABLECARD) + riowd_stoptimer(); + else if (options & WDIOS_ENABLECARD) + riowd_starttimer(); + else + return -EINVAL; + + break; + + case WDIOC_SETTIMEOUT: + if (get_user(new_margin, (int __user *)argp)) + return -EFAULT; + if ((new_margin < 60) || (new_margin > (255 * 60))) + return -EINVAL; + riowd_timeout = (new_margin + 59) / 60; + riowd_pingtimer(); + /* Fall */ + + case WDIOC_GETTIMEOUT: + return put_user(riowd_timeout * 60, (int __user *)argp); + + default: + return -EINVAL; + }; + + return 0; +} + +static ssize_t riowd_write(struct file *file, const char __user *buf, size_t count, loff_t *ppos) +{ + if (count) { + riowd_pingtimer(); + return 1; + } + + return 0; +} + +static struct file_operations riowd_fops = { + .owner = THIS_MODULE, + .ioctl = riowd_ioctl, + .open = riowd_open, + .write = riowd_write, + .release = riowd_release, +}; + +static struct miscdevice riowd_miscdev = { RIOWD_MINOR, RIOWD_NAME, &riowd_fops }; + +static int __init riowd_bbc_init(void) +{ + struct linux_ebus *ebus = NULL; + struct linux_ebus_device *edev = NULL; + u8 val; + + for_each_ebus(ebus) { + for_each_ebusdev(edev, ebus) { + if (!strcmp(edev->prom_name, "bbc")) + goto found_bbc; + } + } + +found_bbc: + if (!edev) + return -ENODEV; + bbc_regs = ioremap(edev->resource[0].start, BBC_REGS_SIZE); + if (!bbc_regs) + return -ENODEV; + + /* Turn it off. */ + val = readb(bbc_regs + BBC_WDACTION); + val &= ~BBC_WDACTION_RST; + writeb(val, bbc_regs + BBC_WDACTION); + + return 0; +} + +static int __init riowd_init(void) +{ + struct linux_ebus *ebus = NULL; + struct linux_ebus_device *edev = NULL; + + for_each_ebus(ebus) { + for_each_ebusdev(edev, ebus) { + if (!strcmp(edev->prom_name, RIOWD_NAME)) + goto ebus_done; + } + } + +ebus_done: + if (!edev) + goto fail; + + riowd_regs = ioremap(edev->resource[0].start, 2); + if (riowd_regs == NULL) { + printk(KERN_ERR "pmc: Cannot map registers.\n"); + return -ENODEV; + } + + if (riowd_bbc_init()) { + printk(KERN_ERR "pmc: Failure initializing BBC config.\n"); + goto fail; + } + + if (misc_register(&riowd_miscdev)) { + printk(KERN_ERR "pmc: Cannot register watchdog misc device.\n"); + goto fail; + } + + printk(KERN_INFO "pmc: Hardware watchdog [%i minutes], " + "regs at %p\n", riowd_timeout, riowd_regs); + + return 0; + +fail: + if (riowd_regs) { + iounmap(riowd_regs); + riowd_regs = NULL; + } + if (bbc_regs) { + iounmap(bbc_regs); + bbc_regs = NULL; + } + return -ENODEV; +} + +static void __exit riowd_cleanup(void) +{ + misc_deregister(&riowd_miscdev); + iounmap(riowd_regs); + riowd_regs = NULL; + iounmap(bbc_regs); + bbc_regs = NULL; +} + +module_init(riowd_init); +module_exit(riowd_cleanup); diff --git a/pool/shard002/C/0062989_led.c b/pool/shard002/C/0062989_led.c new file mode 100644 index 0000000000000000000000000000000000000000..8618339acfaa877cb1d72ec5eaa157f90688546f --- /dev/null +++ b/pool/shard002/C/0062989_led.c @@ -0,0 +1,34 @@ +/***************************************************************************** +Copyright: 2014, Shanghai Toptech Tech. Co., Ltd. +File name: led.c +Description: ledÓ¦Óú¯Êý +Author: CharlieShao +Version: V1.0 +Date: 2014/12/1 +History: ÎÞ +*****************************************************************************/ +#include "led.h" +/*********************************************************************************** +FunctionName: void WorkLED_GPIO_Config(void) +Description: ¹¤×÷ÐźÅָʾµÆµÄ³õʼ»¯º¯Êý +Input: ÎÞ +Output: ÎÞ +Return: ÎÞ +***********************************************************************************/ +void WorkLED_GPIO_Config(void) +{ + GPIO_InitTypeDef GPIO_InitStructure; + + //µãÁÁ¹¤×÷ָʾµÆ + RCC_APB2PeriphClockCmd( RCC_APB2Periph_GPIOE, ENABLE); + + GPIO_InitStructure.GPIO_Pin = GPIO_Pin_1; + GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP; + GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz; + GPIO_Init(GPIOE, &GPIO_InitStructure); + + GPIO_ResetBits(GPIOE, GPIO_Pin_1); // turn off all led +} + + +/************************END OF FILE************************/ diff --git a/pool/shard002/C/0062996_add.c b/pool/shard002/C/0062996_add.c new file mode 100644 index 0000000000000000000000000000000000000000..770e2bd5c1a158642b8799c9375954f0f7953983 --- /dev/null +++ b/pool/shard002/C/0062996_add.c @@ -0,0 +1,28 @@ +#include + +int main(int argc, char *argv[]) { + + FILE *f; + long double sum = 0, x = 0; + + // if the file name is not specified, attempt to read from the standard + // input + if(!(f = argc <= 1 ? stdin : fopen(argv[1], "r"))) { + printf("Unable to open stream for reading.\n"); + return 1; + } + + while(!feof(f)) { + + // increment the sum + sum += x; + + // read the number + fscanf(f, "%Lf", &x); + + } + + printf("%.10Lg\n", sum); + + return 0; +} diff --git a/pool/shard002/C/0062998_test-objects-foreach.c b/pool/shard002/C/0062998_test-objects-foreach.c new file mode 100644 index 0000000000000000000000000000000000000000..fef7094dd34f55d420f677ecd11dc0731a9ad564 --- /dev/null +++ b/pool/shard002/C/0062998_test-objects-foreach.c @@ -0,0 +1,133 @@ +/* Copyright JS Foundation and other contributors, http://js.foundation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "jerryscript.h" +#include "test-common.h" + +static int test_data = 1; + +static void free_test_data (void *data_p) +{ + TEST_ASSERT ((int *) data_p == &test_data); +} /* free_test_data */ + +static const jerry_object_native_info_t test_info = +{ + .free_cb = free_test_data +}; + +static const char *strict_equal_source = "var x = function(a, b) {return a === b;}; x"; + +static bool +find_test_object_by_data (const jerry_value_t candidate, + void *object_data_p, + void *context_p) +{ + if (object_data_p == &test_data) + { + *((jerry_value_t *) context_p) = jerry_acquire_value (candidate); + return false; + } + return true; +} /* find_test_object_by_data */ + +static bool +find_test_object_by_property (const jerry_value_t candidate, + void *context_p) +{ + jerry_value_t *args_p = (jerry_value_t *) context_p; + jerry_value_t result = jerry_has_property (candidate, args_p[0]); + + bool has_property = (!jerry_value_has_error_flag (result) && jerry_get_boolean_value (result)); + + /* If the object has the desired property, store a new reference to it in args_p[1]. */ + if (has_property) + { + args_p[1] = jerry_acquire_value (candidate); + } + + jerry_release_value (result); + + /* Stop iterating if we've found our object. */ + return !has_property; +} /* find_test_object_by_property */ + +int +main (void) +{ + jerry_init (JERRY_INIT_EMPTY); + + /* Render strict-equal as a function. */ + jerry_value_t parse_result = jerry_parse ((jerry_char_t *) strict_equal_source, strlen (strict_equal_source), true); + TEST_ASSERT (!jerry_value_has_error_flag (parse_result)); + jerry_value_t strict_equal = jerry_run (parse_result); + TEST_ASSERT (!jerry_value_has_error_flag (strict_equal)); + jerry_release_value (parse_result); + + /* Create an object and associate some native data with it. */ + jerry_value_t object = jerry_create_object (); + jerry_set_object_native_pointer (object, &test_data, &test_info); + + /* Retrieve the object by its native pointer. */ + + jerry_value_t found_object; + TEST_ASSERT (jerry_objects_foreach_by_native_info (&test_info, find_test_object_by_data, &found_object)); + jerry_value_t args[2] = {object, found_object}; + + /* Assert that the correct object was retrieved. */ + jerry_value_t undefined = jerry_create_undefined (); + jerry_value_t strict_equal_result = jerry_call_function (strict_equal, undefined, args, 2); + TEST_ASSERT (jerry_value_is_boolean (strict_equal_result) && jerry_get_boolean_value (strict_equal_result)); + jerry_release_value (strict_equal_result); + jerry_release_value (found_object); + jerry_release_value (object); + + /* Collect garbage. */ + jerry_gc (); + + /* Attempt to retrieve the object by its native pointer again. */ + TEST_ASSERT (!jerry_objects_foreach_by_native_info (&test_info, find_test_object_by_data, &found_object)); + + /* Create an object and set a property on it. */ + object = jerry_create_object (); + jerry_value_t property_name = jerry_create_string ((jerry_char_t *) "xyzzy"); + jerry_value_t property_value = jerry_create_number (42); + jerry_release_value (jerry_set_property (object, property_name, property_value)); + jerry_release_value (property_value); + + /* Retrieve the object by the presence of its property, placing it at args[1]. */ + args[0] = property_name; + TEST_ASSERT (jerry_objects_foreach (find_test_object_by_property, args)); + + /* Assert that the right object was retrieved and release both the original reference to it and the retrieved one. */ + args[0] = object; + strict_equal_result = jerry_call_function (strict_equal, undefined, args, 2); + TEST_ASSERT (jerry_value_is_boolean (strict_equal_result) && jerry_get_boolean_value (strict_equal_result)); + jerry_release_value (strict_equal_result); + jerry_release_value (args[0]); + jerry_release_value (args[1]); + + /* Collect garbage. */ + jerry_gc (); + + /* Attempt to retrieve the object by the presence of its property again. */ + args[0] = property_name; + TEST_ASSERT (!jerry_objects_foreach (find_test_object_by_property, args)); + + jerry_release_value (property_name); + jerry_release_value (undefined); + jerry_release_value (strict_equal); + jerry_cleanup (); +} /* main */ diff --git a/pool/shard002/C/0063006_vao.c b/pool/shard002/C/0063006_vao.c new file mode 100644 index 0000000000000000000000000000000000000000..a4f8f847e843fa0617f05453594f8bd7856a1fba --- /dev/null +++ b/pool/shard002/C/0063006_vao.c @@ -0,0 +1,87 @@ +/* + Madd Software Renderer + + Copyright (c) 2014-2017, Madd Games. + 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. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ + +#include "context.h" +#include "vao.h" + +DDIGL_VertexArray* srCreateVertexArray(DDIGL_Context *ctx, GLenum *error) +{ + DDIGL_VertexArray *vao = (DDIGL_VertexArray*) malloc(sizeof(DDIGL_VertexArray)); + if (vao == NULL) + { + *error = GL_OUT_OF_MEMORY; + return NULL; + }; + + memset(vao, 0, sizeof(DDIGL_VertexArray)); + return vao; +}; + +GLenum srBindVertexArray(DDIGL_Context *ctx, DDIGL_VertexArray *vao) +{ + // no-op: we can just use ctx->vaoCurrent when we need the binding + return GL_NO_ERROR; +}; + +void srDeleteVertexArray(DDIGL_Context *ctx, DDIGL_VertexArray *vao) +{ + free(vao); +}; + +GLenum srSetAttribEnable(DDIGL_Context *ctx, GLuint index, GLboolean enable) +{ + if (index >= 64) return GL_INVALID_VALUE; + + if (enable) + { + ctx->vaoCurrent->enable |= (1 << index); + } + else + { + ctx->vaoCurrent->enable &= ~(1 << index); + }; + + return GL_NO_ERROR; +}; + +GLenum srAttribPointer(DDIGL_Context *ctx, GLuint index, GLint size, GLenum type, GLboolean normalized, + GLsizei stride, GLsizeiptr offset) +{ + if (index >= 64) return GL_INVALID_VALUE; + if (ctx->arrayBuffer == NULL) return GL_INVALID_OPERATION; + + SRVertexAttrib *attrib = &ctx->vaoCurrent->attribs[index]; + attrib->buffer = ctx->arrayBuffer; + attrib->size = size; + attrib->type = type; + attrib->normalized = normalized; + attrib->stride = stride; + attrib->offset = offset; + + return GL_NO_ERROR; +}; diff --git a/pool/shard002/C/0063027_smbus.c b/pool/shard002/C/0063027_smbus.c new file mode 100644 index 0000000000000000000000000000000000000000..ddbcdf2683177762b0449c0621eac8012a43571c --- /dev/null +++ b/pool/shard002/C/0063027_smbus.c @@ -0,0 +1,187 @@ +/* + * This file is part of the coreboot project. + * + * Copyright (C) 2007 Advanced Micro Devices, Inc. + * + * 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. + */ + +#include +#include +#include "cs5536.h" +#include "smbus.h" + +#define SMBUS_TIMEOUT (1000) + +static void smbus_delay(void) +{ + /* inb(0x80); */ +} + +static int smbus_wait(unsigned smbus_io_base) +{ + unsigned long loops = SMBUS_TIMEOUT; + unsigned char val; + + do { + smbus_delay(); + val = inb(smbus_io_base + SMB_STS); + if ((val & SMB_STS_SDAST) != 0) + break; + if (val & (SMB_STS_BER | SMB_STS_NEGACK)) { + /*printk(BIOS_DEBUG, "SMBUS WAIT ERROR %x\n", val); */ + return SMBUS_ERROR; + } + } while (--loops); + return loops ? 0 : SMBUS_WAIT_UNTIL_READY_TIMEOUT; +} + +/* generate a smbus start condition */ +int smbus_start_condition(unsigned smbus_io_base) +{ + unsigned char val; + + /* issue a START condition */ + val = inb(smbus_io_base + SMB_CTRL1); + outb(val | SMB_CTRL1_START, smbus_io_base + SMB_CTRL1); + + /* check for bus conflict */ + val = inb(smbus_io_base + SMB_STS); + if ((val & SMB_STS_BER) != 0) + return SMBUS_ERROR; + + return smbus_wait(smbus_io_base); +} + +int smbus_check_stop_condition(unsigned smbus_io_base) +{ + unsigned char val; + unsigned long loops; + loops = SMBUS_TIMEOUT; + /* check for SDA status */ + do { + smbus_delay(); + val = inb(smbus_io_base + SMB_CTRL1); + if ((val & SMB_CTRL1_STOP) == 0) { + break; + } + outb((0x7F << 1) | SMB_CTRL2_ENABLE, smbus_io_base + SMB_CTRL2); + } while (--loops); + return loops ? 0 : SMBUS_WAIT_UNTIL_READY_TIMEOUT; +} + +int smbus_stop_condition(unsigned smbus_io_base) +{ + outb(SMB_CTRL1_STOP, smbus_io_base + SMB_CTRL1); + return smbus_wait(smbus_io_base); +} + +static int smbus_ack(unsigned smbus_io_base, int state) +{ + unsigned char val = inb(smbus_io_base + SMB_CTRL1); + +/* if (state) */ + outb(val | SMB_CTRL1_ACK, smbus_io_base + SMB_CTRL1); +/* else + outb(val & ~SMB_CTRL1_ACK, smbus_io_base + SMB_CTRL1); +*/ + return 0; +} + +int smbus_send_slave_address(unsigned smbus_io_base, + unsigned char device) +{ + unsigned char val; + + /* send the slave address */ + outb(device, smbus_io_base + SMB_SDA); + + /* check for bus conflict and NACK */ + val = inb(smbus_io_base + SMB_STS); + if (((val & SMB_STS_BER) != 0) || ((val & SMB_STS_NEGACK) != 0)) { + /* printk(BIOS_DEBUG, "SEND SLAVE ERROR (%x)\n", val); */ + return SMBUS_ERROR; + } + return smbus_wait(smbus_io_base); +} + +int smbus_send_command(unsigned smbus_io_base, unsigned char command) +{ + unsigned char val; + + /* send the command */ + outb(command, smbus_io_base + SMB_SDA); + + /* check for bus conflict and NACK */ + val = inb(smbus_io_base + SMB_STS); + if (((val & SMB_STS_BER) != 0) || ((val & SMB_STS_NEGACK) != 0)) + return SMBUS_ERROR; + + return smbus_wait(smbus_io_base); +} + +static unsigned char smbus_get_result(unsigned smbus_io_base) +{ + return inb(smbus_io_base + SMB_SDA); +} + +unsigned char do_smbus_read_byte(unsigned smbus_io_base, + unsigned char device, + unsigned char address) +{ + unsigned char error = 0; + + if ((smbus_check_stop_condition(smbus_io_base))) { + error = 1; + goto err; + } + + if ((smbus_start_condition(smbus_io_base))) { + error = 2; + goto err; + } + + if ((smbus_send_slave_address(smbus_io_base, device << 1))) { + error = 3; + goto err; + } + + smbus_ack(smbus_io_base, 1); + + if ((smbus_send_command(smbus_io_base, address))) { + error = 4; + goto err; + } + + if ((smbus_start_condition(smbus_io_base))) { + error = 5; + goto err; + } + + if ((smbus_send_slave_address(smbus_io_base, (device << 1) | 0x01))) { + error = 6; + goto err; + } + + if ((smbus_stop_condition(smbus_io_base))) { + error = 7; + goto err; + } + + return smbus_get_result(smbus_io_base); + +err: + printk(BIOS_DEBUG, "SMBUS READ ERROR: %02x device: %02x\n", error, device); + /* stop, clean up the error, and leave */ + smbus_stop_condition(smbus_io_base); + outb(inb(smbus_io_base + SMB_STS), smbus_io_base + SMB_STS); + outb(0x0, smbus_io_base + SMB_STS); + return 0xFF; +} diff --git a/pool/shard002/C/0063037_libmprof.c b/pool/shard002/C/0063037_libmprof.c new file mode 100644 index 0000000000000000000000000000000000000000..82abfd6113d4a0d4a7e576845429a3e0c42fd7d8 --- /dev/null +++ b/pool/shard002/C/0063037_libmprof.c @@ -0,0 +1,133 @@ +/* + Copyright (c) 2013 by Alexander Haase ( https://www.alexanderhaase.net ) + Project: mprof ( https://www.alexanderhaase.net/projects/mprof.html ) + Created: 2013-09-08 + License: LGPL + + mprof 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. + + mprof 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 mprof. If not, see . +*/ +/* Description: + base file for the shared library, sets up mprof bindings. +*/ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +const char * defaultConfig = "INIT=LD_NEXT MODE=Count"; + +const struct AllocatorVtable * mprofInitTargets[] = { &mprofLDInitVtable, NULL }; +const struct AllocatorVtable * mprofModeTargets[] = { &mprofLogFDVtable, &mprofCountVtable, &mprofLogMmapVtable, NULL }; + + +const struct AllocatorVtable * lookupVtable( const char * in_str, size_t in_strSize, const struct AllocatorVtable * in_tables[] ) { + size_t index; + for( index = 0; in_tables[ index ] != NULL; index++ ) { + if( strncmp( in_tables[ index ]->name, in_str, in_strSize ) == 0 ) { + return in_tables[ index ]; + } + } + return NULL; +} + +void installVtableOrDie( const char * in_key, const struct AllocatorVtable * in_tables[], struct AllocatorVtable * out_table ) { + const char * config = getConfStr(); + if( NULL == config ) { + config = defaultConfig; + } + + size_t valueSize; + const char * value = findArg( config, in_key, &valueSize ); + if( NULL == value ) { + fprintf( stderr, "Error: libmprof: Could not find value for '%s' in env var 'MPROF_CONF'.\n", in_key ); + exit( -1 ); + } + + const struct AllocatorVtable * table = lookupVtable( value, valueSize, in_tables ); + if( NULL == table ) { + //not wise, but neither is fprintf without malloc.... + ((char*) value )[ valueSize ] = '\0'; + fprintf( stderr, "Error: libmprof: Cannot find vtable '%s' candidate for '%s'\n", value, in_key ); + exit( -1 ); + } + + *out_table = *table; + if( table->construct ) { + table->construct(); + } +} + +static void /*__attribute__(( constructor ))*/ libmprofInit( void ) { + /* AH order is important: INIT will probably strap in MODE's vtable */ + mprofVtable = tmpAllocVtable; //AH, maybe this will let fprintf work in a pinch? + installVtableOrDie( "MODE", mprofModeTargets, &postInitVtable ); + installVtableOrDie( "INIT", mprofInitTargets, &mprofVtable ); +} + +void __attribute__(( destructor )) libmprofDestruct( void ) { + if( mprofVtable.destruct ) { + mprofVtable.destruct(); + + /* dump some text so people know we exited cleanly */ + const char * modeName = mprofVtable.name; + mprofVtable = tmpAllocVtable; + fprintf( stderr, "Info: libmprof: called destructor for 'MODE' '%s'\n", modeName ); + } + +} + +void * malloc( size_t in_size ) { + return mprofVtable.malloc( in_size ); +} + +void free( void * in_ptr ) { + mprofVtable.free( in_ptr ); +} + +void * calloc( size_t in_qty, size_t in_size ) { + return mprofVtable.calloc( in_qty, in_size ); +} + +void * realloc( void * in_ptr, size_t in_size ) { + return mprofVtable.realloc( in_ptr, in_size ); +} + +/* we need to provide on-demand init functionality..construct order not dependable*/ +static void * mallocLibInit( size_t in_size ) { + libmprofInit(); + return mprofVtable.malloc( in_size ); +} + +static void freeLibInit( void * in_ptr ) { + libmprofInit(); + mprofVtable.free( in_ptr ); +} + +static void * callocLibInit( size_t in_qty, size_t in_size ) { + libmprofInit(); + return mprofVtable.calloc( in_qty, in_size ); +} + +static void * reallocLibInit( void * in_ptr, size_t in_size ) { + libmprofInit(); + return mprofVtable.realloc( in_ptr, in_size ); +} + +struct AllocatorVtable mprofVtable = { mallocLibInit, freeLibInit, callocLibInit, reallocLibInit, NULL, NULL, "LIBMPROF_BOOTSTRAP" }; diff --git a/pool/shard002/C/0063039_class.c b/pool/shard002/C/0063039_class.c new file mode 100644 index 0000000000000000000000000000000000000000..ad353c98ec576b451cfe5795ccd910e29116f3d2 --- /dev/null +++ b/pool/shard002/C/0063039_class.c @@ -0,0 +1,242 @@ +/* + * RTC subsystem, base class + * + * Copyright (C) 2005 Tower Technologies + * Author: Alessandro Zummo + * + * class skeleton from drivers/hwmon/hwmon.c + * + * 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 "rtc-core.h" + + +static DEFINE_IDR(rtc_idr); +static DEFINE_MUTEX(idr_lock); +struct class *rtc_class; + +static void rtc_device_release(struct device *dev) +{ + struct rtc_device *rtc = to_rtc_device(dev); + mutex_lock(&idr_lock); + idr_remove(&rtc_idr, rtc->id); + mutex_unlock(&idr_lock); + kfree(rtc); +} + +#if defined(CONFIG_PM) && defined(CONFIG_RTC_HCTOSYS_DEVICE) + +/* + * On suspend(), measure the delta between one RTC and the + * system's wall clock; restore it on resume(). + */ + +static struct timespec delta; +static time_t oldtime; + +static int rtc_suspend(struct device *dev, pm_message_t mesg) +{ + struct rtc_device *rtc = to_rtc_device(dev); + struct rtc_time tm; + struct timespec ts = current_kernel_time(); + + if (strncmp(rtc->dev.bus_id, + CONFIG_RTC_HCTOSYS_DEVICE, + BUS_ID_SIZE) != 0) + return 0; + + rtc_read_time(rtc, &tm); + rtc_tm_to_time(&tm, &oldtime); + + /* RTC precision is 1 second; adjust delta for avg 1/2 sec err */ + set_normalized_timespec(&delta, + ts.tv_sec - oldtime, + ts.tv_nsec - (NSEC_PER_SEC >> 1)); + + return 0; +} + +static int rtc_resume(struct device *dev) +{ + struct rtc_device *rtc = to_rtc_device(dev); + struct rtc_time tm; + time_t newtime; + struct timespec time; + + if (strncmp(rtc->dev.bus_id, + CONFIG_RTC_HCTOSYS_DEVICE, + BUS_ID_SIZE) != 0) + return 0; + + rtc_read_time(rtc, &tm); + if (rtc_valid_tm(&tm) != 0) { + pr_debug("%s: bogus resume time\n", rtc->dev.bus_id); + return 0; + } + rtc_tm_to_time(&tm, &newtime); + if (newtime <= oldtime) { + if (newtime < oldtime) + pr_debug("%s: time travel!\n", rtc->dev.bus_id); + return 0; + } + + /* restore wall clock using delta against this RTC; + * adjust again for avg 1/2 second RTC sampling error + */ + set_normalized_timespec(&time, + newtime + delta.tv_sec, + (NSEC_PER_SEC >> 1) + delta.tv_nsec); + do_settimeofday(&time); + + return 0; +} + +#else +#define rtc_suspend NULL +#define rtc_resume NULL +#endif + + +/** + * rtc_device_register - register w/ RTC class + * @dev: the device to register + * + * rtc_device_unregister() must be called when the class device is no + * longer needed. + * + * Returns the pointer to the new struct class device. + */ +struct rtc_device *rtc_device_register(const char *name, struct device *dev, + const struct rtc_class_ops *ops, + struct module *owner) +{ + struct rtc_device *rtc; + int id, err; + + if (idr_pre_get(&rtc_idr, GFP_KERNEL) == 0) { + err = -ENOMEM; + goto exit; + } + + + mutex_lock(&idr_lock); + err = idr_get_new(&rtc_idr, NULL, &id); + mutex_unlock(&idr_lock); + + if (err < 0) + goto exit; + + id = id & MAX_ID_MASK; + + rtc = kzalloc(sizeof(struct rtc_device), GFP_KERNEL); + if (rtc == NULL) { + err = -ENOMEM; + goto exit_idr; + } + + rtc->id = id; + rtc->ops = ops; + rtc->owner = owner; + rtc->max_user_freq = 64; + rtc->dev.parent = dev; + rtc->dev.class = rtc_class; + rtc->dev.release = rtc_device_release; + + mutex_init(&rtc->ops_lock); + spin_lock_init(&rtc->irq_lock); + spin_lock_init(&rtc->irq_task_lock); + init_waitqueue_head(&rtc->irq_queue); + + strlcpy(rtc->name, name, RTC_DEVICE_NAME_SIZE); + snprintf(rtc->dev.bus_id, BUS_ID_SIZE, "rtc%d", id); + + rtc_dev_prepare(rtc); + + err = device_register(&rtc->dev); + if (err) + goto exit_kfree; + + rtc_dev_add_device(rtc); + rtc_sysfs_add_device(rtc); + rtc_proc_add_device(rtc); + +#ifdef CONFIG_POLLUX_KERNEL_BOOT_MESSAGE_ENABLE + dev_info(dev, "rtc core: registered %s as %s\n", + rtc->name, rtc->dev.bus_id); +#endif + + return rtc; + +exit_kfree: + kfree(rtc); + +exit_idr: + mutex_lock(&idr_lock); + idr_remove(&rtc_idr, id); + mutex_unlock(&idr_lock); + +exit: + dev_err(dev, "rtc core: unable to register %s, err = %d\n", + name, err); + return ERR_PTR(err); +} +EXPORT_SYMBOL_GPL(rtc_device_register); + + +/** + * rtc_device_unregister - removes the previously registered RTC class device + * + * @rtc: the RTC class device to destroy + */ +void rtc_device_unregister(struct rtc_device *rtc) +{ + if (get_device(&rtc->dev) != NULL) { + mutex_lock(&rtc->ops_lock); + /* remove innards of this RTC, then disable it, before + * letting any rtc_class_open() users access it again + */ + rtc_sysfs_del_device(rtc); + rtc_dev_del_device(rtc); + rtc_proc_del_device(rtc); + device_unregister(&rtc->dev); + rtc->ops = NULL; + mutex_unlock(&rtc->ops_lock); + put_device(&rtc->dev); + } +} +EXPORT_SYMBOL_GPL(rtc_device_unregister); + +static int __init rtc_init(void) +{ + rtc_class = class_create(THIS_MODULE, "rtc"); + if (IS_ERR(rtc_class)) { + printk(KERN_ERR "%s: couldn't create class\n", __FILE__); + return PTR_ERR(rtc_class); + } + rtc_class->suspend = rtc_suspend; + rtc_class->resume = rtc_resume; + rtc_dev_init(); + rtc_sysfs_init(rtc_class); + return 0; +} + +static void __exit rtc_exit(void) +{ + rtc_dev_exit(); + class_destroy(rtc_class); +} + +subsys_initcall(rtc_init); +module_exit(rtc_exit); + +MODULE_AUTHOR("Alessandro Zummo "); +MODULE_DESCRIPTION("RTC class support"); +MODULE_LICENSE("GPL"); diff --git a/pool/shard002/C/0063054_tc-dwc-g210-pci.c b/pool/shard002/C/0063054_tc-dwc-g210-pci.c new file mode 100644 index 0000000000000000000000000000000000000000..67a6a61154b7184771bbe2447f19a84f69ac4b18 --- /dev/null +++ b/pool/shard002/C/0063054_tc-dwc-g210-pci.c @@ -0,0 +1,176 @@ +// SPDX-License-Identifier: GPL-2.0-only +/* + * Synopsys G210 Test Chip driver + * + * Copyright (C) 2015-2016 Synopsys, Inc. (www.synopsys.com) + * + * Authors: Joao Pinto + */ + +#include "ufshcd.h" +#include "ufshcd-dwc.h" +#include "tc-dwc-g210.h" + +#include +#include + +/* Test Chip type expected values */ +#define TC_G210_20BIT 20 +#define TC_G210_40BIT 40 +#define TC_G210_INV 0 + +static int tc_type = TC_G210_INV; +module_param(tc_type, int, 0); +MODULE_PARM_DESC(tc_type, "Test Chip Type (20 = 20-bit, 40 = 40-bit)"); + +static int tc_dwc_g210_pci_suspend(struct device *dev) +{ + return ufshcd_system_suspend(dev_get_drvdata(dev)); +} + +static int tc_dwc_g210_pci_resume(struct device *dev) +{ + return ufshcd_system_resume(dev_get_drvdata(dev)); +} + +static int tc_dwc_g210_pci_runtime_suspend(struct device *dev) +{ + return ufshcd_runtime_suspend(dev_get_drvdata(dev)); +} + +static int tc_dwc_g210_pci_runtime_resume(struct device *dev) +{ + return ufshcd_runtime_resume(dev_get_drvdata(dev)); +} + +static int tc_dwc_g210_pci_runtime_idle(struct device *dev) +{ + return ufshcd_runtime_idle(dev_get_drvdata(dev)); +} + +/* + * struct ufs_hba_dwc_vops - UFS DWC specific variant operations + */ +static struct ufs_hba_variant_ops tc_dwc_g210_pci_hba_vops = { + .name = "tc-dwc-g210-pci", + .link_startup_notify = ufshcd_dwc_link_startup_notify, +}; + +/** + * tc_dwc_g210_pci_shutdown - main function to put the controller in reset state + * @pdev: pointer to PCI device handle + */ +static void tc_dwc_g210_pci_shutdown(struct pci_dev *pdev) +{ + ufshcd_shutdown((struct ufs_hba *)pci_get_drvdata(pdev)); +} + +/** + * tc_dwc_g210_pci_remove - de-allocate PCI/SCSI host and host memory space + * data structure memory + * @pdev: pointer to PCI handle + */ +static void tc_dwc_g210_pci_remove(struct pci_dev *pdev) +{ + struct ufs_hba *hba = pci_get_drvdata(pdev); + + pm_runtime_forbid(&pdev->dev); + pm_runtime_get_noresume(&pdev->dev); + ufshcd_remove(hba); +} + +/** + * tc_dwc_g210_pci_probe - probe routine of the driver + * @pdev: pointer to PCI device handle + * @id: PCI device id + * + * Returns 0 on success, non-zero value on failure + */ +static int +tc_dwc_g210_pci_probe(struct pci_dev *pdev, const struct pci_device_id *id) +{ + struct ufs_hba *hba; + void __iomem *mmio_base; + int err; + + /* Check Test Chip type and set the specific setup routine */ + if (tc_type == TC_G210_20BIT) { + tc_dwc_g210_pci_hba_vops.phy_initialization = + tc_dwc_g210_config_20_bit; + } else if (tc_type == TC_G210_40BIT) { + tc_dwc_g210_pci_hba_vops.phy_initialization = + tc_dwc_g210_config_40_bit; + } else { + dev_err(&pdev->dev, "test chip version not specified\n"); + return -EPERM; + } + + err = pcim_enable_device(pdev); + if (err) { + dev_err(&pdev->dev, "pcim_enable_device failed\n"); + return err; + } + + pci_set_master(pdev); + + err = pcim_iomap_regions(pdev, 1 << 0, UFSHCD); + if (err < 0) { + dev_err(&pdev->dev, "request and iomap failed\n"); + return err; + } + + mmio_base = pcim_iomap_table(pdev)[0]; + + err = ufshcd_alloc_host(&pdev->dev, &hba); + if (err) { + dev_err(&pdev->dev, "Allocation failed\n"); + return err; + } + + hba->vops = &tc_dwc_g210_pci_hba_vops; + + err = ufshcd_init(hba, mmio_base, pdev->irq); + if (err) { + dev_err(&pdev->dev, "Initialization failed\n"); + return err; + } + + pci_set_drvdata(pdev, hba); + pm_runtime_put_noidle(&pdev->dev); + pm_runtime_allow(&pdev->dev); + + return 0; +} + +static const struct dev_pm_ops tc_dwc_g210_pci_pm_ops = { + .suspend = tc_dwc_g210_pci_suspend, + .resume = tc_dwc_g210_pci_resume, + .runtime_suspend = tc_dwc_g210_pci_runtime_suspend, + .runtime_resume = tc_dwc_g210_pci_runtime_resume, + .runtime_idle = tc_dwc_g210_pci_runtime_idle, +}; + +static const struct pci_device_id tc_dwc_g210_pci_tbl[] = { + { PCI_VENDOR_ID_SYNOPSYS, 0xB101, PCI_ANY_ID, PCI_ANY_ID, 0, 0, 0 }, + { PCI_VENDOR_ID_SYNOPSYS, 0xB102, PCI_ANY_ID, PCI_ANY_ID, 0, 0, 0 }, + { } /* terminate list */ +}; + +MODULE_DEVICE_TABLE(pci, tc_dwc_g210_pci_tbl); + +static struct pci_driver tc_dwc_g210_pci_driver = { + .name = "tc-dwc-g210-pci", + .id_table = tc_dwc_g210_pci_tbl, + .probe = tc_dwc_g210_pci_probe, + .remove = tc_dwc_g210_pci_remove, + .shutdown = tc_dwc_g210_pci_shutdown, + .driver = { + .pm = &tc_dwc_g210_pci_pm_ops + }, +}; + +module_pci_driver(tc_dwc_g210_pci_driver); + +MODULE_AUTHOR("Joao Pinto "); +MODULE_DESCRIPTION("Synopsys Test Chip G210 PCI glue driver"); +MODULE_LICENSE("Dual BSD/GPL"); diff --git a/pool/shard002/C/0063055_gcs_params.c b/pool/shard002/C/0063055_gcs_params.c new file mode 100644 index 0000000000000000000000000000000000000000..c1005133d134d294957fa34ec6a4aeb4185ff7fb --- /dev/null +++ b/pool/shard002/C/0063055_gcs_params.c @@ -0,0 +1,201 @@ +/* + * Copyright (C) 2010-2014 Codership Oy + * + * $Id: gcs_params.c 3455 2014-02-01 18:11:09Z alex $ + */ + +#include "gcs_params.h" + +#include +#include + +const char* const GCS_PARAMS_FC_FACTOR = "gcs.fc_factor"; +const char* const GCS_PARAMS_FC_LIMIT = "gcs.fc_limit"; +const char* const GCS_PARAMS_FC_MASTER_SLAVE = "gcs.fc_master_slave"; +const char* const GCS_PARAMS_FC_DEBUG = "gcs.fc_debug"; +const char* const GCS_PARAMS_SYNC_DONOR = "gcs.sync_donor"; +const char* const GCS_PARAMS_MAX_PKT_SIZE = "gcs.max_packet_size"; +const char* const GCS_PARAMS_RECV_Q_HARD_LIMIT = "gcs.recv_q_hard_limit"; +const char* const GCS_PARAMS_RECV_Q_SOFT_LIMIT = "gcs.recv_q_soft_limit"; +const char* const GCS_PARAMS_MAX_THROTTLE = "gcs.max_throttle"; + +static const char* const GCS_PARAMS_FC_FACTOR_DEFAULT = "1.0"; +static const char* const GCS_PARAMS_FC_LIMIT_DEFAULT = "16"; +static const char* const GCS_PARAMS_FC_MASTER_SLAVE_DEFAULT = "no"; +static const char* const GCS_PARAMS_FC_DEBUG_DEFAULT = "0"; +static const char* const GCS_PARAMS_SYNC_DONOR_DEFAULT = "no"; +static const char* const GCS_PARAMS_MAX_PKT_SIZE_DEFAULT = "64500"; +static ssize_t const GCS_PARAMS_RECV_Q_HARD_LIMIT_DEFAULT = SSIZE_MAX; +static const char* const GCS_PARAMS_RECV_Q_SOFT_LIMIT_DEFAULT = "0.25"; +static const char* const GCS_PARAMS_MAX_THROTTLE_DEFAULT = "0.25"; + +void +gcs_params_register(gu_config_t* conf) +{ + gu_config_add (conf, GCS_PARAMS_FC_FACTOR, GCS_PARAMS_FC_FACTOR_DEFAULT); + gu_config_add (conf, GCS_PARAMS_FC_LIMIT, GCS_PARAMS_FC_LIMIT_DEFAULT); + gu_config_add (conf, GCS_PARAMS_FC_MASTER_SLAVE, + GCS_PARAMS_FC_MASTER_SLAVE_DEFAULT); + gu_config_add (conf, GCS_PARAMS_FC_DEBUG, GCS_PARAMS_FC_DEBUG_DEFAULT); + gu_config_add (conf, GCS_PARAMS_SYNC_DONOR, GCS_PARAMS_SYNC_DONOR_DEFAULT); + gu_config_add (conf, GCS_PARAMS_MAX_PKT_SIZE, + GCS_PARAMS_MAX_PKT_SIZE_DEFAULT); + + char tmp[32] = { 0, }; + snprintf (tmp, sizeof(tmp) - 1, "%zd",GCS_PARAMS_RECV_Q_HARD_LIMIT_DEFAULT); + gu_config_add (conf, GCS_PARAMS_RECV_Q_HARD_LIMIT,tmp); + + gu_config_add (conf, GCS_PARAMS_RECV_Q_SOFT_LIMIT, + GCS_PARAMS_RECV_Q_SOFT_LIMIT_DEFAULT); + gu_config_add (conf, GCS_PARAMS_MAX_THROTTLE, + GCS_PARAMS_MAX_THROTTLE_DEFAULT); +} + +static long +params_init_bool (gu_config_t* conf, const char* const name, bool* const var) +{ + bool val; + + long rc = gu_config_get_bool(conf, name, &val); + + if (rc < 0) { + /* Cannot parse parameter value */ + gu_error ("Bad %s value", name); + return rc; + } + else if (rc > 0) { + assert(0); + val = false; + rc = -EINVAL; + } + + *var = val; + + return rc; +} + +static long +params_init_long (gu_config_t* conf, const char* const name, + long min_val, long max_val, long* const var) +{ + int64_t val; + + long rc = gu_config_get_int64(conf, name, &val); + + if (rc < 0) { + /* Cannot parse parameter value */ + gu_error ("Bad %s value", name); + return rc; + } + else { + /* Found parameter value */ + if (max_val == min_val) { + max_val = LONG_MAX; + min_val = LONG_MIN; + } + + if (val < min_val || val > max_val) { + gu_error ("%s value out of range [%ld, %ld]: %"PRIi64, + name, min_val, max_val, val); + return -EINVAL; + } + } + + *var = val; + + return 0; +} + +static long +params_init_int64 (gu_config_t* conf, const char* const name, + int64_t const min_val, int64_t const max_val, + int64_t* const var) +{ + int64_t val; + + long rc = gu_config_get_int64(conf, name, &val); + + if (rc < 0) { + /* Cannot parse parameter value */ + gu_error ("Bad %s value", name); + return rc; + } + else { + /* Found parameter value */ + if ((min_val != max_val) && (val < min_val || val > max_val)) { + gu_error ("%s value out of range [%"PRIi64", %"PRIi64"]: %"PRIi64, + name, min_val, max_val, val); + return -EINVAL; + } + } + + *var = val; + + return 0; +} + +static long +params_init_double (gu_config_t* conf, const char* const name, + double const min_val, double const max_val, + double* const var) +{ + double val; + + long rc = gu_config_get_double(conf, name, &val); + + if (rc < 0) { + /* Cannot parse parameter value */ + gu_error ("Bad %s value", name); + return rc; + } + else { + /* Found parameter value */ + if ((min_val != max_val) && (val < min_val || val > max_val)) { + gu_error ("%s value out of range [%f, %f]: %f", + name, min_val, max_val, val); + return -EINVAL; + } + } + + *var = val; + + return 0; +} + +long +gcs_params_init (struct gcs_params* params, gu_config_t* config) +{ + long ret; + + if ((ret = params_init_long (config, GCS_PARAMS_FC_LIMIT, 0, LONG_MAX, + ¶ms->fc_base_limit))) return ret; + + if ((ret = params_init_long (config, GCS_PARAMS_FC_DEBUG, 0, LONG_MAX, + ¶ms->fc_debug))) return ret; + + if ((ret = params_init_long (config, GCS_PARAMS_MAX_PKT_SIZE, 0,LONG_MAX, + ¶ms->max_packet_size))) return ret; + + if ((ret = params_init_double (config, GCS_PARAMS_FC_FACTOR, 0.0, 1.0, + ¶ms->fc_resume_factor))) return ret; + + if ((ret = params_init_double (config, GCS_PARAMS_RECV_Q_SOFT_LIMIT, + 0.0, 1.0 - 1.e-9, + ¶ms->recv_q_soft_limit))) return ret; + + if ((ret = params_init_double (config, GCS_PARAMS_MAX_THROTTLE, + 0.0, 1.0 - 1.e-9, + ¶ms->max_throttle))) return ret; + + int64_t tmp; + if ((ret = params_init_int64 (config, GCS_PARAMS_RECV_Q_HARD_LIMIT, 0, 0, + &tmp))) return ret; + params->recv_q_hard_limit = tmp * 0.9; // allow for some meta overhead + + if ((ret = params_init_bool (config, GCS_PARAMS_FC_MASTER_SLAVE, + ¶ms->fc_master_slave))) return ret; + + if ((ret = params_init_bool (config, GCS_PARAMS_SYNC_DONOR, + ¶ms->sync_donor))) return ret; + return 0; +} diff --git a/pool/shard002/C/0063064_pdf-cmap-load.c b/pool/shard002/C/0063064_pdf-cmap-load.c new file mode 100644 index 0000000000000000000000000000000000000000..5fcae15d0041e790eb3bcd9b8fc8f2d192f05957 --- /dev/null +++ b/pool/shard002/C/0063064_pdf-cmap-load.c @@ -0,0 +1,141 @@ +#include "mupdf/pdf.h" + +unsigned int +pdf_cmap_size(fz_context *ctx, pdf_cmap *cmap) +{ + if (cmap == NULL) + return 0; + if (cmap->storable.refs < 0) + return 0; + + return cmap->rcap * sizeof(pdf_range) + cmap->tcap * sizeof(short) + pdf_cmap_size(ctx, cmap->usecmap); +} + +/* + * Load CMap stream in PDF file + */ +pdf_cmap * +pdf_load_embedded_cmap(pdf_document *xref, pdf_obj *stmobj) +{ + fz_stream *file = NULL; + pdf_cmap *cmap = NULL; + pdf_cmap *usecmap; + pdf_obj *wmode; + pdf_obj *obj = NULL; + fz_context *ctx = xref->ctx; + int phase = 0; + + fz_var(phase); + fz_var(obj); + fz_var(file); + fz_var(cmap); + + if (pdf_obj_marked(stmobj)) + fz_throw(ctx, FZ_ERROR_GENERIC, "Recursion in embedded cmap"); + + if ((cmap = pdf_find_item(ctx, pdf_free_cmap_imp, stmobj))) + { + return cmap; + } + + fz_try(ctx) + { + file = pdf_open_stream(xref, pdf_to_num(stmobj), pdf_to_gen(stmobj)); + phase = 1; + cmap = pdf_load_cmap(ctx, file); + phase = 2; + fz_close(file); + file = NULL; + + wmode = pdf_dict_gets(stmobj, "WMode"); + if (pdf_is_int(wmode)) + pdf_set_cmap_wmode(ctx, cmap, pdf_to_int(wmode)); + obj = pdf_dict_gets(stmobj, "UseCMap"); + if (pdf_is_name(obj)) + { + usecmap = pdf_load_system_cmap(ctx, pdf_to_name(obj)); + pdf_set_usecmap(ctx, cmap, usecmap); + pdf_drop_cmap(ctx, usecmap); + } + else if (pdf_is_indirect(obj)) + { + phase = 3; + pdf_obj_mark(obj); + usecmap = pdf_load_embedded_cmap(xref, obj); + pdf_obj_unmark(obj); + phase = 4; + pdf_set_usecmap(ctx, cmap, usecmap); + pdf_drop_cmap(ctx, usecmap); + } + + pdf_store_item(ctx, stmobj, cmap, pdf_cmap_size(ctx, cmap)); + } + fz_catch(ctx) + { + if (file) + fz_close(file); + if (cmap) + pdf_drop_cmap(ctx, cmap); + if (phase < 1) + fz_rethrow_message(ctx, "cannot open cmap stream (%d %d R)", pdf_to_num(stmobj), pdf_to_gen(stmobj)); + else if (phase < 2) + fz_rethrow_message(ctx, "cannot parse cmap stream (%d %d R)", pdf_to_num(stmobj), pdf_to_gen(stmobj)); + else if (phase < 3) + fz_rethrow_message(ctx, "cannot load system usecmap '%s'", pdf_to_name(obj)); + else + { + if (phase == 3) + pdf_obj_unmark(obj); + fz_rethrow_message(ctx, "cannot load embedded usecmap (%d %d R)", pdf_to_num(obj), pdf_to_gen(obj)); + } + } + + return cmap; +} + +/* + * Create an Identity-* CMap (for both 1 and 2-byte encodings) + */ +pdf_cmap * +pdf_new_identity_cmap(fz_context *ctx, int wmode, int bytes) +{ + pdf_cmap *cmap = pdf_new_cmap(ctx); + fz_try(ctx) + { + sprintf(cmap->cmap_name, "Identity-%c", wmode ? 'V' : 'H'); + pdf_add_codespace(ctx, cmap, 0x0000, 0xffff, bytes); + pdf_map_range_to_range(ctx, cmap, 0x0000, 0xffff, 0); + pdf_sort_cmap(ctx, cmap); + pdf_set_cmap_wmode(ctx, cmap, wmode); + } + fz_catch(ctx) + { + pdf_drop_cmap(ctx, cmap); + fz_rethrow(ctx); + } + return cmap; +} + +/* + * Load predefined CMap from system. + */ +pdf_cmap * +pdf_load_system_cmap(fz_context *ctx, char *cmap_name) +{ + pdf_cmap *usecmap; + pdf_cmap *cmap; + + cmap = pdf_load_builtin_cmap(ctx, cmap_name); + if (!cmap) + fz_throw(ctx, FZ_ERROR_GENERIC, "no builtin cmap file: %s", cmap_name); + + if (cmap->usecmap_name[0] && !cmap->usecmap) + { + usecmap = pdf_load_builtin_cmap(ctx, cmap->usecmap_name); + if (!usecmap) + fz_throw(ctx, FZ_ERROR_GENERIC, "nu builtin cmap file: %s", cmap->usecmap_name); + pdf_set_usecmap(ctx, cmap, usecmap); + } + + return cmap; +} diff --git a/pool/shard002/C/0063067_s3c2410.c b/pool/shard002/C/0063067_s3c2410.c new file mode 100644 index 0000000000000000000000000000000000000000..feb141b1f915bf131622b6388ce69901e9636797 --- /dev/null +++ b/pool/shard002/C/0063067_s3c2410.c @@ -0,0 +1,141 @@ +/* linux/arch/arm/mach-s3c2410/s3c2410.c + * + * Copyright (c) 2003-2005 Simtec Electronics + * Ben Dooks + * + * http://www.simtec.co.uk/products/EB2410ITX/ + * + * 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 +#include +#include +#include +#include + +/* Initial IO mappings */ + +static struct map_desc s3c2410_iodesc[] __initdata = { + IODESC_ENT(CLKPWR), + IODESC_ENT(TIMER), + IODESC_ENT(WATCHDOG), +}; + +/* our uart devices */ + +/* uart registration process */ + +void __init s3c2410_init_uarts(struct s3c2410_uartcfg *cfg, int no) +{ + s3c24xx_init_uartdevs("s3c2410-uart", s3c2410_uart_resources, cfg, no); +} + +/* s3c2410_map_io + * + * register the standard cpu IO areas, and any passed in from the + * machine specific initialisation. +*/ + +void __init s3c2410_map_io(void) +{ + iotable_init(s3c2410_iodesc, ARRAY_SIZE(s3c2410_iodesc)); +} + +void __init_or_cpufreq s3c2410_setup_clocks(void) +{ + struct clk *xtal_clk; + unsigned long tmp; + unsigned long xtal; + unsigned long fclk; + unsigned long hclk; + unsigned long pclk; + + xtal_clk = clk_get(NULL, "xtal"); + xtal = clk_get_rate(xtal_clk); + clk_put(xtal_clk); + + /* now we've got our machine bits initialised, work out what + * clocks we've got */ + + fclk = s3c24xx_get_pll(__raw_readl(S3C2410_MPLLCON), xtal); + + tmp = __raw_readl(S3C2410_CLKDIVN); + + /* work out clock scalings */ + + hclk = fclk / ((tmp & S3C2410_CLKDIVN_HDIVN) ? 2 : 1); + pclk = hclk / ((tmp & S3C2410_CLKDIVN_PDIVN) ? 2 : 1); + + /* print brieft summary of clocks, etc */ + + printk("S3C2410: core %ld.%03ld MHz, memory %ld.%03ld MHz, peripheral %ld.%03ld MHz\n", + print_mhz(fclk), print_mhz(hclk), print_mhz(pclk)); + + /* initialise the clocks here, to allow other things like the + * console to use them + */ + + s3c24xx_setup_clocks(fclk, hclk, pclk); +} + +void __init s3c2410_init_clocks(int xtal) +{ + s3c24xx_register_baseclocks(xtal); + s3c2410_setup_clocks(); + s3c2410_baseclk_add(); +} + +struct sysdev_class s3c2410_sysclass = { + .name = "s3c2410-core", +}; + +static struct sys_device s3c2410_sysdev = { + .cls = &s3c2410_sysclass, +}; + +/* need to register class before we actually register the device, and + * we also need to ensure that it has been initialised before any of the + * drivers even try to use it (even if not on an s3c2410 based system) + * as a driver which may support both 2410 and 2440 may try and use it. +*/ + +static int __init s3c2410_core_init(void) +{ + return sysdev_class_register(&s3c2410_sysclass); +} + +core_initcall(s3c2410_core_init); + +int __init s3c2410_init(void) +{ + printk("S3C2410: Initialising architecture\n"); + + return sysdev_register(&s3c2410_sysdev); +} diff --git a/pool/shard002/C/0063083_lab4_all_workqueue.c b/pool/shard002/C/0063083_lab4_all_workqueue.c new file mode 100644 index 0000000000000000000000000000000000000000..5d215da5d94f0bcd938e6ee7b4ebd3a10ce8b7a8 --- /dev/null +++ b/pool/shard002/C/0063083_lab4_all_workqueue.c @@ -0,0 +1,64 @@ +/* **************** LF331:1.6 s_18/lab4_all_workqueue.c **************** */ +/* + * The code herein is: Copyright the Linux Foundation, 2011 + * + * This Copyright is retained for the purpose of protecting free + * redistribution of source. + * + * URL: http://training.linuxfoundation.org + * email: trainingquestions@linuxfoundation.org + * + * The primary maintainer for this code is Jerry Cooperstein + * The CONTRIBUTORS file (distributed with this + * file) lists those known to have contributed to the source. + * + * This code is distributed under Version 2 of the GNU General Public + * License, which you should have received with the source. + * + */ +/* + * Sharing All Interrupts, Bottom Halves (workqueue solution) + * + * Extend the solution to share all possible interrupts, and evaluate + * the consumer/producer problem. + * + @*/ + +#include +#include "lab_all_interrupt.h" + +static struct my_dat { + int irq; + struct work_struct work; +} my_data; + +static void w_fun(struct work_struct *w_arg) +{ + struct my_dat *data = container_of(w_arg, struct my_dat, work); + atomic_inc(&bhs[data->irq]); +} + +static irqreturn_t my_interrupt(int irq, void *dev_id) +{ + struct my_dat *data = (struct my_dat *)&my_data; + data->irq = irq; + atomic_inc(&interrupts[irq]); + schedule_work(&data->work); + mdelay(delay); + /* we return IRQ_NONE because we are just observing */ + return IRQ_NONE; +} + +static int my_init(void) +{ + struct my_dat *data = (struct my_dat *)&my_data; + INIT_WORK(&data->work, w_fun); + return my_generic_init(); +} + +module_init(my_init); +module_exit(my_generic_exit); + +MODULE_AUTHOR("Jerry Cooperstein"); +MODULE_DESCRIPTION("LF331:1.6 s_18/lab4_all_workqueue.c"); +MODULE_LICENSE("GPL v2"); diff --git a/pool/shard002/C/0063094_dsim_panel.c b/pool/shard002/C/0063094_dsim_panel.c new file mode 100644 index 0000000000000000000000000000000000000000..583c5fb86772800c419ce93cf68e48107397d8fe --- /dev/null +++ b/pool/shard002/C/0063094_dsim_panel.c @@ -0,0 +1,287 @@ + +/* linux/drivers/video/exynos_decon/panel/dsim_panel.c + * + * Header file for Samsung MIPI-DSI LCD Panel driver. + * + * Copyright (c) 2013 Samsung Electronics + * Minwoo Kim + * + * 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 "../dsim.h" + +#include "dsim_panel.h" +#include "dsim_backlight.h" +#include "panel_info.h" + +#if defined(CONFIG_EXYNOS_DECON_MDNIE_LITE) +#include "mdnie.h" +#if defined(CONFIG_PANEL_S6E3HF2_DYNAMIC) +#include "mdnie_lite_table_zero.h" +#elif defined(CONFIG_PANEL_S6E3HA2_DYNAMIC) +#include "mdnie_lite_table_zerof.h" +#elif defined(CONFIG_PANEL_S6E3HA3_DYNAMIC) +#include "mdnie_lite_table_noble.h" +#elif defined(CONFIG_PANEL_S6E3HF3_DYNAMIC) +#include "mdnie_lite_table_zen.h" +#endif +#endif + +#if defined(CONFIG_EXYNOS_DECON_MDNIE_LITE) +static int mdnie_lite_write_set(struct dsim_device *dsim, struct lcd_seq_info *seq, u32 num) +{ + int ret = 0, i; + + for (i = 0; i < num; i++) { + if (seq[i].cmd) { + ret = dsim_write_hl_data(dsim, seq[i].cmd, seq[i].len); + if (ret != 0) { + dsim_err("%s failed.\n", __func__); + return ret; + } + } + if (seq[i].sleep) + usleep_range(seq[i].sleep * 1000 , seq[i].sleep * 1000); + } + return ret; +} + +int mdnie_lite_send_seq(struct dsim_device *dsim, struct lcd_seq_info *seq, u32 num) +{ + int ret = 0; + struct panel_private *panel = &dsim->priv; + + if (panel->state != PANEL_STATE_RESUMED) { + dsim_info("%s : panel is not active\n", __func__); + return -EIO; + } + + mutex_lock(&panel->lock); + ret = mdnie_lite_write_set(dsim, seq, num); + + mutex_unlock(&panel->lock); + + return ret; +} + +int mdnie_lite_read(struct dsim_device *dsim, u8 addr, u8 *buf, u32 size) +{ + int ret = 0; + struct panel_private *panel = &dsim->priv; + + if (panel->state != PANEL_STATE_RESUMED) { + dsim_info("%s : panel is not active\n", __func__); + return -EIO; + } + mutex_lock(&panel->lock); + ret = dsim_read_hl_data(dsim, addr, size, buf); + + mutex_unlock(&panel->lock); + + return ret; +} +#endif + +static int dsim_panel_early_probe(struct dsim_device *dsim) +{ + int ret = 0; + struct panel_private *panel = &dsim->priv; + + panel->ops = dsim_panel_get_priv_ops(dsim); + + if (panel->ops->early_probe) { + ret = panel->ops->early_probe(dsim); + } + return ret; +} + +static int dsim_panel_probe(struct dsim_device *dsim) +{ + int ret = 0; + struct panel_private *panel = &dsim->priv; +#if defined(CONFIG_EXYNOS_DECON_MDNIE_LITE) + u16 coordinate[2] = {0, }; +#endif + + dsim->lcd = lcd_device_register("panel", dsim->dev, &dsim->priv, NULL); + if (IS_ERR(dsim->lcd)) { + dsim_err("%s : faield to register lcd device\n", __func__); + ret = PTR_ERR(dsim->lcd); + goto probe_err; + } + + ret = dsim_backlight_probe(dsim); + if (ret) { + dsim_err("%s : failed to prbe backlight driver\n", __func__); + goto probe_err; + } + + + panel->lcdConnected = PANEL_CONNECTED; + panel->state = PANEL_STATE_RESUMED; + panel->temperature = NORMAL_TEMPERATURE; + panel->acl_enable = 0; + panel->current_acl = 0; + panel->auto_brightness = 0; + panel->siop_enable = 0; + panel->current_hbm = 0; + panel->current_vint = 0; + + panel->weakness_hbm_comp = 0; + dsim->glide_display_size = 0; + panel->auto_brightness_level = 6; + + +#ifdef AID_INTERPOLATION + panel->brightness_step = 256; +#else + panel->brightness_step = 65; // 360 +#endif + + mutex_init(&panel->lock); +#ifdef CONFIG_EXYNOS_DECON_LCD_MCD + panel->mcd_on = 0; +#endif + + if (panel->ops->probe) { + ret = panel->ops->probe(dsim); + if (ret) { + dsim_err("%s : failed to probe panel\n", __func__); + goto probe_err; + } + } +#if defined(CONFIG_EXYNOS_DECON_LCD_SYSFS) + lcd_init_sysfs(dsim); +#endif + +#if defined(CONFIG_EXYNOS_DECON_MDNIE_LITE) + coordinate[0] = (u16)panel->coordinate[0]; + coordinate[1] = (u16)panel->coordinate[1]; + if (panel->mdnie_support) + mdnie_register(&dsim->lcd->dev, dsim, (mdnie_w)mdnie_lite_send_seq, (mdnie_r)mdnie_lite_read, coordinate, &tune_info); +#endif + +probe_err: + return ret; +} + +static int dsim_panel_displayon(struct dsim_device *dsim) +{ + int ret = 0; + struct panel_private *panel = &dsim->priv; + +#ifdef CONFIG_LCD_ALPM + mutex_lock(&panel->alpm_lock); +#endif + + if (panel->state == PANEL_STATE_SUSPENED) { + if (panel->ops->init) { + ret = panel->ops->init(dsim); + if (ret) { + dsim_err("%s : failed to panel init\n", __func__); + goto displayon_err; + } + } + panel->state = PANEL_STATE_RESUMED; + } +#ifdef CONFIG_LCD_HMT + if(panel->hmt_on == HMT_ON) + hmt_set_mode(dsim, true); +#endif + dsim_panel_set_brightness(dsim, 1); + + if (panel->ops->displayon) { + ret = panel->ops->displayon(dsim); + if (ret) { + dsim_err("%s : failed to panel display on\n", __func__); + goto displayon_err; + } + } + +displayon_err: +#ifdef CONFIG_LCD_ALPM + mutex_unlock(&panel->alpm_lock); +#endif + return ret; +} + +static int dsim_panel_suspend(struct dsim_device *dsim) +{ + int ret = 0; + struct panel_private *panel = &dsim->priv; + + if (panel->state == PANEL_STATE_SUSPENED) + goto suspend_err; + + panel->state = PANEL_STATE_SUSPENDING; + + if (panel->ops->exit) { + ret = panel->ops->exit(dsim); + if (ret) { + dsim_err("%s : failed to panel exit \n", __func__); + goto suspend_err; + } + } + panel->state = PANEL_STATE_SUSPENED; + +suspend_err: + return ret; +} + +static int dsim_panel_resume(struct dsim_device *dsim) +{ + int ret = 0; + return ret; +} + + +static int dsim_panel_dump(struct dsim_device *dsim) +{ + int ret = 0; + struct panel_private *panel = &dsim->priv; + + dsim_info("%s was called\n", __func__); + + if (panel->ops->dump) + ret = panel->ops->dump(dsim); + + return ret; +} +static struct mipi_dsim_lcd_driver mipi_lcd_driver = { + .early_probe = dsim_panel_early_probe, + .probe = dsim_panel_probe, + .displayon = dsim_panel_displayon, + .suspend = dsim_panel_suspend, + .resume = dsim_panel_resume, + .dump = dsim_panel_dump, +}; + + +int dsim_panel_ops_init(struct dsim_device *dsim) +{ + int ret = 0; + + if (dsim) + dsim->panel_ops = &mipi_lcd_driver; + + return ret; +} + +unsigned int lcdtype = 0; +EXPORT_SYMBOL(lcdtype); + +static int __init get_lcd_type(char *arg) +{ + get_option(&arg, &lcdtype); + + dsim_info("--- Parse LCD TYPE ---\n"); + dsim_info("LCDTYPE : %x\n", lcdtype); + + return 0; +} +early_param("lcdtype", get_lcd_type); + diff --git a/pool/shard002/C/0063104_main.c b/pool/shard002/C/0063104_main.c new file mode 100644 index 0000000000000000000000000000000000000000..b9b4b61e264ada10b6a91c2cd18bf4d5176b8f53 --- /dev/null +++ b/pool/shard002/C/0063104_main.c @@ -0,0 +1,113 @@ +#include +#include + +#include "adlist.h" + +adlist_t read_details_for_add_listing(void) +{ + adlist_t adlist; + + printf(" %s\n\n", "Hint: Use acronym for subject name " + "and don't include spaces in Book Name."); + printf(" %s\n", "Enter Details:"); + + printf(" %s ", "Your Name:"); + scanf("%s %s", adlist.fname, adlist.lname); + + printf(" %s ", "Mobile No:"); + scanf("%ld", &(adlist.mobile)); + + printf(" %s ", "Subject:"); + scanf("%s", adlist.subject); + + printf(" %s ", "Book Name:"); + scanf("%s", adlist.bname); + + printf(" %s ", "Price:"); + scanf("%d", &(adlist.price)); + + return adlist; +} + +adlist_t read_details_for_search_listings(void) +{ + adlist_t adlist; + + printf(" %s\n\n", "Hint: Use acronym for subject and " + "entering 0 removes respective criteria from search."); + printf(" %s\n", "Enter Details:"); + + printf(" %s ", "Subject:"); + scanf("%s", adlist.subject); + + printf(" %s ", "Book Name:"); + scanf("%s", adlist.bname); + + printf(" %s ", "Maximum Price:"); + scanf("%d", &(adlist.price)); + + return adlist; +} + +const char menu[] = + " +----------------------+\n" + " | PREVIOUS YEAR BOOKS |\n" + " | MENU |\n" + " +----------------------+\n" + " | 1: Sell Books |\n" + " | 2: Search for Books |\n" + " | 9: Exit |\n" + " +----------------------+"; + +int main(int argc, char **argv) +{ + FILE *database = fopen("adlist.txt", "a+"); + + int choice = 0; + + /* main loop */ + while (1) { + printf("%s\n", menu); + + /* Read number of choice */ + printf(" Enter Choice: "); + scanf("%d", &choice); + + printf("\n"); + + adlist_t adlist; + + switch (choice) { + /* Add new listing */ + case 1: + adlist = read_details_for_add_listing(); + add_listing(database, &adlist); + rewind(database); + + break; + + /* Search listing */ + case 2: + adlist = read_details_for_search_listings(); + search_listings(database, &adlist); + rewind(database); + + break; + + /* Exit programm */ + case 9: + printf(" Exiting....\n"); + fclose(database); + + return EXIT_SUCCESS; + + /* Unknown option */ + default: + continue; + } + + printf("\n"); + } + + return EXIT_SUCCESS; +} diff --git a/pool/shard002/C/0063114_br.c b/pool/shard002/C/0063114_br.c new file mode 100644 index 0000000000000000000000000000000000000000..54e310c2ba8dbc3cb86c3cbaa6978815c64f5915 --- /dev/null +++ b/pool/shard002/C/0063114_br.c @@ -0,0 +1,113 @@ +/* + * Generic parts + * Linux ethernet bridge + * + * Authors: + * Lennert Buytenhek + * + * 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 "br_private.h" + +static const struct stp_proto br_stp_proto = { + .rcv = br_stp_rcv, +}; + +static struct pernet_operations br_net_ops = { + .exit = br_net_exit, +}; + +static int __init br_init(void) +{ + int err; + + err = stp_proto_register(&br_stp_proto); + if (err < 0) { + pr_err("bridge: can't register sap for STP\n"); + return err; + } + + err = br_fdb_init(); + if (err) + goto err_out; + + err = register_pernet_subsys(&br_net_ops); + if (err) + goto err_out1; + + err = br_netfilter_init(); + if (err) + goto err_out2; + + err = register_netdevice_notifier(&br_device_notifier); + if (err) + goto err_out3; + + err = br_netlink_init(); + if (err) + goto err_out4; + + brioctl_set(br_ioctl_deviceless_stub); + +#if defined(CONFIG_NETFILTER_XT_MATCH_PHYSDEV) || defined(CONFIG_NETFILTER_XT_MATCH_PHYSDEV_MODULE) + br_fdb_get_port_hook = br_fdb_get_port; +#endif +#if IS_ENABLED(CONFIG_ATM_LANE) + br_fdb_test_addr_hook = br_fdb_test_addr; +#endif + + return 0; +err_out4: + unregister_netdevice_notifier(&br_device_notifier); +err_out3: + br_netfilter_fini(); +err_out2: + unregister_pernet_subsys(&br_net_ops); +err_out1: + br_fdb_fini(); +err_out: + stp_proto_unregister(&br_stp_proto); + return err; +} + +static void __exit br_deinit(void) +{ + stp_proto_unregister(&br_stp_proto); + + br_netlink_fini(); + unregister_netdevice_notifier(&br_device_notifier); + brioctl_set(NULL); + + unregister_pernet_subsys(&br_net_ops); + + rcu_barrier(); /* Wait for completion of call_rcu()'s */ + + br_netfilter_fini(); +#if defined(CONFIG_NETFILTER_XT_MATCH_PHYSDEV) || defined(CONFIG_NETFILTER_XT_MATCH_PHYSDEV_MODULE) + br_fdb_get_port_hook = NULL; +#endif +#if IS_ENABLED(CONFIG_ATM_LANE) + br_fdb_test_addr_hook = NULL; +#endif + + br_fdb_fini(); +} + +module_init(br_init) +module_exit(br_deinit) +MODULE_LICENSE("GPL"); +MODULE_VERSION(BR_VERSION); +MODULE_ALIAS_RTNL_LINK("bridge"); diff --git a/pool/shard002/C/0063124_threads.c b/pool/shard002/C/0063124_threads.c new file mode 100644 index 0000000000000000000000000000000000000000..e36e333a0aa0d7430c852ce419ac7ed85094bbec --- /dev/null +++ b/pool/shard002/C/0063124_threads.c @@ -0,0 +1,250 @@ +/* + * Copyright (c) 2006 Oracle. All rights reserved. + * + * This software is available to you under a choice of one of two + * licenses. You may choose to be licensed under the terms of the GNU + * General Public License (GPL) Version 2, available from the file + * COPYING in the main directory of this source tree, or the + * OpenIB.org BSD license below: + * + * 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. + * + * 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 "rds.h" + +/* + * All of connection management is simplified by serializing it through + * work queues that execute in a connection managing thread. + * + * TCP wants to send acks through sendpage() in response to data_ready(), + * but it needs a process context to do so. + * + * The receive paths need to allocate but can't drop packets (!) so we have + * a thread around to block allocating if the receive fast path sees an + * allocation failure. + */ + +/* Grand Unified Theory of connection life cycle: + * At any point in time, the connection can be in one of these states: + * DOWN, CONNECTING, UP, DISCONNECTING, ERROR + * + * The following transitions are possible: + * ANY -> ERROR + * UP -> DISCONNECTING + * ERROR -> DISCONNECTING + * DISCONNECTING -> DOWN + * DOWN -> CONNECTING + * CONNECTING -> UP + * + * Transition to state DISCONNECTING/DOWN: + * - Inside the shutdown worker; synchronizes with xmit path + * through RDS_IN_XMIT, and with connection management callbacks + * via c_cm_lock. + * + * For receive callbacks, we rely on the underlying transport + * (TCP, IB/RDMA) to provide the necessary synchronisation. + */ +struct workqueue_struct *rds_wq; +EXPORT_SYMBOL_GPL(rds_wq); + +void rds_connect_path_complete(struct rds_conn_path *cp, int curr) +{ + if (!rds_conn_path_transition(cp, curr, RDS_CONN_UP)) { + printk(KERN_WARNING "%s: Cannot transition to state UP, " + "current state is %d\n", + __func__, + atomic_read(&cp->cp_state)); + rds_conn_path_drop(cp); + return; + } + + rdsdebug("conn %p for %pI4 to %pI4 complete\n", + cp->cp_conn, &cp->cp_conn->c_laddr, &cp->cp_conn->c_faddr); + + cp->cp_reconnect_jiffies = 0; + set_bit(0, &cp->cp_conn->c_map_queued); + queue_delayed_work(rds_wq, &cp->cp_send_w, 0); + queue_delayed_work(rds_wq, &cp->cp_recv_w, 0); +} +EXPORT_SYMBOL_GPL(rds_connect_path_complete); + +void rds_connect_complete(struct rds_connection *conn) +{ + rds_connect_path_complete(&conn->c_path[0], RDS_CONN_CONNECTING); +} +EXPORT_SYMBOL_GPL(rds_connect_complete); + +/* + * This random exponential backoff is relied on to eventually resolve racing + * connects. + * + * If connect attempts race then both parties drop both connections and come + * here to wait for a random amount of time before trying again. Eventually + * the backoff range will be so much greater than the time it takes to + * establish a connection that one of the pair will establish the connection + * before the other's random delay fires. + * + * Connection attempts that arrive while a connection is already established + * are also considered to be racing connects. This lets a connection from + * a rebooted machine replace an existing stale connection before the transport + * notices that the connection has failed. + * + * We should *always* start with a random backoff; otherwise a broken connection + * will always take several iterations to be re-established. + */ +void rds_queue_reconnect(struct rds_conn_path *cp) +{ + unsigned long rand; + struct rds_connection *conn = cp->cp_conn; + + rdsdebug("conn %p for %pI4 to %pI4 reconnect jiffies %lu\n", + conn, &conn->c_laddr, &conn->c_faddr, + cp->cp_reconnect_jiffies); + + /* let peer with smaller addr initiate reconnect, to avoid duels */ + if (conn->c_trans->t_type == RDS_TRANS_TCP && + conn->c_laddr > conn->c_faddr) + return; + + set_bit(RDS_RECONNECT_PENDING, &cp->cp_flags); + if (cp->cp_reconnect_jiffies == 0) { + cp->cp_reconnect_jiffies = rds_sysctl_reconnect_min_jiffies; + queue_delayed_work(rds_wq, &cp->cp_conn_w, 0); + return; + } + + get_random_bytes(&rand, sizeof(rand)); + rdsdebug("%lu delay %lu ceil conn %p for %pI4 -> %pI4\n", + rand % cp->cp_reconnect_jiffies, cp->cp_reconnect_jiffies, + conn, &conn->c_laddr, &conn->c_faddr); + queue_delayed_work(rds_wq, &cp->cp_conn_w, + rand % cp->cp_reconnect_jiffies); + + cp->cp_reconnect_jiffies = min(cp->cp_reconnect_jiffies * 2, + rds_sysctl_reconnect_max_jiffies); +} + +void rds_connect_worker(struct work_struct *work) +{ + struct rds_conn_path *cp = container_of(work, + struct rds_conn_path, + cp_conn_w.work); + struct rds_connection *conn = cp->cp_conn; + int ret; + + if (cp->cp_index > 1 && cp->cp_conn->c_laddr > cp->cp_conn->c_faddr) + return; + clear_bit(RDS_RECONNECT_PENDING, &cp->cp_flags); + ret = rds_conn_path_transition(cp, RDS_CONN_DOWN, RDS_CONN_CONNECTING); + if (ret) { + ret = conn->c_trans->conn_path_connect(cp); + rdsdebug("conn %p for %pI4 to %pI4 dispatched, ret %d\n", + conn, &conn->c_laddr, &conn->c_faddr, ret); + + if (ret) { + if (rds_conn_path_transition(cp, + RDS_CONN_CONNECTING, + RDS_CONN_DOWN)) + rds_queue_reconnect(cp); + else + rds_conn_path_error(cp, "connect failed\n"); + } + } +} + +void rds_send_worker(struct work_struct *work) +{ + struct rds_conn_path *cp = container_of(work, + struct rds_conn_path, + cp_send_w.work); + int ret; + + if (rds_conn_path_state(cp) == RDS_CONN_UP) { + clear_bit(RDS_LL_SEND_FULL, &cp->cp_flags); + ret = rds_send_xmit(cp); + cond_resched(); + rdsdebug("conn %p ret %d\n", cp->cp_conn, ret); + switch (ret) { + case -EAGAIN: + rds_stats_inc(s_send_immediate_retry); + queue_delayed_work(rds_wq, &cp->cp_send_w, 0); + break; + case -ENOMEM: + rds_stats_inc(s_send_delayed_retry); + queue_delayed_work(rds_wq, &cp->cp_send_w, 2); + default: + break; + } + } +} + +void rds_recv_worker(struct work_struct *work) +{ + struct rds_conn_path *cp = container_of(work, + struct rds_conn_path, + cp_recv_w.work); + int ret; + + if (rds_conn_path_state(cp) == RDS_CONN_UP) { + ret = cp->cp_conn->c_trans->recv_path(cp); + rdsdebug("conn %p ret %d\n", cp->cp_conn, ret); + switch (ret) { + case -EAGAIN: + rds_stats_inc(s_recv_immediate_retry); + queue_delayed_work(rds_wq, &cp->cp_recv_w, 0); + break; + case -ENOMEM: + rds_stats_inc(s_recv_delayed_retry); + queue_delayed_work(rds_wq, &cp->cp_recv_w, 2); + default: + break; + } + } +} + +void rds_shutdown_worker(struct work_struct *work) +{ + struct rds_conn_path *cp = container_of(work, + struct rds_conn_path, + cp_down_w); + + rds_conn_shutdown(cp); +} + +void rds_threads_exit(void) +{ + destroy_workqueue(rds_wq); +} + +int rds_threads_init(void) +{ + rds_wq = create_singlethread_workqueue("krdsd"); + if (!rds_wq) + return -ENOMEM; + + return 0; +} diff --git a/pool/shard002/C/0063130_N-312ext.c b/pool/shard002/C/0063130_N-312ext.c new file mode 100644 index 0000000000000000000000000000000000000000..cfe79d695d0dd33e01fd59a79113fd5a2c509353 --- /dev/null +++ b/pool/shard002/C/0063130_N-312ext.c @@ -0,0 +1,150 @@ +/* + * Generated by asn1c-0.9.24 (http://lionet.info/asn1c) + * From ASN.1 module "InformationElements" + * found in "../asn/InformationElements.asn" + * `asn1c -fcompound-names -fnative-types` + */ + +#include "N-312ext.h" + +int +N_312ext_constraint(asn_TYPE_descriptor_t *td, const void *sptr, + asn_app_constraint_failed_f *ctfailcb, void *app_key) { + /* Replace with underlying type checker */ + td->check_constraints = asn_DEF_NativeEnumerated.check_constraints; + return td->check_constraints(td, sptr, ctfailcb, app_key); +} + +/* + * This type is implemented using NativeEnumerated, + * so here we adjust the DEF accordingly. + */ +static void +N_312ext_1_inherit_TYPE_descriptor(asn_TYPE_descriptor_t *td) { + td->free_struct = asn_DEF_NativeEnumerated.free_struct; + td->print_struct = asn_DEF_NativeEnumerated.print_struct; + td->ber_decoder = asn_DEF_NativeEnumerated.ber_decoder; + td->der_encoder = asn_DEF_NativeEnumerated.der_encoder; + td->xer_decoder = asn_DEF_NativeEnumerated.xer_decoder; + td->xer_encoder = asn_DEF_NativeEnumerated.xer_encoder; + td->uper_decoder = asn_DEF_NativeEnumerated.uper_decoder; + td->uper_encoder = asn_DEF_NativeEnumerated.uper_encoder; + if(!td->per_constraints) + td->per_constraints = asn_DEF_NativeEnumerated.per_constraints; + td->elements = asn_DEF_NativeEnumerated.elements; + td->elements_count = asn_DEF_NativeEnumerated.elements_count; + /* td->specifics = asn_DEF_NativeEnumerated.specifics; // Defined explicitly */ +} + +void +N_312ext_free(asn_TYPE_descriptor_t *td, + void *struct_ptr, int contents_only) { + N_312ext_1_inherit_TYPE_descriptor(td); + td->free_struct(td, struct_ptr, contents_only); +} + +int +N_312ext_print(asn_TYPE_descriptor_t *td, const void *struct_ptr, + int ilevel, asn_app_consume_bytes_f *cb, void *app_key) { + N_312ext_1_inherit_TYPE_descriptor(td); + return td->print_struct(td, struct_ptr, ilevel, cb, app_key); +} + +asn_dec_rval_t +N_312ext_decode_ber(asn_codec_ctx_t *opt_codec_ctx, asn_TYPE_descriptor_t *td, + void **structure, const void *bufptr, size_t size, int tag_mode) { + N_312ext_1_inherit_TYPE_descriptor(td); + return td->ber_decoder(opt_codec_ctx, td, structure, bufptr, size, tag_mode); +} + +asn_enc_rval_t +N_312ext_encode_der(asn_TYPE_descriptor_t *td, + void *structure, int tag_mode, ber_tlv_tag_t tag, + asn_app_consume_bytes_f *cb, void *app_key) { + N_312ext_1_inherit_TYPE_descriptor(td); + return td->der_encoder(td, structure, tag_mode, tag, cb, app_key); +} + +asn_dec_rval_t +N_312ext_decode_xer(asn_codec_ctx_t *opt_codec_ctx, asn_TYPE_descriptor_t *td, + void **structure, const char *opt_mname, const void *bufptr, size_t size) { + N_312ext_1_inherit_TYPE_descriptor(td); + return td->xer_decoder(opt_codec_ctx, td, structure, opt_mname, bufptr, size); +} + +asn_enc_rval_t +N_312ext_encode_xer(asn_TYPE_descriptor_t *td, void *structure, + int ilevel, enum xer_encoder_flags_e flags, + asn_app_consume_bytes_f *cb, void *app_key) { + N_312ext_1_inherit_TYPE_descriptor(td); + return td->xer_encoder(td, structure, ilevel, flags, cb, app_key); +} + +asn_dec_rval_t +N_312ext_decode_uper(asn_codec_ctx_t *opt_codec_ctx, asn_TYPE_descriptor_t *td, + asn_per_constraints_t *constraints, void **structure, asn_per_data_t *per_data) { + N_312ext_1_inherit_TYPE_descriptor(td); + return td->uper_decoder(opt_codec_ctx, td, constraints, structure, per_data); +} + +asn_enc_rval_t +N_312ext_encode_uper(asn_TYPE_descriptor_t *td, + asn_per_constraints_t *constraints, + void *structure, asn_per_outp_t *per_out) { + N_312ext_1_inherit_TYPE_descriptor(td); + return td->uper_encoder(td, constraints, structure, per_out); +} + +static asn_per_constraints_t asn_PER_type_N_312ext_constr_1 = { + { APC_CONSTRAINED, 2, 2, 0, 3 } /* (0..3) */, + { APC_UNCONSTRAINED, -1, -1, 0, 0 }, + 0, 0 /* No PER value map */ +}; +static asn_INTEGER_enum_map_t asn_MAP_N_312ext_value2enum_1[] = { + { 0, 2, "s2" }, + { 1, 2, "s4" }, + { 2, 3, "s10" }, + { 3, 3, "s20" } +}; +static unsigned int asn_MAP_N_312ext_enum2value_1[] = { + 2, /* s10(2) */ + 0, /* s2(0) */ + 3, /* s20(3) */ + 1 /* s4(1) */ +}; +static asn_INTEGER_specifics_t asn_SPC_N_312ext_specs_1 = { + asn_MAP_N_312ext_value2enum_1, /* "tag" => N; sorted by tag */ + asn_MAP_N_312ext_enum2value_1, /* N => "tag"; sorted by N */ + 4, /* Number of elements in the maps */ + 0, /* Enumeration is not extensible */ + 1, /* Strict enumeration */ + 0, /* Native long size */ + 0 +}; +static ber_tlv_tag_t asn_DEF_N_312ext_tags_1[] = { + (ASN_TAG_CLASS_UNIVERSAL | (10 << 2)) +}; +asn_TYPE_descriptor_t asn_DEF_N_312ext = { + "N-312ext", + "N-312ext", + N_312ext_free, + N_312ext_print, + N_312ext_constraint, + N_312ext_decode_ber, + N_312ext_encode_der, + N_312ext_decode_xer, + N_312ext_encode_xer, + N_312ext_decode_uper, + N_312ext_encode_uper, + 0, /* Use generic outmost tag fetcher */ + asn_DEF_N_312ext_tags_1, + sizeof(asn_DEF_N_312ext_tags_1) + /sizeof(asn_DEF_N_312ext_tags_1[0]), /* 1 */ + asn_DEF_N_312ext_tags_1, /* Same as above */ + sizeof(asn_DEF_N_312ext_tags_1) + /sizeof(asn_DEF_N_312ext_tags_1[0]), /* 1 */ + &asn_PER_type_N_312ext_constr_1, + 0, 0, /* Defined elsewhere */ + &asn_SPC_N_312ext_specs_1 /* Additional specs */ +}; + diff --git a/pool/shard002/C/0063134_main.c b/pool/shard002/C/0063134_main.c new file mode 100644 index 0000000000000000000000000000000000000000..e52babbf3fd0a867576ed6d880025abb86513ff7 --- /dev/null +++ b/pool/shard002/C/0063134_main.c @@ -0,0 +1,33 @@ +#include + +void change(char *a, char *b) +{ + // char tmp; + // if (*a > *b) + // { + // tmp = *a; + // *a = *b; + // *b = tmp; + // } + if (*a > *b) + { + *a = *a ^ *b; + *b = *a ^ *b; + *a = *a ^ *b; + } +} + +int main() +{ + char a, b, c; + while (scanf("%c%c%c", &a, &b, &c) != EOF) + { + char tmp; + change(&a, &b); + change(&a, &c); + change(&b, &c); + printf("%c %c %c\n", a, b, c); + getchar(); + } + return 0; +} diff --git a/pool/shard002/C/0063145_task2.c b/pool/shard002/C/0063145_task2.c new file mode 100644 index 0000000000000000000000000000000000000000..3f2421ba99e73184857e7fa09f3f76baa7246064 --- /dev/null +++ b/pool/shard002/C/0063145_task2.c @@ -0,0 +1,23 @@ +#include +#include + +int main() +{ + char word[50]; + int i=0; + int check=0; + scanf("%s",word); + for(i=0;i + * Copyright (C) 2008-2009 PetaLogix + * Copyright (C) 2006 Atmark Techno, Inc. + * + * 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. + */ + +#include +#include +#include +#include +#include +#include +#include +#include /* for USER_DS macros */ +#include + +void show_regs(struct pt_regs *regs) +{ + pr_info(" Registers dump: mode=%X\r\n", regs->pt_mode); + pr_info(" r1=%08lX, r2=%08lX, r3=%08lX, r4=%08lX\n", + regs->r1, regs->r2, regs->r3, regs->r4); + pr_info(" r5=%08lX, r6=%08lX, r7=%08lX, r8=%08lX\n", + regs->r5, regs->r6, regs->r7, regs->r8); + pr_info(" r9=%08lX, r10=%08lX, r11=%08lX, r12=%08lX\n", + regs->r9, regs->r10, regs->r11, regs->r12); + pr_info(" r13=%08lX, r14=%08lX, r15=%08lX, r16=%08lX\n", + regs->r13, regs->r14, regs->r15, regs->r16); + pr_info(" r17=%08lX, r18=%08lX, r19=%08lX, r20=%08lX\n", + regs->r17, regs->r18, regs->r19, regs->r20); + pr_info(" r21=%08lX, r22=%08lX, r23=%08lX, r24=%08lX\n", + regs->r21, regs->r22, regs->r23, regs->r24); + pr_info(" r25=%08lX, r26=%08lX, r27=%08lX, r28=%08lX\n", + regs->r25, regs->r26, regs->r27, regs->r28); + pr_info(" r29=%08lX, r30=%08lX, r31=%08lX, rPC=%08lX\n", + regs->r29, regs->r30, regs->r31, regs->pc); + pr_info(" msr=%08lX, ear=%08lX, esr=%08lX, fsr=%08lX\n", + regs->msr, regs->ear, regs->esr, regs->fsr); +} + +void (*pm_power_off)(void) = NULL; +EXPORT_SYMBOL(pm_power_off); + +static int hlt_counter = 1; + +void disable_hlt(void) +{ + hlt_counter++; +} +EXPORT_SYMBOL(disable_hlt); + +void enable_hlt(void) +{ + hlt_counter--; +} +EXPORT_SYMBOL(enable_hlt); + +static int __init nohlt_setup(char *__unused) +{ + hlt_counter = 1; + return 1; +} +__setup("nohlt", nohlt_setup); + +static int __init hlt_setup(char *__unused) +{ + hlt_counter = 0; + return 1; +} +__setup("hlt", hlt_setup); + +void default_idle(void) +{ + if (likely(hlt_counter)) { + local_irq_disable(); + stop_critical_timings(); + cpu_relax(); + start_critical_timings(); + local_irq_enable(); + } else { + clear_thread_flag(TIF_POLLING_NRFLAG); + smp_mb__after_clear_bit(); + local_irq_disable(); + while (!need_resched()) + cpu_sleep(); + local_irq_enable(); + set_thread_flag(TIF_POLLING_NRFLAG); + } +} + +void cpu_idle(void) +{ + set_thread_flag(TIF_POLLING_NRFLAG); + + /* endless idle loop with no priority at all */ + while (1) { + tick_nohz_idle_enter(); + rcu_idle_enter(); + while (!need_resched()) + default_idle(); + rcu_idle_exit(); + tick_nohz_idle_exit(); + + schedule_preempt_disabled(); + check_pgt_cache(); + } +} + +void flush_thread(void) +{ +} + +int copy_thread(unsigned long clone_flags, unsigned long usp, + unsigned long arg, struct task_struct *p) +{ + struct pt_regs *childregs = task_pt_regs(p); + struct thread_info *ti = task_thread_info(p); + + if (unlikely(p->flags & PF_KTHREAD)) { + /* if we're creating a new kernel thread then just zeroing all + * the registers. That's OK for a brand new thread.*/ + memset(childregs, 0, sizeof(struct pt_regs)); + memset(&ti->cpu_context, 0, sizeof(struct cpu_context)); + ti->cpu_context.r1 = (unsigned long)childregs; + ti->cpu_context.r20 = (unsigned long)usp; /* fn */ + ti->cpu_context.r19 = (unsigned long)arg; + childregs->pt_mode = 1; + local_save_flags(childregs->msr); +#ifdef CONFIG_MMU + ti->cpu_context.msr = childregs->msr & ~MSR_IE; +#endif + ti->cpu_context.r15 = (unsigned long)ret_from_kernel_thread - 8; + return 0; + } + *childregs = *current_pt_regs(); + if (usp) + childregs->r1 = usp; + + memset(&ti->cpu_context, 0, sizeof(struct cpu_context)); + ti->cpu_context.r1 = (unsigned long)childregs; +#ifndef CONFIG_MMU + ti->cpu_context.msr = (unsigned long)childregs->msr; +#else + childregs->msr |= MSR_UMS; + + /* we should consider the fact that childregs is a copy of the parent + * regs which were saved immediately after entering the kernel state + * before enabling VM. This MSR will be restored in switch_to and + * RETURN() and we want to have the right machine state there + * specifically this state must have INTs disabled before and enabled + * after performing rtbd + * compose the right MSR for RETURN(). It will work for switch_to also + * excepting for VM and UMS + * don't touch UMS , CARRY and cache bits + * right now MSR is a copy of parent one */ + childregs->msr &= ~MSR_EIP; + childregs->msr |= MSR_IE; + childregs->msr &= ~MSR_VM; + childregs->msr |= MSR_VMS; + childregs->msr |= MSR_EE; /* exceptions will be enabled*/ + + ti->cpu_context.msr = (childregs->msr|MSR_VM); + ti->cpu_context.msr &= ~MSR_UMS; /* switch_to to kernel mode */ + ti->cpu_context.msr &= ~MSR_IE; +#endif + ti->cpu_context.r15 = (unsigned long)ret_from_fork - 8; + + /* + * r21 is the thread reg, r10 is 6th arg to clone + * which contains TLS area + */ + if (clone_flags & CLONE_SETTLS) + childregs->r21 = childregs->r10; + + return 0; +} + +#ifndef CONFIG_MMU +/* + * Return saved PC of a blocked thread. + */ +unsigned long thread_saved_pc(struct task_struct *tsk) +{ + struct cpu_context *ctx = + &(((struct thread_info *)(tsk->stack))->cpu_context); + + /* Check whether the thread is blocked in resume() */ + if (in_sched_functions(ctx->r15)) + return (unsigned long)ctx->r15; + else + return ctx->r14; +} +#endif + +unsigned long get_wchan(struct task_struct *p) +{ +/* TBD (used by procfs) */ + return 0; +} + +/* Set up a thread for executing a new program */ +void start_thread(struct pt_regs *regs, unsigned long pc, unsigned long usp) +{ + regs->pc = pc; + regs->r1 = usp; + regs->pt_mode = 0; +#ifdef CONFIG_MMU + regs->msr |= MSR_UMS; + regs->msr &= ~MSR_VM; +#endif +} + +#ifdef CONFIG_MMU +#include +/* + * Set up a thread for executing a new program + */ +int dump_fpu(struct pt_regs *regs, elf_fpregset_t *fpregs) +{ + return 0; /* MicroBlaze has no separate FPU registers */ +} +#endif /* CONFIG_MMU */ diff --git a/pool/shard002/C/0063152_zoom_box.c b/pool/shard002/C/0063152_zoom_box.c new file mode 100644 index 0000000000000000000000000000000000000000..d2f370d21faac68edf20087e733d79ae70a8419c --- /dev/null +++ b/pool/shard002/C/0063152_zoom_box.c @@ -0,0 +1,182 @@ +#include "globals.h" +#include "local_proto.h" +#include + +static int zoom1(int, int); +static int zoom2(int, int); +static int cancel(void); + +static int x1, y1, x2, y2; +static View *pick_view, *zoom_view, *main_view; +static int target_flag; + +int zoom_box(void) +{ + static int use = 1; + + static Objects objects[] = { + MENU("CANCEL", cancel, &use), + INFO(" Mark first corner of region ", &use), + OTHER(zoom1, &use), + {0} + }; + + Input_pointer(objects); + return 1; +} + +static int zoom1(int x, int y) +{ /* called by Input_pointer */ + static int use = 1; + + static Objects objects[] = { + MENU("CANCEL", cancel, &use), + INFO(" Define the region ", &use), + OTHER(zoom2, &use), + {0} + }; + + /* + * user has marked first corner + * this determines which view is being zoomed + */ + x1 = x; + y1 = y; + + if (In_view(pick_view = VIEW_MAP1, x1, y1)) { + main_view = VIEW_MAP1; + zoom_view = VIEW_MAP1_ZOOM; + target_flag = 0; + } + else if (In_view(pick_view = VIEW_MAP2, x1, y1)) { + if (!pick_view->cell.configured) + return 0; /* ignore the mouse event */ + main_view = VIEW_MAP2; + zoom_view = VIEW_MAP2_ZOOM; + target_flag = 1; + } + else if (In_view(pick_view = VIEW_MAP1_ZOOM, x1, y1)) { + if (!pick_view->cell.configured) + return 0; /* ignore the mouse event */ + main_view = VIEW_MAP1; + zoom_view = VIEW_MAP1_ZOOM; + target_flag = 0; + } + else if (In_view(pick_view = VIEW_MAP2_ZOOM, x1, y1)) { + if (!pick_view->cell.configured) + return 0; /* ignore the mouse event */ + main_view = VIEW_MAP2; + zoom_view = VIEW_MAP2_ZOOM; + target_flag = 1; + } + else + return 0; /* ignore the mouse event */ + if (!pick_view->cell.configured) + return 0; /* just to be sure */ + + return Input_box(objects, x, y); +} + +static int zoom2(int x, int y) +{ + int top, bottom, left, right; + int row, col; + struct Cell_head cellhd; + + x2 = x; + y2 = y; + /* + * user has completed the zoom window. + * must be in same view as first corner + */ + if (x1 == x2 || y1 == y2) + return 0; /* ignore event */ + if (!In_view(pick_view, x2, y2)) + return 0; + /* + * ok, erase menu messages + */ + Menu_msg(""); + + /* + * assign window coordinates to top,bottom,left,right + */ + if (x1 < x2) { + left = x1; + right = x2; + } + else { + left = x2; + right = x1; + } + if (y1 < y2) { + top = y1; + bottom = y2; + } + else { + top = y2; + bottom = y1; + } + + /* + * Determine the the zoom window (ie, cellhd) + * must copy the current view cellhd first, to preserve header info + * (such as projection, zone, and other items.) + * compute zoom window northings,eastings, rows, cols, and resolution + */ + + G_copy(&cellhd, &pick_view->cell.head, sizeof(cellhd)); + + /* convert top to northing at top edge of cell + * left to easting at left edge + */ + col = view_to_col(pick_view, left); + row = view_to_row(pick_view, top); + cellhd.north = row_to_northing(&pick_view->cell.head, row, 0.0); + cellhd.west = col_to_easting(&pick_view->cell.head, col, 0.0); + + /* convert bottom to northing at bottom edge of cell + * right to easting at right edge + */ + col = view_to_col(pick_view, right); + row = view_to_row(pick_view, bottom); + cellhd.south = row_to_northing(&pick_view->cell.head, row, 1.0); + cellhd.east = col_to_easting(&pick_view->cell.head, col, 1.0); + + + cellhd.rows = bottom - top + 1; + cellhd.cols = right - left + 1; + cellhd.ns_res = (cellhd.north - cellhd.south) / cellhd.rows; + cellhd.ew_res = (cellhd.east - cellhd.west) / cellhd.cols; + + /* + * Outline the zoom window on the main map + * Turn previous one to grey. + */ + if (zoom_view->cell.configured) { + R_standard_color(GREY); + Outline_cellhd(main_view, &zoom_view->cell.head); + } + R_standard_color(RED); + Outline_cellhd(main_view, &cellhd); + + + /* + * zoom + */ + if (target_flag) + select_target_env(); + G_adjust_window_to_box(&cellhd, &zoom_view->cell.head, zoom_view->nrows, + zoom_view->ncols); + Configure_view(zoom_view, pick_view->cell.name, pick_view->cell.mapset, + pick_view->cell.ns_res, pick_view->cell.ew_res); + drawcell(zoom_view); + select_current_env(); + display_points(1); + return 1; /* pop back */ +} + +static int cancel(void) +{ + return -1; +} diff --git a/pool/shard002/C/0063154_CWE78_OS_Command_Injection__wchar_t_listen_socket_execl_21.c b/pool/shard002/C/0063154_CWE78_OS_Command_Injection__wchar_t_listen_socket_execl_21.c new file mode 100644 index 0000000000000000000000000000000000000000..007fb4ede183c9882842ede7a2a45d3ab347663a --- /dev/null +++ b/pool/shard002/C/0063154_CWE78_OS_Command_Injection__wchar_t_listen_socket_execl_21.c @@ -0,0 +1,259 @@ +/* TEMPLATE GENERATED TESTCASE FILE +Filename: CWE78_OS_Command_Injection__wchar_t_listen_socket_execl_21.c +Label Definition File: CWE78_OS_Command_Injection.strings.label.xml +Template File: sources-sink-21.tmpl.c +*/ +/* + * @description + * CWE: 78 OS Command Injection + * BadSource: listen_socket Read data using a listen socket (server side) + * GoodSource: Fixed string + * Sink: execl + * BadSink : execute command with wexecl + * Flow Variant: 21 Control flow: Flow controlled by value of a static global variable. All functions contained in one 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"ls" +#define COMMAND_ARG2 L"-la" +#define COMMAND_ARG3 data +#endif + +#ifdef _WIN32 +#include +#include +#include +#pragma comment(lib, "ws2_32") /* include ws2_32.lib when linking */ +#define CLOSE_SOCKET closesocket +#else +#include +#include +#include +#include +#define INVALID_SOCKET -1 +#define SOCKET_ERROR -1 +#define CLOSE_SOCKET close +#define SOCKET int +#endif + +#define TCP_PORT 27015 +#define LISTEN_BACKLOG 5 + +#ifdef _WIN32 +#include +#define EXECL _wexecl +#else /* NOT _WIN32 */ +#define EXECL execl +#endif + +#ifndef OMITBAD + +/* The static variable below is used to drive control flow in the source function */ +static int badStatic = 0; + +static wchar_t * badSource(wchar_t * data) +{ + if(badStatic) + { + { +#ifdef _WIN32 + WSADATA wsaData; + int wsaDataInit = 0; +#endif + int recvResult; + struct sockaddr_in service; + wchar_t *replace; + SOCKET listenSocket = INVALID_SOCKET; + SOCKET acceptSocket = INVALID_SOCKET; + size_t dataLen = wcslen(data); + do + { +#ifdef _WIN32 + if (WSAStartup(MAKEWORD(2,2), &wsaData) != NO_ERROR) + { + break; + } + wsaDataInit = 1; +#endif + /* POTENTIAL FLAW: Read data using a listen socket */ + listenSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); + if (listenSocket == INVALID_SOCKET) + { + break; + } + memset(&service, 0, sizeof(service)); + service.sin_family = AF_INET; + service.sin_addr.s_addr = INADDR_ANY; + service.sin_port = htons(TCP_PORT); + if (bind(listenSocket, (struct sockaddr*)&service, sizeof(service)) == SOCKET_ERROR) + { + break; + } + if (listen(listenSocket, LISTEN_BACKLOG) == SOCKET_ERROR) + { + break; + } + acceptSocket = accept(listenSocket, NULL, NULL); + if (acceptSocket == SOCKET_ERROR) + { + break; + } + /* Abort on error or the connection was closed */ + recvResult = recv(acceptSocket, (char *)(data + dataLen), sizeof(wchar_t) * (100 - dataLen - 1), 0); + if (recvResult == SOCKET_ERROR || recvResult == 0) + { + break; + } + /* Append null terminator */ + data[dataLen + recvResult / sizeof(wchar_t)] = L'\0'; + /* Eliminate CRLF */ + replace = wcschr(data, L'\r'); + if (replace) + { + *replace = L'\0'; + } + replace = wcschr(data, L'\n'); + if (replace) + { + *replace = L'\0'; + } + } + while (0); + if (listenSocket != INVALID_SOCKET) + { + CLOSE_SOCKET(listenSocket); + } + if (acceptSocket != INVALID_SOCKET) + { + CLOSE_SOCKET(acceptSocket); + } +#ifdef _WIN32 + if (wsaDataInit) + { + WSACleanup(); + } +#endif + } + } + return data; +} + +void CWE78_OS_Command_Injection__wchar_t_listen_socket_execl_21_bad() +{ + wchar_t * data; + wchar_t dataBuffer[100] = L""; + data = dataBuffer; + badStatic = 1; /* true */ + data = badSource(data); + /* wexecl - specify the path where the command is located */ + /* POTENTIAL FLAW: Execute command without validating input possibly leading to command injection */ + EXECL(COMMAND_INT_PATH, COMMAND_INT_PATH, COMMAND_ARG1, COMMAND_ARG2, COMMAND_ARG3, NULL); +} + +#endif /* OMITBAD */ + +#ifndef OMITGOOD + +/* The static variables below are used to drive control flow in the source functions. */ +static int goodG2B1Static = 0; +static int goodG2B2Static = 0; + +/* goodG2B1() - use goodsource and badsink by setting the static variable to false instead of true */ +static wchar_t * goodG2B1Source(wchar_t * data) +{ + if(goodG2B1Static) + { + /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */ + printLine("Benign, fixed string"); + } + else + { + /* FIX: Append a fixed string to data (not user / external input) */ + wcscat(data, L"*.*"); + } + return data; +} + +static void goodG2B1() +{ + wchar_t * data; + wchar_t dataBuffer[100] = L""; + data = dataBuffer; + goodG2B1Static = 0; /* false */ + data = goodG2B1Source(data); + /* wexecl - specify the path where the command is located */ + /* POTENTIAL FLAW: Execute command without validating input possibly leading to command injection */ + EXECL(COMMAND_INT_PATH, COMMAND_INT_PATH, COMMAND_ARG1, COMMAND_ARG2, COMMAND_ARG3, NULL); +} + +/* goodG2B2() - use goodsource and badsink by reversing the blocks in the if in the source function */ +static wchar_t * goodG2B2Source(wchar_t * data) +{ + if(goodG2B2Static) + { + /* FIX: Append a fixed string to data (not user / external input) */ + wcscat(data, L"*.*"); + } + return data; +} + +static void goodG2B2() +{ + wchar_t * data; + wchar_t dataBuffer[100] = L""; + data = dataBuffer; + goodG2B2Static = 1; /* true */ + data = goodG2B2Source(data); + /* wexecl - specify the path where the command is located */ + /* POTENTIAL FLAW: Execute command without validating input possibly leading to command injection */ + EXECL(COMMAND_INT_PATH, COMMAND_INT_PATH, COMMAND_ARG1, COMMAND_ARG2, COMMAND_ARG3, NULL); +} + +void CWE78_OS_Command_Injection__wchar_t_listen_socket_execl_21_good() +{ + goodG2B1(); + goodG2B2(); +} + +#endif /* OMITGOOD */ + +/* Below is the main(). It is only used when building this testcase on + * its own for testing or for building a binary to use in testing binary + * analysis tools. It is not used when compiling all the testcases as one + * application, which is how source code analysis tools are tested. + */ + +#ifdef INCLUDEMAIN + +int main(int argc, char * argv[]) +{ + /* seed randomness */ + srand( (unsigned)time(NULL) ); +#ifndef OMITGOOD + printLine("Calling good()..."); + CWE78_OS_Command_Injection__wchar_t_listen_socket_execl_21_good(); + printLine("Finished good()"); +#endif /* OMITGOOD */ +#ifndef OMITBAD + printLine("Calling bad()..."); + CWE78_OS_Command_Injection__wchar_t_listen_socket_execl_21_bad(); + printLine("Finished bad()"); +#endif /* OMITBAD */ + return 0; +} + +#endif diff --git a/pool/shard002/C/0063159_cmd_help.c b/pool/shard002/C/0063159_cmd_help.c new file mode 100644 index 0000000000000000000000000000000000000000..4f80797213544f5826fe6ff9fb9931f8cf6c9404 --- /dev/null +++ b/pool/shard002/C/0063159_cmd_help.c @@ -0,0 +1,41 @@ + +int cmd_help(char cmd[]) +{ + +int i; + +#if LANG_ENG + char available[]={" %d commands available:\n\r"}; +#elif LANG_RUS + char available[]={" Š®«¨ç¥á⢮ ¤®áâ㯭ëå ª®¬ ­¤: %d\n\r"}; +#endif + +if ( !strlen(cmd) ) + { + printf (available, NUM_OF_CMD); + for (i = 0; i < NUM_OF_CMD; i++) + printf(" %s\n\r", COMMANDS[i].name); + return TRUE; + } +else + { + for (i=0; i + * Based on ideas by Tomasz Wlostowski + * + * 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 "minipc-int.h" + +struct minipc_ch *minipc_client_create(const char *name, int f) +{ + return __minipc_link_create(name, MPC_USER_FLAGS(f) | MPC_FLAG_CLIENT); +} + +int minipc_call(struct minipc_ch *ch, int millisec_timeout, + const struct minipc_pd *pd, void *ret, ...) +{ + struct mpc_link *link = mpc_get_link(ch); + struct mpc_shmem *shm = link->memaddr; + struct pollfd pfd; + int i, narg, size, retsize, pollnr; + int atype, asize; + va_list ap; + struct mpc_req_packet *p_out, _pkt_out = {"",}; + struct mpc_rep_packet *p_in, _pkt_in; + + CHECK_LINK(link); + + if (shm) { + p_out = &shm->request; + p_in = &shm->reply; + } else { + p_out = & _pkt_out; + p_in = & _pkt_in; + } + + /* Build the packet to send out -- marshall args */ + if (link->logf) { + fprintf(link->logf, "%s: calling \"%s\"\n", + __func__, pd->name); + } + memcpy(p_out->name, pd->name, MINIPC_MAX_NAME); + + va_start(ap, ret); + for (i = narg = 0; ; i++) { + int next_narg = narg; + + atype = MINIPC_GET_ATYPE(pd->args[i]); + asize = MINIPC_GET_ASIZE(pd->args[i]); + next_narg += MINIPC_GET_ANUM(asize); + if (next_narg >= MINIPC_MAX_ARGUMENTS) /* unlikely */ + goto doesnt_fit; + + switch (atype) { + case MINIPC_ATYPE_NONE: + goto out; /* end of list */ + case MINIPC_ATYPE_INT: + p_out->args[narg++] = va_arg(ap, int); + break; + case MINIPC_ATYPE_INT64: + *(uint64_t *)(p_out->args + narg) + = va_arg(ap, uint64_t); + narg = next_narg; + break; + case MINIPC_ATYPE_DOUBLE: + *(double *)(p_out->args + narg) = va_arg(ap, double); + narg = next_narg; + break; + case MINIPC_ATYPE_STRING: + { + char *sin = va_arg(ap, void *); + char *sout = (void *)(p_out->args + narg); + int slen = strlen(sin); + int alen; + + /* + * argument len is arbitrary, terminate and 4-align + * we can't use next_narg here, as len changes + */ + alen = MINIPC_GET_ANUM(slen + 1); + if (narg + alen >= MINIPC_MAX_ARGUMENTS) + goto doesnt_fit; + strcpy(sout, sin); + narg += alen; + break; + } + case MINIPC_ATYPE_STRUCT: + memcpy(p_out->args + narg, va_arg(ap, void *), asize); + narg = next_narg; + break; + + default: + if (link->logf) { + fprintf(link->logf, "%s: unkown type 0x%x\n", + __func__, atype); + } + errno = EPROTO; + return -1; + } + } + out: + va_end(ap); + + if (shm) { + shm->nrequest++; + } else { + size = sizeof(p_out->name) + sizeof(p_out->args[0]) * narg; + if (send(ch->fd, p_out, size, 0) < 0) { + /* errno already set */ + return -1; + } + } + + /* Wait for the reply packet */ + pfd.fd = ch->fd; + pfd.events = POLLIN | POLLHUP; + pfd.revents = 0; + pollnr = poll(&pfd, 1, millisec_timeout); + if (pollnr < 0) { + /* errno already set */ + return -1; + } + if (pollnr == 0) { + errno = ETIMEDOUT; + return -1; + } + + if (shm) { + read(ch->fd, &i, 1); + size = retsize = sizeof(shm->reply); + } else { + /* this "size" is wrong for strings, so recv the max size */ + size = MINIPC_GET_ASIZE(pd->retval) + sizeof(uint32_t); + retsize = recv(ch->fd, p_in, sizeof(*p_in), 0); + } + /* if very short, we have a problem */ + if (retsize < (sizeof(p_in->type)) + sizeof(int)) + goto too_short; + /* remote error reported */ + if (MINIPC_GET_ATYPE(p_in->type) == MINIPC_ATYPE_ERROR) { + int remoteerr = *(int *)&p_in->val; + + if (link->logf) { + fprintf(link->logf, "%s: remote error \"%s\"\n", + __func__, strerror(remoteerr)); + } + *(int *)ret = remoteerr; + errno = EREMOTEIO; + return -1; + } + /* another check: the return type must match */ + if (MINIPC_GET_ATYPE(p_in->type) != MINIPC_GET_ATYPE(pd->retval)) { + if (link->logf) { + fprintf(link->logf, "%s: wrong code %08x (not %08x)\n", + __func__, p_in->type, pd->retval); + } + errno = EPROTO; + return -1; + } + /* check size */ + if (retsize < size) + goto too_short; + /* all good */ + memcpy(ret, &p_in->val, MINIPC_GET_ASIZE(p_in->type)); + return 0; + +too_short: + if (link->logf) { + fprintf(link->logf, "%s: short reply (%i bytes)\n", + __func__, retsize); + } + errno = EPROTO; + return -1; + +doesnt_fit: + if (link->logf) { + fprintf(link->logf, "%s: rpc call \"%s\" won't fit %i slots\n", + __func__, pd->name, MINIPC_MAX_ARGUMENTS); + } + errno = EPROTO; + return -1; +} diff --git a/pool/shard002/C/0063167_test-menu-manager2.c b/pool/shard002/C/0063167_test-menu-manager2.c new file mode 100644 index 0000000000000000000000000000000000000000..9ea220b55082527e0fc2cd8fc2c1306087659b80 --- /dev/null +++ b/pool/shard002/C/0063167_test-menu-manager2.c @@ -0,0 +1,68 @@ +#include + +#define assert_item_at_index(menu, i, label) \ +G_STMT_START { \ + g_autofree gchar *str = NULL; \ + gboolean r = g_menu_model_get_item_attribute (G_MENU_MODEL (menu), i, "label", "s", &str); \ + g_assert (r); \ + g_assert_cmpstr (str, ==, label); \ +} G_STMT_END + +static void +test_menu_manager (void) +{ + g_autoptr(DzlMenuManager) manager = dzl_menu_manager_new (); + g_autoptr(GMenu) menu1 = g_menu_new (); + g_autoptr(GMenu) menu2 = g_menu_new (); + g_autoptr(GMenuItem) item1 = g_menu_item_new ("item1", "item1"); + g_autoptr(GMenuItem) item2 = g_menu_item_new ("item2", "item2"); + g_autoptr(GMenuItem) item3 = g_menu_item_new ("item3", "item3"); + g_autoptr(GMenuItem) item4 = g_menu_item_new ("item4", "item4"); + g_autoptr(GMenuItem) item5 = g_menu_item_new ("item5", "item5"); + g_autoptr(GMenuItem) item6 = g_menu_item_new ("item6", "item6"); + GMenu *merged; + guint n_items; + + g_menu_item_set_attribute (item1, "after", "s", "item3"); + g_menu_item_set_attribute (item1, "before", "s", "item5"); + + g_menu_append_item (menu1, item1); + g_menu_append_item (menu1, item2); + g_menu_append_item (menu1, item3); + + dzl_menu_manager_merge (manager, "menu", G_MENU_MODEL (menu1)); + + merged = dzl_menu_manager_get_menu_by_id (manager, "menu"); + + assert_item_at_index (merged, 0, "item2"); + assert_item_at_index (merged, 1, "item3"); + assert_item_at_index (merged, 2, "item1"); + + g_menu_item_set_attribute (item4, "after", "s", "item2"); + g_menu_item_set_attribute (item4, "before", "s", "item3"); + + g_menu_append_item (menu2, item4); + g_menu_append_item (menu2, item5); + g_menu_append_item (menu2, item6); + + dzl_menu_manager_merge (manager, "menu", G_MENU_MODEL (menu2)); + + n_items = g_menu_model_get_n_items (G_MENU_MODEL (merged)); + g_assert_cmpint (n_items, ==, 6); + + assert_item_at_index (merged, 0, "item2"); + assert_item_at_index (merged, 1, "item4"); + assert_item_at_index (merged, 2, "item3"); + assert_item_at_index (merged, 3, "item1"); + assert_item_at_index (merged, 4, "item5"); + assert_item_at_index (merged, 5, "item6"); +} + +gint +main (gint argc, + gchar *argv[]) +{ + g_test_init (&argc, &argv, NULL); + g_test_add_func ("/Dazzle/MenuManager/basic", test_menu_manager); + return g_test_run (); +} diff --git a/pool/shard002/C/0063169_fpm_cleanup.c b/pool/shard002/C/0063169_fpm_cleanup.c new file mode 100644 index 0000000000000000000000000000000000000000..260ddb32e76219da05f347c19dcd26c1ffc93193 --- /dev/null +++ b/pool/shard002/C/0063169_fpm_cleanup.c @@ -0,0 +1,52 @@ + + /* $Id: fpm_cleanup.c,v 1.8 2008/05/24 17:38:47 anight Exp $ */ + /* (c) 2007,2008 Andrei Nigmatulin */ + +#include "fpm_config.h" + +#include + +#include "fpm_arrays.h" +#include "fpm_cleanup.h" + +struct cleanup_s { + int type; + void (*cleanup)(int, void *); + void *arg; +}; + +static struct fpm_array_s cleanups = { .sz = sizeof(struct cleanup_s) }; + +int fpm_cleanup_add(int type, void (*cleanup)(int, void *), void *arg) /* {{{ */ +{ + struct cleanup_s *c; + + c = fpm_array_push(&cleanups); + + if (!c) { + return -1; + } + + c->type = type; + c->cleanup = cleanup; + c->arg = arg; + + return 0; +} +/* }}} */ + +void fpm_cleanups_run(int type) /* {{{ */ +{ + struct cleanup_s *c = fpm_array_item_last(&cleanups); + int cl = cleanups.used; + + for ( ; cl--; c--) { + if (c->type & type) { + c->cleanup(type, c->arg); + } + } + + fpm_array_free(&cleanups); +} +/* }}} */ + diff --git a/pool/shard002/C/0063170_CWE78_OS_Command_Injection__wchar_t_file_execl_13.c b/pool/shard002/C/0063170_CWE78_OS_Command_Injection__wchar_t_file_execl_13.c new file mode 100644 index 0000000000000000000000000000000000000000..e36dd93fbe974b0496cd5594932827137d2e2211 --- /dev/null +++ b/pool/shard002/C/0063170_CWE78_OS_Command_Injection__wchar_t_file_execl_13.c @@ -0,0 +1,159 @@ +/* TEMPLATE GENERATED TESTCASE FILE +Filename: CWE78_OS_Command_Injection__wchar_t_file_execl_13.c +Label Definition File: CWE78_OS_Command_Injection.strings.label.xml +Template File: sources-sink-13.tmpl.c +*/ +/* + * @description + * CWE: 78 OS Command Injection + * BadSource: file Read input from a file + * GoodSource: Fixed string + * Sink: execl + * BadSink : execute command with wexecl + * Flow Variant: 13 Control flow: if(GLOBAL_CONST_FIVE==5) and if(GLOBAL_CONST_FIVE!=5) + * + * */ + +#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 + +#ifdef _WIN32 +#define FILENAME "C:\\temp\\file.txt" +#else +#define FILENAME "/tmp/file.txt" +#endif + +#ifdef _WIN32 +#include +#define EXECL _wexecl +#else /* NOT _WIN32 */ +#define EXECL execl +#endif + +#ifndef OMITBAD + +void CWE78_OS_Command_Injection__wchar_t_file_execl_13_bad() +{ + wchar_t * data; + wchar_t dataBuffer[100] = COMMAND_ARG2; + data = dataBuffer; + if(GLOBAL_CONST_FIVE==5) + { + { + /* Read input from a file */ + size_t dataLen = wcslen(data); + FILE * pFile; + /* if there is room in data, attempt to read the input from a file */ + if (100-dataLen > 1) + { + pFile = fopen(FILENAME, "r"); + if (pFile != NULL) + { + /* POTENTIAL FLAW: Read data from a file */ + if (fgetws(data+dataLen, (int)(100-dataLen), pFile) == NULL) + { + printLine("fgetws() failed"); + /* Restore NUL terminator if fgetws fails */ + data[dataLen] = L'\0'; + } + fclose(pFile); + } + } + } + } + /* wexecl - specify the path where the command is located */ + /* POTENTIAL FLAW: Execute command without validating input possibly leading to command injection */ + EXECL(COMMAND_INT_PATH, COMMAND_INT_PATH, COMMAND_ARG1, COMMAND_ARG3, NULL); +} + +#endif /* OMITBAD */ + +#ifndef OMITGOOD + +/* goodG2B1() - use goodsource and badsink by changing the GLOBAL_CONST_FIVE==5 to GLOBAL_CONST_FIVE!=5 */ +static void goodG2B1() +{ + wchar_t * data; + wchar_t dataBuffer[100] = COMMAND_ARG2; + data = dataBuffer; + if(GLOBAL_CONST_FIVE!=5) + { + /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */ + printLine("Benign, fixed string"); + } + else + { + /* FIX: Append a fixed string to data (not user / external input) */ + wcscat(data, L"*.*"); + } + /* wexecl - specify the path where the command is located */ + /* POTENTIAL FLAW: Execute command without validating input possibly leading to command injection */ + EXECL(COMMAND_INT_PATH, COMMAND_INT_PATH, COMMAND_ARG1, COMMAND_ARG3, NULL); +} + +/* goodG2B2() - use goodsource and badsink by reversing the blocks in the if statement */ +static void goodG2B2() +{ + wchar_t * data; + wchar_t dataBuffer[100] = COMMAND_ARG2; + data = dataBuffer; + if(GLOBAL_CONST_FIVE==5) + { + /* FIX: Append a fixed string to data (not user / external input) */ + wcscat(data, L"*.*"); + } + /* wexecl - specify the path where the command is located */ + /* POTENTIAL FLAW: Execute command without validating input possibly leading to command injection */ + EXECL(COMMAND_INT_PATH, COMMAND_INT_PATH, COMMAND_ARG1, COMMAND_ARG3, NULL); +} + +void CWE78_OS_Command_Injection__wchar_t_file_execl_13_good() +{ + goodG2B1(); + goodG2B2(); +} + +#endif /* OMITGOOD */ + +/* Below is the main(). It is only used when building this testcase on + * its own for testing or for building a binary to use in testing binary + * analysis tools. It is not used when compiling all the testcases as one + * application, which is how source code analysis tools are tested. + */ + +#ifdef INCLUDEMAIN + +int main(int argc, char * argv[]) +{ + /* seed randomness */ + srand( (unsigned)time(NULL) ); +#ifndef OMITGOOD + printLine("Calling good()..."); + CWE78_OS_Command_Injection__wchar_t_file_execl_13_good(); + printLine("Finished good()"); +#endif /* OMITGOOD */ +#ifndef OMITBAD + printLine("Calling bad()..."); + CWE78_OS_Command_Injection__wchar_t_file_execl_13_bad(); + printLine("Finished bad()"); +#endif /* OMITBAD */ + return 0; +} + +#endif diff --git a/pool/shard002/C/0063178_cpuusagereset.c b/pool/shard002/C/0063178_cpuusagereset.c new file mode 100644 index 0000000000000000000000000000000000000000..6b0539f8bce6cce74d283a899d9e44778862ff00 --- /dev/null +++ b/pool/shard002/C/0063178_cpuusagereset.c @@ -0,0 +1,59 @@ +/** + * @file + * + * @brief CPU Usage Reset + * @ingroup libmisc_cpuuse CPU Usage + */ + +/* + * COPYRIGHT (c) 1989-2009 + * 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. + */ + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +#include +#include +#include +#include + +static void CPU_usage_Per_thread_handler( + Thread_Control *the_thread +) +{ + #ifndef __RTEMS_USE_TICKS_FOR_STATISTICS__ + _Timestamp_Set_to_zero( &the_thread->cpu_time_used ); + #else + the_thread->cpu_time_used = 0; + #endif +} + +/* + * rtems_cpu_usage_reset + */ +void rtems_cpu_usage_reset( void ) +{ + #ifndef __RTEMS_USE_TICKS_FOR_STATISTICS__ + uint32_t processor_count; + uint32_t processor; + + _TOD_Get_uptime( &CPU_usage_Uptime_at_last_reset ); + + processor_count = rtems_smp_get_processor_count(); + for ( processor = 0 ; processor < processor_count ; ++processor ) { + Per_CPU_Control *per_cpu = _Per_CPU_Get_by_index( processor ); + + per_cpu->time_of_last_context_switch = CPU_usage_Uptime_at_last_reset; + } + #else + CPU_usage_Ticks_at_last_reset = _Watchdog_Ticks_since_boot; + #endif + + rtems_iterate_over_all_threads(CPU_usage_Per_thread_handler); +} diff --git a/pool/shard002/C/0063186_Timers.c b/pool/shard002/C/0063186_Timers.c new file mode 100644 index 0000000000000000000000000000000000000000..6cd24b376a84e9581e6506714ea2e3a38b0d58a3 --- /dev/null +++ b/pool/shard002/C/0063186_Timers.c @@ -0,0 +1,52 @@ +// Timer.c + +#include "includes.h" + +__irq __nested __arm void TimerHandler0() +{ + T0IR = BIT_0; + VICADDRESS = 0; + + timer0_handler(); +} + +void InitTimer0(void(*handler)()) +{ + //Disable Timer0 + T0TCR &= ~BIT_0; + + //Configure Interrupt Register + T0IR = BIT_0; + + //Configure Count Control Register + T0CTCR = 0; + + //Configure Prescale Counter Register + T0PC = 0; + + //Configure Prescale Counter Register + //15000000 - 1Hz + //1500000 - 10Hz + //150000 - 100Hz + //15000 - 1kHz + + //5Hz + T0MR0 = 3000000; + + //Configure Match Control Register + T0MCR = (BIT_0 | BIT_1); + + timer0_handler = handler; + + InstallIRQ( TIMER0_INT, (void *)TimerHandler0, 0x03 ); +} + +void DisableTimer0() +{ + T0TCR &= ~BIT_0; +} + +void EnableTimer0() +{ + T0TCR = BIT_0; +} \ No newline at end of file diff --git a/pool/shard002/C/0063191_init.c b/pool/shard002/C/0063191_init.c new file mode 100644 index 0000000000000000000000000000000000000000..cc618a5cf6fa732f04f35645f4370699b1acd423 --- /dev/null +++ b/pool/shard002/C/0063191_init.c @@ -0,0 +1,219 @@ +/* + * COPYRIGHT (c) 1989-2012. + * 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. + */ + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +#include +#include +#include +#include +#include + +const char rtems_test_name[] = "PSXPASSWD 1"; + +/* forward declarations to avoid warnings */ +rtems_task Init(rtems_task_argument ignored); +void print_passwd(struct passwd *pw); +void print_group(struct group *gr); + +void print_passwd( + struct passwd *pw +) +{ + printf( + " username: %s\n" + " user password: %s\n" + " user ID: %d\n" + " group ID: %d\n" + " real name: %s\n" + " home directory: %s\n" + " shell program: %s\n", + pw->pw_name, + pw->pw_passwd, + pw->pw_uid, + pw->pw_gid, + pw->pw_gecos, + pw->pw_dir, + pw->pw_shell + ); +} + +void print_group( + struct group *gr +) +{ + printf( + " group name: %s\n" + " group password: %s\n" + " group ID: %d\n", + gr->gr_name, + gr->gr_passwd, + gr->gr_gid + ); + + /* TBD print users in group */ +} + +rtems_task Init( + rtems_task_argument ignored +) +{ + struct passwd *pw; + struct group *gr; + + TEST_BEGIN(); + + /* getpwent */ + puts( "Init - getpwent() -- OK, result should be NULL" ); + pw = getpwent(); + rtems_test_assert( !pw ); + + /* getgrent */ + puts( "Init - getgrent() -- OK, result should be NULL" ); + gr = getgrent(); + rtems_test_assert( !gr ); + + /* setpwent */ + + puts( "Init - setpwent() -- OK" ); + setpwent(); + + /* setgrent */ + + puts( "Init - setgrent() -- OK" ); + setgrent(); + + /* getpwent */ + + puts( "Init - getpwent() (1) -- OK" ); + pw = getpwent(); + rtems_test_assert( pw ); + print_passwd( pw ); + + puts( "Init - getpwent() (2) -- OK" ); + pw = getpwent(); + rtems_test_assert( pw ); + print_passwd( pw ); + + puts( "Init - getpwent() (3) -- OK" ); + pw = getpwent(); + rtems_test_assert( pw ); + print_passwd( pw ); + + puts( "Init - getpwent() (4) -- result should be NULL" ); + pw = getpwent(); + rtems_test_assert( !pw ); + + /* getgrent */ + + puts( "Init - getgrent() (1) -- OK" ); + gr = getgrent(); + rtems_test_assert( gr ); + print_group( gr ); + + puts( "Init - getgrent() (2) -- OK" ); + gr = getgrent(); + rtems_test_assert( gr ); + print_group( gr ); + + puts( "Init - getgrent() (3) -- OK" ); + gr = getgrent(); + rtems_test_assert( gr ); + print_group( gr ); + + puts( "Init - getgrent() (4) -- result should be NULL" ); + gr = getgrent(); + rtems_test_assert( !gr ); + + /* getpwnam */ + puts( "Init - getpwnam(\"root\") -- OK" ); + pw = getpwnam( "root" ); + rtems_test_assert( pw ); + print_passwd( pw ); + + puts( "Init - getpwnam(\"rtems\") -- OK" ); + pw = getpwnam( "rtems" ); + rtems_test_assert( pw ); + print_passwd( pw ); + + puts( "Init - getpwnam(\"suser\") -- result should be NULL" ); + pw = getpwnam( "suser" ); + rtems_test_assert( !pw ); + + /* getpwuid */ + puts( "Init - getpwuid(0) -- OK" ); + pw = getpwuid( 0 ); + rtems_test_assert( pw ); + print_passwd( pw ); + + puts( "Init - getpwuid(1) -- OK" ); + pw = getpwuid( 1 ); + rtems_test_assert( pw ); + print_passwd( pw ); + + puts( "Init - getpwuid(4) -- result should be NULL" ); + pw = getpwuid( 4 ); + rtems_test_assert( !pw ); + + /* getgrnam */ + puts( "Init - getgrnam(\"root\") -- OK" ); + gr = getgrnam("root"); + rtems_test_assert( gr ); + print_group( gr ); + + puts( "Init - getgrnam(\"rtems\") -- OK" ); + gr = getgrnam("rtems"); + rtems_test_assert( gr ); + print_group( gr ); + + /* getgrgid */ + puts( "Init - getgrgid(0) -- OK" ); + gr = getgrgid(0); + rtems_test_assert( gr ); + print_group( gr ); + + puts( "Init - getgrgid(1) -- OK" ); + gr = getgrgid(1); + rtems_test_assert( gr ); + print_group( gr ); + + puts( "Init - getgrgid(4) -- result should be NULL"); + gr = getgrgid( 4 ); + rtems_test_assert( !gr ); + + /* endpwent */ + puts( "Init - endpwent() -- OK" ); + endpwent(); + + /* endgrent */ + puts( "Init - endgrent() -- OK" ); + endgrent(); + + TEST_END(); + rtems_test_exit( 0 ); +} + +/* configuration information */ + +#define CONFIGURE_APPLICATION_NEEDS_CONSOLE_DRIVER +#define CONFIGURE_APPLICATION_NEEDS_CLOCK_DRIVER + +#define CONFIGURE_USE_IMFS_AS_BASE_FILESYSTEM +#define CONFIGURE_LIBIO_MAXIMUM_FILE_DESCRIPTORS 6 + +#define CONFIGURE_MAXIMUM_TASKS 1 +#define CONFIGURE_INITIAL_EXTENSIONS RTEMS_TEST_INITIAL_EXTENSION + +#define CONFIGURE_RTEMS_INIT_TASKS_TABLE + +#define CONFIGURE_INIT +#include +/* end of file */ diff --git a/pool/shard002/C/0063192_vivid-cec.c b/pool/shard002/C/0063192_vivid-cec.c new file mode 100644 index 0000000000000000000000000000000000000000..66aa7292076b1aed54928f056ad631046b9c9831 --- /dev/null +++ b/pool/shard002/C/0063192_vivid-cec.c @@ -0,0 +1,241 @@ +/* + * vivid-cec.c - A Virtual Video Test Driver, cec emulation + * + * Copyright 2016 Cisco Systems, Inc. and/or its affiliates. All rights reserved. + * + * This program is free software; you may 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. + * + * 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 "vivid-core.h" +#include "vivid-cec.h" + +void vivid_cec_bus_free_work(struct vivid_dev *dev) +{ + spin_lock(&dev->cec_slock); + while (!list_empty(&dev->cec_work_list)) { + struct vivid_cec_work *cw = + list_first_entry(&dev->cec_work_list, + struct vivid_cec_work, list); + + spin_unlock(&dev->cec_slock); + cancel_delayed_work_sync(&cw->work); + spin_lock(&dev->cec_slock); + list_del(&cw->list); + cec_transmit_done(cw->adap, CEC_TX_STATUS_LOW_DRIVE, 0, 0, 1, 0); + kfree(cw); + } + spin_unlock(&dev->cec_slock); +} + +static bool vivid_cec_find_dest_adap(struct vivid_dev *dev, + struct cec_adapter *adap, u8 dest) +{ + unsigned int i; + + if (dest >= 0xf) + return false; + + if (adap != dev->cec_rx_adap && dev->cec_rx_adap && + dev->cec_rx_adap->is_configured && + cec_has_log_addr(dev->cec_rx_adap, dest)) + return true; + + for (i = 0; i < MAX_OUTPUTS && dev->cec_tx_adap[i]; i++) { + if (adap == dev->cec_tx_adap[i]) + continue; + if (!dev->cec_tx_adap[i]->is_configured) + continue; + if (cec_has_log_addr(dev->cec_tx_adap[i], dest)) + return true; + } + return false; +} + +static void vivid_cec_xfer_done_worker(struct work_struct *work) +{ + struct vivid_cec_work *cw = + container_of(work, struct vivid_cec_work, work.work); + struct vivid_dev *dev = cw->dev; + struct cec_adapter *adap = cw->adap; + u8 dest = cec_msg_destination(&cw->msg); + bool valid_dest; + unsigned int i; + + valid_dest = cec_msg_is_broadcast(&cw->msg); + if (!valid_dest) + valid_dest = vivid_cec_find_dest_adap(dev, adap, dest); + + cw->tx_status = valid_dest ? CEC_TX_STATUS_OK : CEC_TX_STATUS_NACK; + spin_lock(&dev->cec_slock); + dev->cec_xfer_time_jiffies = 0; + dev->cec_xfer_start_jiffies = 0; + list_del(&cw->list); + spin_unlock(&dev->cec_slock); + cec_transmit_done(cw->adap, cw->tx_status, 0, valid_dest ? 0 : 1, 0, 0); + + /* Broadcast message */ + if (adap != dev->cec_rx_adap) + cec_received_msg(dev->cec_rx_adap, &cw->msg); + for (i = 0; i < MAX_OUTPUTS && dev->cec_tx_adap[i]; i++) + if (adap != dev->cec_tx_adap[i]) + cec_received_msg(dev->cec_tx_adap[i], &cw->msg); + kfree(cw); +} + +static void vivid_cec_xfer_try_worker(struct work_struct *work) +{ + struct vivid_cec_work *cw = + container_of(work, struct vivid_cec_work, work.work); + struct vivid_dev *dev = cw->dev; + + spin_lock(&dev->cec_slock); + if (dev->cec_xfer_time_jiffies) { + list_del(&cw->list); + spin_unlock(&dev->cec_slock); + cec_transmit_done(cw->adap, CEC_TX_STATUS_ARB_LOST, 1, 0, 0, 0); + kfree(cw); + } else { + INIT_DELAYED_WORK(&cw->work, vivid_cec_xfer_done_worker); + dev->cec_xfer_start_jiffies = jiffies; + dev->cec_xfer_time_jiffies = usecs_to_jiffies(cw->usecs); + spin_unlock(&dev->cec_slock); + schedule_delayed_work(&cw->work, dev->cec_xfer_time_jiffies); + } +} + +static int vivid_cec_adap_enable(struct cec_adapter *adap, bool enable) +{ + return 0; +} + +static int vivid_cec_adap_log_addr(struct cec_adapter *adap, u8 log_addr) +{ + return 0; +} + +/* + * One data bit takes 2400 us, each byte needs 10 bits so that's 24000 us + * per byte. + */ +#define USECS_PER_BYTE 24000 + +static int vivid_cec_adap_transmit(struct cec_adapter *adap, u8 attempts, + u32 signal_free_time, struct cec_msg *msg) +{ + struct vivid_dev *dev = adap->priv; + struct vivid_cec_work *cw = kzalloc(sizeof(*cw), GFP_KERNEL); + long delta_jiffies = 0; + + if (cw == NULL) + return -ENOMEM; + cw->dev = dev; + cw->adap = adap; + cw->usecs = CEC_FREE_TIME_TO_USEC(signal_free_time) + + msg->len * USECS_PER_BYTE; + cw->msg = *msg; + + spin_lock(&dev->cec_slock); + list_add(&cw->list, &dev->cec_work_list); + if (dev->cec_xfer_time_jiffies == 0) { + INIT_DELAYED_WORK(&cw->work, vivid_cec_xfer_done_worker); + dev->cec_xfer_start_jiffies = jiffies; + dev->cec_xfer_time_jiffies = usecs_to_jiffies(cw->usecs); + delta_jiffies = dev->cec_xfer_time_jiffies; + } else { + INIT_DELAYED_WORK(&cw->work, vivid_cec_xfer_try_worker); + delta_jiffies = dev->cec_xfer_start_jiffies + + dev->cec_xfer_time_jiffies - jiffies; + } + spin_unlock(&dev->cec_slock); + schedule_delayed_work(&cw->work, delta_jiffies < 0 ? 0 : delta_jiffies); + return 0; +} + +static int vivid_received(struct cec_adapter *adap, struct cec_msg *msg) +{ + struct vivid_dev *dev = adap->priv; + struct cec_msg reply; + u8 dest = cec_msg_destination(msg); + u16 pa; + u8 disp_ctl; + char osd[14]; + + if (cec_msg_is_broadcast(msg)) + dest = adap->log_addrs.log_addr[0]; + cec_msg_init(&reply, dest, cec_msg_initiator(msg)); + + switch (cec_msg_opcode(msg)) { + case CEC_MSG_SET_STREAM_PATH: + if (cec_is_sink(adap)) + return -ENOMSG; + cec_ops_set_stream_path(msg, &pa); + if (pa != adap->phys_addr) + return -ENOMSG; + cec_msg_active_source(&reply, adap->phys_addr); + cec_transmit_msg(adap, &reply, false); + break; + case CEC_MSG_SET_OSD_STRING: + if (!cec_is_sink(adap)) + return -ENOMSG; + cec_ops_set_osd_string(msg, &disp_ctl, osd); + switch (disp_ctl) { + case CEC_OP_DISP_CTL_DEFAULT: + strcpy(dev->osd, osd); + dev->osd_jiffies = jiffies; + break; + case CEC_OP_DISP_CTL_UNTIL_CLEARED: + strcpy(dev->osd, osd); + dev->osd_jiffies = 0; + break; + case CEC_OP_DISP_CTL_CLEAR: + dev->osd[0] = 0; + dev->osd_jiffies = 0; + break; + default: + cec_msg_feature_abort(&reply, cec_msg_opcode(msg), + CEC_OP_ABORT_INVALID_OP); + cec_transmit_msg(adap, &reply, false); + break; + } + break; + default: + return -ENOMSG; + } + return 0; +} + +static const struct cec_adap_ops vivid_cec_adap_ops = { + .adap_enable = vivid_cec_adap_enable, + .adap_log_addr = vivid_cec_adap_log_addr, + .adap_transmit = vivid_cec_adap_transmit, + .received = vivid_received, +}; + +struct cec_adapter *vivid_cec_alloc_adap(struct vivid_dev *dev, + unsigned int idx, + struct device *parent, + bool is_source) +{ + char name[sizeof(dev->vid_out_dev.name) + 2]; + u32 caps = CEC_CAP_TRANSMIT | CEC_CAP_LOG_ADDRS | + CEC_CAP_PASSTHROUGH | CEC_CAP_RC | CEC_CAP_MONITOR_ALL; + + snprintf(name, sizeof(name), "%s%d", + is_source ? dev->vid_out_dev.name : dev->vid_cap_dev.name, + idx); + return cec_allocate_adapter(&vivid_cec_adap_ops, dev, + name, caps, 1, parent); +} diff --git a/pool/shard002/C/0063194_lapacke_zhegvx.c b/pool/shard002/C/0063194_lapacke_zhegvx.c new file mode 100644 index 0000000000000000000000000000000000000000..18e94dd649e857e80d7cf49b76087703f922a6d1 --- /dev/null +++ b/pool/shard002/C/0063194_lapacke_zhegvx.c @@ -0,0 +1,118 @@ +/***************************************************************************** + Copyright (c) 2014, Intel Corp. + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + * Neither the name of Intel Corporation nor the names of its contributors + may be used to endorse or promote products derived from this software + without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE + LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + THE POSSIBILITY OF SUCH DAMAGE. +***************************************************************************** +* Contents: Native high-level C interface to LAPACK function zhegvx +* Author: Intel Corporation +* Generated November 2015 +*****************************************************************************/ + +#include "lapacke_utils.h" + +lapack_int LAPACKE_zhegvx( int matrix_layout, lapack_int itype, char jobz, + char range, char uplo, lapack_int n, + lapack_complex_double* a, lapack_int lda, + lapack_complex_double* b, lapack_int ldb, double vl, + double vu, lapack_int il, lapack_int iu, + double abstol, lapack_int* m, double* w, + lapack_complex_double* z, lapack_int ldz, + lapack_int* ifail ) +{ + lapack_int info = 0; + lapack_int lwork = -1; + lapack_int* iwork = NULL; + double* rwork = NULL; + lapack_complex_double* work = NULL; + lapack_complex_double work_query; + if( matrix_layout != LAPACK_COL_MAJOR && matrix_layout != LAPACK_ROW_MAJOR ) { + LAPACKE_xerbla( "LAPACKE_zhegvx", -1 ); + return -1; + } +#ifndef LAPACK_DISABLE_NAN_CHECK + /* Optionally check input matrices for NaNs */ + if( LAPACKE_zhe_nancheck( matrix_layout, uplo, n, a, lda ) ) { + return -7; + } + if( LAPACKE_d_nancheck( 1, &abstol, 1 ) ) { + return -15; + } + if( LAPACKE_zge_nancheck( matrix_layout, n, n, b, ldb ) ) { + return -9; + } + if( LAPACKE_lsame( range, 'v' ) ) { + if( LAPACKE_d_nancheck( 1, &vl, 1 ) ) { + return -11; + } + } + if( LAPACKE_lsame( range, 'v' ) ) { + if( LAPACKE_d_nancheck( 1, &vu, 1 ) ) { + return -12; + } + } +#endif + /* Allocate memory for working array(s) */ + iwork = (lapack_int*)LAPACKE_malloc( sizeof(lapack_int) * MAX(1,5*n) ); + if( iwork == NULL ) { + info = LAPACK_WORK_MEMORY_ERROR; + goto exit_level_0; + } + rwork = (double*)LAPACKE_malloc( sizeof(double) * MAX(1,7*n) ); + if( rwork == NULL ) { + info = LAPACK_WORK_MEMORY_ERROR; + goto exit_level_1; + } + /* Query optimal working array(s) size */ + info = LAPACKE_zhegvx_work( matrix_layout, itype, jobz, range, uplo, n, a, + lda, b, ldb, vl, vu, il, iu, abstol, m, w, z, + ldz, &work_query, lwork, rwork, iwork, ifail ); + if( info != 0 ) { + goto exit_level_2; + } + lwork = LAPACK_Z2INT( work_query ); + /* Allocate memory for work arrays */ + work = (lapack_complex_double*) + LAPACKE_malloc( sizeof(lapack_complex_double) * lwork ); + if( work == NULL ) { + info = LAPACK_WORK_MEMORY_ERROR; + goto exit_level_2; + } + /* Call middle-level interface */ + info = LAPACKE_zhegvx_work( matrix_layout, itype, jobz, range, uplo, n, a, + lda, b, ldb, vl, vu, il, iu, abstol, m, w, z, + ldz, work, lwork, rwork, iwork, ifail ); + /* Release memory and exit */ + LAPACKE_free( work ); +exit_level_2: + LAPACKE_free( rwork ); +exit_level_1: + LAPACKE_free( iwork ); +exit_level_0: + if( info == LAPACK_WORK_MEMORY_ERROR ) { + LAPACKE_xerbla( "LAPACKE_zhegvx", info ); + } + return info; +} diff --git a/pool/shard002/C/0063215_stream.c b/pool/shard002/C/0063215_stream.c new file mode 100644 index 0000000000000000000000000000000000000000..c29a5ca6005e389f172eba2c6eaecda1a26991f9 --- /dev/null +++ b/pool/shard002/C/0063215_stream.c @@ -0,0 +1,104 @@ +#include "stream.h" + +#include +#include + +#include +#include + +#include "sys-mmap.h" + +#ifndef O_BINARY +# define O_BINARY 0 +#endif + +int stream_open(stream *f, buffer *fn) { + struct stat st; +#ifdef HAVE_MMAP + int fd; +#elif defined __WIN32 + HANDLE *fh, *mh; + void *p; +#endif + + f->start = NULL; + + if (-1 == stat(fn->ptr, &st)) { + return -1; + } + + f->size = st.st_size; + +#ifdef HAVE_MMAP + if (-1 == (fd = open(fn->ptr, O_RDONLY | O_BINARY))) { + return -1; + } + + f->start = mmap(NULL, f->size, PROT_READ, MAP_SHARED, fd, 0); + + close(fd); + + if (MAP_FAILED == f->start) { + return -1; + } + +#elif defined __WIN32 + fh = CreateFile(fn->ptr, + GENERIC_READ, + FILE_SHARE_READ, + NULL, + OPEN_EXISTING, + FILE_ATTRIBUTE_READONLY, + NULL); + + if (!fh) return -1; + + mh = CreateFileMapping( fh, + NULL, + PAGE_READONLY, + (sizeof(off_t) > 4) ? f->size >> 32 : 0, + f->size & 0xffffffff, + NULL); + + if (!mh) { +/* + LPVOID lpMsgBuf; + FormatMessage( + FORMAT_MESSAGE_ALLOCATE_BUFFER | + FORMAT_MESSAGE_FROM_SYSTEM, + NULL, + GetLastError(), + MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), + (LPTSTR) &lpMsgBuf, + 0, NULL ); +*/ + return -1; + } + + p = MapViewOfFile(mh, + FILE_MAP_READ, + 0, + 0, + 0); + CloseHandle(mh); + CloseHandle(fh); + + f->start = p; +#else +# error no mmap found +#endif + + return 0; +} + +int stream_close(stream *f) { +#ifdef HAVE_MMAP + if (f->start) munmap(f->start, f->size); +#elif defined(__WIN32) + if (f->start) UnmapViewOfFile(f->start); +#endif + + f->start = NULL; + + return 0; +} diff --git a/pool/shard002/C/0063228_custom.c b/pool/shard002/C/0063228_custom.c new file mode 100644 index 0000000000000000000000000000000000000000..0c9e49c8ffeb591a9ff30dfdd7c890e80fae7997 --- /dev/null +++ b/pool/shard002/C/0063228_custom.c @@ -0,0 +1,216 @@ +/* + * custom - interface for custom software and hardware interfaces + * + * Copyright (C) 1999 Landon Curt Noll + * + * Calc is open software; you can redistribute it and/or modify it under + * the terms of the version 2.1 of the GNU Lesser General Public License + * as published by the Free Software Foundation. + * + * Calc 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. + * + * A copy of version 2.1 of the GNU Lesser General Public License is + * distributed with calc under the filename COPYING-LGPL. You should have + * received a copy with calc; if not, write to Free Software Foundation, Inc. + * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. + * + * @(#) $Revision: 29.4 $ + * @(#) $Id: custom.c,v 29.4 2004/02/25 23:54:40 chongo Exp $ + * @(#) $Source: /usr/local/src/cmd/calc/custom/../RCS/custom.c,v $ + * + * Under source code control: 1997/03/03 04:53:08 + * File existed as early as: 1997 + * + * chongo /\oo/\ http://www.isthe.com/chongo/ + * Share and enjoy! :-) http://www.isthe.com/chongo/tech/comp/calc/ + */ + + +/* these include files are needed regardless of CUSTOM */ +#include "have_const.h" +#include "value.h" +#include "custom.h" + +#include + +#if defined(CUSTOM) + +#include "calc.h" + +#include "have_string.h" +#ifdef HAVE_STRING_H +# include +#endif + +#else /* CUSTOM */ + +#include "config.h" + +#endif /* CUSTOM */ + +BOOL allow_custom = FALSE; /* TRUE => custom builtins allowed */ + + +/* + * custom - custom callout function + */ +/*ARGSUSED*/ +VALUE +custom(char *name, int count, VALUE **vals) +{ +#if defined(CUSTOM) + + CONST struct custom *p; /* current function */ + + /* + * search the custom interface table for a function + */ + for (p = cust; p->name != NULL; ++p) { + + /* look for the first match */ + if (strcmp(name, p->name) == 0) { + + /* arg count check */ + if (count < p->minargs) { + math_error("Too few arguments for custom " + "function \"%s\"", p->name); + /*NOTREACHED*/ + } + if (count > p->maxargs) { + math_error("Too many arguments for custom " + "function \"%s\"", p->name); + /*NOTREACHED*/ + } + + /* call the custom function */ + return p->func(name, count, vals); + } + } + + /* + * no such custom function + */ + return error_value(E_UNK_CUSTOM); + +#else /* CUSTOM */ + + fprintf(stderr, + "%sCalc was built with custom functions disabled\n", + (conf->tab_ok ? "\t" : "")); + return error_value(E_NO_CUSTOM); + +#endif /* CUSTOM */ +} + + +/* + * showcustom - display the names and brief descriptins of custom functions + */ +/*ARGSUSED*/ +void +showcustom(void) +{ +#if defined(CUSTOM) + + CONST struct custom *p; /* current function */ + + /* + * disable custom functions unless -C was given + */ + if (!allow_custom) { + fprintf(stderr, + "%sCalc must be run with a -C argument to " + "show custom functions\n", + (conf->tab_ok ? "\t" : "")); + return; + } + + /* + * print header + */ + printf("\nName\tArgs\tDescription\n\n"); + for (p = cust; p->name != NULL; ++p) { + printf("%-9s ", p->name); + if (p->maxargs == MAX_CUSTOM_ARGS) + printf("%d+ ", p->minargs); + else if (p->minargs == p->maxargs) + printf("%-6d", p->minargs); + else + printf("%d-%-4d", p->minargs, p->maxargs); + printf("%s\n", p->desc); + } + printf("\n"); + +#else /* CUSTOM */ + + fprintf(stderr, + "%sCalc was built with custom functions disabled\n", + (conf->tab_ok ? "\t" : "")); + +#endif /* CUSTOM */ +} + + +/* + * customhelp - standard help interface to a custom function + * + * This function assumes that a help file with the same name as + * the custom function has been installed by the custom/Makefile + * (as listed in the CUSTOM_HELP makefile variable) under the + * CUSTOMHELPDIR == HELPDIR/custhelp directory. + * + * The help command first does a search in HELPDIR and later + * in CUSTOMHELPDIR. If a custom help file has the same name + * as a file under HELPDIR then help will display the HELPDIR + * file and NOT the custom file. This function will ignore + * and HELPDIR file and work directly with the custom help file. + * + * given: + * name name of the custom help file to directly access + */ +/*ARGSUSED*/ +void +customhelp(char *name) +{ +#if defined(CUSTOM) + + char *customname; /* a string of the form: custom/name */ + + /* + * firewall + */ + if (name == NULL) { + name = "help"; + } + + /* + * form the custom help name + */ + customname = (char *)malloc(sizeof("custhelp")+strlen(name)+1); + if (customname == NULL) { + math_error("bad malloc of customname"); + /*NOTREACHED*/ + } + sprintf(customname, "custhelp/%s", name); + + /* + * give help directly to the custom file + */ + givehelp(customname); + + /* + * all done + */ + free(customname); + +#else /* CUSTOM */ + + fprintf(stderr, + "%sCalc was built with custom functions disabled\n", + (conf->tab_ok ? "\t" : "")); + +#endif /* CUSTOM */ +} diff --git a/pool/shard002/C/0063231_QueueCtl.c b/pool/shard002/C/0063231_QueueCtl.c new file mode 100644 index 0000000000000000000000000000000000000000..5c1e4d0988fd4af8d5fe44fb0345d3bdcbaee7d4 --- /dev/null +++ b/pool/shard002/C/0063231_QueueCtl.c @@ -0,0 +1,158 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "myargs.h" + +//type: +//1:check a job +//2:cancel a job +//3:cancel all jobs +//4:list all jobs + +struct u_packet_info +{ + struct nlmsghdr hdr; + char msg[40000]; +}; +int qctl(struct request *req) { + struct sockaddr_nl local; + struct sockaddr_nl kpeer; + int skfd, kpeerlen = sizeof(struct sockaddr_nl); + struct nlmsghdr *message; + struct u_packet_info info; + char *retval; + int ret; + message = (struct nlmsghdr *)malloc(1); + + skfd = socket(PF_NETLINK, SOCK_RAW, 22); + if (skfd < 0) { + printf("can not create a netlink socket\n"); + return -1; + } + + memset(&local, 0, sizeof(local)); + local.nl_family = AF_NETLINK; + local.nl_pid = getpid(); + local.nl_groups = 0; + if (bind(skfd, (struct sockaddr *)&local, sizeof(local)) != 0) { + printf("bind() error\n"); + return -1; + } + memset(&kpeer, 0, sizeof(kpeer)); + kpeer.nl_family = AF_NETLINK; + kpeer.nl_pid = 0; + kpeer.nl_groups = 0; + + memset(message, '\0', sizeof(struct nlmsghdr)); + message->nlmsg_len = NLMSG_SPACE(sizeof(struct request)); + message->nlmsg_flags = 0; + message->nlmsg_type = 0; + message->nlmsg_seq = 0; + message->nlmsg_pid = local.nl_pid; + + retval = memcpy(NLMSG_DATA(message), req, sizeof(struct request)); + //printf("message sendto kernel are:%s, len:%d\n", (char *)NLMSG_DATA(message), message->nlmsg_len); + ret = sendto(skfd, message, message->nlmsg_len, 0, (struct sockaddr *)&kpeer, sizeof(kpeer)); + if (!ret) { + printf("send message failed\n"); + return -1; + } + + ret = recvfrom(skfd, &info, sizeof(struct u_packet_info), 0, (struct sockaddr *)&kpeer, (socklen_t *)&kpeerlen); + if (!ret) { + printf("receive message failed\n"); + return -1; + } + + printf("message receive from kernel:\n%s\n", (char *)info.msg); + close(skfd); + if (((char *)info.msg)[0]=='f' && ((char *)info.msg)[1]=='i' && ((char *)info.msg)[2]=='n') { + return 1;//finished + } else if (((char *)info.msg)[0]=='e' && ((char *)info.msg)[1]=='r' && ((char *)info.msg)[2]=='r') { + return 2;//error + } else { + return 0;//not finished + } +} +int main(int argc, char **argv) +{ + int ret; + char c; + struct request *req = malloc(sizeof(struct request)); + int pid = 0; + long job_id = 0L; + //4 list all + //2 remove one + //3 cancel all + //1 query one + int type = 0; + int index; + + if(argc <= 1){ + printf("use -h to see help infomation\n"); + goto out; + } + + // process en/decrypt, (de)compress or checksum + while ((c = getopt (argc, argv, "hlrcq")) != -1){ + switch (c) + { + case 'h': + printf("-q : check status of a job, following pid and job id\n\ + -l : list all jobs, includes errors\n\ + -r : remove a job, following pid and job id\n\ + -c : cancel all jobs, empty error list\n"); + goto out; + break; + case 'l': + type = 4; + break; + case 'r': + type = 2; + break; + case 'c': + type = 3; + break; + case 'q': + type = 1; + break; + default: + printf("wrong parameters, use -h to see help document\n"); + goto out; + } + } + + index = optind; + + //4 list all + //2 remove one + //3 cancel all + //1 query one + if((type == 1 || type == 2) && index > argc - 2){ + printf("wrong parameter, please specify pid and job id to check/remove a job\n"); + goto out; + } + if(type == 1 || type == 2){ + pid = atoi(argv[index]); + index ++; + job_id = atol(argv[index]); + index ++; + } + + req->type = type; + req->pid = pid; + req->job_id = job_id; + ret = qctl(req); + +out: + return 0; + + +} diff --git a/pool/shard002/C/0063234_aarch64-common.c b/pool/shard002/C/0063234_aarch64-common.c new file mode 100644 index 0000000000000000000000000000000000000000..a0b7f486652ca0b6b043f8a858bde66847fe5359 --- /dev/null +++ b/pool/shard002/C/0063234_aarch64-common.c @@ -0,0 +1,343 @@ +/* Common hooks for AArch64. + Copyright (C) 2012-2017 Free Software Foundation, Inc. + Contributed by ARM Ltd. + + 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" +#define INCLUDE_STRING +#include "system.h" +#include "coretypes.h" +#include "tm.h" +#include "memmodel.h" +#include "tm_p.h" +#include "common/common-target.h" +#include "common/common-target-def.h" +#include "opts.h" +#include "flags.h" +#include "diagnostic.h" + +#ifdef TARGET_BIG_ENDIAN_DEFAULT +#undef TARGET_DEFAULT_TARGET_FLAGS +#define TARGET_DEFAULT_TARGET_FLAGS (MASK_BIG_END) +#endif + +#undef TARGET_HANDLE_OPTION +#define TARGET_HANDLE_OPTION aarch64_handle_option + +#undef TARGET_OPTION_OPTIMIZATION_TABLE +#define TARGET_OPTION_OPTIMIZATION_TABLE aarch_option_optimization_table + +/* Set default optimization options. */ +static const struct default_options aarch_option_optimization_table[] = + { + /* Enable section anchors by default at -O1 or higher. */ + { OPT_LEVELS_1_PLUS, OPT_fsection_anchors, NULL, 1 }, + /* Enable -fsched-pressure by default when optimizing. */ + { OPT_LEVELS_1_PLUS, OPT_fsched_pressure, NULL, 1 }, + /* Enable redundant extension instructions removal at -O2 and higher. */ + { OPT_LEVELS_2_PLUS, OPT_free, NULL, 1 }, + { OPT_LEVELS_NONE, 0, NULL, 0 } + }; + +/* Implement TARGET_HANDLE_OPTION. + This function handles the target specific options for CPU/target selection. + + -mcpu=CPU is shorthand for -march=ARCH_FOR_CPU, -mtune=CPU. + If either of -march or -mtune is given, they override their + respective component of -mcpu. This logic is implemented + in config/aarch64/aarch64.c:aarch64_override_options. */ + +bool +aarch64_handle_option (struct gcc_options *opts, + struct gcc_options *opts_set ATTRIBUTE_UNUSED, + const struct cl_decoded_option *decoded, + location_t loc ATTRIBUTE_UNUSED) +{ + size_t code = decoded->opt_index; + const char *arg = decoded->arg; + int val = decoded->value; + + switch (code) + { + case OPT_march_: + opts->x_aarch64_arch_string = arg; + return true; + + case OPT_mcpu_: + opts->x_aarch64_cpu_string = arg; + return true; + + case OPT_mtune_: + opts->x_aarch64_tune_string = arg; + return true; + + case OPT_mgeneral_regs_only: + opts->x_target_flags |= MASK_GENERAL_REGS_ONLY; + return true; + + case OPT_mfix_cortex_a53_835769: + opts->x_aarch64_fix_a53_err835769 = val; + return true; + + case OPT_mstrict_align: + opts->x_target_flags |= MASK_STRICT_ALIGN; + return true; + + case OPT_momit_leaf_frame_pointer: + opts->x_flag_omit_leaf_frame_pointer = val; + return true; + + default: + return true; + } +} + +struct gcc_targetm_common targetm_common = TARGETM_COMMON_INITIALIZER; + +/* An ISA extension in the co-processor and main instruction set space. */ +struct aarch64_option_extension +{ + const char *const name; + const unsigned long flag_canonical; + const unsigned long flags_on; + const unsigned long flags_off; +}; + +/* ISA extensions in AArch64. */ +static const struct aarch64_option_extension all_extensions[] = +{ +#define AARCH64_OPT_EXTENSION(NAME, FLAG_CANONICAL, FLAGS_ON, FLAGS_OFF, Z) \ + {NAME, FLAG_CANONICAL, FLAGS_ON, FLAGS_OFF}, +#include "config/aarch64/aarch64-option-extensions.def" + {NULL, 0, 0, 0} +}; + +struct processor_name_to_arch +{ + const std::string processor_name; + const enum aarch64_arch arch; + const unsigned long flags; +}; + +struct arch_to_arch_name +{ + const enum aarch64_arch arch; + const std::string arch_name; + const unsigned long flags; +}; + +/* Map processor names to the architecture revision they implement and + the default set of architectural feature flags they support. */ +static const struct processor_name_to_arch all_cores[] = +{ +#define AARCH64_CORE(NAME, X, IDENT, ARCH_IDENT, FLAGS, COSTS, IMP, PART, VARIANT) \ + {NAME, AARCH64_ARCH_##ARCH_IDENT, FLAGS}, +#include "config/aarch64/aarch64-cores.def" + {"generic", AARCH64_ARCH_8A, AARCH64_FL_FOR_ARCH8}, + {"", aarch64_no_arch, 0} +}; + +/* Map architecture revisions to their string representation. */ +static const struct arch_to_arch_name all_architectures[] = +{ +#define AARCH64_ARCH(NAME, CORE, ARCH_IDENT, ARCH, FLAGS) \ + {AARCH64_ARCH_##ARCH_IDENT, NAME, FLAGS}, +#include "config/aarch64/aarch64-arches.def" + {aarch64_no_arch, "", 0} +}; + +/* Parse the architecture extension string STR and update ISA_FLAGS + with the architecture features turned on or off. Return a + aarch64_parse_opt_result describing the result. */ + +enum aarch64_parse_opt_result +aarch64_parse_extension (const char *str, unsigned long *isa_flags) +{ + /* The extension string is parsed left to right. */ + const struct aarch64_option_extension *opt = NULL; + + /* Flag to say whether we are adding or removing an extension. */ + int adding_ext = -1; + + while (str != NULL && *str != 0) + { + const char *ext; + size_t len; + + str++; + ext = strchr (str, '+'); + + if (ext != NULL) + len = ext - str; + else + len = strlen (str); + + if (len >= 2 && strncmp (str, "no", 2) == 0) + { + adding_ext = 0; + len -= 2; + str += 2; + } + else if (len > 0) + adding_ext = 1; + + if (len == 0) + return AARCH64_PARSE_MISSING_ARG; + + + /* Scan over the extensions table trying to find an exact match. */ + for (opt = all_extensions; opt->name != NULL; opt++) + { + if (strlen (opt->name) == len && strncmp (opt->name, str, len) == 0) + { + /* Add or remove the extension. */ + if (adding_ext) + *isa_flags |= (opt->flags_on | opt->flag_canonical); + else + *isa_flags &= ~(opt->flags_off | opt->flag_canonical); + break; + } + } + + if (opt->name == NULL) + { + /* Extension not found in list. */ + return AARCH64_PARSE_INVALID_FEATURE; + } + + str = ext; + }; + + return AARCH64_PARSE_OK; +} + +/* Return a string representation of ISA_FLAGS. DEFAULT_ARCH_FLAGS + gives the default set of flags which are implied by whatever -march + we'd put out. Our job is to figure out the minimal set of "+" and + "+no" feature flags to put out, and to put them out grouped such + that all the "+" flags come before the "+no" flags. */ + +std::string +aarch64_get_extension_string_for_isa_flags (unsigned long isa_flags, + unsigned long default_arch_flags) +{ + const struct aarch64_option_extension *opt = NULL; + std::string outstr = ""; + + /* Pass one: Find all the things we need to turn on. As a special case, + we always want to put out +crc if it is enabled. */ + for (opt = all_extensions; opt->name != NULL; opt++) + if ((isa_flags & opt->flag_canonical + && !(default_arch_flags & opt->flag_canonical)) + || (default_arch_flags & opt->flag_canonical + && opt->flag_canonical == AARCH64_ISA_CRC)) + { + outstr += "+"; + outstr += opt->name; + } + + /* Pass two: Find all the things we need to turn off. */ + for (opt = all_extensions; opt->name != NULL; opt++) + if ((~isa_flags) & opt->flag_canonical + && !((~default_arch_flags) & opt->flag_canonical)) + { + outstr += "+no"; + outstr += opt->name; + } + + return outstr; +} + +/* Attempt to rewrite NAME, which has been passed on the command line + as a -mcpu option to an equivalent -march value. If we can do so, + return the new string, otherwise return an error. */ + +const char * +aarch64_rewrite_selected_cpu (const char *name) +{ + std::string original_string (name); + std::string extension_str; + std::string processor; + size_t extension_pos = original_string.find_first_of ('+'); + + /* Strip and save the extension string. */ + if (extension_pos != std::string::npos) + { + processor = original_string.substr (0, extension_pos); + extension_str = original_string.substr (extension_pos, + std::string::npos); + } + else + { + /* No extensions. */ + processor = original_string; + } + + const struct processor_name_to_arch* p_to_a; + for (p_to_a = all_cores; + p_to_a->arch != aarch64_no_arch; + p_to_a++) + { + if (p_to_a->processor_name == processor) + break; + } + + const struct arch_to_arch_name* a_to_an; + for (a_to_an = all_architectures; + a_to_an->arch != aarch64_no_arch; + a_to_an++) + { + if (a_to_an->arch == p_to_a->arch) + break; + } + + /* We couldn't find that proceesor name, or the processor name we + found does not map to an architecture we understand. */ + if (p_to_a->arch == aarch64_no_arch + || a_to_an->arch == aarch64_no_arch) + fatal_error (input_location, "unknown value %qs for -mcpu", name); + + unsigned long extensions = p_to_a->flags; + aarch64_parse_extension (extension_str.c_str (), &extensions); + + std::string outstr = a_to_an->arch_name + + aarch64_get_extension_string_for_isa_flags (extensions, + a_to_an->flags); + + /* We are going to memory leak here, nobody elsewhere + in the callchain is going to clean up after us. The alternative is + to allocate a static buffer, and assert that it is big enough for our + modified string, which seems much worse! */ + return xstrdup (outstr.c_str ()); +} + +/* Called by the driver to rewrite a name passed to the -mcpu + argument in preparation to be passed to the assembler. The + names passed from the commend line will be in ARGV, we want + to use the right-most argument, which should be in + ARGV[ARGC - 1]. ARGC should always be greater than 0. */ + +const char * +aarch64_rewrite_mcpu (int argc, const char **argv) +{ + gcc_assert (argc); + return aarch64_rewrite_selected_cpu (argv[argc - 1]); +} + +#undef AARCH64_CPU_NAME_LENGTH + diff --git a/pool/shard002/C/0063239_gnunet-core.c b/pool/shard002/C/0063239_gnunet-core.c new file mode 100644 index 0000000000000000000000000000000000000000..17b840480dbbc713fc7043d6f75d226389af5b3d --- /dev/null +++ b/pool/shard002/C/0063239_gnunet-core.c @@ -0,0 +1,233 @@ +/* + This file is part of GNUnet. + (C) 2011, 2012 Christian Grothoff (and other contributing authors) + + 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., 59 Temple Place - Suite 330, + Boston, MA 02111-1307, USA. +*/ + +/** + * @file core/gnunet-core.c + * @brief Print information about other known _connected_ peers. + * @author Nathan Evans + */ +#include "platform.h" +#include "gnunet_crypto_lib.h" +#include "gnunet_configuration_lib.h" +#include "gnunet_getopt_lib.h" +#include "gnunet_peerinfo_service.h" +#include "gnunet_transport_service.h" +#include "gnunet_core_service.h" +#include "gnunet_program_lib.h" + +/** + * Option -m. + */ +static int monitor_connections; + +/** + * Current number of connections in monitor mode + */ +static int monitor_connections_counter; + +static struct GNUNET_CORE_Handle *ch; + +static struct GNUNET_PeerIdentity my_id; + +/** + * Task run in monitor mode when the user presses CTRL-C to abort. + * Stops monitoring activity. + * + * @param cls the 'struct GNUNET_TRANSPORT_PeerIterateContext *' + * @param tc scheduler context + */ +static void +shutdown_task (void *cls, + const struct GNUNET_SCHEDULER_TaskContext *tc) +{ + if (NULL != ch) + { + GNUNET_CORE_disconnect (ch); + ch = NULL; + } +} + + +/** + * Callback for retrieving a list of connected peers. + * + * @param cls closure (unused) + * @param peer peer identity this notification is about + * @param atsi performance data for the connection + * @param atsi_count number of records in 'atsi' + */ +static void +connected_peer_callback (void *cls, const struct GNUNET_PeerIdentity *peer, + const struct GNUNET_ATS_Information *atsi, + unsigned int atsi_count) +{ + struct GNUNET_CRYPTO_HashAsciiEncoded enc; + + if (NULL == peer) + return; + GNUNET_CRYPTO_hash_to_enc (&peer->hashPubKey, &enc); + printf (_("Peer `%s'\n"), (const char *) &enc); +} + +void +monitor_notify_startup (void *cls, + struct GNUNET_CORE_Handle * server, + const struct GNUNET_PeerIdentity * + my_identity) +{ + my_id = (*my_identity); +} + + +/** + * Function called to notify core users that another + * peer connected to us. + * + * @param cls closure + * @param peer the peer that connected + * @param ats performance data + * @param ats_count number of entries in ats (excluding 0-termination) + */ +static void +monitor_notify_connect (void *cls, const struct GNUNET_PeerIdentity *peer, + const struct GNUNET_ATS_Information *ats, uint32_t ats_count) +{ + struct GNUNET_TIME_Absolute now = GNUNET_TIME_absolute_get(); + const char *now_str; + + if (0 != memcmp (&my_id, peer, sizeof (my_id))) + { + monitor_connections_counter ++; + now_str = GNUNET_STRINGS_absolute_time_to_string (now); + FPRINTF (stdout, _("%24s: %-17s %4s (%u connections in total)\n"), + now_str, + _("Connected to"), + GNUNET_i2s (peer), + monitor_connections_counter); + } +} + + +/** + * Function called to notify core users that another + * peer disconnected from us. + * + * @param cls closure + * @param peer the peer that disconnected + */ +static void +monitor_notify_disconnect (void *cls, const struct GNUNET_PeerIdentity *peer) +{ + struct GNUNET_TIME_Absolute now = GNUNET_TIME_absolute_get(); + const char *now_str; + + if (0 != memcmp (&my_id, peer, sizeof (my_id))) + { + now_str = GNUNET_STRINGS_absolute_time_to_string (now); + + GNUNET_assert (monitor_connections_counter > 0); + monitor_connections_counter--; + FPRINTF (stdout, _("%24s: %-17s %4s (%u connections in total)\n"), + now_str, + _("Disconnected from"), + GNUNET_i2s (peer), + monitor_connections_counter); + } +} + + + +/** + * Main function that will be run by the scheduler. + * + * @param cls closure + * @param args remaining command-line arguments + * @param cfgfile name of the configuration file used (for saving, can be NULL!) + * @param cfg configuration + */ +static void +run (void *cls, char *const *args, const char *cfgfile, + const struct GNUNET_CONFIGURATION_Handle *cfg) +{ + static const struct GNUNET_CORE_MessageHandler handlers[] = { + {NULL, 0, 0} + }; + if (args[0] != NULL) + { + FPRINTF (stderr, _("Invalid command line argument `%s'\n"), args[0]); + return; + } + if (GNUNET_NO == monitor_connections) + GNUNET_CORE_iterate_peers (cfg, &connected_peer_callback, NULL); + else + { + memset(&my_id, '\0', sizeof (my_id)); + ch = GNUNET_CORE_connect (cfg, NULL, + monitor_notify_startup, + monitor_notify_connect, + monitor_notify_disconnect, + NULL, GNUNET_NO, + NULL, GNUNET_NO, + handlers); + + if (NULL == ch) + GNUNET_SCHEDULER_add_now (shutdown_task, NULL); + else + GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL, shutdown_task, NULL); + } +} + + +/** + * The main function to obtain peer information. + * + * @param argc number of arguments from the command line + * @param argv command line arguments + * @return 0 ok, 1 on error + */ +int +main (int argc, char *const *argv) +{ + int res; + static const struct GNUNET_GETOPT_CommandLineOption options[] = { + {'m', "monitor", NULL, + gettext_noop ("provide information about all current connections (continuously)"), + 0, &GNUNET_GETOPT_set_one, &monitor_connections}, + GNUNET_GETOPT_OPTION_END + }; + + if (GNUNET_OK != GNUNET_STRINGS_get_utf8_args (argc, argv, &argc, &argv)) + return 2; + + + res = GNUNET_PROGRAM_run (argc, argv, "gnunet-core", + gettext_noop + ("Print information about connected peers."), + options, &run, NULL); + + GNUNET_free ((void *) argv); + + if (GNUNET_OK == res) + return 0; + else + return 1; +} + +/* end of gnunet-core.c */ diff --git a/pool/shard002/C/0063251_bsearch.c b/pool/shard002/C/0063251_bsearch.c new file mode 100644 index 0000000000000000000000000000000000000000..f39e54ff49ba5db49bb9e4a6cb9abb5bb724836e --- /dev/null +++ b/pool/shard002/C/0063251_bsearch.c @@ -0,0 +1,37 @@ + +/* + * This file lifted in toto from 'Dlibs' on the atari ST (RdeBath) + * + * + * Dale Schumacher 399 Beacon Ave. + * (alias: Dalnefre') St. Paul, MN 55104 + * dal@syntel.UUCP United States of America + * "It's not reality that's important, but how you perceive things." + */ +#include + +static int _bsearch; /* index of element found, or where to + * insert */ + +char *bsearch(char *key, char *base, int num, int size, + int (*cmp) (char *, char *)) +{ + int a, b, c, dir; + + a = 0; + b = num - 1; + while (a <= b) { + c = (a + b) >> 1; /* == ((a + b) / 2) */ + if ((dir = (*cmp) ((base + (c * size)), key)) != 0) { + if (dir > 0) + b = c - 1; + else /* (dir < 0) */ + a = c + 1; + } else { + _bsearch = c; + return (base + (c * size)); + } + } + _bsearch = b; + return (NULL); +} diff --git a/pool/shard002/C/0063257_msp_serial.c b/pool/shard002/C/0063257_msp_serial.c new file mode 100644 index 0000000000000000000000000000000000000000..696bdc91a81cd57f7f6a22fdabff2714cfe3c655 --- /dev/null +++ b/pool/shard002/C/0063257_msp_serial.c @@ -0,0 +1,154 @@ +/* + * The setup file for serial related hardware on PMC-Sierra MSP processors. + * + * Copyright 2005 PMC-Sierra, 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 SOFTWARE IS PROVIDED ``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. + * + * 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 +#include +#include +#include + +#include +#include +#include + +struct msp_uart_data { + int last_lcr; +}; + +static void msp_serial_out(struct uart_port *p, int offset, int value) +{ + struct msp_uart_data *d = p->private_data; + + if (offset == UART_LCR) + d->last_lcr = value; + + offset <<= p->regshift; + writeb(value, p->membase + offset); +} + +static unsigned int msp_serial_in(struct uart_port *p, int offset) +{ + offset <<= p->regshift; + + return readb(p->membase + offset); +} + +static int msp_serial_handle_irq(struct uart_port *p) +{ + struct msp_uart_data *d = p->private_data; + unsigned int iir = readb(p->membase + (UART_IIR << p->regshift)); + + if (serial8250_handle_irq(p, iir)) { + return 1; + } else if ((iir & UART_IIR_BUSY) == UART_IIR_BUSY) { + /* + + + + + + + + + */ + (void)readb(p->membase + 0xc0); + writeb(d->last_lcr, p->membase + (UART_LCR << p->regshift)); + + return 1; + } + + return 0; +} + +void __init msp_serial_setup(void) +{ + char *s; + char *endp; + struct uart_port up; + unsigned int uartclk; + + memset(&up, 0, sizeof(up)); + + /* */ + s = prom_getenv("uartfreqhz"); + if(!(s && *s && (uartclk = simple_strtoul(s, &endp, 10)) && *endp == 0)) + uartclk = MSP_BASE_BAUD; + ppfinit("UART clock set to %d\n", uartclk); + + /* */ + up.mapbase = MSP_UART0_BASE; + up.membase = ioremap_nocache(up.mapbase, MSP_UART_REG_LEN); + up.irq = MSP_INT_UART0; + up.uartclk = uartclk; + up.regshift = 2; + up.iotype = UPIO_MEM; + up.flags = ASYNC_BOOT_AUTOCONF | ASYNC_SKIP_TEST; + up.type = PORT_16550A; + up.line = 0; + up.serial_out = msp_serial_out; + up.serial_in = msp_serial_in; + up.handle_irq = msp_serial_handle_irq; + up.private_data = kzalloc(sizeof(struct msp_uart_data), GFP_KERNEL); + if (!up.private_data) { + pr_err("failed to allocate uart private data\n"); + return; + } + if (early_serial_setup(&up)) { + kfree(up.private_data); + pr_err("Early serial init of port 0 failed\n"); + } + + /* */ + switch (mips_machtype) { + case MACH_MSP4200_EVAL: + case MACH_MSP4200_GW: + case MACH_MSP4200_FPGA: + case MACH_MSP7120_EVAL: + case MACH_MSP7120_GW: + case MACH_MSP7120_FPGA: + /* */ + *GPIO_CFG2_REG = 0x00002299; + break; + + default: + return; /* */ + } + + up.mapbase = MSP_UART1_BASE; + up.membase = ioremap_nocache(up.mapbase, MSP_UART_REG_LEN); + up.irq = MSP_INT_UART1; + up.line = 1; + up.private_data = (void*)UART1_STATUS_REG; + if (early_serial_setup(&up)) { + kfree(up.private_data); + pr_err("Early serial init of port 1 failed\n"); + } +} diff --git a/pool/shard002/C/0063263_micro-app-aos-ispc.c b/pool/shard002/C/0063263_micro-app-aos-ispc.c new file mode 100644 index 0000000000000000000000000000000000000000..cf6f0f8c246e17c86b67616c12eadb79ece4b37b --- /dev/null +++ b/pool/shard002/C/0063263_micro-app-aos-ispc.c @@ -0,0 +1,197 @@ +#include +#include +#include +#include +#include +#include +#include +#include "micro-app-aos.h" + +#define NPOINTS 10000 +#define NEDGES 10000 + +struct edge edges[NEDGES]; +float pt_data[NPOINTS][3]; +float edge_data[NEDGES]; + +void print_help() { + printf("Usage: \n"); + printf("\t --help print this message and exit \n"); + printf("\t --type Type of graph, must be one of:\n"); + printf("\t\t\t pure_random \n"); + printf("\t\t\t regular_random \n"); + printf("\t\t\t contiguous \n"); + printf("\t\t\t file \n"); + printf("\t --nloops Number of repetitions, must be \n"); + printf("\t at least one. \n"); + printf("\t --file File from which to read graph \n"); +} + +double timer() { + struct timeval tp; + struct timezone tzp; + long i; + + i = gettimeofday(&tp, &tzp); + return ((double)tp.tv_sec) + ((double) tp.tv_usec) * 1e-6; +} + +int graph_init(char* graph_type, char* fname) { + lua_State *L; + int i, j, k, v; + + L = luaL_newstate(); + luaL_openlibs(L); + luaL_loadfile(L, "graph.lua"); + lua_pcall(L, 0, 0, 0); + + lua_getglobal(L, "create_graph"); + lua_pushstring(L, graph_type); + lua_pushinteger(L, NPOINTS); + lua_pushinteger(L, NEDGES); + + if (fname != NULL) { + lua_pushstring(L, fname); + lua_call(L, 4, 1); + } else { + lua_call(L, 3, 1); + } + + /* Table is now sitting at the top of the stack */ + i = 0; + lua_pushnil(L); /* Make sure lua_next starts at beginning */ + while (lua_next(L, -2) != 0) { + // fetch first key + k = lua_tointeger(L, -2); + lua_pushnil(L); + while (lua_next(L, -2) != 0) { // loop over neighbors + lua_pop(L,1); + v = lua_tointeger(L, -1); + + // build edges array here + edges[i].v0 = k - 1; + edges[i].v1 = v - 1; + + for (j = 0; j < 3; j++) { + edges[i].v0_pt_data[j] = 0; + edges[i].v1_pt_data[j] = 0; + } + + i++; + } + lua_pop(L,1); + } + + lua_close(L); + + if (i == 0) { + return -1; + } else { + return 0; + } +} + +int data_init() { + int i; + + for (i = 0; i < NPOINTS; i++) { + pt_data[i][0] = 1; + pt_data[i][1] = 1; + pt_data[i][2] = 1; + } + + return 0; +} + +int edge_data_init() { + int i; + + for (i = 0; i < NEDGES; i++) { + edge_data[i] = 1; + } + + return 0; +} + +int main(int argc, char** argv) { + int i; + int rv; + double time0, time1; + int c, opt_i; + int nloops = 0; + char* gt = ""; + char* fname = ""; + + static struct option long_opts[] = { + {"help", no_argument, 0, 0}, + {"type", required_argument, 0, 0}, + {"nloops", required_argument, 0, 0}, + {"file", required_argument, 0, 0} + }; + + /* Parse command-line arguments */ + while (1) { + c = getopt_long(argc, argv, "", + long_opts, &opt_i); + + if (c == -1) { + break; + } + + if (c == 0) { + switch (opt_i) { + case 0: + print_help(); + exit(0); + case 1: + gt = optarg; + break; + case 2: + nloops = atoi(optarg); + break; + case 3: + fname = optarg; + break; + } + } else { + print_help(); + exit(0); + } + } + + /* check for errors */ + if (gt == NULL || nloops < 1) { + print_help(); + exit(0); + } + + + // initialize data structures + rv = graph_init(gt, fname); + if (rv < 0) { + printf("Error creating graph. \n"); + exit(0); + } + + data_init(); + edge_data_init(); + + // loop + time0 = timer(); + for (i = 0; i < nloops; i++) { + edge_gather(NEDGES, edges, pt_data, edge_data); + edge_compute(NEDGES, edges); + edge_scatter(NEDGES, edges, pt_data); + } + time1 = timer(); + + + // print results + for (i = 0; i < 10; i++) { + printf("%i : %f %f %f \n", i, pt_data[i][0], pt_data[i][1], pt_data[i][2]); + } + + printf("Time: %f s \n", (time1 - time0) / ((float) nloops)); + + return 0; +} diff --git a/pool/shard002/C/0063277_mathlib.c b/pool/shard002/C/0063277_mathlib.c new file mode 100644 index 0000000000000000000000000000000000000000..d430ff70a609a2e4dd5812b17daffeb7399f614c --- /dev/null +++ b/pool/shard002/C/0063277_mathlib.c @@ -0,0 +1,131 @@ +/* +=========================================================================== +Copyright (C) 1997-2006 Id Software, Inc. + +This file is part of Quake 2 Tools source code. + +Quake 2 Tools source code 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. + +Quake 2 Tools source code 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 Quake 2 Tools source code; if not, write to the Free Software +Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +=========================================================================== +*/ + +// mathlib.c -- math primitives + +#include "cmdlib.h" +#include "mathlib.h" + +vec3_t vec3_origin = {0.0f,0.0f,0.0f}; + + +float VectorLength(vec3_t v) +{ + int i; + float length; + + length = 0.0f; + for (i=0 ; i< 3 ; i++) + length += v[i]*v[i]; + length = (float)sqrt (length); + + return length; +} + +qboolean VectorCompare (vec3_t v1, vec3_t v2) +{ + int i; + + for (i=0 ; i<3 ; i++) + if (fabs(v1[i]-v2[i]) > EQUAL_EPSILON) + return false; + + return true; +} + +vec_t Q_rint (vec_t in) +{ + return (float)floor (in + 0.5); +} + +void VectorMA (vec3_t va, float scale, vec3_t vb, vec3_t vc) +{ + vc[0] = va[0] + scale*vb[0]; + vc[1] = va[1] + scale*vb[1]; + vc[2] = va[2] + scale*vb[2]; +} + +void CrossProduct (vec3_t v1, vec3_t v2, vec3_t cross) +{ + cross[0] = v1[1]*v2[2] - v1[2]*v2[1]; + cross[1] = v1[2]*v2[0] - v1[0]*v2[2]; + cross[2] = v1[0]*v2[1] - v1[1]*v2[0]; +} + +vec_t _DotProduct (vec3_t v1, vec3_t v2) +{ + return v1[0]*v2[0] + v1[1]*v2[1] + v1[2]*v2[2]; +} + +void _VectorSubtract (vec3_t va, vec3_t vb, vec3_t out) +{ + out[0] = va[0]-vb[0]; + out[1] = va[1]-vb[1]; + out[2] = va[2]-vb[2]; +} + +void _VectorAdd (vec3_t va, vec3_t vb, vec3_t out) +{ + out[0] = va[0]+vb[0]; + out[1] = va[1]+vb[1]; + out[2] = va[2]+vb[2]; +} + +void _VectorCopy (vec3_t in, vec3_t out) +{ + out[0] = in[0]; + out[1] = in[1]; + out[2] = in[2]; +} + +vec_t VectorNormalize (vec3_t v) +{ + int i; + float length; + + length = 0.0f; + for (i=0 ; i< 3 ; i++) + length += v[i]*v[i]; + length = (float)sqrt (length); + if (length == 0) + return (vec_t)0; + + for (i=0 ; i< 3 ; i++) + v[i] /= length; + + return length; +} + +void VectorInverse (vec3_t v) +{ + v[0] = -v[0]; + v[1] = -v[1]; + v[2] = -v[2]; +} + +void VectorScale (vec3_t v, vec_t scale, vec3_t out) +{ + out[0] = v[0] * scale; + out[1] = v[1] * scale; + out[2] = v[2] * scale; +} + diff --git a/pool/shard002/C/0063281_ft_lstdelif.c b/pool/shard002/C/0063281_ft_lstdelif.c new file mode 100644 index 0000000000000000000000000000000000000000..035700922dde8803709ead3182001bc0301c4c5e --- /dev/null +++ b/pool/shard002/C/0063281_ft_lstdelif.c @@ -0,0 +1,35 @@ +/* ************************************************************************** */ +/* */ +/* ::: :::::::: */ +/* ft_lstdelif.c :+: :+: :+: */ +/* +:+ +:+ +:+ */ +/* By: gmange +#+ +:+ +#+ */ +/* +#+#+#+#+#+ +#+ */ +/* Created: 2013/12/08 08:50:32 by gmange #+# #+# */ +/* Updated: 2013/12/08 08:55:57 by gmange ### ########.fr */ +/* */ +/* ************************************************************************** */ + +#include "libft.h" + +void ft_lstdelif(t_list **alst, size_t size, void (*del)(void *, size_t)) +{ + t_list *ptr; + t_list *tmp; + + tmp = *alst; + while (tmp) + { + if (tmp->content_size == size) + { + ptr = tmp->next; + if (tmp == *alst) + ft_lstdelone(alst, del); + else + ft_lstdelone(&tmp, del); + tmp = ptr; + } + else + tmp = tmp->next; + } +} diff --git a/pool/shard002/C/0063289_controller.c b/pool/shard002/C/0063289_controller.c new file mode 100644 index 0000000000000000000000000000000000000000..6619aedd0966929975eeb4486b17288a0517556f --- /dev/null +++ b/pool/shard002/C/0063289_controller.c @@ -0,0 +1,44 @@ + +#include +#include +#include + +#include + +#include + +int +main() +{ + int mpi_argc = 0; + char** mpi_argv = NULL; + + MPI_Init(&mpi_argc, &mpi_argv); + + // Create communicator for ADLB + MPI_Comm comm; + MPI_Comm_dup(MPI_COMM_WORLD, &comm); + + int rank; + MPI_Comm_rank(comm, &rank); + + // Build up arguments + int argc = 3; + char* argv[argc]; + argv[0] = "howdy"; + argv[1] = "ok"; + argv[2] = "bye"; + + char output[128]; + + // Run Turbine + turbine_code rc = turbine_run(comm, "test-f.tcl", + argc, argv, output); + assert(rc == TURBINE_SUCCESS); + + if (rank == 0) + printf("controller: output: %s\n", output); + + MPI_Finalize(); + return 0; +} diff --git a/pool/shard002/C/0063297_IMB_reduce.c b/pool/shard002/C/0063297_IMB_reduce.c new file mode 100644 index 0000000000000000000000000000000000000000..f74378c4649aa523319bdbe5cdbd43f960520c31 --- /dev/null +++ b/pool/shard002/C/0063297_IMB_reduce.c @@ -0,0 +1,180 @@ +/***************************************************************************** + * * + * Copyright (c) 2003-2012 Intel Corporation. * + * All rights reserved. * + * * + ***************************************************************************** + +This code is covered by the Community Source License (CPL), version +1.0 as published by IBM and reproduced in the file "license.txt" in the +"license" subdirectory. Redistribution in source and binary form, with +or without modification, is permitted ONLY within the regulations +contained in above mentioned license. + +Use of the name and trademark "Intel(R) MPI Benchmarks" is allowed ONLY +within the regulations of the "License for Use of "Intel(R) MPI +Benchmarks" Name and Trademark" as reproduced in the file +"use-of-trademark-license.txt" in the "license" subdirectory. + +THE PROGRAM IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OR +CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED INCLUDING, WITHOUT +LIMITATION, ANY WARRANTIES OR CONDITIONS OF TITLE, NON-INFRINGEMENT, +MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Each Recipient is +solely responsible for determining the appropriateness of using and +distributing the Program and assumes all risks associated with its +exercise of rights under this Agreement, including but not limited to +the risks and costs of program errors, compliance with applicable +laws, damage to or loss of data, programs or equipment, and +unavailability or interruption of operations. + +EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, NEITHER RECIPIENT NOR +ANY CONTRIBUTORS SHALL HAVE ANY LIABILITY FOR ANY DIRECT, INDIRECT, +INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING +WITHOUT LIMITATION LOST PROFITS), 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 OR +DISTRIBUTION OF THE PROGRAM OR THE EXERCISE OF ANY RIGHTS GRANTED +HEREUNDER, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. + +EXPORT LAWS: THIS LICENSE ADDS NO RESTRICTIONS TO THE EXPORT LAWS OF +YOUR JURISDICTION. It is licensee's responsibility to comply with any +export regulations applicable in licensee's jurisdiction. Under +CURRENT U.S. export regulations this software is eligible for export +from the U.S. and can be downloaded by or otherwise exported or +reexported worldwide EXCEPT to U.S. embargoed destinations which +include Cuba, Iraq, Libya, North Korea, Iran, Syria, Sudan, +Afghanistan and any other country to which the U.S. has embargoed +goods and services. + + *************************************************************************** + +For more documentation than found here, see + +[1] doc/ReadMe_IMB.txt + +[2] Intel (R) MPI Benchmarks + Users Guide and Methodology Description + In + doc/IMB_Users_Guide.pdf + + File: IMB_reduce.c + + Implemented functions: + + IMB_reduce; + + ***************************************************************************/ + + + + + +#include "IMB_declare.h" +#include "IMB_benchmark.h" + +#include "IMB_prototypes.h" + +/*******************************************************************************/ + +/* ===================================================================== */ +/* +IMB 3.1 changes +July 2007 +Hans-Joachim Plum, Intel GmbH + +- replace "int n_sample" by iteration scheduling object "ITERATIONS" + (see => IMB_benchmark.h) + +- proceed with offsets in send / recv buffers to eventually provide + out-of-cache data +*/ +/* ===================================================================== */ + + +void IMB_reduce(struct comm_info* c_info, int size, struct iter_schedule* ITERATIONS, + MODES RUN_MODE, double* time) +/* + + + MPI-1 benchmark kernel + Benchmarks MPI_Reduce + + + +Input variables: + +-c_info (type struct comm_info*) + Collection of all base data for MPI; + see [1] for more information + + +-size (type int) + Basic message size in bytes + +-ITERATIONS (type struct iter_schedule *) + Repetition scheduling + +-RUN_MODE (type MODES) + (only MPI-2 case: see [1]) + + +Output variables: + +-time (type double*) + Timing result per sample + + +*/ +{ + double t1, t2; + int i,i1; + Type_Size s_size; + int s_num; + +#ifdef CHECK +defect=0.; +#endif + + ierr = 0; + + /* GET SIZE OF DATA TYPE */ + MPI_Type_size(c_info->red_data_type,&s_size); + if (s_size!=0) s_num=size/s_size; + + if(c_info->rank!=-1) + { + i1=0; + + for(i=0; icommunicator); + + t1 = MPI_Wtime(); + for(i=0;i< ITERATIONS->n_sample;i++) + { + ierr = MPI_Reduce((char*)c_info->s_buffer+i%ITERATIONS->s_cache_iter*ITERATIONS->s_offs, + (char*)c_info->r_buffer+i%ITERATIONS->r_cache_iter*ITERATIONS->r_offs, + s_num, + c_info->red_data_type,c_info->op_type, + i1,c_info->communicator); + MPI_ERRHAND(ierr); + +#ifdef CHECK + if( c_info->rank == i1 ) + { + CHK_DIFF("Reduce",c_info, (char*)c_info->r_buffer+i%ITERATIONS->r_cache_iter*ITERATIONS->r_offs, 0, + size, size, asize, + put, 0, ITERATIONS->n_sample, i, + -1, &defect); + } +#endif + /* CHANGE THE ROOT NODE */ + i1=(++i1)%c_info->num_procs; + } + t2 = MPI_Wtime(); + *time=(t2 - t1)/ITERATIONS->n_sample; + } + else + { + *time = 0.; + } +} + diff --git a/pool/shard002/C/0063299_nice.c b/pool/shard002/C/0063299_nice.c new file mode 100644 index 0000000000000000000000000000000000000000..700305c0e9b18754972c764c1bc709822b8ca5c1 --- /dev/null +++ b/pool/shard002/C/0063299_nice.c @@ -0,0 +1,50 @@ +/* Copyright (C) 1992, 1996, 1997, 2001, 2002 Free Software Foundation, Inc. + This file is part of the GNU C Library. + + 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, write to the Free + Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA + 02111-1307 USA. */ + +#include +#include +#include + +/* Increment the scheduling priority of the calling process by INCR. + The superuser may use a negative INCR to decrement the priority. */ +int +nice (int incr) +{ + int save; + int prio; + int result; + + /* -1 is a valid priority, so we use errno to check for an error. */ + save = errno; + __set_errno (0); + prio = getpriority (PRIO_PROCESS, 0); + if (prio == -1) + { + if (errno != 0) + return -1; + else + __set_errno (save); + } + + result = setpriority (PRIO_PROCESS, 0, prio + incr); + if (result != -1) + return getpriority (PRIO_PROCESS, 0); + else + return -1; + +} diff --git a/pool/shard002/C/0063301_st_accel_spi.c b/pool/shard002/C/0063301_st_accel_spi.c new file mode 100644 index 0000000000000000000000000000000000000000..dbd45c08711fd70ddf1e9804863ca7031c529561 --- /dev/null +++ b/pool/shard002/C/0063301_st_accel_spi.c @@ -0,0 +1,86 @@ +/* + * STMicroelectronics accelerometers driver + * + * Copyright 2012-2013 STMicroelectronics Inc. + * + * Denis Ciocca + * + * Licensed under the GPL-2. + */ + +#include +#include +#include +#include +#include +#include + +#include +#include +#include "st_accel.h" + +static int st_accel_spi_probe(struct spi_device *spi) +{ + struct iio_dev *indio_dev; + struct st_sensor_data *adata; + int err; + + indio_dev = iio_device_alloc(sizeof(*adata)); + if (indio_dev == NULL) { + err = -ENOMEM; + goto iio_device_alloc_error; + } + + adata = iio_priv(indio_dev); + adata->dev = &spi->dev; + + st_sensors_spi_configure(indio_dev, spi, adata); + + err = st_accel_common_probe(indio_dev); + if (err < 0) + goto st_accel_common_probe_error; + + return 0; + +st_accel_common_probe_error: + iio_device_free(indio_dev); +iio_device_alloc_error: + return err; +} + +static int st_accel_spi_remove(struct spi_device *spi) +{ + st_accel_common_remove(spi_get_drvdata(spi)); + + return 0; +} + +static const struct spi_device_id st_accel_id_table[] = { + { LSM303DLH_ACCEL_DEV_NAME }, + { LSM303DLHC_ACCEL_DEV_NAME }, + { LIS3DH_ACCEL_DEV_NAME }, + { LSM330D_ACCEL_DEV_NAME }, + { LSM330DL_ACCEL_DEV_NAME }, + { LSM330DLC_ACCEL_DEV_NAME }, + { LIS331DLH_ACCEL_DEV_NAME }, + { LSM303DL_ACCEL_DEV_NAME }, + { LSM303DLM_ACCEL_DEV_NAME }, + { LSM330_ACCEL_DEV_NAME }, + {}, +}; +MODULE_DEVICE_TABLE(spi, st_accel_id_table); + +static struct spi_driver st_accel_driver = { + .driver = { + .owner = THIS_MODULE, + .name = "st-accel-spi", + }, + .probe = st_accel_spi_probe, + .remove = st_accel_spi_remove, + .id_table = st_accel_id_table, +}; +module_spi_driver(st_accel_driver); + +MODULE_AUTHOR("Denis Ciocca "); +MODULE_DESCRIPTION("STMicroelectronics accelerometers spi driver"); +MODULE_LICENSE("GPL v2"); diff --git a/pool/shard002/C/0063305_tcp_client_uv.c b/pool/shard002/C/0063305_tcp_client_uv.c new file mode 100644 index 0000000000000000000000000000000000000000..2f1d237c07b0e1a392b6ba8dd6e30a687e74d66a --- /dev/null +++ b/pool/shard002/C/0063305_tcp_client_uv.c @@ -0,0 +1,180 @@ +/* + * + * Copyright 2016 gRPC authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +#include "src/core/lib/iomgr/port.h" + +#ifdef GRPC_UV + +#include + +#include +#include + +#include "src/core/lib/iomgr/error.h" +#include "src/core/lib/iomgr/sockaddr_utils.h" +#include "src/core/lib/iomgr/tcp_client.h" +#include "src/core/lib/iomgr/tcp_uv.h" +#include "src/core/lib/iomgr/timer.h" + +extern grpc_tracer_flag grpc_tcp_trace; + +typedef struct grpc_uv_tcp_connect { + uv_connect_t connect_req; + grpc_timer alarm; + grpc_closure on_alarm; + uv_tcp_t *tcp_handle; + grpc_closure *closure; + grpc_endpoint **endpoint; + int refs; + char *addr_name; + grpc_resource_quota *resource_quota; +} grpc_uv_tcp_connect; + +static void uv_tcp_connect_cleanup(grpc_exec_ctx *exec_ctx, + grpc_uv_tcp_connect *connect) { + grpc_resource_quota_unref_internal(exec_ctx, connect->resource_quota); + gpr_free(connect->addr_name); + gpr_free(connect); +} + +static void tcp_close_callback(uv_handle_t *handle) { gpr_free(handle); } + +static void uv_tc_on_alarm(grpc_exec_ctx *exec_ctx, void *acp, + grpc_error *error) { + int done; + grpc_uv_tcp_connect *connect = acp; + if (GRPC_TRACER_ON(grpc_tcp_trace)) { + const char *str = grpc_error_string(error); + gpr_log(GPR_DEBUG, "CLIENT_CONNECT: %s: on_alarm: error=%s", + connect->addr_name, str); + } + if (error == GRPC_ERROR_NONE) { + /* error == NONE implies that the timer ran out, and wasn't cancelled. If + it was cancelled, then the handler that cancelled it also should close + the handle, if applicable */ + uv_close((uv_handle_t *)connect->tcp_handle, tcp_close_callback); + } + done = (--connect->refs == 0); + if (done) { + uv_tcp_connect_cleanup(exec_ctx, connect); + } +} + +static void uv_tc_on_connect(uv_connect_t *req, int status) { + grpc_uv_tcp_connect *connect = req->data; + grpc_exec_ctx exec_ctx = GRPC_EXEC_CTX_INIT; + grpc_error *error = GRPC_ERROR_NONE; + int done; + grpc_closure *closure = connect->closure; + grpc_timer_cancel(&exec_ctx, &connect->alarm); + if (status == 0) { + *connect->endpoint = grpc_tcp_create( + connect->tcp_handle, connect->resource_quota, connect->addr_name); + } else { + error = GRPC_ERROR_CREATE_FROM_STATIC_STRING( + "Failed to connect to remote host"); + error = grpc_error_set_int(error, GRPC_ERROR_INT_ERRNO, -status); + error = + grpc_error_set_str(error, GRPC_ERROR_STR_OS_ERROR, + grpc_slice_from_static_string(uv_strerror(status))); + if (status == UV_ECANCELED) { + error = + grpc_error_set_str(error, GRPC_ERROR_STR_OS_ERROR, + grpc_slice_from_static_string("Timeout occurred")); + // This should only happen if the handle is already closed + } else { + error = grpc_error_set_str( + error, GRPC_ERROR_STR_OS_ERROR, + grpc_slice_from_static_string(uv_strerror(status))); + uv_close((uv_handle_t *)connect->tcp_handle, tcp_close_callback); + } + } + done = (--connect->refs == 0); + if (done) { + grpc_exec_ctx_flush(&exec_ctx); + uv_tcp_connect_cleanup(&exec_ctx, connect); + } + GRPC_CLOSURE_SCHED(&exec_ctx, closure, error); + grpc_exec_ctx_finish(&exec_ctx); +} + +static void tcp_client_connect_impl(grpc_exec_ctx *exec_ctx, + grpc_closure *closure, grpc_endpoint **ep, + grpc_pollset_set *interested_parties, + const grpc_channel_args *channel_args, + const grpc_resolved_address *resolved_addr, + gpr_timespec deadline) { + grpc_uv_tcp_connect *connect; + grpc_resource_quota *resource_quota = grpc_resource_quota_create(NULL); + (void)channel_args; + (void)interested_parties; + + if (channel_args != NULL) { + for (size_t i = 0; i < channel_args->num_args; i++) { + if (0 == strcmp(channel_args->args[i].key, GRPC_ARG_RESOURCE_QUOTA)) { + grpc_resource_quota_unref_internal(exec_ctx, resource_quota); + resource_quota = grpc_resource_quota_ref_internal( + channel_args->args[i].value.pointer.p); + } + } + } + + connect = gpr_zalloc(sizeof(grpc_uv_tcp_connect)); + connect->closure = closure; + connect->endpoint = ep; + connect->tcp_handle = gpr_malloc(sizeof(uv_tcp_t)); + connect->addr_name = grpc_sockaddr_to_uri(resolved_addr); + connect->resource_quota = resource_quota; + uv_tcp_init(uv_default_loop(), connect->tcp_handle); + connect->connect_req.data = connect; + connect->refs = 1; + + if (GRPC_TRACER_ON(grpc_tcp_trace)) { + gpr_log(GPR_DEBUG, "CLIENT_CONNECT: %s: asynchronously connecting", + connect->addr_name); + } + + // TODO(murgatroid99): figure out what the return value here means + uv_tcp_connect(&connect->connect_req, connect->tcp_handle, + (const struct sockaddr *)resolved_addr->addr, + uv_tc_on_connect); + GRPC_CLOSURE_INIT(&connect->on_alarm, uv_tc_on_alarm, connect, + grpc_schedule_on_exec_ctx); + grpc_timer_init(exec_ctx, &connect->alarm, + gpr_convert_clock_type(deadline, GPR_CLOCK_MONOTONIC), + &connect->on_alarm, gpr_now(GPR_CLOCK_MONOTONIC)); +} + +// overridden by api_fuzzer.c +void (*grpc_tcp_client_connect_impl)( + grpc_exec_ctx *exec_ctx, grpc_closure *closure, grpc_endpoint **ep, + grpc_pollset_set *interested_parties, const grpc_channel_args *channel_args, + const grpc_resolved_address *addr, + gpr_timespec deadline) = tcp_client_connect_impl; + +void grpc_tcp_client_connect(grpc_exec_ctx *exec_ctx, grpc_closure *closure, + grpc_endpoint **ep, + grpc_pollset_set *interested_parties, + const grpc_channel_args *channel_args, + const grpc_resolved_address *addr, + gpr_timespec deadline) { + grpc_tcp_client_connect_impl(exec_ctx, closure, ep, interested_parties, + channel_args, addr, deadline); +} + +#endif /* GRPC_UV */ diff --git a/pool/shard002/C/0063310_lapacke_chegv_2stage.c b/pool/shard002/C/0063310_lapacke_chegv_2stage.c new file mode 100644 index 0000000000000000000000000000000000000000..fc339583396f5bd2034efe31a68ab7e4f3f62676 --- /dev/null +++ b/pool/shard002/C/0063310_lapacke_chegv_2stage.c @@ -0,0 +1,93 @@ +/***************************************************************************** + Copyright (c) 2014, Intel Corp. + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + * Neither the name of Intel Corporation nor the names of its contributors + may be used to endorse or promote products derived from this software + without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE + LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + THE POSSIBILITY OF SUCH DAMAGE. +***************************************************************************** +* Contents: Native high-level C interface to LAPACK function chegv_2stage +* Author: Intel Corporation +* Generated December 2016 +*****************************************************************************/ + +#include "lapacke_utils.h" + +lapack_int LAPACKE_chegv_2stage( int matrix_layout, lapack_int itype, char jobz, + char uplo, lapack_int n, lapack_complex_float* a, + lapack_int lda, lapack_complex_float* b, + lapack_int ldb, float* w ) +{ + lapack_int info = 0; + lapack_int lwork = -1; + float* rwork = NULL; + lapack_complex_float* work = NULL; + lapack_complex_float work_query; + if( matrix_layout != LAPACK_COL_MAJOR && matrix_layout != LAPACK_ROW_MAJOR ) { + LAPACKE_xerbla( "LAPACKE_chegv_2stage", -1 ); + return -1; + } +#ifndef LAPACK_DISABLE_NAN_CHECK + if( LAPACKE_get_nancheck() ) { + /* Optionally check input matrices for NaNs */ + if( LAPACKE_che_nancheck( matrix_layout, uplo, n, a, lda ) ) { + return -6; + } + if( LAPACKE_che_nancheck( matrix_layout, uplo, n, b, ldb ) ) { + return -8; + } + } +#endif + /* Allocate memory for working array(s) */ + rwork = (float*)LAPACKE_malloc( sizeof(float) * MAX(1,3*n-2) ); + if( rwork == NULL ) { + info = LAPACK_WORK_MEMORY_ERROR; + goto exit_level_0; + } + /* Query optimal working array(s) size */ + info = LAPACKE_chegv_2stage_work( matrix_layout, itype, jobz, uplo, n, a, lda, b, + ldb, w, &work_query, lwork, rwork ); + if( info != 0 ) { + goto exit_level_1; + } + lwork = LAPACK_C2INT( work_query ); + /* Allocate memory for work arrays */ + work = (lapack_complex_float*) + LAPACKE_malloc( sizeof(lapack_complex_float) * lwork ); + if( work == NULL ) { + info = LAPACK_WORK_MEMORY_ERROR; + goto exit_level_1; + } + /* Call middle-level interface */ + info = LAPACKE_chegv_2stage_work( matrix_layout, itype, jobz, uplo, n, a, lda, b, + ldb, w, work, lwork, rwork ); + /* Release memory and exit */ + LAPACKE_free( work ); +exit_level_1: + LAPACKE_free( rwork ); +exit_level_0: + if( info == LAPACK_WORK_MEMORY_ERROR ) { + LAPACKE_xerbla( "LAPACKE_chegv_2stage", info ); + } + return info; +} diff --git a/pool/shard002/C/0063339_chflags.c b/pool/shard002/C/0063339_chflags.c new file mode 100644 index 0000000000000000000000000000000000000000..a0b427ccf003c55237f9d81fd58f32134449df89 --- /dev/null +++ b/pool/shard002/C/0063339_chflags.c @@ -0,0 +1,39 @@ +/* Copyright (C) 1991, 92, 93, 94, 97, 98 Free Software Foundation, Inc. + This file is part of the GNU C Library. + + 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, write to the Free + Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA + 02111-1307 USA. */ + +#include +#include +#include +#include + +/* Change the flags of FILE to FLAGS. */ + +/* XXX shouldn't this be __chflags? */ +int +chflags (const char *file, int flags) +{ + error_t err; + file_t port = __file_name_lookup (file, 0, 0); + if (port == MACH_PORT_NULL) + return -1; + err = __file_chflags (port, flags); + __mach_port_deallocate (__mach_task_self (), port); + if (err) + return __hurd_fail (err); + return 0; +} diff --git a/pool/shard002/C/0063347_substation.c b/pool/shard002/C/0063347_substation.c new file mode 100644 index 0000000000000000000000000000000000000000..bac208bbd4b93b4010602f3546288b5dbbe87267 --- /dev/null +++ b/pool/shard002/C/0063347_substation.c @@ -0,0 +1,124 @@ +/* ---------------------------------------------------------------------- * + * substation.c + * This file is part of lincity. + * Lincity is copyright (c) I J Peters 1995-1997, (c) Greg Sharp 1997-2001. + * (c) Corey Keasling, 2004 + * ---------------------------------------------------------------------- */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +/*** Substations ***/ +/* + int_5 is the power demand at this substation + int_6 is the grid its connected to + int_7 is a grid timestamp +*/ + +void +do_power_substation (int x, int y) +{ + switch(grid[MP_INFO(x,y).int_6]->powered) { + case -1: { + MP_TYPE(x,y) = CST_SUBSTATION_R; + } break; + case 0 : { + MP_TYPE(x,y) = CST_SUBSTATION_RG; + } break; + case 1 : { + MP_TYPE(x,y) = CST_SUBSTATION_G; + } break; + default : { + printf("Default case in do_power_substation\n"); + } break; + } +} + +int +add_a_substation (int x, int y) /* add to substationx substationy to list */ +{ + if (numof_substations >= MAX_NUMOF_SUBSTATIONS) + return (0); + substationx[numof_substations] = x; + substationy[numof_substations] = y; + numof_substations++; + return (1); +} + +void +remove_a_substation (int x, int y) +{ + int q; + for (q = 0; q < numof_substations; q++) + if (substationx[q] == x && substationy[q] == y) + break; + for (; q < numof_substations; q++) + { + substationx[q] = substationx[q + 1]; + substationy[q] = substationy[q + 1]; + } + numof_substations--; +} + +void +shuffle_substations (void) +{ + int q, x, r, m; + m = (numof_substations / 2) + 1; + for (x = 0; x < m; x++) + { + r = rand () % numof_substations; + if (r == x) + continue; + q = substationx[x]; + substationx[x] = substationx[r]; + substationx[r] = q; + q = substationy[x]; + substationy[x] = substationy[r]; + substationy[r] = q; + } +} + +void +mps_substation (int x, int y) +{ + int i = 0; + char s[12]; + + mps_store_title(i++,_("Substation")); + i++; + + format_power (s, sizeof(s), MP_INFO(x,y).int_5); + mps_store_title(i++,_("Local Demand")); + mps_store_title(i++,s); + + if (MP_INFO(x,y).int_6 == 0) + return; + + i++; + mps_store_title(i++,_("Grid Status")); + + format_power (s, sizeof(s), grid[MP_INFO(x,y).int_6]->max_power); + mps_store_ss(i++,_("T. Cap."), s); + + format_power (s, sizeof(s), grid[MP_INFO(x,y).int_6]->avail_power); + mps_store_ss(i++,_("A. Cap."), s); + + format_power (s, sizeof(s), grid[MP_INFO(x,y).int_6]->demand); + mps_store_ss(i++,_("Demand"), s); + i++; + + mps_store_sd(i++,_("Grid ID"), MP_INFO(x,y).int_6); + + +} diff --git a/pool/shard002/C/0063349_client_pool_test.c b/pool/shard002/C/0063349_client_pool_test.c new file mode 100644 index 0000000000000000000000000000000000000000..2ad52e9f2d68360748d0ec4f6b3d338df4d5bf85 --- /dev/null +++ b/pool/shard002/C/0063349_client_pool_test.c @@ -0,0 +1,236 @@ +/* + * Copyright (C) 2012-2014 Paul Ionkin + * Copyright (C) 2012-2014 Skoobe GmbH. 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 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 "global.h" +#include "test_application.h" +#include "http_connection.h" +#include "client_pool.h" +#include "utils.h" + +#define POOL_TEST "pool_test" +typedef struct { + gchar *in_name; + gchar *md5; + gchar *url; + + gchar *out_name; + FILE *fout; + + gboolean checked; + GList *l; +} FileData; + +typedef struct { + ClientPool *pool; + GList *l_files; +} CBData; + +static Application *app; + +// create max_files and fill with random data +// return list of {file name, content md5} +static GList *populate_file_list (gint max_files, GList *l_files, gchar *in_dir) +{ + gint i; + gchar *out_dir; + GError *error = NULL; + FileData *fdata; + gchar *name; + FILE *f; + + out_dir = g_dir_make_tmp (NULL, &error); + g_assert (out_dir); + + + LOG_debug (POOL_TEST, "In dir: %s Out dir: %s", in_dir, out_dir); + + for (i = 0; i < max_files; i++) { + char *bytes; + size_t bytes_len; + + fdata = g_new0 (FileData, 1); + fdata->checked = FALSE; + bytes_len = g_random_int_range (100000, 1000000); + bytes = g_malloc (bytes_len + 1); + RAND_bytes ((unsigned char *)bytes, bytes_len); + *(bytes + bytes_len) = '\0'; + + name = get_random_string (15, TRUE); + fdata->in_name = g_strdup_printf ("%s/%s", in_dir, name); + f = fopen (fdata->in_name, "w"); + fwrite (bytes, 1, bytes_len + 1, f); + fclose (f); + + fdata->out_name = g_strdup_printf ("%s/%s", out_dir, name); + get_md5_sum (bytes, bytes_len + 1, &fdata->md5, NULL); + + fdata->fout = fopen (fdata->out_name, "w"); + g_assert (fdata->fout); + + fdata->url = g_strdup_printf ("http://127.0.0.1:8011/%s", name); + g_assert (fdata->url); + + LOG_debug (POOL_TEST, "%s -> %s, size: %u", fdata->in_name, fdata->md5, bytes_len); + + l_files = g_list_append (l_files, fdata); + } + + return l_files; +} + +gboolean check_list (GList *l) +{ + GList *tmp; + + for (tmp = g_list_first (l); tmp; tmp = g_list_next (tmp)) { + FileData *fdata = (FileData *) tmp->data; + if (!fdata->checked) + return FALSE; + } + return TRUE; +} + +static void on_output_timer (evutil_socket_t fd, short event, void *ctx) +{ + gint i; + GList *l; + + CBData *cb = (CBData *) ctx; + ClientPool *pool = cb->pool; + + for (l = g_list_first (cb->l_files); l; l = g_list_next (l)) { + FileData *fd = (FileData *) l->data; + // g_assert (s3client_pool_get_client (pool, on_get_http_client, fd)); + } +} + +#define BUFFER_SIZE 1024 * 10 + +static void on_srv_request (struct evhttp_request *req, void *ctx) +{ + struct evbuffer *in; + gchar *dir = (gchar *) ctx; + gchar *path, *decoded_path; + const gchar *tmp; + const char *uri = evhttp_request_get_uri(req); + struct evhttp_uri *decoded = NULL; + struct evbuffer *evb = NULL; + char buf[BUFFER_SIZE]; + FILE *f; + size_t bytes_read; + size_t total_bytes = 0; + + in = evhttp_request_get_input_buffer (req); + + decoded = evhttp_uri_parse(uri); + g_assert (decoded); + tmp = evhttp_uri_get_path (decoded); + g_assert (tmp); + decoded_path = evhttp_uridecode(tmp, 0, NULL); + + evb = evbuffer_new(); + + path = g_strdup_printf ("%s/%s", dir, decoded_path); + LOG_debug (POOL_TEST, "SRV: received %d bytes. Req: %s, path: %s", evbuffer_get_length (in), evhttp_request_get_uri (req), path); + + f = fopen (path, "r"); + g_assert (f); + + while ((bytes_read = fread (buf, 1, BUFFER_SIZE, f)) > 0) { + evbuffer_add (evb, buf, bytes_read); + total_bytes += bytes_read; + } + evhttp_send_reply(req, 200, "OK", evb); + + LOG_debug (POOL_TEST, "Total bytes sent: %u", total_bytes); + + fclose(f); + evbuffer_free(evb); +} + +static void start_srv (struct event_base *base, gchar *in_dir) +{ + struct evhttp *http; + + http = evhttp_new (base); + evhttp_bind_socket (http, "127.0.0.1", 8011); + evhttp_set_gencb (http, on_srv_request, in_dir); +} + + +static gboolean print_foreach (gconstpointer a, gconstpointer b) +{ + g_printf ("%p: %i\n", a, GPOINTER_TO_INT (b)); + return FALSE; +} + +int main (int argc, char *argv[]) +{ + ClientPool *pool; + struct event *timeout; + struct timeval tv; + GList *l_files = NULL; + CBData *cb; + gchar *in_dir; + + log_level = LOG_debug; + + event_set_mem_functions (g_malloc, g_realloc, g_free); + + in_dir = g_dir_make_tmp (NULL, NULL); + g_assert (in_dir); + + l_files = populate_file_list (100, l_files, in_dir); + g_assert (l_files); + + + + app = app_create (); + + + + app->h_clients_freq = g_hash_table_new (g_direct_hash, g_direct_equal); + app->l_files = l_files; + // start server + start_srv (app->evbase, in_dir); + + /* + pool = client_pool_create (app, 12, + http_client_create, + http_client_destroy, + http_client_set_on_released_cb, + http_client_check_rediness + ); + */ + + cb = g_new (CBData, 1); + cb->pool = pool; + cb->l_files = l_files; + + timeout = evtimer_new (app->evbase, on_output_timer, cb); + + evutil_timerclear(&tv); + tv.tv_sec = 0; + tv.tv_usec = 500; + event_add (timeout, &tv); + + event_base_dispatch (app->evbase); + + g_hash_table_foreach (app->h_clients_freq, (GHFunc)print_foreach, NULL); + + return 0; +} diff --git a/pool/shard002/C/0063356_chp1-ex6.c b/pool/shard002/C/0063356_chp1-ex6.c new file mode 100644 index 0000000000000000000000000000000000000000..5cda4a3f13f9bcda492e737795f3c8a952871132 --- /dev/null +++ b/pool/shard002/C/0063356_chp1-ex6.c @@ -0,0 +1,25 @@ +/*Interchange C and D + * author:lakshmanan + * date: 01-May-2009 + */ + +#include + +int main() +{ + int c,d; + int t; + + printf("enter c and d: "); + scanf("%d %d",&c,&d); + + printf("C and D before swapping : \n c=%d d = %d\n",c,d); + + t=c; + c=d; + d=t; + + printf("C and D after swapping : \n c=%d d = %d\n",c,d); + + return 0; +} diff --git a/pool/shard002/C/0063360_vigenere.c b/pool/shard002/C/0063360_vigenere.c new file mode 100644 index 0000000000000000000000000000000000000000..9a64c3cb10839e3a9f91ffff24c19ae47bf48381 --- /dev/null +++ b/pool/shard002/C/0063360_vigenere.c @@ -0,0 +1,71 @@ +/* + * 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, *decodepos, *decodeneg; + long offset; + size_t keylength, textlength; + + if (argc != 4) { + fprintf(stderr, "Usage: %s \n", argv[0]); + exit(EXIT_FAILURE); + } + + offset = strtol(argv[1], NULL, 10); + ciphertext = argv[2]; + key = argv[3]; + + preprocess(key); + preprocess(ciphertext); + + keylength = strlen(key); + textlength = strlen(ciphertext); + + decodepos = malloc(textlength + 1); + decodeneg = malloc(textlength + 1); + + for (size_t i = 0; i < textlength; i++) { + decodepos[i] = ITOC((CTOI(ciphertext[i]) + offset + CTOI(key[i % keylength])) % 26); + decodeneg[i] = ITOC((CTOI(ciphertext[i]) + 52 - offset - CTOI(key[i % keylength])) % 26); + } + + decodepos[textlength] = '\0'; + decodeneg[textlength] = '\0'; + + printf("+ %s\n- %s\n", decodepos, decodeneg); + + free(decodepos); + free(decodeneg); + + 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/shard002/C/0063372_lxc_unfreeze.c b/pool/shard002/C/0063372_lxc_unfreeze.c new file mode 100644 index 0000000000000000000000000000000000000000..3a13d3723fac04a28f281bbc5e7ae4c2aba8313c --- /dev/null +++ b/pool/shard002/C/0063372_lxc_unfreeze.c @@ -0,0 +1,90 @@ +/* + * lxc: linux Container library + * + * (C) Copyright IBM Corp. 2007, 2008 + * + * Authors: + * Daniel Lezcano + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ +#include +#include +#include +#include + +#include + +#include "lxc.h" +#include "log.h" +#include "arguments.h" + +lxc_log_define(lxc_unfreeze_ui, lxc); + +static const struct option my_longopts[] = { + LXC_COMMON_OPTIONS +}; + +static struct lxc_arguments my_args = { + .progname = "lxc-unfreeze", + .help = "\ +--name=NAME\n\ +\n\ +lxc-unfreeze unfreezes a container with the identifier NAME\n\ +\n\ +Options :\n\ + -n, --name=NAME NAME of the container\n", + .options = my_longopts, + .parser = NULL, + .checker = NULL, +}; + +int main(int argc, char *argv[]) +{ + struct lxc_container *c; + + if (lxc_arguments_parse(&my_args, argc, argv)) + exit(1); + + if (!my_args.log_file) + my_args.log_file = "none"; + + if (lxc_log_init(my_args.name, my_args.log_file, my_args.log_priority, + my_args.progname, my_args.quiet, my_args.lxcpath[0])) + exit(1); + lxc_log_options_no_override(); + + c = lxc_container_new(my_args.name, my_args.lxcpath[0]); + if (!c) { + ERROR("No such container: %s:%s", my_args.lxcpath[0], my_args.name); + exit(1); + } + + if (!c->may_control(c)) { + ERROR("Insufficent privileges to control %s:%s", my_args.lxcpath[0], my_args.name); + lxc_container_put(c); + exit(1); + } + + if (!c->unfreeze(c)) { + ERROR("Failed to unfreeze %s:%s", my_args.lxcpath[0], my_args.name); + lxc_container_put(c); + exit(1); + } + + lxc_container_put(c); + + exit(0); +} diff --git a/pool/shard002/C/0063378_pwfile_test.c b/pool/shard002/C/0063378_pwfile_test.c new file mode 100644 index 0000000000000000000000000000000000000000..868eb9d366b4694c65d211c1a0d1021b40386909 --- /dev/null +++ b/pool/shard002/C/0063378_pwfile_test.c @@ -0,0 +1,60 @@ +#include +#include +#include +#include + +#include + +#include "pwfile.h" + +const char *cbpwfile = "pwfile_test.pw"; + +const char *user1 = "mikewied"; +const char *pass1 = "mikepw"; +const char *user2 = "cseo"; +const char *pass2 = "seopw"; +const char *user3 = "jlim"; +const char *pass3 = "limpw"; + +static void create_pw_file() +{ + FILE *fp = fopen(cbpwfile, "w"); + cb_assert(fp != NULL); + + fprintf(fp, "mikewied mikepw \ncseo seopw \njlim limpw \n"); + cb_assert(fclose(fp) == 0); + + putenv("ISASL_PWFILE=pwfile_test.pw"); +} + +static void remove_pw_file() +{ + cb_assert(remove(cbpwfile) == 0); + free_user_ht(); +} + +static void test_pwfile() +{ + char *cfg; + char *password; + + pwfile_init(); + create_pw_file(); + cb_assert(load_user_db() == SASL_OK); + password = find_pw(user1, &cfg); + cb_assert(strncmp(password, pass1, strlen(pass1)) == 0); + + password = find_pw(user2, &cfg); + cb_assert(strncmp(password, pass2, strlen(pass2)) == 0); + + password = find_pw(user3, &cfg); + cb_assert(strncmp(password, pass3, strlen(pass3)) == 0); + + remove_pw_file(); +} + +int main() +{ + test_pwfile(); + return 0; +} diff --git a/pool/shard002/C/0063380_aasc.c b/pool/shard002/C/0063380_aasc.c new file mode 100644 index 0000000000000000000000000000000000000000..e6f363de4c4ba35c2e70deedca1e74470f77981c --- /dev/null +++ b/pool/shard002/C/0063380_aasc.c @@ -0,0 +1,123 @@ +/* + * Autodesk RLE Decoder + * Copyright (C) 2005 the ffmpeg project + * + * 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 + */ + +/** + * @file + * Autodesk RLE Video Decoder by Konstantin Shishkov + */ + +#include +#include +#include + +#include "avcodec.h" +#include "dsputil.h" +#include "msrledec.h" + +typedef struct AascContext { + AVCodecContext *avctx; + AVFrame frame; +} AascContext; + +#define FETCH_NEXT_STREAM_BYTE() \ + if (stream_ptr >= buf_size) \ + { \ + av_log(s->avctx, AV_LOG_ERROR, " AASC: stream ptr just went out of bounds (fetch)\n"); \ + break; \ + } \ + stream_byte = buf[stream_ptr++]; + +static av_cold int aasc_decode_init(AVCodecContext *avctx) +{ + AascContext *s = avctx->priv_data; + + s->avctx = avctx; + avctx->pix_fmt = PIX_FMT_BGR24; + avcodec_get_frame_defaults(&s->frame); + + return 0; +} + +static int aasc_decode_frame(AVCodecContext *avctx, + void *data, int *data_size, + AVPacket *avpkt) +{ + const uint8_t *buf = avpkt->data; + int buf_size = avpkt->size; + AascContext *s = avctx->priv_data; + int compr, i, stride; + + s->frame.reference = 1; + s->frame.buffer_hints = FF_BUFFER_HINTS_VALID | FF_BUFFER_HINTS_PRESERVE | FF_BUFFER_HINTS_REUSABLE; + if (avctx->reget_buffer(avctx, &s->frame)) { + av_log(avctx, AV_LOG_ERROR, "reget_buffer() failed\n"); + return -1; + } + + compr = AV_RL32(buf); + buf += 4; + buf_size -= 4; + switch(compr){ + case 0: + stride = (avctx->width * 3 + 3) & ~3; + for(i = avctx->height - 1; i >= 0; i--){ + memcpy(s->frame.data[0] + i*s->frame.linesize[0], buf, avctx->width*3); + buf += stride; + } + break; + case 1: + ff_msrle_decode(avctx, (AVPicture*)&s->frame, 8, buf - 4, buf_size + 4); + break; + default: + av_log(avctx, AV_LOG_ERROR, "Unknown compression type %d\n", compr); + return -1; + } + + *data_size = sizeof(AVFrame); + *(AVFrame*)data = s->frame; + + /* report that the buffer was completely consumed */ + return buf_size; +} + +static av_cold int aasc_decode_end(AVCodecContext *avctx) +{ + AascContext *s = avctx->priv_data; + + /* release the last frame */ + if (s->frame.data[0]) + avctx->release_buffer(avctx, &s->frame); + + return 0; +} + +AVCodec ff_aasc_decoder = { + "aasc", + AVMEDIA_TYPE_VIDEO, + CODEC_ID_AASC, + sizeof(AascContext), + aasc_decode_init, + NULL, + aasc_decode_end, + aasc_decode_frame, + CODEC_CAP_DR1, + .long_name = NULL_IF_CONFIG_SMALL("Autodesk RLE"), +}; diff --git a/pool/shard002/C/0063399_file.c b/pool/shard002/C/0063399_file.c new file mode 100644 index 0000000000000000000000000000000000000000..b2c13f739ffa27b8b8a249cadcd025737a512ce6 --- /dev/null +++ b/pool/shard002/C/0063399_file.c @@ -0,0 +1,285 @@ +/* + * fs/logfs/file.c - prepare_write, commit_write and friends + * + * As should be obvious for Linux kernel code, license is GPLv2 + * + * Copyright (c) 2005-2008 Joern Engel + */ +#include "logfs.h" +#include +#include + +static int logfs_write_begin(struct file *file, struct address_space *mapping, + loff_t pos, unsigned len, unsigned flags, + struct page **pagep, void **fsdata) +{ + struct inode *inode = mapping->host; + struct page *page; + pgoff_t index = pos >> PAGE_CACHE_SHIFT; + + page = grab_cache_page_write_begin(mapping, index, flags); + if (!page) + return -ENOMEM; + *pagep = page; + + if ((len == PAGE_CACHE_SIZE) || PageUptodate(page)) + return 0; + if ((pos & PAGE_CACHE_MASK) >= i_size_read(inode)) { + unsigned start = pos & (PAGE_CACHE_SIZE - 1); + unsigned end = start + len; + + /* Reading beyond i_size is simple: memset to zero */ + zero_user_segments(page, 0, start, end, PAGE_CACHE_SIZE); + return 0; + } + return logfs_readpage_nolock(page); +} + +static int logfs_write_end(struct file *file, struct address_space *mapping, + loff_t pos, unsigned len, unsigned copied, struct page *page, + void *fsdata) +{ + struct inode *inode = mapping->host; + pgoff_t index = page->index; + unsigned start = pos & (PAGE_CACHE_SIZE - 1); + unsigned end = start + copied; + int ret = 0; + + BUG_ON(PAGE_CACHE_SIZE != inode->i_sb->s_blocksize); + BUG_ON(page->index > I3_BLOCKS); + + if (copied < len) { + /* + * Short write of a non-initialized paged. Just tell userspace + * to retry the entire page. + */ + if (!PageUptodate(page)) { + copied = 0; + goto out; + } + } + if (copied == 0) + goto out; /* FIXME: do we need to update inode? */ + + if (i_size_read(inode) < (index << PAGE_CACHE_SHIFT) + end) { + i_size_write(inode, (index << PAGE_CACHE_SHIFT) + end); + mark_inode_dirty_sync(inode); + } + + SetPageUptodate(page); + if (!PageDirty(page)) { + if (!get_page_reserve(inode, page)) + __set_page_dirty_nobuffers(page); + else + ret = logfs_write_buf(inode, page, WF_LOCK); + } +out: + unlock_page(page); + page_cache_release(page); + return ret ? ret : copied; +} + +int logfs_readpage(struct file *file, struct page *page) +{ + int ret; + + ret = logfs_readpage_nolock(page); + unlock_page(page); + return ret; +} + +/* Clear the page's dirty flag in the radix tree. */ +/* TODO: mucking with PageWriteback is silly. Add a generic function to clear + * the dirty bit from the radix tree for filesystems that don't have to wait + * for page writeback to finish (i.e. any compressing filesystem). + */ +static void clear_radix_tree_dirty(struct page *page) +{ + BUG_ON(PagePrivate(page) || page->private); + set_page_writeback(page); + end_page_writeback(page); +} + +static int __logfs_writepage(struct page *page) +{ + struct inode *inode = page->mapping->host; + int err; + + err = logfs_write_buf(inode, page, WF_LOCK); + if (err) + set_page_dirty(page); + else + clear_radix_tree_dirty(page); + unlock_page(page); + return err; +} + +static int logfs_writepage(struct page *page, struct writeback_control *wbc) +{ + struct inode *inode = page->mapping->host; + loff_t i_size = i_size_read(inode); + pgoff_t end_index = i_size >> PAGE_CACHE_SHIFT; + unsigned offset; + u64 bix; + level_t level; + + log_file("logfs_writepage(%lx, %lx, %p)\n", inode->i_ino, page->index, + page); + + logfs_unpack_index(page->index, &bix, &level); + + /* Indirect blocks are never truncated */ + if (level != 0) + return __logfs_writepage(page); + + /* + * TODO: everything below is a near-verbatim copy of nobh_writepage(). + * The relevant bits should be factored out after logfs is merged. + */ + + /* Is the page fully inside i_size? */ + if (bix < end_index) + return __logfs_writepage(page); + + /* Is the page fully outside i_size? (truncate in progress) */ + offset = i_size & (PAGE_CACHE_SIZE-1); + if (bix > end_index || offset == 0) { + unlock_page(page); + return 0; /* don't care */ + } + + /* + * The page straddles i_size. It must be zeroed out on each and every + * writepage invokation because it may be mmapped. "A file is mapped + * in multiples of the page size. For a file that is not a multiple of + * the page size, the remaining memory is zeroed when mapped, and + * writes to that region are not written out to the file." + */ + zero_user_segment(page, offset, PAGE_CACHE_SIZE); + return __logfs_writepage(page); +} + +static void logfs_invalidatepage(struct page *page, unsigned int offset, + unsigned int length) +{ + struct logfs_block *block = logfs_block(page); + + if (block->reserved_bytes) { + struct super_block *sb = page->mapping->host->i_sb; + struct logfs_super *super = logfs_super(sb); + + super->s_dirty_pages -= block->reserved_bytes; + block->ops->free_block(sb, block); + BUG_ON(bitmap_weight(block->alias_map, LOGFS_BLOCK_FACTOR)); + } else + move_page_to_btree(page); + BUG_ON(PagePrivate(page) || page->private); +} + +static int logfs_releasepage(struct page *page, gfp_t only_xfs_uses_this) +{ + return 0; /* None of these are easy to release */ +} + + +long logfs_ioctl(struct file *file, unsigned int cmd, unsigned long arg) +{ + struct inode *inode = file_inode(file); + struct logfs_inode *li = logfs_inode(inode); + unsigned int oldflags, flags; + int err; + + switch (cmd) { + case FS_IOC_GETFLAGS: + flags = li->li_flags & LOGFS_FL_USER_VISIBLE; + return put_user(flags, (int __user *)arg); + case FS_IOC_SETFLAGS: + if (IS_RDONLY(inode)) + return -EROFS; + + if (!inode_owner_or_capable(inode)) + return -EACCES; + + err = get_user(flags, (int __user *)arg); + if (err) + return err; + + mutex_lock(&inode->i_mutex); + oldflags = li->li_flags; + flags &= LOGFS_FL_USER_MODIFIABLE; + flags |= oldflags & ~LOGFS_FL_USER_MODIFIABLE; + li->li_flags = flags; + mutex_unlock(&inode->i_mutex); + + inode->i_ctime = CURRENT_TIME; + mark_inode_dirty_sync(inode); + return 0; + + default: + return -ENOTTY; + } +} + +int logfs_fsync(struct file *file, loff_t start, loff_t end, int datasync) +{ + struct super_block *sb = file->f_mapping->host->i_sb; + struct inode *inode = file->f_mapping->host; + int ret; + + ret = filemap_write_and_wait_range(inode->i_mapping, start, end); + if (ret) + return ret; + + mutex_lock(&inode->i_mutex); + logfs_get_wblocks(sb, NULL, WF_LOCK); + logfs_write_anchor(sb); + logfs_put_wblocks(sb, NULL, WF_LOCK); + mutex_unlock(&inode->i_mutex); + + return 0; +} + +static int logfs_setattr(struct dentry *dentry, struct iattr *attr) +{ + struct inode *inode = dentry->d_inode; + int err = 0; + + err = inode_change_ok(inode, attr); + if (err) + return err; + + if (attr->ia_valid & ATTR_SIZE) { + err = logfs_truncate(inode, attr->ia_size); + if (err) + return err; + } + + setattr_copy(inode, attr); + mark_inode_dirty(inode); + return 0; +} + +const struct inode_operations logfs_reg_iops = { + .setattr = logfs_setattr, +}; + +const struct file_operations logfs_reg_fops = { + .read_iter = generic_file_read_iter, + .write_iter = generic_file_write_iter, + .fsync = logfs_fsync, + .unlocked_ioctl = logfs_ioctl, + .llseek = generic_file_llseek, + .mmap = generic_file_readonly_mmap, + .open = generic_file_open, +}; + +const struct address_space_operations logfs_reg_aops = { + .invalidatepage = logfs_invalidatepage, + .readpage = logfs_readpage, + .releasepage = logfs_releasepage, + .set_page_dirty = __set_page_dirty_nobuffers, + .writepage = logfs_writepage, + .writepages = generic_writepages, + .write_begin = logfs_write_begin, + .write_end = logfs_write_end, +}; diff --git a/pool/shard002/C/0063401_input_hid_driver.c b/pool/shard002/C/0063401_input_hid_driver.c new file mode 100644 index 0000000000000000000000000000000000000000..9ce7570387c0de884c9ce3cad87191eb2defc03d --- /dev/null +++ b/pool/shard002/C/0063401_input_hid_driver.c @@ -0,0 +1,109 @@ +/* RetroArch - A frontend for libretro. + * Copyright (C) 2010-2014 - Hans-Kristian Arntzen + * Copyright (C) 2011-2015 - Daniel De Matteis + * + * RetroArch 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 Found- + * ation, either version 3 of the License, or (at your option) any later version. + * + * RetroArch 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 RetroArch. + * If not, see . + */ + +#include +#include +#include + +#include "input_hid_driver.h" +#include "../general.h" +#include "../string_list_special.h" + +static hid_driver_t *hid_drivers[] = { +#if defined(HAVE_BTSTACK) + &btstack_hid, +#endif +#if defined(__APPLE__) && defined(HAVE_IOHIDMANAGER) + &iohidmanager_hid, +#endif +#ifdef HAVE_LIBUSB + &libusb_hid, +#endif +#ifdef HW_RVL + &wiiusb_hid, +#endif + &null_hid, + NULL, +}; + +/** + * hid_driver_find_handle: + * @idx : index of driver to get handle to. + * + * Returns: handle to HID driver at index. Can be NULL + * if nothing found. + **/ +const void *hid_driver_find_handle(int idx) +{ + const void *drv = hid_drivers[idx]; + if (!drv) + return NULL; + return drv; +} + +/** + * hid_driver_find_ident: + * @idx : index of driver to get handle to. + * + * Returns: Human-readable identifier of HID driver at index. Can be NULL + * if nothing found. + **/ +const char *hid_driver_find_ident(int idx) +{ + const hid_driver_t *drv = hid_drivers[idx]; + if (!drv) + return NULL; + return drv->ident; +} + +/** + * config_get_hid_driver_options: + * + * Get an enumerated list of all HID driver names, separated by '|'. + * + * Returns: string listing of all HID driver names, separated by '|'. + **/ +const char* config_get_hid_driver_options(void) +{ + return char_list_new_special(STRING_LIST_INPUT_HID_DRIVERS, NULL); +} + +/** + * input_hid_init_first: + * + * Finds first suitable HID driver and initializes. + * + * Returns: HID driver if found, otherwise NULL. + **/ +const hid_driver_t *input_hid_init_first(void) +{ + unsigned i; + + for (i = 0; hid_drivers[i]; i++) + { + driver_t *driver = driver_get_ptr(); + driver->hid_data = hid_drivers[i]->init(); + + if (driver->hid_data) + { + RARCH_LOG("Found HID driver: \"%s\".\n", + hid_drivers[i]->ident); + return hid_drivers[i]; + } + } + + return NULL; +} diff --git a/pool/shard002/C/0063404_nwrite.c b/pool/shard002/C/0063404_nwrite.c new file mode 100644 index 0000000000000000000000000000000000000000..4b83e5aa1f309110e8929e3823ff26dc714909bd --- /dev/null +++ b/pool/shard002/C/0063404_nwrite.c @@ -0,0 +1,23 @@ +#include +#include +#include +#include +#include +#include +ktime_t ktime_get(void); + +asmlinkage size_t sys_nwrite(unsigned long fd, const char __user *buf, size_t count) { + ktime_t start, end; + s64 atime; + start = ktime_get(); + + size_t ret; + // printk(KERN_ALERT "[sensong] sys_nwrite()\n"); + ret = nm_top_write(fd, buf, count); + end = ktime_get(); + atime = ktime_to_ns(ktime_sub(end, start)); + printk(KERN_ALERT "[sensong] sys_nwrite() execution time = %lld\n", atime); + return ret; +} +// asmlinkage long sys_nread(unsigned int fd, char __user *buf, size_t count); + diff --git a/pool/shard002/C/0063430_array.c b/pool/shard002/C/0063430_array.c new file mode 100644 index 0000000000000000000000000000000000000000..ee769e297f0134d2cc9bb085ef5104e51672dd3f --- /dev/null +++ b/pool/shard002/C/0063430_array.c @@ -0,0 +1,139 @@ +/* + * Copyright(C) 2016 Pedro H. Penna + * + * This file is part of MyLib. + * + * MyLib 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. + * + * MyLib 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 MyLib; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA + * 02110-1301, USA. + */ + +#include +#include + +#include + +/** + * @brief Array. + */ +struct array +{ + int size; /**< Maximum size. */ + void **elements; /**< Elements. */ +}; + +/** + * @brief Creates an array. + * + * @param size Array size. + */ +struct array *array_create(int size) +{ + struct array *a; + + /* Sanity check. */ + assert(size >= 0); + + /* Create array. */ + a = smalloc(sizeof(struct array)); + a->size = size; + a->elements = smalloc(size*sizeof(void *)); + + return (a); +} + +/** + * @brief Destroys an array. + * + * @param a Target array. + */ +void array_destroy(struct array *a) +{ + /* Sanity check. */ + assert(a != NULL); + + free(a->elements); + free(a); +} + +/** + * @brief Returns the size of an array. + * + * @param a Target array. + */ +int array_size(const struct array *a) +{ + /* Sanity check. */ + assert(a != NULL); + + return (a->size); +} + +/** + * @brief Sets the ith element of an array. + * + * @param a Target array. + * @param idx Index. + * @param obj Object. + */ +void array_set(struct array *a, int idx, void *obj) +{ + /* Sanity check. */ + assert(a != NULL); + assert((idx >= 0) && (idx < a->size)); + assert(obj != NULL); + + a->elements[idx] = obj; +} + +/** + * @brief Gets the ith element of an array. + * + * @param a Target array. + * @param idx Index. + * + * @returns The ith element of the target array. + */ +void *array_get(const struct array *a, int idx) +{ + /* Sanity check. */ + assert(a != NULL); + assert((idx >= 0) && (idx < a->size)); + + return (a->elements[idx]); +} + +/** + * @brief Shuffles an array. + * + * @param a Target array. + */ +void array_shuffle(struct array *a) +{ + /* Sanity check. */ + assert(a != NULL); + + /* Shuffle array. */ + for (int i = 0; i < a->size - 1; i++) + { + int j; /* Shuffle index. */ + void *tmp; /* Temporary data. */ + + j = rand()%a->size; + + tmp = a->elements[i]; + a->elements[i] = a->elements[j]; + a->elements[j] = tmp; + } +} diff --git a/pool/shard002/C/0063435_ipa-icf-13.c b/pool/shard002/C/0063435_ipa-icf-13.c new file mode 100644 index 0000000000000000000000000000000000000000..9bd16b0c1cb631897582304bf008a0a721541f12 --- /dev/null +++ b/pool/shard002/C/0063435_ipa-icf-13.c @@ -0,0 +1,193 @@ +/* { dg-do compile } */ +/* { dg-options "-O2 -fdump-ipa-icf-optimized-all-all" } */ + +#include +#include + +int gcd(int x, int y) __attribute__ ((pure)); + +__attribute__ ((noinline)) +int gcd(int x, int y) +{ + int swap; + + if(x <= 0 || y <= 0) + return 0; + + if(x < y) + { + swap = x; + x = y; + y = swap; + } + + while(x != y) + { + x = x - y; + + if(y > x) + { + swap = x; + x = y; + y = swap; + } + } + + return x; +} + +int nsd(int x, int y) __attribute__ ((pure)); + +__attribute__ ((noinline)) +int nsd(int x, int y) +{ + int swap; + + if(x <= 0 || y <= 0) + return 0; + + if(x < y) + { + swap = x; + x = y; + y = swap; + } + + while(x != y) + { + x = x - y; + + if(y > x) + { + swap = x; + x = y; + y = swap; + } + } + + return x; +} + +int nsd_different_result(int x, int y) __attribute__ ((pure)); + +__attribute__ ((noinline)) +int nsd_different_result(int x, int y) +{ + int pes; + + if(x <= 0 || y <= 0) + return 1; + + if(x < 10) + y = 12; + else if(x == 44) + y = 124; + else + y = 1111; + + if(x < y) + { + pes = x; + x = y; + y = pes; + } + + while(x != y) + { + x = x - y; + + if(y > x) + { + pes = x; + x = y; + y = pes; + } + } + + return x; +} + +int nsd_different_result2(int x, int y) __attribute__ ((pure)); + +__attribute__ ((noinline)) +int nsd_different_result2(int x, int y) +{ + int pes; + + if(x <= 0 || y <= 0) + return 1; + + if(x < 10) + y = 12; + else if(x == 44) + y = 124; + else + y = 1111; + + if(x < y) + { + pes = x; + x = y; + y = pes; + } + + while(x != y) + { + x = x - y; + + if(y > x) + { + pes = x; + x = y; + y = pes; + } + } + + return x; +} + +__attribute__ ((noinline)) +int s1(int x) +{ + switch (x) + { + case 10: + case 11: + return 2; + case 12: + return 123; + default: + return x + 2; + } +} + +__attribute__ ((noinline)) +int s2(int x) +{ + switch (x) + { + case 10: + case 11: + return 2; + case 12: + return 123; + default: + return x + 2; + } +} +int main(int argc, char **argv) +{ + if(argc < 3) + return 1; + + int a = atoi(argv[1]); + int b = atoi(argv[2]); + + printf("Test1: %d, %d, gdc: %d\n", a, b, gcd(a, b)); + printf("Test2: %d, %d, gdc: %d\n", a, b, nsd(a, b)); +} + +/* { dg-final { scan-ipa-dump "Semantic equality hit:s1/\[0-9+\]+->s2/\[0-9+\]+" "icf" } } */ +/* { dg-final { scan-ipa-dump "Semantic equality hit:nsd_different_result/\[0-9+\]+->nsd_different_result2/\[0-9+\]+" "icf" } } */ +/* { dg-final { scan-ipa-dump "Semantic equality hit:gcd/\[0-9+\]+->nsd/\[0-9+\]+" "icf" } } */ +/* { dg-final { scan-ipa-dump "Equal symbols: 3" "icf" } } */ diff --git a/pool/shard002/C/0063437_zatabase.c b/pool/shard002/C/0063437_zatabase.c new file mode 100644 index 0000000000000000000000000000000000000000..6b53a441c1695834bc8500c8605b811ee267e7e4 --- /dev/null +++ b/pool/shard002/C/0063437_zatabase.c @@ -0,0 +1,273 @@ + +/* This file was generated automatically by Zephir do not modify it! */ + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +#include + +#if PHP_VERSION_ID < 50500 +#include +#endif + +#include "php_ext.h" +#include "zatabase.h" + +#include + +#include +#include +#include + +#include "kernel/main.h" +#include "kernel/fcall.h" +#include "kernel/memory.h" + + + +zend_class_entry *zatabase_di_injectionawareinterface_ce; +zend_class_entry *zatabase_di_serviceinterface_ce; +zend_class_entry *zatabase_diinterface_ce; +zend_class_entry *zatabase_di_injectable_ce; +zend_class_entry *zatabase_exception_ce; +zend_class_entry *zatabase_execute_querytype_ce; +zend_class_entry *zatabase_execute_condition_ce; +zend_class_entry *zatabase_table_relation_ce; +zend_class_entry *zatabase_0__closure_ce; +zend_class_entry *zatabase_1__closure_ce; +zend_class_entry *zatabase_2__closure_ce; +zend_class_entry *zatabase_3__closure_ce; +zend_class_entry *zatabase_4__closure_ce; +zend_class_entry *zatabase_5__closure_ce; +zend_class_entry *zatabase_db_ce; +zend_class_entry *zatabase_db_exception_ce; +zend_class_entry *zatabase_di_ce; +zend_class_entry *zatabase_di_exception_ce; +zend_class_entry *zatabase_di_service_builder_ce; +zend_class_entry *zatabase_di_service_ce; +zend_class_entry *zatabase_execute_ce; +zend_class_entry *zatabase_execute_complexresults_ce; +zend_class_entry *zatabase_execute_condition_between_ce; +zend_class_entry *zatabase_execute_condition_equals_ce; +zend_class_entry *zatabase_execute_condition_exception_ce; +zend_class_entry *zatabase_execute_condition_lessthan_ce; +zend_class_entry *zatabase_execute_condition_like_ce; +zend_class_entry *zatabase_execute_condition_morethan_ce; +zend_class_entry *zatabase_execute_condition_within_ce; +zend_class_entry *zatabase_execute_delete_ce; +zend_class_entry *zatabase_execute_exception_ce; +zend_class_entry *zatabase_execute_insert_ce; +zend_class_entry *zatabase_execute_results_ce; +zend_class_entry *zatabase_execute_select_ce; +zend_class_entry *zatabase_execute_update_ce; +zend_class_entry *zatabase_helper_arraytoobject_ce; +zend_class_entry *zatabase_helper_csv_ce; +zend_class_entry *zatabase_helper_exception_ce; +zend_class_entry *zatabase_helper_filehandler_ce; +zend_class_entry *zatabase_schema_alter_ce; +zend_class_entry *zatabase_schema_ce; +zend_class_entry *zatabase_schema_exception_ce; +zend_class_entry *zatabase_storage_adapter_file_ce; +zend_class_entry *zatabase_storage_btree_ce; +zend_class_entry *zatabase_storage_btree_node_ce; +zend_class_entry *zatabase_storage_btree_node_element_ce; +zend_class_entry *zatabase_storage_exception_ce; +zend_class_entry *zatabase_table_ce; +zend_class_entry *zatabase_table_column_ce; +zend_class_entry *zatabase_table_exception_ce; +zend_class_entry *zatabase_table_relations_belongsto_ce; +zend_class_entry *zatabase_table_relations_hasone_ce; + +ZEND_DECLARE_MODULE_GLOBALS(zatabase) + +static PHP_MINIT_FUNCTION(zatabase) +{ +#if PHP_VERSION_ID < 50500 + char* old_lc_all = setlocale(LC_ALL, NULL); + if (old_lc_all) { + size_t len = strlen(old_lc_all); + char *tmp = calloc(len+1, 1); + if (UNEXPECTED(!tmp)) { + return FAILURE; + } + + memcpy(tmp, old_lc_all, len); + old_lc_all = tmp; + } + + setlocale(LC_ALL, "C"); +#endif + + ZEPHIR_INIT(ZataBase_Di_InjectionAwareInterface); + ZEPHIR_INIT(ZataBase_DiInterface); + ZEPHIR_INIT(ZataBase_Di_ServiceInterface); + ZEPHIR_INIT(ZataBase_Di_Injectable); + ZEPHIR_INIT(ZataBase_Exception); + ZEPHIR_INIT(ZataBase_Execute_QueryType); + ZEPHIR_INIT(ZataBase_Execute_Condition); + ZEPHIR_INIT(ZataBase_Table_Relation); + ZEPHIR_INIT(ZataBase_Db); + ZEPHIR_INIT(ZataBase_Db_Exception); + ZEPHIR_INIT(ZataBase_Di); + ZEPHIR_INIT(ZataBase_Di_Exception); + ZEPHIR_INIT(ZataBase_Di_Service); + ZEPHIR_INIT(ZataBase_Di_Service_Builder); + ZEPHIR_INIT(ZataBase_Execute); + ZEPHIR_INIT(ZataBase_Execute_ComplexResults); + ZEPHIR_INIT(ZataBase_Execute_Condition_Between); + ZEPHIR_INIT(ZataBase_Execute_Condition_Equals); + ZEPHIR_INIT(ZataBase_Execute_Condition_Exception); + ZEPHIR_INIT(ZataBase_Execute_Condition_LessThan); + ZEPHIR_INIT(ZataBase_Execute_Condition_Like); + ZEPHIR_INIT(ZataBase_Execute_Condition_MoreThan); + ZEPHIR_INIT(ZataBase_Execute_Condition_Within); + ZEPHIR_INIT(ZataBase_Execute_Delete); + ZEPHIR_INIT(ZataBase_Execute_Exception); + ZEPHIR_INIT(ZataBase_Execute_Insert); + ZEPHIR_INIT(ZataBase_Execute_Results); + ZEPHIR_INIT(ZataBase_Execute_Select); + ZEPHIR_INIT(ZataBase_Execute_Update); + ZEPHIR_INIT(ZataBase_Helper_ArrayToObject); + ZEPHIR_INIT(ZataBase_Helper_Csv); + ZEPHIR_INIT(ZataBase_Helper_Exception); + ZEPHIR_INIT(ZataBase_Helper_FileHandler); + ZEPHIR_INIT(ZataBase_Schema); + ZEPHIR_INIT(ZataBase_Schema_Alter); + ZEPHIR_INIT(ZataBase_Schema_Exception); + ZEPHIR_INIT(ZataBase_Storage_Adapter_File); + ZEPHIR_INIT(ZataBase_Storage_BTree); + ZEPHIR_INIT(ZataBase_Storage_BTree_Node); + ZEPHIR_INIT(ZataBase_Storage_BTree_Node_Element); + ZEPHIR_INIT(ZataBase_Storage_Exception); + ZEPHIR_INIT(ZataBase_Table); + ZEPHIR_INIT(ZataBase_Table_Column); + ZEPHIR_INIT(ZataBase_Table_Exception); + ZEPHIR_INIT(ZataBase_Table_Relations_BelongsTo); + ZEPHIR_INIT(ZataBase_Table_Relations_HasOne); + ZEPHIR_INIT(zatabase_0__closure); + ZEPHIR_INIT(zatabase_1__closure); + ZEPHIR_INIT(zatabase_2__closure); + ZEPHIR_INIT(zatabase_3__closure); + ZEPHIR_INIT(zatabase_4__closure); + ZEPHIR_INIT(zatabase_5__closure); + +#if PHP_VERSION_ID < 50500 + setlocale(LC_ALL, old_lc_all); + free(old_lc_all); +#endif + return SUCCESS; +} + +#ifndef ZEPHIR_RELEASE +static PHP_MSHUTDOWN_FUNCTION(zatabase) +{ + + zephir_deinitialize_memory(TSRMLS_C); + + return SUCCESS; +} +#endif + +/** + * Initialize globals on each request or each thread started + */ +static void php_zephir_init_globals(zend_zatabase_globals *zephir_globals TSRMLS_DC) +{ + zephir_globals->initialized = 0; + + /* Memory options */ + zephir_globals->active_memory = NULL; + + /* Virtual Symbol Tables */ + zephir_globals->active_symbol_table = NULL; + + /* Cache Enabled */ + zephir_globals->cache_enabled = 1; + + /* Recursive Lock */ + zephir_globals->recursive_lock = 0; + + +} + +static PHP_RINIT_FUNCTION(zatabase) +{ + + zend_zatabase_globals *zephir_globals_ptr = ZEPHIR_VGLOBAL; + + php_zephir_init_globals(zephir_globals_ptr TSRMLS_CC); + //zephir_init_interned_strings(TSRMLS_C); + + zephir_initialize_memory(zephir_globals_ptr TSRMLS_CC); + + return SUCCESS; +} + +static PHP_RSHUTDOWN_FUNCTION(zatabase) +{ + + + + zephir_deinitialize_memory(TSRMLS_C); + return SUCCESS; +} + +static PHP_MINFO_FUNCTION(zatabase) +{ + php_info_print_box_start(0); + php_printf("%s", PHP_ZATABASE_DESCRIPTION); + php_info_print_box_end(); + + php_info_print_table_start(); + php_info_print_table_header(2, PHP_ZATABASE_NAME, "enabled"); + php_info_print_table_row(2, "Author", PHP_ZATABASE_AUTHOR); + php_info_print_table_row(2, "Version", PHP_ZATABASE_VERSION); + php_info_print_table_row(2, "Powered by Zephir", "Version " PHP_ZATABASE_ZEPVERSION); + php_info_print_table_end(); + + +} + +static PHP_GINIT_FUNCTION(zatabase) +{ + php_zephir_init_globals(zatabase_globals TSRMLS_CC); +} + +static PHP_GSHUTDOWN_FUNCTION(zatabase) +{ + +} + + +zend_function_entry php_zatabase_functions[] = { +ZEND_FE_END + +}; + +zend_module_entry zatabase_module_entry = { + STANDARD_MODULE_HEADER_EX, + NULL, + NULL, + PHP_ZATABASE_EXTNAME, + php_zatabase_functions, + PHP_MINIT(zatabase), +#ifndef ZEPHIR_RELEASE + PHP_MSHUTDOWN(zatabase), +#else + NULL, +#endif + PHP_RINIT(zatabase), + PHP_RSHUTDOWN(zatabase), + PHP_MINFO(zatabase), + PHP_ZATABASE_VERSION, + ZEND_MODULE_GLOBALS(zatabase), + PHP_GINIT(zatabase), + PHP_GSHUTDOWN(zatabase), + NULL, + STANDARD_MODULE_PROPERTIES_EX +}; + +#ifdef COMPILE_DL_ZATABASE +ZEND_GET_MODULE(zatabase) +#endif diff --git a/pool/shard002/C/0063438_hash.c b/pool/shard002/C/0063438_hash.c new file mode 100644 index 0000000000000000000000000000000000000000..8a3a2b722ec23d268a8b3bc09efbc1c766711abf --- /dev/null +++ b/pool/shard002/C/0063438_hash.c @@ -0,0 +1,238 @@ +#include + +void test_hash(); +void test_hash_methods(); +void hash_get(HempHash, char *); +void hash_set(HempHash table, HempString, HempString); +void hash_has(HempHash table, HempString, HempString); +void hash_hasnt(HempHash table, HempString); +void hash_has_keylen(HempHash table, HempString, HempSize, HempString); +void hash_hasnt_keylen(HempHash table, HempString, HempSize); +void hash_index_same(HempString, HempSize, HempString, HempSize); +void hash_index_different(HempString, HempSize, HempString, HempSize); +void hash_keys_do_match(HempString, HempString, HempSize); +void hash_keys_no_match(HempString, HempString, HempSize); + + +int main( + int argc, char **argv, char **env +) { + plan(28); + test_hash(); + test_hash_methods(); + return done(); +} + + +void test_hash() { + HempHash table = hemp_hash_new(); + HempHash child = hemp_hash_new(); + + + hash_index_same( + "foo", 3, + "food", 3 + ); + hash_index_different( + "foo", 3, + "food", 4 + ); + hash_index_same( + "Rachmaninov", 6, + "Rachmaninoff", 6 + ); + hash_index_same( + "Rachmaninov", 10, + "Rachmaninoff", 10 + ); + hash_index_different( + "Rachmaninov", 11, + "Rachmaninoff", 11 + ); + hash_index_different( + "Rachmaninoff", 11, + "Rachmaninoff", 12 + ); + + /* it's OK for a key in the hash (first arg) to match a prefix substring + * of the search key (second arg), but not OK for a search key to match a + * prefix of the hash key + */ + hash_keys_do_match("foo", "food", 3); + hash_keys_no_match("food", "foo", 3); + + hash_set(table, "msg", "hello world"); + hash_has(table, "msg", "hello world"); + + hash_set(child, "foo", "The foo item"); + hash_has(child, "foo", "The foo item"); + + hash_hasnt(child, "msg"); + + hemp_hash_attach(child, table); + + hash_has(child, "foo", "The foo item"); + hash_has(child, "msg", "hello world"); + + hash_set(table, "bar", "The bar item"); + hash_has(child, "bar", "The bar item"); + + hash_has_keylen(child, "food", 3, "The foo item"); + hash_has_keylen(child, "msgism", 3, "hello world"); + hash_hasnt_keylen(child, "msgism", 4); + + hemp_hash_detach(child); + + hash_hasnt(child, "msg"); + hash_has_keylen(child, "food", 3, "The foo item"); + hash_hasnt_keylen(child, "msgism", 3); + + hemp_hash_free(table); + hemp_hash_free(child); +} + + +void hash_keys_do_match( + HempString hash_key, + HempString search_key, + HempSize length +) { + ok( + hemp_hash_key_match(hash_key, search_key, length), + "match hash key [%s] with search key [%s] length [%d]", + hash_key, search_key, length + ); +} + + +void hash_keys_no_match( + HempString hash_key, + HempString search_key, + HempSize length +) { + ok( + ! hemp_hash_key_match(hash_key, search_key, length), + "no hash key [%s] with search key [%s] length [%d]", + hash_key, search_key, length + ); +} + +void hash_index_same( + HempString key1, + HempSize len1, + HempString key2, + HempSize len2 +) { + HempSize hash1 = hemp_hash_function(key1, len1); + HempSize hash2 = hemp_hash_function(key2, len2); + ok( hash1 == hash2, "hash(%s[%d]) == hash(%s[%d])", key1, len1, key2, len2); +} + + +void hash_index_different( + HempString key1, + HempSize len1, + HempString key2, + HempSize len2 +) { + HempSize hash1 = hemp_hash_function(key1, len1); + HempSize hash2 = hemp_hash_function(key2, len2); + ok( hash1 != hash2, "hash(%s[%d]) != hash(%s[%d])", key1, len1, key2, len2); +} + + +void +hash_has( + HempHash table, + HempString key, + HempString expect +) { + HempString value = hemp_hash_fetch_string(table, key); + ok( + value && hemp_string_eq(value, expect), + "found %s => %s", key, value + ); +} + + +void +hash_hasnt( + HempHash table, + HempString key +) { + HempString value = hemp_hash_fetch_string(table, key); + ok( ! value, "no entry for %s", key); +} + + +void +hash_has_keylen( + HempHash table, + HempString key, + HempSize length, + HempString expect +) { + HempValue value = hemp_hash_fetch_keylen(table, key, length); + + if (hemp_is_missing(value)) { + fail("not found: %s (length:%d)", key, length); + } + else { + HempString str = hemp_val_str(value); + ok( + str && hemp_string_eq(str, expect), + "found %s (length: %d) => %s", key, length, str + ); + } +} + +void +hash_hasnt_keylen( + HempHash table, + HempString key, + HempSize length +) { + HempValue value = hemp_hash_fetch_keylen(table, key, length); + ok( hemp_is_missing(value), "no entry for %s (length: %d)", key, length); +} + + +void +hash_set( + HempHash table, + HempString key, + HempString value +) { + ok( + hemp_hash_store_string(table, key, value), + "set %s to %s", key, value + ); +} + + +void test_hash_methods() { + Hemp hemp = hemp_new(); + HempHash hash = hemp_hash_new(); +// HempText text = hemp_text_from_string("Hello World!"); + HempValue value = hemp_hash_val(hash); + HempContext context = hemp_context(hemp); + + hemp_hash_store_string(hash, "message", "Hello World"); + hemp_hash_store_integer(hash, "answer", 42); + hemp_hash_store_number(hash, "pi", 3.14159); + + ok( hemp_is_hash(value), "value is a hash" ); + + HempValue length = hemp_send(value, "length", context); + ok( hemp_is_defined(length), "got defined length" ); + ok( hemp_is_integer(length), "got an integer length" ); + eq( hemp_val_int(length), 3, "hash length is 3" ); + + HempValue htext = hemp_send(value, "text", context); + ok( hemp_is_text(htext), "got hash as text" ); + + hemp_context_free(context); + hemp_hash_free(hash); +// hemp_text_free( hemp_val_text(htext) ); + hemp_free(hemp); +} \ No newline at end of file diff --git a/pool/shard002/C/0063449_hashbang.c b/pool/shard002/C/0063449_hashbang.c new file mode 100644 index 0000000000000000000000000000000000000000..7941a3f2a6dde7f9a4e74f169a5d56aa75816dbd --- /dev/null +++ b/pool/shard002/C/0063449_hashbang.c @@ -0,0 +1,135 @@ +/*********************************************************** +* +* PROGRAM: hashbang +* +* DESCRIPTION: allow a #! to call a #! +* +* USAGE: #!/usr/local/bin/hashbang perl!-lpi.bak +* +***********************************************************/ + +#include +#include +#include +#include +#include "topher.h" + +//extern char *optarg; +//extern int optind, optopt; + +int main(int argc, char *argv[]) +{ + char *inter; /* the interpreter */ + char *largs[32]; /* local (hashbang) flags */ + char *pargs[32]; /* passthru (interpreter) flags */ + char *pos; /* temp pointer */ + char delim = '!'; /* the argument delimiter */ + int c; /* temp char */ + bool errflg = FALSE; /* switch error flag */ + int i = 0; + int j = 0; + int k = 0; + bool found = FALSE; /* interpreter arg found */ + gid_t rgid,egid,fgid; /* real, effective, and file gid */ + uid_t ruid,euid,fuid; /* real, effective, and file uid */ + struct stat finfo; /* stat struct for script info */ + mode_t fmode; /* mode of script */ + bool setgroup = FALSE; /* set group-id flag */ + bool setuser = FALSE; /* set user-id flag */ + + rgid = egid = getgid(); + ruid = euid = getuid(); + + if(argc < 3) + { + printf("Usage: #!/usr/local/bin/hashbang shell!args\n"); + exit(EXIT_FAILURE); + } + largs[j++] = argv[0]; + pos = argv[1]; + while(pos) + { + if(((*pos) == '-')&&(! found)) + { + largs[j++] = pos; + } + else if(!found) + { + if(stat(argv[2], &finfo)) + { + PERROR(argv[2]); + } + fgid = finfo.st_gid; + fuid = finfo.st_uid; + fmode= finfo.st_mode; + setgroup = ((fmode & S_ISGID) == S_ISGID); + setuser = ((fmode & S_ISUID) == S_ISUID); + inter = pos; + pargs[i++] = pos; + found = TRUE; + while ((c = getopt(j, largs, "red:")) != -1) + { + switch (c) + { + case 'r': + if(setgroup) + { + rgid = egid = fgid; + } + if(setuser) + { + ruid = euid = fuid; + } + break; + case 'e': + if(setgroup) + { + egid = fgid; + } + if(setuser) + { + euid = fuid; + } + break; + case 'd': + delim = optarg[0]; + break; + case '?': + errflg++; + break; + } + } + if((getgid() != rgid) || (getegid() != egid)) + { + if(setregid(rgid,egid)) + { + PERROR("setgid"); + } + } + if((getuid() != ruid) || (geteuid() != euid)) + { + if(setreuid(ruid,euid)) + { + PERROR("setuid"); + } + } + } + else + { + pargs[i++] = pos; + } + pos = (char *)strchr(pos,delim); + if(pos) + { + (*pos) = '\0'; + pos++; + } + } + for(k=2;k + * + * 1. Block on a bitset futex and wait for timeout, the difference between + * normal futex and bitset futex is that that the later have absolute timeout. + * 2. Check that the futex waited for expected time. + */ + +#include + +#include "tst_test.h" +#include "tst_timer.h" +#include "futextest.h" + +#define THRESHOLD_US 100000 +#define DEFAULT_TIMEOUT_US 100010 + +static struct test_case_t { + clockid_t clk_id; +} tcases[] = { + { CLOCK_MONOTONIC }, + { CLOCK_REALTIME } +}; + +static void verify_futex_wait_bitset(long long wait_us, clock_t clk_id) +{ + struct timespec start, to, end; + futex_t futex = FUTEX_INITIALIZER; + u_int32_t bitset = 0xffffffff; + int flags = clk_id == CLOCK_REALTIME ? FUTEX_CLOCK_REALTIME : 0; + + tst_res(TINFO, "testing futex_wait_bitset() timeout with %s", + clk_id == CLOCK_REALTIME ? "CLOCK_REALTIME" : "CLOCK_MONOTONIC"); + + clock_gettime(clk_id, &start); + to = tst_timespec_add_us(start, wait_us); + + TEST(futex_wait_bitset(&futex, futex, &to, bitset, flags)); + + clock_gettime(clk_id, &end); + + if (TST_RET != -1) { + tst_res(TFAIL, "futex_wait_bitset() returned %li, expected -1", + TST_RET); + return; + } + + if (TST_ERR == ENOSYS) { + tst_res(TCONF, + "In this kernel, futex() does not support FUTEX_WAIT_BITSET operation"); + return; + } + + if (TST_ERR != ETIMEDOUT) { + tst_res(TFAIL | TTERRNO, "expected %s", + tst_strerrno(ETIMEDOUT)); + return; + } + + if (tst_timespec_lt(end, to)) { + tst_res(TFAIL, + "futex_wait_bitset() woken up prematurely %llius, expected %llius", + tst_timespec_diff_us(end, start), wait_us); + return; + } + + if (tst_timespec_diff_us(end, to) > THRESHOLD_US) { + tst_res(TFAIL, + "futex_wait_bitset() waited too long %llius, expected %llius", + tst_timespec_diff_us(end, start), wait_us); + return; + } + + tst_res(TPASS, "futex_wait_bitset() waited %llius, expected %llius", + tst_timespec_diff_us(end, start), wait_us); +} + +static void run(unsigned int n) +{ + verify_futex_wait_bitset(DEFAULT_TIMEOUT_US, tcases[n].clk_id); +} + +static struct tst_test test = { + .test = run, + .tcnt = ARRAY_SIZE(tcases), +}; diff --git a/pool/shard002/C/0063453_test-RSVarintFread64.c b/pool/shard002/C/0063453_test-RSVarintFread64.c new file mode 100644 index 0000000000000000000000000000000000000000..7168569f3dcf12d0c82f1326431aabad3606a7ed --- /dev/null +++ b/pool/shard002/C/0063453_test-RSVarintFread64.c @@ -0,0 +1,62 @@ +#include +#include + +void test_RSVarintFread64() { + DESCRIBE("RSVarintFread64"); + uint64_t value; + FILE *file; + int ok; + + IT("errors if the file pointer is null") { + ok = RSVarintFread64(NULL, &value); + assert_ints_equal(ok, 0); + } + + IT("errors if the file is empty") { + file = assert_fopen("fixtures/empty_file", "r"); + ok = RSVarintFread64(file, &value); + assert_ints_equal(ok, 0); + fclose(file); + } + + IT("errors when reading a non-empty incomplete varint") { + file = assert_fopen("fixtures/128_truncated.varint", "r"); + ok = RSVarintFread64(file, &value); + assert_ints_equal(ok, 0); + fclose(file); + } + + IT("errors when reading 2**64") { + file = assert_fopen("fixtures/largest_uint64_plus_one.varint", "r"); + ok = RSVarintFread64(file, &value); + assert_ints_equal(ok, 0); + fclose(file); + } + + IT("reads (2**64 - 1)") { + value = 2; + file = assert_fopen("fixtures/largest_uint64.varint", "r"); + ok = RSVarintFread64(file, &value); + assert_ints_equal(ok, 1); + assert_uints_equal(value, 18446744073709551615ull); + fclose(file); + } + + IT("reads 0") { + value = 2; + file = assert_fopen("fixtures/0.varint", "r"); + ok = RSVarintFread64(file, &value); + assert_ints_equal(ok, 1); + assert_uints_equal(value, 0); + fclose(file); + } + + IT("reads 128") { + value = 2; + file = assert_fopen("fixtures/128.varint", "r"); + ok = RSVarintFread64(file, &value); + assert_ints_equal(ok, 1); + // assert_uints_equal(value, 128); + fclose(file); + } +} diff --git a/pool/shard002/C/0063470_html.c b/pool/shard002/C/0063470_html.c new file mode 100644 index 0000000000000000000000000000000000000000..8d41983e662fac83d1b9789a4c4ace47b2102a2c --- /dev/null +++ b/pool/shard002/C/0063470_html.c @@ -0,0 +1,143 @@ +/***************************************************************************** + * html.c : HTML playlist export module + ***************************************************************************** + * Copyright (C) 2008-2009 the VideoLAN team + * $Id$ + * + * Authors: Rémi Duraffort + * + * 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. + *****************************************************************************/ + +#ifdef HAVE_CONFIG_H +# include "config.h" +#endif + +#include +#include +#include +#include + +#include + + +// Export the playlist in HTML +int Export_HTML( vlc_object_t *p_this ); + + +/** + * Recursively follow the playlist + * @param p_export: the export structure + * @param p_root: the current node + */ +static void DoChildren( playlist_export_t *p_export, playlist_item_t *p_root ) +{ + /* Go through the playlist and add items */ + for( int i = 0; i < p_root->i_children ; i++) + { + playlist_item_t *p_current = p_root->pp_children[i]; + assert( p_current ); + + if( p_current->i_flags & PLAYLIST_SAVE_FLAG ) + continue; + + if( p_current->i_children >= 0 ) + { + DoChildren( p_export, p_current ); + continue; + } + + char* psz_name = NULL; + char *psz_tmp = input_item_GetName( p_current->p_input ); + if( psz_tmp ) + psz_name = vlc_xml_encode( psz_tmp ); + free( psz_tmp ); + + if( psz_name ) + { + char* psz_artist = NULL; + psz_tmp = input_item_GetArtist( p_current->p_input ); + if( psz_tmp ) + psz_artist = vlc_xml_encode( psz_tmp ); + free( psz_tmp ); + + mtime_t i_duration = input_item_GetDuration( p_current->p_input ); + int min = ( i_duration / 1000000 ) / 60; + int sec = ( i_duration / 1000000 ) - min * 60; + + // Print the artist if we have one + if( psz_artist && *psz_artist ) + fprintf( p_export->p_file, "
  • %s - %s (%02d:%02d)
  • \n", psz_artist, psz_name, min, sec ); + else + fprintf( p_export->p_file, "
  • %s (%2d:%2d)
  • \n", psz_name, min, sec ); + + free( psz_artist ); + } + free( psz_name ); + } +} + + +/** + * Export the playlist as an HTML page + * @param p_this: the playlist + * @return VLC_SUCCESS if everything goes fine + */ +int Export_HTML( vlc_object_t *p_this ) +{ + playlist_export_t *p_export = (playlist_export_t *)p_this; + + msg_Dbg( p_export, "saving using HTML format" ); + + /* Write header */ + fprintf( p_export->p_file, "\n" +"\n" +"\n" +"\n" +" \n" +" \n" +" \n" +" VLC generated playlist\n" +" \n" +"\n\n" +"\n" +"

    Playlist

    \n" +"
    \n" +"
      \n" ); + + // Call the playlist constructor + DoChildren( p_export, p_export->p_root ); + + // Print the footer + fprintf( p_export->p_file, "
    \n" +"
    \n" +"\n" +"" ); + return VLC_SUCCESS; +} + diff --git a/pool/shard002/C/0063473_gvloadimage_poppler.c b/pool/shard002/C/0063473_gvloadimage_poppler.c new file mode 100644 index 0000000000000000000000000000000000000000..66c8af87f3208452de383da84962008fa8e9e633 --- /dev/null +++ b/pool/shard002/C/0063473_gvloadimage_poppler.c @@ -0,0 +1,167 @@ +/* $Id$ $Revision$ */ +/* vim:set shiftwidth=4 ts=8: */ + +/************************************************************************* + * Copyright (c) 2011 AT&T Intellectual Property + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/epl-v10.html + * + * Contributors: See CVS logs. Details at http://www.graphviz.org/ + *************************************************************************/ + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +#include +#include + +#include "gvplugin_loadimage.h" + +#ifdef HAVE_PANGOCAIRO +#ifdef HAVE_POPPLER +#include +#include + +#ifdef WIN32 +#define NUL_FILE "nul" +#else +#define NUL_FILE "/dev/null" +#endif + +typedef enum { + FORMAT_PDF_CAIRO, +} format_type; + + +static void gvloadimage_poppler_free(usershape_t *us) +{ + g_object_unref((PopplerDocument*)us->data); +} + +static PopplerDocument* gvloadimage_poppler_load(GVJ_t * job, usershape_t *us) +{ + PopplerDocument *document = NULL; + GError *error; + gchar *absolute, *uri; + int num_pages; + + assert(job); + assert(us); + assert(us->name); + + if (us->data) { + if (us->datafree == gvloadimage_poppler_free) + document = (PopplerDocument*)(us->data); /* use cached data */ + else { + us->datafree(us); /* free incompatible cache data */ + us->data = NULL; + us->datafree = NULL; + } + + } + + if (!document) { /* read file into cache */ + if (!gvusershape_file_access(us)) + return NULL; + switch (us->type) { + case FT_PDF: + + if (g_path_is_absolute(us->name)) { + absolute = g_strdup (us->name); + } else { + gchar *dir = g_get_current_dir (); + absolute = g_build_filename (dir, us->name, (gchar *) 0); + free (dir); + } + + uri = g_filename_to_uri (absolute, NULL, &error); + + free (absolute); + if (uri == NULL) { + printf("%s\n", error->message); + return NULL; + } + + document = poppler_document_new_from_file (uri, NULL, &error); + if (document == NULL) { + printf("%s\n", error->message); + return NULL; + } + + // check page 1 exists + + num_pages = poppler_document_get_n_pages (document); + if (num_pages < 1) { + printf("poppler fail: num_pages %d, must be at least 1", num_pages); + return NULL; + } + break; + + default: + break; + } + + if (document) { + us->data = (void*)document; + us->datafree = gvloadimage_poppler_free; + } + + gvusershape_file_release(us); + } + + return document; +} + +static void gvloadimage_poppler_cairo(GVJ_t * job, usershape_t *us, boxf b, boolean filled) +{ + PopplerDocument* document = gvloadimage_poppler_load(job, us); + PopplerPage* page; + + cairo_t *cr = (cairo_t *) job->context; /* target context */ + cairo_surface_t *surface; /* source surface */ + + if (document) { + + // already done this once, so no err checking + page = poppler_document_get_page (document, 0); + + cairo_save(cr); + +// FIXME +#define IMAGE_DPI 72 + surface = cairo_image_surface_create (CAIRO_FORMAT_ARGB32, + IMAGE_DPI*(us->w)/72.0, + IMAGE_DPI*(us->h)/72.0); + + cairo_surface_reference(surface); + + cairo_set_source_surface(cr, surface, 0, 0); + + cairo_translate(cr, ROUND(b.LL.x), ROUND(-b.UR.y)); + cairo_scale(cr, (b.UR.x - b.LL.x) / us->w, + (b.UR.y - b.LL.y) / us->h); + + poppler_page_render (page, cr); + cairo_paint (cr); + + cairo_restore(cr); + } +} + +static gvloadimage_engine_t engine_cairo = { + gvloadimage_poppler_cairo +}; +#endif +#endif + +gvplugin_installed_t gvloadimage_poppler_types[] = { +#ifdef HAVE_PANGOCAIRO +#ifdef HAVE_POPPLER + {FORMAT_PDF_CAIRO, "pdf:cairo", 1, &engine_cairo, NULL}, +#endif +#endif + {0, NULL, 0, NULL, NULL} +}; diff --git a/pool/shard002/C/0063477_sbrk.c b/pool/shard002/C/0063477_sbrk.c new file mode 100644 index 0000000000000000000000000000000000000000..b3409a9dd1766c2e30831139ea17c48c3783a449 --- /dev/null +++ b/pool/shard002/C/0063477_sbrk.c @@ -0,0 +1,41 @@ +/* Copyright (C) 1991-2016 Free Software Foundation, Inc. + This file is part of the GNU C Library. + + 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 + +/* Extend the process's data space by INCREMENT. + If INCREMENT is negative, shrink data space by - INCREMENT. + Return the address of the start of the new data space, or -1 for errors. */ +void * +__sbrk (intptr_t increment) +{ + void *result; + + HURD_CRITICAL_BEGIN; + __mutex_lock (&_hurd_brk_lock); + result = (void *) _hurd_brk; + if (increment != 0 && _hurd_set_brk (_hurd_brk + increment) < 0) + result = (void *) -1; + __mutex_unlock (&_hurd_brk_lock); + HURD_CRITICAL_END; + + return result; +} +libc_hidden_def (__sbrk) +weak_alias (__sbrk, sbrk) diff --git a/pool/shard002/C/0063493_fifo.c b/pool/shard002/C/0063493_fifo.c new file mode 100644 index 0000000000000000000000000000000000000000..6b617ab6fff316b79006a11da45df60c3197f7a8 --- /dev/null +++ b/pool/shard002/C/0063493_fifo.c @@ -0,0 +1,110 @@ +/************************************************************************************************************* + This file is part of HWMonitor. + + HWMonitor 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. + + HWMonitor 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 HWMonitor. If not, see . +*************************************************************************************************************/ + +#include +#include "fifo.h" +#include "log.h" +#include "allocators.h" + +void fifo_init(fifo_t** l, data_release_cb cb) { + *l = zalloc(sizeof(fifo_t)); + (*l)->rel_cb = cb; +} + +void fifo_node_init(fifo_node_t** node) { + *node = zalloc(sizeof(fifo_node_t)); +} + +void fifo_push(fifo_t* l, void* s) { + + if (!l->head) { + fifo_node_init(&l->head); + + fifo_node_t* node = l->head; + + node->data = s; + + l->top = l->head; + } else { + fifo_node_t* node = NULL; + fifo_node_init(&node); + node->data = s; + l->top->next = node; + + l->top = node; + + } + + ++l->size; +} + +void* fifo_pop(fifo_t* l) { + if (!l->head) + return NULL; + + fifo_node_t* tmp = l->head; + l->head = tmp->next; + l->size--; + + void* p = tmp->data; + SAFE_RELEASE(tmp); + + return p; +} + +ret_t fifo_release(fifo_t* l, bool data_release) { + + void* p = NULL; + while ((p = fifo_pop(l))) { + if (data_release) + l->rel_cb(p); + } + + SAFE_RELEASE(l); + + return ST_OK; + +} + +#ifndef NDEBUG +void test_fifo() { + u64 ii[] = {0, 1, 2, 3, 4, 5, 6, 7}; + + fifo_t* f = NULL; + fifo_init(&f, NULL); + + fifo_push(f, &ii[0]); + fifo_push(f, &ii[1]); + fifo_push(f, &ii[2]); + fifo_push(f, &ii[3]); + fifo_push(f, &ii[4]); + fifo_push(f, &ii[5]); + fifo_push(f, &ii[6]); + fifo_push(f, &ii[7]); + + u64* p = NULL; + u64 i = 0; + while ((p = (u64*)fifo_pop(f))) { + ASSERT(ii[i++] == *p); + LOG_TRACE("fifo %lu", *p); + } + + fifo_release(f, false); + +} + +#endif diff --git a/pool/shard002/C/0063498_expand.c b/pool/shard002/C/0063498_expand.c new file mode 100644 index 0000000000000000000000000000000000000000..8fa45f2d212e071e8ea3ad4970832b263299f1aa --- /dev/null +++ b/pool/shard002/C/0063498_expand.c @@ -0,0 +1,284 @@ +/*---------------------------------------------------------------*/ +/* expand.c */ +/*---------------------------------------------------------------*/ +/* Norbert Kuck 26.4.93 */ +/* Version 4.0 seq */ +/*---------------------------------------------------------------*/ +/* Expander: Funktionen zur Expansion von Knoten + */ +/*------------------------ PRAEPROZESSOR ------------------------*/ + +/* #define TRACE_ON */ +#define TRACE_CONDITION glob.flags & TRACE_EXP + +#include +#include +#include "types.h" +#include "u_types.h" +#include "mem.h" +#include "expand.h" +#include "heap.h" +#include "u_funcs.h" +#include "error.h" +#include "trace.h" + +/*------------------------ GLOBALE VEREINBARUNGEN ---------------*/ + +extern stat_t statistic; +extern glob_t glob; + +/*------------------------ MAKROS -------------------------------*/ +/*------------------------ FUNKTIONEN ---------------------------*/ + +#ifdef SUN_CC + +static int try_pruning (); + +#else + +static int try_pruning ( + u_glob_t* /* u_glob */, + u_node_t* /* node */); +#endif + +/*^*/ +/*------------------------ EXPANDER -----------------------------*/ +/* Schleife zur Expansion von Knoten. Nimmt jeweils einen + * (Vater-)Knoten vom Heap, erzeugt dessen Soehne und versucht sie + * zu eliminieren. Leere Knoten zur Erzeugung der Soehne werden aus + * der Freelist entnommen. Die nicht eliminierten Soehne werden auf + * den Heap gelegt Dispatcher weitergegeben. Wenn ein erzeugter + * Sohn eine neue Bestloesung (Incumbent) darstellt, wird er als + * solche eingetragen. Wenn ein Fehler auftritt, beendet sich die + * Funktion mit einem Status. geschickt und der Prozess beendet. + */ + +int expander (u_glob) + +u_glob_t *u_glob; + + { + boolean e_finished; + node_t *parent; + int sts; + node_t *son; + int last_selection; + node_t *incumbent; + int prof_slot; + + e_finished = OK_FALSE; + + /* Hole leeren Knoten fuer ersten Sohn: */ + sts = m_get_node (u_glob, &son); + if (sts > ERROR) + e_finished = sts; + + /* Solange nicht fertig */ + while (!e_finished) + { + /* Hole besten Knoten vom Heap: */ + sts = h_get_from_heap (&parent); + /* Wenn Heap leer: */ + if (sts == OK_FALSE) + { + T ("Expander finished"); + /* Hier Schluss machen: */ + e_finished = OK_TRUE; + /* Kein Fehler: */ + sts = OK; + } + else + { + B_ST + TKN ("Vom Heap geholt", parent); + statistic.expanded++; + /* Wenn Profil der L-Bounds erwuenscht: */ + if (glob.flags & PROFILE) + { + if (parent->l_bound < glob.prof_start) + prof_slot = 0; + else if (parent->l_bound > glob.prof_start + + glob.prof_unit * (PROF_BUF_SIZE - 2)) + prof_slot = PROF_BUF_SIZE - 1; + else + prof_slot = (parent->l_bound + glob.prof_unit + - glob.prof_start) / glob.prof_unit; + statistic.profile[prof_slot]++; + } + /* Erzeuge ersten Sohn: */ + sts = u_first_child (u_glob, parent->u_node, son->u_node, + &last_selection); + B_ST + /* Solange noch ein Sohn entstanden */ + while (sts) + { + /* T ("Sohn erzeugt"); */ + statistic.nodes++; + /* Wenn Sohn eine zulaessige Loesung ist */ + sts = u_is_feasible (u_glob, son->u_node); + if (sts) + { + B_ST + statistic.feasible++; + /* Erzeuge die Loesung: */ + sts = u_solution (u_glob, son->u_node, + &son->value); + B_ST + + /* Prioritaet setzen fuer korrektes Tracing: */ +# ifdef TRACE_ON + son->priority = 0; +# endif + TKN ("Sohn ist zulaessige Loesung:", son); + + /* Incumbent holen: */ + incumbent = h_read_incumbent (); + /* Wenn Sohn besser als incumbent */ + if (son->value < incumbent->value) + { + /* Verkuende neue incumbent: */ + h_new_incumbent (son); + T ("Neue Incumbent"); + statistic.improved++; + /* Hole Knoten fuer neuen Sohn: */ + sts = m_get_node (u_glob, &son); + B_ST + } + /* (Vergiss diesen Sohn) */ + } + else + { + B_ST + /* Versuche Sohn zu eliminieren: */ + sts = try_pruning (u_glob, son->u_node); + B_ST + /* Wenn Sohn ueberlebt: */ + if (sts == OK_FALSE) + { + /* Berechne Prioritaet fuer den Sohn: */ + sts = u_priority (u_glob, son->u_node, + glob.prio_par, + &son->priority); + B_ST + /* Kopiere l_bound von u_node: */ + sts = u_lower_bound (u_glob, son->u_node, + &son->l_bound); + B_ST + /* Merke Dir die Familienzugehoerigkeit: */ + son->father = parent; + /* Schicke Sohn an Dispatcher: */ + TKN ("Sohn an Dispatcher geschickt:", son); + h_put_on_heap (son); + /* Hole Knoten fuer neuen Sohn: */ + sts = m_get_node (u_glob, &son); + B_ST + } + else + { + /* (Vergiss diesen Sohn) */ + /* Uebertrage Werte fuer korrektes Tracing: */ +# ifdef TRACE_ON + /* Berechne Prioritaet fuer den Sohn: */ + sts = u_priority (u_glob, son->u_node, + glob.prio_par, + &son->priority); + B_ST + /* Kopiere l_bound von u_node: */ + sts = u_lower_bound (u_glob, son->u_node, + &son->l_bound); + B_ST +# endif + TKN ("Sohn eliminiert", son); + } + } + /* Erzeuge naechsten Sohn: */ + sts = u_next_child (u_glob, parent->u_node, + son->u_node, &last_selection); + B_ST + } /* end while */ + B_ST + /* Abgearbeitete Elternknoten recyclen: */ + m_free_node (parent); + } /* end else */ + } /* end while */ + return (sts); + } + +/*^*/ +/*------------------------ TRY_PRUNING --------------------------*/ +/* Versucht, den Knoten 'node' zu eliminieren. Berechnet die Upper + * Bound; wenn diese groesser als die incumbent ist, kann der + * Knoten eliminiert werden. Sonst wird die Upper Bound berechnet. + * Ist diese kleiner als die incumbent, so liegt eine neue + * incumbent vor. Diese wird veroeffentlicht und 'node' eliminiert. + * Sonst werden die Bounds verglichen: Ist die Lower Bound nicht + * kleiner als die Upper Bound, kann 'node' eliminiert werden. Der + * Rueckgabewert ist 'OK_TRUE', wenn 'node' eliminiert werden kann. + */ + +static int try_pruning (u_glob, node) + +u_glob_t *u_glob; +u_node_t *node; + + { + u_zf_t l_bound; + node_t *incumbent; + static node_t *solution; + int sts; + u_zf_t value; + extern glob_t glob; + + /* Incumbent holen: */ + incumbent = h_read_incumbent (); + /* Berechne Lower Bound: */ + sts = u_lower_bound (u_glob, node, &l_bound); + R_ST + /* Wenn schlechter als incumbent oder unbeschraenkt */ + if (l_bound >= incumbent->value || l_bound == MAXINT) + { + statistic.elim_by_lb++; + return (OK_TRUE); + } + + /* Hole bei Bedarf neuen leeren Knoten fuer heuristische Loesung: */ + if (!solution) + { + sts = m_get_node (u_glob, &solution); + R_ST + } + + /* Wenn Verwendung von Heuristik erwuenscht: */ + if (glob.flags & ELIM_BY_HEUR) + { + /* Berechne Upper Bound (heuristische Loesung): */ + sts = u_heur_loes (u_glob, node, solution->u_node, &value); + R_ST + /* TV ("Heuristische Loesung", value); */ + statistic.heur_solved++; + /* Wenn besser als incumbent */ + if (value < incumbent->value) + { + /* Trage value in node ein: */ + solution->value = value; + TKN ("Neue Bestloesung:", solution); + statistic.improved++; + /* Verkuende neue incumbent: */ + h_new_incumbent (solution); + /* solution muss beim naechsten Mal neu allokiert werden: */ + solution = (node_t *) 0; + } + + /* Wenn Lower Bound = Upper Bound */ + if (l_bound == value) + { + T ("Lower = Upper Bound"); + statistic.elim_by_ub++; + return (OK_TRUE); + } + } + + return (OK_FALSE); + } + +/*------------------------ ENDE ---------------------------------*/ diff --git a/pool/shard002/C/0063499_lcdc_samsung_wsvga.c b/pool/shard002/C/0063499_lcdc_samsung_wsvga.c new file mode 100644 index 0000000000000000000000000000000000000000..5f6680f11d5dff25f6a16fd7075264eff966283a --- /dev/null +++ b/pool/shard002/C/0063499_lcdc_samsung_wsvga.c @@ -0,0 +1,178 @@ +/* Copyright (c) 2009-2010, Code Aurora Forum. 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. + * + * 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 +#ifdef CONFIG_PMIC8058_PWM +#include +#include +#endif +#include +#include "msm_fb.h" + + + +#ifdef CONFIG_PMIC8058_PWM +static struct pwm_device *bl_pwm0; +static struct pwm_device *bl_pwm1; + +/* for samsung panel 300hz was the minimum freq where flickering wasnt + * observed as the screen was dimmed + */ + +#define PWM_FREQ_HZ 300 +#define PWM_PERIOD_USEC (USEC_PER_SEC / PWM_FREQ_HZ) +#define PWM_LEVEL 15 +#define PWM_DUTY_LEVEL (PWM_PERIOD_USEC / PWM_LEVEL) +#endif + +static struct msm_panel_common_pdata *lcdc_samsung_pdata; + + +static void lcdc_samsung_panel_set_backlight(struct msm_fb_data_type *mfd) +{ + int bl_level; + int ret; + + bl_level = mfd->bl_level; + +#ifdef CONFIG_PMIC8058_PWM + if (bl_pwm0) { + ret = pwm_config(bl_pwm0, PWM_DUTY_LEVEL * bl_level, + PWM_PERIOD_USEC); + if (ret) + printk(KERN_ERR "pwm_config on pwm 0 failed %d\n", ret); + } + + if (bl_pwm1) { + ret = pwm_config(bl_pwm1, + PWM_PERIOD_USEC - (PWM_DUTY_LEVEL * bl_level), + PWM_PERIOD_USEC); + if (ret) + printk(KERN_ERR "pwm_config on pwm 1 failed %d\n", ret); + } + + if (bl_pwm0) { + ret = pwm_enable(bl_pwm0); + if (ret) + printk(KERN_ERR "pwm_enable on pwm 0 failed %d\n", ret); + } + + if (bl_pwm1) { + ret = pwm_enable(bl_pwm1); + if (ret) + printk(KERN_ERR "pwm_enable on pwm 1 failed %d\n", ret); + } +#endif + +} + +static int __init samsung_probe(struct platform_device *pdev) +{ + if (pdev->id == 0) { + lcdc_samsung_pdata = pdev->dev.platform_data; + return 0; + } + +#ifdef CONFIG_PMIC8058_PWM + bl_pwm0 = pwm_request(lcdc_samsung_pdata->gpio_num[0], "backlight1"); + if (bl_pwm0 == NULL || IS_ERR(bl_pwm0)) { + pr_err("%s pwm_request() failed\n", __func__); + bl_pwm0 = NULL; + } + + bl_pwm1 = pwm_request(lcdc_samsung_pdata->gpio_num[1], "backlight2"); + if (bl_pwm1 == NULL || IS_ERR(bl_pwm1)) { + pr_err("%s pwm_request() failed\n", __func__); + bl_pwm1 = NULL; + } + + printk(KERN_INFO "samsung_probe: bl_pwm0=%p LPG_chan0=%d " + "bl_pwm1=%p LPG_chan1=%d\n", + bl_pwm0, (int)lcdc_samsung_pdata->gpio_num[0], + bl_pwm1, (int)lcdc_samsung_pdata->gpio_num[1] + ); +#endif + + msm_fb_add_device(pdev); + + return 0; +} + +static struct platform_driver this_driver = { + .probe = samsung_probe, + .driver = { + .name = "lcdc_samsung_wsvga", + }, +}; + +static struct msm_fb_panel_data samsung_panel_data = { + .set_backlight = lcdc_samsung_panel_set_backlight, +}; + +static struct platform_device this_device = { + .name = "lcdc_samsung_wsvga", + .id = 1, + .dev = { + .platform_data = &samsung_panel_data, + } +}; + +static int __init lcdc_samsung_panel_init(void) +{ + int ret; + struct msm_panel_info *pinfo; + +#ifdef CONFIG_FB_MSM_MDDI_AUTO_DETECT + if (msm_fb_detect_client("lcdc_samsung_wsvga")) + return 0; +#endif + + ret = platform_driver_register(&this_driver); + if (ret) + return ret; + + pinfo = &samsung_panel_data.panel_info; + pinfo->xres = 1024; + pinfo->yres = 600; + pinfo->type = LCDC_PANEL; + pinfo->pdest = DISPLAY_1; + pinfo->wait_cycle = 0; + pinfo->bpp = 18; + pinfo->fb_num = 2; + pinfo->clk_rate = 43192000; + pinfo->bl_max = 15; + pinfo->bl_min = 1; + + pinfo->lcdc.h_back_porch = 80; + pinfo->lcdc.h_front_porch = 48; + pinfo->lcdc.h_pulse_width = 32; + pinfo->lcdc.v_back_porch = 4; + pinfo->lcdc.v_front_porch = 3; + pinfo->lcdc.v_pulse_width = 1; + pinfo->lcdc.border_clr = 0; + pinfo->lcdc.underflow_clr = 0xff; + pinfo->lcdc.hsync_skew = 0; + + ret = platform_device_register(&this_device); + if (ret) + platform_driver_unregister(&this_driver); + + return ret; +} + +module_init(lcdc_samsung_panel_init); diff --git a/pool/shard002/C/0063507_board.c b/pool/shard002/C/0063507_board.c new file mode 100644 index 0000000000000000000000000000000000000000..69ed25f12614c7b2a8307dd2354e884a57fcf168 --- /dev/null +++ b/pool/shard002/C/0063507_board.c @@ -0,0 +1,68 @@ +/* + ChibiOS - Copyright (C) 2006..2016 Giovanni Di Sirio + + 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 "hal.h" + +#if HAL_USE_PAL || defined(__DOXYGEN__) +/* Initial setup of all defined pads, the list is terminated by a {-1, 0, 0}.*/ +static const spc_siu_init_t spc_siu_init[] = { + {PCR(PORT_B, PB_LIN0_TDX), PAL_HIGH, PAL_MODE_OUTPUT_ALTERNATE(1)}, + {PCR(PORT_B, PB_LIN0_RDX), PAL_HIGH, PAL_MODE_INPUT}, + {PCR(PORT_D, PD_BUTTON1), PAL_LOW, PAL_MODE_INPUT}, + {PCR(PORT_D, PD_BUTTON2), PAL_LOW, PAL_MODE_INPUT}, + {PCR(PORT_D, PD_BUTTON3), PAL_LOW, PAL_MODE_INPUT}, + {PCR(PORT_D, PD_BUTTON4), PAL_LOW, PAL_MODE_INPUT}, + {PCR(PORT_D, PD_LED1), PAL_HIGH, PAL_MODE_OUTPUT_PUSHPULL}, + {PCR(PORT_D, PD_LED2), PAL_HIGH, PAL_MODE_OUTPUT_PUSHPULL}, + {PCR(PORT_D, PD_LED3), PAL_HIGH, PAL_MODE_OUTPUT_PUSHPULL}, + {PCR(PORT_D, PD_LED4), PAL_HIGH, PAL_MODE_OUTPUT_PUSHPULL}, + {-1, 0, 0} +}; + +/* Initialization array for the PSMI registers.*/ +static const uint8_t spc_padsels_init[SPC5_SIUL_NUM_PADSELS] = { + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, +}; + +/** + * @brief PAL setup. + */ +const PALConfig pal_default_config = { + PAL_MODE_UNCONNECTED, + spc_siu_init, + spc_padsels_init +}; +#endif + +/* + * Early initialization code. + * This initialization must be performed just after stack setup and before + * any other initialization. + */ +void __early_init(void) { + + spc_clock_init(); +} + +/* + * Board-specific initialization code. + */ +void boardInit(void) { +} diff --git a/pool/shard002/C/0063509_th959.c b/pool/shard002/C/0063509_th959.c new file mode 100644 index 0000000000000000000000000000000000000000..9199a658da97cd5701bb4bced1f9d442295651e5 --- /dev/null +++ b/pool/shard002/C/0063509_th959.c @@ -0,0 +1,22 @@ +#include +#include + +int main(int argc, char const *argv[]) { + int x, y, z, i = 1, j = 0; + scanf(" %d %d %d", &x, &y, &z); + + while(i <= y) { + + printf("%d", i); + i += z; + + if(++j >= x) { + j = 0; + printf("\n"); + } + else printf(" "); + } + printf("\n"); + + return 0; +} \ No newline at end of file diff --git a/pool/shard002/C/0063518_main-cast6-test.c b/pool/shard002/C/0063518_main-cast6-test.c new file mode 100644 index 0000000000000000000000000000000000000000..6697eed574d97f14f74445d2278bd12bf0065a65 --- /dev/null +++ b/pool/shard002/C/0063518_main-cast6-test.c @@ -0,0 +1,160 @@ +/* + * rc6 test-suit + * +*/ + +#include +#include +#include +#include "config.h" +#include "cli.h" +#include "dump.h" +#include "uart_lowlevel.h" +#include "sysclock.h" +#include "hw_gptm.h" + +#include "cast6.h" +#include "nessie_bc_test.h" +#include "cli.h" +#include "performance_test.h" +#include "bcal-performance.h" +#include "bcal_cast6.h" + +char* algo_name = "CAST-256"; + +void uart0_putc(char byte){ + uart_putc(UART_0, byte); +} + +char uart0_getc(void){ + return uart_getc(UART_0); +} + +const bcdesc_t* algolist[] = { + (bcdesc_t*)&cast6_desc, + NULL +}; + +/***************************************************************************** + * additional validation-functions * + *****************************************************************************/ + + +void testrun_nessie_cast6(void){ + nessie_bc_init(); + nessie_bc_ctx.blocksize_B = 16; + nessie_bc_ctx.keysize_b = 128; + nessie_bc_ctx.name = algo_name; + nessie_bc_ctx.ctx_size_B = sizeof(cast6_ctx_t); + nessie_bc_ctx.cipher_enc = (nessie_bc_enc_fpt)cast6_enc; + nessie_bc_ctx.cipher_dec = (nessie_bc_dec_fpt)cast6_dec; + nessie_bc_ctx.cipher_genctx = (nessie_bc_gen_fpt)cast6_init; + + nessie_bc_run(); + + nessie_bc_ctx.keysize_b = 192; + nessie_bc_run(); + + nessie_bc_ctx.keysize_b = 256; + nessie_bc_run(); +} + +void testrun_rfc_cast6(void){ + cli_putstr("\r\n testvalues from rfc-2612\r\n"); + uint8_t key[32], data[16]; + cast6_ctx_t ctx; + memcpy(key, "\x23\x42\xbb\x9e\xfa\x38\x54\x2c" + "\x0a\xf7\x56\x47\xf2\x9f\x61\x5d", 16); + memset(data, 0, 16); + + cli_putstr("\r\n key: "); + cli_hexdump(key, 16); + cli_putstr("\r\n PT: "); + cli_hexdump(data, 16); + cast6_init(key, 128, &ctx); + cast6_enc(data, &ctx); + cli_putstr("\r\n CT: "); + cli_hexdump(data, 16); + cast6_dec(data, &ctx); + cli_putstr("\r\n PT: "); + cli_hexdump(data, 16); + + cli_putstr("\r\n\r\n"); + + memcpy(key, "\x23\x42\xbb\x9e\xfa\x38\x54\x2c" + "\xbe\xd0\xac\x83\x94\x0a\xc2\x98" + "\xba\xc7\x7a\x77\x17\x94\x28\x63", 24); + + cli_putstr("\r\n key: "); + cli_hexdump(key, 24); + cli_putstr("\r\n PT: "); + cli_hexdump(data, 16); + cast6_init(key, 192, &ctx); + cast6_enc(data, &ctx); + cli_putstr("\r\n CT: "); + cli_hexdump(data, 16); + cast6_dec(data, &ctx); + cli_putstr("\r\n PT: "); + cli_hexdump(data, 16); + + cli_putstr("\r\n\r\n"); + + memcpy(key, "\x23\x42\xbb\x9e\xfa\x38\x54\x2c" + "\xbe\xd0\xac\x83\x94\x0a\xc2\x98" + "\x8d\x7c\x47\xce\x26\x49\x08\x46" + "\x1c\xc1\xb5\x13\x7a\xe6\xb6\x04", 32); + cli_putstr("\r\n key: "); + cli_hexdump(key, 32); + cli_putstr("\r\n PT: "); + cli_hexdump(data, 16); + cast6_init(key, 256, &ctx); + cast6_enc(data, &ctx); + cli_putstr("\r\n CT: "); + cli_hexdump(data, 16); + cast6_dec(data, &ctx); + cli_putstr("\r\n PT: "); + cli_hexdump(data, 16); + + cli_putstr("\r\n\r\n"); +} + +void testrun_performance_cast6(void){ + bcal_performance_multiple(algolist); +} + +/***************************************************************************** + * main * + *****************************************************************************/ + +const char nessie_str[] = "nessie"; +const char test_str[] = "test"; +const char performance_str[] = "performance"; +const char echo_str[] = "echo"; + +const cmdlist_entry_t cmdlist[] = { + { nessie_str, NULL, testrun_nessie_cast6 }, + { test_str, NULL, testrun_rfc_cast6}, + { performance_str, NULL, testrun_performance_cast6}, + { echo_str, (void*)1, (void_fpt)echo_ctrl}, + { NULL, NULL, NULL} +}; + +int main (void){ + sysclk_set_freq(SYS_FREQ); + sysclk_mosc_verify_enable(); + uart_init(UART_0, 115200, 8, UART_PARATY_NONE, UART_STOPBITS_ONE); + gptm_set_timer_32periodic(TIMER0); + + cli_rx = (cli_rx_fpt)uart0_getc; + cli_tx = (cli_tx_fpt)uart0_putc; + for(;;){ + cli_putstr("\r\n\r\nARM-Crypto-Lib VS ("); + cli_putstr(algo_name); + cli_putstr("; "); + cli_putstr(__DATE__); + cli_putc(' '); + cli_putstr(__TIME__); + cli_putstr(")\r\nloaded and running\r\n"); + cmd_interface(cmdlist); + } +} diff --git a/pool/shard002/C/0063520_rq_asset_recovery_rate.c b/pool/shard002/C/0063520_rq_asset_recovery_rate.c new file mode 100644 index 0000000000000000000000000000000000000000..700774a5c368e65b500f088d53c9d57db4956184 --- /dev/null +++ b/pool/shard002/C/0063520_rq_asset_recovery_rate.c @@ -0,0 +1,88 @@ +/* +** rq_asset_recovery_rate.c +** +** Written by Todd Cooper +** +** Copyright (C) 2002-2008 Brett Hutley +** +** This file is part of the Risk Quantify Library +** +** Risk Quantify 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. +** +** Risk Quantify 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 Risk Quantify; if not, write to the Free +** Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA +*/ +#include "rq_asset_recovery_rate.h" +#include "rq_asset_mgr.h" +#include +#include + +const char * const rq_asset_type_id_recovery_rate = "RecoveryRate"; + +static struct rq_asset_recovery_rate * +rq_asset_recovery_rate_alloc() +{ + struct rq_asset_recovery_rate *asset = + (struct rq_asset_recovery_rate *)RQ_CALLOC(1, sizeof(struct rq_asset_recovery_rate)); + + return asset; +} + +static void +rq_asset_recovery_rate_free(struct rq_asset_recovery_rate *asset_recovery_rate) +{ + if (asset_recovery_rate->name) + RQ_FREE((char *)asset_recovery_rate->name); + RQ_FREE(asset_recovery_rate); +} + +void +rq_asset_recovery_rate_freefunc(void *asset_data) +{ + rq_asset_recovery_rate_free((struct rq_asset_recovery_rate *)asset_data); +} + +RQ_EXPORT rq_asset_t +rq_asset_recovery_rate_build( + const char *asset_id, + const char *name + ) +{ + struct rq_asset_recovery_rate *asset_recovery_rate = rq_asset_recovery_rate_alloc(); + rq_asset_t asset = _rq_asset_alloc( + rq_asset_type_id_recovery_rate, + asset_id, + asset_recovery_rate, + rq_asset_recovery_rate_freefunc + ); + + if (name) + asset_recovery_rate->name = (const char *)RQ_STRDUP(name); + else + asset_recovery_rate->name = NULL; + + return asset; +} + +RQ_EXPORT const char * +rq_asset_recovery_rate_get_name(const rq_asset_t asset) +{ + struct rq_asset_recovery_rate *asset_recovery_rate = + (struct rq_asset_recovery_rate *)_rq_asset_get_asset_type_data(asset); + return asset_recovery_rate->name; +} + +RQ_EXPORT short +rq_asset_is_recovery_rate(rq_asset_t asset) +{ + return !strcmp(rq_asset_get_asset_type_id(asset), rq_asset_type_id_recovery_rate); +} diff --git a/pool/shard002/C/0063526_tosa_bl.c b/pool/shard002/C/0063526_tosa_bl.c new file mode 100644 index 0000000000000000000000000000000000000000..be3ba0c76e02843688e925b826188634a7fa975e --- /dev/null +++ b/pool/shard002/C/0063526_tosa_bl.c @@ -0,0 +1,189 @@ + + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +#include + +#define COMADJ_DEFAULT 97 + +#define DAC_CH1 0 +#define DAC_CH2 1 + +struct tosa_bl_data { + struct i2c_client *i2c; + struct backlight_device *bl; + + int comadj; +}; + +static void tosa_bl_set_backlight(struct tosa_bl_data *data, int brightness) +{ + struct spi_device *spi = data->i2c->dev.platform_data; + + i2c_smbus_write_byte_data(data->i2c, DAC_CH1, data->comadj); + + /* SetBacklightDuty */ + i2c_smbus_write_byte_data(data->i2c, DAC_CH2, (u8)(brightness & 0xff)); + + /* SetBacklightVR */ + gpio_set_value(TOSA_GPIO_BL_C20MA, brightness & 0x100); + + tosa_bl_enable(spi, brightness); +} + +static int tosa_bl_update_status(struct backlight_device *dev) +{ + struct backlight_properties *props = &dev->props; + struct tosa_bl_data *data = dev_get_drvdata(&dev->dev); + int power = max(props->power, props->fb_blank); + int brightness = props->brightness; + + if (power) + brightness = 0; + + tosa_bl_set_backlight(data, brightness); + + return 0; +} + +static int tosa_bl_get_brightness(struct backlight_device *dev) +{ + struct backlight_properties *props = &dev->props; + + return props->brightness; +} + +static const struct backlight_ops bl_ops = { + .get_brightness = tosa_bl_get_brightness, + .update_status = tosa_bl_update_status, +}; + +static int __devinit tosa_bl_probe(struct i2c_client *client, + const struct i2c_device_id *id) +{ + struct backlight_properties props; + struct tosa_bl_data *data = kzalloc(sizeof(struct tosa_bl_data), GFP_KERNEL); + int ret = 0; + if (!data) + return -ENOMEM; + + data->comadj = sharpsl_param.comadj == -1 ? COMADJ_DEFAULT : sharpsl_param.comadj; + + ret = gpio_request(TOSA_GPIO_BL_C20MA, "backlight"); + if (ret) { + dev_dbg(&data->bl->dev, "Unable to request gpio!\n"); + goto err_gpio_bl; + } + ret = gpio_direction_output(TOSA_GPIO_BL_C20MA, 0); + if (ret) + goto err_gpio_dir; + + i2c_set_clientdata(client, data); + data->i2c = client; + + memset(&props, 0, sizeof(struct backlight_properties)); + props.max_brightness = 512 - 1; + data->bl = backlight_device_register("tosa-bl", &client->dev, data, + &bl_ops, &props); + if (IS_ERR(data->bl)) { + ret = PTR_ERR(data->bl); + goto err_reg; + } + + data->bl->props.brightness = 69; + data->bl->props.power = FB_BLANK_UNBLANK; + + backlight_update_status(data->bl); + + return 0; + +err_reg: + data->bl = NULL; +err_gpio_dir: + gpio_free(TOSA_GPIO_BL_C20MA); +err_gpio_bl: + kfree(data); + return ret; +} + +static int __devexit tosa_bl_remove(struct i2c_client *client) +{ + struct tosa_bl_data *data = i2c_get_clientdata(client); + + backlight_device_unregister(data->bl); + data->bl = NULL; + + gpio_free(TOSA_GPIO_BL_C20MA); + + kfree(data); + + return 0; +} + +#ifdef CONFIG_PM +static int tosa_bl_suspend(struct i2c_client *client, pm_message_t pm) +{ + struct tosa_bl_data *data = i2c_get_clientdata(client); + + tosa_bl_set_backlight(data, 0); + + return 0; +} + +static int tosa_bl_resume(struct i2c_client *client) +{ + struct tosa_bl_data *data = i2c_get_clientdata(client); + + backlight_update_status(data->bl); + return 0; +} +#else +#define tosa_bl_suspend NULL +#define tosa_bl_resume NULL +#endif + +static const struct i2c_device_id tosa_bl_id[] = { + { "tosa-bl", 0 }, + { }, +}; + + +static struct i2c_driver tosa_bl_driver = { + .driver = { + .name = "tosa-bl", + .owner = THIS_MODULE, + }, + .probe = tosa_bl_probe, + .remove = __devexit_p(tosa_bl_remove), + .suspend = tosa_bl_suspend, + .resume = tosa_bl_resume, + .id_table = tosa_bl_id, +}; + +static int __init tosa_bl_init(void) +{ + return i2c_add_driver(&tosa_bl_driver); +} + +static void __exit tosa_bl_exit(void) +{ + i2c_del_driver(&tosa_bl_driver); +} + +module_init(tosa_bl_init); +module_exit(tosa_bl_exit); + +MODULE_AUTHOR("Dmitry Baryshkov"); +MODULE_LICENSE("GPL v2"); +MODULE_DESCRIPTION("LCD/Backlight control for Sharp SL-6000 PDA"); + diff --git a/pool/shard002/C/0063532_thread-fsm.c b/pool/shard002/C/0063532_thread-fsm.c new file mode 100644 index 0000000000000000000000000000000000000000..4a27d024a8195971bd22d47117e430ed0f534000 --- /dev/null +++ b/pool/shard002/C/0063532_thread-fsm.c @@ -0,0 +1,107 @@ +/* Thread command's finish-state machine, for GDB, the GNU debugger. + Copyright (C) 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 "thread-fsm.h" + +/* See thread-fsm.h. */ + +void +thread_fsm_ctor (struct thread_fsm *self, struct thread_fsm_ops *ops) +{ + self->finished = 0; + self->ops = ops; +} + +/* See thread-fsm.h. */ + +void +thread_fsm_delete (struct thread_fsm *self) +{ + if (self != NULL) + { + if (self->ops->dtor != NULL) + self->ops->dtor (self); + xfree (self); + } +} + +/* See thread-fsm.h. */ + +void +thread_fsm_clean_up (struct thread_fsm *self) +{ + if (self->ops->clean_up != NULL) + self->ops->clean_up (self); +} + +/* See thread-fsm.h. */ + +int +thread_fsm_should_stop (struct thread_fsm *self) +{ + return self->ops->should_stop (self); +} + +/* See thread-fsm.h. */ + +struct return_value_info * +thread_fsm_return_value (struct thread_fsm *self) +{ + if (self->ops->return_value != NULL) + return self->ops->return_value (self); + return NULL; +} + +/* See thread-fsm.h. */ + +void +thread_fsm_set_finished (struct thread_fsm *self) +{ + self->finished = 1; +} + +/* See thread-fsm.h. */ + +int +thread_fsm_finished_p (struct thread_fsm *self) +{ + return self->finished; +} + +/* See thread-fsm.h. */ + +enum async_reply_reason +thread_fsm_async_reply_reason (struct thread_fsm *self) +{ + /* If we didn't finish, then the stop reason must come from + elsewhere. E.g., a breakpoint hit or a signal intercepted. */ + gdb_assert (thread_fsm_finished_p (self)); + + return self->ops->async_reply_reason (self); +} + +/* See thread-fsm.h. */ + +int +thread_fsm_should_notify_stop (struct thread_fsm *self) +{ + if (self->ops->should_notify_stop != NULL) + return self->ops->should_notify_stop (self); + return 1; +} diff --git a/pool/shard002/C/0063538_snb_idle.c b/pool/shard002/C/0063538_snb_idle.c new file mode 100644 index 0000000000000000000000000000000000000000..efc8a69c9abafea4c492b52457d5f645254c3180 --- /dev/null +++ b/pool/shard002/C/0063538_snb_idle.c @@ -0,0 +1,200 @@ +/* + * (C) 2010,2011 Thomas Renninger , Novell Inc. + * + * Licensed under the terms of the GNU GPL License version 2. + * + * Based on Len Brown's turbostat tool. + */ + +#if defined(__i386__) || defined(__x86_64__) + +#include +#include +#include +#include + +#include "helpers/helpers.h" +#include "idle_monitor/cpupower-monitor.h" + +#define MSR_PKG_C2_RESIDENCY 0x60D +#define MSR_PKG_C7_RESIDENCY 0x3FA +#define MSR_CORE_C7_RESIDENCY 0x3FE + +#define MSR_TSC 0x10 + +enum intel_snb_id { C7 = 0, PC2, PC7, SNB_CSTATE_COUNT, TSC = 0xFFFF }; + +static int snb_get_count_percent(unsigned int self_id, double *percent, + unsigned int cpu); + +static cstate_t snb_cstates[SNB_CSTATE_COUNT] = { + { + .name = "C7", + .desc = N_("Processor Core C7"), + .id = C7, + .range = RANGE_CORE, + .get_count_percent = snb_get_count_percent, + }, + { + .name = "PC2", + .desc = N_("Processor Package C2"), + .id = PC2, + .range = RANGE_PACKAGE, + .get_count_percent = snb_get_count_percent, + }, + { + .name = "PC7", + .desc = N_("Processor Package C7"), + .id = PC7, + .range = RANGE_PACKAGE, + .get_count_percent = snb_get_count_percent, + }, +}; + +static unsigned long long tsc_at_measure_start; +static unsigned long long tsc_at_measure_end; +static unsigned long long *previous_count[SNB_CSTATE_COUNT]; +static unsigned long long *current_count[SNB_CSTATE_COUNT]; +/* valid flag for all CPUs. If a MSR read failed it will be zero */ +static int *is_valid; + +static int snb_get_count(enum intel_snb_id id, unsigned long long *val, + unsigned int cpu) +{ + int msr; + + switch (id) { + case C7: + msr = MSR_CORE_C7_RESIDENCY; + break; + case PC2: + msr = MSR_PKG_C2_RESIDENCY; + break; + case PC7: + msr = MSR_PKG_C7_RESIDENCY; + break; + case TSC: + msr = MSR_TSC; + break; + default: + return -1; + }; + if (read_msr(cpu, msr, val)) + return -1; + return 0; +} + +static int snb_get_count_percent(unsigned int id, double *percent, + unsigned int cpu) +{ + *percent = 0.0; + + if (!is_valid[cpu]) + return -1; + + *percent = (100.0 * + (current_count[id][cpu] - previous_count[id][cpu])) / + (tsc_at_measure_end - tsc_at_measure_start); + + dprint("%s: previous: %llu - current: %llu - (%u)\n", + snb_cstates[id].name, previous_count[id][cpu], + current_count[id][cpu], cpu); + + dprint("%s: tsc_diff: %llu - count_diff: %llu - percent: %2.f (%u)\n", + snb_cstates[id].name, + (unsigned long long) tsc_at_measure_end - tsc_at_measure_start, + current_count[id][cpu] - previous_count[id][cpu], + *percent, cpu); + + return 0; +} + +static int snb_start(void) +{ + int num, cpu; + unsigned long long val; + + for (num = 0; num < SNB_CSTATE_COUNT; num++) { + for (cpu = 0; cpu < cpu_count; cpu++) { + snb_get_count(num, &val, cpu); + previous_count[num][cpu] = val; + } + } + snb_get_count(TSC, &tsc_at_measure_start, 0); + return 0; +} + +static int snb_stop(void) +{ + unsigned long long val; + int num, cpu; + + snb_get_count(TSC, &tsc_at_measure_end, 0); + + for (num = 0; num < SNB_CSTATE_COUNT; num++) { + for (cpu = 0; cpu < cpu_count; cpu++) { + is_valid[cpu] = !snb_get_count(num, &val, cpu); + current_count[num][cpu] = val; + } + } + return 0; +} + +struct cpuidle_monitor intel_snb_monitor; + +static struct cpuidle_monitor *snb_register(void) +{ + int num; + + if (cpupower_cpu_info.vendor != X86_VENDOR_INTEL + || cpupower_cpu_info.family != 6) + return NULL; + + switch (cpupower_cpu_info.model) { + case 0x2A: /* SNB */ + case 0x2D: /* SNB Xeon */ + case 0x3A: /* IVB */ + case 0x3E: /* IVB Xeon */ + case 0x3C: /* HSW */ + case 0x3F: /* HSW */ + case 0x45: /* HSW */ + case 0x46: /* HSW */ + break; + default: + return NULL; + } + + is_valid = calloc(cpu_count, sizeof(int)); + for (num = 0; num < SNB_CSTATE_COUNT; num++) { + previous_count[num] = calloc(cpu_count, + sizeof(unsigned long long)); + current_count[num] = calloc(cpu_count, + sizeof(unsigned long long)); + } + intel_snb_monitor.name_len = strlen(intel_snb_monitor.name); + return &intel_snb_monitor; +} + +void snb_unregister(void) +{ + int num; + free(is_valid); + for (num = 0; num < SNB_CSTATE_COUNT; num++) { + free(previous_count[num]); + free(current_count[num]); + } +} + +struct cpuidle_monitor intel_snb_monitor = { + .name = "SandyBridge", + .hw_states = snb_cstates, + .hw_states_num = SNB_CSTATE_COUNT, + .start = snb_start, + .stop = snb_stop, + .do_register = snb_register, + .unregister = snb_unregister, + .needs_root = 1, + .overflow_s = 922000000 /* 922337203 seconds TSC overflow + at 20GHz */ +}; +#endif /* defined(__i386__) || defined(__x86_64__) */ diff --git a/pool/shard002/C/0063540_dhash.c b/pool/shard002/C/0063540_dhash.c new file mode 100644 index 0000000000000000000000000000000000000000..c1707bee75c3676da6a6cac39680bc85dde82133 --- /dev/null +++ b/pool/shard002/C/0063540_dhash.c @@ -0,0 +1,202 @@ +/* + * This file is part of the sn package. + * Distribution of sn is covered by the GNU GPL. See file COPYING. + * Copyright © 1998-2000 Harold Tay. + * Copyright © 2000- Patrik Rådman. + */ + +/* + * Disk based persistent hash table, like gdbm. + * + * This is specifically for the news system. The keys are message + * ids, the values are {newsgroup, serial number} tuples. + * + * The table is static in size. There a 3 files: ".table" is the hash + * table proper. It contains an array of chain "pointers". The + * other 2 files are handled by allo_*(). ".chain" is an arena of + * chain structures; ".newsgroup" contains all newsgroups. + * + * Supported opertions are insert, delete, and search. + * + * Requires allocate.c to allocate space on a disk file (".chain") + * for data. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "config.h" +#include "allocate.h" /* Save ids and chains */ +#include "dhash.h" +#include "newsgroup.h" /* Save newsgroup names */ +#include +#include + +static const char ver_ctrl_id[] = "$Id: dhash.c 56 2004-07-27 16:54:48Z patrik $"; + +extern char dh_tablefile[]; +extern char dh_chainfile[]; +extern char dh_groupfile[]; +extern struct table *dh_table; +extern unsigned dhhash (char *); +extern struct chain *dhlocatechain (char *); +extern bool dh_isreadonly; +extern int dhlock(void); +extern int dhunlock(void); + +static char *inttochar2 (int integer) +{ + static unsigned char buf[2]; + + buf[0] = (integer & 0xffff) >> 8; + buf[1] = integer & 0xff; + return ((char *) buf); +} + +static char *inttochar3 (unsigned integer) +{ + static unsigned char buf[3]; + + integer >>= 2; /* last 2 bits will be 0 */ + buf[0] = (integer & 0xffffff) >> 16; + buf[1] = (integer & 0xffff) >> 8; + buf[2] = integer & 0xff; + return ((char *) buf); +} + +int dh_insert (struct data *dp) +{ + struct chain *chp; + unsigned h; + int off; + int len; + + if (dh_isreadonly) + { + errno = EPERM; + return -1; + } + /* Search first; if found, cannot insert. */ + if (dhlock() == -1) + return -1; + chp = dhlocatechain(dp->messageid); + while (chp != NULL) + { + unsigned index; + + if (strcmp(dp->messageid, chp->messageid) == 0) + { + dhunlock(); + errno = EEXIST; + return -1; + } + index = (unsigned) chp->next; + if (index == 0) + break; + chp = allo_deref(index); + if (chp == NULL) + { + LOG("dh_insert:bad deref in chain for \"<%s>\" during search", dp->messageid); + break; + } + } + + len = sizeof (struct chain) + strlen(dp->messageid) + 1 - sizeof (chp->messageid); + off = allo_make(len); + chp = allo_deref(off); + if (chp == NULL) + { + LOG("dh_insert:allo_make gave bad allo_deref"); + dhunlock(); + return -1; + } + chp->serial = dp->serial; + strcpy(chp->messageid, dp->messageid); + { + int ident; + + ident = ng_ident(dp->newsgroup); + if (-1 == ident) + if (-1 == (ident = ng_addgroup(dp->newsgroup))) + return -1; + memcpy(chp->newsgroup, inttochar2(ident), 2); + } + + /* + * If someone searches before + * dh_table->next[h] is updated, they just will miss the new one. + * Readers don't need to lock, not even LOCK_SH. The worst that + * can come of this is, someone else has just inserted the same + * object, and we have two of them instead of one. + */ + + h = dhhash(dp->messageid); + + { + unsigned char *x = dh_table->next + h * 3; + + chp->next = char3toint(x); + memcpy(x, inttochar3(off), 3); + } + dhunlock(); + return 0; +} + +int dh_delete (struct data *dp) +{ + struct chain *oldchp = NULL; + struct chain *chp; + + if (dh_isreadonly) + { + errno = EPERM; + return -1; + } + + if (dhlock() == -1) + return -1; + chp = dhlocatechain(dp->messageid); + if (chp == NULL) + goto fail; + + while (strcmp(chp->messageid, dp->messageid) != 0) + { + unsigned index = chp->next; + + if (index == 0) + goto fail; + oldchp = chp; + chp = allo_deref(index); + if (chp == NULL) + { + LOG2("dh_delete:dereferencing bad offset"); + goto fail; + } + } + + *chp->messageid = '\0'; + if (oldchp != NULL) + oldchp->next = chp->next; + else + { + unsigned i = chp->next; + unsigned h = dhhash(dp->messageid); + + memcpy(dh_table->next + h * 3, inttochar3(i), 3); + } + allo_free(allo_ref(chp), sizeof (struct chain) + strlen(dp->messageid) + 1 - sizeof (chp->messageid)); + + dhunlock(); + return 0; + +fail: + dhunlock(); + return -1; /* Not found */ +} diff --git a/pool/shard002/C/0063542_cpsw.c b/pool/shard002/C/0063542_cpsw.c new file mode 100644 index 0000000000000000000000000000000000000000..689528c53b25ebff67e1319ab86c83fa96f01ae0 --- /dev/null +++ b/pool/shard002/C/0063542_cpsw.c @@ -0,0 +1,231 @@ +/** + * \file cpsw.c + * + * \brief This file contains functions which configure CPSW instance + */ + +/* +* Copyright (C) 2010 Texas Instruments Incorporated - http://www.ti.com/ +*/ +/* +* 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 Texas Instruments Incorporated nor the names of +* its contributors may be used to endorse or promote products derived +* from this software without specific prior written permission. +* +* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +* +*/ + +#include "soc_AM335x.h" +#include "hw_control_AM335x.h" +#include "hw_types.h" +#include "evmAM335x.h" +#include "hw_cm_per.h" +#include "hsi2c.h" + +/****************************************************************************** +** INTERNAL MACRO DEFINITIONS +******************************************************************************/ +#define CPSW_RGMII_SEL_MODE (0x02u) +#define CPSW_MDIO_SEL_MODE (0x00u) +#define LEN_MAC_ADDR (0x06u) +#define OFFSET_MAC_ADDR (0x30u) +#define I2C_SLAVE_EEPROM (0xA0u) + +/****************************************************************************** +** FUNCTION DEFINITIONS +******************************************************************************/ +/** + * \brief This function selects the CPSW pins for use in RGMII mode. + * + * \param None + * + * \return TRUE/FALSE + * + * \note This muxing depends on the profile in which the EVM is configured. + */ +unsigned int CPSWPinMuxSetup(void) +{ + unsigned int profile; + unsigned int status = FALSE; + + profile = EVMProfileGet(); + + switch (profile) + { + /* + ** All profiles have same settings for RGMII1 + ** profile 1 has settings for RGMII2 + */ + case 1: + HWREG(SOC_CONTROL_REGS + CONTROL_CONF_GPMC_A(0)) = + CPSW_RGMII_SEL_MODE; + HWREG(SOC_CONTROL_REGS + CONTROL_CONF_GPMC_A(1)) = + CONTROL_CONF_GPMC_AD0_CONF_GPMC_AD0_RXACTIVE + | CPSW_RGMII_SEL_MODE; + HWREG(SOC_CONTROL_REGS + CONTROL_CONF_GPMC_A(2)) = + CPSW_RGMII_SEL_MODE; + HWREG(SOC_CONTROL_REGS + CONTROL_CONF_GPMC_A(3)) = + CPSW_RGMII_SEL_MODE; + HWREG(SOC_CONTROL_REGS + CONTROL_CONF_GPMC_A(4)) = + CPSW_RGMII_SEL_MODE; + HWREG(SOC_CONTROL_REGS + CONTROL_CONF_GPMC_A(5)) = + CPSW_RGMII_SEL_MODE; + HWREG(SOC_CONTROL_REGS + CONTROL_CONF_GPMC_A(6)) = + CPSW_RGMII_SEL_MODE; + HWREG(SOC_CONTROL_REGS + CONTROL_CONF_GPMC_A(7)) = + CONTROL_CONF_GPMC_AD0_CONF_GPMC_AD0_RXACTIVE + | CPSW_RGMII_SEL_MODE; + HWREG(SOC_CONTROL_REGS + CONTROL_CONF_GPMC_A(8)) = + CONTROL_CONF_GPMC_AD0_CONF_GPMC_AD0_RXACTIVE + | CPSW_RGMII_SEL_MODE; + HWREG(SOC_CONTROL_REGS + CONTROL_CONF_GPMC_A(9)) = + CONTROL_CONF_GPMC_AD0_CONF_GPMC_AD0_RXACTIVE + | CPSW_RGMII_SEL_MODE; + HWREG(SOC_CONTROL_REGS + CONTROL_CONF_GPMC_A(10)) = + CONTROL_CONF_GPMC_AD0_CONF_GPMC_AD0_RXACTIVE + | CPSW_RGMII_SEL_MODE; + HWREG(SOC_CONTROL_REGS + CONTROL_CONF_GPMC_A(11)) = + CONTROL_CONF_GPMC_AD0_CONF_GPMC_AD0_RXACTIVE + | CPSW_RGMII_SEL_MODE; + + case 0: + case 2: + case 3: + case 4: + case 5: + case 6: + case 7: + HWREG(SOC_CONTROL_REGS + CONTROL_CONF_MII1_COL) = + CONTROL_CONF_MII1_COL_CONF_MII1_COL_RXACTIVE + | CPSW_RGMII_SEL_MODE; + HWREG(SOC_CONTROL_REGS + CONTROL_CONF_MII1_CRS) = + CONTROL_CONF_MII1_CRS_CONF_MII1_CRS_RXACTIVE + | CPSW_RGMII_SEL_MODE; + HWREG(SOC_CONTROL_REGS + CONTROL_CONF_MII1_RXERR) = + CONTROL_CONF_MII1_RXERR_CONF_MII1_RXERR_RXACTIVE + | CPSW_RGMII_SEL_MODE; + HWREG(SOC_CONTROL_REGS + CONTROL_CONF_MII1_TXEN) = + CPSW_RGMII_SEL_MODE; + HWREG(SOC_CONTROL_REGS + CONTROL_CONF_MII1_RXDV) = + CONTROL_CONF_MII1_RXDV_CONF_MII1_RXDV_RXACTIVE + | CPSW_RGMII_SEL_MODE; + HWREG(SOC_CONTROL_REGS + CONTROL_CONF_MII1_TXD3) = + CPSW_RGMII_SEL_MODE; + HWREG(SOC_CONTROL_REGS + CONTROL_CONF_MII1_TXD2) = + CPSW_RGMII_SEL_MODE; + HWREG(SOC_CONTROL_REGS + CONTROL_CONF_MII1_TXD1) = + CPSW_RGMII_SEL_MODE; + HWREG(SOC_CONTROL_REGS + CONTROL_CONF_MII1_TXD0) = + CPSW_RGMII_SEL_MODE; + HWREG(SOC_CONTROL_REGS + CONTROL_CONF_MII1_TXCLK) = + CPSW_RGMII_SEL_MODE; + HWREG(SOC_CONTROL_REGS + CONTROL_CONF_MII1_RXCLK) = + CONTROL_CONF_MII1_RXCLK_CONF_MII1_RXCLK_RXACTIVE + | CPSW_RGMII_SEL_MODE; + HWREG(SOC_CONTROL_REGS + CONTROL_CONF_MII1_RXD3) = + CONTROL_CONF_MII1_RXD3_CONF_MII1_RXD3_RXACTIVE + | CPSW_RGMII_SEL_MODE; + HWREG(SOC_CONTROL_REGS + CONTROL_CONF_MII1_RXD2) = + CONTROL_CONF_MII1_RXD2_CONF_MII1_RXD2_RXACTIVE + | CPSW_RGMII_SEL_MODE; + HWREG(SOC_CONTROL_REGS + CONTROL_CONF_MII1_RXD1) = + CONTROL_CONF_MII1_RXD1_CONF_MII1_RXD1_RXACTIVE + | CPSW_RGMII_SEL_MODE; + HWREG(SOC_CONTROL_REGS + CONTROL_CONF_MII1_RXD0) = + CONTROL_CONF_MII1_RXD0_CONF_MII1_RXD0_RXACTIVE + | CPSW_RGMII_SEL_MODE; + HWREG(SOC_CONTROL_REGS + CONTROL_CONF_RMII1_REFCLK) = + CONTROL_CONF_RMII1_REFCLK_CONF_RMII1_REFCLK_RXACTIVE; + HWREG(SOC_CONTROL_REGS + CONTROL_CONF_MDIO_DATA) = + CONTROL_CONF_MDIO_DATA_CONF_MDIO_DATA_RXACTIVE + | CONTROL_CONF_MDIO_DATA_CONF_MDIO_DATA_PUTYPESEL + | CPSW_MDIO_SEL_MODE; + HWREG(SOC_CONTROL_REGS + CONTROL_CONF_MDIO_CLK) = + CONTROL_CONF_MDIO_CLK_CONF_MDIO_CLK_PUTYPESEL + | CPSW_MDIO_SEL_MODE; + status = TRUE; + default: + break; + } + + return status; +} + +/** + * \brief Enables CPSW clocks + * + * \param None + * + * \return None. + */ +void CPSWClkEnable(void) +{ + HWREG(SOC_PRCM_REGS + CM_PER_CPGMAC0_CLKCTRL) = + CM_PER_CPGMAC0_CLKCTRL_MODULEMODE_ENABLE; + + while(0 != (HWREG(SOC_PRCM_REGS + CM_PER_CPGMAC0_CLKCTRL) + & CM_PER_CPGMAC0_CLKCTRL_IDLEST)); +} + +/** + * \brief This function sets the RGMII mode for both ports + * + * \param None + * + * \return None. + */ +void EVMPortRGMIIModeSelect(void) +{ + /* Select RGMII, Internal Delay mode */ + HWREG(SOC_CONTROL_REGS + CONTROL_GMII_SEL) = 0x0A; +} + +/** + * \brief This function returns the MAC address for the EVM + * + * \param addrIdx the MAC address index. + * \param macAddr the Pointer where the MAC address shall be stored + * 'addrIdx' can be either 0 or 1 + * + * \return None. + */ +void EVMMACAddrGet(unsigned int addrIdx, unsigned char *macAddr) +{ + macAddr[0] = (HWREG(SOC_CONTROL_REGS + CONTROL_MAC_ID_LO(addrIdx)) + >> 8) & 0xFF; + macAddr[1] = (HWREG(SOC_CONTROL_REGS + CONTROL_MAC_ID_LO(addrIdx))) + & 0xFF; + macAddr[2] = (HWREG(SOC_CONTROL_REGS + CONTROL_MAC_ID_HI(addrIdx)) + >> 24) & 0xFF; + macAddr[3] = (HWREG(SOC_CONTROL_REGS + CONTROL_MAC_ID_HI(addrIdx)) + >> 16) & 0xFF; + macAddr[4] = (HWREG(SOC_CONTROL_REGS + CONTROL_MAC_ID_HI(addrIdx)) + >> 8) & 0xFF; + macAddr[5] = (HWREG(SOC_CONTROL_REGS + CONTROL_MAC_ID_HI(addrIdx))) + & 0xFF; +} + +/****************************** End Of File *********************************/ diff --git a/pool/shard002/C/0063554_map.c b/pool/shard002/C/0063554_map.c new file mode 100644 index 0000000000000000000000000000000000000000..c55ad1aa77e88d2dc5b58a1ac62d764dbb0b8948 --- /dev/null +++ b/pool/shard002/C/0063554_map.c @@ -0,0 +1,73 @@ +/* + * Copyright (C) the libgit2 contributors. All rights reserved. + * + * This file is part of libgit2, distributed under the GNU GPL v2 with + * a Linking Exception. For full terms see the included COPYING file. + */ +#include + +#if !defined(GIT_WIN32) && !defined(NO_MMAP) + +#include "map.h" +#include +#include +#include + +int git__page_size(size_t *page_size) +{ + long sc_page_size = sysconf(_SC_PAGE_SIZE); + if (sc_page_size < 0) { + giterr_set(GITERR_OS, "can't determine system page size"); + return -1; + } + *page_size = (size_t) sc_page_size; + return 0; +} + +int git__mmap_alignment(size_t *alignment) +{ + return git__page_size(alignment); +} + +int p_mmap(git_map *out, size_t len, int prot, int flags, int fd, git_off_t offset) +{ + int mprot = PROT_READ; + int mflag = 0; + + GIT_MMAP_VALIDATE(out, len, prot, flags); + + out->data = NULL; + out->len = 0; + + if (prot & GIT_PROT_WRITE) + mprot |= PROT_WRITE; + + if ((flags & GIT_MAP_TYPE) == GIT_MAP_SHARED) + mflag = MAP_SHARED; + else if ((flags & GIT_MAP_TYPE) == GIT_MAP_PRIVATE) + mflag = MAP_PRIVATE; + else + mflag = MAP_SHARED; + + out->data = mmap(NULL, len, mprot, mflag, fd, offset); + + if (!out->data || out->data == MAP_FAILED) { + giterr_set(GITERR_OS, "Failed to mmap. Could not write data"); + return -1; + } + + out->len = len; + + return 0; +} + +int p_munmap(git_map *map) +{ + assert(map != NULL); + munmap(map->data, map->len); + + return 0; +} + +#endif + diff --git a/pool/shard002/C/0063558_test_ppm_loopback.c b/pool/shard002/C/0063558_test_ppm_loopback.c new file mode 100644 index 0000000000000000000000000000000000000000..addd57bea4ca506bc9d6690ec73592f42db551ec --- /dev/null +++ b/pool/shard002/C/0063558_test_ppm_loopback.c @@ -0,0 +1,177 @@ +/**************************************************************************** + * + * Copyright (c) 2012, 2013 PX4 Development Team. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * 3. Neither the name PX4 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. + * + ****************************************************************************/ + +/** + * @file test_ppm_loopback.c + * Tests the PWM outputs and PPM input + * + */ + +#include + +#include + +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include + +#include "tests.h" + +#include +#include + +int test_ppm_loopback(int argc, char *argv[]) +{ + + int _rc_sub = orb_subscribe(ORB_ID(input_rc)); + + int servo_fd, result; + servo_position_t pos; + + servo_fd = open(PWM_OUTPUT_DEVICE_PATH, O_RDWR); + + if (servo_fd < 0) { + printf("failed opening /dev/pwm_servo\n"); + } + + printf("Servo readback, pairs of values should match defaults\n"); + + unsigned servo_count; + result = ioctl(servo_fd, PWM_SERVO_GET_COUNT, (unsigned long)&servo_count); + if (result != OK) { + warnx("PWM_SERVO_GET_COUNT"); + return ERROR; + } + + for (unsigned i = 0; i < servo_count; i++) { + result = ioctl(servo_fd, PWM_SERVO_GET(i), (unsigned long)&pos); + + if (result < 0) { + printf("failed reading channel %u\n", i); + } + + //printf("%u: %u %u\n", i, pos, data[i]); + + } + + // /* tell safety that its ok to disable it with the switch */ + // result = ioctl(servo_fd, PWM_SERVO_SET_ARM_OK, 0); + // if (result != OK) + // warnx("FAIL: PWM_SERVO_SET_ARM_OK"); + // tell output device that the system is armed (it will output values if safety is off) + // result = ioctl(servo_fd, PWM_SERVO_ARM, 0); + // if (result != OK) + // warnx("FAIL: PWM_SERVO_ARM"); + + int pwm_values[] = {1200, 1300, 1900, 1700, 1500, 1250, 1800, 1400}; + + + // for (unsigned i = 0; (i < servo_count) && (i < sizeof(pwm_values) / sizeof(pwm_values[0])); i++) { + // result = ioctl(servo_fd, PWM_SERVO_SET(i), pwm_values[i]); + + // if (result) { + // (void)close(servo_fd); + // return ERROR; + // } else { + // warnx("channel %d set to %d", i, pwm_values[i]); + // } + // } + + warnx("servo count: %d", servo_count); + + struct pwm_output_values pwm_out = {.values = {0}, .channel_count = 0}; + + for (unsigned i = 0; (i < servo_count) && (i < sizeof(pwm_values) / sizeof(pwm_values[0])); i++) { + pwm_out.values[i] = pwm_values[i]; + //warnx("channel %d: disarmed PWM: %d", i+1, pwm_values[i]); + pwm_out.channel_count++; + } + + result = ioctl(servo_fd, PWM_SERVO_SET_DISARMED_PWM, (long unsigned int)&pwm_out); + + /* give driver 10 ms to propagate */ + + /* read low-level values from FMU or IO RC inputs (PPM, Spektrum, S.Bus) */ + struct rc_input_values rc_input; + orb_copy(ORB_ID(input_rc), _rc_sub, &rc_input); + usleep(100000); + + /* open PPM input and expect values close to the output values */ + + bool rc_updated; + orb_check(_rc_sub, &rc_updated); + + if (rc_updated) { + + orb_copy(ORB_ID(input_rc), _rc_sub, &rc_input); + + // int ppm_fd = open(RC_INPUT_DEVICE_PATH, O_RDONLY); + + + + // struct rc_input_values rc; + // result = read(ppm_fd, &rc, sizeof(rc)); + + // if (result != sizeof(rc)) { + // warnx("Error reading RC output"); + // (void)close(servo_fd); + // (void)close(ppm_fd); + // return ERROR; + // } + + /* go and check values */ + for (unsigned i = 0; (i < servo_count) && (i < sizeof(pwm_values) / sizeof(pwm_values[0])); i++) { + if (fabsf(rc_input.values[i] - pwm_values[i]) > 10) { + warnx("comparison fail: RC: %d, expected: %d", rc_input.values[i], pwm_values[i]); + (void)close(servo_fd); + return ERROR; + } + } + } else { + warnx("failed reading RC input data"); + return ERROR; + } + + warnx("PPM LOOPBACK TEST PASSED SUCCESSFULLY!"); + + return 0; +} diff --git a/pool/shard002/C/0063561_input_device.c b/pool/shard002/C/0063561_input_device.c new file mode 100644 index 0000000000000000000000000000000000000000..fff45b467c000c5f004c8c017b02e4951a5a1b23 --- /dev/null +++ b/pool/shard002/C/0063561_input_device.c @@ -0,0 +1,262 @@ +/* + * waysome - wayland based window manager + * + * Copyright in alphabetical order: + * + * Copyright (C) 2014-2015 Julian Ganz + * Copyright (C) 2014-2015 Manuel Messner + * Copyright (C) 2014-2015 Marcel Müller + * Copyright (C) 2014-2015 Matthias Beyer + * Copyright (C) 2014-2015 Nadja Sommerfeld + * + * This file is part of waysome. + * + * waysome 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. + * + * waysome 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 waysome. If not, see . + */ + +#include +#include +#include +#include +#include +#include +#include + +#include "compositor/cursor.h" +#include "compositor/keyboard.h" +#include "input/hotkeys.h" +#include "input/input_device.h" +#include "input/utils.h" +#include "util/arithmetical.h" + +/* + * + * Internal constants + * + */ + +static struct ws_logger_context log_ctx = { .prefix = "[Input/Module] " }; + +static size_t +hash_callback( + struct ws_object * _self +); + +static int +cmp_callback( + struct ws_object const* obj1, + struct ws_object const* obj2 +); + +/** + * The callback used by libev to watch the INPUT_PATH directory + */ +static void +watch_pointers( + struct ev_loop* loop, //!< loop on which the callback was called + ev_io* watcher, //!< watcher which triggered the update + int revents //!< events +); + + +/** + * Type information for ws_wayland_obj type + */ +ws_object_type_id WS_OBJECT_TYPE_ID_INPUT_DEVICE = { + .supertype = &WS_OBJECT_TYPE_ID_OBJECT, + .typestr = "ws_input_device", + + .hash_callback = hash_callback, + .deinit_callback = NULL, + .cmp_callback = cmp_callback, + .uuid_callback = NULL, + + .attribute_table = NULL, + .function_table = NULL, +}; + +/* + * + * Interface implementations + * + */ + +struct ws_input_device* +ws_input_device_new( + int fd +) { + struct ws_input_device* self = calloc(1, sizeof(*self)); + ws_object_init(&self->obj); + self->obj.id = &WS_OBJECT_TYPE_ID_INPUT_DEVICE; + self->obj.settings |= WS_OBJECT_HEAPALLOCED; + + libevdev_new_from_fd(fd, &self->dev); + if (!self->dev) { + ws_log(&log_ctx, LOG_ERR, "Could not create evdev struct"); + close(fd); + return NULL; + } + + self->watcher.data = self; + ev_io_init(&self->watcher, watch_pointers, fd, EV_READ); + + struct ev_loop* default_loop = ev_default_loop(EVFLAG_AUTO); + if (!default_loop) { + close(fd); + return NULL; + } + + if (libevdev_has_event_code(self->dev, EV_KEY, KEY_A)) { + ws_log(&log_ctx, LOG_DEBUG, "Device is a keyboard"); + self->capabilities |= WL_SEAT_CAPABILITY_KEYBOARD; + } + + if (libevdev_has_event_code(self->dev, EV_REL, REL_Y) && + libevdev_has_event_code(self->dev, EV_REL, REL_X) && + libevdev_has_event_code(self->dev, EV_KEY, BTN_MOUSE)) { + ws_log(&log_ctx, LOG_DEBUG, "Device is a mouse"); + self->capabilities |= WL_SEAT_CAPABILITY_POINTER; + } + + ev_io_start(default_loop, &self->watcher); + + return self; +} + +static size_t +hash_callback( + struct ws_object * self +) { + return SIZE_MAX / (((struct ws_input_device*) self)->fd + 1); +} + +static int +cmp_callback( + struct ws_object const* obj1, + struct ws_object const* obj2 +) { + struct ws_input_device* dev1 = (struct ws_input_device*) obj1; + struct ws_input_device* dev2 = (struct ws_input_device*) obj2; + // It's short signum function + return signum((int32_t)(dev1->fd > dev2->fd)); +} + + +static void +handle_relative_event( + struct input_event* ev +) { + //ws_log(&log_ctx, LOG_DEBUG, "It's a mouse event!"); + + switch (ev->code) { + case REL_X: + { + struct ws_cursor* pointer = ws_cursor_get(); + ws_cursor_add_position(pointer, ev->value, 0); + break; + } + case REL_Y: + { + struct ws_cursor* pointer = ws_cursor_get(); + ws_cursor_add_position(pointer, 0, ev->value); + break; + } + } + + +} + +static void +handle_mouse_click_event( + struct input_event* ev +) { + ws_log(&log_ctx, LOG_DEBUG, "It's a mouse click! %x", ev->code); + + int state = ev->value ? WL_POINTER_BUTTON_STATE_PRESSED : + WL_POINTER_BUTTON_STATE_RELEASED; + + struct ws_cursor* pointer = ws_cursor_get(); + ws_cursor_set_button_state(pointer, &ev->time, ev->code, state); +} + +static void +handle_keyboard_press_event( + struct input_event* ev +) { + ws_log(&log_ctx, LOG_DEBUG, "It's a keyboard press! %x", ev->code); + + int state = ev->value ? WL_KEYBOARD_KEY_STATE_PRESSED : + WL_KEYBOARD_KEY_STATE_RELEASED; + + struct ws_keyboard* k = ws_keyboard_get(); + + // XKB map has an offset of 8 to linux/input.h concerning to keycodes + ws_keyboard_send_key(k, &ev->time, ev->code, state); +} + +static void +watch_pointers( + struct ev_loop* loop, + ev_io* watcher, + int revents +) { + struct ws_input_device* self = (struct ws_input_device*) watcher->data; + struct input_event ev; + + while (true) { + int retval = libevdev_next_event(self->dev, LIBEVDEV_READ_FLAG_NORMAL, + &ev); + if (retval == -EAGAIN) { + break; + } + + if (retval < 0) { + ws_log(&log_ctx, LOG_ERR, "libevdev errored: %s", strerror(retval)); + break; + } + + if (retval == LIBEVDEV_READ_STATUS_SYNC) { + //!< @todo: Do something about this? + continue; + } + + if (retval != LIBEVDEV_READ_STATUS_SUCCESS) { + ws_log(&log_ctx, LOG_ERR, "libevdev unspecified error %d", retval); + continue; + } + + if (ev.type == EV_REL) { + handle_relative_event(&ev); + continue; + } + + if (ev.type == EV_KEY) { + // process all events after checking whether it's a key-combo + struct wl_array events = ws_hotkeys_eval(&ev); + struct input_event* buf; + wl_array_for_each(buf, &events) { + if (BTN_MISC <= buf->code && buf->code <= BTN_GEAR_UP) { + handle_mouse_click_event(buf); + } + if (KEY_ESC <= buf->code && buf->code <= KEY_MICMUTE) { + handle_keyboard_press_event(buf); + } + } + continue; + } + + ws_log(&log_ctx, LOG_DEBUG, "Unhandled event: %x %x", ev.type, ev.code); + + } +} diff --git a/pool/shard002/C/0063564_pl310.c b/pool/shard002/C/0063564_pl310.c new file mode 100644 index 0000000000000000000000000000000000000000..d88c8c444ba495b6c6e7cb20c0795523fb521b55 --- /dev/null +++ b/pool/shard002/C/0063564_pl310.c @@ -0,0 +1,205 @@ +/* + * Copyright (c) 2014 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 +#include +#include +#include +#include +#include + +/* configuration of the pl310 comes from #define space */ +#ifndef PL310_BASE +#error need to define PL310_BASE +#endif + +#define LOCAL_TRACE 0 + +#define PL310_REG(reg) (*REG32(PL310_BASE + (reg))) + +/* registers */ +#define REG0_CACHE_ID 0x000 +#define REG0_CACHE_TYPE 0x004 +#define REG1_CONTROL 0x100 +#define REG1_AUX_CONTROL 0x104 +#define REG1_TAG_RAM_CONTROL 0x108 +#define REG1_DATA_RAM_CONTROL 0x10c +#define REG2_EV_COUNTER_CTRL 0x200 +#define REG2_EV_COUNTER1_CFG 0x204 +#define REG2_EV_COUNTER0_CFG 0x208 +#define REG2_EV_COUNTER1 0x20c +#define REG2_EV_COUNTER0 0x210 +#define REG2_INT_MASK 0x214 +#define REG2_INT_MASK_STATUS 0x218 +#define REG2_INT_RAW_STATUS 0x21c +#define REG2_INT_CLEAR 0x220 +#define REG7_CACHE_SYNC 0x730 +#define REG7_INV_PA 0x770 +#define REG7_INV_WAY 0x77c +#define REG7_CLEAN_PA 0x7b0 +#define REG7_CLEAN_INDEX 0x7b8 +#define REG7_CLEAN_WAY 0x7bc +#define REG7_CLEAN_INV_PA 0x7f0 +#define REG7_CLEAN_INV_INDEX 0x7f8 +#define REG7_CLEAN_INV_WAY 0x7fc +#define REG9_D_LOCKDOWN0 0x900 +#define REG9_I_LOCKDOWN0 0x904 +#define REG9_D_LOCKDOWN1 0x908 +#define REG9_I_LOCKDOWN1 0x90c +#define REG9_D_LOCKDOWN2 0x910 +#define REG9_I_LOCKDOWN2 0x914 +#define REG9_D_LOCKDOWN3 0x918 +#define REG9_I_LOCKDOWN3 0x91c +#define REG9_D_LOCKDOWN4 0x920 +#define REG9_I_LOCKDOWN4 0x924 +#define REG9_D_LOCKDOWN5 0x928 +#define REG9_I_LOCKDOWN5 0x92c +#define REG9_D_LOCKDOWN6 0x930 +#define REG9_I_LOCKDOWN6 0x934 +#define REG9_D_LOCKDOWN7 0x938 +#define REG9_I_LOCKDOWN7 0x93c +#define REG9_LOCK_LINE_EN 0x950 +#define REG9_UNLOCK_WAY 0x954 +#define REG12_ADDR_FILTERING_START 0xc00 +#define REG12_ADDR_FILTERING_END 0xc04 +#define REG15_DEBUG_CTRL 0xf40 +#define REG15_PREFETCH_CTRL 0xf60 +#define REG15_POWER_CTRL 0xf80 + +static inline bool pl310_enabled(void) +{ + return !!(PL310_REG(REG1_CONTROL) & 1); +} + +static void pl310_init(uint level) +{ + /* make sure it's already disabled */ + DEBUG_ASSERT(!pl310_enabled()); + + /* set tag and data ram latency */ + PL310_REG(REG1_TAG_RAM_CONTROL) = PL310_TAG_RAM_LATENCY; + PL310_REG(REG1_DATA_RAM_CONTROL) = PL310_DATA_RAM_LATENCY; + + /* flush all the ways */ + PL310_REG(REG7_INV_WAY) = 0xffff; +} + +/* run just before arch_early_init so the L2 is ready to go when + * the arch code starts up the caching system. + */ +LK_INIT_HOOK(pl310_init, pl310_init, LK_INIT_LEVEL_ARCH_EARLY - 1); + +status_t pl310_set_enable(bool enable) +{ + LTRACEF("enable %d\n", enable); + + if (enable) { + if ((PL310_REG(REG1_CONTROL) & 1) == 0) { + /* if disabled */ + PL310_REG(REG1_CONTROL) = 1; + } + } else { + if ((PL310_REG(REG1_CONTROL) & 1) == 1) { + /* if enabled */ + pl310_flush_invalidate(); + PL310_REG(REG1_CONTROL) = 0; + /* this seems to not always latch on the first try */ + while (PL310_REG(REG1_CONTROL) & 1) { + PL310_REG(REG1_CONTROL) = 0; + } + } + } + + return NO_ERROR; +} + +void pl310_invalidate(void) +{ + if (unlikely(!pl310_enabled())) + return; + PL310_REG(REG7_INV_WAY) = 0xffff; + while (PL310_REG(REG7_INV_WAY) != 0) + ; +} + +void pl310_flush_invalidate(void) +{ + if (unlikely(!pl310_enabled())) + return; + PL310_REG(REG7_CLEAN_INV_WAY) = 0xffff; + while (PL310_REG(REG7_CLEAN_INV_WAY) != 0) + ; +} + +void pl310_sync_range(void) +{ + if (unlikely(!pl310_enabled())) + return; + + PL310_REG(REG7_CACHE_SYNC) = 1; +} + +#define PL310_LOOP_BODY(reg) \ + if (unlikely(!pl310_enabled())) \ + return; \ + \ + addr_t pa = 0; \ + uint32_t last_pa_page = 1; \ + addr_t last_va = start + len; \ + start &= ~(CACHE_LINE - 1); \ + while (start < last_va) { \ + if (unlikely(pa / PAGE_SIZE != last_pa_page)) { \ + /* get the physical address */ \ + if (unlikely(arm_vtop(start, &pa))) \ + return; \ + last_pa_page = pa / PAGE_SIZE; \ + } \ + PL310_REG(reg) = pa; \ + \ + pa += CACHE_LINE; \ + start += CACHE_LINE; \ + } \ +\ + PL310_REG(REG7_CACHE_SYNC) = 1; + +void pl310_clean_range(addr_t start, size_t len) +{ + LTRACEF("start 0x%lx, len %zd\n", start, len); + PL310_LOOP_BODY(REG7_CLEAN_PA); +} + +void pl310_clean_invalidate_range(addr_t start, size_t len) +{ + LTRACEF("start 0x%lx, len %zd\n", start, len); + PL310_LOOP_BODY(REG7_CLEAN_INV_PA); +} + +void pl310_invalidate_range(addr_t start, size_t len) +{ + LTRACEF("start 0x%lx, len %zd\n", start, len); + PL310_LOOP_BODY(REG7_INV_PA); +} + diff --git a/pool/shard002/C/0063572_cls_align_pointer.c b/pool/shard002/C/0063572_cls_align_pointer.c new file mode 100644 index 0000000000000000000000000000000000000000..9fb42b4898899f97a8ee088cbf20d08e8f55df4f --- /dev/null +++ b/pool/shard002/C/0063572_cls_align_pointer.c @@ -0,0 +1,98 @@ +/* Area: ffi_call, closure_call + Purpose: Check structure alignment of pointer. + Limitations: none. + PR: none. + Originator: 20031203 */ + +/* { dg-do run { xfail mips*-*-* arm*-*-* strongarm*-*-* xscale*-*-* } } */ +#include "ffitest.h" + +typedef struct cls_struct_align { + unsigned char a; + void *b; + unsigned char c; +} cls_struct_align; + +cls_struct_align cls_struct_align_fn(struct cls_struct_align a1, + struct cls_struct_align a2) +{ + struct cls_struct_align result; + + result.a = a1.a + a2.a; + result.b = (void *)((size_t)a1.b + (size_t)a2.b); + result.c = a1.c + a2.c; + + printf("%d %d %d %d %d %d: %d %d %d\n", a1.a, (size_t)a1.b, a1.c, a2.a, (size_t)a2.b, a2.c, result.a, (size_t)result.b, result.c); + + return result; +} + +static void +cls_struct_align_gn(ffi_cif* cif, void* resp, void** args, void* userdata) +{ + + struct cls_struct_align a1, a2; + + a1 = *(struct cls_struct_align*)(args[0]); + a2 = *(struct cls_struct_align*)(args[1]); + + *(cls_struct_align*)resp = cls_struct_align_fn(a1, a2); +} + +int main (void) +{ + ffi_cif cif; +#ifndef USING_MMAP + static ffi_closure cl; +#endif + ffi_closure *pcl; + void* args_dbl[5]; + ffi_type* cls_struct_fields[4]; + ffi_type cls_struct_type; + ffi_type* dbl_arg_types[5]; + +#ifdef USING_MMAP + pcl = allocate_mmap (sizeof(ffi_closure)); +#else + pcl = &cl; +#endif + + cls_struct_type.size = 0; + cls_struct_type.alignment = 0; + cls_struct_type.type = FFI_TYPE_STRUCT; + cls_struct_type.elements = cls_struct_fields; + + struct cls_struct_align g_dbl = { 12, (void *)4951, 127 }; + struct cls_struct_align f_dbl = { 1, (void *)9320, 13 }; + struct cls_struct_align res_dbl; + + cls_struct_fields[0] = &ffi_type_uchar; + cls_struct_fields[1] = &ffi_type_pointer; + cls_struct_fields[2] = &ffi_type_uchar; + cls_struct_fields[3] = NULL; + + dbl_arg_types[0] = &cls_struct_type; + dbl_arg_types[1] = &cls_struct_type; + dbl_arg_types[2] = NULL; + + CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 2, &cls_struct_type, + dbl_arg_types) == FFI_OK); + + args_dbl[0] = &g_dbl; + args_dbl[1] = &f_dbl; + args_dbl[2] = NULL; + + ffi_call(&cif, FFI_FN(cls_struct_align_fn), &res_dbl, args_dbl); + /* { dg-output "12 4951 127 1 9320 13: 13 14271 140" } */ + printf("res: %d %d %d\n", res_dbl.a, (size_t)res_dbl.b, res_dbl.c); + /* { dg-output "\nres: 13 14271 140" } */ + + CHECK(ffi_prep_closure(pcl, &cif, cls_struct_align_gn, NULL) == FFI_OK); + + res_dbl = ((cls_struct_align(*)(cls_struct_align, cls_struct_align))(pcl))(g_dbl, f_dbl); + /* { dg-output "\n12 4951 127 1 9320 13: 13 14271 140" } */ + printf("res: %d %d %d\n", res_dbl.a, (size_t)res_dbl.b, res_dbl.c); + /* { dg-output "\nres: 13 14271 140" } */ + + exit(0); +} diff --git a/pool/shard002/C/0063576_ec_cvt.c b/pool/shard002/C/0063576_ec_cvt.c new file mode 100644 index 0000000000000000000000000000000000000000..1145bfb68f90df428a65b1f88d6dfad34b3c8cea --- /dev/null +++ b/pool/shard002/C/0063576_ec_cvt.c @@ -0,0 +1,89 @@ +/* + * Copyright 2001-2021 The OpenSSL Project Authors. All Rights Reserved. + * Copyright (c) 2002, Oracle and/or its affiliates. All rights reserved + * + * Licensed under the Apache License 2.0 (the "License"). You may not use + * this file except in compliance with the License. You can obtain a copy + * in the file LICENSE in the source distribution or at + * https://www.openssl.org/source/license.html + */ + +/* + * ECDSA low level APIs are deprecated for public use, but still ok for + * internal use. + */ +#include "internal/deprecated.h" + +#include +#include "crypto/bn.h" +#include "ec_local.h" + +EC_GROUP *EC_GROUP_new_curve_GFp(const BIGNUM *p, const BIGNUM *a, + const BIGNUM *b, BN_CTX *ctx) +{ + const EC_METHOD *meth; + EC_GROUP *ret; + +#if defined(OPENSSL_BN_ASM_MONT) + /* + * This might appear controversial, but the fact is that generic + * prime method was observed to deliver better performance even + * for NIST primes on a range of platforms, e.g.: 60%-15% + * improvement on IA-64, ~25% on ARM, 30%-90% on P4, 20%-25% + * in 32-bit build and 35%--12% in 64-bit build on Core2... + * Coefficients are relative to optimized bn_nist.c for most + * intensive ECDSA verify and ECDH operations for 192- and 521- + * bit keys respectively. Choice of these boundary values is + * arguable, because the dependency of improvement coefficient + * from key length is not a "monotone" curve. For example while + * 571-bit result is 23% on ARM, 384-bit one is -1%. But it's + * generally faster, sometimes "respectfully" faster, sometimes + * "tolerably" slower... What effectively happens is that loop + * with bn_mul_add_words is put against bn_mul_mont, and the + * latter "wins" on short vectors. Correct solution should be + * implementing dedicated NxN multiplication subroutines for + * small N. But till it materializes, let's stick to generic + * prime method... + * + */ + meth = EC_GFp_mont_method(); +#else + if (BN_nist_mod_func(p)) + meth = EC_GFp_nist_method(); + else + meth = EC_GFp_mont_method(); +#endif + + ret = ossl_ec_group_new_ex(ossl_bn_get_libctx(ctx), NULL, meth); + if (ret == NULL) + return NULL; + + if (!EC_GROUP_set_curve(ret, p, a, b, ctx)) { + EC_GROUP_free(ret); + return NULL; + } + + return ret; +} + +#ifndef OPENSSL_NO_EC2M +EC_GROUP *EC_GROUP_new_curve_GF2m(const BIGNUM *p, const BIGNUM *a, + const BIGNUM *b, BN_CTX *ctx) +{ + const EC_METHOD *meth; + EC_GROUP *ret; + + meth = EC_GF2m_simple_method(); + + ret = ossl_ec_group_new_ex(ossl_bn_get_libctx(ctx), NULL, meth); + if (ret == NULL) + return NULL; + + if (!EC_GROUP_set_curve(ret, p, a, b, ctx)) { + EC_GROUP_free(ret); + return NULL; + } + + return ret; +} +#endif diff --git a/pool/shard002/C/0063587_contents.c b/pool/shard002/C/0063587_contents.c new file mode 100644 index 0000000000000000000000000000000000000000..ab8538faa079955787e0fca7e30cbe8368b4eacc --- /dev/null +++ b/pool/shard002/C/0063587_contents.c @@ -0,0 +1,155 @@ +// ---------------------------------------------------------------------------- +// Routines for Saving and retreiving Contents data. +// The flash RAM is used to store the contents in a binary array. Data is +// received and sent as JSON. +// ---------------------------------------------------------------------------- +#include +#include +#include +#include +#include +#include "espmissingincludes.h" +#include "stdout.h" +#include "contents.h" + +// ---------------------------------------------------------------------------- +// Global definitions and variables +// ---------------------------------------------------------------------------- +#define FLASHCONTENTS 0x11000 // Flash RAM location for user memory +#define FLASHSECTOR FLASHCONTENTS/0x1000 // Flash RAM location for user memory +#define RECORD_LEN 32 // each record is 32 bytes + +// ---------------------------------------------------------------------------- +// Get it back from Flash +// ---------------------------------------------------------------------------- +static void getfromFlash(uint32 flash_addr, char *str, int len) +{ + SpiFlashOpResult ret; + ret = spi_flash_read(flash_addr, (uint32 *)str, len); + if(ret != SPI_FLASH_RESULT_OK) { + os_printf("flash read error: %d\r\n", (int)ret); + } +} + +// ---------------------------------------------------------------------------- +// CGI that reads the json db and returns it +// ---------------------------------------------------------------------------- +int ICACHE_FLASH_ATTR get_contents(char *buffer) +{ + char str[32]; // place for just the content item + uint32 flash_addr = FLASHCONTENTS; // user memory + + os_sprintf(buffer,"{\"contents\":[\n"); + int n = strlen(buffer); + for(int i = 0; i < 32; i++) { + getfromFlash(flash_addr, str, 32); // ingredient str len is 32 fixed + if(str[0] == 0xFF) { // This means it is an empty slot + n += os_sprintf(&buffer[n],"{\"name\":\"empty\",\"amount\":0},"); + } + else { + int val = (str[30] << 8) | str[31]; + str[30] = 0; // precautionary + n += os_sprintf(&buffer[n],"{\"name\":\"%s\",\"amount\":%d},", str, val); + } + flash_addr += 32; + } + n--; + n += os_sprintf(&buffer[n],"]}\n"); + return(n); +} + +// ---------------------------------------------------------------------------- +// Erase the sector from flash so it is ready to be reprogrammed +// ---------------------------------------------------------------------------- +static void eraseFlashsector(int sector) +{ + SpiFlashOpResult ret; + ret = spi_flash_erase_sector(sector); + if(ret != SPI_FLASH_RESULT_OK) { + os_printf("flash sector erase error: %d\r\n", (int)ret); + } +} + +// ---------------------------------------------------------------------------- +// Save contentst to Flash +// ---------------------------------------------------------------------------- +static void savetoFlash(char *buffer, int len) +{ + SpiFlashOpResult ret; + uint32 flash_addr = FLASHCONTENTS; // user memory + + ret = spi_flash_write(flash_addr, (uint32 *)buffer, len); + if(ret != SPI_FLASH_RESULT_OK) os_printf("error ret: %d\r\n", (int)ret); +} + +// ---------------------------------------------------------------------------- +// CGI that receives the json list of canister contents +// ---------------------------------------------------------------------------- +void ICACHE_FLASH_ATTR put_contents(char *jsdata, int len) +{ + char type; + char str[80]; + char buffer[1024]; // contents names + + struct jsonparse_state state; + struct jsonparse_state *js = &state; + jsonparse_setup(js, jsdata, len); + type = jsonparse_next(js); + if(type != JSON_TYPE_OBJECT) { + os_printf("Not a valid JSON file(1)\n"); + return; + } + type = jsonparse_next(js); + if(type != JSON_TYPE_PAIR_NAME) { + os_printf("Not a valid JSON file(2)\n"); + return; + } + jsonparse_copy_value(js, str, 80); + if(jsonparse_strcmp_value(js, "contents") != 0) { + os_printf("Not a valid Contents file\n"); + return; + } + int n = 0; + for(int i=0; i < 1024; i++) buffer[i] = 0; + while(js->pos < js->len) { + type = jsonparse_next(js); + if(type != JSON_TYPE_PAIR_NAME) continue; + if(jsonparse_strcmp_value(js, "name") == 0) { + type = jsonparse_next(js); + if(type == JSON_TYPE_PAIR) { + type = jsonparse_next(js); + if(type == JSON_TYPE_STRING) { + jsonparse_copy_value(js, &buffer[n], 30); + n += 32; + } + } + } + if(jsonparse_strcmp_value(js, "amount") == 0) { + type = jsonparse_next(js); + if(type == JSON_TYPE_PAIR) { + type = jsonparse_next(js); + int val = 0; + if(type == JSON_TYPE_NUMBER) val = jsonparse_get_value_as_int(js); + else if(type == JSON_TYPE_STRING) { + jsonparse_copy_value(js, str, 16); + val = atoi(str); + } + buffer[n-2] = (uint8_t)(val >> 8); + buffer[n-1] = (uint8_t)(val & 0xff); + } + } + if(n > 1024) { + os_printf("file is too large to save all\n"); + break; + } + } + os_printf("json object parsed\n"); + // now that we parsed all that JSON bullshit, now we can finnaly save + // our data into flash, but first, we have to erase a sector + eraseFlashsector(FLASHSECTOR); + savetoFlash(buffer, n); + os_printf("Contents data saved to flash\n"); +} + +// ---------------------------------------------------------------------------- + diff --git a/pool/shard002/C/0063589_adsp_Options.c b/pool/shard002/C/0063589_adsp_Options.c new file mode 100644 index 0000000000000000000000000000000000000000..f40ce433be1e1206788224afb01a8dd49e4cbabe --- /dev/null +++ b/pool/shard002/C/0063589_adsp_Options.c @@ -0,0 +1,103 @@ +/* + * Copyright (c) 2000 Apple Computer, Inc. All rights reserved. + * + * @APPLE_OSREFERENCE_LICENSE_HEADER_START@ + * + * This file contains Original Code and/or Modifications of Original Code + * as defined in and that are subject to the Apple Public Source License + * Version 2.0 (the 'License'). You may not use this file except in + * compliance with the License. The rights granted to you under the License + * may not be used to create, or enable the creation or redistribution of, + * unlawful or unlicensed copies of an Apple operating system, or to + * circumvent, violate, or enable the circumvention or violation of, any + * terms of an Apple operating system software license agreement. + * + * Please obtain a copy of the License at + * http://www.opensource.apple.com/apsl/ and read it before using this file. + * + * The Original Code and all software distributed under the License are + * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER + * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, + * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. + * Please see the License for the specific language governing rights and + * limitations under the License. + * + * @APPLE_OSREFERENCE_LICENSE_HEADER_END@ + */ +/* + * dspOptions.c + * + * From v01.06 04/19/90 mbs + * Modified, April 9, 1997 by Tuyen Nguyen for MacOSX. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +/* + * dspOptions + * + * INPUTS: + * --> ccbRefNum refnum of connection end + * --> sendBlocking send blocking threshold + * --> sendTimer send timer interval + * --> rtmtTimer retransmit timer interval + * --> badSeqMax retransmit advice send threshold + * --> useCheckSum generate DDP checksum on internet packets + * + * OUTPUTS: + * none + * + * ERRORS: + * errRefNum bad connection refnum +*/ +int adspOptions(sp, pb) /* (DSPPBPtr pb) */ + CCBPtr sp; + struct adspcmd *pb; +{ + if (sp == 0) { + pb->ioResult = errRefNum; + return EINVAL; + } + + if (pb->u.optionParams.sendBlocking) + sp->sendBlocking = pb->u.optionParams.sendBlocking; + + if (pb->u.optionParams.sendTimer) + sp->sendInterval = pb->u.optionParams.sendTimer; + + /* No longer allowed to set retransmit timer as of ADSP 1.5 */ + /* Use it to specify a command blocking request specific to MacOS + * emulation. */ + if (pb->u.optionParams.rtmtTimer) + sp->delay = pb->u.optionParams.rtmtTimer; + KERNEL_DEBUG(DBG_ADSP_MISC, 0, sp, sp->delay, pb, pb->u.optionParams.rtmtTimer); + + if (pb->u.optionParams.badSeqMax) + sp->badSeqMax = pb->u.optionParams.badSeqMax; + + sp->useCheckSum = pb->u.optionParams.useCheckSum; + if (pb->u.optionParams.newPID) + sp->pid = pb->u.optionParams.newPID; + pb->ioResult = 0; + adspioc_ack(0, (gbuf_t *)pb->ioc, pb->gref); + return 0; + +} diff --git a/pool/shard002/C/0063601_pppox.c b/pool/shard002/C/0063601_pppox.c new file mode 100644 index 0000000000000000000000000000000000000000..9128e42e33e74f5f744fa4b9564cb31d2394d71b --- /dev/null +++ b/pool/shard002/C/0063601_pppox.c @@ -0,0 +1,163 @@ +/** -*- linux-c -*- *********************************************************** + * Linux PPP over X/Ethernet (PPPoX/PPPoE) Sockets + * + * PPPoX --- Generic PPP encapsulation socket family + * PPPoE --- PPP over Ethernet (RFC 2516) + * + * + * Version: 0.5.2 + * + * Author: Michal Ostrowski + * + * 051000 : Initialization cleanup + * + * License: + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version + * 2 of the License, or (at your option) any later version. + * + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +#include + +static const struct pppox_proto *pppox_protos[PX_MAX_PROTO + 1]; + +int register_pppox_proto(int proto_num, const struct pppox_proto *pp) +{ + if (proto_num < 0 || proto_num > PX_MAX_PROTO) + return -EINVAL; + if (pppox_protos[proto_num]) + return -EALREADY; + pppox_protos[proto_num] = pp; + return 0; +} + +void unregister_pppox_proto(int proto_num) +{ + if (proto_num >= 0 && proto_num <= PX_MAX_PROTO) + pppox_protos[proto_num] = NULL; +} + +void pppox_unbind_sock(struct sock *sk) +{ + /* Clear connection to ppp device, if attached. */ + + if (sk->sk_state & (PPPOX_BOUND | PPPOX_CONNECTED)) { + ppp_unregister_channel(&pppox_sk(sk)->chan); + sk->sk_state = PPPOX_DEAD; + } +} + +EXPORT_SYMBOL(register_pppox_proto); +EXPORT_SYMBOL(unregister_pppox_proto); +EXPORT_SYMBOL(pppox_unbind_sock); + +int pppox_ioctl(struct socket *sock, unsigned int cmd, unsigned long arg) +{ + struct sock *sk = sock->sk; + struct pppox_sock *po = pppox_sk(sk); + int rc; + + lock_sock(sk); + + switch (cmd) { + case PPPIOCGCHAN: { + int index; + rc = -ENOTCONN; + if (!(sk->sk_state & PPPOX_CONNECTED)) + break; + + rc = -EINVAL; + index = ppp_channel_index(&po->chan); + if (put_user(index , (int __user *) arg)) + break; + + rc = 0; + sk->sk_state |= PPPOX_BOUND; + break; + } + default: + rc = pppox_protos[sk->sk_protocol]->ioctl ? + pppox_protos[sk->sk_protocol]->ioctl(sock, cmd, arg) : -ENOTTY; + } + + release_sock(sk); + return rc; +} + +EXPORT_SYMBOL(pppox_ioctl); + +#ifdef CONFIG_COMPAT +int pppox_compat_ioctl(struct socket *sock, unsigned int cmd, unsigned long arg) +{ + if (cmd == PPPOEIOCSFWD32) + cmd = PPPOEIOCSFWD; + + return pppox_ioctl(sock, cmd, (unsigned long)compat_ptr(arg)); +} + +EXPORT_SYMBOL(pppox_compat_ioctl); +#endif + +static int pppox_create(struct net *net, struct socket *sock, int protocol, + int kern) +{ + int rc = -EPROTOTYPE; + + if (protocol < 0 || protocol > PX_MAX_PROTO) + goto out; + + rc = -EPROTONOSUPPORT; + if (!pppox_protos[protocol]) + request_module("net-pf-%d-proto-%d", PF_PPPOX, protocol); + if (!pppox_protos[protocol] || + !try_module_get(pppox_protos[protocol]->owner)) + goto out; + + rc = pppox_protos[protocol]->create(net, sock, kern); + + module_put(pppox_protos[protocol]->owner); +out: + return rc; +} + +static const struct net_proto_family pppox_proto_family = { + .family = PF_PPPOX, + .create = pppox_create, + .owner = THIS_MODULE, +}; + +static int __init pppox_init(void) +{ + return sock_register(&pppox_proto_family); +} + +static void __exit pppox_exit(void) +{ + sock_unregister(PF_PPPOX); +} + +module_init(pppox_init); +module_exit(pppox_exit); + +MODULE_AUTHOR("Michal Ostrowski "); +MODULE_DESCRIPTION("PPP over Ethernet driver (generic socket layer)"); +MODULE_LICENSE("GPL"); +MODULE_ALIAS_NETPROTO(PF_PPPOX); diff --git a/pool/shard002/C/0063609_liberation_01.c b/pool/shard002/C/0063609_liberation_01.c new file mode 100644 index 0000000000000000000000000000000000000000..3bb4516062fa44198590748106dd8a5e37ab5ba2 --- /dev/null +++ b/pool/shard002/C/0063609_liberation_01.c @@ -0,0 +1,159 @@ +/* Examples/liberation_01.c +Jerasure - A C/C++ Library for a Variety of Reed-Solomon and RAID-6 Erasure Coding Techniques + +Revision 1.2A +May 24, 2011 + +James S. Plank +Department of Electrical Engineering and Computer Science +University of Tennessee +Knoxville, TN 37996 +plank@cs.utk.edu + +Copyright (c) 2011, James S. Plank +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: + + - Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + + - Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in + the documentation and/or other materials provided with the + distribution. + + - Neither the name of the University of Tennessee 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. + + + */ + + +/* + revised by S. Simmerman + 2/25/08 +*/ +#include +#include +#include +#include "jerasure.h" +#include "liberation.h" +#include "examples.h" + +usage(char *s) +{ + fprintf(stderr, "usage: liberation_01 k w - Liberation RAID-6 coding/decoding example in GF(2^w).\n"); + fprintf(stderr, " \n"); + fprintf(stderr, " w must be prime and k <= w. It sets up a Liberation bit-matrix\n"); + fprintf(stderr, " then it encodes k devices of w*%d bytes using dumb bit-matrix scheduling.\n", sizeof(gdata)); + fprintf(stderr, " It decodes using smart bit-matrix scheduling.\n"); + fprintf(stderr, " \n"); + fprintf(stderr, "This demonstrates: liberation_coding_bitmatrix()\n"); + fprintf(stderr, " jerasure_smart_bitmatrix_to_schedule()\n"); + fprintf(stderr, " jerasure_dumb_bitmatrix_to_schedule()\n"); + fprintf(stderr, " jerasure_schedule_encode()\n"); + fprintf(stderr, " jerasure_schedule_decode_lazy()\n"); + fprintf(stderr, " jerasure_print_bitmatrix()\n"); + fprintf(stderr, " jerasure_get_stats()\n"); + if (s != NULL) fprintf(stderr, "%s\n", s); + exit(1); +} + +int main(int argc, char **argv) +{ + gdata l; + int k, w, i, j, m; + int *bitmatrix; + char **data, **coding, **ptrs; + int **dumb; + int *erasures, *erased; + double stats[3]; + + if (argc != 3) usage(NULL); + if (sscanf(argv[1], "%d", &k) == 0 || k <= 0) usage("Bad k"); + if (sscanf(argv[2], "%d", &w) == 0 || w <= 0 || w > 32) usage("Bad w"); + m = 2; + if (w < k) usage("k is too big"); + + bitmatrix = liberation_coding_bitmatrix(k, w); + if (bitmatrix == NULL) { + usage("couldn't make coding matrix"); + } + + printf("Coding Bit-Matrix:\n\n"); + jerasure_print_bitmatrix(bitmatrix, w*m, w*k, w); + printf("\n"); + + dumb = jerasure_dumb_bitmatrix_to_schedule(k, m, w, bitmatrix); + + srand48(0); + data = talloc(char *, k); + for (i = 0; i < k; i++) { + data[i] = talloc(char, sizeof(gdata)*w); + fillrand(data[i], sizeof(gdata)*w); + } + + coding = talloc(char *, m); + for (i = 0; i < m; i++) { + coding[i] = talloc(char, sizeof(gdata)*w); + } + + jerasure_schedule_encode(k, m, w, dumb, data, coding, w*sizeof(gdata), sizeof(gdata)); + jerasure_get_stats(stats); + printf("Smart Encoding Complete: - %.0lf XOR'd bytes\n\n", stats[0]); + print_data_and_coding_2(k, m, w, sizeof(gdata), data, coding); + + erasures = talloc(int, (m+1)); + erased = talloc(int, (k+m)); + for (i = 0; i < m+k; i++) erased[i] = 0; + for (i = 0; i < m; ) { + erasures[i] = lrand48()%(k+m); + if (erased[erasures[i]] == 0) { + erased[erasures[i]] = 1; + memset((erasures[i] < k) ? data[erasures[i]] : coding[erasures[i]-k], 0, sizeof(gdata)*w); + i++; + } + } + erasures[i] = -1; + + printf("Erased %d random devices:\n\n", m); + print_data_and_coding_2(k, m, w, sizeof(gdata), data, coding); + + jerasure_schedule_decode_lazy(k, m, w, bitmatrix, erasures, data, coding, w*sizeof(gdata), sizeof(gdata), 1); + jerasure_get_stats(stats); + + printf("State of the system after decoding: %.0lf XOR'd bytes\n\n", stats[0]); + print_data_and_coding_2(k, m, w, sizeof(gdata), data, coding); + /* free data to avoid false positives for leak testing */ + free(erased); + free(erasures); + for (i = 0; i < m; i++) { + free(coding[i]); + } + free(coding); + for (i = 0; i < k; i++) { + free(data[i]); + } + free(data); + jerasure_free_schedule(dumb); + free(bitmatrix); + + return 0; +} diff --git a/pool/shard002/C/0063643_ieee802154_security.c b/pool/shard002/C/0063643_ieee802154_security.c new file mode 100644 index 0000000000000000000000000000000000000000..40359799ff527cbce8c59aaeffba2f5df344f7d0 --- /dev/null +++ b/pool/shard002/C/0063643_ieee802154_security.c @@ -0,0 +1,197 @@ +/* + * Copyright (c) 2017 Intel Corporation. + * + * SPDX-License-Identifier: Apache-2.0 + */ + +#include +LOG_MODULE_REGISTER(net_ieee802154_security, + CONFIG_NET_L2_IEEE802154_LOG_LEVEL); + +#include +#include + +#include "ieee802154_frame.h" +#include "ieee802154_security.h" + +extern const uint8_t level_2_tag_size[4]; + +int ieee802154_security_setup_session(struct ieee802154_security_ctx *sec_ctx, + uint8_t level, uint8_t key_mode, + uint8_t *key, uint8_t key_len) +{ + uint8_t tag_size; + int ret; + + if (level > IEEE802154_SECURITY_LEVEL_ENC_MIC_128 || + key_mode > IEEE802154_KEY_ID_MODE_SRC_8_INDEX) { + return -EINVAL; + } + + /* ToDo: supporting other key modes */ + if (level > IEEE802154_SECURITY_LEVEL_NONE && + (key_len > IEEE802154_KEY_MAX_LEN || !key || + key_mode != IEEE802154_KEY_ID_MODE_IMPLICIT)) { + return -EINVAL; + } + + if (level >= IEEE802154_SECURITY_LEVEL_ENC) { + tag_size = level_2_tag_size[level - 4]; + } else { + tag_size = level_2_tag_size[level]; + } + + sec_ctx->level = level; + + if (level > IEEE802154_SECURITY_LEVEL_NONE) { + memcpy(sec_ctx->key, key, key_len); + sec_ctx->key_len = key_len; + sec_ctx->key_mode = key_mode; + + sec_ctx->enc.key.bit_stream = sec_ctx->key; + sec_ctx->enc.keylen = sec_ctx->key_len; + + sec_ctx->dec.key.bit_stream = sec_ctx->key; + sec_ctx->dec.keylen = sec_ctx->key_len; + } + + sec_ctx->enc.mode_params.ccm_info.tag_len = tag_size; + sec_ctx->dec.mode_params.ccm_info.tag_len = tag_size; + + ret = cipher_begin_session(sec_ctx->enc.device, &sec_ctx->enc, + CRYPTO_CIPHER_ALGO_AES, + CRYPTO_CIPHER_MODE_CCM, + CRYPTO_CIPHER_OP_ENCRYPT); + if (ret) { + NET_ERR("Could not setup encryption context"); + + return ret; + } + + ret = cipher_begin_session(sec_ctx->dec.device, &sec_ctx->dec, + CRYPTO_CIPHER_ALGO_AES, + CRYPTO_CIPHER_MODE_CCM, + CRYPTO_CIPHER_OP_DECRYPT); + if (ret) { + NET_ERR("Could not setup decryption context"); + cipher_free_session(sec_ctx->enc.device, &sec_ctx->enc); + + return ret; + } + + return 0; +} + +bool ieee802154_decrypt_auth(struct ieee802154_security_ctx *sec_ctx, + uint8_t *frame, + uint8_t auth_payload_len, + uint8_t decrypt_payload_len, + uint8_t *src_ext_addr, + uint32_t frame_counter) +{ + struct cipher_aead_pkt apkt; + struct cipher_pkt pkt; + uint8_t nonce[13]; + int ret; + + if (!sec_ctx || sec_ctx->level == IEEE802154_SECURITY_LEVEL_NONE) { + return true; + } + + /* See Section 7.3.2 */ + memcpy(nonce, src_ext_addr, IEEE802154_EXT_ADDR_LENGTH); + nonce[8] = (uint8_t)(frame_counter >> 24); + nonce[9] = (uint8_t)(frame_counter >> 16); + nonce[10] = (uint8_t)(frame_counter >> 8); + nonce[11] = (uint8_t)frame_counter; + nonce[12] = sec_ctx->level; + + pkt.in_buf = decrypt_payload_len ? frame + auth_payload_len : NULL; + pkt.in_len = decrypt_payload_len; + pkt.out_buf = frame; + pkt.out_buf_max = IEEE802154_MTU - IEEE802154_MFR_LENGTH; + + apkt.ad = frame; + apkt.ad_len = auth_payload_len; + apkt.tag = sec_ctx->dec.mode_params.ccm_info.tag_len ? + frame + auth_payload_len + decrypt_payload_len : NULL; + apkt.pkt = &pkt; + + ret = cipher_ccm_op(&sec_ctx->dec, &apkt, nonce); + if (ret) { + NET_ERR("Cannot decrypt/auth (%i): %p %u/%u - fc %u", + ret, frame, auth_payload_len, decrypt_payload_len, + frame_counter); + return false; + } + + return true; +} + +bool ieee802154_encrypt_auth(struct ieee802154_security_ctx *sec_ctx, + uint8_t *frame, + uint8_t auth_payload_len, + uint8_t encrypt_payload_len, + uint8_t *src_ext_addr) +{ + struct cipher_aead_pkt apkt; + struct cipher_pkt pkt; + uint8_t nonce[13]; + int ret; + + if (!sec_ctx || sec_ctx->level == IEEE802154_SECURITY_LEVEL_NONE) { + return true; + } + + /* See Section 7.3.2 */ + memcpy(nonce, src_ext_addr, IEEE802154_EXT_ADDR_LENGTH); + sys_put_be32(sec_ctx->frame_counter, &nonce[8]); + nonce[12] = sec_ctx->level; + + pkt.in_buf = encrypt_payload_len ? frame + auth_payload_len : NULL; + pkt.in_len = encrypt_payload_len; + pkt.out_buf = frame; + pkt.out_buf_max = IEEE802154_MTU - IEEE802154_MFR_LENGTH; + + apkt.ad = frame; + apkt.ad_len = auth_payload_len; + apkt.tag = NULL; + apkt.pkt = &pkt; + + ret = cipher_ccm_op(&sec_ctx->enc, &apkt, nonce); + if (ret) { + NET_ERR("Cannot encrypt/auth (%i): %p %u/%u - fc %u", + ret, frame, auth_payload_len, encrypt_payload_len, + sec_ctx->frame_counter); + return false; + } + + sec_ctx->frame_counter++; + + return true; +} + +int ieee802154_security_init(struct ieee802154_security_ctx *sec_ctx) +{ + const struct device *dev; + + (void)memset(&sec_ctx->enc, 0, sizeof(struct cipher_ctx)); + (void)memset(&sec_ctx->dec, 0, sizeof(struct cipher_ctx)); + + dev = device_get_binding( + CONFIG_NET_L2_IEEE802154_SECURITY_CRYPTO_DEV_NAME); + if (!dev) { + return -ENODEV; + } + + sec_ctx->enc.flags = cipher_query_hwcaps(dev); + sec_ctx->dec.flags = cipher_query_hwcaps(dev); + + sec_ctx->enc.mode_params.ccm_info.nonce_len = 13U; + sec_ctx->dec.mode_params.ccm_info.nonce_len = 13U; + + sec_ctx->enc.device = dev; + sec_ctx->dec.device = dev; + + return 0; +} diff --git a/pool/shard002/C/0063644_rc5speed.c b/pool/shard002/C/0063644_rc5speed.c new file mode 100644 index 0000000000000000000000000000000000000000..8e363be535b4ff926756374a1ec937da157fa0ee --- /dev/null +++ b/pool/shard002/C/0063644_rc5speed.c @@ -0,0 +1,277 @@ +/* crypto/rc5/rc5speed.c */ +/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com) + * All rights reserved. + * + * This package is an SSL implementation written + * by Eric Young (eay@cryptsoft.com). + * The implementation was written so as to conform with Netscapes SSL. + * + * This library is free for commercial and non-commercial use as long as + * the following conditions are aheared to. The following conditions + * apply to all code found in this distribution, be it the RC4, RSA, + * lhash, DES, etc., code; not just the SSL code. The SSL documentation + * included with this distribution is covered by the same copyright terms + * except that the holder is Tim Hudson (tjh@cryptsoft.com). + * + * Copyright remains Eric Young's, and as such any Copyright notices in + * the code are not to be removed. + * If this package is used in a product, Eric Young should be given attribution + * as the author of the parts of the library used. + * This can be in the form of a textual message at program startup or + * in documentation (online or textual) provided with the package. + * + * 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 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 cryptographic software written by + * Eric Young (eay@cryptsoft.com)" + * The word 'cryptographic' can be left out if the rouines from the library + * being used are not cryptographic related :-). + * 4. If you include any Windows specific code (or a derivative thereof) from + * the apps directory (application code) you must include an acknowledgement: + * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)" + * + * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``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. + * + * The licence and distribution terms for any publically available version or + * derivative of this code cannot be changed. i.e. this code cannot simply be + * copied and put under another distribution licence + * [including the GNU Public Licence.] + */ + +/* 11-Sep-92 Andrew Daviel Support for Silicon Graphics IRIX added */ +/* 06-Apr-92 Luke Brennan Support for VMS and add extra signal calls */ + +#if !defined(OPENSSL_SYS_MSDOS) && (!defined(OPENSSL_SYS_VMS) || defined(__DECC)) && !defined(OPENSSL_SYS_MACOSX) +#define TIMES +#endif + +#include + +#include +#include OPENSSL_UNISTD_IO +OPENSSL_DECLARE_EXIT + +#ifndef OPENSSL_SYS_NETWARE +#include +#endif + +#ifndef _IRIX +#include +#endif +#ifdef TIMES +#include +#include +#endif + +/* Depending on the VMS version, the tms structure is perhaps defined. + The __TMS macro will show if it was. If it wasn't defined, we should + undefine TIMES, since that tells the rest of the program how things + should be handled. -- Richard Levitte */ +#if defined(OPENSSL_SYS_VMS_DECC) && !defined(__TMS) +#undef TIMES +#endif + +#ifndef TIMES +#include +#endif + +#if defined(sun) || defined(__ultrix) +#define _POSIX_SOURCE +#include +#include +#endif + +#include + +/* The following if from times(3) man page. It may need to be changed */ +#ifndef HZ +#ifndef CLK_TCK +#define HZ 100.0 +#else /* CLK_TCK */ +#define HZ ((double)CLK_TCK) +#endif +#endif + +#define BUFSIZE ((long)1024) +long run=0; + +double Time_F(int s); +#ifdef SIGALRM +#if defined(__STDC__) || defined(sgi) || defined(_AIX) +#define SIGRETTYPE void +#else +#define SIGRETTYPE int +#endif + +SIGRETTYPE sig_done(int sig); +SIGRETTYPE sig_done(int sig) + { + signal(SIGALRM,sig_done); + run=0; +#ifdef LINT + sig=sig; +#endif + } +#endif + +#define START 0 +#define STOP 1 + +double Time_F(int s) + { + double ret; +#ifdef TIMES + static struct tms tstart,tend; + + if (s == START) + { + times(&tstart); + return(0); + } + else + { + times(&tend); + ret=((double)(tend.tms_utime-tstart.tms_utime))/HZ; + return((ret == 0.0)?1e-6:ret); + } +#else /* !times() */ + static struct timeb tstart,tend; + long i; + + if (s == START) + { + ftime(&tstart); + return(0); + } + else + { + ftime(&tend); + i=(long)tend.millitm-(long)tstart.millitm; + ret=((double)(tend.time-tstart.time))+((double)i)/1e3; + return((ret == 0.0)?1e-6:ret); + } +#endif + } + +int main(int argc, char **argv) + { + long count; + static unsigned char buf[BUFSIZE]; + static unsigned char key[] ={ + 0x12,0x34,0x56,0x78,0x9a,0xbc,0xde,0xf0, + 0xfe,0xdc,0xba,0x98,0x76,0x54,0x32,0x10, + }; + RC5_32_KEY sch; + double a,b,c,d; +#ifndef SIGALRM + long ca,cb,cc; +#endif + +#ifndef TIMES + printf("To get the most accurate results, try to run this\n"); + printf("program when this computer is idle.\n"); +#endif + +#ifndef SIGALRM + printf("First we calculate the approximate speed ...\n"); + RC5_32_set_key(&sch,16,key,12); + count=10; + do { + long i; + unsigned long data[2]; + + count*=2; + Time_F(START); + for (i=count; i; i--) + RC5_32_encrypt(data,&sch); + d=Time_F(STOP); + } while (d < 3.0); + ca=count/512; + cb=count; + cc=count*8/BUFSIZE+1; + printf("Doing RC5_32_set_key %ld times\n",ca); +#define COND(d) (count != (d)) +#define COUNT(d) (d) +#else +#define COND(c) (run) +#define COUNT(d) (count) + signal(SIGALRM,sig_done); + printf("Doing RC5_32_set_key for 10 seconds\n"); + alarm(10); +#endif + + Time_F(START); + for (count=0,run=1; COND(ca); count+=4) + { + RC5_32_set_key(&sch,16,key,12); + RC5_32_set_key(&sch,16,key,12); + RC5_32_set_key(&sch,16,key,12); + RC5_32_set_key(&sch,16,key,12); + } + d=Time_F(STOP); + printf("%ld RC5_32_set_key's in %.2f seconds\n",count,d); + a=((double)COUNT(ca))/d; + +#ifdef SIGALRM + printf("Doing RC5_32_encrypt's for 10 seconds\n"); + alarm(10); +#else + printf("Doing RC5_32_encrypt %ld times\n",cb); +#endif + Time_F(START); + for (count=0,run=1; COND(cb); count+=4) + { + unsigned long data[2]; + + RC5_32_encrypt(data,&sch); + RC5_32_encrypt(data,&sch); + RC5_32_encrypt(data,&sch); + RC5_32_encrypt(data,&sch); + } + d=Time_F(STOP); + printf("%ld RC5_32_encrypt's in %.2f second\n",count,d); + b=((double)COUNT(cb)*8)/d; + +#ifdef SIGALRM + printf("Doing RC5_32_cbc_encrypt on %ld byte blocks for 10 seconds\n", + BUFSIZE); + alarm(10); +#else + printf("Doing RC5_32_cbc_encrypt %ld times on %ld byte blocks\n",cc, + BUFSIZE); +#endif + Time_F(START); + for (count=0,run=1; COND(cc); count++) + RC5_32_cbc_encrypt(buf,buf,BUFSIZE,&sch, + &(key[0]),RC5_ENCRYPT); + d=Time_F(STOP); + printf("%ld RC5_32_cbc_encrypt's of %ld byte blocks in %.2f second\n", + count,BUFSIZE,d); + c=((double)COUNT(cc)*BUFSIZE)/d; + + printf("RC5_32/12/16 set_key per sec = %12.2f (%9.3fuS)\n",a,1.0e6/a); + printf("RC5_32/12/16 raw ecb bytes per sec = %12.2f (%9.3fuS)\n",b,8.0e6/b); + printf("RC5_32/12/16 cbc bytes per sec = %12.2f (%9.3fuS)\n",c,8.0e6/c); + exit(0); +#if defined(LINT) || defined(OPENSSL_SYS_MSDOS) + return(0); +#endif + } diff --git a/pool/shard002/C/0063649_readline.c b/pool/shard002/C/0063649_readline.c new file mode 100644 index 0000000000000000000000000000000000000000..5bca55dadc7933b8dc804a5da71fa5fe5816a03e --- /dev/null +++ b/pool/shard002/C/0063649_readline.c @@ -0,0 +1,61 @@ +/* include readline */ +#include "unpipc.h" + +static ssize_t +my_read(int fd, char *ptr) +{ + static int read_cnt = 0; + static char *read_ptr; + static char read_buf[MAXLINE]; + + if (read_cnt <= 0) { +again: + if ( (read_cnt = read(fd, read_buf, sizeof(read_buf))) < 0) { + if (errno == EINTR) + goto again; + return(-1); + } else if (read_cnt == 0) + return(0); + read_ptr = read_buf; + } + + read_cnt--; + *ptr = *read_ptr++; + return(1); +} + +ssize_t +readline(int fd, void *vptr, size_t maxlen) +{ + int n, rc; + char c, *ptr; + + ptr = vptr; + for (n = 1; n < maxlen; n++) { + if ( (rc = my_read(fd, &c)) == 1) { + *ptr++ = c; + if (c == '\n') + break; /* newline is stored, like fgets() */ + } else if (rc == 0) { + if (n == 1) + return(0); /* EOF, no data read */ + else + break; /* EOF, some data was read */ + } else + return(-1); /* error, errno set by read() */ + } + + *ptr = 0; /* null terminate like fgets() */ + return(n); +} +/* end readline */ + +ssize_t +Readline(int fd, void *ptr, size_t maxlen) +{ + ssize_t n; + + if ( (n = readline(fd, ptr, maxlen)) < 0) + err_sys("readline error"); + return(n); +} diff --git a/pool/shard002/C/0063658_doc_string.c b/pool/shard002/C/0063658_doc_string.c new file mode 100644 index 0000000000000000000000000000000000000000..184bfcbb0aeecd0dd20c413e37daa4443157a017 --- /dev/null +++ b/pool/shard002/C/0063658_doc_string.c @@ -0,0 +1,37 @@ +#include "doc_string.h" +#include "string_utilities.h" +#include + +const DocString* DocString_new(Location location, const wchar_t* delimiter, const wchar_t* content_type, const wchar_t* content) { + DocString* doc_string = (DocString*)malloc(sizeof(DocString)); + doc_string->doc_string_delete = (item_delete_function)DocString_delete; + doc_string->type = Gherkin_DocString; + doc_string->location.line = location.line; + doc_string->location.column = location.column; + doc_string->delimiter = 0; + if (delimiter && wcslen(delimiter) > 0) { + doc_string->delimiter = StringUtilities_copy_string(delimiter); + } + doc_string->content_type = 0; + if (content_type && wcslen(content_type) > 0) { + doc_string->content_type = StringUtilities_copy_string(content_type); + } + doc_string->content = content; + return doc_string; +} + +void DocString_delete(const DocString* doc_string) { + if (!doc_string) { + return; + } + if (doc_string->delimiter) { + free((void*)doc_string->delimiter); + } + if (doc_string->content_type) { + free((void*)doc_string->content_type); + } + if (doc_string->content) { + free((void*)doc_string->content); + } + free((void*)doc_string); +} diff --git a/pool/shard002/C/0063659_nf_conntrack_timestamp.c b/pool/shard002/C/0063659_nf_conntrack_timestamp.c new file mode 100644 index 0000000000000000000000000000000000000000..705b912bd91f7a82cd4a42d1e81540228ff01ebd --- /dev/null +++ b/pool/shard002/C/0063659_nf_conntrack_timestamp.c @@ -0,0 +1,48 @@ +/* + * (C) 2010 Pablo Neira Ayuso + * + * 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 (or any later at your option). + */ + +#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt + +#include +#include +#include +#include + +#include +#include +#include + +static bool nf_ct_tstamp __read_mostly; + +module_param_named(tstamp, nf_ct_tstamp, bool, 0644); +MODULE_PARM_DESC(tstamp, "Enable connection tracking flow timestamping."); + +static const struct nf_ct_ext_type tstamp_extend = { + .len = sizeof(struct nf_conn_tstamp), + .align = __alignof__(struct nf_conn_tstamp), + .id = NF_CT_EXT_TSTAMP, +}; + +void nf_conntrack_tstamp_pernet_init(struct net *net) +{ + net->ct.sysctl_tstamp = nf_ct_tstamp; +} + +int nf_conntrack_tstamp_init(void) +{ + int ret; + ret = nf_ct_extend_register(&tstamp_extend); + if (ret < 0) + pr_err("Unable to register extension\n"); + return ret; +} + +void nf_conntrack_tstamp_fini(void) +{ + nf_ct_extend_unregister(&tstamp_extend); +} diff --git a/pool/shard002/C/0063665_stdvga.c b/pool/shard002/C/0063665_stdvga.c new file mode 100644 index 0000000000000000000000000000000000000000..3ca1070d0cba95ef9000ae8ec44a76c92ce35fb5 --- /dev/null +++ b/pool/shard002/C/0063665_stdvga.c @@ -0,0 +1,134 @@ +#include "pci.h" +#include "pci-vga.h" +#include +//#include +//#include + + +#define VGA_PALETTE_SIZE (256u * 3) + +typedef struct stdvga_device { + pci_device_t *pci_device; + resource_t *mem; + resource_t *io; + + unsigned int width; + unsigned int height; + + vga_device_t vga; +} stdvga_device_t; + +static stdvga_device_t stdvga[1]; + +/* Detailed information about VGA registers is available at + http://www.osdever.net/FreeVGA/vga/vga.htm */ + +#define VGA_PALETTE_ADDR 0x3C8 +#define VGA_PALETTE_DATA 0x3C9 +#define VGA_AR_ADDR 0x3C0 +#define VGA_AR_PAS 0x20 /* Palette Address Source bit */ + +/* Bochs VBE. Simplifies VGA graphics mode configuration a great deal. Some + documentation is available at http://wiki.osdev.org/Bochs_VBE_Extensions */ +#define VBE_DISPI_INDEX_XRES 0x01 +#define VBE_DISPI_INDEX_YRES 0x02 +#define VBE_DISPI_INDEX_BPP 0x03 +#define VBE_DISPI_INDEX_ENABLE 0x04 +#define VBE_DISPI_ENABLED 0x01 /* VBE Enabled bit */ + +/* Offsets for accessing ioports via PCI BAR1 (MMIO) */ +#define VGA_MMIO_OFFSET (0x400 - 0x3c0) +#define VBE_MMIO_OFFSET 0x500 + +/* The general overview of the QEMU std vga device is available at + https://github.com/qemu/qemu/blob/master/docs/specs/standard-vga.txt */ +#define VGA_QEMU_STDVGA_VENDOR_ID 0x1234 +#define VGA_QEMU_STDVGA_DEVICE_ID 0x1111 + +static void stdvga_io_write(stdvga_device_t *vga, uint16_t reg, uint8_t value) { + bus_space_write_1(vga->io, reg + VGA_MMIO_OFFSET, value); +} +static uint8_t __unused stdvga_io_read(stdvga_device_t *vga, uint16_t reg) { + return bus_space_read_1(vga->io, reg + VGA_MMIO_OFFSET); +} +static void stdvga_vbe_write(stdvga_device_t *vga, uint16_t reg, + uint16_t value) { + /* <<1 shift enables access to 16-bit registers. */ + bus_space_write_2(vga->io, (reg << 1) + VBE_MMIO_OFFSET, value); +} +static uint16_t stdvga_vbe_read(stdvga_device_t *vga, uint16_t reg) { + return bus_space_read_2(vga->io, (reg << 1) + VBE_MMIO_OFFSET); +} + +static void stdvga_palette_write_single(stdvga_device_t *stdvga, uint8_t offset, + uint8_t r, uint8_t g, uint8_t b) { + stdvga_io_write(stdvga, VGA_PALETTE_ADDR, offset); + stdvga_io_write(stdvga, VGA_PALETTE_DATA, r >> 2); + stdvga_io_write(stdvga, VGA_PALETTE_DATA, g >> 2); + stdvga_io_write(stdvga, VGA_PALETTE_DATA, b >> 2); +} + +static void stdvga_palette_write_buffer(stdvga_device_t *stdvga, + const uint8_t buf[VGA_PALETTE_SIZE]) { + for (unsigned i = 0; i < VGA_PALETTE_SIZE / 3; i++) + stdvga_palette_write_single(stdvga, i, buf[3 * i + 0], buf[3 * i + 1], + buf[3 * i + 2]); +} + +int stdvga_palette_write(uint8_t *buf) { + /* TODO: Only update the modified area. */ + stdvga_palette_write_buffer(stdvga, buf); + return 0; +} + +int stdvga_fb_write(uint8_t *buf) { + bus_space_write_region_1(stdvga->mem, 0, buf, + stdvga->width * stdvga->height); + return 0; +} + +int stdvga_pci_attach(pci_device_t *pci, unsigned width, unsigned height) { + if (pci->vendor_id != VGA_QEMU_STDVGA_VENDOR_ID || + pci->device_id != VGA_QEMU_STDVGA_DEVICE_ID) + return 0; + + /* TODO: Enabling PCI regions should probably be performed by PCI bus resource + * reservation code. */ + uint16_t command = pci_read_config(pci, PCIR_COMMAND, 2); + command |= PCIM_CMD_PORTEN | PCIM_CMD_MEMEN; + pci_write_config(pci, PCIR_COMMAND, 2, command); + + assert(pci->bar[0].r_flags | RF_PREFETCHABLE); + /* TODO: This will get replaced by bus_alloc_resource* function */ + stdvga->mem = &pci->bar[0]; + stdvga->io = &pci->bar[1]; + + /* Switching output resolution is straightforward - but not implemented since + we don't need it ATM. */ + stdvga->width = width; + stdvga->height = height; + + stdvga->vga = (vga_device_t){ + .palette_write = stdvga_palette_write, .fb_write = stdvga_fb_write, + }; + + /* Apply resolution */ + stdvga_vbe_write(stdvga, VBE_DISPI_INDEX_XRES, stdvga->width); + stdvga_vbe_write(stdvga, VBE_DISPI_INDEX_YRES, stdvga->height); + + /* Enable palette access */ + stdvga_io_write(stdvga, VGA_AR_ADDR, VGA_AR_PAS); + + /* Set 8 BPP */ + stdvga_vbe_write(stdvga, VBE_DISPI_INDEX_BPP, 8); + + /* Enable VBE. */ + stdvga_vbe_write(stdvga, VBE_DISPI_INDEX_ENABLE, + stdvga_vbe_read(stdvga, VBE_DISPI_INDEX_ENABLE) | + VBE_DISPI_ENABLED); + + /* Install /dev/vga interace. */ + //dev_vga_install(&stdvga->vga); + + return 1; +} diff --git a/pool/shard002/C/0063666_1116.c b/pool/shard002/C/0063666_1116.c new file mode 100644 index 0000000000000000000000000000000000000000..46408e57ef354777633473d2bdab95e5a8783d52 --- /dev/null +++ b/pool/shard002/C/0063666_1116.c @@ -0,0 +1,21 @@ +#include +#include + +void str_reverse(char *str) { + int i, n = strlen(str); + char tmp; + for (i = 0; i < n/2; i++) { + tmp = str[i]; + str[i] = str[n-1-i]; + str[n-1-i] = tmp; + } +} + +int main(int argc, const char *argv[]) +{ + char buf[1000]; + scanf("%s", buf); + str_reverse(buf); + printf("%s", buf); + return 0; +} diff --git a/pool/shard002/C/0063667_pci.c b/pool/shard002/C/0063667_pci.c new file mode 100644 index 0000000000000000000000000000000000000000..203b2923fe7f8339da337a8de9573b732f096302 --- /dev/null +++ b/pool/shard002/C/0063667_pci.c @@ -0,0 +1,147 @@ +/* + * linux/arch/sh/boards/se/7751/pci.c + * + * Author: Ian DaSilva (idasilva@mvista.com) + * + * Highly leveraged from pci-bigsur.c, written by Dustin McIntire. + * + * May be copied or modified under the terms of the GNU General Public + * License. See linux/COPYING for more information. + * + * PCI initialization for the Hitachi SH7751 Solution Engine board (MS7751SE01) + */ + +#include +#include +#include +#include +#include + +#include +#include "../../../drivers/pci/pci-sh7751.h" + +#define PCIMCR_MRSET_OFF 0xBFFFFFFF +#define PCIMCR_RFSH_OFF 0xFFFFFFFB + +/* + * Only long word accesses of the PCIC's internal local registers and the + * configuration registers from the CPU is supported. + */ +#define PCIC_WRITE(x,v) writel((v), PCI_REG(x)) +#define PCIC_READ(x) readl(PCI_REG(x)) + +/* + * Description: This function sets up and initializes the pcic, sets + * up the BARS, maps the DRAM into the address space etc, etc. + */ +int __init pcibios_init_platform(void) +{ + unsigned long bcr1, wcr1, wcr2, wcr3, mcr; + unsigned short bcr2; + + /* + * Initialize the slave bus controller on the pcic. The values used + * here should not be hardcoded, but they should be taken from the bsc + * on the processor, to make this function as generic as possible. + * (i.e. Another sbc may usr different SDRAM timing settings -- in order + * for the pcic to work, its settings need to be exactly the same.) + */ + bcr1 = (*(volatile unsigned long*)(SH7751_BCR1)); + bcr2 = (*(volatile unsigned short*)(SH7751_BCR2)); + wcr1 = (*(volatile unsigned long*)(SH7751_WCR1)); + wcr2 = (*(volatile unsigned long*)(SH7751_WCR2)); + wcr3 = (*(volatile unsigned long*)(SH7751_WCR3)); + mcr = (*(volatile unsigned long*)(SH7751_MCR)); + + bcr1 = bcr1 | 0x00080000; /* Enable Bit 19, BREQEN */ + (*(volatile unsigned long*)(SH7751_BCR1)) = bcr1; + + bcr1 = bcr1 | 0x40080000; /* Enable Bit 19 BREQEN, set PCIC to slave */ + PCIC_WRITE(SH7751_PCIBCR1, bcr1); /* PCIC BCR1 */ + PCIC_WRITE(SH7751_PCIBCR2, bcr2); /* PCIC BCR2 */ + PCIC_WRITE(SH7751_PCIWCR1, wcr1); /* PCIC WCR1 */ + PCIC_WRITE(SH7751_PCIWCR2, wcr2); /* PCIC WCR2 */ + PCIC_WRITE(SH7751_PCIWCR3, wcr3); /* PCIC WCR3 */ + mcr = (mcr & PCIMCR_MRSET_OFF) & PCIMCR_RFSH_OFF; + PCIC_WRITE(SH7751_PCIMCR, mcr); /* PCIC MCR */ + + + /* Enable all interrupts, so we know what to fix */ + PCIC_WRITE(SH7751_PCIINTM, 0x0000c3ff); + PCIC_WRITE(SH7751_PCIAINTM, 0x0000380f); + + /* Set up standard PCI config registers */ + PCIC_WRITE(SH7751_PCICONF1, 0xF39000C7); /* Bus Master, Mem & I/O access */ + PCIC_WRITE(SH7751_PCICONF2, 0x00000000); /* PCI Class code & Revision ID */ + PCIC_WRITE(SH7751_PCICONF4, 0xab000001); /* PCI I/O address (local regs) */ + PCIC_WRITE(SH7751_PCICONF5, 0x0c000000); /* PCI MEM address (local RAM) */ + PCIC_WRITE(SH7751_PCICONF6, 0xd0000000); /* PCI MEM address (unused) */ + PCIC_WRITE(SH7751_PCICONF11, 0x35051054); /* PCI Subsystem ID & Vendor ID */ + PCIC_WRITE(SH7751_PCILSR0, 0x03f00000); /* MEM (full 64M exposed) */ + PCIC_WRITE(SH7751_PCILSR1, 0x00000000); /* MEM (unused) */ + PCIC_WRITE(SH7751_PCILAR0, 0x0c000000); /* MEM (direct map from PCI) */ + PCIC_WRITE(SH7751_PCILAR1, 0x00000000); /* MEM (unused) */ + + /* Now turn it on... */ + PCIC_WRITE(SH7751_PCICR, 0xa5000001); + + /* + * Set PCIMBR and PCIIOBR here, assuming a single window + * (16M MEM, 256K IO) is enough. If a larger space is + * needed, the readx/writex and inx/outx functions will + * have to do more (e.g. setting registers for each call). + */ + + /* + * Set the MBR so PCI address is one-to-one with window, + * meaning all calls go straight through... use BUG_ON to + * catch erroneous assumption. + */ + BUG_ON(PCIBIOS_MIN_MEM != SH7751_PCI_MEMORY_BASE); + + PCIC_WRITE(SH7751_PCIMBR, PCIBIOS_MIN_MEM); + + /* Set IOBR for window containing area specified in pci.h */ + PCIC_WRITE(SH7751_PCIIOBR, (PCIBIOS_MIN_IO & SH7751_PCIIOBR_MASK)); + + /* All done, may as well say so... */ + printk("SH7751 PCI: Finished initialization of the PCI controller\n"); + + return 1; +} + +int __init pcibios_map_platform_irq(u8 slot, u8 pin) +{ + switch (slot) { + case 0: return 13; + case 1: return 13; /* AMD Ethernet controller */ + case 2: return -1; + case 3: return -1; + case 4: return -1; + default: + printk("PCI: Bad IRQ mapping request for slot %d\n", slot); + return -1; + } +} + +static struct resource sh7751_io_resource = { + .name = "SH7751 IO", + .start = SH7751_PCI_IO_BASE, + .end = SH7751_PCI_IO_BASE + SH7751_PCI_IO_SIZE - 1, + .flags = IORESOURCE_IO +}; + +static struct resource sh7751_mem_resource = { + .name = "SH7751 mem", + .start = SH7751_PCI_MEMORY_BASE, + .end = SH7751_PCI_MEMORY_BASE + SH7751_PCI_MEM_SIZE - 1, + .flags = IORESOURCE_MEM +}; + +extern struct pci_ops sh7751_pci_ops; + +struct pci_channel board_pci_channels[] = { + { &sh7751_pci_ops, &sh7751_io_resource, &sh7751_mem_resource, 0, 0xff }, + { NULL, NULL, NULL, 0, 0 }, +}; + diff --git a/pool/shard002/C/0063681_checks_db.c b/pool/shard002/C/0063681_checks_db.c new file mode 100644 index 0000000000000000000000000000000000000000..d56e1eab0b5266953211e68710ffbb4aec80c73b --- /dev/null +++ b/pool/shard002/C/0063681_checks_db.c @@ -0,0 +1,191 @@ +/* +** Zabbix +** Copyright (C) 2000-2011 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" + +#ifdef HAVE_ODBC +# include "zbxodbc.h" +#endif /* HAVE_ODBC */ + +#include "checks_db.h" +#include "log.h" + +#ifdef HAVE_ODBC +/****************************************************************************** + * * + * Function: get_param_value * + * * + * Purpose: retrieve parameter value by name * + * * + * Parameters: params - list of params * + * param_name - name of requested parameter * + * * + * Return value: NULL - if parameter missing param_name, * + * else return value in new allocated memory * + * * + * Author: Eugene Grigorjev * + * * + * Comments: this function allocates memory, required zbx_free for result!!! * + * one parameter format: param1_name=param1_value * + * parameters separated by '\n' * + * * + ******************************************************************************/ +static char* get_param_value(char* params, const char* param_name) +{ + char + *p = NULL, + *l = NULL, + *n = NULL, + *r = NULL, + *buf = NULL; + + for(p = params; p && *p; p++) + { + r = NULL; + + /* trim left spaces */ + for(; *p == ' '; p++); + + /* find '=' */ + for(n = p; *n && *n != '\n'; n++) + { + if(*n == '=') + { + /* trim right spaces */ + for(l = n - 1; *l == ' '; l--); + l++; + + /* compare parameter name */ + if(l - p != strlen(param_name)) break; + if(strncmp(p, param_name, l - p)) break; + + r = n+1; + break; + } + } + + /* find EOL */ + for(p = n; *p && *p != '\n'; p++); + + /* allocate result */ + if(r) + { + /* trim right EOL characters */ + while(*p == '\r' || *p == '\n' || *p == '\0') p--; + p++; + + /* allocate result */ + buf = zbx_malloc(buf, p - r + 1); + memmove(buf, r, p - r); + buf[p - r] = '\0'; + + break; + } + } + + if(buf == NULL) + { + /* allocate result */ + buf = zbx_malloc(buf, 1); + *buf = '\0'; + } + return buf; +} +#endif /* HAVE_ODBC */ + +/****************************************************************************** + * * + * Function: get_value_db * + * * + * Purpose: retrieve data from database * + * * + * Parameters: item - item we are interested in * + * * + * Return value: SUCCEED - data successfully retrieved and stored in result * + * NOTSUPPORTED - requested item is not supported * + * * + * Author: Eugene Grigorjev * + * * + * Comments: * + * * + ******************************************************************************/ +int get_value_db(DC_ITEM *item, AGENT_RESULT *result) +{ +#ifdef HAVE_ODBC + ZBX_ODBC_DBH dbh; + ZBX_ODBC_ROW row; + + char + *db_dsn = NULL, + *db_user = NULL, + *db_pass = NULL, + *db_sql = NULL; +#endif /* HAVE_ODBC */ + + int ret = NOTSUPPORTED; + + init_result(result); + + zabbix_log(LOG_LEVEL_DEBUG, "In database monitor: %s", item->key_orig); + +#ifdef HAVE_ODBC + + #define DB_ODBC_SELECT_KEY "db.odbc.select[" + + if (0 == strncmp(item->key, DB_ODBC_SELECT_KEY, strlen(DB_ODBC_SELECT_KEY))) + { + db_dsn = get_param_value(item->params, "DSN"); + db_user = get_param_value(item->params, "user"); + db_pass = get_param_value(item->params, "password"); + db_sql = get_param_value(item->params, "sql"); + + if (SUCCEED == odbc_DBconnect(&dbh, db_dsn, db_user, db_pass)) + { + if (NULL != (row = odbc_DBfetch(odbc_DBselect(&dbh, db_sql)))) + { + if (SUCCEED == set_result_type(result, item->value_type, item->data_type, row[0])) + ret = SUCCEED; + } + else + SET_MSG_RESULT(result, strdup(get_last_odbc_strerror())); + + odbc_DBclose(&dbh); + } + else + SET_MSG_RESULT(result, strdup(get_last_odbc_strerror())); + + zbx_free(db_dsn); + zbx_free(db_user); + zbx_free(db_pass); + zbx_free(db_sql); + } + +#endif /* HAVE_ODBC */ + + /* + * TODO: + * + * db.*.select[] + * db.*.ping + * ... + * + */ + + return ret; +} diff --git a/pool/shard002/C/0063684_iref.c b/pool/shard002/C/0063684_iref.c new file mode 100644 index 0000000000000000000000000000000000000000..74efb9b0e355f8dc63df2d947271fcfac43e14a8 --- /dev/null +++ b/pool/shard002/C/0063684_iref.c @@ -0,0 +1,88 @@ +/** + * \file + * \brief IREF allocation/management + */ + +/* + * Copyright (c) 2007, 2008, 2010, ETH Zurich. + * All rights reserved. + * + * This file is distributed under the terms in the attached LICENSE file. + * If you do not find this file, copies can be found by writing to: + * ETH Zurich D-INFK, Universitaetstrasse 6, CH-8092 Zurich. Attn: Systems Group. + */ + +#include "monitor.h" + +struct iref_service { + struct monitor_binding *binding; + uintptr_t service_id; +}; + +#define MAX_IREF_PERCORE 256 +static struct iref_service iref_table[MAX_IREF_PERCORE]; + +/** + * \brief Allocate a new iref + * + * Associate it with the server's connection and service id. + */ +errval_t iref_alloc(struct monitor_binding *binding, uintptr_t service_id, + iref_t *iref) +{ + assert(binding != NULL); + + // find a free slot in the local table + for (iref_t i = 0; i < MAX_IREF_PERCORE; i++) { + if (iref_table[i].binding == NULL) { + iref_table[i].binding = binding; + iref_table[i].service_id = service_id; + // XXX: avoid zero being a valid iref + *iref = MAX_IREF_PERCORE * my_core_id + i + 1; + return SYS_ERR_OK; + } + } + + return MON_ERR_IREF_ALLOC; +} + +/** + * \brief Return core_id + * + * The core_id is stored in the iref itself. + */ +errval_t iref_get_core_id(iref_t iref, coreid_t *core_id) +{ + *core_id = (iref - 1) / MAX_IREF_PERCORE; + return SYS_ERR_OK; +} + +/** + * \brief Return conn + */ +errval_t iref_get_binding(iref_t iref, struct monitor_binding **binding) +{ + if ((iref - 1) / MAX_IREF_PERCORE != my_core_id) { + return MON_ERR_INVALID_CORE_ID; + } + + *binding = iref_table[(iref - 1) % MAX_IREF_PERCORE].binding; + if (*binding == NULL) { + return MON_ERR_INVALID_IREF; + } else { + return SYS_ERR_OK; + } +} + +/** + * \brief Return service_id + */ +errval_t iref_get_service_id(iref_t iref, uintptr_t *service_id) +{ + if ((iref - 1) / MAX_IREF_PERCORE != my_core_id) { + return MON_ERR_INVALID_CORE_ID; + } + + *service_id = iref_table[(iref - 1) % MAX_IREF_PERCORE].service_id; + return SYS_ERR_OK; +} diff --git a/pool/shard002/C/0063691_memindex.c b/pool/shard002/C/0063691_memindex.c new file mode 100644 index 0000000000000000000000000000000000000000..5818ac5993ecf0f45d18a65ca5e3a485c1f29178 --- /dev/null +++ b/pool/shard002/C/0063691_memindex.c @@ -0,0 +1,256 @@ +/* + * Copyright 2012 Steven Gribble + * + * This file is part of the UW CSE 333 course project sequence + * (333proj). + * + * 333proj 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. + * + * 333proj 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 333proj. If not, see . + */ + +#include +#include +#include +#include + +#include "memindex.h" +#include "libhw1/CSE333.h" +#include "libhw1/HashTable.h" + +// This helper function is passed to SortLinkedList(); +// it is the comparator that compares the rank of two +// search results while sorting the result list. +static int MISearchListComparator(LLPayload_t e1, LLPayload_t e2) { + SearchResult *sr1 = (SearchResult *) e1; + SearchResult *sr2 = (SearchResult *) e2; + + if (sr1->rank > sr2->rank) + return 1; + if (sr1->rank < sr2->rank) + return -1; + return 0; +} + +// Used by MIListFree() to free a linked list of positions. +static void MINullFree(LLPayload_t ptr) { } + +// Frees a linked list of positions. +static void MIListFree(HTValue_t ptr) { + LinkedList list = (LinkedList) ptr; + FreeLinkedList(list, &MINullFree); +} + +// Frees a WordDocSet structure. +static void MIFree(HTValue_t ptr) { + WordDocSetPtr wd = (WordDocSetPtr)ptr; + free(wd->word); + FreeHashTable(wd->docIDs, &MIListFree); + free(wd); +} + +MemIndex AllocateMemIndex(void) { + // Happily, HashTables dynamically resize themselves + // now, so we can start by allocating a small hashtable. + HashTable mi = AllocateHashTable(128); + return mi; +} + +void FreeMemIndex(MemIndex index) { + FreeHashTable(index, &MIFree); +} + +HWSize_t MINumWordsInMemIndex(MemIndex index) { + return NumElementsInHashTable(index); +} + +int MIAddPostingList(MemIndex index, char *word, DocID_t docid, + LinkedList positions) { + HTKey_t wordkey = FNVHash64((unsigned char *) word, strlen(word)); + HTKeyValue kv, hitkv; + WordDocSet *wds; + int res; + + // STEP 1. + // Remove this "return 1;". We added this in here + // so that your filecrawler unit tests would pass + // even though you hadn't yet finished the + // memindex.c implementation. + + + // First, we have to see if the word we're being handed + // already exists in the inverted index. + res = LookupHashTable(index, wordkey, &kv); + if (res == 0) { + // STEP 2. + // No, this is the first time the inverted index has + // seen this word. We need to malloc and prepare a + // new WordDocSet structure. After malloc'ing it, + // we need to: + // (1) insert the word into the WordDocSet, + // (2) allocate a new hashtable for the docID->positions mapping, + // (3) insert that hashtable into the WordDocSet, and + // (4) insert the the new WordDocSet into the inverted + // index (i.e., into the "index" table). + wds = (WordDocSet *) malloc(sizeof(WordDocSet)); + if (wds == NULL) return 0; + wds->word = word; + wds->docIDs = AllocateHashTable(32); + Verify333(wds->docIDs != NULL); + kv.key = wordkey; + kv.value = (void *) wds; + res = InsertHashTable(index, kv, &hitkv); + Verify333(res == 1); + } else { + // Yes, this word already exists in the inverted index. + // So, there's no need to insert it again; we can go + // ahead and free the word. + free(word); + + // Instead of allocating a new WordDocSet, we'll + // use the one that's already in the inverted index. + wds = (WordDocSet *) kv.value; + } + + // Verify that the docID doesn't exist in the WordDocSet. + res = LookupHashTable(wds->docIDs, docid, &hitkv); + Verify333(res == 0); + + // STEP 3. + // Insert a new entry into the wds->docIDs hash table. + // The entry's key is this docID and the entry's value + // is the "positions" word positions list we were passed + // as an argument. + kv.key = docid; + kv.value = positions; + res = InsertHashTable(wds->docIDs, kv, &hitkv); + Verify333(res == 1); + + return 1; +} + +LinkedList MIProcessQuery(MemIndex index, char *query[], uint8_t qlen) { + LinkedList retlist; + HTKeyValue kv; + WordDocSet *wds; + int res; + HTKey_t wordkey; + + // If the user provided us with an empty search query, return NULL + // to indicate failure. + if (qlen == 0) + return NULL; + + // Allocate a linked list to store our search results. A search + // result is just a list of SearchResult structures. + retlist = AllocateLinkedList(); + + // STEP 4. + // The most interesting part of Part C starts here...! + // + // Look up the first query word (query[0]) in the inverted + // index. For each document that matches, allocate a SearchResult + // structure. Initialize that SearchResult structure with the + // docID, and the initial computed rank for the document. (The + // initial computed rank is the number of times the word appears + // in that document.) + // + // Then, append the SearchResult structure onto retlist. + // + // If there are no matching documents, free retlist and return NULL. + wordkey = FNVHash64((unsigned char*) query[0], strlen(query[0])); + res = LookupHashTable(index, wordkey, &kv); + if (res == 0) { + FreeLinkedList(retlist, (LLPayloadFreeFnPtr) free); + return NULL; + } else { + wds = (WordDocSet *) kv.value; + HTIter iter = HashTableMakeIterator(wds->docIDs); + do { + res = HTIteratorGet(iter, &kv); + SearchResult *sr = (SearchResult *) malloc(sizeof(SearchResult)); + LinkedList positions = (LinkedList) kv.value; + sr->docid = kv.key; + sr->rank = NumElementsInLinkedList(positions); + + PushLinkedList(retlist, (LLPayload_t) sr); + } while (HTIteratorNext(iter)); + HTIteratorFree(iter); + } + + // Great; we have our search results for the first query + // word. If there is only one query word, we're done! + // Sort the result list and return it to the caller. + if (qlen == 1) { + SortLinkedList(retlist, 0, &MISearchListComparator); + return retlist; + } + + // OK, there are additional query words. Handle them one + // at a time. + int i; + for (i = 1; i < qlen; i++) { + LLIter llit; + int j, ne; + + // STEP 5. + // Look up the next query word (query[i]) in the inverted index. + // If there are no matches, it means the overall query + // should return no documents, so free retlist and return NULL. + wordkey = FNVHash64((unsigned char*) query[i], strlen(query[i])); + res = LookupHashTable(index, wordkey, &kv); + if (res == 0) { + FreeLinkedList(retlist, (LLPayloadFreeFnPtr) free); + return NULL; + } + + // STEP 6. + // There are matches. We're going to iterate through + // the docIDs in our current search result list, testing each + // to see whether it is also in the set of matches for + // the query[i]. + // + // If it is, we leave it in the search + // result list and we update its rank by adding in the + // number of matches for the current word. + // + // If it isn't, we delete that docID from the search result list. + wds = (WordDocSet *) kv.value; + llit = LLMakeIterator(retlist, 0); + ne = NumElementsInLinkedList(retlist); + SearchResult *rs = NULL; + for (j = 0; j < ne; j++) { + LLIteratorGetPayload(llit, (LLPayload_t *) &rs); + Verify333(rs != NULL); + res = LookupHashTable(wds->docIDs, rs->docid, &kv); + if (res == 0) { + LLIteratorDelete(llit, (LLPayloadFreeFnPtr) free); + } else { + rs->rank += NumElementsInLinkedList((LinkedList) kv.value); + LLIteratorNext(llit); + } + } + LLIteratorFree(llit); + } + + // We've finished processing all of the query words. + // If there are no documents left in our query result list, + // free retlist and return NULL. + if (NumElementsInLinkedList(retlist) == 0) { + FreeLinkedList(retlist, (LLPayloadFreeFnPtr)free); + return NULL; + } + + // Sort the result list by rank and return it to the caller. + SortLinkedList(retlist, 0, &MISearchListComparator); + return retlist; +} diff --git a/pool/shard002/C/0063701_ecc_ansi_x963_export.c b/pool/shard002/C/0063701_ecc_ansi_x963_export.c new file mode 100644 index 0000000000000000000000000000000000000000..28c83f2b738a8e41b2ccda000fec6cb8ca07645c --- /dev/null +++ b/pool/shard002/C/0063701_ecc_ansi_x963_export.c @@ -0,0 +1,107 @@ +// SPDX-License-Identifier: BSD-2-Clause +/* + * Copyright (c) 2001-2007, Tom St Denis + * 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 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. + */ + +/* 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://libtom.org + */ + +/* Implements ECC over Z/pZ for curve y^2 = x^3 - 3x + b + * + * All curves taken from NIST recommendation paper of July 1999 + * Available at http://csrc.nist.gov/cryptval/dss.htm + */ +#include "tomcrypt.h" + +/** + @file ecc_ansi_x963_export.c + ECC Crypto, Tom St Denis +*/ + +#ifdef LTC_MECC + +/** ECC X9.63 (Sec. 4.3.6) uncompressed export + @param key Key to export + @param out [out] destination of export + @param outlen [in/out] Length of destination and final output size + Return CRYPT_OK on success +*/ +int ecc_ansi_x963_export(ecc_key *key, unsigned char *out, unsigned long *outlen) +{ + unsigned char buf[ECC_BUF_SIZE]; + unsigned long numlen, xlen, ylen; + + LTC_ARGCHK(key != NULL); + LTC_ARGCHK(outlen != NULL); + + if (ltc_ecc_is_valid_idx(key->idx) == 0) { + return CRYPT_INVALID_ARG; + } + numlen = key->dp->size; + xlen = mp_unsigned_bin_size(key->pubkey.x); + ylen = mp_unsigned_bin_size(key->pubkey.y); + + if (xlen > numlen || ylen > numlen || sizeof(buf) < numlen) { + return CRYPT_BUFFER_OVERFLOW; + } + + if (*outlen < (1 + 2*numlen)) { + *outlen = 1 + 2*numlen; + return CRYPT_BUFFER_OVERFLOW; + } + + LTC_ARGCHK(out != NULL); + + /* store byte 0x04 */ + out[0] = 0x04; + + /* pad and store x */ + zeromem(buf, sizeof(buf)); + mp_to_unsigned_bin(key->pubkey.x, buf + (numlen - xlen)); + XMEMCPY(out+1, buf, numlen); + + /* pad and store y */ + zeromem(buf, sizeof(buf)); + mp_to_unsigned_bin(key->pubkey.y, buf + (numlen - ylen)); + XMEMCPY(out+1+numlen, buf, numlen); + + *outlen = 1 + 2*numlen; + return CRYPT_OK; +} + +#endif + +/* $Source: /cvs/libtom/libtomcrypt/src/pk/ecc/ecc_ansi_x963_export.c,v $ */ +/* $Revision: 1.6 $ */ +/* $Date: 2007/05/12 14:32:35 $ */ diff --git a/pool/shard002/C/0063706_oscillator.c b/pool/shard002/C/0063706_oscillator.c new file mode 100644 index 0000000000000000000000000000000000000000..760de31aaa3b9598023acf1e0657a3408d3279e0 --- /dev/null +++ b/pool/shard002/C/0063706_oscillator.c @@ -0,0 +1,127 @@ +/* oscillator.c + +This routine implements a common fixed-frequency oscillator + +This file is part of a program that implements a Software-Defined Radio. + +Copyright (C) 2004, 2005, 2006 by Frank Brickle, AB2KT and Bob McGwier, N4HY + +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 + +The authors can be reached by email at + +ab2kt@arrl.net +or +rwmcgwier@comcast.net + +or by paper mail at + +The DTTS Microwave Society +6 Kathleen Place +Bridgewater, NJ 08807 +*/ + +#include + +#define HUGE_PHASE 1256637061.43593 + +void +ComplexOSC (OSC p) +{ + int i; + COMPLEX z, delta_z; + + if (OSCphase (p) > TWOPI) + OSCphase (p) -= TWOPI; + else if (OSCphase (p) < -TWOPI) + OSCphase (p) += TWOPI; + + z = Cmplx ((REAL) cos (OSCphase (p)), (IMAG) sin (OSCphase (p))), + delta_z = Cmplx ((REAL) cos (OSCfreq (p)), (IMAG) sin (OSCfreq (p))); + + for (i = 0; i < OSCsize (p); i++) + /*z = CXBdata ((CXB) OSCbase (p), i) + = Cmul (z, delta_z), OSCphase (p) += OSCfreq (p);*/ + CXBdata((CXB)OSCbase(p), i) = Cmplx ((REAL) cos (OSCphase (p)), (IMAG) sin (OSCphase (p))), + OSCphase (p) += OSCfreq (p); + +} + +#ifdef notdef +void +ComplexOSC (OSC p) +{ + int i; +/* if (OSCphase (p) > 1256637061.43593) + OSCphase (p) -= 1256637061.43593; */ + for (i = 0; i < OSCsize (p); i++) + { + OSCreal (p, i) = cos (OSCphase (p)); + OSCimag (p, i) = sin (OSCphase (p)); + OSCphase (p) += OSCfreq (p); + } +} +#endif + +PRIVATE double +_phasemod (double angle) +{ + while (angle >= TWOPI) + angle -= TWOPI; + while (angle < 0.0) + angle += TWOPI; + return angle; +} + +void +RealOSC (OSC p) +{ + int i; + for (i = 0; i < OSCsize (p); i++) + { + OSCRdata (p, i) = (REAL) sin (OSCphase (p)); + OSCphase (p) = _phasemod (OSCfreq (p) + OSCphase (p)); + } +} + +OSC +newOSC (int size, + OscType TypeOsc, + double Frequency, double Phase, REAL SampleRate, char *tag) +{ + OSC p = (OSC) safealloc (1, sizeof (oscillator), tag); + if ((OSCtype (p) = TypeOsc) == ComplexTone) + OSCbase (p) = (void *) newCXB (size, + NULL, + "complex buffer for oscillator output"); + else + OSCbase (p) = (void *) newRLB (size, + NULL, "real buffer for oscillator output"); + OSCsize (p) = size; + OSCfreq (p) = 2.0 * M_PI * Frequency / SampleRate; + OSCphase (p) = Phase; + return p; +} + +void +delOSC (OSC p) +{ + if (p->OscillatorType == ComplexTone) + delCXB ((CXB) p->signalpoints); + else + delRLB ((RLB) p->signalpoints); + if (p) + safefree ((char *) p); +} diff --git a/pool/shard002/C/0063707_asin_series.c b/pool/shard002/C/0063707_asin_series.c new file mode 100644 index 0000000000000000000000000000000000000000..9c9c73de05756463b7c64c49e820af6183c93ce3 --- /dev/null +++ b/pool/shard002/C/0063707_asin_series.c @@ -0,0 +1,70 @@ +/* + Copyright (C) 2013 Fredrik Johansson + + This file is part of Arb. + + Arb 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. See . +*/ + +#include "arb_poly.h" + +void +_arb_poly_asin_series(arb_ptr g, arb_srcptr h, slong hlen, slong n, slong prec) +{ + arb_t c; + arb_init(c); + + arb_asin(c, h, prec); + + hlen = FLINT_MIN(hlen, n); + + if (hlen == 1) + { + _arb_vec_zero(g + 1, n - 1); + } + else + { + arb_ptr t, u; + slong ulen; + + t = _arb_vec_init(n); + u = _arb_vec_init(n); + + /* asin(h(x)) = integral(h'(x)/sqrt(1-h(x)^2)) */ + ulen = FLINT_MIN(n, 2 * hlen - 1); + _arb_poly_mullow(u, h, hlen, h, hlen, ulen, prec); + arb_sub_ui(u, u, 1, prec); + _arb_vec_neg(u, u, ulen); + _arb_poly_rsqrt_series(t, u, ulen, n, prec); + _arb_poly_derivative(u, h, hlen, prec); + _arb_poly_mullow(g, t, n, u, hlen - 1, n, prec); + _arb_poly_integral(g, g, n, prec); + + _arb_vec_clear(t, n); + _arb_vec_clear(u, n); + } + + arb_swap(g, c); + arb_clear(c); +} + +void +arb_poly_asin_series(arb_poly_t g, const arb_poly_t h, slong n, slong prec) +{ + slong hlen = h->length; + + if (hlen == 0 || n == 0) + { + arb_poly_zero(g); + return; + } + + arb_poly_fit_length(g, n); + _arb_poly_asin_series(g->coeffs, h->coeffs, hlen, n, prec); + _arb_poly_set_length(g, n); + _arb_poly_normalise(g); +} + diff --git a/pool/shard002/C/0063711_AbsolutePermutation.c b/pool/shard002/C/0063711_AbsolutePermutation.c new file mode 100644 index 0000000000000000000000000000000000000000..de2524dd61a58aca1cbd791022062ca01ad5aad2 --- /dev/null +++ b/pool/shard002/C/0063711_AbsolutePermutation.c @@ -0,0 +1,40 @@ +#include +#include +#include +#include +#include +#include +#include + +int main(){ + + int t; + scanf("%d", &t); + + while(t--){ + int n, k; + scanf("%d %d", &n, &k); + + if(k == 0){ + for(int i=1; i<=n; i++) + printf("%d ",i); + printf("\n"); + } + + else if(n % (2*k)) + printf("-1\n"); + + else{ + int sign = 0; + for(int i=1; i<=n; i++){ + sign ? printf("%d ",i-k) : printf("%d ",i+k); + if(i % k == 0) sign = !sign; + } + + printf("\n"); + } + + } + + return 0; +} diff --git a/pool/shard002/C/0063713_util-lua-ssh.c b/pool/shard002/C/0063713_util-lua-ssh.c new file mode 100644 index 0000000000000000000000000000000000000000..4b52ece34c1889fa1977728eb22e9a3a7640f213 --- /dev/null +++ b/pool/shard002/C/0063713_util-lua-ssh.c @@ -0,0 +1,220 @@ +/* Copyright (C) 2014 Open Information Security Foundation + * + * You can copy, redistribute or modify this Program under the terms of + * the GNU General Public License version 2 as published by the Free + * Software Foundation. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * version 2 along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA + * 02110-1301, USA. + */ + + +/** + * \file + * + * \author Mats Klepsland + * + */ + +#include "suricata-common.h" +#include "debug.h" +#include "detect.h" +#include "pkt-var.h" +#include "conf.h" + +#include "threads.h" +#include "threadvars.h" +#include "tm-threads.h" + +#include "util-print.h" +#include "util-unittest.h" + +#include "util-debug.h" + +#include "output.h" +#include "app-layer.h" +#include "app-layer-parser.h" +#include "app-layer-ssh.h" +#include "util-privs.h" +#include "util-buffer.h" +#include "util-proto-name.h" +#include "util-logopenfile.h" +#include "util-time.h" +#include "rust.h" + +#ifdef HAVE_LUA + +#include +#include +#include + +#include "util-lua.h" +#include "util-lua-common.h" +#include "util-lua-ssh.h" + +static int GetServerProtoVersion(lua_State *luastate, const Flow *f) +{ + void *state = FlowGetAppState(f); + if (state == NULL) + return LuaCallbackError(luastate, "error: no app layer state"); + const uint8_t *protocol = NULL; + uint32_t b_len = 0; + + void *tx = rs_ssh_state_get_tx(state, 0); + if (rs_ssh_tx_get_protocol(tx, &protocol, &b_len, STREAM_TOCLIENT) != 1) + return LuaCallbackError(luastate, "error: no server proto version"); + if (protocol == NULL || b_len == 0) { + return LuaCallbackError(luastate, "error: no server proto version"); + } + + return LuaPushStringBuffer(luastate, protocol, b_len); +} + +static int SshGetServerProtoVersion(lua_State *luastate) +{ + int r; + + if (!(LuaStateNeedProto(luastate, ALPROTO_SSH))) + return LuaCallbackError(luastate, "error: protocol not ssh"); + + Flow *f = LuaStateGetFlow(luastate); + if (f == NULL) + return LuaCallbackError(luastate, "internal error: no flow"); + + r = GetServerProtoVersion(luastate, f); + + return r; +} + +static int GetServerSoftwareVersion(lua_State *luastate, const Flow *f) +{ + void *state = FlowGetAppState(f); + if (state == NULL) + return LuaCallbackError(luastate, "error: no app layer state"); + + const uint8_t *software = NULL; + uint32_t b_len = 0; + + void *tx = rs_ssh_state_get_tx(state, 0); + if (rs_ssh_tx_get_software(tx, &software, &b_len, STREAM_TOCLIENT) != 1) + return LuaCallbackError(luastate, "error: no server software version"); + if (software == NULL || b_len == 0) { + return LuaCallbackError(luastate, "error: no server software version"); + } + + return LuaPushStringBuffer(luastate, software, b_len); +} + +static int SshGetServerSoftwareVersion(lua_State *luastate) +{ + int r; + + if (!(LuaStateNeedProto(luastate, ALPROTO_SSH))) + return LuaCallbackError(luastate, "error: protocol not ssh"); + + Flow *f = LuaStateGetFlow(luastate); + if (f == NULL) + return LuaCallbackError(luastate, "internal error: no flow"); + + r = GetServerSoftwareVersion(luastate, f); + + return r; +} + +static int GetClientProtoVersion(lua_State *luastate, const Flow *f) +{ + void *state = FlowGetAppState(f); + if (state == NULL) + return LuaCallbackError(luastate, "error: no app layer state"); + + const uint8_t *protocol = NULL; + uint32_t b_len = 0; + + void *tx = rs_ssh_state_get_tx(state, 0); + if (rs_ssh_tx_get_protocol(tx, &protocol, &b_len, STREAM_TOSERVER) != 1) + return LuaCallbackError(luastate, "error: no client proto version"); + if (protocol == NULL || b_len == 0) { + return LuaCallbackError(luastate, "error: no client proto version"); + } + + return LuaPushStringBuffer(luastate, protocol, b_len); +} + +static int SshGetClientProtoVersion(lua_State *luastate) +{ + int r; + + if (!(LuaStateNeedProto(luastate, ALPROTO_SSH))) + return LuaCallbackError(luastate, "error: protocol not ssh"); + + Flow *f = LuaStateGetFlow(luastate); + if (f == NULL) + return LuaCallbackError(luastate, "internal error: no flow"); + + r = GetClientProtoVersion(luastate, f); + + return r; +} + +static int GetClientSoftwareVersion(lua_State *luastate, const Flow *f) +{ + void *state = FlowGetAppState(f); + if (state == NULL) + return LuaCallbackError(luastate, "error: no app layer state"); + + const uint8_t *software = NULL; + uint32_t b_len = 0; + + void *tx = rs_ssh_state_get_tx(state, 0); + if (rs_ssh_tx_get_software(tx, &software, &b_len, STREAM_TOSERVER) != 1) + return LuaCallbackError(luastate, "error: no client software version"); + if (software == NULL || b_len == 0) { + return LuaCallbackError(luastate, "error: no client software version"); + } + + return LuaPushStringBuffer(luastate, software, b_len); +} + +static int SshGetClientSoftwareVersion(lua_State *luastate) +{ + int r; + + if (!(LuaStateNeedProto(luastate, ALPROTO_SSH))) + return LuaCallbackError(luastate, "error: protocol not ssh"); + + Flow *f = LuaStateGetFlow(luastate); + if (f == NULL) + return LuaCallbackError(luastate, "internal error: no flow"); + + r = GetClientSoftwareVersion(luastate, f); + + return r; +} + +/** \brief register ssh lua extensions in a luastate */ +int LuaRegisterSshFunctions(lua_State *luastate) +{ + /* registration of the callbacks */ + lua_pushcfunction(luastate, SshGetServerProtoVersion); + lua_setglobal(luastate, "SshGetServerProtoVersion"); + + lua_pushcfunction(luastate, SshGetServerSoftwareVersion); + lua_setglobal(luastate, "SshGetServerSoftwareVersion"); + + lua_pushcfunction(luastate, SshGetClientProtoVersion); + lua_setglobal(luastate, "SshGetClientProtoVersion"); + + lua_pushcfunction(luastate, SshGetClientSoftwareVersion); + lua_setglobal(luastate, "SshGetClientSoftwareVersion"); + + return 0; +} + +#endif /* HAVE_LUA */ diff --git a/pool/shard002/C/0063714_libext2_fs.c b/pool/shard002/C/0063714_libext2_fs.c new file mode 100644 index 0000000000000000000000000000000000000000..33b033fd1f784d911ab0c761f81537e726051bb6 --- /dev/null +++ b/pool/shard002/C/0063714_libext2_fs.c @@ -0,0 +1,110 @@ +/* + * Copyright (c) 2008 The tyndur Project. All rights reserved. + * + * This code is derived from software contributed to the tyndur Project + * by Antoine Kaufmann. + * + * 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 tyndur Project + * and its contributors. + * 4. Neither the name of the tyndur Project nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED + * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS 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 + + +/** + * Prueft ob das Dateisystem konsistent aussieht, ohne Bitmap-Checks und co. + * Dazu muss die Superblockkopie in der FS-Struktur geladen sein. + * + * @return 1 wenn das Dateisystem in Ordung ist, 0 sonst. + */ +#if 0 +static int fs_check_fast(ext2_fs_t* fs) +{ + int count = ext2_sb_copy_count(fs->sb); + int i; + ext2_superblock_t sb; + + // Superblockkopien vergleichen + for (i = 0; i < count; i++) { + if (!ext2_sb_read_copy(fs, &sb, i)) { + return 0; + } + + if (!ext2_sb_compare(fs->sb, &sb)) { + return 0; + } + } + return 1; +} +#endif + +int ext2_fs_mount(ext2_fs_t* fs) +{ + fs->sb = malloc(sizeof(ext2_superblock_t)); + + if (!ext2_sb_read(fs, fs->sb)) { + free(fs->sb); + fs->sb = NULL; + return 0; + } + + fs->cache_handle = fs->cache_create(fs, ext2_sb_blocksize(fs->sb)); + fs->block_prev_alloc = 0; + + // Die Blocknummer in der der Superblock liegt, variiert je nach + // Blockgroesse, da der offset fix 1024 ist. + fs->sb_block = (ext2_sb_blocksize(fs->sb) > 1024 ? 0 : 1); + +#if 0 + if (!fs_check_fast(fs)) { + free(fs->sb); + fs->sb = NULL; + return 0; + } +#endif + return 1; +} + +int ext2_fs_unmount(ext2_fs_t* fs) +{ + // Sicherstellen, dass alle Aenderungen am Superblock geschrieben sind + if (!ext2_sb_update(fs, fs->sb)) { + return 0; + } + + free(fs->sb); + fs->cache_destroy(fs->cache_handle); + fs->sb = fs->cache_handle = NULL; + return 1; +} + +void ext2_fs_sync(ext2_fs_t* fs) +{ + fs->cache_sync(fs->cache_handle); +} + diff --git a/pool/shard002/C/0063729_hk_request.c b/pool/shard002/C/0063729_hk_request.c new file mode 100644 index 0000000000000000000000000000000000000000..a5c4fdd435a02b22448c2af7dfec763f1d222a31 --- /dev/null +++ b/pool/shard002/C/0063729_hk_request.c @@ -0,0 +1,202 @@ +#include +#include +#include + +#include "hk_request.h" +#include "hk_atomic.h" +#include "hk_buffer.h" +#include "hk_log.h" + +static void hk_request_free(hk_http_request_t *request); + +hk_http_header_t * +hk_header_init() +{ + hk_http_header_t *header; + + header = malloc(sizeof(hk_http_header_t)); + if ( header == NULL ) { + return NULL; + } + + header->name = NULL; + header->value = NULL; + + return header; +} + +void +hk_header_free(hk_http_header_t *header) +{ + if ( header->name != NULL ) { + free(header->name); + } + + if ( header->value != NULL ) { + free(header->value); + } + + free(header); +} + +hk_http_request_t * +hk_request_init() +{ + hk_http_request_t *request; + + request = malloc(sizeof(hk_http_request_t)); + if ( request == NULL ) { + return NULL; + } + + request->uri = NULL; + request->headers = hk_hash_init(10); + + request->ref = 0; + + return request; +} + +void +hk_request_set_uri(hk_http_request_t *request, char *uri, size_t length) +{ + if ( request->uri != NULL ) { + free(request->uri); + } + + if ( uri == NULL || length == 0 ) { + request->uri = NULL; + return; + } + + request->uri = malloc(length+1); + memcpy(request->uri, uri, length); + request->uri[length] = '\0'; +} + +void +hk_request_add_header(hk_http_request_t *request, char *name, size_t name_length, char *value, size_t value_length) +{ + hk_http_header_t *header = hk_header_init(); + + if ( name == NULL || value == NULL ) { + return; + } + + if ( value_length == -1 ) { + value_length = strlen(value); + } + + header->value = malloc(value_length+1); + if ( header->value == NULL ) { + hk_log_error("Cannot allocate memory for request header value"); + return; + } + + header->value = memcpy(header->value, value, value_length); + header->value[value_length] = '\0'; + + if ( name_length == -1 ) { + name_length = strlen(name); + } + header->name = malloc(name_length+1); + if ( header->name == NULL ) { + hk_log_error("Cannot allocate memory for request header name"); + return; + } + + header->name = memcpy(header->name, name, name_length); + header->name[name_length] = '\0'; + + hk_hash_insert(request->headers, header, header->name, name_length+1); +} + +hk_http_header_t * +hk_request_get_header(hk_http_request_t *request, char *name, size_t name_length) +{ + hk_http_header_t *header; + + if ( name_length == -1 ) { + name_length = strlen(name)+1; + } + + header = (hk_http_header_t *) hk_hash_exists_key(request->headers, name, name_length); + + return header; +} + +char * +hk_request_get_headers_string(hk_http_request_t *request, int *size) +{ + hk_buffer_t *buffer; + hk_http_header_t *header; + char *string; + + buffer = hk_buffer_init(1024); + + hk_hash_cursor_t *cursor = hk_hash_cursor_init(request->headers); + + while ( (header = hk_hash_cursor_next(cursor)) != NULL ) { + hk_buffer_append_string(buffer, (const char*)header->name, -1); + hk_buffer_append_string(buffer, ": ", 2); + hk_buffer_append_string(buffer, (const char*)header->value, -1); + hk_buffer_append_string(buffer, "\r\n", 2); + } + hk_buffer_append_string(buffer, "\r\n", 2); + + hk_hash_cursor_free(cursor); + + string = hk_buffer_copy_string(buffer); + if ( string == NULL ) { + return NULL; + } + + if ( size != NULL ) { + *size = buffer->used-1; + } + + hk_buffer_free(buffer); + + return string; +} + +void +hk_request_ref(hk_http_request_t *request) +{ + hk_atomic_fetch_add( &(request->ref), 1 ); +} + +void +hk_request_unref(hk_http_request_t *request) +{ + uint32_t old_ref; + old_ref = hk_atomic_sub_fetch( &(request->ref), 1 ); + + if ( old_ref == 0 ) { + hk_request_free(request); + } +} + +static void +hk_request_free(hk_http_request_t *request) +{ + if ( request->uri != NULL ) { + free(request->uri); + request->uri = NULL; + } + + /* Free headers */ + hk_http_header_t *header; + hk_hash_cursor_t *cursor = hk_hash_cursor_init(request->headers); + + while ( (header = hk_hash_cursor_next(cursor)) != NULL ) { + hk_header_free(header); + } + + hk_hash_cursor_free(cursor); + hk_hash_free(request->headers); + request->headers = NULL; + + free(request); +} + diff --git a/pool/shard002/C/0063731_rt5025-misc.c b/pool/shard002/C/0063731_rt5025-misc.c new file mode 100644 index 0000000000000000000000000000000000000000..e84475afe518db75f05fcbfa917c8991ca65f4f7 --- /dev/null +++ b/pool/shard002/C/0063731_rt5025-misc.c @@ -0,0 +1,119 @@ +/* + * drivers/mfd/rt5025-misc.c + * Driver foo Richtek RT5025 PMIC Misc Part + * + * Copyright (C) 2013 Richtek Electronics + * cy_huang + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License version 2 as + * published by the Free Software Foundation. + */ + +#include +#include +#include +#include +#include +#include + +#include +#include + +struct rt5025_misc_info { + struct i2c_client *i2c; +}; + +static struct i2c_client *g_shdn; +void rt5025_power_off(void) +{ + rt5025_reg_write(g_shdn, RT5025_CHENH_REG, 0x00); + rt5025_reg_write(g_shdn, RT5025_CHENL_REG, 0x80); + rt5025_set_bits(g_shdn, RT5025_SHDNCTRL_REG, RT5025_SHDNCTRL_MASK); +} +EXPORT_SYMBOL(rt5025_power_off); + +int rt5025_cable_exist(void) +{ + int ret = 0; + ret = rt5025_reg_read(g_shdn, 0x01); + if (ret < 0) + return 0; + else + { + if (ret&0x3) + return 1; + return 0; + } +} +EXPORT_SYMBOL(rt5025_cable_exist); + +static int __devinit rt5025_misc_reg_init(struct i2c_client *client, struct rt5025_misc_data *md) +{ + int ret = 0; + + rt5025_reg_write(client, RT5025_RESETCTRL_REG, md->RSTCtrl.val); + rt5025_assign_bits(client, RT5025_VSYSULVO_REG, RT5025_VSYSOFF_MASK, md->VSYSCtrl.val); + rt5025_reg_write(client, RT5025_PWRONCTRL_REG, md->PwrOnCfg.val); + rt5025_reg_write(client, RT5025_SHDNCTRL_REG, md->SHDNCtrl.val); + rt5025_reg_write(client, RT5025_PWROFFEN_REG, md->PwrOffCond.val); + + return ret; +} + +static int __devinit rt5025_misc_probe(struct platform_device *pdev) +{ + struct rt5025_chip *chip = dev_get_drvdata(pdev->dev.parent); + struct rt5025_platform_data *pdata = chip->dev->platform_data; + struct rt5025_misc_info *mi; + + mi = kzalloc(sizeof(*mi), GFP_KERNEL); + if (!mi) + return -ENOMEM; + + mi->i2c = chip->i2c; + rt5025_misc_reg_init(mi->i2c, pdata->misc_data); + + //for shutdown control + g_shdn = chip->i2c; + + platform_set_drvdata(pdev, mi); + return 0; +} + +static int __devexit rt5025_misc_remove(struct platform_device *pdev) +{ + struct rt5025_misc_info *mi = platform_get_drvdata(pdev); + + kfree(mi); + platform_set_drvdata(pdev, NULL); + return 0; +} + +static struct platform_driver rt5025_misc_driver = +{ + .driver = { + .name = RT5025_DEVICE_NAME "-misc", + .owner = THIS_MODULE, + }, + .probe = rt5025_misc_probe, + .remove = __devexit_p(rt5025_misc_remove), +}; + +static int __init rt5025_misc_init(void) +{ + return platform_driver_register(&rt5025_misc_driver); +} +module_init(rt5025_misc_init); + +static void __exit rt5025_misc_exit(void) +{ + platform_driver_unregister(&rt5025_misc_driver); +} +module_exit(rt5025_misc_exit); + +MODULE_LICENSE("GPL v2"); +MODULE_AUTHOR("CY Huang +#include +#include "../bsdthread/cancelable.h" + +long sys_select(int nfds, void* rfds, void* wfds, void* efds, struct bsd_timeval* timeout) +{ + CANCELATION_POINT(); + return sys_select_nocancel(nfds, rfds, wfds, efds, timeout); +} + +long sys_select_nocancel(int nfds, void* rfds, void* wfds, void* efds, struct bsd_timeval* timeout) +{ + int ret; + struct linux_timeval ltv; + + if (timeout != NULL) + { + ltv.tv_sec = timeout->tv_sec; + ltv.tv_usec = timeout->tv_usec; + } + +#ifdef __NR__newselect + ret = LINUX_SYSCALL(__NR__newselect, nfds, rfds, wfds, efds, + (timeout != NULL) ? <v : NULL); +#else + ret = LINUX_SYSCALL(__NR_select, nfds, rfds, wfds, efds, + (timeout != NULL) ? <v : NULL); +#endif + if (ret < 0) + ret = errno_linux_to_bsd(ret); + + return ret; +} + diff --git a/pool/shard002/C/0063738_default_panel.c b/pool/shard002/C/0063738_default_panel.c new file mode 100644 index 0000000000000000000000000000000000000000..fab26e989f18ed61363fae133882bb4528775abd --- /dev/null +++ b/pool/shard002/C/0063738_default_panel.c @@ -0,0 +1,139 @@ +#include "default_panel.h" + +static void LCD_power_on(u32 sel); +static void LCD_power_off(u32 sel); +static void LCD_bl_open(u32 sel); +static void LCD_bl_close(u32 sel); + +static void LCD_panel_init(u32 sel); +static void LCD_panel_exit(u32 sel); + +static void LCD_cfg_panel_info(panel_extend_para * info) +{ + u32 i = 0, j=0; + u32 items; + u8 lcd_gamma_tbl[][2] = + { + //{input value, corrected value} + {0, 0}, + {15, 15}, + {30, 30}, + {45, 45}, + {60, 60}, + {75, 75}, + {90, 90}, + {105, 105}, + {120, 120}, + {135, 135}, + {150, 150}, + {165, 165}, + {180, 180}, + {195, 195}, + {210, 210}, + {225, 225}, + {240, 240}, + {255, 255}, + }; + + u32 lcd_cmap_tbl[2][3][4] = { + { + {LCD_CMAP_G0,LCD_CMAP_B1,LCD_CMAP_G2,LCD_CMAP_B3}, + {LCD_CMAP_B0,LCD_CMAP_R1,LCD_CMAP_B2,LCD_CMAP_R3}, + {LCD_CMAP_R0,LCD_CMAP_G1,LCD_CMAP_R2,LCD_CMAP_G3}, + }, + { + {LCD_CMAP_B3,LCD_CMAP_G2,LCD_CMAP_B1,LCD_CMAP_G0}, + {LCD_CMAP_R3,LCD_CMAP_B2,LCD_CMAP_R1,LCD_CMAP_B0}, + {LCD_CMAP_G3,LCD_CMAP_R2,LCD_CMAP_G1,LCD_CMAP_R0}, + }, + }; + + items = sizeof(lcd_gamma_tbl)/2; + for(i=0; ilcd_gamma_tbl[lcd_gamma_tbl[i][0] + j] = (value<<16) + (value<<8) + value; + } + } + info->lcd_gamma_tbl[255] = (lcd_gamma_tbl[items-1][1]<<16) + (lcd_gamma_tbl[items-1][1]<<8) + lcd_gamma_tbl[items-1][1]; + + memcpy(info->lcd_cmap_tbl, lcd_cmap_tbl, sizeof(lcd_cmap_tbl)); + +} + +static s32 LCD_open_flow(u32 sel) +{ + LCD_OPEN_FUNC(sel, LCD_power_on, 30); //open lcd power, and delay 50ms + LCD_OPEN_FUNC(sel, LCD_panel_init, 50); //open lcd power, than delay 200ms + LCD_OPEN_FUNC(sel, sunxi_lcd_tcon_enable, 100); //open lcd controller, and delay 100ms + LCD_OPEN_FUNC(sel, LCD_bl_open, 0); //open lcd backlight, and delay 0ms + + return 0; +} + +static s32 LCD_close_flow(u32 sel) +{ + LCD_CLOSE_FUNC(sel, LCD_bl_close, 0); //close lcd backlight, and delay 0ms + LCD_CLOSE_FUNC(sel, sunxi_lcd_tcon_disable, 0); //close lcd controller, and delay 0ms + LCD_CLOSE_FUNC(sel, LCD_panel_exit, 200); //open lcd power, than delay 200ms + LCD_CLOSE_FUNC(sel, LCD_power_off, 500); //close lcd power, and delay 500ms + + return 0; +} + +static void LCD_power_on(u32 sel) +{ + sunxi_lcd_power_enable(sel, 0);//config lcd_power pin to open lcd power0 + sunxi_lcd_pin_cfg(sel, 1); +} + +static void LCD_power_off(u32 sel) +{ + sunxi_lcd_pin_cfg(sel, 0); + sunxi_lcd_power_disable(sel, 0);//config lcd_power pin to close lcd power0 +} + +static void LCD_bl_open(u32 sel) +{ + sunxi_lcd_pwm_enable(sel);//open pwm module + sunxi_lcd_backlight_enable(sel);//config lcd_bl_en pin to open lcd backlight +} + +static void LCD_bl_close(u32 sel) +{ + sunxi_lcd_backlight_disable(sel);//config lcd_bl_en pin to close lcd backlight + sunxi_lcd_pwm_disable(sel);//close pwm module +} + +static void LCD_panel_init(u32 sel) +{ + + return; +} + +static void LCD_panel_exit(u32 sel) +{ + + return ; +} + +//sel: 0:lcd0; 1:lcd1 +static s32 LCD_user_defined_func(u32 sel, u32 para1, u32 para2, u32 para3) +{ + return 0; +} + +__lcd_panel_t default_panel = { + /* panel driver name, must mach the name of lcd_drv_name in sys_config.fex */ + .name = "default_lcd", + .func = { + .cfg_panel_info = LCD_cfg_panel_info, + .cfg_open_flow = LCD_open_flow, + .cfg_close_flow = LCD_close_flow, + .lcd_user_defined_func = LCD_user_defined_func, + }, +}; diff --git a/pool/shard002/C/0063740_papi_fml_ins.c b/pool/shard002/C/0063740_papi_fml_ins.c new file mode 100644 index 0000000000000000000000000000000000000000..c1ba55877bd4749dc89601766b21897a258eb66e --- /dev/null +++ b/pool/shard002/C/0063740_papi_fml_ins.c @@ -0,0 +1,53 @@ +/* This code runs some sanity checks on the PAPI_FML_INS */ +/* (Floating point multiply instructions) events. */ + +/* by Vince Weaver, vweaver1 _at_ eecs.utk.edu */ + +#include +#include +#include + +#include "papi.h" + +#include "test_utils.h" + +int main(int argc, char **argv) { + + int events[1]; + long long counts[1]; + + int retval,quiet; + + char test_string[]="Testing PAPI_FML_INS predefined event..."; + + quiet=test_quiet(); + + retval = PAPI_library_init(PAPI_VER_CURRENT); + if (retval != PAPI_VER_CURRENT) { + if (!quiet) printf("Error! PAPI_library_init %d\n",retval); + test_fail(test_string); + } + + retval = PAPI_query_event(PAPI_FML_INS); + if (retval != PAPI_OK) { + if (!quiet) printf("PAPI_FML_INS not available\n"); + test_skip(test_string); + } + + events[0]=PAPI_FML_INS; + + PAPI_start_counters(events,1); + + PAPI_stop_counters(counts,1); + + if (counts[0]<1) { + if (!quiet) printf("Error! Count too low\n"); + test_fail(test_string); + } + + PAPI_shutdown(); + + test_unimplemented(test_string); + + return 0; +} diff --git a/pool/shard002/C/0063747_single.c b/pool/shard002/C/0063747_single.c new file mode 100644 index 0000000000000000000000000000000000000000..446a464e92ec23f7bcfc69713e393a6149383cb6 --- /dev/null +++ b/pool/shard002/C/0063747_single.c @@ -0,0 +1,190 @@ +/* Single-image implementation of GNU Fortran Coarray Library + Copyright (C) 2011-2013 Free Software Foundation, Inc. + Contributed by Tobias Burnus + +This file is part of the GNU Fortran Coarray Runtime Library (libcaf). + +Libcaf 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. + +Libcaf 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 "libcaf.h" +#include /* For fputs and fprintf. */ +#include /* For exit and malloc. */ +#include /* For memcpy and memset. */ +#include /* For variadic arguments. */ + +/* Define GFC_CAF_CHECK to enable run-time checking. */ +/* #define GFC_CAF_CHECK 1 */ + +/* Single-image implementation of the CAF library. + Note: For performance reasons -fcoarry=single should be used + rather than this library. */ + +/* Global variables. */ +caf_static_t *caf_static_list = NULL; + + +/* Keep in sync with mpi.c. */ +static void +caf_runtime_error (const char *message, ...) +{ + va_list ap; + fprintf (stderr, "Fortran runtime error: "); + va_start (ap, message); + vfprintf (stderr, message, ap); + va_end (ap); + fprintf (stderr, "\n"); + + /* FIXME: Shutdown the Fortran RTL to flush the buffer. PR 43849. */ + exit (EXIT_FAILURE); +} + +void +_gfortran_caf_init (int *argc __attribute__ ((unused)), + char ***argv __attribute__ ((unused)), + int *this_image, int *num_images) +{ + *this_image = 1; + *num_images = 1; +} + + +void +_gfortran_caf_finalize (void) +{ + while (caf_static_list != NULL) + { + caf_static_t *tmp = caf_static_list->prev; + free (caf_static_list->token[0]); + free (caf_static_list->token); + free (caf_static_list); + caf_static_list = tmp; + } +} + + +void * +_gfortran_caf_register (ptrdiff_t size, caf_register_t type, void ***token, + int *stat, char *errmsg, int errmsg_len) +{ + void *local; + + local = malloc (size); + *token = malloc (sizeof (void*) * 1); + (*token)[0] = local; + + if (unlikely (local == NULL || token == NULL)) + { + const char msg[] = "Failed to allocate coarray"; + if (stat) + { + *stat = 1; + if (errmsg_len > 0) + { + int len = ((int) sizeof (msg) > errmsg_len) ? errmsg_len + : (int) sizeof (msg); + memcpy (errmsg, msg, len); + if (errmsg_len > len) + memset (&errmsg[len], ' ', errmsg_len-len); + } + return NULL; + } + else + caf_runtime_error (msg); + } + + if (stat) + *stat = 0; + + if (type == CAF_REGTYPE_COARRAY_STATIC) + { + caf_static_t *tmp = malloc (sizeof (caf_static_t)); + tmp->prev = caf_static_list; + tmp->token = *token; + caf_static_list = tmp; + } + return local; +} + + +void +_gfortran_caf_deregister (void ***token, int *stat, + char *errmsg __attribute__ ((unused)), + int errmsg_len __attribute__ ((unused))) +{ + free ((*token)[0]); + free (*token); + + if (stat) + *stat = 0; +} + + +void +_gfortran_caf_sync_all (int *stat, + char *errmsg __attribute__ ((unused)), + int errmsg_len __attribute__ ((unused))) +{ + if (stat) + *stat = 0; +} + + +void +_gfortran_caf_sync_images (int count __attribute__ ((unused)), + int images[] __attribute__ ((unused)), + int *stat, + char *errmsg __attribute__ ((unused)), + int errmsg_len __attribute__ ((unused))) +{ +#ifdef GFC_CAF_CHECK + int i; + + for (i = 0; i < count; i++) + if (images[i] != 1) + { + fprintf (stderr, "COARRAY ERROR: Invalid image index %d to SYNC " + "IMAGES", images[i]); + exit (EXIT_FAILURE); + } +#endif + + if (stat) + *stat = 0; +} + + +void +_gfortran_caf_error_stop_str (const char *string, int32_t len) +{ + fputs ("ERROR STOP ", stderr); + while (len--) + fputc (*(string++), stderr); + fputs ("\n", stderr); + + exit (1); +} + + +void +_gfortran_caf_error_stop (int32_t error) +{ + fprintf (stderr, "ERROR STOP %d\n", error); + exit (error); +} diff --git a/pool/shard002/C/0063752_CWE195_Signed_to_Unsigned_Conversion_Error__listen_socket_memmove_52a.c b/pool/shard002/C/0063752_CWE195_Signed_to_Unsigned_Conversion_Error__listen_socket_memmove_52a.c new file mode 100644 index 0000000000000000000000000000000000000000..5a7254eadfc07e67f6a95b14151359b4e05a85d0 --- /dev/null +++ b/pool/shard002/C/0063752_CWE195_Signed_to_Unsigned_Conversion_Error__listen_socket_memmove_52a.c @@ -0,0 +1,173 @@ +/* TEMPLATE GENERATED TESTCASE FILE +Filename: CWE195_Signed_to_Unsigned_Conversion_Error__listen_socket_memmove_52a.c +Label Definition File: CWE195_Signed_to_Unsigned_Conversion_Error.label.xml +Template File: sources-sink-52a.tmpl.c +*/ +/* + * @description + * CWE: 195 Signed to Unsigned Conversion Error + * BadSource: listen_socket Read data using a listen socket (server side) + * GoodSource: Positive integer + * Sink: memmove + * BadSink : Copy strings using memmove() with the length of data + * Flow Variant: 52 Data flow: data passed as an argument from one function to another to another in three different source files + * + * */ + +#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 +#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 +#define CHAR_ARRAY_SIZE (3 * sizeof(data) + 2) + +#ifndef OMITBAD + +/* bad function declaration */ +void CWE195_Signed_to_Unsigned_Conversion_Error__listen_socket_memmove_52b_badSink(int data); + +void CWE195_Signed_to_Unsigned_Conversion_Error__listen_socket_memmove_52_bad() +{ + int data; + /* Initialize data */ + data = -1; + { +#ifdef _WIN32 + WSADATA wsaData; + int wsaDataInit = 0; +#endif + int recvResult; + struct sockaddr_in service; + SOCKET listenSocket = INVALID_SOCKET; + SOCKET acceptSocket = 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 listen socket */ + listenSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); + if (listenSocket == INVALID_SOCKET) + { + break; + } + memset(&service, 0, sizeof(service)); + service.sin_family = AF_INET; + service.sin_addr.s_addr = INADDR_ANY; + service.sin_port = htons(TCP_PORT); + if (bind(listenSocket, (struct sockaddr*)&service, sizeof(service)) == SOCKET_ERROR) + { + break; + } + if (listen(listenSocket, LISTEN_BACKLOG) == SOCKET_ERROR) + { + break; + } + acceptSocket = accept(listenSocket, NULL, NULL); + if (acceptSocket == SOCKET_ERROR) + { + break; + } + /* Abort on error or the connection was closed */ + recvResult = recv(acceptSocket, 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 (listenSocket != INVALID_SOCKET) + { + CLOSE_SOCKET(listenSocket); + } + if (acceptSocket != INVALID_SOCKET) + { + CLOSE_SOCKET(acceptSocket); + } +#ifdef _WIN32 + if (wsaDataInit) + { + WSACleanup(); + } +#endif + } + CWE195_Signed_to_Unsigned_Conversion_Error__listen_socket_memmove_52b_badSink(data); +} + +#endif /* OMITBAD */ + +#ifndef OMITGOOD + +/* good function declaration */ +void CWE195_Signed_to_Unsigned_Conversion_Error__listen_socket_memmove_52b_goodG2BSink(int data); + +/* 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; + CWE195_Signed_to_Unsigned_Conversion_Error__listen_socket_memmove_52b_goodG2BSink(data); +} + +void CWE195_Signed_to_Unsigned_Conversion_Error__listen_socket_memmove_52_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__listen_socket_memmove_52_good(); + printLine("Finished good()"); +#endif /* OMITGOOD */ +#ifndef OMITBAD + printLine("Calling bad()..."); + CWE195_Signed_to_Unsigned_Conversion_Error__listen_socket_memmove_52_bad(); + printLine("Finished bad()"); +#endif /* OMITBAD */ + return 0; +} + +#endif diff --git a/pool/shard002/C/0063757_btstack.c b/pool/shard002/C/0063757_btstack.c new file mode 100644 index 0000000000000000000000000000000000000000..b51b81e9faadc434152b972b17d23381d62bf420 --- /dev/null +++ b/pool/shard002/C/0063757_btstack.c @@ -0,0 +1,135 @@ +/* + * Copyright (C) 2009-2012 by Matthias Ringwald + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of the copyright holders nor the names of + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * 4. Any redistribution, use, or modification is done solely for + * personal benefit and not for any commercial purpose or for + * monetary gain. + * + * THIS SOFTWARE IS PROVIDED BY MATTHIAS RINGWALD 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 MATTHIAS + * RINGWALD 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. + * + * Please inquire about commercial licensing options at btstack@ringwald.ch + * + */ + +/* + * btstack.c + * + * Created by Matthias Ringwald on 7/1/09. + * + * BTstack client API + */ + +#include + +#include "l2cap.h" +#include "socket_connection.h" +#include + +#include +#include +#include +#include + +// static uint8_t hci_cmd_buffer[3+255]; // HCI Command Header + max payload +static uint8_t hci_cmd_buffer[HCI_ACL_BUFFER_SIZE]; // BTstack command packets are not size restricted + +static connection_t *btstack_connection = NULL; + +/** prototypes & dummy functions */ +static void dummy_handler(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size){}; +static int btstack_packet_handler(connection_t *connection, uint16_t packet_type, uint16_t channel, uint8_t *data, uint16_t size); + +/** local globals :) */ +static void (*client_packet_handler)(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size) = dummy_handler; + +static const char * daemon_tcp_address = NULL; +static uint16_t daemon_tcp_port = BTSTACK_PORT; + +// optional: if called before bt_open, TCP socket is used instead of local unix socket +// note: address is not copied and must be valid during bt_open +void bt_use_tcp(const char * address, uint16_t port){ + daemon_tcp_address = address; + daemon_tcp_port = port; +} + +// init BTstack library +int bt_open(){ + + socket_connection_register_packet_callback(btstack_packet_handler); + + // BTdaemon + if (daemon_tcp_address) { + btstack_connection = socket_connection_open_tcp(daemon_tcp_address,daemon_tcp_port); + } else { + btstack_connection = socket_connection_open_unix(); + } + if (!btstack_connection) return -1; + + return 0; +} + +// stop using BTstack library +int bt_close(){ + return socket_connection_close_tcp(btstack_connection); +} + +// send hci cmd packet +int bt_send_cmd(const hci_cmd_t *cmd, ...){ + va_list argptr; + va_start(argptr, cmd); + uint16_t len = hci_create_cmd_internal(hci_cmd_buffer, cmd, argptr); + va_end(argptr); + socket_connection_send_packet(btstack_connection, HCI_COMMAND_DATA_PACKET, 0, hci_cmd_buffer, len); + return 0; +} + +int btstack_packet_handler(connection_t *connection, uint16_t packet_type, uint16_t channel, uint8_t *data, uint16_t size){ + // printf("BTstack client handler: packet type %u, data[0] %x\n", packet_type, data[0]); + (*client_packet_handler)(packet_type, channel, data, size); + return 0; +} + +// register packet handler +btstack_packet_handler_t bt_register_packet_handler(btstack_packet_handler_t handler){ + btstack_packet_handler_t old_handler = client_packet_handler; + client_packet_handler = handler; + return old_handler; +} + +void bt_send_l2cap(uint16_t source_cid, uint8_t *data, uint16_t len){ + // send + socket_connection_send_packet(btstack_connection, L2CAP_DATA_PACKET, source_cid, data, len); +} + +void bt_send_rfcomm(uint16_t rfcomm_cid, uint8_t *data, uint16_t len){ + // send + socket_connection_send_packet(btstack_connection, RFCOMM_DATA_PACKET, rfcomm_cid, data, len); +} + +void bt_send_acl(uint8_t * data, uint16_t len){ + // send + socket_connection_send_packet(btstack_connection, HCI_ACL_DATA_PACKET, 0, data, len); +} diff --git a/pool/shard002/C/0063765_builder.c b/pool/shard002/C/0063765_builder.c new file mode 100644 index 0000000000000000000000000000000000000000..254ecdc166c94ada6177f7ad9ca525bc0393c726 --- /dev/null +++ b/pool/shard002/C/0063765_builder.c @@ -0,0 +1,70 @@ +/* Builder + * + * Demonstrates an interface loaded from a XML description. + */ +#undef GTK_DISABLE_DEPRECATED +#include + +static GtkBuilder *builder; + +G_MODULE_EXPORT void +quit_activate (GtkAction *action) +{ + GtkWidget *window; + + window = GTK_WIDGET (gtk_builder_get_object (builder, "window1")); + gtk_widget_destroy (window); +} + +G_MODULE_EXPORT void +about_activate (GtkAction *action) +{ + GtkWidget *about_dlg; + + about_dlg = GTK_WIDGET (gtk_builder_get_object (builder, "aboutdialog1")); + gtk_dialog_run (GTK_DIALOG (about_dlg)); + gtk_widget_hide (about_dlg); +} + +G_MODULE_EXPORT void +help_activate (GtkAction *action) +{ + g_print ("Help not available\n"); +} + +GtkWidget * +do_builder (GtkWidget *do_widget) +{ + static GtkWidget *window = NULL; + GError *err = NULL; + + if (!window) + { + builder = gtk_builder_new (); + gtk_builder_add_from_resource (builder, "/builder/demo.ui", &err); + if (err) + { + g_error ("ERROR: %s\n", err->message); + return NULL; + } + gtk_builder_connect_signals (builder, NULL); + window = GTK_WIDGET (gtk_builder_get_object (builder, "window1")); + gtk_window_set_screen (GTK_WINDOW (window), + gtk_widget_get_screen (do_widget)); + g_signal_connect (window, "destroy", + G_CALLBACK (gtk_widget_destroyed), &window); + } + + if (!gtk_widget_get_visible (window)) + { + gtk_widget_show_all (window); + } + else + { + gtk_widget_destroy (window); + window = NULL; + } + + + return window; +} diff --git a/pool/shard002/C/0063772_LB+PPO0491.c b/pool/shard002/C/0063772_LB+PPO0491.c new file mode 100644 index 0000000000000000000000000000000000000000..b5e5c5370c8cde8cca38189d023f6130b8a4d903 --- /dev/null +++ b/pool/shard002/C/0063772_LB+PPO0491.c @@ -0,0 +1,59 @@ +/* Copyright (C) 2018 Magnus Lång and Tuan Phong Ngo + * This benchmark is part of SWSC */ + +#include +#include +#include +#include + +atomic_int vars[2]; +atomic_int atom_0_r1_1; +atomic_int atom_1_r1_1; + +void *t0(void *arg){ +label_1:; + int v2_r1 = atomic_load_explicit(&vars[0], memory_order_seq_cst); + int v3_r3 = v2_r1 ^ v2_r1; + int v4_r3 = v3_r3 + 1; + atomic_store_explicit(&vars[1], v4_r3, memory_order_seq_cst); + int v17 = (v2_r1 == 1); + atomic_store_explicit(&atom_0_r1_1, v17, memory_order_seq_cst); + return NULL; +} + +void *t1(void *arg){ +label_2:; + int v6_r1 = atomic_load_explicit(&vars[1], memory_order_seq_cst); + int v8_r3 = atomic_load_explicit(&vars[1], memory_order_seq_cst); + atomic_store_explicit(&vars[1], 2, memory_order_seq_cst); + int v10_r5 = atomic_load_explicit(&vars[1], memory_order_seq_cst); + atomic_store_explicit(&vars[0], 1, memory_order_seq_cst); + int v18 = (v6_r1 == 1); + atomic_store_explicit(&atom_1_r1_1, v18, memory_order_seq_cst); + return NULL; +} + +int main(int argc, char *argv[]){ + pthread_t thr0; + pthread_t thr1; + + atomic_init(&vars[1], 0); + atomic_init(&vars[0], 0); + atomic_init(&atom_0_r1_1, 0); + atomic_init(&atom_1_r1_1, 0); + + pthread_create(&thr0, NULL, t0, NULL); + pthread_create(&thr1, NULL, t1, NULL); + + pthread_join(thr0, NULL); + pthread_join(thr1, NULL); + + int v11 = atomic_load_explicit(&vars[1], memory_order_seq_cst); + int v12 = (v11 == 2); + int v13 = atomic_load_explicit(&atom_0_r1_1, memory_order_seq_cst); + int v14 = atomic_load_explicit(&atom_1_r1_1, memory_order_seq_cst); + int v15_conj = v13 & v14; + int v16_conj = v12 & v15_conj; + if (v16_conj == 1) assert(0); + return 0; +} diff --git a/pool/shard002/C/0063774_Version.c b/pool/shard002/C/0063774_Version.c new file mode 100644 index 0000000000000000000000000000000000000000..3f5d9b753842e8d28de04dad72ba9f3efb0e739a --- /dev/null +++ b/pool/shard002/C/0063774_Version.c @@ -0,0 +1,169 @@ +/* + * Generated by asn1c-0.9.22 (http://lionet.info/asn1c) + * From ASN.1 module "ULP-Components" + * found in "../supl-common.asn" + */ + +#include "Version.h" + +static int +memb_maj_constraint_1(asn_TYPE_descriptor_t *td, const void *sptr, + asn_app_constraint_failed_f *ctfailcb, void *app_key) { + long value; + + if(!sptr) { + _ASN_CTFAIL(app_key, td, sptr, + "%s: value not given (%s:%d)", + td->name, __FILE__, __LINE__); + return -1; + } + + value = *(const long *)sptr; + + if((value >= 0 && value <= 255)) { + /* Constraint check succeeded */ + return 0; + } else { + _ASN_CTFAIL(app_key, td, sptr, + "%s: constraint failed (%s:%d)", + td->name, __FILE__, __LINE__); + return -1; + } +} + +static int +memb_min_constraint_1(asn_TYPE_descriptor_t *td, const void *sptr, + asn_app_constraint_failed_f *ctfailcb, void *app_key) { + long value; + + if(!sptr) { + _ASN_CTFAIL(app_key, td, sptr, + "%s: value not given (%s:%d)", + td->name, __FILE__, __LINE__); + return -1; + } + + value = *(const long *)sptr; + + if((value >= 0 && value <= 255)) { + /* Constraint check succeeded */ + return 0; + } else { + _ASN_CTFAIL(app_key, td, sptr, + "%s: constraint failed (%s:%d)", + td->name, __FILE__, __LINE__); + return -1; + } +} + +static int +memb_servind_constraint_1(asn_TYPE_descriptor_t *td, const void *sptr, + asn_app_constraint_failed_f *ctfailcb, void *app_key) { + long value; + + if(!sptr) { + _ASN_CTFAIL(app_key, td, sptr, + "%s: value not given (%s:%d)", + td->name, __FILE__, __LINE__); + return -1; + } + + value = *(const long *)sptr; + + if((value >= 0 && value <= 255)) { + /* Constraint check succeeded */ + return 0; + } else { + _ASN_CTFAIL(app_key, td, sptr, + "%s: constraint failed (%s:%d)", + td->name, __FILE__, __LINE__); + return -1; + } +} + +static asn_per_constraints_t asn_PER_memb_maj_constr_2 = { + { APC_CONSTRAINED, 8, 8, 0, 255 } /* (0..255) */, + { APC_UNCONSTRAINED, -1, -1, 0, 0 }, + 0, 0 /* No PER value map */ +}; +static asn_per_constraints_t asn_PER_memb_min_constr_3 = { + { APC_CONSTRAINED, 8, 8, 0, 255 } /* (0..255) */, + { APC_UNCONSTRAINED, -1, -1, 0, 0 }, + 0, 0 /* No PER value map */ +}; +static asn_per_constraints_t asn_PER_memb_servind_constr_4 = { + { APC_CONSTRAINED, 8, 8, 0, 255 } /* (0..255) */, + { APC_UNCONSTRAINED, -1, -1, 0, 0 }, + 0, 0 /* No PER value map */ +}; +static asn_TYPE_member_t asn_MBR_Version_1[] = { + { ATF_NOFLAGS, 0, offsetof(struct Version, maj), + (ASN_TAG_CLASS_CONTEXT | (0 << 2)), + -1, /* IMPLICIT tag at current level */ + &asn_DEF_NativeInteger, + memb_maj_constraint_1, + &asn_PER_memb_maj_constr_2, + 0, + "maj" + }, + { ATF_NOFLAGS, 0, offsetof(struct Version, min), + (ASN_TAG_CLASS_CONTEXT | (1 << 2)), + -1, /* IMPLICIT tag at current level */ + &asn_DEF_NativeInteger, + memb_min_constraint_1, + &asn_PER_memb_min_constr_3, + 0, + "min" + }, + { ATF_NOFLAGS, 0, offsetof(struct Version, servind), + (ASN_TAG_CLASS_CONTEXT | (2 << 2)), + -1, /* IMPLICIT tag at current level */ + &asn_DEF_NativeInteger, + memb_servind_constraint_1, + &asn_PER_memb_servind_constr_4, + 0, + "servind" + }, +}; +static ber_tlv_tag_t asn_DEF_Version_tags_1[] = { + (ASN_TAG_CLASS_UNIVERSAL | (16 << 2)) +}; +static asn_TYPE_tag2member_t asn_MAP_Version_tag2el_1[] = { + { (ASN_TAG_CLASS_CONTEXT | (0 << 2)), 0, 0, 0 }, /* maj at 10 */ + { (ASN_TAG_CLASS_CONTEXT | (1 << 2)), 1, 0, 0 }, /* min at 11 */ + { (ASN_TAG_CLASS_CONTEXT | (2 << 2)), 2, 0, 0 } /* servind at 12 */ +}; +static asn_SEQUENCE_specifics_t asn_SPC_Version_specs_1 = { + sizeof(struct Version), + offsetof(struct Version, _asn_ctx), + asn_MAP_Version_tag2el_1, + 3, /* Count of tags in the map */ + 0, 0, 0, /* Optional elements (not needed) */ + -1, /* Start extensions */ + -1 /* Stop extensions */ +}; +asn_TYPE_descriptor_t asn_DEF_Version = { + "Version", + "Version", + SEQUENCE_free, + SEQUENCE_print, + SEQUENCE_constraint, + SEQUENCE_decode_ber, + SEQUENCE_encode_der, + SEQUENCE_decode_xer, + SEQUENCE_encode_xer, + SEQUENCE_decode_uper, + SEQUENCE_encode_uper, + 0, /* Use generic outmost tag fetcher */ + asn_DEF_Version_tags_1, + sizeof(asn_DEF_Version_tags_1) + /sizeof(asn_DEF_Version_tags_1[0]), /* 1 */ + asn_DEF_Version_tags_1, /* Same as above */ + sizeof(asn_DEF_Version_tags_1) + /sizeof(asn_DEF_Version_tags_1[0]), /* 1 */ + 0, /* No PER visible constraints */ + asn_MBR_Version_1, + 3, /* Elements count */ + &asn_SPC_Version_specs_1 /* Additional specs */ +}; + diff --git a/pool/shard002/C/0063778_playlist.c b/pool/shard002/C/0063778_playlist.c new file mode 100644 index 0000000000000000000000000000000000000000..abebec33463adca5e8b4ce404baaf0c92e5f3d60 --- /dev/null +++ b/pool/shard002/C/0063778_playlist.c @@ -0,0 +1,153 @@ +/** + * (c) 2001-2006 Nathan Hjelm + * v1.5.0 playlist.c + * + * 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., 675 Mass Ave, Cambridge, MA 02139, USA. + **/ + +#include +#include +#include + +#include +#include +#include +#include + +#include +#include +#include +#include + +#include "rioi.h" + +#ifdef HAVE_LIBGEN_H +#include +#endif + +#if !defined (PATH_MAX) +#define PATH_MAX 255 +#endif + +int create_playlist_rio (rios_t *rio, char *name, int songs[], int memory_units[], int nsongs) { + info_page_t info; + int error, addpipe, i, tmpi; + char filename[PATH_MAX]; + char tmpc; + file_list *tmp; + FILE *fh; + + if (!rio) + return -EINVAL; + + /* Current implementation only works for S-Series and newer. For + older, upload a .lst file. */ + if (return_generation_rio (rio) < 4) + return -EPERM; + + if (try_lock_rio (rio) != 0) + return -EBUSY; + + rio_log (rio, 0, "create_playlist_rio: creating a new playlist %s.\n", name); + + /* Create a temporary file to store the new playlist */ + snprintf (filename, PATH_MAX, "/tmp/rioutil_%s.%08x.lst", name, time (NULL)); + fh = fopen (filename, "w"); + if (fh == 0) + UNLOCK(-errno); + fprintf (fh, "FIDLST%c%c%c", 1, 0, 0); + tmpi = arch32_2_little32(nsongs); + fwrite (&tmpi, 1, 3, fh); + + for (i = 0 ; i < nsongs ; i++) { + rio_log (rio, 0, "Adding for song %i to playlist %s...\n", songs[i], name); + for (tmp = rio->info.memory[memory_units[i]].files ; tmp ; tmp = tmp->next) + if (tmp->num == songs[i]) + break; + + if (tmp == NULL) + continue; + + tmpi = arch32_2_little32(tmp->rio_num); + fwrite (&tmpi, 1, 3, fh); + fwrite (tmp->sflags, 3, 1, fh); + } + + fclose (fh); + + new_playlist_info (&info, filename, name); + + if ((addpipe = open(filename, O_RDONLY)) == -1) + return -1; + + /* i moved the major functionality of both add_file and add_song down a layer */ + if ((error = do_upload (rio, 0, addpipe, info, 0)) != URIO_SUCCESS) { + free (info.data); + + close (addpipe); + + /* make sure no malicious user has messed with this variable */ + if (strstr (filename, "/tmp/rioutil_") == filename) + unlink (filename); + + UNLOCK(error); + } + + close (addpipe); + + if (strstr (filename, "/tmp/rioutil_") == filename) + unlink (filename); + + free (info.data); + + rio_log (rio, 0, "add_file_rio: copy complete.\n"); + + UNLOCK(URIO_SUCCESS); +} + + +/* + playlist_info: +*/ +int playlist_info (info_page_t *newInfo, char *file_name) { + rio_file_t *playlist_file = newInfo->data; + int fnum; + + sscanf(file_name, "Playlist%02d.lst", &fnum); + + sprintf((char *)playlist_file->title, "Playlist %02d", fnum); + + playlist_file->bits = 0x21000590; /* playlist bits + file bits + download bit */ + + newInfo->skip = 0; + newInfo->data = playlist_file; + + return URIO_SUCCESS; +} + +/* Playlists for S-Series and newer. */ +int new_playlist_info (info_page_t *newInfo, char *file_name, char *name) { + rio_file_t *playlist_file = newInfo->data; + + snprintf((char *)playlist_file->title, 64, "%s", name); + + playlist_file->bits = 0x11000110; + playlist_file->type = TYPE_PLS; + + newInfo->skip = 0; + newInfo->data = playlist_file; + + return URIO_SUCCESS; +} diff --git a/pool/shard002/C/0063789_ooaofooa_I_BSF_class.c b/pool/shard002/C/0063789_ooaofooa_I_BSF_class.c new file mode 100644 index 0000000000000000000000000000000000000000..617ecfc0e9f388a0e3636904db9e3c983320e237 --- /dev/null +++ b/pool/shard002/C/0063789_ooaofooa_I_BSF_class.c @@ -0,0 +1,133 @@ +/*---------------------------------------------------------------------------- + * File: ooaofooa_I_BSF_class.c + * + * Class: Block in Stack Frame (I_BSF) + * 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_I_BSF_instanceloader( Escher_iHandle_t instance, const c_t * avlstring[] ) +{ + Escher_iHandle_t return_identifier = 0; + ooaofooa_I_BSF * self = (ooaofooa_I_BSF *) instance; + /* Initialize application analysis class attributes. */ + self->Block_ID = (Escher_iHandle_t) Escher_atoi( avlstring[ 1 ] ); + self->Stack_Frame_ID = (Escher_iHandle_t) Escher_atoi( avlstring[ 2 ] ); + self->Statement_ID = (Escher_iHandle_t) Escher_atoi( avlstring[ 3 ] ); + self->isExecuting = ( '0' != *avlstring[ 4 ] ); + return return_identifier; +} + +/* + * Select any where using referential/identifying attribute set. + * If not_empty, relate this instance to the selected instance. + */ +void ooaofooa_I_BSF_batch_relate( Escher_iHandle_t instance ) +{ + ooaofooa_I_BSF * ooaofooa_I_BSF_instance = (ooaofooa_I_BSF *) instance; + ooaofooa_I_STF * ooaofooa_I_STFrelated_instance1 = (ooaofooa_I_STF *) Escher_instance_cache[ (intptr_t) ooaofooa_I_BSF_instance->Stack_Frame_ID ]; + ooaofooa_ACT_BLK * ooaofooa_ACT_BLKrelated_instance2 = (ooaofooa_ACT_BLK *) Escher_instance_cache[ (intptr_t) ooaofooa_I_BSF_instance->Block_ID ]; + if ( ooaofooa_I_STFrelated_instance1 && ooaofooa_ACT_BLKrelated_instance2 ) { + ooaofooa_I_BSF_R2923_Link( ooaofooa_ACT_BLKrelated_instance2, ooaofooa_I_STFrelated_instance1, ooaofooa_I_BSF_instance ); + } + { + ooaofooa_ACT_SMT * ooaofooa_ACT_SMTrelated_instance1 = (ooaofooa_ACT_SMT *) Escher_instance_cache[ (intptr_t) ooaofooa_I_BSF_instance->Statement_ID ]; + if ( ooaofooa_ACT_SMTrelated_instance1 ) { + ooaofooa_I_BSF_R2941_Link_is_visited_within_scope_of( ooaofooa_ACT_SMTrelated_instance1, ooaofooa_I_BSF_instance ); + } + } +} + + +/* + * RELATE ACT_BLK TO I_STF ACROSS R2923 USING I_BSF + */ +void +ooaofooa_I_BSF_R2923_Link( ooaofooa_ACT_BLK * aone, ooaofooa_I_STF * aoth, ooaofooa_I_BSF * assr ) +{ + /* Use TagEmptyHandleDetectionOn() to detect empty handle references. */ + assr->Block_ID = aone->Block_ID; + assr->Stack_Frame_ID = aoth->Stack_Frame_ID; + /* Initialize optimized relationship storage extended attributes */ + assr->ACT_BLK_R2923_supplies_context_for = aone; + assr->I_STF_R2923_is_executed_within_the_context_of = aoth; + Escher_SetInsertElement( &aone->I_BSF_R2923, assr ); + Escher_SetInsertElement( &aoth->I_BSF_R2923, assr ); +} + +/* + * UNRELATE ACT_BLK FROM I_STF ACROSS R2923 USING I_BSF + */ +void +ooaofooa_I_BSF_R2923_Unlink( ooaofooa_ACT_BLK * aone, ooaofooa_I_STF * aoth, ooaofooa_I_BSF * assr ) +{ + /* Use TagEmptyHandleDetectionOn() to detect empty handle references. */ + assr->ACT_BLK_R2923_supplies_context_for = 0; + assr->I_STF_R2923_is_executed_within_the_context_of = 0; + Escher_SetRemoveElement( &aone->I_BSF_R2923, assr ); + Escher_SetRemoveElement( &aoth->I_BSF_R2923, assr ); +} + +/* + * RELATE ACT_SMT TO I_BSF ACROSS R2941 + */ +void +ooaofooa_I_BSF_R2941_Link_is_visited_within_scope_of( ooaofooa_ACT_SMT * part, ooaofooa_I_BSF * form ) +{ + /* Use TagEmptyHandleDetectionOn() to detect empty handle references. */ + form->Statement_ID = part->Statement_ID; + form->ACT_SMT_R2941_is_currently_visiting = part; + Escher_SetInsertElement( &part->I_BSF_R2941_is_visited_within_scope_of, (Escher_ObjectSet_s *) form ); +} + +/* + * UNRELATE ACT_SMT FROM I_BSF ACROSS R2941 + */ +void +ooaofooa_I_BSF_R2941_Unlink_is_visited_within_scope_of( ooaofooa_ACT_SMT * part, ooaofooa_I_BSF * form ) +{ + /* Use TagEmptyHandleDetectionOn() to detect empty handle references. */ + form->Statement_ID = 0; + form->ACT_SMT_R2941_is_currently_visiting = 0; + Escher_SetRemoveElement( &part->I_BSF_R2941_is_visited_within_scope_of, (Escher_ObjectSet_s *) form ); +} + +/* + * Dump instances in SQL format. + */ +void +ooaofooa_I_BSF_instancedumper( Escher_iHandle_t instance ) +{ + ooaofooa_I_BSF * self = (ooaofooa_I_BSF *) instance; + printf( "INSERT INTO I_BSF VALUES ( %ld,%ld,%ld,%d );\n", + ((long)self->Block_ID & ESCHER_IDDUMP_MASK), + ((long)self->Stack_Frame_ID & ESCHER_IDDUMP_MASK), + ((long)self->Statement_ID & ESCHER_IDDUMP_MASK), + self->isExecuting ); +} +/* + * 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_I_BSF_container[ ooaofooa_I_BSF_MAX_EXTENT_SIZE ]; +static ooaofooa_I_BSF ooaofooa_I_BSF_instances[ ooaofooa_I_BSF_MAX_EXTENT_SIZE ]; +Escher_Extent_t pG_ooaofooa_I_BSF_extent = { + {0,0}, {0,0}, &ooaofooa_I_BSF_container[ 0 ], + (Escher_iHandle_t) &ooaofooa_I_BSF_instances, + sizeof( ooaofooa_I_BSF ), 0, ooaofooa_I_BSF_MAX_EXTENT_SIZE + }; + + diff --git a/pool/shard002/C/0063794_cbuffer.c b/pool/shard002/C/0063794_cbuffer.c new file mode 100644 index 0000000000000000000000000000000000000000..082b0ddcd96949301b2731b425b2723b21d6b98e --- /dev/null +++ b/pool/shard002/C/0063794_cbuffer.c @@ -0,0 +1,231 @@ +/* Copyright (C) 2007-2008 The Android Open Source Project +** +** 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 "cbuffer.h" +#include "android_utils.h" +#include +#include +#include +#include + +#define DEBUG 0 + +#if DEBUG +# define ASSERT(cond,fmt,...) ({ if (!(cond)) { fprintf(stderr, fmt, __VA_ARGS__); assert(cond); } }) +#else +# define ASSERT(cond,fmt,...) ((void)0) +#endif + +#if DEBUG +void +cbuffer_assert( CBuffer* cb, const char* file, long lineno ) +{ + const char* reason = NULL; + + if (cb->rpos < 0 || cb->rpos >= cb->size) { + reason = "rpos is out of bounds"; + } + else if (cb->count < 0 || cb->count > cb->size) { + reason = "count is incorrect"; + } + if (!reason) + return; + + fprintf(stderr, "assert:%s:%ld: assertion failed: %s (pos=%d count=%d size=%d)\n", + file, lineno, reason, cb->rpos, cb->count, cb->size); + assert(0); +} +# define CBUFFER_ASSERT(cb) cbuffer_assert(cb,__FUNCTION__,__LINE__) +#else +# define CBUFFER_ASSERT(cb) ((void)0) +#endif + +int +cbuffer_write_peek( CBuffer* cb, uint8_t* *pbase ) +{ + int wpos = cb->rpos + cb->count; + int avail = cb->size - cb->count; + + CBUFFER_ASSERT(cb); + + if (wpos >= cb->size) + wpos -= cb->size; + + if (wpos + avail > cb->size) + avail = cb->size - wpos; + + *pbase = cb->buff + wpos; + return avail; +} + +void +cbuffer_write_step( CBuffer* cb, int len ) +{ + CBUFFER_ASSERT(cb); + + cb->count += len; + if (cb->count > cb->size) + cb->count = cb->size; +} + + +int +cbuffer_write( CBuffer* cb, const void* from, int len ) +{ + int len2 = len; + + CBUFFER_ASSERT(cb); + + while (len2 > 0) { + int avail = cb->size - cb->count; + int wpos = cb->rpos + cb->count; + + ASSERT(avail >= 0, "avail is negative: %d", avail); + + if (avail == 0) + break; + + if (wpos >= cb->size) + wpos -= cb->size; + + ASSERT( wpos >= 0 && wpos < cb->size, "wpos is out-of-bounds: %d (rpos=%d)", wpos, cb->rpos); + + if (wpos + avail > cb->size) + avail = cb->size - wpos; + + if (avail > len2) + avail = len2; + + memcpy( cb->buff + wpos, (const char*)from, avail ); + + from = (char*)from + avail; + len2 -= avail; + cb->count += avail; + } + return len - len2; +} + +int +cbuffer_read( CBuffer* cb, void* to, int len ) +{ + int len2 = len; + + CBUFFER_ASSERT(cb); + + while (len2 > 0) { + int avail = cb->count; + int rpos = cb->rpos; + + ASSERT(avail >= 0, "avail is negative: %d", avail); + + if (avail == 0) + break; + + ASSERT((rpos >= 0 && rpos < cb->size), "rpos is out-of-bounds: %d", rpos); + + if (rpos+avail > cb->size) + avail = cb->size - rpos; + + if (avail > len2) + avail = len2; + + memcpy( (char*)to, (const char*)cb->buff + rpos, avail ); + to = (char*)to + avail; + len2 -= avail; + cb->count -= avail; + cb->rpos += avail; + if (cb->rpos >= cb->size) + cb->rpos -= cb->size; + } + return len - len2; +} + +int +cbuffer_read_peek( CBuffer* cb, uint8_t* *pbase ) +{ + int rpos = cb->rpos; + int avail = cb->count; + + CBUFFER_ASSERT(cb); + + if (rpos + avail > cb->size) + avail = cb->size - rpos; + + *pbase = cb->buff + rpos; + return avail; +} + + +void +cbuffer_read_step( CBuffer* cb, int len ) +{ + CBUFFER_ASSERT(cb); + + if (len > cb->count) + len = cb->count; + + cb->rpos += len; + if (cb->rpos >= cb->size) + cb->rpos -= cb->size; + + cb->count -= len; +} + +const char* +cbuffer_quote( CBuffer* cb ) +{ + STRALLOC_DEFINE(s); + char* q; + + stralloc_format( s, "cbuffer %p (pos=%d count=%d size=%d)", + cb, cb->rpos, cb->count, cb->size ); + + q = tempstr_from_stralloc( s ); + stralloc_reset(s); + + return q; +} + +const char* +cbuffer_quote_data( CBuffer* cb ) +{ + STRALLOC_DEFINE(s); + int len = cb->count; + int rpos = cb->rpos; + char* result; + + while (len > 0) { + int avail = len; + + if (rpos >= cb->size) + rpos -= cb->size; + + if (rpos + avail > cb->size) + avail = cb->size - rpos; + + stralloc_add_quote_bytes( s, cb->buff + rpos, avail ); + rpos += avail; + len -= avail; + } + + result = tempstr_from_stralloc(s); + stralloc_reset(s); + + return result; +} + +void +cbuffer_print( CBuffer* cb ) +{ + /* print the content of a cbuffer */ + printf( "%s: %s", cbuffer_quote(cb), cbuffer_quote_data(cb) ); +} + diff --git a/pool/shard002/C/0063810_wrap_accelerate_c.c b/pool/shard002/C/0063810_wrap_accelerate_c.c new file mode 100644 index 0000000000000000000000000000000000000000..0d8aab09a042f850a5c442b479dd7f3b8f503599 --- /dev/null +++ b/pool/shard002/C/0063810_wrap_accelerate_c.c @@ -0,0 +1,53 @@ +#include "cblas.h" + +#define WRAP_F77(a) a##_ + +/* This intermediate C-file is necessary also for the Fortran wrapper: + - The cblas_* functions cannot be called from Fortran directly + as they do not take all of their arguments as pointers + (as is done in Fortran). + - It would in principle be possible to make a wrapper directly between + Fortran as for Lapack. However, apparently some versions of + MacOSX have a bug in the FORTRAN interface to SDOT + (). In addition, the cblas seems to be the only standard officially + endorsed by Apple. +*/ + +void WRAP_F77(acc_sdot)(const int *N, const float *X, const int *incX, + const float *Y, const int *incY, + float *result) +{ + *result = cblas_sdot(*N, X, *incX, Y, *incY); +} + +void WRAP_F77(acc_sdsdot)(const int *N, const float *alpha, + const float *X, const int *incX, + const float *Y, const int *incY, + float *result) +{ + *result = cblas_sdsdot(*N, *alpha, X, *incX, Y, *incY); +} + +void WRAP_F77(acc_sasum)(const int *N, const float *X, const int *incX, + float *result) +{ + *result = cblas_sasum(*N, X, *incX); +} + +void WRAP_F77(acc_snrm2)(const int *N, const float *X, const int *incX, + float *result) +{ + *result = cblas_snrm2(*N, X, *incX); +} + +void WRAP_F77(acc_scasum)(const int *N, const void *X, const int *incX, + float *result) +{ + *result = cblas_scasum(*N, X, *incX); +} + +void WRAP_F77(acc_scnrm2)(const int *N, const void *X, const int *incX, + float *result) +{ + *result = cblas_scnrm2(*N, X, *incX); +} diff --git a/pool/shard002/C/0063813_lfp_stringitem.c b/pool/shard002/C/0063813_lfp_stringitem.c new file mode 100644 index 0000000000000000000000000000000000000000..ab81410a39c0e46ee40308cd2cecc8e6d65bf062 --- /dev/null +++ b/pool/shard002/C/0063813_lfp_stringitem.c @@ -0,0 +1,227 @@ +/* + * + * + * Copyright 1990-2006 Sun Microsystems, Inc. All Rights Reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License version + * 2 only, 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 version 2 for more details (a copy is + * included at /legal/license.txt). + * + * You should have received a copy of the GNU General Public License + * version 2 along with this work; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA + * 02110-1301 USA + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa + * Clara, CA 95054 or visit www.sun.com if you need additional + * information or have any questions. + */ + +/** + * @file + * + * Cross platform functions for StringItem. + */ + + +#include + +#include +#include + +#include +#include +#include "lfp_intern_registry.h" + +#include + +/* cached field ids for Font class */ +static jfieldID _f_face_cache = NULL; +static jfieldID _f_style_cache = NULL; +static jfieldID _f_size_cache = NULL; + +#define _CACHE_FIELDID(HANDLE, name, type, cache) \ + ((cache)==NULL?((cache)=KNI_GetFieldID((HANDLE), (name), (type))):(cache)) + +/** + * KNI function that creates native resource for the current StringItem. + * + * Class: javax.microedition.lcdui.StringItemLFImpl + * + * Java prototype: + * private native int createNativeResource0(int ownerId, + * String label, int layout, String text, int maxSize, + * int constraints, String initialInputMode) + * + * INTERFACE (operand stack manipulation): + * parameters: ownerId id of the owner's native resource + * label StringItem's label + * layout StringItem's layout + * text StringItem's text + * appearanceMode the appearanceMode of StringItem + * font font to paint text + * returns: id of the created platform widget + */ +KNIEXPORT KNI_RETURNTYPE_INT +Java_javax_microedition_lcdui_StringItemLFImpl_createNativeResource0() { + MidpError err = KNI_OK; + MidpDisplayable *ownerPtr; + MidpItem *itemPtr = NULL; + pcsl_string label, text; + pcsl_string_status rc1 = PCSL_STRING_OK, rc2 = PCSL_STRING_OK; + PlatformFontPtr fontPtr = NULL; + int appearanceMode, layout; + + KNI_StartHandles(4); + + KNI_DeclareHandle(labelJString); + KNI_DeclareHandle(textJString); + KNI_DeclareHandle(fontJFont); + KNI_DeclareHandle(fontHandle); + + ownerPtr = (MidpDisplayable *)KNI_GetParameterAsInt(1); + KNI_GetParameterAsObject(2, labelJString); + layout = KNI_GetParameterAsInt(3); + KNI_GetParameterAsObject(4, textJString); + appearanceMode = KNI_GetParameterAsInt(5); + KNI_GetParameterAsObject(6, fontJFont); + + if (KNI_IsNullHandle(fontJFont) != KNI_TRUE) { + int face, style, size; + + KNI_FindClass("javax/microedition/lcdui/Font", fontHandle); + + face = KNI_GetIntField(fontJFont, _CACHE_FIELDID(fontHandle, "face", + "I", _f_face_cache)); + style = KNI_GetIntField(fontJFont, _CACHE_FIELDID(fontHandle, "style", + "I", _f_style_cache)); + size = KNI_GetIntField(fontJFont, _CACHE_FIELDID(fontHandle, "size", + "I", _f_size_cache)); + + err = lfpport_get_font(&fontPtr, face, style, size); + } + + if (err == KNI_OK) { + rc1 = midp_jstring_to_pcsl_string(labelJString, &label); + rc2 = midp_jstring_to_pcsl_string(textJString, &text); + } + + KNI_EndHandles(); + + if (err != KNI_OK || PCSL_STRING_OK != rc1 || PCSL_STRING_OK != rc2) { + err = KNI_ENOMEM; + goto cleanup; + } + + + itemPtr = MidpNewItem(ownerPtr, MIDP_PLAIN_STRING_ITEM_TYPE+appearanceMode); + if (itemPtr == NULL) { + err = KNI_ENOMEM; + goto cleanup; + } + + err = lfpport_stringitem_create(itemPtr, ownerPtr, &label, layout, + &text, fontPtr, appearanceMode); + + cleanup: + pcsl_string_free(&text); + pcsl_string_free(&label); + + if (err != KNI_OK) { + MidpDeleteItem(itemPtr); + KNI_ThrowNew(midpOutOfMemoryError, NULL); + } + + KNI_ReturnInt(itemPtr); +} + +/** + * KNI function that sets new content on the native resource corresponding to + * the current StringItem. + * + * Class: javax.microedition.lcdui.StringLFImpl + * Java prototype: + * private native int setContent0(int nativeId, Image image, altText, + * appearanceMode) + * + * INTERFACE (operand stack manipulation): + * parameters: nativeId pointer to the native resource of the StringItem + * text the new string set in the StringItem + * appearanceMode the appearance mode of the passed in text + * returns: + */ +KNIEXPORT KNI_RETURNTYPE_VOID +Java_javax_microedition_lcdui_StringItemLFImpl_setContent0() { + MidpError err = KNI_OK; + MidpItem *itemPtr = (MidpItem *)KNI_GetParameterAsInt(1); + int appearanceMode = KNI_GetParameterAsInt(3); + pcsl_string text; + pcsl_string_status rc; + + KNI_StartHandles(1); + KNI_DeclareHandle(textJString); + + KNI_GetParameterAsObject(2, textJString); + + rc = midp_jstring_to_pcsl_string(textJString, &text); + + KNI_EndHandles(); + + if (PCSL_STRING_OK != rc) { + err = KNI_ENOMEM; + } else { + err = lfpport_stringitem_set_content(itemPtr, &text, appearanceMode); + } + + pcsl_string_free(&text); + + if (err == KNI_ENOMEM) { + KNI_ThrowNew(midpOutOfMemoryError, NULL); + } + + KNI_ReturnVoid(); +} + +/** + * KNI function that sets new font on the native resource corresponding to + * the current StringItem. + * + * Class: javax.microedition.lcdui.StringLFImpl + * Java prototype: + * private native int setFont0(int nativeId, int face, int style, int size) + * + * INTERFACE (operand stack manipulation): + * parameters: id pointer to the native resource + * face face of the new font set in the StringItem + * style style of the new font set in the StringItem + * size size of the new font set in the StringItem + * returns: + */ +KNIEXPORT KNI_RETURNTYPE_VOID +Java_javax_microedition_lcdui_StringItemLFImpl_setFont0() { + MidpError err = KNI_OK; + PlatformFontPtr fontPtr; + MidpItem *itemPtr = (MidpItem *)KNI_GetParameterAsInt(1); + int face = KNI_GetParameterAsInt(2); + int style = KNI_GetParameterAsInt(3); + int size = KNI_GetParameterAsInt(4); + + err = lfpport_get_font(&fontPtr, face, style, size); + + if (err == KNI_OK) { + err = lfpport_stringitem_set_font(itemPtr, fontPtr); + } + + if (err == KNI_ENOMEM) { + KNI_ThrowNew(midpOutOfMemoryError, NULL); + } + + KNI_ReturnVoid(); +} diff --git a/pool/shard002/C/0063816_remquol.c b/pool/shard002/C/0063816_remquol.c new file mode 100644 index 0000000000000000000000000000000000000000..721231b4c02184e98dcb9ed21f3d4eb781995651 --- /dev/null +++ b/pool/shard002/C/0063816_remquol.c @@ -0,0 +1,193 @@ +/* origin: FreeBSD /usr/src/lib/msun/src/s_remquol.c */ +/*- + * ==================================================== + * Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved. + * + * Developed at SunSoft, a Sun Microsystems, Inc. business. + * Permission to use, copy, modify, and distribute this + * software is freely granted, provided that this notice + * is preserved. + * ==================================================== + */ + +#include "libm.h" + +#if LDBL_MANT_DIG == 53 && LDBL_MAX_EXP == 1024 +long double remquol(long double x, long double y, int *quo) +{ + return remquo(x, y, quo); +} +#elif (LDBL_MANT_DIG == 64 || LDBL_MANT_DIG == 113) && LDBL_MAX_EXP == 16384 + +#define BIAS (LDBL_MAX_EXP - 1) + +#if LDBL_MANL_SIZE > 32 +typedef uint64_t manl_t; +#else +typedef uint32_t manl_t; +#endif + +#if LDBL_MANH_SIZE > 32 +typedef uint64_t manh_t; +#else +typedef uint32_t manh_t; +#endif + +/* + * These macros add and remove an explicit integer bit in front of the + * fractional mantissa, if the architecture doesn't have such a bit by + * default already. + */ +#ifdef LDBL_IMPLICIT_NBIT +#define SET_NBIT(hx) ((hx) | (1ULL << LDBL_MANH_SIZE)) +#define HFRAC_BITS LDBL_MANH_SIZE +#else +#define SET_NBIT(hx) (hx) +#define HFRAC_BITS (LDBL_MANH_SIZE - 1) +#endif + +#define MANL_SHIFT (LDBL_MANL_SIZE - 1) + +static const long double Zero[] = {0.0, -0.0}; + +/* + * Return the IEEE remainder and set *quo to the last n bits of the + * quotient, rounded to the nearest integer. We choose n=31 because + * we wind up computing all the integer bits of the quotient anyway as + * a side-effect of computing the remainder by the shift and subtract + * method. In practice, this is far more bits than are needed to use + * remquo in reduction algorithms. + * + * Assumptions: + * - The low part of the mantissa fits in a manl_t exactly. + * - The high part of the mantissa fits in an int64_t with enough room + * for an explicit integer bit in front of the fractional bits. + */ +long double remquol(long double x, long double y, int *quo) +{ + union IEEEl2bits ux, uy; + int64_t hx,hz; /* We need a carry bit even if LDBL_MANH_SIZE is 32. */ + manh_t hy; + manl_t lx,ly,lz; + int ix,iy,n,q,sx,sxy; + + ux.e = x; + uy.e = y; + sx = ux.bits.sign; + sxy = sx ^ uy.bits.sign; + ux.bits.sign = 0; /* |x| */ + uy.bits.sign = 0; /* |y| */ + x = ux.e; + + /* purge off exception values */ + if ((uy.bits.exp|uy.bits.manh|uy.bits.manl)==0 || /* y=0 */ + (ux.bits.exp == BIAS + LDBL_MAX_EXP) || /* or x not finite */ + (uy.bits.exp == BIAS + LDBL_MAX_EXP && + ((uy.bits.manh&~LDBL_NBIT)|uy.bits.manl)!=0)) /* or y is NaN */ + return (x*y)/(x*y); + if (ux.bits.exp <= uy.bits.exp) { + if ((ux.bits.exp < uy.bits.exp) || + (ux.bits.manh <= uy.bits.manh && + (ux.bits.manh < uy.bits.manh || + ux.bits.manl < uy.bits.manl))) { + q = 0; + goto fixup; /* |x|<|y| return x or x-y */ + } + if (ux.bits.manh == uy.bits.manh && ux.bits.manl == uy.bits.manl) { + *quo = 1; + return Zero[sx]; /* |x|=|y| return x*0*/ + } + } + + /* determine ix = ilogb(x) */ + if (ux.bits.exp == 0) { /* subnormal x */ + ux.e *= 0x1.0p512; + ix = ux.bits.exp - (BIAS + 512); + } else { + ix = ux.bits.exp - BIAS; + } + + /* determine iy = ilogb(y) */ + if (uy.bits.exp == 0) { /* subnormal y */ + uy.e *= 0x1.0p512; + iy = uy.bits.exp - (BIAS + 512); + } else { + iy = uy.bits.exp - BIAS; + } + + /* set up {hx,lx}, {hy,ly} and align y to x */ + hx = SET_NBIT(ux.bits.manh); + hy = SET_NBIT(uy.bits.manh); + lx = ux.bits.manl; + ly = uy.bits.manl; + + /* fix point fmod */ + n = ix - iy; + q = 0; + + while (n--) { + hz = hx - hy; + lz = lx - ly; + if (lx < ly) + hz -= 1; + if (hz < 0) { + hx = hx + hx + (lx>>MANL_SHIFT); + lx = lx + lx; + } else { + hx = hz + hz + (lz>>MANL_SHIFT); + lx = lz + lz; + q++; + } + q <<= 1; + } + hz = hx - hy; + lz = lx - ly; + if (lx < ly) + hz -= 1; + if (hz >= 0) { + hx = hz; + lx = lz; + q++; + } + + /* convert back to floating value and restore the sign */ + if ((hx|lx) == 0) { /* return sign(x)*0 */ + *quo = sxy ? -q : q; + return Zero[sx]; + } + while (hx < (1ULL<>MANL_SHIFT); + lx = lx + lx; + iy -= 1; + } + ux.bits.manh = hx; /* The integer bit is truncated here if needed. */ + ux.bits.manl = lx; + if (iy < LDBL_MIN_EXP) { + ux.bits.exp = iy + (BIAS + 512); + ux.e *= 0x1p-512; + } else { + ux.bits.exp = iy + BIAS; + } + ux.bits.sign = 0; + x = ux.e; +fixup: + y = fabsl(y); + if (y < LDBL_MIN * 2) { + if (x + x > y || (x + x == y && (q & 1))) { + q++; + x-=y; + } + } else if (x > 0.5*y || (x == 0.5*y && (q & 1))) { + q++; + x-=y; + } + + ux.e = x; + ux.bits.sign ^= sx; + x = ux.e; + + q &= 0x7fffffff; + *quo = sxy ? -q : q; + return x; +} +#endif diff --git a/pool/shard002/C/0063825_testmmiotrace.c b/pool/shard002/C/0063825_testmmiotrace.c new file mode 100644 index 0000000000000000000000000000000000000000..1f7176b28de936e14f5817ec08cd9c406f03c1ed --- /dev/null +++ b/pool/shard002/C/0063825_testmmiotrace.c @@ -0,0 +1,134 @@ +/* + * Written by Pekka Paalanen, 2008-2009 + */ + +#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt + +#include +#include +#include + +static unsigned long mmio_address; +module_param(mmio_address, ulong, 0); +MODULE_PARM_DESC(mmio_address, " Start address of the mapping of 16 kB " + "(or 8 MB if read_far is non-zero)."); + +static unsigned long read_far = 0x400100; +module_param(read_far, ulong, 0); +MODULE_PARM_DESC(read_far, " Offset of a 32-bit read within 8 MB " + "(default: 0x400100)."); + +static unsigned v16(unsigned i) +{ + return i * 12 + 7; +} + +static unsigned v32(unsigned i) +{ + return i * 212371 + 13; +} + +static void do_write_test(void __iomem *p) +{ + unsigned int i; + pr_info("write test.\n"); + mmiotrace_printk("Write test.\n"); + + for (i = 0; i < 256; i++) + iowrite8(i, p + i); + + for (i = 1024; i < (5 * 1024); i += 2) + iowrite16(v16(i), p + i); + + for (i = (5 * 1024); i < (16 * 1024); i += 4) + iowrite32(v32(i), p + i); +} + +static void do_read_test(void __iomem *p) +{ + unsigned int i; + unsigned errs[3] = { 0 }; + pr_info("read test.\n"); + mmiotrace_printk("Read test.\n"); + + for (i = 0; i < 256; i++) + if (ioread8(p + i) != i) + ++errs[0]; + + for (i = 1024; i < (5 * 1024); i += 2) + if (ioread16(p + i) != v16(i)) + ++errs[1]; + + for (i = (5 * 1024); i < (16 * 1024); i += 4) + if (ioread32(p + i) != v32(i)) + ++errs[2]; + + mmiotrace_printk("Read errors: 8-bit %d, 16-bit %d, 32-bit %d.\n", + errs[0], errs[1], errs[2]); +} + +static void do_read_far_test(void __iomem *p) +{ + pr_info("read far test.\n"); + mmiotrace_printk("Read far test.\n"); + + ioread32(p + read_far); +} + +static void do_test(unsigned long size) +{ + void __iomem *p = ioremap_nocache(mmio_address, size); + if (!p) { + pr_err("could not ioremap, aborting.\n"); + return; + } + mmiotrace_printk("ioremap returned %p.\n", p); + do_write_test(p); + do_read_test(p); + if (read_far && read_far < size - 4) + do_read_far_test(p); + iounmap(p); +} + +static void do_test_bulk_ioremapping(void) +{ + void __iomem *p; + int i; + + for (i = 0; i < 10; ++i) { + p = ioremap_nocache(mmio_address, PAGE_SIZE); + if (p) + iounmap(p); + } + + + synchronize_rcu(); +} + +static int __init init(void) +{ + unsigned long size = (read_far) ? (8 << 20) : (16 << 10); + + if (mmio_address == 0) { + pr_err("you have to use the module argument mmio_address.\n"); + pr_err("DO NOT LOAD THIS MODULE UNLESS YOU REALLY KNOW WHAT YOU ARE DOING!\n"); + return -ENXIO; + } + + pr_warning("WARNING: mapping %lu kB @ 0x%08lx in PCI address space, " + "and writing 16 kB of rubbish in there.\n", + size >> 10, mmio_address); + do_test(size); + do_test_bulk_ioremapping(); + pr_info("All done.\n"); + return 0; +} + +static void __exit cleanup(void) +{ + pr_debug("unloaded.\n"); +} + +module_init(init); +module_exit(cleanup); +MODULE_LICENSE("GPL"); diff --git a/pool/shard002/C/0063830_ext2initrd.c b/pool/shard002/C/0063830_ext2initrd.c new file mode 100644 index 0000000000000000000000000000000000000000..5e5ad29cb90f378242f962d8b9f0f9184b204291 --- /dev/null +++ b/pool/shard002/C/0063830_ext2initrd.c @@ -0,0 +1,280 @@ +/* febootstrap-supermin-helper reimplementation in C. + * Copyright (C) 2009-2012 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., 675 Mass Ave, Cambridge, MA 02139, USA. + */ + +/* ext2 requires a small initrd in order to boot. This builds it. */ + +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +#include "error.h" +#include "full-write.h" +#include "xalloc.h" +#include "xvasprintf.h" + +#include "helper.h" +#include "ext2internal.h" + +static void read_module_deps (const char *modpath); +static void free_module_deps (void); +static void add_module_dep (const char *name, const char *dep); +static struct module * add_module (const char *name); +static struct module * find_module (const char *name); +static void print_module_load_order (FILE *f, FILE *pp, struct module *m); + +/* The init binary. */ +extern char _binary_init_start, _binary_init_end, _binary_init_size; + +/* The list of modules (wildcards) we consider for inclusion in the + * mini initrd. Only what is needed in order to find a device with an + * ext2 filesystem on it. + */ +static const char *kmods[] = { + "ext2.ko*", + "ext4.ko*", /* CONFIG_EXT4_USE_FOR_EXT23=y option might be set */ + "virtio*.ko*", + "ide*.ko*", + "libata*.ko*", + "piix*.ko*", + "scsi_transport_spi.ko*", + "scsi_mod.ko*", + "sd_mod.ko*", + "sym53c8xx.ko*", + "ata_piix.ko*", + "sr_mod.ko*", + "mbcache.ko*", + "crc*.ko*", + "libcrc*.ko*", + "ibmvscsic.ko*", + NULL +}; + +/* Module dependencies. */ +struct module { + struct module *next; + struct moddep *deps; + char *name; + int visited; +}; +struct module *modules = NULL; + +struct moddep { + struct moddep *next; + struct module *dep; +}; + +void +ext2_make_initrd (const char *modpath, const char *initrd) +{ + char dir[] = "/tmp/ext2initrdXXXXXX"; + if (mkdtemp (dir) == NULL) + error (EXIT_FAILURE, errno, "mkdtemp"); + + read_module_deps (modpath); + add_module (""); + int i; + struct module *m; + for (i = 0; kmods[i] != NULL; ++i) { + for (m = modules; m; m = m->next) { + char *n = strrchr (m->name, '/'); + if (n) + n += 1; + else + n = m->name; + if (fnmatch (kmods[i], n, FNM_PATHNAME) == 0) { + if (verbose >= 2) + fprintf (stderr, "Adding top-level dependency %s (%s)\n", m->name, kmods[i]); + add_module_dep ("", m->name); + } + } + } + + char *cmd = xasprintf ("cd %s; xargs cp -t %s", modpath, dir); + char *outfile = xasprintf ("%s/modules", dir); + if (verbose >= 2) fprintf (stderr, "writing to %s\n", cmd); + + FILE *f = fopen (outfile, "w"); + if (f == NULL) + error (EXIT_FAILURE, errno, "failed to create modules list (%s)", outfile); + free (outfile); + FILE *pp = popen (cmd, "w"); + if (pp == NULL) + error (EXIT_FAILURE, errno, "failed to create pipe (%s)", cmd); + + /* The "pseudo" module depends on all modules matched by the contents of kmods */ + struct module *pseudo = find_module (""); + print_module_load_order (pp, f, pseudo); + fclose (pp); + pclose (f); + + free (cmd); + free_module_deps (); + + /* Copy in the init program, linked into this program as a data blob. */ + char *init = xasprintf ("%s/init", dir); + int fd = open (init, O_WRONLY|O_TRUNC|O_CREAT|O_NOCTTY, 0755); + if (fd == -1) + error (EXIT_FAILURE, errno, "open: %s", init); + + size_t n = (size_t) &_binary_init_size; + if (full_write (fd, &_binary_init_start, n) != n) + error (EXIT_FAILURE, errno, "write: %s", init); + + if (close (fd) == -1) + error (EXIT_FAILURE, errno, "close: %s", init); + + free (init); + + /* Build the cpio file. */ + cmd = xasprintf ("(cd %s && (echo . ; ls -1)" + " | cpio --quiet -o -H newc) > '%s'", + dir, initrd); + if (verbose >= 2) fprintf (stderr, "%s\n", cmd); + int r = system (cmd); + if (r == -1 || WEXITSTATUS (r) != 0) + error (EXIT_FAILURE, 0, "ext2_make_initrd: cpio failed"); + free (cmd); + + /* Construction of 'dir' above ensures this is safe. */ + cmd = xasprintf ("rm -rf %s", dir); + if (verbose >= 2) fprintf (stderr, "%s\n", cmd); + system (cmd); + free (cmd); +} + +static void +free_module_deps (void) +{ + /* Short-lived program, don't bother to free it. */ + modules = NULL; +} + +/* Read modules.dep into internal structure. */ +static void +read_module_deps (const char *modpath) +{ + free_module_deps (); + + char *filename = xasprintf ("%s/modules.dep", modpath); + FILE *fp = fopen (filename, "r"); + free (filename); + if (fp == NULL) + error (EXIT_FAILURE, errno, "open: %s/modules.dep", modpath); + + char *line = NULL; + size_t llen = 0; + ssize_t len; + while ((len = getline (&line, &llen, fp)) != -1) { + if (len > 0 && line[len-1] == '\n') + line[--len] = '\0'; + + char *name = strtok (line, ": "); + if (!name) continue; + + add_module (name); + char *dep; + while ((dep = strtok (NULL, " ")) != NULL) { + add_module_dep (name, dep); + } + } + + free (line); + fclose (fp); +} + +static struct module * +add_module (const char *name) +{ + struct module *m = find_module (name); + if (m) + return m; + m = xmalloc (sizeof *m); + m->name = xstrdup (name); + m->deps = NULL; + m->next = modules; + m->visited = 0; + modules = m; + return m; +} + +static struct module * +find_module (const char *name) +{ + struct module *m; + for (m = modules; m; m = m->next) { + if (strcmp (name, m->name) == 0) + break; + } + return m; +} + +/* Module 'name' requires 'dep' to be loaded first. */ +static void +add_module_dep (const char *name, const char *dep) +{ + if (verbose >= 2) fprintf (stderr, "add_module_dep %s: %s\n", name, dep); + struct module *m1 = add_module (name); + struct module *m2 = add_module (dep); + struct moddep *d; + for (d = m1->deps; d; d = d->next) { + if (d->dep == m2) + return; + } + d = xmalloc (sizeof *d); + d->next = m1->deps; + d->dep = m2; + m1->deps = d; + return; +} + +/* DFS on the dependency graph */ +static void +print_module_load_order (FILE *pipe, FILE *list, struct module *m) +{ + if (m->visited) + return; + + struct moddep *d; + for (d = m->deps; d; d = d->next) + print_module_load_order (pipe, list, d->dep); + + if (m->name[0] == 0) + return; + + char *basename = strrchr (m->name, '/'); + if (basename) + ++basename; + else + basename = m->name; + + fputs (m->name, pipe); + fputc ('\n', pipe); + fputs (basename, list); + fputc ('\n', list); + m->visited = 1; + + if (verbose >= 2) + fprintf (stderr, "print_module_load_order: %s %s\n", m->name, basename); +} diff --git a/pool/shard002/C/0063832_timer.c b/pool/shard002/C/0063832_timer.c new file mode 100644 index 0000000000000000000000000000000000000000..57dfb336575255186d6cd07670249ab5b945289b --- /dev/null +++ b/pool/shard002/C/0063832_timer.c @@ -0,0 +1,119 @@ +/*************************************************************************** + * Copyright (C) 2010 + * by Dimok + * + * This software is provided 'as-is', without any express or implied + * warranty. In no event will the authors be held liable for any + * damages arising from the use of this software. + * + * Permission is granted to anyone to use this software for any + * purpose, including commercial applications, and to alter it and + * redistribute it freely, subject to the following restrictions: + * + * 1. The origin of this software must not be misrepresented; you + * must not claim that you wrote the original software. If you use + * this software in a product, an acknowledgment in the product + * documentation would be appreciated but is not required. + * + * 2. Altered source versions must be plainly marked as such, and + * must not be misrepresented as being the original software. + * + * 3. This notice may not be removed or altered from any source + * distribution. + * + * for WiiXplorer 2010 + ***************************************************************************/ +#include +#include +#include "timer.h" + +bool TimePassed(int limit) +{ + static time_t starttime = 0; + time_t timer = time(NULL); + + if (starttime == 0) + starttime = timer; + + if(difftime(timer, starttime) >= limit) + { + starttime = 0; + return true; + } + + return false; +} + +#define PERIOD_4 (4 * 365 + 1) +#define PERIOD_100 (PERIOD_4 * 25 - 1) +#define PERIOD_400 (PERIOD_100 * 4 + 1) +void ConvertNTFSDate(u64 ulNTFSDate, TimeStruct * ptm) +{ + unsigned year, mon, day, hour, min, sec; + u64 v64 = ulNTFSDate; + u8 ms[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; + unsigned temp; + u32 v; + v64 /= 10000000; + sec = (unsigned)(v64 % 60); + v64 /= 60; + min = (unsigned)(v64 % 60); + v64 /= 60; + hour = (unsigned)(v64 % 24)+1; + v64 /= 24; + + v = (u32)v64; + + year = (unsigned)(1601 + v / PERIOD_400 * 400); + v %= PERIOD_400; + + temp = (unsigned)(v / PERIOD_100); + if (temp == 4) + temp = 3; + year += temp * 100; + v -= temp * PERIOD_100; + + temp = v / PERIOD_4; + if (temp == 25) + temp = 24; + year += temp * 4; + v -= temp * PERIOD_4; + + temp = v / 365; + if (temp == 4) + temp = 3; + year += temp; + v -= temp * 365; + + if (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)) + ms[1] = 29; + for (mon = 1; mon <= 12; mon++) + { + unsigned s = ms[mon - 1]; + if (v < s) + break; + v -= s; + } + day = (unsigned)v + 1; + + ptm->tm_mday = (u32)day; + ptm->tm_mon = (u32)mon; + ptm->tm_year = (u32)year; + + ptm->tm_hour = (u32)hour; + ptm->tm_min = (u32)min; + ptm->tm_sec = (u32)sec; +} + +void ConvertDosDate(u64 ulDosDate, TimeStruct * ptm) +{ + u32 uDate; + uDate = (u32)(ulDosDate>>16); + ptm->tm_mday = (u32)(uDate&0x1f) ; + ptm->tm_mon = (u32)((((uDate)&0x1E0)/0x20)) ; + ptm->tm_year = (u32)(((uDate&0x0FE00)/0x0200)+1980) ; + + ptm->tm_hour = (u32) ((ulDosDate &0xF800)/0x800); + ptm->tm_min = (u32) ((ulDosDate&0x7E0)/0x20) ; + ptm->tm_sec = (u32) (2*(ulDosDate&0x1f)) ; +} diff --git a/pool/shard002/C/0063833_cpu.c b/pool/shard002/C/0063833_cpu.c new file mode 100644 index 0000000000000000000000000000000000000000..ab5cafc4e371628d55bd1da3885a53afc49b8da2 --- /dev/null +++ b/pool/shard002/C/0063833_cpu.c @@ -0,0 +1,122 @@ +/* + * arch/arm/mach-meson6/cpu.c + * + * Copyright (C) 2011-2012 Amlogic, 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 +#include + +extern void meson6_l2x0_init(void __iomem *); + +#ifdef CONFIG_MESON_L2CC_OPTIMIZE +static inline u32 __init read_actlr(void) +{ + u32 actlr; + + __asm__("mrc p15, 0, %0, c1, c0, 1\n" : "=r" (actlr)); + printk(KERN_INFO "===actlr=0x%x\n", actlr); + return actlr; +} + +static inline void __init write_actlr(u32 actlr) +{ + __asm__("mcr p15, 0, %0, c1, c0, 1\n" : : "r" (actlr)); +} +#endif + + +static void __init meson_cache_init(void) +{ +#ifdef CONFIG_CACHE_L2X0 + __u32 prefetch, aux; + void __iomem *l2x0_base; + /* + * Early BRESP, I/D prefetch enabled + * Shared attribute override enabled + * Full line of zero enabled + */ +// l2x0_init((void __iomem *)IO_PL310_BASE, ((1 << L2X0_AUX_CTRL_ASSOCIATIVITY_SHIFT) | +// (0x1 << 25) | +// (0x1 << L2X0_AUX_CTRL_NS_LOCKDOWN_SHIFT) | +// (0x1 << L2X0_AUX_CTRL_NS_INT_CTRL_SHIFT))|(0x2 << L2X0_AUX_CTRL_WAY_SIZE_SHIFT), L2X0_AUX_CTRL_MASK); +// (3<<28)|(3<<26) | (1<<11) |(1<<10)|(1<<13)|(1<<22), ~0); + + l2x0_base=(void __iomem *)IO_PL310_BASE; +#ifdef CONFIG_MESON_L2CC_OPTIMIZE + l2x0_init(l2x0_base, ((1< +#include +#include +#include +#include +#include +#include +#include +#include + +#include "src/common/libsbig/sbig.h" +#include "src/common/libutil/log.h" + +void show_eth (sbig_t *sb); +void show_usb (sbig_t *sb); +void show_lpt (sbig_t *sb); + +#define OPTIONS "h" +static const struct option longopts[] = { + {"help", no_argument, 0, 'h'}, + {0, 0, 0, 0}, +}; + +void usage (void) +{ + fprintf (stderr, +"Usage: sbig-find [eth] [usb] [lpt]\n" +); + exit (1); +} + +int main (int argc, char *argv[]) +{ + sbig_t *sb; + const char *sbig_udrv = getenv ("SBIG_UDRV"); + int e; + int ch; + int find_eth = 0; + int find_usb = 0; + int find_lpt = 0; + + log_init ("sbig-find"); + + while ((ch = getopt_long (argc, argv, OPTIONS, longopts, NULL)) != -1) { + switch (ch) { + case 'h': /* --help */ + default: + usage (); + } + } + if (optind == argc) { + find_eth = find_usb = find_lpt = 1; + } else { + while (optind < argc) { + if (!strcasecmp (argv[optind], "eth")) + find_eth = 1; + else if (!strcasecmp (argv[optind], "usb")) + find_usb = 1; + else if (!strcasecmp (argv[optind], "lpt")) + find_lpt = 1; + else + usage (); + optind++; + } + } + + if (!(sb = sbig_new ())) + err_exit ("sbig_new"); + if (sbig_dlopen (sb, sbig_udrv) != 0) + msg_exit ("%s", dlerror ()); + if ((e = sbig_open_driver (sb)) != 0) + msg_exit ("sbig_open_driver: %s", sbig_get_error_string (sb, e)); + + if (find_eth) + show_eth (sb); + if (find_usb) + show_usb (sb); + if (find_lpt) + show_lpt (sb); + + sbig_destroy (sb); + log_fini (); + return 0; +} + +void show_eth (sbig_t *sb) +{ + int i, e; + QueryEthernetResults devices; + + e = sbig_query_ethernet (sb, &devices); + if (e != CE_NO_ERROR) + msg_exit ("sbig_query_ethernet: %s", sbig_get_error_string (sb, e)); + for (i = 0; i < devices.camerasFound; i++) { + if (devices.ethernetInfo[i].cameraFound) + printf ("%lu.%lu.%lu.%lu: %s '%s' %s\n", + (devices.ethernetInfo[i].ipAddress >> 24) & 0xff, + (devices.ethernetInfo[i].ipAddress >> 16) & 0xff, + (devices.ethernetInfo[i].ipAddress >> 8) & 0xff, + devices.ethernetInfo[i].ipAddress & 0xff, + sbig_strcam (devices.ethernetInfo[i].cameraType), + devices.ethernetInfo[i].name, + devices.ethernetInfo[i].serialNumber); + } +} + +void show_usb (sbig_t *sb) +{ + int i, e; + QueryUSBResults devices; + + e = sbig_query_usb (sb, &devices); + if (e != CE_NO_ERROR) + msg_exit ("sbig_query_usb: %s", sbig_get_error_string (sb, e)); + for (i = 0; i < devices.camerasFound; i++) { + if (devices.usbInfo[i].cameraFound) + printf ("USB%d: %s '%s' %s\n", i + 1, + sbig_strcam (devices.usbInfo[i].cameraType), + devices.usbInfo[i].name, + devices.usbInfo[i].serialNumber); + } +} + +void show_device_info (sbig_t *sb, const char *device) +{ + sbig_ccd_t *ccd; + GetCCDInfoResults0 info0; + GetCCDInfoResults2 info2; + int e; + const char *serial = "serial-unknown"; + + if ((e = sbig_ccd_create (sb, CCD_IMAGING, &ccd))) + msg_exit ("sbig_ccd_create: %s", sbig_get_error_string (sb, e)); + e = sbig_ccd_get_info0 (ccd, &info0); + if (e != CE_NO_ERROR) + msg_exit ("sbig_ccd_get_info: %s", sbig_get_error_string (sb, e)); + e = sbig_ccd_get_info2 (ccd, &info2); + if (e == CE_NO_ERROR) + serial = info2.serialNumber; + printf ("%s: %s '%s' %s\n", device, + sbig_strcam (info0.cameraType), + info0.name, + serial); +} + +void show_lpt (sbig_t *sb) +{ + int i, e; + char device[8]; + CAMERA_TYPE type; + + for (i = 1; i <= 3; i++) { + snprintf (device, sizeof (device), "LPT%d", i); + + e = sbig_open_device (sb, device); + if (e != CE_NO_ERROR) + continue; + + e = sbig_establish_link (sb, &type); + if (e != CE_NO_ERROR) { + msg ("sbig_establish_link %s: %s", + device, sbig_get_error_string (sb, e)); + goto close_continue; + } + + show_device_info (sb, device); + +close_continue: + e = sbig_close_device (sb); + if (e != CE_NO_ERROR) { + msg ("sbig_close_device %s: %s", + device, sbig_get_error_string (sb, e)); + } + } +} + + +/* + * vi:tabstop=4 shiftwidth=4 expandtab + */ diff --git a/pool/shard002/C/0063856_strtol.c b/pool/shard002/C/0063856_strtol.c new file mode 100644 index 0000000000000000000000000000000000000000..c2f336b6ab70fd98433a9848b3334e1325139fd7 --- /dev/null +++ b/pool/shard002/C/0063856_strtol.c @@ -0,0 +1,83 @@ +/* + * strtol.c -- + * + * Source code for the "strtol" library procedure. + * + * Copyright (c) 1988 The Regents of the University of California. + * Copyright (c) 1994 Sun Microsystems, Inc. + * + * See the file "license.terms" for information on usage and redistribution + * of this file, and for a DISCLAIMER OF ALL WARRANTIES. + * + * RCS: @(#) $Id: strtol.c,v 1.2 1998/09/14 18:39:45 stanton Exp $ + */ + +#include + + +/* + *---------------------------------------------------------------------- + * + * strtol -- + * + * Convert an ASCII string into an integer. + * + * Results: + * The return value is the integer equivalent of string. If endPtr + * is non-NULL, then *endPtr is filled in with the character + * after the last one that was part of the integer. If string + * doesn't contain a valid integer value, then zero is returned + * and *endPtr is set to string. + * + * Side effects: + * None. + * + *---------------------------------------------------------------------- + */ + +long int +strtol(string, endPtr, base) + char *string; /* String of ASCII digits, possibly + * preceded by white space. For bases + * greater than 10, either lower- or + * upper-case digits may be used. + */ + char **endPtr; /* Where to store address of terminating + * character, or NULL. */ + int base; /* Base for conversion. Must be less + * than 37. If 0, then the base is chosen + * from the leading characters of string: + * "0x" means hex, "0" means octal, anything + * else means decimal. + */ +{ + register char *p; + int result; + + /* + * Skip any leading blanks. + */ + + p = string; + while (isspace(*p)) { + p += 1; + } + + /* + * Check for a sign. + */ + + if (*p == '-') { + p += 1; + result = -(strtoul(p, endPtr, base)); + } else { + if (*p == '+') { + p += 1; + } + result = strtoul(p, endPtr, base); + } + if ((result == 0) && (endPtr != 0) && (*endPtr == p)) { + *endPtr = string; + } + return result; +} diff --git a/pool/shard002/C/0063861_IsLongPresentPass.c b/pool/shard002/C/0063861_IsLongPresentPass.c new file mode 100644 index 0000000000000000000000000000000000000000..048f3678c0a9187c979d6341e2f8c8622ad142c6 --- /dev/null +++ b/pool/shard002/C/0063861_IsLongPresentPass.c @@ -0,0 +1,91 @@ +/* + * Copyright (C) 2006-2009 Daniel Prevost + * + * This file is part of Photon (photonsoftware.org). + * + * This file may be distributed and/or modified under the terms of the + * GNU General Public License version 2 or version 3 as published by the + * Free Software Foundation and appearing in the file COPYING.GPL2 and + * COPYING.GPL3 included in the packaging of this software. + * + * Licensees holding a valid Photon Commercial license can use this file + * in accordance with the terms of their license. + * + * This software is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. + */ + +/* --+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+-- */ + +#include "Common/Options.h" +#include "Tests/PrintError.h" + +const bool expectedToPass = true; + +/* --+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+-- */ + +int main() +{ + int errcode = 0; + char dummyArgs[100]; + char *dummyPtrs[10]; + psocOptionHandle handle; + bool gotIt, ok; + + struct psocOptStruct opts[5] = { + { '3', "three", 1, "", "repeat the loop three times" }, + { 'a', "address", 0, "QUASAR_ADDRESS", "tcp/ip port number of the server" }, + { 'x', "", 1, "DISPLAY", "X display to use" }, + { 'v', "verbose", 1, "", "try to explain what is going on" }, + { 'z', "zzz", 1, "", "go to sleep..." } + }; + + ok = psocSetSupportedOptions( 5, opts, &handle ); + if ( ok != true ) { + ERROR_EXIT( expectedToPass, NULL, ; ); + } + + strcpy( dummyArgs, "OptionTest2 --address 12345 -v --zzz" ); + /* 012345678901234567890123456789012345 */ + dummyPtrs[0] = dummyArgs; + dummyPtrs[1] = &dummyArgs[12]; + dummyPtrs[2] = &dummyArgs[22]; + dummyPtrs[3] = &dummyArgs[28]; + dummyPtrs[4] = &dummyArgs[31]; + + dummyArgs[11] = 0; + dummyArgs[21] = 0; + dummyArgs[27] = 0; + dummyArgs[30] = 0; + + errcode = psocValidateUserOptions( handle, 5, dummyPtrs, 1 ); + if ( errcode != 0 ) { + ERROR_EXIT( expectedToPass, NULL, ; ); + } + + /* Option is present */ + gotIt = psocIsLongOptPresent( handle, "address" ); + if ( ! gotIt ) { + ERROR_EXIT( expectedToPass, NULL, ; ); + } + + /* Option is absent */ + gotIt = psocIsLongOptPresent( handle, "three" ); + if ( gotIt ) { + ERROR_EXIT( expectedToPass, NULL, ; ); + } + + /* Unknown option */ + gotIt = psocIsLongOptPresent( handle, "zzaddress" ); + if ( gotIt ) { + ERROR_EXIT( expectedToPass, NULL, ; ); + } + + psocUnsetSupportedOptions( handle ); + + return 0; +} + +/* --+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+-- */ + diff --git a/pool/shard002/C/0063869_mcts.c b/pool/shard002/C/0063869_mcts.c new file mode 100644 index 0000000000000000000000000000000000000000..a15f51d8b3b18d4703b6cfbb4ba3ae0b9c413417 --- /dev/null +++ b/pool/shard002/C/0063869_mcts.c @@ -0,0 +1,206 @@ +#define _POSIX_C_SOURCE 1 + +#include +#include +#include +#include +#include +#include + +#include "mcts.h" + +void mc_run_random_playout(struct go_state *state) { + unsigned int rand_state = rand(); + + while (!state->scored) { + uint16_t all_moves[512]; + size_t num_moves; + go_moves_loose(state, all_moves, &num_moves); + + uint16_t move; + do { + move = all_moves[rand_r(&rand_state) % num_moves]; + } while (!go_legal(state, move)); + + go_play(state, move); + } +} + +struct mcts_tree *mcts_new(struct go_state *state) { + size_t num_moves; + uint16_t moves[512]; + go_moves(state, moves, &num_moves); + + struct mcts_tree *tree = malloc( + sizeof(struct mcts_tree) + + num_moves * sizeof(struct mcts_tree*) + ); + + if (!tree) { + return NULL; + } + + go_copy(state, &tree->state); + tree->num_playouts = 0; + tree->num_black_wins = 0; + tree->parent = NULL; + tree->num_moves = num_moves; + for (size_t i = 0; i < num_moves; i++) { + tree->moves[i] = moves[i]; + tree->subtrees[i] = NULL; + } + + return tree; +} + +struct mcts_tree *mcts_descend(struct mcts_tree *tree, uint16_t move) { + + for (size_t i = 0; i < tree->num_moves; i++) { + if (tree->moves[i] == move && tree->subtrees[i]) { + struct mcts_tree *subtree = tree->subtrees[i]; + subtree->parent = NULL; + tree->subtrees[i] = NULL; + mcts_free(tree); + return subtree; + } + } + + return NULL; +} + +void mcts_free(struct mcts_tree *tree) { + + if (!tree) { + return; + } + + assert(!tree->parent); + + for (size_t i = 0; i < tree->num_moves; i++) { + if (tree->subtrees[i]) { + tree->subtrees[i]->parent = NULL; + mcts_free(tree->subtrees[i]); + tree->subtrees[i] = NULL; + } + } + + free(tree); +} + +#define EXPAND_THRESHOLD 2 +#define OPTIMISM 10 + +void mcts_run_random_playout(struct mcts_tree *tree) { + unsigned int rand_state = rand(); + + // descend tree, choosing max UCT node at each level + size_t depth = 1; + while (1) { + + if (tree->num_playouts < EXPAND_THRESHOLD) { + break; + } + + if (tree->num_moves == 0) { + break; + } + + //double curr_wr = (double) tree->num_black_wins / tree->num_playouts; + + double best_uct = (tree->state.turn == GO_COLOR_BLACK) ? -100. : 100.; + struct mcts_tree *best_subtree = NULL; + for (size_t i = 0; i < tree->num_moves; i++) { + if (!tree->subtrees[i]) { + + // derive successor position + struct go_state sub_state; + go_copy(&tree->state, &sub_state); + go_play(&sub_state, tree->moves[i]); + + // expand + tree->subtrees[i] = mcts_new(&sub_state); + tree->subtrees[i]->parent = tree; + + // always choose newly-expanded nodes + best_subtree = tree->subtrees[i]; + break; + } + else { + struct mcts_tree *st = tree->subtrees[i]; + + double wr = (double) (st->num_black_wins + (tree->state.turn == GO_COLOR_BLACK) ? OPTIMISM : -OPTIMISM) / st->num_playouts; + double jitter = 0.001 * rand_r(&rand_state) / RAND_MAX; + wr += jitter; + double uct = wr; + + if (tree->state.turn == GO_COLOR_BLACK) { + // max node + if (uct > best_uct) { + best_uct = uct; + best_subtree = st; + } + } + else { + // min node + if (uct < best_uct) { + best_uct = uct; + best_subtree = st; + } + } + } + } + + assert(best_subtree != NULL); + tree = best_subtree; + depth++; + } + + // perform playout + struct go_state playout_state; + go_copy(&tree->state, &playout_state); + mc_run_random_playout(&playout_state); + + bool b_won = (playout_state.score - 5.5) > 0 ? true : false; + + // propagate back to root + while (tree) { + tree->num_playouts++; + if (b_won) { + tree->num_black_wins++; + } + + tree = tree->parent; + } +} + +uint16_t mcts_choose(struct mcts_tree *tree) { + unsigned int rand_state = rand(); + + double best_wr = (tree->state.turn == GO_COLOR_BLACK) ? -100. : 100.; + uint16_t best_move = 0; + for (size_t i = 0; i < tree->num_moves; i++) { + if (tree->subtrees[i]) { + struct mcts_tree *st = tree->subtrees[i]; + double wr = (double) (st->num_black_wins - (tree->state.turn == GO_COLOR_BLACK) ? OPTIMISM : -OPTIMISM) / st->num_playouts; + double jitter = 0.001 * rand_r(&rand_state) / RAND_MAX; + wr += jitter; + + if (tree->state.turn == GO_COLOR_BLACK) { + // max + if (wr > best_wr) { + best_wr = wr; + best_move = tree->moves[i]; + } + } + else { + // min + if (wr < best_wr) { + best_wr = wr; + best_move = tree->moves[i]; + } + } + } + } + + return best_move; +} diff --git a/pool/shard002/C/0063872_daemon_init.c b/pool/shard002/C/0063872_daemon_init.c new file mode 100644 index 0000000000000000000000000000000000000000..9edad1abf89eb4ba175e3f1996f7c40dade47312 --- /dev/null +++ b/pool/shard002/C/0063872_daemon_init.c @@ -0,0 +1,217 @@ +/* + * daemon_init.c - Part of AFD, an automatic file distribution program. + * Copyright (c) 1997 - 2014 Holger Kiehl + * + * 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., 675 Mass Ave, Cambridge, MA 02139, USA. + */ + +#include "afddefs.h" + +DESCR__S_M3 +/* + ** NAME + ** daemon_init - initialises the calling process as daemon + ** + ** SYNOPSIS + ** void daemon_init(char *process) + ** + ** DESCRIPTION + ** + ** RETURN VALUES + ** None. When it fails it will exit with INCORRECT. + ** + ** AUTHOR + ** H.Kiehl + ** + ** HISTORY + ** 07.06.1997 H.Kiehl Created + ** 22.05.1999 H.Kiehl Log everything from stdout and stderr. + ** + */ +DESCR__E_M3 + +#include +#include /* strerror(), strlen(), memset() */ +#include /* malloc(), free() */ +#include /* time() */ +#include +#include +#ifdef HAVE_FCNTL_H +# include +#endif +#include /* STDIN_FILENO, dup2() */ +#include + +/* External global variables. */ +extern char *p_work_dir; + +/* + * NOTE: Only define _CLOSE_STDIN if you are absolutly sure you do + * not need stdin. There are always some application (eg. IDL) + * that need stdin when called with the exec option. + */ + +/*############################ daemon_init() ############################*/ +void +daemon_init(char *process) +{ + pid_t pid; + + if ((pid = fork()) < 0) + { + (void)fprintf(stderr, _("fork() error : %s (%s %d)\n"), + strerror(errno), __FILE__, __LINE__); + exit(INCORRECT); + } + else if (pid != 0) + { + _exit(0); /* Parent process exits. */ + } + + if (setsid() == (pid_t)-1) + { + (void)fprintf(stderr, _("setsid() error : %s (%s %d)\n"), + strerror(errno), __FILE__, __LINE__); + exit(INCORRECT); + } + + if ((pid = fork()) < 0) + { + (void)fprintf(stderr, _("fork() error : %s (%s %d)\n"), + strerror(errno), __FILE__, __LINE__); + exit(INCORRECT); + } + else if (pid != 0) + { + _exit(0); /* Parent process exits. */ + } + + /* + * Redirect stdout and stderr to DAEMON_LOG.process. And redirect + * stdin to /dev/null. That way we are able to see if someone writes + * to stdout or stderr and will not hang if some process wants to read + * from stdin. + */ + if (process != NULL) + { + int fd, + mode; + time_t current_time; + size_t length; + char *buffer, + daemon_log[MAX_PATH_LENGTH]; + struct stat stat_buf; + + (void)snprintf(daemon_log, MAX_PATH_LENGTH, "%s%s", p_work_dir, LOG_DIR); + if (check_dir(daemon_log, R_OK | W_OK | X_OK) < 0) + { + (void)fprintf(stderr, _("Failed to create directory `%s' (%s %d)\n"), + daemon_log, __FILE__, __LINE__); + exit(INCORRECT); + } + (void)snprintf(daemon_log, MAX_PATH_LENGTH, "%s%s/DAEMON_LOG.%s", + p_work_dir, LOG_DIR, process); + if (stat(daemon_log, &stat_buf) == -1) + { + mode = O_CREAT | O_TRUNC | O_WRONLY; + } + else + { + if (stat_buf.st_size > 102400) + { + mode = O_CREAT | O_TRUNC | O_WRONLY; + } + else + { + mode = O_CREAT | O_APPEND | O_WRONLY; + } + } + /* if ((fd = coe_open(daemon_log, mode, FILE_MODE)) == -1) */ + if ((fd = coe_open(daemon_log, mode, (S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH))) == -1) + { + (void)fprintf(stderr, _("Failed to coe_open() `%s' : %s (%s %d)\n"), + daemon_log, strerror(errno), __FILE__, __LINE__); + exit(INCORRECT); + } + dup2(fd, STDERR_FILENO); + dup2(fd, STDOUT_FILENO); + if (close(fd) == -1) + { + (void)fprintf(stderr, _("close() error : %s (%s %d)\n"), + strerror(errno), __FILE__, __LINE__); + } +#ifdef _CLOSE_STDIN + (void)fclose(stdin); +#else + if ((fd = coe_open("/dev/null", O_RDONLY)) == -1) + { + (void)fprintf(stderr, + _("Failed to coe_open() /dev/null : %s (%s %d)\n"), + strerror(errno), __FILE__, __LINE__); + exit(INCORRECT); + } + dup2(fd, STDIN_FILENO); + if (close(fd) == -1) + { + (void)fprintf(stderr, _("close() error : %s (%s %d)\n"), + strerror(errno), __FILE__, __LINE__); + } +#endif + length = 35 + strlen(process); + if ((buffer = malloc(length + 1)) != NULL) + { + (void)memset(buffer, '=', length); + buffer[length] = '\0'; + current_time = time(NULL); + (void)fprintf(stderr, _("%s\n%.24s : Started %s\n"), + buffer, ctime(¤t_time), process); + (void)memset(buffer, '-', length); + (void)fprintf(stderr, "%s\n", buffer); + free(buffer); + } + } + else + { + (void)fclose(stdin); + (void)fclose(stdout); + (void)fclose(stderr); + } + + /* + * Hmm. For the daemon process to dump a core it needs to write + * access in the directory where the core gets dumped. + */ + if (p_work_dir != NULL) + { + if (chdir(p_work_dir) == -1) + { + (void)fprintf(stderr, + "Failed to change directory to `%s' : %s (%s %d)\n", + p_work_dir, strerror(errno), __FILE__, __LINE__); + } + } + else + { + if (chdir("/") == -1) + { + (void)fprintf(stderr, + "Failed to change directory to `/' : %s (%s %d)\n", + strerror(errno), __FILE__, __LINE__); + } + } + umask(0); + + return; +} diff --git a/pool/shard002/C/0063884_cyassl_MDK_ARM.c b/pool/shard002/C/0063884_cyassl_MDK_ARM.c new file mode 100644 index 0000000000000000000000000000000000000000..f0959de128f0cab8a157d3c543a425d96bb00984 --- /dev/null +++ b/pool/shard002/C/0063884_cyassl_MDK_ARM.c @@ -0,0 +1,201 @@ +/* cyassl_KEIL_RL.c + * + * Copyright (C) 2006-2013 wolfSSL Inc. + * + * This file is part of CyaSSL. + * + * CyaSSL 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. + * + * CyaSSL 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 + */ + + +/***************************************************************************************/ +/** This file is for defining functions for specific to KEIL-RL. **/ +/***************************************************************************************/ +#ifdef HAVE_CONFIG_H + #include +#endif + +#include + +#include +#include "cyassl_MDK_ARM.h" + +#include +#include + + +/** KEIL-RL TCPnet ****/ +/** TCPnet BSD socket does not have following functions. **/ + +char *inet_ntoa(struct in_addr in) +{ + #define NAMESIZE 16 + static char name[NAMESIZE] ; + sprintf(name, "%d.%d.%d.%d", (in.s_addr>>24)&0xff, (in.s_addr>>16)&0xff, (in.s_addr>>8)&0xff, in.s_addr&0xff) ; + return name ; +} + +unsigned long inet_addr(const char *cp) +{ + unsigned int a[4] ; unsigned long ret ; + sscanf(cp, "%d.%d.%d.%d", &a[0], &a[1], &a[2], &a[3]) ; + ret = ((a[3]<<24) + (a[2]<<16) + (a[1]<<8) + a[0]) ; + return(ret) ; +} + + +/*** tcp_connect is actually associated with following syassl_tcp_connect. ***/ +int Cyassl_connect(int sd, const struct sockaddr* sa, int sz) +{ + int ret = 0 ; + #if defined(CYASSL_KEIL_TCP_NET) + + SOCKADDR_IN addr ; + + addr = *(SOCKADDR_IN *)sa ; + + do { + #undef connect /* Go to KEIL TCPnet connect */ + ret = connect(sd, (SOCKADDR *)&addr, sizeof(addr)) ; + os_dly_wait(50); + } while(ret == SCK_EWOULDBLOCK) ; + #ifdef DEBUG_CYASSL + { + char msg[50] ; + sprintf(msg, "BSD Connect return code: %d\n", ret) ; + CYASSL_MSG(msg) ; + } + #endif + + #endif /* CYASSL_KEIL_TCP_NET */ + return(ret ) ; +} + + +int Cyassl_accept(int sd, struct sockaddr *addr, int *addrlen) +{ + int ret = 0 ; + + #if defined(CYASSL_KEIL_TCP_NET) + while(1) { + #undef accept /* Go to KEIL TCPnet accept */ + ret = accept(sd, addr, addrlen) ; + if(ret != SCK_EWOULDBLOCK) break ; + os_dly_wait(1); + } + #ifdef DEBUG_CYASSL + { + char msg[50] ; + sprintf(msg, "BSD Accept return code: %d\n", ret) ; + CYASSL_MSG(msg) ; + } + #endif + + #endif /* CYASSL_KEIL_TCP_NET */ + return(ret ) ; + +} + +int Cyassl_recv(int sd, void *buf, size_t len, int flags) +{ + int ret = 0; + #if defined(CYASSL_KEIL_TCP_NET) + while(1) { + #undef recv /* Go to KEIL TCPnet recv */ + ret = recv(sd, buf, len, flags) ; + if(ret != SCK_EWOULDBLOCK) break ; + os_dly_wait(1); + } + #ifdef DEBUG_CYASSL + { + char msg[50] ; + sprintf(msg, "BSD Recv return code: %d\n", ret) ; + CYASSL_MSG(msg) ; + } + #endif + + #endif /* CYASSL_KEIL_TCP_NET */ + return(ret ) ; +} + +int Cyassl_send(int sd, const void *buf, size_t len, int flags) +{ + int ret = 0 ; + + #if defined(CYASSL_KEIL_TCP_NET) + while(1) { + #undef send /* Go to KEIL TCPnet send */ + ret = send(sd, buf, len, flags) ; + if(ret != SCK_EWOULDBLOCK) break ; + os_dly_wait(1); + } + #ifdef DEBUG_CYASSL + { + char msg[50] ; + sprintf(msg, "BSD Send return code: %d\n", ret) ; + CYASSL_MSG(msg) ; + } + #endif + +#endif /* CYASSL_KEIL_TCP_NET */ + return(ret) ; + +} + +#if defined(CYASSL_KEIL_TCP_NET) +void Cyassl_sleep(int t) +{ + #if defined(HAVE_KEIL_RTX) + os_dly_wait(t/1000+1) ; + #endif +} + +int Cyassl_tcp_select(int sd, int timeout) +{ + + return 0 ; + +} +#endif + + +extern int getkey(void) ; +extern int sendchar(int c) ; + +char * Cyassl_fgets ( char * str, int num, FILE * f ) +{ + int i ; + + for(i = 0 ; i< num ; i++) { + while((str[i] = getkey()) == 0) ; + if(str[i] == '\n' || str[i] == '\012' || str[i] == '\015') { + sendchar('\n') ; + str[i++] = '\n' ; + str[i] = '\0' ; + break ; + } else if(str[i] == '\010') { /* BS */ + if(i) { /* erace one char */ + sendchar('\010') ; sendchar(' ') ; sendchar('\010') ; + i = (i>0 ? (i-2) : -1 ) ; + continue ; + } + } else if(str[i] == '\033' || str[i] == '\004' ) { /* ESC or ^D */ + str[i] = '\0' ; + return(0) ; + } + sendchar(str[i]) ; + } + return(str) ; +} diff --git a/pool/shard002/C/0063892_fuse_signals.c b/pool/shard002/C/0063892_fuse_signals.c new file mode 100644 index 0000000000000000000000000000000000000000..bf979563268b7dde9d2acaae597697718d0fd674 --- /dev/null +++ b/pool/shard002/C/0063892_fuse_signals.c @@ -0,0 +1,73 @@ +/* + FUSE: Filesystem in Userspace + Copyright (C) 2001-2007 Miklos Szeredi + + This program can be distributed under the terms of the GNU LGPLv2. + See the file COPYING.LIB +*/ + +#include "config.h" +#include "fuse_lowlevel.h" + +#include +#include +#include + +static struct fuse_session *fuse_instance; + +static void exit_handler(int sig) +{ + (void) sig; + if (fuse_instance) + fuse_session_exit(fuse_instance); +} + +static int set_one_signal_handler(int sig, void (*handler)(int)) +{ + struct sigaction sa; + struct sigaction old_sa; + + memset(&sa, 0, sizeof(struct sigaction)); + sa.sa_handler = handler; + sigemptyset(&(sa.sa_mask)); + sa.sa_flags = 0; + + if (sigaction(sig, NULL, &old_sa) == -1) { + perror("fuse: cannot get old signal handler"); + return -1; + } + + if (old_sa.sa_handler == SIG_DFL && + sigaction(sig, &sa, NULL) == -1) { + perror("fuse: cannot set signal handler"); + return -1; + } + return 0; +} + +int fuse_set_signal_handlers(struct fuse_session *se) +{ + if (set_one_signal_handler(SIGHUP, exit_handler) == -1 || + set_one_signal_handler(SIGINT, exit_handler) == -1 || + set_one_signal_handler(SIGTERM, exit_handler) == -1 || + set_one_signal_handler(SIGPIPE, SIG_IGN) == -1) + return -1; + + fuse_instance = se; + return 0; +} + +void fuse_remove_signal_handlers(struct fuse_session *se) +{ + if (fuse_instance != se) + fprintf(stderr, + "fuse: fuse_remove_signal_handlers: unknown session\n"); + else + fuse_instance = NULL; + + set_one_signal_handler(SIGHUP, SIG_DFL); + set_one_signal_handler(SIGINT, SIG_DFL); + set_one_signal_handler(SIGTERM, SIG_DFL); + set_one_signal_handler(SIGPIPE, SIG_DFL); +} + diff --git a/pool/shard002/C/0063897_td_ta_set_event.c b/pool/shard002/C/0063897_td_ta_set_event.c new file mode 100644 index 0000000000000000000000000000000000000000..fcafba542265ace8878ab8f64e37979f584ae160 --- /dev/null +++ b/pool/shard002/C/0063897_td_ta_set_event.c @@ -0,0 +1,77 @@ +/* Globally enable events. + Copyright (C) 1999,2001,2002,2003,2004 Free Software Foundation, Inc. + This file is part of the GNU C Library. + Contributed by Ulrich Drepper , 1999. + + 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, write to the Free + Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA + 02111-1307 USA. */ + +#include "thread_dbP.h" + + +td_err_e +td_ta_set_event (const td_thragent_t *ta_arg, td_thr_events_t *event) +{ + td_thragent_t *const ta = (td_thragent_t *) ta_arg; + td_err_e err; + psaddr_t eventmask = 0; + void *copy = NULL; + + LOG ("td_ta_set_event"); + + /* Test whether the TA parameter is ok. */ + if (! ta_ok (ta)) + return TD_BADTA; + + /* Fetch the old event mask from the inferior and modify it in place. */ + err = DB_GET_SYMBOL (eventmask, ta, __nptl_threads_events); + if (err == TD_OK) + err = DB_GET_STRUCT (copy, ta, eventmask, td_thr_events_t); + if (err == TD_OK) + { + uint32_t idx; + for (idx = 0; idx < TD_EVENTSIZE; ++idx) + { + psaddr_t word; + uint32_t mask; + err = DB_GET_FIELD_LOCAL (word, ta, copy, + td_thr_events_t, event_bits, idx); + if (err != TD_OK) + break; + mask = (uintptr_t) word; + mask |= event->event_bits[idx]; + word = (psaddr_t) (uintptr_t) mask; + err = DB_PUT_FIELD_LOCAL (ta, copy, + td_thr_events_t, event_bits, idx, word); + if (err != TD_OK) + break; + } + if (err == TD_NOAPLIC) + { + err = TD_OK; + while (idx < TD_EVENTSIZE) + if (event->event_bits[idx++] != 0) + { + err = TD_NOEVENT; + break; + } + } + if (err == TD_OK) + /* Now write it back to the inferior. */ + err = DB_PUT_STRUCT (ta, eventmask, td_thr_events_t, copy); + } + + return err; +} diff --git a/pool/shard002/C/0063918_extpdp.c b/pool/shard002/C/0063918_extpdp.c new file mode 100644 index 0000000000000000000000000000000000000000..79ee16e8b87c662a75703152211a68c96820047b --- /dev/null +++ b/pool/shard002/C/0063918_extpdp.c @@ -0,0 +1,64 @@ +#include +#include + +int main() +{ + int rt, ach, acl, dsp, pos, efi; + int result; + + ach = 0x05; + acl = 0xB4CB; + dsp = 0x07; + result = 0x000C; + + __asm + ("wrdsp %1, 0x01\n\t" + "mthi %2, $ac1\n\t" + "mtlo %3, $ac1\n\t" + "extpdp %0, $ac1, 0x03\n\t" + "rddsp %1\n\t" + : "=r"(rt), "+r"(dsp) + : "r"(ach), "r"(acl) + ); + pos = dsp & 0x3F; + efi = (dsp >> 14) & 0x01; + assert(pos == 3); + assert(efi == 0); + assert(result == rt); + + ach = 0x05; + acl = 0xB4CB; + dsp = 0x01; + + __asm + ("wrdsp %1, 0x01\n\t" + "mthi %2, $ac1\n\t" + "mtlo %3, $ac1\n\t" + "extpdp %0, $ac1, 0x03\n\t" + "rddsp %1\n\t" + : "=r"(rt), "+r"(dsp) + : "r"(ach), "r"(acl) + ); + efi = (dsp >> 14) & 0x01; + assert(efi == 1); + + + ach = 0; + acl = 0; + dsp = 0; + result = 0; + + __asm + ("wrdsp %1\n\t" + "mthi %2, $ac1\n\t" + "mtlo %3, $ac1\n\t" + "extpdp %0, $ac1, 0x00\n\t" + "rddsp %1\n\t" + : "=r"(rt), "+r"(dsp) + : "r"(ach), "r"(acl) + ); + assert(dsp == 0x3F); + assert(result == rt); + + return 0; +} diff --git a/pool/shard002/C/0063919_arch_memory_mapping.c b/pool/shard002/C/0063919_arch_memory_mapping.c new file mode 100644 index 0000000000000000000000000000000000000000..462f984a26bdaec414c2381cf2b758040098eb8b --- /dev/null +++ b/pool/shard002/C/0063919_arch_memory_mapping.c @@ -0,0 +1,277 @@ +/* + * i386 memory mapping + * + * Copyright Fujitsu, Corp. 2011, 2012 + * + * Authors: + * Wen Congyang + * + * This work is licensed under the terms of the GNU GPL, version 2 or later. + * See the COPYING file in the top-level directory. + * + */ + +#include "cpu.h" +#include "exec/cpu-all.h" +#include "sysemu/memory_mapping.h" + +/* PAE Paging or IA-32e Paging */ +static void walk_pte(MemoryMappingList *list, hwaddr pte_start_addr, + int32_t a20_mask, target_ulong start_line_addr) +{ + hwaddr pte_addr, start_paddr; + uint64_t pte; + target_ulong start_vaddr; + int i; + + for (i = 0; i < 512; i++) { + pte_addr = (pte_start_addr + i * 8) & a20_mask; + pte = ldq_phys(pte_addr); + if (!(pte & PG_PRESENT_MASK)) { + /* not present */ + continue; + } + + start_paddr = (pte & ~0xfff) & ~(0x1ULL << 63); + if (cpu_physical_memory_is_io(start_paddr)) { + /* I/O region */ + continue; + } + + start_vaddr = start_line_addr | ((i & 0x1ff) << 12); + memory_mapping_list_add_merge_sorted(list, start_paddr, + start_vaddr, 1 << 12); + } +} + +/* 32-bit Paging */ +static void walk_pte2(MemoryMappingList *list, + hwaddr pte_start_addr, int32_t a20_mask, + target_ulong start_line_addr) +{ + hwaddr pte_addr, start_paddr; + uint32_t pte; + target_ulong start_vaddr; + int i; + + for (i = 0; i < 1024; i++) { + pte_addr = (pte_start_addr + i * 4) & a20_mask; + pte = ldl_phys(pte_addr); + if (!(pte & PG_PRESENT_MASK)) { + /* not present */ + continue; + } + + start_paddr = pte & ~0xfff; + if (cpu_physical_memory_is_io(start_paddr)) { + /* I/O region */ + continue; + } + + start_vaddr = start_line_addr | ((i & 0x3ff) << 12); + memory_mapping_list_add_merge_sorted(list, start_paddr, + start_vaddr, 1 << 12); + } +} + +/* PAE Paging or IA-32e Paging */ +#define PLM4_ADDR_MASK 0xffffffffff000ULL /* selects bits 51:12 */ + +static void walk_pde(MemoryMappingList *list, hwaddr pde_start_addr, + int32_t a20_mask, target_ulong start_line_addr) +{ + hwaddr pde_addr, pte_start_addr, start_paddr; + uint64_t pde; + target_ulong line_addr, start_vaddr; + int i; + + for (i = 0; i < 512; i++) { + pde_addr = (pde_start_addr + i * 8) & a20_mask; + pde = ldq_phys(pde_addr); + if (!(pde & PG_PRESENT_MASK)) { + /* not present */ + continue; + } + + line_addr = start_line_addr | ((i & 0x1ff) << 21); + if (pde & PG_PSE_MASK) { + /* 2 MB page */ + start_paddr = (pde & ~0x1fffff) & ~(0x1ULL << 63); + if (cpu_physical_memory_is_io(start_paddr)) { + /* I/O region */ + continue; + } + start_vaddr = line_addr; + memory_mapping_list_add_merge_sorted(list, start_paddr, + start_vaddr, 1 << 21); + continue; + } + + pte_start_addr = (pde & PLM4_ADDR_MASK) & a20_mask; + walk_pte(list, pte_start_addr, a20_mask, line_addr); + } +} + +/* 32-bit Paging */ +static void walk_pde2(MemoryMappingList *list, + hwaddr pde_start_addr, int32_t a20_mask, + bool pse) +{ + hwaddr pde_addr, pte_start_addr, start_paddr, high_paddr; + uint32_t pde; + target_ulong line_addr, start_vaddr; + int i; + + for (i = 0; i < 1024; i++) { + pde_addr = (pde_start_addr + i * 4) & a20_mask; + pde = ldl_phys(pde_addr); + if (!(pde & PG_PRESENT_MASK)) { + /* not present */ + continue; + } + + line_addr = (((unsigned int)i & 0x3ff) << 22); + if ((pde & PG_PSE_MASK) && pse) { + /* + * 4 MB page: + * bits 39:32 are bits 20:13 of the PDE + * bit3 31:22 are bits 31:22 of the PDE + */ + high_paddr = ((hwaddr)(pde & 0x1fe000) << 19); + start_paddr = (pde & ~0x3fffff) | high_paddr; + if (cpu_physical_memory_is_io(start_paddr)) { + /* I/O region */ + continue; + } + start_vaddr = line_addr; + memory_mapping_list_add_merge_sorted(list, start_paddr, + start_vaddr, 1 << 22); + continue; + } + + pte_start_addr = (pde & ~0xfff) & a20_mask; + walk_pte2(list, pte_start_addr, a20_mask, line_addr); + } +} + +/* PAE Paging */ +static void walk_pdpe2(MemoryMappingList *list, + hwaddr pdpe_start_addr, int32_t a20_mask) +{ + hwaddr pdpe_addr, pde_start_addr; + uint64_t pdpe; + target_ulong line_addr; + int i; + + for (i = 0; i < 4; i++) { + pdpe_addr = (pdpe_start_addr + i * 8) & a20_mask; + pdpe = ldq_phys(pdpe_addr); + if (!(pdpe & PG_PRESENT_MASK)) { + /* not present */ + continue; + } + + line_addr = (((unsigned int)i & 0x3) << 30); + pde_start_addr = (pdpe & ~0xfff) & a20_mask; + walk_pde(list, pde_start_addr, a20_mask, line_addr); + } +} + +#ifdef TARGET_X86_64 +/* IA-32e Paging */ +static void walk_pdpe(MemoryMappingList *list, + hwaddr pdpe_start_addr, int32_t a20_mask, + target_ulong start_line_addr) +{ + hwaddr pdpe_addr, pde_start_addr, start_paddr; + uint64_t pdpe; + target_ulong line_addr, start_vaddr; + int i; + + for (i = 0; i < 512; i++) { + pdpe_addr = (pdpe_start_addr + i * 8) & a20_mask; + pdpe = ldq_phys(pdpe_addr); + if (!(pdpe & PG_PRESENT_MASK)) { + /* not present */ + continue; + } + + line_addr = start_line_addr | ((i & 0x1ffULL) << 30); + if (pdpe & PG_PSE_MASK) { + /* 1 GB page */ + start_paddr = (pdpe & ~0x3fffffff) & ~(0x1ULL << 63); + if (cpu_physical_memory_is_io(start_paddr)) { + /* I/O region */ + continue; + } + start_vaddr = line_addr; + memory_mapping_list_add_merge_sorted(list, start_paddr, + start_vaddr, 1 << 30); + continue; + } + + pde_start_addr = (pdpe & PLM4_ADDR_MASK) & a20_mask; + walk_pde(list, pde_start_addr, a20_mask, line_addr); + } +} + +/* IA-32e Paging */ +static void walk_pml4e(MemoryMappingList *list, + hwaddr pml4e_start_addr, int32_t a20_mask) +{ + hwaddr pml4e_addr, pdpe_start_addr; + uint64_t pml4e; + target_ulong line_addr; + int i; + + for (i = 0; i < 512; i++) { + pml4e_addr = (pml4e_start_addr + i * 8) & a20_mask; + pml4e = ldq_phys(pml4e_addr); + if (!(pml4e & PG_PRESENT_MASK)) { + /* not present */ + continue; + } + + line_addr = ((i & 0x1ffULL) << 39) | (0xffffULL << 48); + pdpe_start_addr = (pml4e & PLM4_ADDR_MASK) & a20_mask; + walk_pdpe(list, pdpe_start_addr, a20_mask, line_addr); + } +} +#endif + +void x86_cpu_get_memory_mapping(CPUState *cs, MemoryMappingList *list, + Error **errp) +{ + X86CPU *cpu = X86_CPU(cs); + CPUX86State *env = &cpu->env; + + if (!cpu_paging_enabled(cs)) { + /* paging is disabled */ + return; + } + + if (env->cr[4] & CR4_PAE_MASK) { +#ifdef TARGET_X86_64 + if (env->hflags & HF_LMA_MASK) { + hwaddr pml4e_addr; + + pml4e_addr = (env->cr[3] & PLM4_ADDR_MASK) & env->a20_mask; + walk_pml4e(list, pml4e_addr, env->a20_mask); + } else +#endif + { + hwaddr pdpe_addr; + + pdpe_addr = (env->cr[3] & ~0x1f) & env->a20_mask; + walk_pdpe2(list, pdpe_addr, env->a20_mask); + } + } else { + hwaddr pde_addr; + bool pse; + + pde_addr = (env->cr[3] & ~0xfff) & env->a20_mask; + pse = !!(env->cr[4] & CR4_PSE_MASK); + walk_pde2(list, pde_addr, env->a20_mask, pse); + } +} + diff --git a/pool/shard002/C/0063921_filters.c b/pool/shard002/C/0063921_filters.c new file mode 100644 index 0000000000000000000000000000000000000000..8a96d8c7ca39c1411d7eec76b82a2dbf6aa80423 --- /dev/null +++ b/pool/shard002/C/0063921_filters.c @@ -0,0 +1,220 @@ +/***************************************************************************** + * filters.c : audio output filters management + ***************************************************************************** + * Copyright (C) 2002-2007 VLC authors and VideoLAN + * $Id$ + * + * Authors: Christophe Massiot + * + * 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; 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 Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with this program; if not, write to the Free Software Foundation, + * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA. + *****************************************************************************/ + +/***************************************************************************** + * Preamble + *****************************************************************************/ +#ifdef HAVE_CONFIG_H +# include "config.h" +#endif + +#include + +#include +#include +#include + +#include +#include +#include +#include "aout_internal.h" +#include + +/***************************************************************************** + * FindFilter: find an audio filter for a specific transformation + *****************************************************************************/ +static filter_t * FindFilter( vlc_object_t *obj, + const audio_sample_format_t * p_input_format, + const audio_sample_format_t * p_output_format ) +{ + static const char typename[] = "audio filter"; + filter_t * p_filter; + + p_filter = vlc_custom_create( obj, sizeof(*p_filter), typename ); + + if ( p_filter == NULL ) return NULL; + + memcpy( &p_filter->fmt_in.audio, p_input_format, + sizeof(audio_sample_format_t) ); + p_filter->fmt_in.i_codec = p_input_format->i_format; + memcpy( &p_filter->fmt_out.audio, p_output_format, + sizeof(audio_sample_format_t) ); + p_filter->fmt_out.i_codec = p_output_format->i_format; + p_filter->p_owner = NULL; + + p_filter->p_module = module_need( p_filter, "audio filter", NULL, false ); + if ( p_filter->p_module == NULL ) + { + vlc_object_release( p_filter ); + return NULL; + } + + assert( p_filter->pf_audio_filter ); + return p_filter; +} + +/** + * Splits audio format conversion in two simpler conversions + * @return 0 on successful split, -1 if the input and output formats are too + * similar to split the conversion. + */ +static int SplitConversion( const audio_sample_format_t *restrict infmt, + const audio_sample_format_t *restrict outfmt, + audio_sample_format_t *midfmt ) +{ + *midfmt = *outfmt; + + if( infmt->i_rate != outfmt->i_rate ) + midfmt->i_rate = infmt->i_rate; + else + if( infmt->i_physical_channels != outfmt->i_physical_channels + || infmt->i_original_channels != outfmt->i_original_channels ) + { + midfmt->i_physical_channels = infmt->i_physical_channels; + midfmt->i_original_channels = infmt->i_original_channels; + } + else + { + assert( infmt->i_format != outfmt->i_format ); + if( AOUT_FMT_LINEAR( infmt ) ) + /* NOTE: Use S16N as intermediate. We have all conversions to S16N, + * and all useful conversions from S16N. TODO: FL32 if HAVE_FPU. */ + midfmt->i_format = VLC_CODEC_S16N; + else + if( AOUT_FMT_LINEAR( outfmt ) ) + /* NOTE: our non-linear -> linear filters always output 32-bits */ + midfmt->i_format = HAVE_FPU ? VLC_CODEC_FL32 : VLC_CODEC_FI32; + else + return -1; /* no indirect non-linear -> non-linear */ + } + + aout_FormatPrepare( midfmt ); + return AOUT_FMTS_IDENTICAL( infmt, midfmt ) ? -1 : 0; +} + +#undef aout_FiltersCreatePipeline +/** + * Allocates audio format conversion filters + * @param obj parent VLC object for new filters + * @param filters table of filters [IN/OUT] + * @param nb_filters pointer to the number of filters in the table [IN/OUT] + * @param infmt input audio format + * @param outfmt output audio format + * @return 0 on success, -1 on failure + */ +int aout_FiltersCreatePipeline( vlc_object_t *obj, + filter_t **filters, + int *nb_filters, + const audio_sample_format_t *restrict infmt, + const audio_sample_format_t *restrict outfmt ) +{ + audio_sample_format_t curfmt = *outfmt; + unsigned i = 0, max = *nb_filters - AOUT_MAX_FILTERS; + + filters += *nb_filters; + aout_FormatsPrint( obj, "filter(s)", infmt, outfmt ); + + while( !AOUT_FMTS_IDENTICAL( infmt, &curfmt ) ) + { + if( i >= max ) + { + msg_Err( obj, "max (%u) filters reached", AOUT_MAX_FILTERS ); + dialog_Fatal( obj, _("Audio filtering failed"), + _("The maximum number of filters (%u) was reached."), + AOUT_MAX_FILTERS ); + goto rollback; + } + + /* Make room and prepend a filter */ + memmove( filters + 1, filters, i * sizeof( *filters ) ); + + *filters = FindFilter( obj, infmt, &curfmt ); + if( *filters != NULL ) + { + i++; + break; /* done! */ + } + + audio_sample_format_t midfmt; + /* Split the conversion */ + if( SplitConversion( infmt, &curfmt, &midfmt ) ) + { + msg_Err( obj, "conversion pipeline failed: %4.4s -> %4.4s", + (const char *)&infmt->i_format, + (const char *)&outfmt->i_format ); + goto rollback; + } + + *filters = FindFilter( obj, &midfmt, &curfmt ); + if( *filters == NULL ) + { + msg_Err( obj, "cannot find filter for simple conversion" ); + goto rollback; + } + curfmt = midfmt; + i++; + } + + msg_Dbg( obj, "conversion pipeline completed" ); + *nb_filters += i; + return 0; + +rollback: + aout_FiltersDestroyPipeline( filters, i ); + return -1; +} + +/** + * Destroys a chain of audio filters. + */ +void aout_FiltersDestroyPipeline( filter_t *const *filters, unsigned n ) +{ + for( unsigned i = 0; i < n; i++ ) + { + filter_t *p_filter = filters[i]; + + module_unneed( p_filter, p_filter->p_module ); + free( p_filter->p_owner ); + vlc_object_release( p_filter ); + } +} + +/** + * Filters an audio buffer through a chain of filters. + */ +void aout_FiltersPlay( filter_t *const *pp_filters, + unsigned i_nb_filters, block_t ** pp_block ) +{ + block_t *p_block = *pp_block; + + /* TODO: use filter chain */ + for( unsigned i = 0; (i < i_nb_filters) && (p_block != NULL); i++ ) + { + filter_t * p_filter = pp_filters[i]; + + /* Please note that p_block->i_nb_samples & i_buffer + * shall be set by the filter plug-in. */ + p_block = p_filter->pf_audio_filter( p_filter, p_block ); + } + *pp_block = p_block; +} diff --git a/pool/shard002/C/0063939_CWE122_Heap_Based_Buffer_Overflow__c_CWE193_wchar_t_loop_44.c b/pool/shard002/C/0063939_CWE122_Heap_Based_Buffer_Overflow__c_CWE193_wchar_t_loop_44.c new file mode 100644 index 0000000000000000000000000000000000000000..8e941d25fc9464a979f9c3f848816b7c0ae5b5b6 --- /dev/null +++ b/pool/shard002/C/0063939_CWE122_Heap_Based_Buffer_Overflow__c_CWE193_wchar_t_loop_44.c @@ -0,0 +1,122 @@ +/* TEMPLATE GENERATED TESTCASE FILE +Filename: CWE122_Heap_Based_Buffer_Overflow__c_CWE193_wchar_t_loop_44.c +Label Definition File: CWE122_Heap_Based_Buffer_Overflow__c_CWE193.label.xml +Template File: sources-sink-44.tmpl.c +*/ +/* + * @description + * CWE: 122 Heap Based Buffer Overflow + * BadSource: Allocate memory for a string, but do not allocate space for NULL terminator + * GoodSource: Allocate enough memory for a string and the NULL terminator + * Sinks: loop + * BadSink : Copy array to data using a loop + * Flow Variant: 44 Data/control flow: data passed as an argument from one function to a function in the same source file called via a function pointer + * + * */ + +#include "std_testcase.h" + +#ifndef _WIN32 +#include +#endif + +/* MAINTENANCE NOTE: The length of this string should equal the 10 */ +#define SRC_STRING L"AAAAAAAAAA" + +#ifndef OMITBAD + +static void badSink(wchar_t * data) +{ + { + wchar_t source[10+1] = SRC_STRING; + size_t i, sourceLen; + sourceLen = wcslen(source); + /* Copy length + 1 to include NUL terminator from source */ + /* POTENTIAL FLAW: data may not have enough space to hold source */ + for (i = 0; i < sourceLen + 1; i++) + { + data[i] = source[i]; + } + printWLine(data); + free(data); + } +} + +void CWE122_Heap_Based_Buffer_Overflow__c_CWE193_wchar_t_loop_44_bad() +{ + wchar_t * data; + /* define a function pointer */ + void (*funcPtr) (wchar_t *) = badSink; + data = NULL; + /* FLAW: Did not leave space for a null terminator */ + data = (wchar_t *)malloc(10*sizeof(wchar_t)); + if (data == NULL) {exit(-1);} + /* use the function pointer */ + funcPtr(data); +} + +#endif /* OMITBAD */ + +#ifndef OMITGOOD + +/* goodG2B() uses the GoodSource with the BadSink */ +static void goodG2BSink(wchar_t * data) +{ + { + wchar_t source[10+1] = SRC_STRING; + size_t i, sourceLen; + sourceLen = wcslen(source); + /* Copy length + 1 to include NUL terminator from source */ + /* POTENTIAL FLAW: data may not have enough space to hold source */ + for (i = 0; i < sourceLen + 1; i++) + { + data[i] = source[i]; + } + printWLine(data); + free(data); + } +} + +static void goodG2B() +{ + wchar_t * data; + void (*funcPtr) (wchar_t *) = goodG2BSink; + data = NULL; + /* FIX: Allocate space for a null terminator */ + data = (wchar_t *)malloc((10+1)*sizeof(wchar_t)); + if (data == NULL) {exit(-1);} + funcPtr(data); +} + +void CWE122_Heap_Based_Buffer_Overflow__c_CWE193_wchar_t_loop_44_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_CWE193_wchar_t_loop_44_good(); + printLine("Finished good()"); +#endif /* OMITGOOD */ +#ifndef OMITBAD + printLine("Calling bad()..."); + CWE122_Heap_Based_Buffer_Overflow__c_CWE193_wchar_t_loop_44_bad(); + printLine("Finished bad()"); +#endif /* OMITBAD */ + return 0; +} + +#endif diff --git a/pool/shard002/C/0063943_spi_dev.c b/pool/shard002/C/0063943_spi_dev.c new file mode 100644 index 0000000000000000000000000000000000000000..5f55e243a0a47e9d6e11da4d967c02d7adbabb58 --- /dev/null +++ b/pool/shard002/C/0063943_spi_dev.c @@ -0,0 +1,274 @@ +#include "spi_main.h" +#include "spi_dev.h" +#include "spi_os.h" + +#ifdef SPI_FEATURE_SC8800G + +#elif defined SPI_FEATURE_OMAP4430 +#include +#include +#include +#include +#endif + +int spi_dev_gpio_mrdy = -1; +int spi_dev_gpio_srdy = -1; +int spi_dev_gpio_submrdy = -1; +int spi_dev_gpio_subsrdy = -1; + +#ifdef SPI_FEATURE_MASTER +int spi_is_restart = 0; +#endif + +#ifdef SPI_FEATURE_MASTER +static SPI_DEV_GPIOLEVEL_T _gpio_mrdy_state = SPI_DEV_GPIOLEVEL_LOW; +static SPI_DEV_GPIOLEVEL_T _gpio_submrdy_state = SPI_DEV_GPIOLEVEL_LOW; +#else +static SPI_DEV_GPIOLEVEL_T _gpio_srdy_state = SPI_DEV_GPIOLEVEL_LOW; +static SPI_DEV_GPIOLEVEL_T _gpio_subsrdy_state = SPI_DEV_GPIOLEVEL_LOW; +#endif + +/* +//init variables and status +*/ +#ifdef SPI_FEATURE_SC8800G +extern void _start_packet_tx_callback( void ); +extern void _start_packet_rx_callback( void ); +#endif + + +void spi_dev_init ( void * data) +{ +#ifdef SPI_FEATURE_SC8800G +{ + SPI_SLAVE_DEV dev; + SPI_OS_TRACE(("spi_dev_init \n")); + + spi_dev_gpio_mrdy = GPIO_PROD_APCP_MRDY; + spi_dev_gpio_srdy = GPIO_PROD_APCP_SRDY; + spi_dev_gpio_submrdy = GPIO_PROD_APCP_SubMRDY; + spi_dev_gpio_subsrdy = GPIO_PROD_APCP_SubSRDY; + + // Open SPI interface + dev.mode = 1; /* CPOL=0, CPHA=1 */ + dev.tx_bit_length = 32; /* Transmit data Length */ + dev.tx_callback = _start_packet_tx_callback; + dev.rx_callback = _start_packet_rx_callback; + SPI_SLAVE_HAL_Open(&dev); + + spi_dev_set_gpio ( spi_dev_gpio_srdy, SPI_DEV_GPIOLEVEL_LOW ); + spi_dev_set_gpio ( spi_dev_gpio_subsrdy, SPI_DEV_GPIOLEVEL_LOW ); +} +#elif defined SPI_FEATURE_OMAP4430 +{ + struct ipc_spi_platform_data * pdata; + + SPI_OS_TRACE(("spi_dev_init \n")); + + pdata = (struct ipc_spi_platform_data *) data; + + spi_dev_gpio_mrdy = (int) pdata->gpio_ipc_mrdy; + spi_dev_gpio_srdy = (int) pdata->gpio_ipc_srdy; + spi_dev_gpio_submrdy = (int) pdata->gpio_ipc_sub_mrdy; + spi_dev_gpio_subsrdy = (int) pdata->gpio_ipc_sub_srdy; + + spi_dev_set_gpio ( spi_dev_gpio_mrdy, SPI_DEV_GPIOLEVEL_LOW ); + if ( spi_is_restart == 0 ) + { + spi_dev_set_gpio ( spi_dev_gpio_submrdy, SPI_DEV_GPIOLEVEL_LOW ); + } +} +#endif +} + + +void spi_dev_destroy( void ) +{ +#if defined SPI_FEATURE_OMAP4430 + spi_dev_unreigster_irq_handler(spi_dev_gpio_srdy, 0); + spi_dev_unreigster_irq_handler(spi_dev_gpio_subsrdy, 0); +#endif +} + +int spi_dev_send ( void * buf, unsigned int length ) +{ +#ifdef SPI_FEATURE_SC8800G + uint32 spi_write_result = 0; + + spi_write_result = SPI_SLAVE_HAL_Write(buf, length); + + if ( spi_write_result == length ) + return 0; // success + else + { + SPI_OS_ERROR (("spi_dev_send fail length %d/%d\n", spi_write_result, length)); + return spi_write_result; // fail + } +#elif defined SPI_FEATURE_OMAP4430 + extern int ipc_spi_tx_rx_sync( u8 *tx_d, u8 *rx_d, unsigned len ); + int result; + + result = ipc_spi_tx_rx_sync (buf, 0, length); + return result; +#endif +} + + +int spi_dev_receive ( void * buf, unsigned int length) +{ +#ifdef SPI_FEATURE_SC8800G + uint32 spi_read_result = 0; + + spi_read_result = SPI_SLAVE_HAL_Read(buf, length); + + if ( spi_read_result == length ) + return 0; // success + else + { + SPI_OS_ERROR (("spi_dev_send faile length %d/%d\n", spi_read_result, length)); + return spi_read_result; // fail + } + +#elif defined SPI_FEATURE_OMAP4430 + extern int ipc_spi_tx_rx_sync( u8 *tx_d, u8 *rx_d, unsigned len ); + int value; + + value = ipc_spi_tx_rx_sync (0, buf, length); + + return value; +#endif +} + + +/* +//Param input gpio_id : number of gpio id +//Value : SPI_DEV_GPIOLEVEL_HIGH for raising pin state up +// : SPI_DEV_GPIOLEVEL_LOW for getting pin state down +*/ +void spi_dev_set_gpio ( int gpio_id, SPI_DEV_GPIOLEVEL_T value ) +{ + SPI_OS_TRACE_MID(("spi_dev_set_gpio: gpio_id =[%d], value =[%d]\n",gpio_id, (int) value)); + +#ifdef SPI_FEATURE_SC8800G +{ + unsigned char level = 0; + GPIO_CFG_INFO_T_PTR cfg_ptr = GPIO_PROD_GetCfgInfo ((GPIO_PROD_ID_E)gpio_id); + + switch (value) + { + case SPI_DEV_GPIOLEVEL_LOW : level = 0; break; + case SPI_DEV_GPIOLEVEL_HIGH : level = 1; break; + } + + GPIO_SetValue(cfg_ptr->gpio_num, level); +} +#elif defined SPI_FEATURE_OMAP4430 +{ + int level = 0; + + switch (value) + { + case SPI_DEV_GPIOLEVEL_LOW : level = 0; break; + case SPI_DEV_GPIOLEVEL_HIGH : level = 1; break; + } + + gpio_set_value ((unsigned int) gpio_id, level); +} +#endif +} + + +/* +// Log should be removed for loop +//Param input gpio_id : gpio pin id +//Return value SPI_DEV_GPIOLEVEL +*/ +SPI_DEV_GPIOLEVEL_T spi_dev_get_gpio(int gpio_id) +{ + SPI_DEV_GPIOLEVEL_T value = SPI_DEV_GPIOLEVEL_LOW; + int level; + +#ifdef SPI_FEATURE_SC8800G +{ + GPIO_CFG_INFO_T_PTR cfg_ptr = GPIO_PROD_GetCfgInfo ((GPIO_PROD_ID_E)gpio_id); + + level = GPIO_GetValue (cfg_ptr->gpio_num); + + switch (level) + { + case 0 : value = SPI_DEV_GPIOLEVEL_LOW; break; + case 1 : value = SPI_DEV_GPIOLEVEL_HIGH; break; + } +} +#elif defined SPI_FEATURE_OMAP4430 + level = gpio_get_value ((unsigned int) gpio_id); + + switch (level) + { + case 0 : value = SPI_DEV_GPIOLEVEL_LOW; break; + case 1 : value = SPI_DEV_GPIOLEVEL_HIGH; break; + } +#endif + + return value; +} + + +/* +//Param input gpio_id : gpio pin id + tigger : interrupt detection mode + handler : interrupt handler function +//Return value 0 : fail + 1 : success +*/ +int spi_dev_reigster_irq_handler (int gpio_id, SPI_DEV_IRQ_TRIGGER_T trigger, SPI_DEV_IRQ_HANDLER_T handler, char * name, void * data) +{ + int value; + +#ifdef SPI_FEATURE_SC8800G + value = GPIO_PROD_RegGpio( + (GPIO_PROD_ID_E)gpio_id, /* ID */ + SCI_FALSE, /* Direction, SCI_FALSE: Input dir; SCI_TRUE: output dir */ + SCI_FALSE, /* Default_value */ + SCI_FALSE, /* Shaking Enable */ + NULL, /* Shaking interval */ + (SPI_DEV_IRQ_HANDLER_T)handler /* the type of handler should be compatable with SPRD */ + ); + if ( value == SCI_FALSE ) + { + SPI_OS_ERROR(("spi_dev_reigster_irq_handler: registration fail\n")); + return 0; + } + +#elif defined SPI_FEATURE_OMAP4430 +{ + int _trigger = IRQF_TRIGGER_NONE; + + switch (trigger) + { + case SPI_DEV_IRQ_TRIGGER_RISING : _trigger = IRQF_TRIGGER_RISING; break; + case SPI_DEV_IRQ_TRIGGER_FALLING : _trigger = IRQF_TRIGGER_FALLING; break; + default : _trigger = IRQF_TRIGGER_NONE; break; + } + + value = request_irq (OMAP_GPIO_IRQ( gpio_id ), handler, _trigger, name, data); + if (value != 0) + { + SPI_OS_ERROR(("spi_dev_reigster_irq_handler: registration fail (err %d)\n", value)); + return 0; + } +} +#endif + return 1; +} + + +void spi_dev_unreigster_irq_handler (int gpio_id, void * data) +{ + +#ifdef SPI_FEATURE_SC8800G +#elif defined SPI_FEATURE_OMAP4430 + free_irq (OMAP_GPIO_IRQ( gpio_id ), data); +#endif +} + diff --git a/pool/shard002/C/0063946_lapacke_dormbr_work.c b/pool/shard002/C/0063946_lapacke_dormbr_work.c new file mode 100644 index 0000000000000000000000000000000000000000..5adbb0702be965e629d71e976417c259180a717b --- /dev/null +++ b/pool/shard002/C/0063946_lapacke_dormbr_work.c @@ -0,0 +1,111 @@ +/***************************************************************************** + Copyright (c) 2011, Intel Corp. + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + * Neither the name of Intel Corporation nor the names of its contributors + may be used to endorse or promote products derived from this software + without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE + LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + THE POSSIBILITY OF SUCH DAMAGE. +***************************************************************************** +* Contents: Native middle-level C interface to LAPACK function dormbr +* Author: Intel Corporation +* Generated November, 2011 +*****************************************************************************/ + +#include "lapacke.h" +#include "lapacke_utils.h" + +lapack_int LAPACKE_dormbr_work( int matrix_order, char vect, char side, + char trans, lapack_int m, lapack_int n, + lapack_int k, const double* a, lapack_int lda, + const double* tau, double* c, lapack_int ldc, + double* work, lapack_int lwork ) +{ + lapack_int info = 0; + if( matrix_order == LAPACK_COL_MAJOR ) { + /* Call LAPACK function and adjust info */ + LAPACK_dormbr( &vect, &side, &trans, &m, &n, &k, a, &lda, tau, c, &ldc, + work, &lwork, &info ); + if( info < 0 ) { + info = info - 1; + } + } else if( matrix_order == LAPACK_ROW_MAJOR ) { + lapack_int nq = LAPACKE_lsame( side, 'l' ) ? m : n; + lapack_int r = LAPACKE_lsame( vect, 'q' ) ? nq : MIN(nq,k); + lapack_int lda_t = MAX(1,r); + lapack_int ldc_t = MAX(1,m); + double* a_t = NULL; + double* c_t = NULL; + /* Check leading dimension(s) */ + if( lda < MIN(nq,k) ) { + info = -9; + LAPACKE_xerbla( "LAPACKE_dormbr_work", info ); + return info; + } + if( ldc < n ) { + info = -12; + LAPACKE_xerbla( "LAPACKE_dormbr_work", info ); + return info; + } + /* Query optimal working array(s) size if requested */ + if( lwork == -1 ) { + LAPACK_dormbr( &vect, &side, &trans, &m, &n, &k, a, &lda_t, tau, c, + &ldc_t, work, &lwork, &info ); + return (info < 0) ? (info - 1) : info; + } + /* Allocate memory for temporary array(s) */ + a_t = (double*) + LAPACKE_malloc( sizeof(double) * lda_t * MAX(1,MIN(nq,k)) ); + if( a_t == NULL ) { + info = LAPACK_TRANSPOSE_MEMORY_ERROR; + goto exit_level_0; + } + c_t = (double*)LAPACKE_malloc( sizeof(double) * ldc_t * MAX(1,n) ); + if( c_t == NULL ) { + info = LAPACK_TRANSPOSE_MEMORY_ERROR; + goto exit_level_1; + } + /* Transpose input matrices */ + LAPACKE_dge_trans( matrix_order, r, MIN(nq,k), a, lda, a_t, lda_t ); + LAPACKE_dge_trans( matrix_order, m, n, c, ldc, c_t, ldc_t ); + /* Call LAPACK function and adjust info */ + LAPACK_dormbr( &vect, &side, &trans, &m, &n, &k, a_t, &lda_t, tau, c_t, + &ldc_t, work, &lwork, &info ); + if( info < 0 ) { + info = info - 1; + } + /* Transpose output matrices */ + LAPACKE_dge_trans( LAPACK_COL_MAJOR, m, n, c_t, ldc_t, c, ldc ); + /* Release memory and exit */ + LAPACKE_free( c_t ); +exit_level_1: + LAPACKE_free( a_t ); +exit_level_0: + if( info == LAPACK_TRANSPOSE_MEMORY_ERROR ) { + LAPACKE_xerbla( "LAPACKE_dormbr_work", info ); + } + } else { + info = -1; + LAPACKE_xerbla( "LAPACKE_dormbr_work", info ); + } + return info; +} diff --git a/pool/shard002/C/0063957_tty_functions.c b/pool/shard002/C/0063957_tty_functions.c new file mode 100644 index 0000000000000000000000000000000000000000..726cc8a611a91127fd7234d12277d475f4a3a131 --- /dev/null +++ b/pool/shard002/C/0063957_tty_functions.c @@ -0,0 +1,89 @@ +/*************************************************************************\ +* Copyright (C) Michael Kerrisk, 2017. * +* * +* This program is free software. You may use, modify, and redistribute it * +* under the terms of the GNU Lesser General Public License as published * +* by the Free Software Foundation, either version 3 or (at your option) * +* any later version. This program is distributed without any warranty. * +* See the files COPYING.lgpl-v3 and COPYING.gpl-v3 for details. * +\*************************************************************************/ + +/* Listing 62-3 */ + +/* tty_functions.c + + Implement ttySetCbreak() and ttySetRaw(). +*/ +#include +#include +#include "tty_functions.h" /* Declares functions defined here */ + +/* Place terminal referred to by 'fd' in cbreak mode (noncanonical mode + with echoing turned off). This function assumes that the terminal is + currently in cooked mode (i.e., we shouldn't call it if the terminal + is currently in raw mode, since it does not undo all of the changes + made by the ttySetRaw() function below). Return 0 on success, or -1 + on error. If 'prevTermios' is non-NULL, then use the buffer to which + it points to return the previous terminal settings. */ + +int +ttySetCbreak(int fd, struct termios *prevTermios) +{ + struct termios t; + + if (tcgetattr(fd, &t) == -1) + return -1; + + if (prevTermios != NULL) + *prevTermios = t; + + t.c_lflag &= ~(ICANON | ECHO); + t.c_lflag |= ISIG; + + t.c_iflag &= ~ICRNL; + + t.c_cc[VMIN] = 1; /* Character-at-a-time input */ + t.c_cc[VTIME] = 0; /* with blocking */ + + if (tcsetattr(fd, TCSAFLUSH, &t) == -1) + return -1; + + return 0; +} + +/* Place terminal referred to by 'fd' in raw mode (noncanonical mode + with all input and output processing disabled). Return 0 on success, + or -1 on error. If 'prevTermios' is non-NULL, then use the buffer to + which it points to return the previous terminal settings. */ + +int +ttySetRaw(int fd, struct termios *prevTermios) +{ + struct termios t; + + if (tcgetattr(fd, &t) == -1) + return -1; + + if (prevTermios != NULL) + *prevTermios = t; + + t.c_lflag &= ~(ICANON | ISIG | IEXTEN | ECHO); + /* Noncanonical mode, disable signals, extended + input processing, and echoing */ + + t.c_iflag &= ~(BRKINT | ICRNL | IGNBRK | IGNCR | INLCR | + INPCK | ISTRIP | IXON | PARMRK); + /* Disable special handling of CR, NL, and BREAK. + No 8th-bit stripping or parity error handling. + Disable START/STOP output flow control. */ + + t.c_oflag &= ~OPOST; /* Disable all output processing */ + + t.c_cc[VMIN] = 1; /* Character-at-a-time input */ + t.c_cc[VTIME] = 0; /* with blocking */ + + if (tcsetattr(fd, TCSAFLUSH, &t) == -1) + return -1; + + return 0; +} diff --git a/pool/shard002/C/0063963_wcsdup.c b/pool/shard002/C/0063963_wcsdup.c new file mode 100644 index 0000000000000000000000000000000000000000..f5b3d5c3dab77b545aa1e341c63ac799d9d940c9 --- /dev/null +++ b/pool/shard002/C/0063963_wcsdup.c @@ -0,0 +1,56 @@ +/* + * Copyright(C) 2016 Davidson Francis + * + * This file is part of Nanvix. + * + * Nanvix 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. + * + * Nanvix 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 Nanvix. If not, see . + */ + +#include +#include +#include + +#if defined(_POSIX_C_SOURCE) || defined(_XOPEN_SOURCE) + +wchar_t *_wcsdup_r(struct _reent *p, const wchar_t *str) +{ + size_t len = wcslen (str) + 1; + wchar_t *copy = _malloc_r (p, len * sizeof (wchar_t)); + if (copy) + wmemcpy (copy, str, len); + return copy; +} + +#ifndef _REENT_ONLY + +/** + * @brief Duplicates a wide-character string. + * + * @details Returns a pointer to a new wide-character string, + * allocated as if by a call to malloc(), which is the duplicate + * of the wide-character string @p str. The returned pointer can + * be passed to free(). A null pointer is returned if the new + * wide-character string cannot be created. + * + * @return Returns a pointer to the newly allocated wide-character + * string. Otherwise, it returns a null pointer and set errno to + * indicate the error. + */ +wchar_t *wcsdup(const wchar_t *str) +{ + return _wcsdup_r (_REENT, str); +} + +#endif /* !_REENT_ONLY */ +#endif /* _POSIX_C_SOURCE || _XOPEN_SOURCE */ diff --git a/pool/shard002/C/0063971_exeslave.c b/pool/shard002/C/0063971_exeslave.c new file mode 100644 index 0000000000000000000000000000000000000000..884ca4af30a94cc4d29b73855e50179b0c939cdb --- /dev/null +++ b/pool/shard002/C/0063971_exeslave.c @@ -0,0 +1,88 @@ +unsigned long long num = 0; + +void Timer2_interrupt() iv IVT_INT_TIM2 { + TIM2_SR.UIF = 0; + num++; +} + +void PrintHandler(char c) { + UART1_Write(c); +} + +PCF_WrSingle(unsigned char wAddr, unsigned char wData) +{ + unsigned char buf[1]; + buf[0] = wData; + I2C3_Start(); + I2C3_Write(wAddr,buf,1,END_MODE_STOP); +} + +void main() { + unsigned rxdata; + + RCC_APB1ENR.TIM2EN = 1; // Enable clock gating for timer module 2 + TIM2_CR1.CEN = 0; // Disable timer + TIM2_PSC = 0; // Set timer prescaler. + TIM2_ARR = 15999; + NVIC_IntEnable(IVT_INT_TIM2); // Enable timer interrupt + TIM2_DIER.UIE = 1; // Update interrupt enable + TIM2_CR1.CEN = 1; // Enable timer + + I2C3_Init_Advanced(100000, &_GPIO_MODULE_I2C3_PA8_C9); + UART1_Init(115200);//(stdio/aux3) + UART1_Write_Text("hello123\r\n"); + UART5_Init_Advanced(9600, _UART_9_BIT_DATA, _UART_NOPARITY, _UART_ONE_STOPBIT, &_GPIO_MODULE_UART5_PC12_PD2);//mdb/exe2 + UART5_CR1bits.M = 1; //9 bit data transfer + PCF_WrSingle(0x20, 0b00000000); //both ports slaves + while(1) + { + if (UART5_Data_Ready()) + { + rxdata = UART5_Read(); + //PrintOut(PrintHandler,"RX5 %X\r\n",rxdata); + switch (rxdata) + { + case 0x131: // 1 001 1 0001 (VMC STATUS) + if (num > 5000) + UART5_Write(0); // ACK + else + UART5_Write(0x140); // VMC FVR OK + // UART5_Write(0x128); // Free vend request + break; + case 0x132: // 1 001 1 0010 (VMC CREDIT) + UART5_Write(0x1FE);// no sell | no vend request + //UART5_Write(0x101); //sell | vend request + //UART5_Write(0x0); //vend price = 0 + break; + case 0x33: // 1 001 1 0010 (VMC VEND) + UART5_Write(0);// vend succeded + break; + /*case 0x138: // 1 001 1 1000 (VMC ACCEPT DATA) + case 0x120: // 1 001 0 0000 (BUV 0x0) + case 0x24: + case 0x21: // 0 001 0 0001 (EC 1) -> OK + case 0x39: // 0 001 1 1001 (DATA SYNC) + UART5_Write(0); + PrintOut(PrintHandler,"RX5 %X\r\n",rxdata); + break;*/ + + case 0x138: // 1 001 1 1000 (VMC ACCEPT DATA) + UART5_Write(0); //OK + rxdata = UART5_Read(); PrintOut(PrintHandler,"RX5 %X BUV 0\r\n",rxdata);UART5_Write(0); //OK + rxdata = UART5_Read(); PrintOut(PrintHandler,"RX5 %X BUV 1\r\n",rxdata);UART5_Write(0); //OK + rxdata = UART5_Read(); PrintOut(PrintHandler,"RX5 %X BUV 2\r\n",rxdata);UART5_Write(0); //OK + rxdata = UART5_Read(); PrintOut(PrintHandler,"RX5 %X BUV 3\r\n",rxdata);UART5_Write(0); //OK + rxdata = UART5_Read(); PrintOut(PrintHandler,"RX5 %X SF 0\r\n",rxdata);UART5_Write(0); //OK + rxdata = UART5_Read(); PrintOut(PrintHandler,"RX5 %X SF 1\r\n",rxdata);UART5_Write(0); //OK + rxdata = UART5_Read(); PrintOut(PrintHandler,"RX5 %X DPI\r\n",rxdata);UART5_Write(0); //OK + rxdata = UART5_Read(); PrintOut(PrintHandler,"RX5 %X EC\r\n",rxdata);UART5_Write(0); //OK + rxdata = UART5_Read(); PrintOut(PrintHandler,"RX5 %X DATA SYNC\r\n",rxdata);UART5_Write(0); //OK + break; + + default: + PrintOut(PrintHandler,"RX5 %X\r\n",rxdata); + break; + } + } + } +} \ No newline at end of file diff --git a/pool/shard002/C/0063975_dollar_glue.c b/pool/shard002/C/0063975_dollar_glue.c new file mode 100644 index 0000000000000000000000000000000000000000..1a6957e7b11e1e3e19c554b3aeffd51cdfad83a8 --- /dev/null +++ b/pool/shard002/C/0063975_dollar_glue.c @@ -0,0 +1,107 @@ +/**************************************************************************** + * Copyright (c) 2012-2013, the Konoha project authors. 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. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED + * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; + * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, + * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR + * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + ***************************************************************************/ + +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif +// -------------------------------------------------------------------------- + +// -------------------------------------------------------------------------- + +static KMETHOD Expression_dollar(KonohaContext *kctx, KonohaStack *sfp) +{ + VAR_Expression(stmt, tokenList, beginIdx, currentIdx, endIdx); + DBG_ASSERT(beginIdx == currentIdx); + if(currentIdx + 1 < endIdx) { + kToken *nextToken = tokenList->TokenItems[currentIdx+1]; + DBG_P("nextToken='%s'", kString_text(nextToken->text)); +// if(nextToken->resolvedSyntaxInfo->keyword == KSymbol_SymbolPattern) { +// KReturn(Expression_DollarSymbol(kctx, stmt, nextToken)); +// } + + } +// KClass *foundClass = NULL; +// int nextIdx = SUGAR ParseTypePattern(kctx, stmt, kNode_ns(stmt), tokenList, beginIdx + 1, endIdx, &foundClass); +// if(nextIdx != -1 && nextIdx < kArray_size(tokenList)) { +// kToken *nextTokenAfterClassName = tokenList->TokenItems[nextIdx]; +//// if(ct->typeId == KType_void) { +//// KReturn(SUGAR MessageNode(kctx, stmt, tk1, ErrTag, "undefined class: %s", kString_text(tk1->text))); +//// } else if(KClass_Is(Virtual, ct)) { +//// SUGAR MessageNode(kctx, stmt, NULL, ErrTag, "invalid application of 'dollar' to incomplete class %s", KClass_text(ct)); +//// } +// if(nextTokenAfterClassName->resolvedSyntaxInfo->keyword == KSymbol_ParenthesisGroup) { // dollar C (...) +// kSyntax *syn = kSyntax_(kNode_ns(stmt), KSymbol_ParamPattern/*MethodCall*/); +// kNode *expr = SUGAR dollar_UntypedCallStyleNode(kctx, syn, 2, dollarToken, NewNode(kctx, syn, tokenList->TokenVarItems[beginIdx+1], foundClass->typeId)); +// dollarToken->symbol = MN_dollar; +// KReturn(expr); +// } +// if(nextTokenAfterClassName->resolvedSyntaxInfo->keyword == KSymbol_BracketGroup) { // dollar int [100] +// kSyntax *syn = kSyntax_(kNode_ns(stmt), KSymbol_("dollar")); +// KClass *arrayClass = KClass_p0(kctx, KClass_Array, foundClass->typeId); +// dollarToken->symbol = KMethodName_("dollarArray"); +// kNode *expr = SUGAR dollar_UntypedCallStyleNode(kctx, syn, 2, dollarToken, NewNode(kctx, syn, tokenList->TokenVarItems[beginIdx+1], arrayClass->typeId)); +// KReturn(expr); +// } +// } +} + +// ---------------------------------------------------------------------------- +/* define class */ + +static kbool_t dollar_defineSyntax(KonohaContext *kctx, kNameSpace *ns, KTraceInfo *trace) +{ + KDEFINE_SYNTAX SYNTAX[] = { + { KSymbol_("$"), 0, NULL, 0, Precedence_CStyleSuffixCall, NULL, Expression_dollar, NULL, NULL, NULL, }, + { KSymbol_END, }, + }; + SUGAR kNameSpace_DefineSyntax(kctx, ns, SYNTAX, trace); + return true; +} + +static kbool_t dollar_PackupNameSpace(KonohaContext *kctx, kNameSpace *ns, int option, KTraceInfo *trace) +{ + dollar_defineSyntax(kctx, ns, trace); + return true; +} + +static kbool_t dollar_ExportNameSpace(KonohaContext *kctx, kNameSpace *ns, kNameSpace *exportNS, int option, KTraceInfo *trace) +{ + return true; +} + +KDEFINE_PACKAGE *dollar_Init(void) +{ + static KDEFINE_PACKAGE d = {0}; + KSetPackageName(d, "dscript", "1.0"); + d.PackupNameSpace = dollar_PackupNameSpace; + d.ExportNameSpace = dollar_ExportNameSpace; + return &d; +} + +#ifdef __cplusplus +} /* extern "C" */ +#endif diff --git a/pool/shard002/C/0063994_omap44xx_spinlock.c b/pool/shard002/C/0063994_omap44xx_spinlock.c new file mode 100644 index 0000000000000000000000000000000000000000..7d0b21100681891dcc708a5f8fb5edd3e7637294 --- /dev/null +++ b/pool/shard002/C/0063994_omap44xx_spinlock.c @@ -0,0 +1,76 @@ +/** + * \file + * \brief kernel driver for the spinlock module, used for serial output + * see OMAP4460 TRM chapter 21 for a functional description + */ + +/* + * Copyright (c) 2013, ETH Zurich. + * All rights reserved. + * + * This file is distributed under the terms in the attached LICENSE file. + * If you do not find this file, copies can be found by writing to: + * ETH Zurich D-INFK, Universitaetstrasse 6, CH-8092 Zurich. Attn: Systems Group. + */ + +#include +#include +#include +#include +#include + + +#define MSG(format, ...) printk( LOG_NOTE, "OMAP44xx spinlock: "format, ## __VA_ARGS__ ) + +static omap44xx_spinlock_t spinlock; +static bool locks_initialized; //allows early initialization + +/** + * \brief Map the OMAP44xx spinlock device into kernel virtual memory + * and reset it. + */ + +errval_t omap44xx_spinlock_init(void) +{ + if (locks_initialized) { + MSG("already initialized; skipping.\n"); + return SYS_ERR_OK; + } + + lvaddr_t base = paging_map_device(OMAP44XX_MAP_L4_CFG_SPINLOCK, + OMAP44XX_MAP_L4_CFG_SPINLOCK_SIZE); + MSG("init base = 0x%"PRIxLVADDR"\n", base); + omap44xx_spinlock_initialize(&spinlock, (mackerel_addr_t)base); + + // This next line to rest the module is probably not needed. + omap44xx_spinlock_sysconfig_softreset_wrf(&spinlock, 1); + + MSG("testing spinlock: first read (should be 0): 0x%x\n", + omap44xx_spinlock_lock_reg_i_taken_rdf(&spinlock, 2)); + + MSG("testing spinlock: second read (should be 1): 0x%x\n", + omap44xx_spinlock_lock_reg_i_taken_rdf(&spinlock, 2)); + + omap44xx_spinlock_lock_reg_i_taken_wrf(&spinlock, 2, 0);//clear lock + locks_initialized = true; + MSG("init done.\n"); + return SYS_ERR_OK; +} + +/** + * \brief acquire an OMAP44xx spinlock. We repeatedly read the + * register; 0 means we have the lock, 1 means we have to try again. + */ +void omap44xx_spinlock_acquire( unsigned locknumber ) { + assert( locknumber < OMAP44XX_SPINLOCK_NUM_LOCKS ); + while( omap44xx_spinlock_lock_reg_i_taken_rdf(&spinlock, locknumber)) { } +} + +/** + * \brief release an OMAP44xx spinlock. + */ +void omap44xx_spinlock_release( unsigned locknumber ) { + assert( locknumber < OMAP44XX_SPINLOCK_NUM_LOCKS ); + omap44xx_spinlock_lock_reg_i_taken_wrf(&spinlock, locknumber, 0); +} + diff --git a/pool/shard002/C/0063998_aux_pcm.c b/pool/shard002/C/0063998_aux_pcm.c new file mode 100644 index 0000000000000000000000000000000000000000..40e7fcbbfdee3e637a45d42e58c495f12fcd2258 --- /dev/null +++ b/pool/shard002/C/0063998_aux_pcm.c @@ -0,0 +1,285 @@ +/* Copyright (c) 2009-2010, Code Aurora Forum. 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. + * + * 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 +#include +#include + +/*---------------------------------------------------------------------------- + * Preprocessor Definitions and Constants + * -------------------------------------------------------------------------*/ + +/* define offset of registers here, may put them into platform data */ +#define AUX_CODEC_CTL_OFFSET 0x00 +#define PCM_PATH_CTL_OFFSET 0x04 +#define AUX_CODEC_CTL_OUT_OFFSET 0x08 + +/* define some bit values in PCM_PATH_CTL register */ +#define PCM_PATH_CTL__ADSP_CTL_EN_BMSK 0x8 + +/* mask and shift */ +#define AUX_CODEC_CTL_ADSP_CODEC_CTL_EN_BMSK 0x800 +#define AUX_CODEC_CTL_PCM_SYNC_LONG_BMSK 0x400 +#define AUX_CODEC_CTL_PCM_SYNC_SHORT_BMSK 0x200 +#define AUX_CODEC_CTL_I2S_SAMPLE_CLK_SRC_BMSK 0x80 +#define AUX_CODEC_CTL_I2S_SAMPLE_CLK_MODE_BMSK 0x40 +#define AUX_CODEC_CTL_I2S_RX_MODE_BMSK 0x20 +#define AUX_CODEC_CTL_I2S_CLK_MODE_BMSK 0x10 +#define AUX_CODEC_CTL_AUX_PCM_MODE_BMSK 0x0b +#define AUX_CODEC_CTL_AUX_CODEC_MODE_BMSK 0x02 + +/* AUX PCM MODE */ +#define MASTER_PRIM_PCM_SHORT 0 +#define MASTER_AUX_PCM_LONG 1 +#define SLAVE_PRIM_PCM_SHORT 2 + +struct aux_pcm_state { + void __iomem *aux_pcm_base; /* configure aux pcm through Scorpion */ + int dout; + int din; + int syncout; + int clkin_a; +}; + +static struct aux_pcm_state the_aux_pcm_state; + +static void __iomem *get_base_addr(struct aux_pcm_state *aux_pcm) +{ + return aux_pcm->aux_pcm_base; +} + +/* Set who control aux pcm : adsp or MSM */ +void aux_codec_adsp_codec_ctl_en(bool msm_adsp_en) +{ + void __iomem *baddr = get_base_addr(&the_aux_pcm_state); + uint32_t val; + + if (!IS_ERR(baddr)) { + val = readl(baddr + AUX_CODEC_CTL_OFFSET); + if (msm_adsp_en) { /* adsp */ + writel( + ((val & ~AUX_CODEC_CTL_ADSP_CODEC_CTL_EN_BMSK) | + AUX_CODEC_CTL__ADSP_CODEC_CTL_EN__ADSP_V), + baddr + AUX_CODEC_CTL_OFFSET); + } else { /* MSM */ + writel( + ((val & ~AUX_CODEC_CTL_ADSP_CODEC_CTL_EN_BMSK) | + AUX_CODEC_CTL__ADSP_CODEC_CTL_EN__MSM_V), + baddr + AUX_CODEC_CTL_OFFSET); + } + } + +} + +/* Set who control aux pcm path: adsp or MSM */ +void aux_codec_pcm_path_ctl_en(bool msm_adsp_en) +{ + void __iomem *baddr = get_base_addr(&the_aux_pcm_state); + uint32_t val; + + if (!IS_ERR(baddr)) { + val = readl(baddr + PCM_PATH_CTL_OFFSET); + if (msm_adsp_en) { /* adsp */ + writel( + ((val & ~PCM_PATH_CTL__ADSP_CTL_EN_BMSK) | + PCM_PATH_CTL__ADSP_CTL_EN__ADSP_V), + baddr + PCM_PATH_CTL_OFFSET); + } else { /* MSM */ + writel( + ((val & ~PCM_PATH_CTL__ADSP_CTL_EN_BMSK) | + PCM_PATH_CTL__ADSP_CTL_EN__MSM_V), + baddr + PCM_PATH_CTL_OFFSET); + } + } + + return; +} +EXPORT_SYMBOL(aux_codec_pcm_path_ctl_en); + +int aux_pcm_gpios_request(void) +{ + int rc = 0; + + MM_DBG("aux_pcm_gpios_request\n"); + rc = gpio_request(the_aux_pcm_state.dout, "AUX PCM DOUT"); + if (rc) { + MM_ERR("GPIO request for AUX PCM DOUT failed\n"); + return rc; + } + + rc = gpio_request(the_aux_pcm_state.din, "AUX PCM DIN"); + if (rc) { + MM_ERR("GPIO request for AUX PCM DIN failed\n"); + gpio_free(the_aux_pcm_state.dout); + return rc; + } + + rc = gpio_request(the_aux_pcm_state.syncout, "AUX PCM SYNC OUT"); + if (rc) { + MM_ERR("GPIO request for AUX PCM SYNC OUT failed\n"); + gpio_free(the_aux_pcm_state.dout); + gpio_free(the_aux_pcm_state.din); + return rc; + } + + rc = gpio_request(the_aux_pcm_state.clkin_a, "AUX PCM CLKIN A"); + if (rc) { + MM_ERR("GPIO request for AUX PCM CLKIN A failed\n"); + gpio_free(the_aux_pcm_state.dout); + gpio_free(the_aux_pcm_state.din); + gpio_free(the_aux_pcm_state.syncout); + return rc; + } + + return rc; +} +EXPORT_SYMBOL(aux_pcm_gpios_request); + + +void aux_pcm_gpios_free(void) +{ + MM_DBG(" aux_pcm_gpios_free \n"); + + /* + * Feed silence frames before close to prevent buzzing sound in BT at + * call end. This fix is applicable only to Marimba BT. + */ + gpio_tlmm_config(GPIO_CFG(the_aux_pcm_state.dout, 0, GPIO_OUTPUT, + GPIO_NO_PULL, GPIO_2MA), GPIO_ENABLE); + gpio_set_value(the_aux_pcm_state.dout, 0); + msleep(20); + gpio_tlmm_config(GPIO_CFG(the_aux_pcm_state.dout, 1, GPIO_OUTPUT, + GPIO_NO_PULL, GPIO_2MA), GPIO_ENABLE); + + gpio_free(the_aux_pcm_state.dout); + gpio_free(the_aux_pcm_state.din); + gpio_free(the_aux_pcm_state.syncout); + gpio_free(the_aux_pcm_state.clkin_a); +} +EXPORT_SYMBOL(aux_pcm_gpios_free); + + +static int get_aux_pcm_gpios(struct platform_device *pdev) +{ + int rc = 0; + struct resource *res; + + /* Claim all of the GPIOs. */ + res = platform_get_resource_byname(pdev, IORESOURCE_IO, + "aux_pcm_dout"); + if (!res) { + MM_ERR("%s: failed to get gpio AUX PCM DOUT\n", __func__); + return -ENODEV; + } + + the_aux_pcm_state.dout = res->start; + + res = platform_get_resource_byname(pdev, IORESOURCE_IO, + "aux_pcm_din"); + if (!res) { + MM_ERR("%s: failed to get gpio AUX PCM DIN\n", __func__); + return -ENODEV; + } + + the_aux_pcm_state.din = res->start; + + res = platform_get_resource_byname(pdev, IORESOURCE_IO, + "aux_pcm_syncout"); + if (!res) { + MM_ERR("%s: failed to get gpio AUX PCM SYNC OUT\n", __func__); + return -ENODEV; + } + + the_aux_pcm_state.syncout = res->start; + + res = platform_get_resource_byname(pdev, IORESOURCE_IO, + "aux_pcm_clkin_a"); + if (!res) { + MM_ERR("%s: failed to get gpio AUX PCM CLKIN A\n", __func__); + return -ENODEV; + } + + the_aux_pcm_state.clkin_a = res->start; + + return rc; +} +static int aux_pcm_probe(struct platform_device *pdev) +{ + int rc = 0; + struct resource *mem_src; + + MM_DBG("aux_pcm_probe \n"); + mem_src = platform_get_resource_byname(pdev, IORESOURCE_MEM, + "aux_codec_reg_addr"); + if (!mem_src) { + rc = -ENODEV; + goto done; + } + + the_aux_pcm_state.aux_pcm_base = ioremap(mem_src->start, + (mem_src->end - mem_src->start) + 1); + if (!the_aux_pcm_state.aux_pcm_base) { + rc = -ENOMEM; + goto done; + } + rc = get_aux_pcm_gpios(pdev); + if (rc) { + MM_ERR("GPIO configuration failed\n"); + rc = -ENODEV; + } + +done: return rc; + +} + +static int aux_pcm_remove(struct platform_device *pdev) +{ + iounmap(the_aux_pcm_state.aux_pcm_base); + return 0; +} + +static struct platform_driver aux_pcm_driver = { + .probe = aux_pcm_probe, + .remove = aux_pcm_remove, + .driver = { + .name = "msm_aux_pcm", + .owner = THIS_MODULE, + }, +}; + +static int __init aux_pcm_init(void) +{ + + return platform_driver_register(&aux_pcm_driver); +} + +static void __exit aux_pcm_exit(void) +{ + platform_driver_unregister(&aux_pcm_driver); +} + +module_init(aux_pcm_init); +module_exit(aux_pcm_exit); + +MODULE_DESCRIPTION("MSM AUX PCM driver"); +MODULE_LICENSE("GPL v2"); diff --git a/pool/shard002/C/0064002_mplib.c b/pool/shard002/C/0064002_mplib.c new file mode 100644 index 0000000000000000000000000000000000000000..c79a56f476e94c1ce4159b7e72f5468b9a3fa262 --- /dev/null +++ b/pool/shard002/C/0064002_mplib.c @@ -0,0 +1,235 @@ +/* + mplib.c + + @description@ + + Copyright (C) 1996-1997 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: + + Free Software Foundation, Inc. + 59 Temple Place - Suite 330 + Boston, MA 02111-1307, USA + + $Id$ +*/ + +#ifdef HAVE_CONFIG_H +# include "config.h" +#endif + +#include + +//#include "types.h" +typedef unsigned char BYTE; +typedef unsigned short WORD; +typedef unsigned long DWORD; + +//#include "mgenord.h" +#define MGENVXD_REGISTER_ORD 1 +#define MGENVXD_GETMEM_ORD 2 +#define MGENVXD_DEREGISTER_ORD 3 +#define MGENVXD_WAKEUP_ORD 4 +#define MGENVXD_MAKEDQS_ORD 5 + + +// Virtual 8086 API Ordinals +#define V86API_GETSELECTOR16_ORD (1) +#define V86API_GETSELECTOR32_ORD (2) +#define V86API_GETFLAT32_ORD (3) +#define V86API_MOVERP_ORD (6) +#define V86API_MOVEPR_ORD (7) +#define V86API_POST_ORD (8) +#define V86API_INIT_ORD (9) +#define V86API_UNINIT_ORD (10) +#define V86API_INSERTKEY_ORD (11) +#define V86API_REMOVEHOTKEY_ORD (12) +#define V86API_INSTALLHOTKEY_ORD (13) +#define V86API_HOOKINT48_ORD (14) +#define V86API_WAKEUPDLL_ORD (15) + +#define DPMIAPI_GETFLAT32_ORD (1) +#define DPMIAPI_POST_WINDOWS_ORD (2) +// these are DPMI functions. Make sure they don't clash with the +// other MGENVXD_XXXX functions above, or the DPMI functions! +#define MGENVXD_GETQUEUECTR_ORD 6 +#define MGENVXD_MOVENODE_ORD 7 +#define MGENVXD_GETNODE_ORD 8 +#define MGENVXD_FLUSHNODE_ORD 9 +#define MGENVXD_MCOUNT_ORD 10 +#define MGENVXD_MASTERNODE_ORD 11 +#define MGENVXD_SANITYCHECK_ORD 12 +#define MGENVXD_WAKEUPDLL_ORD 13 +#define MGENVXD_WAIT_ORD 14 + +// +#define HWND_OFFSET (0) +#define UMSG_OFFSET (1) +#define SIZEREQUEST_OFFSET (2) +#define HVXD_OFFSET (3) +#define DATUM_OFFSET (4) +#define SLOT_OFFSET (5) +#define SIZEGIVEN_OFFSET (6) +#define SELECTOR32_OFFSET (7) +#define SELECTOR16_OFFSET (8) + +//#include "magic.h" +#define MGENVXD_DEVICE_ID 0x18AA + +//#include "rtq.h" +#define RTQ_NODE struct rtq_node + +RTQ_NODE + { + RTQ_NODE *self; // Ring zero address of this node + RTQ_NODE *left; // Ring zero address of preceding node + RTQ_NODE *right; // Ring zero address of succeding node + BYTE * rtqDatum; // Ring 3 Datum of Buffer (start of preface) + BYTE * rtqInsert; // Ring 3 insertion position + WORD rtqLen; // Length of buffer, excluding preface + WORD rtqUpCtr; // Up Counter of bytes used so far + WORD rtqQCtr; // number of nodes attached + WORD padding; // DWORD alignment + }; + +#define RTQ_PARAM_MOVENODE struct rtq_param_movenode +RTQ_PARAM_MOVENODE + { + WORD rtqFromDQ; + WORD rtqToDQ; + }; + +RTQ_NODE* rtq_fetch(RTQ_NODE*, RTQ_NODE*); // To, From + +int _int86(int vector, __dpmi_regs *iregs, __dpmi_regs *oregs); + +#define CHUNNEL_INT 0x48 + +#define int386 _int86 +#define REGISTERS __dpmi_regs + +void +Yield(void) +{ + __dpmi_yield(); +} + +void +PostWindowsMessage(void) +{ + REGISTERS regs; + + regs.d.eax = DPMIAPI_POST_WINDOWS_ORD << 16 | MGENVXD_DEVICE_ID; + regs.d.ebx = 0; + regs.d.ecx = 0; + int386(CHUNNEL_INT, ®s, ®s); +} + +int +MGenWait(void) +{ + REGISTERS regs; + + regs.d.eax = MGENVXD_WAIT_ORD << 16 | MGENVXD_DEVICE_ID; + int386(CHUNNEL_INT, ®s, ®s); + return regs.d.eax; +} + +int MGenGetQueueCtr(int qNo) +{ + REGISTERS regs; + + regs.d.eax = MGENVXD_GETQUEUECTR_ORD << 16 | MGENVXD_DEVICE_ID; + regs.d.ebx = qNo; + int386(CHUNNEL_INT, ®s, ®s); + + return regs.d.eax; +} + +RTQ_NODE *MGenMoveTo(int qFrom, int qTo) +{ + REGISTERS regs; + + regs.d.eax = MGENVXD_MOVENODE_ORD << 16 | MGENVXD_DEVICE_ID; + regs.d.ebx = qFrom; + regs.d.ecx = qTo; + int386(CHUNNEL_INT, ®s, ®s); + + return (RTQ_NODE *) regs.d.eax; +} + +RTQ_NODE *MGenGetNode(int q) +{ + REGISTERS regs; + + regs.d.eax = MGENVXD_GETNODE_ORD << 16 | MGENVXD_DEVICE_ID; + regs.d.ebx = q; + int386(CHUNNEL_INT, ®s, ®s); + + return (RTQ_NODE *) regs.d.eax; +} + +RTQ_NODE *MGenGetMasterNode(unsigned *size) +{ + REGISTERS regs; + + regs.d.eax = MGENVXD_MASTERNODE_ORD << 16 | MGENVXD_DEVICE_ID; + int386(CHUNNEL_INT, ®s, ®s); + *size = regs.d.ecx; + + return (RTQ_NODE *) regs.d.eax; +} + +RTQ_NODE *MGenFlushNodes(int qFrom, int qTo) +{ + REGISTERS regs; + + regs.d.eax = MGENVXD_FLUSHNODE_ORD << 16 | MGENVXD_DEVICE_ID; + regs.d.ebx = qFrom; + regs.d.ecx = qTo; + int386(CHUNNEL_INT, ®s, ®s); + + return (RTQ_NODE *) regs.d.eax; +} + +int MGenMCount(unsigned lowerOrderBits, unsigned upperOrderBits) +{ + REGISTERS regs; + + regs.d.eax = MGENVXD_MCOUNT_ORD << 16 | MGENVXD_DEVICE_ID; + regs.d.ebx = lowerOrderBits; + regs.d.ecx = upperOrderBits; + int386(CHUNNEL_INT, ®s, ®s); + + return regs.d.eax; +} + +int MGenSanityCheck(void) +{ + REGISTERS regs; + + regs.d.eax = MGENVXD_SANITYCHECK_ORD << 16 | MGENVXD_DEVICE_ID; + int386(CHUNNEL_INT, ®s, ®s); + + return regs.d.eax; +} + +void MGenWakeupDll(void) +{ + REGISTERS regs; + + regs.d.eax = MGENVXD_WAKEUPDLL_ORD << 16 | MGENVXD_DEVICE_ID; + int386(CHUNNEL_INT, ®s, ®s); +} diff --git a/pool/shard002/C/0064018_htab_statistics.c b/pool/shard002/C/0064018_htab_statistics.c new file mode 100644 index 0000000000000000000000000000000000000000..3705cf0d2d07826016cffc9124a4232ccc953ae2 --- /dev/null +++ b/pool/shard002/C/0064018_htab_statistics.c @@ -0,0 +1,48 @@ +/** @file htab_statistics.c + * @brief Prejde cely zoznam a vypise nad nim statistiku + * Riesenie IJC-DU2, priklad b) + * Přeloženo: gcc 4.8.1 + * @author David Mikus, FIT + * @date 26.4.2014 + */ + +#include "htable.h" + +void htab_statistics(htab_t *t) +{ + if (t==NULL) return; + int *count = malloc(sizeof(int)*t->size); + if (count==NULL) + { + fprintf(stderr,"Nepodarilo sa alokovat miesto pre statistiku"); + return; + } + int counter=0; + struct htab_listitem *item = NULL; + /* Spocitanie kazdeho zaznamu */ + for (unsigned long i = 0; isize; i++) + { + counter=0; + for(item=t->data[i];item;item=item->next) + { + counter++; + } + count[i]=counter; + } + int sum=0; + int min=count[0]; + int max=0; + /* Zistenie min,max a spocitanie sumy */ + for (unsigned long i =0;isize; i++) + { + sum+=count[i]; + if(count[i]>max) max=count[i]; + else if (count[i]size); + printf("###### Statistika #######\n"); + printf("Min = %d\t\t\nMax = %d\t\t\nAvg = %.2f\t\t\n",min,max,avg); + printf("#########################\n"); + free(count); +} diff --git a/pool/shard002/C/0064021_print.c b/pool/shard002/C/0064021_print.c new file mode 100644 index 0000000000000000000000000000000000000000..ba078dae904e9073860977485115db621216728b --- /dev/null +++ b/pool/shard002/C/0064021_print.c @@ -0,0 +1,33 @@ +/* + Copyright (C) 2010 William Hart + Copyright (C) 2014 Abhinav Baid + + This file is part of FLINT. + + FLINT 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. See . +*/ + +#include "d_mat.h" + +void +d_mat_print(const d_mat_t mat) +{ + slong i, j; + + flint_printf("["); + for (i = 0; i < mat->r; i++) + { + flint_printf("["); + for (j = 0; j < mat->c; j++) + { + flint_printf("%E", d_mat_entry(mat, i, j)); + if (j < mat->c - 1) + flint_printf(" "); + } + flint_printf("]\n"); + } + flint_printf("]\n"); +}