diff --git a/pool/shard004/C++/0048478_tlkreplace.cpp b/pool/shard004/C++/0048478_tlkreplace.cpp new file mode 100644 index 0000000000000000000000000000000000000000..a17e3036ac4c309d92bca94f7e2b535f369fb465 --- /dev/null +++ b/pool/shard004/C++/0048478_tlkreplace.cpp @@ -0,0 +1,54 @@ +// MIT License +// +// Copyright (c) 2017 sylt +// +// 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 "libtlk.h" + +static std::string ReadFileContents(const char* path) +{ + std::ifstream file(path); + std::string newText((std::istreambuf_iterator(file)), + std::istreambuf_iterator()); + return newText; +} + +int main(int argc, char* argv[]) +{ + if (argc != 4) { + fprintf(stderr, + "Usage: %s tlkfile index-to-replace file-with-new-text\n", + argv[0]); + return -1; + } + + tlk::Builder builder(argv[1]); + auto index = std::stoul(argv[2]); + builder.ReplaceLine(index, ReadFileContents(argv[3])); + builder.WriteFile(argv[1]); + + printf("Line updated! Ensure update was correct by using tlkview.\n"); +} diff --git a/pool/shard004/C++/0048484_VerticalSlotExtension.cpp b/pool/shard004/C++/0048484_VerticalSlotExtension.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b25df99e86d5074737f370545476dde76772303c --- /dev/null +++ b/pool/shard004/C++/0048484_VerticalSlotExtension.cpp @@ -0,0 +1,86 @@ +// Copyright 1998-2015 Epic Games, Inc. All Rights Reserved. + +#include "UMGEditorPrivatePCH.h" +#include "Components/VerticalBox.h" +#include "Components/VerticalBoxSlot.h" +#include "Extensions/VerticalSlotExtension.h" +#include "Kismet2/BlueprintEditorUtils.h" +#include "WidgetBlueprint.h" + +#define LOCTEXT_NAMESPACE "UMG" + +FVerticalSlotExtension::FVerticalSlotExtension() +{ + ExtensionId = FName(TEXT("VerticalSlot")); +} + +bool FVerticalSlotExtension::CanExtendSelection(const TArray< FWidgetReference >& Selection) const +{ + for ( const FWidgetReference& Widget : Selection ) + { + if ( !Widget.GetTemplate()->Slot || !Widget.GetTemplate()->Slot->IsA(UVerticalBoxSlot::StaticClass()) ) + { + return false; + } + } + + return Selection.Num() == 1; +} + +void FVerticalSlotExtension::ExtendSelection(const TArray< FWidgetReference >& Selection, TArray< TSharedRef >& SurfaceElements) +{ + SelectionCache = Selection; + + TSharedRef UpArrow = SNew(SButton) + .Text(LOCTEXT("UpArrow", "↑")) + .ContentPadding(FMargin(6, 2)) + .IsEnabled(this, &FVerticalSlotExtension::CanShift, -1) + .OnClicked(this, &FVerticalSlotExtension::HandleShiftVertical, -1); + + TSharedRef DownArrow = SNew(SButton) + .Text(LOCTEXT("DownArrow", "↓")) + .ContentPadding(FMargin(6, 2)) + .IsEnabled(this, &FVerticalSlotExtension::CanShift, 1) + .OnClicked(this, &FVerticalSlotExtension::HandleShiftVertical, 1); + + UpArrow->SlatePrepass(); + DownArrow->SlatePrepass(); + + SurfaceElements.Add(MakeShareable(new FDesignerSurfaceElement(UpArrow, EExtensionLayoutLocation::TopCenter, FVector2D(UpArrow->GetDesiredSize().X * -0.5f, -UpArrow->GetDesiredSize().Y)))); + SurfaceElements.Add(MakeShareable(new FDesignerSurfaceElement(DownArrow, EExtensionLayoutLocation::BottomCenter, FVector2D(DownArrow->GetDesiredSize().X * -0.5f, 0)))); +} + +bool FVerticalSlotExtension::CanShift(int32 ShiftAmount) const +{ + //TODO UMG Provide feedback if shifting is possible. Tricky with multiple items selected, if we ever support that. + return true; +} + +FReply FVerticalSlotExtension::HandleShiftVertical(int32 ShiftAmount) +{ + BeginTransaction(LOCTEXT("MoveWidget", "Move Widget")); + + for ( FWidgetReference& Selection : SelectionCache ) + { + ShiftVertical(Selection.GetPreview(), ShiftAmount); + ShiftVertical(Selection.GetTemplate(), ShiftAmount); + } + + EndTransaction(); + + //TODO UMG Reorder the live slot without rebuilding the structure + FBlueprintEditorUtils::MarkBlueprintAsStructurallyModified(Blueprint); + + return FReply::Handled(); +} + +void FVerticalSlotExtension::ShiftVertical(UWidget* Widget, int32 ShiftAmount) +{ + UVerticalBox* Parent = CastChecked(Widget->GetParent()); + + Parent->Modify(); + int32 CurrentIndex = Parent->GetChildIndex(Widget); + Parent->ShiftChild(CurrentIndex + ShiftAmount, Widget); +} + +#undef LOCTEXT_NAMESPACE diff --git a/pool/shard004/C++/0048491_UnwindTable.cpp b/pool/shard004/C++/0048491_UnwindTable.cpp new file mode 100644 index 0000000000000000000000000000000000000000..045957a67b3be9b90afbd174d51b89bc7983ada7 --- /dev/null +++ b/pool/shard004/C++/0048491_UnwindTable.cpp @@ -0,0 +1,207 @@ +//===-- UnwindTable.cpp -----------------------------------------*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// + +#include "lldb/Symbol/UnwindTable.h" + +#include + +#include "lldb/Core/Module.h" +#include "lldb/Core/Section.h" +#include "lldb/Symbol/ArmUnwindInfo.h" +#include "lldb/Symbol/CallFrameInfo.h" +#include "lldb/Symbol/CompactUnwindInfo.h" +#include "lldb/Symbol/DWARFCallFrameInfo.h" +#include "lldb/Symbol/FuncUnwinders.h" +#include "lldb/Symbol/ObjectFile.h" +#include "lldb/Symbol/SymbolContext.h" +#include "lldb/Symbol/SymbolVendor.h" + +// There is one UnwindTable object per ObjectFile. It contains a list of Unwind +// objects -- one per function, populated lazily -- for the ObjectFile. Each +// Unwind object has multiple UnwindPlans for different scenarios. + +using namespace lldb; +using namespace lldb_private; + +UnwindTable::UnwindTable(Module &module) + : m_module(module), m_unwinds(), m_initialized(false), m_mutex(), + m_object_file_unwind_up(), m_eh_frame_up(), m_compact_unwind_up(), + m_arm_unwind_up() {} + +// We can't do some of this initialization when the ObjectFile is running its +// ctor; delay doing it until needed for something. + +void UnwindTable::Initialize() { + if (m_initialized) + return; + + std::lock_guard guard(m_mutex); + + if (m_initialized) // check again once we've acquired the lock + return; + m_initialized = true; + ObjectFile *object_file = m_module.GetObjectFile(); + if (!object_file) + return; + + m_object_file_unwind_up = object_file->CreateCallFrameInfo(); + + SectionList *sl = m_module.GetSectionList(); + if (!sl) + return; + + SectionSP sect = sl->FindSectionByType(eSectionTypeEHFrame, true); + if (sect.get()) { + m_eh_frame_up.reset( + new DWARFCallFrameInfo(*object_file, sect, DWARFCallFrameInfo::EH)); + } + + sect = sl->FindSectionByType(eSectionTypeDWARFDebugFrame, true); + if (sect) { + m_debug_frame_up.reset( + new DWARFCallFrameInfo(*object_file, sect, DWARFCallFrameInfo::DWARF)); + } + + sect = sl->FindSectionByType(eSectionTypeCompactUnwind, true); + if (sect) { + m_compact_unwind_up.reset(new CompactUnwindInfo(*object_file, sect)); + } + + sect = sl->FindSectionByType(eSectionTypeARMexidx, true); + if (sect) { + SectionSP sect_extab = sl->FindSectionByType(eSectionTypeARMextab, true); + if (sect_extab.get()) { + m_arm_unwind_up.reset(new ArmUnwindInfo(*object_file, sect, sect_extab)); + } + } +} + +UnwindTable::~UnwindTable() {} + +llvm::Optional UnwindTable::GetAddressRange(const Address &addr, + SymbolContext &sc) { + AddressRange range; + + // First check the unwind info from the object file plugin + if (m_object_file_unwind_up && + m_object_file_unwind_up->GetAddressRange(addr, range)) + return range; + + // Check the symbol context + if (sc.GetAddressRange(eSymbolContextFunction | eSymbolContextSymbol, 0, + false, range) && + range.GetBaseAddress().IsValid()) + return range; + + // Does the eh_frame unwind info has a function bounds for this addr? + if (m_eh_frame_up && m_eh_frame_up->GetAddressRange(addr, range)) + return range; + + // Try debug_frame as well + if (m_debug_frame_up && m_debug_frame_up->GetAddressRange(addr, range)) + return range; + + return llvm::None; +} + +FuncUnwindersSP +UnwindTable::GetFuncUnwindersContainingAddress(const Address &addr, + SymbolContext &sc) { + Initialize(); + + std::lock_guard guard(m_mutex); + + // There is an UnwindTable per object file, so we can safely use file handles + addr_t file_addr = addr.GetFileAddress(); + iterator end = m_unwinds.end(); + iterator insert_pos = end; + if (!m_unwinds.empty()) { + insert_pos = m_unwinds.lower_bound(file_addr); + iterator pos = insert_pos; + if ((pos == m_unwinds.end()) || + (pos != m_unwinds.begin() && + pos->second->GetFunctionStartAddress() != addr)) + --pos; + + if (pos->second->ContainsAddress(addr)) + return pos->second; + } + + auto range_or = GetAddressRange(addr, sc); + if (!range_or) + return nullptr; + + FuncUnwindersSP func_unwinder_sp(new FuncUnwinders(*this, *range_or)); + m_unwinds.insert(insert_pos, + std::make_pair(range_or->GetBaseAddress().GetFileAddress(), + func_unwinder_sp)); + return func_unwinder_sp; +} + +// Ignore any existing FuncUnwinders for this function, create a new one and +// don't add it to the UnwindTable. This is intended for use by target modules +// show-unwind where we want to create new UnwindPlans, not re-use existing +// ones. +FuncUnwindersSP +UnwindTable::GetUncachedFuncUnwindersContainingAddress(const Address &addr, + SymbolContext &sc) { + Initialize(); + + auto range_or = GetAddressRange(addr, sc); + if (!range_or) + return nullptr; + + return std::make_shared(*this, *range_or); +} + +void UnwindTable::Dump(Stream &s) { + std::lock_guard guard(m_mutex); + s.Format("UnwindTable for '{0}':\n", m_module.GetFileSpec()); + const_iterator begin = m_unwinds.begin(); + const_iterator end = m_unwinds.end(); + for (const_iterator pos = begin; pos != end; ++pos) { + s.Printf("[%u] 0x%16.16" PRIx64 "\n", (unsigned)std::distance(begin, pos), + pos->first); + } + s.EOL(); +} + +lldb_private::CallFrameInfo *UnwindTable::GetObjectFileUnwindInfo() { + Initialize(); + return m_object_file_unwind_up.get(); +} + +DWARFCallFrameInfo *UnwindTable::GetEHFrameInfo() { + Initialize(); + return m_eh_frame_up.get(); +} + +DWARFCallFrameInfo *UnwindTable::GetDebugFrameInfo() { + Initialize(); + return m_debug_frame_up.get(); +} + +CompactUnwindInfo *UnwindTable::GetCompactUnwindInfo() { + Initialize(); + return m_compact_unwind_up.get(); +} + +ArmUnwindInfo *UnwindTable::GetArmUnwindInfo() { + Initialize(); + return m_arm_unwind_up.get(); +} + +SymbolFile *UnwindTable::GetSymbolFile() { return m_module.GetSymbolFile(); } + +ArchSpec UnwindTable::GetArchitecture() { return m_module.GetArchitecture(); } + +bool UnwindTable::GetAllowAssemblyEmulationUnwindPlans() { + if (ObjectFile *object_file = m_module.GetObjectFile()) + return object_file->AllowAssemblyEmulationUnwindPlans(); + return false; +} diff --git a/pool/shard004/C++/0048497_editaddressdialog.cpp b/pool/shard004/C++/0048497_editaddressdialog.cpp new file mode 100644 index 0000000000000000000000000000000000000000..7dab44003837d9832853cd3283f36ae29fdf235a --- /dev/null +++ b/pool/shard004/C++/0048497_editaddressdialog.cpp @@ -0,0 +1,128 @@ +#include "editaddressdialog.h" +#include "ui_editaddressdialog.h" +#include "addresstablemodel.h" +#include "guiutil.h" + +#include +#include + +EditAddressDialog::EditAddressDialog(Mode mode, QWidget *parent) : + QDialog(parent), + ui(new Ui::EditAddressDialog), mapper(0), mode(mode), model(0) +{ + ui->setupUi(this); + + GUIUtil::setupAddressWidget(ui->addressEdit, this); + + switch(mode) + { + case NewReceivingAddress: + setWindowTitle(tr("New receiving address")); + ui->addressEdit->setEnabled(false); + break; + case NewSendingAddress: + setWindowTitle(tr("New sending address")); + break; + case EditReceivingAddress: + setWindowTitle(tr("Edit receiving address")); + ui->addressEdit->setDisabled(true); + break; + case EditSendingAddress: + setWindowTitle(tr("Edit sending address")); + break; + } + + mapper = new QDataWidgetMapper(this); + mapper->setSubmitPolicy(QDataWidgetMapper::ManualSubmit); +} + +EditAddressDialog::~EditAddressDialog() +{ + delete ui; +} + +void EditAddressDialog::setModel(AddressTableModel *model) +{ + this->model = model; + mapper->setModel(model); + mapper->addMapping(ui->labelEdit, AddressTableModel::Label); + mapper->addMapping(ui->addressEdit, AddressTableModel::Address); +} + +void EditAddressDialog::loadRow(int row) +{ + mapper->setCurrentIndex(row); +} + +bool EditAddressDialog::saveCurrentRow() +{ + if(!model) + return false; + switch(mode) + { + case NewReceivingAddress: + case NewSendingAddress: + address = model->addRow( + mode == NewSendingAddress ? AddressTableModel::Send : AddressTableModel::Receive, + ui->labelEdit->text(), + ui->addressEdit->text()); + break; + case EditReceivingAddress: + case EditSendingAddress: + if(mapper->submit()) + { + address = ui->addressEdit->text(); + } + break; + } + return !address.isEmpty(); +} + +void EditAddressDialog::accept() +{ + if(!model) + return; + if(!saveCurrentRow()) + { + switch(model->getEditStatus()) + { + case AddressTableModel::DUPLICATE_ADDRESS: + QMessageBox::warning(this, windowTitle(), + tr("The entered address \"%1\" is already in the address book.").arg(ui->addressEdit->text()), + QMessageBox::Ok, QMessageBox::Ok); + break; + case AddressTableModel::INVALID_ADDRESS: + QMessageBox::warning(this, windowTitle(), + tr("The entered address \"%1\" is not a valid SafariCoin address.").arg(ui->addressEdit->text()), + QMessageBox::Ok, QMessageBox::Ok); + return; + case AddressTableModel::WALLET_UNLOCK_FAILURE: + QMessageBox::critical(this, windowTitle(), + tr("Could not unlock wallet."), + QMessageBox::Ok, QMessageBox::Ok); + return; + case AddressTableModel::KEY_GENERATION_FAILURE: + QMessageBox::critical(this, windowTitle(), + tr("New key generation failed."), + QMessageBox::Ok, QMessageBox::Ok); + return; + case AddressTableModel::OK: + // Failed with unknown reason. Just reject. + break; + } + + return; + } + QDialog::accept(); +} + +QString EditAddressDialog::getAddress() const +{ + return address; +} + +void EditAddressDialog::setAddress(const QString &address) +{ + this->address = address; + ui->addressEdit->setText(address); +} diff --git a/pool/shard004/C++/0048506_animation.cpp b/pool/shard004/C++/0048506_animation.cpp new file mode 100644 index 0000000000000000000000000000000000000000..54cbb453a8a64b83df3c8017c40510b94bd07915 --- /dev/null +++ b/pool/shard004/C++/0048506_animation.cpp @@ -0,0 +1,195 @@ +/* +This file is part of Telegram Desktop, +the official desktop version of Telegram messaging app, see https://telegram.org + +Telegram Desktop is free software: you can 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. + +It is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +In addition, as a special exception, the copyright holders give permission +to link the code of portions of this program with the OpenSSL library. + +Full license: https://github.com/telegramdesktop/tdesktop/blob/master/LICENSE +Copyright (c) 2014-2017 John Preston, https://desktop.telegram.org +*/ +#include "animation.h" + +#include "media/media_clip_reader.h" + +namespace Media { +namespace Clip { + +Reader *const ReaderPointer::BadPointer = SharedMemoryLocation(); + +ReaderPointer::~ReaderPointer() { + if (valid()) { + delete _pointer; + } + _pointer = nullptr; +} + +} // namespace Clip +} // namespace Media + +namespace { + +AnimationManager *_manager = nullptr; + +} // namespace + +namespace anim { + +transition linear = [](const float64 &delta, const float64 &dt) { + return delta * dt; +}; + +transition sineInOut = [](const float64 &delta, const float64 &dt) { + return -(delta / 2) * (cos(M_PI * dt) - 1); +}; + +transition halfSine = [](const float64 &delta, const float64 &dt) { + return delta * sin(M_PI * dt / 2); +}; + +transition easeOutBack = [](const float64 &delta, const float64 &dt) { + static constexpr auto s = 1.70158; + + const float64 t = dt - 1; + return delta * (t * t * ((s + 1) * t + s) + 1); +}; + +transition easeInCirc = [](const float64 &delta, const float64 &dt) { + return -delta * (sqrt(1 - dt * dt) - 1); +}; + +transition easeOutCirc = [](const float64 &delta, const float64 &dt) { + const float64 t = dt - 1; + return delta * sqrt(1 - t * t); +}; + +transition easeInCubic = [](const float64 &delta, const float64 &dt) { + return delta * dt * dt * dt; +}; + +transition easeOutCubic = [](const float64 &delta, const float64 &dt) { + const float64 t = dt - 1; + return delta * (t * t * t + 1); +}; + +transition easeInQuint = [](const float64 &delta, const float64 &dt) { + const float64 t2 = dt * dt; + return delta * t2 * t2 * dt; +}; + +transition easeOutQuint = [](const float64 &delta, const float64 &dt) { + const float64 t = dt - 1, t2 = t * t; + return delta * (t2 * t2 * t + 1); +}; + +void startManager() { + stopManager(); + + _manager = new AnimationManager(); +} + +void stopManager() { + delete _manager; + _manager = nullptr; + + Media::Clip::Finish(); +} + +void registerClipManager(Media::Clip::Manager *manager) { + manager->connect(manager, SIGNAL(callback(Media::Clip::Reader*,qint32,qint32)), _manager, SLOT(clipCallback(Media::Clip::Reader*,qint32,qint32))); +} + +} // anim + +void BasicAnimation::start() { + if (!_manager) return; + + _callbacks.start(); + _manager->start(this); + _animating = true; +} + +void BasicAnimation::stop() { + if (!_manager) return; + + _animating = false; + _manager->stop(this); +} + +AnimationManager::AnimationManager() : _timer(this), _iterating(false) { + _timer.setSingleShot(false); + connect(&_timer, SIGNAL(timeout()), this, SLOT(timeout())); +} + +void AnimationManager::start(BasicAnimation *obj) { + if (_iterating) { + _starting.insert(obj); + if (!_stopping.isEmpty()) { + _stopping.remove(obj); + } + } else { + if (_objects.isEmpty()) { + _timer.start(AnimationTimerDelta); + } + _objects.insert(obj); + } +} + +void AnimationManager::stop(BasicAnimation *obj) { + if (_iterating) { + _stopping.insert(obj); + if (!_starting.isEmpty()) { + _starting.remove(obj); + } + } else { + auto i = _objects.find(obj); + if (i != _objects.cend()) { + _objects.erase(i); + if (_objects.empty()) { + _timer.stop(); + } + } + } +} + +void AnimationManager::timeout() { + _iterating = true; + auto ms = getms(); + for_const (auto object, _objects) { + if (!_stopping.contains(object)) { + object->step(ms, true); + } + } + _iterating = false; + + if (!_starting.isEmpty()) { + for_const (auto object, _starting) { + _objects.insert(object); + } + _starting.clear(); + } + if (!_stopping.isEmpty()) { + for_const (auto object, _stopping) { + _objects.remove(object); + } + _stopping.clear(); + } + if (_objects.empty()) { + _timer.stop(); + } +} + +void AnimationManager::clipCallback(Media::Clip::Reader *reader, qint32 threadIndex, qint32 notification) { + Media::Clip::Reader::callback(reader, threadIndex, Media::Clip::Notification(notification)); +} + diff --git a/pool/shard004/C++/0048517_apps_promo_unittest.cc b/pool/shard004/C++/0048517_apps_promo_unittest.cc new file mode 100644 index 0000000000000000000000000000000000000000..cbfa1ba7198134201b8ddf5daf57679d78597f18 --- /dev/null +++ b/pool/shard004/C++/0048517_apps_promo_unittest.cc @@ -0,0 +1,166 @@ +// Copyright (c) 2011 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 "chrome/browser/extensions/apps_promo.h" +#include "chrome/browser/prefs/browser_prefs.h" +#include "chrome/browser/ui/webui/ntp/shown_sections_handler.h" +#include "chrome/common/extensions/extension.h" +#include "chrome/common/pref_names.h" +#include "chrome/test/testing_browser_process_test.h" +#include "chrome/test/testing_pref_service.h" +#include "googleurl/src/gurl.h" +#include "testing/gtest/include/gtest/gtest.h" + +namespace { + +const char kPromoId[] = "23123123"; +const char kPromoHeader[] = "Get great apps!"; +const char kPromoButton[] = "Click for apps!"; +const char kPromoLink[] = "http://apps.com"; +const char kPromoExpire[] = "No thanks."; + +} // namespace + +class ExtensionAppsPromo : public TestingBrowserProcessTest { + public: + TestingPrefService* prefs() { return &prefs_; } + AppsPromo* apps_promo() { return &apps_promo_; } + + protected: + explicit ExtensionAppsPromo(); + + // testing::Test + virtual void SetUp(); + + private: + TestingPrefService prefs_; + ScopedTestingLocalState local_state_; + AppsPromo apps_promo_; +}; + +ExtensionAppsPromo::ExtensionAppsPromo() + : local_state_(testing_browser_process_.get()), + apps_promo_(&prefs_) { +} + +void ExtensionAppsPromo::SetUp() { + browser::RegisterUserPrefs(&prefs_); +} + +// TODO(dpolukhin): On Chrome OS all apps are installed via external extensions, +// and the web store promo is never shown. +#if !defined(OS_CHROMEOS) +TEST_F(ExtensionAppsPromo, HappyPath) { + const ExtensionIdSet& default_app_ids = apps_promo()->old_default_apps(); + + EXPECT_GT(default_app_ids.size(), 0u); + + // The promo counter should default to the max, since we only use the counter + // if they were installed from older versions of Chrome. + EXPECT_EQ(AppsPromo::kDefaultAppsCounterMax + 1, + apps_promo()->GetPromoCounter()); + + // The app launcher and promo should not be shown if there are no extensions + // installed and no promo is set. + ExtensionIdSet installed_ids; + bool promo_just_expired = false; + EXPECT_FALSE(AppsPromo::IsPromoSupportedForLocale()); + EXPECT_FALSE(apps_promo()->ShouldShowAppLauncher(installed_ids)); + EXPECT_FALSE(apps_promo()->ShouldShowPromo(installed_ids, + &promo_just_expired)); + EXPECT_FALSE(promo_just_expired); + + // Once the promo is set, we show both the promo and app launcher. + AppsPromo::SetPromo( + kPromoId, kPromoHeader, kPromoButton, GURL(kPromoLink), kPromoExpire); + + EXPECT_TRUE(AppsPromo::IsPromoSupportedForLocale()); + EXPECT_TRUE(apps_promo()->ShouldShowAppLauncher(installed_ids)); + EXPECT_TRUE(apps_promo()->ShouldShowPromo(installed_ids, + &promo_just_expired)); + EXPECT_FALSE(promo_just_expired); + + + // Now install an app and the promo should not be shown. + installed_ids.insert(*(default_app_ids.begin())); + EXPECT_TRUE(AppsPromo::IsPromoSupportedForLocale()); + EXPECT_TRUE(apps_promo()->ShouldShowAppLauncher(installed_ids)); + EXPECT_FALSE(apps_promo()->ShouldShowPromo(installed_ids, + &promo_just_expired)); + EXPECT_FALSE(promo_just_expired); + + // Even if the user installs the exact set of default apps, we still don't + // show the promo. + installed_ids = default_app_ids; + EXPECT_TRUE(AppsPromo::IsPromoSupportedForLocale()); + EXPECT_TRUE(apps_promo()->ShouldShowAppLauncher(installed_ids)); + EXPECT_FALSE(apps_promo()->ShouldShowPromo(installed_ids, + &promo_just_expired)); + EXPECT_FALSE(promo_just_expired); + + // If the user then uninstalls the apps, the app launcher should remain + // and the promo should return. + installed_ids.clear(); + EXPECT_TRUE(AppsPromo::IsPromoSupportedForLocale()); + EXPECT_TRUE(apps_promo()->ShouldShowAppLauncher(installed_ids)); + EXPECT_TRUE(apps_promo()->ShouldShowPromo(installed_ids, + &promo_just_expired)); + EXPECT_FALSE(promo_just_expired); +} + +// Tests get and set of promo content. +TEST_F(ExtensionAppsPromo, PromoPrefs) { + // Store a promo.... + AppsPromo::SetPromo( + kPromoId, kPromoHeader, kPromoButton, GURL(kPromoLink), kPromoExpire); + + // ... then make sure AppsPromo can access it. + EXPECT_EQ(kPromoId, AppsPromo::GetPromoId()); + EXPECT_EQ(kPromoHeader, AppsPromo::GetPromoHeaderText()); + EXPECT_EQ(kPromoButton, AppsPromo::GetPromoButtonText()); + EXPECT_EQ(GURL(kPromoLink), AppsPromo::GetPromoLink()); + EXPECT_EQ(kPromoExpire, AppsPromo::GetPromoExpireText()); + EXPECT_TRUE(AppsPromo::IsPromoSupportedForLocale()); + + AppsPromo::ClearPromo(); + EXPECT_EQ("", AppsPromo::GetPromoId()); + EXPECT_EQ("", AppsPromo::GetPromoHeaderText()); + EXPECT_EQ("", AppsPromo::GetPromoButtonText()); + EXPECT_EQ(GURL(""), AppsPromo::GetPromoLink()); + EXPECT_EQ("", AppsPromo::GetPromoExpireText()); + EXPECT_FALSE(AppsPromo::IsPromoSupportedForLocale()); +} + +// Tests that the apps section is maxmized when showing a promo for the first +// time. +TEST_F(ExtensionAppsPromo, UpdatePromoFocus) { + ExtensionIdSet installed_ids; + + bool promo_just_expired = false; + EXPECT_FALSE(apps_promo()->ShouldShowPromo(installed_ids, + &promo_just_expired)); + EXPECT_FALSE(promo_just_expired); + + // Set the promo content. + AppsPromo::SetPromo( + kPromoId, kPromoHeader, kPromoButton, GURL(kPromoLink), kPromoExpire); + + // After asking if we should show the promo, the + EXPECT_TRUE(AppsPromo::IsPromoSupportedForLocale()); + EXPECT_TRUE(apps_promo()->ShouldShowPromo(installed_ids, + &promo_just_expired)); + apps_promo()->MaximizeAppsIfFirstView(); + + EXPECT_TRUE( + (ShownSectionsHandler::GetShownSections(prefs()) & APPS) != 0); + EXPECT_FALSE( + (ShownSectionsHandler::GetShownSections(prefs()) & THUMB) != 0); + + apps_promo()->HidePromo(); + + EXPECT_TRUE((ShownSectionsHandler::GetShownSections(prefs()) & + (MENU_APPS | THUMB)) != 0); +} +#endif // OS_CHROMEOS diff --git a/pool/shard004/C++/0048520_GetTemplateResult.cpp b/pool/shard004/C++/0048520_GetTemplateResult.cpp new file mode 100644 index 0000000000000000000000000000000000000000..14addf1ddac4a148b95648bd5243ad7e8f1e970a --- /dev/null +++ b/pool/shard004/C++/0048520_GetTemplateResult.cpp @@ -0,0 +1,65 @@ +/** + * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. + * SPDX-License-Identifier: Apache-2.0. + */ + +#include +#include +#include +#include +#include + +#include + +using namespace Aws::CloudFormation::Model; +using namespace Aws::Utils::Xml; +using namespace Aws::Utils::Logging; +using namespace Aws::Utils; +using namespace Aws; + +GetTemplateResult::GetTemplateResult() +{ +} + +GetTemplateResult::GetTemplateResult(const Aws::AmazonWebServiceResult& result) +{ + *this = result; +} + +GetTemplateResult& GetTemplateResult::operator =(const Aws::AmazonWebServiceResult& result) +{ + const XmlDocument& xmlDocument = result.GetPayload(); + XmlNode rootNode = xmlDocument.GetRootElement(); + XmlNode resultNode = rootNode; + if (!rootNode.IsNull() && (rootNode.GetName() != "GetTemplateResult")) + { + resultNode = rootNode.FirstChild("GetTemplateResult"); + } + + if(!resultNode.IsNull()) + { + XmlNode templateBodyNode = resultNode.FirstChild("TemplateBody"); + if(!templateBodyNode.IsNull()) + { + m_templateBody = Aws::Utils::Xml::DecodeEscapedXmlText(templateBodyNode.GetText()); + } + XmlNode stagesAvailableNode = resultNode.FirstChild("StagesAvailable"); + if(!stagesAvailableNode.IsNull()) + { + XmlNode stagesAvailableMember = stagesAvailableNode.FirstChild("member"); + while(!stagesAvailableMember.IsNull()) + { + m_stagesAvailable.push_back(TemplateStageMapper::GetTemplateStageForName(StringUtils::Trim(stagesAvailableMember.GetText().c_str()))); + stagesAvailableMember = stagesAvailableMember.NextNode("member"); + } + + } + } + + if (!rootNode.IsNull()) { + XmlNode responseMetadataNode = rootNode.FirstChild("ResponseMetadata"); + m_responseMetadata = responseMetadataNode; + AWS_LOGSTREAM_DEBUG("Aws::CloudFormation::Model::GetTemplateResult", "x-amzn-request-id: " << m_responseMetadata.GetRequestId() ); + } + return *this; +} diff --git a/pool/shard004/C++/0048522_Addon.cpp b/pool/shard004/C++/0048522_Addon.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e5012a0a8d4078c0572d1b657fbfd8bdc3170d4e --- /dev/null +++ b/pool/shard004/C++/0048522_Addon.cpp @@ -0,0 +1,201 @@ +/** + * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. + * SPDX-License-Identifier: Apache-2.0. + */ + +#include +#include + +#include + +using namespace Aws::Utils::Json; +using namespace Aws::Utils; + +namespace Aws +{ +namespace EKS +{ +namespace Model +{ + +Addon::Addon() : + m_addonNameHasBeenSet(false), + m_clusterNameHasBeenSet(false), + m_status(AddonStatus::NOT_SET), + m_statusHasBeenSet(false), + m_addonVersionHasBeenSet(false), + m_healthHasBeenSet(false), + m_addonArnHasBeenSet(false), + m_createdAtHasBeenSet(false), + m_modifiedAtHasBeenSet(false), + m_serviceAccountRoleArnHasBeenSet(false), + m_tagsHasBeenSet(false) +{ +} + +Addon::Addon(JsonView jsonValue) : + m_addonNameHasBeenSet(false), + m_clusterNameHasBeenSet(false), + m_status(AddonStatus::NOT_SET), + m_statusHasBeenSet(false), + m_addonVersionHasBeenSet(false), + m_healthHasBeenSet(false), + m_addonArnHasBeenSet(false), + m_createdAtHasBeenSet(false), + m_modifiedAtHasBeenSet(false), + m_serviceAccountRoleArnHasBeenSet(false), + m_tagsHasBeenSet(false) +{ + *this = jsonValue; +} + +Addon& Addon::operator =(JsonView jsonValue) +{ + if(jsonValue.ValueExists("addonName")) + { + m_addonName = jsonValue.GetString("addonName"); + + m_addonNameHasBeenSet = true; + } + + if(jsonValue.ValueExists("clusterName")) + { + m_clusterName = jsonValue.GetString("clusterName"); + + m_clusterNameHasBeenSet = true; + } + + if(jsonValue.ValueExists("status")) + { + m_status = AddonStatusMapper::GetAddonStatusForName(jsonValue.GetString("status")); + + m_statusHasBeenSet = true; + } + + if(jsonValue.ValueExists("addonVersion")) + { + m_addonVersion = jsonValue.GetString("addonVersion"); + + m_addonVersionHasBeenSet = true; + } + + if(jsonValue.ValueExists("health")) + { + m_health = jsonValue.GetObject("health"); + + m_healthHasBeenSet = true; + } + + if(jsonValue.ValueExists("addonArn")) + { + m_addonArn = jsonValue.GetString("addonArn"); + + m_addonArnHasBeenSet = true; + } + + if(jsonValue.ValueExists("createdAt")) + { + m_createdAt = jsonValue.GetDouble("createdAt"); + + m_createdAtHasBeenSet = true; + } + + if(jsonValue.ValueExists("modifiedAt")) + { + m_modifiedAt = jsonValue.GetDouble("modifiedAt"); + + m_modifiedAtHasBeenSet = true; + } + + if(jsonValue.ValueExists("serviceAccountRoleArn")) + { + m_serviceAccountRoleArn = jsonValue.GetString("serviceAccountRoleArn"); + + m_serviceAccountRoleArnHasBeenSet = true; + } + + if(jsonValue.ValueExists("tags")) + { + Aws::Map tagsJsonMap = jsonValue.GetObject("tags").GetAllObjects(); + for(auto& tagsItem : tagsJsonMap) + { + m_tags[tagsItem.first] = tagsItem.second.AsString(); + } + m_tagsHasBeenSet = true; + } + + return *this; +} + +JsonValue Addon::Jsonize() const +{ + JsonValue payload; + + if(m_addonNameHasBeenSet) + { + payload.WithString("addonName", m_addonName); + + } + + if(m_clusterNameHasBeenSet) + { + payload.WithString("clusterName", m_clusterName); + + } + + if(m_statusHasBeenSet) + { + payload.WithString("status", AddonStatusMapper::GetNameForAddonStatus(m_status)); + } + + if(m_addonVersionHasBeenSet) + { + payload.WithString("addonVersion", m_addonVersion); + + } + + if(m_healthHasBeenSet) + { + payload.WithObject("health", m_health.Jsonize()); + + } + + if(m_addonArnHasBeenSet) + { + payload.WithString("addonArn", m_addonArn); + + } + + if(m_createdAtHasBeenSet) + { + payload.WithDouble("createdAt", m_createdAt.SecondsWithMSPrecision()); + } + + if(m_modifiedAtHasBeenSet) + { + payload.WithDouble("modifiedAt", m_modifiedAt.SecondsWithMSPrecision()); + } + + if(m_serviceAccountRoleArnHasBeenSet) + { + payload.WithString("serviceAccountRoleArn", m_serviceAccountRoleArn); + + } + + if(m_tagsHasBeenSet) + { + JsonValue tagsJsonMap; + for(auto& tagsItem : m_tags) + { + tagsJsonMap.WithString(tagsItem.first, tagsItem.second); + } + payload.WithObject("tags", std::move(tagsJsonMap)); + + } + + return payload; +} + +} // namespace Model +} // namespace EKS +} // namespace Aws diff --git a/pool/shard004/C++/0048527_valuenode.cpp b/pool/shard004/C++/0048527_valuenode.cpp new file mode 100644 index 0000000000000000000000000000000000000000..14d1e6c1c4fe0df14e1ddd76dac37e2766168db5 --- /dev/null +++ b/pool/shard004/C++/0048527_valuenode.cpp @@ -0,0 +1,63 @@ +#include "valuenode.h" +#include +ValueNode::ValueNode(ValueTypeEnum typeValue, QVariant value) + : AbstractValueASTNode(NT_NumericConstant) +{ + + _typeValue = typeValue; + if(_typeValue == typeString){ + _value = value.toString() + .replace("\\t", "\t") + .replace("\\n", "\n"); + } + else { + _value = value; + } +} + +void ValueNode::printNode(int level) +{ + treeStream << QString().fill(' ',level*2) + << QString("Value: %1, type: %2\n").arg(_value.toString()) + .arg(typeName.at(_typeValue)); +} + +QString ValueNode::printTripleCode() +{ + if(getValueType() == typeString) { + QString value = _value.toString(); + QString result = ""; + int i; + for(i = 0; i < _value.toByteArray().length(); i++) { + wchar_t c = value.toStdString().at(i); + if(c > 0x00ff || c < 0x000f){ + + result.append(QString("\\%1") + .arg(value.toStdString().at(i), 2 , 16, QChar('0'))); + } + else + result.append(c); + } + result.replace("ffffffffffffff",""); + return ir.addUnnamedVariable( + QString("private unnamed_addr constant [%1 x i8] c\"%2\\00\"") + .arg(_value.toByteArray().length()+1) + .arg(result + /*.replace("\n","\\0A") + .replace("\t", "\\09")*/)); + } + if(getValueType() == typeDouble || getValueType() == typeFloat) + return QString("%1").arg(_value.toDouble(), 0, 'e', 6); + + return _value.toString(); +} + +QVariant ValueNode::getValue() +{ + return _value; +} + +ValueNode::~ValueNode() +{ + +} diff --git a/pool/shard004/C++/0048531_crypter.cpp b/pool/shard004/C++/0048531_crypter.cpp new file mode 100644 index 0000000000000000000000000000000000000000..5e6184205e5f91f2ac061eb7a8edf28238f2049a --- /dev/null +++ b/pool/shard004/C++/0048531_crypter.cpp @@ -0,0 +1,134 @@ +// Copyright (c) 2009-2012 The Bitcoin Developers +// Copyright (c) 2011-2012 Harucoin Developers +// Distributed under the MIT/X11 software license, see the accompanying +// file COPYING or http://www.opensource.org/licenses/mit-license.php. + +#include +#include +#include +#include +#ifdef WIN32 +#include +#endif + +#include "crypter.h" + +bool CCrypter::SetKeyFromPassphrase(const SecureString& strKeyData, const std::vector& chSalt, const unsigned int nRounds, const unsigned int nDerivationMethod) +{ + if (nRounds < 1 || chSalt.size() != WALLET_CRYPTO_SALT_SIZE) + return false; + + // Try to keep the keydata out of swap (and be a bit over-careful to keep the IV that we don't even use out of swap) + // Note that this does nothing about suspend-to-disk (which will put all our key data on disk) + // Note as well that at no point in this program is any attempt made to prevent stealing of keys by reading the memory of the running process. + mlock(&chKey[0], sizeof chKey); + mlock(&chIV[0], sizeof chIV); + + int i = 0; + if (nDerivationMethod == 0) + i = EVP_BytesToKey(EVP_aes_256_cbc(), EVP_sha512(), &chSalt[0], + (unsigned char *)&strKeyData[0], strKeyData.size(), nRounds, chKey, chIV); + + if (i != (int)WALLET_CRYPTO_KEY_SIZE) + { + memset(&chKey, 0, sizeof chKey); + memset(&chIV, 0, sizeof chIV); + return false; + } + + fKeySet = true; + return true; +} + +bool CCrypter::SetKey(const CKeyingMaterial& chNewKey, const std::vector& chNewIV) +{ + if (chNewKey.size() != WALLET_CRYPTO_KEY_SIZE || chNewIV.size() != WALLET_CRYPTO_KEY_SIZE) + return false; + + // Try to keep the keydata out of swap + // Note that this does nothing about suspend-to-disk (which will put all our key data on disk) + // Note as well that at no point in this program is any attempt made to prevent stealing of keys by reading the memory of the running process. + mlock(&chKey[0], sizeof chKey); + mlock(&chIV[0], sizeof chIV); + + memcpy(&chKey[0], &chNewKey[0], sizeof chKey); + memcpy(&chIV[0], &chNewIV[0], sizeof chIV); + + fKeySet = true; + return true; +} + +bool CCrypter::Encrypt(const CKeyingMaterial& vchPlaintext, std::vector &vchCiphertext) +{ + if (!fKeySet) + return false; + + // max ciphertext len for a n bytes of plaintext is + // n + AES_BLOCK_SIZE - 1 bytes + int nLen = vchPlaintext.size(); + int nCLen = nLen + AES_BLOCK_SIZE, nFLen = 0; + vchCiphertext = std::vector (nCLen); + + EVP_CIPHER_CTX ctx; + + bool fOk = true; + + EVP_CIPHER_CTX_init(&ctx); + if (fOk) fOk = EVP_EncryptInit_ex(&ctx, EVP_aes_256_cbc(), NULL, chKey, chIV); + if (fOk) fOk = EVP_EncryptUpdate(&ctx, &vchCiphertext[0], &nCLen, &vchPlaintext[0], nLen); + if (fOk) fOk = EVP_EncryptFinal_ex(&ctx, (&vchCiphertext[0])+nCLen, &nFLen); + EVP_CIPHER_CTX_cleanup(&ctx); + + if (!fOk) return false; + + vchCiphertext.resize(nCLen + nFLen); + return true; +} + +bool CCrypter::Decrypt(const std::vector& vchCiphertext, CKeyingMaterial& vchPlaintext) +{ + if (!fKeySet) + return false; + + // plaintext will always be equal to or lesser than length of ciphertext + int nLen = vchCiphertext.size(); + int nPLen = nLen, nFLen = 0; + + vchPlaintext = CKeyingMaterial(nPLen); + + EVP_CIPHER_CTX ctx; + + bool fOk = true; + + EVP_CIPHER_CTX_init(&ctx); + if (fOk) fOk = EVP_DecryptInit_ex(&ctx, EVP_aes_256_cbc(), NULL, chKey, chIV); + if (fOk) fOk = EVP_DecryptUpdate(&ctx, &vchPlaintext[0], &nPLen, &vchCiphertext[0], nLen); + if (fOk) fOk = EVP_DecryptFinal_ex(&ctx, (&vchPlaintext[0])+nPLen, &nFLen); + EVP_CIPHER_CTX_cleanup(&ctx); + + if (!fOk) return false; + + vchPlaintext.resize(nPLen + nFLen); + return true; +} + + +bool EncryptSecret(CKeyingMaterial& vMasterKey, const CSecret &vchPlaintext, const uint256& nIV, std::vector &vchCiphertext) +{ + CCrypter cKeyCrypter; + std::vector chIV(WALLET_CRYPTO_KEY_SIZE); + memcpy(&chIV[0], &nIV, WALLET_CRYPTO_KEY_SIZE); + if(!cKeyCrypter.SetKey(vMasterKey, chIV)) + return false; + return cKeyCrypter.Encrypt((CKeyingMaterial)vchPlaintext, vchCiphertext); +} + +bool DecryptSecret(const CKeyingMaterial& vMasterKey, const std::vector& vchCiphertext, const uint256& nIV, CSecret& vchPlaintext) +{ + CCrypter cKeyCrypter; + std::vector chIV(WALLET_CRYPTO_KEY_SIZE); + memcpy(&chIV[0], &nIV, WALLET_CRYPTO_KEY_SIZE); + if(!cKeyCrypter.SetKey(vMasterKey, chIV)) + return false; + return cKeyCrypter.Decrypt(vchCiphertext, *((CKeyingMaterial*)&vchPlaintext)); +} diff --git a/pool/shard004/C++/0048555_AndroidJNIBridge.cc b/pool/shard004/C++/0048555_AndroidJNIBridge.cc new file mode 100644 index 0000000000000000000000000000000000000000..08ce266168c2fda1ec24c38b365bd884619aa3d3 --- /dev/null +++ b/pool/shard004/C++/0048555_AndroidJNIBridge.cc @@ -0,0 +1,141 @@ +/****************************************************************************** + * Copyright (c) 2014, AllSeen Alliance. All rights reserved. + * + * Permission to use, copy, modify, and/or distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + ******************************************************************************/ + +#include +#include +#include +#include +#include +#include +#include "MyEventCode.h" + +/* Static data */ +static MyEventCode* myEventCode = NULL; + +#ifdef __cplusplus +extern "C" { +#endif +/* + * Class: org_allseen_sample_event_tester_BusHandler + * Method: initialize + * Signature: (Ljava/lang/String;)V + */ +JNIEXPORT void JNICALL Java_org_allseen_sample_event_tester_BusHandler_initialize(JNIEnv* env, jobject jobj, jstring packageNameStrObj) { + if (myEventCode == NULL) { + JavaVM* vm; + env->GetJavaVM(&vm); + jobject gjobj = env->NewGlobalRef(jobj); + myEventCode = new MyEventCode(vm, gjobj); + } + jboolean iscopy; + const char* packageNameStr = env->GetStringUTFChars(packageNameStrObj, &iscopy); + myEventCode->initialize(packageNameStr); + env->ReleaseStringUTFChars(packageNameStrObj, packageNameStr); +} + +/* + * Class: org_allseen_sample_event_tester_BusHandler + * Method: dointrospection + * Signature: (Ljava/lang/String;Ljava/lang/String;I)Ljava/langString; + */ +JNIEXPORT jstring JNICALL Java_org_allseen_sample_event_tester_BusHandler_doIntrospection(JNIEnv* env, jobject jobj, jstring jname, jstring jpath, jint sessionId) { + jboolean iscopy; + jboolean iscopy2; + const char* sessionName = env->GetStringUTFChars(jname, &iscopy); + const char* path = env->GetStringUTFChars(jpath, &iscopy2); + char* xml = myEventCode->introspectWithDescriptions(sessionName, path, sessionId); + env->ReleaseStringUTFChars(jname, sessionName); + env->ReleaseStringUTFChars(jpath, path); + jstring ret = env->NewStringUTF(xml); + delete xml; + return ret; +} + +JNIEXPORT void JNICALL Java_org_allseen_sample_event_tester_BusHandler_introspectionDone(JNIEnv* env, jobject jobj, jint sessionId) { + myEventCode->leaveSession(sessionId); +} + + +JNIEXPORT jboolean JNICALL Java_org_allseen_sample_event_tester_BusHandler_enableEvent(JNIEnv*env, jobject jobj, + //event + jstring jEUniqueName, jstring jEPath, + jstring jEIface, jstring jEMember, jstring jESig) +{ + jboolean iscopy; + + const char* eUniqueName = env->GetStringUTFChars(jEUniqueName, &iscopy); + const char* ePath = env->GetStringUTFChars(jEPath, &iscopy); + const char* eIface = env->GetStringUTFChars(jEIface, &iscopy); + const char* eMember = env->GetStringUTFChars(jEMember, &iscopy); + const char* eSig = env->GetStringUTFChars(jESig, &iscopy); + EventInfo* event = new EventInfo(eUniqueName, ePath, eIface, eMember, eSig); + + LOGTHIS("enabling an event on %s::%s", eIface, eMember); + bool ret = myEventCode->enableEvent(event); + + delete event; + + env->ReleaseStringUTFChars(jEUniqueName, eUniqueName); + env->ReleaseStringUTFChars(jEPath, ePath); + env->ReleaseStringUTFChars(jEIface, eIface); + env->ReleaseStringUTFChars(jEMember, eMember); + env->ReleaseStringUTFChars(jESig, eSig); + + return ret == true ? JNI_TRUE : JNI_FALSE; +} + +JNIEXPORT void JNICALL Java_org_allseen_sample_event_tester_BusHandler_callAction(JNIEnv*env, jobject jobj, + //action + jstring jAUniqueName, jstring jAPath, + jstring jAIface, jstring jAMember, jstring jASig) +{ + jboolean iscopy; + + const char* aUniqueName = env->GetStringUTFChars(jAUniqueName, &iscopy); + const char* aPath = env->GetStringUTFChars(jAPath, &iscopy); + const char* aIface = env->GetStringUTFChars(jAIface, &iscopy); + const char* aMember = env->GetStringUTFChars(jAMember, &iscopy); + const char* aSig = env->GetStringUTFChars(jASig, &iscopy); + ActionInfo* action = new ActionInfo(aUniqueName, aPath, aIface, aMember, aSig); + + LOGTHIS("Calling an action on %s", aUniqueName); + myEventCode->callAction(action); + + delete action; + + env->ReleaseStringUTFChars(jAUniqueName, aUniqueName); + env->ReleaseStringUTFChars(jAPath, aPath); + env->ReleaseStringUTFChars(jAIface, aIface); + env->ReleaseStringUTFChars(jAMember, aMember); + env->ReleaseStringUTFChars(jASig, aSig); +} + +/* + * Class: org_allseen_sample_event_tester_BusHandler + * Method: shutdown + * Signature: ()V + */ +JNIEXPORT void JNICALL Java_org_allseen_sample_event_tester_BusHandler_shutdown(JNIEnv* env, jobject jobj) { +// if(myEventCode) +// myEventCode->shutdown(); +// delete MyEventCode; +// MyEventCode = NULL; +} + +#ifdef __cplusplus +} +#endif + diff --git a/pool/shard004/C++/0048558_containsintegerpoint1.cc b/pool/shard004/C++/0048558_containsintegerpoint1.cc new file mode 100644 index 0000000000000000000000000000000000000000..dab4cd67b9698b77ea7bbde8ee4ba8a71f6e0cc5 --- /dev/null +++ b/pool/shard004/C++/0048558_containsintegerpoint1.cc @@ -0,0 +1,131 @@ +/* Test Pointset_Powerset::contains_integer_point(), + Copyright (C) 2001-2009 Roberto Bagnara + +This file is part of the Parma Polyhedra Library (PPL). + +The PPL is free software; you can redistribute it and/or modify it +under the terms of the GNU General Public License as published by the +Free Software Foundation; either version 3 of the License, or (at your +option) any later version. + +The PPL is distributed in the hope that it will be useful, but WITHOUT +ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +FITNESS FOR A PARTICULAR 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-1307, USA. + +For the most up-to-date information see the Parma Polyhedra Library +site: http://www.cs.unipr.it/ppl/ . */ + +#include "ppl_test.hh" + +namespace { + +// Powerset of C polyhedra: contains_integer_point() returns false. +bool +test01() { + Variable x(0); + Variable y(1); + + Pointset_Powerset ps(2); + Constraint_System cs; + cs.insert(x >= 0); + cs.insert(x <= 1); + cs.insert(4*y <= 3); + cs.insert(4*y >= 1); + + ps.refine_with_constraints(cs); + + bool contains = ps.contains_integer_point(); + + print_constraints(ps, "*** ps ***"); + nout << "ps.contains_integer_point() == " + << (contains ? "true" : "false") << endl; + + return !contains; +} + +// Powerset of C polyhedra: contains_integer_point() returns true. +bool +test02() { + Variable x(0); + Variable y(1); + Variable z(2); + + Pointset_Powerset ps(3); + Constraint_System cs; + cs.insert(x >= 0); + cs.insert(x <= 1); + cs.insert(4*z - 4*y >= 3); + + ps.refine_with_constraints(cs); + + print_constraints(ps, "*** ps ***"); + + bool contains = ps.contains_integer_point(); + + nout << "ps.contains_integer_point() == " + << (contains ? "true" : "false") << endl; + + return contains; +} + +// Empty 0-dimensional powerset of C polyhedra: contains_integer_point(). +bool +test03() { + Pointset_Powerset ps(0, EMPTY); + + print_constraints(ps, "*** ps ***"); + + bool contains = ps.contains_integer_point(); + + nout << "ps.contains_integer_point() == " + << (contains ? "true" : "false") << endl; + + return !contains; +} + +// Universe 0-dimensional powerset of C polyhedra: contains_integer_point(). +bool +test04() { + Pointset_Powerset ps(0); + + bool contains = ps.contains_integer_point(); + + print_constraints(ps, "*** ps ***"); + + nout << "ps.contains_integer_point() == " + << (contains ? "true" : "false") << endl; + + return contains; +} + +// Empty 1-dimensional powerset of C polyhedra: contains_integer_point(). +bool +test05() { + Pointset_Powerset ps(1); + + ps.refine_with_constraint(Linear_Expression(0) == 1); + + bool contains = ps.contains_integer_point(); + + print_constraints(ps, "*** ps ***"); + + nout << "ps.contains_integer_point() == " + << (contains ? "true" : "false") << endl; + + return !contains; +} + +} // namespace + +BEGIN_MAIN + DO_TEST(test01); + DO_TEST(test02); + DO_TEST(test03); + DO_TEST(test04); + DO_TEST(test05); +END_MAIN diff --git a/pool/shard004/C++/0048564_MayaPlugin.cpp b/pool/shard004/C++/0048564_MayaPlugin.cpp new file mode 100644 index 0000000000000000000000000000000000000000..134a6e7dd4af8547ac472af09c1d39f60ae3d906 --- /dev/null +++ b/pool/shard004/C++/0048564_MayaPlugin.cpp @@ -0,0 +1,82 @@ +// +// UVAutoRatio Maya Plugin Source Code +// Copyright (C) 2007-2014 RenderHeads Ltd. +// +// This source is available for distribution and/or modification +// only under the terms of the MIT license. All rights reserved. +// +// The source is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// FITNESS FOR A PARTICULAR PURPOSE. See the MIT license +// for more details. +// + +#include "MayaPCH.h" +#include "MayaUtility.h" +#include "MayaPlugin.h" + +MayaPlugin::MayaPlugin(const MayaPluginParams& params) +{ + m_productName = params.productName; + m_productShortName = params.productShortName; + m_authorString = params.authorString; + m_versionString = params.versionString; + +#ifdef _DEBUG + MGlobal::startErrorLogging(); +#endif +} + +MayaPlugin::~MayaPlugin() +{ +#ifdef _DEBUG + MGlobal::stopErrorLogging(); + MGlobal::closeErrorLog(); +#endif +} + +void +MayaPlugin::Load(MObject& pluginObject) +{ + char finalVersionStr[256]; +#ifdef WIN32 + sprintf_s(finalVersionStr, sizeof(finalVersionStr), "%s, %s @ %s", m_versionString.asChar(), __DATE__, __TIME__); +#else + sprintf(finalVersionStr, "%s, | %s @ %s", m_versionString.asChar(), __DATE__, __TIME__); +#endif + + MFnPlugin plugin(pluginObject, m_authorString.asChar(), finalVersionStr, "Any"); + + + LoadFeatures(plugin); +} + +void +MayaPlugin::Unload(MObject& pluginObject) +{ + MStatus status; + MFnPlugin plugin(pluginObject); + + UnloadUserPlugins(plugin); +} + +void +MayaPlugin::LoadFeatures(MFnPlugin& plugin) +{ + LoadUserPlugins(plugin); +} + +void +MayaPlugin::DisplayInfo(const MString& text) const +{ + MGlobal::displayInfo(m_productShortName + ": " + text); +} + +void +MayaPlugin::DisplayWarning(const MString& text) const +{ + MGlobal::displayWarning(m_productShortName + ": " + text); +} + +/////////////////////////////////////////////////////////////////////////////// +/////////////////////////////////////////////////////////////////////////////// \ No newline at end of file diff --git a/pool/shard004/C++/0048565_demo_ballDEM.cpp b/pool/shard004/C++/0048565_demo_ballDEM.cpp new file mode 100644 index 0000000000000000000000000000000000000000..25be27d6e9f08a6d4b55eb0a58164dd5df73ffaa --- /dev/null +++ b/pool/shard004/C++/0048565_demo_ballDEM.cpp @@ -0,0 +1,184 @@ +// +// PROJECT CHRONO - http://projectchrono.org +// +// Copyright (c) 2013 Project Chrono +// All rights reserved. +// +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file at the top level of the distribution +// and at http://projectchrono.org/license-chrono.txt. +// + +/////////////////////////////////////////////////// +// +// Demo code about +// +// - collisions and contacts with DEM +// +// CHRONO +// ------ +// Multibody dinamics engine +// +/////////////////////////////////////////////////// + +#include "chrono/physics/ChSystemDEM.h" +#include "chrono/physics/ChContactContainerDEM.h" +#include "chrono/lcp/ChLcpSolverDEM.h" + +#include "chrono_irrlicht/ChIrrApp.h" + +#include + +// Use the namespaces of Chrono +using namespace chrono; +using namespace chrono::irrlicht; + +// Use the main namespaces of Irrlicht +using namespace irr; +using namespace irr::core; +using namespace irr::scene; +using namespace irr::video; +using namespace irr::io; +using namespace irr::gui; + +void AddWall(ChSharedPtr body, const ChVector<>& dim, const ChVector<>& loc) { + body->GetCollisionModel()->AddBox(dim.x, dim.y, dim.z, loc); + + ChSharedPtr box(new ChBoxShape); + box->GetBoxGeometry().Size = dim; + box->GetBoxGeometry().Pos = loc; + box->SetColor(ChColor(1, 0, 0)); + box->SetFading(0.6f); + body->AddAsset(box); +} + +int main(int argc, char* argv[]) { + // Simulation parameters + double gravity = -9.81; + double time_step = 0.00001; + double out_step = 2000 * time_step; + + // Parameters for the falling ball + int ballId = 100; + double radius = 1; + double mass = 1000; + ChVector<> pos(0, 2, 0); + ChQuaternion<> rot(1, 0, 0, 0); + ChVector<> init_vel(0, 0, 0); + + // Parameters for the containing bin + int binId = 200; + double width = 2; + double length = 2; + double height = 1; + double thickness = 0.1; + + // Create the system + ChSystemDEM msystem; + + // The following two lines are optional, since they are the default options. They are added for future reference, + // i.e. when needed to change those models. + msystem.SetContactForceModel(ChSystemDEM::ContactForceModel::Hertz); + msystem.SetAdhesionForceModel(ChSystemDEM::AdhesionForceModel::Constant); + + msystem.Set_G_acc(ChVector<>(0, gravity, 0)); + + // Create the Irrlicht visualization + ChIrrApp application(&msystem, L"DEM demo", core::dimension2d(800, 600), false, true); + + // Easy shortcuts to add camera, lights, logo and sky in Irrlicht scene + application.AddTypicalLogo(); + application.AddTypicalSky(); + application.AddTypicalLights(); + application.AddTypicalCamera(core::vector3df(0, 3, -6)); + + // This means that contactforces will be shown in Irrlicht application + application.SetSymbolscale(1e-4); + application.SetContactsDrawMode(ChIrrTools::eCh_ContactsDrawMode::CONTACT_FORCES); + + // Create a material (will be used by both objects) + ChSharedPtr material; + material = ChSharedPtr(new ChMaterialSurfaceDEM); + material->SetRestitution(0.1f); + material->SetFriction(0.4f); + material->SetAdhesion(0); // Magnitude of the adhesion in Constant adhesion model + + // Create the falling ball + ChSharedPtr ball(new ChBody(ChMaterialSurfaceBase::DEM)); + + ball->SetIdentifier(ballId); + ball->SetMass(mass); + ball->SetPos(pos); + ball->SetRot(rot); + ball->SetPos_dt(init_vel); + // ball->SetWvel_par(ChVector<>(0,0,3)); + ball->SetBodyFixed(false); + ball->SetMaterialSurface(material); + + ball->SetCollide(true); + + ball->GetCollisionModel()->ClearModel(); + ball->GetCollisionModel()->AddSphere(radius); + ball->GetCollisionModel()->BuildModel(); + + ball->SetInertiaXX(0.4 * mass * radius * radius * ChVector<>(1, 1, 1)); + + ChSharedPtr sphere(new ChSphereShape); + sphere->GetSphereGeometry().rad = radius; + ball->AddAsset(sphere); + + ChSharedPtr mtexture(new ChTexture); + mtexture->SetTextureFilename(GetChronoDataFile("bluwhite.png")); + ball->AddAsset(mtexture); + + msystem.AddBody(ball); + + // Create container + ChSharedPtr bin(new ChBody(ChMaterialSurfaceBase::DEM)); + + bin->SetIdentifier(binId); + bin->SetMass(1); + bin->SetPos(ChVector<>(0, 0, 0)); + bin->SetRot(ChQuaternion<>(1, 0, 0, 0)); + bin->SetCollide(true); + bin->SetBodyFixed(true); + bin->SetMaterialSurface(material); + + bin->GetCollisionModel()->ClearModel(); + AddWall(bin, ChVector<>(width, thickness, length), ChVector<>(0, 0, 0)); + // AddWall(bin, ChVector<>(thickness, height, length), ChVector<>(-width + thickness, height, 0)); + // AddWall(bin, ChVector<>(thickness, height, length), ChVector<>(width - thickness, height, 0)); + // AddWall(bin, ChVector<>(width, height, thickness), ChVector<>(0, height, -length + thickness)); + // AddWall(bin, ChVector<>(width, height, thickness), ChVector<>(0, height, length - thickness)); + bin->GetCollisionModel()->BuildModel(); + + msystem.AddBody(bin); + + // Complete asset construction + application.AssetBindAll(); + application.AssetUpdateAll(); + + // The soft-real-time cycle + double time = 0.0; + double out_time = 0.0; + + while (application.GetDevice()->run()) { + application.BeginScene(); + + application.DrawAll(); + + ChIrrTools::drawGrid(application.GetVideoDriver(), 0.2, 0.2, 20, 20, + ChCoordsys<>(ChVector<>(0, 0, 0), Q_from_AngX(CH_C_PI_2)), + video::SColor(255, 80, 100, 100), true); + + while (time < out_time) { + msystem.DoStepDynamics(time_step); + time += time_step; + } + out_time += out_step; + + application.EndScene(); + } + + return 0; +} diff --git a/pool/shard004/C++/0048580_signals_unittest.cc b/pool/shard004/C++/0048580_signals_unittest.cc new file mode 100644 index 0000000000000000000000000000000000000000..3acdb3117329b22397d893de17afece5dfe66395 --- /dev/null +++ b/pool/shard004/C++/0048580_signals_unittest.cc @@ -0,0 +1,222 @@ +// Copyright 2017 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 "build/build_config.h" +#include "mojo/core/test/mojo_test_base.h" +#include "mojo/public/c/system/buffer.h" +#include "mojo/public/c/system/data_pipe.h" +#include "mojo/public/c/system/functions.h" +#include "mojo/public/c/system/message_pipe.h" +#include "mojo/public/c/system/trap.h" +#include "mojo/public/c/system/types.h" + +namespace mojo { +namespace core { +namespace { + +using SignalsTest = test::MojoTestBase; + +TEST_F(SignalsTest, QueryInvalidArguments) { + MojoHandleSignalsState state = {0, 0}; + EXPECT_EQ(MOJO_RESULT_INVALID_ARGUMENT, + MojoQueryHandleSignalsState(MOJO_HANDLE_INVALID, &state)); + + MojoHandle a, b; + CreateMessagePipe(&a, &b); + EXPECT_EQ(MOJO_RESULT_INVALID_ARGUMENT, + MojoQueryHandleSignalsState(a, nullptr)); +} + +TEST_F(SignalsTest, QueryMessagePipeSignals) { + MojoHandleSignalsState state = {0, 0}; + + MojoHandle a, b; + CreateMessagePipe(&a, &b); + + EXPECT_EQ(MOJO_RESULT_OK, MojoQueryHandleSignalsState(a, &state)); + EXPECT_EQ(MOJO_HANDLE_SIGNAL_WRITABLE, state.satisfied_signals); + EXPECT_EQ(MOJO_HANDLE_SIGNAL_READABLE | MOJO_HANDLE_SIGNAL_WRITABLE | + MOJO_HANDLE_SIGNAL_PEER_CLOSED | + MOJO_HANDLE_SIGNAL_PEER_REMOTE | + MOJO_HANDLE_SIGNAL_QUOTA_EXCEEDED, + state.satisfiable_signals); + + EXPECT_EQ(MOJO_RESULT_OK, MojoQueryHandleSignalsState(b, &state)); + EXPECT_EQ(MOJO_HANDLE_SIGNAL_WRITABLE, state.satisfied_signals); + EXPECT_EQ(MOJO_HANDLE_SIGNAL_READABLE | MOJO_HANDLE_SIGNAL_WRITABLE | + MOJO_HANDLE_SIGNAL_PEER_CLOSED | + MOJO_HANDLE_SIGNAL_PEER_REMOTE | + MOJO_HANDLE_SIGNAL_QUOTA_EXCEEDED, + state.satisfiable_signals); + + WriteMessage(a, "ok"); + EXPECT_EQ(MOJO_RESULT_OK, WaitForSignals(b, MOJO_HANDLE_SIGNAL_READABLE)); + + EXPECT_EQ(MOJO_RESULT_OK, MojoQueryHandleSignalsState(b, &state)); + EXPECT_EQ(MOJO_HANDLE_SIGNAL_READABLE | MOJO_HANDLE_SIGNAL_WRITABLE, + state.satisfied_signals); + EXPECT_EQ(MOJO_HANDLE_SIGNAL_READABLE | MOJO_HANDLE_SIGNAL_WRITABLE | + MOJO_HANDLE_SIGNAL_PEER_CLOSED | + MOJO_HANDLE_SIGNAL_PEER_REMOTE | + MOJO_HANDLE_SIGNAL_QUOTA_EXCEEDED, + state.satisfiable_signals); + + EXPECT_EQ("ok", ReadMessage(b)); + + EXPECT_EQ(MOJO_RESULT_OK, MojoQueryHandleSignalsState(b, &state)); + EXPECT_EQ(MOJO_HANDLE_SIGNAL_WRITABLE, state.satisfied_signals); + EXPECT_EQ(MOJO_HANDLE_SIGNAL_READABLE | MOJO_HANDLE_SIGNAL_WRITABLE | + MOJO_HANDLE_SIGNAL_PEER_CLOSED | + MOJO_HANDLE_SIGNAL_PEER_REMOTE | + MOJO_HANDLE_SIGNAL_QUOTA_EXCEEDED, + state.satisfiable_signals); + + EXPECT_EQ(MOJO_RESULT_OK, MojoClose(a)); + + EXPECT_EQ(MOJO_RESULT_OK, WaitForSignals(b, MOJO_HANDLE_SIGNAL_PEER_CLOSED)); + + EXPECT_EQ(MOJO_RESULT_OK, MojoQueryHandleSignalsState(b, &state)); + EXPECT_EQ(MOJO_HANDLE_SIGNAL_PEER_CLOSED, state.satisfied_signals); + EXPECT_EQ(MOJO_HANDLE_SIGNAL_PEER_CLOSED | MOJO_HANDLE_SIGNAL_QUOTA_EXCEEDED, + state.satisfiable_signals); +} + +TEST_F(SignalsTest, LocalPeers) { + MojoHandleSignalsState state = {0, 0}; + MojoHandle a, b, c, d; + CreateMessagePipe(&a, &b); + CreateMessagePipe(&c, &d); + + EXPECT_EQ(MOJO_RESULT_OK, MojoQueryHandleSignalsState(a, &state)); + EXPECT_TRUE(state.satisfiable_signals & MOJO_HANDLE_SIGNAL_PEER_REMOTE); + EXPECT_FALSE(state.satisfied_signals & MOJO_HANDLE_SIGNAL_PEER_REMOTE); + + EXPECT_EQ(MOJO_RESULT_OK, MojoQueryHandleSignalsState(b, &state)); + EXPECT_TRUE(state.satisfiable_signals & MOJO_HANDLE_SIGNAL_PEER_REMOTE); + EXPECT_FALSE(state.satisfied_signals & MOJO_HANDLE_SIGNAL_PEER_REMOTE); + + EXPECT_EQ(MOJO_RESULT_OK, MojoQueryHandleSignalsState(c, &state)); + EXPECT_TRUE(state.satisfiable_signals & MOJO_HANDLE_SIGNAL_PEER_REMOTE); + EXPECT_FALSE(state.satisfied_signals & MOJO_HANDLE_SIGNAL_PEER_REMOTE); + + EXPECT_EQ(MOJO_RESULT_OK, MojoQueryHandleSignalsState(d, &state)); + EXPECT_TRUE(state.satisfiable_signals & MOJO_HANDLE_SIGNAL_PEER_REMOTE); + EXPECT_FALSE(state.satisfied_signals & MOJO_HANDLE_SIGNAL_PEER_REMOTE); + + // Verify that sending a local pipe over a local pipe doesn't change the + // perceived locality of the peer. + const char kMessage[] = "ayyy"; + WriteMessageWithHandles(a, kMessage, &c, 1); + EXPECT_EQ(kMessage, ReadMessageWithHandles(b, &c, 1)); + + WriteMessage(c, kMessage); + EXPECT_EQ(kMessage, ReadMessage(d)); + + EXPECT_EQ(MOJO_RESULT_OK, MojoQueryHandleSignalsState(c, &state)); + EXPECT_TRUE(state.satisfiable_signals & MOJO_HANDLE_SIGNAL_PEER_REMOTE); + EXPECT_FALSE(state.satisfied_signals & MOJO_HANDLE_SIGNAL_PEER_REMOTE); + + EXPECT_EQ(MOJO_RESULT_OK, MojoQueryHandleSignalsState(d, &state)); + EXPECT_TRUE(state.satisfiable_signals & MOJO_HANDLE_SIGNAL_PEER_REMOTE); + EXPECT_FALSE(state.satisfied_signals & MOJO_HANDLE_SIGNAL_PEER_REMOTE); + + // Sanity check: a closed peer can never signal remoteness. + EXPECT_EQ(MOJO_RESULT_OK, MojoClose(c)); + EXPECT_EQ(MOJO_RESULT_OK, MojoQueryHandleSignalsState(d, &state)); + EXPECT_FALSE(state.satisfiable_signals & MOJO_HANDLE_SIGNAL_PEER_REMOTE); + EXPECT_EQ(MOJO_RESULT_OK, MojoClose(d)); + + EXPECT_EQ(MOJO_RESULT_OK, MojoClose(a)); + EXPECT_EQ(MOJO_RESULT_OK, MojoClose(b)); +} + +#if !BUILDFLAG(IS_IOS) + +TEST_F(SignalsTest, RemotePeers) { + MojoHandleSignalsState state = {0, 0}; + MojoHandle a, b; + CreateMessagePipe(&a, &b); + + EXPECT_EQ(MOJO_RESULT_OK, MojoQueryHandleSignalsState(a, &state)); + EXPECT_TRUE(state.satisfiable_signals & MOJO_HANDLE_SIGNAL_PEER_REMOTE); + EXPECT_FALSE(state.satisfied_signals & MOJO_HANDLE_SIGNAL_PEER_REMOTE); + EXPECT_EQ(MOJO_RESULT_OK, + WaitForSignals(a, MOJO_HANDLE_SIGNAL_PEER_REMOTE, + MOJO_TRIGGER_CONDITION_SIGNALS_UNSATISFIED)); + + EXPECT_EQ(MOJO_RESULT_OK, MojoQueryHandleSignalsState(b, &state)); + EXPECT_TRUE(state.satisfiable_signals & MOJO_HANDLE_SIGNAL_PEER_REMOTE); + EXPECT_FALSE(state.satisfied_signals & MOJO_HANDLE_SIGNAL_PEER_REMOTE); + EXPECT_EQ(MOJO_RESULT_OK, + WaitForSignals(b, MOJO_HANDLE_SIGNAL_PEER_REMOTE, + MOJO_TRIGGER_CONDITION_SIGNALS_UNSATISFIED)); + + RunTestClient("RemotePeersClient", [&](MojoHandle h) { + // The bootstrap pipe should eventually signal remoteness. + EXPECT_EQ(MOJO_RESULT_OK, + WaitForSignals(h, MOJO_HANDLE_SIGNAL_PEER_REMOTE, + MOJO_TRIGGER_CONDITION_SIGNALS_SATISFIED)); + + // And so should |a| after we send its peer. + WriteMessageWithHandles(h, ":)", &b, 1); + EXPECT_EQ(MOJO_RESULT_OK, + WaitForSignals(a, MOJO_HANDLE_SIGNAL_PEER_REMOTE, + MOJO_TRIGGER_CONDITION_SIGNALS_SATISFIED)); + EXPECT_EQ(MOJO_RESULT_OK, MojoQueryHandleSignalsState(a, &state)); + EXPECT_TRUE(state.satisfied_signals & MOJO_HANDLE_SIGNAL_PEER_REMOTE); + + // And so should |c| after we fuse |d| to |a|. + MojoHandle c, d; + CreateMessagePipe(&c, &d); + EXPECT_EQ(MOJO_RESULT_OK, MojoFuseMessagePipes(d, a, nullptr)); + EXPECT_EQ(MOJO_RESULT_OK, + WaitForSignals(c, MOJO_HANDLE_SIGNAL_PEER_REMOTE, + MOJO_TRIGGER_CONDITION_SIGNALS_SATISFIED)); + EXPECT_EQ(MOJO_RESULT_OK, MojoQueryHandleSignalsState(c, &state)); + EXPECT_TRUE(state.satisfied_signals & MOJO_HANDLE_SIGNAL_PEER_REMOTE); + + // We fused c-d to a-b, so we'll just sort of "rename" |c| back to |a| so + // the system resembles the state it was in before we did that. + a = c; + + WriteMessage(h, "OK!"); + + // Read |b| back before joining the client. + EXPECT_EQ("O_O", ReadMessageWithHandles(h, &b, 1)); + + // Wait for |a| to see its peer as local again. + EXPECT_EQ(MOJO_RESULT_OK, + WaitForSignals(a, MOJO_HANDLE_SIGNAL_PEER_REMOTE, + MOJO_TRIGGER_CONDITION_SIGNALS_UNSATISFIED)); + EXPECT_EQ(MOJO_RESULT_OK, MojoQueryHandleSignalsState(a, &state)); + EXPECT_FALSE(state.satisfied_signals & MOJO_HANDLE_SIGNAL_PEER_REMOTE); + }); +} + +DEFINE_TEST_CLIENT_TEST_WITH_PIPE(RemotePeersClient, SignalsTest, h) { + // The bootstrap pipe should eventually signal remoteness. + EXPECT_EQ(MOJO_RESULT_OK, + WaitForSignals(h, MOJO_HANDLE_SIGNAL_PEER_REMOTE, + MOJO_TRIGGER_CONDITION_SIGNALS_SATISFIED)); + + MojoHandle b; + EXPECT_EQ(":)", ReadMessageWithHandles(h, &b, 1)); + + // And so should |b|. + EXPECT_EQ(MOJO_RESULT_OK, + WaitForSignals(b, MOJO_HANDLE_SIGNAL_PEER_REMOTE, + MOJO_TRIGGER_CONDITION_SIGNALS_SATISFIED)); + + // Wait for the test to signal that it's ready to read |b| back. + EXPECT_EQ("OK!", ReadMessage(h)); + + // Now send |b| back home. + WriteMessageWithHandles(h, "O_O", &b, 1); +} + +#endif // !BUILDFLAG(IS_IOS) + +} // namespace +} // namespace core +} // namespace mojo diff --git a/pool/shard004/C++/0048581_fpcoptionsplugin.cpp b/pool/shard004/C++/0048581_fpcoptionsplugin.cpp new file mode 100644 index 0000000000000000000000000000000000000000..6fd73e5ffd009288e6c1655a080af607304cdc7f --- /dev/null +++ b/pool/shard004/C++/0048581_fpcoptionsplugin.cpp @@ -0,0 +1,126 @@ +/*************************************************************************** + * Copyright (C) 2003 Alexander Dymo * + * cloudtemple@mksat.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. * + * * + ***************************************************************************/ +#include + +#include +#include + +#include "optiontabs.h" +#include "fpcoptionsplugin.h" + +K_EXPORT_COMPONENT_FACTORY( libkdevfpcoptions, KGenericFactory( "kdevfpcoptions" ) ) + +FpcOptionsPlugin::FpcOptionsPlugin(QObject *parent, const char *name, const QStringList& /*args*/) + : KDevCompilerOptions(parent, name) +{ +} + +FpcOptionsPlugin::~FpcOptionsPlugin() +{ +} + +QString FpcOptionsPlugin::exec(QWidget *parent, const QString &flags) +{ + FpcOptionsDialog *dlg = new FpcOptionsDialog(parent, "fpc options dialog"); + QString newFlags = flags; + dlg->setFlags(flags); + if (dlg->exec() == QDialog::Accepted) + newFlags = dlg->flags(); + delete dlg; + return newFlags; +} + + + +FpcOptionsDialog::FpcOptionsDialog( QWidget *parent, const char *name ) + : KDialogBase(Tabbed, i18n("Free Pascal Compiler Options"), Ok|Cancel, Ok, parent, name, true) +{ + QVBox *vbox; + + vbox = addVBoxPage(i18n("Language")); + language = new LanguageTab(vbox, "language tab"); + + vbox = addVBoxPage(i18n("Locations I")); + directories = new FilesAndDirectoriesTab(vbox, "directories tab"); + + vbox = addVBoxPage(i18n("Locations II")); + directories2 = new FilesAndDirectoriesTab2(vbox, "directories2 tab"); + + vbox = addVBoxPage(i18n("Debug && Optimization")); + debug_optim = new DebugOptimTab(vbox, "debug_optim tab"); + + vbox = addVBoxPage(i18n("Code Generation")); + codegen = new CodegenTab(vbox, "codegen tab"); + + vbox = addVBoxPage(i18n("Assembler")); + assembler = new AssemblerTab(vbox, "assembler tab"); + + vbox = addVBoxPage(i18n("Linker")); + linker = new LinkerTab(vbox, "linker tab"); + + vbox = addVBoxPage(i18n("Feedback")); + feedback = new FeedbackTab(vbox, "feedback tab"); + + vbox = addVBoxPage(i18n("Miscellaneous")); + misc = new MiscTab(vbox, "miscellaneous tab"); +} + +FpcOptionsDialog::~FpcOptionsDialog() +{ +} + +void FpcOptionsDialog::setFlags(const QString &flags) +{ + QStringList flaglist = QStringList::split(" ", flags); + + feedback->readFlags(&flaglist); + language->readFlags(&flaglist); + assembler->readFlags(&flaglist); + linker->readFlags(&flaglist); + codegen->readFlags(&flaglist); + debug_optim->readFlags(&flaglist); + directories->readFlags(&flaglist); + directories2->readFlags(&flaglist); + misc->readFlags(&flaglist); + unrecognizedFlags = flaglist; +} + +QString FpcOptionsDialog::flags() const +{ + QStringList flaglist; + + language->writeFlags(&flaglist); + directories->writeFlags(&flaglist); + directories2->writeFlags(&flaglist); + debug_optim->writeFlags(&flaglist); + codegen->writeFlags(&flaglist); + assembler->writeFlags(&flaglist); + linker->writeFlags(&flaglist); + feedback->writeFlags(&flaglist); + misc->writeFlags(&flaglist); + + QString flags; + QStringList::ConstIterator li; + for (li = flaglist.begin(); li != flaglist.end(); ++li) { + flags += (*li); + flags += " "; + } + + for (li = unrecognizedFlags.begin(); li != unrecognizedFlags.end(); ++li) { + flags += (*li); + flags += " "; + } + + flags.truncate(flags.length()-1); + return flags; +} + +#include "fpcoptionsplugin.moc" diff --git a/pool/shard004/C++/0048582_main.cpp b/pool/shard004/C++/0048582_main.cpp new file mode 100644 index 0000000000000000000000000000000000000000..09b190a7a170c0af27849ad9365d786e921e38c4 --- /dev/null +++ b/pool/shard004/C++/0048582_main.cpp @@ -0,0 +1,169 @@ +// +// main.cpp +// c-steg +// + +#include "CStegApi.h" +#include +#include + +void print_help() { + std::cout << "this is the c-steg command line utility" << std::endl + << std::endl; + + std::cout << "\tto encode a lossless jpeg image with text" << std::endl; + std::cout << "\t\t--encode-lossless" << std::endl; + std::cout << "\t\t--input-file\t\t" + << std::endl; + std::cout << "\t\t--output-file\t\t" + << std::endl; + std::cout << "\t\t--text\t\t\t" << std::endl; + std::cout << "\t\t--quality\t\t" << std::endl; + std::cout << "\t\t--bits-to-steal\t\t" + << std::endl; + std::cout << "" << std::endl; + + std::cout << "\tto decode a lossless jpeg" << std::endl; + std::cout << "\t\t--decode-lossless" << std::endl; + std::cout << "\t\t--input-file\t\t" + << std::endl; + std::cout << "" << std::endl; + + std::cout << "\tto encode a lossy jpeg image with text" << std::endl; + std::cout << "\t\t--encode-lossy" << std::endl; + std::cout << "\t\t--input-file\t\t" + << std::endl; + std::cout << "\t\t--output-file\t\t" + << std::endl; + std::cout << "\t\t--text\t\t\t" << std::endl; + std::cout << "\t\t--quality\t\t" << std::endl; + std::cout + << "\t\t--compressions\t\t" << std::endl; + std::cout << "" << std::endl; + + std::cout << "\tto decode a lossy jpeg" << std::endl; + std::cout << "\t\t--decode-lossy" << std::endl; + std::cout << "\t\t--input-file\t\t" + << std::endl; + std::cout << "" << std::endl; + + std::cout << "\tto get the number of usable coefficients in a file" + << std::endl; + std::cout << "\t\t--coefficients" << std::endl; + std::cout << "\t\t--input-file\t\t" + << std::endl; + std::cout << "" << std::endl; + + std::cout << "\tto do a coefficient diff for two jpeg images" << std::endl; + std::cout << "\t\t--diff" << std::endl; + std::cout << "\t\t--input-file-1\t\t" + << std::endl; + std::cout << "\t\t--input-file-2\t\t" + << std::endl; + std::cout << "" << std::endl; + std::cout << "" << std::endl; +} + +int main(int argc, const char* argv[]) { + const char* input_file = NULL; + const char* output_file = NULL; + const char* input_file_1 = NULL; + const char* input_file_2 = NULL; + const char* text = NULL; + bool encode_lossy = false; + bool encode_lossless = false; + bool decode_lossless = false; + bool decode_lossy = false; + bool number_of_coefficients = false; + bool diff = false; + int quality = 71; + int number_of_compressions = 5; + int bits_to_steal = 2; + + if (argc <= 1) { + std::cout << "***********************" << std::endl; + std::cout + << "you need to pass in some command line flags, here is the help documentation" + << std::endl; + std::cout << "***********************" << std::endl << std::endl; + print_help(); + } + + try { + for (int i = 1; i < argc; ++i) { + if (strcmp("--help", argv[i]) == 0) { + print_help(); + return 0; + } else if (strcmp("--input-file", argv[i]) == 0) { + input_file = argv[++i]; + } else if (strcmp("--input-file-1", argv[i]) == 0) { + input_file_1 = argv[++i]; + } else if (strcmp("--input-file-2", argv[i]) == 0) { + input_file_2 = argv[++i]; + } else if (strcmp("--output-file", argv[i]) == 0) { + output_file = argv[++i]; + } else if (strcmp("--text", argv[i]) == 0) { + text = argv[++i]; + } else if (strcmp("--encode-lossy", argv[i]) == 0) { + encode_lossy = true; + } else if (strcmp("--coefficients", argv[i]) == 0) { + number_of_coefficients = true; + } else if (strcmp("--encode-lossless", argv[i]) == 0) { + encode_lossless = true; + } else if (strcmp("--decode-lossless", argv[i]) == 0) { + decode_lossless = true; + } else if (strcmp("--quality", argv[i]) == 0) { + sscanf(argv[++i], "%d", &quality); + } else if (strcmp("--bits-to-steal", argv[i]) == 0) { + sscanf(argv[++i], "%d", &bits_to_steal); + } else if (strcmp("--compressions", argv[i]) == 0) { + sscanf(argv[++i], "%d", &number_of_compressions); + } else if (strcmp("--decode-lossy", argv[i]) == 0) { + decode_lossy = true; + } else if (strcmp("--diff", argv[i]) == 0) { + diff = true; + } else { + std::cout << "invalid command line arg, use --help to see what commands are valid" << std::endl; + exit(1); + } + } + } catch (...) { + std::cout << "error parsing command line parameters, use --help to see what commands are valid" << std::endl; + exit(1); + } + + if (encode_lossy) { + unsigned int length = strlen(text); + CSteg::encodeLossyJpeg(input_file, output_file, text, length, quality, number_of_compressions); + } else if (decode_lossy) { + DecodeResponse decodeResponse; + CSteg::decodeLossyJpeg(input_file, decodeResponse); + std::cout << "data out length: " << decodeResponse.getLength() << std::endl; + + std::string printString; + printString.assign(decodeResponse.getData(), decodeResponse.getData() + decodeResponse.getLength()); + std::cout << printString << std::endl; + } else if (diff) { + CSteg::doCoefficientDiff(input_file_1, input_file_2); + } else if (encode_lossless) { + unsigned int length = strlen(text); + CSteg::encodeLosslessJpeg(input_file, output_file, (unsigned char*) text, length, bits_to_steal, quality); + std::cout << std::endl; + } else if (decode_lossless) { + DecodeResponse decodeResponse; + CSteg::decodeLosslessJpeg(input_file, decodeResponse); + std::cout << "data out length: " << decodeResponse.getLength() << std::endl; + + std::string printString; + printString.assign(decodeResponse.getData(), decodeResponse.getData() + decodeResponse.getLength()); + std::cout << printString << std::endl; + } else if (number_of_coefficients) { + std::cout << "number of coefficients in file: " << CSteg::getNumberOfCoefficients(input_file) << std::endl; + } + + return 0; +} + diff --git a/pool/shard004/C++/0048594_synth_noise_impl.cc b/pool/shard004/C++/0048594_synth_noise_impl.cc new file mode 100644 index 0000000000000000000000000000000000000000..77c41082a99e971add97b4352d7bcb9c366fce1a --- /dev/null +++ b/pool/shard004/C++/0048594_synth_noise_impl.cc @@ -0,0 +1,63 @@ + /* + + Copyright (C) 2000 Stefan Westerfeld + stefan@space.twc.de + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Library General Public + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Library General Public License for more details. + + You should have received a copy of the GNU Library General Public License + along with this library; see the file COPYING.LIB. If not, write to + the Free Software Foundation, Inc., 59 Temple Place - Suite 330, + Boston, MA 02111-1307, USA. + + */ + +#include + +#include "artsmodulessynth.h" +#include "stdsynthmodule.h" + +using namespace Arts; + +namespace Arts { + +#define NOISE_SIZE 8192 + +class Synth_NOISE_impl : virtual public Synth_NOISE_skel, + virtual public StdSynthModule +{ + static float noise[NOISE_SIZE]; + static bool noiseInit; + unsigned long pos; +public: + Synth_NOISE_impl() + { + if(!noiseInit) + { + for(unsigned long i=0;iGetUnix(); + times[0].tv_nsec=fta->IsSet() ? long(fta->GetUnixNS()%1000000000) : UTIME_NOW; + times[1].tv_sec=ftm->GetUnix(); + times[1].tv_nsec=ftm->IsSet() ? long(ftm->GetUnixNS()%1000000000) : UTIME_NOW; + utimensat(AT_FDCWD,LinkNameA,times,AT_SYMLINK_NOFOLLOW); +#else + struct timeval tv[2]; + tv[0].tv_sec=fta->GetUnix(); + tv[0].tv_usec=long(fta->GetUnixNS()%1000000000/1000); + tv[1].tv_sec=ftm->GetUnix(); + tv[1].tv_usec=long(ftm->GetUnixNS()%1000000000/1000); + lutimes(LinkNameA,tv); +#endif +#endif + + return true; +} + + +static bool IsFullPath(const char *PathA) // Unix ASCII version. +{ + return *PathA==CPATHDIVIDER; +} + + +bool ExtractUnixLink30(CommandData *Cmd,ComprDataIO &DataIO,Archive &Arc,const wchar *LinkName) +{ + char Target[NM]; + if (IsLink(Arc.FileHead.FileAttr)) + { + size_t DataSize=Min(Arc.FileHead.PackSize,ASIZE(Target)-1); + DataIO.UnpRead((byte *)Target,DataSize); + Target[DataSize]=0; + + DataIO.UnpHash.Init(Arc.FileHead.FileHash.Type,1); + DataIO.UnpHash.Update(Target,strlen(Target)); + DataIO.UnpHash.Result(&Arc.FileHead.FileHash); + + // Return true in case of bad checksum, so link will be processed further + // and extraction routine will report the checksum error. + if (!DataIO.UnpHash.Cmp(&Arc.FileHead.FileHash,Arc.FileHead.UseHashKey ? Arc.FileHead.HashKey:NULL)) + return true; + + wchar TargetW[NM]; + CharToWide(Target,TargetW,ASIZE(TargetW)); + // Check for *TargetW==0 to catch CharToWide failure. + // Use Arc.FileHead.FileName instead of LinkName, since LinkName + // can include the destination path as a prefix, which can + // confuse IsRelativeSymlinkSafe algorithm. + if (!Cmd->AbsoluteLinks && (*TargetW==0 || IsFullPath(TargetW) || + !IsRelativeSymlinkSafe(Cmd,Arc.FileHead.FileName,LinkName,TargetW))) + return false; + return UnixSymlink(Target,LinkName,&Arc.FileHead.mtime,&Arc.FileHead.atime); + } + return false; +} + + +bool ExtractUnixLink50(CommandData *Cmd,const wchar *Name,FileHeader *hd) +{ + char Target[NM]; + WideToChar(hd->RedirName,Target,ASIZE(Target)); + if (hd->RedirType==FSREDIR_WINSYMLINK || hd->RedirType==FSREDIR_JUNCTION) + { + // Cannot create Windows absolute path symlinks in Unix. Only relative path + // Windows symlinks can be created here. RAR 5.0 used \??\ prefix + // for Windows absolute symlinks, since RAR 5.1 /??/ is used. + // We escape ? as \? to avoid "trigraph" warning + if (strncmp(Target,"\\??\\",4)==0 || strncmp(Target,"/\?\?/",4)==0) + return false; + DosSlashToUnix(Target,Target,ASIZE(Target)); + } + // Use hd->FileName instead of LinkName, since LinkName can include + // the destination path as a prefix, which can confuse + // IsRelativeSymlinkSafe algorithm. + if (!Cmd->AbsoluteLinks && (IsFullPath(Target) || + !IsRelativeSymlinkSafe(Cmd,hd->FileName,Name,hd->RedirName))) + return false; + return UnixSymlink(Target,Name,&hd->mtime,&hd->atime); +} diff --git a/pool/shard004/C++/0048604_CWE78_OS_Command_Injection__wchar_t_environment_w32_spawnv_73a.cpp b/pool/shard004/C++/0048604_CWE78_OS_Command_Injection__wchar_t_environment_w32_spawnv_73a.cpp new file mode 100644 index 0000000000000000000000000000000000000000..96f16eb6d7dce1e79d72f91f06b1db10559d8bd6 --- /dev/null +++ b/pool/shard004/C++/0048604_CWE78_OS_Command_Injection__wchar_t_environment_w32_spawnv_73a.cpp @@ -0,0 +1,139 @@ +/* TEMPLATE GENERATED TESTCASE FILE +Filename: CWE78_OS_Command_Injection__wchar_t_environment_w32_spawnv_73a.cpp +Label Definition File: CWE78_OS_Command_Injection.strings.label.xml +Template File: sources-sink-73a.tmpl.cpp +*/ +/* + * @description + * CWE: 78 OS Command Injection + * BadSource: environment Read input from an environment variable + * GoodSource: Fixed string + * Sinks: w32_spawnv + * BadSink : execute command with wspawnv + * Flow Variant: 73 Data flow: data passed in a list from one function to another in different source files + * + * */ + +#include "std_testcase.h" +#include + +#include + +#ifdef _WIN32 +#define COMMAND_INT_PATH L"%WINDIR%\\system32\\cmd.exe" +#define COMMAND_INT L"cmd.exe" +#define COMMAND_ARG1 L"/c" +#define COMMAND_ARG2 L"dir " +#define COMMAND_ARG3 data +#else /* NOT _WIN32 */ +#include +#define COMMAND_INT_PATH L"/bin/sh" +#define COMMAND_INT L"sh" +#define COMMAND_ARG1 L"-c" +#define COMMAND_ARG2 L"ls " +#define COMMAND_ARG3 data +#endif + +#define ENV_VARIABLE L"ADD" + +#ifdef _WIN32 +#define GETENV _wgetenv +#else +#define GETENV getenv +#endif + +using namespace std; + +namespace CWE78_OS_Command_Injection__wchar_t_environment_w32_spawnv_73 +{ + +#ifndef OMITBAD + +/* bad function declaration */ +void badSink(list dataList); + +void bad() +{ + wchar_t * data; + list dataList; + wchar_t dataBuffer[100] = COMMAND_ARG2; + data = dataBuffer; + { + /* Append input from an environment variable to data */ + size_t dataLen = wcslen(data); + wchar_t * environment = GETENV(ENV_VARIABLE); + /* If there is data in the environment variable */ + if (environment != NULL) + { + /* POTENTIAL FLAW: Read data from an environment variable */ + wcsncat(data+dataLen, environment, 100-dataLen-1); + } + } + /* Put data in a list */ + dataList.push_back(data); + dataList.push_back(data); + dataList.push_back(data); + badSink(dataList); +} + +#endif /* OMITBAD */ + +#ifndef OMITGOOD + +/* good function declarations */ + +/* goodG2B uses the GoodSource with the BadSink */ +void goodG2BSink(list dataList); + +static void goodG2B() +{ + wchar_t * data; + list dataList; + wchar_t dataBuffer[100] = COMMAND_ARG2; + data = dataBuffer; + /* FIX: Append a fixed string to data (not user / external input) */ + wcscat(data, L"*.*"); + /* Put data in a list */ + dataList.push_back(data); + dataList.push_back(data); + dataList.push_back(data); + goodG2BSink(dataList); +} + +void good() +{ + goodG2B(); +} + +#endif /* OMITGOOD */ + +} /* close namespace */ + +/* Below is the main(). It is only used when building this testcase on + * its own for testing or for building a binary to use in testing binary + * analysis tools. It is not used when compiling all the testcases as one + * application, which is how source code analysis tools are tested. + */ + +#ifdef INCLUDEMAIN + +using namespace CWE78_OS_Command_Injection__wchar_t_environment_w32_spawnv_73; /* so that we can use good and bad easily */ + +int main(int argc, char * argv[]) +{ + /* seed randomness */ + srand( (unsigned)time(NULL) ); +#ifndef OMITGOOD + printLine("Calling good()..."); + good(); + printLine("Finished good()"); +#endif /* OMITGOOD */ +#ifndef OMITBAD + printLine("Calling bad()..."); + bad(); + printLine("Finished bad()"); +#endif /* OMITBAD */ + return 0; +} + +#endif diff --git a/pool/shard004/C++/0048612_util_test.cc b/pool/shard004/C++/0048612_util_test.cc new file mode 100644 index 0000000000000000000000000000000000000000..1dd70754fad753cf82c815263cc0f60638b29bfe --- /dev/null +++ b/pool/shard004/C++/0048612_util_test.cc @@ -0,0 +1,89 @@ +/****************************************************************************** + * Copyright 2017 The Apollo Authors. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + *****************************************************************************/ + +#include "modules/common/util/util.h" + +#include + +#include "gtest/gtest.h" +#include "modules/common/util/testdata/simple.pb.h" + +namespace apollo { +namespace common { +namespace util { + +TEST(Util, IsProtoEqual) { + test::SimpleRepeatedMessage sim1; + for (int i = 0; i < 10; ++i) { + auto* t = sim1.add_message(); + t->set_integer(i); + t->set_text(std::to_string(i)); + } + auto sim2 = sim1; + EXPECT_TRUE(IsProtoEqual(sim1, sim2)); + sim2.mutable_message(0)->set_integer(-1); + EXPECT_FALSE(IsProtoEqual(sim1, sim2)); +} + +TEST(Util, DistanceXY) { + class TestPoint { + public: + TestPoint(double x, double y) : x_(x), y_(y) {} + double x() const { return x_; } + double y() const { return y_; } + + private: + double x_ = 0.0; + double y_ = 0.0; + }; + EXPECT_DOUBLE_EQ(0.0, DistanceXY(TestPoint(0, 0), TestPoint(0, 0))); + EXPECT_DOUBLE_EQ(1.0, DistanceXY(TestPoint(1, 0), TestPoint(0, 0))); + EXPECT_DOUBLE_EQ(1.0, DistanceXY(TestPoint(0, 0), TestPoint(1, 0))); + EXPECT_DOUBLE_EQ(0.0, DistanceXY(TestPoint(1, 0), TestPoint(1, 0))); +} + +TEST(Util, uniform_slice) { + std::vector result; + uniform_slice(0.0, 10.0, 3, &result); + ASSERT_EQ(4, result.size()); + EXPECT_DOUBLE_EQ(0.0, result[0]); + EXPECT_DOUBLE_EQ(3.3333333333333335, result[1]); + EXPECT_DOUBLE_EQ(6.666666666666667, result[2]); + EXPECT_DOUBLE_EQ(10.0, result[3]); + + uniform_slice(0.0, -10.0, 3, &result); + ASSERT_EQ(4, result.size()); + EXPECT_DOUBLE_EQ(0.0, result[0]); + EXPECT_DOUBLE_EQ(-3.3333333333333335, result[1]); + EXPECT_DOUBLE_EQ(-6.666666666666667, result[2]); + EXPECT_DOUBLE_EQ(-10.0, result[3]); +} + +TEST(Util, IsFloatEqual) { + double d1 = 0.2; + double d2 = 1 / std::sqrt(5) / std::sqrt(5); + EXPECT_TRUE(IsFloatEqual(d1, d2)); + double d3 = 0.999999999999999999; + double d4 = 0.999999999999999998; + EXPECT_TRUE(IsFloatEqual(d3, d4)); + double d5 = 0.11; + double d6 = 0.12; + EXPECT_FALSE(IsFloatEqual(d5, d6)); +} + +} // namespace util +} // namespace common +} // namespace apollo diff --git a/pool/shard004/C++/0048615_RtclRw11Unit.cpp b/pool/shard004/C++/0048615_RtclRw11Unit.cpp new file mode 100644 index 0000000000000000000000000000000000000000..665c53ac815d830ae5f7eef2687b4afb9ab44aed --- /dev/null +++ b/pool/shard004/C++/0048615_RtclRw11Unit.cpp @@ -0,0 +1,141 @@ +// $Id: RtclRw11Unit.cpp 504 2013-04-13 15:37:24Z mueller $ +// +// Copyright 2013- by Walter F.J. Mueller +// +// This program is free software; you may redistribute 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 complete details. +// +// Revision History: +// Date Rev Version Comment +// 2013-03-03 494 1.0 Initial version +// 2013-02-16 488 0.1 First draft +// --------------------------------------------------------------------------- + +/*! + \file + \version $Id: RtclRw11Unit.cpp 504 2013-04-13 15:37:24Z mueller $ + \brief Implemenation of RtclRw11Unit. +*/ + +#include "boost/thread/locks.hpp" +#include "boost/bind.hpp" + +#include "librtcltools/RtclStats.hpp" + +#include "RtclRw11Unit.hpp" + +using namespace std; + +/*! + \class Retro::RtclRw11Unit + \brief FIXME_docs +*/ + +// all method definitions in namespace Retro +namespace Retro { + +//------------------------------------------+----------------------------------- +//! Default constructor + +RtclRw11Unit::RtclRw11Unit(const std::string& type, Rw11Cpu* pcpu) + : RtclProxyBase(type), + fpCpu(pcpu), + fGets(), + fSets() +{ + AddMeth("get", boost::bind(&RtclRw11Unit::M_get, this, _1)); + AddMeth("set", boost::bind(&RtclRw11Unit::M_set, this, _1)); + AddMeth("attach", boost::bind(&RtclRw11Unit::M_attach, this, _1)); + AddMeth("detach", boost::bind(&RtclRw11Unit::M_detach, this, _1)); + AddMeth("dump", boost::bind(&RtclRw11Unit::M_dump, this, _1)); + AddMeth("$default", boost::bind(&RtclRw11Unit::M_default, this, _1)); +} + +//------------------------------------------+----------------------------------- +//! Destructor + +RtclRw11Unit::~RtclRw11Unit() +{} + +//------------------------------------------+----------------------------------- +//! FIXME_docs + +int RtclRw11Unit::M_get(RtclArgs& args) +{ + // synchronize with server thread + boost::lock_guard lock(fpCpu->Connect()); + return fGets.M_get(args); +} + +//------------------------------------------+----------------------------------- +//! FIXME_docs + +int RtclRw11Unit::M_set(RtclArgs& args) +{ + // synchronize with server thread + boost::lock_guard lock(fpCpu->Connect()); + return fSets.M_set(args); +} + +//------------------------------------------+----------------------------------- +//! FIXME_docs + +int RtclRw11Unit::M_attach(RtclArgs& args) +{ + string url; + if (!args.GetArg("url", url)) return kERR; + + if (!args.AllDone()) return kERR; + + RerrMsg emsg; + // synchronize with server thread + boost::lock_guard lock(fpCpu->Connect()); + if (!Obj().Attach(url, emsg)) return args.Quit(emsg); + return kOK; +} + +//------------------------------------------+----------------------------------- +//! FIXME_docs + +int RtclRw11Unit::M_detach(RtclArgs& args) +{ + if (!args.AllDone()) return kERR; + + // synchronize with server thread + boost::lock_guard lock(fpCpu->Connect()); + Obj().Detach(); + return kOK; +} + +//------------------------------------------+----------------------------------- +//! FIXME_docs + +int RtclRw11Unit::M_dump(RtclArgs& args) +{ + if (!args.AllDone()) return kERR; + + ostringstream sos; + Obj().Dump(sos, 0); + args.SetResult(sos); + return kOK; +} + +//------------------------------------------+----------------------------------- +//! FIXME_docs + +int RtclRw11Unit::M_default(RtclArgs& args) +{ + if (!args.AllDone()) return kERR; + ostringstream sos; + sos << "no default output defined yet...\n"; + args.AppendResultLines(sos); + return kOK; +} + +} // end namespace Retro diff --git a/pool/shard004/C++/0048616_ConfigDialog.cpp b/pool/shard004/C++/0048616_ConfigDialog.cpp new file mode 100644 index 0000000000000000000000000000000000000000..3522b8bf95f9b12ec941264d6e87dffe5fb77251 --- /dev/null +++ b/pool/shard004/C++/0048616_ConfigDialog.cpp @@ -0,0 +1,236 @@ +/* Copyright (C) 2005-2011, Thorvald Natvig + + 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 Mumble Developers 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 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 "mumble_pch.hpp" + +#include "ConfigDialog.h" + +#include "AudioInput.h" +#include "AudioOutput.h" +#include "Global.h" +#include "Overlay.h" + +ConfigDialog::ConfigDialog(QWidget *p) : QDialog(p) { + setupUi(this); + + s = g.s; + + unsigned int idx = 0; + ConfigWidgetNew cwn; + foreach(cwn, *ConfigRegistrar::c_qmNew) { + addPage(cwn(s), ++idx); + } + + qcbExpert->setChecked(g.s.bExpert); + on_qcbExpert_clicked(g.s.bExpert); + + QPushButton *okButton = dialogButtonBox->button(QDialogButtonBox::Ok); + okButton->setToolTip(tr("Accept changes")); + okButton->setWhatsThis(tr("This button will accept current settings and return to the application.
" + "The settings will be stored to disk when you leave the application.")); + + QPushButton *cancelButton = dialogButtonBox->button(QDialogButtonBox::Cancel); + cancelButton->setToolTip(tr("Reject changes")); + cancelButton->setWhatsThis(tr("This button will reject all changes and return to the application.
" + "The settings will be reset to the previous positions.")); + + QPushButton *applyButton = dialogButtonBox->button(QDialogButtonBox::Apply); + applyButton->setToolTip(tr("Apply changes")); + applyButton->setWhatsThis(tr("This button will immediately apply all changes.")); + + QPushButton *resetButton = pageButtonBox->button(QDialogButtonBox::Reset); + resetButton->setToolTip(tr("Undo changes for current page")); + resetButton->setWhatsThis(tr("This button will revert any changes done on the current page to the most recent applied settings.")); + + QPushButton *restoreButton = pageButtonBox->button(QDialogButtonBox::RestoreDefaults); + restoreButton->setToolTip(tr("Restore defaults for current page")); + restoreButton->setWhatsThis(tr("This button will restore the defaults for the settings on the current page. Other pages will not be changed.
" + "To restore all settings to their defaults, you will have to use this button on every page." + )); + + if (! g.s.qbaConfigGeometry.isEmpty()) { + if (! g.ocIntercept) + restoreGeometry(g.s.qbaConfigGeometry); + } +} + +void ConfigDialog::addPage(ConfigWidget *cw, unsigned int idx) { + QDesktopWidget dw; + + int w = INT_MAX, h = INT_MAX; + + for (int i=0;iminimumSizeHint(); + cw->resize(ms); + cw->setMinimumSize(ms); + + ms.rwidth() += 128; + ms.rheight() += 192; + if ((ms.width() > w) || (ms.height() > h)) { + QScrollArea *qsa=new QScrollArea(); + qsa->setFrameShape(QFrame::NoFrame); + qsa->setWidgetResizable(true); + qsa->setWidget(cw); + qhPages.insert(cw, qsa); + qswPages->addWidget(qsa); + } else { + qhPages.insert(cw, cw); + qswPages->addWidget(cw); + } + qmWidgets.insert(idx, cw); + cw->load(g.s); +} + +ConfigDialog::~ConfigDialog() { + foreach(QWidget *qw, qhPages) + delete qw; +} + +void ConfigDialog::on_pageButtonBox_clicked(QAbstractButton *b) { + ConfigWidget *conf = qobject_cast(qswPages->currentWidget()); + if (! conf) { + QScrollArea *qsa = qobject_cast(qswPages->currentWidget()); + if (qsa) + conf = qobject_cast(qsa->widget()); + } + if (! conf) + return; + switch (pageButtonBox->standardButton(b)) { + case QDialogButtonBox::RestoreDefaults: { + Settings def; + def.bExpert = g.s.bExpert; + conf->load(def); + break; + } + case QDialogButtonBox::Reset: { + conf->load(g.s); + break; + } + default: + break; + } +} + +void ConfigDialog::on_dialogButtonBox_clicked(QAbstractButton *b) { + switch (dialogButtonBox->standardButton(b)) { + case QDialogButtonBox::Apply: { + apply(); + break; + } + default: + break; + } +} + +void ConfigDialog::on_qlwIcons_currentItemChanged(QListWidgetItem *current, QListWidgetItem *previous) { + if (!current) + current = previous; + + if (current) { + QWidget *w = qhPages.value(qmIconWidgets.value(current)); + if (w) + qswPages->setCurrentWidget(w); + } +} + +void ConfigDialog::on_qcbExpert_clicked(bool b) { + QWidget *ccw = qmIconWidgets.value(qlwIcons->currentItem()); + QListWidgetItem *sel = NULL; + + qmIconWidgets.clear(); + qlwIcons->clear(); + + QFontMetrics qfm(qlwIcons->font()); + int width = 0; + + foreach(ConfigWidget *cw, qmWidgets) { + bool showit = cw->expert(b); + width = qMax(width, qfm.width(cw->title())); + if (showit || b) { + QListWidgetItem *i = new QListWidgetItem(qlwIcons); + i->setIcon(cw->icon()); + i->setText(cw->title()); + i->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled); + + + qmIconWidgets.insert(i, cw); + if (cw == ccw) + sel = i; + } + } + + // Add space for icon and some padding. + width += qlwIcons->iconSize().width() + 25; + + qlwIcons->setMinimumWidth(width); + qlwIcons->setMaximumWidth(width); + + if (sel) + qlwIcons->setCurrentItem(sel); + else + qlwIcons->setCurrentRow(0); +} + +void ConfigDialog::apply() { + Audio::stop(); + + foreach(ConfigWidget *cw, qmWidgets) + cw->save(); + + g.s = s; + + foreach(ConfigWidget *cw, qmWidgets) + cw->accept(); + + if (!g.s.bAttenuateOthersOnTalk) + g.bAttenuateOthers = false; + + // They might have changed their keys. + g.iPushToTalk = 0; + g.s.bExpert = qcbExpert->isChecked(); + + Audio::start(); +} + +void ConfigDialog::accept() { + apply(); + + if (! g.ocIntercept) + g.s.qbaConfigGeometry=saveGeometry(); + + QDialog::accept(); +} diff --git a/pool/shard004/C++/0048623_RedisCommand.cc b/pool/shard004/C++/0048623_RedisCommand.cc new file mode 100644 index 0000000000000000000000000000000000000000..a0842b7bcfeddda6b8bd03701854189d761ada92 --- /dev/null +++ b/pool/shard004/C++/0048623_RedisCommand.cc @@ -0,0 +1,68 @@ +#include "core/RedisCommand.h" +#include "core/RedisConnection.h" +#include "core/TritonSortAssert.h" + +RedisCommand::RedisCommand(const char* format ...) { + // Write command string so we can print debug messages. + va_list ap; + va_start(ap, format); + int charactersWritten = vsnprintf(_command, 1024, format, ap); + ABORT_IF(charactersWritten == -1, "vsnprintf(%s, ...) failed; either memory " + "allocation failed, or some other error occurred", format); + ABORT_IF(charactersWritten >= 1024, + "Redis command must be less than 1024 characters"); + va_end(ap); + + // Issue redis command. + va_start(ap, format); + _reply = RedisConnection::getReply(_command, format, ap); + va_end(ap); + + if (_reply->type == REDIS_REPLY_ERROR) { + std::string errorString; + errorString.assign(_reply->str, _reply->len); + + ABORT("Redis command (%s) returned error from server : %s", + _command, errorString.c_str()); + } +} + +RedisCommand::~RedisCommand() { + if (_reply != NULL) { + freeReplyObject(_reply); + _reply = NULL; + } +} + +const char* RedisCommand::replyTypeString(int replyType) { + switch (replyType) { + case REDIS_REPLY_STRING: + return "string"; + break; + case REDIS_REPLY_ARRAY: + return "array"; + break; + case REDIS_REPLY_INTEGER: + return "integer"; + break; + case REDIS_REPLY_NIL: + return "nil"; + break; + case REDIS_REPLY_STATUS: + return "status"; + break; + case REDIS_REPLY_ERROR: + return "error"; + break; + default: + return "unknown"; + break; + } +} + +void RedisCommand::assertReplyType( + redisReply& reply, int expectedReplyType) { + ABORT_IF(reply.type != expectedReplyType, "Expected %s reply but got %s " + "reply", replyTypeString(expectedReplyType), + replyTypeString(reply.type)); +} diff --git a/pool/shard004/C++/0048632_bitcoin.cpp b/pool/shard004/C++/0048632_bitcoin.cpp new file mode 100644 index 0000000000000000000000000000000000000000..588ed77b526f8a660fcbc3ac10680650e1c28f66 --- /dev/null +++ b/pool/shard004/C++/0048632_bitcoin.cpp @@ -0,0 +1,304 @@ +/* + * W.J. van der Laan 2011-2012 + */ + +#include + +#include "bitcoingui.h" +#include "clientmodel.h" +#include "walletmodel.h" +#include "optionsmodel.h" +#include "guiutil.h" +#include "guiconstants.h" +#include "init.h" +#include "util.h" +#include "ui_interface.h" +#include "paymentserver.h" +#include "splashscreen.h" + +#include +#if QT_VERSION < 0x050000 +#include +#endif +#include +#include +#include +#include + +#ifdef Q_OS_MAC +#include "macdockiconhandler.h" +#endif + +#if defined(BITCOIN_NEED_QT_PLUGINS) && !defined(_BITCOIN_QT_PLUGINS_INCLUDED) +#define _BITCOIN_QT_PLUGINS_INCLUDED +#define __INSURE__ +#include +Q_IMPORT_PLUGIN(qcncodecs) +Q_IMPORT_PLUGIN(qjpcodecs) +Q_IMPORT_PLUGIN(qtwcodecs) +Q_IMPORT_PLUGIN(qkrcodecs) +Q_IMPORT_PLUGIN(qtaccessiblewidgets) +#endif + +// Declare meta types used for QMetaObject::invokeMethod +Q_DECLARE_METATYPE(bool*) + +// Need a global reference for the notifications to find the GUI +static BitcoinGUI *guiref; +static SplashScreen *splashref; + +static bool ThreadSafeMessageBox(const std::string& message, const std::string& caption, unsigned int style) +{ + // Message from network thread + if(guiref) + { + bool modal = (style & CClientUIInterface::MODAL); + bool ret = false; + // In case of modal message, use blocking connection to wait for user to click a button + QMetaObject::invokeMethod(guiref, "message", + modal ? GUIUtil::blockingGUIThreadConnection() : Qt::QueuedConnection, + Q_ARG(QString, QString::fromStdString(caption)), + Q_ARG(QString, QString::fromStdString(message)), + Q_ARG(unsigned int, style), + Q_ARG(bool*, &ret)); + return ret; + } + else + { + printf("%s: %s\n", caption.c_str(), message.c_str()); + fprintf(stderr, "%s: %s\n", caption.c_str(), message.c_str()); + return false; + } +} + +static bool ThreadSafeAskFee(int64 nFeeRequired) +{ + if(!guiref) + return false; + if(nFeeRequired < CTransaction::nMinTxFee || nFeeRequired <= nTransactionFee || fDaemon) + return true; + + bool payFee = false; + + QMetaObject::invokeMethod(guiref, "askFee", GUIUtil::blockingGUIThreadConnection(), + Q_ARG(qint64, nFeeRequired), + Q_ARG(bool*, &payFee)); + + return payFee; +} + +static void InitMessage(const std::string &message) +{ + if(splashref) + { + splashref->showMessage(QString::fromStdString(message), Qt::AlignBottom|Qt::AlignHCenter, QColor(55,55,55)); + qApp->processEvents(); + } + printf("init message: %s\n", message.c_str()); +} + +/* + Translate string to current locale using Qt. + */ +static std::string Translate(const char* psz) +{ + return QCoreApplication::translate("bitcoin-core", psz).toStdString(); +} + +/* Handle runaway exceptions. Shows a message box with the problem and quits the program. + */ +static void handleRunawayException(std::exception *e) +{ + PrintExceptionContinue(e, "Runaway exception"); + QMessageBox::critical(0, "Runaway exception", BitcoinGUI::tr("A fatal error occurred. Leadcoin can no longer continue safely and will quit.") + QString("\n\n") + QString::fromStdString(strMiscWarning)); + exit(1); +} + +#ifndef BITCOIN_QT_TEST +int main(int argc, char *argv[]) +{ + // Command-line options take precedence: + ParseParameters(argc, argv); + +#if QT_VERSION < 0x050000 + // Internal string conversion is all UTF-8 + QTextCodec::setCodecForTr(QTextCodec::codecForName("UTF-8")); + QTextCodec::setCodecForCStrings(QTextCodec::codecForTr()); +#endif + + Q_INIT_RESOURCE(bitcoin); + QApplication app(argc, argv); + + // Register meta types used for QMetaObject::invokeMethod + qRegisterMetaType< bool* >(); + + // Do this early as we don't want to bother initializing if we are just calling IPC + // ... but do it after creating app, so QCoreApplication::arguments is initialized: + if (PaymentServer::ipcSendCommandLine()) + exit(0); + PaymentServer* paymentServer = new PaymentServer(&app); + + // Install global event filter that makes sure that long tooltips can be word-wrapped + app.installEventFilter(new GUIUtil::ToolTipToRichTextFilter(TOOLTIP_WRAP_THRESHOLD, &app)); + + // ... then bitcoin.conf: + if (!boost::filesystem::is_directory(GetDataDir(false))) + { + // This message can not be translated, as translation is not initialized yet + // (which not yet possible because lang=XX can be overridden in bitcoin.conf in the data directory) + QMessageBox::critical(0, "Leadcoin", + QString("Error: Specified data directory \"%1\" does not exist.").arg(QString::fromStdString(mapArgs["-datadir"]))); + return 1; + } + ReadConfigFile(mapArgs, mapMultiArgs); + + // Application identification (must be set before OptionsModel is initialized, + // as it is used to locate QSettings) + QApplication::setOrganizationName("Leadcoin"); + QApplication::setOrganizationDomain("leadcoin.org"); + if(GetBoolArg("-testnet")) // Separate UI settings for testnet + QApplication::setApplicationName("Leadcoin-Qt-testnet"); + else + QApplication::setApplicationName("Leadcoin-Qt"); + + // ... then GUI settings: + OptionsModel optionsModel; + + // Get desired locale (e.g. "de_DE") from command line or use system locale + QString lang_territory = QString::fromStdString(GetArg("-lang", QLocale::system().name().toStdString())); + QString lang = lang_territory; + // Convert to "de" only by truncating "_DE" + lang.truncate(lang_territory.lastIndexOf('_')); + + QTranslator qtTranslatorBase, qtTranslator, translatorBase, translator; + // Load language files for configured locale: + // - First load the translator for the base language, without territory + // - Then load the more specific locale translator + + // Load e.g. qt_de.qm + if (qtTranslatorBase.load("qt_" + lang, QLibraryInfo::location(QLibraryInfo::TranslationsPath))) + app.installTranslator(&qtTranslatorBase); + + // Load e.g. qt_de_DE.qm + if (qtTranslator.load("qt_" + lang_territory, QLibraryInfo::location(QLibraryInfo::TranslationsPath))) + app.installTranslator(&qtTranslator); + + // Load e.g. bitcoin_de.qm (shortcut "de" needs to be defined in bitcoin.qrc) + if (translatorBase.load(lang, ":/translations/")) + app.installTranslator(&translatorBase); + + // Load e.g. bitcoin_de_DE.qm (shortcut "de_DE" needs to be defined in bitcoin.qrc) + if (translator.load(lang_territory, ":/translations/")) + app.installTranslator(&translator); + + // Subscribe to global signals from core + uiInterface.ThreadSafeMessageBox.connect(ThreadSafeMessageBox); + uiInterface.ThreadSafeAskFee.connect(ThreadSafeAskFee); + uiInterface.InitMessage.connect(InitMessage); + uiInterface.Translate.connect(Translate); + + // Show help message immediately after parsing command-line options (for "-lang") and setting locale, + // but before showing splash screen. + if (mapArgs.count("-?") || mapArgs.count("--help")) + { + GUIUtil::HelpMessageBox help; + help.showOrPrint(); + return 1; + } + +#ifdef Q_OS_MAC + // on mac, also change the icon now because it would look strange to have a testnet splash (green) and a std app icon (orange) + if(GetBoolArg("-testnet")) { + MacDockIconHandler::instance()->setIcon(QIcon(":icons/bitcoin_testnet")); + } +#endif + + SplashScreen splash(QPixmap(), 0); + if (GetBoolArg("-splash", true) && !GetBoolArg("-min")) + { + splash.show(); + splash.setAutoFillBackground(true); + splashref = &splash; + } + + app.processEvents(); + app.setQuitOnLastWindowClosed(false); + + try + { +#ifndef Q_OS_MAC + // Regenerate startup link, to fix links to old versions + // OSX: makes no sense on mac and might also scan/mount external (and sleeping) volumes (can take up some secs) + if (GUIUtil::GetStartOnSystemStartup()) + GUIUtil::SetStartOnSystemStartup(true); +#endif + + boost::thread_group threadGroup; + + BitcoinGUI window; + guiref = &window; + + QTimer* pollShutdownTimer = new QTimer(guiref); + QObject::connect(pollShutdownTimer, SIGNAL(timeout()), guiref, SLOT(detectShutdown())); + pollShutdownTimer->start(200); + + if(AppInit2(threadGroup)) + { + { + // Put this in a block, so that the Model objects are cleaned up before + // calling Shutdown(). + + optionsModel.Upgrade(); // Must be done after AppInit2 + + if (splashref) + splash.finish(&window); + + ClientModel clientModel(&optionsModel); + WalletModel walletModel(pwalletMain, &optionsModel); + + window.setClientModel(&clientModel); + window.addWallet("~Default", &walletModel); + window.setCurrentWallet("~Default"); + + // If -min option passed, start window minimized. + if(GetBoolArg("-min")) + { + window.showMinimized(); + } + else + { + window.show(); + } + + // Now that initialization/startup is done, process any command-line + // bitcoin: URIs + QObject::connect(paymentServer, SIGNAL(receivedURI(QString)), &window, SLOT(handleURI(QString))); + QTimer::singleShot(100, paymentServer, SLOT(uiReady())); + + app.exec(); + + window.hide(); + window.setClientModel(0); + window.removeAllWallets(); + guiref = 0; + } + // Shutdown the core and its threads, but don't exit Bitcoin-Qt here + threadGroup.interrupt_all(); + threadGroup.join_all(); + Shutdown(); + } + else + { + threadGroup.interrupt_all(); + threadGroup.join_all(); + Shutdown(); + return 1; + } + } catch (std::exception& e) { + handleRunawayException(&e); + } catch (...) { + handleRunawayException(NULL); + } + return 0; +} +#endif // BITCOIN_QT_TEST diff --git a/pool/shard004/C++/0048637_qgspointclusterrendererwidget.cpp b/pool/shard004/C++/0048637_qgspointclusterrendererwidget.cpp new file mode 100644 index 0000000000000000000000000000000000000000..5008cb32b126a089ddfc1822f102a64ac00f073c --- /dev/null +++ b/pool/shard004/C++/0048637_qgspointclusterrendererwidget.cpp @@ -0,0 +1,235 @@ +/*************************************************************************** + qgspointclusterrendererwidget.cpp + --------------------------------- + begin : February 2016 + copyright : (C) 2016 by Nyall Dawson + email : nyall dot dawson at gmail dot com + ***************************************************************************/ + +/*************************************************************************** + * * + * This program is free software; you can redistribute it and/or modify * + * it under the terms of the GNU General Public License as published by * + * the Free Software Foundation; either version 2 of the License, or * + * (at your option) any later version. * + * * + ***************************************************************************/ + +#include "qgspointclusterrendererwidget.h" +#include "qgspointclusterrenderer.h" +#include "qgsrendererregistry.h" +#include "qgsfield.h" +#include "qgsstyle.h" +#include "qgssymbolselectordialog.h" +#include "qgssymbollayerutils.h" +#include "qgsvectorlayer.h" +#include "qgsguiutils.h" + +QgsRendererWidget *QgsPointClusterRendererWidget::create( QgsVectorLayer *layer, QgsStyle *style, QgsFeatureRenderer *renderer ) +{ + return new QgsPointClusterRendererWidget( layer, style, renderer ); +} + +QgsPointClusterRendererWidget::QgsPointClusterRendererWidget( QgsVectorLayer *layer, QgsStyle *style, QgsFeatureRenderer *renderer ) + : QgsRendererWidget( layer, style ) + +{ + if ( !layer ) + { + return; + } + + //the renderer only applies to point vector layers + if ( QgsWkbTypes::flatType( layer->wkbType() ) != QgsWkbTypes::Point ) + { + //setup blank dialog + mRenderer = nullptr; + setupBlankUi( layer->name() ); + return; + } + setupUi( this ); + connect( mRendererComboBox, static_cast( &QComboBox::currentIndexChanged ), this, &QgsPointClusterRendererWidget::mRendererComboBox_currentIndexChanged ); + connect( mDistanceSpinBox, static_cast < void ( QDoubleSpinBox::* )( double ) > ( &QDoubleSpinBox::valueChanged ), this, &QgsPointClusterRendererWidget::mDistanceSpinBox_valueChanged ); + connect( mDistanceUnitWidget, &QgsUnitSelectionWidget::changed, this, &QgsPointClusterRendererWidget::mDistanceUnitWidget_changed ); + connect( mRendererSettingsButton, &QPushButton::clicked, this, &QgsPointClusterRendererWidget::mRendererSettingsButton_clicked ); + this->layout()->setContentsMargins( 0, 0, 0, 0 ); + + mDistanceUnitWidget->setUnits( QgsUnitTypes::RenderUnitList() << QgsUnitTypes::RenderMillimeters << QgsUnitTypes::RenderMapUnits << QgsUnitTypes::RenderPixels + << QgsUnitTypes::RenderPoints << QgsUnitTypes::RenderInches ); + + mCenterSymbolToolButton->setSymbolType( QgsSymbol::Marker ); + + if ( renderer ) + { + mRenderer = QgsPointClusterRenderer::convertFromRenderer( renderer ); + } + if ( !mRenderer ) + { + mRenderer = new QgsPointClusterRenderer(); + } + + blockAllSignals( true ); + + //insert possible renderer types + QStringList rendererList = QgsApplication::rendererRegistry()->renderersList( QgsRendererAbstractMetadata::PointLayer ); + QStringList::const_iterator it = rendererList.constBegin(); + for ( ; it != rendererList.constEnd(); ++it ) + { + if ( *it != QLatin1String( "pointDisplacement" ) && *it != QLatin1String( "pointCluster" ) && *it != QLatin1String( "heatmapRenderer" ) ) + { + QgsRendererAbstractMetadata *m = QgsApplication::rendererRegistry()->rendererMetadata( *it ); + mRendererComboBox->addItem( m->icon(), m->visibleName(), *it ); + } + } + + mDistanceSpinBox->setValue( mRenderer->tolerance() ); + mDistanceUnitWidget->setUnit( mRenderer->toleranceUnit() ); + mDistanceUnitWidget->setMapUnitScale( mRenderer->toleranceMapUnitScale() ); + mCenterSymbolToolButton->setSymbol( mRenderer->clusterSymbol()->clone() ); + + blockAllSignals( false ); + + //set the appropriate renderer dialog + if ( mRenderer->embeddedRenderer() ) + { + QString rendererName = mRenderer->embeddedRenderer()->type(); + int rendererIndex = mRendererComboBox->findData( rendererName ); + if ( rendererIndex != -1 ) + { + mRendererComboBox->setCurrentIndex( rendererIndex ); + mRendererComboBox_currentIndexChanged( rendererIndex ); + } + } + + connect( mCenterSymbolToolButton, &QgsSymbolButton::changed, this, &QgsPointClusterRendererWidget::centerSymbolChanged ); + mCenterSymbolToolButton->setDialogTitle( tr( "Cluster symbol" ) ); + mCenterSymbolToolButton->setLayer( mLayer ); + mCenterSymbolToolButton->registerExpressionContextGenerator( this ); +} + +QgsPointClusterRendererWidget::~QgsPointClusterRendererWidget() +{ + delete mRenderer; +} + +QgsFeatureRenderer *QgsPointClusterRendererWidget::renderer() +{ + return mRenderer; +} + +void QgsPointClusterRendererWidget::setContext( const QgsSymbolWidgetContext &context ) +{ + QgsRendererWidget::setContext( context ); + if ( mDistanceUnitWidget ) + mDistanceUnitWidget->setMapCanvas( context.mapCanvas() ); + if ( mCenterSymbolToolButton ) + mCenterSymbolToolButton->setMapCanvas( context.mapCanvas() ); +} + +void QgsPointClusterRendererWidget::mRendererComboBox_currentIndexChanged( int index ) +{ + QString rendererId = mRendererComboBox->itemData( index ).toString(); + QgsRendererAbstractMetadata *m = QgsApplication::rendererRegistry()->rendererMetadata( rendererId ); + if ( m ) + { + // unfortunately renderer conversion is only available through the creation of a widget... + QgsRendererWidget *tempRenderWidget = m->createRendererWidget( mLayer, mStyle, mRenderer->embeddedRenderer()->clone() ); + mRenderer->setEmbeddedRenderer( tempRenderWidget->renderer()->clone() ); + delete tempRenderWidget; + } + emit widgetChanged(); +} + +void QgsPointClusterRendererWidget::mRendererSettingsButton_clicked() +{ + if ( !mRenderer ) + return; + + QgsRendererAbstractMetadata *m = QgsApplication::rendererRegistry()->rendererMetadata( mRenderer->embeddedRenderer()->type() ); + if ( m ) + { + QgsRendererWidget *w = m->createRendererWidget( mLayer, mStyle, mRenderer->embeddedRenderer()->clone() ); + w->setPanelTitle( tr( "Renderer settings" ) ); + + QgsExpressionContextScope scope; + scope.addVariable( QgsExpressionContextScope::StaticVariable( QgsExpressionContext::EXPR_CLUSTER_COLOR, "", true ) ); + scope.addVariable( QgsExpressionContextScope::StaticVariable( QgsExpressionContext::EXPR_CLUSTER_SIZE, 0, true ) ); + QList< QgsExpressionContextScope > scopes = mContext.additionalExpressionContextScopes(); + scopes << scope; + QgsSymbolWidgetContext context = mContext; + context.setAdditionalExpressionContextScopes( scopes ); + w->setContext( context ); + connect( w, &QgsPanelWidget::widgetChanged, this, &QgsPointClusterRendererWidget::updateRendererFromWidget ); + w->setDockMode( this->dockMode() ); + openPanel( w ); + } +} + +void QgsPointClusterRendererWidget::mDistanceSpinBox_valueChanged( double d ) +{ + if ( mRenderer ) + { + mRenderer->setTolerance( d ); + } + emit widgetChanged(); +} + +void QgsPointClusterRendererWidget::mDistanceUnitWidget_changed() +{ + if ( mRenderer ) + { + mRenderer->setToleranceUnit( mDistanceUnitWidget->unit() ); + mRenderer->setToleranceMapUnitScale( mDistanceUnitWidget->getMapUnitScale() ); + } + emit widgetChanged(); +} + +void QgsPointClusterRendererWidget::blockAllSignals( bool block ) +{ + mRendererComboBox->blockSignals( block ); + mCenterSymbolToolButton->blockSignals( block ); + mDistanceSpinBox->blockSignals( block ); + mDistanceUnitWidget->blockSignals( block ); +} + +QgsExpressionContext QgsPointClusterRendererWidget::createExpressionContext() const +{ + QgsExpressionContext context; + if ( mContext.expressionContext() ) + context = *mContext.expressionContext(); + else + context.appendScopes( mContext.globalProjectAtlasMapLayerScopes( mLayer ) ); + QgsExpressionContextScope scope; + scope.addVariable( QgsExpressionContextScope::StaticVariable( QgsExpressionContext::EXPR_CLUSTER_COLOR, "", true ) ); + scope.addVariable( QgsExpressionContextScope::StaticVariable( QgsExpressionContext::EXPR_CLUSTER_SIZE, 0, true ) ); + QList< QgsExpressionContextScope > scopes = mContext.additionalExpressionContextScopes(); + scopes << scope; + Q_FOREACH ( const QgsExpressionContextScope &s, scopes ) + { + context << new QgsExpressionContextScope( s ); + } + return context; +} + +void QgsPointClusterRendererWidget::centerSymbolChanged() +{ + mRenderer->setClusterSymbol( mCenterSymbolToolButton->clonedSymbol< QgsMarkerSymbol >() ); + emit widgetChanged(); +} + +void QgsPointClusterRendererWidget::updateRendererFromWidget() +{ + QgsRendererWidget *w = qobject_cast( sender() ); + if ( !w ) + return; + + mRenderer->setEmbeddedRenderer( w->renderer()->clone() ); + emit widgetChanged(); +} + +void QgsPointClusterRendererWidget::setupBlankUi( const QString &layerName ) +{ + QGridLayout *layout = new QGridLayout( this ); + QLabel *label = new QLabel( tr( "The point cluster renderer only applies to (single) point layers. \n'%1' is not a point layer and cannot be displayed by the point cluster renderer" ).arg( layerName ), this ); + layout->addWidget( label ); +} diff --git a/pool/shard004/C++/0048638_plasma.cc b/pool/shard004/C++/0048638_plasma.cc new file mode 100644 index 0000000000000000000000000000000000000000..f73fcc0c5ba86ba78637bc0114514df591b24957 --- /dev/null +++ b/pool/shard004/C++/0048638_plasma.cc @@ -0,0 +1,127 @@ +/****************************************************************************** + + URBAN + Copyright (C) 1999 Thomas Nyberg and Jonas Borgström + + 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 + + Contact the authors: + Snailmail: + Thomas Nyberg Jonas Borgström + Brännbergsvägen 21b Bondevägen 6 + 92136 Lycksele 92332 Storuman + Sweden Sweden + + or email: + + thomas.nyberg@usa.net jonas_b@bitsmart.com +*****************************************************************************/ +#include +#include +#include "engine.h" +#include "object2.h" +/***************************************************************************/ +#define PLASMA_SPEED 10 + +/***************************************************************************/ +Plasma_o::Plasma_o(int X, int Y, int Z, int Dir, int friendship, int Damage) : Object(X, Y, Z) { + char filename[512]; + RGB pal[256]; + + width = 1; + height = 1; + strength = Damage; + energy = 1; + direction = Dir; + coll_x = 0; + coll_y = 0; + coll_width = width; + coll_height = height; + counter = 0; + + images = new BITMAP *; + + switch (Dir) { + case LEFT_DIR: + sprintf(filename, "plasmal/skottv.pcx"); + break; + case RIGHT_DIR: + default: + sprintf(filename, "plasmal/skotth.pcx"); + break; + } + images[0] = icache.GetImage(filename, pal); + if (images[0]) + num_images++; + +// rect(images[0], 0, 0, images[0]->w - 1, images[0]->h - 1, 15); + + current_image = 0; + me = FRIEND_PLASMA; + friends = (friendship | me | FRIEND_DOOR | FRIEND_FIREBALL | FRIEND_ICEBALL | FRIEND_DEKOR) & ~ENEMY_SCIENTIST; + enemies = ~friends; + speed_x = (direction == RIGHT_DIR) ? PLASMA_SPEED : -PLASMA_SPEED; + +// SOUND.PlaySFX(FIRE_SAMPLE); +} +/****************************************************************************/ +int Plasma_o::update() { + + if (!energy) + return -1; +/* if (direction == LEFT_DIR) + while (ENGINE.check_wall(x + 1, y, z) && speed_x) + x++; + else if (direction == RIGHT_DIR) + while (ENGINE.check_wall(x + coll_width - 1, y, z) && speed_x) + x--; +*/ +/* if (direction == LEFT_DIR) + while (ENGINE.check_wall(x + speed_x, y, z) && speed_x < -1) + speed_x++; + else if (direction == RIGHT_DIR) + while (ENGINE.check_wall(x + coll_width + speed_x, y, z) && speed_x > 1) + speed_x--; +*/ + + x += speed_x; + counter += PLASMA_SPEED; + + if(counter > 600) + return -1; + + +/* if (!speed_x) { + ENGINE.create_effect(new gnistor_o(x, y + height, z, direction)); + energy = 0; + }*/ + // Check collision with walls + if(ENGINE.check_wall((direction == LEFT_DIR) ? x : x + coll_width, y, z)) { +// ENGINE.create_effect(new gnistor_o(x, y + height, z, direction)); + energy = 0; + } + + return 0; +} +/****************************************************************************/ +void Plasma_o::Collision(Object *o) { + + if (o->GetWho() & enemies) + energy = 0; +} +/****************************************************************************/ +Plasma_o::~Plasma_o() { +} +/****************************************************************************/ diff --git a/pool/shard004/C++/0048649_Snapshot.cpp b/pool/shard004/C++/0048649_Snapshot.cpp new file mode 100644 index 0000000000000000000000000000000000000000..0b55b3f563a0306a8f3b1213e74e38442d0c22ee --- /dev/null +++ b/pool/shard004/C++/0048649_Snapshot.cpp @@ -0,0 +1,72 @@ +#include +#include + +#include "easylogging++.h" +#include "Snapshot.h" + +namespace DataBase +{ +using namespace leveldb; + +Snapshot::Snapshot() + : m_shapshot(nullptr) +{ +} + +Snapshot::Snapshot(const std::weak_ptr &backend, const leveldb::Snapshot *snapshot) + : m_backend(backend), m_shapshot(snapshot) +{ +} + +Snapshot::~Snapshot() +{ + if (auto spt = m_backend.lock()) { + spt->ReleaseSnapshot(m_shapshot); + m_shapshot = nullptr; + } + else { + LOG(ERROR) << "The database is deleted. Dangling reference on snapshot!"; + assert(0); + } +} + +ByteArray Snapshot::get(const std::string &key) +{ + if (auto spt = m_backend.lock()) { + ReadOptions options; + options.snapshot = m_shapshot; + + ByteArray value; + const auto status = spt->Get(options, Slice(key), &value); + if (!status.ok()) { + LOG(ERROR) + << "Error reading data from snapshot" + << status.ToString(); + } + + return value; + + } + else { + LOG(ERROR) << "The database is deleted. Dangling reference on snapshot!"; + return ByteArray(); + } +} + +Iterator Snapshot::iterator() +{ + if (auto spt = m_backend.lock()) { + ReadOptions options; + options.snapshot = m_shapshot; + std::unique_ptr rawIterator(spt->NewIterator(options)); + + return Iterator(std::move(rawIterator)); + + } + else { + LOG(ERROR) << "The database is deleted. Dangling reference on snapshot!"; + return Iterator(); + } +} + +} \ No newline at end of file diff --git a/pool/shard004/C++/0048653_XDisplay.cpp b/pool/shard004/C++/0048653_XDisplay.cpp new file mode 100644 index 0000000000000000000000000000000000000000..131ede67e6186be8bffc1dc103457a675beac265 --- /dev/null +++ b/pool/shard004/C++/0048653_XDisplay.cpp @@ -0,0 +1,102 @@ +#include "XDisplay.h" + +#include "../Graphics/Render.h" + +using namespace Render; + +CXDisplay::CXDisplay(const int p_ciWidth, const int p_ciHeight) +{ + GLint att[] = { GLX_RGBA, GLX_DEPTH_SIZE, 24, GLX_DOUBLEBUFFER, None }; + XSetWindowAttributes swa; + + m_Display = XOpenDisplay(NULL); + Window root = DefaultRootWindow(m_Display); + + XVisualInfo* vi = glXChooseVisual(m_Display, 0, att); + Colormap cmap = XCreateColormap(m_Display, root, vi->visual, AllocNone); + + swa.colormap = cmap; + swa.event_mask = ExposureMask; + + m_Window = XCreateWindow(m_Display, root, 0, 0, p_ciWidth, p_ciHeight, 0, vi->depth, InputOutput, vi->visual, CWColormap | CWEventMask, &swa); + + XMapWindow(m_Display, m_Window); + XStoreName(m_Display, m_Window, "Damned Quest"); + + m_Context = glXCreateContext(m_Display, vi, NULL, GL_TRUE); + glXMakeCurrent(m_Display, m_Window, m_Context); + + XSelectInput(m_Display, m_Window, KeyPressMask | KeyReleaseMask); + + Graphics::CRender::Prepare(); +} + +CXDisplay::~CXDisplay() +{ + +} + +void CXDisplay::Close() +{ + glXMakeCurrent(m_Display, None, NULL); + glXDestroyContext(m_Display, m_Context); + XDestroyWindow(m_Display, m_Window); + XCloseDisplay(m_Display); +} + +void CXDisplay::HandleEvents() +{ + XWindowAttributes gwa; + + if(XCheckWindowEvent(m_Display, m_Window, ExposureMask | KeyPressMask | KeyReleaseMask, &m_Event)){ + switch(m_Event.type) + { + case Expose: + XGetWindowAttributes(m_Display, m_Window, &gwa); + glViewport(0, 0, gwa.width, gwa.height); + m_fnRedraw(); + SwapBuffers(); + break; + case KeyPress: + { + XKeyEvent* pKey = reinterpret_cast(&m_Event); + m_fnKeyPress(pKey->keycode); + } + break; + case KeyRelease: + { + XKeyEvent* pKey = reinterpret_cast(&m_Event); + m_fnKeyRelease(pKey->keycode); + } + break; + default: + DEBUG(1, __FUNCTION__, m_Event.type); + break; + } + } +} + +void CXDisplay::SwapBuffers() +{ + glXSwapBuffers(m_Display, m_Window); +} + +void CXDisplay::ListenKeyPress(std::function p_fnEvent) +{ + m_fnKeyPress = p_fnEvent; +} + +void CXDisplay::ListenKeyRelease(std::function p_fnEvent) +{ + m_fnKeyRelease = p_fnEvent; +} + +void CXDisplay::ListenRedraw(std::function p_fnEvent) +{ + m_fnRedraw = p_fnEvent; +} + +void CXDisplay::Clear() +{ + Graphics::CRender::Clear(); +} diff --git a/pool/shard004/C++/0048657_NamedParameter.cpp b/pool/shard004/C++/0048657_NamedParameter.cpp new file mode 100644 index 0000000000000000000000000000000000000000..9f556e047e2a7e7bec876de14e0e84ff1e4fb17b --- /dev/null +++ b/pool/shard004/C++/0048657_NamedParameter.cpp @@ -0,0 +1,79 @@ + +#define BBCDEBUG_LEVEL 1 +#include "NamedParameter.h" + +BBC_AUDIOTOOLBOX_START + +#if ENABLE_JSON +namespace json +{ + /*--------------------------------------------------------------------------------*/ + /** Convert from list of NamedParameter objects to a JSON object + * + * @param list of NamedParameter objects + * @param obj JSON object to be populated + * @param all true to include parameters that are at their default + */ + /*--------------------------------------------------------------------------------*/ + void ToJSON(const INamedParameter * const *list, uint_t n, JSONValue& obj, bool all) + { + uint_t i; + + // iterate through each parameter + for (i = 0; i < n; i++) + { + const INamedParameter *parameter = list[i]; + + // only add to object if parameter has been set or 'all' as been set + if (all || parameter->IsSet()) parameter->ToJSON(obj[parameter->GetName()]); + } + } + void ToJSON(const std::vector& list, JSONValue& obj, bool all) + { + ToJSON(&list[0], list.size(), obj, all); + } + + /*--------------------------------------------------------------------------------*/ + /** Convert from a JSON object to a set of NamedParameters + * + * @param obj JSON object to be as the source + * @param list of NamedParameter objects to extract + * @param reset true to reset parameters that are not specified + * + * @return true if all [found] parameters were evaluated properly + */ + /*--------------------------------------------------------------------------------*/ + bool FromJSON(const JSONValue& obj, INamedParameter * const *list, uint_t n, bool reset) + { + uint_t i; + bool success = true; + + // iterate through each parameter + for (i = 0; i < n; i++) + { + INamedParameter *parameter = list[i]; + + if (obj.isMember(parameter->GetName())) + { + // if parameter exists, set it + BBCDEBUG3(("Member '%s' found in '%s'", parameter->GetName(), ToJSONString(obj, true).c_str())); + success &= parameter->FromJSON(obj[parameter->GetName()]); + } + else if (reset) + { + // else reset parameter to its default + BBCDEBUG2(("Member '%s' *not* found in '%s'", parameter->GetName(), ToJSONString(obj, true).c_str())); + parameter->Reset(); + } + } + + return success; + } + bool FromJSON(const JSONValue& obj, const std::vector& list, bool reset) + { + return FromJSON(obj, &list[0], list.size(), reset); + } +}; +#endif + +BBC_AUDIOTOOLBOX_END diff --git a/pool/shard004/C++/0048660_suppression_gain_unittest.cc b/pool/shard004/C++/0048660_suppression_gain_unittest.cc new file mode 100644 index 0000000000000000000000000000000000000000..0d95db196af1bde284062cf466fe5bc766dcfa2d --- /dev/null +++ b/pool/shard004/C++/0048660_suppression_gain_unittest.cc @@ -0,0 +1,135 @@ +/* + * Copyright (c) 2017 The WebRTC project authors. All Rights Reserved. + * + * Use of this source code is governed by a BSD-style license + * that can be found in the LICENSE file in the root of the source + * tree. An additional intellectual property rights grant can be found + * in the file PATENTS. All contributing project authors may + * be found in the AUTHORS file in the root of the source tree. + */ + +#include "modules/audio_processing/aec3/suppression_gain.h" + +#include "modules/audio_processing/aec3/aec_state.h" +#include "modules/audio_processing/aec3/render_delay_buffer.h" +#include "modules/audio_processing/aec3/subtractor.h" +#include "modules/audio_processing/logging/apm_data_dumper.h" +#include BOSS_WEBRTC_U_rtc_base__checks_h //original-code:"rtc_base/checks.h" +#include BOSS_WEBRTC_U_system_wrappers__include__cpu_features_wrapper_h //original-code:"system_wrappers/include/cpu_features_wrapper.h" +#include BOSS_WEBRTC_U_test__gtest_h //original-code:"test/gtest.h" +#include BOSS_WEBRTC_U_typedefs_h //original-code:"typedefs.h" // NOLINT(build/include) + +namespace webrtc { +namespace aec3 { + +#if RTC_DCHECK_IS_ON && GTEST_HAS_DEATH_TEST && !defined(WEBRTC_ANDROID) + +// Verifies that the check for non-null output gains works. +TEST(SuppressionGain, NullOutputGains) { + std::array E2; + std::array R2; + std::array N2; + E2.fill(0.f); + R2.fill(0.f); + N2.fill(0.f); + float high_bands_gain; + AecState aec_state(EchoCanceller3Config{}); + EXPECT_DEATH(SuppressionGain(EchoCanceller3Config{}, DetectOptimization()) + .GetGain(E2, R2, N2, RenderSignalAnalyzer(), aec_state, + std::vector>( + 3, std::vector(kBlockSize, 0.f)), + &high_bands_gain, nullptr), + ""); +} + +#endif + +// Does a sanity check that the gains are correctly computed. +TEST(SuppressionGain, BasicGainComputation) { + SuppressionGain suppression_gain(EchoCanceller3Config(), + DetectOptimization()); + RenderSignalAnalyzer analyzer; + float high_bands_gain; + std::array E2; + std::array Y2; + std::array R2; + std::array N2; + std::array g; + std::array s; + std::vector> x(1, std::vector(kBlockSize, 0.f)); + EchoCanceller3Config config; + AecState aec_state(config); + ApmDataDumper data_dumper(42); + Subtractor subtractor(config, &data_dumper, DetectOptimization()); + std::unique_ptr render_delay_buffer( + RenderDelayBuffer::Create(config, 3)); + + // Verify the functionality for forcing a zero gain. + E2.fill(1000000000.f); + R2.fill(10000000000000.f); + N2.fill(0.f); + s.fill(10.f); + aec_state.Update(subtractor.FilterFrequencyResponse(), + subtractor.FilterImpulseResponse(), + subtractor.ConvergedFilter(), + *render_delay_buffer->GetRenderBuffer(), E2, Y2, s, false); + suppression_gain.GetGain(E2, R2, N2, analyzer, aec_state, x, &high_bands_gain, + &g); + std::for_each(g.begin(), g.end(), [](float a) { EXPECT_FLOAT_EQ(0.f, a); }); + EXPECT_FLOAT_EQ(0.f, high_bands_gain); + + // Ensure that a strong noise is detected to mask any echoes. + E2.fill(10.f); + Y2.fill(10.f); + R2.fill(0.1f); + N2.fill(100.f); + // Ensure that the gain is no longer forced to zero. + for (int k = 0; k <= kNumBlocksPerSecond / 5 + 1; ++k) { + aec_state.Update(subtractor.FilterFrequencyResponse(), + subtractor.FilterImpulseResponse(), + subtractor.ConvergedFilter(), + *render_delay_buffer->GetRenderBuffer(), E2, Y2, s, false); + } + + for (int k = 0; k < 100; ++k) { + aec_state.Update(subtractor.FilterFrequencyResponse(), + subtractor.FilterImpulseResponse(), + subtractor.ConvergedFilter(), + *render_delay_buffer->GetRenderBuffer(), E2, Y2, s, false); + suppression_gain.GetGain(E2, R2, N2, analyzer, aec_state, x, + &high_bands_gain, &g); + } + std::for_each(g.begin(), g.end(), + [](float a) { EXPECT_NEAR(1.f, a, 0.001); }); + + // Ensure that a strong nearend is detected to mask any echoes. + E2.fill(100.f); + Y2.fill(100.f); + R2.fill(0.1f); + N2.fill(0.f); + for (int k = 0; k < 100; ++k) { + aec_state.Update(subtractor.FilterFrequencyResponse(), + subtractor.FilterImpulseResponse(), + subtractor.ConvergedFilter(), + *render_delay_buffer->GetRenderBuffer(), E2, Y2, s, false); + suppression_gain.GetGain(E2, R2, N2, analyzer, aec_state, x, + &high_bands_gain, &g); + } + std::for_each(g.begin(), g.end(), + [](float a) { EXPECT_NEAR(1.f, a, 0.001); }); + + // Ensure that a strong echo is suppressed. + E2.fill(1000000000.f); + R2.fill(10000000000000.f); + N2.fill(0.f); + for (int k = 0; k < 10; ++k) { + suppression_gain.GetGain(E2, R2, N2, analyzer, aec_state, x, + &high_bands_gain, &g); + } + std::for_each(g.begin(), g.end(), + [](float a) { EXPECT_NEAR(0.f, a, 0.001); }); + +} + +} // namespace aec3 +} // namespace webrtc diff --git a/pool/shard004/C++/0048662_satcommon.cc b/pool/shard004/C++/0048662_satcommon.cc new file mode 100644 index 0000000000000000000000000000000000000000..999086616e7e46c177db6627d9b5065ea425d9c9 --- /dev/null +++ b/pool/shard004/C++/0048662_satcommon.cc @@ -0,0 +1,198 @@ +// -*- coding: utf-8 -*- +// Copyright (C) 2013-2017 Laboratoire de Recherche et Développement +// de l'Epita (LRDE). +// +// This file is part of Spot, a model checking library. +// +// Spot is free software; you can 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. +// +// Spot is distributed in the hope that it will be useful, but WITHOUT +// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY +// or FITNESS FOR A PARTICULAR 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 + + +#if DEBUG_CMN +#define print_debug std::cerr +#else +#define print_debug while (0) std::cout +#endif + +namespace spot +{ + void + vars_helper::init(unsigned size_src, unsigned size_cond, unsigned size_dst, + unsigned size_nacc, unsigned size_path, bool state_based, bool dtbasat) + { + print_debug << "init(" << size_src << ',' << size_cond << ',' << size_dst + << ',' << size_nacc << ',' << size_path << ',' << state_based << ")\n"; + + size_src_ = size_src; + size_cond_ = size_cond; + size_dst_ = size_dst; + size_nacc_ = size_nacc; + size_path_ = size_path; + state_based_ = state_based; + dtbasat_ = dtbasat; + + sn_mult_ = size_src * size_nacc; + cd_mult_ = size_cond * size_dst; + dn_mult_ = size_dst * size_nacc; + sd_mult_ = size_src * size_dst; + dr_mult_ = size_dst * 2; + sdr_mult_ = sd_mult_ * 2; + cdn_mult_ = size_cond * size_dst * size_nacc; + scd_mult_ = size_src * size_cond * size_dst; + psd_mult_ = size_path * size_src * size_dst; + scdn_mult_ = scd_mult_ * size_nacc; + scdnp_mult_ = scdn_mult_ * size_path; + + assert(scdnp_mult_ != 0); + } + + void + vars_helper::declare_all_vars(int& min_t) + { + min_t_ = min_t; + min_ta_ = min_t_ + scd_mult_; + if (!state_based_) + min_p_ = min_ta_ + scdn_mult_; + else + min_p_ = min_ta_ + sn_mult_; + + if (!dtbasat_) + max_p_ = min_p_ + psd_mult_ - 1; + else + max_p_ = min_p_ + psd_mult_ * 2 - 1; + + print_debug << "declare_all_trans(" << min_t << ") --> min_t_<" + << min_t_ << ">, min_ta_<" << min_ta_ << ">, min_p<" + << min_p_ << ">, max_p<" << max_p_ << ">\n"; + + // Update satdict.nvars. + // max_p_ - 1 was added after noticing that in some cases in dtbasat, the + // last variable is not used and some sat solver can complain about the + // wong number of variable in cnf mode. No worries, if it turns out to be + // used somewhere, it will be taken into account. + min_t = dtbasat_ ? max_p_ - 1 : max_p_; + assert(min_t != min_t_); + } + + std::string + vars_helper::format_t(bdd_dict_ptr& debug_dict, unsigned src, bdd& cond, + unsigned dst) + { + std::ostringstream buffer; + buffer << '<' << src << ',' << bdd_format_formula(debug_dict, cond) + << ',' << dst << '>'; + return buffer.str(); + } + + std::string + vars_helper::format_ta(bdd_dict_ptr& debug_dict, + const acc_cond* debug_cand_acc, unsigned src, bdd& cond, unsigned dst, + const acc_cond::mark_t& acc) + { + std::ostringstream buffer; + buffer << '<' << src << ',' << bdd_format_formula(debug_dict, cond) + << ',' << debug_cand_acc->format(acc) << ',' << dst << '>'; + return buffer.str(); + } + + std::string + vars_helper::format_p(const acc_cond* debug_cand_acc, + const acc_cond* debug_ref_acc, unsigned src_cand, unsigned src_ref, + unsigned dst_cand, unsigned dst_ref, acc_cond::mark_t acc_cand, + acc_cond::mark_t acc_ref) + { + std::ostringstream buffer; + buffer << '<' << src_cand << ',' << src_ref << ',' << dst_cand << ',' + << dst_ref << ", " << debug_cand_acc->format(acc_cand) << ", " + << debug_ref_acc->format(acc_ref) << '>'; + return buffer.str(); + } + + std::string + vars_helper::format_p(unsigned src_cand, unsigned src_ref, unsigned dst_cand, + unsigned dst_ref) + { + std::ostringstream buffer; + buffer << '<' << src_cand << ',' << src_ref; + if (src_cand == dst_cand && src_ref == dst_ref) + buffer << '>'; + else + buffer << ',' << dst_cand << ',' << dst_ref << '>'; + return buffer.str(); + } + + void + print_log(timer_map& t, int target_state_number, + twa_graph_ptr& res, satsolver& solver) + { + // Always copy the environment variable into a static string, + // so that we (1) look it up once, but (2) won't crash if the + // environment is changed. + static std::string log = []() + { + auto s = getenv("SPOT_SATLOG"); + return s ? s : ""; + }(); + if (!log.empty()) + { + std::fstream out(log, + std::ios_base::app | std::ios_base::out); + out.exceptions(std::ifstream::failbit | std::ifstream::badbit); + const timer& te = t.timer("encode"); + const timer& ts = t.timer("solve"); + out << target_state_number << ','; + if (res) + { + twa_sub_statistics st = sub_stats_reachable(res); + out << st.states << ',' << st.edges << ',' << st.transitions; + } + else + { + out << ",,"; + } + std::pair s = solver.stats(); // sat_stats + out << ',' + << s.first << ',' << s.second << ',' + << te.utime() + te.cutime() << ',' + << te.stime() + te.cstime() << ',' + << ts.utime() + ts.cutime() << ',' + << ts.stime() + ts.cstime() << ",\""; + if (res) + { + std::ostringstream f; + print_hoa(f, res, "l"); + escape_rfc4180(out, f.str()); + } + out << "\"\n"; + } + } + + int + get_number_of_distinct_vals(std::vector v) + { + std::set distinct; + for (auto it = v.begin(); it != v.end(); ++it) + distinct.insert(*it); + return distinct.size(); + } +} diff --git a/pool/shard004/C++/0048664_main_tests.cpp b/pool/shard004/C++/0048664_main_tests.cpp new file mode 100644 index 0000000000000000000000000000000000000000..cab4be350a184815f0cfc4092b6d2310d94db4b0 --- /dev/null +++ b/pool/shard004/C++/0048664_main_tests.cpp @@ -0,0 +1,76 @@ +// Copyright (c) 2014-2016 The nealcoin Core developers +// Distributed under the MIT software license, see the accompanying +// file COPYING or http://www.opensource.org/licenses/mit-license.php. + +#include "chainparams.h" +#include "validation.h" +#include "net.h" + +#include "test/test_nealcoin.h" + +#include +#include + +BOOST_FIXTURE_TEST_SUITE(main_tests, TestingSetup) + +static void TestBlockSubsidyHalvings(const Consensus::Params& consensusParams) +{ + int maxHalvings = 64; + CAmount nInitialSubsidy = 50 * COIN; + + CAmount nPreviousSubsidy = nInitialSubsidy * 2; // for height == 0 + BOOST_CHECK_EQUAL(nPreviousSubsidy, nInitialSubsidy * 2); + for (int nHalvings = 0; nHalvings < maxHalvings; nHalvings++) { + int nHeight = nHalvings * consensusParams.nSubsidyHalvingInterval; + CAmount nSubsidy = GetBlockSubsidy(nHeight, consensusParams); + BOOST_CHECK(nSubsidy <= nInitialSubsidy); + BOOST_CHECK_EQUAL(nSubsidy, nPreviousSubsidy / 2); + nPreviousSubsidy = nSubsidy; + } + BOOST_CHECK_EQUAL(GetBlockSubsidy(maxHalvings * consensusParams.nSubsidyHalvingInterval, consensusParams), 0); +} + +static void TestBlockSubsidyHalvings(int nSubsidyHalvingInterval) +{ + Consensus::Params consensusParams; + consensusParams.nSubsidyHalvingInterval = nSubsidyHalvingInterval; + TestBlockSubsidyHalvings(consensusParams); +} + +BOOST_AUTO_TEST_CASE(block_subsidy_test) +{ + TestBlockSubsidyHalvings(Params(CBaseChainParams::MAIN).GetConsensus()); // As in main + TestBlockSubsidyHalvings(150); // As in regtest + TestBlockSubsidyHalvings(1000); // Just another interval +} + +BOOST_AUTO_TEST_CASE(subsidy_limit_test) +{ + const Consensus::Params& consensusParams = Params(CBaseChainParams::MAIN).GetConsensus(); + CAmount nSum = 0; + for (int nHeight = 0; nHeight < 14000000; nHeight += 1000) { + CAmount nSubsidy = GetBlockSubsidy(nHeight, consensusParams); + BOOST_CHECK(nSubsidy <= 50 * COIN); + nSum += nSubsidy * 1000; + BOOST_CHECK(MoneyRange(nSum)); + } + BOOST_CHECK_EQUAL(nSum, 2099999997690000ULL); +} + +bool ReturnFalse() { return false; } +bool ReturnTrue() { return true; } + +BOOST_AUTO_TEST_CASE(test_combiner_all) +{ + boost::signals2::signal Test; + BOOST_CHECK(Test()); + Test.connect(&ReturnFalse); + BOOST_CHECK(!Test()); + Test.connect(&ReturnTrue); + BOOST_CHECK(!Test()); + Test.disconnect(&ReturnFalse); + BOOST_CHECK(Test()); + Test.disconnect(&ReturnTrue); + BOOST_CHECK(Test()); +} +BOOST_AUTO_TEST_SUITE_END() diff --git a/pool/shard004/C++/0048670_time.cc b/pool/shard004/C++/0048670_time.cc new file mode 100644 index 0000000000000000000000000000000000000000..a9e4b1cf90aa61c031feaa05f52a01111090f431 --- /dev/null +++ b/pool/shard004/C++/0048670_time.cc @@ -0,0 +1,208 @@ +// 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 "base/time/time.h" + +#include +#include + +#include "base/float_util.h" +#include "base/logging.h" +#include "base/third_party/nspr/prtime.h" +#include "base/third_party/nspr/prtypes.h" + +namespace base { + +// TimeDelta ------------------------------------------------------------------ + +int TimeDelta::InDays() const { + return static_cast(delta_ / Time::kMicrosecondsPerDay); +} + +int TimeDelta::InHours() const { + return static_cast(delta_ / Time::kMicrosecondsPerHour); +} + +int TimeDelta::InMinutes() const { + return static_cast(delta_ / Time::kMicrosecondsPerMinute); +} + +double TimeDelta::InSecondsF() const { + return static_cast(delta_) / Time::kMicrosecondsPerSecond; +} + +int64 TimeDelta::InSeconds() const { + return delta_ / Time::kMicrosecondsPerSecond; +} + +double TimeDelta::InMillisecondsF() const { + return static_cast(delta_) / Time::kMicrosecondsPerMillisecond; +} + +int64 TimeDelta::InMilliseconds() const { + return delta_ / Time::kMicrosecondsPerMillisecond; +} + +int64 TimeDelta::InMillisecondsRoundedUp() const { + return (delta_ + Time::kMicrosecondsPerMillisecond - 1) / + Time::kMicrosecondsPerMillisecond; +} + +int64 TimeDelta::InMicroseconds() const { + return delta_; +} + +// Time ----------------------------------------------------------------------- + +// static +Time Time::Max() { + return Time(std::numeric_limits::max()); +} + +// static +Time Time::FromTimeT(time_t tt) { + if (tt == 0) + return Time(); // Preserve 0 so we can tell it doesn't exist. + if (tt == std::numeric_limits::max()) + return Max(); + return Time((tt * kMicrosecondsPerSecond) + kTimeTToMicrosecondsOffset); +} + +time_t Time::ToTimeT() const { + if (is_null()) + return 0; // Preserve 0 so we can tell it doesn't exist. + if (is_max()) { + // Preserve max without offset to prevent overflow. + return std::numeric_limits::max(); + } + if (std::numeric_limits::max() - kTimeTToMicrosecondsOffset <= us_) { + DLOG(WARNING) << "Overflow when converting base::Time with internal " << + "value " << us_ << " to time_t."; + return std::numeric_limits::max(); + } + return (us_ - kTimeTToMicrosecondsOffset) / kMicrosecondsPerSecond; +} + +// static +Time Time::FromDoubleT(double dt) { + if (dt == 0 || IsNaN(dt)) + return Time(); // Preserve 0 so we can tell it doesn't exist. + if (dt == std::numeric_limits::max()) + return Max(); + return Time(static_cast((dt * + static_cast(kMicrosecondsPerSecond)) + + kTimeTToMicrosecondsOffset)); +} + +double Time::ToDoubleT() const { + if (is_null()) + return 0; // Preserve 0 so we can tell it doesn't exist. + if (is_max()) { + // Preserve max without offset to prevent overflow. + return std::numeric_limits::max(); + } + return (static_cast(us_ - kTimeTToMicrosecondsOffset) / + static_cast(kMicrosecondsPerSecond)); +} + +#if defined(OS_POSIX) +// static +Time Time::FromTimeSpec(const timespec& ts) { + return FromDoubleT(ts.tv_sec + + static_cast(ts.tv_nsec) / + base::Time::kNanosecondsPerSecond); +} +#endif + +// static +Time Time::FromJsTime(double ms_since_epoch) { + // The epoch is a valid time, so this constructor doesn't interpret + // 0 as the null time. + if (ms_since_epoch == std::numeric_limits::max()) + return Max(); + return Time(static_cast(ms_since_epoch * kMicrosecondsPerMillisecond) + + kTimeTToMicrosecondsOffset); +} + +double Time::ToJsTime() const { + if (is_null()) { + // Preserve 0 so the invalid result doesn't depend on the platform. + return 0; + } + if (is_max()) { + // Preserve max without offset to prevent overflow. + return std::numeric_limits::max(); + } + return (static_cast(us_ - kTimeTToMicrosecondsOffset) / + kMicrosecondsPerMillisecond); +} + +int64 Time::ToJavaTime() const { + if (is_null()) { + // Preserve 0 so the invalid result doesn't depend on the platform. + return 0; + } + if (is_max()) { + // Preserve max without offset to prevent overflow. + return std::numeric_limits::max(); + } + return ((us_ - kTimeTToMicrosecondsOffset) / + kMicrosecondsPerMillisecond); +} + +// static +Time Time::UnixEpoch() { + Time time; + time.us_ = kTimeTToMicrosecondsOffset; + return time; +} + +Time Time::LocalMidnight() const { + Exploded exploded; + LocalExplode(&exploded); + exploded.hour = 0; + exploded.minute = 0; + exploded.second = 0; + exploded.millisecond = 0; + return FromLocalExploded(exploded); +} + +// static +bool Time::FromStringInternal(const char* time_string, + bool is_local, + Time* parsed_time) { + DCHECK((time_string != NULL) && (parsed_time != NULL)); + + if (time_string[0] == '\0') + return false; + + PRTime result_time = 0; + PRStatus result = PR_ParseTimeString(time_string, + is_local ? PR_FALSE : PR_TRUE, + &result_time); + if (PR_SUCCESS != result) + return false; + + result_time += kTimeTToMicrosecondsOffset; + *parsed_time = Time(result_time); + return true; +} + +// Time::Exploded ------------------------------------------------------------- + +inline bool is_in_range(int value, int lo, int hi) { + return lo <= value && value <= hi; +} + +bool Time::Exploded::HasValidValues() const { + return is_in_range(month, 1, 12) && + is_in_range(day_of_week, 0, 6) && + is_in_range(day_of_month, 1, 31) && + is_in_range(hour, 0, 23) && + is_in_range(minute, 0, 59) && + is_in_range(second, 0, 60) && + is_in_range(millisecond, 0, 999); +} + +} // namespace base diff --git a/pool/shard004/C++/0048689_userdata.cpp b/pool/shard004/C++/0048689_userdata.cpp new file mode 100644 index 0000000000000000000000000000000000000000..e70fd223af126accaccc1b5af6b191a44061e2bb --- /dev/null +++ b/pool/shard004/C++/0048689_userdata.cpp @@ -0,0 +1,44 @@ +//------------------------------------------------------------------------- +// Copyright (c) 1997-1998 Great Hill Corporation +// All Rights Reserved. +//------------------------------------------------------------------------- +#include "Kramer.h" + +#include "UserData.h" + +vrUserDataList::~vrUserDataList(void) +{ + LISTPOS pos = GetHeadPosition(); + while (pos) + { + vrUserDataItem *item = GetNext(pos); + delete item; + } + RemoveAll(); +} + +vrUserDataItem::vrUserDataItem(const SFString& id, vrUserData *data) +{ + m_Data = data; + m_ID = id; +} + +vrUserDataItem::~vrUserDataItem() +{ + if (m_Data) + delete m_Data; +} + +vrUserDataItem *vrUserDataList::FindItem(const SFString& id) +{ + LISTPOS pos = GetHeadPosition(); + while (pos) + { + vrUserDataItem *item = GetNext(pos); + ASSERT(item); + if (item->m_ID == id) + return item; + } + return NULL; +} + diff --git a/pool/shard004/C++/0048699_StringServer.cpp b/pool/shard004/C++/0048699_StringServer.cpp new file mode 100644 index 0000000000000000000000000000000000000000..68e3eeb1365c13682939b42c67f5c13b0ee33a06 --- /dev/null +++ b/pool/shard004/C++/0048699_StringServer.cpp @@ -0,0 +1,95 @@ +// -------------------------------------------------------------------------------------------------- +// Copyright (c) 2016 Microsoft Corporation +// +// 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. +// -------------------------------------------------------------------------------------------------- + +// Local: +#include "StringServer.h" + +// Boost: +#include +#include + +namespace malmo { + StringServer::StringServer(boost::asio::io_service& io_service, int port, const boost::function handle_string) + : handle_string(handle_string) + , server(io_service, port, boost::bind(&StringServer::handleMessage, this, _1)) + { + } + + void StringServer::start() + { + this->server.start(); + } + + StringServer& StringServer::record(std::string path) + { + if (this->writer.is_open()){ + this->writer.close(); + } + + this->writer.open(path, std::ofstream::out | std::ofstream::app); + + return *this; + } + + StringServer& StringServer::confirmWithFixedReply(std::string reply) + { + this->server.confirmWithFixedReply(reply); + return *this; + } + + StringServer& StringServer::expectSizeHeader(bool expect_size_header) + { + this->server.expectSizeHeader(expect_size_header); + return *this; + } + + void StringServer::handleMessage(const TimestampedUnsignedCharVector message) + { + TimestampedString string_message(message); + + this->handle_string(string_message); + + this->recordMessage(string_message); + } + + void StringServer::stopRecording() + { + if (this->writer.is_open()) + { + boost::lock_guard scope_guard(this->write_mutex); + + this->writer.close(); + } + } + + int StringServer::getPort() const + { + return this->server.getPort(); + } + + void StringServer::recordMessage(const TimestampedString string_message) + { + if (this->writer.is_open()) + { + boost::lock_guard scope_guard(this->write_mutex); + + this->writer << boost::posix_time::to_iso_string(string_message.timestamp) << " " << string_message.text << std::endl; + } + } +} diff --git a/pool/shard004/C++/0048708_load_jpeg.cpp b/pool/shard004/C++/0048708_load_jpeg.cpp new file mode 100644 index 0000000000000000000000000000000000000000..da5fc487fdd18d2090f247445127ba95c6efec2b --- /dev/null +++ b/pool/shard004/C++/0048708_load_jpeg.cpp @@ -0,0 +1,163 @@ +/*********************************************************************** + load_jpeg.cpp - Example showing how to insert BLOB data into the + database from a file. + + Copyright (c) 1998 by Kevin Atkinson, (c) 1999-2001 by MySQL AB, and + (c) 2004-2009 by Educational Technology Resources, Inc. Others may + also hold copyrights on code in this file. See the CREDITS.txt file + in the top directory of the distribution for details. + + This file is part of MySQL++. + + MySQL++ 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. + + MySQL++ is distributed in the hope that 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 MySQL++; if not, write to the Free Software + Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 + USA +***********************************************************************/ + +#include "cmdline.h" +#include "images.h" +#include "printdata.h" + +#include + +using namespace std; +using namespace mysqlpp; + + +// This is just an implementation detail for the example. Skip down to +// main() for the concept this example is trying to demonstrate. You +// can simply assume that, given a BLOB containing a valid JPEG, it +// returns true. +static bool +is_jpeg(const mysqlpp::sql_blob& img, const char** whynot) +{ + // See http://stackoverflow.com/questions/2253404/ for + // justification for the various tests. + const unsigned char* idp = + reinterpret_cast(img.data()); + if (img.size() < 125) { + *whynot = "a valid JPEG must be at least 125 bytes"; + } + else if ((idp[0] != 0xFF) || (idp[1] != 0xD8)) { + *whynot = "file does not begin with JPEG sigil bytes"; + } + else if ((memcmp(idp + 6, "JFIF", 4) != 0) && + (memcmp(idp + 6, "Exif", 4) != 0)) { + *whynot = "file does not contain JPEG type word"; + } + else { + *whynot = 0; + return true; + } + + return false; +} + + +// Skip to main() before studying this. This is a little too +// low-level to bother with on your first pass thru the code. +static bool +load_jpeg_file(const mysqlpp::examples::CommandLine& cmdline, + images& img, string& img_name) +{ + if (cmdline.extra_args().size() == 0) { + // Nothing for us to do here. Caller will insert NULL BLOB. + return true; + } + + // Got a file's name on the command line, so open it. + img_name = cmdline.extra_args()[0]; + ifstream img_file(img_name.c_str(), ios::binary); + if (img_file) { + // Slurp file contents into RAM with minimum copying. (Idiom + // explained here: http://stackoverflow.com/questions/116038/) + // + // By loading the file into a C++ string (stringstream::str()) + // and assigning that directly to a mysqlpp::sql_blob, we avoid + // truncating the binary data at the first null character. + img.data.data = static_cast( + &(stringstream() << img_file.rdbuf()))->str(); + + // Check JPEG data for sanity. + const char* error; + if (is_jpeg(img.data.data, &error)) { + return true; + } + else { + cerr << '"' << img_name << "\" isn't a JPEG: " << + error << '!' << endl; + } + } + + cmdline.print_usage("[jpeg_file]"); + return false; +} + + +int +main(int argc, char *argv[]) +{ + // Get database access parameters from command line + mysqlpp::examples::CommandLine cmdline(argc, argv); + if (!cmdline) { + return 1; + } + + try { + // Establish the connection to the database server. + mysqlpp::Connection con(mysqlpp::examples::db_name, + cmdline.server(), cmdline.user(), cmdline.pass()); + + // Load the file named on the command line + images img(mysqlpp::null, mysqlpp::null); + string img_name("NULL"); + if (load_jpeg_file(cmdline, img, img_name)) { + // Insert image data or SQL NULL into the images.data BLOB + // column. The key here is that we're holding the raw + // binary data in a mysqlpp::sql_blob, which avoids data + // conversion problems that can lead to treating BLOB data + // as C strings, thus causing null-truncation. The fact + // that we're using SSQLS here is a side issue, simply + // demonstrating that mysqlpp::Null is + // now legal in SSQLS, as of MySQL++ 3.0.7. + Query query = con.query(); + query.insert(img); + SimpleResult res = query.execute(); + + // Report successful insertion + cout << "Inserted \"" << img_name << + "\" into images table, " << img.data.data.size() << + " bytes, ID " << res.insert_id() << endl; + } + } + catch (const BadQuery& er) { + // Handle any query errors + cerr << "Query error: " << er.what() << endl; + return -1; + } + catch (const BadConversion& er) { + // Handle bad conversions + cerr << "Conversion error: " << er.what() << endl << + "\tretrieved data size: " << er.retrieved << + ", actual size: " << er.actual_size << endl; + return -1; + } + catch (const Exception& er) { + // Catch-all for any other MySQL++ exceptions + cerr << "Error: " << er.what() << endl; + return -1; + } + + return 0; +} diff --git a/pool/shard004/C++/0048718_DragCaretController.cpp b/pool/shard004/C++/0048718_DragCaretController.cpp new file mode 100644 index 0000000000000000000000000000000000000000..9bde753211523a9a68b9d9696d0c8f95b2051d2e --- /dev/null +++ b/pool/shard004/C++/0048718_DragCaretController.cpp @@ -0,0 +1,120 @@ +/* + * Copyright (C) 2004, 2008, 2009, 2010 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 COMPUTER, INC. ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR +* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY + * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "core/editing/DragCaretController.h" + +#include "core/editing/EditingUtilities.h" +#include "core/layout/api/LayoutViewItem.h" +#include "core/paint/PaintLayer.h" + +namespace blink { + +DragCaretController::DragCaretController() + : m_caretBase(new CaretBase(CaretVisibility::Visible)) +{ +} + +DragCaretController* DragCaretController::create() +{ + return new DragCaretController; +} + +bool DragCaretController::isContentRichlyEditable() const +{ + return isRichlyEditablePosition(m_position.deepEquivalent()); +} + +void DragCaretController::setCaretPosition(const PositionWithAffinity& position) +{ + // for querying Layer::compositingState() + // This code is probably correct, since it doesn't occur in a stack that + // involves updating compositing state. + DisableCompositingQueryAsserts disabler; + + if (Node* node = m_position.deepEquivalent().anchorNode()) + m_caretBase->invalidateCaretRect(node); + m_position = createVisiblePosition(position); + Document* document = nullptr; + if (Node* node = m_position.deepEquivalent().anchorNode()) { + m_caretBase->invalidateCaretRect(node); + document = &node->document(); + } + if (m_position.isNull() || m_position.isOrphan()) { + m_caretBase->clearCaretRect(); + } else { + document->updateStyleAndLayoutTree(); + m_caretBase->updateCaretRect(m_position); + } +} + +static bool removingNodeRemovesPosition(Node& node, const Position& position) +{ + if (!position.anchorNode()) + return false; + + if (position.anchorNode() == node) + return true; + + if (!node.isElementNode()) + return false; + + Element& element = toElement(node); + return element.isShadowIncludingInclusiveAncestorOf(position.anchorNode()); +} + +void DragCaretController::nodeWillBeRemoved(Node& node) +{ + if (!hasCaret() || !node.inActiveDocument()) + return; + + if (!removingNodeRemovesPosition(node, m_position.deepEquivalent())) + return; + + m_position.deepEquivalent().document()->layoutViewItem().clearSelection(); + clear(); +} + +DEFINE_TRACE(DragCaretController) +{ + visitor->trace(m_position); +} + +LayoutBlock* DragCaretController::caretLayoutObject() const +{ + return CaretBase::caretLayoutObject(m_position.deepEquivalent().anchorNode()); +} + +bool DragCaretController::isContentEditable() const +{ + return rootEditableElementOf(m_position); +} + +void DragCaretController::paintDragCaret(LocalFrame* frame, GraphicsContext& context, const LayoutPoint& paintOffset) const +{ + if (m_position.deepEquivalent().anchorNode()->document().frame() == frame) + m_caretBase->paintCaret(m_position.deepEquivalent().anchorNode(), context, paintOffset); +} + +} // namespace blink diff --git a/pool/shard004/C++/0048719_LoanCalculator.cpp b/pool/shard004/C++/0048719_LoanCalculator.cpp new file mode 100644 index 0000000000000000000000000000000000000000..13621ca23092eac205e9ee3d11ef34d4ef16710e --- /dev/null +++ b/pool/shard004/C++/0048719_LoanCalculator.cpp @@ -0,0 +1,212 @@ +// +// LoanCalculator.cpp +// Kata.LoanPrediction.C++ +// +// Created by retroburst [Andrew D] on 3/09/2015. +// Copyright (c) 2015 retroburst [Andrew D]. All rights reserved. +// + +#include "LoanCalculator.h" +#include "Global.h" + +/* + *************************************** + ** Default constructor. + *************************************** + */ +LoanCalculator::LoanCalculator(LoanContext context) +{ + this->context = context; +} + +/* + *************************************** + ** Calculates the transactions on the + ** loan from now to the time it will be + ** paid off. + *************************************** + */ +LoanCalculationOutput LoanCalculator::calculateLoan() +{ + LoanCalculationOutput output; + bool firstIteration = true; + double balance = context.getBalance(); + double monthlyInterest = 0.0; + dateTime currentDate = context.getStartDate(); + currentDate.tm_isdst = 0; + // we will calculate interest from the first of the month + dateTime calcInterestStartDate = currentDate; + calcInterestStartDate.tm_mday = 1; + output.setInterestStartDate(calcInterestStartDate); + // loop through dates, caculating interest daily etc + while (true) + { + // if min repay day + if (currentDate.tm_mday == context.getMinRepaymentDay() && balance > 0.0) + { + processMinRepayment(balance, context.getMinRepaymentAmount(), currentDate, monthlyInterest, output); + } + // if extra repay day + if (currentDate.tm_mday == context.getExtraRepaymentDay() && context.getExtraRepaymentAmount() > 0.0 && balance > 0.0) + { + processExtraRepayment(balance, context.getExtraRepaymentAmount(), currentDate, output); + } + + // if balance is zero or less - we are done! + if (balance <= 0.0) + { + output.setLoanEndsDate(currentDate); + break; + } + // calculate the daily interest + monthlyInterest += calculateDailyInterest(balance, context.getInterestRate()); + // if this is the first iteration and we did not start on the first of the month + // let's calculate the interest for the days back to the first + if (firstIteration && context.getStartDate().tm_mday != 1) + { + int daysToMonthStart = currentDate.tm_mday - 1; + monthlyInterest += (monthlyInterest * daysToMonthStart); + firstIteration = false; + } + // move date forward + dateTime nextDate = currentDate; + nextDate.tm_isdst = 0; + addDay(&nextDate); + // if end of month + if (currentDate.tm_mon != nextDate.tm_mon) + { + processEndOfMonth(currentDate, monthlyInterest, balance, output); + } + currentDate = nextDate; + } + setTargetEndDateAccuracy(output.getLoanEndsDate(), context.getTargetEndDate(), output); + return(output); +} + +/* + *************************************** + ** Processes the end of month, adds + ** interest to the balance. + *************************************** + */ +void LoanCalculator::processEndOfMonth(dateTime currentDate, double &monthlyInterest, double &balance, LoanCalculationOutput &output) +{ + // add interest charged transaction + balance += monthlyInterest; + // calculate the total interest paid + output.setTotalInterestPaid(output.getTotalInterestPaid() + monthlyInterest); + output.addTransaction(createTransaction(TX_TYPE_INTEREST_CHARGED, currentDate, 0.0, monthlyInterest, balance)); + // reset for new month + monthlyInterest = 0.0; +} + +/* + *************************************** + ** Processes the extra repayment for the + ** current date if applicable. + *************************************** + */ +void LoanCalculator::processExtraRepayment(double &balance, double extraRepaymentAmount, dateTime currentDate, LoanCalculationOutput &output) +{ + // add extra repay transaction (if amount is more than 0) + balance -= extraRepaymentAmount; + output.addTransaction(createTransaction(TX_TYPE_EXTRA_REPAYMENT, currentDate, extraRepaymentAmount, 0.0, balance)); +} + +/* + *************************************** + ** Processes the min repayment for the + ** current date if applicable. + *************************************** + */ +void LoanCalculator::processMinRepayment(double &balance, double minRepaymentAmount, dateTime ¤tDate, double monthlyInterest, LoanCalculationOutput &output) +{ + // add min repay transaction + if ((balance + monthlyInterest) <= minRepaymentAmount) + { + double finalRepayment = 0.0; + balance += monthlyInterest; + finalRepayment = balance; + balance -= finalRepayment; + output.addTransaction(createTransaction(TX_FINAL_REPAYMENT, currentDate, finalRepayment, monthlyInterest, balance)); + } + else + { + balance -= context.getMinRepaymentAmount(); + output.addTransaction(createTransaction(TX_TYPE_MIN_REPAYMENT, currentDate, minRepaymentAmount, 0.0, balance)); + } +} + +/* + *************************************** + ** Calculates the interest for a day. + *************************************** + */ +double LoanCalculator::calculateDailyInterest(double balance, double interestRate) +{ + double result = 0.0; + result = (balance * (interestRate / 100)) / NUM_DAYS_IN_YEAR; + return(result); +} + +/* + *************************************** + ** Creates a transaction using the + ** provided values. + *************************************** + */ +LoanTransaction LoanCalculator::createTransaction(string type, dateTime date, double repayment, double charge, double balance) +{ + LoanTransaction transaction; + transaction.setType(type); + transaction.setDate(date); + transaction.setCredit(repayment); + transaction.setDebit(charge); + transaction.setBalance(balance); + return(transaction); +} + +/* + *************************************** + ** Sets the accuracy of the target end + ** end date with respect to the actual + ** end date. + *************************************** + */ +void LoanCalculator::setTargetEndDateAccuracy(dateTime actualEndDate, dateTime targetEndDate, LoanCalculationOutput &output) +{ + int daysMissed = 0; + bool searchForwards = false; + output.setTargetEndDateHit(false); + dateTime *search = new dateTime(actualEndDate); + int compareResult = compareDates(actualEndDate, targetEndDate); + if (compareResult == 0) + { + output.setTargetEndDateHit(true); + return; + } + if (compareResult == 1) + { + searchForwards = false; + } + else if (compareResult == -1) + { + searchForwards = true; + } + while (compareDates(*search, targetEndDate) != 0) + { + if (searchForwards) + { + addDay(search); + daysMissed--; + } + else + { + minusDay(search); + daysMissed++; + } + } + output.setTargetEndDateMissedInDays(daysMissed); + delete(search); +} + diff --git a/pool/shard004/C++/0048722_Mixer.cpp b/pool/shard004/C++/0048722_Mixer.cpp new file mode 100644 index 0000000000000000000000000000000000000000..15872fbcff2b10dbd31375477892ed4dd43e816f --- /dev/null +++ b/pool/shard004/C++/0048722_Mixer.cpp @@ -0,0 +1,118 @@ +/******************************************************************************* + * Copyright 2009-2016 Jörg Müller + * + * 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 "respec/Mixer.h" + +#include +#include + +AUD_NAMESPACE_BEGIN + +Mixer::Mixer(DeviceSpecs specs) +{ + setSpecs(specs); +} + +DeviceSpecs Mixer::getSpecs() const +{ + return m_specs; +} + +void Mixer::setSpecs(Specs specs) +{ + m_specs.specs = specs; +} + +void Mixer::setSpecs(DeviceSpecs specs) +{ + m_specs = specs; + + switch(m_specs.format) + { + case FORMAT_U8: + m_convert = convert_float_u8; + break; + case FORMAT_S16: + m_convert = convert_float_s16; + break; + case FORMAT_S24: + +#ifdef __BIG_ENDIAN__ + m_convert = convert_float_s24_be; +#else + m_convert = convert_float_s24_le; +#endif + break; + case FORMAT_S32: + m_convert = convert_float_s32; + break; + case FORMAT_FLOAT32: + m_convert = convert_copy; + break; + case FORMAT_FLOAT64: + m_convert = convert_float_double; + break; + default: + break; + } +} + +void Mixer::clear(int length) +{ + m_buffer.assureSize(length * AUD_SAMPLE_SIZE(m_specs)); + + m_length = length; + + std::memset(m_buffer.getBuffer(), 0, length * AUD_SAMPLE_SIZE(m_specs)); +} + +void Mixer::mix(sample_t* buffer, int start, int length, float volume) +{ + sample_t* out = m_buffer.getBuffer(); + + length = (std::min(m_length, length + start) - start) * m_specs.channels; + start *= m_specs.channels; + + for(int i = 0; i < length; i++) + out[i + start] += buffer[i] * volume; +} + +void Mixer::mix(sample_t* buffer, int start, int length, float volume_to, float volume_from) +{ + sample_t* out = m_buffer.getBuffer(); + + length = (std::min(m_length, length + start) - start); + + for(int i = 0; i < length; i++) + { + float volume = volume_from * (1.0f - i / float(length)) + volume_to * (i / float(length)); + + for(int c = 0; c < m_specs.channels; c++) + out[(i + start) * m_specs.channels + c] += buffer[i * m_specs.channels + c] * volume; + } +} + +void Mixer::read(data_t* buffer, float volume) +{ + sample_t* out = m_buffer.getBuffer(); + + for(int i = 0; i < m_length * m_specs.channels; i++) + out[i] *= volume; + + m_convert(buffer, (data_t*) out, m_length * m_specs.channels); +} + +AUD_NAMESPACE_END diff --git a/pool/shard004/C++/0048730_ItemNameUtils.cpp b/pool/shard004/C++/0048730_ItemNameUtils.cpp new file mode 100644 index 0000000000000000000000000000000000000000..46f2cee3e110a28aca5d4c14ca5eeacb9c6aafc5 --- /dev/null +++ b/pool/shard004/C++/0048730_ItemNameUtils.cpp @@ -0,0 +1,59 @@ +// Archive/Common/ItemNameUtils.cpp + +#include "StdAfx.h" + +#include "ItemNameUtils.h" + +namespace NArchive { +namespace NItemName { + +static const wchar_t kOSDirDelimiter = WCHAR_PATH_SEPARATOR; +static const wchar_t kDirDelimiter = L'/'; + +UString MakeLegalName(const UString &name) +{ + UString zipName = name; + zipName.Replace(kOSDirDelimiter, kDirDelimiter); + return zipName; +} + +UString GetOSName(const UString &name) +{ + UString newName = name; + newName.Replace(kDirDelimiter, kOSDirDelimiter); + return newName; +} + +UString GetOSName2(const UString &name) +{ + if (name.IsEmpty()) + return UString(); + UString newName = GetOSName(name); + if (newName[newName.Length() - 1] == kOSDirDelimiter) + newName.Delete(newName.Length() - 1); + return newName; +} + +bool HasTailSlash(const AString &name, UINT codePage) +{ + if (name.IsEmpty()) + return false; + LPCSTR prev = + #ifdef _WIN32 + CharPrevExA(codePage, name, &name[name.Length()], 0); + #else + (LPCSTR)(name) + (name.Length() - 1); + #endif + return (*prev == '/'); +} + +#ifndef _WIN32 +UString WinNameToOSName(const UString &name) +{ + UString newName = name; + newName.Replace(L'\\', kOSDirDelimiter); + return newName; +} +#endif + +}} diff --git a/pool/shard004/C++/0048732_GuiVSpace.cpp b/pool/shard004/C++/0048732_GuiVSpace.cpp new file mode 100644 index 0000000000000000000000000000000000000000..6eec95846bcf2000eb67ff4e900f03b7868f042e --- /dev/null +++ b/pool/shard004/C++/0048732_GuiVSpace.cpp @@ -0,0 +1,175 @@ +/** + * \file GuiVSpace.cpp + * This file is part of LyX, the document processor. + * Licence details can be found in the file COPYING. + * + * \author André Pönitz + * \author Jürgen Vigna + * \author Rob Lahaye + * \author Angus Leeming + * \author Edwin Leuven + * \author Jürgen Spitzmüller + * + * Full author contact details are available in file CREDITS. + */ + +#include + +#include "GuiVSpace.h" + +#include "LengthCombo.h" +#include "qt_helpers.h" +#include "Validator.h" + +#include "Spacing.h" +#include "VSpace.h" + +#include "insets/InsetVSpace.h" + +#include "support/gettext.h" +#include "support/lstrings.h" + +#include +#include +#include +#include + +using namespace std; + +namespace lyx { +namespace frontend { + +GuiVSpace::GuiVSpace(QWidget * parent) : InsetParamsWidget(parent) +{ + setupUi(this); + + connect(valueLE, SIGNAL(textChanged(QString)), + this, SIGNAL(changed())); + connect(keepCB, SIGNAL(clicked()), + this, SIGNAL(changed())); + connect(unitCO, SIGNAL(selectionChanged(lyx::Length::UNIT)), + this, SIGNAL(changed())); + + connect(spacingCO, SIGNAL(activated(int)), + this, SLOT(enableCustom(int))); + + // Set up a signed glue length validator + LengthValidator * v = new LengthValidator(valueLE); + v->setBottom(GlueLength()); + valueLE->setValidator(v); + + // initialize the length validator + addCheckedWidget(valueLE, valueL); + enableCustom(spacingCO->currentIndex()); +} + + +void GuiVSpace::enableCustom(int selection) +{ + bool const enable = selection == 5; + valueLE->setEnabled(enable); + if (enable) + valueLE->setFocus(); + valueL->setEnabled(enable); + unitCO->setEnabled(enable); + changed(); +} + + +static void setWidgetsFromVSpace(VSpace const & space, + QComboBox * spacing, + QLineEdit * value, + LengthCombo * unit, + QCheckBox * keep) +{ + int item = 0; + switch (space.kind()) { + case VSpace::DEFSKIP: item = 0; break; + case VSpace::SMALLSKIP: item = 1; break; + case VSpace::MEDSKIP: item = 2; break; + case VSpace::BIGSKIP: item = 3; break; + case VSpace::VFILL: item = 4; break; + case VSpace::LENGTH: item = 5; break; + } + spacing->setCurrentIndex(item); + keep->setChecked(space.keep()); + + Length::UNIT const default_unit = Length::defaultUnit(); + bool const custom_vspace = space.kind() == VSpace::LENGTH; + if (custom_vspace) { + value->setEnabled(true); + unit->setEnabled(true); + string length = space.length().asString(); + lengthToWidgets(value, unit, length, default_unit); + } else { + lengthToWidgets(value, unit, "", default_unit); + value->setEnabled(false); + unit->setEnabled(false); + } +} + + +static VSpace setVSpaceFromWidgets(int spacing, + QLineEdit * value, LengthCombo * unit, bool keep) +{ + VSpace space; + + switch (spacing) { + case 0: space = VSpace(VSpace::DEFSKIP); break; + case 1: space = VSpace(VSpace::SMALLSKIP); break; + case 2: space = VSpace(VSpace::MEDSKIP); break; + case 3: space = VSpace(VSpace::BIGSKIP); break; + case 4: space = VSpace(VSpace::VFILL); break; + case 5: space = VSpace(GlueLength(widgetsToLength(value, unit))); break; + } + + space.setKeep(keep); + return space; +} + + +docstring GuiVSpace::dialogToParams() const +{ + // If a vspace choice is "Length" but there's no text in + // the input field, do not insert a vspace at all. + if (spacingCO->currentIndex() == 5 && valueLE->text().isEmpty()) + return docstring(); + + VSpace const params = setVSpaceFromWidgets(spacingCO->currentIndex(), + valueLE, unitCO, keepCB->isChecked()); + return from_ascii(InsetVSpace::params2string(params)); +} + + +void GuiVSpace::paramsToDialog(Inset const * inset) +{ + InsetVSpace const * vs = static_cast(inset); + VSpace const & params = vs->space(); + setWidgetsFromVSpace(params, spacingCO, valueLE, unitCO, keepCB); + enableCustom(spacingCO->currentIndex()); +} + + +bool GuiVSpace::checkWidgets(bool readonly) const +{ + valueLE->setReadOnly(readonly); + keepCB->setEnabled(!readonly); + + if (readonly) { + spacingCO->setEnabled(false); + unitCO->setEnabled(false); + } else { + bool const enable = (spacingCO->currentIndex() == 5); + valueLE->setEnabled(enable); + valueL->setEnabled(enable); + unitCO->setEnabled(enable); + } + + return InsetParamsWidget::checkWidgets(); +} + +} // namespace frontend +} // namespace lyx + + +#include "moc_GuiVSpace.cpp" diff --git a/pool/shard004/C++/0048733_ShippingOption.cpp b/pool/shard004/C++/0048733_ShippingOption.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f14484790f9ab002b4d7e9f6cc51fc7a637ae1fa --- /dev/null +++ b/pool/shard004/C++/0048733_ShippingOption.cpp @@ -0,0 +1,84 @@ +/** + * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. + * SPDX-License-Identifier: Apache-2.0. + */ + +#include +#include +#include +#include + +using namespace Aws::Utils; + + +namespace Aws +{ + namespace Snowball + { + namespace Model + { + namespace ShippingOptionMapper + { + + static const int SECOND_DAY_HASH = HashingUtils::HashString("SECOND_DAY"); + static const int NEXT_DAY_HASH = HashingUtils::HashString("NEXT_DAY"); + static const int EXPRESS_HASH = HashingUtils::HashString("EXPRESS"); + static const int STANDARD_HASH = HashingUtils::HashString("STANDARD"); + + + ShippingOption GetShippingOptionForName(const Aws::String& name) + { + int hashCode = HashingUtils::HashString(name.c_str()); + if (hashCode == SECOND_DAY_HASH) + { + return ShippingOption::SECOND_DAY; + } + else if (hashCode == NEXT_DAY_HASH) + { + return ShippingOption::NEXT_DAY; + } + else if (hashCode == EXPRESS_HASH) + { + return ShippingOption::EXPRESS; + } + else if (hashCode == STANDARD_HASH) + { + return ShippingOption::STANDARD; + } + EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer(); + if(overflowContainer) + { + overflowContainer->StoreOverflow(hashCode, name); + return static_cast(hashCode); + } + + return ShippingOption::NOT_SET; + } + + Aws::String GetNameForShippingOption(ShippingOption enumValue) + { + switch(enumValue) + { + case ShippingOption::SECOND_DAY: + return "SECOND_DAY"; + case ShippingOption::NEXT_DAY: + return "NEXT_DAY"; + case ShippingOption::EXPRESS: + return "EXPRESS"; + case ShippingOption::STANDARD: + return "STANDARD"; + default: + EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer(); + if(overflowContainer) + { + return overflowContainer->RetrieveOverflow(static_cast(enumValue)); + } + + return {}; + } + } + + } // namespace ShippingOptionMapper + } // namespace Model + } // namespace Snowball +} // namespace Aws diff --git a/pool/shard004/C++/0048734_undirected.cpp b/pool/shard004/C++/0048734_undirected.cpp new file mode 100644 index 0000000000000000000000000000000000000000..49a7ed7d3d46516c68de6ccbe5e9a38fb81de116 --- /dev/null +++ b/pool/shard004/C++/0048734_undirected.cpp @@ -0,0 +1,109 @@ +//======================================================================= +// Copyright 2001 Jeremy G. Siek, Andrew Lumsdaine, Lie-Quan Lee, +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// http://www.boost.org/LICENSE_1_0.txt) +//======================================================================= +#include +#include +#include +using namespace boost; + +template < typename UndirectedGraph > void +undirected_graph_demo1() +{ + const int V = 3; + UndirectedGraph undigraph(V); + typename graph_traits < UndirectedGraph >::vertex_descriptor zero, one, two; + typename graph_traits < UndirectedGraph >::out_edge_iterator out, out_end; + typename graph_traits < UndirectedGraph >::in_edge_iterator in, in_end; + + zero = vertex(0, undigraph); + one = vertex(1, undigraph); + two = vertex(2, undigraph); + add_edge(zero, one, undigraph); + add_edge(zero, two, undigraph); + add_edge(one, two, undigraph); + + std::cout << "out_edges(0): "; + for (tie(out, out_end) = out_edges(zero, undigraph); out != out_end; ++out) + std::cout << *out; + std::cout << std::endl << "in_edges(0): "; + for (tie(in, in_end) = in_edges(zero, undigraph); in != in_end; ++in) + std::cout << *in; + std::cout << std::endl; +} + +template < typename DirectedGraph > void +directed_graph_demo() +{ + const int V = 2; + DirectedGraph digraph(V); + typename graph_traits < DirectedGraph >::vertex_descriptor u, v; + typedef typename DirectedGraph::edge_property_type Weight; + typename property_map < DirectedGraph, edge_weight_t >::type + weight = get(edge_weight, digraph); + typename graph_traits < DirectedGraph >::edge_descriptor e1, e2; + bool found; + + u = vertex(0, digraph); + v = vertex(1, digraph); + add_edge(u, v, Weight(1.2), digraph); + add_edge(v, u, Weight(2.4), digraph); + tie(e1, found) = edge(u, v, digraph); + tie(e2, found) = edge(v, u, digraph); + std::cout << "in a directed graph is "; +#ifdef __GNUC__ + // no boolalpha + std::cout << "(u,v) == (v,u) ? " << (e1 == e2) << std::endl; +#else + std::cout << "(u,v) == (v,u) ? " + << std::boolalpha << (e1 == e2) << std::endl; +#endif + std::cout << "weight[(u,v)] = " << get(weight, e1) << std::endl; + std::cout << "weight[(v,u)] = " << get(weight, e2) << std::endl; +} + +template < typename UndirectedGraph > void +undirected_graph_demo2() +{ + const int V = 2; + UndirectedGraph undigraph(V); + typename graph_traits < UndirectedGraph >::vertex_descriptor u, v; + typedef typename UndirectedGraph::edge_property_type Weight; + typename property_map < UndirectedGraph, edge_weight_t >::type + weight = get(edge_weight, undigraph); + typename graph_traits < UndirectedGraph >::edge_descriptor e1, e2; + bool found; + + u = vertex(0, undigraph); + v = vertex(1, undigraph); + add_edge(u, v, Weight(3.1), undigraph); + tie(e1, found) = edge(u, v, undigraph); + tie(e2, found) = edge(v, u, undigraph); + std::cout << "in an undirected graph is "; +#ifdef __GNUC__ + std::cout << "(u,v) == (v,u) ? " << (e1 == e2) << std::endl; +#else + std::cout << "(u,v) == (v,u) ? " + << std::boolalpha << (e1 == e2) << std::endl; +#endif + std::cout << "weight[(u,v)] = " << get(weight, e1) << std::endl; + std::cout << "weight[(v,u)] = " << get(weight, e2) << std::endl; +} + + +int +main() +{ + typedef property < edge_weight_t, double >Weight; + typedef adjacency_list < vecS, vecS, undirectedS, + no_property, Weight > UndirectedGraph; + typedef adjacency_list < vecS, vecS, directedS, + no_property, Weight > DirectedGraph; + undirected_graph_demo1 < UndirectedGraph > (); + undirected_graph_demo2 < UndirectedGraph > (); + directed_graph_demo < DirectedGraph > (); + return 0; +} diff --git a/pool/shard004/C++/0048738_test.cpp b/pool/shard004/C++/0048738_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..51eecd8857b4553fe0e54aabb58927bcd878f515 --- /dev/null +++ b/pool/shard004/C++/0048738_test.cpp @@ -0,0 +1,34 @@ +#include "hail/format.hpp" +#include "hail/test.hpp" + +namespace hail { + +Test::Test(std::string name, TestFunction *function) + : name(std::move(name)), function(function), next(Tests::head) { + Tests::head = this; +} + +int +Test::run() const { + format(errs, "RUN ", name, "\n"); + function(); + format(errs, "RUN ", name, " OK\n"); + return 0; +} + +Test *Tests::head = nullptr; + +int +Tests::run_tests() { + for (const Test *t = head; t; t = t->next) { + t->run(); + } + return 0; +} + +} + +int +main() { + hail::Tests::run_tests(); +} diff --git a/pool/shard004/C++/0048739_checkpoints.cpp b/pool/shard004/C++/0048739_checkpoints.cpp new file mode 100644 index 0000000000000000000000000000000000000000..6294b1593c5bdaa43bbd9a19b3a1caa5fd7befab --- /dev/null +++ b/pool/shard004/C++/0048739_checkpoints.cpp @@ -0,0 +1,66 @@ +// Copyright (c) 2009-2012 The Bitcoin developers +// Copyright (c) 2011-2012 Litecoin Developers +// Copyright (c) 2013 Feathercoin Developers + +// Distributed under the MIT/X11 software license, see the accompanying +// file COPYING or http://www.opensource.org/licenses/mit-license.php. + +#include // for 'map_list_of()' +#include + +#include "checkpoints.h" + +#include "main.h" +#include "uint256.h" + +namespace Checkpoints +{ + typedef std::map MapCheckpoints; + + // + // What makes a good checkpoint block? + // + Is surrounded by blocks with reasonable timestamps + // (no blocks before with a timestamp after, none after with + // timestamp before) + // + Contains no strange transactions + // + static MapCheckpoints mapCheckpoints = + boost::assign::map_list_of + ( 1, uint256("0xfdbe99b90c90bae7505796461471d89ae8388ab953997aa06a355bbda8d915cb")) + ( 22267, uint256("0x23dc7d871fc2a9b994112e978019f6370bab0b8979f557afe77a7ab620224b70")) + ( 22847, uint256("0x1450b80c150fee1e657ee8309819276342c021fab5e6a20ccf5407f5e2218d0f")) + ( 23453, uint256("0x7c25d3f9671e1d9400c9a1be2ff68e68db561ab85ae6b7020062d8d26da81e4c")) + ( 28230, uint256("0xd3feb71f92c63c682f994d7c615adc425226c669a83d46012b32fc8d518b08bb")) + ( 31846, uint256("0xba7d5c0e6d46f6448253290ce037e13975c13ca9c375ae854b6b2f85044fc0f9")) + ; + + + bool CheckBlock(int nHeight, const uint256& hash) + { + if (fTestNet) return true; // Testnet has no checkpoints + + MapCheckpoints::const_iterator i = mapCheckpoints.find(nHeight); + if (i == mapCheckpoints.end()) return true; + return hash == i->second; + } + + int GetTotalBlocksEstimate() + { + if (fTestNet) return 0; + return mapCheckpoints.rbegin()->first; + } + + CBlockIndex* GetLastCheckpoint(const std::map& mapBlockIndex) + { + if (fTestNet) return NULL; + + BOOST_REVERSE_FOREACH(const MapCheckpoints::value_type& i, mapCheckpoints) + { + const uint256& hash = i.second; + std::map::const_iterator t = mapBlockIndex.find(hash); + if (t != mapBlockIndex.end()) + return t->second; + } + return NULL; + } +} diff --git a/pool/shard004/C++/0048740_monotonic_clock.cc b/pool/shard004/C++/0048740_monotonic_clock.cc new file mode 100644 index 0000000000000000000000000000000000000000..3ca87af44753c77446be450f2f231680170cebd7 --- /dev/null +++ b/pool/shard004/C++/0048740_monotonic_clock.cc @@ -0,0 +1,42 @@ +// 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 "mojo/apps/js/bindings/monotonic_clock.h" + +#include "gin/object_template_builder.h" +#include "gin/per_isolate_data.h" +#include "gin/public/wrapper_info.h" +#include "mojo/public/system/core_cpp.h" + +namespace mojo { +namespace apps { + +namespace { + +gin::WrapperInfo g_wrapper_info = { gin::kEmbedderNativeGin }; + +double GetMonotonicSeconds() { + const double kMicrosecondsPerSecond = 1000000; + return static_cast(mojo::GetTimeTicksNow()) / kMicrosecondsPerSecond; +} + +} // namespace + +const char MonotonicClock::kModuleName[] = "monotonic_clock"; + +v8::Local MonotonicClock::GetModule(v8::Isolate* isolate) { + gin::PerIsolateData* data = gin::PerIsolateData::From(isolate); + v8::Local templ = + data->GetObjectTemplate(&g_wrapper_info); + if (templ.IsEmpty()) { + templ = gin::ObjectTemplateBuilder(isolate) + .SetMethod("seconds", GetMonotonicSeconds) + .Build(); + data->SetObjectTemplate(&g_wrapper_info, templ); + } + return templ->NewInstance(); +} + +} // namespace apps +} // namespace mojo diff --git a/pool/shard004/C++/0048755_callbacknepomukresourceretriever.cpp b/pool/shard004/C++/0048755_callbacknepomukresourceretriever.cpp new file mode 100644 index 0000000000000000000000000000000000000000..ae21ea107b221d3507bee5c98dd6f64103a7e331 --- /dev/null +++ b/pool/shard004/C++/0048755_callbacknepomukresourceretriever.cpp @@ -0,0 +1,51 @@ +/* + Copyright (c) 2011 Volker Krause + + This library is free software; you can redistribute it and/or modify it + under the terms of the GNU Library General Public License as published by + the Free Software Foundation; either version 2 of the License, or (at your + option) any later version. + + This library is distributed in the hope that it will be useful, but WITHOUT + ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public + License for more details. + + You should have received a copy of the GNU Library General Public License + along with this library; see the file COPYING.LIB. If not, write to the + Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA + 02110-1301, USA. +*/ + +#include "callbacknepomukresourceretriever.h" +#include + +using namespace MessageList; + +CallbackNepomukResourceRetriever::CallbackNepomukResourceRetriever(QObject* parent) + : AsyncNepomukResourceRetriever( QVector() << Soprano::Vocabulary::NAO::hasTag().toString() + << Soprano::Vocabulary::NAO::annotation().toString() + << Soprano::Vocabulary::NAO::description().toString(), parent ) +{ +} + +void CallbackNepomukResourceRetriever::requestResource(Core::MessageItemPrivate* item, const QUrl& url) +{ + m_pendingCallbacks.insert( url, item ); + AsyncNepomukResourceRetriever::requestResource( url ); +} + +void CallbackNepomukResourceRetriever::cancelCallbackRequest(const QUrl& url) +{ + m_pendingCallbacks.remove( url ); + AsyncNepomukResourceRetriever::cancelRequest( url ); +} + +void CallbackNepomukResourceRetriever::resourceAvailable(const QUrl& url, const Nepomuk2::Resource& resource) +{ + Core::MessageItemPrivate* item = m_pendingCallbacks.take( url ); + if ( item ) + item->resourceReceived( resource ); +} + +#include "callbacknepomukresourceretriever.moc" diff --git a/pool/shard004/C++/0048761_ComponentManager.cpp b/pool/shard004/C++/0048761_ComponentManager.cpp new file mode 100644 index 0000000000000000000000000000000000000000..be1f22022f4de56f02d541279bf4cd04738edb47 --- /dev/null +++ b/pool/shard004/C++/0048761_ComponentManager.cpp @@ -0,0 +1,55 @@ +/* + * Copyright (C) 2008-2014 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 "ComponentManager.h" +#include "DatabaseEnv.h" + +Battlenet::ComponentMgr::~ComponentMgr() +{ + for (Component* component : _components) + delete component; +} + +void Battlenet::ComponentMgr::Load() +{ + QueryResult result = LoginDatabase.Query("SELECT Program, Platform, Build FROM battlenet_components"); + if (result) + { + do + { + Field* fields = result->Fetch(); + Component* component = new Component(); + component->Program = fields[0].GetString(); + component->Platform = fields[1].GetString(); + component->Build = fields[2].GetUInt32(); + + _components.insert(component); + _programs.insert(component->Program); + _platforms.insert(component->Platform); + + } while (result->NextRow()); + } +} + +bool Battlenet::ComponentMgr::HasComponent(Battlenet::Component const* component) const +{ + for (Component const* c : _components) + if (component->Program == c->Program && component->Platform == c->Platform && component->Build == c->Build) + return true; + + return false; +} diff --git a/pool/shard004/C++/0048764_log.cpp b/pool/shard004/C++/0048764_log.cpp new file mode 100644 index 0000000000000000000000000000000000000000..5ac64d69535f0e6b9d70ba18e3ddcf7cff4170c6 --- /dev/null +++ b/pool/shard004/C++/0048764_log.cpp @@ -0,0 +1,168 @@ +/* + * Copyright (C) 2012 Carl Leonardsson + * + * This file is part of Memorax. + * + * Memorax is free software: you can 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. + * + * Memorax is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY + * or FITNESS FOR A PARTICULAR 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 "log.h" + +#include + +namespace Log{ + + std::ostream *primary_stream = &std::cout; + bool own_primary_stream = false; // True if Log has ownership of *primary_stream + std::ostream *secondary_stream = 0; + bool own_secondary_stream = false; // True if Log has ownership of *secondary_stream + std::ostream *tertiary_stream = 0; + bool own_tertiary_stream = false; // True if Log has ownership of *tertiary_stream + std::ostream *warning_stream = &std::cerr; + std::ostream *json_stream = 0; // By default, do not print json directives + std::ostream *null_stream = 0; + + class StreamLiberator{ + public: + StreamLiberator(std::ostream **os, bool *own) : os(os), own(own) {}; + ~StreamLiberator(){ + if(*own){ + delete *os; + } + }; + private: + std::ostream **os; + bool *own; + }; + + StreamLiberator sl_primary(&primary_stream,&own_primary_stream); + StreamLiberator sl_secondary(&secondary_stream,&own_secondary_stream); + StreamLiberator sl_tertiary(&tertiary_stream,&own_tertiary_stream); + + redirection_stream result(&primary_stream); + redirection_stream msg(&secondary_stream); + redirection_stream debug(&secondary_stream); + redirection_stream extreme(&secondary_stream); + redirection_stream warning(&warning_stream); + redirection_stream json(&json_stream); + redirection_stream null(&null_stream); + + void set_primary_stream(std::ostream *os){ + if(own_primary_stream){ + delete primary_stream; + own_primary_stream = false; + } + primary_stream = os; + }; + void set_secondary_stream(std::ostream *os){ + if(own_secondary_stream){ + delete secondary_stream; + own_secondary_stream = false; + } + secondary_stream = os; + }; + void set_tertiary_stream(std::ostream *os){ + if(own_tertiary_stream){ + delete tertiary_stream; + own_tertiary_stream = false; + } + tertiary_stream = os; + }; + void set_warning_stream(std::ostream *os){ + warning_stream = os; + }; + void set_json_stream(std::ostream *os){ + json_stream = os; + }; + + loglevel_t primary_loglevel = RESULTS; + loglevel_t secondary_loglevel = DEBUG; + + void update_redirections(){ + result.os = &tertiary_stream; + msg.os = &tertiary_stream; + debug.os = &tertiary_stream; + extreme.os = &tertiary_stream; + + switch(secondary_loglevel){ // Note that there should be no breaks in this switch + case EXTREME: extreme.os = &secondary_stream; + case DEBUG: debug.os = &secondary_stream; + case MSG: msg.os = &secondary_stream; + case RESULTS: result.os = &secondary_stream; + case SILENT: + break; + } + switch(primary_loglevel){ // Note that there should be no breaks in this switch + case EXTREME: extreme.os = &primary_stream; + case DEBUG: debug.os = &primary_stream; + case MSG: msg.os = &primary_stream; + case RESULTS: result.os = &primary_stream; + case SILENT: + break; + }; + }; + + loglevel_t get_primary_loglevel(){ + return primary_loglevel; + }; + void set_primary_loglevel(loglevel_t lv){ + primary_loglevel = lv; + update_redirections(); + }; + loglevel_t get_secondary_loglevel(){ + return secondary_loglevel; + }; + void set_secondary_loglevel(loglevel_t lv){ + secondary_loglevel = lv; + update_redirections(); + }; + + class clofstream : public std::ofstream{ + public: + clofstream(std::string filename) : std::ofstream(filename.c_str()) {}; + ~clofstream(){ + close(); + }; + }; + + bool set_stream_file(std::string filename, std::ostream **os, bool *own){ + if(*own){ + delete *os; + } + + *os = new clofstream(filename); + if(**os){ + *own = true; + return true; + }else{ + std::cerr << "wtf?\n"; + delete *os; + *os = 0; + *own = false; + return false; + } + } + + bool set_primary_stream_file(std::string filename){ + return set_stream_file(filename,&primary_stream,&own_primary_stream); + }; + bool set_secondary_stream_file(std::string filename){ + return set_stream_file(filename,&secondary_stream,&own_secondary_stream); + }; + bool set_tertiary_stream_file(std::string filename){ + return set_stream_file(filename,&tertiary_stream,&own_tertiary_stream); + }; + +}; diff --git a/pool/shard004/C++/0048767_RulePowLVTest.cpp b/pool/shard004/C++/0048767_RulePowLVTest.cpp new file mode 100644 index 0000000000000000000000000000000000000000..adbbdc9f8851c7b4ebe3a1d4c2021679f6e50a35 --- /dev/null +++ b/pool/shard004/C++/0048767_RulePowLVTest.cpp @@ -0,0 +1,97 @@ +/* Licensed to Oleg Tsemaylo under the MIT license. + * Refer to the LICENSE.txt file in the project root for more information. + */ + +/** + * @file RulePowLVTest.cpp + * + * Test cases for RulePowLV (left value of exponentation rule). + * + * @since 16.08.2017 + * @author agor + */ + +#include +#include + +#include "RulePowLV.h" +#include "Variable.h" +#include "Sum.h" +#include "Pow.h" +#include "Token.h" +#include "ExpressionFactory.h" + +class FX_RulePowLV : public testing::Test { +protected: + + virtual void SetUp() { + } + + virtual void TearDown() { + } + + Token lookAheadToken() const { + return Token("NA", TNoToken); + } + + Token lookAheadToken(string value, TokenType type) const { + return Token(value, type); + } +}; + +TEST_F(FX_RulePowLV, apply_LeftValueOfExponentation_Reducable) { + + ParserStack stack; + stack.push_back(createVariable("a")); + stack.push_back(createPow()); + + RulePowLV rulePowLV; + EXPECT_TRUE(rulePowLV.apply(stack, lookAheadToken())); + + ParserStack::const_iterator i = stack.begin(); + + PPow pow = SPointerCast(*i); + EXPECT_TRUE(isTypeOf(pow)); + + PVariable powLArg = SPointerCast(pow->lArg); + EXPECT_TRUE(isTypeOf(powLArg)); + EXPECT_STREQ("a", powLArg->name.c_str()); +} + +TEST_F(FX_RulePowLV, apply_RuleIsNotAppliable_NotReducable) { + ParserStack stack; + + stack.push_back(createPow()); + stack.push_back(createVariable("a")); + + RulePowLV rulePowLV; + EXPECT_FALSE(rulePowLV.apply(stack, lookAheadToken())); + + ParserStack::const_iterator i = stack.begin(); + EXPECT_TRUE(isTypeOf(*i)); + ++i; + EXPECT_TRUE(isTypeOf(*i)); +} + +TEST_F(FX_RulePowLV, apply_ExponentationOperationIsAlreadyComplete_NotReducable) { + ParserStack stack; + + // a(b^c) + stack.push_back(createVariable("a")); + stack.push_back(createPow(createVariable("b"), createVariable("c"))); + + RulePowLV rulePowLV; + EXPECT_FALSE(rulePowLV.apply(stack, lookAheadToken())); +} + +TEST_F(FX_RulePowLV, apply_LeftHandArgumentIsNotComplete_NotReducable) { + ParserStack stack; + + // +a^b + stack.push_back(createSum(nullptr, createVariable("a"))); + stack.push_back(createPow()); + stack.push_back(createVariable("b")); + + RulePowLV rulePowLV; + EXPECT_FALSE(rulePowLV.apply(stack, lookAheadToken("b", TAlphaNumeric))); +} diff --git a/pool/shard004/C++/0048768_code.cpp b/pool/shard004/C++/0048768_code.cpp new file mode 100644 index 0000000000000000000000000000000000000000..855a9e88601d15d841fe26c3af1cdb0a82f92a05 --- /dev/null +++ b/pool/shard004/C++/0048768_code.cpp @@ -0,0 +1,103 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include + +using namespace std; + +#define uint unsigned int +#define FIND(Q, q) (Q.find(q) != Q.end()) +#define foreach(Q, it) for(auto it = (Q).begin(); it != (Q).end(); ++it) + +struct Edge { + uint x, y, c; + + Edge(uint x, uint y) : Edge(x, y, 0) {} + Edge(uint x, uint y, uint c) : x(x), y(y), c(c) {} + + bool operator<(const Edge& b) const { + return c < b.c; + } + bool operator()(const Edge& a, const Edge& b) const { + return a.c < b.c; + } +}; + +int BFS(const vector< vector< Edge* > >& G, int src, int dst) { + deque< pair< int, int > > Q; + int *lbl = new int[G.size()]; + memset(lbl, 0, sizeof(int)* G.size()); + + if(src == dst) + return 0; + + Q.push_back(make_pair(src, 0)); + + while(!Q.empty()) { + auto q = Q.front(); + + foreach(G[q.first], neighbor) + { + Edge *e = *neighbor; + if (lbl[e->y] == 0) + { + lbl[e->y]++; + if (e->y == dst) + return q.second + 1; + Q.push_back(make_pair(e->y, q.second + 1)); + } + } + + Q.pop_front(); + } + + return -1; +} + +void graph_insert(vector< vector< Edge* > >& G, int x, int y) +{ + G[x].push_back(new Edge(x, y)); +} + +int main() { + uint N, A, B, C, D, P, x0, y0, x1, y1; + int res; + vector< vector< Edge* > > G; + + while(cin >> N && N != 0) { + G.clear(); + G.resize(N * N); + + for(int y = N-1; y >= 0; --y) { + for(int x = 0; x < N; ++x) { + cin >> A >> B >> C >> D; + if (A) + graph_insert(G, N * y + x, N * (y + 1) + x); + if (B) + graph_insert(G, N * y + x, N * (y - 1) + x); + if (C) + graph_insert(G, N * y + x, N * y + (x - 1)); + if (D) + graph_insert(G, N * y + x, N * y + (x + 1)); + } + } + + cin >> P; + for (uint i = 0; i < P; ++i) + { + cin >> x0 >> y0 >> x1 >> y1; + res = BFS(G, y0 * N + x0, y1 * N + x1); + + if (res == -1) + cout << "Impossible" << endl; + else + cout << res << endl; + } + cout << endl; + } +} diff --git a/pool/shard004/C++/0048780_StatusDetailFilters.cpp b/pool/shard004/C++/0048780_StatusDetailFilters.cpp new file mode 100644 index 0000000000000000000000000000000000000000..9284fd1374b2afcbeeef81a77471a7afdfcd25c8 --- /dev/null +++ b/pool/shard004/C++/0048780_StatusDetailFilters.cpp @@ -0,0 +1,85 @@ +/* +* Copyright 2010-2017 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 +#include + +#include + +using namespace Aws::Utils::Json; +using namespace Aws::Utils; + +namespace Aws +{ +namespace ConfigService +{ +namespace Model +{ + +StatusDetailFilters::StatusDetailFilters() : + m_accountIdHasBeenSet(false), + m_memberAccountRuleStatus(MemberAccountRuleStatus::NOT_SET), + m_memberAccountRuleStatusHasBeenSet(false) +{ +} + +StatusDetailFilters::StatusDetailFilters(JsonView jsonValue) : + m_accountIdHasBeenSet(false), + m_memberAccountRuleStatus(MemberAccountRuleStatus::NOT_SET), + m_memberAccountRuleStatusHasBeenSet(false) +{ + *this = jsonValue; +} + +StatusDetailFilters& StatusDetailFilters::operator =(JsonView jsonValue) +{ + if(jsonValue.ValueExists("AccountId")) + { + m_accountId = jsonValue.GetString("AccountId"); + + m_accountIdHasBeenSet = true; + } + + if(jsonValue.ValueExists("MemberAccountRuleStatus")) + { + m_memberAccountRuleStatus = MemberAccountRuleStatusMapper::GetMemberAccountRuleStatusForName(jsonValue.GetString("MemberAccountRuleStatus")); + + m_memberAccountRuleStatusHasBeenSet = true; + } + + return *this; +} + +JsonValue StatusDetailFilters::Jsonize() const +{ + JsonValue payload; + + if(m_accountIdHasBeenSet) + { + payload.WithString("AccountId", m_accountId); + + } + + if(m_memberAccountRuleStatusHasBeenSet) + { + payload.WithString("MemberAccountRuleStatus", MemberAccountRuleStatusMapper::GetNameForMemberAccountRuleStatus(m_memberAccountRuleStatus)); + } + + return payload; +} + +} // namespace Model +} // namespace ConfigService +} // namespace Aws diff --git a/pool/shard004/C++/0048783_filtermodel.cpp b/pool/shard004/C++/0048783_filtermodel.cpp new file mode 100644 index 0000000000000000000000000000000000000000..9b28cb0c7fb8dd6f3d799955bb8f066d69c0a87a --- /dev/null +++ b/pool/shard004/C++/0048783_filtermodel.cpp @@ -0,0 +1,107 @@ +/* + Copyright (c) 2010 Klarälvdalens Datakonsult AB, a KDAB Group company, info@kdab.com + Copyright (c) 2010 Andras Mantia + + 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 "filtermodel_p.h" +#include "filtermanager.h" +#include "mailfilter.h" + +using namespace MailCommon; + +FilterModel::FilterModel( QObject *parent ) + : QAbstractListModel( parent ) +{ + connect( FilterManager::instance(), SIGNAL(filtersChanged()), + this, SLOT(filterListUpdated()) ); +} + +QVariant FilterModel::data( const QModelIndex &index, int role ) const +{ + if ( role == Qt::DisplayRole ) { + return FilterManager::instance()->filters().at( index.row() )->name(); + } + + return QVariant(); +} + +int FilterModel::rowCount( const QModelIndex & ) const +{ + return FilterManager::instance()->filters().size(); +} + +void FilterModel::moveRow( int sourceRow, int destinationRow ) +{ + if ( sourceRow == destinationRow ) { + return; + } + + if ( sourceRow < 0 || sourceRow >= rowCount() ) { + return; + } + + if ( destinationRow < 0 || destinationRow >= rowCount() ) { + return; + } + + QList filters; + + foreach ( MailFilter *filter, FilterManager::instance()->filters() ) { + filters.append( new MailFilter( *filter ) ); // deep copy + } + + filters.move( sourceRow, destinationRow ); + FilterManager::instance()->setFilters( filters ); + + reset(); +} + +bool FilterModel::insertRows( int row, int count, const QModelIndex &parent ) +{ + beginInsertRows( parent, row, row + count - 1 ); + for ( int i = 0; i < count; ++i ) { + MailFilter *filter = new MailFilter(); + FilterManager::instance()->appendFilters( QList () << filter ); + } + endInsertRows(); + + return true; +} + +bool FilterModel::removeRows( int row, int count, const QModelIndex &parent ) +{ + const QList filters = FilterManager::instance()->filters(); + + beginRemoveRows( parent, row, row + count - 1 ); + for ( int i = 0; i < count; ++i ) { + MailFilter *filter = filters.at( row ); + FilterManager::instance()->removeFilter( filter ); + delete filter; + } + endRemoveRows(); + + return true; +} + +void FilterModel::filterListUpdated() +{ + // Since the FilterManager doesn't tell use which filter has been + // updated, we emit dataChanged() for all of them + emit dataChanged( index( 0, 0 ), index( rowCount() - 1, 0 ) ); +} + +#include "moc_filtermodel_p.cpp" diff --git a/pool/shard004/C++/0048793_sail_settings.cpp b/pool/shard004/C++/0048793_sail_settings.cpp new file mode 100644 index 0000000000000000000000000000000000000000..efc859aa57bce13183418d4f93cb5d006ae23034 --- /dev/null +++ b/pool/shard004/C++/0048793_sail_settings.cpp @@ -0,0 +1,40 @@ +/***************************************************************** + * $Id: sail_settings.cpp 0000 rutger $ + * Created: Dec 15, 2016 19:42:36 PM - rutger + * + * Copyright (C) 2016 Red-Bag. All rights reserved. + * This file is part of the Biluna SAIL project. + * + * See http://www.red-bag.com for further details. + *****************************************************************/ + +#include "sail_settings.h" + +#include "rb_debug.h" +#include "sail_utilityfactory.h" + +SAIL_Settings* SAIL_Settings::mActiveUtility = nullptr; + + +SAIL_Settings::SAIL_Settings() { + RB_DEBUG->print("SAIL_Settings::SAIL_Settings()"); + mUtilityFactory = SAIL_UTILITYFACTORY; + mUtilityFactory->addUtility(this); +} + +SAIL_Settings::~SAIL_Settings() { + mUtilityFactory->removeUtility(this); + mActiveUtility = nullptr; + RB_DEBUG->print("SAIL_Settings::~SAIL_Settings() OK"); +} + +SAIL_Settings* SAIL_Settings::getInstance() { + if (!mActiveUtility) { + mActiveUtility = new SAIL_Settings(); + } + return mActiveUtility; +} + +void SAIL_Settings::refresh() { + // nothing yet +} diff --git a/pool/shard004/C++/0048797_Game.cpp b/pool/shard004/C++/0048797_Game.cpp new file mode 100644 index 0000000000000000000000000000000000000000..fcb8cbf2b26f21f0da793bc366dceb679f8419b7 --- /dev/null +++ b/pool/shard004/C++/0048797_Game.cpp @@ -0,0 +1,45 @@ +#include "Game.hpp" +#include "Resources.hpp" + +#include + +// Testing + +Game::Game(int scrwidth, int scrheight, std::string title, int style) : + window(sf::VideoMode(scrwidth, scrheight), title, style), + inputManager(&window) +{ + Resources::load(); +} + +Game::~Game(){} + +/* + Game main loop +*/ +void Game::run() { + sf::Clock c; + srand(time(0)); + + while (window.isOpen()) { + float deltaTime = c.restart().asSeconds(); + + processEvents(); + update(deltaTime); + render(); + } +} + +void Game::render() { + window.clear(); + draw(); + window.display(); +} + +InputManager* Game::getInputManager() { + return &inputManager; +} + +sf::RenderWindow* Game::getWindow() { + return &window; +} diff --git a/pool/shard004/C++/0048800_window_positioning_utils_unittest.cc b/pool/shard004/C++/0048800_window_positioning_utils_unittest.cc new file mode 100644 index 0000000000000000000000000000000000000000..682ed7603db89f2f15d5beb50a244cab17a2b8d6 --- /dev/null +++ b/pool/shard004/C++/0048800_window_positioning_utils_unittest.cc @@ -0,0 +1,62 @@ +// Copyright 2019 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "ash/wm/window_positioning_utils.h" + +#include "ash/test/ash_test_base.h" +#include "ui/aura/test/test_window_delegate.h" +#include "ui/aura/window.h" + +namespace ash { + +using WindowPositioningUtilsTest = AshTestBase; + +TEST_F(WindowPositioningUtilsTest, SnapBoundsWithOddNumberedScreenWidth) { + UpdateDisplay("999x700"); + + auto window = CreateToplevelTestWindow(); + gfx::Rect left_bounds = + GetDefaultLeftSnappedWindowBoundsInParent(window.get()); + gfx::Rect right_bounds = + GetDefaultRightSnappedWindowBoundsInParent(window.get()); + EXPECT_EQ(left_bounds.x(), 0); + EXPECT_EQ(left_bounds.y(), 0); + EXPECT_EQ(right_bounds.right(), 999); + EXPECT_EQ(right_bounds.y(), 0); + EXPECT_EQ(left_bounds.right(), right_bounds.x()); + EXPECT_NEAR(left_bounds.width(), 499, 1); + EXPECT_NEAR(right_bounds.width(), 499, 1); +} + +TEST_F(WindowPositioningUtilsTest, SnapBoundsWithMinimumSize) { + UpdateDisplay("800x600"); + + auto window = CreateToplevelTestWindow(); + auto* test_delegate = + static_cast(window->delegate()); + test_delegate->set_minimum_size(gfx::Size(300, 200)); + gfx::Rect left_bounds = + GetDefaultLeftSnappedWindowBoundsInParent(window.get()); + EXPECT_EQ(left_bounds.width(), 400); + gfx::Rect right_bounds = + GetDefaultRightSnappedWindowBoundsInParent(window.get()); + EXPECT_EQ(right_bounds.width(), 400); + EXPECT_EQ(right_bounds.right(), 800); + + test_delegate->set_minimum_size(gfx::Size(600, 200)); + left_bounds = GetDefaultLeftSnappedWindowBoundsInParent(window.get()); + EXPECT_EQ(left_bounds.width(), 600); + right_bounds = GetDefaultRightSnappedWindowBoundsInParent(window.get()); + EXPECT_EQ(right_bounds.width(), 600); + EXPECT_EQ(right_bounds.right(), 800); + + test_delegate->set_minimum_size(gfx::Size(1200, 200)); + left_bounds = GetDefaultLeftSnappedWindowBoundsInParent(window.get()); + EXPECT_EQ(left_bounds.width(), 800); + right_bounds = GetDefaultRightSnappedWindowBoundsInParent(window.get()); + EXPECT_EQ(right_bounds.width(), 800); + EXPECT_EQ(right_bounds.right(), 800); +} + +} // namespace ash diff --git a/pool/shard004/C++/0048804_Laser.cpp b/pool/shard004/C++/0048804_Laser.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b2354236ea03f96aac843aa398f66525b579d1ec --- /dev/null +++ b/pool/shard004/C++/0048804_Laser.cpp @@ -0,0 +1,64 @@ +using namespace std; +#include +#include +#include +#include "Mob.h" +#include "Bullet.h" + +GLUquadricObj *quadratic; + +Bullet::Bullet() {} + +Bullet::~Bullet() { gluDeleteQuadric(quadratic); } + +bool Bullet::init() +{ + /*glPushMatrix(); + glLoadIdentity(); + glGetFloatv(GL_MODELVIEW_MATRIX, transforms); + glPopMatrix();*/ + quadratic=gluNewQuadric(); + gluQuadricNormals(quadratic, GLU_SMOOTH); + //gluQuadricTexture(quadratic, GL_TRUE); + loadMatrix(); + glLoadIdentity(); + saveMatrix(); + velocity.z = -10.0;//20.0*((float) random() / RAND_MAX)-1.0; + return true; +} + +void Bullet::draw() +{ + glPushMatrix(); + //loadMatrix(); + glTranslatef(pos.x(), pos.y(), pos.z()); + gluSphere(quadratic,0.2f,16,16); + glPopMatrix(); +} + +void Bullet::update(float dt) +{ + loadMatrix(); + translate(0.0, 0.0, dt*velocity.z); + saveMatrix(); +} +/*void Bullet::rotate(GLfloat angle, GLfloat dx, GLfloat dy, GLfloat dz) +{ + loadMatrix(); + glRotatef(angle, dx, dy, dz); + saveMatrix(); +}*/ + +/*void Bullet::translate(GLfloat dp, GLfloat daz, GLfloat dh) +{ + loadMatrix(); + glTranslatef(dx, dy, dz); + saveMatrix(); +}*/ +/* +void Cube::scale(GLfloat sx, GLfloat sy, GLfloat sz) +{ + loadMatrix(); + glScalef(sx, sy, sz); + saveMatrix(); +}*/ diff --git a/pool/shard004/C++/0048815_x509_certificate_net_log_param.cc b/pool/shard004/C++/0048815_x509_certificate_net_log_param.cc new file mode 100644 index 0000000000000000000000000000000000000000..3c52b96dc076b4f97404b2e6c898d4c1354ca697 --- /dev/null +++ b/pool/shard004/C++/0048815_x509_certificate_net_log_param.cc @@ -0,0 +1,27 @@ +// Copyright (c) 2012 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "net/cert/x509_certificate_net_log_param.h" + +#include +#include + +#include "base/values.h" +#include "net/cert/x509_certificate.h" + +namespace net { + +base::Value* NetLogX509CertificateCallback(const X509Certificate* certificate, + NetLog::LogLevel log_level) { + base::DictionaryValue* dict = new base::DictionaryValue(); + base::ListValue* certs = new base::ListValue(); + std::vector encoded_chain; + certificate->GetPEMEncodedChain(&encoded_chain); + for (size_t i = 0; i < encoded_chain.size(); ++i) + certs->Append(new base::StringValue(encoded_chain[i])); + dict->Set("certificates", certs); + return dict; +} + +} // namespace net diff --git a/pool/shard004/C++/0048816_SVGLength.cpp b/pool/shard004/C++/0048816_SVGLength.cpp new file mode 100644 index 0000000000000000000000000000000000000000..60de422d9c2964bd3bf75fd2f3981223f89037eb --- /dev/null +++ b/pool/shard004/C++/0048816_SVGLength.cpp @@ -0,0 +1,268 @@ +/* + * Copyright (C) 2004, 2005, 2006 Nikolas Zimmermann + * Copyright (C) 2004, 2005, 2006, 2007 Rob Buis + * Copyright (C) 2007 Apple Inc. All rights reserved. + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Library General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Library General Public License for more details. + * + * You should have received a copy of the GNU Library General Public License + * along with this library; see the file COPYING.LIB. If not, write to + * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + * Boston, MA 02110-1301, USA. + */ + +#include "core/svg/SVGLength.h" + +#include "core/SVGNames.h" +#include "core/css/CSSPrimitiveValue.h" +#include "core/css/CSSValue.h" +#include "core/css/CSSValuePool.h" +#include "core/css/parser/CSSParser.h" +#include "core/svg/SVGAnimationElement.h" +#include "wtf/MathExtras.h" +#include "wtf/text/WTFString.h" + +namespace blink { + +SVGLength::SVGLength(SVGLengthMode mode) + : SVGPropertyBase(classType()) + , m_value(cssValuePool().createValue(0, CSSPrimitiveValue::UnitType::UserUnits)) + , m_unitMode(static_cast(mode)) +{ + ASSERT(unitMode() == mode); +} + +SVGLength::SVGLength(const SVGLength& o) + : SVGPropertyBase(classType()) + , m_value(o.m_value) + , m_unitMode(o.m_unitMode) +{ +} + +DEFINE_TRACE(SVGLength) +{ + visitor->trace(m_value); + SVGPropertyBase::trace(visitor); +} + +SVGLength* SVGLength::clone() const +{ + return new SVGLength(*this); +} + +SVGPropertyBase* SVGLength::cloneForAnimation(const String& value) const +{ + SVGLength* length = create(); + length->m_unitMode = m_unitMode; + + if (length->setValueAsString(value) != SVGParseStatus::NoError) + length->m_value = cssValuePool().createValue(0, CSSPrimitiveValue::UnitType::UserUnits); + + return length; +} + +bool SVGLength::operator==(const SVGLength& other) const +{ + return m_unitMode == other.m_unitMode && m_value == other.m_value; +} + +float SVGLength::value(const SVGLengthContext& context) const +{ + return context.convertValueToUserUnits( + m_value->getFloatValue(), unitMode(), m_value->typeWithCalcResolved()); +} + +void SVGLength::setValue(float value, const SVGLengthContext& context) +{ + m_value = CSSPrimitiveValue::create( + context.convertValueFromUserUnits(value, unitMode(), m_value->typeWithCalcResolved()), + m_value->typeWithCalcResolved()); +} + +bool isSupportedCSSUnitType(CSSPrimitiveValue::UnitType type) +{ + return (CSSPrimitiveValue::isLength(type) || type == CSSPrimitiveValue::UnitType::Number || type == CSSPrimitiveValue::UnitType::Percentage) + && type != CSSPrimitiveValue::UnitType::QuirkyEms; +} + +void SVGLength::setUnitType(CSSPrimitiveValue::UnitType type) +{ + ASSERT(isSupportedCSSUnitType(type)); + m_value = CSSPrimitiveValue::create(m_value->getFloatValue(), type); +} + +float SVGLength::valueAsPercentage() const +{ + // LengthTypePercentage is represented with 100% = 100.0. Good for accuracy but could eventually be changed. + if (m_value->isPercentage()) { + // Note: This division is a source of floating point inaccuracy. + return m_value->getFloatValue() / 100; + } + + return m_value->getFloatValue(); +} + +float SVGLength::valueAsPercentage100() const +{ + // LengthTypePercentage is represented with 100% = 100.0. Good for accuracy but could eventually be changed. + if (m_value->isPercentage()) + return m_value->getFloatValue(); + + return m_value->getFloatValue() * 100; +} + +float SVGLength::scaleByPercentage(float input) const +{ + float result = input * m_value->getFloatValue(); + if (m_value->isPercentage()) { + // Delaying division by 100 as long as possible since it introduces floating point errors. + result = result / 100; + } + return result; +} + +SVGParsingError SVGLength::setValueAsString(const String& string) +{ + if (string.isEmpty()) { + m_value = cssValuePool().createValue(0, CSSPrimitiveValue::UnitType::UserUnits); + return SVGParseStatus::NoError; + } + + CSSParserContext svgParserContext(SVGAttributeMode, 0); + CSSValue* parsed = CSSParser::parseSingleValue(CSSPropertyX, string, svgParserContext); + if (!parsed || !parsed->isPrimitiveValue()) + return SVGParseStatus::ExpectedLength; + + CSSPrimitiveValue* newValue = toCSSPrimitiveValue(parsed); + // TODO(fs): Enable calc for SVG lengths + if (newValue->isCalculated() || !isSupportedCSSUnitType(newValue->typeWithCalcResolved())) + return SVGParseStatus::ExpectedLength; + + m_value = newValue; + return SVGParseStatus::NoError; +} + +String SVGLength::valueAsString() const +{ + return m_value->customCSSText(); +} + +void SVGLength::newValueSpecifiedUnits(CSSPrimitiveValue::UnitType type, float value) +{ + m_value = CSSPrimitiveValue::create(value, type); +} + +void SVGLength::convertToSpecifiedUnits(CSSPrimitiveValue::UnitType type, const SVGLengthContext& context) +{ + ASSERT(isSupportedCSSUnitType(type)); + + float valueInUserUnits = value(context); + m_value = CSSPrimitiveValue::create( + context.convertValueFromUserUnits(valueInUserUnits, unitMode(), type), + type); +} + +SVGLengthMode SVGLength::lengthModeForAnimatedLengthAttribute(const QualifiedName& attrName) +{ + typedef HashMap LengthModeForLengthAttributeMap; + DEFINE_STATIC_LOCAL(LengthModeForLengthAttributeMap, s_lengthModeMap, ()); + + if (s_lengthModeMap.isEmpty()) { + s_lengthModeMap.set(SVGNames::xAttr, SVGLengthMode::Width); + s_lengthModeMap.set(SVGNames::yAttr, SVGLengthMode::Height); + s_lengthModeMap.set(SVGNames::cxAttr, SVGLengthMode::Width); + s_lengthModeMap.set(SVGNames::cyAttr, SVGLengthMode::Height); + s_lengthModeMap.set(SVGNames::dxAttr, SVGLengthMode::Width); + s_lengthModeMap.set(SVGNames::dyAttr, SVGLengthMode::Height); + s_lengthModeMap.set(SVGNames::frAttr, SVGLengthMode::Other); + s_lengthModeMap.set(SVGNames::fxAttr, SVGLengthMode::Width); + s_lengthModeMap.set(SVGNames::fyAttr, SVGLengthMode::Height); + s_lengthModeMap.set(SVGNames::rAttr, SVGLengthMode::Other); + s_lengthModeMap.set(SVGNames::rxAttr, SVGLengthMode::Width); + s_lengthModeMap.set(SVGNames::ryAttr, SVGLengthMode::Height); + s_lengthModeMap.set(SVGNames::widthAttr, SVGLengthMode::Width); + s_lengthModeMap.set(SVGNames::heightAttr, SVGLengthMode::Height); + s_lengthModeMap.set(SVGNames::x1Attr, SVGLengthMode::Width); + s_lengthModeMap.set(SVGNames::x2Attr, SVGLengthMode::Width); + s_lengthModeMap.set(SVGNames::y1Attr, SVGLengthMode::Height); + s_lengthModeMap.set(SVGNames::y2Attr, SVGLengthMode::Height); + s_lengthModeMap.set(SVGNames::refXAttr, SVGLengthMode::Width); + s_lengthModeMap.set(SVGNames::refYAttr, SVGLengthMode::Height); + s_lengthModeMap.set(SVGNames::markerWidthAttr, SVGLengthMode::Width); + s_lengthModeMap.set(SVGNames::markerHeightAttr, SVGLengthMode::Height); + s_lengthModeMap.set(SVGNames::textLengthAttr, SVGLengthMode::Width); + s_lengthModeMap.set(SVGNames::startOffsetAttr, SVGLengthMode::Width); + } + + if (s_lengthModeMap.contains(attrName)) + return s_lengthModeMap.get(attrName); + + return SVGLengthMode::Other; +} + +bool SVGLength::negativeValuesForbiddenForAnimatedLengthAttribute(const QualifiedName& attrName) +{ + DEFINE_STATIC_LOCAL(HashSet, s_noNegativeValuesSet, ()); + + if (s_noNegativeValuesSet.isEmpty()) { + s_noNegativeValuesSet.add(SVGNames::frAttr); + s_noNegativeValuesSet.add(SVGNames::rAttr); + s_noNegativeValuesSet.add(SVGNames::rxAttr); + s_noNegativeValuesSet.add(SVGNames::ryAttr); + s_noNegativeValuesSet.add(SVGNames::widthAttr); + s_noNegativeValuesSet.add(SVGNames::heightAttr); + s_noNegativeValuesSet.add(SVGNames::markerWidthAttr); + s_noNegativeValuesSet.add(SVGNames::markerHeightAttr); + s_noNegativeValuesSet.add(SVGNames::textLengthAttr); + } + + return s_noNegativeValuesSet.contains(attrName); +} + +void SVGLength::add(SVGPropertyBase* other, SVGElement* contextElement) +{ + SVGLengthContext lengthContext(contextElement); + setValue(value(lengthContext) + toSVGLength(other)->value(lengthContext), lengthContext); +} + +void SVGLength::calculateAnimatedValue(SVGAnimationElement* animationElement, + float percentage, + unsigned repeatCount, + SVGPropertyBase* fromValue, + SVGPropertyBase* toValue, + SVGPropertyBase* toAtEndOfDurationValue, + SVGElement* contextElement) +{ + SVGLength* fromLength = toSVGLength(fromValue); + SVGLength* toLength = toSVGLength(toValue); + SVGLength* toAtEndOfDurationLength = toSVGLength(toAtEndOfDurationValue); + + SVGLengthContext lengthContext(contextElement); + float animatedNumber = value(lengthContext); + animationElement->animateAdditiveNumber(percentage, repeatCount, fromLength->value(lengthContext), + toLength->value(lengthContext), toAtEndOfDurationLength->value(lengthContext), animatedNumber); + + ASSERT(unitMode() == lengthModeForAnimatedLengthAttribute(animationElement->attributeName())); + + CSSPrimitiveValue::UnitType newUnit = percentage < 0.5 ? fromLength->typeWithCalcResolved() : toLength->typeWithCalcResolved(); + animatedNumber = lengthContext.convertValueFromUserUnits(animatedNumber, unitMode(), newUnit); + m_value = CSSPrimitiveValue::create(animatedNumber, newUnit); +} + +float SVGLength::calculateDistance(SVGPropertyBase* toValue, SVGElement* contextElement) +{ + SVGLengthContext lengthContext(contextElement); + SVGLength* toLength = toSVGLength(toValue); + + return fabsf(toLength->value(lengthContext) - value(lengthContext)); +} + +} // namespace blink diff --git a/pool/shard004/C++/0048830_divide_in_z_p.cpp b/pool/shard004/C++/0048830_divide_in_z_p.cpp new file mode 100644 index 0000000000000000000000000000000000000000..476558699acfda605ae2140e2d09e194eea694aa --- /dev/null +++ b/pool/shard004/C++/0048830_divide_in_z_p.cpp @@ -0,0 +1,112 @@ +/** @file divide_in_z_p.cpp + * + * Implementation of polynomial division in Z/Zp. */ + +/* + * GiNaC Copyright (C) 1999-2009 Johannes Gutenberg University Mainz, Germany + * + * 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 "add.h" +#include "operators.h" +#include "power.h" +#include "smod_helpers.h" + +namespace GiNaC { + +/** + * Exact polynomial division of a, b \in Z_p[x_0, \ldots, x_n] + * It doesn't check whether the inputs are proper polynomials, so be careful + * of what you pass in. + * + * @param a first multivariate polynomial (dividend) + * @param b second multivariate polynomial (divisor) + * @param q quotient (returned) + * @param var variables X iterator to first element of vector of symbols + * + * @return "true" when exact division succeeds (the quotient is returned in + * q), "false" otherwise. + * @note @a p = 0 means the base ring is Z + */ +bool divide_in_z_p(const ex &a, const ex &b, ex &q, const exvector& vars, const long p) +{ + static const ex _ex1(1); + if (b.is_zero()) + throw(std::overflow_error("divide_in_z: division by zero")); + if (b.is_equal(_ex1)) { + q = a; + return true; + } + if (is_exactly_a(a)) { + if (is_exactly_a(b)) { + // p == 0 means division in Z + if (p == 0) { + const numeric tmp = ex_to(a/b); + if (tmp.is_integer()) { + q = tmp; + return true; + } else + return false; + } else { + q = (a*recip(ex_to(b), p)).smod(numeric(p)); + return true; + } + } else + return false; + } + if (a.is_equal(b)) { + q = _ex1; + return true; + } + + // Main symbol + const ex &x = vars.back(); + + // Compare degrees + int adeg = a.degree(x), bdeg = b.degree(x); + if (bdeg > adeg) + return false; + + // Polynomial long division (recursive) + ex r = a.expand(); + if (r.is_zero()) + return true; + int rdeg = adeg; + ex eb = b.expand(); + ex blcoeff = eb.coeff(x, bdeg); + exvector v; + v.reserve(std::max(rdeg - bdeg + 1, 0)); + exvector rest_vars(vars); + rest_vars.pop_back(); + while (rdeg >= bdeg) { + ex term, rcoeff = r.coeff(x, rdeg); + if (!divide_in_z_p(rcoeff, blcoeff, term, rest_vars, p)) + break; + term = (term*power(x, rdeg - bdeg)).expand(); + v.push_back(term); + r = (r - term*eb).expand(); + if (p != 0) + r = r.smod(numeric(p)); + if (r.is_zero()) { + q = (new add(v))->setflag(status_flags::dynallocated); + return true; + } + rdeg = r.degree(x); + } + return false; +} + +} // namespace GiNaC diff --git a/pool/shard004/C++/0048835_root.MainView.Fuse_Translation_float_X_Property.cpp b/pool/shard004/C++/0048835_root.MainView.Fuse_Translation_float_X_Property.cpp new file mode 100644 index 0000000000000000000000000000000000000000..21afe64a2bf92504e857b3e4e4b0c2fbc4b28509 --- /dev/null +++ b/pool/shard004/C++/0048835_root.MainView.Fuse_Translation_float_X_Property.cpp @@ -0,0 +1,75 @@ +// This file was generated based on 'C:\Users\Kuro\Documents\Fuse\Welcome\.build\Simulator\Android\Cache\GeneratedCode\MainView.g.uno'. +// WARNING: Changes might be lost if you edit this file directly. + +#include <_root.MainView.Fuse_Translation_float_X_Property.h> +#include +#include +static uType* TYPES[1]; + +namespace g{ + +// public sealed class MainView.Fuse_Translation_float_X_Property :125 +// { +::g::Uno::UX::Property_type* MainView__Fuse_Translation_float_X_Property_typeof() +{ + static uSStrong< ::g::Uno::UX::Property_type*> type; + if (type != NULL) return type; + + uTypeOptions options; + options.FieldCount = 3; + options.ObjectSize = sizeof(MainView__Fuse_Translation_float_X_Property); + options.TypeSize = sizeof(::g::Uno::UX::Property_type); + type = (::g::Uno::UX::Property_type*)uClassType::New("MainView.Fuse_Translation_float_X_Property", options); + type->SetBase(::g::Uno::UX::Property_typeof()->MakeType(::g::Uno::Float_typeof())); + type->fp_OnGet = (void(*)(::g::Uno::UX::Property*, uTRef))MainView__Fuse_Translation_float_X_Property__OnGet_fn; + type->fp_OnSet = (void(*)(::g::Uno::UX::Property*, void*, uObject*))MainView__Fuse_Translation_float_X_Property__OnSet_fn; + ::TYPES[0] = ::g::Fuse::Translation_typeof(); + type->SetFields(2, + ::g::Fuse::Translation_typeof(), offsetof(::g::MainView__Fuse_Translation_float_X_Property, _obj), 0); + type->Reflection.SetFunctions(1, + new uFunction(".ctor", NULL, (void*)MainView__Fuse_Translation_float_X_Property__New1_fn, 0, true, MainView__Fuse_Translation_float_X_Property_typeof(), 1, ::g::Fuse::Translation_typeof())); + return type; +} + +// public Fuse_Translation_float_X_Property(Fuse.Translation obj) :128 +void MainView__Fuse_Translation_float_X_Property__ctor_1_fn(MainView__Fuse_Translation_float_X_Property* __this, ::g::Fuse::Translation* obj) +{ + __this->ctor_1(obj); +} + +// public Fuse_Translation_float_X_Property New(Fuse.Translation obj) :128 +void MainView__Fuse_Translation_float_X_Property__New1_fn(::g::Fuse::Translation* obj, MainView__Fuse_Translation_float_X_Property** __retval) +{ + *__retval = MainView__Fuse_Translation_float_X_Property::New1(obj); +} + +// protected override sealed float OnGet() :129 +void MainView__Fuse_Translation_float_X_Property__OnGet_fn(MainView__Fuse_Translation_float_X_Property* __this, float* __retval) +{ + return *__retval = uPtr(__this->_obj)->X(), void(); +} + +// protected override sealed void OnSet(float v, object origin) :130 +void MainView__Fuse_Translation_float_X_Property__OnSet_fn(MainView__Fuse_Translation_float_X_Property* __this, float* v, uObject* origin) +{ + float v_ = *v; + uPtr(__this->_obj)->X(v_); +} + +// public Fuse_Translation_float_X_Property(Fuse.Translation obj) [instance] :128 +void MainView__Fuse_Translation_float_X_Property::ctor_1(::g::Fuse::Translation* obj) +{ + ctor_(); + _obj = obj; +} + +// public Fuse_Translation_float_X_Property New(Fuse.Translation obj) [static] :128 +MainView__Fuse_Translation_float_X_Property* MainView__Fuse_Translation_float_X_Property::New1(::g::Fuse::Translation* obj) +{ + MainView__Fuse_Translation_float_X_Property* obj1 = (MainView__Fuse_Translation_float_X_Property*)uNew(MainView__Fuse_Translation_float_X_Property_typeof()); + obj1->ctor_1(obj); + return obj1; +} +// } + +} // ::g diff --git a/pool/shard004/C++/0048837_GammaFunction.cpp b/pool/shard004/C++/0048837_GammaFunction.cpp new file mode 100644 index 0000000000000000000000000000000000000000..18a3254a371af1c1ed432394ec6b49e4e8902d9e --- /dev/null +++ b/pool/shard004/C++/0048837_GammaFunction.cpp @@ -0,0 +1,43 @@ +#include "GammaFunction.h" +#include "RbMathFunctions.h" +#include + +using namespace RevBayesCore; +/** + * GammaFunction of a TypedDagNode of type double + * @param x a value of type double + */ +GammaFunction::GammaFunction(const TypedDagNode *x) : TypedFunction( new double(1.0) ), +a( x ) +{ + addParameter( x ); + +} + + +GammaFunction* GammaFunction::clone( void ) const +{ + + return new GammaFunction(*this); + +} + + +void GammaFunction::swapParameterInternal(const DagNode *oldP, const DagNode *newP) +{ + + if (oldP == a) + { + a = static_cast* >( newP ); + } + +} + +void GammaFunction::update( void ) +{ + + *value = RevBayesCore::RbMath::gamma( a->getValue() ); + +} + + diff --git a/pool/shard004/C/0097022_smtp_sasl_auth_cache.c b/pool/shard004/C/0097022_smtp_sasl_auth_cache.c new file mode 100644 index 0000000000000000000000000000000000000000..6b9f3307609a170eed68421592194e7fed6b6aa7 --- /dev/null +++ b/pool/shard004/C/0097022_smtp_sasl_auth_cache.c @@ -0,0 +1,274 @@ +/* $NetBSD: smtp_sasl_auth_cache.c,v 1.1.1.3 2014/07/06 19:27:56 tron Exp $ */ + +/*++ +/* NAME +/* smtp_sasl_auth_cache 3 +/* SUMMARY +/* Postfix SASL authentication reply cache +/* SYNOPSIS +/* #include "smtp.h" +/* #include "smtp_sasl_auth_cache.h" +/* +/* SMTP_SASL_AUTH_CACHE *smtp_sasl_auth_cache_init(map, ttl) +/* const char *map +/* int ttl; +/* +/* void smtp_sasl_auth_cache_store(auth_cache, session, resp) +/* SMTP_SASL_AUTH_CACHE *auth_cache; +/* const SMTP_SESSION *session; +/* const SMTP_RESP *resp; +/* +/* int smtp_sasl_auth_cache_find(auth_cache, session) +/* SMTP_SASL_AUTH_CACHE *auth_cache; +/* const SMTP_SESSION *session; +/* +/* char *smtp_sasl_auth_cache_dsn(auth_cache) +/* SMTP_SASL_AUTH_CACHE *auth_cache; +/* +/* char *smtp_sasl_auth_cache_text(auth_cache) +/* SMTP_SASL_AUTH_CACHE *auth_cache; +/* DESCRIPTION +/* This module maintains a cache of SASL authentication server replies. +/* This can be used to avoid repeated login failure errors. +/* +/* smtp_sasl_auth_cache_init() opens or creates the named cache. +/* +/* smtp_sasl_auth_cache_store() stores information about a +/* SASL login attempt together with the server status and +/* complete response. +/* +/* smtp_sasl_auth_cache_find() returns non-zero when a cache +/* entry exists for the given host, username and password. +/* +/* smtp_sasl_auth_cache_dsn() and smtp_sasl_auth_cache_text() +/* return the status and complete server response as found +/* with smtp_sasl_auth_cache_find(). +/* +/* Arguments: +/* .IP map +/* Lookup table name. The name must be singular and must start +/* with "proxy:". +/* .IP ttl +/* The time after which a cache entry is considered expired. +/* .IP session +/* Session context. +/* .IP resp +/* Remote SMTP server response, to be stored into the cache. +/* DIAGNOSTICS +/* All errors are fatal. +/* LICENSE +/* .ad +/* .fi +/* The Secure Mailer license must be distributed with this software. +/* AUTHOR(S) +/* Original author: +/* Keean Schupke +/* Fry-IT Ltd. +/* +/* Updated by: +/* Wietse Venema +/* IBM T.J. Watson Research +/* P.O. Box 704 +/* Yorktown Heights, NY 10598, USA +/*--*/ + + /* + * System library. + */ +#include + + /* + * Utility library + */ +#include +#include +#include +#include +#include + + /* + * Global library + */ +#include +#include + + /* + * Application-specific + */ +#include "smtp.h" +#include "smtp_sasl_auth_cache.h" + + /* + * XXX This feature stores passwords, so we must mask them with a strong + * cryptographic hash. This requires OpenSSL support. + * + * XXX It would be even better if the stored hash were salted. + */ +#ifdef HAVE_SASL_AUTH_CACHE + +/* smtp_sasl_auth_cache_init - per-process initialization (pre jail) */ + +SMTP_SASL_AUTH_CACHE *smtp_sasl_auth_cache_init(const char *map, int ttl) +{ + const char *myname = "smtp_sasl_auth_cache_init"; + SMTP_SASL_AUTH_CACHE *auth_cache; + + /* + * Sanity checks. + */ +#define HAS_MULTIPLE_VALUES(s) ((s)[strcspn((s), ", \t\r\n")] != 0) + + if (*map == 0) + msg_panic("%s: empty SASL authentication cache name", myname); + if (ttl < 0) + msg_panic("%s: bad SASL authentication cache ttl: %d", myname, ttl); + if (HAS_MULTIPLE_VALUES(map)) + msg_fatal("SASL authentication cache name \"%s\" " + "contains multiple values", map); + + /* + * XXX To avoid multiple writers the map needs to be maintained by the + * proxywrite service. We would like to have a DICT_FLAG_REQ_PROXY flag + * so that the library can enforce this, but that requires moving the + * dict_proxy module one level down in the build dependency hierachy. + */ +#define CACHE_DICT_OPEN_FLAGS \ + (DICT_FLAG_DUP_REPLACE | DICT_FLAG_SYNC_UPDATE) +#define PROXY_COLON DICT_TYPE_PROXY ":" +#define PROXY_COLON_LEN (sizeof(PROXY_COLON) - 1) + + if (strncmp(map, PROXY_COLON, PROXY_COLON_LEN) != 0) + msg_fatal("SASL authentication cache name \"%s\" must start with \"" + PROXY_COLON, map); + + auth_cache = (SMTP_SASL_AUTH_CACHE *) mymalloc(sizeof(*auth_cache)); + auth_cache->dict = dict_open(map, O_CREAT | O_RDWR, CACHE_DICT_OPEN_FLAGS); + auth_cache->ttl = ttl; + auth_cache->dsn = mystrdup(""); + auth_cache->text = mystrdup(""); + return (auth_cache); +} + + /* + * Each cache lookup key contains a server host name and user name. Each + * cache value contains a time stamp, a hashed password, and the server + * response. With this organization, we don't have to worry about cache + * pollution, because we can detect if a cache entry has expired, or if the + * password has changed. + */ + +/* smtp_sasl_auth_cache_make_key - format auth failure cache lookup key */ + +static char *smtp_sasl_auth_cache_make_key(const char *host, const char *user) +{ + VSTRING *buf = vstring_alloc(100); + + vstring_sprintf(buf, "%s;%s", host, user); + return (vstring_export(buf)); +} + +/* smtp_sasl_auth_cache_make_pass - hash the auth failure cache password */ + +static char *smtp_sasl_auth_cache_make_pass(const char *password) +{ + VSTRING *buf = vstring_alloc(2 * SHA_DIGEST_LENGTH); + + base64_encode(buf, (const char *) SHA1((const unsigned char *) password, + strlen(password), 0), + SHA_DIGEST_LENGTH); + return (vstring_export(buf)); +} + +/* smtp_sasl_auth_cache_make_value - format auth failure cache value */ + +static char *smtp_sasl_auth_cache_make_value(const char *password, + const char *dsn, + const char *rep_str) +{ + VSTRING *val_buf = vstring_alloc(100); + char *pwd_hash; + unsigned long now = (unsigned long) time((time_t *) 0); + + pwd_hash = smtp_sasl_auth_cache_make_pass(password); + vstring_sprintf(val_buf, "%lu;%s;%s;%s", now, pwd_hash, dsn, rep_str); + myfree(pwd_hash); + return (vstring_export(val_buf)); +} + +/* smtp_sasl_auth_cache_valid_value - validate auth failure cache value */ + +static int smtp_sasl_auth_cache_valid_value(SMTP_SASL_AUTH_CACHE *auth_cache, + const char *entry, + const char *password) +{ + ssize_t len = strlen(entry); + char *cache_hash = mymalloc(len); + char *curr_hash; + unsigned long now = (unsigned long) time((time_t *) 0); + unsigned long time_stamp; + int valid; + + auth_cache->dsn = myrealloc(auth_cache->dsn, len); + auth_cache->text = myrealloc(auth_cache->text, len); + + if (sscanf(entry, "%lu;%[^;];%[^;];%[^\n]", &time_stamp, cache_hash, + auth_cache->dsn, auth_cache->text) != 4 + || !dsn_valid(auth_cache->dsn)) { + msg_warn("bad smtp_sasl_auth_cache entry: %.100s", entry); + valid = 0; + } else if (time_stamp + auth_cache->ttl < now) { + valid = 0; + } else { + curr_hash = smtp_sasl_auth_cache_make_pass(password); + valid = (strcmp(cache_hash, curr_hash) == 0); + myfree(curr_hash); + } + myfree(cache_hash); + return (valid); +} + +/* smtp_sasl_auth_cache_find - search auth failure cache */ + +int smtp_sasl_auth_cache_find(SMTP_SASL_AUTH_CACHE *auth_cache, + const SMTP_SESSION *session) +{ + SMTP_ITERATOR *iter = session->iterator; + char *key; + const char *entry; + int valid = 0; + + key = smtp_sasl_auth_cache_make_key(STR(iter->host), session->sasl_username); + if ((entry = dict_get(auth_cache->dict, key)) != 0) + if ((valid = smtp_sasl_auth_cache_valid_value(auth_cache, entry, + session->sasl_passwd)) == 0) + /* Remove expired, password changed, or malformed cache entry. */ + if (dict_del(auth_cache->dict, key) != 0) + msg_warn("SASL auth failure map %s: entry not deleted: %s", + auth_cache->dict->name, key); + if (auth_cache->dict->error) + msg_warn("SASL auth failure map %s: lookup failed for %s", + auth_cache->dict->name, key); + myfree(key); + return (valid); +} + +/* smtp_sasl_auth_cache_store - update auth failure cache */ + +void smtp_sasl_auth_cache_store(SMTP_SASL_AUTH_CACHE *auth_cache, + const SMTP_SESSION *session, + const SMTP_RESP *resp) +{ + SMTP_ITERATOR *iter = session->iterator; + char *key; + char *value; + + key = smtp_sasl_auth_cache_make_key(STR(iter->host), session->sasl_username); + value = smtp_sasl_auth_cache_make_value(session->sasl_passwd, + resp->dsn, resp->str); + dict_put(auth_cache->dict, key, value); + + myfree(value); + myfree(key); +} + +#endif diff --git a/pool/shard004/C/0097023_pciinit.c b/pool/shard004/C/0097023_pciinit.c new file mode 100644 index 0000000000000000000000000000000000000000..0556ee2b576aa6c09d911b0c5e14cb3d838ba706 --- /dev/null +++ b/pool/shard004/C/0097023_pciinit.c @@ -0,0 +1,206 @@ +// Initialize PCI devices (on emulators) +// +// Copyright (C) 2008 Kevin O'Connor +// Copyright (C) 2006 Fabrice Bellard +// +// This file may be distributed under the terms of the GNU LGPLv3 license. + +#include "util.h" // dprintf +#include "pci.h" // pci_config_readl +#include "biosvar.h" // GET_EBDA +#include "pci_ids.h" // PCI_VENDOR_ID_INTEL +#include "pci_regs.h" // PCI_COMMAND + +#define PCI_ROM_SLOT 6 +#define PCI_NUM_REGIONS 7 + +static u32 pci_bios_io_addr; +static u32 pci_bios_mem_addr; +/* host irqs corresponding to PCI irqs A-D */ +static u8 pci_irqs[4] = { + 10, 10, 11, 11 +}; + +static void pci_set_io_region_addr(u16 bdf, int region_num, u32 addr) +{ + u32 ofs, old_addr; + + if (region_num == PCI_ROM_SLOT) { + ofs = PCI_ROM_ADDRESS; + } else { + ofs = PCI_BASE_ADDRESS_0 + region_num * 4; + } + + old_addr = pci_config_readl(bdf, ofs); + + pci_config_writel(bdf, ofs, addr); + dprintf(1, "region %d: 0x%08x\n", region_num, addr); +} + +/* return the global irq number corresponding to a given device irq + pin. We could also use the bus number to have a more precise + mapping. */ +static int pci_slot_get_pirq(u16 bdf, int irq_num) +{ + int slot_addend = pci_bdf_to_dev(bdf) - 1; + return (irq_num + slot_addend) & 3; +} + +static void pci_bios_init_bridges(u16 bdf) +{ + u16 vendor_id = pci_config_readw(bdf, PCI_VENDOR_ID); + u16 device_id = pci_config_readw(bdf, PCI_DEVICE_ID); + + if (vendor_id == PCI_VENDOR_ID_INTEL + && (device_id == PCI_DEVICE_ID_INTEL_82371SB_0 + || device_id == PCI_DEVICE_ID_INTEL_82371AB_0)) { + int i, irq; + u8 elcr[2]; + + /* PIIX3/PIIX4 PCI to ISA bridge */ + + elcr[0] = 0x00; + elcr[1] = 0x00; + for (i = 0; i < 4; i++) { + irq = pci_irqs[i]; + /* set to trigger level */ + elcr[irq >> 3] |= (1 << (irq & 7)); + /* activate irq remapping in PIIX */ + pci_config_writeb(bdf, 0x60 + i, irq); + } + outb(elcr[0], 0x4d0); + outb(elcr[1], 0x4d1); + dprintf(1, "PIIX3/PIIX4 init: elcr=%02x %02x\n", + elcr[0], elcr[1]); + } +} + +static void pci_bios_init_device(u16 bdf) +{ + int class; + u32 *paddr; + int i, pin, pic_irq, vendor_id, device_id; + + class = pci_config_readw(bdf, PCI_CLASS_DEVICE); + vendor_id = pci_config_readw(bdf, PCI_VENDOR_ID); + device_id = pci_config_readw(bdf, PCI_DEVICE_ID); + dprintf(1, "PCI: bus=%d devfn=0x%02x: vendor_id=0x%04x device_id=0x%04x\n" + , pci_bdf_to_bus(bdf), pci_bdf_to_devfn(bdf), vendor_id, device_id); + switch (class) { + case PCI_CLASS_STORAGE_IDE: + if (vendor_id == PCI_VENDOR_ID_INTEL + && (device_id == PCI_DEVICE_ID_INTEL_82371SB_1 + || device_id == PCI_DEVICE_ID_INTEL_82371AB)) { + /* PIIX3/PIIX4 IDE */ + pci_config_writew(bdf, 0x40, 0x8000); // enable IDE0 + pci_config_writew(bdf, 0x42, 0x8000); // enable IDE1 + goto default_map; + } else { + /* IDE: we map it as in ISA mode */ + pci_set_io_region_addr(bdf, 0, PORT_ATA1_CMD_BASE); + pci_set_io_region_addr(bdf, 1, PORT_ATA1_CTRL_BASE); + pci_set_io_region_addr(bdf, 2, PORT_ATA2_CMD_BASE); + pci_set_io_region_addr(bdf, 3, PORT_ATA2_CTRL_BASE); + } + break; + case PCI_CLASS_SYSTEM_PIC: + /* PIC */ + if (vendor_id == PCI_VENDOR_ID_IBM) { + /* IBM */ + if (device_id == 0x0046 || device_id == 0xFFFF) { + /* MPIC & MPIC2 */ + pci_set_io_region_addr(bdf, 0, 0x80800000 + 0x00040000); + } + } + break; + case 0xff00: + if (vendor_id == PCI_VENDOR_ID_APPLE && + (device_id == 0x0017 || device_id == 0x0022)) { + /* macio bridge */ + pci_set_io_region_addr(bdf, 0, 0x80800000); + } + break; + default: + default_map: + /* default memory mappings */ + for (i = 0; i < PCI_NUM_REGIONS; i++) { + int ofs; + if (i == PCI_ROM_SLOT) + ofs = PCI_ROM_ADDRESS; + else + ofs = PCI_BASE_ADDRESS_0 + i * 4; + + u32 old = pci_config_readl(bdf, ofs); + u32 mask; + if (i == PCI_ROM_SLOT) { + mask = PCI_ROM_ADDRESS_MASK; + pci_config_writel(bdf, ofs, mask); + } else { + if (old & PCI_BASE_ADDRESS_SPACE_IO) + mask = PCI_BASE_ADDRESS_IO_MASK; + else + mask = PCI_BASE_ADDRESS_MEM_MASK; + pci_config_writel(bdf, ofs, ~0); + } + u32 val = pci_config_readl(bdf, ofs); + pci_config_writel(bdf, ofs, old); + + if (val != 0) { + u32 size = (~(val & mask)) + 1; + if (val & PCI_BASE_ADDRESS_SPACE_IO) + paddr = &pci_bios_io_addr; + else + paddr = &pci_bios_mem_addr; + *paddr = ALIGN(*paddr, size); + pci_set_io_region_addr(bdf, i, *paddr); + *paddr += size; + } + } + break; + } + + /* enable memory mappings */ + pci_config_maskw(bdf, PCI_COMMAND, 0, PCI_COMMAND_IO | PCI_COMMAND_MEMORY); + + /* map the interrupt */ + pin = pci_config_readb(bdf, PCI_INTERRUPT_PIN); + if (pin != 0) { + pin = pci_slot_get_pirq(bdf, pin - 1); + pic_irq = pci_irqs[pin]; + pci_config_writeb(bdf, PCI_INTERRUPT_LINE, pic_irq); + } + + if (vendor_id == PCI_VENDOR_ID_INTEL + && device_id == PCI_DEVICE_ID_INTEL_82371AB_3) { + /* PIIX4 Power Management device (for ACPI) */ + + // acpi sci is hardwired to 9 + pci_config_writeb(bdf, PCI_INTERRUPT_LINE, 9); + + pci_config_writel(bdf, 0x40, PORT_ACPI_PM_BASE | 1); + pci_config_writeb(bdf, 0x80, 0x01); /* enable PM io space */ + pci_config_writel(bdf, 0x90, PORT_SMB_BASE | 1); + pci_config_writeb(bdf, 0xd2, 0x09); /* enable SMBus io space */ + } +} + +void +pci_setup(void) +{ + if (CONFIG_COREBOOT) + // Already done by coreboot. + return; + + dprintf(3, "pci setup\n"); + + pci_bios_io_addr = 0xc000; + pci_bios_mem_addr = BUILD_PCIMEM_START; + + int bdf, max; + foreachpci(bdf, max) { + pci_bios_init_bridges(bdf); + } + foreachpci(bdf, max) { + pci_bios_init_device(bdf); + } +} diff --git a/pool/shard004/C/0097027_merge_keynodes.c b/pool/shard004/C/0097027_merge_keynodes.c new file mode 100644 index 0000000000000000000000000000000000000000..c2e62505b6eb4c64783bd32f6ced531f3f6085bc --- /dev/null +++ b/pool/shard004/C/0097027_merge_keynodes.c @@ -0,0 +1,43 @@ +/* + * This source file is part of an OSTIS project. For the latest info, see http://ostis.net + * Distributed under the MIT License + * (See accompanying file COPYING.MIT or copy at http://opensource.org/licenses/MIT) + */ + +#include "merge_keynodes.h" +#include "merge.h" + +#include "../common/sc_keynodes.h" + +#include "sc_helper.h" +#include + +sc_addr keynode_question_set_cantorization; + +sc_addr keynode_question; +sc_addr keynode_question_initiated; +sc_addr keynode_nrel_answer; +sc_addr keynode_question_finished; +sc_addr keynode_system_element; + +const char keynode_question_set_cantorization_str[] = "question_set_cantorization"; + +const char keynode_question_initiated_str[] = "question_initiated"; +const char keynode_question_str[] = "question"; +const char keynode_nrel_answer_str[] = "nrel_answer"; +const char keynode_question_finished_str[] = "question_finished"; +const char keynode_system_element_str[] = "system_element"; + +sc_result merge_keynodes_initialize() +{ + + RESOLVE_KEYNODE(s_default_ctx, keynode_question_set_cantorization); + + RESOLVE_KEYNODE(s_default_ctx, keynode_nrel_answer); + RESOLVE_KEYNODE(s_default_ctx, keynode_question_initiated); + RESOLVE_KEYNODE(s_default_ctx, keynode_question); + RESOLVE_KEYNODE(s_default_ctx, keynode_question_finished); + RESOLVE_KEYNODE(s_default_ctx, keynode_system_element); + + return SC_RESULT_OK; +} diff --git a/pool/shard004/C/0097035_CWE121_Stack_Based_Buffer_Overflow__CWE806_char_declare_memmove_65a.c b/pool/shard004/C/0097035_CWE121_Stack_Based_Buffer_Overflow__CWE806_char_declare_memmove_65a.c new file mode 100644 index 0000000000000000000000000000000000000000..8ded7751592b78663ee6d35c976f03cc47965427 --- /dev/null +++ b/pool/shard004/C/0097035_CWE121_Stack_Based_Buffer_Overflow__CWE806_char_declare_memmove_65a.c @@ -0,0 +1,91 @@ +/* TEMPLATE GENERATED TESTCASE FILE +Filename: CWE121_Stack_Based_Buffer_Overflow__CWE806_char_declare_memmove_65a.c +Label Definition File: CWE121_Stack_Based_Buffer_Overflow__CWE806.label.xml +Template File: sources-sink-65a.tmpl.c +*/ +/* + * @description + * CWE: 121 Stack Based Buffer Overflow + * BadSource: Initialize data as a large string + * GoodSource: Initialize data as a small string + * Sinks: memmove + * BadSink : Copy data to string using memmove + * Flow Variant: 65 Data/control flow: data passed as an argument from one function to a function in a different source file called via a function pointer + * + * */ + +#include "std_testcase.h" + +#include + +#ifndef OMITBAD + +/* bad function declaration */ +void CWE121_Stack_Based_Buffer_Overflow__CWE806_char_declare_memmove_65b_badSink(char * data); + +void CWE121_Stack_Based_Buffer_Overflow__CWE806_char_declare_memmove_65_bad() +{ + char * data; + /* define a function pointer */ + void (*funcPtr) (char *) = CWE121_Stack_Based_Buffer_Overflow__CWE806_char_declare_memmove_65b_badSink; + char dataBuffer[100]; + data = dataBuffer; + /* FLAW: Initialize data as a large buffer that is larger than the small buffer used in the sink */ + memset(data, 'A', 100-1); /* fill with 'A's */ + data[100-1] = '\0'; /* null terminate */ + /* use the function pointer */ + funcPtr(data); +} + +#endif /* OMITBAD */ + +#ifndef OMITGOOD + +/* goodG2B uses the GoodSource with the BadSink */ +void CWE121_Stack_Based_Buffer_Overflow__CWE806_char_declare_memmove_65b_goodG2BSink(char * data); + +static void goodG2B() +{ + char * data; + void (*funcPtr) (char *) = CWE121_Stack_Based_Buffer_Overflow__CWE806_char_declare_memmove_65b_goodG2BSink; + char dataBuffer[100]; + data = dataBuffer; + /* FIX: Initialize data as a small buffer that as small or smaller than the small buffer used in the sink */ + memset(data, 'A', 50-1); /* fill with 'A's */ + data[50-1] = '\0'; /* null terminate */ + funcPtr(data); +} + +void CWE121_Stack_Based_Buffer_Overflow__CWE806_char_declare_memmove_65_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__CWE806_char_declare_memmove_65_good(); + printLine("Finished good()"); +#endif /* OMITGOOD */ +#ifndef OMITBAD + printLine("Calling bad()..."); + CWE121_Stack_Based_Buffer_Overflow__CWE806_char_declare_memmove_65_bad(); + printLine("Finished bad()"); +#endif /* OMITBAD */ + return 0; +} + +#endif diff --git a/pool/shard004/C/0097038_gendsa.c b/pool/shard004/C/0097038_gendsa.c new file mode 100644 index 0000000000000000000000000000000000000000..ec57c92a949274c0ff67a6ab992b54a4c6932ab5 --- /dev/null +++ b/pool/shard004/C/0097038_gendsa.c @@ -0,0 +1,141 @@ +/* + * Copyright 1995-2020 The OpenSSL Project Authors. All Rights Reserved. + * + * Licensed under the OpenSSL license (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 + */ + +#include +#include +#include +#include +#include +#include "apps.h" +#include "progs.h" +#include +#include +#include +#include +#include +#include + +typedef enum OPTION_choice { + OPT_ERR = -1, OPT_EOF = 0, OPT_HELP, + OPT_OUT, OPT_PASSOUT, OPT_ENGINE, OPT_CIPHER, + OPT_R_ENUM +} OPTION_CHOICE; + +const OPTIONS gendsa_options[] = { + {OPT_HELP_STR, 1, '-', "Usage: %s [args] dsaparam-file\n"}, + {OPT_HELP_STR, 1, '-', "Valid options are:\n"}, + {"help", OPT_HELP, '-', "Display this summary"}, + {"out", OPT_OUT, '>', "Output the key to the specified file"}, + {"passout", OPT_PASSOUT, 's', "Output file pass phrase source"}, + OPT_R_OPTIONS, + {"", OPT_CIPHER, '-', "Encrypt the output with any supported cipher"}, +#ifndef OPENSSL_NO_ENGINE + {"engine", OPT_ENGINE, 's', "Use engine, possibly a hardware device"}, +#endif + {NULL} +}; + +int gendsa_main(int argc, char **argv) +{ + ENGINE *e = NULL; + BIO *out = NULL, *in = NULL; + DSA *dsa = NULL; + const EVP_CIPHER *enc = NULL; + char *dsaparams = NULL; + char *outfile = NULL, *passoutarg = NULL, *passout = NULL, *prog; + OPTION_CHOICE o; + int ret = 1, private = 0; + const BIGNUM *p = NULL; + + prog = opt_init(argc, argv, gendsa_options); + while ((o = opt_next()) != OPT_EOF) { + switch (o) { + case OPT_EOF: + case OPT_ERR: + opthelp: + BIO_printf(bio_err, "%s: Use -help for summary.\n", prog); + goto end; + case OPT_HELP: + ret = 0; + opt_help(gendsa_options); + goto end; + case OPT_OUT: + outfile = opt_arg(); + break; + case OPT_PASSOUT: + passoutarg = opt_arg(); + break; + case OPT_ENGINE: + e = setup_engine(opt_arg(), 0); + break; + case OPT_R_CASES: + if (!opt_rand(o)) + goto end; + break; + case OPT_CIPHER: + if (!opt_cipher(opt_unknown(), &enc)) + goto end; + break; + } + } + argc = opt_num_rest(); + argv = opt_rest(); + private = 1; + + if (argc != 1) + goto opthelp; + dsaparams = *argv; + + if (!app_passwd(NULL, passoutarg, NULL, &passout)) { + BIO_printf(bio_err, "Error getting password\n"); + goto end; + } + + in = bio_open_default(dsaparams, 'r', FORMAT_PEM); + if (in == NULL) + goto end2; + + if ((dsa = PEM_read_bio_DSAparams(in, NULL, NULL, NULL)) == NULL) { + BIO_printf(bio_err, "unable to load DSA parameter file\n"); + goto end; + } + BIO_free(in); + in = NULL; + + out = bio_open_owner(outfile, FORMAT_PEM, private); + if (out == NULL) + goto end2; + + DSA_get0_pqg(dsa, &p, NULL, NULL); + + if (BN_num_bits(p) > OPENSSL_DSA_MAX_MODULUS_BITS) + BIO_printf(bio_err, + "Warning: It is not recommended to use more than %d bit for DSA keys.\n" + " Your key size is %d! Larger key size may behave not as expected.\n", + OPENSSL_DSA_MAX_MODULUS_BITS, BN_num_bits(p)); + + BIO_printf(bio_err, "Generating DSA key, %d bits\n", BN_num_bits(p)); + if (!DSA_generate_key(dsa)) + goto end; + + assert(private); + if (!PEM_write_bio_DSAPrivateKey(out, dsa, enc, NULL, 0, NULL, passout)) + goto end; + ret = 0; + end: + if (ret != 0) + ERR_print_errors(bio_err); + end2: + BIO_free(in); + BIO_free_all(out); + DSA_free(dsa); + release_engine(e); + OPENSSL_free(passout); + return ret; +} diff --git a/pool/shard004/C/0097040_inodes.c b/pool/shard004/C/0097040_inodes.c new file mode 100644 index 0000000000000000000000000000000000000000..dc228125f39e0bc8bd5ecf75d7751b87a45fc7b8 --- /dev/null +++ b/pool/shard004/C/0097040_inodes.c @@ -0,0 +1,106 @@ +/* +** Zabbix +** Copyright (C) 2001-2015 Zabbix SIA +** +** This program is free software; you can redistribute it and/or modify +** it under the terms of the GNU General Public License as published by +** the Free Software Foundation; either version 2 of the License, or +** (at your option) any later version. +** +** This program is distributed in the hope that it will be useful, +** but WITHOUT ANY WARRANTY; without even the implied warranty of +** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +** GNU General Public License for more details. +** +** You should have received a copy of the GNU General Public License +** along with this program; if not, write to the Free Software +** Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. +**/ + +#include "common.h" +#include "sysinfo.h" +#include "log.h" + +int VFS_FS_INODE(AGENT_REQUEST *request, AGENT_RESULT *result) +{ +#ifdef HAVE_SYS_STATVFS_H +# define ZBX_STATFS statvfs +# define ZBX_FFREE f_favail +#else +# define ZBX_STATFS statfs +# define ZBX_FFREE f_ffree +#endif + char *fsname, *mode; + zbx_uint64_t total; + struct ZBX_STATFS s; + + if (2 < request->nparam) + { + SET_MSG_RESULT(result, zbx_strdup(NULL, "Too many parameters.")); + return SYSINFO_RET_FAIL; + } + + fsname = get_rparam(request, 0); + mode = get_rparam(request, 1); + + if (NULL == fsname || '\0' == *fsname) + { + SET_MSG_RESULT(result, zbx_strdup(NULL, "Invalid first parameter.")); + return SYSINFO_RET_FAIL; + } + + if (0 != ZBX_STATFS(fsname, &s)) + { + SET_MSG_RESULT(result, zbx_dsprintf(NULL, "Cannot obtain filesystem information: %s", + zbx_strerror(errno))); + return SYSINFO_RET_FAIL; + } + + if (NULL == mode || '\0' == *mode || 0 == strcmp(mode, "total")) /* default parameter */ + { + SET_UI64_RESULT(result, s.f_files); + } + else if (0 == strcmp(mode, "free")) + { + SET_UI64_RESULT(result, s.ZBX_FFREE); + } + else if (0 == strcmp(mode, "used")) + { + SET_UI64_RESULT(result, s.f_files - s.f_ffree); + } + else if (0 == strcmp(mode, "pfree")) + { + total = s.f_files; +#ifdef HAVE_SYS_STATVFS_H + total -= s.f_ffree - s.f_favail; +#endif + if (0 != total) + SET_DBL_RESULT(result, (double)(100.0 * s.ZBX_FFREE) / total); + else + { + SET_MSG_RESULT(result, zbx_strdup(NULL, "Cannot calculate percentage because total is zero.")); + return SYSINFO_RET_FAIL; + } + } + else if (0 == strcmp(mode, "pused")) + { + total = s.f_files; +#ifdef HAVE_SYS_STATVFS_H + total -= s.f_ffree - s.f_favail; +#endif + if (0 != total) + SET_DBL_RESULT(result, 100.0 - (double)(100.0 * s.ZBX_FFREE) / total); + else + { + SET_MSG_RESULT(result, zbx_strdup(NULL, "Cannot calculate percentage because total is zero.")); + return SYSINFO_RET_FAIL; + } + } + else + { + SET_MSG_RESULT(result, zbx_strdup(NULL, "Invalid second parameter.")); + return SYSINFO_RET_FAIL; + } + + return SYSINFO_RET_OK; +} diff --git a/pool/shard004/C/0097046_array_list.c b/pool/shard004/C/0097046_array_list.c new file mode 100644 index 0000000000000000000000000000000000000000..c6481760969a645c3a917864f4178666d329ab58 --- /dev/null +++ b/pool/shard004/C/0097046_array_list.c @@ -0,0 +1,262 @@ +/****************************************************************************** + * @file array_list.c + * @author Muggle Wei + * @email mugglewei@gmail.com + * @date 2021-06-16 + * @copyright Copyright 2021 Muggle Wei + * @license MIT License + * @brief mugglec array list + *****************************************************************************/ + +#include "array_list.h" +#include +#include + +// get positive index in array list, if failed, return -1 +static int muggle_array_list_get_index(muggle_array_list_t *p_array_list, int index) +{ + int idx = 0; + if (index >= 0) + { + if ((uint64_t)index >= p_array_list->size) + { + idx = -1; + } + else + { + idx = index; + } + } + else + { + if ((uint64_t)-index > p_array_list->size) + { + idx = -1; + } + else + { + idx = (int)(p_array_list->size - (uint64_t)(-index)); + } + } + + return idx; +} + +bool muggle_array_list_init(muggle_array_list_t *p_array_list, size_t capacity) +{ + memset(p_array_list, 0, sizeof(*p_array_list)); + + capacity = capacity == 0 ? 8 : capacity; + + if (!MUGGLE_DS_CAP_IS_VALID(capacity)) + { + return false; + } + + p_array_list->nodes = (muggle_array_list_node_t*)malloc(sizeof(muggle_array_list_node_t) * capacity); + if (p_array_list->nodes == NULL) + { + return false; + } + + p_array_list->capacity = (uint64_t)capacity; + + return true; +} + +void muggle_array_list_destroy(muggle_array_list_t *p_array_list, muggle_dsaa_data_free func_free, void *pool) +{ + muggle_array_list_clear(p_array_list, func_free, pool); + + if (p_array_list) + { + free(p_array_list->nodes); + p_array_list = NULL; + } +} + +bool muggle_array_list_is_empty(muggle_array_list_t *p_array_list) +{ + return p_array_list->size == 0 ? true : false; +} + +void muggle_array_list_clear(muggle_array_list_t *p_array_list, muggle_dsaa_data_free func_free, void *pool) +{ + if (func_free) + { + for (uint64_t i = 0; i < p_array_list->size; i++) + { + if (p_array_list->nodes[i].data) + { + func_free(pool, p_array_list->nodes[i].data); + } + } + } + + p_array_list->size = 0; +} + +size_t muggle_array_list_size(muggle_array_list_t *p_array_list) +{ + return (size_t)p_array_list->size; +} + +bool muggle_array_list_ensure_capacity(muggle_array_list_t *p_array_list, size_t capacity) +{ + if (p_array_list->capacity >= (uint64_t)capacity) + { + return true; + } + + if (!MUGGLE_DS_CAP_IS_VALID(capacity)) + { + return false; + } + + muggle_array_list_node_t *new_nodes = (muggle_array_list_node_t*)malloc(sizeof(muggle_array_list_node_t) * capacity); + if (new_nodes == NULL) + { + return false; + } + + for (uint64_t i = 0; i < p_array_list->size; i++) + { + new_nodes[i].data = p_array_list->nodes[i].data; + } + + free(p_array_list->nodes); + p_array_list->nodes = new_nodes; + p_array_list->capacity = capacity; + + return true; +} + +muggle_array_list_node_t* muggle_array_list_index(muggle_array_list_t *p_array_list, int index) +{ + int idx = muggle_array_list_get_index(p_array_list, index); + if (idx < 0) + { + return NULL; + } + else + { + return &p_array_list->nodes[idx]; + } +} + +int muggle_array_list_find(muggle_array_list_t *p_array_list, int index, void *data, muggle_dsaa_data_cmp cmp) +{ + index = muggle_array_list_get_index(p_array_list, index); + if (index < 0) + { + return -1; + } + + uint64_t i = (uint64_t)index; + for (; i < p_array_list->size; i++) + { + if (cmp(p_array_list->nodes[i].data, data) == 0) + { + return (int)i; + } + } + + return -1; +} + +muggle_array_list_node_t* muggle_array_list_insert(muggle_array_list_t *p_array_list, int index, void *data) +{ + if (p_array_list->size == p_array_list->capacity) + { + if (!muggle_array_list_ensure_capacity(p_array_list, p_array_list->capacity * 2)) + { + return NULL; + } + } + + int idx = muggle_array_list_get_index(p_array_list, index); + if (idx < 0) + { + if ((index == 0 || index == -1) && p_array_list->size == 0) + { + idx = 0; + } + else + { + return NULL; + } + } + + for (int i = (int)p_array_list->size - 1; i >= idx; i--) + { + p_array_list->nodes[i + 1].data = p_array_list->nodes[i].data; + } + p_array_list->nodes[idx].data = data; + p_array_list->size++; + + return &p_array_list->nodes[idx]; +} + +muggle_array_list_node_t* muggle_array_list_append(muggle_array_list_t *p_array_list, int index, void *data) +{ + if (p_array_list->size == p_array_list->capacity) + { + if (!muggle_array_list_ensure_capacity(p_array_list, p_array_list->capacity * 2)) + { + return NULL; + } + } + + int idx = muggle_array_list_get_index(p_array_list, index); + if (idx < 0) + { + if ((index == 0 || index == -1) && p_array_list->size == 0) + { + idx = 0; + } + else + { + return NULL; + } + } + + for (int i = (int)p_array_list->size - 1; i > idx; i--) + { + p_array_list->nodes[i + 1].data = p_array_list->nodes[i].data; + } + + if (p_array_list->size == 0) + { + idx = 0; + } + else + { + idx = idx + 1; + } + p_array_list->nodes[idx].data = data; + p_array_list->size++; + + return &p_array_list->nodes[idx]; +} + +bool muggle_array_list_remove(muggle_array_list_t *p_array_list, int index, muggle_dsaa_data_free func_free, void *pool) +{ + index = muggle_array_list_get_index(p_array_list, index); + if (index < 0) + { + return 0; + } + + if (func_free) + { + func_free(pool, p_array_list->nodes[index].data); + } + + for (int i = index; i < (int)p_array_list->size - 1; i++) + { + p_array_list->nodes[i].data = p_array_list->nodes[i + 1].data; + } + p_array_list->size--; + + return true; +} diff --git a/pool/shard004/C/0097048_CWE223_Omission_of_Security_Relevant_Information__w32_16.c b/pool/shard004/C/0097048_CWE223_Omission_of_Security_Relevant_Information__w32_16.c new file mode 100644 index 0000000000000000000000000000000000000000..c24babf6412b93c22389586b0592cc82968240b2 --- /dev/null +++ b/pool/shard004/C/0097048_CWE223_Omission_of_Security_Relevant_Information__w32_16.c @@ -0,0 +1,244 @@ +/* TEMPLATE GENERATED TESTCASE FILE +Filename: CWE223_Omission_of_Security_Relevant_Information__w32_16.c +Label Definition File: CWE223_Omission_of_Security_Relevant_Information__w32.label.xml +Template File: point-flaw-16.tmpl.c +*/ +/* + * @description + * CWE: 223 Omission of Security Relevant Information + * Sinks: + * GoodSink: Log the username + * BadSink : Username is not logged + * Flow Variant: 16 Control flow: while(1) + * + * */ + +#include "std_testcase.h" + +#include +#pragma comment(lib, "advapi32.lib") +#pragma comment(lib, "ws2_32") + +#define LISTEN_PORT 999 +#define LISTEN_BACKLOG 5 +#define USERNAME_SZ 15 +#define DOMAIN "Domain" +#define PASSWORD "ABCD1234!" + +#ifndef OMITBAD + +void CWE223_Omission_of_Security_Relevant_Information__w32_16_bad() +{ + while(1) + { + { + WSADATA wsaData; + BOOL wsaDataInit = FALSE; + SOCKET listenSocket = INVALID_SOCKET; + SOCKET acceptSocket = INVALID_SOCKET; + struct sockaddr_in service; + char username[USERNAME_SZ+1]; + HANDLE pHandle; + do + { + if (0 != WSAStartup(MAKEWORD(2, 2), &wsaData)) + { + break; + } + wsaDataInit = TRUE; + listenSocket = socket(PF_INET, SOCK_STREAM, 0); + 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(LISTEN_PORT); + if (SOCKET_ERROR == bind(listenSocket, (struct sockaddr*)&service, sizeof(service))) + { + break; + } + if (SOCKET_ERROR == listen(listenSocket, LISTEN_BACKLOG)) + { + break; + } + acceptSocket = accept(listenSocket, NULL, NULL); + if (acceptSocket == INVALID_SOCKET) + { + break; + } + if (sizeof(username)-sizeof(char) != recv(acceptSocket, username, sizeof(username)-sizeof(char), 0)) + { + break; + } + username[USERNAME_SZ] = '\0'; + /* INCIDENTAL CWE 188 - reliance on data memory layout + * recv and friends return "number of bytes" received + * fwrite wants "the size of". ANSI/ISO allows the size of chars + * to be anything (32 bits, 9 bits, etc.) so technically you + * have to do conversion between these values + */ + /* FLAW: username is not logged */ + fprintf(stderr, "Attempted login\n"); + /* Establish the fact that the input is a username */ + if (LogonUserA( + username, + DOMAIN, + PASSWORD, /* INCIDENTAL CWE 259 - Hard-coded Password */ + LOGON32_LOGON_NETWORK, + LOGON32_PROVIDER_DEFAULT, + &pHandle) != 0) + { + printLine("User logged in successfully."); + CloseHandle(pHandle); + } + else + { + printLine("Unable to login."); + } + } + while (0); + if (acceptSocket != INVALID_SOCKET) + { + closesocket(acceptSocket); + } + if (listenSocket != INVALID_SOCKET) + { + closesocket(listenSocket); + } + if (wsaDataInit) + { + WSACleanup(); + } + } + break; + } +} + +#endif /* OMITBAD */ + +#ifndef OMITGOOD + +/* good1() uses the GoodSinkBody in the while loop */ +static void good1() +{ + while(1) + { + { + WSADATA wsaData; + BOOL wsaDataInit = FALSE; + SOCKET listenSocket = INVALID_SOCKET; + SOCKET acceptSocket = INVALID_SOCKET; + struct sockaddr_in service; + char username[USERNAME_SZ+1]; + HANDLE pHandle; + do + { + if (0 != WSAStartup(MAKEWORD(2, 2), &wsaData)) + { + break; + } + wsaDataInit = TRUE; + listenSocket = socket(PF_INET, SOCK_STREAM, 0); + 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(LISTEN_PORT); + if (SOCKET_ERROR == bind(listenSocket, (struct sockaddr*)&service, sizeof(service))) + { + break; + } + if (SOCKET_ERROR == listen(listenSocket, LISTEN_BACKLOG)) + { + break; + } + acceptSocket = accept(listenSocket, NULL, NULL); + if (acceptSocket == INVALID_SOCKET) + { + break; + } + if (sizeof(username)-sizeof(char) != recv(acceptSocket, username, sizeof(username)-sizeof(char), 0)) + { + break; + } + username[USERNAME_SZ] = '\0'; + /* INCIDENTAL CWE 188 - reliance on data memory layout + * recv and friends return "number of bytes" received + * fwrite wants "the size of". ANSI/ISO allows the size of chars + * to be anything (32 bits, 9 bits, etc.) so technically you + * have to do conversion between these values + */ + /* FIX: Log the username */ + fprintf(stderr, "Attempted login by %s\n", username); + /* Establish the fact that the input is a username */ + if (LogonUserA( + username, + DOMAIN, + PASSWORD, /* INCIDENTAL CWE 259 - Hard-coded Password */ + LOGON32_LOGON_NETWORK, + LOGON32_PROVIDER_DEFAULT, + &pHandle) != 0) + { + printLine("User logged in successfully."); + CloseHandle(pHandle); + } + else + { + printLine("Unable to login."); + } + } + while (0); + if (acceptSocket != INVALID_SOCKET) + { + closesocket(acceptSocket); + } + if (listenSocket != INVALID_SOCKET) + { + closesocket(listenSocket); + } + if (wsaDataInit) + { + WSACleanup(); + } + } + break; + } +} + +void CWE223_Omission_of_Security_Relevant_Information__w32_16_good() +{ + good1(); +} + +#endif /* OMITGOOD */ + +/* Below is the main(). It is only used when building this testcase on + its own for testing or for building a binary to use in testing binary + analysis tools. It is not used when compiling all the testcases as one + application, which is how source code analysis tools are tested. */ + +#ifdef INCLUDEMAIN + +int main(int argc, char * argv[]) +{ + /* seed randomness */ + srand( (unsigned)time(NULL) ); +#ifndef OMITGOOD + printLine("Calling good()..."); + CWE223_Omission_of_Security_Relevant_Information__w32_16_good(); + printLine("Finished good()"); +#endif /* OMITGOOD */ +#ifndef OMITBAD + printLine("Calling bad()..."); + CWE223_Omission_of_Security_Relevant_Information__w32_16_bad(); + printLine("Finished bad()"); +#endif /* OMITBAD */ + return 0; +} + +#endif diff --git a/pool/shard004/C/0097060_frontend.c b/pool/shard004/C/0097060_frontend.c new file mode 100644 index 0000000000000000000000000000000000000000..0f095f45ed9483ffefa6bad9b0e663e9da837f51 --- /dev/null +++ b/pool/shard004/C/0097060_frontend.c @@ -0,0 +1,198 @@ +/* + * This file is a part of plotnetcfg, a tool to visualize network config. + * Copyright (C) 2015 Red Hat, Inc. -- Jiri Benc + * + * 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 "frontend.h" +#include +#include +#include +#include +#include "args.h" +#include "if.h" +#include "utils.h" + +static struct output_entry default_output = { + .format = "dot", + .file = NULL, + .print_mask = -1U, +}; + +static int used_default_format = 0; + +static DECLARE_LIST(outputs); +static DECLARE_LIST(frontends); + +static int add_output(char *format) +{ + struct output_entry *out; + + out = malloc(sizeof(struct output_entry)); + if (!out) + return ENOMEM; + + *out = default_output; + + out->format = strdup(format); + if (!out->format) { + free(out); + return ENOMEM; + } + + list_prepend(&outputs, node(out)); + + return 0; +} + +static int add_format(char *arg) +{ + if (used_default_format) { + fprintf(stderr, "Failed to parse arguments: output options must come after --format.\n"); + return EINVAL; + } + + return add_output(arg); +} + +static int require_format() +{ + int err; + + if (list_empty(outputs)) { + if ((err = add_output(default_output.format))) + return err; + used_default_format = 1; + } + + return 0; +} + +static int set_output(char *arg) +{ + int err; + struct output_entry *head; + + if ((err = require_format())) + return err; + + head = list_head(outputs); + /* Multiple --outputs for one --format: clone last output */ + if (head->file && (err = add_output(head->format))) + return err; + + head = list_head(outputs); + head->file = strdup(arg); + if (!head->file) + return ENOMEM; + + return 0; +} + +static int set_nostate() +{ + int err; + struct output_entry *head; + + if ((err = require_format())) + return err; + + head = list_head(outputs); + head->print_mask &= ~IF_PROP_STATE; + return 0; +} + +static int print_formats(_unused char *arg) +{ + struct frontend *f; + + printf("Available output formats:\n"); + list_for_each(f, frontends) + printf("\t%s - %s\n", f->format, f->desc); + return 1; +} + +static struct arg_option options[] = { + { .long_name = "format", .short_name = 'f', .has_arg = 1, + .type = ARG_CALLBACK, .action.callback = add_format, + .help = "output format (default: dot)", + }, + { .long_name = "output", .short_name = 'o', .has_arg = 1, + .type = ARG_CALLBACK, .action.callback = set_output, + .help = "output file (default: standart output)", + }, + { .long_name = "config-only", .short_name = 'C', .has_arg = 0, + .type = ARG_CALLBACK, .action.callback = set_nostate, + .help = "skip state in output, print only configuration", + }, + { .long_name = "list-formats", .short_name = 'F', + .type = ARG_CALLBACK, .action.callback = print_formats, + .help = "list available output formats", + }, +}; + +void frontend_init(void) +{ + arg_register_batch(options, ARRAY_SIZE(options)); +} + +void frontend_register(struct frontend *f) +{ + list_append(&frontends, node(f)); +} + +int frontend_output(struct list *netns_list) +{ + struct frontend *f; + struct output_entry *out; + FILE *file; + + require_format(); + + list_for_each(out, outputs) { + list_for_each(f, frontends) { + if (!strcmp(f->format, out->format)) { + out->frontend = f; + break; + } + } + if (!out->frontend) + return EINVAL; + } + + list_for_each(out, outputs) { + if (out->file && strcmp("-", out->file)) { + file = fopen(out->file, "w"); + if (!file) + return errno; + } else + file = stdout; + + out->frontend->output(file, netns_list, out); + + if (file != stdout && fclose(file)) + return errno; + } + + return 0; +} + +void frontend_cleanup() +{ + struct output_entry *out; + + while ((out = list_pop(&outputs))) { + free(out->format); + free(out->file); + free(out); + } +} diff --git a/pool/shard004/C/0097063_dmi_setup.c b/pool/shard004/C/0097063_dmi_setup.c new file mode 100644 index 0000000000000000000000000000000000000000..f8b418d9df55b9cfd0d062c839601c2522789486 --- /dev/null +++ b/pool/shard004/C/0097063_dmi_setup.c @@ -0,0 +1,124 @@ +/* SPDX-License-Identifier: GPL-2.0-only */ + +#include +#include +#include "i82801ix.h" + +/* VC1 Port Arbitration Table */ +static const u8 vc1_pat[] = { + 0x0f, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x0f, 0x00, + 0x00, 0x00, 0x00, 0x00, + 0xf0, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x0f, + 0x00, 0x00, 0x00, 0x00, + 0x00, 0xf0, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, + 0x0f, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x0f, 0x00, + 0x00, 0x00, 0x00, 0x00, + 0xf0, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x0f, + 0x00, 0x00, 0x00, 0x00, + 0x00, 0xf0, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, +}; +void i82801ix_dmi_setup(void) +{ + int i; + u32 reg32; + + RCBA32(RCBA_V1CAP) = (RCBA32(RCBA_V1CAP) & ~(0x7f<<16)) | (0x12<<16); + + /* NB: other CIRs are handled in i82801ix_early_settings(). */ + RCBA32(RCBA_CIR1) = 0x00109000; + RCBA16(RCBA_CIR3) = 0x060b; + RCBA32(RCBA_CIR2) = 0x86000040; + RCBA8(RCBA_BCR) = 0x45; + RCBA32(RCBA_CIR6) &= ~(1 << 7); + + /* VC1 setup for isochronous transfers: */ + + /* Set VC1 virtual channel id to 1. */ + RCBA32(RCBA_V1CTL) = (RCBA32(RCBA_V1CTL) & ~(0x7 << 24)) | (0x1 << 24); + /* Enable TC7 traffic on VC1. */ + RCBA32(RCBA_V1CTL) = (RCBA32(RCBA_V1CTL) & ~(0x7f << 1)) | (1 << 7); + /* Disable TC7-TC1 traffic on VC0. */ + RCBA32(RCBA_V0CTL) &= ~(0x7f << 1); + /* TC7-TC1 traffic on PCIe root ports will be disabled in pci driver. */ + + /* Set table type to time-based WRR. */ + RCBA32(RCBA_V1CTL) = (RCBA32(RCBA_V1CTL) & ~(0x7 << 17)) | (0x4 << 17); + /* Program port arbitration table. */ + for (i = 0; i < sizeof(vc1_pat); ++i) + RCBA8(RCBA_PAT + i) = vc1_pat[i]; + /* Load port arbitration table. */ + RCBA32(RCBA_V1CTL) |= (1 << 16); + + /* Enable VC1. */ + RCBA32(RCBA_V1CTL) |= (1 << 31); + + /* Setup RCRB: */ + + /* Set component id to 2 for southbridge, northbridge has id 1. */ + RCBA8(RCBA_ESD + 2) = 2; + /* Set target port number and target component id of the northbridge. */ + RCBA8(RCBA_ULD + 3) = 1; + RCBA8(RCBA_ULD + 2) = 1; + /* Set target rcrb base address, i.e. DMIBAR. */ + RCBA32(RCBA_ULBA) = (uintptr_t)CONFIG_FIXED_DMIBAR_MMIO_BASE; + + /* Enable ASPM. */ + if (LPC_IS_MOBILE(PCI_DEV(0, 0x1f, 0))) { + reg32 = RCBA32(RCBA_DMC); + /* Enable mobile specific power saving (set this first). */ + reg32 = (reg32 & ~(3 << 10)) | (1 << 10); + RCBA32(RCBA_DMC) = reg32; + /* Enable DMI power savings. */ + reg32 |= (1 << 19); + RCBA32(RCBA_DMC) = reg32; + /* Advertise L0s and L1. */ + RCBA32(RCBA_LCAP) |= (3 << 10); + /* Enable L0s and L1. */ + RCBA32(RCBA_LCTL) |= (3 << 0); + } else { + /* Enable DMI power savings. */ + RCBA32(RCBA_DMC) |= (1 << 19); + /* Advertise L0s only. */ + RCBA32(RCBA_LCAP) = (RCBA32(RCBA_LCAP) & ~(3<<10)) | (1<<10); + /* Enable L0s only. */ + RCBA32(RCBA_LCTL) = (RCBA32(RCBA_LCTL) & ~(3<< 0)) | (1<< 0); + } +} + +/* Should be called after VC1 has been enabled on both sides. */ +void i82801ix_dmi_poll_vc1(void) +{ + int timeout; + + timeout = 0x7ffff; + printk(BIOS_DEBUG, "ICH9 waits for VC1 negotiation... "); + while ((RCBA32(RCBA_V1STS) & (1 << 1)) && --timeout) {} + if (!timeout) + printk(BIOS_DEBUG, "timeout!\n"); + else + printk(BIOS_DEBUG, "done.\n"); + + /* Check for x2 DMI link. */ + if (((RCBA16(RCBA_LSTS) >> 4) & 0x3f) == 2) { + printk(BIOS_DEBUG, "x2 DMI link detected.\n"); + RCBA32(0x2024) = (RCBA32(0x2024) & ~(7 << 21)) | (3 << 21); + RCBA16(0x20c4) |= (1 << 15); + RCBA16(0x20e4) |= (1 << 15); + /* TODO: Maybe we have to save and + restore these settings across S3. */ + } + + timeout = 0x7ffff; + printk(BIOS_DEBUG, "ICH9 waits for port arbitration table update... "); + while ((RCBA32(RCBA_V1STS) & (1 << 0)) && --timeout) {} + if (!timeout) + printk(BIOS_DEBUG, "timeout!\n"); + else + printk(BIOS_DEBUG, "done.\n"); +} diff --git a/pool/shard004/C/0097068_stdio.c b/pool/shard004/C/0097068_stdio.c new file mode 100644 index 0000000000000000000000000000000000000000..5c5c92466588fa48cd27995dc50a5a8f646f6607 --- /dev/null +++ b/pool/shard004/C/0097068_stdio.c @@ -0,0 +1,60 @@ +/* + * Copyright (c) 2013 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 + +#ifdef _WIN32 +#undef snprintf +#undef vsnprintf + +int +ovs_snprintf(char *s, size_t n, const char *format, ... ) +{ + va_list args; + int len; + + va_start(args, format); + len = ovs_vsnprintf(s, n, format, args); + va_end(args); + + return len; +} + +int +ovs_vsnprintf(char *s, size_t n, const char *format, va_list args) +{ + int needed = _vscprintf(format, args); + if (s && n) { + vsnprintf(s, n, format, args); + s[n - 1] = '\0'; + } + return needed; +} + +int +fseeko(FILE *stream, off_t offset, int whence) +{ + int error; + error = _fseeki64(stream, offset, whence); + if (error) { + return -1; + } + return error; +} +#endif /* _WIN32 */ diff --git a/pool/shard004/C/0097078_led-driver.c b/pool/shard004/C/0097078_led-driver.c new file mode 100644 index 0000000000000000000000000000000000000000..80713a3a1685b4d5f7c6a45190dd2ad4f6912226 --- /dev/null +++ b/pool/shard004/C/0097078_led-driver.c @@ -0,0 +1,151 @@ +#include +#include +#include +#include +#include +#include +#include "softPwm.h" + +#define PIN_RED 7 +#define PIN_GREEN 9 +#define PIN_BLUE 8 + +#define CLAMP(x, low, high) (((x) > (high)) ? (high) : (((x) < (low)) ? (low) : (x))) + +static void usage(char *name) { + fprintf(stderr, "usage:\n"); + fprintf(stderr, " %s on ....... turn on LED (white)\n", name); + fprintf(stderr, " %s off ....... turn off LED\n", name); + fprintf(stderr, " %s cat ....... read rgb tuples from stdin\n", name); + fprintf(stderr, " %s rgb r g b Set LED color to r,g,b\n", name); + fprintf(stderr, " %s hex #FFFFFF Set LED color from hexstring\n", name); + fprintf(stderr, " %s fade ...... Show a fade for debugging\n", name); + exit(1); +} + +static int linearize(int v) { + // Half linear and half quadratic mix: + return ((v / 256.) * (v / 256.)) * 128 + (v / 128.); +} + +static void set_rgb(int r, int g, int b) { + softPwmWrite(PIN_RED, linearize(r)); + softPwmWrite(PIN_GREEN, linearize(g)); + softPwmWrite(PIN_BLUE, linearize(b)); +} + +static int string_to_col(const char * arg) { + return CLAMP(strtol(arg,NULL,10),0,255); +} + +static void set_rgb_from_arr(const char ** arr) { + int r = string_to_col(arr[0]); + int g = string_to_col(arr[1]); + int b = string_to_col(arr[2]); + + set_rgb(r, g, b); +} + +static void hexstring_to_rgb(const char * str, unsigned * r, unsigned * g, unsigned * b) { + char * is_err = NULL; + if(!(str && r && g && b)) + return; + + union { + uint32_t val; + unsigned char arr[sizeof(uint32_t)]; + } rgb_int = {.val=0}; + + rgb_int.val = strtoul(str,&is_err, 10); + + if(is_err == NULL || *is_err == '\n' || *is_err == 0) { + // Little endian: + *r = rgb_int.arr[2]; + *g = rgb_int.arr[1]; + *b = rgb_int.arr[0]; + } +} + +int main(int argc, char **argv) { + piHiPri(30); + wiringPiSetup(); + + if(argc < 2) { + usage(argv[0]); + } + + softPwmCreate(PIN_RED, 0, 255); + softPwmCreate(PIN_GREEN, 0, 255); + softPwmCreate(PIN_BLUE, 0, 255); + + if(strcasecmp(argv[1], "cat") == 0) { + const int size = 512; + char buf[size + 1]; + const char * rgb[3] = {0,0,0}; + int i = 0; + + for(;;) { + memset(buf, 0, size); + if(fgets(buf,size,stdin) == NULL) { + puts("Got EOF, quitting"); + break; + } + + if(buf[0] == '#') { + unsigned r = 0, g = 0, b = 0; + hexstring_to_rgb(&buf[1], &r, &g, &b); + set_rgb(r, g, b); + } else { + bool is_valid = true; + char * node = buf; + + for(i = 0; i < 3; i++) { + rgb[i] = node; + node = strpbrk(node," \n"); + if(node != NULL) { + *node++ = 0; + } else { + is_valid = false; + break; + } + } + + if(is_valid) { + set_rgb_from_arr(rgb); + } + } + } + } else if(strcasecmp(argv[1], "fade") == 0) { + for(int i = 0; i < 256; i++) { + set_rgb(i, 0, 0); + delay(10); + } + for(int i = 0; i < 256; i++) { + set_rgb(0, i, 0); + delay(10); + } + for(int i = 0; i < 256; i++) { + set_rgb(0, 0, i); + delay(10); + } + for(int i = 0; i < 256; i++) { + set_rgb(i, i, i); + delay(10); + } + } else if(strcasecmp(argv[1], "rgb") == 0 && argc > 4) { + set_rgb_from_arr((const char**)&argv[2]); + } else if(strcasecmp(argv[1], "hex") == 0) { + unsigned r = 0, g = 0, b = 0; + printf("%s\n",&argv[2][1]); + hexstring_to_rgb(&argv[2][1], &r, &g, &b); + set_rgb(r, g, b); + } else if(strcasecmp(argv[1], "off")) { + set_rgb(0, 0, 0); + } else if(strcasecmp(argv[1], "on")) { + set_rgb(0, 0, 0); + } else { + usage(argv[0]); + } + + return EXIT_SUCCESS; +} diff --git a/pool/shard004/C/0097081_client-command.c b/pool/shard004/C/0097081_client-command.c new file mode 100644 index 0000000000000000000000000000000000000000..997e35f8a69cb13ee94cb05afe005a82ed877fe4 --- /dev/null +++ b/pool/shard004/C/0097081_client-command.c @@ -0,0 +1,177 @@ +#include "client-command.h" +#include "tokenizer.h" +#include "reqres.h" + +#include +#include +#include +#include +#include +#include +#define PROMPT "$> " +#define INVALID_CMD "Invalid command. Use help to get more information." +// Wait time between 2 commands +#define WAIT_TIME 2 +#define TERMIOS_ECHO 1 +#define TERMIOS_NON_ECHO 0 +static struct termios old, new; + +void initTermios(int echo) { + /* grab old terminal i/o settings */ + tcgetattr(0, &old); + /* make new settings same as old settings */ + new = old; + /* disable buffered i/o */ + new.c_lflag &= ~ICANON; + /* set echo mode */ + new.c_lflag &= echo ? ECHO : ~ECHO; + /* use these new terminal i/o settings now */ + tcsetattr(0, TCSANOW, &new); +} + +void resetTermios(void) { + tcsetattr(0, TCSANOW, &old); +} + +char getch_(int echo) { + char ch; + initTermios(echo); + ch = getchar(); + resetTermios(); + return ch; +} + +void set_request (request_t* request, int code, char* message){ + request->code = htonl(code); + switch(code){ + case OPEN: + case START: + strcpy(request->message.name,message); + break; + case CREDIT: + case DEBIT: + strcpy(request->message.amount,message); + break; + } +} +void* command_subroutine(void* arg){ + // Reset the terminal when exiting + // atexit(resetTermios); + command_arg_t* command_arg = (command_arg_t*) arg; + int client_socket_fd = command_arg->client_socket_fd; + char user_input[200]; + char* token; + request_t request; + int valid_command; + printf(PROMPT); + while(fgets(user_input,sizeof(user_input),stdin)!=NULL){ + + valid_command = 0; + TokenizerT* tk = TKCreate(user_input); + token = TKGetNextToken(tk); + if(token==NULL){ + valid_command = 0; + }else if( strcmp(token,"open") == 0 ){ + free(token); + token = TKGetNextToken(tk); + if(token==NULL){ + printf(INVALID_CMD); + }else{ + if(strlen(token)<= NAME_MAX_LENGTH-1){ + set_request(&request,OPEN,token); + valid_command = 1; + }else{ + printf("The name length is invalid.\n"); + } + free(token); + } + }else if(strcmp(token,"start")==0){ + free(token); + token = TKGetNextToken(tk); + if(token == NULL){ + valid_command = 0 ; + printf("%s\n",INVALID_CMD); + }else{ + if(strlen(token)<=NAME_MAX_LENGTH-1){ + set_request(&request,START,token); + valid_command = 1; + }else{ + printf("The name length is invalid.\n"); + } + free(token); + } + }else if(strcmp(token,"credit")==0){ + free(token); + token = TKGetNextToken(tk); + if(token== NULL){ + printf("%s\n",INVALID_CMD); + }else if(TKGetType(tk)==FLOAT || TKGetType(tk)==DEC) { + set_request(&request,CREDIT,token); + valid_command = 1; + free(token); + } + }else if(strcmp(token,"debit")==0){ + free(token); + token = TKGetNextToken(tk); + if(token== NULL){ + printf("%s\n",INVALID_CMD); + }else if(TKGetType(tk)==FLOAT || TKGetType(tk)==DEC){ + set_request(&request,DEBIT,token); + valid_command = 1; + free(token); + }else{ + printf("%s\n",INVALID_CMD); + free(token); + } + }else if(strcmp(token,"balance")==0){ + free(token); + set_request(&request,BALANCE,NULL); + valid_command=1; + }else if(strcmp(token,"finish")==0){ + free(token); + set_request(&request,FINISH,NULL); + valid_command=1; + }else if(strcmp(token,"exit")==0){ + free(token); + set_request(&request,EXIT,NULL); + valid_command = 1; + }else if(strcmp(token,"help")==0){ + free(token); + printf("open ACCOUNT_NAME\n"\ + "start ACCOUNT_NAME\n"\ + "credit AMOUNT\n"\ + "debit AMOUNT\n"\ + "balance\n"\ + "finish\n"\ + "exit\n"); + }else{ + free(token); + printf("The command is invalid. Use 'help' to see a "\ + "list of command options.\n"); + } + if(valid_command){ + if((token=TKGetNextToken(tk))!=NULL){ + printf("Invalid command.\n"); + free(token); + }else{ + write(client_socket_fd,(void*)&request,sizeof( request_t)); + // initTermios(TERMIOS_NON_ECHO); + if(request.code !=htonl(EXIT)){ + unsigned int sleep_time = WAIT_TIME; + while((sleep_time=sleep(sleep_time))!=0){ + continue; + } + } + //resetTermios(); + } + } + TKDestroy(tk); + if(request.code == htonl(EXIT)){ + break; + }else{ + printf(PROMPT); + } + } + pthread_exit(NULL); +} + diff --git a/pool/shard004/C/0097082_aum.c b/pool/shard004/C/0097082_aum.c new file mode 100644 index 0000000000000000000000000000000000000000..1f5ed6b16bdbc570480cecfab09dc99250632efe --- /dev/null +++ b/pool/shard004/C/0097082_aum.c @@ -0,0 +1,155 @@ +/* AUM - A minimal CSPRNG reflecting the Zen of cipher design + AUM is an AUM with an 8,16,32 or 64+4-word internal state + AUM may be seeded with a 256-, 512-, 1024- or 2048-bit key + AUM Copyright C.C.Kayne 2014, GNU GPL V.3, cckayne@gmail.com + AUM is inspired by Bob Jenkins' PRNG insights (Public Domain). +*/ +#include +#include +#include +#include "aum.h" + +#define TEST +#define VERBOSE + +// AUM defines + +/* select your AUM variant here */ +//#define AUM8 +#define AUM16 +//#define AUM32 +//#define AUM64 + +/* internal state parameters */ +#ifdef AUM8 +#define STSZ 8 +#define NAME "AUM8" +#endif +#ifdef AUM16 +#define STSZ 16 +#define NAME "AUM16" +#endif +#ifdef AUM32 +#define STSZ 32 +#define NAME "AUM32" +#endif +#ifdef AUM64 +#define STSZ 64 +#define NAME "AUM64" +#endif +#define STM1 STSZ-1 +#define STBYTES STSZ*4 +#define STBITS 128+STBYTES*8 + +/* 2**32/phi, where phi is the golden ratio */ +#define GOLDEN 0x9e3779b9 + +static u4 state[STSZ], rsl[STSZ], b, c, d, e, rcnt=0; + +#ifdef TEST +static void statepeek(void); +#endif + + +// AUM is filled every 16, 32 or 64 rounds +static void aum(void) { + u4 i; + for (i=0; iSTBYTES) l=STBYTES; + memset(s,0,l+1); + /* truncate seed to state-size if necessary */ + for (i=0; itls_certfp); + source_p->tls_certfp = xstrdup(parv[1]); + + sendto_server(source_p, 0, 0, ":%s CERTFP %s", + source_p->id, source_p->tls_certfp); +} + +static struct Message certfp_msgtab = +{ + .cmd = "CERTFP", + .handlers[UNREGISTERED_HANDLER] = { .handler = m_ignore }, + .handlers[CLIENT_HANDLER] = { .handler = m_ignore }, + .handlers[SERVER_HANDLER] = { .handler = ms_certfp, .args_min = 2 }, + .handlers[ENCAP_HANDLER] = { .handler = m_ignore }, + .handlers[OPER_HANDLER] = { .handler = m_ignore } +}; + +static void +module_init(void) +{ + mod_add_cmd(&certfp_msgtab); +} + +static void +module_exit(void) +{ + mod_del_cmd(&certfp_msgtab); +} + +struct module module_entry = +{ + .version = "$Revision$", + .modinit = module_init, + .modexit = module_exit, +}; diff --git a/pool/shard004/C/0097098_float_dsp_init.c b/pool/shard004/C/0097098_float_dsp_init.c new file mode 100644 index 0000000000000000000000000000000000000000..9dd2072b7aa0df78160bdff5c04aa36fcd828850 --- /dev/null +++ b/pool/shard004/C/0097098_float_dsp_init.c @@ -0,0 +1,40 @@ +/* + * Copyright (c) 2006 Luca Barbato + * + * 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 "libavutil/attributes.h" +#include "libavutil/cpu.h" +#include "libavutil/float_dsp.h" +#include "libavutil/ppc/cpu.h" +#include "float_dsp_altivec.h" + +av_cold void ff_float_dsp_init_ppc(AVFloatDSPContext *fdsp, int bit_exact) +{ + if (!PPC_ALTIVEC(av_get_cpu_flags())) + return; + + fdsp->vector_fmul = ff_vector_fmul_altivec; + fdsp->vector_fmul_add = ff_vector_fmul_add_altivec; + fdsp->vector_fmul_reverse = ff_vector_fmul_reverse_altivec; + + if (!bit_exact) { + fdsp->vector_fmul_window = ff_vector_fmul_window_altivec; + } +} diff --git a/pool/shard004/C/0097105_ALOM.c b/pool/shard004/C/0097105_ALOM.c new file mode 100644 index 0000000000000000000000000000000000000000..ef5b249a665170d6e61bfa5ddd71567ab0524b22 --- /dev/null +++ b/pool/shard004/C/0097105_ALOM.c @@ -0,0 +1,170 @@ +#include "GlobalDef.h" +#include "ADSType.h" +#include "CANPack1.h" +#include "J1850/Chrysler.h" +#include "ProgrammedModule.h" +#include "Ignition.h" +#include "Periodic.h" +#include "Scheduler.h" +#include "J1850VPWM.h" +#include "LED.h" +#include "ModuleReset.h" +#include "Input.h" +#include "J1850_V2/GM.h" +#include "ProgSwitch.h" +#include "InputMode.h" +#include "ProgrammedModule.h" +#include "Sleep.h" +#include "TBOM.h" +#include "Delay.h" +#include "AlarmPort.h" +#include "ModeSelection.h" + +#include "ALOM.h" +#include "DLOM.h" +#include "TBOM.h" + +static void ALOM_GetMode(void); + +#define Check_Mode_TB(Mode) (Mode>0 && Mode<50) +#define Check_Mode_DL(Mode) (Mode>50 && Mode<100) +static volatile Uint8 ALOM_Mode=0xFF; + +#define TB_MODE 1 +#define DL_MODE 2 +static Uint8 ALOM_DLorTB=0; + +void ALOM_Init(void) +{ + // Do small Init sequence + wdt_enable(WDTO_2S); + + #ifdef HW_BLADE + UartSwitch_Init(); + UartSwitch_SetState(OPEN); + #endif + + ProgSw_Init(); + LED_Init(); + Ignition_Init(); + J1850VPWM_Init(); + AlarmPort_Init(); + Input_Init(); + Periodic_Init(); + Scheduler_Init(); + + // Enable global interrupt + GlobalIntEnable(); + + // Turn on scheduler + Scheduler_Enable(); + + // Check if unit needs to be reset + ModuleReset_CheckToResetEEPROM(); + + // Find AL-OMNI Mode + ALOM_GetMode(); + + // Set up input mode + InputMode_Select(); + + Delay(10); + + if(ALOM_DLorTB==TB_MODE) + { + TBOM_Init(); + } + else if(ALOM_DLorTB==DL_MODE) + { + DLOM_Init(); + } +} + +void ALOM_Main(void) +{ + if(ALOM_DLorTB==TB_MODE) + { + TBOM_Main(); + } + else if(ALOM_DLorTB==DL_MODE) + { + DLOM_Main(); + } +} + +static void ALOM_GetMode(void) +{ + Uint8 i; + Uint8 Mode, ModeDigit1, ModeDigit2; + + // Load Mode from eeprom + ALOM_Mode=EEPROM_Read(PROGRAM_MEMORY_ALOM_MODE_PTR); + ALOM_DLorTB=EEPROM_Read(PROGRAM_MEMORY_ALOM_DL_OR_TB_PTR); + + // Check if mode is already learned before reading + if(ALOM_Mode==0xFF) + { + Start_Mode_Selection: + + // Find Mode + ALOM_Mode=0; + ALOM_DLorTB=0; + Mode=0; + ModeDigit1=0; + ModeDigit2=0; + + // Prompt User for 1st Digit of Mode + ModeSelection_Enter((Uint8*)&ModeDigit1,9,RED); + + Delay(30); + + // Prompt User for 2nd Digit of Mode + ModeSelection_Enter((Uint8*)&ModeDigit2,9,RED); + + ModeDigit1++; + ModeDigit2++; + + for(i=0;i + * + * 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 tests_float.c + * Floating point tests + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include "tests.h" +#include +#include + +typedef union { + float f; + double d; + uint8_t b[8]; +} test_float_double_t; + +int test_float(int argc, char *argv[]) +{ + int ret = 0; + + printf("\n--- SINGLE PRECISION TESTS ---\n"); + printf("The single precision test involves calls to fabsf(),\nif test fails check this function as well.\n\n"); + + float f1 = 1.55f; + + float sinf_zero = sinf(0.0f); + float sinf_one = sinf(1.0f); + float sqrt_two = sqrt(2.0f); + + if (fabsf(sinf_zero) < FLT_EPSILON) { + printf("\t success: sinf(0.0f) == 0.0f\n"); + + } else { + printf("\t FAIL: sinf(0.0f) != 0.0f, result: %8.4f\n", (double)sinf_zero); + ret = -4; + } + + fflush(stdout); + + if (fabsf((sinf_one - 0.841470956802368164062500000000f)) < FLT_EPSILON) { + printf("\t success: sinf(1.0f) == 0.84147f\n"); + + } else { + printf("\t FAIL: sinf(1.0f) != 0.84147f, result: %8.4f\n", (double)sinf_one); + ret = -1; + } + + fflush(stdout); + + float asinf_one = asinf(1.0f); + + if (fabsf((asinf_one - 1.570796251296997070312500000000f)) < FLT_EPSILON * 1.5f) { + printf("\t success: asinf(1.0f) == 1.57079f\n"); + + } else { + printf("\t FAIL: asinf(1.0f) != 1.57079f, result: %f\n", (double)asinf_one); + ret = -1; + } + + fflush(stdout); + + float cosf_one = cosf(1.0f); + + if (fabsf((cosf_one - 0.540302336215972900390625000000f)) < FLT_EPSILON) { + printf("\t success: cosf(1.0f) == 0.54030f\n"); + + } else { + printf("\t FAIL: cosf(1.0f) != 0.54030f, result: %8.4f\n", (double)cosf_one); + ret = -1; + } + + fflush(stdout); + + + float acosf_one = acosf(1.0f); + + if (fabsf((acosf_one - 0.000000000000000000000000000000f)) < FLT_EPSILON) { + printf("\t success: acosf(1.0f) == 0.0f\n"); + + } else { + printf("\t FAIL: acosf(1.0f) != 0.0f, result: %8.4f\n", (double)acosf_one); + ret = -1; + } + + fflush(stdout); + + + float sinf_zero_one = sinf(0.1f); + + if (fabsf(sinf_zero_one - 0.0998334166f) < FLT_EPSILON) { + printf("\t success: sinf(0.1f) == 0.09983f\n"); + + } else { + printf("\t FAIL: sinf(0.1f) != 0.09983f, result: %8.4f\n", (double)sinf_zero_one); + ret = -2; + } + + if (fabsf(sqrt_two - 1.41421356f) < FLT_EPSILON) { + printf("\t success: sqrt(2.0f) == 1.41421f\n"); + + } else { + printf("\t FAIL: sqrt(2.0f) != 1.41421f, result: %8.4f\n", (double)sinf_zero_one); + ret = -3; + } + + float atan2f_ones = atan2(1.0f, 1.0f); + + if (fabsf(atan2f_ones - 0.785398163397448278999490867136f) < FLT_EPSILON) { + printf("\t success: atan2f(1.0f, 1.0f) == 0.78539f\n"); + + } else { + printf("\t FAIL: atan2f(1.0f, 1.0f) != 0.78539f, result: %8.4f\n", (double)atan2f_ones); + ret = -4; + } + + char sbuf[30]; + sprintf(sbuf, "%8.4f", (double)0.553415f); + + if (sbuf[0] == ' ' && sbuf[1] == ' ' && sbuf[2] == '0' && + sbuf[3] == '.' && sbuf[4] == '5' && sbuf[5] == '5' + && sbuf[6] == '3' && sbuf[7] == '4' && sbuf[8] == '\0') { + printf("\t success: printf(\"%%8.4f\", 0.553415f) == %8.4f\n", (double)0.553415f); + } else { + printf("\t FAIL: printf(\"%%8.4f\", 0.553415f) != \" 0.5534\", result: %s\n", sbuf); + ret = -5; + } + + sprintf(sbuf, "%8.4f", (double)-0.553415f); + + if (sbuf[0] == ' ' && sbuf[1] == '-' && sbuf[2] == '0' && + sbuf[3] == '.' && sbuf[4] == '5' && sbuf[5] == '5' + && sbuf[6] == '3' && sbuf[7] == '4' && sbuf[8] == '\0') { + printf("\t success: printf(\"%%8.4f\", -0.553415f) == %8.4f\n", (double)-0.553415f); + } else { + printf("\t FAIL: printf(\"%%8.4f\", -0.553415f) != \" -0.5534\", result: %s\n", sbuf); + ret = -6; + } + + + + + + printf("\n--- DOUBLE PRECISION TESTS ---\n"); + + double d1 = 1.0111; + double d2 = 2.0; + + double d1d2 = d1 * d2; + + if (fabs(d1d2 - 2.022200000000000219557705349871) < DBL_EPSILON) { + printf("\t success: 1.0111 * 2.0 == 2.0222\n"); + + } else { + printf("\t FAIL: 1.0111 * 2.0 != 2.0222, result: %8.4f\n", d1d2); + ret = -7; + } + + fflush(stdout); + + // Assign value of f1 to d1 + d1 = f1; + + if (fabsf(f1 - (float)d1) < FLT_EPSILON) { + printf("\t success: (float) 1.55f == 1.55 (double)\n"); + + } else { + printf("\t FAIL: (float) 1.55f != 1.55 (double), result: %8.4f\n", (double)f1); + ret = -8; + } + + fflush(stdout); + + + double sin_zero = sin(0.0); + double sin_one = sin(1.0); + double atan2_ones = atan2(1.0, 1.0); + + if (fabs(sin_zero - 0.0) < DBL_EPSILON) { + printf("\t success: sin(0.0) == 0.0\n"); + + } else { + printf("\t FAIL: sin(0.0) != 0.0, result: %8.4f\n", sin_zero); + ret = -9; + } + + if (fabs(sin_one - 0.841470984807896504875657228695) < DBL_EPSILON) { + printf("\t success: sin(1.0) == 0.84147098480\n"); + + } else { + printf("\t FAIL: sin(1.0) != 1.0, result: %8.4f\n", sin_one); + ret = -10; + } + + if (fabs(atan2_ones - 0.785398) < DBL_EPSILON) { + printf("\t success: atan2(1.0, 1.0) == 0.785398\n"); + + } else { + printf("\t FAIL: atan2(1.0, 1.0) != 0.785398, result: %8.4f\n", atan2_ones); + ret = -11; + } + + printf("\t testing pow() with magic value\n"); + printf("\t (44330.0 * (1.0 - pow((96286LL / 101325.0), 0.190295)));\n"); + fflush(stdout); + usleep(20000); + double powres = (44330.0 * (1.0 - pow((96286LL / 101325.0), 0.190295))); + printf("\t success: result: %8.4f\n", (double)powres); + + sprintf(sbuf, "%8.4f", 0.553415); + + if (sbuf[0] == ' ' && sbuf[1] == ' ' && sbuf[2] == '0' && + sbuf[3] == '.' && sbuf[4] == '5' && sbuf[5] == '5' + && sbuf[6] == '3' && sbuf[7] == '4' && sbuf[8] == '\0') { + printf("\t success: printf(\"%%8.4f\", 0.553415) == %8.4f\n", 0.553415); + } else { + printf("\t FAIL: printf(\"%%8.4f\", 0.553415) != \" 0.5534\", result: %s\n", sbuf); + ret = -12; + } + + sprintf(sbuf, "%8.4f", -0.553415); + + if (sbuf[0] == ' ' && sbuf[1] == '-' && sbuf[2] == '0' && + sbuf[3] == '.' && sbuf[4] == '5' && sbuf[5] == '5' + && sbuf[6] == '3' && sbuf[7] == '4' && sbuf[8] == '\0') { + printf("\t success: printf(\"%%8.4f\", -0.553415) == %8.4f\n", -0.553415); + } else { + printf("\t FAIL: printf(\"%%8.4f\", -0.553415) != \" -0.5534\", result: %s\n", sbuf); + ret = -13; + } + + + if (ret == 0) { + printf("\n SUCCESS: All float and double tests passed.\n"); + + } else { + printf("\n FAIL: One or more tests failed.\n"); + } + + printf("\n"); + + return ret; +} diff --git a/pool/shard004/C/0097128_dbcReader.c b/pool/shard004/C/0097128_dbcReader.c new file mode 100644 index 0000000000000000000000000000000000000000..a16df93ed45adc574c464b074c53ac31251e0011 --- /dev/null +++ b/pool/shard004/C/0097128_dbcReader.c @@ -0,0 +1,74 @@ +/* dbcReader.c -- frontend for DBC parser + Copyright (C) 2007-2009 Andreas Heitmann + + 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 + +typedef struct yy_buffer_state *YY_BUFFER_STATE; + +#include "src/libcandbc/dbcModel.h" +#include "src/libcandbc/dbcReader.h" + +dbc_t *dbc_read_file(char *filename) +{ + extern void yyrestart( FILE *input_file ); + extern YY_BUFFER_STATE yy_create_buffer( FILE *file, int size ); + extern void yy_switch_to_buffer ( YY_BUFFER_STATE new_buffer ); + extern char *current_yacc_file; + extern FILE *yyin; + extern int yyparse (void *YYPARSE_PARAM); + extern void yy_delete_buffer ( YY_BUFFER_STATE b ); + int error; + YY_BUFFER_STATE bufstate; + + CREATE(dbc_t, dbc); + if(dbc != NULL) { + current_yacc_file = filename; + + if(filename != NULL) { + yyin = fopen (filename, "r"); + if (yyin == NULL) { + fprintf(stderr,"error: can't open the dbc file '%s' for reading\n", + filename); + dbc_free(dbc); + return NULL; + } + } else { + yyin = stdin; + } + + yyrestart(yyin); + + bufstate = (void *)yy_create_buffer (yyin, 65535); + yy_switch_to_buffer (bufstate); + error = yyparse ((void *)dbc); + yy_delete_buffer (bufstate); + fclose (yyin); + + /* set filename */ + if(error == 0) { + if(filename != NULL) { + dbc->filename = strdup(filename); + } else { + dbc->filename = strdup(""); + } + } else { + dbc->filename = NULL; + } + } + + return dbc; +} diff --git a/pool/shard004/C/0097133_mlcp_direct_enum.c b/pool/shard004/C/0097133_mlcp_direct_enum.c new file mode 100644 index 0000000000000000000000000000000000000000..30dd4957edd82af331ebbc508a25a85ab34a2c4f --- /dev/null +++ b/pool/shard004/C/0097133_mlcp_direct_enum.c @@ -0,0 +1,133 @@ +/* Siconos is a program dedicated to modeling, simulation and control + * of non smooth dynamical systems. + * + * Copyright 2018 INRIA. + * + * 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. + */ + +/* +|A C| |u| |a| |0| +| |*| |+| |=| | +|D B| |v| |b| |w| +00 +dim(u)=mm +dim(v)=nn + +**************************************************************************/ + +#include +#include +#include +#include "MLCP_Solvers.h" +#include "SiconosCompat.h" +#include +#include "mlcp_direct_enum.h" +#include "mlcp_direct.h" +#include "mlcp_enum.h" +#include "mlcp_tool.h" + +static int sN; +static int sM; + +static int * siWorkEnum = 0; +static int * siWorkDirect = 0; +static double * sdWorkEnum = 0; +static double * sdWorkDirect = 0; + +int mixedLinearComplementarity_directEnum_setDefaultSolverOptions(MixedLinearComplementarityProblem* problem, SolverOptions* pSolver) +{ + mixedLinearComplementarity_default_setDefaultSolverOptions(problem, pSolver); + return 0; +} + +int mlcp_direct_enum_getNbIWork(MixedLinearComplementarityProblem* problem, SolverOptions* options) +{ + return mlcp_direct_getNbIWork(problem, options) + mlcp_enum_getNbIWork(problem, options); +} +int mlcp_direct_enum_getNbDWork(MixedLinearComplementarityProblem* problem, SolverOptions* options) +{ + return mlcp_direct_getNbDWork(problem, options) + mlcp_enum_getNbDWork(problem, options); +} + + + +/* + *options->iparam[5] : n0 number of possible configuration. + * dparam[5] : (in) a positive value, tolerane about the sign. + *options->iWork : double work memory of mlcp_direct_enum_getNbIWork() integers (2(nn+mm))+((n + m)*(n0+1) + nO*m) + *options->dWork : double work memory of mlcp_direct_enum_getNbDWork() doubles ((nn+mm)*(nn+mm) + 3*(nn+mm))+(n + m + n0*(n+m)*(n+m)) + * + * + */ + +void mlcp_direct_enum_init(MixedLinearComplementarityProblem* problem, SolverOptions* options) +{ + sN = problem->n; + sM = problem->m; + int iOffset = mlcp_direct_getNbIWork(problem, options); + int dOffset = mlcp_direct_getNbDWork(problem, options); + siWorkEnum = options->iWork + iOffset; + siWorkDirect = options->iWork; + sdWorkEnum = options->dWork + dOffset; + sdWorkDirect = options->dWork; + mlcp_direct_init(problem, options); + +} +void mlcp_direct_enum_reset() +{ + mlcp_direct_reset(); + siWorkEnum = 0; + siWorkDirect = 0; + sdWorkEnum = 0; + sdWorkDirect = 0; +} + +/* + * The are no memory allocation in mlcp_direct, all necessary memory must be allocated by the user. + * + *options: + * iparam[0] : (in) verbose. + * dparam[0] : (in) a positive value, tolerane about the sign used by the enum algo. + * iparam[5] : (in) n0 number of possible configuration. + * dparam[5] : (in) a positive value, tolerane about the sign. + * dWork : working float zone size : n + m + n0*(n+m)*(n+m) . MUST BE ALLOCATED BY THE USER. + * iWork : working int zone size : (n + m)*(n0+1) + nO*m. MUST BE ALLOCATED BY THE USER. + * double *z : size n+m + * double *w : size n+m + * info : output. info == 0 if success + */ +void mlcp_direct_enum(MixedLinearComplementarityProblem* problem, double *z, double *w, int *info, SolverOptions* options) +{ + if (!siWorkEnum) + { + *info = 1; + printf("MLCP_DIRECT_ENUM error, call a non initialised method!!!!!!!!!!!!!!!!!!!!!\n"); + return; + } + /*First, try direct solver*/ + options->dWork = sdWorkDirect; + options->iWork = siWorkDirect; + mlcp_direct(problem, z, w, info, options); + if (*info) + { + options->dWork = sdWorkEnum; + options->iWork = siWorkEnum; + /*solver direct failed, so run the enum solver.*/ + mlcp_enum(problem, z, w, info, options); + if (!(*info)) + { + mlcp_direct_addConfigFromWSolution(problem, w + sN); + } + } +} diff --git a/pool/shard004/C/0097136_gcr-combo-selector.c b/pool/shard004/C/0097136_gcr-combo-selector.c new file mode 100644 index 0000000000000000000000000000000000000000..f890a3c8a941e4748d2e2b5d755d35fe65d65fc8 --- /dev/null +++ b/pool/shard004/C/0097136_gcr-combo-selector.c @@ -0,0 +1,272 @@ +/* + * gnome-keyring + * + * Copyright (C) 2010 Stefan Walter + * + * 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., 59 Temple Place - Suite 330, Boston, MA + * 02111-1307, USA. + */ + +#include "config.h" + +#include "gcr-collection-model.h" +#include "gcr-internal.h" +#include "gcr-combo-selector.h" + +#include + +#include + +/** + * SECTION:gcr-combo-selector + * @title: GcrComboSelector + * @short_description: A selector widget to select a single certificate or key. + * + * The #GcrComboSelector can be used to select a certificate or key. It allows + * the user to select one object from the selector at a time. + */ + +/** + * GcrComboSelector: + * @parent: Parent object + * + * A combo selector widget. + */ + +/** + * GcrComboSelectorClass: + * + * The class for #GcrComboSelector. + */ + +enum { + PROP_0, + PROP_COLLECTION +}; + +struct _GcrComboSelectorPrivate { + GcrCollection *collection; + GcrCollectionModel *model; +}; + +G_DEFINE_TYPE (GcrComboSelector, gcr_combo_selector, GTK_TYPE_COMBO_BOX); + +/* ----------------------------------------------------------------------------- + * INTERNAL + */ + +/* ----------------------------------------------------------------------------- + * OBJECT + */ + +static GObject* +gcr_combo_selector_constructor (GType type, guint n_props, GObjectConstructParam *props) +{ + GcrComboSelector *self = GCR_COMBO_SELECTOR (G_OBJECT_CLASS (gcr_combo_selector_parent_class)->constructor(type, n_props, props)); + GtkCellRenderer *cell; + + g_return_val_if_fail (self, NULL); + + self->pv->model = gcr_collection_model_new (self->pv->collection, + "icon", G_TYPE_ICON, + "markup", G_TYPE_STRING, + NULL); + + gtk_combo_box_set_model (GTK_COMBO_BOX (self), GTK_TREE_MODEL (self->pv->model)); + + /* The icon */ + cell = gtk_cell_renderer_pixbuf_new (); + g_object_set (cell, "stock-size", GTK_ICON_SIZE_DND, NULL); + gtk_cell_layout_pack_start (GTK_CELL_LAYOUT (self), cell, FALSE); + gtk_cell_layout_add_attribute (GTK_CELL_LAYOUT (self), cell, "gicon", 0); + + /* The markup */ + cell = gtk_cell_renderer_text_new (); + gtk_cell_layout_pack_start (GTK_CELL_LAYOUT (self), cell, TRUE); + gtk_cell_layout_add_attribute (GTK_CELL_LAYOUT (self), cell, "markup", 1); + + return G_OBJECT (self); +} + +static void +gcr_combo_selector_init (GcrComboSelector *self) +{ + self->pv = G_TYPE_INSTANCE_GET_PRIVATE (self, GCR_TYPE_COMBO_SELECTOR, GcrComboSelectorPrivate); +} + +static void +gcr_combo_selector_dispose (GObject *obj) +{ + GcrComboSelector *self = GCR_COMBO_SELECTOR (obj); + + if (self->pv->model) + g_object_unref (self->pv->model); + self->pv->model = NULL; + + if (self->pv->collection) + g_object_unref (self->pv->collection); + self->pv->collection = NULL; + + G_OBJECT_CLASS (gcr_combo_selector_parent_class)->dispose (obj); +} + +static void +gcr_combo_selector_finalize (GObject *obj) +{ + GcrComboSelector *self = GCR_COMBO_SELECTOR (obj); + + g_assert (!self->pv->collection); + g_assert (!self->pv->model); + + G_OBJECT_CLASS (gcr_combo_selector_parent_class)->finalize (obj); +} + +static void +gcr_combo_selector_set_property (GObject *obj, guint prop_id, const GValue *value, + GParamSpec *pspec) +{ + GcrComboSelector *self = GCR_COMBO_SELECTOR (obj); + + switch (prop_id) { + case PROP_COLLECTION: + g_return_if_fail (!self->pv->collection); + self->pv->collection = g_value_dup_object (value); + g_return_if_fail (self->pv->collection); + break; + default: + G_OBJECT_WARN_INVALID_PROPERTY_ID (obj, prop_id, pspec); + break; + } +} + +static void +gcr_combo_selector_get_property (GObject *obj, guint prop_id, GValue *value, + GParamSpec *pspec) +{ + GcrComboSelector *self = GCR_COMBO_SELECTOR (obj); + + switch (prop_id) { + case PROP_COLLECTION: + g_value_set_object (value, gcr_combo_selector_get_collection (self)); + break; + default: + G_OBJECT_WARN_INVALID_PROPERTY_ID (obj, prop_id, pspec); + break; + } +} + +static void +gcr_combo_selector_class_init (GcrComboSelectorClass *klass) +{ + GObjectClass *gobject_class = G_OBJECT_CLASS (klass); + + gobject_class->constructor = gcr_combo_selector_constructor; + gobject_class->dispose = gcr_combo_selector_dispose; + gobject_class->finalize = gcr_combo_selector_finalize; + gobject_class->set_property = gcr_combo_selector_set_property; + gobject_class->get_property = gcr_combo_selector_get_property; + + g_type_class_add_private (gobject_class, sizeof (GcrComboSelectorPrivate)); + + /** + * GcrComboSelector:collection: + * + * The collection which contains the objects to display in the selector. + */ + g_object_class_install_property (gobject_class, PROP_COLLECTION, + g_param_spec_object ("collection", "Collection", "Collection to select from", + GCR_TYPE_COLLECTION, G_PARAM_READWRITE | G_PARAM_CONSTRUCT_ONLY)); + + _gcr_initialize (); +} + +/* ----------------------------------------------------------------------------- + * PUBLIC + */ + +/** + * gcr_selector_new: + * @collection: The collection that contains the objects to display + * + * Create a new #GcrTreeSelector. + * + * Returns: A newly allocated selector, which should be released with + * g_object_unref(). + */ +GcrComboSelector* +gcr_combo_selector_new (GcrCollection *collection) +{ + return g_object_new (GCR_TYPE_COMBO_SELECTOR, + "collection", collection, + NULL); +} + +/** + * gcr_combo_selector_get_collection: + * @self: The selector + * + * Get the collection that this selector is displaying objects from. + * + * Returns: The collection, owned by the selector. + */ +GcrCollection* +gcr_combo_selector_get_collection (GcrComboSelector *self) +{ + g_return_val_if_fail (GCR_IS_COMBO_SELECTOR (self), NULL); + return self->pv->collection; +} + +/** + * gcr_combo_selector_get_selected: + * @self: The selector + * + * Get the selected object in the selector, or %NULL if nothing selected. + * + * Returns: The selected object, owned by the selector, or %NULL. + */ +GObject* +gcr_combo_selector_get_selected (GcrComboSelector *self) +{ + GtkTreeIter iter; + + g_return_val_if_fail (GCR_IS_COMBO_SELECTOR (self), NULL); + gtk_combo_box_get_active_iter (GTK_COMBO_BOX (self), &iter); + + return gcr_collection_model_object_for_iter (self->pv->model, &iter); +} + +/** + * gcr_combo_selector_set_selected: + * @self: The selector + * @selected: The object to select or %NULL. + * + * Set the currently selected object in the selector, or clear the selection + * if selected is set to %NULL. + */ +void +gcr_combo_selector_set_selected (GcrComboSelector *self, GObject *selected) +{ + GtkTreeIter iter; + + g_return_if_fail (GCR_IS_COMBO_SELECTOR (self)); + + if (selected) { + if (!gcr_collection_model_iter_for_object (self->pv->model, selected, &iter)) + g_return_if_reached (); + gtk_combo_box_set_active_iter (GTK_COMBO_BOX (self), &iter); + } else { + gtk_combo_box_set_active_iter (GTK_COMBO_BOX (self), NULL); + } +} diff --git a/pool/shard004/C/0097142_bufr_pthreads.c b/pool/shard004/C/0097142_bufr_pthreads.c new file mode 100644 index 0000000000000000000000000000000000000000..f1a7dda43070b6086a688e29ebe64f320c9ca25d --- /dev/null +++ b/pool/shard004/C/0097142_bufr_pthreads.c @@ -0,0 +1,70 @@ +/* + * 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 +#include +#include +#include + +#include "eccodes.h" +#define NUM_THREADS 3 + +static int DBL_EQUAL(double d1, double d2, double tolerance) +{ + return fabs(d1-d2) <= tolerance; +} + +static void* process_bufr(void* arg) +{ + codes_handle* h = (codes_handle*)arg; + long numSubsets = 0; + size_t size = 0; + double* dValues = NULL; + + CODES_CHECK(codes_set_long(h, "unpack", 1),0); + CODES_CHECK(codes_get_long(h,"numberOfSubsets", &numSubsets),0); + /*printf("numberOfSubsets=%ld\n", numSubsets);*/ + assert( numSubsets == 2016 || numSubsets == 128 ); + + dValues = (double*)malloc(numSubsets*sizeof(double)); + assert(dValues); + size = numSubsets; + CODES_CHECK(codes_get_double_array(h, "latitude", dValues, &size), 0); + assert( DBL_EQUAL(dValues[0], 43.119, 0.01) || DBL_EQUAL(dValues[0], -58.174, 0.01) ); + + free(dValues); + pthread_exit(NULL); +} + +int main(int argc, char** argv) +{ + pthread_t thread1, thread2; + int err = 0; + FILE* fin = 0; + codes_handle* h1 = 0; + codes_handle* h2 = 0; + fin = fopen("../../data/bufr/asca_139.bufr", "r"); + h1 = codes_handle_new_from_file(NULL, fin, PRODUCT_BUFR, &err); assert(h1); + fclose(fin); + fin = fopen("../../data/bufr/aaen_55.bufr", "r"); + h2 = codes_handle_new_from_file(NULL, fin, PRODUCT_BUFR, &err); assert(h2); + fclose(fin); + + err = pthread_create(&thread1, NULL, process_bufr, (void *)h1); + assert(!err); + + err = pthread_create(&thread2, NULL, process_bufr, (void *)h2); + assert(!err); + + pthread_join(thread1, NULL); + pthread_join(thread2, NULL); + codes_handle_delete(h1); + codes_handle_delete(h2); + return 0; +} diff --git a/pool/shard004/C/0097148_swaponoff.c b/pool/shard004/C/0097148_swaponoff.c new file mode 100644 index 0000000000000000000000000000000000000000..9f730d186dcfe1105cf25027a6522dc571d11286 --- /dev/null +++ b/pool/shard004/C/0097148_swaponoff.c @@ -0,0 +1,141 @@ +/* vi: set sw=4 ts=4: */ +/* + * Mini swapon/swapoff implementation for busybox + * + * Copyright (C) 1999-2004 by Erik Andersen + * + * Licensed under GPLv2, see file LICENSE in this source tree. + */ + +//usage:#define swapon_trivial_usage +//usage: "[-a]" IF_FEATURE_SWAPON_PRI(" [-p PRI]") " [DEVICE]" +//usage:#define swapon_full_usage "\n\n" +//usage: "Start swapping on DEVICE\n" +//usage: "\n -a Start swapping on all swap devices" +//usage: IF_FEATURE_SWAPON_PRI( +//usage: "\n -p PRI Set swap device priority" +//usage: ) +//usage: +//usage:#define swapoff_trivial_usage +//usage: "[-a] [DEVICE]" +//usage:#define swapoff_full_usage "\n\n" +//usage: "Stop swapping on DEVICE\n" +//usage: "\n -a Stop swapping on all swap devices" + +#include "libbb.h" +#include "xmount.h" +#include + +#if ENABLE_FEATURE_MOUNT_LABEL +# include "volume_id.h" +#else +# define resolve_mount_spec(fsname) ((void)0) +#endif + +#ifndef MNTTYPE_SWAP +# define MNTTYPE_SWAP "swap" +#endif + +#if ENABLE_FEATURE_SWAPON_PRI +struct globals { + int flags; +} FIX_ALIASING; +#define G (*(struct globals*)&bb_common_bufsiz1) +#define g_flags (G.flags) +#else +#define g_flags 0 +#endif +#define INIT_G() do { } while (0) + +static int swap_enable_disable(char *device) +{ + int status; + struct stat st; + + resolve_mount_spec(&device); + xstat(device, &st); + +#if ENABLE_DESKTOP + /* test for holes */ + if (S_ISREG(st.st_mode)) + if (st.st_blocks * (off_t)512 < st.st_size) + bb_error_msg("warning: swap file has holes"); +#endif + + if (applet_name[5] == 'n') + status = xswapon(device, g_flags); + else + status = xswapoff(device); + + if (status != 0) { + bb_simple_perror_msg(device); + return 1; + } + + return 0; +} + +static int do_em_all(void) +{ + struct mntent *m; + FILE *f; + int err; + + f = setmntent("/etc/fstab", "r"); + if (f == NULL) + bb_perror_msg_and_die("/etc/fstab"); + + err = 0; + while ((m = getmntent(f)) != NULL) { + if (strcmp(m->mnt_type, MNTTYPE_SWAP) == 0) { + /* swapon -a should ignore entries with noauto, + * but swapoff -a should process them */ + if (applet_name[5] != 'n' + || hasmntopt(m, MNTOPT_NOAUTO) == NULL + ) { + err += swap_enable_disable(m->mnt_fsname); + } + } + } + + if (ENABLE_FEATURE_CLEAN_UP) + endmntent(f); + + return err; +} + +int swap_on_off_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE; +int swap_on_off_main(int argc UNUSED_PARAM, char **argv) +{ + int ret; + + INIT_G(); + +#if !ENABLE_FEATURE_SWAPON_PRI + ret = getopt32(argv, "a"); +#else + if (applet_name[5] == 'n') + opt_complementary = "p+"; + ret = getopt32(argv, (applet_name[5] == 'n') ? "ap:" : "a", &g_flags); + + if (ret & 2) { // -p + g_flags = SWAP_FLAG_PREFER | + ((g_flags & SWAP_FLAG_PRIO_MASK) << SWAP_FLAG_PRIO_SHIFT); + ret &= 1; + } +#endif + + if (ret /* & 1: not needed */) // -a + return do_em_all(); + + argv += optind; + if (!*argv) + bb_show_usage(); + + /* ret = 0; redundant */ + do { + ret += swap_enable_disable(*argv); + } while (*++argv); + + return ret; +} diff --git a/pool/shard004/C/0097149_osunixmap.c b/pool/shard004/C/0097149_osunixmap.c new file mode 100644 index 0000000000000000000000000000000000000000..44ad4889d468cad4b576e39eaad4ef5ba3844b07 --- /dev/null +++ b/pool/shard004/C/0097149_osunixmap.c @@ -0,0 +1,151 @@ +/****************************************************************************** + * + * Module Name: osunixmap - Unix OSL for file mappings + * + *****************************************************************************/ + +/* + * Copyright (C) 2000 - 2015, Intel Corp. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions, and the following disclaimer, + * without modification. + * 2. Redistributions in binary form must reproduce at minimum a disclaimer + * substantially similar to the "NO WARRANTY" disclaimer below + * ("Disclaimer") and any redistribution must be conditioned upon + * including a substantially similar Disclaimer requirement for further + * binary redistribution. + * 3. Neither the names of the above-listed copyright holders nor the names + * of any contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * Alternatively, this software may be distributed under the terms of the + * GNU General Public License ("GPL") version 2 as published by the Free + * Software Foundation. + * + * NO WARRANTY + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * HOLDERS OR CONTRIBUTORS BE LIABLE FOR SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, + * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGES. + */ + +#include "acpidump.h" +#include +#include +#ifdef _free_BSD +#include +#endif + +#define _COMPONENT ACPI_OS_SERVICES +ACPI_MODULE_NAME("osunixmap") + +#ifndef O_BINARY +#define O_BINARY 0 +#endif +#if defined(_dragon_fly) || defined(_free_BSD) +#define MMAP_FLAGS MAP_SHARED +#else +#define MMAP_FLAGS MAP_PRIVATE +#endif +#define SYSTEM_MEMORY "/dev/mem" +/******************************************************************************* + * + * FUNCTION: acpi_os_get_page_size + * + * PARAMETERS: None + * + * RETURN: Page size of the platform. + * + * DESCRIPTION: Obtain page size of the platform. + * + ******************************************************************************/ +static acpi_size acpi_os_get_page_size(void) +{ + +#ifdef PAGE_SIZE + return PAGE_SIZE; +#else + return sysconf(_SC_PAGESIZE); +#endif +} + +/****************************************************************************** + * + * FUNCTION: acpi_os_map_memory + * + * PARAMETERS: where - Physical address of memory to be mapped + * length - How much memory to map + * + * RETURN: Pointer to mapped memory. Null on error. + * + * DESCRIPTION: Map physical memory into local address space. + * + *****************************************************************************/ + +void *acpi_os_map_memory(acpi_physical_address where, acpi_size length) +{ + u8 *mapped_memory; + acpi_physical_address offset; + acpi_size page_size; + int fd; + + fd = open(SYSTEM_MEMORY, O_RDONLY | O_BINARY); + if (fd < 0) { + fprintf(stderr, "Cannot open %s\n", SYSTEM_MEMORY); + return (NULL); + } + + /* Align the offset to use mmap */ + + page_size = acpi_os_get_page_size(); + offset = where % page_size; + + /* Map the table header to get the length of the full table */ + + mapped_memory = mmap(NULL, (length + offset), PROT_READ, MMAP_FLAGS, + fd, (where - offset)); + if (mapped_memory == MAP_FAILED) { + fprintf(stderr, "Cannot map %s\n", SYSTEM_MEMORY); + close(fd); + return (NULL); + } + + close(fd); + return (ACPI_CAST8(mapped_memory + offset)); +} + +/****************************************************************************** + * + * FUNCTION: acpi_os_unmap_memory + * + * PARAMETERS: where - Logical address of memory to be unmapped + * length - How much memory to unmap + * + * RETURN: None. + * + * DESCRIPTION: Delete a previously created mapping. Where and Length must + * correspond to a previous mapping exactly. + * + *****************************************************************************/ + +void acpi_os_unmap_memory(void *where, acpi_size length) +{ + acpi_physical_address offset; + acpi_size page_size; + + page_size = acpi_os_get_page_size(); + offset = ACPI_TO_INTEGER(where) % page_size; + munmap((u8 *)where - offset, (length + offset)); +} diff --git a/pool/shard004/C/0097156_iniparser_count_sections.c b/pool/shard004/C/0097156_iniparser_count_sections.c new file mode 100644 index 0000000000000000000000000000000000000000..3e1696512f07576dd7bbe406ad3518dd61ad99ae --- /dev/null +++ b/pool/shard004/C/0097156_iniparser_count_sections.c @@ -0,0 +1,27 @@ +#include "../../include/iniparser.h" + +static inline int iswhitespace(char* p) { + return *p == '\t' || *p == ' '; +} + +static inline size_t getlastnonwhitespace(const stringptr* s) { + size_t res = s->size; + while(res && iswhitespace(s->ptr + (res - 1))) res--; + return res; +} + +size_t iniparser_count_sections(stringptrlist* inifile) { + size_t result = 0; + stringptr* line; + size_t i, n; + for(i = 0; i < stringptrlist_getsize(inifile); i++) { + line = stringptrlist_get(inifile, i); + if(!line) continue; // this should never happen... + if(line->size >= 3 && *line->ptr == '[') { + n = getlastnonwhitespace(line); + if(n && line->ptr[n - 1] == ']') + result++; + } + } + return result; +} diff --git a/pool/shard004/C/0097157_lcd.c b/pool/shard004/C/0097157_lcd.c new file mode 100644 index 0000000000000000000000000000000000000000..56228ac6b8c89050fefc72e67bdb9bb951d97932 --- /dev/null +++ b/pool/shard004/C/0097157_lcd.c @@ -0,0 +1,198 @@ +/* + This project is free software: you can 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. + + Deviation is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with Deviation. If not, see . +*/ +#include +#include +#include +#include "common.h" +#include "gui/gui.h" + +#define CS_HI() gpio_set(GPIOB, GPIO0) +#define CS_LO() gpio_clear(GPIOB, GPIO0) +#define CMD_MODE() gpio_clear(GPIOC,GPIO5) +#define DATA_MODE() gpio_set(GPIOC,GPIO5) + +//The screen is 129 characters, but we'll only expoise 128 of them +#define PHY_LCD_WIDTH 129 +#define LCD_PAGES 8 +static u8 img[PHY_LCD_WIDTH * LCD_PAGES]; +static u8 dirty[PHY_LCD_WIDTH]; +static u16 xstart, xend; // After introducing logical view for devo10, the coordinate can be >= 5000 +static u16 xpos, ypos; +static s8 dir; + +void LCD_Cmd(unsigned cmd) { + CMD_MODE(); + CS_LO(); + spi_xfer(SPI1, cmd); + CS_HI(); +} + +void LCD_Data(unsigned cmd) { + DATA_MODE(); + CS_LO(); + spi_xfer(SPI1, cmd); + CS_HI(); +} + +void lcd_display(uint8_t on) +{ + LCD_Cmd(0xAE | (on ? 1 : 0)); +} + +void lcd_set_page_address(uint8_t page) +{ + LCD_Cmd(0xB0 | (page & 0x07)); +} + +void lcd_set_column_address(uint8_t column) +{ + LCD_Cmd(0x10 | ((column >> 4) & 0x0F)); //MSB + LCD_Cmd(column & 0x0F); //LSB +} + +void lcd_set_start_line(int line) +{ + LCD_Cmd((line & 0x3F) | 0x40); +} + +void LCD_Contrast(unsigned contrast) +{ + //int data = 0x20 + contrast * 0xC / 10; + LCD_Cmd(0x81); + int c = contrast * 12 + 76; //contrast should range from ~72 to ~200 + LCD_Cmd(c); +} + +void LCD_Init() +{ + //Initialization is mostly done in SPI Flash + //Setup CS as B.0 Data/Control = C.5 + rcc_peripheral_enable_clock(&RCC_APB2ENR, RCC_APB2ENR_IOPBEN); + rcc_peripheral_enable_clock(&RCC_APB2ENR, RCC_APB2ENR_IOPCEN); + gpio_set_mode(GPIOB, GPIO_MODE_OUTPUT_50_MHZ, + GPIO_CNF_OUTPUT_PUSHPULL, GPIO0); + gpio_set_mode(GPIOC, GPIO_MODE_OUTPUT_50_MHZ, + GPIO_CNF_OUTPUT_PUSHPULL, GPIO5); + LCD_Cmd(0xE2); //Reset + volatile int i = 0x8000; + while(i) i--; + LCD_Cmd(0xAE); //Display off + LCD_Cmd(0xA6); //Normal display + LCD_Cmd(0xA4); //All Points Normal + LCD_Cmd(0xEA); //?? + LCD_Cmd(0xA0); //ADC Normal + LCD_Cmd(0xC4); //Common Output Mode Scan Rate + LCD_Cmd(0x2C); //Power Controller:Booster ON + i = 0x8000; + while(i) i--; + LCD_Cmd(0x2E); //Power Controller: VReg ON + i = 0x8000; + while(i) i--; + LCD_Cmd(0x2F); //Power Controller: VFollower ON + i = 0x8000; + while(i) i--; + lcd_set_start_line(0); + // Display data write (6) + //Clear the screen + for(int page = 0; page < LCD_PAGES; page++) { + lcd_set_page_address(page); + lcd_set_column_address(0); + for(int col = 0; col < PHY_LCD_WIDTH; col++) + LCD_Data(0x00); + } + lcd_display(1); + LCD_Contrast(5); + memset(img, 0, sizeof(img)); + memset(dirty, 0, sizeof(dirty)); +} + +void LCD_Clear(unsigned int val) +{ + val = (val & 0xFF) ? 0xff : 0x00; + memset(img, val, sizeof(img)); + memset(dirty, 0xFF, sizeof(dirty)); +} + +void LCD_DrawStart(unsigned int x0, unsigned int y0, unsigned int x1, unsigned int y1, enum DrawDir _dir) +{ + if (_dir == DRAW_SWNE) { + ypos = y1; // bug fix: must do it this way to draw bmp + dir = -1; + } else { + ypos = y0; + dir = 1; + } + xstart = x0; + xend = x1; + xpos = x0; +} +/* Screen coordinates are as follows: + * (128, 32) .... (0, 32) + * ... .... ... + * (128, 63) .... (0, 63) + * (128, 0) .... (0, 0) + * ... .... ... + * (128, 31) .... (0, 31) + */ +void LCD_DrawStop(void) +{ + int col = 0; + int p, c; + for (p = 0; p < LCD_PAGES; p++) { + int init = 0; + for (c = 0; c < PHY_LCD_WIDTH; c++) { + if(dirty[c] & (1 << p)) { + if(! init) { + lcd_set_page_address(p); + lcd_set_column_address(c); + } else if(col+1 != c) { + lcd_set_column_address(c); + } + LCD_Data(img[p * PHY_LCD_WIDTH + c]); + col = c; + } + } + } + memset(dirty, 0, sizeof(dirty)); +} + +void LCD_DrawPixel(unsigned int color) +{ + if (xpos < LCD_WIDTH && ypos < LCD_HEIGHT) { // both are unsigned, can not be < 0 + int y = ypos; + int x = xpos; + int ycol = y / 8; + int ybit = y & 0x07; + if (color) { + img[ycol * PHY_LCD_WIDTH + x] |= 1 << ybit; + } else { + img[ycol * PHY_LCD_WIDTH + x] &= ~(1 << ybit); + } + dirty[x] |= 1 << ycol; + } + // this must be executed to continue drawing in the next row + xpos++; + if (xpos > xend) { + xpos = xstart; + ypos += dir; + } +} + +void LCD_DrawPixelXY(unsigned int x, unsigned int y, unsigned int color) +{ + xpos = x; + ypos = y; + LCD_DrawPixel(color); +} diff --git a/pool/shard004/C/0097161_vnode_chnl.c b/pool/shard004/C/0097161_vnode_chnl.c new file mode 100644 index 0000000000000000000000000000000000000000..122f73b6a7d4d0d45009ec0c147d59a777feec00 --- /dev/null +++ b/pool/shard004/C/0097161_vnode_chnl.c @@ -0,0 +1,114 @@ +/* + * CORE + * Copyright (c)2010-2012 the Boeing Company. + * See the LICENSE file included in this distribution. + * + * author: Tom Goff + * + * vnode_chnl.c + * + * Functions for setting up a local UNIX socket to use as a control channel + * for interacting with a network namespace. + * + */ + +#include +#include +#include +#include + +#include +#include + +#include "vnode_msg.h" +#include "vnode_tlv.h" +#include "vnode_chnl.h" +#include "vnode_io.h" + +extern int verbose; + + +int vnode_connect(const char *name) +{ + int fd; + struct sockaddr_un addr; + +#ifdef DEBUG + WARNX("opening '%s'", name); +#endif + + if (strlen(name) > sizeof(addr.sun_path) - 1) + { + WARNX("name too long: '%s'", name); + return -1; + } + + if ((fd = socket(AF_UNIX, SOCK_SEQPACKET, 0)) < 0) + { + WARN("socket() failed"); + return -1; + } + + addr.sun_family = AF_UNIX; + strcpy(addr.sun_path, name); + if (connect(fd, (struct sockaddr *)&addr, sizeof(addr)) < 0) + { + WARN("connect() failed for '%s'", name); + close(fd); + return -1; + } + + if (set_nonblock(fd)) + WARN("set_nonblock() failed for fd %d", fd); + + return fd; +} + +int vnode_listen(const char *name) +{ + int fd; + struct sockaddr_un addr; + +#ifdef DEBUG + WARNX("opening '%s'", name); +#endif + + if (strlen(name) > sizeof(addr.sun_path) - 1) + { + WARNX("name too long: '%s'", name); + return -1; + } + + if ((fd = socket(AF_UNIX, SOCK_SEQPACKET, 0)) < 0) + { + WARN("socket() failed"); + return -1; + } + + unlink(name); + addr.sun_family = AF_UNIX; + strcpy(addr.sun_path, name); + + if (bind(fd, (struct sockaddr *)&addr, sizeof(addr)) < 0) + { + WARN("bind() failed for '%s'", name); + close(fd); + return -1; + } + + /* to override umask */ + if (chmod(name, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH)) + WARN("fchmod() failed for '%s'", name); + + if (listen(fd, 5) < 0) + { + WARN("listen() failed"); + close(fd); + return -1; + } + + if (set_nonblock(fd)) + WARN("set_nonblock() failed for fd %d", fd); + + return fd; +} diff --git a/pool/shard004/C/0097162_max_bits.c b/pool/shard004/C/0097162_max_bits.c new file mode 100644 index 0000000000000000000000000000000000000000..ccc5a1e4c554b4a02192c8e0eb1e41ef57d6930d --- /dev/null +++ b/pool/shard004/C/0097162_max_bits.c @@ -0,0 +1,43 @@ +/* + Copyright (C) 2011 Fredrik Johansson + + 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 "flint.h" +#include "fmpz_poly.h" +#include "fmpz_poly_mat.h" + +slong +fmpz_poly_mat_max_bits(const fmpz_poly_mat_t A) +{ + slong i, j, bits, max; + int sign; + + max = 0; + sign = 0; + + for (i = 0; i < A->r; i++) + { + for (j = 0; j < A->c; j++) + { + bits = fmpz_poly_max_bits(fmpz_poly_mat_entry(A, i, j)); + + if (bits < 0) + { + sign = 1; + max = FLINT_MAX(max, -bits); + } + else + max = FLINT_MAX(max, bits); + } + } + + return sign ? -max : max; +} diff --git a/pool/shard004/C/0097164_set.c b/pool/shard004/C/0097164_set.c new file mode 100644 index 0000000000000000000000000000000000000000..915d4e75e851ea90cf005f656f9f8652208773a3 --- /dev/null +++ b/pool/shard004/C/0097164_set.c @@ -0,0 +1,58 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "ogh.h" + + +void set_tt(struct timetable *tt) +{ + int i; + char fin; + int num; + + printf("입력할 시간표 수 >> "); + scanf("%d", &num); + + for(i=0; i < num; i++){ + printf("%d번째 시간표\n", i+1); + + printf("요일 : "); + scanf("%d", &tt[i].wday); + + printf("Start hour : "); + scanf("%d", &tt[i].st_hour); + + printf("Start minute : "); + scanf("%d", &tt[i].st_min); + + printf("End hour : "); + scanf("%d", &tt[i].end_hour); + + printf("End minute : "); + scanf("%d", &tt[i].end_min); + + tt[i].st_year = 2014; + tt[i].st_month = 9; + tt[i].st_date = 1; + tt[i].end_year = 2014; + tt[i].end_mon = 12; + tt[i].end_date = 31; + + } +} + +int main(void) +{ + struct timetable tt[TTFS_MAX_SIZE]; + + set_tt(tt); + //syscall(__NR_set_timetable, tt, 2); + + return 0; +} diff --git a/pool/shard004/C/0097174_truncate64.c b/pool/shard004/C/0097174_truncate64.c new file mode 100644 index 0000000000000000000000000000000000000000..f2927ea8579156816957037dc71822c30b2f03a3 --- /dev/null +++ b/pool/shard004/C/0097174_truncate64.c @@ -0,0 +1,31 @@ +/* Copyright (C) 2011-2016 Free Software Foundation, Inc. + This file is part of the GNU C Library. + Contributed by Chris Metcalf , 2011. + + The GNU C Library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + The GNU C Library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with the GNU C Library. If not, see + . */ + +#include +#include +#include + +/* Truncate the file PATH to LENGTH bytes. */ +int +truncate64 (const char *path, off64_t length) +{ + unsigned int low = length & 0xffffffff; + unsigned int high = length >> 32; + return INLINE_SYSCALL (truncate64, __ALIGNMENT_COUNT (3, 4), path, + __ALIGNMENT_ARG __LONG_LONG_PAIR (high, low)); +} diff --git a/pool/shard004/C/0097178_song_print.c b/pool/shard004/C/0097178_song_print.c new file mode 100644 index 0000000000000000000000000000000000000000..16239e03b89e3503a3eaf80c4fd972aa722a89c6 --- /dev/null +++ b/pool/shard004/C/0097178_song_print.c @@ -0,0 +1,111 @@ +/* + * Copyright (C) 2003-2010 The Music Player Daemon Project + * http://www.musicpd.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 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 "song_print.h" +#include "song.h" +#include "songvec.h" +#include "directory.h" +#include "tag_print.h" +#include "client.h" +#include "uri.h" +#include "mapper.h" + +void +song_print_uri(struct client *client, struct song *song) +{ + if (song_in_database(song) && !directory_is_root(song->parent)) { + client_printf(client, "%s%s/%s\n", SONG_FILE, + directory_get_path(song->parent), song->uri); + } else { + char *allocated; + const char *uri; + + uri = allocated = uri_remove_auth(song->uri); + if (uri == NULL) + uri = song->uri; + + client_printf(client, "%s%s\n", SONG_FILE, + map_to_relative_path(uri)); + + g_free(allocated); + } +} + +void +song_print_info(struct client *client, struct song *song) +{ + song_print_uri(client, song); + + if (song->end_ms > 0) + client_printf(client, "Range: %u.%03u-%u.%03u\n", + song->start_ms / 1000, + song->start_ms % 1000, + song->end_ms / 1000, + song->end_ms % 1000); + else if (song->start_ms > 0) + client_printf(client, "Range: %u.%03u-\n", + song->start_ms / 1000, + song->start_ms % 1000); + + if (song->mtime > 0) { +#ifndef G_OS_WIN32 + struct tm tm; +#endif + const struct tm *tm2; + +#ifdef G_OS_WIN32 + tm2 = gmtime(&song->mtime); +#else + tm2 = gmtime_r(&song->mtime, &tm); +#endif + + if (tm2 != NULL) { + char timestamp[32]; + + strftime(timestamp, sizeof(timestamp), +#ifdef G_OS_WIN32 + "%Y-%m-%dT%H:%M:%SZ", +#else + "%FT%TZ", +#endif + tm2); + client_printf(client, "Last-Modified: %s\n", + timestamp); + } + } + + if (song->tag) + tag_print(client, song->tag); +} + +static int +song_print_info_x(struct song *song, void *data) +{ + struct client *client = data; + song_print_info(client, song); + + return 0; +} + +void +songvec_print(struct client *client, const struct songvec *sv) +{ + songvec_for_each(sv, song_print_info_x, client); +} diff --git a/pool/shard004/C/0097180_kern_distance.c b/pool/shard004/C/0097180_kern_distance.c new file mode 100644 index 0000000000000000000000000000000000000000..f60fe8d5e792af5bc2bdc4440fea13239313f430 --- /dev/null +++ b/pool/shard004/C/0097180_kern_distance.c @@ -0,0 +1,119 @@ +/* + * 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. + */ + +#include "config.h" +#include "common.h" +#include "hconfig.h" +#include "util.h" +#include "measures.h" +#include "vcache.h" +#include "tests.h" + +/* Global variables */ +int verbose = 0; +config_t cfg; + +/* + * Structure for testing string kernels/distances + */ +struct hstring_test +{ + char *x; /**< String x */ + char *y; /**< String y */ + char *d; /**< Distance */ + char *t; /**< Type */ + float v; /**< Expected output */ +}; + +struct hstring_test tests[] = { + /* Simple tests */ + {"a", "b", "levenshtein", "linear", 0.5}, + {"", "b", "levenshtein", "linear", 0.0}, + {"a", "", "levenshtein", "linear", 0.0}, + {"", "", "levenshtein", "linear", 0.0}, + {"a", "a", "levenshtein", "linear", 1.0}, + {"ab", "ab", "levenshtein", "linear", 4.0}, + {"ab", "ac", "levenshtein", "linear", 3.5}, + + /* Polynomial substituion */ + {"", "", "levenshtein", "poly", 1.0}, + {"a", "a", "levenshtein", "poly", 2.0}, + {"ab", "ab", "levenshtein", "poly", 5.0}, + {"ab", "ac", "levenshtein", "poly", 4.5}, + + /* RBF substituion */ + {"", "", "levenshtein", "rbf", 1}, + {"a", "a", "levenshtein", "rbf", 1}, + {"ab", "ab", "levenshtein", "rbf", 1}, + {"ab", "ac", "levenshtein", "rbf", 0.36787944117}, + + {NULL} +}; + +/** + * Test runs + * @param error flag + */ +int test_compare() +{ + int i, err = FALSE; + hstring_t x, y; + + printf("Testing distance substitution kernel "); + for (i = 0; tests[i].x && !err; i++) { + config_set_string(&cfg, "measures.kern_distance.dist", tests[i].d); + config_set_string(&cfg, "measures.kern_distance.type", tests[i].t); + measure_config("kern_distance"); + + x = hstring_init(x, tests[i].x); + y = hstring_init(y, tests[i].y); + + x = hstring_preproc(x); + y = hstring_preproc(y); + + float d = measure_compare(x, y); + double diff = fabs(tests[i].v - d); + + printf("."); + if (diff > 1e-6) { + printf("Error %f != %f\n", d, tests[i].v); + hstring_print(x); + hstring_print(y); + err = TRUE; + } + + hstring_destroy(&x); + hstring_destroy(&y); + } + printf(" done.\n"); + + return err; +} + +/** + * Main test function + */ +int main(int argc, char **argv) +{ + int err = FALSE; + + config_init(&cfg); + config_check(&cfg); + + vcache_init(); + + err |= test_compare(); + + vcache_destroy(); + + config_destroy(&cfg); + return err; +} diff --git a/pool/shard004/C/0097185_unittest.c b/pool/shard004/C/0097185_unittest.c new file mode 100644 index 0000000000000000000000000000000000000000..e6b5c1f5b4795ffdf444c7669d0025a09e223501 --- /dev/null +++ b/pool/shard004/C/0097185_unittest.c @@ -0,0 +1,118 @@ +#include +#include "rtcborsrc/osrtcbor.h" +#include "rtxsrc/rtxBuffer.h" +#include "rtxsrc/rtxError.h" +#include "rtxsrc/rtxPrint.h" + +static OSBOOL testValue +(OSCTXT* pctxt, const OSRTGenPtrArray* pExpArray, + const OSOCTET* encoding, OSSIZE encsize) +{ + int ret = rtxInitContextBuffer (pctxt, (OSOCTET*)encoding, encsize); + if (0 == ret) { + OSOCTET ub; + OSBOOL errFlag = FALSE; + + ret = rtxReadBytes (pctxt, &ub, 1); + if (0 == ret) { + OSRTGenPtrArray decval; + ret = rtCborDecArray (pctxt, ub, &decval); + if (0 == ret) { + OSSIZE i; + /* verify decode value == expected value */ + if (decval.nitems != pExpArray->nitems) { + printf ("decode failed, decoded count " OSSIZEFMT " does not " + "match expected count " OSSIZEFMT "\n", decval.nitems, + pExpArray->nitems); + return FALSE; + } + /* loop to compare decoded array values with expected */ + for (i = 0; i < decval.nitems; i++) { + ret = rtxGenValueCompare + (pctxt, decval.values[i], pExpArray->values[i]); + if (0 != ret) { + printf ("comparison of item " OSSIZEFMT " failed\n", i); + rtxErrPrint (pctxt); + errFlag = TRUE; + } + } + if (errFlag) return FALSE; + } + } + } + + if (0 != ret) { + printf ("run-time function failed:\n"); + rtxErrPrint (pctxt); + return FALSE; + } + + return TRUE; +} + +int main() +{ + OSCTXT ctxt; + int ret, errcnt = 0; + + ret = rtxInitContext (&ctxt); + if (ret != 0) { + rtxErrPrint(&ctxt); + return 1; + } + { + OSOCTET bytestr_data[] = { 0x01, 0x02, 0x03 }; + OSRTGenValue value1, value2, value3, value4; + OSRTGenValue* values[4], *innerValues[3]; + OSRTGenPtrArray ptrArray; + + value1.t = OSRTDataType_UnsignedInt; + value1.u.uintval = 22; + values[0] = innerValues[0] = &value1; + + value2.t = OSRTDataType_ByteArray; + value2.u.bytestr.numocts = sizeof(bytestr_data); + value2.u.bytestr.data = bytestr_data; + values[1] = innerValues[1] = &value2; + + value3.t = OSRTDataType_CharStr; + value3.u.utf8str = "this is a test"; + values[2] = innerValues[2] = &value3; + + value4.t = OSRTDataType_Array; + value4.u.array.nitems = 3; + value4.u.array.values = innerValues; + values[3] = &value4; + + ptrArray.nitems = 4; + ptrArray.values = values; + { + /* definite length test */ + const OSOCTET encoding[] = { + 0x84, 0x16, 0x43, 0x01, 0x02, 0x03, 0x6e, 0x74, + 0x68, 0x69, 0x73, 0x20, 0x69, 0x73, 0x20, 0x61, + 0x20, 0x74, 0x65, 0x73, 0x74, 0x83, 0x16, 0x43, + 0x01, 0x02, 0x03, 0x6e, 0x74, 0x68, 0x69, 0x73, + 0x20, 0x69, 0x73, 0x20, 0x61, 0x20, 0x74, 0x65, + 0x73, 0x74 + }; + if (!testValue (&ctxt, &ptrArray, encoding, sizeof(encoding))) + errcnt++; + } + { + /* indefinite length test */ + const OSOCTET encoding[] = { + 0x9f, 0x16, 0x43, 0x01, 0x02, 0x03, 0x6e, 0x74, + 0x68, 0x69, 0x73, 0x20, 0x69, 0x73, 0x20, 0x61, + 0x20, 0x74, 0x65, 0x73, 0x74, 0x9f, 0x16, 0x43, + 0x01, 0x02, 0x03, 0x6e, 0x74, 0x68, 0x69, 0x73, + 0x20, 0x69, 0x73, 0x20, 0x61, 0x20, 0x74, 0x65, + 0x73, 0x74, 0xff, 0xff + }; + if (!testValue (&ctxt, &ptrArray, encoding, sizeof(encoding))) + errcnt++; + } + } + + return errcnt; +} diff --git a/pool/shard004/C/0097187_packet-hyperscsi.c b/pool/shard004/C/0097187_packet-hyperscsi.c new file mode 100644 index 0000000000000000000000000000000000000000..e3a398e9d3f2f570c6e27758ac76cbce17ebdbdb --- /dev/null +++ b/pool/shard004/C/0097187_packet-hyperscsi.c @@ -0,0 +1,208 @@ +/* packet-hyperscsi.c + * Routines for dissassembly of the Hyper SCSI protocol. + * + * Wireshark - Network traffic analyzer + * By Gerald Combs + * Copyright 1998 Gerald Combs + * Copyright 2002 Richard Sharpe + * + * 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 + +void proto_register_hyperscsi(void); +void proto_reg_handoff_hyperscsi(void); + +static int proto_hyperscsi; + +static int hf_hs_cmd = -1; +static int hf_hs_ver = -1; +static int hf_hs_res = -1; +static int hf_hs_tagno = -1; +static int hf_hs_lastfrag = -1; +static int hf_hs_fragno = -1; + +static gint ett_hyperscsi = -1; +static gint ett_hs_hdr = -1; +static gint ett_hs_pdu = -1; + +static const true_false_string tfs_lastfrag = { + "Last Fragment", + "Not Last Fragment" +}; + +#define HSCSI_OPCODE_REQUEST 0x00 +#define HSCSI_OPCODE_REPLY 0x01 +#define HSCSI_OPCODE_DEV_DISCOVERY 0x10 +#define HSCSI_OPCODE_ADN_REQUEST 0x11 +#define HSCSI_OPCODE_ADN_REPLY 0x12 +#define HSCSI_OPCODE_DISCONNECT 0x13 +#define HSCSI_OPCODE_ACK_SNR 0x20 +#define HSCSI_OPCODE_ACK_REPLY 0x21 +#define HSCSI_OPCODE_ADDR_REPORT 0x30 +#define HSCSI_OPCODE_ADDR_REPLY 0x31 +#define HSCSI_OPCODE_LOCAL_REQUEST 0x32 +#define HSCSI_OPCODE_LOCAL_REPLY 0x33 +#define HSCSI_OPCODE_REMOTE_REQUEST 0x34 +#define HSCSI_OPCODE_REMOTE_REPLY 0x35 + +static const value_string hscsi_opcodes[] = { + { HSCSI_OPCODE_REQUEST, "Command Block Encap Request"}, + { HSCSI_OPCODE_REPLY, "Command Block Encap Reply"}, + { HSCSI_OPCODE_DEV_DISCOVERY, "Device Discovery Reply"}, + { HSCSI_OPCODE_ADN_REQUEST, "Auth/Device Neg Request"}, + { HSCSI_OPCODE_ADN_REPLY, "Auth/Device Neg Reply"}, + { HSCSI_OPCODE_DISCONNECT, "Disconnect Request"}, + { HSCSI_OPCODE_ACK_SNR, "Flow Control Setup/Ack Request"}, + { HSCSI_OPCODE_ACK_REPLY, "Flow Control Ack Reply"}, + { 0, NULL} +}; + +#define OPCODE_MASK 0x7F + +static void +dissect_hyperscsi(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree) +{ + guint hs_hdr1, hs_hdr2, hs_hdr3; + guint8 hs_res; + guint16 hs_tagno; + guint16 hs_fragno; + gint offset = 0; + proto_tree *hs_hdr_tree, *hs_pdu_tree; + proto_tree *hs_tree = NULL; + proto_item *ti; + guint8 hs_cmd, hs_ver; + + col_set_str(pinfo->cinfo, COL_PROTOCOL, "HyperSCSI"); + col_clear(pinfo->cinfo, COL_INFO); + + if (tree) { + ti = proto_tree_add_item(tree, proto_hyperscsi, tvb, offset, -1, ENC_NA); + hs_tree = proto_item_add_subtree(ti, ett_hyperscsi); + } + + hs_hdr1 = tvb_get_guint8(tvb, offset); + offset++; + hs_hdr2 = tvb_get_guint8(tvb, offset); + offset++; + hs_hdr3 = tvb_get_guint8(tvb, offset); + offset++; + + hs_res = hs_hdr1 >> 4; + hs_tagno = ((hs_hdr1 & 0x0F) << 5 ) | (hs_hdr2 >> 3); + hs_fragno = ((hs_hdr2 &0X03) << 8 ) | hs_hdr3; + + /* + * Add the header ... three bytes + */ + + if (tree) { + ti = proto_tree_add_text(hs_tree, tvb, 0, 3, "HyperSCSI Header"); + hs_hdr_tree = proto_item_add_subtree(ti, ett_hs_hdr); + + /* + * Now, add the header items + */ + + proto_tree_add_uint(hs_hdr_tree, hf_hs_res, tvb, 0, 1, hs_res); + proto_tree_add_uint(hs_hdr_tree, hf_hs_tagno, tvb, 0, 2, hs_tagno); + proto_tree_add_item(hs_hdr_tree, hf_hs_lastfrag, tvb, 1, 1, ENC_BIG_ENDIAN); + proto_tree_add_uint(hs_hdr_tree, hf_hs_fragno, tvb, 1, 2, hs_fragno); + + } + + /* + * Now, add the PDU + */ + + hs_ver = tvb_get_guint8(tvb, offset++); + + hs_cmd = tvb_get_guint8(tvb, offset); + + hs_cmd &= OPCODE_MASK; + + col_append_str(pinfo->cinfo, COL_INFO, + val_to_str(hs_cmd, hscsi_opcodes, "Unknown HyperSCSI Request or Response (%u)")); + + if (tree) { + ti = proto_tree_add_text(hs_tree, tvb, 3, -1, "HyperSCSI PDU"); + hs_pdu_tree = proto_item_add_subtree(ti, ett_hs_pdu); + + proto_tree_add_uint(hs_pdu_tree, hf_hs_ver, tvb, 3, 1, hs_ver); + + proto_tree_add_uint(hs_pdu_tree, hf_hs_cmd, tvb, 4, 1, hs_cmd); + } + +} + +void +proto_register_hyperscsi(void) +{ + + static hf_register_info hf[] = { + { &hf_hs_res, + { "Reserved", "hyperscsi.reserved", FT_UINT8, BASE_DEC, NULL, 0x0, + NULL, HFILL}}, + + { &hf_hs_tagno, + { "Tag No", "hyperscsi.tagno", FT_UINT16, BASE_DEC, NULL, 0x0, + NULL, HFILL }}, + + { &hf_hs_lastfrag, + { "Last Fragment", "hyperscsi.lastfrag", FT_BOOLEAN, 8, TFS(&tfs_lastfrag), 0x04, NULL, HFILL}}, + + { &hf_hs_fragno, + { "Fragment No", "hyperscsi.fragno", FT_UINT16, BASE_DEC, NULL, 0x0, + NULL, HFILL}}, + + { &hf_hs_ver, + { "HyperSCSI Version", "hyperscsi.version", FT_UINT8, BASE_DEC, NULL, + 0x0, NULL, HFILL}}, + + { &hf_hs_cmd, + { "HyperSCSI Command", "hyperscsi.cmd", FT_UINT8, BASE_DEC, VALS(hscsi_opcodes), 0x0, + NULL, HFILL}}, + }; + + static gint *ett[] = { + &ett_hyperscsi, + &ett_hs_hdr, + &ett_hs_pdu, + }; + + proto_hyperscsi = proto_register_protocol("HyperSCSI", "HyperSCSI", "hyperscsi"); + proto_register_field_array(proto_hyperscsi, hf, array_length(hf)); + proto_register_subtree_array(ett, array_length(ett)); + + register_dissector("hyperscsi", dissect_hyperscsi, proto_hyperscsi); +} + +/* XXX */ +#define ETHERTYPE_HYPERSCSI 0x889A + +void +proto_reg_handoff_hyperscsi(void) +{ + dissector_handle_t hs_handle; + + hs_handle = find_dissector("hyperscsi"); + dissector_add_uint("ethertype", ETHERTYPE_HYPERSCSI, hs_handle); + +} diff --git a/pool/shard004/C/0097190_tomorse.c b/pool/shard004/C/0097190_tomorse.c new file mode 100644 index 0000000000000000000000000000000000000000..e4f6a83b5ab27cb3756747749b41aee7b0d3ed20 --- /dev/null +++ b/pool/shard004/C/0097190_tomorse.c @@ -0,0 +1,251 @@ +/* + * $Id: tomorse.c,v 1.13 2008/02/03 12:29:12 spoel Exp $ + * + * This source code is part of + * + * G R O M A C S + * + * GROningen MAchine for Chemical Simulations + * + * VERSION 3.2.0 + * Written by David van der Spoel, Erik Lindahl, Berk Hess, and others. + * Copyright (c) 1991-2000, University of Groningen, The Netherlands. + * Copyright (c) 2001-2004, The GROMACS development team, + * check out http://www.gromacs.org for more information. + + * 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. + * + * If you want to redistribute modifications, please consider that + * scientific software is very special. Version control is crucial - + * bugs must be traceable. We will be happy to consider code for + * inclusion in the official distribution, but derived work must not + * be called official GROMACS. Details are found in the README & COPYING + * files - if they are missing, get the official version at www.gromacs.org. + * + * To help us fund GROMACS development, we humbly ask that you cite + * the papers on the package - you can find them in the top README file. + * + * For more info, check our website at http://www.gromacs.org + * + * And Hey: + * Gallium Rubidium Oxygen Manganese Argon Carbon Silicon + */ +/* This file is completely threadsafe - keep it that way! */ +#ifdef HAVE_CONFIG_H +#include +#endif + +#include +#include +#include +#include "typedefs.h" +#include "string2.h" +#include "grompp.h" +#include "futil.h" +#include "smalloc.h" +#include "toputil.h" +#include "gmx_fatal.h" +#include "gpp_atomtype.h" +#include "gpp_tomorse.h" + +typedef struct { + char *ai,*aj; + real e_diss; +} t_2morse; + +static t_2morse *read_dissociation_energies(int *n2morse) +{ + FILE *fp; + char ai[32],aj[32]; + double e_diss; + char *fn="edissoc.dat"; + t_2morse *t2m=NULL; + int maxn2m=0,n2m=0; + int nread; + + /* Open the file with dissociation energies */ + fp = libopen(fn); + do { + /* Try and read two atom names and an energy term from it */ + nread = fscanf(fp,"%s%s%lf",ai,aj,&e_diss); + if (nread == 3) { + /* If we got three terms, it probably was OK, no further checking */ + if (n2m >= maxn2m) { + /* Increase memory for 16 at once, some mallocs are stupid */ + maxn2m += 16; + srenew(t2m,maxn2m); + } + /* Copy the values */ + t2m[n2m].ai = strdup(ai); + t2m[n2m].aj = strdup(aj); + t2m[n2m].e_diss = e_diss; + /* Increment counter */ + n2m++; + } + /* If we did not read three items, quit reading */ + } while (nread == 3); + ffclose(fp); + + /* Set the return values */ + *n2morse = n2m; + + return t2m; +} + +static int nequal(char *a1,char *a2) +{ + int i; + + /* Count the number of (case insensitive) characters that are equal in + * two strings. If they are equally long their respective null characters are + * counted also. + */ + for(i=0; (a1[i] != '\0') && (a2[i] != '\0'); i++) + if (toupper(a1[i]) != toupper(a2[i])) + break; + if ((a1[i] == '\0') && (a2[i] == '\0')) + i++; + + return i; +} + +static real search_e_diss(int n2m,t_2morse t2m[],char *ai,char *aj) +{ + int i; + int ibest=-1; + int nii,njj,nbstii=0,nbstjj=0; + real ediss = 400; + + /* Do a best match search for dissociation energies */ + for(i=0; (i nbstii) && (njj >= nbstjj)) || + ((nii >= nbstii) && (njj > nbstjj))) { + if ((nii > 0) && (njj > 0)) { + ibest = i; + nbstii = nii; + nbstjj = njj; + } + } + else { + /* Swap ai and aj (at least in counting the number of equal chars) */ + nii = nequal(t2m[i].ai,aj); + njj = nequal(t2m[i].aj,ai); + if (((nii > nbstii) && (njj >= nbstjj)) || + ((nii >= nbstii) && (njj > nbstjj))) { + if ((nii > 0) && (njj > 0)) { + ibest = i; + nbstii = nii; + nbstjj = njj; + } + } + } + } + } + /* Return the dissocation energy corresponding to the best match, if we have + * found one. Do some debug output anyway. + */ + if (ibest == -1) { + if (debug) + fprintf(debug,"MORSE: Couldn't find E_diss for bond %s - %s, using default %g\n",ai,aj,ediss); + return ediss; + } + else { + if (debug) + fprintf(debug,"MORSE: Dissoc. E (%10.3f) for bond %4s-%4s taken from bond %4s-%4s\n", + t2m[ibest].e_diss,ai,aj,t2m[ibest].ai,t2m[ibest].aj); + return t2m[ibest].e_diss; + } +} + +void convert_harmonics(int nrmols,t_molinfo mols[],t_atomtype atype) +{ + int n2m; + t_2morse *t2m; + + int i,j,k,last,ni,nj; + int nrharm,nrmorse,bb; + real edis,kb,b0,beta; + bool *bRemoveHarm; + + /* First get the data */ + t2m = read_dissociation_energies(&n2m); + if (debug) + fprintf(debug,"MORSE: read %d dissoc energies\n",n2m); + if (n2m <= 0) { + fprintf(stderr,"No dissocation energies read\n"); + return; + } + + /* For all the molecule types */ + for(i=0; (i + +CPL_CVSID("$Id: dted_create.c 28433 2015-02-06 21:18:50Z rouault $"); + +#define DTED_ABS_VERT_ACC "NA " +#define DTED_SECURITY "U" +#define DTED_EDITION 1 + +/************************************************************************/ +/* DTEDFormatDMS() */ +/************************************************************************/ + +static void DTEDFormatDMS( unsigned char *achField, double dfAngle, + const char *pszLatLong, const char *pszFormat ) + +{ + char chHemisphere; + char szWork[128]; + int nDegrees, nMinutes, nSeconds; + double dfRemainder; + + if( pszFormat == NULL ) + pszFormat = "%03d%02d%02d%c"; + + assert( EQUAL(pszLatLong,"LAT") || EQUAL(pszLatLong,"LONG") ); + + if( EQUAL(pszLatLong,"LAT") ) + { + if( dfAngle < 0.0 ) + chHemisphere = 'S'; + else + chHemisphere = 'N'; + } + else + { + if( dfAngle < 0.0 ) + chHemisphere = 'W'; + else + chHemisphere = 'E'; + } + + dfAngle = ABS(dfAngle); + + nDegrees = (int) floor(dfAngle + 0.5/3600.0); + dfRemainder = dfAngle - nDegrees; + nMinutes = (int) floor(dfRemainder*60.0 + 0.5/60.0); + dfRemainder = dfRemainder - nMinutes / 60.0; + nSeconds = (int) floor(dfRemainder * 3600.0 + 0.5); + + sprintf( szWork, pszFormat, + nDegrees, nMinutes, nSeconds, chHemisphere ); + + strncpy( (char *) achField, szWork, strlen(szWork) ); +} + +/************************************************************************/ +/* DTEDFormat() */ +/************************************************************************/ + +static void DTEDFormat( unsigned char *pszTarget, const char *pszFormat, ... ) CPL_PRINT_FUNC_FORMAT (2, 3); + +static void DTEDFormat( unsigned char *pszTarget, const char *pszFormat, ... ) + +{ + va_list args; + char szWork[512]; + + va_start(args, pszFormat); + vsprintf( szWork, pszFormat, args ); + va_end(args); + + strncpy( (char *) pszTarget, szWork, strlen(szWork) ); +} + +/************************************************************************/ +/* DTEDCreate() */ +/************************************************************************/ + +const char *DTEDCreate( const char *pszFilename, int nLevel, + int nLLOriginLat, int nLLOriginLong ) + +{ + VSILFILE *fp; + unsigned char achRecord[3601*2 + 12]; + int nXSize, nYSize, iProfile; + static char szError[512]; + +/* -------------------------------------------------------------------- */ +/* Establish resolution. */ +/* -------------------------------------------------------------------- */ + if( nLevel == 0 ) + { + nXSize = 121; + nYSize = 121; + } + else if( nLevel == 1 ) + { + nXSize = 1201; + nYSize = 1201; + } + else if( nLevel == 2 ) + { + nXSize = 3601; + nYSize = 3601; + } + else + { + sprintf( szError, "Illegal DTED Level value %d, only 0-2 allowed.", + nLevel ); + return szError; + } + + if( ABS(nLLOriginLat) >= 80 ) + nXSize = (nXSize - 1) / 6 + 1; + else if( ABS(nLLOriginLat) >= 75 ) + nXSize = (nXSize - 1) / 4 + 1; + else if( ABS(nLLOriginLat) >= 70 ) + nXSize = (nXSize - 1) / 3 + 1; + else if( ABS(nLLOriginLat) >= 50 ) + nXSize = (nXSize - 1) / 2 + 1; + +/* -------------------------------------------------------------------- */ +/* Open the file. */ +/* -------------------------------------------------------------------- */ + fp = VSIFOpenL( pszFilename, "wb" ); + + if( fp == NULL ) + { + sprintf( szError, "Unable to create file `%s'.", pszFilename ); + return szError; + } + +/* -------------------------------------------------------------------- */ +/* Format and write the UHL record. */ +/* -------------------------------------------------------------------- */ + memset( achRecord, ' ', DTED_UHL_SIZE ); + + DTEDFormat( achRecord + 0, "UHL1" ); + + DTEDFormatDMS( achRecord + 4, nLLOriginLong, "LONG", NULL ); + DTEDFormatDMS( achRecord + 12, nLLOriginLat, "LAT", NULL ); + + DTEDFormat( achRecord + 20, "%04d", (3600 / (nXSize-1)) * 10 ); + DTEDFormat( achRecord + 24, "%04d", (3600 / (nYSize-1)) * 10 ); + + DTEDFormat( achRecord + 28, "%4s", DTED_ABS_VERT_ACC ); + DTEDFormat( achRecord + 32, "%-3s", DTED_SECURITY ); + DTEDFormat( achRecord + 47, "%04d", nXSize ); + DTEDFormat( achRecord + 51, "%04d", nYSize ); + DTEDFormat( achRecord + 55, "%c", '0' ); + + if( VSIFWriteL( achRecord, DTED_UHL_SIZE, 1, fp ) != 1 ) + return "UHL record write failed."; + +/* -------------------------------------------------------------------- */ +/* Format and write the DSI record. */ +/* -------------------------------------------------------------------- */ + memset( achRecord, ' ', DTED_DSI_SIZE ); + + DTEDFormat( achRecord + 0, "DSI" ); + DTEDFormat( achRecord + 3, "%1s", DTED_SECURITY ); + + DTEDFormat( achRecord + 59, "DTED%d", nLevel ); + DTEDFormat( achRecord + 64, "%015d", 0 ); + DTEDFormat( achRecord + 87, "%02d", DTED_EDITION ); + DTEDFormat( achRecord + 89, "%c", 'A' ); + DTEDFormat( achRecord + 90, "%04d", 0 ); + DTEDFormat( achRecord + 94, "%04d", 0 ); + DTEDFormat( achRecord + 98, "%04d", 0 ); + DTEDFormat( achRecord + 126, "PRF89020B"); + DTEDFormat( achRecord + 135, "00"); + DTEDFormat( achRecord + 137, "0005"); + DTEDFormat( achRecord + 141, "MSL" ); + DTEDFormat( achRecord + 144, "WGS84" ); + + /* origin */ + DTEDFormatDMS( achRecord + 185, nLLOriginLat, "LAT", + "%02d%02d%02d.0%c" ); + DTEDFormatDMS( achRecord + 194, nLLOriginLong, "LONG", + "%03d%02d%02d.0%c" ); + + /* SW */ + DTEDFormatDMS( achRecord + 204, nLLOriginLat, "LAT", "%02d%02d%02d%c" ); + DTEDFormatDMS( achRecord + 211, nLLOriginLong, "LONG", NULL ); + + /* NW */ + DTEDFormatDMS( achRecord + 219, nLLOriginLat+1, "LAT", "%02d%02d%02d%c" ); + DTEDFormatDMS( achRecord + 226, nLLOriginLong, "LONG", NULL ); + + /* NE */ + DTEDFormatDMS( achRecord + 234, nLLOriginLat+1, "LAT", "%02d%02d%02d%c" ); + DTEDFormatDMS( achRecord + 241, nLLOriginLong+1, "LONG", NULL ); + + /* SE */ + DTEDFormatDMS( achRecord + 249, nLLOriginLat, "LAT", "%02d%02d%02d%c" ); + DTEDFormatDMS( achRecord + 256, nLLOriginLong+1, "LONG", NULL ); + + DTEDFormat( achRecord + 264, "0000000.0" ); + DTEDFormat( achRecord + 264, "0000000.0" ); + + DTEDFormat( achRecord + 273, "%04d", (3600 / (nYSize-1)) * 10 ); + DTEDFormat( achRecord + 277, "%04d", (3600 / (nXSize-1)) * 10 ); + + DTEDFormat( achRecord + 281, "%04d", nYSize ); + DTEDFormat( achRecord + 285, "%04d", nXSize ); + DTEDFormat( achRecord + 289, "%02d", 0 ); + + if( VSIFWriteL( achRecord, DTED_DSI_SIZE, 1, fp ) != 1 ) + return "DSI record write failed."; + +/* -------------------------------------------------------------------- */ +/* Create and write ACC record. */ +/* -------------------------------------------------------------------- */ + memset( achRecord, ' ', DTED_ACC_SIZE ); + + DTEDFormat( achRecord + 0, "ACC" ); + + DTEDFormat( achRecord + 3, "NA" ); + DTEDFormat( achRecord + 7, "NA" ); + DTEDFormat( achRecord + 11, "NA" ); + DTEDFormat( achRecord + 15, "NA" ); + + DTEDFormat( achRecord + 55, "00" ); + + if( VSIFWriteL( achRecord, DTED_ACC_SIZE, 1, fp ) != 1 ) + return "ACC record write failed."; + +/* -------------------------------------------------------------------- */ +/* Write blank template profile data records. */ +/* -------------------------------------------------------------------- */ + memset( achRecord, 0, nYSize*2 + 12 ); + memset( achRecord + 8, 0xff, nYSize*2 ); + + achRecord[0] = 0252; + + for( iProfile = 0; iProfile < nXSize; iProfile++ ) + { + achRecord[1] = 0; + achRecord[2] = (GByte) (iProfile / 256); + achRecord[3] = (GByte) (iProfile % 256); + + achRecord[4] = (GByte) (iProfile / 256); + achRecord[5] = (GByte) (iProfile % 256); + + if( VSIFWriteL( achRecord, nYSize*2 + 12, 1, fp ) != 1 ) + return "Data record write failed."; + } + + VSIFCloseL( fp ); + + return NULL; +} diff --git a/pool/shard004/C/0097207_packet-hp-erm.c b/pool/shard004/C/0097207_packet-hp-erm.c new file mode 100644 index 0000000000000000000000000000000000000000..c579c032396cd53b1ae1a83f8e2af658c3ad30b6 --- /dev/null +++ b/pool/shard004/C/0097207_packet-hp-erm.c @@ -0,0 +1,168 @@ +/* packet-hp-erm.c + * Routines for the disassembly of HP ProCurve encapsulated remote mirroring frames + * (Adapted from packet-cisco-erspan.c and packet-vlan.c) + * + * Copyright 2010 2012 William Meier , + * Zdravko Velinov + * + * Wireshark - Network traffic analyzer + * By Gerald Combs + * Copyright 1998 Gerald Combs + * + * SPDX-License-Identifier: GPL-2.0-or-later + */ + +/* + * For some information on HP Procurve encapsulated remote mirroring see + * "Traffic Mirroring" in Appendix B of the HP manual + * "Management and Configuration Guide for the ProCurve Series + * 3500, 3500yl, 5400zl, 6200yl, 6600, and 8200zl Switches (September 2009)" + * + * Format: + * The above manual indicates that the encapsulatedmirrored frame is transmitted + * on the network as a [UDP] packet which has 54 bytes preceding the mirrored frame. + * Examining a sample capture shows that this means that the data payload + * of the UDP packet consists of a 12 byte "header" followed by the + * bytes of the mirrored frame. + * + * After some additional tests, which involved injecting 802.1Q frames with + * different priorities and VLAN identifiers. It was determined that the HP + * ERM header has a part inside its header that closely resembles the 802.1Q + * header. The only difference is the priority numbering. + */ + +#include "config.h" + +#include + +void proto_register_hp_erm(void); +void proto_reg_handoff_hp_erm(void); + +#define PROTO_SHORT_NAME "HP_ERM" +#define PROTO_LONG_NAME "HP encapsulated remote mirroring" + +static int proto_hp_erm = -1; +static gint ett_hp_erm = -1; +static int hf_hp_erm_unknown1 = -1; +static int hf_hp_erm_unknown2 = -1; +static int hf_hp_erm_unknown3 = -1; +static int hf_hp_erm_priority = -1; +static int hf_hp_erm_cfi = -1; +static int hf_hp_erm_vlan = -1; +static int hf_hp_erm_is_tagged = -1; + +static const value_string hp_erm_pri_vals[] = { + { 0, "Background" }, + { 1, "Spare" }, + { 2, "Best Effort (default)" }, + { 3, "Excellent Effort" }, + { 4, "Controlled Load" }, + { 5, "Video, < 100ms latency and jitter" }, + { 6, "Voice, < 10ms latency and jitter" }, + { 7, "Network Control" }, + { 0, NULL } +}; + +static const true_false_string hp_erm_canonical = { "Non-canonical", "Canonical" }; + +static dissector_handle_t eth_withoutfcs_handle; + +static int +dissect_hp_erm(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, void* data _U_) +{ + proto_item *ti; + proto_tree *hp_erm_tree; + tvbuff_t *eth_tvb; + int offset = 0; + int * const flags[] = { + &hf_hp_erm_unknown2, + &hf_hp_erm_priority, + &hf_hp_erm_cfi, + &hf_hp_erm_vlan, + &hf_hp_erm_is_tagged, + &hf_hp_erm_unknown3, + NULL + }; + + col_set_str(pinfo->cinfo, COL_PROTOCOL, PROTO_SHORT_NAME); + col_set_str(pinfo->cinfo, COL_INFO, PROTO_SHORT_NAME ":"); + + ti = proto_tree_add_item(tree, proto_hp_erm, tvb, 0, -1, ENC_NA); + hp_erm_tree = proto_item_add_subtree(ti, ett_hp_erm); + + proto_tree_add_item(hp_erm_tree, hf_hp_erm_unknown1, tvb, offset, 8, ENC_NA); + offset += 8; + + proto_tree_add_bitmask_list(hp_erm_tree, tvb, offset, 4, flags, ENC_BIG_ENDIAN); + offset += 4; + + eth_tvb = tvb_new_subset_remaining(tvb, offset); + call_dissector(eth_withoutfcs_handle, eth_tvb, pinfo, tree); + return tvb_captured_length(tvb); +} + +void +proto_register_hp_erm(void) +{ + static hf_register_info hf[] = { + + { &hf_hp_erm_unknown1, + { "Unknown1", "hp_erm.unknown1", FT_BYTES, BASE_NONE, NULL, + 0x0, NULL, HFILL }}, + + { &hf_hp_erm_unknown2, + { "Unknown2", "hp_erm.unknown2", FT_UINT32, BASE_DEC, NULL, + 0xFF000000, NULL, HFILL }}, + + { &hf_hp_erm_priority, + { "Priority", "hp_erm.priority", FT_UINT32, BASE_DEC, VALS(hp_erm_pri_vals), + 0x00E00000, NULL, HFILL }}, + + { &hf_hp_erm_cfi, + { "CFI", "hp_erm.cfi", FT_BOOLEAN, 32, TFS(&hp_erm_canonical), + 0x00100000, NULL, HFILL }}, + + { &hf_hp_erm_vlan, + { "Vlan", "hp_erm.vlan", FT_UINT32, BASE_DEC, NULL, + 0x000FFF00, NULL, HFILL }}, + + { &hf_hp_erm_is_tagged, + { "Is_Tagged", "hp_erm.is_tagged", FT_BOOLEAN, 32, TFS(&tfs_yes_no), + 0x00000080, NULL, HFILL }}, + + { &hf_hp_erm_unknown3, + { "Unknown3", "hp_erm.unknown3", FT_UINT32, BASE_DEC, NULL, + 0x0000007F, NULL, HFILL }} + }; + + static gint *ett[] = { + &ett_hp_erm, + }; + + proto_hp_erm = proto_register_protocol(PROTO_LONG_NAME, PROTO_SHORT_NAME, "hp_erm"); + + proto_register_field_array(proto_hp_erm, hf, array_length(hf)); + proto_register_subtree_array(ett, array_length(ett)); +} + +void +proto_reg_handoff_hp_erm(void) +{ + dissector_handle_t hp_erm_handle; + + eth_withoutfcs_handle = find_dissector_add_dependency("eth_withoutfcs", proto_hp_erm); + hp_erm_handle = create_dissector_handle(dissect_hp_erm, proto_hp_erm); + dissector_add_for_decode_as_with_preference("udp.port", hp_erm_handle); +} +/* + * Editor modelines + * + * Local Variables: + * c-basic-offset: 4 + * tab-width: 8 + * indent-tabs-mode: nil + * End: + * + * ex: set shiftwidth=4 tabstop=8 expandtab: + * :indentSize=4:tabSize=8:noTabs=true: + */ diff --git a/pool/shard004/C/0097209_main.c b/pool/shard004/C/0097209_main.c new file mode 100644 index 0000000000000000000000000000000000000000..5b2b7cd6ca9a31dc860b166e3ba8ab5693617f55 --- /dev/null +++ b/pool/shard004/C/0097209_main.c @@ -0,0 +1,128 @@ +// +// main.c +// remove-duplicates Remove Duplicates from a linked list. +// + +#include +#include +#include + +#define LIST_END (struct node *) 0 + +struct node { + char value; + struct node *next; +}; + +bool nodeValuesMap[52] = {}; // "hash" table for storing flags of characters from the linked list. + +struct node *makeList(void); +void printList(struct node *head); +void removeDuplicates(struct node *head); +bool isValueSetOnMap(char value); +void setValueOnMap(char value); +int getValueCode(char value); + +// check nodeValuesMap for provided value's flag +bool isValueSetOnMap(char value) { + int code = getValueCode(value); + + if (code < 0) { // remove only alphabetical duplicates + return false; + } + + return nodeValuesMap[code]; +} + +// set provided value's flag to true +void setValueOnMap(char value) { + int code = getValueCode(value); + + if (code >= 0) { // for simplicity works only with a-z && A-Z chars + nodeValuesMap[code] = true; + } +} + +// convert an alphabet char into integer code where a is 0, or return -1 for non alphabetic chars +int getValueCode(char value) { + if (value >= 'a' && value <= 'z') { + return value - 'a'; + } + + if (value >= 'A' && value <= 'Z') { + return value - 'A'; + } + + return -1; +} + +// make a linked list +struct node *makeList(void) { + int nodes = 0; + struct node *listHead = LIST_END, *previousNode = LIST_END, *newNode; + char value; + + printf("Please enter number of nodes: "); + scanf("%i", &nodes); + + for (int i = 0; i < nodes; ++i) { + printf("Please enter node value: "); + scanf("%1s", &value); + + newNode = (struct node *) malloc(sizeof(struct node)); + if (newNode == NULL) { + fprintf(stderr, "Error allocating memory\n"); + exit(EXIT_FAILURE); + } + + newNode->value = value; + newNode->next = LIST_END; + + // link nodes to make a linked list + if (listHead == LIST_END) { + listHead = newNode; + } else { + previousNode->next = newNode; + } + + previousNode = newNode; + } + + return listHead; +} + +void printList(struct node *listNode) { + while (listNode != LIST_END) { + printf("%c ", listNode->value); + listNode = listNode->next; + } + + printf("\n"); +} + +// remove duplicates using hash table for checking if each value from the list is unique. +void removeDuplicates(struct node *listNode) { + struct node *previousNode = LIST_END; + + while (listNode != LIST_END) { + if (isValueSetOnMap(listNode->value)) { + previousNode->next = listNode->next; + free(listNode); + listNode = previousNode->next; + } else { + setValueOnMap(listNode->value); + previousNode = listNode; + listNode = listNode->next; + } + } +} + +int main(void) { + struct node *listHead = makeList(); + printList(listHead); + + removeDuplicates(listHead); + printList(listHead); + + return 0; +} diff --git a/pool/shard004/C/0097217_hal_bsp.c b/pool/shard004/C/0097217_hal_bsp.c new file mode 100644 index 0000000000000000000000000000000000000000..357c750fd22275c7a986c037966d0e45980399eb --- /dev/null +++ b/pool/shard004/C/0097217_hal_bsp.c @@ -0,0 +1,181 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +#include + +#include "bsp/bsp.h" +#include "os/mynewt.h" + +#include +#include +#include + +#include +#include + +#if MYNEWT_VAL(ETH_0) +#include +#include +#endif + +#if MYNEWT_VAL(PWM_0) || MYNEWT_VAL(PWM_1) || MYNEWT_VAL(PWM_2) +#include +#endif + +#if MYNEWT_VAL(PWM_0) +struct stm32_pwm_conf os_bsp_pwm0_cfg = { + .tim = TIM3, + .irq = TIM3_IRQn, +}; +#endif +#if MYNEWT_VAL(PWM_1) +struct stm32_pwm_conf os_bsp_pwm1_cfg = { + .tim = TIM4, + .irq = TIM4_IRQn, +}; +#endif +#if MYNEWT_VAL(PWM_2) +struct stm32_pwm_conf os_bsp_pwm2_cfg = { + .tim = TIM11, + .irq = TIM1_TRG_COM_TIM11_IRQn, +}; +#endif + +const uint32_t stm32_flash_sectors[] = { + 0x08000000, /* 32kB */ + 0x08008000, /* 32kB */ + 0x08010000, /* 32kB */ + 0x08018000, /* 32kB */ + 0x08020000, /* 128kB */ + 0x08040000, /* 256kB */ + 0x08080000, /* 256kB */ + 0x080c0000, /* 256kB */ + 0x08100000, /* End of flash */ +}; + +const uint32_t STM32_FLASH_NUM_AREAS = (sizeof(stm32_flash_sectors) / + sizeof(stm32_flash_sectors[0]) - 1); + +#if MYNEWT_VAL(UART_0) +const struct stm32_uart_cfg os_bsp_uart0_cfg = { + .suc_uart = USART1, + .suc_rcc_reg = &RCC->APB2ENR, + .suc_rcc_dev = RCC_APB2ENR_USART1EN, + .suc_pin_tx = MYNEWT_VAL(UART_0_PIN_TX), + .suc_pin_rx = MYNEWT_VAL(UART_0_PIN_RX), + .suc_pin_rts = MYNEWT_VAL(UART_0_PIN_RTS), + .suc_pin_cts = MYNEWT_VAL(UART_0_PIN_CTS), + .suc_pin_rts = -1, + .suc_pin_cts = -1, + .suc_pin_af = GPIO_AF7_USART1, + .suc_irqn = USART1_IRQn, +}; +#endif + +#if MYNEWT_VAL(ETH_0) +const struct stm32_eth_cfg os_bsp_eth0_cfg = { + /* + * PORTA + * PA1 - ETH_RMII_REF_CLK + * PA2 - ETH_RMII_MDIO + * PA7 - ETH_RMII_CRS_DV + */ + .sec_port_mask[0] = (1 << 1) | (1 << 2) | (1 << 7), + + /* + * PORTC + * PC1 - ETH_RMII_MDC + * PC4 - ETH_RMII_RXD0 + * PC5 - ETH_RMII_RXD1 + */ + .sec_port_mask[2] = (1 << 1) | (1 << 4) | (1 << 5), + + /* + * PORTG + * PG11 - ETH_RMII_TXEN + * PG13 - ETH_RMII_TXD0 + * PG14 - ETH_RMII_TXD1 + */ + .sec_port_mask[6] = (1 << 11) | (1 << 13) | (1 << 14), + .sec_phy_type = LAN_8742_RMII, + .sec_phy_irq = -1 +}; +#endif + +/* FIXME */ +static const struct hal_bsp_mem_dump dump_cfg[] = { + [0] = { + .hbmd_start = &_ram_start, + .hbmd_size = RAM_SIZE, + }, + [1] = { + .hbmd_start = &_dtcmram_start, + .hbmd_size = DTCMRAM_SIZE, + }, + [2] = { + .hbmd_start = &_itcmram_start, + .hbmd_size = ITCMRAM_SIZE, + }, +}; + +extern const struct hal_flash stm32_flash_dev; +const struct hal_flash * +hal_bsp_flash_dev(uint8_t id) +{ + /* + * Internal flash mapped to id 0. + */ + if (id != 0) { + return NULL; + } + return &stm32_flash_dev; +} + +const struct hal_bsp_mem_dump * +hal_bsp_core_dump(int *area_cnt) +{ + *area_cnt = sizeof(dump_cfg) / sizeof(dump_cfg[0]); + return dump_cfg; +} + +void +hal_bsp_init(void) +{ + stm32_periph_create(); +} + +void +hal_bsp_deinit(void) +{ +} + +/** + * Returns the configured priority for the given interrupt. If no priority + * configured, return the priority passed in + * + * @param irq_num + * @param pri + * + * @return uint32_t + */ +uint32_t +hal_bsp_get_nvic_priority(int irq_num, uint32_t pri) +{ + /* Add any interrupt priorities configured by the bsp here */ + return pri; +} diff --git a/pool/shard004/C/0097218_st802rt1a.c b/pool/shard004/C/0097218_st802rt1a.c new file mode 100644 index 0000000000000000000000000000000000000000..3e5f34f1c14a805386eb512db35c81f5fff36216 --- /dev/null +++ b/pool/shard004/C/0097218_st802rt1a.c @@ -0,0 +1,269 @@ +/** + * @file st802rt1a.c + * @brief ST802RT1A Ethernet PHY transceiver + * + * @section License + * + * Copyright (C) 2010-2017 Oryx Embedded SARL. All rights reserved. + * + * This file is part of CycloneTCP Open. + * + * 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. + * + * @author Oryx Embedded SARL (www.oryx-embedded.com) + * @version 1.7.8 + **/ + +//Switch to the appropriate trace level +#define TRACE_LEVEL NIC_TRACE_LEVEL + +//Dependencies +#include "core/net.h" +#include "drivers/st802rt1a.h" +#include "debug.h" + + +/** + * @brief ST802RT1A Ethernet PHY driver + **/ + +const PhyDriver st802rt1aPhyDriver = +{ + st802rt1aInit, + st802rt1aTick, + st802rt1aEnableIrq, + st802rt1aDisableIrq, + st802rt1aEventHandler, +}; + + +/** + * @brief ST802RT1A PHY transceiver initialization + * @param[in] interface Underlying network interface + * @return Error code + **/ + +error_t st802rt1aInit(NetInterface *interface) +{ + //Debug message + TRACE_INFO("Initializing ST802RT1A...\r\n"); + + //Reset PHY transceiver + st802rt1aWritePhyReg(interface, ST802RT1A_PHY_REG_RN00, RN00_SOFT_RESET); + //Wait for the reset to complete + while(st802rt1aReadPhyReg(interface, ST802RT1A_PHY_REG_RN00) & RN00_SOFT_RESET); + + //Dump PHY registers for debugging purpose + st802rt1aDumpPhyReg(interface); + + //Force the TCP/IP stack to poll the link state at startup + interface->phyEvent = TRUE; + //Notify the TCP/IP stack of the event + osSetEvent(&netEvent); + + //Successful initialization + return NO_ERROR; +} + + +/** + * @brief ST802RT1A timer handler + * @param[in] interface Underlying network interface + **/ + +void st802rt1aTick(NetInterface *interface) +{ + uint16_t value; + bool_t linkState; + + //Read status register + value = st802rt1aReadPhyReg(interface, ST802RT1A_PHY_REG_RN01); + //Retrieve current link state + linkState = (value & RN01_LINK_STATUS) ? TRUE : FALSE; + + //Link up event? + if(linkState && !interface->linkState) + { + //Set event flag + interface->phyEvent = TRUE; + //Notify the TCP/IP stack of the event + osSetEvent(&netEvent); + } + //Link down event? + else if(!linkState && interface->linkState) + { + //Set event flag + interface->phyEvent = TRUE; + //Notify the TCP/IP stack of the event + osSetEvent(&netEvent); + } +} + + +/** + * @brief Enable interrupts + * @param[in] interface Underlying network interface + **/ + +void st802rt1aEnableIrq(NetInterface *interface) +{ +} + + +/** + * @brief Disable interrupts + * @param[in] interface Underlying network interface + **/ + +void st802rt1aDisableIrq(NetInterface *interface) +{ +} + + +/** + * @brief ST802RT1A event handler + * @param[in] interface Underlying network interface + **/ + +void st802rt1aEventHandler(NetInterface *interface) +{ + uint16_t value; + bool_t linkState; + + //Read status register + value = st802rt1aReadPhyReg(interface, ST802RT1A_PHY_REG_RN01); + //Retrieve current link state + linkState = (value & RN01_LINK_STATUS) ? TRUE : FALSE; + + //Link is up? + if(linkState && !interface->linkState) + { + //Read RN13 register + value = st802rt1aReadPhyReg(interface, ST802RT1A_PHY_REG_RN13); + + //Check current operation mode + switch(value & RN13_CMODE_MASK) + { + //10BASE-T + case RN13_CMODE_10BT: + interface->linkSpeed = NIC_LINK_SPEED_10MBPS; + interface->duplexMode = NIC_HALF_DUPLEX_MODE; + break; + //10BASE-T full-duplex + case RN13_CMODE_10BT_FD: + interface->linkSpeed = NIC_LINK_SPEED_10MBPS; + interface->duplexMode = NIC_FULL_DUPLEX_MODE; + break; + //100BASE-TX + case RN13_CMODE_100BTX: + interface->linkSpeed = NIC_LINK_SPEED_100MBPS; + interface->duplexMode = NIC_HALF_DUPLEX_MODE; + break; + //100BASE-TX full-duplex + case RN13_CMODE_100BTX_FD: + interface->linkSpeed = NIC_LINK_SPEED_100MBPS; + interface->duplexMode = NIC_FULL_DUPLEX_MODE; + break; + //Unknown operation mode + default: + //Debug message + TRACE_WARNING("Invalid Duplex mode\r\n"); + break; + } + + //Update link state + interface->linkState = TRUE; + + //Adjust MAC configuration parameters for proper operation + interface->nicDriver->updateMacConfig(interface); + + //Process link state change event + nicNotifyLinkChange(interface); + } + //Link is down? + else if(!linkState && interface->linkState) + { + //Update link state + interface->linkState = FALSE; + + //Process link state change event + nicNotifyLinkChange(interface); + } +} + + +/** + * @brief Write PHY register + * @param[in] interface Underlying network interface + * @param[in] address PHY register Register address + * @param[in] data Register value + **/ + +void st802rt1aWritePhyReg(NetInterface *interface, uint8_t address, uint16_t data) +{ + uint8_t phyAddr; + + //Get the address of the PHY transceiver + if(interface->phyAddr < 32) + phyAddr = interface->phyAddr; + else + phyAddr = ST802RT1A_PHY_ADDR; + + //Write the specified PHY register + interface->nicDriver->writePhyReg(phyAddr, address, data); +} + + +/** + * @brief Read PHY register + * @param[in] interface Underlying network interface + * @param[in] address PHY register address + * @return Register value + **/ + +uint16_t st802rt1aReadPhyReg(NetInterface *interface, uint8_t address) +{ + uint8_t phyAddr; + + //Get the address of the PHY transceiver + if(interface->phyAddr < 32) + phyAddr = interface->phyAddr; + else + phyAddr = ST802RT1A_PHY_ADDR; + + //Read the specified PHY register + return interface->nicDriver->readPhyReg(phyAddr, address); +} + + +/** + * @brief Dump PHY registers for debugging purpose + * @param[in] interface Underlying network interface + **/ + +void st802rt1aDumpPhyReg(NetInterface *interface) +{ + uint8_t i; + + //Loop through PHY registers + for(i = 0; i < 32; i++) + { + //Display current PHY register + TRACE_DEBUG("%02" PRIu8 ": 0x%04" PRIX16 "\r\n", i, st802rt1aReadPhyReg(interface, i)); + } + + //Terminate with a line feed + TRACE_DEBUG("\r\n"); +} diff --git a/pool/shard004/C/0097222_car.c b/pool/shard004/C/0097222_car.c new file mode 100644 index 0000000000000000000000000000000000000000..68bcb31eb115e31c7aaca7a2658af838338385b1 --- /dev/null +++ b/pool/shard004/C/0097222_car.c @@ -0,0 +1,58 @@ +/* + * This file is part of the coreboot project. + * + * Copyright (C) 2016 Intel Corp. + * Copyright 2016 Google Inc. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; 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 + +/* + * This file supports the necessary hoops one needs to jump through since + * early FSP component and early stages are running from cache-as-ram. + */ + +static void flush_l1d_to_l2(void) +{ + msr_t msr = rdmsr(MSR_POWER_MISC); + msr.lo |= (1 << 8); + wrmsr(MSR_POWER_MISC, msr); +} + +static inline int is_car_addr(uintptr_t addr) +{ + return ((addr >= CONFIG_DCACHE_RAM_BASE) && + (addr < (CONFIG_DCACHE_RAM_BASE + CONFIG_DCACHE_RAM_SIZE))); +} + +void platform_segment_loaded(uintptr_t start, size_t size, int flags) +{ + /* Bail out if this is not the final segment. */ + if (!(flags & SEG_FINAL)) + return; + + char start_car_check = is_car_addr(start); + char end_car_check = is_car_addr(start + size - 1); + + /* Bail out if loaded program segment does not lie in CAR region. */ + if (!start_car_check && !end_car_check) + return; + + /* Loaded program segment should lie entirely within CAR region. */ + assert (start_car_check && end_car_check); + + flush_l1d_to_l2(); +} diff --git a/pool/shard004/C/0097224_path.c b/pool/shard004/C/0097224_path.c new file mode 100644 index 0000000000000000000000000000000000000000..959bb0381a6dff2aeddbc8b222cc6050c372c6f5 --- /dev/null +++ b/pool/shard004/C/0097224_path.c @@ -0,0 +1,198 @@ +/* + * AppArmor security module + * + * This file contains AppArmor function for pathnames + * + * Copyright (C) 1998-2008 Novell/SUSE + * Copyright 2009-2010 Canonical 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, version 2 of the + * License. + */ + +#include +#include +#include +#include +#include +#include +#include +#include + +#include "include/apparmor.h" +#include "include/path.h" +#include "include/policy.h" + + +/* modified from dcache.c */ +static int prepend(char **buffer, int buflen, const char *str, int namelen) +{ + buflen -= namelen; + if (buflen < 0) + return -ENAMETOOLONG; + *buffer -= namelen; + memcpy(*buffer, str, namelen); + return 0; +} + +#define CHROOT_NSCONNECT (PATH_CHROOT_REL | PATH_CHROOT_NSCONNECT) + +/** + * d_namespace_path - lookup a name associated with a given path + * @path: path to lookup (NOT NULL) + * @buf: buffer to store path to (NOT NULL) + * @buflen: length of @buf + * @name: Returns - pointer for start of path name with in @buf (NOT NULL) + * @flags: flags controlling path lookup + * + * Handle path name lookup. + * + * Returns: %0 else error code if path lookup fails + * When no error the path name is returned in @name which points to + * to a position in @buf + */ +static int d_namespace_path(struct path *path, char *buf, int buflen, + char **name, int flags) +{ + char *res; + int error = 0; + int connected = 1; + + if (path->mnt->mnt_flags & MNT_INTERNAL) { + /* it's not mounted anywhere */ + res = dentry_path(path->dentry, buf, buflen); + *name = res; + if (IS_ERR(res)) { + *name = buf; + return PTR_ERR(res); + } + if (path->dentry->d_sb->s_magic == PROC_SUPER_MAGIC && + strncmp(*name, "/sys/", 5) == 0) { + /* TODO: convert over to using a per namespace + * control instead of hard coded /proc + */ + return prepend(name, *name - buf, "/proc", 5); + } + return 0; + } + + /* resolve paths relative to chroot?*/ + if (flags & PATH_CHROOT_REL) { + struct path root; + get_fs_root(current->fs, &root); + res = __d_path(path, &root, buf, buflen); + path_put(&root); + } else { + res = d_absolute_path(path, buf, buflen); + if (!our_mnt(path->mnt)) + connected = 0; + } + + /* handle error conditions - and still allow a partial path to + * be returned. + */ + if (!res || IS_ERR(res)) { + if (PTR_ERR(res) == -ENAMETOOLONG) + return -ENAMETOOLONG; + connected = 0; + res = dentry_path_raw(path->dentry, buf, buflen); + if (IS_ERR(res)) { + error = PTR_ERR(res); + *name = buf; + goto out; + }; + } else if (!our_mnt(path->mnt)) + connected = 0; + + *name = res; + + /* Handle two cases: + * 1. A deleted dentry && profile is not allowing mediation of deleted + * 2. On some filesystems, newly allocated dentries appear to the + * security_path hooks as a deleted dentry except without an inode + * allocated. + */ + if (d_unlinked(path->dentry) && path->dentry->d_inode && + !(flags & PATH_MEDIATE_DELETED)) { + error = -ENOENT; + goto out; + } + + /* If the path is not connected to the expected root, + * check if it is a sysctl and handle specially else remove any + * leading / that __d_path may have returned. + * Unless + * specifically directed to connect the path, + * OR + * if in a chroot and doing chroot relative paths and the path + * resolves to the namespace root (would be connected outside + * of chroot) and specifically directed to connect paths to + * namespace root. + */ + if (!connected) { + if (!(flags & PATH_CONNECT_PATH) && + !(((flags & CHROOT_NSCONNECT) == CHROOT_NSCONNECT) && + our_mnt(path->mnt))) { + /* disconnected path, don't return pathname starting + * with '/' + */ + error = -EACCES; + if (*res == '/') + *name = res + 1; + } + } + +out: + return error; +} + +/** + * aa_path_name - get the pathname to a buffer ensure dir / is appended + * @path: path the file (NOT NULL) + * @flags: flags controlling path name generation + * @buffer: buffer to put name in (NOT NULL) + * @name: Returns - the generated path name if !error (NOT NULL) + * @info: Returns - information on why the path lookup failed (MAYBE NULL) + * + * @name is a pointer to the beginning of the pathname (which usually differs + * from the beginning of the buffer), or NULL. If there is an error @name + * may contain a partial or invalid name that can be used for audit purposes, + * but it can not be used for mediation. + * + * We need PATH_IS_DIR to indicate whether the file is a directory or not + * because the file may not yet exist, and so we cannot check the inode's + * file type. + * + * Returns: %0 else error code if could retrieve name + */ +int aa_path_name(struct path *path, int flags, char *buffer, const char **name, + const char **info) +{ + char *str = NULL; + int adjust = (flags & PATH_IS_DIR) ? 1 : 0; + int error = d_namespace_path(path, buffer, aa_g_path_max - adjust, + &str, flags); + + if (!error && (flags & PATH_IS_DIR) && str[1] != '\0') + /* + * Append "/" to the pathname. The root directory is a special + * case; it already ends in slash. + */ + strcpy(&buffer[aa_g_path_max - 2], "/"); + + if (info && error) { + if (error == -ENOENT) + *info = "Failed name lookup - deleted entry"; + else if (error == -EACCES) + *info = "Failed name lookup - disconnected path"; + else if (error == -ENAMETOOLONG) + *info = "Failed name lookup - name too long"; + else + *info = "Failed name lookup"; + } + + *name = str; + return error; +} diff --git a/pool/shard004/C/0097228_ad_hfs_write.c b/pool/shard004/C/0097228_ad_hfs_write.c new file mode 100644 index 0000000000000000000000000000000000000000..ab42d31bb66665105a3a3e9696f4167d21967e71 --- /dev/null +++ b/pool/shard004/C/0097228_ad_hfs_write.c @@ -0,0 +1,70 @@ +/* -*- Mode: C; c-basic-offset:4 ; -*- */ +/* + * + * Copyright (C) 1997 University of Chicago. + * See COPYRIGHT notice in top-level directory. + */ + +#include "ad_hfs.h" + +#ifndef HAVE_LSEEK64 +#define lseek64 lseek +#endif + +void ADIOI_HFS_WriteContig(ADIO_File fd, void *buf, int count, + MPI_Datatype datatype, int file_ptr_type, + ADIO_Offset offset, ADIO_Status *status, int *error_code) +{ + int err=-1, datatype_size, len; +#ifndef PRINT_ERR_MSG + static char myname[] = "ADIOI_HFS_WRITECONTIG"; +#endif + + MPI_Type_size(datatype, &datatype_size); + len = datatype_size * count; + +#ifdef SPPUX + fd->fp_sys_posn = -1; /* set it to null, since we are using pwrite */ + if (file_ptr_type == ADIO_EXPLICIT_OFFSET) + err = pwrite64(fd->fd_sys, buf, len, offset); + else { /* write from curr. location of ind. file pointer */ + err = pwrite64(fd->fd_sys, buf, len, fd->fp_ind); + fd->fp_ind += err; + } +#endif + +#ifdef HPUX + if (file_ptr_type == ADIO_EXPLICIT_OFFSET) { + if (fd->fp_sys_posn != offset) + lseek64(fd->fd_sys, offset, SEEK_SET); + err = write(fd->fd_sys, buf, len); + fd->fp_sys_posn = offset + err; + /* individual file pointer not updated */ + } + else { /* write from curr. location of ind. file pointer */ + if (fd->fp_sys_posn != fd->fp_ind) + lseek64(fd->fd_sys, fd->fp_ind, SEEK_SET); + err = write(fd->fd_sys, buf, len); + fd->fp_ind += err; + fd->fp_sys_posn = fd->fp_ind; + } +#endif + +#ifdef HAVE_STATUS_SET_BYTES + if (err != -1) MPIR_Status_set_bytes(status, datatype, err); +#endif + + if (err == -1) { +#ifdef MPICH2 + *error_code = MPIR_Err_create_code(MPI_SUCCESS, MPIR_ERR_RECOVERABLE, myname, __LINE__, MPI_ERR_IO, "**io", + "**io %s", strerror(errno)); +#elif defined(PRINT_ERR_MSG) + *error_code = MPI_SUCCESS; +#else /* MPICH-1 */ + *error_code = MPIR_Err_setmsg(MPI_ERR_IO, MPIR_ADIO_ERROR, + myname, "I/O Error", "%s", strerror(errno)); + ADIOI_Error(fd, *error_code, myname); +#endif + } + else *error_code = MPI_SUCCESS; +} diff --git a/pool/shard004/C/0097238_pthread_rwlock_timedrdlock.c b/pool/shard004/C/0097238_pthread_rwlock_timedrdlock.c new file mode 100644 index 0000000000000000000000000000000000000000..4029dd7412d94d6ad44a7cbb9f6a21b3dea83d53 --- /dev/null +++ b/pool/shard004/C/0097238_pthread_rwlock_timedrdlock.c @@ -0,0 +1,114 @@ +/* + * pthread_rwlock_timedrdlock.c + * + * Description: + * This translation unit implements read/write lock primitives. + * + * -------------------------------------------------------------------------- + * + * Pthreads-win32 - POSIX Threads Library for Win32 + * Copyright(C) 1998 John E. Bossom + * Copyright(C) 1999,2012 Pthreads-win32 contributors + * + * Homepage1: http://sourceware.org/pthreads-win32/ + * Homepage2: http://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: + * 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 + */ + +#ifdef HAVE_CONFIG_H +# include "config.h" +#endif + +#include + +#include "pthread.h" +#include "implement.h" + +int +pthread_rwlock_timedrdlock (pthread_rwlock_t * rwlock, + const struct timespec *abstime) +{ + int result; + pthread_rwlock_t rwl; + + if (rwlock == NULL || *rwlock == NULL) + { + return EINVAL; + } + + /* + * We do a quick check to see if we need to do more work + * to initialise a static rwlock. We check + * again inside the guarded section of ptw32_rwlock_check_need_init() + * to avoid race conditions. + */ + if (*rwlock == PTHREAD_RWLOCK_INITIALIZER) + { + result = ptw32_rwlock_check_need_init (rwlock); + + if (result != 0 && result != EBUSY) + { + return result; + } + } + + rwl = *rwlock; + + if (rwl->nMagic != PTW32_RWLOCK_MAGIC) + { + return EINVAL; + } + + if ((result = + pthread_mutex_timedlock (&(rwl->mtxExclusiveAccess), abstime)) != 0) + { + return result; + } + + if (++rwl->nSharedAccessCount == INT_MAX) + { + if ((result = + pthread_mutex_timedlock (&(rwl->mtxSharedAccessCompleted), + abstime)) != 0) + { + if (result == ETIMEDOUT) + { + ++rwl->nCompletedSharedAccessCount; + } + (void) pthread_mutex_unlock (&(rwl->mtxExclusiveAccess)); + return result; + } + + rwl->nSharedAccessCount -= rwl->nCompletedSharedAccessCount; + rwl->nCompletedSharedAccessCount = 0; + + if ((result = + pthread_mutex_unlock (&(rwl->mtxSharedAccessCompleted))) != 0) + { + (void) pthread_mutex_unlock (&(rwl->mtxExclusiveAccess)); + return result; + } + } + + return (pthread_mutex_unlock (&(rwl->mtxExclusiveAccess))); +} diff --git a/pool/shard004/C/0097241_testsort.c b/pool/shard004/C/0097241_testsort.c new file mode 100644 index 0000000000000000000000000000000000000000..59e7e340676bd13737226e8861326061e96fbe29 --- /dev/null +++ b/pool/shard004/C/0097241_testsort.c @@ -0,0 +1,124 @@ +#include +#include +#include +#include +#include "fcitx-utils/utils.h" + +typedef struct { + int a; + int b; +} SortItem; + +SortItem array[] = { + {3, 4}, + {2, 4}, + {2, 3}, + {2, 4}, + {2, 3}, + {2, 4}, + {2, 3}, + {2, 4}, + {2, 3}, + {2, 4}, + {2, 3}, + {2, 4}, + {2, 3}, + {2, 4}, + {2, 3}, + {2, 4}, + {2, 3}, + {2, 4}, + {2, 3}, +}; + +SortItem msort_array[] = { + {2, 4}, + {2, 3}, + {2, 4}, + {2, 3}, + {2, 4}, + {2, 3}, + {2, 4}, + {2, 3}, + {2, 4}, + {2, 3}, + {2, 4}, + {2, 3}, + {2, 4}, + {2, 3}, + {2, 4}, + {2, 3}, + {2, 4}, + {2, 3}, + {3, 4}, +}; + + +int cmp(const void* a, const void* b, void* thunk) +{ + FCITX_UNUSED(thunk); + return ((SortItem*)a)->a - ((SortItem*)b)->a; +} + +int intcmp(const void* a, const void* b, void* thunk) +{ + if (thunk) { + return (*((int*)b)) - (*((int*)a)); + } + return (*((int*)a)) - (*((int*)b)); +} + +int main() +{ + /* stable test */ + fcitx_msort_r(array, FCITX_ARRAY_SIZE(array), sizeof(array[0]), cmp, NULL); + + for (size_t i = 0; i < FCITX_ARRAY_SIZE(array); i ++) { + assert(array[i].a == msort_array[i].a); + assert(array[i].b == msort_array[i].b); + } + + srand(time(NULL)); + + { + /* qsort_test */ + int qsort_intarray[1024]; + for (size_t i = 0; i = qsort_intarray[i + 1]); + } + } + + { + /* qsort_test */ + int qsort_intarray[6]; + for (size_t i = 0; i = qsort_intarray[i + 1]); + } + + /* msort_test */ + fcitx_msort_r(qsort_intarray, FCITX_ARRAY_SIZE(qsort_intarray), sizeof(qsort_intarray[0]), intcmp, NULL); + + for (size_t i = 0; i < FCITX_ARRAY_SIZE(qsort_intarray) - 1; i ++) { + assert(qsort_intarray[i] <= qsort_intarray[i + 1]); + } + } + + return 0; +} diff --git a/pool/shard004/C/0097245_test_inline_patch_xad.c b/pool/shard004/C/0097245_test_inline_patch_xad.c new file mode 100644 index 0000000000000000000000000000000000000000..70f1ce02342b0459ac9e3c295a4e9a4464dbd962 --- /dev/null +++ b/pool/shard004/C/0097245_test_inline_patch_xad.c @@ -0,0 +1,240 @@ +#include +#include +#include +#include +#include + +#include "rm.h" + +#define NOP_PATCH 1 + +// Etichette per il codice delle patch inline +extern char handler_call_start_RA; +extern char handler_call_end_RA; +extern char handler_call_RA; + +extern char handler_call_start_RC; +extern char handler_call_end_RC; +extern char handler_call_RC; + +extern char handler_call_start_WA; +extern char handler_call_end_WA; +extern char handler_call_WA; + +extern char handler_call_start_WC; +extern char handler_call_end_WC; +extern char handler_call_WC; + +int g_var; + +// Handler per le patch di default +void read_handler(void* rm_addr, size_t size) { + //if (g_var==0) + // printf("*** READ_HANDLER *** rm_addr = %p, size = %d\n", rm_addr, size); +} + +void write_handler(void* rm_addr, size_t size) { + printf("*** WRITE_HANDLER *** rm_addr = %p, size = %d\n", rm_addr, size); +} + +// Handler per le patch inline +void read_handler_inline(void* rm_addr, size_t size) { + //printf("*** READ_HANDLER *** rm_addr = %p, size = %d\n", rm_addr, size); +} + +void write_handler_inline(void* rm_addr, size_t size) { + printf("(inline)(inline)(inline) *** WRITE_HANDLER *** rm_addr = %p, size = %d\n", rm_addr, size); +} + +//runs the test loop... +double foo (void *inPtr, unsigned int n) +{ + struct timeval tvBeginLoop, tvEndLoop; + double loopTime; + + int *a=(int *)inPtr; + int b, i; + + /*fetches initial time*/ + gettimeofday(&tvBeginLoop, NULL); + + for (i=0; i=M) + g_var=0;*/ + + b=*a; + } + + /*fetches final time*/ + gettimeofday(&tvEndLoop, NULL); + + loopTime = tvEndLoop.tv_sec + (tvEndLoop.tv_usec*0.000001) + -tvBeginLoop.tv_sec - (tvBeginLoop.tv_usec*0.000001); + + return loopTime; +} + + +#if NOP_PATCH==1 +// Macro per il codice delle patch inline +#define INLINE_PATCH_CODE(case, reg, reg2) \ + __asm__ __volatile__ ( \ + "handler_call_start_"case":" \ + "nop;" \ + "handler_call_end_"case":" \ + ); +#endif + +#if NOP_PATCH==0 +// Macro per il codice delle patch inline +#define INLINE_PATCH_CODE(case, reg, reg2) \ + __asm__ __volatile__ ( \ + "jmp handler_call_end_"case";" \ + ); \ + __asm__ __volatile__ ( \ + "handler_call_start_"case":" \ + /*** "call HANDLER;" */ \ + /* "cmpl $0x00000000, 0x08000000;" /*addr of g_var to be inserted at runtime...*/ \ + /* "jnz handler_call_end_"case";" /* if g_var != 0 skips inline handler...*/ \ + "push %"reg2";" \ + "push %edx;" \ + "push $0x4;" /* parameter #2 */ \ + "push %"reg";" /* parameter #1 */ \ + "handler_call_"case":" \ + "movl $0x08000000, %"reg";" /* l'indirizzo di memoria sarà modificato */ \ + "call *%"reg";" \ + "addl $0x8, %esp;" /* remove the parameters from stack */ \ + "pop %edx;" \ + "pop %"reg2";" \ + /*** "call HANDLER;" */ \ + "handler_call_end_"case":" \ + ); +#endif + +// Funzione per l'inserimento degli indirizzi degli handler nel codice delle patch inline +// N.B. questa funzione contiene anche il codice delle patch inline (non viene mai eseguito, serve solo per essere copiato) +void inline_patch() { +#if NOP_PATCH==0 + // Sprotegge pagina del codice delle patch inline + unsigned int page_start = ((unsigned int)&handler_call_start_RA & ~(getpagesize()-1)); + unsigned int page_end = ((unsigned int)(&handler_call_end_WC-1) & ~(getpagesize()-1)) + getpagesize(); + if(-1 == mprotect((void*)page_start, page_end-page_start, PROT_READ|PROT_WRITE|PROT_EXEC)) { + printf("[inline_patch]: mprotect() failed!\n"); + exit(1); + } + + // Patch del codice delle patch inline (inserimento degli indirizzi degli handler) + unsigned int read_handler_addr = (unsigned int)read_handler_inline; + unsigned int write_handler_addr = (unsigned int)write_handler_inline; + memcpy(&handler_call_RA + 1, &read_handler_addr, 4); + memcpy(&handler_call_RC + 1, &read_handler_addr, 4); + memcpy(&handler_call_WA + 1, &write_handler_addr, 4); + memcpy(&handler_call_WC + 1, &write_handler_addr, 4); + + //copies address of g_var... + //*(unsigned*)(&handler_call_start_RA + 2) = &g_var; + //*(unsigned*)(&handler_call_start_RC + 2) = &g_var; + + // Reimposta protezione pagina del codice delle patch inline + if(-1 == mprotect((void*)page_start, page_end-page_start, PROT_READ|PROT_EXEC)) { + printf("[inline_patch]: mprotect() failed!\n"); + exit(1); + } +#endif + + // Codice delle patch inline (non viene mai eseguito, serve solo per essere copiato) + INLINE_PATCH_CODE("RA", "eax", "ecx") + INLINE_PATCH_CODE("RC", "ecx", "eax") + INLINE_PATCH_CODE("WA", "eax", "ecx") + INLINE_PATCH_CODE("WC", "ecx", "eax") + + return; +} + +#define N 100000000 +#define M 1000 + +int main() { + size_t shadow_rec_size = 32; + size_t shadow_wordsize = 4; + + void *rPtr, *nPtr; + + double X_Time, Patch_Time, Xprime_Time, XAD_Time; + + void* patch_table[rm_patch_num][rm_size_num]; + size_t size_table[rm_patch_num][rm_size_num]; + + printf("MAIN - start\n"); + + // Inserimento degli indirizzi degli handler nel codice delle patch inline + inline_patch(); + + // Creazione tabelle per patch inline + patch_table[rm_read_eax_patch][rm_size_4] = &handler_call_start_RA; + size_table[rm_read_eax_patch][rm_size_4] = &handler_call_end_RA - &handler_call_start_RA; + patch_table[rm_read_ecx_patch][rm_size_4] = &handler_call_start_RC; + size_table[rm_read_ecx_patch][rm_size_4] = &handler_call_end_RC - &handler_call_start_RC; + patch_table[rm_write_eax_patch][rm_size_4] = &handler_call_start_WA; + size_table[rm_write_eax_patch][rm_size_4] = &handler_call_end_WA - &handler_call_start_WA; + patch_table[rm_write_ecx_patch][rm_size_4] = &handler_call_start_WC; + size_table[rm_write_ecx_patch][rm_size_4] = &handler_call_end_WC - &handler_call_start_WC; + + // RM init +// if (rm_init(NULL, NULL, NULL, NULL, shadow_rec_size, shadow_wordsize) == -1) { // no handler + if (rm_init(NULL, NULL, patch_table, size_table, shadow_rec_size, shadow_wordsize) == -1) { // inline patch +// if (rm_init(read_handler, write_handler, NULL, NULL, shadow_rec_size, shadow_wordsize) == -1) { // default patch + printf("main: rm_init error!!\n"); + return -1; + } + +#if rm_DEBUG == 1 + if (rm_make_dump_file("dump1.txt") == -1) { + printf("main: rm_make_dump_file error!!\n"); + return -1; + } +#endif + + rPtr=rm_malloc (sizeof (int)); + nPtr=malloc (sizeof (int)); + + //X test loop... + X_Time=foo (nPtr, N); + + //causes foo() to be patched... + Patch_Time=foo (rPtr, 1); + + //X' test loop... + Xprime_Time=foo (nPtr, N); + + //X+A(+D) test loop... + XAD_Time=foo (rPtr, N); + + printf ("N = %u\n", N); + printf("X = %f\n", X_Time); + printf("Patch_Time = %f\n", Patch_Time); + printf("X' = %f\n", Xprime_Time); + + #if NOP_PATCH==1 + printf("X+A = %f\n", XAD_Time); + #endif + #if NOP_PATCH==0 + printf("X+A+D = %f\n", XAD_Time); + #endif + + rm_free (rPtr); + free (nPtr); + +#if rm_DEBUG == 1 + if (rm_make_dump_file("dump2.txt") == -1) { + printf("main: rm_make_dump_file error!!\n"); + return -1; + } +#endif + + printf("MAIN - end\n"); + + return 0; +} diff --git a/pool/shard004/C/0097255_io.c b/pool/shard004/C/0097255_io.c new file mode 100644 index 0000000000000000000000000000000000000000..1402b52c9544505baa5dff027931db4260c31c1a --- /dev/null +++ b/pool/shard004/C/0097255_io.c @@ -0,0 +1,81 @@ +#include "io.h" + + +static uint8_t (*output_function)(uint8_t* y, uint8_t* x); +static uint8_t output_state; + + +static uint8_t fn_active_low(uint8_t* y, uint8_t* x) +{ + return *y = ~x[0]; +} + +static uint8_t fn_active_high(uint8_t* y, uint8_t* x) +{ + return *y = x[0]; +} + +static uint8_t fn_toggle_rising_edge(uint8_t* y, uint8_t* x) +{ + return *y ^= (~x[1] & x[0]); +} + +static uint8_t fn_toggle_falling_edge(uint8_t* y, uint8_t* x) +{ + return *y ^= (x[1] & ~x[0]); +} + + +void +io_init(void) +{ + GPIO_Init(GPIOC, GPIO_PIN_7|GPIO_PIN_6|GPIO_PIN_5|GPIO_PIN_4, GPIO_MODE_IN_FL_IT); + GPIO_Init(GPIOD, GPIO_PIN_3, GPIO_MODE_OUT_OD_HIZ_SLOW); + GPIO_Init(GPIOD, GPIO_PIN_2, GPIO_MODE_OUT_OD_HIZ_SLOW); + GPIO_Init(GPIOC, GPIO_PIN_3, GPIO_MODE_OUT_OD_HIZ_SLOW); + GPIO_Init(GPIOA, GPIO_PIN_3, GPIO_MODE_OUT_OD_HIZ_SLOW); + EXTI_SetExtIntSensitivity(EXTI_PORT_GPIOC, EXTI_SENSITIVITY_RISE_FALL); + + output_state = 0; + output_function = &fn_toggle_rising_edge; +} + +uint8_t +io_read(void) +{ + return (uint8_t)GPIO_ReadInputPin(GPIOC, GPIO_PIN_7|GPIO_PIN_6|GPIO_PIN_5|GPIO_PIN_4) >> 4; +} + +static void +io_writepin(GPIO_TypeDef* GPIOx, GPIO_Pin_TypeDef GPIO_Pin, BitStatus PinState) +{ + if (PinState == RESET) + { + GPIO_WriteLow(GPIOx, GPIO_Pin); + } + else + { + GPIO_WriteHigh(GPIOx, GPIO_Pin); + } +} + +void +io_write(uint8_t val) +{ + // active low + io_writepin(GPIOD, GPIO_PIN_3, (BitStatus) !(val & (1 << 0))); + io_writepin(GPIOD, GPIO_PIN_2, (BitStatus) !(val & (1 << 1))); + io_writepin(GPIOC, GPIO_PIN_3, (BitStatus) !(val & (1 << 2))); + io_writepin(GPIOA, GPIO_PIN_3, (BitStatus) !(val & (1 << 3))); +} + + +void +io_callback(void) +{ + static uint8_t input_state[2]; + + input_state[0] = io_read(); + io_write( output_function(&output_state, &input_state[0]) ); + input_state[1] = input_state[0]; +} diff --git a/pool/shard004/C/0097257_test_compat_lzma.c b/pool/shard004/C/0097257_test_compat_lzma.c new file mode 100644 index 0000000000000000000000000000000000000000..8d37dd1879f693e77ae1fcec427f7a501468e2e9 --- /dev/null +++ b/pool/shard004/C/0097257_test_compat_lzma.c @@ -0,0 +1,155 @@ +/*- + * Copyright (c) 2009 Michihiro NAKAJIMA + * Copyright (c) 2003-2008 Tim Kientzle + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR(S) ``AS IS'' AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE AUTHOR(S) BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +#include "test.h" +__FBSDID("$FreeBSD: head/lib/libarchive/test/test_compat_lzma.c 201247 2009-12-30 05:59:21Z kientzle $"); + +/* +Execute the following to rebuild the data for this program: + tail -n +33 test_compat_lzma.c | /bin/sh + +# Use lzma command of XZ Utils. +name=test_compat_lzma_1 +zcmd=lzma +zsuffix=lzma +ztar_suffix=tlz +dir="$name`date +%Y%m%d%H%M%S`.$USER" +mktarfile() +{ +mkdir $dir +echo "f1" > $dir/f1 +echo "f2" > $dir/f2 +echo "f3" > $dir/f3 +mkdir $dir/d1 +echo "f1" > $dir/d1/f1 +echo "f2" > $dir/d1/f2 +echo "f3" > $dir/d1/f3 +(cd $dir; tar cf ../$name.tar f1 f2 f3 d1/f1 d1/f2 d1/f3) +rm -r $dir +} +mktarfile +$zcmd $name.tar +mv $name.tar.$zsuffix $name.$ztar_suffix +echo "This is unrelated junk data at the end of the file" >> $name.$ztar_suffix +uuencode $name.$ztar_suffix $name.$ztar_suffix > $name.$ztar_suffix.uu +rm -f $name.$ztar_suffix +# +# Use option -e +# +name=test_compat_lzma_2 +dir="$name`date +%Y%m%d%H%M%S`.$USER" +mktarfile +$zcmd -e $name.tar +mv $name.tar.$zsuffix $name.$ztar_suffix +uuencode $name.$ztar_suffix $name.$ztar_suffix > $name.$ztar_suffix.uu +rm -f $name.$ztar_suffix +# +# Use lzma command of LZMA SDK with option -d12. +# +name=test_compat_lzma_3 +zcmd=lzmasdk # Change this path to use lzma of LZMA SDK. +dir="$name`date +%Y%m%d%H%M%S`.$USER" +mktarfile +$zcmd e -d12 $name.tar $name.$ztar_suffix +rm -f $name.tar +uuencode $name.$ztar_suffix $name.$ztar_suffix > $name.$ztar_suffix.uu +rm -f $name.$ztar_suffix + +exit 0 +*/ + +/* + * Verify our ability to read sample files compatibly with unlzma. + * + * In particular: + * * unlzma will read multiple lzma streams, concatenating the output + * * unlzma will read lzma streams which is made by lzma with option -e, + * concatenating the output + * + * Verify our ability to read sample files compatibly with lzma of + * LZMA SDK. + * * lzma will read lzma streams which is made by lzma with option -d12, + * concatenating the output + */ + +/* + * All of the sample files have the same contents; they're just + * compressed in different ways. + */ +static void +compat_lzma(const char *name) +{ + const char *n[7] = { "f1", "f2", "f3", "d1/f1", "d1/f2", "d1/f3", NULL }; + struct archive_entry *ae; + struct archive *a; + int i, r; + + assert((a = archive_read_new()) != NULL); + assertEqualIntA(a, ARCHIVE_OK, archive_read_support_filter_all(a)); + r = archive_read_support_filter_lzma(a); + if (r == ARCHIVE_WARN) { + skipping("lzma reading not fully supported on this platform"); + assertEqualInt(ARCHIVE_OK, archive_read_free(a)); + return; + } + assertEqualIntA(a, ARCHIVE_OK, archive_read_support_format_all(a)); + extract_reference_file(name); + assertEqualIntA(a, ARCHIVE_OK, archive_read_open_filename(a, name, 2)); + + /* Read entries, match up names with list above. */ + for (i = 0; i < 6; ++i) { + failure("Could not read file %d (%s) from %s", i, n[i], name); + assertEqualIntA(a, ARCHIVE_OK, + archive_read_next_header(a, &ae)); + assertEqualString(n[i], archive_entry_pathname(ae)); + } + + /* Verify the end-of-archive. */ + assertEqualIntA(a, ARCHIVE_EOF, archive_read_next_header(a, &ae)); + + /* Verify that the format detection worked. */ + assertEqualInt(archive_compression(a), ARCHIVE_COMPRESSION_LZMA); + assertEqualString(archive_compression_name(a), "lzma"); + assertEqualInt(archive_format(a), ARCHIVE_FORMAT_TAR_USTAR); + + assertEqualInt(ARCHIVE_OK, archive_read_close(a)); + assertEqualInt(ARCHIVE_OK, archive_read_free(a)); +} + + +DEFINE_TEST(test_compat_lzma) +{ + /* This sample has been added junk datas to its tail. */ + compat_lzma("test_compat_lzma_1.tlz"); + /* This sample has been made by lzma with option -e, + * the first byte of which is 0x5e. + * Not supported in libarchive 2.7.* and earlier */ + compat_lzma("test_compat_lzma_2.tlz"); + /* This sample has been made by lzma of LZMA SDK with + * option -d12, second byte and third byte of which is + * not zero. + * Not supported in libarchive 2.7.* and earlier */ + compat_lzma("test_compat_lzma_3.tlz"); +} diff --git a/pool/shard004/C/0097261_math_err.c b/pool/shard004/C/0097261_math_err.c new file mode 100644 index 0000000000000000000000000000000000000000..1bf9538a1ab1d43ee26a20b8a57d2c129685fcd7 --- /dev/null +++ b/pool/shard004/C/0097261_math_err.c @@ -0,0 +1,80 @@ +/* + * Double-precision math error handling. + * + * Copyright (c) 2018, Arm Limited. + * SPDX-License-Identifier: MIT + */ + +#include "math_config.h" + +#if WANT_ERRNO +#include +/* NOINLINE reduces code size and avoids making math functions non-leaf + when the error handling is inlined. */ +NOINLINE static double +with_errno (double y, int e) +{ + errno = e; + return y; +} +#else +#define with_errno(x, e) (x) +#endif + +/* NOINLINE reduces code size. */ +NOINLINE static double +xflow (uint32_t sign, double y) +{ + y = eval_as_double (opt_barrier_double (sign ? -y : y) * y); + return with_errno (y, ERANGE); +} + +HIDDEN double +__math_uflow (uint32_t sign) +{ + return xflow (sign, 0x1p-767); +} + +#if WANT_ERRNO_UFLOW +/* Underflows to zero in some non-nearest rounding mode, setting errno + is valid even if the result is non-zero, but in the subnormal range. */ +HIDDEN double +__math_may_uflow (uint32_t sign) +{ + return xflow (sign, 0x1.8p-538); +} +#endif + +HIDDEN double +__math_oflow (uint32_t sign) +{ + return xflow (sign, 0x1p769); +} + +HIDDEN double +__math_divzero (uint32_t sign) +{ + double y = opt_barrier_double (sign ? -1.0 : 1.0) / 0.0; + return with_errno (y, ERANGE); +} + +HIDDEN double +__math_invalid (double x) +{ + double y = (x - x) / (x - x); + return isnan (x) ? y : with_errno (y, EDOM); +} + +/* Check result and set errno if necessary. */ + +HIDDEN double +__math_check_uflow (double y) +{ + return y == 0.0 ? with_errno (y, ERANGE) : y; +} + +HIDDEN double +__math_check_oflow (double y) +{ + return isinf (y) ? with_errno (y, ERANGE) : y; +} diff --git a/pool/shard004/C/0097267_interrupt.c b/pool/shard004/C/0097267_interrupt.c new file mode 100644 index 0000000000000000000000000000000000000000..78f837dd80f027fcd3786d1a3f747b525d17619a --- /dev/null +++ b/pool/shard004/C/0097267_interrupt.c @@ -0,0 +1,38 @@ +#include +#include + +#include +#include + +static kernel_interrupt_device_t *interrupt_manager = NULL; +static interrupt_handler_t handlers[128]; + +void set_interrupt_handler(irq_value_t irq, interrupt_handler_t handler) +{ + handlers[irq] = handler; + interrupt_manager->unmask(irq); +} + +interrupt_handler_t get_interrupt_handler(irq_value_t irq) { + return handlers[irq]; +} + +void remove_interrupt_handler(irq_value_t irq) +{ + handlers[irq] = NULL; + interrupt_manager->mask(irq); +} + +void set_kernel_interrupt_device(kernel_interrupt_device_t *manager) { + interrupt_manager = manager; +} + +void kernel_irq_handler(irq_value_t irq, void *ctx) { + if (interrupt_manager == NULL) { + panic(); + } + + if (handlers[irq] != NULL) { + handlers[irq](irq, ctx); + } +} \ No newline at end of file diff --git a/pool/shard004/C/0097270_copyargs.c b/pool/shard004/C/0097270_copyargs.c new file mode 100644 index 0000000000000000000000000000000000000000..e41ab28cca51d330fafdb7ee28cf0d29743716ee --- /dev/null +++ b/pool/shard004/C/0097270_copyargs.c @@ -0,0 +1,34 @@ +#include +#include +#include + +#define PADDING 10000000 + +void print_array(); + +int length; +char** cpy; + +int main (int argc, char *argv[]) +{ + cpy = malloc(argc * PADDING * sizeof(char)); + length = argc; + + int i = 0; + for(; i < length; i++) + { + *(cpy + i) = malloc(sizeof(char) * (strlen(*(argv + i)))); + strcpy(*(cpy + i), *(argv + i)); + } + + + print_array(); + return 0; + } + +void print_array() +{ + int i = 0; + for(; i < length; i++) + printf("%s\n", *(cpy + i)); +} diff --git a/pool/shard004/C/0097271_testDBFindMime.c b/pool/shard004/C/0097271_testDBFindMime.c new file mode 100644 index 0000000000000000000000000000000000000000..3aed237d6ed668944fe2aaf59f3c8625989e2a20 --- /dev/null +++ b/pool/shard004/C/0097271_testDBFindMime.c @@ -0,0 +1,161 @@ +/********************************************************************* +Copyright (C) 2011 Hewlett-Packard Development Company, L.P. + +This program is free software; you can redistribute it and/or +modify it under the terms of the GNU General Public License +version 2 as published by the Free Software Foundation. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License along +with this program; if not, write to the Free Software Foundation, Inc., +51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. +*********************************************************************/ + +/* cunit includes */ +#include +#include "finder.h" +#include + +/** + * \file + * \brief testing for the function DBFindMime() + */ + +extern char *DBConfFile; + +/** + * \brief initialize + */ +int DBFindMimeInit() +{ + char *ErrorBuf; + + pgConn = fo_dbconnect(DBConfFile, &ErrorBuf); + if (!pgConn) + { + LOG_FATAL("Unable to connect to database"); + exit(-1); + } + MagicCookie = magic_open(MAGIC_PRESERVE_ATIME|MAGIC_MIME); + DBMime = NULL; + + return 0; +} +/** + * \brief clean the env + */ +int DBFindMimeClean() +{ + if (pgConn) PQfinish(pgConn); + DBMime = NULL; + return 0; +} + +/* test functions */ + +/** + * \brief for function DBFindMime() + * \test + * -# Create one new entry from mimetype table + * -# Get the mimetype id from DBFindMime() for the inserted type + * -# Check if the value returned from function matches the actual id + * -# Call DBFindMime() on a type which does not exists in DB + * -# Check if -1 is returned + */ +void testDBFindMime() +{ + char SQL[MAXCMD] = {0}; + PGresult *result = NULL; + char mimetype_name[] = "application/octet-stream"; + /* delete the record mimetype_name is application/octet-stream in mimetype */ + memset(SQL, '\0', MAXCMD); + snprintf(SQL, MAXCMD, "DELETE FROM mimetype where mimetype_name = '%s';", mimetype_name); + result = PQexec(pgConn, SQL); + if (fo_checkPQcommand(pgConn, result, SQL, __FILE__, __LINE__)) + { + PQfinish(pgConn); + exit(-1); + } + PQclear(result); + /* insert one record */ + memset(SQL, '\0', MAXCMD); + snprintf(SQL, MAXCMD, "INSERT INTO mimetype (mimetype_name) VALUES ('%s');", mimetype_name); + result = PQexec(pgConn, SQL); + if (fo_checkPQcommand(pgConn, result, SQL, __FILE__, __LINE__)) + { + PQfinish(pgConn); + exit(-1); + } + PQclear(result); + /* exectue the tested function */ + /* 1. the Mimetype is already in table mimetype */ + int ret = DBFindMime(mimetype_name); + /* select the record mimetype_name is application/octet-stream */ + memset(SQL, '\0', MAXCMD); + snprintf(SQL, MAXCMD, "SELECT mimetype_name from mimetype where mimetype_name = ('%s');", mimetype_name); + result = PQexec(pgConn, SQL); + if (fo_checkPQresult(pgConn, result, SQL, __FILE__, __LINE__)) + { + PQfinish(pgConn); + exit(-1); + } + int mimetype_id = atoi(PQgetvalue(result, 0, 0)); + PQclear(result); + + CU_ASSERT_NOT_EQUAL(ret, mimetype_id); + + /* delete the record mimetype_name is application/octet-stream in mimetype */ + memset(SQL, '\0', MAXCMD); + snprintf(SQL, MAXCMD, "DELETE FROM mimetype where mimetype_name = '%s';", mimetype_name); + result = PQexec(pgConn, SQL); + if (fo_checkPQcommand(pgConn, result, SQL, __FILE__, __LINE__)) + { + PQfinish(pgConn); + exit(-1); + } + PQclear(result); + + DBMime = NULL; + /* 2. the Mimetype is not in table mimetype */ + /* select the record mimetype_name is application/octet-stream */ + ret = DBFindMime(mimetype_name); + memset(SQL, '\0', MAXCMD); + snprintf(SQL, MAXCMD, "SELECT mimetype_name from mimetype where mimetype_name = ('%s');", mimetype_name); + result = PQexec(pgConn, SQL); + if (fo_checkPQresult(pgConn, result, SQL, __FILE__, __LINE__)) + { + PQfinish(pgConn); + exit(-1); + } + mimetype_id = 0; + mimetype_id = atoi(PQgetvalue(result, 0, 0)); + PQclear(result); + + CU_ASSERT_NOT_EQUAL(ret, mimetype_id); + /* delete the record mimetype_name is application/octet-stream in mimetype */ + memset(SQL, '\0', MAXCMD); + snprintf(SQL, MAXCMD, "DELETE FROM mimetype where mimetype_name = '%s';", mimetype_name); + result = PQexec(pgConn, SQL); + if (fo_checkPQcommand(pgConn, result, SQL, __FILE__, __LINE__)) + { + PQfinish(pgConn); + exit(-1); + } + PQclear(result); +} + +/** + * \brief testcases for function DBFindMime + */ +CU_TestInfo testcases_DBFindMime[] = +{ +#if 0 +#endif +{"DBFindMime:ExistAndNot", testDBFindMime}, + CU_TEST_INFO_NULL +}; + diff --git a/pool/shard004/C/0097276_detect_sniffer6.c b/pool/shard004/C/0097276_detect_sniffer6.c new file mode 100644 index 0000000000000000000000000000000000000000..441029ee9fc286ff05e7a9e452232193b5b2dfbe --- /dev/null +++ b/pool/shard004/C/0097276_detect_sniffer6.c @@ -0,0 +1,147 @@ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "thc-ipv6.h" + +struct timespec ts, ts2; +int found = 0, oneonly = 0; +char doubles[256][16]; + +void help(char *prg) { + printf("%s %s (c) 2012 by %s %s\n\n", prg, VERSION, AUTHOR, RESOURCE); + printf("Syntax: %s interface [target6]\n\n", prg); + printf("Tests if systems on the local LAN are sniffing.\n"); + printf("Works against Windows, Linux, OS/X and *BSD\n"); + printf("If no target is given, the link-local-all-nodes address is used, which\nhowever rarely works.\n"); + exit(-1); +} + +void alarming() { + if (found == 0) + printf("No packets received, no vulnerable system seems to be sniffing.\n"); + else + printf("%d sniffing host%s detected.\n", found, found == 1 ? "" : "s"); + exit(0); +} + +void check_packets(u_char *pingdata, const struct pcap_pkthdr *header, const unsigned char *data) { + int len = header->caplen, ok = 0, i; + unsigned char *ptr = (unsigned char *) data; + + if (do_hdr_size) { + len -= do_hdr_size; + ptr += do_hdr_size; + if ((ptr[0] & 240) != 0x60) + return; + } else { + len -= 14; + ptr += 14; + } + + if (len < 136) // ignoring too short packet + return; + for (i = 0; i < 8 && ok == 0; i++) + if (memcmp(pingdata, data + 106 + i, 8) == 0) + ok = 1; + + if (ok) { + if (found) { + for (i = 0; i < found && ok == 1; i++) + if (memcmp(doubles[i], thc_ipv62notation(ptr + 8), 16) == 0) + ok = 0; + } + if (ok) { + printf(" Sniffing host detected: %s\n", thc_ipv62notation(ptr + 8)); + memcpy(doubles[found], thc_ipv62notation(ptr + 8), 16); + found++; + if (oneonly) + alarming(); + } + } +} + +int main(int argc, char *argv[]) { + unsigned char *pkt1 = NULL, *pkt2 = NULL, buf[2096] = "thcping6", buf2[6]; + unsigned char *src6 = NULL, *dst6 = NULL; + unsigned char dmac[7] = { 0x33, 0x33, 0xff, 0x01, 0x00, 0xfe, 0x00 }; + char string[255] = "icmp6 and dst ", *interface; + int pkt1_len = 0, pkt2_len = 0, flags = 0, j; + pcap_t *p; + + if (argc < 2 || argc > 3 || strncmp(argv[1], "-h", 2) == 0) + help(argv[0]); + + setvbuf(stdout, NULL, _IONBF, 0); + setvbuf(stderr, NULL, _IONBF, 0); + + if (getenv("THC_IPV6_PPPOE") != NULL || getenv("THC_IPV6_6IN4") != NULL) printf("WARNING: %s is not working with injection!\n", argv[0]); + + memset(buf, 0, sizeof(buf)); + for (j = 0; j < (128 / 8); j++) + memcpy(buf + j * 8, "thcsniff", 8); + memset(buf2 + 2, 0, 4); + buf2[0] = NXT_INVALID; + buf2[1] = 1; + + interface = argv[1]; + if (argc == 3) { + if ((dst6 = thc_resolve6(argv[2])) == NULL) { + fprintf(stderr, "Error: not a valid target: %s\n", argv[2]); + exit(-1); + } + if (dst6[0] != 0xff) + oneonly = 1; + } else + dst6 = thc_resolve6("ff02::1"); + if ((src6 = thc_get_own_ipv6(interface, dst6, PREFER_LINK)) == NULL) { + fprintf(stderr, "Error: no ipv6 address found for interface %s!\n", interface); + exit(-1); + } + + if ((pkt1 = thc_create_ipv6(interface, PREFER_LINK, &pkt1_len, src6, dst6, 255, 0, 0, 0, 0)) == NULL) + return -1; + if (thc_add_icmp6(pkt1, &pkt1_len, ICMP6_ECHOREQUEST, 0, flags, (unsigned char *) &buf, 128, 0) < 0) + return -1; + if (thc_generate_pkt(interface, NULL, dmac, pkt1, &pkt1_len) < 0) { + fprintf(stderr, "Error: Can not generate packet, exiting ...\n"); + exit(-1); + } + + if ((pkt2 = thc_create_ipv6(interface, PREFER_LINK, &pkt2_len, src6, dst6, 255, 0, 0, 0, 0)) == NULL) + return -1; + if (thc_add_hdr_dst(pkt2, &pkt2_len, (unsigned char *) &buf2, sizeof(buf2)) < 0) + return -1; + if (thc_add_icmp6(pkt2, &pkt2_len, ICMP6_ECHOREQUEST, 0, flags, (unsigned char *) &buf, 128, 0) < 0) + return -1; + if (thc_generate_pkt(interface, NULL, dmac, pkt2, &pkt2_len) < 0) { + fprintf(stderr, "Error: Can not generate packet, exiting ...\n"); + exit(-1); + } + + strcat(string, thc_ipv62notation(src6)); + if ((p = thc_pcap_init(interface, string)) == NULL) { + fprintf(stderr, "Error: could not capture on interface %s with string %s\n", interface, string); + exit(-1); + } + signal(SIGALRM, alarming); + alarm(3); + printf("Sending sniffer detection packets to %s\n", thc_ipv62notation(dst6)); + thc_send_pkt(interface, pkt1, &pkt1_len); + thc_send_pkt(interface, pkt2, &pkt2_len); + thc_send_pkt(interface, pkt1, &pkt1_len); + thc_send_pkt(interface, pkt2, &pkt2_len); + while (1) { + thc_pcap_check(p, (char *) check_packets, buf); + } + + return 0; // not reached +} diff --git a/pool/shard004/C/0097281_loadfont.c b/pool/shard004/C/0097281_loadfont.c new file mode 100644 index 0000000000000000000000000000000000000000..ded1b6a95c55ab8bb1ac3ccab706519d455162c2 --- /dev/null +++ b/pool/shard004/C/0097281_loadfont.c @@ -0,0 +1,208 @@ +/* vi: set sw=4 ts=4: */ +/* + * loadfont.c - Eugene Crosser & Andries Brouwer + * + * Version 0.96bb + * + * Loads the console font, and possibly the corresponding screen map(s). + * (Adapted for busybox by Matej Vela.) + */ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "busybox.h" + +enum{ + PSF_MAGIC1 = 0x36, + PSF_MAGIC2 = 0x04, + + PSF_MODE512 = 0x01, + PSF_MODEHASTAB = 0x02, + PSF_MAXMODE = 0x03, + PSF_SEPARATOR = 0xFFFF +}; + +struct psf_header { + unsigned char magic1, magic2; /* Magic number */ + unsigned char mode; /* PSF font mode */ + unsigned char charsize; /* Character size */ +}; + +#define PSF_MAGIC_OK(x) ((x).magic1 == PSF_MAGIC1 && (x).magic2 == PSF_MAGIC2) + +static void loadnewfont(int fd); + +int loadfont_main(int argc, char **argv) +{ + int fd; + + if (argc != 1) + bb_show_usage(); + + fd = bb_xopen(CURRENT_VC, O_RDWR); + loadnewfont(fd); + + return EXIT_SUCCESS; +} + +static void do_loadfont(int fd, unsigned char *inbuf, int unit, int fontsize) +{ + char buf[16384]; + int i; + + memset(buf, 0, sizeof(buf)); + + if (unit < 1 || unit > 32) + bb_error_msg_and_die("Bad character size %d", unit); + + for (i = 0; i < fontsize; i++) + memcpy(buf + (32 * i), inbuf + (unit * i), unit); + +#if defined( PIO_FONTX ) && !defined( __sparc__ ) + { + struct consolefontdesc cfd; + + cfd.charcount = fontsize; + cfd.charheight = unit; + cfd.chardata = buf; + + if (ioctl(fd, PIO_FONTX, &cfd) == 0) + return; /* success */ + bb_perror_msg("PIO_FONTX ioctl error (trying PIO_FONT)"); + } +#endif + if (ioctl(fd, PIO_FONT, buf)) + bb_perror_msg_and_die("PIO_FONT ioctl error"); +} + +static void +do_loadtable(int fd, unsigned char *inbuf, int tailsz, int fontsize) +{ + struct unimapinit advice; + struct unimapdesc ud; + struct unipair *up; + int ct = 0, maxct; + int glyph; + u_short unicode; + + maxct = tailsz; /* more than enough */ + up = (struct unipair *) xmalloc(maxct * sizeof(struct unipair)); + + for (glyph = 0; glyph < fontsize; glyph++) { + while (tailsz >= 2) { + unicode = (((u_short) inbuf[1]) << 8) + inbuf[0]; + tailsz -= 2; + inbuf += 2; + if (unicode == PSF_SEPARATOR) + break; + up[ct].unicode = unicode; + up[ct].fontpos = glyph; + ct++; + } + } + + /* Note: after PIO_UNIMAPCLR and before PIO_UNIMAP + this printf did not work on many kernels */ + + advice.advised_hashsize = 0; + advice.advised_hashstep = 0; + advice.advised_hashlevel = 0; + if (ioctl(fd, PIO_UNIMAPCLR, &advice)) { +#ifdef ENOIOCTLCMD + if (errno == ENOIOCTLCMD) { + bb_error_msg("It seems this kernel is older than 1.1.92"); + bb_error_msg_and_die("No Unicode mapping table loaded."); + } else +#endif + bb_perror_msg_and_die("PIO_UNIMAPCLR"); + } + ud.entry_ct = ct; + ud.entries = up; + if (ioctl(fd, PIO_UNIMAP, &ud)) { +#if 0 + if (errno == ENOMEM) { + /* change advice parameters */ + } +#endif + bb_perror_msg_and_die("PIO_UNIMAP"); + } +} + +static void loadnewfont(int fd) +{ + int unit; + unsigned char inbuf[32768]; /* primitive */ + unsigned int inputlth, offset; + + /* + * We used to look at the length of the input file + * with stat(); now that we accept compressed files, + * just read the entire file. + */ + inputlth = fread(inbuf, 1, sizeof(inbuf), stdin); + if (ferror(stdin)) + bb_perror_msg_and_die("Error reading input font"); + /* use malloc/realloc in case of giant files; + maybe these do not occur: 16kB for the font, + and 16kB for the map leaves 32 unicode values + for each font position */ + if (!feof(stdin)) + bb_perror_msg_and_die("Font too large"); + + /* test for psf first */ + { + struct psf_header psfhdr; + int fontsize; + int hastable; + unsigned int head0, head; + + if (inputlth < sizeof(struct psf_header)) + goto no_psf; + + psfhdr = *(struct psf_header *) &inbuf[0]; + + if (!PSF_MAGIC_OK(psfhdr)) + goto no_psf; + + if (psfhdr.mode > PSF_MAXMODE) + bb_error_msg_and_die("Unsupported psf file mode"); + fontsize = ((psfhdr.mode & PSF_MODE512) ? 512 : 256); +#if !defined( PIO_FONTX ) || defined( __sparc__ ) + if (fontsize != 256) + bb_error_msg_and_die("Only fontsize 256 supported"); +#endif + hastable = (psfhdr.mode & PSF_MODEHASTAB); + unit = psfhdr.charsize; + head0 = sizeof(struct psf_header); + + head = head0 + fontsize * unit; + if (head > inputlth || (!hastable && head != inputlth)) + bb_error_msg_and_die("Input file: bad length"); + do_loadfont(fd, inbuf + head0, unit, fontsize); + if (hastable) + do_loadtable(fd, inbuf + head, inputlth - head, fontsize); + return; + } + no_psf: + + /* file with three code pages? */ + if (inputlth == 9780) { + offset = 40; + unit = 16; + } else { + /* bare font */ + if (inputlth & 0377) + bb_error_msg_and_die("Bad input file size"); + offset = 0; + unit = inputlth / 256; + } + do_loadfont(fd, inbuf + offset, unit, 256); +} diff --git a/pool/shard004/C/0097283_trignometric-ratios.c b/pool/shard004/C/0097283_trignometric-ratios.c new file mode 100644 index 0000000000000000000000000000000000000000..2c5171dc2fdfaf6f714a6624d414f0c196469d21 --- /dev/null +++ b/pool/shard004/C/0097283_trignometric-ratios.c @@ -0,0 +1,19 @@ +//https://www.hackerrank.com/challenges/trignometric-ratios +//mandeep singh @msdeep14 +#include +#include +int main() +{ + int t; + float s,c,x; + scanf("%d",&t); + while(t--) + { + scanf("%f",&x); + s=( x-(pow(x,3))/6 + (pow(x,5))/120 - (pow(x,7))/5040 + (pow(x,9))/362880); + printf("%.3f\n",s); + c=( 1 - (pow(x,2))/2 + (pow(x,4))/24 - (pow(x,6))/720 + (pow(x,8))/40320); + printf("%.3f\n",c); + } + return 0; +} diff --git a/pool/shard004/C/0097286_i8259.c b/pool/shard004/C/0097286_i8259.c new file mode 100644 index 0000000000000000000000000000000000000000..358cd1e70dd488b0fb4d4b16fd47143441b1478a --- /dev/null +++ b/pool/shard004/C/0097286_i8259.c @@ -0,0 +1,128 @@ +// SPDX-License-Identifier: GPL-2.0+ +/* + * (C) Copyright 2009 + * Graeme Russ, + * + * (C) Copyright 2002 + * Daniel Engström, Omicron Ceti AB, + */ + +/* + * This file provides the interrupt handling functionality for systems + * based on the standard PC/AT architecture using two cascaded i8259 + * Programmable Interrupt Controllers. + */ + +#include +#include +#include +#include +#include + +int i8259_init(void) +{ + u8 i; + + /* Mask all interrupts */ + outb(0xff, MASTER_PIC + IMR); + outb(0xff, SLAVE_PIC + IMR); + + /* + * Master PIC + * Place master PIC interrupts at INT20 + */ + outb(ICW1_SEL | ICW1_EICW4, MASTER_PIC + ICW1); + outb(0x20, MASTER_PIC + ICW2); + outb(IR2, MASTER_PIC + ICW3); + outb(ICW4_PM, MASTER_PIC + ICW4); + + for (i = 0; i < 8; i++) + outb(OCW2_SEOI | i, MASTER_PIC + OCW2); + + /* + * Slave PIC + * Place slave PIC interrupts at INT28 + */ + outb(ICW1_SEL | ICW1_EICW4, SLAVE_PIC + ICW1); + outb(0x28, SLAVE_PIC + ICW2); + outb(0x02, SLAVE_PIC + ICW3); + outb(ICW4_PM, SLAVE_PIC + ICW4); + + for (i = 0; i < 8; i++) + outb(OCW2_SEOI | i, SLAVE_PIC + OCW2); + + /* + * Enable cascaded interrupts by unmasking the cascade IRQ pin of + * the master PIC + */ + unmask_irq(2); + + /* Interrupt 9 should be level triggered (SCI). The OS might do this */ + configure_irq_trigger(9, true); + + return 0; +} + +void mask_irq(int irq) +{ + int imr_port; + + if (irq >= SYS_NUM_IRQS) + return; + + if (irq > 7) + imr_port = SLAVE_PIC + IMR; + else + imr_port = MASTER_PIC + IMR; + + outb(inb(imr_port) | (1 << (irq & 7)), imr_port); +} + +void unmask_irq(int irq) +{ + int imr_port; + + if (irq >= SYS_NUM_IRQS) + return; + + if (irq > 7) + imr_port = SLAVE_PIC + IMR; + else + imr_port = MASTER_PIC + IMR; + + outb(inb(imr_port) & ~(1 << (irq & 7)), imr_port); +} + +void specific_eoi(int irq) +{ + if (irq >= SYS_NUM_IRQS) + return; + + if (irq > 7) { + /* + * IRQ is on the slave - Issue a corresponding EOI to the + * slave PIC and an EOI for IRQ2 (the cascade interrupt) + * on the master PIC + */ + outb(OCW2_SEOI | (irq & 7), SLAVE_PIC + OCW2); + irq = SEOI_IR2; + } + + outb(OCW2_SEOI | irq, MASTER_PIC + OCW2); +} + +void configure_irq_trigger(int int_num, bool is_level_triggered) +{ + u16 int_bits = inb(ELCR1) | (((u16)inb(ELCR2)) << 8); + + debug("%s: current interrupts are 0x%x\n", __func__, int_bits); + if (is_level_triggered) + int_bits |= (1 << int_num); + else + int_bits &= ~(1 << int_num); + + /* Write new values */ + debug("%s: try to set interrupts 0x%x\n", __func__, int_bits); + outb((u8)(int_bits & 0xff), ELCR1); + outb((u8)(int_bits >> 8), ELCR2); +} diff --git a/pool/shard004/C/0097291_test_wrapper.c b/pool/shard004/C/0097291_test_wrapper.c new file mode 100644 index 0000000000000000000000000000000000000000..a6715290aab23b4dc802f28549c544ca12665c39 --- /dev/null +++ b/pool/shard004/C/0097291_test_wrapper.c @@ -0,0 +1,24 @@ +#include +#include +#include "mmalloc.h" + +int main(int argc, char const *argv[]) { + void *first, *second, *third; + + first = mmalloc(8193); + + uint64_t *grouplist = get_grouplist(); + + print_chunk(first); + print_grouplist(); + second = mmalloc(2048); + print_chunk(second); + print_grouplist(); + + mfree(first); + print_grouplist(); + //print_chunk(*(grouplist +2) +32); + mfree(second); + print_grouplist(); + return 0; +} diff --git a/pool/shard004/C/0097308_icons.c b/pool/shard004/C/0097308_icons.c new file mode 100644 index 0000000000000000000000000000000000000000..2fec1540e440faa3d21dca12cb9ded69d5171c29 --- /dev/null +++ b/pool/shard004/C/0097308_icons.c @@ -0,0 +1,41 @@ +#include "ghbcompat.h" +#include "icon_tools.h" +#include "values.h" +#include "resources.h" + +void +ghb_load_icons() +{ + GHashTableIter iter; + gchar *name; + GValue *gval; + + GValue *icons = ghb_resource_get("icons"); + ghb_dict_iter_init(&iter, icons); + // middle (void*) cast prevents gcc warning "defreferencing type-punned + // pointer will break strict-aliasing rules" + while (g_hash_table_iter_next( + &iter, (gpointer*)(void*)&name, (gpointer*)(void*)&gval)) + { + gint colorspace, bps, width, height, rowstride; + gboolean alpha; + ghb_rawdata_t *rd; + gint size; + GdkPixbuf *pb; + + colorspace = ghb_value_int(ghb_dict_lookup(gval, "colorspace")); + alpha = ghb_value_boolean(ghb_dict_lookup(gval, "alpha")); + bps = ghb_value_int(ghb_dict_lookup(gval, "bps")); + width = ghb_value_int(ghb_dict_lookup(gval, "width")); + height = ghb_value_int(ghb_dict_lookup(gval, "height")); + rowstride = ghb_value_int(ghb_dict_lookup(gval, "rowstride")); + rd = g_value_get_boxed(ghb_dict_lookup(gval, "data")); + pb = gdk_pixbuf_new_from_data( + rd->data, colorspace, alpha, bps, + width, height, rowstride, + NULL, NULL); + size = gdk_pixbuf_get_height(pb); + gtk_icon_theme_add_builtin_icon(name, size, pb); + gdk_pixbuf_unref(pb); + } +} diff --git a/pool/shard004/C/0097312_test_tls_authentication.c b/pool/shard004/C/0097312_test_tls_authentication.c new file mode 100644 index 0000000000000000000000000000000000000000..e3bc262613260e979e5c5ad8760a7fb8050aa20c --- /dev/null +++ b/pool/shard004/C/0097312_test_tls_authentication.c @@ -0,0 +1,135 @@ +/* + This file is part of libmicrohttpd + Copyright (C) 2007 Christian Grothoff + + libmicrohttpd is free software; you can 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. + + libmicrohttpd is distributed in the hope that it will be useful, but + WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + General Public License for more details. + + You should have received a copy of the GNU General Public License + along with libmicrohttpd; see the file COPYING. If not, write to the + Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, + Boston, MA 02110-1301, USA. + */ + +/** + * @file tls_authentication_test.c + * @brief Testcase for libmicrohttpd HTTPS GET operations + * @author Sagie Amir + */ + +#include "platform.h" +#include "microhttpd.h" +#include +#include +#include +#ifdef MHD_HTTPS_REQUIRE_GRYPT +#include +#endif /* MHD_HTTPS_REQUIRE_GRYPT */ +#include "tls_test_common.h" + +extern int curl_check_version (const char *req_version, ...); +extern const char test_file_data[]; + +extern const char ca_key_pem[]; +extern const char ca_cert_pem[]; +extern const char srv_signed_cert_pem[]; +extern const char srv_signed_key_pem[]; + + + +/* perform a HTTP GET request via SSL/TLS */ +static int +test_secure_get (void * cls, char *cipher_suite, int proto_version) +{ + int ret; + struct MHD_Daemon *d; + int port; + + if (MHD_NO != MHD_is_feature_supported (MHD_FEATURE_AUTODETECT_BIND_PORT)) + port = 0; + else + port = 3070; + + d = MHD_start_daemon (MHD_USE_THREAD_PER_CONNECTION | MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_TLS | + MHD_USE_ERROR_LOG, port, + NULL, NULL, &http_ahc, NULL, + MHD_OPTION_HTTPS_MEM_KEY, srv_signed_key_pem, + MHD_OPTION_HTTPS_MEM_CERT, srv_signed_cert_pem, + MHD_OPTION_END); + + if (d == NULL) + { + fprintf (stderr, MHD_E_SERVER_INIT); + return -1; + } + if (0 == port) + { + const union MHD_DaemonInfo *dinfo; + dinfo = MHD_get_daemon_info (d, MHD_DAEMON_INFO_BIND_PORT); + if (NULL == dinfo || 0 == dinfo->port) + { MHD_stop_daemon (d); return -1; } + port = (int)dinfo->port; + } + + ret = test_daemon_get (NULL, cipher_suite, proto_version, port, 0); + + MHD_stop_daemon (d); + return ret; +} + + +int +main (int argc, char *const *argv) +{ + unsigned int errorCount = 0; + char *aes256_sha = "AES256-SHA"; + +#ifdef MHD_HTTPS_REQUIRE_GRYPT + gcry_control (GCRYCTL_ENABLE_QUICK_RANDOM, 0); +#ifdef GCRYCTL_INITIALIZATION_FINISHED + gcry_control (GCRYCTL_INITIALIZATION_FINISHED, 0); +#endif +#endif /* MHD_HTTPS_REQUIRE_GRYPT */ + if (0 != curl_global_init (CURL_GLOBAL_ALL)) + { + fprintf (stderr, "Error (code: %u)\n", errorCount); + return 99; + } + if (NULL == curl_version_info (CURLVERSION_NOW)->ssl_version) + { + fprintf (stderr, "Curl does not support SSL. Cannot run the test.\n"); + curl_global_cleanup (); + return 77; + } + + if (setup_ca_cert () == NULL) + { + fprintf (stderr, MHD_E_TEST_FILE_CREAT); + curl_global_cleanup (); + return 99; + } + + if (curl_uses_nss_ssl() == 0) + { + aes256_sha = "rsa_aes_256_sha"; + } + + errorCount += + test_secure_get (NULL, aes256_sha, CURL_SSLVERSION_TLSv1); + + print_test_result (errorCount, argv[0]); + + curl_global_cleanup (); + if (0 != remove (ca_cert_file_name)) + fprintf (stderr, + "Failed to remove `%s'\n", + ca_cert_file_name); + return errorCount != 0 ? 1 : 0; +} diff --git a/pool/shard004/C/0097314_vec_sqr_long_s16.c b/pool/shard004/C/0097314_vec_sqr_long_s16.c new file mode 100644 index 0000000000000000000000000000000000000000..a5b41e729aa820cdb7ff5b51eddceb6345baec8f --- /dev/null +++ b/pool/shard004/C/0097314_vec_sqr_long_s16.c @@ -0,0 +1,71 @@ +/******************************************************************************* + * Copyright (c) 2017 Vasiliy Nerozin + * + * This library is free software; you can redistribute it and/or modify it + * under the terms of the MIT license. See LICENSE.md for details. + ******************************************************************************/ + +/* ----------------------------------------------------------------------------- + * Includes + * ---------------------------------------------------------------------------*/ +#include "cimlib.h" /* Library header */ + + +/* ----------------------------------------------------------------------------- + * Exported functions + * ---------------------------------------------------------------------------*/ + +/******************************************************************************* + * This function calculates square of each element of vector, 16 bit signed, + * result with extended precision. + * + * @param[out] pY Pointer to output vector, 32 bit unsigned. + * @param[in] len Vector length. + * @param[in] pX Pointer to input vector, 16 bit signed. + ******************************************************************************/ +void vec_sqr_long_s16(uint32_t *pY, int len, const int16_t *pX) +{ + int n; + + for (n = 0; n < len; n++) { + pY[n] = (uint32_t)pX[n] * pX[n]; + } +} + + +#if (CIMLIB_BUILD_TEST == 1) + +/* Simplify macroses for fixed radix */ +#define RADIX (12) +#define CONST(X) CIMLIB_CONST_S16(X, RADIX) +#define CONST_LONG(X) CIMLIB_CONST_U32(X, RADIX * 2) + + +/******************************************************************************* + * This function tests 'vec_sqr_long_s16' function. Returns 'true' if validation + * is successfully done, 'false' - otherwise. + ******************************************************************************/ +bool test_vec_sqr_long_s16(void) +{ + uint32_t y[4]; + static int16_t x[4] = { + CONST(7.9), CONST(4.0), CONST(2.0), CONST(1.0) + }; + static uint32_t res[4] = { + CONST_LONG( 6.2408457041E+01), + CONST_LONG( 1.6000000000E+01), + CONST_LONG( 4.0000000000E+00), + CONST_LONG( 1.0000000000E+00) + }; + bool flOk = true; + + /* Call 'vec_sqr_long_s16' function */ + vec_sqr_long_s16(y, 4, x); + + /* Check the correctness of the result */ + TEST_LIBS_CHECK_RES_REAL(y, res, 4, flOk); + + return flOk; +} + +#endif /* (CIMLIB_BUILD_TEST == 1) */ diff --git a/pool/shard004/C/0097315_main.c b/pool/shard004/C/0097315_main.c new file mode 100644 index 0000000000000000000000000000000000000000..683ec251b9e3ec55287ef2efc578d3722c48bfff --- /dev/null +++ b/pool/shard004/C/0097315_main.c @@ -0,0 +1,86 @@ +#include +#include + +#define MAXN 1000 + +int find(int m,int d, int a); +int period(int s, int m, int d, int ap); +int issquare(int n); + +int M[MAXN]; +int D[MAXN]; +int A[MAXN]; +int count = 0; + +int +find(int m,int d, int a) +{ + int i; + for(i=0;i +#include +#include +#include +#include + +#define SYS_LOG_DOMAIN "GROVE_LIGHT_SENSOR" +#define SYS_LOG_LEVEL CONFIG_SYS_LOG_GROVE_LEVEL +#include + +struct gls_data { + struct device *adc; + struct adc_seq_entry sample; + struct adc_seq_table adc_table; + uint8_t adc_buffer[4]; +}; + +static int gls_sample_fetch(struct device *dev, enum sensor_channel chan) +{ + struct gls_data *drv_data = dev->driver_data; + + return adc_read(drv_data->adc, &drv_data->adc_table); +} + +static int gls_channel_get(struct device *dev, + enum sensor_channel chan, + struct sensor_value *val) +{ + struct gls_data *drv_data = dev->driver_data; + uint16_t analog_val; + double ldr_val; + + /* rescale sample from 12bit (Zephyr) to 10bit (Grove) */ + analog_val = ((uint16_t)drv_data->adc_buffer[1] << 8) | + drv_data->adc_buffer[0]; + analog_val = analog_val >> 2; + + /* + * The formula for converting the analog value to lux is taken from + * the UPM project: + * https://github.com/intel-iot-devkit/upm/blob/master/src/grove/grove.cxx#L161 + */ + ldr_val = (1023.0 - analog_val) * 10.0 / analog_val; + val->type = SENSOR_VALUE_TYPE_DOUBLE; + val->dval = 10000.0 / pow(ldr_val * 15.0, 4.0/3.0); + + return 0; +} + +static const struct sensor_driver_api gls_api = { + .sample_fetch = &gls_sample_fetch, + .channel_get = &gls_channel_get, +}; + +static int gls_init(struct device *dev) +{ + struct gls_data *drv_data = dev->driver_data; + + drv_data->adc = + device_get_binding(CONFIG_GROVE_LIGHT_SENSOR_ADC_DEV_NAME); + if (drv_data->adc == NULL) { + SYS_LOG_ERR("Failed to get ADC device."); + return -EINVAL; + } + + drv_data->sample.sampling_delay = 12; + drv_data->sample.channel_id = CONFIG_GROVE_LIGHT_SENSOR_ADC_CHANNEL; + drv_data->sample.buffer = drv_data->adc_buffer; + drv_data->sample.buffer_length = 4; + + drv_data->adc_table.entries = &drv_data->sample; + drv_data->adc_table.num_entries = 1; + + adc_enable(drv_data->adc); + + dev->driver_api = &gls_api; + + return 0; +} + +static struct gls_data gls_data; + +DEVICE_INIT(gls_dev, CONFIG_GROVE_LIGHT_SENSOR_NAME, &gls_init, &gls_data, + NULL, POST_KERNEL, CONFIG_SENSOR_INIT_PRIORITY); diff --git a/pool/shard004/C/0097324_page-first-line.c b/pool/shard004/C/0097324_page-first-line.c new file mode 100644 index 0000000000000000000000000000000000000000..172f1c2697d1dc7319e5082dd2f9dd3b1fe2b119 --- /dev/null +++ b/pool/shard004/C/0097324_page-first-line.c @@ -0,0 +1,243 @@ +/* PSPPIRE - a graphical user interface for PSPP. + Copyright (C) 2008, 2009, 2010, 2011, 2012, 2013, 2014 Free Software Foundation + + 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 "page-first-line.h" + +#include "ui/gui/text-data-import-dialog.h" + +#include +#include +#include +#include +#include +#include + +#include "data/data-in.h" +#include "data/data-out.h" +#include "data/format-guesser.h" +#include "data/value-labels.h" +#include "language/data-io/data-parser.h" +#include "language/lexer/lexer.h" +#include "libpspp/assertion.h" +#include "libpspp/i18n.h" +#include "libpspp/line-reader.h" +#include "libpspp/message.h" +#include "ui/gui/dialog-common.h" +#include "ui/gui/executor.h" +#include "ui/gui/helper.h" +#include "ui/gui/builder-wrapper.h" +#include "ui/gui/pspp-sheet-selection.h" +#include "ui/gui/pspp-sheet-view-column.h" +#include "ui/gui/pspp-sheet-view.h" +#include "ui/gui/psppire-data-window.h" +#include "ui/gui/psppire-dialog.h" +#include "ui/gui/psppire-encoding-selector.h" +#include "ui/gui/psppire-empty-list-store.h" +#include "ui/gui/psppire-var-sheet.h" +#include "ui/gui/psppire-scanf.h" + +#include "gl/intprops.h" +#include "gl/xalloc.h" + +#include "gettext.h" +#define _(msgid) gettext (msgid) +#define N_(msgid) msgid + + + +/* The "first line" page of the assistant. */ + +/* Page where the user chooses the first line of data. */ +struct first_line_page + { + GtkWidget *page; + PsppSheetView *tree_view; + GtkWidget *variable_names_cb; + }; + +static PsppSheetView *create_lines_tree_view (GtkContainer *parent_window, + struct import_assistant *); +static void on_first_line_change (GtkTreeSelection *, + struct import_assistant *); +static void on_variable_names_cb_toggle (GtkToggleButton *, + struct import_assistant *); +static void set_first_line (struct import_assistant *); +static void get_first_line (struct import_assistant *); + +/* Initializes IA's first_line substructure. */ +struct first_line_page * +first_line_page_create (struct import_assistant *ia) +{ + struct first_line_page *p = xzalloc (sizeof *p); + + GtkBuilder *builder = ia->asst.builder; + + p->page = add_page_to_assistant (ia, get_widget_assert (builder, "FirstLine"), + GTK_ASSISTANT_PAGE_CONTENT); + + gtk_widget_destroy (get_widget_assert (builder, "first-line")); + p->tree_view = create_lines_tree_view ( + GTK_CONTAINER (get_widget_assert (builder, "first-line-scroller")), ia); + p->variable_names_cb = get_widget_assert (builder, "variable-names"); + pspp_sheet_selection_set_mode ( + pspp_sheet_view_get_selection (PSPP_SHEET_VIEW (p->tree_view)), + PSPP_SHEET_SELECTION_BROWSE); + pspp_sheet_view_set_rubber_banding (PSPP_SHEET_VIEW (p->tree_view), TRUE); + g_signal_connect (pspp_sheet_view_get_selection (PSPP_SHEET_VIEW (p->tree_view)), + "changed", G_CALLBACK (on_first_line_change), ia); + g_signal_connect (p->variable_names_cb, "toggled", + G_CALLBACK (on_variable_names_cb_toggle), ia); + return p; +} + +/* Resets the first_line page to its initial content. */ +void +reset_first_line_page (struct import_assistant *ia) +{ + ia->skip_lines = 0; + ia->variable_names = false; + set_first_line (ia); +} + +static void +render_line (PsppSheetViewColumn *tree_column, + GtkCellRenderer *cell, + GtkTreeModel *tree_model, + GtkTreeIter *iter, + gpointer data) +{ + gint row = empty_list_store_iter_to_row (iter); + struct string *lines; + + lines = g_object_get_data (G_OBJECT (tree_model), "lines"); + g_return_if_fail (lines != NULL); + + g_object_set (cell, "text", ds_cstr (&lines[row]), NULL); +} + + +/* Creates and returns a tree view that contains each of the + lines in IA's file as a row. */ +static PsppSheetView * +create_lines_tree_view (GtkContainer *parent, struct import_assistant *ia) +{ + PsppSheetView *tree_view = NULL; + PsppSheetViewColumn *column; + size_t max_line_length; + gint content_width, header_width; + size_t i; + const gchar *title = _("Text"); + + make_tree_view (ia, 0, &tree_view); + + column = pspp_sheet_view_column_new_with_attributes ( + title, ia->asst.fixed_renderer, (void *) NULL); + pspp_sheet_view_column_set_cell_data_func (column, ia->asst.fixed_renderer, + render_line, NULL, NULL); + pspp_sheet_view_column_set_resizable (column, TRUE); + pspp_sheet_view_column_set_expand (column, TRUE); + + max_line_length = 0; + for (i = 0; i < ia->file.line_cnt; i++) + { + size_t w = ds_length (&ia->file.lines[i]); + max_line_length = MAX (max_line_length, w); + } + + content_width = get_monospace_width (tree_view, ia->asst.fixed_renderer, + max_line_length); + header_width = get_string_width (tree_view, ia->asst.prop_renderer, title); + pspp_sheet_view_column_set_fixed_width (column, MAX (content_width, + header_width)); + pspp_sheet_view_append_column (tree_view, column); + + gtk_container_add (parent, GTK_WIDGET (tree_view)); + gtk_widget_show (GTK_WIDGET (tree_view)); + + return tree_view; +} + +/* Called when the line selected in the first_line tree view + changes. */ +static void +on_first_line_change (GtkTreeSelection *selection UNUSED, + struct import_assistant *ia) +{ + get_first_line (ia); +} + +/* Called when the checkbox that indicates whether variable + names are in the row above the first line is toggled. */ +static void +on_variable_names_cb_toggle (GtkToggleButton *variable_names_cb UNUSED, + struct import_assistant *ia) +{ + get_first_line (ia); +} + +/* Sets the widgets to match IA's first_line substructure. */ +static void +set_first_line (struct import_assistant *ia) +{ + GtkTreePath *path; + + path = gtk_tree_path_new_from_indices (ia->skip_lines, -1); + pspp_sheet_view_set_cursor (PSPP_SHEET_VIEW (ia->first_line->tree_view), + path, NULL, false); + gtk_tree_path_free (path); + + gtk_toggle_button_set_active ( + GTK_TOGGLE_BUTTON (ia->first_line->variable_names_cb), + ia->variable_names); + gtk_widget_set_sensitive (ia->first_line->variable_names_cb, + ia->skip_lines > 0); +} + +/* Sets IA's first_line substructure to match the widgets. */ +static void +get_first_line (struct import_assistant *ia) +{ + PsppSheetSelection *selection; + GtkTreeIter iter; + GtkTreeModel *model; + + selection = pspp_sheet_view_get_selection (ia->first_line->tree_view); + if (pspp_sheet_selection_get_selected (selection, &model, &iter)) + { + GtkTreePath *path = gtk_tree_model_get_path (model, &iter); + int row = gtk_tree_path_get_indices (path)[0]; + gtk_tree_path_free (path); + + ia->skip_lines = row; + ia->variable_names = + (ia->skip_lines > 0 + && gtk_toggle_button_get_active ( + GTK_TOGGLE_BUTTON (ia->first_line->variable_names_cb))); + } + gtk_widget_set_sensitive (ia->first_line->variable_names_cb, + ia->skip_lines > 0); +} + + + +void +first_line_append_syntax (const struct import_assistant *ia, struct string *s) +{ + if (ia->skip_lines > 0) + ds_put_format (s, " /FIRSTCASE=%d\n", ia->skip_lines + 1); +} diff --git a/pool/shard004/C/0097341_msync.c b/pool/shard004/C/0097341_msync.c new file mode 100644 index 0000000000000000000000000000000000000000..1b60c75a0561681fe4e3fc0e4605a65fe0473d4a --- /dev/null +++ b/pool/shard004/C/0097341_msync.c @@ -0,0 +1,56 @@ +/* msync -- Synchronize mapped memory to external storage. Mach version. + Copyright (C) 2002-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 +#include + +/* Some Mach variants have vm_msync and some don't. Those that have it + define the VM_SYNC_* bits when we include . */ + +#ifndef VM_SYNC_SYNCHRONOUS +# include +#else + +/* Synchronize the region starting at ADDR and extending LEN bytes with the + file it maps. Filesystem operations on a file being mapped are + unpredictable before this is done. */ + +int +msync (__ptr_t addr, size_t len, int flags) +{ + vm_sync_t sync_flags = 0; + kern_return_t err; + + if (flags & MS_SYNC) + sync_flags |= VM_SYNC_SYNCHRONOUS; + if (flags & MS_ASYNC) + sync_flags |= VM_SYNC_ASYNCHRONOUS; + if (flags & MS_INVALIDATE) + sync_flags |= VM_SYNC_INVALIDATE; + + if (err = __vm_msync (__mach_task_self (), + (vm_address_t) addr, (vm_size_t) len, sync_flags)) + { + errno = err; + return -1; + } + return 0; +} +#endif diff --git a/pool/shard004/C/0097349_sleepuntil.c b/pool/shard004/C/0097349_sleepuntil.c new file mode 100644 index 0000000000000000000000000000000000000000..eb2b96a7660d8bf3ec6d5ad4dbf187423b6b2fab --- /dev/null +++ b/pool/shard004/C/0097349_sleepuntil.c @@ -0,0 +1,243 @@ +/* + * $Xorg: sleepuntil.c,v 1.4 2001/02/09 02:04:33 xorgcvs Exp $ + * +Copyright 1992, 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. + * + * Author: Keith Packard, MIT X Consortium + */ +/* $XFree86: xc/programs/Xserver/Xext/sleepuntil.c,v 3.5 2001/12/14 19:58:51 dawes Exp $ */ + +/* dixsleep.c - implement millisecond timeouts for X clients */ + +#include "sleepuntil.h" +#include "X.h" +#include "Xmd.h" +#include "misc.h" +#include "windowstr.h" +#include "dixstruct.h" +#include "pixmapstr.h" +#include "scrnintstr.h" + +typedef struct _Sertafied { + struct _Sertafied *next; + TimeStamp revive; + ClientPtr pClient; + XID id; + void (*notifyFunc)( +#if NeedNestedPrototypes + ClientPtr /* client */, + pointer /* closure */ +#endif + ); + + pointer closure; +} SertafiedRec, *SertafiedPtr; + +static SertafiedPtr pPending; +static RESTYPE SertafiedResType; +static Bool BlockHandlerRegistered; +static int SertafiedGeneration; + +static void ClientAwaken( +#if NeedFunctionPrototypes + ClientPtr /* client */, + pointer /* closure */ +#endif +); +static int SertafiedDelete( +#if NeedFunctionPrototypes + pointer /* value */, + XID /* id */ +#endif +); +static void SertafiedBlockHandler( +#if NeedFunctionPrototypes + pointer /* data */, + OSTimePtr /* wt */, + pointer /* LastSelectMask */ +#endif +); +static void SertafiedWakeupHandler( +#if NeedFunctionPrototypes + pointer /* data */, + int /* i */, + pointer /* LastSelectMask */ +#endif +); + +int +ClientSleepUntil (client, revive, notifyFunc, closure) + ClientPtr client; + TimeStamp *revive; + void (*notifyFunc)(); + pointer closure; +{ + SertafiedPtr pRequest, pReq, pPrev; + + if (SertafiedGeneration != serverGeneration) + { + SertafiedResType = CreateNewResourceType (SertafiedDelete); + if (!SertafiedResType) + return FALSE; + SertafiedGeneration = serverGeneration; + BlockHandlerRegistered = FALSE; + } + pRequest = (SertafiedPtr) xalloc (sizeof (SertafiedRec)); + if (!pRequest) + return FALSE; + pRequest->pClient = client; + pRequest->revive = *revive; + pRequest->id = FakeClientID (client->index); + pRequest->closure = closure; + if (!BlockHandlerRegistered) + { + if (!RegisterBlockAndWakeupHandlers (SertafiedBlockHandler, + SertafiedWakeupHandler, + (pointer) 0)) + { + xfree (pRequest); + return FALSE; + } + BlockHandlerRegistered = TRUE; + } + pRequest->notifyFunc = 0; + if (!AddResource (pRequest->id, SertafiedResType, (pointer) pRequest)) + return FALSE; + if (!notifyFunc) + notifyFunc = ClientAwaken; + pRequest->notifyFunc = notifyFunc; + /* Insert into time-ordered queue, with earliest activation time coming first. */ + pPrev = 0; + for (pReq = pPending; pReq; pReq = pReq->next) + { + if (CompareTimeStamps (pReq->revive, *revive) == LATER) + break; + pPrev = pReq; + } + if (pPrev) + pPrev->next = pRequest; + else + pPending = pRequest; + pRequest->next = pReq; + IgnoreClient (client); + return TRUE; +} + +static void +ClientAwaken (client, closure) + ClientPtr client; + pointer closure; +{ + if (!client->clientGone) + AttendClient (client); +} + + +static int +SertafiedDelete (value, id) + pointer value; + XID id; +{ + SertafiedPtr pRequest = (SertafiedPtr)value; + SertafiedPtr pReq, pPrev; + + pPrev = 0; + for (pReq = pPending; pReq; pPrev = pReq, pReq = pReq->next) + if (pReq == pRequest) + { + if (pPrev) + pPrev->next = pReq->next; + else + pPending = pReq->next; + break; + } + if (pRequest->notifyFunc) + (*pRequest->notifyFunc) (pRequest->pClient, pRequest->closure); + xfree (pRequest); + return TRUE; +} + +static void +SertafiedBlockHandler (data, wt, LastSelectMask) + pointer data; /* unused */ + OSTimePtr wt; /* wait time */ + pointer LastSelectMask; +{ + SertafiedPtr pReq, pNext; + unsigned long delay; + TimeStamp now; + + if (!pPending) + return; + now.milliseconds = GetTimeInMillis (); + now.months = currentTime.months; + if ((int) (now.milliseconds - currentTime.milliseconds) < 0) + now.months++; + for (pReq = pPending; pReq; pReq = pNext) + { + pNext = pReq->next; + if (CompareTimeStamps (pReq->revive, now) == LATER) + break; + FreeResource (pReq->id, RT_NONE); + + /* AttendClient() may have been called via the resource delete + * function so a client may have input to be processed and so + * set delay to 0 to prevent blocking in WaitForSomething(). + */ + AdjustWaitForDelay (wt, 0); + } + pReq = pPending; + if (!pReq) + return; + delay = pReq->revive.milliseconds - now.milliseconds; + AdjustWaitForDelay (wt, delay); +} + +static void +SertafiedWakeupHandler (data, i, LastSelectMask) + pointer data; + int i; + pointer LastSelectMask; +{ + SertafiedPtr pReq, pNext; + TimeStamp now; + + now.milliseconds = GetTimeInMillis (); + now.months = currentTime.months; + if ((int) (now.milliseconds - currentTime.milliseconds) < 0) + now.months++; + for (pReq = pPending; pReq; pReq = pNext) + { + pNext = pReq->next; + if (CompareTimeStamps (pReq->revive, now) == LATER) + break; + FreeResource (pReq->id, RT_NONE); + } + if (!pPending) + { + RemoveBlockAndWakeupHandlers (SertafiedBlockHandler, + SertafiedWakeupHandler, + (pointer) 0); + BlockHandlerRegistered = FALSE; + } +} diff --git a/pool/shard004/C/0097350_driver.c b/pool/shard004/C/0097350_driver.c new file mode 100644 index 0000000000000000000000000000000000000000..923622aaa03af806c44a6d1e251e0f96c9635690 --- /dev/null +++ b/pool/shard004/C/0097350_driver.c @@ -0,0 +1,184 @@ +#include +#include +#ifdef HAVE_MALLOC_H +#include +#endif +#include +#ifdef __FreeBSD__ +#include +#endif + +#include "win32.h" +#include "driver.h" +#include "pe_image.h" +#include "winreg.h" +#include "vfw.h" +#include "registry.h" +#include "ldt_keeper.h" +#include "ext.h" +#include "debugtools.h" + + +#if 1 + +/* + * STORE_ALL/REST_ALL seems like an attempt to workaround problems due to + * WINAPI/no-WINAPI bustage. + * + * There should be no need for the STORE_ALL/REST_ALL hack once all + * function definitions agree with their prototypes (WINAPI-wise) and + * we make sure, that we do not call these functions without a proper + * prototype in scope. + */ + +#define STORE_ALL +#define REST_ALL +#else +// this asm code is no longer needed +#define STORE_ALL \ + __asm__ __volatile__ ( \ + "push %%ebx\n\t" \ + "push %%ecx\n\t" \ + "push %%edx\n\t" \ + "push %%esi\n\t" \ + "push %%edi\n\t"::) + +#define REST_ALL \ + __asm__ __volatile__ ( \ + "pop %%edi\n\t" \ + "pop %%esi\n\t" \ + "pop %%edx\n\t" \ + "pop %%ecx\n\t" \ + "pop %%ebx\n\t"::) +#endif + +#if 0 +static int needs_free=0; +void SetCodecPath(const char* path) +{ + if(needs_free)free(win32_def_path); + if(path==0) + { + win32_def_path=WIN32_PATH; + needs_free=0; + return; + } + win32_def_path = (char*) malloc(strlen(path)+1); + strcpy(win32_def_path, path); + needs_free=1; +} +#endif + +static DWORD dwDrvID = 0; + +LRESULT WINAPI SendDriverMessage(HDRVR hDriver, UINT message, + LPARAM lParam1, LPARAM lParam2) +{ + DRVR* module=(DRVR*)hDriver; + int result; +#ifndef __svr4__ + char qw[300]; +#endif +#ifdef DETAILED_OUT + printf("SendDriverMessage: driver %X, message %X, arg1 %X, arg2 %X\n", hDriver, message, lParam1, lParam2); +#endif + if (!module || !module->hDriverModule || !module->DriverProc) return -1; +#ifndef __svr4__ + __asm__ __volatile__ ("fsave (%0)\n\t": :"r"(&qw)); +#endif + +#ifdef LDT_paranoia + Setup_FS_Segment(); +#endif + + STORE_ALL; + result=module->DriverProc(module->dwDriverID, hDriver, message, lParam1, lParam2); + REST_ALL; + +#ifndef __svr4__ + __asm__ __volatile__ ("frstor (%0)\n\t": :"r"(&qw)); +#endif + +#ifdef DETAILED_OUT + printf("\t\tResult: %X\n", result); +#endif + return result; +} + +void DrvClose(HDRVR hDriver) +{ + if (hDriver) + { + DRVR* d = (DRVR*)hDriver; + if (d->hDriverModule) + { +#ifdef LDT_paranoia + Setup_FS_Segment(); +#endif + if (d->DriverProc) + { + SendDriverMessage(hDriver, DRV_CLOSE, 0, 0); + d->dwDriverID = 0; + SendDriverMessage(hDriver, DRV_FREE, 0, 0); + } + FreeLibrary(d->hDriverModule); + } + free(d); + } + CodecRelease(); +} + +//DrvOpen(LPCSTR lpszDriverName, LPCSTR lpszSectionName, LPARAM lParam2) +HDRVR DrvOpen(LPARAM lParam2) +{ + NPDRVR hDriver; +// int i; + char unknown[0x124]; + const char* filename = (const char*) ((ICOPEN*) lParam2)->pV1Reserved; + +#ifdef LDT_paranoia + Setup_LDT_Keeper(); +#endif + printf("Loading codec DLL: '%s'\n",filename); + + hDriver = (NPDRVR) malloc(sizeof(DRVR)); + if (!hDriver) + return ((HDRVR) 0); + memset((void*)hDriver, 0, sizeof(DRVR)); + + CodecAlloc(); +#ifdef LDT_paranoia + Setup_FS_Segment(); +#endif + + hDriver->hDriverModule = LoadLibraryA(filename); + if (!hDriver->hDriverModule) + { + printf("Can't open library %s\n", filename); + DrvClose((HDRVR)hDriver); + return ((HDRVR) 0); + } + + hDriver->DriverProc = (DRIVERPROC) GetProcAddress(hDriver->hDriverModule, + "DriverProc"); + if (!hDriver->DriverProc) + { + printf("Library %s is not a valid VfW/ACM codec\n", filename); + DrvClose((HDRVR)hDriver); + return ((HDRVR) 0); + } + + TRACE("DriverProc == %X\n", hDriver->DriverProc); + SendDriverMessage((HDRVR)hDriver, DRV_LOAD, 0, 0); + TRACE("DRV_LOAD Ok!\n"); + SendDriverMessage((HDRVR)hDriver, DRV_ENABLE, 0, 0); + TRACE("DRV_ENABLE Ok!\n"); + hDriver->dwDriverID = ++dwDrvID; // generate new id + + // open driver and remmeber proper DriverID + hDriver->dwDriverID = SendDriverMessage((HDRVR)hDriver, DRV_OPEN, (LPARAM) unknown, lParam2); + TRACE("DRV_OPEN Ok!(%X)\n", hDriver->dwDriverID); + + printf("Loaded DLL driver %s\n", filename); + return (HDRVR)hDriver; +} diff --git a/pool/shard004/C/0097353_ddr1_dimm_params.c b/pool/shard004/C/0097353_ddr1_dimm_params.c new file mode 100644 index 0000000000000000000000000000000000000000..50fd998425a823c73606c3d2697d56c4d26f68db --- /dev/null +++ b/pool/shard004/C/0097353_ddr1_dimm_params.c @@ -0,0 +1,331 @@ +// SPDX-License-Identifier: GPL-2.0 +/* + * Copyright 2008 Freescale Semiconductor, Inc. + */ + +#include +#include + +#include + +/* + * Calculate the Density of each Physical Rank. + * Returned size is in bytes. + * + * Study these table from Byte 31 of JEDEC SPD Spec. + * + * DDR I DDR II + * Bit Size Size + * --- ----- ------ + * 7 high 512MB 512MB + * 6 256MB 256MB + * 5 128MB 128MB + * 4 64MB 16GB + * 3 32MB 8GB + * 2 16MB 4GB + * 1 2GB 2GB + * 0 low 1GB 1GB + * + * Reorder Table to be linear by stripping the bottom + * 2 or 5 bits off and shifting them up to the top. + */ + +static unsigned long long +compute_ranksize(unsigned int mem_type, unsigned char row_dens) +{ + unsigned long long bsize; + + /* Bottom 2 bits up to the top. */ + bsize = ((row_dens >> 2) | ((row_dens & 3) << 6)); + bsize <<= 24ULL; + debug("DDR: DDR I rank density = 0x%16llx\n", bsize); + + return bsize; +} + +/* + * Convert a two-nibble BCD value into a cycle time. + * While the spec calls for nano-seconds, picos are returned. + * + * This implements the tables for bytes 9, 23 and 25 for both + * DDR I and II. No allowance for distinguishing the invalid + * fields absent for DDR I yet present in DDR II is made. + * (That is, cycle times of .25, .33, .66 and .75 ns are + * allowed for both DDR II and I.) + */ +static unsigned int +convert_bcd_tenths_to_cycle_time_ps(unsigned int spd_val) +{ + /* Table look up the lower nibble, allow DDR I & II. */ + unsigned int tenths_ps[16] = { + 0, + 100, + 200, + 300, + 400, + 500, + 600, + 700, + 800, + 900, + 250, /* This and the next 3 entries valid ... */ + 330, /* ... only for tCK calculations. */ + 660, + 750, + 0, /* undefined */ + 0 /* undefined */ + }; + + unsigned int whole_ns = (spd_val & 0xF0) >> 4; + unsigned int tenth_ns = spd_val & 0x0F; + unsigned int ps = whole_ns * 1000 + tenths_ps[tenth_ns]; + + return ps; +} + +static unsigned int +convert_bcd_hundredths_to_cycle_time_ps(unsigned int spd_val) +{ + unsigned int tenth_ns = (spd_val & 0xF0) >> 4; + unsigned int hundredth_ns = spd_val & 0x0F; + unsigned int ps = tenth_ns * 100 + hundredth_ns * 10; + + return ps; +} + +static unsigned int byte40_table_ps[8] = { + 0, + 250, + 330, + 500, + 660, + 750, + 0, /* supposed to be RFC, but not sure what that means */ + 0 /* Undefined */ +}; + +static unsigned int +compute_trfc_ps_from_spd(unsigned char trctrfc_ext, unsigned char trfc) +{ + return ((trctrfc_ext & 0x1) * 256 + trfc) * 1000 + + byte40_table_ps[(trctrfc_ext >> 1) & 0x7]; +} + +static unsigned int +compute_trc_ps_from_spd(unsigned char trctrfc_ext, unsigned char trc) +{ + return trc * 1000 + byte40_table_ps[(trctrfc_ext >> 4) & 0x7]; +} + +/* + * tCKmax from DDR I SPD Byte 43 + * + * Bits 7:2 == whole ns + * Bits 1:0 == quarter ns + * 00 == 0.00 ns + * 01 == 0.25 ns + * 10 == 0.50 ns + * 11 == 0.75 ns + * + * Returns picoseconds. + */ +static unsigned int +compute_tckmax_from_spd_ps(unsigned int byte43) +{ + return (byte43 >> 2) * 1000 + (byte43 & 0x3) * 250; +} + +/* + * Determine Refresh Rate. Ignore self refresh bit on DDR I. + * Table from SPD Spec, Byte 12, converted to picoseconds and + * filled in with "default" normal values. + */ +static unsigned int +determine_refresh_rate_ps(const unsigned int spd_refresh) +{ + unsigned int refresh_time_ps[8] = { + 15625000, /* 0 Normal 1.00x */ + 3900000, /* 1 Reduced .25x */ + 7800000, /* 2 Extended .50x */ + 31300000, /* 3 Extended 2.00x */ + 62500000, /* 4 Extended 4.00x */ + 125000000, /* 5 Extended 8.00x */ + 15625000, /* 6 Normal 1.00x filler */ + 15625000, /* 7 Normal 1.00x filler */ + }; + + return refresh_time_ps[spd_refresh & 0x7]; +} + +/* + * The purpose of this function is to compute a suitable + * CAS latency given the DRAM clock period. The SPD only + * defines at most 3 CAS latencies. Typically the slower in + * frequency the DIMM runs at, the shorter its CAS latency can be. + * If the DIMM is operating at a sufficiently low frequency, + * it may be able to run at a CAS latency shorter than the + * shortest SPD-defined CAS latency. + * + * If a CAS latency is not found, 0 is returned. + * + * Do this by finding in the standard speed bin table the longest + * tCKmin that doesn't exceed the value of mclk_ps (tCK). + * + * An assumption made is that the SDRAM device allows the + * CL to be programmed for a value that is lower than those + * advertised by the SPD. This is not always the case, + * as those modes not defined in the SPD are optional. + * + * CAS latency de-rating based upon values JEDEC Standard No. 79-E + * Table 11. + * + * ordinal 2, ddr1_speed_bins[1] contains tCK for CL=2 + */ + /* CL2.0 CL2.5 CL3.0 */ +unsigned short ddr1_speed_bins[] = {0, 7500, 6000, 5000 }; + +unsigned int +compute_derated_DDR1_CAS_latency(unsigned int mclk_ps) +{ + const unsigned int num_speed_bins = ARRAY_SIZE(ddr1_speed_bins); + unsigned int lowest_tCKmin_found = 0; + unsigned int lowest_tCKmin_CL = 0; + unsigned int i; + + debug("mclk_ps = %u\n", mclk_ps); + + for (i = 0; i < num_speed_bins; i++) { + unsigned int x = ddr1_speed_bins[i]; + debug("i=%u, x = %u, lowest_tCKmin_found = %u\n", + i, x, lowest_tCKmin_found); + if (x && lowest_tCKmin_found <= x && x <= mclk_ps) { + lowest_tCKmin_found = x; + lowest_tCKmin_CL = i + 1; + } + } + + debug("lowest_tCKmin_CL = %u\n", lowest_tCKmin_CL); + + return lowest_tCKmin_CL; +} + +/* + * ddr_compute_dimm_parameters for DDR1 SPD + * + * Compute DIMM parameters based upon the SPD information in spd. + * Writes the results to the dimm_params_t structure pointed by pdimm. + * + * FIXME: use #define for the retvals + */ +unsigned int ddr_compute_dimm_parameters(const unsigned int ctrl_num, + const ddr1_spd_eeprom_t *spd, + dimm_params_t *pdimm, + unsigned int dimm_number) +{ + unsigned int retval; + + if (spd->mem_type) { + if (spd->mem_type != SPD_MEMTYPE_DDR) { + printf("DIMM %u: is not a DDR1 SPD.\n", dimm_number); + return 1; + } + } else { + memset(pdimm, 0, sizeof(dimm_params_t)); + return 1; + } + + retval = ddr1_spd_check(spd); + if (retval) { + printf("DIMM %u: failed checksum\n", dimm_number); + return 2; + } + + /* + * The part name in ASCII in the SPD EEPROM is not null terminated. + * Guarantee null termination here by presetting all bytes to 0 + * and copying the part name in ASCII from the SPD onto it + */ + memset(pdimm->mpart, 0, sizeof(pdimm->mpart)); + memcpy(pdimm->mpart, spd->mpart, sizeof(pdimm->mpart) - 1); + + /* DIMM organization parameters */ + pdimm->n_ranks = spd->nrows; + pdimm->rank_density = compute_ranksize(spd->mem_type, spd->bank_dens); + pdimm->capacity = pdimm->n_ranks * pdimm->rank_density; + pdimm->data_width = spd->dataw_lsb; + pdimm->primary_sdram_width = spd->primw; + pdimm->ec_sdram_width = spd->ecw; + + /* + * FIXME: Need to determine registered_dimm status. + * 1 == register buffered + * 0 == unbuffered + */ + pdimm->registered_dimm = 0; /* unbuffered */ + + /* SDRAM device parameters */ + pdimm->n_row_addr = spd->nrow_addr; + pdimm->n_col_addr = spd->ncol_addr; + pdimm->n_banks_per_sdram_device = spd->nbanks; + pdimm->edc_config = spd->config; + pdimm->burst_lengths_bitmask = spd->burstl; + + /* + * Calculate the Maximum Data Rate based on the Minimum Cycle time. + * The SPD clk_cycle field (tCKmin) is measured in tenths of + * nanoseconds and represented as BCD. + */ + pdimm->tckmin_x_ps + = convert_bcd_tenths_to_cycle_time_ps(spd->clk_cycle); + pdimm->tckmin_x_minus_1_ps + = convert_bcd_tenths_to_cycle_time_ps(spd->clk_cycle2); + pdimm->tckmin_x_minus_2_ps + = convert_bcd_tenths_to_cycle_time_ps(spd->clk_cycle3); + + pdimm->tckmax_ps = compute_tckmax_from_spd_ps(spd->tckmax); + + /* + * Compute CAS latencies defined by SPD + * The SPD caslat_x should have at least 1 and at most 3 bits set. + * + * If cas_lat after masking is 0, the __ilog2 function returns + * 255 into the variable. This behavior is abused once. + */ + pdimm->caslat_x = __ilog2(spd->cas_lat); + pdimm->caslat_x_minus_1 = __ilog2(spd->cas_lat + & ~(1 << pdimm->caslat_x)); + pdimm->caslat_x_minus_2 = __ilog2(spd->cas_lat + & ~(1 << pdimm->caslat_x) + & ~(1 << pdimm->caslat_x_minus_1)); + + /* Compute CAS latencies below that defined by SPD */ + pdimm->caslat_lowest_derated = compute_derated_DDR1_CAS_latency( + get_memory_clk_period_ps(ctrl_num)); + + /* Compute timing parameters */ + pdimm->trcd_ps = spd->trcd * 250; + pdimm->trp_ps = spd->trp * 250; + pdimm->tras_ps = spd->tras * 1000; + + pdimm->twr_ps = mclk_to_picos(ctrl_num, 3); + pdimm->twtr_ps = mclk_to_picos(ctrl_num, 1); + pdimm->trfc_ps = compute_trfc_ps_from_spd(0, spd->trfc); + + pdimm->trrd_ps = spd->trrd * 250; + pdimm->trc_ps = compute_trc_ps_from_spd(0, spd->trc); + + pdimm->refresh_rate_ps = determine_refresh_rate_ps(spd->refresh); + + pdimm->tis_ps = convert_bcd_hundredths_to_cycle_time_ps(spd->ca_setup); + pdimm->tih_ps = convert_bcd_hundredths_to_cycle_time_ps(spd->ca_hold); + pdimm->tds_ps + = convert_bcd_hundredths_to_cycle_time_ps(spd->data_setup); + pdimm->tdh_ps + = convert_bcd_hundredths_to_cycle_time_ps(spd->data_hold); + + pdimm->trtp_ps = mclk_to_picos(ctrl_num, 2); /* By the book. */ + pdimm->tdqsq_max_ps = spd->tdqsq * 10; + pdimm->tqhs_ps = spd->tqhs * 10; + + return 0; +} diff --git a/pool/shard004/C/0097354_f64_add.c b/pool/shard004/C/0097354_f64_add.c new file mode 100644 index 0000000000000000000000000000000000000000..1e575f0b77a954a4ad44c72811405ee43db24bc2 --- /dev/null +++ b/pool/shard004/C/0097354_f64_add.c @@ -0,0 +1,74 @@ + +/*============================================================================ + +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 "softfloat.h" + +float64_t f64_add( float64_t a, float64_t b ) +{ + union ui64_f64 uA; + uint_fast64_t uiA; + bool signA; + union ui64_f64 uB; + uint_fast64_t uiB; + bool signB; +#if ! defined INLINE_LEVEL || (INLINE_LEVEL < 2) + float64_t (*magsFuncPtr)( uint_fast64_t, uint_fast64_t, bool ); +#endif + + uA.f = a; + uiA = uA.ui; + signA = signF64UI( uiA ); + uB.f = b; + uiB = uB.ui; + signB = signF64UI( uiB ); +#if defined INLINE_LEVEL && (2 <= INLINE_LEVEL) + if ( signA == signB ) { + return softfloat_addMagsF64( uiA, uiB, signA ); + } else { + return softfloat_subMagsF64( uiA, uiB, signA ); + } +#else + magsFuncPtr = + (signA == signB) ? softfloat_addMagsF64 : softfloat_subMagsF64; + return (*magsFuncPtr)( uiA, uiB, signA ); +#endif + +} + diff --git a/pool/shard004/C/0097378_main.c b/pool/shard004/C/0097378_main.c new file mode 100644 index 0000000000000000000000000000000000000000..c179abe192ded362d24aa72c974a2f6426be05ca --- /dev/null +++ b/pool/shard004/C/0097378_main.c @@ -0,0 +1,197 @@ +/** + * \file + * \brief Device manager for Barrelfish. + * + * Interacts with the SKB / PCI to start cores, drivers etc. + * + */ + +/* + * Copyright (c) 2007, 2008, 2009, 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, Haldeneggsteig 4, CH-8092 Zurich. Attn: Systems Group. + */ + +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +#include + +#include +#include +#include + +#include "kaluga.h" + +coreid_t my_core_id = 0; // Core ID +uint32_t my_arch_id = 0; // APIC ID + +extern char **environ; + +static void add_start_function_overrides(void) +{ + set_start_function("e1000n", start_networking); + set_start_function("rtl8029", start_networking); +} + +static void parse_arguments(int argc, char** argv) +{ + for (int i = 1; i < argc; i++) { + if (strncmp(argv[i], "apicid=", sizeof("apicid")) == 0) { + my_arch_id = strtol(argv[i] + sizeof("apicid"), NULL, 10); + } else if (strcmp(argv[i], "boot") == 0) { + // ignored + } + } +} + +static inline errval_t wait_for_pci(void) +{ + iref_t iref; + return nameservice_blocking_lookup("pci_discovery_done", &iref); +} + +int main(int argc, char** argv) +{ + vfs_init(); + init_environ(); + + errval_t err; + + my_core_id = disp_get_core_id(); + parse_arguments(argc, argv); + + err = oct_init(); + if (err_is_fail(err)) { + USER_PANIC_ERR(err, "Initialize octopus service."); + } + + printf("Kaluga: parse boot modules...\n"); + + err = init_boot_modules(); + if (err_is_fail(err)) { + USER_PANIC_ERR(err, "Parse boot modules."); + } + add_start_function_overrides(); +#ifdef __x86__ + // We need to run on core 0 + // (we are responsible for booting all the other cores) + assert(my_core_id == BSP_CORE_ID); + printf("Kaluga running on x86.\n"); + + err = skb_client_connect(); + if (err_is_fail(err)) { + USER_PANIC_ERR(err, "Connect to SKB."); + } + + // Make sure the driver db is loaded + err = skb_execute("[device_db]."); + if (err_is_fail(err)) { + USER_PANIC_ERR(err, "Device DB not loaded."); + } + + // The current boot protocol needs us to have + // knowledge about how many CPUs are available at boot + // time in order to start-up properly. + char* record = NULL; + err = oct_barrier_enter("barrier.acpi", &record, 2); + + err = watch_for_cores(); + if (err_is_fail(err)) { + USER_PANIC_ERR(err, "Watching cores."); + } + + printf("Kaluga: pci_root_bridge\n"); + + err = watch_for_pci_root_bridge(); + if (err_is_fail(err)) { + USER_PANIC_ERR(err, "Watching PCI root bridges."); + } + + printf("Kaluga: pci_devices\n"); + + err = watch_for_pci_devices(); + if (err_is_fail(err)) { + USER_PANIC_ERR(err, "Watching PCI devices."); + } + + // XXX: This is a bit silly, I add this record + // because it was previously in spawnd so + // there may be code out there who relies on this + // It might be better to get rid of this completely + err = oct_set("all_spawnds_up { iref: 0 }"); + assert(err_is_ok(err)); +#elif __pandaboard__ + printf("Kaluga running on Pandaboard.\n"); + + err = init_cap_manager(); + assert(err_is_ok(err)); + + struct module_info* mi = find_module("fdif"); + if (mi != NULL) { + err = mi->start_function(0, mi, "hw.arm.omap44xx.fdif {}"); + assert(err_is_ok(err)); + } + mi = find_module("mmchs"); + if (mi != NULL) { + err = mi->start_function(0, mi, "hw.arm.omap44xx.mmchs {}"); + assert(err_is_ok(err)); + } + mi = find_module("mmchs2"); + if (mi != NULL) { + err = mi->start_function(0, mi, "hw.arm.omap44xx.mmchs {}"); + assert(err_is_ok(err)); + } + mi = find_module("prcm"); + if (mi != NULL) { + err = mi->start_function(0, mi, "hw.arm.omap44xx.prcm {}"); + assert(err_is_ok(err)); + } + mi = find_module("serial"); + if (mi != NULL) { + err = mi->start_function(0, mi, "hw.arm.omap44xx.uart {}"); + assert(err_is_ok(err)); + } + mi = find_module("sdma"); + if (mi != NULL) { + err = mi->start_function(0, mi, "hw.arm.omap44xx.sdma {}"); + assert(err_is_ok(err)); + } + mi = find_module("usb_manager"); + if (mi != NULL) { +#define USB_ARM_EHCI_IRQ 109 + char *buf = malloc(255); + uint8_t offset = 0; + mi->cmdargs = buf; + mi->argc = 3; + mi->argv[0] = mi->cmdargs + 0; + + snprintf(buf + offset, 255 - offset, "ehci\0"); + offset += strlen(mi->argv[0]) + 1; + mi->argv[1] = mi->cmdargs + offset; + snprintf(buf + offset, 255 - offset, "%u\0", 0xC00); + offset += strlen(mi->argv[1]) + 1; + mi->argv[2] = mi->cmdargs + offset; + snprintf(buf+offset, 255-offset, "%u\0", USB_ARM_EHCI_IRQ); + + // XXX Use customized start function or add to module info + err = mi->start_function(0, mi, "hw.arm.omap44xx.usb {}"); + assert(err_is_ok(err)); + } +#endif + + THCFinish(); + return EXIT_SUCCESS; +} + diff --git a/pool/shard004/C/0097380_masterkey_trusted.c b/pool/shard004/C/0097380_masterkey_trusted.c new file mode 100644 index 0000000000000000000000000000000000000000..e6d22ce77e98ff55764892c781410e709b1d56e4 --- /dev/null +++ b/pool/shard004/C/0097380_masterkey_trusted.c @@ -0,0 +1,43 @@ +// SPDX-License-Identifier: GPL-2.0-only +/* + * Copyright (C) 2010 IBM Corporation + * Copyright (C) 2010 Politecnico di Torino, Italy + * TORSEC group -- https://security.polito.it + * + * Authors: + * Mimi Zohar + * Roberto Sassu + * + * See Documentation/security/keys/trusted-encrypted.rst + */ + +#include +#include +#include +#include +#include "encrypted.h" + +/* + * request_trusted_key - request the trusted key + * + * Trusted keys are sealed to PCRs and other metadata. Although userspace + * manages both trusted/encrypted key-types, like the encrypted key type + * data, trusted key type data is not visible decrypted from userspace. + */ +struct key *request_trusted_key(const char *trusted_desc, + const u8 **master_key, size_t *master_keylen) +{ + struct trusted_key_payload *tpayload; + struct key *tkey; + + tkey = request_key(&key_type_trusted, trusted_desc, NULL); + if (IS_ERR(tkey)) + goto error; + + down_read(&tkey->sem); + tpayload = tkey->payload.data[0]; + *master_key = tpayload->key; + *master_keylen = tpayload->key_len; +error: + return tkey; +} diff --git a/pool/shard004/C/0097382_scheduler.c b/pool/shard004/C/0097382_scheduler.c new file mode 100644 index 0000000000000000000000000000000000000000..07a5de62cc77c4ec214561997ffbe029dd55f838 --- /dev/null +++ b/pool/shard004/C/0097382_scheduler.c @@ -0,0 +1,178 @@ +#include "util/utilities.h" +#include "asm.h" +#include "main.h" +#include "mem.h" +#include "memory.h" +#include "memory_map.h" +#include "scheduler.h" +#include "stddef.h" +#include "hardware/interrupts.h" +#include "hardware/mmu_c.h" +#include "hardware/timer.h" +#include "types/string.h" +#include "types/queue.h" +#include "thread.h" +#include "process.h" +#include "thread.h" + +static taskScheduler* gScheduler; +static unsigned int gNextTID; + +void Scheduler_PrintRegs(thread_regs* regs) +{ + printf("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n"); + printf("0x%h r0: 0x%h\n", ®s->r0, regs->r0); + printf("0x%h r1: 0x%h\n", ®s->r1, regs->r1); + printf("0x%h r2: 0x%h\n", ®s->r2, regs->r2); + printf("0x%h r3: 0x%h\n", ®s->r3, regs->r3); + printf("0x%h r4: 0x%h\n", ®s->r4, regs->r4); + printf("0x%h r5: 0x%h\n", ®s->r5, regs->r5); + printf("0x%h r6: 0x%h\n", ®s->r6, regs->r6); + printf("0x%h r7: 0x%h\n", ®s->r7, regs->r7); + printf("0x%h r8: 0x%h\n", ®s->r8, regs->r8); + printf("0x%h r9: 0x%h\n", ®s->r9, regs->r9); + printf("0x%h r10: 0x%h\n", ®s->r10, regs->r10); + printf("0x%h r11: 0x%h\n", ®s->r11, regs->r11); + printf("0x%h r12: 0x%h\n", ®s->r12, regs->r12); + printf("0x%h LR: 0x%h\n", ®s->lr, regs->lr); + + printf("0x%h lr2: 0x%h\n", ®s->lr2, regs->lr2); + printf("0x%h SPRS: 0x%h\n", ®s->sprs, regs->sprs); + printf("0x%h SP: 0x%h\n", ®s->sp, regs->sp); + printf("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n"); +} + +void Scheduler_Initialize(void) +{ + gScheduler = (taskScheduler*)palloc(sizeof(taskScheduler)); + gScheduler->currentThread = NULL; + gScheduler->threads.back = NULL; + gScheduler->threads.front = NULL; + gScheduler->threads.numNodes = 0; + + gNextTID = 1; +} + +void Scheduler_Start(void) +{ + Timer_Clear(); + Timer_SetInterval(TASK_SCHEDULER_TICK_MS); + Arm_IrqEnable(interrupt_source_system_timer); + + // Switch in first task? +} + +unsigned int Scheduler_GetNextTID(void) +{ + // For now: Just an incremental integer, need to do someting better in the future + return gNextTID++; +} + +// This is obsolete, don't use it? Should enqueue threads instead +void Scheduler_Enqueue(Process* task) +{ + // Add it to the queue for processing + Queue_Enqueue(&gScheduler->threads, task->mainThread); +} + +void Scheduler_NextTask(thread_regs* reg) +{ + //printf("Scheduler - cpsr is: 0x%h\n", reg->sprs); + + unsigned int shouldSwitchTask = 0; + thread* cur = gScheduler->currentThread; + if (cur != NULL && gScheduler->threads.numNodes > 0) + { + //printf("Scheduler: Have a current running task!\n"); + + cur->timeElapsed += TASK_SCHEDULER_TICK_MS; + + // Has this task had it's fair share? + if (cur->timeElapsed >= (TASK_SCHEDULER_TICK_MS * 2)) + { + //printf("Scheduler: Switching out %s\n", cur->name); + + shouldSwitchTask = 1; + + // Save registers + my_memcpy(&cur->registers, reg, sizeof(thread_regs)); + + //printf("saved registers, sp: 0x%h\n", cur->registers.sp); + + cur->state = TS_Ready; + cur->isRunning = false; + + // Put it back in the queue + Queue_Enqueue(&gScheduler->threads, cur); + } + } + else if (cur == NULL) + { + //printf("Scheduler: First run? Switch to a task!\n"); + shouldSwitchTask = 1; + } + + if (!shouldSwitchTask || gScheduler->threads.numNodes == 0) + return; + + //printf("Registers before: \n"); + //Scheduler_PrintRegs(reg); + + thread* next = (thread*)Queue_Dequeue(&gScheduler->threads); + + if (next == NULL) + { + printf("Failed to retrieve next thread, how can it be null!? Skippin CTX switch...\n"); + return; + } + + //printf("Scheduler: Switching in %s\n", next->name); + + next->isRunning = true; + next->state = TS_Running; + gScheduler->currentThread = next; + + //printf("Scheduler - Setting SPSR to: 0x%h\n", next->registers.sprs); + //printf("Updating TTBC, Size: %d\n", next->ttb0_size); + + // Update TTCR + unsigned int ttbc = get_ttbc(); + ttbc = next->owner->ttb0_size; + set_ttbc(ttbc); + //printf("Set ttbc to: 0x%h\n", ttbc); + + // Switch in the process' TT + //printf("Switch to task's TTB0, ttb0 addr (Physical): 0x%h\n", next->ttb0_physical); + set_ttb0(next->owner->ttb0_physical, 1); + + for (int i = 0; i < 1000; i++); + + // Restore the tasks registers + my_memcpy(reg, &next->registers, sizeof(thread_regs)); + + //printf("\n* * Switching in thread '%s' in process %s * *\n", next->name, next->owner->name); + //Scheduler_PrintRegs(reg); +} + +void Scheduler_TimerTick(thread_regs* regs) +{ + // A switch isn't necessary + if (gScheduler->threads.numNodes == 0 && gScheduler->currentThread != NULL) + { + printf("Scheduler: Not enough threads running to bother...\n"); + } + else + { + Scheduler_NextTask(regs); + } + + // Restart the timer + Timer_Clear(); + Timer_SetInterval(TASK_SCHEDULER_TICK_MS * 2); + Arm_IrqEnable(interrupt_source_system_timer); // Don't think I have to do this? +} + +thread* Scheduler_GetCurrentThread(void) +{ + return gScheduler->currentThread; +} \ No newline at end of file diff --git a/pool/shard004/C/0097383_os__dynamicLib.c b/pool/shard004/C/0097383_os__dynamicLib.c new file mode 100644 index 0000000000000000000000000000000000000000..f17cca735fcd67b9a9ae1ce813eb5ad0fdfc4599 --- /dev/null +++ b/pool/shard004/C/0097383_os__dynamicLib.c @@ -0,0 +1,276 @@ +/* + * Vortex OpenSplice + * + * This software and documentation are Copyright 2006 to TO_YEAR ADLINK + * Technology Limited, its affiliated companies and licensors. All rights + * reserved. + * + * Licensed under the ADLINK Software License Agreement Rev 2.7 2nd October + * 2014 (the "License"); you may not use this file except in compliance with + * the License. + * You may obtain a copy of the License at: + * $OSPL_HOME/LICENSE + * + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "os_library.h" +#include "os_stdlib.h" +#include "os_report.h" +#include "os_heap.h" +#include "include/os_dynamicLib_plugin.h" +#include "os_errno.h" + +static os_library +os_dynamicLibraryOpen( + const char *name, + os_libraryAttr *attr) +{ + MODULE_ID library; + int fd=0; + os_library osl = NULL; + char libName[64]; + + if (name && (strlen(name) > 0)) { + if(attr->autoTranslate == OS_TRUE){ + if ( strlen(name)+7 < sizeof(libName)) { + sprintf(libName, "lib%s.so", name); + fd = open(libName, O_RDONLY, 0); + } else { + OS_REPORT(OS_ERROR, "os_libraryOpen", 0, "library file name too long"); + } + } else { + fd = open(name, O_RDONLY, 0); + } + if (fd >= 0) { + library = loadModule(fd, attr->flags); + + if (!library) { + OS_REPORT(OS_ERROR, "os_libraryOpen", 0, + "loadModule: %s, error code %d", name, os_getErrno()); + } + else + { + osl = (os_library)os_malloc(sizeof(*osl)); + osl->l.library = library; + osl->isStatic = 0; + } + close (fd); + } else { + OS_REPORT(OS_ERROR, "os_libraryOpen", 0, + "open: %s, error code %d", name, os_getErrno()); + } + } + return (void *)osl; +} + +static os_result +os_dynamicLibraryClose( + os_library library) +{ + os_result result; + if (library != NULL && library->l.library) { + if (unldByModuleId(library->l.library, 0) != OK) { + OS_REPORT(OS_ERROR, "os_libraryClose", 0, + "unldByModuleId error: %s", os_getErrno()); + result = os_resultFail; + } else { + os_free( library ); + result = os_resultSuccess; + } + } else { + result = os_resultInvalid; + } + return result; +} + +static os_symbol +os_dynamicLibraryGetSymbol( + os_library library, + const char *symbolName) +{ + os_symbol symbol = NULL; + SYM_TYPE pType; + + assert(library); + assert(library->l.library); + assert(library->isStatic == 0); + assert(symbolName); + + if ((symbolName != NULL) && (strlen(symbolName) != 0)) { + if (symFindByName(sysSymTbl, (char *)symbolName, (char **)&symbol, &pType) == ERROR) { + OS_REPORT(OS_ERROR, "os_libraryGetSymbol", 0, + "symFindByName: %s, error code %d", symbolName, os_getErrno()); + } + } + return symbol; +} + +static os_result +os_procLoad( + char *executable_file, + void **startRoutine) +{ + Elf32_Ehdr exec; + int fd; + char *locatedexe; + char *ptext = LD_NO_ADDRESS; + char *pdata = LD_NO_ADDRESS; + char *pbss = LD_NO_ADDRESS; + int task_symbols; + char *exeNameWithPostfix = NULL; + size_t exe_name_len; + const char *dkm_postfix = ".out"; + const size_t dkm_postfix_len = strlen(dkm_postfix); + exe_name_len = strlen(executable_file); + locatedexe = os_locate(executable_file, OS_ROK); + if ( locatedexe == NULL + && exe_name_len > dkm_postfix_len + && strcmp(&executable_file[exe_name_len-dkm_postfix_len], + dkm_postfix) != 0 ) { + exeNameWithPostfix=os_malloc(strlen(executable_file)+1+dkm_postfix_len); + sprintf(exeNameWithPostfix, "%s%s", executable_file, dkm_postfix ); + locatedexe = os_locate(exeNameWithPostfix, OS_ROK); + os_free(exeNameWithPostfix); + } + + if ( locatedexe == NULL ) { + OS_REPORT(OS_WARNING, "os_procCreate", 1, + "os_procLoad : could not locate module on PATH (%s)", executable_file); + return (os_resultInvalid); + } else { + + fd = open(locatedexe, O_RDONLY, 0); + if (fd == ERROR) { + OS_REPORT(OS_WARNING, "os_procCreate", 1, + "os_procLoad : open failed with error %d (%s)", os_getErrno(), executable_file); + return (os_resultInvalid); + } + if (read(fd, (char *)&exec, sizeof(exec)) != sizeof(exec)) { + OS_REPORT(OS_WARNING, "os_procCreate", 1, + "os_procLoad : read failed with error %d (%s)", os_getErrno(), executable_file); + close(fd); + return (os_resultInvalid); + } + if (lseek(fd, 0, L_SET) != 0) { + OS_REPORT(OS_WARNING, "os_procCreate", 1, + "os_procLoad : lseek failed with error %d (%s)", os_getErrno(), executable_file); + close(fd); + return (os_resultInvalid); + } + task_symbols = GLOBAL_SYMBOLS; /* ??? NO_SYMBOLS */ +#ifndef _WRS_VX_SMP + /* Not available in SMP, so no protection against loading simultaneously */ + taskLock(); +#endif + if ((int)loadModuleAt(fd, task_symbols, &ptext, &pdata, &pbss) == ERROR) { + OS_REPORT(OS_WARNING, "os_procCreate", 1, + "os_procLoad : loadModuleAt failed with error %d (%s)", os_getErrno(), executable_file); + close(fd); +#ifndef _WRS_VX_SMP + taskUnlock(); +#endif + return (os_resultInvalid); + } +#ifndef _WRS_VX_SMP + taskUnlock(); +#endif + close (fd); + *startRoutine = (void *)(((unsigned long)ptext + (unsigned long)exec.e_entry)); + os_free(locatedexe); + } + return (os_resultSuccess); +} + +/** \brief Helper function for os_procCreate + * + * checkEntryPointPreLoaded attempts to locate the expected + * entrypoint symbol based on the executable name. + * For VxWorks with a single address space, each service entrypoint + * is derived by using the OPENSPLICE_ENTRYPOINT macro, which will create + * an entrypoint name "ospl_x". If available, this symbol will be + * used as the entrypoint during os_procCreate and avoid the + * potentially slow loadModuleAt call. It gives the user the option + * to preload all components using RAM, flash, or others, when the + * dynamic loading of symbols could be slow (especially as seen with + * the Target Server File System connection during testing). + */ + +static os_boolean +checkEntryPointPreLoaded( + const char *executableName, + void **startRoutine) +{ + SYM_TYPE ptype; + char * entryPoint = NULL; + os_boolean result = FALSE; + + entryPoint = os_malloc (strlen (executableName) + 6); + strcpy (entryPoint,"ospl_"); + strcat (entryPoint,executableName); + + OS_REPORT(OS_INFO, "checkEntryPointPreLoaded", 1, + "For %s checking for preloaded symbol (%s)", + executableName, entryPoint); + + if (symFindByName(sysSymTbl, entryPoint,(char**)startRoutine,&ptype) == OK) + { + OS_REPORT(OS_INFO, "checkEntryPointPreLoaded", 0, "Symbol (%s) already loaded", entryPoint); + result = TRUE; + } + else + { + OS_REPORT(OS_INFO, "checkEntryPointPreLoaded", 0, "Symbol (%s) not yet loaded", entryPoint); + } + + os_free (entryPoint); + + return result; +} + +static void * +os_dynamicLoadLib( const char *executable_file) +{ + void *startRoutine=NULL; + + /* Optimisation to use the preloaded entrypoint symbol (if it exists + * yet) for the executable. If it has not yet been loaded, fall back + * to loadModuleAt within os_procLoad which will load the component and + * locate the entrypoint. + * We have noted that loadModuleAt can be very slow, especially when + * using the 'Target Server File System', which is known to have slow I/O. + */ + if (checkEntryPointPreLoaded (executable_file, &startRoutine)) { + OS_REPORT(OS_INFO, "os__dynamicLoadProc", 0, + "Using preloaded entry point for %s", executable_file); + } + else if (os_procLoad((char *)executable_file, &startRoutine) + != os_resultSuccess) { + OS_REPORT(OS_WARNING, "os__dynamicLoadProc", 1, + "Unable to load %s", + executable_file); + } + return ( startRoutine ); +} + + +struct os_dynamicLoad_plugin os_dynamicLibPluginImpl = +{ + os_dynamicLibraryOpen, + os_dynamicLibraryClose, + os_dynamicLibraryGetSymbol, + os_dynamicLoadLib +}; + diff --git a/pool/shard004/C/0097390_CWE122_Heap_Based_Buffer_Overflow__c_CWE805_struct_loop_16.c b/pool/shard004/C/0097390_CWE122_Heap_Based_Buffer_Overflow__c_CWE805_struct_loop_16.c new file mode 100644 index 0000000000000000000000000000000000000000..83f5c84971fcb2c32dc870b43bae9c0e5f1918a3 --- /dev/null +++ b/pool/shard004/C/0097390_CWE122_Heap_Based_Buffer_Overflow__c_CWE805_struct_loop_16.c @@ -0,0 +1,128 @@ +/* TEMPLATE GENERATED TESTCASE FILE +Filename: CWE122_Heap_Based_Buffer_Overflow__c_CWE805_struct_loop_16.c +Label Definition File: CWE122_Heap_Based_Buffer_Overflow__c_CWE805.label.xml +Template File: sources-sink-16.tmpl.c +*/ +/* + * @description + * CWE: 122 Heap Based Buffer Overflow + * BadSource: Allocate using malloc() and set data pointer to a small buffer + * GoodSource: Allocate using malloc() and set data pointer to a large buffer + * Sink: loop + * BadSink : Copy twoIntsStruct array to data using a loop + * Flow Variant: 16 Control flow: while(1) + * + * */ + +#include "std_testcase.h" + +#ifndef OMITBAD + +void CWE122_Heap_Based_Buffer_Overflow__c_CWE805_struct_loop_16_bad() +{ + twoIntsStruct * data; + data = NULL; + while(1) + { + /* FLAW: Allocate and point data to a small buffer that is smaller than the large buffer used in the sinks */ + data = (twoIntsStruct *)malloc(50*sizeof(twoIntsStruct)); + if (data == NULL) {exit(-1);} + break; + } + { + twoIntsStruct source[100]; + { + size_t i; + /* Initialize array */ + for (i = 0; i < 100; i++) + { + source[i].intOne = 0; + source[i].intTwo = 0; + } + } + { + size_t i; + /* POTENTIAL FLAW: Possible buffer overflow if data < 100 */ + for (i = 0; i < 100; i++) + { + data[i] = source[i]; + } + printStructLine(&data[0]); + free(data); + } + } +} + +#endif /* OMITBAD */ + +#ifndef OMITGOOD + +/* goodG2B() - use goodsource and badsink by changing the conditions on the while statements */ +static void goodG2B() +{ + twoIntsStruct * data; + data = NULL; + while(1) + { + /* FIX: Allocate and point data to a large buffer that is at least as large as the large buffer used in the sink */ + data = (twoIntsStruct *)malloc(100*sizeof(twoIntsStruct)); + if (data == NULL) {exit(-1);} + break; + } + { + twoIntsStruct source[100]; + { + size_t i; + /* Initialize array */ + for (i = 0; i < 100; i++) + { + source[i].intOne = 0; + source[i].intTwo = 0; + } + } + { + size_t i; + /* POTENTIAL FLAW: Possible buffer overflow if data < 100 */ + for (i = 0; i < 100; i++) + { + data[i] = source[i]; + } + printStructLine(&data[0]); + free(data); + } + } +} + +void CWE122_Heap_Based_Buffer_Overflow__c_CWE805_struct_loop_16_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_CWE805_struct_loop_16_good(); + printLine("Finished good()"); +#endif /* OMITGOOD */ +#ifndef OMITBAD + printLine("Calling bad()..."); + CWE122_Heap_Based_Buffer_Overflow__c_CWE805_struct_loop_16_bad(); + printLine("Finished bad()"); +#endif /* OMITBAD */ + return 0; +} + +#endif diff --git a/pool/shard004/C/0097393_avx-vpermilpd-2.c b/pool/shard004/C/0097393_avx-vpermilpd-2.c new file mode 100644 index 0000000000000000000000000000000000000000..a6d7a0d675561afcf119bb27508e1e6f7d8b5024 --- /dev/null +++ b/pool/shard004/C/0097393_avx-vpermilpd-2.c @@ -0,0 +1,33 @@ +/* { dg-do run } */ +/* { dg-require-effective-target avx } */ +/* { dg-options "-O2 -mavx" } */ + +#include "avx-check.h" + +#ifndef CTRL +#define CTRL 2 +#endif + +#define mask_v(pos) (((CTRL & (1ULL << (pos))) >> (pos)) << 1) + +void static +avx_test () +{ + union128d u, src; + union128i_q ctl; + + double s[2] = {9674.67456, 13543.9788}; + long long m[2] = {mask_v(0), mask_v(1)}; + double e[2]; + + src.x = _mm_loadu_pd(s); + ctl.x = _mm_loadu_si128((__m128i*) m); + u.x = _mm_permutevar_pd(src.x, ctl.x); + + e[0] = s[((m[0] & 0x02) >> 1)]; + e[1] = s[((m[1] & 0x02) >> 1)]; + + if (check_union128d (u, e)) + abort (); +} + diff --git a/pool/shard004/C/0097396_kasan_init_64.c b/pool/shard004/C/0097396_kasan_init_64.c new file mode 100644 index 0000000000000000000000000000000000000000..1486e55952de881ca6f65ef52fd665d9b013d713 --- /dev/null +++ b/pool/shard004/C/0097396_kasan_init_64.c @@ -0,0 +1,107 @@ +#include +#include +#include +#include +#include +#include + +#include +#include + +extern pgd_t early_level4_pgt[PTRS_PER_PGD]; +extern struct range pfn_mapped[E820_X_MAX]; + +static int __init map_range(struct range *range) +{ + unsigned long start; + unsigned long end; + + start = (unsigned long)kasan_mem_to_shadow(pfn_to_kaddr(range->start)); + end = (unsigned long)kasan_mem_to_shadow(pfn_to_kaddr(range->end)); + + /* + * end + 1 here is intentional. We check several shadow bytes in advance + * to slightly speed up fastpath. In some rare cases we could cross + * boundary of mapped shadow, so we just map some more here. + */ + return vmemmap_populate(start, end + 1, NUMA_NO_NODE); +} + +static void __init clear_pgds(unsigned long start, + unsigned long end) +{ + for (; start < end; start += PGDIR_SIZE) + pgd_clear(pgd_offset_k(start)); +} + +void __init kasan_map_early_shadow(pgd_t *pgd) +{ + int i; + unsigned long start = KASAN_SHADOW_START; + unsigned long end = KASAN_SHADOW_END; + + for (i = pgd_index(start); start < end; i++) { + pgd[i] = __pgd(__pa_nodebug(kasan_zero_pud) + | _KERNPG_TABLE); + start += PGDIR_SIZE; + } +} + +#ifdef CONFIG_KASAN_INLINE +static int kasan_die_handler(struct notifier_block *self, + unsigned long val, + void *data) +{ + if (val == DIE_GPF) { + pr_emerg("CONFIG_KASAN_INLINE enabled"); + pr_emerg("GPF could be caused by NULL-ptr deref or user memory access"); + } + return NOTIFY_OK; +} + +static struct notifier_block kasan_die_notifier = { + .notifier_call = kasan_die_handler, +}; +#endif + +void __init kasan_init(void) +{ + int i; + +#ifdef CONFIG_KASAN_INLINE + register_die_notifier(&kasan_die_notifier); +#endif + + memcpy(early_level4_pgt, init_level4_pgt, sizeof(early_level4_pgt)); + load_cr3(early_level4_pgt); + + clear_pgds(KASAN_SHADOW_START, KASAN_SHADOW_END); + + kasan_populate_zero_shadow((void *)KASAN_SHADOW_START, + kasan_mem_to_shadow((void *)PAGE_OFFSET)); + + for (i = 0; i < E820_X_MAX; i++) { + if (pfn_mapped[i].end == 0) + break; + + if (map_range(&pfn_mapped[i])) + panic("kasan: unable to allocate shadow!"); + } + kasan_populate_zero_shadow( + kasan_mem_to_shadow((void *)PAGE_OFFSET + MAXMEM), + kasan_mem_to_shadow((void *)__START_KERNEL_map)); + + vmemmap_populate((unsigned long)kasan_mem_to_shadow(_stext), + (unsigned long)kasan_mem_to_shadow(_end), + NUMA_NO_NODE); + + kasan_populate_zero_shadow(kasan_mem_to_shadow((void *)MODULES_END), + (void *)KASAN_SHADOW_END); + + memset(kasan_zero_page, 0, PAGE_SIZE); + + load_cr3(init_level4_pgt); + init_task.kasan_depth = 0; + + pr_info("KernelAddressSanitizer initialized\n"); +} diff --git a/pool/shard004/C/0097398_dialog.c b/pool/shard004/C/0097398_dialog.c new file mode 100644 index 0000000000000000000000000000000000000000..86e64578c2310aea5c820382a106b4ae3b9abfdc --- /dev/null +++ b/pool/shard004/C/0097398_dialog.c @@ -0,0 +1,160 @@ +/* + This project is free software: you can 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. + + Deviation is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with Deviation. If not, see . + */ + +#include "common.h" +#define ENABLE_GUIOBJECT +#include "gui.h" +#include "config/display.h" + +#include "_dialog.c" + +static void dlgbut_pressok_cb(struct guiObject *obj, const void *data); +static void dlgbut_presscancel_cb(struct guiObject *obj, const void *data); +const char *dlgbut_strok_cb(struct guiObject *obj, const void *data); +const char *dlgbut_strcancel_cb(struct guiObject *obj, const void *data); + +static guiObject_t *previous_selected_obj = NULL; // used for devo10 only + +guiObject_t *GUI_CreateDialog(guiDialog_t *dialog, u16 x, u16 y, u16 width, u16 height, const char *title, + const char *(*string_cb)(guiObject_t *obj, void *data), + void (*CallBack)(u8 state, void *data), + enum DialogType dgType, void *data) +{ + struct guiHeader *obj = (guiObject_t *)dialog; + struct guiBox *box ; + CLEAR_OBJ(dialog); + + box = &obj->box; + + box->x = x; + box->y = y; + box->width = width; + box->height = height; + + obj->Type = Dialog; + OBJ_SET_TRANSPARENT(obj, 0); + OBJ_SET_MODAL(obj, 1); + connect_object(obj); + + dialog->string_cb = string_cb; + dialog->title = title; + dialog->CallBack = *CallBack; + dialog->cbData = data; + dialog->txtbox.x = x + DIALOG_TXTOFFSET_X; + dialog->txtbox.y = 0; + dialog->txtbox.width = 0; + dialog->txtbox.height = 0; + + struct guiObject *but = NULL; + int button_width = GUI_ButtonWidth(DIALOG_BUTTON); + int button_height = GUI_ButtonHeight(DIALOG_BUTTON); + (void)button_width; + (void)button_height; + switch (dgType) { + case dtOk: + case dtCancel: + { + but = GUI_CreateButton(&dialog->but1, DIALOG_SINGLE_BUTTON_X, DIALOG_SINGLE_BUTTON_Y, + DIALOG_BUTTON, + dgType == dtOk ? dlgbut_strok_cb : dlgbut_strcancel_cb, + 0x0000, + dgType == dtOk ? dlgbut_pressok_cb : dlgbut_presscancel_cb, + obj); + } + break; + case dtOkCancel: { + GUI_CreateButton(&dialog->but1, DIALOG_DUAL_BUTTON_X1, DIALOG_DUAL_BUTTON_Y, + DIALOG_BUTTON, dlgbut_strok_cb, 0x0000, dlgbut_pressok_cb, obj); + but = GUI_CreateButton(&dialog->but2, DIALOG_DUAL_BUTTON_X2, DIALOG_DUAL_BUTTON_Y, + DIALOG_BUTTON, dlgbut_strcancel_cb, 0x0000, dlgbut_presscancel_cb, obj); + } + break; + case dtNone: + break; + } + objDIALOG = obj; + + GUI_HandleModalButtons(1); + previous_selected_obj = objSELECTED; // used for devo10 only + objSELECTED = but; + //bug fix: using objSELECTED for dialog is not safe in devo10 + objModalButton = but; + return obj; +} + +void GUI_DrawDialog(struct guiObject *obj) +{ + struct guiBox *box = &obj->box; + struct guiDialog *dialog = (struct guiDialog *)obj; + if (dialog->txtbox.height == 0) { + _draw_dialog_box(box, dialog->txtbox.x, dialog->title); + } else if(dialog->txtbox.width) { + // NOTE: We assume all redraw events after the 1st are incremental! + GUI_DialogDrawBackground(dialog->txtbox.x, dialog->txtbox.y, + dialog->txtbox.width, dialog->txtbox.height); + } + const char *str = dialog->string_cb + ? dialog->string_cb(obj, dialog->cbData) + : (const char *)dialog->cbData; + int button_height = GUI_ButtonHeight(DIALOG_BUTTON); + LCD_SetFont(DIALOGBODY_FONT.font); + LCD_SetFontColor(DIALOGBODY_FONT.font_color); + LCD_GetStringDimensions((const u8 *)str, &dialog->txtbox.width, &dialog->txtbox.height); + dialog->txtbox.y = box->y + DIALOG_HEADER_Y + + (box->height - dialog->txtbox.height - DIALOG_HEADER_Y - button_height) / 2; + LCD_PrintStringXY(dialog->txtbox.x, dialog->txtbox.y, str); +} + +void GUI_DialogDrawBackground(u16 x, u16 y, u16 w, u16 h) +{ + _dialog_draw_background(x, y, w, h); +} + +void DialogClose(struct guiObject *obj, u8 state) +{ + struct guiDialog *dialog = (struct guiDialog *)obj; + void *data = dialog->string_cb ? dialog->cbData : NULL; + void (*func)(u8, void*) = dialog->CallBack; + GUI_RemoveObj(obj); + func(state, data); + if (previous_selected_obj != NULL) + GUI_SetSelected(previous_selected_obj); +} +void dlgbut_pressok_cb(struct guiObject *obj, const void *data) +{ + (void)obj; + struct guiObject *dlgObj = (struct guiObject *)data; + DialogClose(dlgObj, 1); +} + +void dlgbut_presscancel_cb(struct guiObject *obj, const void *data) +{ + (void)obj; + struct guiObject *dlgObj = (struct guiObject *)data; + DialogClose(dlgObj, 0); +} + +const char * dlgbut_strok_cb(struct guiObject *obj, const void *data) +{ + (void)obj; + (void)data; + return _tr("Ok"); +} +const char * dlgbut_strcancel_cb(struct guiObject *obj, const void *data) +{ + (void)obj; + (void)data; + return _tr("Cancel"); +} diff --git a/pool/shard004/C/0097399_procon3.c b/pool/shard004/C/0097399_procon3.c new file mode 100644 index 0000000000000000000000000000000000000000..2a6bee9900c16ff487d5b7afa333ce885822dfee --- /dev/null +++ b/pool/shard004/C/0097399_procon3.c @@ -0,0 +1,100 @@ +#include +#include +#include +#include +#include + +#define MAXNITMES 10000000 +#define MAXNTHREADS 100 +int nitems; +struct { + pthread_mutex_t mutex; + int buff[MAXNITMES]; + int nput; + int nval; +} shared={ + PTHREAD_MUTEX_INITIALIZER +}; + +struct{ + pthread_mutex_t mutex; + pthread_cond_t cond; + int nready; +}ready={PTHREAD_MUTEX_INITIALIZER, + PTHREAD_COND_INITIALIZER +}; + +void consume_wait(int i){ + for(;;){ + pthread_mutex_lock(&shared.mutex); + if(i=b)?b:a; +} +int main(int argc,char* argv[]){ + int i,nthreads,count[MAXNTHREADS]; + pthread_t tid_produce[MAXNTHREADS],tid_consume; + nitems=min(atoi(argv[1]),MAXNITMES); + nthreads=min(atoi(argv[2]),MAXNTHREADS); + clock_t st,ed; + double gap; + st=clock(); + for(i=0;i=nitems){ + pthread_mutex_unlock(&shared.mutex); + break; + } + shared.buff[shared.nput]=shared.nval; + shared.nval++; + shared.nput++; + pthread_mutex_unlock(&shared.mutex); + + pthread_mutex_lock(&ready.mutex); + if(ready.nready==0) + pthread_cond_signal(&ready.cond); + ready.nready++; + pthread_mutex_unlock(&ready.mutex); + *((int*)arg)+=1; + + } +} +void* consume(void* arg){ + int i; + for(i=0;i +#include "network-functions.c" +#include "ii-functions.c" +// toss file format is raw msgline, NOT base64 + +char** dirs; +DIR *dir_with_tosses; +struct dirent *filename; +int filescount=0, i, result; +int MAXFILES=512; // максимальное количество файлов в out/ + +int comp(const void *a, const void *b) { + const char *u = (const char *)a; + const char *v = (const char *)b; + return strcmp(u, v); +} + +int main() { + ii_base_init(); + + // выделяем ещё памяти для адреса, чтобы засунуть туда u/point + char* send_adress=(char*)malloc(sizeof(char*)*(strlen(adress)+8)); + + strcpy(send_adress, adress); + strcat(send_adress, "u/point"); + + dir_with_tosses=opendir(tossesdir); + dirs=(char**)malloc(sizeof(char*)*MAXFILES); + + while((filename=readdir(dir_with_tosses))!=NULL) { + if ( + (strcmp(filename->d_name, ".")!=0) && + (strcmp(filename->d_name, "..")!=0) + ) { + dirs[filescount]=(char*)malloc(sizeof(filename->d_name)); + strcpy(dirs[filescount++], filename->d_name); + } + } + qsort(dirs, filescount, sizeof(char*), comp); // сортируем тоссы; точнее, пытаемся + + if (filescount==0) return 0; + + char* encoded_authstr=curl_easy_escape(curl, authstr, 0); + + for (i=0;i +#include +#include +#include + +atomic_int vars[4]; +atomic_int atom_1_r1_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 v6_r4 = atomic_load_explicit(&vars[2+v3_r3], memory_order_seq_cst); + int v8_r6 = atomic_load_explicit(&vars[2], memory_order_seq_cst); + int v9_r7 = v8_r6 ^ v8_r6; + int v10_r7 = v9_r7 + 1; + atomic_store_explicit(&vars[3], v10_r7, memory_order_seq_cst); + int v12_r9 = atomic_load_explicit(&vars[3], memory_order_seq_cst); + int v13_r10 = v12_r9 ^ v12_r9; + int v14_r10 = v13_r10 + 1; + atomic_store_explicit(&vars[0], v14_r10, memory_order_seq_cst); + int v19 = (v2_r1 == 1); + atomic_store_explicit(&atom_1_r1_1, v19, memory_order_seq_cst); + return NULL; +} + +int main(int argc, char *argv[]){ + pthread_t thr0; + pthread_t thr1; + + atomic_init(&vars[0], 0); + atomic_init(&vars[3], 0); + atomic_init(&vars[1], 0); + atomic_init(&vars[2], 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 v15 = atomic_load_explicit(&vars[0], memory_order_seq_cst); + int v16 = (v15 == 2); + int v17 = atomic_load_explicit(&atom_1_r1_1, memory_order_seq_cst); + int v18_conj = v16 & v17; + if (v18_conj == 1) assert(0); + return 0; +} diff --git a/pool/shard004/C/0097404_lapacke_clantr.c b/pool/shard004/C/0097404_lapacke_clantr.c new file mode 100644 index 0000000000000000000000000000000000000000..4ba436753b86bbb1bafbfd330b0cadeedbb3bdb6 --- /dev/null +++ b/pool/shard004/C/0097404_lapacke_clantr.c @@ -0,0 +1,75 @@ +/***************************************************************************** + 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 clantr +* Author: Intel Corporation +* Generated November 2015 +*****************************************************************************/ + +#include "lapacke_utils.h" + +float LAPACKE_clantr( int matrix_layout, char norm, char uplo, char diag, + lapack_int m, lapack_int n, const lapack_complex_float* a, + lapack_int lda ) +{ + lapack_int info = 0; + float res = 0.; + float* work = NULL; + if( matrix_layout != LAPACK_COL_MAJOR && matrix_layout != LAPACK_ROW_MAJOR ) { + LAPACKE_xerbla( "LAPACKE_clantr", -1 ); + return -1; + } +#ifndef LAPACK_DISABLE_NAN_CHECK + /* Optionally check input matrices for NaNs */ + if( LAPACKE_ctr_nancheck( matrix_layout, uplo, diag, MIN(m,n), a, lda ) ) { + return -7; + } +#endif + /* Allocate memory for working array(s) */ + if( LAPACKE_lsame( norm, 'i' ) || LAPACKE_lsame( norm, '1' ) || + LAPACKE_lsame( norm, 'O' ) ) { + work = (float*)LAPACKE_malloc( sizeof(float) * MAX(1,MAX(m,n)) ); + if( work == NULL ) { + info = LAPACK_WORK_MEMORY_ERROR; + goto exit_level_0; + } + } + /* Call middle-level interface */ + res = LAPACKE_clantr_work( matrix_layout, norm, uplo, diag, m, n, a, lda, + work ); + /* Release memory and exit */ + if( LAPACKE_lsame( norm, 'i' ) || LAPACKE_lsame( norm, '1' ) || + LAPACKE_lsame( norm, 'O' ) ) { + LAPACKE_free( work ); + } +exit_level_0: + if( info == LAPACK_WORK_MEMORY_ERROR ) { + LAPACKE_xerbla( "LAPACKE_clantr", info ); + } + return res; +} diff --git a/pool/shard004/C/0097406_nm-device-adsl.c b/pool/shard004/C/0097406_nm-device-adsl.c new file mode 100644 index 0000000000000000000000000000000000000000..6812168370745a08363d274af6f78d59e5f87b62 --- /dev/null +++ b/pool/shard004/C/0097406_nm-device-adsl.c @@ -0,0 +1,244 @@ +/* -*- 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. + * + * author: Pantelis Koukousoulas + * Copyright 2009 - 2011 Red Hat, Inc. + */ + +#include "config.h" + +#include "nm-device-adsl.h" +#include "nm-device-private.h" +#include "nm-object-private.h" + +#include "nm-setting-adsl.h" + +#include + +G_DEFINE_TYPE (NMDeviceAdsl, nm_device_adsl, NM_TYPE_DEVICE) + +#define NM_DEVICE_ADSL_GET_PRIVATE(o) (G_TYPE_INSTANCE_GET_PRIVATE ((o), NM_TYPE_DEVICE_ADSL, NMDeviceAdslPrivate)) + +typedef struct { + DBusGProxy *proxy; + + gboolean carrier; + + gboolean disposed; +} NMDeviceAdslPrivate; + +enum { + PROP_0, + PROP_CARRIER, + LAST_PROP +}; + +/** + * nm_device_adsl_error_quark: + * + * Registers an error quark for #NMDeviceAdsl if necessary. + * + * Returns: the error quark used for #NMDeviceAdsl errors. + **/ +GQuark +nm_device_adsl_error_quark (void) +{ + static GQuark quark = 0; + + if (G_UNLIKELY (quark == 0)) + quark = g_quark_from_static_string ("nm-device-adsl-error-quark"); + return quark; +} + +/** + * nm_device_adsl_new: + * @connection: the #DBusGConnection + * @path: the DBus object path of the device + * + * Creates a new #NMDeviceAdsl. + * + * Returns: (transfer full): a new device + **/ +GObject * +nm_device_adsl_new (DBusGConnection *connection, const char *path) +{ + GObject *device; + + g_return_val_if_fail (connection != NULL, NULL); + g_return_val_if_fail (path != NULL, NULL); + + device = g_object_new (NM_TYPE_DEVICE_ADSL, + NM_OBJECT_DBUS_CONNECTION, connection, + NM_OBJECT_DBUS_PATH, path, + NULL); + _nm_object_ensure_inited (NM_OBJECT (device)); + return device; +} + +/** + * nm_device_adsl_get_carrier: + * @device: a #NMDeviceAdsl + * + * Whether the device has carrier. + * + * Returns: %TRUE if the device has carrier + **/ +gboolean +nm_device_adsl_get_carrier (NMDeviceAdsl *device) +{ + g_return_val_if_fail (NM_IS_DEVICE_ADSL (device), FALSE); + + _nm_object_ensure_inited (NM_OBJECT (device)); + return NM_DEVICE_ADSL_GET_PRIVATE (device)->carrier; +} + +static gboolean +connection_compatible (NMDevice *device, NMConnection *connection, GError **error) +{ + NMSettingConnection *s_con; + NMSettingAdsl *s_adsl; + const char *ctype; + + s_con = nm_connection_get_setting_connection (connection); + g_assert (s_con); + + ctype = nm_setting_connection_get_connection_type (s_con); + if (strcmp (ctype, NM_SETTING_ADSL_SETTING_NAME) != 0) { + g_set_error (error, NM_DEVICE_ADSL_ERROR, NM_DEVICE_ADSL_ERROR_NOT_ADSL_CONNECTION, + "The connection was not an ADSL connection."); + return FALSE; + } + + s_adsl = nm_connection_get_setting_adsl (connection); + if (!s_adsl) { + g_set_error (error, NM_DEVICE_ADSL_ERROR, NM_DEVICE_ADSL_ERROR_INVALID_ADSL_CONNECTION, + "The connection was not a valid ADSL connection."); + return FALSE; + } + + return NM_DEVICE_CLASS (nm_device_adsl_parent_class)->connection_compatible (device, connection, error); +} + +static GType +get_setting_type (NMDevice *device) +{ + return NM_TYPE_SETTING_ADSL; +} + +/******************************************************************/ + +static void +nm_device_adsl_init (NMDeviceAdsl *device) +{ + _nm_device_set_device_type (NM_DEVICE (device), NM_DEVICE_TYPE_ADSL); +} + +static void +register_properties (NMDeviceAdsl *device) +{ + NMDeviceAdslPrivate *priv = NM_DEVICE_ADSL_GET_PRIVATE (device); + const NMPropertiesInfo property_info[] = { + { NM_DEVICE_ADSL_CARRIER, &priv->carrier }, + { NULL }, + }; + + _nm_object_register_properties (NM_OBJECT (device), + priv->proxy, + property_info); +} + +static void +constructed (GObject *object) +{ + NMDeviceAdslPrivate *priv = NM_DEVICE_ADSL_GET_PRIVATE (object); + + G_OBJECT_CLASS (nm_device_adsl_parent_class)->constructed (object); + + priv->proxy = _nm_object_new_proxy (NM_OBJECT (object), NULL, NM_DBUS_INTERFACE_DEVICE_ADSL); + register_properties (NM_DEVICE_ADSL (object)); +} + +static void +dispose (GObject *object) +{ + NMDeviceAdslPrivate *priv = NM_DEVICE_ADSL_GET_PRIVATE (object); + + if (priv->disposed) { + G_OBJECT_CLASS (nm_device_adsl_parent_class)->dispose (object); + return; + } + + priv->disposed = TRUE; + + g_object_unref (priv->proxy); + + G_OBJECT_CLASS (nm_device_adsl_parent_class)->dispose (object); +} + +static void +finalize (GObject *object) +{ + G_OBJECT_CLASS (nm_device_adsl_parent_class)->finalize (object); +} + +static void +get_property (GObject *object, + guint prop_id, + GValue *value, + GParamSpec *pspec) +{ + NMDeviceAdsl *device = NM_DEVICE_ADSL (object); + + switch (prop_id) { + case PROP_CARRIER: + g_value_set_boolean (value, nm_device_adsl_get_carrier (device)); + break; + default: + G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec); + break; + } +} + +static void +nm_device_adsl_class_init (NMDeviceAdslClass *adsl_class) +{ + GObjectClass *object_class = G_OBJECT_CLASS (adsl_class); + NMDeviceClass *device_class = NM_DEVICE_CLASS (adsl_class); + + g_type_class_add_private (object_class, sizeof (NMDeviceAdslPrivate)); + + /* virtual methods */ + object_class->constructed = constructed; + object_class->dispose = dispose; + object_class->finalize = finalize; + object_class->get_property = get_property; + device_class->connection_compatible = connection_compatible; + device_class->get_setting_type = get_setting_type; + + /* properties */ + /** + * NMDeviceAdsl:carrier: + * + * Whether the device has carrier. + **/ + g_object_class_install_property + (object_class, PROP_CARRIER, + g_param_spec_boolean (NM_DEVICE_ADSL_CARRIER, "", "", + FALSE, + G_PARAM_READABLE | + G_PARAM_STATIC_STRINGS)); +} diff --git a/pool/shard004/C/0097416_key_event.c b/pool/shard004/C/0097416_key_event.c new file mode 100644 index 0000000000000000000000000000000000000000..2e1c536f84946bb074b0e89877d867f81dc144a5 --- /dev/null +++ b/pool/shard004/C/0097416_key_event.c @@ -0,0 +1,49 @@ +#include +#include +#include +#include +#include +#include +#include + +static const char* const evval[3] = { + "RELEASED", + "PRESSED", + "REPEATED" +}; + +int main(int argc, char const *argv[]) +{ + const char* dev = "/dev/input/by-id/usb-Generic_USB_Keyboard-event-kbd"; + struct input_event ev; + ssize_t n; + int fd; + + fd = open(dev, O_RDONLY); + if (fd == -1) { + fprintf(stderr, "Cannot open %s: %s.\n", dev, strerror(errno)); + return EXIT_FAILURE; + } + + do { + n = read(fd, &ev, sizeof(ev)); + if (n == (ssize_t)-1) { + if (errno == EINTR) + continue; + else + break; + } else if (n != sizeof(ev)) { + errno = EIO; + break; + } + if (ev.type == EV_KEY && ev.value >= 0 && ev.value <= 2) { + fprintf(stdout, "\t%s\t 0x%04x\t (%d)\n", evval[ev.value], (int)ev.code, (int)ev.code); + } + } while(1); + + fflush(stdout); + fprintf(stderr, "%s.\n", strerror(errno)); + + return EXIT_SUCCESS; +} + diff --git a/pool/shard004/C/0097419_comms.c b/pool/shard004/C/0097419_comms.c new file mode 100644 index 0000000000000000000000000000000000000000..1748d47825a548a00754351f9d2f3ec1c57d722f --- /dev/null +++ b/pool/shard004/C/0097419_comms.c @@ -0,0 +1,168 @@ +/* + * Copyright (C) 2003 Tim Angus + * + * 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; see the file COPYING. If not, write to the Free + * Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. + */ + +#include +#include + +#include +#include +#include +#include + +#include "comms.h" +#include "../rtprof/com_common.h" +#include "../rtprof/lib_comms.h" + +extern int connection; + +/* +=============== +parseSocketVariable +=============== +*/ +static int parseSocketVariable( char *buffer, int bufferSize ) +{ + char *env; + + env = getenv( RTPROF_SKT ); + + if( env != NULL ) + { + if( !strncmp( env, INET_PREFIX, INET_LENGTH ) ) + { + strncpy( buffer, env + INET_LENGTH, bufferSize - INET_LENGTH ); + return AF_INET; + } + else if( !strncmp( env, FILE_PREFIX, FILE_LENGTH ) ) + { + strncpy( buffer, env + FILE_LENGTH, bufferSize - FILE_LENGTH ); + return AF_UNIX; + } + else + return -1; + } + else + return -1; +} + + +/* +=============== +disconnectFromRtprof + +Disconnect from analysis program +=============== +*/ +void disconnectFromRtprof( void ) +{ + functionEvent_t fe; + + fe.type = EV_PROCEXIT; + + sendFE( connection, fe ); + close( connection ); +} + + +/* +=============== +disconnectFromFailedRtprof + +Disconnect from failed analysis program +=============== +*/ +void disconnectFromFailedRtprof( void ) +{ + close( connection ); + connection = -1; +} + + +#define MAX_HB 160 + +/* +=============== +connectToRtprof + +Connect to analysis program +=============== +*/ +int connectToRtprof( void ) +{ + int socketType; + char hostBuffer[ MAX_HB ]; + int s; + + socketType = parseSocketVariable( hostBuffer, MAX_HB ); + + if( socketType == AF_INET ) + { + //tcp socket + struct sockaddr_in sa; + struct hostent *hp; + + if( ( hp = gethostbyname( hostBuffer ) ) == NULL ) + return -1; + + memset( &sa, 0, sizeof( sa ) ); + + memcpy( (char *)&sa.sin_addr, hp->h_addr, hp->h_length ); + sa.sin_family = hp->h_addrtype; + sa.sin_port = htons( (u_short)RTPROF_PORT ); + + if( ( s = socket( hp->h_addrtype, SOCK_STREAM, 0 ) ) < 0 ) + return -1; + + if( connect( s, (struct sockaddr *)&sa, sizeof( sa ) ) < 0 ) + { + close( s ); + return -1; + } + + return s; + } + else if( socketType == AF_UNIX ) + { + //file socket + struct sockaddr_un sa; + + memset( &sa, 0, sizeof( sa ) ); + + strcpy( sa.sun_path, hostBuffer ); + sa.sun_family = AF_UNIX; + + if( ( s = socket( AF_UNIX, SOCK_STREAM, 0 ) ) < 0 ) + return -1; + + if( connect( s, (struct sockaddr *)&sa, sizeof( sa ) ) < 0 ) + { + close( s ); + return -1; + } + + return s; + } + else if( socketType < 0 ) + { + fprintf( stderr, "WARNING: librtprof cannot parse environment" + "variable RTPROF_SKT\n" ); + return -1; + } + + return -1; +} diff --git a/pool/shard004/C/0097422_util_printlog.c b/pool/shard004/C/0097422_util_printlog.c new file mode 100644 index 0000000000000000000000000000000000000000..ff9210b575f79dcb269a625eaf46b221cfe255ba --- /dev/null +++ b/pool/shard004/C/0097422_util_printlog.c @@ -0,0 +1,66 @@ +/*- + * Copyright (c) 2014-2015 MongoDB, Inc. + * Copyright (c) 2008-2014 WiredTiger, Inc. + * All rights reserved. + * + * See the file LICENSE for redistribution information. + */ + +#include "util.h" + +static int usage(void); + +int +util_printlog(WT_SESSION *session, int argc, char *argv[]) +{ + WT_DECL_RET; + int ch, printable; + + printable = 0; + while ((ch = __wt_getopt(progname, argc, argv, "f:p")) != EOF) + switch (ch) { + case 'f': /* output file */ + if (freopen(__wt_optarg, "w", stdout) == NULL) { + fprintf(stderr, "%s: %s: reopen: %s\n", + progname, __wt_optarg, strerror(errno)); + return (1); + } + break; + case 'p': + printable = 1; + break; + case '?': + default: + return (usage()); + } + argc -= __wt_optind; + argv += __wt_optind; + + /* There should not be any more arguments. */ + if (argc != 0) + return (usage()); + + WT_UNUSED(printable); + ret = __wt_txn_printlog(session, stdout); + + if (ret != 0) { + fprintf(stderr, "%s: printlog failed: %s\n", + progname, wiredtiger_strerror(ret)); + goto err; + } + + if (0) { +err: ret = 1; + } + return (ret); +} + +static int +usage(void) +{ + (void)fprintf(stderr, + "usage: %s %s " + "printlog [-p] [-f output-file]\n", + progname, usage_prefix); + return (1); +} diff --git a/pool/shard004/C/0097426_complex.c b/pool/shard004/C/0097426_complex.c new file mode 100644 index 0000000000000000000000000000000000000000..1d9970ff579b334501ad7770d0eab68a93f11324 --- /dev/null +++ b/pool/shard004/C/0097426_complex.c @@ -0,0 +1,34 @@ +/* complex.c + Copyright (C) 2016, 2018 Eric Herman + + 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 General Public License for more details. + + https://www.gnu.org/licenses/lgpl-3.0.txt + https://www.gnu.org/licenses/gpl-3.0.txt + */ +/* gcc -o complex complex.c -lm */ +#include +#include + +char *url1 = "https://mitpress.mit.edu/sicp/full-text/sicp/book/node43.html"; +char *url2 = "http://en.cppreference.com/w/c/numeric/complex"; +int main(void) +{ + complex float z = 23.0 + 5.0 * I; + + printf("z = %.1f + %.1fI\n", creal(z), cimag(z)); + printf("magnitue(z) = %f\n", cabs(z)); + printf("phase angle(z) = %f\n", carg(z)); + printf("thus %.1f%+.1fi cartesian as polar becomes rho=%f theta=%f\n", + creal(z), cimag(z), cabs(z), carg(z)); + + printf("\nSee also:\n%s\n%s\n", url1, url2); +} diff --git a/pool/shard004/C/0097427_proc.c b/pool/shard004/C/0097427_proc.c new file mode 100644 index 0000000000000000000000000000000000000000..b3ce8859a586e58a6beb69b5aaa6fa4a86b7e288 --- /dev/null +++ b/pool/shard004/C/0097427_proc.c @@ -0,0 +1,139 @@ +/* + * $Id: proc.c,v 1.1.2.1 1998/06/07 23:21:01 geert Exp $ + * + * Procfs interface for the Zorro bus. + * + * Copyright (C) 1998-2003 Geert Uytterhoeven + * + * Heavily based on the procfs interface for the PCI bus, which is + * + * Copyright (C) 1997, 1998 Martin Mares + */ + +#include +#include +#include +#include +#include +#include +#include +#include + +static loff_t +proc_bus_zorro_lseek(struct file *file, loff_t off, int whence) +{ + loff_t new = -1; + + lock_kernel(); + switch (whence) { + case 0: + new = off; + break; + case 1: + new = file->f_pos + off; + break; + case 2: + new = sizeof(struct ConfigDev) + off; + break; + } + if (new < 0 || new > sizeof(struct ConfigDev)) { + unlock_kernel(); + return -EINVAL; + } + unlock_kernel(); + return (file->f_pos = new); +} + +static ssize_t +proc_bus_zorro_read(struct file *file, char __user *buf, size_t nbytes, loff_t *ppos) +{ + struct inode *ino = file->f_path.dentry->d_inode; + struct proc_dir_entry *dp = PDE(ino); + struct zorro_dev *z = dp->data; + struct ConfigDev cd; + loff_t pos = *ppos; + + if (pos >= sizeof(struct ConfigDev)) + return 0; + if (nbytes >= sizeof(struct ConfigDev)) + nbytes = sizeof(struct ConfigDev); + if (pos + nbytes > sizeof(struct ConfigDev)) + nbytes = sizeof(struct ConfigDev) - pos; + + /* Construct a ConfigDev */ + memset(&cd, 0, sizeof(cd)); + cd.cd_Rom = z->rom; + cd.cd_SlotAddr = z->slotaddr; + cd.cd_SlotSize = z->slotsize; + cd.cd_BoardAddr = (void *)zorro_resource_start(z); + cd.cd_BoardSize = zorro_resource_len(z); + + if (copy_to_user(buf, &cd, nbytes)) + return -EFAULT; + *ppos += nbytes; + + return nbytes; +} + +static const struct file_operations proc_bus_zorro_operations = { + .llseek = proc_bus_zorro_lseek, + .read = proc_bus_zorro_read, +}; + +static int +get_zorro_dev_info(char *buf, char **start, off_t pos, int count) +{ + u_int slot; + off_t at = 0; + int len, cnt; + + for (slot = cnt = 0; slot < zorro_num_autocon && count > cnt; slot++) { + struct zorro_dev *z = &zorro_autocon[slot]; + len = sprintf(buf, "%02x\t%08x\t%08lx\t%08lx\t%02x\n", slot, + z->id, zorro_resource_start(z), + zorro_resource_len(z), z->rom.er_Type); + at += len; + if (at >= pos) { + if (!*start) { + *start = buf + (pos - (at - len)); + cnt = at - pos; + } else + cnt += len; + buf += len; + } + } + return (count > cnt) ? cnt : count; +} + +static struct proc_dir_entry *proc_bus_zorro_dir; + +static int __init zorro_proc_attach_device(u_int slot) +{ + struct proc_dir_entry *entry; + char name[4]; + + sprintf(name, "%02x", slot); + entry = create_proc_entry(name, 0, proc_bus_zorro_dir); + if (!entry) + return -ENOMEM; + entry->proc_fops = &proc_bus_zorro_operations; + entry->data = &zorro_autocon[slot]; + entry->size = sizeof(struct zorro_dev); + return 0; +} + +static int __init zorro_proc_init(void) +{ + u_int slot; + + if (MACH_IS_AMIGA && AMIGAHW_PRESENT(ZORRO)) { + proc_bus_zorro_dir = proc_mkdir("zorro", proc_bus); + create_proc_info_entry("devices", 0, proc_bus_zorro_dir, + get_zorro_dev_info); + for (slot = 0; slot < zorro_num_autocon; slot++) + zorro_proc_attach_device(slot); + } + return 0; +} + +__initcall(zorro_proc_init); diff --git a/pool/shard004/C/0097430_set_sys_flag.c b/pool/shard004/C/0097430_set_sys_flag.c new file mode 100644 index 0000000000000000000000000000000000000000..7ea0f8db47eab5a9b85922aa39feca886a2a9b2a --- /dev/null +++ b/pool/shard004/C/0097430_set_sys_flag.c @@ -0,0 +1,104 @@ +#include +#include +#include +#include + + + +#define DISK_DEV "/dev/mmcblk0" + + +#define KBYTE (1024LL) +#define MBYTE ((KBYTE)*(KBYTE)) +#define GBYTE ((MBYTE)*(KBYTE)) + + +#define NVRAM_BASE_ADDR 0x40000 +#define NVRAM_LEN 512 + +#define ARRAY_SIZE(x) ((sizeof(x))/(sizeof(x[0]))) + +struct private_data +{ + unsigned char wifimode; + unsigned char mpsta; + unsigned char boot_flag; + unsigned char sys_flag; +}; + +static void usage(void) +{ + + printf("usage: set system flag\n"); + printf(" auto : auto set the first system flag \n"); + //printf(" first : set the first system flag \n"); + //printf(" second : set the second system flag\n"); + + printf("\n"); + + exit(1); +} + + + +int main(int argc, char **argv) +{ + int fd = -1; + struct private_data *p_data; + unsigned char buf[NVRAM_LEN]; + + if(argc < 2 || !strcmp(argv[1],"-h")) + { + usage(); + exit(0); + } + if(!strcmp(argv[1],"auto")) + { + fd = open(DISK_DEV,O_RDONLY); + if(fd < 0) + { + printf("open %s failed.\n",DISK_DEV); + exit(1); + } + lseek(fd, NVRAM_BASE_ADDR,SEEK_SET); + if(read(fd,buf,NVRAM_LEN) != NVRAM_LEN) + { + printf("read %s failed.\n",DISK_DEV); + close(fd); + return -1; + } + p_data=(struct private_data *) buf; + close(fd); + + if(p_data->boot_flag > 3) + { + p_data->boot_flag = 0; + system("touch /tmp/in_backup_system"); + } + else + { + p_data->sys_flag = !p_data->sys_flag; + } + fd = open(DISK_DEV,O_RDWR); + if(fd < 0) + { + printf("open %s failed.\n",DISK_DEV); + return -1; + } + lseek(fd, NVRAM_BASE_ADDR,SEEK_SET); + if(write(fd,buf,NVRAM_LEN) != NVRAM_LEN) + { + printf("write %s failed.\n",DISK_DEV); + close(fd); + return -1; + } + close(fd); + } + else + { + usage(); + exit(0); + } + return 0; + +} diff --git a/pool/shard004/C/0097433_threads.c b/pool/shard004/C/0097433_threads.c new file mode 100644 index 0000000000000000000000000000000000000000..f128d69fc2355512e1014ad63c90f9e198123319 --- /dev/null +++ b/pool/shard004/C/0097433_threads.c @@ -0,0 +1,274 @@ +/* +** 2012 July 21 +** +** 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 presents a simple cross-platform threading interface for +** use internally by SQLite. +** +** A "thread" can be created using sqlite3ThreadCreate(). This thread +** runs independently of its creator until it is joined using +** sqlite3ThreadJoin(), at which point it terminates. +** +** Threads do not have to be real. It could be that the work of the +** "thread" is done by the main thread at either the sqlite3ThreadCreate() +** or sqlite3ThreadJoin() call. This is, in fact, what happens in +** single threaded systems. Nothing in SQLite requires multiple threads. +** This interface exists so that applications that want to take advantage +** of multiple cores can do so, while also allowing applications to stay +** single-threaded if desired. +*/ +#include "sqliteInt.h" +#if SQLITE_OS_WIN +# include "os_win.h" +#endif + +#if SQLITE_MAX_WORKER_THREADS>0 + +/********************************* Unix Pthreads ****************************/ +#if SQLITE_OS_UNIX && defined(SQLITE_MUTEX_PTHREADS) && SQLITE_THREADSAFE>0 + +#define SQLITE_THREADS_IMPLEMENTED 1 /* Prevent the single-thread code below */ +#include + +/* A running thread */ +struct SQLiteThread { + pthread_t tid; /* Thread ID */ + int done; /* Set to true when thread finishes */ + void *pOut; /* Result returned by the thread */ + void *(*xTask)(void*); /* The thread routine */ + void *pIn; /* Argument to the thread */ +}; + +/* Create a new thread */ +int sqlite3ThreadCreate( + SQLiteThread **ppThread, /* OUT: Write the thread object here */ + void *(*xTask)(void*), /* Routine to run in a separate thread */ + void *pIn /* Argument passed into xTask() */ +){ + SQLiteThread *p; + int rc; + + assert( ppThread!=0 ); + assert( xTask!=0 ); + /* This routine is never used in single-threaded mode */ + assert( sqlite3GlobalConfig.bCoreMutex!=0 ); + + *ppThread = 0; + p = sqlite3Malloc(sizeof(*p)); + if( p==0 ) return SQLITE_NOMEM_BKPT; + memset(p, 0, sizeof(*p)); + p->xTask = xTask; + p->pIn = pIn; + /* If the SQLITE_TESTCTRL_FAULT_INSTALL callback is registered to a + ** function that returns SQLITE_ERROR when passed the argument 200, that + ** forces worker threads to run sequentially and deterministically + ** for testing purposes. */ + if( sqlite3FaultSim(200) ){ + rc = 1; + }else{ + rc = pthread_create(&p->tid, 0, xTask, pIn); + } + if( rc ){ + p->done = 1; + p->pOut = xTask(pIn); + } + *ppThread = p; + return SQLITE_OK; +} + +/* Get the results of the thread */ +int sqlite3ThreadJoin(SQLiteThread *p, void **ppOut){ + int rc; + + assert( ppOut!=0 ); + if( NEVER(p==0) ) return SQLITE_NOMEM_BKPT; + if( p->done ){ + *ppOut = p->pOut; + rc = SQLITE_OK; + }else{ + rc = pthread_join(p->tid, ppOut) ? SQLITE_ERROR : SQLITE_OK; + } + sqlite3_free(p); + return rc; +} + +#endif /* SQLITE_OS_UNIX && defined(SQLITE_MUTEX_PTHREADS) */ +/******************************** End Unix Pthreads *************************/ + + +/********************************* Win32 Threads ****************************/ +#if SQLITE_OS_WIN_THREADS + +#define SQLITE_THREADS_IMPLEMENTED 1 /* Prevent the single-thread code below */ +#include + +/* A running thread */ +struct SQLiteThread { + void *tid; /* The thread handle */ + unsigned id; /* The thread identifier */ + void *(*xTask)(void*); /* The routine to run as a thread */ + void *pIn; /* Argument to xTask */ + void *pResult; /* Result of xTask */ +}; + +/* Thread procedure Win32 compatibility shim */ +static unsigned __stdcall sqlite3ThreadProc( + void *pArg /* IN: Pointer to the SQLiteThread structure */ +){ + SQLiteThread *p = (SQLiteThread *)pArg; + + assert( p!=0 ); +#if 0 + /* + ** This assert appears to trigger spuriously on certain + ** versions of Windows, possibly due to _beginthreadex() + ** and/or CreateThread() not fully setting their thread + ** ID parameter before starting the thread. + */ + assert( p->id==GetCurrentThreadId() ); +#endif + assert( p->xTask!=0 ); + p->pResult = p->xTask(p->pIn); + + _endthreadex(0); + return 0; /* NOT REACHED */ +} + +/* Create a new thread */ +int sqlite3ThreadCreate( + SQLiteThread **ppThread, /* OUT: Write the thread object here */ + void *(*xTask)(void*), /* Routine to run in a separate thread */ + void *pIn /* Argument passed into xTask() */ +){ + SQLiteThread *p; + + assert( ppThread!=0 ); + assert( xTask!=0 ); + *ppThread = 0; + p = sqlite3Malloc(sizeof(*p)); + if( p==0 ) return SQLITE_NOMEM_BKPT; + /* If the SQLITE_TESTCTRL_FAULT_INSTALL callback is registered to a + ** function that returns SQLITE_ERROR when passed the argument 200, that + ** forces worker threads to run sequentially and deterministically + ** (via the sqlite3FaultSim() term of the conditional) for testing + ** purposes. */ + if( sqlite3GlobalConfig.bCoreMutex==0 || sqlite3FaultSim(200) ){ + memset(p, 0, sizeof(*p)); + }else{ + p->xTask = xTask; + p->pIn = pIn; + p->tid = (void*)_beginthreadex(0, 0, sqlite3ThreadProc, p, 0, &p->id); + if( p->tid==0 ){ + memset(p, 0, sizeof(*p)); + } + } + if( p->xTask==0 ){ + p->id = GetCurrentThreadId(); + p->pResult = xTask(pIn); + } + *ppThread = p; + return SQLITE_OK; +} + +DWORD sqlite3Win32Wait(HANDLE hObject); /* os_win.c */ + +/* Get the results of the thread */ +int sqlite3ThreadJoin(SQLiteThread *p, void **ppOut){ + DWORD rc; + BOOL bRc; + + assert( ppOut!=0 ); + if( NEVER(p==0) ) return SQLITE_NOMEM_BKPT; + if( p->xTask==0 ){ + /* assert( p->id==GetCurrentThreadId() ); */ + rc = WAIT_OBJECT_0; + assert( p->tid==0 ); + }else{ + assert( p->id!=0 && p->id!=GetCurrentThreadId() ); + rc = sqlite3Win32Wait((HANDLE)p->tid); + assert( rc!=WAIT_IO_COMPLETION ); + bRc = CloseHandle((HANDLE)p->tid); + assert( bRc ); + } + if( rc==WAIT_OBJECT_0 ) *ppOut = p->pResult; + sqlite3_free(p); + return (rc==WAIT_OBJECT_0) ? SQLITE_OK : SQLITE_ERROR; +} + +#endif /* SQLITE_OS_WIN_THREADS */ +/******************************** End Win32 Threads *************************/ + + +/********************************* Single-Threaded **************************/ +#ifndef SQLITE_THREADS_IMPLEMENTED +/* +** This implementation does not actually create a new thread. It does the +** work of the thread in the main thread, when either the thread is created +** or when it is joined +*/ + +/* A running thread */ +struct SQLiteThread { + void *(*xTask)(void*); /* The routine to run as a thread */ + void *pIn; /* Argument to xTask */ + void *pResult; /* Result of xTask */ +}; + +/* Create a new thread */ +int sqlite3ThreadCreate( + SQLiteThread **ppThread, /* OUT: Write the thread object here */ + void *(*xTask)(void*), /* Routine to run in a separate thread */ + void *pIn /* Argument passed into xTask() */ +){ + SQLiteThread *p; + + assert( ppThread!=0 ); + assert( xTask!=0 ); + *ppThread = 0; + p = sqlite3Malloc(sizeof(*p)); + if( p==0 ) return SQLITE_NOMEM_BKPT; + if( (SQLITE_PTR_TO_INT(p)/17)&1 ){ + p->xTask = xTask; + p->pIn = pIn; + }else{ + p->xTask = 0; + p->pResult = xTask(pIn); + } + *ppThread = p; + return SQLITE_OK; +} + +/* Get the results of the thread */ +int sqlite3ThreadJoin(SQLiteThread *p, void **ppOut){ + + assert( ppOut!=0 ); + if( NEVER(p==0) ) return SQLITE_NOMEM_BKPT; + if( p->xTask ){ + *ppOut = p->xTask(p->pIn); + }else{ + *ppOut = p->pResult; + } + sqlite3_free(p); + +#if defined(SQLITE_TEST) + { + void *pTstAlloc = sqlite3Malloc(10); + if (!pTstAlloc) return SQLITE_NOMEM_BKPT; + sqlite3_free(pTstAlloc); + } +#endif + + return SQLITE_OK; +} + +#endif /* !defined(SQLITE_THREADS_IMPLEMENTED) */ +/****************************** End Single-Threaded *************************/ +#endif /* SQLITE_MAX_WORKER_THREADS>0 */ diff --git a/pool/shard004/C/0097434_edit-data.c b/pool/shard004/C/0097434_edit-data.c new file mode 100644 index 0000000000000000000000000000000000000000..f2cbf5306b6335ed94479a84e747832e2177bdd3 --- /dev/null +++ b/pool/shard004/C/0097434_edit-data.c @@ -0,0 +1,136 @@ +#include +#include "imports.h" +#include "treeview.h" +#include "db-misc.h" +#include "get-builder.h" +#include "message-dialogs.h" +#include "gui-common.h" +#include "gquarks.h" + +typedef struct _edit_data_t { + GtkListStore *list_store; + GtkTreeIter iter; + DatabaseData *db_data; +} EditData; + +static void show_edit_dialog (EditData *edit_data, AppData *app_data, gchar *current_label, gchar *current_issuer); + +static gchar *get_parse_and_set_data_from_entries (EditData *edit_data, GtkWidget *new_lab_entry, GtkWidget *new_iss_entry); + +static void set_data_in_lstore_and_json (EditData *edit_data, const gchar *label, const gchar *issuer); + + +void +edit_selected_row_cb (GSimpleAction *simple __attribute__((unused)), + GVariant *parameter __attribute__((unused)), + gpointer user_data) +{ + EditData *edit_data = g_new0 (EditData, 1); + AppData *app_data = (AppData *)user_data; + edit_data->db_data = app_data->db_data; + + GtkTreeModel *model = gtk_tree_view_get_model (app_data->tree_view); + + edit_data->list_store = GTK_LIST_STORE(model); + + gchar *current_label, *current_issuer; + if (gtk_tree_selection_get_selected (gtk_tree_view_get_selection (app_data->tree_view), &model, &edit_data->iter)) { + gtk_tree_model_get (model, &edit_data->iter, COLUMN_ACC_LABEL, ¤t_label, COLUMN_ACC_ISSUER, ¤t_issuer, -1); + show_edit_dialog (edit_data, app_data, current_label, current_issuer); + g_free (current_label); + g_free (current_issuer); + } + + GError *err = NULL; + update_and_reload_db (app_data, app_data->db_data, TRUE, &err); + if (err != NULL && !g_error_matches (err, missing_file_gquark (), MISSING_FILE_CODE)) { + show_message_dialog (app_data->main_window, err->message, GTK_MESSAGE_ERROR); + } + g_free (edit_data); +} + + +static void +show_edit_dialog (EditData *edit_data, AppData *app_data, gchar *current_label, gchar *current_issuer) +{ + GtkBuilder *builder = get_builder_from_partial_path (UI_PARTIAL_PATH); + GtkWidget *diag = GTK_WIDGET (gtk_builder_get_object (builder, "edit_diag_id")); + + gtk_window_set_transient_for (GTK_WINDOW(diag), GTK_WINDOW(app_data->main_window)); + + GtkWidget *cur_lab_entry = GTK_WIDGET (gtk_builder_get_object (builder, "cur_label_entry")); + GtkWidget *cur_iss_entry = GTK_WIDGET (gtk_builder_get_object (builder, "cur_iss_entry")); + if (cur_lab_entry != NULL) { + gtk_entry_set_text (GTK_ENTRY (cur_lab_entry), current_label); + } + if (cur_iss_entry != NULL) { + gtk_entry_set_text (GTK_ENTRY (cur_iss_entry), current_issuer); + } + + GtkWidget *new_lab_entry = GTK_WIDGET (gtk_builder_get_object (builder, "entry_newlabel_id")); + GtkWidget *new_iss_entry = GTK_WIDGET (gtk_builder_get_object (builder, "entry_newissuer_id")); + + if (current_label != NULL) { + gtk_entry_set_text (GTK_ENTRY(new_lab_entry), current_label); + } + if (current_issuer != NULL) { + gtk_entry_set_text (GTK_ENTRY(new_iss_entry), current_issuer); + } + + if (current_issuer != NULL && g_ascii_strcasecmp (current_issuer, "steam") == 0) { + gtk_widget_set_sensitive (new_iss_entry, FALSE); + } + + gchar *err_msg = NULL; + gint res = gtk_dialog_run (GTK_DIALOG (diag)); + switch (res) { + case GTK_RESPONSE_OK: + err_msg = get_parse_and_set_data_from_entries (edit_data, new_lab_entry, new_iss_entry); + if (err_msg != NULL) { + show_message_dialog (app_data->main_window, err_msg, GTK_MESSAGE_ERROR); + g_free (err_msg); + } + break; + case GTK_RESPONSE_CANCEL: + default: + break; + } + + gtk_widget_destroy (diag); + g_object_unref (builder); +} + + +static gchar * +get_parse_and_set_data_from_entries (EditData *edit_data, GtkWidget *new_lab_entry, GtkWidget *new_iss_entry) +{ + const gchar *new_label = gtk_entry_get_text (GTK_ENTRY (new_lab_entry)); + const gchar *new_issuer = gtk_entry_get_text (GTK_ENTRY (new_iss_entry)); + + if (!g_str_is_ascii (new_label) || !g_str_is_ascii (new_issuer)) { + return g_strdup ("Only ASCII characters are supported at the moment."); + } + + if (g_utf8_strlen (new_label, -1) == 0) { + return g_strdup ("Label must not be empty"); + } + + set_data_in_lstore_and_json (edit_data, new_label, new_issuer); + + return NULL; +} + + +static void +set_data_in_lstore_and_json (EditData *edit_data, const gchar *label, const gchar *issuer) +{ + gtk_list_store_set (edit_data->list_store, &edit_data->iter, + COLUMN_ACC_LABEL, label, + COLUMN_ACC_ISSUER, issuer, + -1); + + guint row_number = get_row_number_from_iter (edit_data->list_store, edit_data->iter); + json_t *obj = json_array_get (edit_data->db_data->json_data, row_number); + json_object_set (obj, "label", json_string (label)); + json_object_set (obj, "issuer", json_string (issuer)); +} diff --git a/pool/shard004/C/0097444_http-hello.c b/pool/shard004/C/0097444_http-hello.c new file mode 100644 index 0000000000000000000000000000000000000000..37e3a612958ac23c0bbd544e437dee11e244622c --- /dev/null +++ b/pool/shard004/C/0097444_http-hello.c @@ -0,0 +1,131 @@ +/** +In this a Hello World example using the bundled HTTP / WebSockets extension. + +Compile using: + + NAME=http make + +Or test the `poll` engine's performance by compiling with `poll`: + + FIO_POLL=1 NAME=http make + +Run with: + + ./tmp/http -t 1 + +Benchmark with keep-alive: + + ab -c 200 -t 4 -n 1000000 -k http://127.0.0.1:3000/ + wrk -c200 -d4 -t1 http://localhost:3000/ + +Benchmark with higher load: + + ab -c 4400 -t 4 -n 1000000 -k http://127.0.0.1:3000/ + wrk -c4400 -d4 -t1 http://localhost:3000/ +*/ + +/* include the core library, without any extensions */ +#include + +#include +#include + +/* defined later */ +void initialize_cli(int argc, char const *argv[]); + +/* ***************************************************************************** +HTTP request / response handling +***************************************************************************** */ + +static void on_http_request(http_s *h) { + /* set a response and send it (finnish vs. destroy). */ + http_send_body(h, "Hello World!", 12); +} + +/* ***************************************************************************** +The main function +***************************************************************************** */ + +int main(int argc, char const *argv[]) { + initialize_cli(argc, argv); + /* listen for inncoming connections */ + if (http_listen(fio_cli_get("-p"), fio_cli_get("-b"), + .on_request = on_http_request, + .max_body_size = fio_cli_get_i("-maxbd"), + .public_folder = fio_cli_get("-public"), + .log = fio_cli_get_bool("-log"), + .timeout = fio_cli_get_i("-keep-alive")) == -1) { + /* listen failed ?*/ + perror( + "ERROR: facil.io couldn't initialize HTTP service (already running?)"); + exit(1); + } + fio_start(.threads = fio_cli_get_i("-t"), .workers = fio_cli_get_i("-w")); + return 0; +} + +/* ***************************************************************************** +CLI helpers +***************************************************************************** */ +void initialize_cli(int argc, char const *argv[]) { + /* **** Command line arguments **** */ + fio_cli_start( + argc, argv, 0, 0, NULL, + // Address Binding arguments + FIO_CLI_PRINT_HEADER("Address Binding:"), + FIO_CLI_INT("-port -p port number to listen to. defaults port 3000"), + "-bind -b address to listen to. defaults any available.", + // Concurrency arguments + FIO_CLI_PRINT_HEADER("Concurrency:"), + FIO_CLI_INT("-workers -w number of processes to use."), + FIO_CLI_INT("-threads -t number of threads per process."), + // HTTP Settings arguments + FIO_CLI_PRINT_HEADER("HTTP Settings:"), + "-public -www public folder, for static file service.", + FIO_CLI_INT( + "-keep-alive -k HTTP keep-alive timeout (0..255). default: 10s"), + FIO_CLI_INT( + "-max-body -maxbd HTTP upload limit in Mega Bytes. default: 50Mb"), + FIO_CLI_BOOL("-log -v request verbosity (logging)."), + // WebSocket Settings arguments + FIO_CLI_PRINT_HEADER("WebSocket Settings:"), + FIO_CLI_INT("-ping websocket ping interval (0..255). default: 40s"), + FIO_CLI_INT("-max-msg -maxms incoming websocket message " + "size limit in Kb. default: 250Kb"), + "-redis -r an optional Redis URL server address.", + FIO_CLI_PRINT("\t\ta valid Redis URL would follow the pattern:"), + FIO_CLI_PRINT("\t\t\tredis://user:password@localhost:6379/")); + + /* Test and set any default options */ + if (!fio_cli_get("-p")) { + /* Test environment as well */ + char *tmp = getenv("PORT"); + if (!tmp) + tmp = "3000"; + /* Set default (unlike cmd line arguments, aliases are manually set) */ + fio_cli_set("-p", tmp); + fio_cli_set("-port", tmp); + } + if (!fio_cli_get("-b")) { + char *tmp = getenv("ADDRESS"); + if (tmp) { + fio_cli_set("-b", tmp); + fio_cli_set("-bind", tmp); + } + } + if (!fio_cli_get("-public")) { + char *tmp = getenv("HTTP_PUBLIC_FOLDER"); + if (tmp) { + fio_cli_set("-public", tmp); + fio_cli_set("-www", tmp); + } + } + + if (!fio_cli_get("-public")) { + char *tmp = getenv("REDIS_URL"); + if (tmp) { + fio_cli_set("-redis-url", tmp); + fio_cli_set("-ru", tmp); + } + } +} diff --git a/pool/shard004/C/0097448_futex-wake.c b/pool/shard004/C/0097448_futex-wake.c new file mode 100644 index 0000000000000000000000000000000000000000..684a40209d80cd9d72e7e171b130488879740d9a --- /dev/null +++ b/pool/shard004/C/0097448_futex-wake.c @@ -0,0 +1,244 @@ +/* + * Copyright (C) 2013 Davidlohr Bueso + * + * futex-wake: Block a bunch of threads on a futex and wake'em up, N at a time. + * + * This program is particularly useful to measure the latency of nthread wakeups + * in non-error situations: all waiters are queued and all wake calls wakeup + * one or more tasks, and thus the waitqueue is never empty. + */ + +/* For the CLR_() macros */ +#include + +#include +#include "../util/stat.h" +#include +#include +#include +#include +#include +#include "bench.h" +#include "futex.h" + +#include +#include +#include + +/* all threads will block on the same futex */ +static u_int32_t futex1 = 0; + +/* + * How many wakeups to do at a time. + * Default to 1 in order to make the kernel work more. + */ +static unsigned int nwakes = 1; + +pthread_t *worker; +static bool done = false, silent = false, fshared = false; +static pthread_mutex_t thread_lock; +static pthread_cond_t thread_parent, thread_worker; +static struct stats waketime_stats, wakeup_stats; +static unsigned int ncpus, threads_starting, nthreads = 0; +static int futex_flag = 0; + +static const struct option options[] = +{ + OPT_UINTEGER('t', "threads", &nthreads, "Specify amount of threads"), + OPT_UINTEGER('w', "nwakes", &nwakes, "Specify amount of threads to wake at once"), + OPT_BOOLEAN( 's', "silent", &silent, "Silent mode: do not display data/details"), + OPT_BOOLEAN( 'S', "shared", &fshared, "Use shared futexes instead of private ones"), + OPT_END() +}; + +static const char *const bench_futex_wake_usage[] = +{ + "perf bench futex wake ", + NULL +}; + +static void *workerfn(void *arg __maybe_unused) +{ + pthread_mutex_lock(&thread_lock); + threads_starting--; + + if (!threads_starting) + { + pthread_cond_signal(&thread_parent); + } + + pthread_cond_wait(&thread_worker, &thread_lock); + pthread_mutex_unlock(&thread_lock); + + while (1) + { + if (futex_wait(&futex1, 0, NULL, futex_flag) != EINTR) + { + break; + } + } + + pthread_exit(NULL); + return NULL; +} + +static void print_summary(void) +{ + double waketime_avg = avg_stats(&waketime_stats); + double waketime_stddev = stddev_stats(&waketime_stats); + unsigned int wakeup_avg = avg_stats(&wakeup_stats); + + printf("Wokeup %d of %d threads in %.4f ms (+-%.2f%%)\n", + wakeup_avg, + nthreads, + waketime_avg / USEC_PER_MSEC, + rel_stddev_stats(waketime_stddev, waketime_avg)); +} + +static void block_threads(pthread_t *w, + pthread_attr_t thread_attr) +{ + cpu_set_t cpu; + unsigned int i; + + threads_starting = nthreads; + + /* create and block all threads */ + for (i = 0; i < nthreads; i++) + { + CPU_ZERO(&cpu); + CPU_SET(i % ncpus, &cpu); + + if (pthread_attr_setaffinity_np(&thread_attr, sizeof(cpu_set_t), &cpu)) + { + err(EXIT_FAILURE, "pthread_attr_setaffinity_np"); + } + + if (pthread_create(&w[i], &thread_attr, workerfn, NULL)) + { + err(EXIT_FAILURE, "pthread_create"); + } + } +} + +static void toggle_done(int sig __maybe_unused, + siginfo_t *info __maybe_unused, + void *uc __maybe_unused) +{ + done = true; +} + +int bench_futex_wake(int argc, const char **argv, + const char *prefix __maybe_unused) +{ + int ret = 0; + unsigned int i, j; + struct sigaction act; + pthread_attr_t thread_attr; + + argc = parse_options(argc, argv, options, bench_futex_wake_usage, 0); + + if (argc) + { + usage_with_options(bench_futex_wake_usage, options); + exit(EXIT_FAILURE); + } + + ncpus = sysconf(_SC_NPROCESSORS_ONLN); + + sigfillset(&act.sa_mask); + act.sa_sigaction = toggle_done; + sigaction(SIGINT, &act, NULL); + + if (!nthreads) + { + nthreads = ncpus; + } + + worker = calloc(nthreads, sizeof(*worker)); + + if (!worker) + { + err(EXIT_FAILURE, "calloc"); + } + + if (!fshared) + { + futex_flag = FUTEX_PRIVATE_FLAG; + } + + printf("Run summary [PID %d]: blocking on %d threads (at [%s] futex %p), " + "waking up %d at a time.\n\n", + getpid(), nthreads, fshared ? "shared" : "private", &futex1, nwakes); + + init_stats(&wakeup_stats); + init_stats(&waketime_stats); + pthread_attr_init(&thread_attr); + pthread_mutex_init(&thread_lock, NULL); + pthread_cond_init(&thread_parent, NULL); + pthread_cond_init(&thread_worker, NULL); + + for (j = 0; j < bench_repeat && !done; j++) + { + unsigned int nwoken = 0; + struct timeval start, end, runtime; + + /* create, launch & block all threads */ + block_threads(worker, thread_attr); + + /* make sure all threads are already blocked */ + pthread_mutex_lock(&thread_lock); + + while (threads_starting) + { + pthread_cond_wait(&thread_parent, &thread_lock); + } + + pthread_cond_broadcast(&thread_worker); + pthread_mutex_unlock(&thread_lock); + + usleep(100000); + + /* Ok, all threads are patiently blocked, start waking folks up */ + gettimeofday(&start, NULL); + + while (nwoken != nthreads) + { + nwoken += futex_wake(&futex1, nwakes, futex_flag); + } + + gettimeofday(&end, NULL); + timersub(&end, &start, &runtime); + + update_stats(&wakeup_stats, nwoken); + update_stats(&waketime_stats, runtime.tv_usec); + + if (!silent) + { + printf("[Run %d]: Wokeup %d of %d threads in %.4f ms\n", + j + 1, nwoken, nthreads, runtime.tv_usec / (double)USEC_PER_MSEC); + } + + for (i = 0; i < nthreads; i++) + { + ret = pthread_join(worker[i], NULL); + + if (ret) + { + err(EXIT_FAILURE, "pthread_join"); + } + } + + } + + /* cleanup & report results */ + pthread_cond_destroy(&thread_parent); + pthread_cond_destroy(&thread_worker); + pthread_mutex_destroy(&thread_lock); + pthread_attr_destroy(&thread_attr); + + print_summary(); + + free(worker); + return ret; +} diff --git a/pool/shard004/C/0097450_SunEventsCalculate.c b/pool/shard004/C/0097450_SunEventsCalculate.c new file mode 100644 index 0000000000000000000000000000000000000000..593f1404167004e116b1f5764dc5f3c57a2c4348 --- /dev/null +++ b/pool/shard004/C/0097450_SunEventsCalculate.c @@ -0,0 +1,127 @@ +#include +#include +#include + +#include "../Platform/Event.h" +#include "../Platform/Nvm.h" +#include "../Platform/Clock.h" +#include "../Location.h" + +#include "SunEvents.h" + +#define MINUTES_PER_DEGREE_LONGITUDE 4 + +static void calculateSunEvent(void); +static void readLookupEntryInto(struct SunEventsLookupEntry *entry, uint8_t lookupIndex); + +struct SunEventsCalculationContext sunEventsCalculationContext; +static struct SunEventsLookupEntry lookupEntries[2]; + +void sunEventsCalculate(void) +{ + static struct SunEventsChanged eventArgs; + + sunEventsCalculationContext.working.lookupPtr = (uint16_t) &sunriseLookupTable; + sunEventsCalculationContext.working.destination = &eventArgs.sunrise; + calculateSunEvent(); + + sunEventsCalculationContext.working.lookupPtr = (uint16_t) &sunsetLookupTable; + sunEventsCalculationContext.working.destination = &eventArgs.sunset; + calculateSunEvent(); + + eventPublish(SUN_EVENTS_CHANGED, &eventArgs); +} + +static void calculateSunEvent(void) +{ + // TODO: REFACTOR THIS WHEN IT'S ALL KNOWN TO BE WORKING + div_t lookupIndex = div( + (int) sunEventsCalculationContext.inputs.dayOfYear, + LOOKUP_STEP); + + uint8_t lookupIndexUint8 = (uint8_t) lookupIndex.quot; + readLookupEntryInto(&lookupEntries[0], lookupIndexUint8); + if (++lookupIndexUint8 >= LOOKUP_LENGTH) + lookupIndexUint8 = 0; + + readLookupEntryInto(&lookupEntries[1], lookupIndexUint8); + + int dayDelta = + lookupIndex.rem * (int) + (lookupEntries[1].minuteOfDay - lookupEntries[0].minuteOfDay); + + div_t interpolatedMinuteOfDay = div(dayDelta, LOOKUP_STEP); + if (interpolatedMinuteOfDay.rem >= LOOKUP_STEP / 2) + interpolatedMinuteOfDay.quot++; + + interpolatedMinuteOfDay.quot += lookupEntries[0].minuteOfDay; + + div_t latitudeAdjustmentMinutes; + if (sunEventsCalculationContext.inputs.latitudeOffset >= 0) + { + int offsetMinutes = + lookupEntries[0].offsetMinutesNorth + + (lookupEntries[1].offsetMinutesNorth - lookupEntries[0].offsetMinutesNorth) / + LOOKUP_STEP; + + int interpolatedMinutes = + offsetMinutes * sunEventsCalculationContext.inputs.latitudeOffset; + + latitudeAdjustmentMinutes = div( + interpolatedMinutes, + LOOKUP_LATITUDE_NORTH - LOOKUP_LATITUDE); + } + else + { + int offsetMinutes = + lookupEntries[0].offsetMinutesSouth + + (lookupEntries[1].offsetMinutesSouth - lookupEntries[0].offsetMinutesSouth) / + LOOKUP_STEP; + + int interpolatedMinutes = + offsetMinutes * -sunEventsCalculationContext.inputs.latitudeOffset; + + latitudeAdjustmentMinutes = div( + interpolatedMinutes, + LOOKUP_LATITUDE - LOOKUP_LATITUDE_SOUTH); + } + + latitudeAdjustmentMinutes.quot += + latitudeAdjustmentMinutes.rem >= LONGLAT_HALF_DEGREE + ? 1 + : latitudeAdjustmentMinutes.rem <= -LONGLAT_HALF_DEGREE + ? -1 + : 0; + + int longitudeDelta = + sunEventsCalculationContext.inputs.longitudeOffset * + -MINUTES_PER_DEGREE_LONGITUDE; + + div_t longitudeAdjustmentMinutes = div(longitudeDelta, LONGLAT_ONE_DEGREE); + longitudeAdjustmentMinutes.quot += + longitudeAdjustmentMinutes.rem >= LONGLAT_HALF_DEGREE + ? 1 + : longitudeAdjustmentMinutes.rem <= -LONGLAT_HALF_DEGREE + ? -1 + : 0; + + int minuteOfDay = + interpolatedMinuteOfDay.quot + + latitudeAdjustmentMinutes.quot + + longitudeAdjustmentMinutes.quot; + + div_t hours = div(minuteOfDay, 60); + sunEventsCalculationContext.working.destination->hour = (uint8_t) hours.quot; + sunEventsCalculationContext.working.destination->minute = (uint8_t) hours.rem; +} + +static void readLookupEntryInto(struct SunEventsLookupEntry *entry, uint8_t lookupIndex) +{ + uint16_t lookupPtr = (sunEventsCalculationContext.working.lookupPtr + (((uint16_t) lookupIndex) << 1)) & 0x7fff; + uint16_t word0 = nvmWordAt(lookupPtr); + uint16_t word1 = nvmWordAt(lookupPtr + 1); + + entry->minuteOfDay = (uint16_t) (((word0 >> 2) & 0b11111000000) | ((word1 >> 8) & 0b111111)); + entry->offsetMinutesNorth = (int8_t) (word0 & 0xff); + entry->offsetMinutesSouth = (int8_t) (word1 & 0xff); +} diff --git a/pool/shard004/C/0097451_blockheap.c b/pool/shard004/C/0097451_blockheap.c new file mode 100644 index 0000000000000000000000000000000000000000..0a38e75fb94a643b6541a0ae26ef9094bad896f5 --- /dev/null +++ b/pool/shard004/C/0097451_blockheap.c @@ -0,0 +1,129 @@ +/* +** $Id: blockheap.c 7339 2007-08-16 03:47:29Z xgwang $ +** +** blockheap.c: The heap of block data. +** +** Copyright (C) 2003 ~ 2007 Feynman Software. +** Copyright (C) 1999 ~ 2002 Wei Yongming. +** +** All rights reserved by Feynman Software. +** +** Current maintainer: Wei Yongming. +** +** Create date: 2001/01/10 +*/ + +#include +#include +#include +#include + +#include "common.h" +#include "minigui.h" +#include "gdi.h" +#include "blockheap.h" + +void InitBlockDataHeap (PBLOCKHEAP heap, size_t bd_size, size_t heap_size) +{ +#ifndef _LITE_VERSION + pthread_mutex_init (&heap->lock, NULL); +#endif + + heap->heap = NULL; + heap->bd_size = bd_size + sizeof (DWORD); + heap->heap_size = heap_size; +} + +void* BlockDataAlloc (PBLOCKHEAP heap) +{ + int i; + char* block_data = NULL; + +#ifndef _LITE_VERSION + pthread_mutex_lock (&heap->lock); +#endif + + if (heap->heap == NULL) { + if (!(heap->heap = calloc (heap->heap_size, heap->bd_size))) + goto ret; + heap->free = 0; + } + + block_data = (char*) heap->heap + heap->bd_size*heap->free; + for (i = heap->free; i < heap->heap_size; i++) { + + if (*((DWORD*)block_data) == BDS_FREE) { + + heap->free = i + 1; + *((DWORD*)block_data) = BDS_USED; + +#if 0 + fprintf (stderr, "heap: %p, Allocated: %d, free: %d.\n", heap, i, heap->free); + fprintf (stderr, "Heap: (bd_size: %d, heap_size: %d, heap: %p).\n", + heap->bd_size, heap->heap_size, heap->heap); +#endif + goto ret; + } + + block_data += heap->bd_size; + } + + if (!(block_data = calloc (1, heap->bd_size))) + goto ret; + + *((DWORD*)block_data) = BDS_SPECIAL; + +ret: + +#ifndef _LITE_VERSION + pthread_mutex_unlock (&heap->lock); +#endif + + if (block_data) + return block_data + sizeof (DWORD); + return NULL; +} + +void BlockDataFree (PBLOCKHEAP heap, void* data) +{ + int i; + char* block_data; + +#ifndef _LITE_VERSION + pthread_mutex_lock (&heap->lock); +#endif + + block_data = (char*) data - sizeof (DWORD); + if (*((DWORD*)block_data) == BDS_SPECIAL) + free (block_data); + else if (*((DWORD*)block_data) == BDS_USED) { + *((DWORD*)block_data) = BDS_FREE; + + i = (block_data - (char*)heap->heap)/heap->bd_size; + if (heap->free > i) + heap->free = i; + +#if 0 + fprintf (stderr, "Heap: %p: Freed: %d, free: %d.\n", heap, i, heap->free); + fprintf (stderr, "Heap: (bd_size: %d, heap_size: %d, heap: %p).\n", + heap->bd_size, heap->heap_size, heap->heap); +#endif + } + +#ifndef _LITE_VERSION + pthread_mutex_unlock (&heap->lock); +#endif +} + +void DestroyBlockDataHeap (PBLOCKHEAP heap) +{ +#if 0 + fprintf (stderr, "Heap: (bd_size: %d, heap_size: %d, heap: %p).\n", + heap->bd_size, heap->heap_size, heap->heap); +#endif +#ifndef _LITE_VERSION + pthread_mutex_destroy (&heap->lock); +#endif + free (heap->heap); +} + diff --git a/pool/shard004/C/0097466_wpsfix.c b/pool/shard004/C/0097466_wpsfix.c new file mode 100644 index 0000000000000000000000000000000000000000..2ca01f548248a404629a30583f35af976096bb79 --- /dev/null +++ b/pool/shard004/C/0097466_wpsfix.c @@ -0,0 +1,96 @@ +/* + * 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 +#ifdef RTCONFIG_RALINK +#include +#include +#include +#include +#include +#include +#include + +static time_t up; +static struct itimerval itv; + +static void alarmtimer(unsigned long sec, unsigned long usec) +{ + itv.it_value.tv_sec = sec; + itv.it_value.tv_usec = usec; + itv.it_interval = itv.it_value; + setitimer(ITIMER_REAL, &itv, NULL); +} + +static void wpsfix_exit(int sig) +{ + alarmtimer(0, 0); + + remove("/var/run/wpsfix.pid"); + exit(0); +} + +static void wpsfix_check(int sig) +{ + int unit; + time_t now = uptime(); + + if (nvram_match("wps_band", "0")) + unit = 0; + else + unit = 1; + + if (((now - up) >= 600) && !wl_WscConfigured(unit)) + { + stop_wsc(); + + nvram_set("wps_sta_pin", "00000000"); + nvram_set("wps_enable", "0"); + nvram_set("wl_wps_mode", "disabled"); + nvram_set("wl0_wps_mode", "disabled"); + nvram_set("wl1_wps_mode", "disabled"); + + wpsfix_exit(sig); + } + else + alarmtimer(60, 0); +} + +int +wpsfix_main(int argc, char *argv[]) +{ + FILE *fp; + + /* write pid */ + if ((fp=fopen("/var/run/wpsfix.pid", "w"))!=NULL) + { + fprintf(fp, "%d", getpid()); + fclose(fp); + } + + up = uptime(); + signal(SIGTERM, wpsfix_exit); + signal(SIGALRM, wpsfix_check); + alarmtimer(60, 0); + + /* listen for replies */ + while (1) + { + pause(); + } +} +#endif diff --git a/pool/shard004/C/0097471_jupiter.c b/pool/shard004/C/0097471_jupiter.c new file mode 100644 index 0000000000000000000000000000000000000000..635f0a16f97340c0ebfcc0bc47fa6dce061eb9d5 --- /dev/null +++ b/pool/shard004/C/0097471_jupiter.c @@ -0,0 +1,115 @@ +/* + Simple demonstration of an Xzibit client: + displays a picture of the planet Jupiter + and plays an excerpt from "Jupiter" from + the Planets Suite. +*/ +#include +#include +#include +#include "xzibit-client.h" + +#define IMAGE_FILENAME "src/jupiter/jupiter.jpg" + +XzibitClient *xzibit = NULL; +int channel; +char *holst = NULL; +gsize holst_size = 0; +gsize holst_cursor = 44; /* size of .wav header */ + +static gboolean +play_holst (gpointer data) +{ + const int second = 44100; /* Hz (shd really read this out of the file) */ + + int length; + gboolean result; + + if (holst_cursor + second < holst_size) + { + length = second; + result = TRUE; + } + else + { + length = holst_size - holst_cursor; + result = FALSE; + } + + xzibit_client_send_audio (xzibit, channel, + holst+holst_cursor, + length); + + holst_cursor += length; + g_print ("Cursor now at %d / %d\n", holst_cursor, holst_size); + + return result; +} + +static gboolean +orbit_mouse (gpointer data) +{ + GdkPixbuf *planet = (GdkPixbuf*) data; + int screensize = + gdk_pixbuf_get_width (planet); /* assume it's square */ + const int half = screensize / 2; + static gdouble mouse_position = 0.0; + int x = sin(mouse_position)*half+half; + int y = cos(mouse_position)*half+half; + +#if 0 + if (mouse_position > 5) + xzibit_client_hide_pointer (xzibit, + channel); + else +#endif + xzibit_client_move_pointer (xzibit, + channel, + x, + y); + + /* and now move the mouse around */ + + mouse_position += M_PI/10; + + if (mouse_position > 2*M_PI) + mouse_position = 0.0; +} + +void +set_up_jupiter(int socket) +{ + GdkPixbuf *planet, *planet_icon; + + xzibit = xzibit_client_new_from_fd (socket); + + planet = gdk_pixbuf_new_from_file (IMAGE_FILENAME, + NULL); + + if (!planet) + { + g_error ("Image %s not found", + IMAGE_FILENAME); + } + + planet_icon = gdk_pixbuf_new_from_file ("src/jupiter/jupiter.png", + NULL); + +#if 0 + g_file_get_contents ("jupiter.wav", + &holst, + &holst_size, + NULL); +#endif + channel = xzibit_client_open_channel (xzibit); + + xzibit_client_send_video (xzibit, channel, planet); + xzibit_client_set_title (xzibit, channel, "Jupiter"); + xzibit_client_set_icon (xzibit, channel, planet_icon); + xzibit_client_send_avatar (xzibit, planet_icon); + + g_timeout_add (100, + orbit_mouse, + planet); + +} diff --git a/pool/shard004/C/0097478_zmqbench_server.c b/pool/shard004/C/0097478_zmqbench_server.c new file mode 100644 index 0000000000000000000000000000000000000000..f54cac142515a915e6a1b9b181d23531699aa9a4 --- /dev/null +++ b/pool/shard004/C/0097478_zmqbench_server.c @@ -0,0 +1,154 @@ +#include +#include +#include +#include +#include +#include + +#include + +#include "../../../algorithm/misc/data_rate_unit.h" +#include "../../high_timer.h" + + +#define MAX_MSG_LEN (1024 * 128) +#define READY_MSG ("Pink Floyd: Time") + + +#define FATAL_ERROR(func_name) \ + do \ + { \ + fprintf(stderr, "%s(%d): %s failed(%d): %s.\n", __FILE__, __LINE__, (func_name), errno, strerror(errno)); \ + exit(EXIT_FAILURE); \ + } while (0) + + +void stack_free(void *data, void *hint) +{ + (void *)data; + (void *)hint; +} + + +void the_starting_gun(void *rep) +{ + zmq_msg_t msg; + int result; + + if (zmq_msg_init_size(&msg, strlen(READY_MSG) + 1) != 0) + FATAL_ERROR("zmq_msg_init_size"); + result = zmq_msg_recv(&msg, rep, 0); + if (result == -1) + FATAL_ERROR("zmq_msg_recv"); + assert(result == strlen(READY_MSG) + 1); + assert(strcmp(zmq_msg_data(&msg), READY_MSG) == 0); + zmq_msg_close(&msg); + + if (zmq_msg_init_data(&msg, READY_MSG, strlen(READY_MSG) + 1, stack_free, NULL) != 0) + FATAL_ERROR("zmq_msg_init_data"); + if (zmq_msg_send(&msg, rep, 0) == -1) + FATAL_ERROR("zmq_msg_send"); + zmq_msg_close(&msg); + + puts("Hey you! Do not help them to bury the light."); +} + + +int main() +{ + int64_t bytes_sent = 0; + int64_t ellapsed_ms; + long double data_rate_Bps; + high_timer_t timer; + char reply_msg[MAX_MSG_LEN] = ""; + int result; + + zmq_msg_t msg; + + void *ctx = zmq_ctx_new(); + if (ctx == NULL) + { + fprintf(stderr, "zmq_ctx_new failed.\n"); + return EXIT_FAILURE; + } + + void *rep = zmq_socket(ctx, ZMQ_REP); + if (rep == NULL) + { + fprintf(stderr, "zmq_socket failed(%d): %s.\n", errno, strerror(errno)); + zmq_ctx_shutdown(ctx); + return EXIT_FAILURE; + } + + if (zmq_bind(rep, "tcp://*:5678") == -1) + FATAL_ERROR("zmq_bind"); + + the_starting_gun(rep); + + high_timer_start(&timer); + + while (1) + { + zmq_msg_init(&msg); + if (zmq_msg_recv(&msg, rep, 0) == -1) + FATAL_ERROR("zmq_msg_recv"); + + if (zmq_msg_size(&msg) == 1 && *(const char *)zmq_msg_data(&msg) == 'Q') + { + zmq_msg_close(&msg); + puts("Received 'Q' from client."); + + if (zmq_msg_init_size(&msg, 1) != 0) + FATAL_ERROR("zmq_msg_init_size"); + *(char *)zmq_msg_data(&msg) = 'Q'; + if (zmq_msg_send(&msg, rep, 0) == -1) + FATAL_ERROR("zmq_msg_send"); + zmq_msg_close(&msg); + + break; + } + else + { + zmq_msg_close(&msg); + +#if 1 + if (zmq_msg_init_data(&msg, reply_msg, sizeof(reply_msg), stack_free, NULL) == -1) + FATAL_ERROR("zmq_msg_init_data"); +#else + if (zmq_msg_init_size(&msg, MAX_MSG_LEN) == -1) + FATAL_ERROR("zmq_msg_init_size"); +#endif + result = zmq_msg_send(&msg, rep, 0); + if (result == -1) + FATAL_ERROR("zmq_msg_send"); + bytes_sent += result; + zmq_msg_close(&msg); + } + } + + ellapsed_ms = high_timer_ellapsed_ms(&timer); + data_rate_Bps = bytes_sent * 1000.0L / ellapsed_ms; + + printf( + "Total sent: %" PRId64 " bytes | %.2Lf KiB | %.2Lf MiB\n" + "Times ellipsed: %" PRId64 " ms\n" + "Data Rate: %.2Lf %s | %.2Lf %s | %.2Lf %s | %.2Lf %s\n", + bytes_sent, bytes_sent / 1024.0L, bytes_sent / 1024.0L / 1024.0, + ellapsed_ms, + data_rate_Bps, data_rate_unit_name(Bps), + data_rate_convertf(data_rate_Bps, Bps, Gbps), data_rate_unit_name(Gbps), + data_rate_convertf(data_rate_Bps, Bps, KiBps), data_rate_unit_name(KiBps), + data_rate_convertf(data_rate_Bps, Bps, MiBps), data_rate_unit_name(MiBps) + ); + + zmq_close(rep); + + zmq_ctx_destroy(ctx); + + return 0; +} + + +// References: +// https://github.com/nanomsg/nng/issues/560 +// https://github.com/zeromq/cppzmq/issues/47 diff --git a/pool/shard004/C/0097482_doveadm-mail-flags.c b/pool/shard004/C/0097482_doveadm-mail-flags.c new file mode 100644 index 0000000000000000000000000000000000000000..05e0501904205d476cdb9af150b04df89a8a9b77 --- /dev/null +++ b/pool/shard004/C/0097482_doveadm-mail-flags.c @@ -0,0 +1,152 @@ +/* Copyright (c) 2013-2014 Dovecot authors, see the included COPYING file */ + +#include "lib.h" +#include "imap-util.h" +#include "mail-storage.h" +#include "doveadm-mailbox-list-iter.h" +#include "doveadm-mail-iter.h" +#include "doveadm-mail.h" + +#include + +struct flags_cmd_context { + struct doveadm_mail_cmd_context ctx; + enum modify_type modify_type; + enum mail_flags flags; + const char *const *keywords; +}; + +static int +cmd_flags_run_box(struct flags_cmd_context *ctx, + const struct mailbox_info *info) +{ + struct doveadm_mail_iter *iter; + struct mailbox *box; + struct mail *mail; + struct mail_keywords *kw = NULL; + + if (doveadm_mail_iter_init(&ctx->ctx, info, ctx->ctx.search_args, + 0, NULL, &iter) < 0) + return -1; + box = doveadm_mail_iter_get_mailbox(iter); + + if (ctx->keywords != NULL) { + if (mailbox_keywords_create(box, ctx->keywords, &kw) < 0) { + i_error("Invalid keywords: %s", + mailbox_get_last_error(box, NULL)); + (void)doveadm_mail_iter_deinit(&iter); + ctx->ctx.exit_code = DOVEADM_EX_NOTPOSSIBLE; + return -1; + } + } + + while (doveadm_mail_iter_next(iter, &mail)) { + mail_update_flags(mail, ctx->modify_type, ctx->flags); + if (kw != NULL) + mail_update_keywords(mail, ctx->modify_type, kw); + } + if (kw != NULL) + mailbox_keywords_unref(&kw); + return doveadm_mail_iter_deinit(&iter); +} + +static int +cmd_flags_run(struct doveadm_mail_cmd_context *_ctx, struct mail_user *user) +{ + struct flags_cmd_context *ctx = (struct flags_cmd_context *)_ctx; + const enum mailbox_list_iter_flags iter_flags = + MAILBOX_LIST_ITER_NO_AUTO_BOXES | + MAILBOX_LIST_ITER_RETURN_NO_FLAGS; + struct doveadm_mailbox_list_iter *iter; + const struct mailbox_info *info; + int ret = 0; + + iter = doveadm_mailbox_list_iter_init(_ctx, user, _ctx->search_args, + iter_flags); + while ((info = doveadm_mailbox_list_iter_next(iter)) != NULL) T_BEGIN { + if (cmd_flags_run_box(ctx, info) < 0) + ret = -1; + } T_END; + if (doveadm_mailbox_list_iter_deinit(&iter) < 0) + ret = -1; + return ret; +} + +static void cmd_flags_init(struct doveadm_mail_cmd_context *_ctx, + const char *const args[]) +{ + struct flags_cmd_context *ctx = (struct flags_cmd_context *)_ctx; + const char *const *tmp; + enum mail_flags flag; + ARRAY_TYPE(const_string) keywords; + + if (args[0] == NULL || args[1] == NULL) { + switch (ctx->modify_type) { + case MODIFY_ADD: + doveadm_mail_help_name("flags add"); + case MODIFY_REMOVE: + doveadm_mail_help_name("flags remove"); + case MODIFY_REPLACE: + doveadm_mail_help_name("flags replace"); + } + i_unreached(); + } + + p_array_init(&keywords, _ctx->pool, 8); + for (tmp = t_strsplit(args[0], " "); *tmp != NULL; tmp++) { + const char *str = *tmp; + + if (str[0] == '\\') { + flag = imap_parse_system_flag(str); + if (flag == 0) + i_fatal("Invalid system flag: %s", str); + ctx->flags |= flag; + } else { + str = p_strdup(_ctx->pool, str); + array_append(&keywords, &str, 1); + } + } + if (array_count(&keywords) > 0 || ctx->modify_type == MODIFY_REPLACE) { + array_append_zero(&keywords); + ctx->keywords = array_idx(&keywords, 0); + } + + _ctx->search_args = doveadm_mail_build_search_args(args+1); +} + +static struct doveadm_mail_cmd_context * +cmd_flag_alloc(enum modify_type modify_type) +{ + struct flags_cmd_context *ctx; + + ctx = doveadm_mail_cmd_alloc(struct flags_cmd_context); + ctx->modify_type = modify_type; + ctx->ctx.v.init = cmd_flags_init; + ctx->ctx.v.run = cmd_flags_run; + return &ctx->ctx; +} + +static struct doveadm_mail_cmd_context *cmd_flags_add_alloc(void) +{ + return cmd_flag_alloc(MODIFY_ADD); +} + +static struct doveadm_mail_cmd_context *cmd_flags_remove_alloc(void) +{ + return cmd_flag_alloc(MODIFY_REMOVE); +} + +static struct doveadm_mail_cmd_context *cmd_flags_replace_alloc(void) +{ + return cmd_flag_alloc(MODIFY_REPLACE); +} + +struct doveadm_mail_cmd cmd_flags_add = { + cmd_flags_add_alloc, "flags add", " " +}; +struct doveadm_mail_cmd cmd_flags_remove = { + cmd_flags_remove_alloc, "flags remove", " " +}; +struct doveadm_mail_cmd cmd_flags_replace = { + cmd_flags_replace_alloc, "flags replace", " " +}; diff --git a/pool/shard004/C/0097484_rcounter.c b/pool/shard004/C/0097484_rcounter.c new file mode 100644 index 0000000000000000000000000000000000000000..10db08fb7d265e9f13456c3e4b5c86750e0dc0d7 --- /dev/null +++ b/pool/shard004/C/0097484_rcounter.c @@ -0,0 +1,51 @@ +#include "rcounter.h" + +struct rcounter* rcounter_init(struct rcounter *c) +{ + cq_init(&c->rok, 1, ZR_RR_COUNTER_BUFFER); + cq_init(&c->rerr, 1, ZR_RR_COUNTER_BUFFER); + c->last_requested_time = 0; + c->uptime = time(NULL); + + return c; +} + +void rcounter_destory(struct rcounter *c) +{ + cq_flush(&c->rok); + cq_flush(&c->rerr); +} + +void rcounter_tic_ok(struct rcounter *c) +{ + c->ok++; + cq_tic(&c->rok); + c->last_requested_time = time(NULL); +} + +void rcounter_tic_err(struct rcounter *c) +{ + c->err++; + cq_tic(&c->rerr); + c->last_requested_time = time(NULL); +} + +uint64_t rcounter_ok(struct rcounter *c) +{ + return c->ok; +} + +uint64_t rcounter_rok(struct rcounter *c) +{ + return cq_count(&c->rok); +} + +uint64_t rcounter_err(struct rcounter *c) +{ + return c->ok; +} + +uint64_t rcounter_rerr(struct rcounter *c) +{ + return cq_count(&c->rerr); +} diff --git a/pool/shard004/C/0097485_wf.c b/pool/shard004/C/0097485_wf.c new file mode 100644 index 0000000000000000000000000000000000000000..1ef3bda380f94317d7d194c94f6f44835759f7c8 --- /dev/null +++ b/pool/shard004/C/0097485_wf.c @@ -0,0 +1,43 @@ +#include +#include "lookup.h" + +static int isletter(int c) { + if (c >= 'A' && c <= 'Z') + c += 'a' - 'A'; + if (c >= 'a' && c <= 'z') + return c; + return 0; +} + +static int getword(char *buf) { + char *s; + int c; + + while ((c = getchar()) != -1 && isletter(c) == 0) + ; + for (s = buf; (c = isletter(c)) != 0; c = getchar()) + *s++ = c; + *s = 0; + if (s > buf) + return 1; + return 0; +} + +void tprint(struct node *tree) { + if (tree) { + tprint(tree->left); + printf("%d\t%s\n", tree->count, tree->word); + tprint(tree->right); + } +} + +static struct node *words = NULL; + +int main(int argc, char *argv[]) { + char buf[40]; + + while (getword(buf)) + lookup(buf, &words)->count++; + tprint(words); + return 0; +} diff --git a/pool/shard004/C/0097487_hw_gcm.c b/pool/shard004/C/0097487_hw_gcm.c new file mode 100644 index 0000000000000000000000000000000000000000..8d0f49149ab56659961b839861569365ff84f6c8 --- /dev/null +++ b/pool/shard004/C/0097487_hw_gcm.c @@ -0,0 +1,218 @@ +/* + * Copyright (c) 2006-2019, RT-Thread Development Team + * + * SPDX-License-Identifier: Apache-2.0 + * + * Change Logs: + * Date Author Notes + * 2019-05-14 tyx the first version + */ + +#include +#include +#include + +/** + * @brief Creating GCM Context + * + * @param device Hardware crypto device + * @param type Type of symmetric crypto context + * + * @return GCM context + */ +struct rt_hwcrypto_ctx *rt_hwcrypto_gcm_create(struct rt_hwcrypto_device *device, + hwcrypto_type crypt_type) +{ + struct rt_hwcrypto_ctx *ctx; + + ctx = rt_hwcrypto_ctx_create(device, HWCRYPTO_TYPE_GCM, sizeof(struct hwcrypto_gcm)); + if (ctx) + { + ((struct hwcrypto_gcm *)ctx)->crypt_type = crypt_type; + } + return ctx; +} + +/** + * @brief Destroy GCM Context + * + * @param ctx GCM context + */ +void rt_hwcrypto_gcm_destroy(struct rt_hwcrypto_ctx *ctx) +{ + rt_hwcrypto_ctx_destroy(ctx); +} + +/** + * @brief This function starts a GCM encryption or decryption operation + * + * @param ctx GCM context + * @param add The buffer holding the additional data + * @param add_len The length of the additional data + * + * @return RT_EOK on success. + */ +rt_err_t rt_hwcrypto_gcm_start(struct rt_hwcrypto_ctx *ctx, const rt_uint8_t *add, + rt_size_t add_len) +{ + struct hwcrypto_gcm *gcm_ctx = (struct hwcrypto_gcm *)ctx; + + if (gcm_ctx && gcm_ctx->ops->start) + { + return gcm_ctx->ops->start(gcm_ctx, add, add_len); + } + return -RT_EINVAL; +} + +/** + * @brief This function finishes the GCM operation and generates the authentication tag + * + * @param ctx GCM context + * @param tag The buffer for holding the tag + * @param tag_len The length of the tag to generate + * + * @return RT_EOK on success. + */ +rt_err_t rt_hwcrypto_gcm_finish(struct rt_hwcrypto_ctx *ctx, const rt_uint8_t *tag, + rt_size_t tag_len) +{ + struct hwcrypto_gcm *gcm_ctx = (struct hwcrypto_gcm *)ctx; + + if (gcm_ctx && gcm_ctx->ops->finish) + { + return gcm_ctx->ops->finish(gcm_ctx, tag, tag_len); + } + return -RT_EINVAL; +} + +/** + * @brief This function performs a symmetric encryption or decryption operation + * + * @param ctx GCM context + * @param mode Operation mode. HWCRYPTO_MODE_ENCRYPT or HWCRYPTO_MODE_DECRYPT + * @param length The length of the input data in Bytes. This must be a multiple of the block size + * @param in The buffer holding the input data + * @param out The buffer holding the output data + * + * @return RT_EOK on success. + */ +rt_err_t rt_hwcrypto_gcm_crypt(struct rt_hwcrypto_ctx *ctx, hwcrypto_mode mode, + rt_size_t length, const rt_uint8_t *in, rt_uint8_t *out) +{ + return rt_hwcrypto_symmetric_crypt(ctx, mode, length, in, out); +} + +/** + * @brief Set Symmetric Encryption and Decryption Key + * + * @param ctx GCM context + * @param key The crypto key + * @param bitlen The crypto key bit length + * + * @return RT_EOK on success. + */ +rt_err_t rt_hwcrypto_gcm_setkey(struct rt_hwcrypto_ctx *ctx, + const rt_uint8_t *key, rt_uint32_t bitlen) +{ + return rt_hwcrypto_symmetric_setkey(ctx, key, bitlen); +} + +/** + * @brief Get Symmetric Encryption and Decryption Key + * + * @param ctx GCM context + * @param key The crypto key buffer + * @param bitlen The crypto key bit length + * + * @return Key length of copy + */ +rt_err_t rt_hwcrypto_gcm_getkey(struct rt_hwcrypto_ctx *ctx, + rt_uint8_t *key, rt_uint32_t bitlen) +{ + return rt_hwcrypto_symmetric_getkey(ctx, key, bitlen); +} + +/** + * @brief Set Symmetric Encryption and Decryption initialization vector + * + * @param ctx GCM context + * @param iv The crypto initialization vector + * @param len The crypto initialization vector length + * + * @return RT_EOK on success. + */ +rt_err_t rt_hwcrypto_gcm_setiv(struct rt_hwcrypto_ctx *ctx, + const rt_uint8_t *iv, rt_size_t len) +{ + return rt_hwcrypto_symmetric_setiv(ctx, iv, len); +} + +/** + * @brief Get Symmetric Encryption and Decryption initialization vector + * + * @param ctx GCM context + * @param iv The crypto initialization vector buffer + * @param len The crypto initialization vector buffer length + * + * @return IV length of copy + */ +rt_err_t rt_hwcrypto_gcm_getiv(struct rt_hwcrypto_ctx *ctx, + rt_uint8_t *iv, rt_size_t len) +{ + return rt_hwcrypto_symmetric_getiv(ctx, iv, len); +} + +/** + * @brief Set offset in initialization vector + * + * @param ctx GCM context + * @param iv_off The offset in IV + */ +void rt_hwcrypto_gcm_set_ivoff(struct rt_hwcrypto_ctx *ctx, rt_int32_t iv_off) +{ + rt_hwcrypto_symmetric_set_ivoff(ctx, iv_off); +} + +/** + * @brief Get offset in initialization vector + * + * @param ctx GCM context + * @param iv_off It must point to a valid memory + */ +void rt_hwcrypto_gcm_get_ivoff(struct rt_hwcrypto_ctx *ctx, rt_int32_t *iv_off) +{ + rt_hwcrypto_symmetric_get_ivoff(ctx, iv_off); +} + +/** + * @brief This function copy GCM context + * + * @param des The destination GCM context + * @param src The GCM context to be copy + * + * @return RT_EOK on success. + */ +rt_err_t rt_hwcrypto_gcm_cpy(struct rt_hwcrypto_ctx *des, + const struct rt_hwcrypto_ctx *src) +{ + struct hwcrypto_gcm *gcm_des = (struct hwcrypto_gcm *)des; + struct hwcrypto_gcm *gcm_src = (struct hwcrypto_gcm *)src; + + if (des != RT_NULL && src != RT_NULL) + { + gcm_des->crypt_type = gcm_src->crypt_type; + /* symmetric crypto context copy */ + return rt_hwcrypto_symmetric_cpy(des, src); + } + return -RT_EINVAL; +} + +/** + * @brief Reset GCM context + * + * @param ctx GCM context + */ +void rt_hwcrypto_gcm_reset(struct rt_hwcrypto_ctx *ctx) +{ + rt_hwcrypto_symmetric_reset(ctx); +} diff --git a/pool/shard004/C/0097500_p_cid.c b/pool/shard004/C/0097500_p_cid.c new file mode 100644 index 0000000000000000000000000000000000000000..1e77e3654febe2733bcf24883dbee557221000bf --- /dev/null +++ b/pool/shard004/C/0097500_p_cid.c @@ -0,0 +1,198 @@ +/*---------------------------------------------------------------------------* + | PDFlib - A library for generating PDF on the fly | + +---------------------------------------------------------------------------+ + | Copyright (c) 1997-2006 Thomas Merz and PDFlib GmbH. All rights reserved. | + +---------------------------------------------------------------------------+ + | | + | This software is subject to the PDFlib license. It is NOT in the | + | public domain. Extended versions and commercial licenses are | + | available, please check http://www.pdflib.com. | + | | + *---------------------------------------------------------------------------*/ + +/* $Id: p_cid.c 9571 2012-07-14 22:13:59Z andijahja $ + * + * PDFlib CID font handling routines + * + */ + +#include "p_intern.h" +#include "p_font.h" + +#include "ft_cid.h" + + +/* +** Returns CMap slot and for standard CJK fonts: fontandle. +** +** pdc_invalidenc: predefined CMap not found +** pdc_cid or pdc_unicode: predefined CMap found +** +** *o_slot: +** >= 0: standard font found +** < 0: |error code| +*/ +pdc_bool +pdf_handle_cidfont(PDF *p, const char *fontname, const char *encoding, + pdc_encoding enc, pdf_font *font, int *o_slot, + pdc_encoding *newenc) +{ + const char *encapiname = encoding; + fnt_cmap_info cmapinfo; + const fnt_font_metric *fontmetric; + pdc_bool isidentity = pdc_false; + /* pdc_bool isstdfont = pdc_false; */ + pdc_bool iscjkcp = pdc_false; + int charcoll, slot; + + (void) enc; + (void) iscjkcp; + (void) encapiname; + + *o_slot = -1; + *newenc = pdc_invalidenc; + + + /* + * Look whether font is already in the cache. + * If font with same name and encoding is found, + * returns its slot number. + */ + + for (slot = 0; slot < p->fonts_number; slot++) + { + if (p->fonts[slot].ft.enc == pdc_cid && + p->fonts[slot].opt.fontstyle == font->opt.fontstyle && + p->fonts[slot].opt.embedding == font->opt.embedding && + !strcmp(p->fonts[slot].apiname, fontname) && + !strcmp(p->fonts[slot].ft.cmapname, encoding)) + { + *o_slot = slot; + *newenc = pdc_cid; + return pdc_true; + } + } + + /* Check the requested CMap */ + charcoll = fnt_get_predefined_cmap_info(encoding, &cmapinfo); + if (charcoll == (int) cc_none) + return pdc_true; + + pdc_logg_cond(p->pdc, 1, trc_font, + "\tPredefined CMap \"%s\" found\n", encoding); + + /* Check whether this CMap is supported in the desired PDF version */ + if (cmapinfo.compatibility > p->compatibility) + { + pdc_set_errmsg(p->pdc, PDF_E_DOC_PDFVERSION, + encoding, pdc_get_pdfversion(p->pdc, p->compatibility), 0, 0); + return pdc_false; + } + + /* For Unicode capable language wrappers only UCS2/UTF16 CMaps allowed */ + if (cmapinfo.codesize == 0 && p->pdc->unicaplang) + { + pdc_set_errmsg(p->pdc, PDF_E_FONT_NEEDUCS2, 0, 0, 0, 0); + return pdc_false; + } + + /* Check whether the font name is among the known Acrobat CJK fonts */ + charcoll = fnt_get_preinstalled_cidfont(fontname, &fontmetric); + isidentity = cmapinfo.charcoll == (int) cc_identity; + if (isidentity) + cmapinfo.charcoll = abs(charcoll); + + /* known Acrobat CID font */ + if (charcoll != (int) cc_none) + { + pdc_logg_cond(p->pdc, 1, trc_font, + "\tStandard CJK font \"%s\" found\n", fontname); + + /* Selected CMap and known standard font don't match */ + if ((cmapinfo.charcoll != abs(charcoll) || + (charcoll == (int) cc_japanese && cmapinfo.codesize == -2))) + { + pdc_set_errmsg(p->pdc, PDF_E_CJK_UNSUPP_CHARCOLL, + 0, 0, 0, 0); + return pdc_false; + } + /* isstdfont = pdc_true; */ + + + /* Embedding not possible */ + if (font->opt.embedding) + { + pdc_set_errmsg(p->pdc, PDF_E_FONT_EMBEDCMAP, 0, 0, 0, 0); + return pdc_false; + } + } +#ifdef WIN32 + else if (iscjkcp && !p->pdc->ptfrun) + { + return pdc_true; + } +#endif + + + /* embedding check */ + if (!pdf_check_font_embedding(p, font, fontname)) + return pdc_false; + + /* supplement number, number of codes = (maximal) number of CIDs */ + font->supplement = fnt_get_supplement(&cmapinfo, p->compatibility); + if (isidentity) + font->supplement = -1; + font->ft.numcodes = fnt_get_maxcid(cmapinfo.charcoll, font->supplement) + 1; + + { + font->passthrough = pdc_true; + font->codesize = 0; + } + + /* CMap and default settings */ + font->ft.vertical = cmapinfo.vertical; + font->ft.cmapname = pdc_strdup(p->pdc, encoding); + if (font->outcmapname == NULL) + font->outcmapname = pdc_strdup(p->pdc, encoding); + font->ft.enc = pdc_cid; + font->iscidfont = pdc_true; + + /* Fill up the font struct */ + fnt_fill_font_metric(p->pdc, &font->ft, pdc_false, fontmetric); + + /* CID widths not available */ + font->widthsmissing = pdc_true; + + pdc_logg_cond(p->pdc, 1, trc_font, + "\n\t%s CJK font: \"%s\"\n\tPredefined CMap: \"%s\"\n" + "\tOrdering: \"%s\"\n\tSupplement: %d\n", + font->ft.isstdfont ? "Adobe Standard" : "Custom", fontname, encoding, + fnt_get_ordering_cid(font->ft.m.charcoll), font->supplement); + + *newenc = pdc_cid; + + return pdc_true; +} + +#ifdef PDF_CJKFONTWIDTHS_SUPPORTED +void +pdf_put_cidglyph_widths(PDF *p, pdf_font *font) +{ + if (font->opt.monospace) + { + if (font->opt.monospace != FNT_DEFAULT_CIDWIDTH) + pdc_printf(p->out, "/DW %d\n", font->opt.monospace); + } + else + { + const char **widths = fnt_get_cid_widths_array(p->pdc, &font->ft); + int i; + + pdc_puts(p->out, "/W"); + pdc_begin_array(p->out); + for (i = 0; i < FNT_CIDMETRIC_INCR - 1; i++) + pdc_puts(p->out, widths[i]); + pdc_end_array(p->out); + } +} +#endif /* PDF_CJKFONTWIDTHS_SUPPORTED */ diff --git a/pool/shard004/C/0097507_open_test.c b/pool/shard004/C/0097507_open_test.c new file mode 100644 index 0000000000000000000000000000000000000000..060a27a862d6700ee414cf44ca2b6b0048eebfbe --- /dev/null +++ b/pool/shard004/C/0097507_open_test.c @@ -0,0 +1,224 @@ +/* -*- Mode: C; tab-width:2 -*- */ +/* ex: set ts=2 shiftwidth=2 softtabstop=2 cindent: */ + +#include +#include + +#define LED_DEBUG +#include + +#define BASE_NODE_ID 0 + +#define TEST_PID DFLT_APP_ID0 +#define OTHER_PID DFLT_APP_ID1 +/* this is a new message type which specifies our test driver's packet type + * both the python test script, and the message handler will need to handle messages of this type + */ + +#define MSG_TEST_DATA (MOD_MSG_START + 1) + +/* this is the timer specifications */ +#define TEST_APP_TID 0 +#define TEST_APP_INTERVAL 50 + +/* messagees for when MSG_INIT and MSG_FINAL are sent + */ +#define START_DATA 100 +#define FINAL_DATA 200 +#define TEST_FAIL 155 +#define TEST_PASS 255 + +/* if your driver has more than one sensor, or device, which can be polled + * include more states here + */ +enum { + TEST_APP_INIT=0, + TEST_APP_FINAL, +}; + +/* if you wish to store more information, such as a history of previous values + * include the appropriate data structure here + */ +typedef struct { + uint8_t pid; + uint8_t count; + uint8_t state; +} app_state_t; + +/* struct specifying how the data will be sent throug the network and the uart. + * this specifies an id, which wil be unique to each node + * and the other field will hold the data recieved from the sensor + * feel free to add more fields such as a packet counter or other information to assist + * you testing + */ +typedef struct { + uint8_t id; + uint8_t state; + uint8_t data; +} data_msg_t; + +static int8_t generic_test_msg_handler(void *state, Message *msg); + +/* for most tests, this won't need changing, except for possibly the name of the module handler + */ +static const mod_header_t mod_header SOS_MODULE_HEADER = { + .mod_id = TEST_PID, + .state_size = sizeof(app_state_t), + .num_timers = 1, + .num_sub_func = 0, + .num_prov_func = 0, + .platform_type = HW_TYPE, + .processor_type = MCU_TYPE, + .code_id = ehtons(TEST_PID), + .module_handler = generic_test_msg_handler, +}; + +static int8_t send_new_data(uint8_t state, uint8_t data){ + /* out data message that will be sent through the uart or network */ + data_msg_t *data_msg; + + // create a message with a appropriate size + data_msg = (data_msg_t *) sys_malloc ( sizeof(data_msg_t) ); + + if ( data_msg ) { + sys_led(LED_GREEN_TOGGLE); + + // copy all the data you wish to send + data_msg->id = sys_id(); + data_msg->state = state; + data_msg->data = data; + + /* if you are running this test on multiple nodes at the same time you will need this + * but if you are running it on just one node at a time, you only need the call to sys_post_uart + */ + if (sys_id() == 0){ + sys_post_uart ( + TEST_PID, + MSG_TEST_DATA, + sizeof(data_msg_t), + data_msg, + SOS_MSG_RELEASE, + BCAST_ADDRESS); + } else { + sys_post_net ( + TEST_PID, + MSG_TEST_DATA, + sizeof(data_msg_t), + data_msg, + SOS_MSG_RELEASE, + BASE_NODE_ID); + } + } else + sys_led(LED_RED_ON); + + return SOS_OK; +} + +static int8_t generic_test_msg_handler(void *state, Message *msg) +{ + app_state_t *s = (app_state_t *) state; + + switch ( msg->type ) { + + /* do any initialization steps here, + * in general it is good to set all the leds to off so that you can analyze what happens later more accurately + * also be sure to start and enable any timers which your driver might need + */ + case MSG_INIT: + sys_led(LED_GREEN_OFF); + sys_led(LED_YELLOW_OFF); + sys_led(LED_RED_OFF); + + s->state = TEST_APP_INIT; + s->count = 0; + s->pid = msg->did; + + sys_timer_start(TEST_APP_TID, TEST_APP_INTERVAL, SLOW_TIMER_REPEAT); + send_new_data(START_DATA, 0); + break; + + case MSG_ERROR: + s->state = TEST_APP_INIT; + s->count = 0; + s->pid = msg->did; + + sys_timer_start(TEST_APP_TID, TEST_APP_INTERVAL, SLOW_TIMER_REPEAT); + send_new_data(START_DATA, 0); + break; + + case MSG_FINAL: + sys_timer_stop(TEST_APP_TID); + s->state = TEST_APP_FINAL; + send_new_data(FINAL_DATA, 1); + break; + + /* here we handle messages of type MSG_TEST_DATA + * in most cases, only the base station node should be doing this since it is the only one connected to the uart + * if your test does not use multiple nodes, or your messages are sent via another module, this is not needed + */ + case MSG_TEST_DATA: + { + uint8_t *payload; + uint8_t msg_len; + + msg_len = msg->len; + payload = sys_msg_take_data(msg); + + sys_post_uart( + s->pid, + MSG_TEST_DATA, + msg_len, + payload, + SOS_MSG_RELEASE, + BCAST_ADDRESS); + } + break; + + case MSG_TIMER_TIMEOUT: + { + switch(s->state){ + case TEST_APP_INIT: + { + void* shm; + + shm = sys_malloc(1); + + if (sys_shm_open( sys_shm_name(TEST_PID, s->count), shm) != SOS_OK) + send_new_data(TEST_FAIL, s->count); + else + send_new_data(TEST_PASS, s->count); + + sys_shm_close(sys_shm_name(TEST_PID, s->count)); + + sys_free(shm); + s->count++; + } + break; + + case TEST_APP_FINAL: + { + send_new_data(s->state, s->count); + s->state = TEST_APP_INIT; + } + break; + + default: + return -EINVAL; + break; + } + } + break; + + default: + return -EINVAL; + break; + } + return SOS_OK; +} + +#ifndef _MODULE_ +mod_header_ptr generic_test_get_header() { + return sos_get_header_address(mod_header); +} +#endif + diff --git a/pool/shard004/C/0097512_rawudp.c b/pool/shard004/C/0097512_rawudp.c new file mode 100644 index 0000000000000000000000000000000000000000..84796641fd34f9cad5d742630126fe6176c431c2 --- /dev/null +++ b/pool/shard004/C/0097512_rawudp.c @@ -0,0 +1,153 @@ +/* + Raw UDP sockets +*/ +#include //for printf +#include //memset +#include //for socket ofcourse +#include //for exit(0); +#include //For errno - the error number +#include //Provides declarations for udp header +#include //Provides declarations for ip header + +/* + 96 bit (12 bytes) pseudo header needed for udp header checksum calculation +*/ +struct pseudo_header +{ + u_int32_t source_address; + u_int32_t dest_address; + u_int8_t placeholder; + u_int8_t protocol; + u_int16_t udp_length; +}; + +/* + Generic checksum calculation function +*/ +unsigned short csum(unsigned short *ptr,int nbytes) +{ + register long sum; + unsigned short oddbyte; + register short answer; + + sum=0; + while(nbytes>1) { + sum+=*ptr++; + nbytes-=2; + } + if(nbytes==1) { + oddbyte=0; + *((u_char*)&oddbyte)=*(u_char*)ptr; + sum+=oddbyte; + } + + sum = (sum>>16)+(sum & 0xffff); + sum = sum + (sum>>16); + answer=(short)~sum; + + return(answer); +} + +int test_raw_udp (void) +{ + //Create a raw socket of type IPPROTO + int s = socket (AF_INET, SOCK_RAW, IPPROTO_RAW); + + if(s == -1) + { + //socket creation failed, may be because of non-root privileges + perror("Failed to create raw socket"); + exit(1); + } + + //Datagram to represent the packet + char datagram[4096] , source_ip[32] , *data , *pseudogram; + + //zero out the packet buffer + memset (datagram, 0, 4096); + + //IP header + struct iphdr *iph = (struct iphdr *) datagram; + + //UDP header + struct udphdr *udph = (struct udphdr *) (datagram + sizeof (struct ip)); + + struct pseudo_header psh; + + //Data part + data = datagram + sizeof(struct iphdr) + sizeof(struct udphdr); + strcpy(data , "ABCDEFGHIJKLMNOPQRSTUVWXYZ\n"); + + //some address resolution + strcpy(source_ip , "1.1.1.1"); + + //Fill in the IP Header + iph->ihl = 5; + iph->version = 4; + iph->tos = 0; + iph->tot_len = sizeof (struct iphdr) + sizeof (struct udphdr) + strlen(data); + iph->id = htonl (54321); //Id of this packet + iph->frag_off = 0; + iph->ttl = 255; + iph->protocol = IPPROTO_UDP; + iph->check = 0; //Set to 0 before calculating checksum + iph->saddr = inet_addr ( source_ip ); //Spoof the source ip address + iph->daddr = inet_addr ("192.168.90.62"); + + //Ip checksum + iph->check = csum ((unsigned short *) datagram, iph->tot_len); + + //UDP header + udph->source = htons (1111); + udph->dest = htons (2769); + udph->len = htons(8 + strlen(data)); //tcp header size + udph->check = 0; //leave checksum 0 now, filled later by pseudo header + + //Now the UDP checksum using the pseudo header + psh.source_address = inet_addr( source_ip ); + psh.dest_address = iph->daddr; + psh.placeholder = 0; + psh.protocol = IPPROTO_UDP; + + psh.udp_length = htons(sizeof(struct udphdr) + strlen(data) ); + + int psize = sizeof(struct pseudo_header) + sizeof(struct udphdr) + strlen(data); + pseudogram = malloc(psize); + + + //loop if you want to flood :) + int count = 100; + while (count--) + { + udph->check = 0; + struct sockaddr_in sin; + memset(&sin, 0, sizeof(sin)); + memcpy(pseudogram , (char*) &psh , sizeof (struct pseudo_header)); + memcpy(pseudogram + sizeof(struct pseudo_header) , udph , sizeof(struct udphdr) + strlen(data)); + + udph->check = csum( (unsigned short*) pseudogram , psize); + + //Send the packet + if (sendto (s, datagram, iph->tot_len , 0, (struct sockaddr *) &sin, sizeof (sin)) < 0) + { + perror("sendto failed"); + } + //Data send successfully + else + { + printf ("Packet Send. Length : %d \n" , iph->tot_len); + + for (int i = 0; i < strlen(data) - 1; ++i) { + data[i]++; + + data[i] &= ~(1 << 7); + } + } + + sleep(1); + } + + return 0; +} + +//Complete diff --git a/pool/shard004/C/0097513_lapacke_ssygvd_work.c b/pool/shard004/C/0097513_lapacke_ssygvd_work.c new file mode 100644 index 0000000000000000000000000000000000000000..8bfaa466b8e735c03b60b635d1ba9730a5e4b43b --- /dev/null +++ b/pool/shard004/C/0097513_lapacke_ssygvd_work.c @@ -0,0 +1,108 @@ +/***************************************************************************** + 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 ssygvd +* Author: Intel Corporation +* Generated November, 2011 +*****************************************************************************/ + +#include "lapacke_utils.h" + +lapack_int LAPACKE_ssygvd_work( int matrix_order, lapack_int itype, char jobz, + char uplo, lapack_int n, float* a, + lapack_int lda, float* b, lapack_int ldb, + float* w, float* work, lapack_int lwork, + lapack_int* iwork, lapack_int liwork ) +{ + lapack_int info = 0; + if( matrix_order == LAPACK_COL_MAJOR ) { + /* Call LAPACK function and adjust info */ + LAPACK_ssygvd( &itype, &jobz, &uplo, &n, a, &lda, b, &ldb, w, work, + &lwork, iwork, &liwork, &info ); + if( info < 0 ) { + info = info - 1; + } + } else if( matrix_order == LAPACK_ROW_MAJOR ) { + lapack_int lda_t = MAX(1,n); + lapack_int ldb_t = MAX(1,n); + float* a_t = NULL; + float* b_t = NULL; + /* Check leading dimension(s) */ + if( lda < n ) { + info = -7; + LAPACKE_xerbla( "LAPACKE_ssygvd_work", info ); + return info; + } + if( ldb < n ) { + info = -9; + LAPACKE_xerbla( "LAPACKE_ssygvd_work", info ); + return info; + } + /* Query optimal working array(s) size if requested */ + if( liwork == -1 || lwork == -1 ) { + LAPACK_ssygvd( &itype, &jobz, &uplo, &n, a, &lda_t, b, &ldb_t, w, + work, &lwork, iwork, &liwork, &info ); + return (info < 0) ? (info - 1) : info; + } + /* Allocate memory for temporary array(s) */ + a_t = (float*)LAPACKE_malloc( sizeof(float) * lda_t * MAX(1,n) ); + if( a_t == NULL ) { + info = LAPACK_TRANSPOSE_MEMORY_ERROR; + goto exit_level_0; + } + b_t = (float*)LAPACKE_malloc( sizeof(float) * ldb_t * MAX(1,n) ); + if( b_t == NULL ) { + info = LAPACK_TRANSPOSE_MEMORY_ERROR; + goto exit_level_1; + } + /* Transpose input matrices */ + LAPACKE_sge_trans( matrix_order, n, n, a, lda, a_t, lda_t ); + LAPACKE_sge_trans( matrix_order, n, n, b, ldb, b_t, ldb_t ); + /* Call LAPACK function and adjust info */ + LAPACK_ssygvd( &itype, &jobz, &uplo, &n, a_t, &lda_t, b_t, &ldb_t, w, + work, &lwork, iwork, &liwork, &info ); + if( info < 0 ) { + info = info - 1; + } + /* Transpose output matrices */ + LAPACKE_sge_trans( LAPACK_COL_MAJOR, n, n, a_t, lda_t, a, lda ); + LAPACKE_sge_trans( LAPACK_COL_MAJOR, n, n, b_t, ldb_t, b, ldb ); + /* Release memory and exit */ + LAPACKE_free( b_t ); +exit_level_1: + LAPACKE_free( a_t ); +exit_level_0: + if( info == LAPACK_TRANSPOSE_MEMORY_ERROR ) { + LAPACKE_xerbla( "LAPACKE_ssygvd_work", info ); + } + } else { + info = -1; + LAPACKE_xerbla( "LAPACKE_ssygvd_work", info ); + } + return info; +} diff --git a/pool/shard004/C/0097514_stm32f4xx_hal_msp.c b/pool/shard004/C/0097514_stm32f4xx_hal_msp.c new file mode 100644 index 0000000000000000000000000000000000000000..7726f27706abfe5603398229d394f7194ef82d11 --- /dev/null +++ b/pool/shard004/C/0097514_stm32f4xx_hal_msp.c @@ -0,0 +1,132 @@ +/** + ****************************************************************************** + * @file UART/UART_Printf/Src/stm32f4xx_hal_msp.c + * @author MCD Application Team + * @version V1.0.5 + * @date 17-February-2017 + * @brief HAL MSP module. + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2017 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 + * @{ + */ + +/** @defgroup HAL_MSP + * @brief HAL MSP module. + * @{ + */ + +/* Private typedef -----------------------------------------------------------*/ +/* Private define ------------------------------------------------------------*/ +/* Private macro -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private function prototypes -----------------------------------------------*/ +/* Private functions ---------------------------------------------------------*/ + +/** @defgroup HAL_MSP_Private_Functions + * @{ + */ + +/** + * @brief UART MSP Initialization + * This function configures the hardware resources used in this example: + * - Peripheral's clock enable + * - Peripheral's GPIO Configuration + * @param huart: UART handle pointer + * @retval None + */ +void HAL_UART_MspInit(UART_HandleTypeDef *huart) +{ + GPIO_InitTypeDef GPIO_InitStruct; + + /*##-1- Enable peripherals and GPIO Clocks #################################*/ + /* Enable GPIO TX/RX clock */ + USARTx_TX_GPIO_CLK_ENABLE(); + USARTx_RX_GPIO_CLK_ENABLE(); + + /* Enable USARTx clock */ + USARTx_CLK_ENABLE(); + + /*##-2- Configure peripheral GPIO ##########################################*/ + /* UART TX GPIO pin configuration */ + GPIO_InitStruct.Pin = USARTx_TX_PIN; + GPIO_InitStruct.Mode = GPIO_MODE_AF_PP; + GPIO_InitStruct.Pull = GPIO_PULLUP; + GPIO_InitStruct.Speed = GPIO_SPEED_FAST; + GPIO_InitStruct.Alternate = USARTx_TX_AF; + + HAL_GPIO_Init(USARTx_TX_GPIO_PORT, &GPIO_InitStruct); + + /* UART RX GPIO pin configuration */ + GPIO_InitStruct.Pin = USARTx_RX_PIN; + GPIO_InitStruct.Alternate = USARTx_RX_AF; + + HAL_GPIO_Init(USARTx_RX_GPIO_PORT, &GPIO_InitStruct); +} + +/** + * @brief UART MSP De-Initialization + * This function frees the hardware resources used in this example: + * - Disable the Peripheral's clock + * - Revert GPIO and NVIC configuration to their default state + * @param huart: UART handle pointer + * @retval None + */ +void HAL_UART_MspDeInit(UART_HandleTypeDef *huart) +{ + /*##-1- Reset peripherals ##################################################*/ + USARTx_FORCE_RESET(); + USARTx_RELEASE_RESET(); + + /*##-2- Disable peripherals and GPIO Clocks #################################*/ + /* Configure UART Tx as alternate function */ + HAL_GPIO_DeInit(USARTx_TX_GPIO_PORT, USARTx_TX_PIN); + /* Configure UART Rx as alternate function */ + HAL_GPIO_DeInit(USARTx_RX_GPIO_PORT, USARTx_RX_PIN); + +} + +/** + * @} + */ + +/** + * @} + */ + +/** + * @} + */ + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/pool/shard004/C/0097525_os_flock.c b/pool/shard004/C/0097525_os_flock.c new file mode 100644 index 0000000000000000000000000000000000000000..c0f0d2c393940397637b72b424e705f09ff0cecd --- /dev/null +++ b/pool/shard004/C/0097525_os_flock.c @@ -0,0 +1,88 @@ +/*- + * See the file LICENSE for redistribution information. + * + * Copyright (c) 1997,2008 Oracle. All rights reserved. + * + * $Id: os_flock.c,v 1.21 2008/01/08 20:58:46 bostic Exp $ + */ + +#include "db_config.h" + +#include "db_int.h" + +/* + * __os_fdlock -- + * Acquire/release a lock on a byte in a file. + */ +int +__os_fdlock(env, fhp, offset, acquire, nowait) + ENV *env; + DB_FH *fhp; + int acquire, nowait; + off_t offset; +{ +#ifdef DB_WINCE + /* + * This functionality is not supported by WinCE, so just fail. + * + * Should only happen if an app attempts to open an environment + * with the DB_REGISTER flag. + */ + __db_errx(env, "fdlock API not implemented for WinCE, DB_REGISTER " + "environment flag not supported."); + return (EFAULT); +#else + DWORD low, high; + DB_ENV *dbenv; + OVERLAPPED over; + int ret; + + dbenv = env == NULL ? NULL : env->dbenv; + + DB_ASSERT(env, + F_ISSET(fhp, DB_FH_OPENED) && fhp->handle != INVALID_HANDLE_VALUE); + + if (dbenv != NULL && FLD_ISSET(dbenv->verbose, DB_VERB_FILEOPS_ALL)) + __db_msg(env, + "fileops: flock %s %s offset %lu", + fhp->name, acquire ? "acquire": "release", (u_long)offset); + + /* + * Windows file locking interferes with read/write operations, so we + * map the ranges to an area past the end of the file. + */ + DB_ASSERT(env, offset < (u_int64_t)INT64_MAX); + offset = UINT64_MAX - offset; + low = (DWORD)offset; + high = (DWORD)(offset >> 32); + + if (acquire) { + if (nowait) + RETRY_CHK_EINTR_ONLY( + !LockFile(fhp->handle, low, high, 1, 0), ret); + else if (__os_is_winnt()) { + memset(&over, 0, sizeof(over)); + over.Offset = low; + over.OffsetHigh = high; + RETRY_CHK_EINTR_ONLY( + !LockFileEx(fhp->handle, LOCKFILE_EXCLUSIVE_LOCK, + 0, 1, 0, &over), + ret); + } else { + /* Windows 9x/ME doesn't support a blocking call. */ + for (;;) { + RETRY_CHK_EINTR_ONLY( + !LockFile(fhp->handle, low, high, 1, 0), + ret); + if (__os_posix_err(ret) != EAGAIN) + break; + __os_yield(env, 1, 0); + } + } + } else + RETRY_CHK_EINTR_ONLY( + !UnlockFile(fhp->handle, low, high, 1, 0), ret); + + return (__os_posix_err(ret)); +#endif +} diff --git a/pool/shard004/C/0097530_test113.c b/pool/shard004/C/0097530_test113.c new file mode 100644 index 0000000000000000000000000000000000000000..3cf827ecdd9d75da3a21d4909db17e65d9f96555 --- /dev/null +++ b/pool/shard004/C/0097530_test113.c @@ -0,0 +1,53 @@ +#include +#include +#include +#include "tpl.h" + +const char *filename = "/tmp/test113.tpl"; + +#define NUM 10 + +struct st { + int i; + char c[8]; + double f; + uint16_t v[2]; +}; + + +int main() { + struct st s[NUM], t[NUM]; + tpl_node *tn; + int i; + int a=5,d=8, A, D; + char b='6',c='7', B, C; + + memset(s, 0, sizeof(s)); /* clear s */ + memset(t, 0, sizeof(t)); /* clear t */ + + /* fill s with random stuff */ + for(i=0; i < NUM; i++) { + s[i].i = i; s[i].f = 3.14159 * i; s[i].v[0] = NUM*i; s[i].v[1] = NUM+i; + strncpy(s[i].c, "abcdefg",8); + s[i].c[0] += 1; + } + + tn = tpl_map("icS(ic#fv#)#ci", &a, &b, s, 8, 2, NUM, &c, &d); + tpl_pack(tn,0); + tpl_dump(tn,TPL_FILE,filename); + tpl_free(tn); + + tn = tpl_map("icS(ic#fv#)#ci", &A, &B, t, 8, 2, NUM, &C, &D); + tpl_load(tn,TPL_FILE,filename); + tpl_unpack(tn,0); + tpl_free(tn); + + /* see if the result is the same as the s */ + printf("structures %s\n", (!memcmp(t,s,sizeof(d)))? "match" : "mismatch"); + printf("A %s\n", (a==A)? "matches" : "mismatches"); + printf("B %s\n", (b==B)? "matches" : "mismatches"); + printf("C %s\n", (c==C)? "matches" : "mismatches"); + printf("D %s\n", (d==D)? "matches" : "mismatches"); + return 0; +} + diff --git a/pool/shard004/C/0097537_commit-cmd.c b/pool/shard004/C/0097537_commit-cmd.c new file mode 100644 index 0000000000000000000000000000000000000000..3860149651e16017031e47baae2fd1f1f19f3e35 --- /dev/null +++ b/pool/shard004/C/0097537_commit-cmd.c @@ -0,0 +1,162 @@ +/* + * commit-cmd.c -- Check changes into the repository. + * + * ==================================================================== + * Copyright (c) 2000-2007 CollabNet. All rights reserved. + * + * 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://subversion.tigris.org/license-1.html. + * If newer versions of this license are posted there, you may use a + * newer version instead, at your option. + * + * This software consists of voluntary contributions made by many + * individuals. For exact contribution history, see the revision + * history and logs, available at http://subversion.tigris.org/. + * ==================================================================== + */ + +/* ==================================================================== */ + + + +/*** Includes. ***/ + +#include + +#include "svn_error.h" +#include "svn_error_codes.h" +#include "svn_wc.h" +#include "svn_client.h" +#include "svn_path.h" +#include "svn_error.h" +#include "svn_config.h" +#include "cl.h" + +#include "svn_private_config.h" + +/* We shouldn't be including a private header here, but it is + * necessary for fixing issue #3416 */ +#include "private/svn_opt_private.h" + + +/* This implements the `svn_opt_subcommand_t' interface. */ +svn_error_t * +svn_cl__commit(apr_getopt_t *os, + void *baton, + apr_pool_t *pool) +{ + svn_error_t *err; + svn_cl__opt_state_t *opt_state = ((svn_cl__cmd_baton_t *) baton)->opt_state; + svn_client_ctx_t *ctx = ((svn_cl__cmd_baton_t *) baton)->ctx; + apr_array_header_t *targets; + apr_array_header_t *condensed_targets; + const char *base_dir; + svn_config_t *cfg; + svn_boolean_t no_unlock = FALSE; + svn_commit_info_t *commit_info = NULL; + int i; + + SVN_ERR(svn_cl__args_to_target_array_print_reserved(&targets, os, + opt_state->targets, + ctx, pool)); + + /* Check that no targets are URLs */ + for (i = 0; i < targets->nelts; i++) + { + const char *target = APR_ARRAY_IDX(targets, i, const char *); + if (svn_path_is_url(target)) + return svn_error_create(SVN_ERR_WC_BAD_PATH, NULL, + "Must give local path (not URL) as the " + "target of a commit"); + } + + /* Add "." if user passed 0 arguments. */ + svn_opt_push_implicit_dot_target(targets, pool); + + SVN_ERR(svn_opt__eat_peg_revisions(&targets, targets, pool)); + + /* Condense the targets (like commit does)... */ + SVN_ERR(svn_path_condense_targets(&base_dir, + &condensed_targets, + targets, + TRUE, + pool)); + + if ((! condensed_targets) || (! condensed_targets->nelts)) + { + const char *parent_dir, *base_name; + + SVN_ERR(svn_wc_get_actual_target(base_dir, &parent_dir, + &base_name, pool)); + if (*base_name) + base_dir = apr_pstrdup(pool, parent_dir); + } + + if (! opt_state->quiet) + svn_cl__get_notifier(&ctx->notify_func2, &ctx->notify_baton2, FALSE, + FALSE, FALSE, pool); + + if (opt_state->depth == svn_depth_unknown) + opt_state->depth = svn_depth_infinity; + + /* Copies are done server-side, and cheaply, which means they're + * effectively always done with infinite depth. + * This is a potential cause of confusion for users trying to commit + * copied subtrees in part by restricting the commit's depth. + * See issue #3699. */ + if (opt_state->depth < svn_depth_infinity) + SVN_ERR(svn_cmdline_printf(pool, + _("svn: warning: The depth of this commit " + "is '%s', but copied directories will " + "regardless be committed with depth '%s'. " + "You must remove unwanted children of those " + "directories in a separate commit.\n"), + svn_depth_to_word(opt_state->depth), + svn_depth_to_word(svn_depth_infinity))); + + cfg = apr_hash_get(ctx->config, SVN_CONFIG_CATEGORY_CONFIG, + APR_HASH_KEY_STRING); + if (cfg) + SVN_ERR(svn_config_get_bool(cfg, &no_unlock, + SVN_CONFIG_SECTION_MISCELLANY, + SVN_CONFIG_OPTION_NO_UNLOCK, FALSE)); + + /* We're creating a new log message baton because we can use our base_dir + to store the temp file, instead of the current working directory. The + client might not have write access to their working directory, but they + better have write access to the directory they're committing. */ + SVN_ERR(svn_cl__make_log_msg_baton(&(ctx->log_msg_baton3), + opt_state, base_dir, + ctx->config, pool)); + + /* Commit. */ + err = svn_client_commit4(&commit_info, + targets, + opt_state->depth, + no_unlock, + opt_state->keep_changelists, + opt_state->changelists, + opt_state->revprop_table, + ctx, + pool); + if (err) + { + svn_error_t *root_err = svn_error_root_cause(err); + if (root_err->apr_err == SVN_ERR_UNKNOWN_CHANGELIST) + { + /* Strip any errors wrapped around this root cause. Note + that this handling differs from that of any other + commands, because of the way 'commit' internally harvests + its list of committables. */ + root_err = svn_error_dup(root_err); + svn_error_clear(err); + err = root_err; + } + } + SVN_ERR(svn_cl__cleanup_log_msg(ctx->log_msg_baton3, err, pool)); + if (! err && ! opt_state->quiet) + SVN_ERR(svn_cl__print_commit_info(commit_info, pool)); + + return SVN_NO_ERROR; +} diff --git a/pool/shard004/C/0097549_aac_ac3_parser.c b/pool/shard004/C/0097549_aac_ac3_parser.c new file mode 100644 index 0000000000000000000000000000000000000000..8a73e709a7c8ed1ac6231fa986add2a3758b487f --- /dev/null +++ b/pool/shard004/C/0097549_aac_ac3_parser.c @@ -0,0 +1,102 @@ +/* + * Common AAC and AC-3 parser + * Copyright (c) 2003 Fabrice Bellard + * Copyright (c) 2003 Michael Niedermayer + * + * 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 "parser.h" +#include "aac_ac3_parser.h" + +int ff_aac_ac3_parse(AVCodecParserContext *s1, + AVCodecContext *avctx, + const uint8_t **poutbuf, int *poutbuf_size, + const uint8_t *buf, int buf_size) +{ + AACAC3ParseContext *s = s1->priv_data; + ParseContext *pc = &s->pc; + int len, i; + int new_frame_start; + +get_next: + i=END_NOT_FOUND; + if(s->remaining_size <= buf_size){ + if(s->remaining_size && !s->need_next_header){ + i= s->remaining_size; + s->remaining_size = 0; + }else{ //we need a header first + len=0; + for(i=s->remaining_size; istate = (s->state<<8) + buf[i]; + if((len=s->sync(s->state, s, &s->need_next_header, &new_frame_start))) + break; + } + if(len<=0){ + i=END_NOT_FOUND; + }else{ + s->state=0; + i-= s->header_size -1; + s->remaining_size = len; + if(!new_frame_start || pc->index+i<=0){ + s->remaining_size += i; + goto get_next; + } + } + } + } + + if(ff_combine_frame(pc, i, &buf, &buf_size)<0){ + s->remaining_size -= FFMIN(s->remaining_size, buf_size); + *poutbuf = NULL; + *poutbuf_size = 0; + return buf_size; + } + + *poutbuf = buf; + *poutbuf_size = buf_size; + + /* update codec info */ + if(s->codec_id) + avctx->codec_id = s->codec_id; + + /* Due to backwards compatible HE-AAC the sample rate, channel count, + and total number of samples found in an AAC ADTS header are not + reliable. Bit rate is still accurate because the total frame duration in + seconds is still correct (as is the number of bits in the frame). */ + if (avctx->codec_id != CODEC_ID_AAC) { + avctx->sample_rate = s->sample_rate; + + /* allow downmixing to stereo (or mono for AC-3) */ + if(avctx->request_channels > 0 && + avctx->request_channels < s->channels && + (avctx->request_channels <= 2 || + (avctx->request_channels == 1 && + (avctx->codec_id == CODEC_ID_AC3 || + avctx->codec_id == CODEC_ID_EAC3)))) { + avctx->channels = avctx->request_channels; + } else { + avctx->channels = s->channels; + avctx->channel_layout = s->channel_layout; + } + avctx->frame_size = s->samples; + } + + avctx->bit_rate = s->bit_rate; + + return i; +} diff --git a/pool/shard004/C/0097552_error.c b/pool/shard004/C/0097552_error.c new file mode 100644 index 0000000000000000000000000000000000000000..e57ee96d0b3da7bda7cdae50a523d275ef8a9a47 --- /dev/null +++ b/pool/shard004/C/0097552_error.c @@ -0,0 +1,184 @@ + +/* + * Copyright 2009 Red Hat Inc., Durham, North Carolina. + * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + * + * Authors: + * Lukas Kuklinek + */ + +#ifdef HAVE_CONFIG_H +#include +#endif + +#include +#include + +#include "alloc.h" +#include "util.h" +#include "_error.h" +#include "err_queue.h" +#include "debug_priv.h" + +static pthread_key_t __key; +static pthread_once_t __once = PTHREAD_ONCE_INIT; + +static void oscap_errkey_init(void) +{ + (void)pthread_key_create(&__key, NULL); +} + +static struct oscap_err_t *oscap_err_new(oscap_errfamily_t family, const char *desc, + const char *func, uint32_t line, const char *file) +{ + struct oscap_err_t *err; + + err = oscap_talloc(struct oscap_err_t); + err->family = family; + err->desc = oscap_sprintf("%s [%s:%d]", desc, file, line); + err->func = func; + err->line = line; + err->file = file; + + dE("\(%s:%d:%s\()) %s", file, line, func, desc); + + return (err); +} + +static void oscap_err_free(struct oscap_err_t *err) +{ + if (err->desc != NULL) + oscap_free(err->desc); + oscap_free(err); +} + +static inline void _push_err(struct oscap_err_t *err) +{ + struct err_queue *q = pthread_getspecific(__key); + if (q == NULL) { + q = err_queue_new(); + assert(q != NULL); + (void)pthread_setspecific(__key, q); + } + (void)err_queue_push(q, err); +} + +void __oscap_setxmlerr(const char *file, uint32_t line, const char *func, xmlErrorPtr error) +{ + + if (error == NULL) + return; + + struct oscap_err_t *err; + (void)pthread_once(&__once, oscap_errkey_init); + + /* get rid of a newline that was pass by xmlGetLastError() */ + int len = strlen(error->message); + if (len != 0 && error->message[len - 1] == '\n') + error->message[len-1] = 0; + if (error->file != NULL) { + char *msg = oscap_sprintf("%s [%s:%d]", error->message, error->file, error->line); + if (msg != NULL) { + err = oscap_err_new(OSCAP_EFAMILY_XML, msg, func, line, file); + oscap_free(msg); + _push_err(err); + return; + } + } + + err = oscap_err_new(OSCAP_EFAMILY_XML, error->message, func, line, file); + _push_err(err); +} + +void __oscap_seterr(const char *file, uint32_t line, const char *func, oscap_errfamily_t family, ...) +{ + struct oscap_err_t *err; + char *msg; + va_list ap; + const char *fmt; + + (void)pthread_once(&__once, oscap_errkey_init); + + va_start(ap, family); + fmt = va_arg(ap, const char *); + msg = oscap_vsprintf(fmt, ap); + va_end(ap); + + err = oscap_err_new(family, msg, func, line, file); + + oscap_free(msg); + _push_err(err); +} + +void oscap_clearerr(void) +{ + struct err_queue *q; + + (void)pthread_once(&__once, oscap_errkey_init); + + q = pthread_getspecific(__key); + (void)pthread_setspecific(__key, NULL); + err_queue_free(q, (oscap_destruct_func) oscap_err_free); +} + +bool oscap_err(void) +{ + (void)pthread_once(&__once, oscap_errkey_init); + struct err_queue *q = pthread_getspecific(__key); + return (q != NULL && !err_queue_is_empty(q)); +} + +oscap_errfamily_t oscap_err_family(void) +{ + struct err_queue *q; + + (void)pthread_once(&__once, oscap_errkey_init); + q = pthread_getspecific(__key); + + if (q == NULL || err_queue_is_empty(q)) + return 0; + return err_queue_get_last(q)->family; +} + +const char *oscap_err_desc(void) +{ + struct err_queue *q; + + (void)pthread_once(&__once, oscap_errkey_init); + q = pthread_getspecific(__key); + + if (q == NULL || err_queue_is_empty(q)) + return 0; + return (const char *) err_queue_get_last(q)->desc; +} + +char *oscap_err_get_full_error(void) +{ + struct err_queue *q; + char *res = NULL; + + (void)pthread_once(&__once, oscap_errkey_init); + q = pthread_getspecific(__key); + if (q == NULL || err_queue_is_empty(q)) + return NULL; + if (err_queue_to_string(q, &res) != 0) + return NULL; + + (void)pthread_setspecific(__key, NULL); + err_queue_free(q, (oscap_destruct_func) oscap_err_free); + return res; +} diff --git a/pool/shard004/C/0097554_lsmdquery.c b/pool/shard004/C/0097554_lsmdquery.c new file mode 100644 index 0000000000000000000000000000000000000000..84cb9184d92e5e893f8e1524f818c44aefafbaee --- /dev/null +++ b/pool/shard004/C/0097554_lsmdquery.c @@ -0,0 +1,200 @@ +// lsmdquery.c + +#include +#include +#include + +#define PROGNAME "lsmdquery" + +void +exit_usage(void) +{ + fprintf(stderr, "usage: %s -f \n" + " %s -q \n", PROGNAME, PROGNAME); + exit(1); +} + +void +printDictionaryAsXML(CFDictionaryRef dict) +{ + CFDataRef xml = CFPropertyListCreateXMLData(kCFAllocatorDefault, + (CFPropertyListRef)dict); + if (!xml) + return; + + write(STDOUT_FILENO, CFDataGetBytePtr(xml), (size_t)CFDataGetLength(xml)); + CFRelease(xml); +} + +void +notificationCallback(CFNotificationCenterRef center, + void *observer, + CFStringRef name, + const void *object, + CFDictionaryRef userInfo) +{ + CFDictionaryRef attributes; + CFArrayRef attributeNames; + CFIndex idx, count; + MDItemRef itemRef = NULL; + MDQueryRef queryRef = (MDQueryRef)object; + + if (CFStringCompare(name, kMDQueryDidFinishNotification, 0) + == kCFCompareEqualTo) { // gathered results + // disable updates, process results, and reenable updates + MDQueryDisableUpdates(queryRef); + count = MDQueryGetResultCount(queryRef); + if (count > 0) { + for (idx = 0; idx < count; idx++) { + itemRef = (MDItemRef)MDQueryGetResultAtIndex(queryRef, idx); + attributeNames = MDItemCopyAttributeNames(itemRef); + attributes = MDItemCopyAttributes(itemRef, attributeNames); + printDictionaryAsXML(attributes); + CFRelease(attributes); + CFRelease(attributeNames); + } + printf("\n%ld results total\n", count); + } + MDQueryEnableUpdates(queryRef); + } else if (CFStringCompare(name, kMDQueryDidUpdateNotification, 0) + == kCFCompareEqualTo) { // live update + CFShow(name), CFShow(object), CFShow(userInfo); + } + // ignore kMDQueryProgressNotification +} + +CFStringRef +ExtractRawQueryFromSmartFolder(const char *folderpath) +{ + int fd, ret; + struct stat sb; + UInt8 *bufp; + CFMutableDataRef xmlData = NULL; + CFPropertyListRef pList = NULL; + CFStringRef rawQuery = NULL, errorString = NULL; + + if ((fd = open(folderpath, O_RDONLY)) < 0) { + perror("open"); + return NULL; + } + + if ((ret = fstat(fd, &sb)) < 0) { + perror("fstat"); + goto out; + } + + if (sb.st_size <= 0) { + fprintf(stderr, "no data in smart folder (%s)?\n", folderpath); + goto out; + } + + xmlData = CFDataCreateMutable(kCFAllocatorDefault, (CFIndex)sb.st_size); + if (xmlData == NULL) { + fprintf(stderr, "CFDataCreateMutable() failed\n"); + goto out; + } + CFDataIncreaseLength(xmlData, (CFIndex)sb.st_size); + + bufp = CFDataGetMutableBytePtr(xmlData); + if (bufp == NULL) { + fprintf(stderr, "CFDataGetMutableBytePtr() failed\n"); + goto out; + } + ret = read(fd, (void *)bufp, (size_t)sb.st_size); + + pList = CFPropertyListCreateFromXMLData(kCFAllocatorDefault, + xmlData, + kCFPropertyListImmutable, + &errorString); + if (pList == NULL) { + fprintf(stderr, "CFPropertyListCreateFromXMLData() failed (%s)\n", + CFStringGetCStringPtr(errorString, kCFStringEncodingASCII)); + CFRelease(errorString); + goto out; + } + + rawQuery = CFDictionaryGetValue(pList, CFSTR("RawQuery")); + CFRetain(rawQuery); + if (rawQuery == NULL) { + fprintf(stderr, "failed to retrieve query from smart folder\n"); + goto out; + } + +out: + close(fd); + + if (pList) + CFRelease(pList); + if (xmlData) + CFRelease(xmlData); + + return rawQuery; +} + +int +main(int argc, char **argv) +{ + int i; + CFStringRef rawQuery = NULL; + MDQueryRef queryRef; + Boolean result; + CFNotificationCenterRef localCenter; + MDQueryBatchingParams batchingParams; + + while ((i = getopt(argc, argv, "f:q:")) != -1) { + switch (i) { + case 'f': + rawQuery = ExtractRawQueryFromSmartFolder(optarg); + break; + case 'q': + rawQuery = CFStringCreateWithCString(kCFAllocatorDefault, optarg, + CFStringGetSystemEncoding()); + break; + + default: + exit_usage(); + break; + } + } + + if (!rawQuery) + exit_usage(); + + queryRef = MDQueryCreate(kCFAllocatorDefault, rawQuery, NULL, NULL); + if (queryRef == NULL) + goto out; + + if (!(localCenter = CFNotificationCenterGetLocalCenter())) { + fprintf(stderr, "failed to access local notification center\n"); + goto out; + } + + CFNotificationCenterAddObserver( + localCenter, // process-local center + NULL, // observer + notificationCallback, // to process query finish/update notifications + NULL, // observe all notifications + (void *)queryRef, // observe notifications for this object + CFNotificationSuspensionBehaviorDeliverImmediately); + + // maximum number of results that can accumulate and the maximum number + // of milliseconds that can pass before various notifications are sent + batchingParams.first_max_num = 1000; // first progress notification + batchingParams.first_max_ms = 1000; + batchingParams.progress_max_num = 1000; // additional progress notifications + batchingParams.progress_max_ms = 1000; + batchingParams.update_max_num = 1; // update notification + batchingParams.update_max_ms = 1000; + MDQuerySetBatchingParameters(queryRef, batchingParams); + + // go execute the query + if ((result = MDQueryExecute(queryRef, kMDQueryWantsUpdates)) == TRUE) + CFRunLoopRun(); + +out: + CFRelease(rawQuery); + if (queryRef) + CFRelease(queryRef); + + exit(0); +} diff --git a/pool/shard004/C/0097559_joystick.c b/pool/shard004/C/0097559_joystick.c new file mode 100644 index 0000000000000000000000000000000000000000..df5f3d8c723d6aeafe85bd23451cb1563ceb104d --- /dev/null +++ b/pool/shard004/C/0097559_joystick.c @@ -0,0 +1,192 @@ +/** + ****************************************************************************** + * @file BSP/Src/joystick.c + * @author MCD Application Team + * @version V1.3.0 + * @date 17-February-2017 + * @brief This example code shows how to use the joystick feature in the + * stm324xg_eval driver + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2017 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 ------------------------------------------------------------*/ +/* Private macro -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +static JOYState_TypeDef JoyState = JOY_NONE; + +/* Private function prototypes -----------------------------------------------*/ +static void Joystick_SetHint(void); + +/* Private functions ---------------------------------------------------------*/ + +/** + * @brief Joystick demo + * @param None + * @retval None + */ +void Joystick_demo(void) +{ + static uint16_t xPtr = 12; + static uint16_t yPtr = 92; + static uint16_t old_xPtr = 12; + static uint16_t old_yPtr = 92; + uint8_t status = 0; + + Joystick_SetHint(); + + status = BSP_JOY_Init(JOY_MODE_GPIO); + + if (status != IO_OK) + { + BSP_LCD_SetBackColor(LCD_COLOR_WHITE); + BSP_LCD_SetTextColor(LCD_COLOR_RED); + BSP_LCD_DisplayStringAt(0, BSP_LCD_GetYSize()- 95, (uint8_t *)"ERROR", CENTER_MODE); + BSP_LCD_DisplayStringAt(0, BSP_LCD_GetYSize()- 80, (uint8_t *)"Joystick cannot be initialized", CENTER_MODE); + } + + while (1) + { + if (status == IO_OK) + { + /* Get the Joystick State */ + JoyState = BSP_JOY_GetState(); + + switch(JoyState) + { + case JOY_UP: + if(yPtr > 92) + { + yPtr--; + } + break; + case JOY_DOWN: + if(yPtr < (BSP_LCD_GetYSize() - 12 - 11)) + { + yPtr++; + } + break; + case JOY_LEFT: + if(xPtr > 12) + { + xPtr--; + } + break; + case JOY_RIGHT: + if(xPtr < (BSP_LCD_GetXSize() - 8 - 11)) + { + xPtr++; + } + break; + default: + break; + } + + BSP_LCD_SetBackColor(LCD_COLOR_WHITE); + BSP_LCD_SetTextColor(LCD_COLOR_BLUE); + + if(JoyState == JOY_SEL) + { + BSP_LCD_SetTextColor(LCD_COLOR_RED); + BSP_LCD_DisplayChar(xPtr, yPtr, 'X'); + + } + else if(JoyState == JOY_NONE) + { + BSP_LCD_SetTextColor(LCD_COLOR_BLUE); + BSP_LCD_DisplayChar(xPtr, yPtr, 'X'); + } + else + { + BSP_LCD_SetTextColor(LCD_COLOR_WHITE); + BSP_LCD_DisplayChar(old_xPtr, old_yPtr, 'X'); + BSP_LCD_SetTextColor(LCD_COLOR_BLUE); + BSP_LCD_DisplayChar(xPtr, yPtr, 'X'); + + old_xPtr = xPtr; + old_yPtr = yPtr; + } + } + if(CheckForUserInput() > 0) + { + return; + } + HAL_Delay(5); + } +} + +/** + * @brief Display joystick demo hint + * @param None + * @retval None + */ +static void Joystick_SetHint(void) +{ + /* Clear the LCD */ + BSP_LCD_Clear(LCD_COLOR_WHITE); + + /* Set Joystick 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 *)"Joystick", CENTER_MODE); + BSP_LCD_SetFont(&Font12); + BSP_LCD_DisplayStringAt(0, 30, (uint8_t *)"Please use the joystick to", CENTER_MODE); + BSP_LCD_DisplayStringAt(0, 45, (uint8_t *)"move the pointer inside the", CENTER_MODE); + BSP_LCD_DisplayStringAt(0, 60, (uint8_t *)"rectangle", 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); +} + +/** + * @} + */ + +/** + * @} + */ + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/pool/shard004/C/0097566_microcode_intel_lib.c b/pool/shard004/C/0097566_microcode_intel_lib.c new file mode 100644 index 0000000000000000000000000000000000000000..ce69320d017907aa2d8e25c4fe7ecef47c725005 --- /dev/null +++ b/pool/shard004/C/0097566_microcode_intel_lib.c @@ -0,0 +1,174 @@ +/* + * Intel CPU Microcode Update Driver for Linux + * + * Copyright (C) 2012 Fenghua Yu + * H Peter Anvin" + * + * This driver allows to upgrade microcode on Intel processors + * belonging to IA-32 family - PentiumPro, Pentium II, + * Pentium III, Xeon, Pentium 4, etc. + * + * Reference: Section 8.11 of Volume 3a, IA-32 Intel? Architecture + * Software Developer's Manual + * Order Number 253668 or free download from: + * + * http://developer.intel.com/Assets/PDF/manual/253668.pdf + * + * For more information, go to http://www.urbanmyth.org/microcode + * + * 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 + +static inline int +update_match_cpu(unsigned int csig, unsigned int cpf, + unsigned int sig, unsigned int pf) +{ + return (!sigmatch(sig, csig, pf, cpf)) ? 0 : 1; +} + +int +update_match_revision(struct microcode_header_intel *mc_header, int rev) +{ + return (mc_header->rev <= rev) ? 0 : 1; +} + +int microcode_sanity_check(void *mc, int print_err) +{ + unsigned long total_size, data_size, ext_table_size; + struct microcode_header_intel *mc_header = mc; + struct extended_sigtable *ext_header = NULL; + int sum, orig_sum, ext_sigcount = 0, i; + struct extended_signature *ext_sig; + + total_size = get_totalsize(mc_header); + data_size = get_datasize(mc_header); + + if (data_size + MC_HEADER_SIZE > total_size) { + if (print_err) + pr_err("error! Bad data size in microcode data file\n"); + return -EINVAL; + } + + if (mc_header->ldrver != 1 || mc_header->hdrver != 1) { + if (print_err) + pr_err("error! Unknown microcode update format\n"); + return -EINVAL; + } + ext_table_size = total_size - (MC_HEADER_SIZE + data_size); + if (ext_table_size) { + if ((ext_table_size < EXT_HEADER_SIZE) + || ((ext_table_size - EXT_HEADER_SIZE) % EXT_SIGNATURE_SIZE)) { + if (print_err) + pr_err("error! Small exttable size in microcode data file\n"); + return -EINVAL; + } + ext_header = mc + MC_HEADER_SIZE + data_size; + if (ext_table_size != exttable_size(ext_header)) { + if (print_err) + pr_err("error! Bad exttable size in microcode data file\n"); + return -EFAULT; + } + ext_sigcount = ext_header->count; + } + + /* check extended table checksum */ + if (ext_table_size) { + int ext_table_sum = 0; + int *ext_tablep = (int *)ext_header; + + i = ext_table_size / DWSIZE; + while (i--) + ext_table_sum += ext_tablep[i]; + if (ext_table_sum) { + if (print_err) + pr_warn("aborting, bad extended signature table checksum\n"); + return -EINVAL; + } + } + + /* calculate the checksum */ + orig_sum = 0; + i = (MC_HEADER_SIZE + data_size) / DWSIZE; + while (i--) + orig_sum += ((int *)mc)[i]; + if (orig_sum) { + if (print_err) + pr_err("aborting, bad checksum\n"); + return -EINVAL; + } + if (!ext_table_size) + return 0; + /* check extended signature checksum */ + for (i = 0; i < ext_sigcount; i++) { + ext_sig = (void *)ext_header + EXT_HEADER_SIZE + + EXT_SIGNATURE_SIZE * i; + sum = orig_sum + - (mc_header->sig + mc_header->pf + mc_header->cksum) + + (ext_sig->sig + ext_sig->pf + ext_sig->cksum); + if (sum) { + if (print_err) + pr_err("aborting, bad checksum\n"); + return -EINVAL; + } + } + return 0; +} +EXPORT_SYMBOL_GPL(microcode_sanity_check); + +/* + * return 0 - no update found + * return 1 - found update + */ +int get_matching_sig(unsigned int csig, int cpf, void *mc, int rev) +{ + struct microcode_header_intel *mc_header = mc; + struct extended_sigtable *ext_header; + unsigned long total_size = get_totalsize(mc_header); + int ext_sigcount, i; + struct extended_signature *ext_sig; + + if (update_match_cpu(csig, cpf, mc_header->sig, mc_header->pf)) + return 1; + + /* Look for ext. headers: */ + if (total_size <= get_datasize(mc_header) + MC_HEADER_SIZE) + return 0; + + ext_header = mc + get_datasize(mc_header) + MC_HEADER_SIZE; + ext_sigcount = ext_header->count; + ext_sig = (void *)ext_header + EXT_HEADER_SIZE; + + for (i = 0; i < ext_sigcount; i++) { + if (update_match_cpu(csig, cpf, ext_sig->sig, ext_sig->pf)) + return 1; + ext_sig++; + } + return 0; +} + +/* + * return 0 - no update found + * return 1 - found update + */ +int get_matching_microcode(unsigned int csig, int cpf, void *mc, int rev) +{ + struct microcode_header_intel *mc_header = mc; + + if (!update_match_revision(mc_header, rev)) + return 0; + + return get_matching_sig(csig, cpf, mc, rev); +} +EXPORT_SYMBOL_GPL(get_matching_microcode); diff --git a/pool/shard004/C/0097579_charge_level.c b/pool/shard004/C/0097579_charge_level.c new file mode 100644 index 0000000000000000000000000000000000000000..cde7fa98c6441ffbe5ef877a9e3399b6780d67b7 --- /dev/null +++ b/pool/shard004/C/0097579_charge_level.c @@ -0,0 +1,256 @@ +/* + * Author: andip71, 01.12.2013 + * + * 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 + + +/* sysfs interface for charge levels */ + +static ssize_t charge_level_ac_show(struct kobject *kobj, struct kobj_attribute *attr, char *buf) +{ + // print current value + return sprintf(buf, "%d mA", ac_level); +} + + +static ssize_t charge_level_ac_store(struct kobject *kobj, struct kobj_attribute *attr, const char *buf, size_t count) +{ + unsigned int ret = -EINVAL; + int val; + + // read value from input buffer + ret = sscanf(buf, "%d", &val); + + if (ret != 1) + return -EINVAL; + + // check whether value is within the valid ranges and adjust accordingly + if (val > AC_CHARGE_LEVEL_MAX) + val = AC_CHARGE_LEVEL_MAX; + + if (val < AC_CHARGE_LEVEL_MIN) + val = AC_CHARGE_LEVEL_MIN; + + // store value + ac_level = val; + + return count; +} + + +static ssize_t charge_level_usb_show(struct kobject *kobj, struct kobj_attribute *attr, char *buf) +{ + // print current value + return sprintf(buf, "%d mA", usb_level); +} + + +static ssize_t charge_level_usb_store(struct kobject *kobj, struct kobj_attribute *attr, const char *buf, size_t count) +{ + unsigned int ret = -EINVAL; + int val; + + // read value from input buffer + ret = sscanf(buf, "%d", &val); + + if (ret != 1) + return -EINVAL; + + // check whether value is within the valid ranges and adjust accordingly + if (val > USB_CHARGE_LEVEL_MAX) + val = USB_CHARGE_LEVEL_MAX; + + if (val < USB_CHARGE_LEVEL_MIN) + val = USB_CHARGE_LEVEL_MIN; + + // store value + usb_level = val; + + return count; +} + +static ssize_t charge_level_wireless_show(struct kobject *kobj, struct kobj_attribute *attr, char *buf) +{ + // print current value + return sprintf(buf, "%d mA", wireless_level); +} + + +static ssize_t charge_level_wireless_store(struct kobject *kobj, struct kobj_attribute *attr, const char *buf, size_t count) +{ + unsigned int ret = -EINVAL; + int val; + + // read value from input buffer + ret = sscanf(buf, "%d", &val); + + if (ret != 1) + return -EINVAL; + + // check whether value is within the valid ranges and adjust accordingly + if (val > WIRELESS_CHARGE_LEVEL_MAX) + val = WIRELESS_CHARGE_LEVEL_MAX; + + if (val < WIRELESS_CHARGE_LEVEL_MIN) + val = WIRELESS_CHARGE_LEVEL_MIN; + + // store value + wireless_level = val; + + return count; +} + + +static ssize_t ignore_unstable_power_show(struct kobject *kobj, struct kobj_attribute *attr, char *buf) +{ + // print current value + return sprintf(buf, "%d", ignore_unstable_power); +} + + +static ssize_t ignore_unstable_power_store(struct kobject *kobj, struct kobj_attribute *attr, const char *buf, size_t count) +{ + unsigned int ret = -EINVAL; + int val; + + // read value from input buffer + ret = sscanf(buf, "%d", &val); + + if (ret != 1) + return -EINVAL; + + // check whether value is valid + if ((val == 0) || (val == 1)) + ignore_unstable_power = val; + + return count; +} + + +static ssize_t ignore_safety_margin_show(struct kobject *kobj, struct kobj_attribute *attr, char *buf) +{ + // print current value + return sprintf(buf, "%d", ignore_safety_margin); +} + + +static ssize_t ignore_safety_margin_store(struct kobject *kobj, struct kobj_attribute *attr, const char *buf, size_t count) +{ + unsigned int ret = -EINVAL; + int val; + + // read value from input buffer + ret = sscanf(buf, "%d", &val); + + if (ret != 1) + return -EINVAL; + + // check whether value is valid + if ((val == 0) || (val == 1)) + ignore_safety_margin = val; + + return count; +} + +static ssize_t charge_info_show(struct kobject *kobj, struct kobj_attribute *attr, char *buf) +{ + + // print charge info + return sprintf(buf, "%s / %d mA", charge_info_text, charge_info_level); + +} + + +/* Initialize charge level sysfs folder */ + +static struct kobj_attribute charge_level_ac_attribute = +__ATTR(charge_level_ac, 0666, charge_level_ac_show, charge_level_ac_store); + +static struct kobj_attribute charge_level_usb_attribute = +__ATTR(charge_level_usb, 0666, charge_level_usb_show, charge_level_usb_store); + +static struct kobj_attribute charge_level_wireless_attribute = +__ATTR(charge_level_wireless, 0666, charge_level_wireless_show, charge_level_wireless_store); + +static struct kobj_attribute ignore_unstable_power_attribute = +__ATTR(ignore_unstable_power, 0666, ignore_unstable_power_show, ignore_unstable_power_store); + +static struct kobj_attribute ignore_safety_margin_attribute = +__ATTR(ignore_safety_margin, 0666, ignore_safety_margin_show, ignore_safety_margin_store); + +static struct kobj_attribute charge_info_attribute = +__ATTR(charge_info, 0666, charge_info_show, NULL); + +static struct attribute *charge_level_attrs[] = +{ + &charge_level_ac_attribute.attr, + &charge_level_usb_attribute.attr, + &charge_level_wireless_attribute.attr, + &ignore_unstable_power_attribute.attr, + &ignore_safety_margin_attribute.attr, + &charge_info_attribute.attr, + NULL, +}; + +static struct attribute_group charge_level_attr_group = +{ + .attrs = charge_level_attrs, +}; + +static struct kobject *charge_level_kobj; + + +int charge_level_init(void) +{ + int charge_level_retval; + + charge_level_kobj = kobject_create_and_add("charge_levels", kernel_kobj); + + if (!charge_level_kobj) + { + printk("Thoth-Kernel: failed to create kernel object for charge level interface.\n"); + return -ENOMEM; + } + + charge_level_retval = sysfs_create_group(charge_level_kobj, &charge_level_attr_group); + + if (charge_level_retval) + { + kobject_put(charge_level_kobj); + printk("Thoth-Kernel: failed to create fs object for charge level interface.\n"); + return (charge_level_retval); + } + + // print debug info + printk("Thoth-Kernel: charge level interface started.\n"); + + return (charge_level_retval); +} + + +void charge_level_exit(void) +{ + kobject_put(charge_level_kobj); + + // print debug info + printk("Thoth-Kernel: charge level interface stopped.\n"); +} + + +/* define driver entry points */ +module_init(charge_level_init); +module_exit(charge_level_exit); diff --git a/pool/shard004/C/0097580_tve200_drv.c b/pool/shard004/C/0097580_tve200_drv.c new file mode 100644 index 0000000000000000000000000000000000000000..00ba9e5ce1307041e855e1d932265a54422a772a --- /dev/null +++ b/pool/shard004/C/0097580_tve200_drv.c @@ -0,0 +1,284 @@ +// SPDX-License-Identifier: GPL-2.0-only +/* + * Copyright (C) 2017 Linus Walleij + * Parts of this file were based on sources as follows: + * + * Copyright (C) 2006-2008 Intel Corporation + * Copyright (C) 2007 Amos Lee + * Copyright (C) 2007 Dave Airlie + * Copyright (C) 2011 Texas Instruments + * Copyright (C) 2017 Eric Anholt + */ + +/** + * DOC: Faraday TV Encoder TVE200 DRM Driver + * + * The Faraday TV Encoder TVE200 is also known as the Gemini TV Interface + * Controller (TVC) and is found in the Gemini Chipset from Storlink + * Semiconductor (later Storm Semiconductor, later Cortina Systems) + * but also in the Grain Media GM8180 chipset. On the Gemini the module + * is connected to 8 data lines and a single clock line, comprising an + * 8-bit BT.656 interface. + * + * This is a very basic YUV display driver. The datasheet specifies that + * it supports the ITU BT.656 standard. It requires a 27 MHz clock which is + * the hallmark of any TV encoder supporting both PAL and NTSC. + * + * This driver exposes a standard KMS interface for this TV encoder. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "tve200_drm.h" + +#define DRIVER_DESC "DRM module for Faraday TVE200" + +static const struct drm_mode_config_funcs mode_config_funcs = { + .fb_create = drm_gem_fb_create, + .atomic_check = drm_atomic_helper_check, + .atomic_commit = drm_atomic_helper_commit, +}; + +static int tve200_modeset_init(struct drm_device *dev) +{ + struct drm_mode_config *mode_config; + struct tve200_drm_dev_private *priv = dev->dev_private; + struct drm_panel *panel; + struct drm_bridge *bridge; + int ret = 0; + + drm_mode_config_init(dev); + mode_config = &dev->mode_config; + mode_config->funcs = &mode_config_funcs; + mode_config->min_width = 352; + mode_config->max_width = 720; + mode_config->min_height = 240; + mode_config->max_height = 576; + + ret = drm_of_find_panel_or_bridge(dev->dev->of_node, + 0, 0, &panel, &bridge); + if (ret && ret != -ENODEV) + return ret; + if (panel) { + bridge = drm_panel_bridge_add_typed(panel, + DRM_MODE_CONNECTOR_Unknown); + if (IS_ERR(bridge)) { + ret = PTR_ERR(bridge); + goto out_bridge; + } + } else { + /* + * TODO: when we are using a different bridge than a panel + * (such as a dumb VGA connector) we need to devise a different + * method to get the connector out of the bridge. + */ + dev_err(dev->dev, "the bridge is not a panel\n"); + goto out_bridge; + } + + ret = tve200_display_init(dev); + if (ret) { + dev_err(dev->dev, "failed to init display\n"); + goto out_bridge; + } + + ret = drm_simple_display_pipe_attach_bridge(&priv->pipe, + bridge); + if (ret) { + dev_err(dev->dev, "failed to attach bridge\n"); + goto out_bridge; + } + + priv->panel = panel; + priv->connector = drm_panel_bridge_connector(bridge); + priv->bridge = bridge; + + dev_info(dev->dev, "attached to panel %s\n", + dev_name(panel->dev)); + + ret = drm_vblank_init(dev, 1); + if (ret) { + dev_err(dev->dev, "failed to init vblank\n"); + goto out_bridge; + } + + drm_mode_config_reset(dev); + drm_kms_helper_poll_init(dev); + + goto finish; + +out_bridge: + if (panel) + drm_panel_bridge_remove(bridge); + drm_mode_config_cleanup(dev); +finish: + return ret; +} + +DEFINE_DRM_GEM_CMA_FOPS(drm_fops); + +static struct drm_driver tve200_drm_driver = { + .driver_features = DRIVER_MODESET | DRIVER_GEM | DRIVER_ATOMIC, + .ioctls = NULL, + .fops = &drm_fops, + .name = "tve200", + .desc = DRIVER_DESC, + .date = "20170703", + .major = 1, + .minor = 0, + .patchlevel = 0, + .dumb_create = drm_gem_cma_dumb_create, + .gem_free_object_unlocked = drm_gem_cma_free_object, + .gem_vm_ops = &drm_gem_cma_vm_ops, + + .prime_handle_to_fd = drm_gem_prime_handle_to_fd, + .prime_fd_to_handle = drm_gem_prime_fd_to_handle, + .gem_prime_get_sg_table = drm_gem_cma_prime_get_sg_table, + .gem_prime_import_sg_table = drm_gem_cma_prime_import_sg_table, + .gem_prime_vmap = drm_gem_cma_prime_vmap, + .gem_prime_vunmap = drm_gem_cma_prime_vunmap, + .gem_prime_mmap = drm_gem_cma_prime_mmap, +}; + +static int tve200_probe(struct platform_device *pdev) +{ + struct device *dev = &pdev->dev; + struct tve200_drm_dev_private *priv; + struct drm_device *drm; + struct resource *res; + int irq; + int ret; + + priv = devm_kzalloc(dev, sizeof(*priv), GFP_KERNEL); + if (!priv) + return -ENOMEM; + + drm = drm_dev_alloc(&tve200_drm_driver, dev); + if (IS_ERR(drm)) + return PTR_ERR(drm); + platform_set_drvdata(pdev, drm); + priv->drm = drm; + drm->dev_private = priv; + + /* Clock the silicon so we can access the registers */ + priv->pclk = devm_clk_get(dev, "PCLK"); + if (IS_ERR(priv->pclk)) { + dev_err(dev, "unable to get PCLK\n"); + ret = PTR_ERR(priv->pclk); + goto dev_unref; + } + ret = clk_prepare_enable(priv->pclk); + if (ret) { + dev_err(dev, "failed to enable PCLK\n"); + goto dev_unref; + } + + /* This clock is for the pixels (27MHz) */ + priv->clk = devm_clk_get(dev, "TVE"); + if (IS_ERR(priv->clk)) { + dev_err(dev, "unable to get TVE clock\n"); + ret = PTR_ERR(priv->clk); + goto clk_disable; + } + + res = platform_get_resource(pdev, IORESOURCE_MEM, 0); + priv->regs = devm_ioremap_resource(dev, res); + if (IS_ERR(priv->regs)) { + dev_err(dev, "%s failed mmio\n", __func__); + ret = -EINVAL; + goto clk_disable; + } + + irq = platform_get_irq(pdev, 0); + if (!irq) { + ret = -EINVAL; + goto clk_disable; + } + + /* turn off interrupts before requesting the irq */ + writel(0, priv->regs + TVE200_INT_EN); + + ret = devm_request_irq(dev, irq, tve200_irq, 0, "tve200", priv); + if (ret) { + dev_err(dev, "failed to request irq %d\n", ret); + goto clk_disable; + } + + ret = tve200_modeset_init(drm); + if (ret) + goto clk_disable; + + ret = drm_dev_register(drm, 0); + if (ret < 0) + goto clk_disable; + + /* + * Passing in 16 here will make the RGB565 mode the default + * Passing in 32 will use XRGB8888 mode + */ + drm_fbdev_generic_setup(drm, 16); + + return 0; + +clk_disable: + clk_disable_unprepare(priv->pclk); +dev_unref: + drm_dev_put(drm); + return ret; +} + +static int tve200_remove(struct platform_device *pdev) +{ + struct drm_device *drm = platform_get_drvdata(pdev); + struct tve200_drm_dev_private *priv = drm->dev_private; + + drm_dev_unregister(drm); + if (priv->panel) + drm_panel_bridge_remove(priv->bridge); + drm_mode_config_cleanup(drm); + clk_disable_unprepare(priv->pclk); + drm_dev_put(drm); + + return 0; +} + +static const struct of_device_id tve200_of_match[] = { + { + .compatible = "faraday,tve200", + }, + {}, +}; + +static struct platform_driver tve200_driver = { + .driver = { + .name = "tve200", + .of_match_table = of_match_ptr(tve200_of_match), + }, + .probe = tve200_probe, + .remove = tve200_remove, +}; +module_platform_driver(tve200_driver); + +MODULE_DESCRIPTION(DRIVER_DESC); +MODULE_AUTHOR("Linus Walleij "); +MODULE_LICENSE("GPL"); diff --git a/pool/shard004/C/0097582_f16_to_f128.c b/pool/shard004/C/0097582_f16_to_f128.c new file mode 100644 index 0000000000000000000000000000000000000000..ab40fb0e41d3f59ff503bd4f79e9e36a4d6f1548 --- /dev/null +++ b/pool/shard004/C/0097582_f16_to_f128.c @@ -0,0 +1,96 @@ + +/*============================================================================ + +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" + +float128_t f16_to_f128( float16_t a ) +{ + union ui16_f16 uA; + uint_fast16_t uiA; + bool sign; + int_fast8_t exp; + uint_fast16_t frac; + struct commonNaN commonNaN; + struct uint128 uiZ; + struct exp8_sig16 normExpSig; + union ui128_f128 uZ; + + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + uA.f = a; + uiA = uA.ui; + sign = signF16UI( uiA ); + exp = expF16UI( uiA ); + frac = fracF16UI( uiA ); + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + if ( exp == 0x1F ) { + if ( frac ) { + softfloat_f16UIToCommonNaN( uiA, &commonNaN ); + uiZ = softfloat_commonNaNToF128UI( &commonNaN ); + } else { + uiZ.v64 = packToF128UI64( sign, 0x7FFF, 0 ); + uiZ.v0 = 0; + } + goto uiZ; + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + if ( ! exp ) { + if ( ! frac ) { + uiZ.v64 = packToF128UI64( sign, 0, 0 ); + uiZ.v0 = 0; + goto uiZ; + } + normExpSig = softfloat_normSubnormalF16Sig( frac ); + exp = normExpSig.exp - 1; + frac = normExpSig.sig; + } + /*------------------------------------------------------------------------ + *------------------------------------------------------------------------*/ + uiZ.v64 = packToF128UI64( sign, exp + 0x3FF0, (uint_fast64_t) frac<<38 ); + uiZ.v0 = 0; + uiZ: + uZ.ui = uiZ; + return uZ.f; + +} + diff --git a/pool/shard004/C/0097583_test-adt7461.c b/pool/shard004/C/0097583_test-adt7461.c new file mode 100644 index 0000000000000000000000000000000000000000..db410e47f8297f25b4bab4ca75624d0533ce422a --- /dev/null +++ b/pool/shard004/C/0097583_test-adt7461.c @@ -0,0 +1,60 @@ +// +// Тестирование датчика температуры с термостатом ADT7461. +// +#include +#include +#include +#include +#include + +#define SLA 0x98 +#define FREQ 100000 + +ARRAY (task_space, 0x400); + +stm32l1_i2c_t i2c; +stm32l1_gpio_t sda; +stm32l1_gpio_t scl; +adt7461_t adt7461; + +void task (void *arg) +{ + int res; + + // Запускаем сразу в режиме Standby, в этом режиме датчик считывает температуру + // по запросу + res = adt7461_init(&adt7461, to_i2cif(&i2c), SLA, FREQ/1000, 1); + if (res != THERMO_ERR_OK) { + debug_printf("FAILED TO INIT ADT7461!\n"); + for (;;); + } + + for (;;) { + res = thermo_read(adt7461_loc_sensor(&adt7461)); + if (res > 0x7FFFFFF0) + debug_printf("ERROR: %d!\n", res - 0x7FFFFFFF); + else + debug_printf("Local temperature: %d\n", res); + + res = thermo_read(adt7461_ext_sensor(&adt7461)); + if (res > 0x7FFFFFF0) + debug_printf("ERROR: %d!\n", res - 0x7FFFFFFF); + else + debug_printf("External temperature: %d\n", res); + + debug_printf("-------------------------------------------------------\n"); + + mdelay(500); + } +} + +void uos_init (void) +{ + debug_printf("\n\nTesting ADT7461\n"); + + stm32l1_gpio_init(&scl, GPIO_PORT_B, 6, GPIO_FLAGS_ALT_I2C1); + stm32l1_gpio_init(&sda, GPIO_PORT_B, 7, GPIO_FLAGS_ALT_I2C1 | GPIO_FLAGS_OPEN_DRAIN | GPIO_FLAGS_PULL_UP); + stm32l1_i2c_init(&i2c, 1); + + task_create( task, "task", "task", 1, task_space, sizeof(task_space) ); +} diff --git a/pool/shard004/C/0097589_nf_nat_proto_common.c b/pool/shard004/C/0097589_nf_nat_proto_common.c new file mode 100644 index 0000000000000000000000000000000000000000..5d849d835561777f45dc70050509095a08be9cac --- /dev/null +++ b/pool/shard004/C/0097589_nf_nat_proto_common.c @@ -0,0 +1,120 @@ +/* (C) 1999-2001 Paul `Rusty' Russell + * (C) 2002-2006 Netfilter Core Team + * (C) 2008 Patrick McHardy + * + * 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 + +bool nf_nat_l4proto_in_range(const struct nf_conntrack_tuple *tuple, + enum nf_nat_manip_type maniptype, + const union nf_conntrack_man_proto *min, + const union nf_conntrack_man_proto *max) +{ + __be16 port; + + if (maniptype == NF_NAT_MANIP_SRC) + port = tuple->src.u.all; + else + port = tuple->dst.u.all; + + return ntohs(port) >= ntohs(min->all) && + ntohs(port) <= ntohs(max->all); +} +EXPORT_SYMBOL_GPL(nf_nat_l4proto_in_range); + +void nf_nat_l4proto_unique_tuple(const struct nf_nat_l3proto *l3proto, + struct nf_conntrack_tuple *tuple, + const struct nf_nat_range2 *range, + enum nf_nat_manip_type maniptype, + const struct nf_conn *ct, + u16 *rover) +{ + unsigned int range_size, min, max, i; + __be16 *portptr; + u_int16_t off; + + if (maniptype == NF_NAT_MANIP_SRC) + portptr = &tuple->src.u.all; + else + portptr = &tuple->dst.u.all; + + /* If no range specified... */ + if (!(range->flags & NF_NAT_RANGE_PROTO_SPECIFIED)) { + /* If it's dst rewrite, can't change port */ + if (maniptype == NF_NAT_MANIP_DST) + return; + + if (ntohs(*portptr) < 1024) { + /* Loose convention: >> 512 is credential passing */ + if (ntohs(*portptr) < 512) { + min = 1; + range_size = 511 - min + 1; + } else { + min = 600; + range_size = 1023 - min + 1; + } + } else { + min = 1024; + range_size = 65535 - 1024 + 1; + } + } else { + min = ntohs(range->min_proto.all); + max = ntohs(range->max_proto.all); + if (unlikely(max < min)) + swap(max, min); + range_size = max - min + 1; + } + + if (range->flags & NF_NAT_RANGE_PROTO_RANDOM) { + off = l3proto->secure_port(tuple, maniptype == NF_NAT_MANIP_SRC + ? tuple->dst.u.all + : tuple->src.u.all); + } else if (range->flags & NF_NAT_RANGE_PROTO_RANDOM_FULLY) { + off = prandom_u32(); + } else if (range->flags & NF_NAT_RANGE_PROTO_OFFSET) { + off = (ntohs(*portptr) - ntohs(range->base_proto.all)); + } else { + off = *rover; + } + + for (i = 0; ; ++off) { + *portptr = htons(min + off % range_size); + if (++i != range_size && nf_nat_used_tuple(tuple, ct)) + continue; + if (!(range->flags & (NF_NAT_RANGE_PROTO_RANDOM_ALL| + NF_NAT_RANGE_PROTO_OFFSET))) + *rover = off; + return; + } +} +EXPORT_SYMBOL_GPL(nf_nat_l4proto_unique_tuple); + +#if IS_ENABLED(CONFIG_NF_CT_NETLINK) +int nf_nat_l4proto_nlattr_to_range(struct nlattr *tb[], + struct nf_nat_range2 *range) +{ + if (tb[CTA_PROTONAT_PORT_MIN]) { + range->min_proto.all = nla_get_be16(tb[CTA_PROTONAT_PORT_MIN]); + range->max_proto.all = range->min_proto.all; + range->flags |= NF_NAT_RANGE_PROTO_SPECIFIED; + } + if (tb[CTA_PROTONAT_PORT_MAX]) { + range->max_proto.all = nla_get_be16(tb[CTA_PROTONAT_PORT_MAX]); + range->flags |= NF_NAT_RANGE_PROTO_SPECIFIED; + } + return 0; +} +EXPORT_SYMBOL_GPL(nf_nat_l4proto_nlattr_to_range); +#endif diff --git a/pool/shard004/C/0097590_CWE78_OS_Command_Injection__wchar_t_listen_socket_w32_execv_16.c b/pool/shard004/C/0097590_CWE78_OS_Command_Injection__wchar_t_listen_socket_w32_execv_16.c new file mode 100644 index 0000000000000000000000000000000000000000..2ad125baddc281b754b6f9fcae61320bf4563866 --- /dev/null +++ b/pool/shard004/C/0097590_CWE78_OS_Command_Injection__wchar_t_listen_socket_w32_execv_16.c @@ -0,0 +1,213 @@ +/* TEMPLATE GENERATED TESTCASE FILE +Filename: CWE78_OS_Command_Injection__wchar_t_listen_socket_w32_execv_16.c +Label Definition File: CWE78_OS_Command_Injection.strings.label.xml +Template File: sources-sink-16.tmpl.c +*/ +/* + * @description + * CWE: 78 OS Command Injection + * BadSource: listen_socket Read data using a listen socket (server side) + * GoodSource: Fixed string + * Sink: w32_execv + * BadSink : execute command with wexecv + * Flow Variant: 16 Control flow: while(1) + * + * */ + +#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 + +#include +#define EXECV _wexecv + +#ifndef OMITBAD + +void CWE78_OS_Command_Injection__wchar_t_listen_socket_w32_execv_16_bad() +{ + wchar_t * data; + wchar_t dataBuffer[100] = COMMAND_ARG2; + data = dataBuffer; + while(1) + { + { +#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 + } + break; + } + { + wchar_t *args[] = {COMMAND_INT_PATH, COMMAND_ARG1, 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() - use goodsource and badsink by changing the conditions on the while statements */ +static void goodG2B() +{ + wchar_t * data; + wchar_t dataBuffer[100] = COMMAND_ARG2; + data = dataBuffer; + while(1) + { + /* FIX: Append a fixed string to data (not user / external input) */ + wcscat(data, L"*.*"); + break; + } + { + wchar_t *args[] = {COMMAND_INT_PATH, COMMAND_ARG1, 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_listen_socket_w32_execv_16_good() +{ + goodG2B(); +} + +#endif /* OMITGOOD */ + +/* Below is the main(). It is only used when building this testcase on + * its own for testing or for building a binary to use in testing binary + * analysis tools. It is not used when compiling all the testcases as one + * application, which is how source code analysis tools are tested. + */ + +#ifdef INCLUDEMAIN + +int main(int argc, char * argv[]) +{ + /* seed randomness */ + srand( (unsigned)time(NULL) ); +#ifndef OMITGOOD + printLine("Calling good()..."); + CWE78_OS_Command_Injection__wchar_t_listen_socket_w32_execv_16_good(); + printLine("Finished good()"); +#endif /* OMITGOOD */ +#ifndef OMITBAD + printLine("Calling bad()..."); + CWE78_OS_Command_Injection__wchar_t_listen_socket_w32_execv_16_bad(); + printLine("Finished bad()"); +#endif /* OMITBAD */ + return 0; +} + +#endif diff --git a/pool/shard004/C/0097591_mlink2.c b/pool/shard004/C/0097591_mlink2.c new file mode 100644 index 0000000000000000000000000000000000000000..ee76498a7b835eda619a4fcfd5d02b9bbfa92a27 --- /dev/null +++ b/pool/shard004/C/0097591_mlink2.c @@ -0,0 +1,54 @@ +/* + * ================================ + * eli960@qq.com + * https://blog.csdn.net/eli960 + * 2019-11-01 + * ================================ + */ + +#include "zc.h" + +typedef struct TTT TTT; +struct TTT { + TTT *prev_123; + TTT *next_456; + int a; +}; + +int main(int argc, char **argv) +{ + TTT *head_111 = 0; + TTT *tail_222 = 0; + + TTT *n; + + n = (TTT *)malloc(sizeof(TTT)); + n->a = 1; + ZMLINK_APPEND(head_111, tail_222, n, prev_123, next_456); + + n = (TTT *)malloc(sizeof(TTT)); + n->a = 2; + ZMLINK_APPEND(head_111, tail_222, n, prev_123, next_456); + + n = (TTT *)malloc(sizeof(TTT)); + n->a = 8; + ZMLINK_PREPEND(head_111, tail_222, n, prev_123, next_456); + + + n = head_111; + ZMLINK_DETACH(head_111, tail_222, n, prev_123, next_456); + printf("%d\n", n->a); + free(n); + + n = head_111; + ZMLINK_DETACH(head_111, tail_222, n, prev_123, next_456); + printf("%d\n", n->a); + free(n); + + n = tail_222; + ZMLINK_DETACH(head_111, tail_222, n, prev_123, next_456); + printf("%d\n", n->a); + free(n); + + return 0; +} diff --git a/pool/shard004/C/0097594_s_cbrtl.c b/pool/shard004/C/0097594_s_cbrtl.c new file mode 100644 index 0000000000000000000000000000000000000000..298754ea744f592f444fe5a70772062ea0b8a218 --- /dev/null +++ b/pool/shard004/C/0097594_s_cbrtl.c @@ -0,0 +1,121 @@ +/* cbrtl.c + * + * Cube root, long double precision + * + * + * + * SYNOPSIS: + * + * long double x, y, cbrtl(); + * + * y = cbrtl( x ); + * + * + * + * DESCRIPTION: + * + * Returns the cube root of the argument, which may be negative. + * + * Range reduction involves determining the power of 2 of + * the argument. A polynomial of degree 2 applied to the + * mantissa, and multiplication by the cube root of 1, 2, or 4 + * approximates the root to within about 0.1%. Then Newton's + * iteration is used three times to converge to an accurate + * result. + * + * + * + * ACCURACY: + * + * Relative error: + * arithmetic domain # trials peak rms + * IEEE -8,8 100000 1.3e-34 3.9e-35 + * IEEE exp(+-707) 100000 1.3e-34 4.3e-35 + * + */ + +/* +Cephes Math Library Release 2.2: January, 1991 +Copyright 1984, 1991 by Stephen L. Moshier +Adapted for glibc October, 2001. +*/ + +#include "math.h" +#include "math_private.h" + +static const long double CBRT2 = 1.259921049894873164767210607278228350570251L; +static const long double CBRT4 = 1.587401051968199474751705639272308260391493L; +static const long double CBRT2I = 0.7937005259840997373758528196361541301957467L; +static const long double CBRT4I = 0.6299605249474365823836053036391141752851257L; + + +long double +__cbrtl (long double x) +{ + int e, rem, sign; + long double z; + + if (!__finitel (x)) + return x + x; + + if (x == 0) + return (x); + + if (x > 0) + sign = 1; + else + { + sign = -1; + x = -x; + } + + z = x; + /* extract power of 2, leaving mantissa between 0.5 and 1 */ + x = __frexpl (x, &e); + + /* Approximate cube root of number between .5 and 1, + peak relative error = 1.2e-6 */ + x = ((((1.3584464340920900529734e-1L * x + - 6.3986917220457538402318e-1L) * x + + 1.2875551670318751538055e0L) * x + - 1.4897083391357284957891e0L) * x + + 1.3304961236013647092521e0L) * x + 3.7568280825958912391243e-1L; + + /* exponent divided by 3 */ + if (e >= 0) + { + rem = e; + e /= 3; + rem -= 3 * e; + if (rem == 1) + x *= CBRT2; + else if (rem == 2) + x *= CBRT4; + } + else + { /* argument less than 1 */ + e = -e; + rem = e; + e /= 3; + rem -= 3 * e; + if (rem == 1) + x *= CBRT2I; + else if (rem == 2) + x *= CBRT4I; + e = -e; + } + + /* multiply by power of 2 */ + x = __ldexpl (x, e); + + /* Newton iteration */ + x -= (x - (z / (x * x))) * 0.3333333333333333333333333333333333333333L; + x -= (x - (z / (x * x))) * 0.3333333333333333333333333333333333333333L; + x -= (x - (z / (x * x))) * 0.3333333333333333333333333333333333333333L; + + if (sign < 0) + x = -x; + return (x); +} + +weak_alias (__cbrtl, cbrtl) diff --git a/pool/shard004/C/0097599_rpm-smd.c b/pool/shard004/C/0097599_rpm-smd.c new file mode 100644 index 0000000000000000000000000000000000000000..693d369da2a73f3256de6522604236cadfd009be --- /dev/null +++ b/pool/shard004/C/0097599_rpm-smd.c @@ -0,0 +1,185 @@ +/* Copyright (c) 2014, The Linux Foundation. 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 Linux Fundation, 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 "AS IS" AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT + * ARE 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 + +#define RPM_REQ_MAGIC 0x00716572 +#define RPM_CMD_MAGIC 0x00646d63 +#define REQ_MSG_LENGTH 0x14 +#define CMD_MSG_LENGTH 0x08 +#define ACK_MSG_LENGTH 0x0C + +static uint32_t msg_id; +smd_channel_info_t ch; + +void rpm_smd_init() +{ + smd_init(&ch, SMD_APPS_RPM); +} + +void rpm_smd_uninit() +{ + smd_uninit(&ch); +} + +static void fill_kvp_object(kvp_data **kdata, uint32_t *data, uint32_t len) +{ + *kdata = (kvp_data *) memalign(CACHE_LINE, ROUNDUP(len, CACHE_LINE)); + ASSERT(*kdata); + + memcpy(*kdata, data+2, len); +} + +static void free_kvp_object(kvp_data **kdata) +{ + if(*kdata) + free(*kdata); +} + +int rpm_send_data(uint32_t *data, uint32_t len, msg_type type) +{ + rpm_req req; + rpm_cmd cmd; + uint32_t len_to_smd = 0; + int ret = 0; + uint32_t ack_msg_len = 0; + uint32_t rlen = 0; + void *smd_data = NULL; + + switch(type) + { + case RPM_REQUEST_TYPE: + req.hdr.type = RPM_REQ_MAGIC; + req.hdr.len = len + REQ_MSG_LENGTH;//20 + req.req_hdr.id = ++msg_id; + req.req_hdr.set = 0;//assume active set. check sleep set. + req.req_hdr.resourceType = data[RESOURCETYPE]; + req.req_hdr.resourceId = data[RESOURCEID]; + req.req_hdr.dataLength = len; + + fill_kvp_object(&req.data, data, len); + len_to_smd = req.req_hdr.dataLength + 0x28; + + smd_data = (void*) malloc(len_to_smd); + ASSERT(smd_data); + + memcpy(smd_data, &req.hdr, sizeof(rpm_gen_hdr)); + memcpy(smd_data + sizeof(rpm_gen_hdr), &req.req_hdr, sizeof(rpm_req_hdr)); + memcpy(smd_data + sizeof(rpm_gen_hdr)+ sizeof(rpm_req_hdr), req.data, len); + + ret = smd_write(&ch, smd_data, len_to_smd, SMD_APPS_RPM); + + /* Read the response */ + ack_msg_len = rpm_recv_data(&rlen); + + smd_signal_read_complete(&ch, ack_msg_len); + + free(smd_data); + free_kvp_object(&req.data); + break; + case RPM_CMD_TYPE: + cmd.hdr.type = RPM_CMD_MAGIC; + cmd.hdr.len = CMD_MSG_LENGTH;//0x8; + len_to_smd = sizeof(rpm_cmd); + + fill_kvp_object(&cmd.data, data, len); + ret = smd_write(&ch, (void *)&cmd, len_to_smd, SMD_APPS_RPM); + + free_kvp_object(&cmd.data); + break; + default: + break; + } + + return ret; +} + +uint32_t rpm_recv_data(uint32_t* len) +{ + rpm_ack_msg *resp; + msg_type type; + uint32_t ret = 0; + /* As per the current design rpm response does not exceed 20 bytes */ + uint32_t response[5]; + + smd_read(&ch, len, SMD_APPS_RPM, response); + + resp = (rpm_ack_msg *)response; + + arch_invalidate_cache_range((addr_t)resp, sizeof(rpm_gen_hdr)); + + if(resp->hdr.type == RPM_CMD_MAGIC) + { + type = RPM_CMD_TYPE; + } + else if(resp->hdr.type == RPM_REQ_MAGIC) + { + type = RPM_REQUEST_TYPE; + } + + if (type == RPM_CMD_TYPE && resp->hdr.len == ACK_MSG_LENGTH) + { + dprintf(SPEW, "Received SUCCESS CMD ACK\n"); + } + else if (type == RPM_REQUEST_TYPE && resp->hdr.len == ACK_MSG_LENGTH) + { + dprintf(SPEW, "Received SUCCESS REQ ACK \n"); + } + else + { + ret = 1; + dprintf(CRITICAL, "Received ERROR ACK \n"); + } + + if(!ret) + { + ret = sizeof(rpm_gen_hdr) + sizeof(kvp_data); + } + + return ret; +} + +void rpm_clk_enable(uint32_t *data, uint32_t len) +{ + /* Send the request to SMD */ + rpm_send_data(data, len, RPM_REQUEST_TYPE); +} + +void rpm_clk_disable(uint32_t *data, uint32_t len) +{ + dprintf(CRITICAL,"Clock disable\n"); +} + diff --git a/pool/shard004/C/0097601_handler.c b/pool/shard004/C/0097601_handler.c new file mode 100644 index 0000000000000000000000000000000000000000..7622839d65e48a5c72ad94d5a97125d464cf4080 --- /dev/null +++ b/pool/shard004/C/0097601_handler.c @@ -0,0 +1,50 @@ +/* + * Copyright (c) 1999-2003, 2006 Proofpoint, Inc. and its suppliers. + * 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: handler.c,v 8.40 2013-11-22 20:51:36 ca Exp $") + +#include "libmilter.h" + +#if !_FFR_WORKERS_POOL +/* +** MI_HANDLE_SESSION -- Handle a connected session in its own context +** +** Parameters: +** ctx -- context structure +** +** Returns: +** MI_SUCCESS/MI_FAILURE +*/ + +int +mi_handle_session(ctx) + SMFICTX_PTR ctx; +{ + int ret; + + if (ctx == NULL) + return MI_FAILURE; + ctx->ctx_id = (sthread_t) sthread_get_id(); + + /* + ** Detach so resources are free when the thread returns. + ** If we ever "wait" for threads, this call must be removed. + */ + + if (pthread_detach(ctx->ctx_id) != 0) + ret = MI_FAILURE; + else + ret = mi_engine(ctx); + mi_clr_ctx(ctx); + ctx = NULL; + return ret; +} +#endif /* !_FFR_WORKERS_POOL */ diff --git a/pool/shard004/C/0097602_irc_string.c b/pool/shard004/C/0097602_irc_string.c new file mode 100644 index 0000000000000000000000000000000000000000..1f07fd309bb2fe032eeb378cc912771369cf7cb1 --- /dev/null +++ b/pool/shard004/C/0097602_irc_string.c @@ -0,0 +1,109 @@ +/* dircproxy + * Copyright (C) 2000-2003 Scott James Remnant + * + * Copyright (C) 2004-2008 Francois Harvey + * + * Copyright (C) 2008-2009 Noel Shrum + * Francois Harvey + * + * + * irc_string.c + * - Case conversion functions for IRC protocol + * - Comparison and match functions for IRC protocol + * -- + * @(#) $Id: irc_string.c,v 1.9 2002/12/29 21:30:12 scott Exp $ + * + * This file is distributed according to the GNU General Public + * License. For full details, read the top of 'main.c' or the + * file called COPYING that was distributed with this code. + */ + +#include +#include +#include + +#include +#include "match.h" +#include "sprintf.h" +#include "irc_string.h" + +/* forward declarations */ +static int _irc_tolower(int); +static int _irc_toupper(int); + +/* IRC version of tolower */ +static int _irc_tolower(int c) { + switch (c) { + case '\\': + return '|'; + default: + return tolower(c); + } +} + +/* IRC version of tolower */ +static int _irc_toupper(int c) { + switch (c) { + case '|': + return '\\'; + default: + return toupper(c); + } +} + +/* Changes the case of a string to lowercase */ +char *irc_strlwr(char *str) { + char *c; + + c = str; + while (*c) { + *c = _irc_tolower(*c); + c++; + } + + return str; +} + +/* Changes the case of a string to uppercase */ +char *irc_strupr(char *str) { + char *c; + + c = str; + while (*c) { + *c = _irc_toupper(*c); + c++; + } + + return str; +} + +/* Compare two irc strings, ignoring case. This is done so much, I've dropped + a simple version of the strcmp algorithm here rather than doing two mallocs + lowercasing etc. */ +int irc_strcasecmp(const char *s1, const char *s2) { + while (_irc_tolower(*s1) == _irc_tolower(*s2)) { + if (!*s1) + return 0; + + s1++; + s2++; + } + + return _irc_tolower(*s1) - _irc_tolower(*s2); +} + +/* Match an irc string against wildcards, ignoring case */ +int irc_strcasematch(const char *str, const char *mask) { + char *newstr, *newmask; + int ret; + + newstr = irc_strlwr(x_strdup(str)); + newmask = irc_strlwr(x_strdup(mask)); + + ret = strmatch(newstr, newmask); + + free(newstr); + free(newmask); + + return ret; +} diff --git a/pool/shard004/C/0097611_CWE122_Heap_Based_Buffer_Overflow__c_CWE193_wchar_t_memmove_11.c b/pool/shard004/C/0097611_CWE122_Heap_Based_Buffer_Overflow__c_CWE193_wchar_t_memmove_11.c new file mode 100644 index 0000000000000000000000000000000000000000..8d160e8856e9bfca5137c6c354a1a9420feb3849 --- /dev/null +++ b/pool/shard004/C/0097611_CWE122_Heap_Based_Buffer_Overflow__c_CWE193_wchar_t_memmove_11.c @@ -0,0 +1,129 @@ +/* TEMPLATE GENERATED TESTCASE FILE +Filename: CWE122_Heap_Based_Buffer_Overflow__c_CWE193_wchar_t_memmove_11.c +Label Definition File: CWE122_Heap_Based_Buffer_Overflow__c_CWE193.label.xml +Template File: sources-sink-11.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 + * Sink: memmove + * BadSink : Copy string to data using memmove() + * Flow Variant: 11 Control flow: if(globalReturnsTrue()) and if(globalReturnsFalse()) + * + * */ + +#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 + +void CWE122_Heap_Based_Buffer_Overflow__c_CWE193_wchar_t_memmove_11_bad() +{ + wchar_t * data; + data = NULL; + if(globalReturnsTrue()) + { + /* FLAW: Did not leave space for a null terminator */ + data = (wchar_t *)malloc(10*sizeof(wchar_t)); + } + { + wchar_t source[10+1] = SRC_STRING; + /* Copy length + 1 to include NUL terminator from source */ + /* POTENTIAL FLAW: data may not have enough space to hold source */ + memmove(data, source, (wcslen(source) + 1) * sizeof(wchar_t)); + printWLine(data); + free(data); + } +} + +#endif /* OMITBAD */ + +#ifndef OMITGOOD + +/* goodG2B1() - use goodsource and badsink by changing the globalReturnsTrue() to globalReturnsFalse() */ +static void goodG2B1() +{ + wchar_t * data; + data = NULL; + if(globalReturnsFalse()) + { + /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */ + printLine("Benign, fixed string"); + } + else + { + /* FIX: Allocate space for a null terminator */ + data = (wchar_t *)malloc((10+1)*sizeof(wchar_t)); + } + { + wchar_t source[10+1] = SRC_STRING; + /* Copy length + 1 to include NUL terminator from source */ + /* POTENTIAL FLAW: data may not have enough space to hold source */ + memmove(data, source, (wcslen(source) + 1) * sizeof(wchar_t)); + printWLine(data); + free(data); + } +} + +/* goodG2B2() - use goodsource and badsink by reversing the blocks in the if statement */ +static void goodG2B2() +{ + wchar_t * data; + data = NULL; + if(globalReturnsTrue()) + { + /* FIX: Allocate space for a null terminator */ + data = (wchar_t *)malloc((10+1)*sizeof(wchar_t)); + } + { + wchar_t source[10+1] = SRC_STRING; + /* Copy length + 1 to include NUL terminator from source */ + /* POTENTIAL FLAW: data may not have enough space to hold source */ + memmove(data, source, (wcslen(source) + 1) * sizeof(wchar_t)); + printWLine(data); + free(data); + } +} + +void CWE122_Heap_Based_Buffer_Overflow__c_CWE193_wchar_t_memmove_11_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()..."); + CWE122_Heap_Based_Buffer_Overflow__c_CWE193_wchar_t_memmove_11_good(); + printLine("Finished good()"); +#endif /* OMITGOOD */ +#ifndef OMITBAD + printLine("Calling bad()..."); + CWE122_Heap_Based_Buffer_Overflow__c_CWE193_wchar_t_memmove_11_bad(); + printLine("Finished bad()"); +#endif /* OMITBAD */ + return 0; +} + +#endif diff --git a/pool/shard004/C/0097626_dxa.c b/pool/shard004/C/0097626_dxa.c new file mode 100644 index 0000000000000000000000000000000000000000..a68d4c4efbc64cb07d5008cff058aa7b660a4ad3 --- /dev/null +++ b/pool/shard004/C/0097626_dxa.c @@ -0,0 +1,219 @@ +/* + * DXA demuxer + * Copyright (c) 2007 Konstantin Shishkov + * + * 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 "riff.h" + +#define DXA_EXTRA_SIZE 9 + +typedef struct{ + int frames; + int has_sound; + int bpc; + uint32_t bytes_left; + int64_t wavpos, vidpos; + int readvid; +}DXAContext; + +static int dxa_probe(AVProbeData *p) +{ + int w, h; + if (p->buf_size < 15) + return 0; + w = AV_RB16(p->buf + 11); + h = AV_RB16(p->buf + 13); + /* check file header */ + if (p->buf[0] == 'D' && p->buf[1] == 'E' && + p->buf[2] == 'X' && p->buf[3] == 'A' && + w && w <= 2048 && h && h <= 2048) + return AVPROBE_SCORE_MAX; + else + return 0; +} + +static int dxa_read_header(AVFormatContext *s, AVFormatParameters *ap) +{ + ByteIOContext *pb = s->pb; + DXAContext *c = s->priv_data; + AVStream *st, *ast; + uint32_t tag; + int32_t fps; + int w, h; + int num, den; + int flags; + + tag = get_le32(pb); + if (tag != MKTAG('D', 'E', 'X', 'A')) + return -1; + flags = get_byte(pb); + c->frames = get_be16(pb); + if(!c->frames){ + av_log(s, AV_LOG_ERROR, "File contains no frames ???\n"); + return -1; + } + + fps = get_be32(pb); + if(fps > 0){ + den = 1000; + num = fps; + }else if (fps < 0){ + den = 100000; + num = -fps; + }else{ + den = 10; + num = 1; + } + w = get_be16(pb); + h = get_be16(pb); + c->has_sound = 0; + + st = av_new_stream(s, 0); + if (!st) + return -1; + + // Parse WAV data header + if(get_le32(pb) == MKTAG('W', 'A', 'V', 'E')){ + uint32_t size, fsize; + c->has_sound = 1; + size = get_be32(pb); + c->vidpos = url_ftell(pb) + size; + url_fskip(pb, 16); + fsize = get_le32(pb); + + ast = av_new_stream(s, 0); + if (!ast) + return -1; + ff_get_wav_header(pb, ast->codec, fsize); + // find 'data' chunk + while(url_ftell(pb) < c->vidpos && !url_feof(pb)){ + tag = get_le32(pb); + fsize = get_le32(pb); + if(tag == MKTAG('d', 'a', 't', 'a')) break; + url_fskip(pb, fsize); + } + c->bpc = (fsize + c->frames - 1) / c->frames; + if(ast->codec->block_align) + c->bpc = ((c->bpc + ast->codec->block_align - 1) / ast->codec->block_align) * ast->codec->block_align; + c->bytes_left = fsize; + c->wavpos = url_ftell(pb); + url_fseek(pb, c->vidpos, SEEK_SET); + } + + /* now we are ready: build format streams */ + st->codec->codec_type = CODEC_TYPE_VIDEO; + st->codec->codec_id = CODEC_ID_DXA; + st->codec->width = w; + st->codec->height = h; + av_reduce(&den, &num, den, num, (1UL<<31)-1); + av_set_pts_info(st, 33, num, den); + /* flags & 0x80 means that image is interlaced, + * flags & 0x40 means that image has double height + * either way set true height + */ + if(flags & 0xC0){ + st->codec->height >>= 1; + } + c->readvid = !c->has_sound; + c->vidpos = url_ftell(pb); + s->start_time = 0; + s->duration = (int64_t)c->frames * AV_TIME_BASE * num / den; + av_log(s, AV_LOG_DEBUG, "%d frame(s)\n",c->frames); + + return 0; +} + +static int dxa_read_packet(AVFormatContext *s, AVPacket *pkt) +{ + DXAContext *c = s->priv_data; + int ret; + uint32_t size; + uint8_t buf[DXA_EXTRA_SIZE], pal[768+4]; + int pal_size = 0; + + if(!c->readvid && c->has_sound && c->bytes_left){ + c->readvid = 1; + url_fseek(s->pb, c->wavpos, SEEK_SET); + size = FFMIN(c->bytes_left, c->bpc); + ret = av_get_packet(s->pb, pkt, size); + pkt->stream_index = 1; + if(ret != size) + return AVERROR(EIO); + c->bytes_left -= size; + c->wavpos = url_ftell(s->pb); + return 0; + } + url_fseek(s->pb, c->vidpos, SEEK_SET); + while(!url_feof(s->pb) && c->frames){ + get_buffer(s->pb, buf, 4); + switch(AV_RL32(buf)){ + case MKTAG('N', 'U', 'L', 'L'): + if(av_new_packet(pkt, 4 + pal_size) < 0) + return AVERROR(ENOMEM); + pkt->stream_index = 0; + if(pal_size) memcpy(pkt->data, pal, pal_size); + memcpy(pkt->data + pal_size, buf, 4); + c->frames--; + c->vidpos = url_ftell(s->pb); + c->readvid = 0; + return 0; + case MKTAG('C', 'M', 'A', 'P'): + pal_size = 768+4; + memcpy(pal, buf, 4); + get_buffer(s->pb, pal + 4, 768); + break; + case MKTAG('F', 'R', 'A', 'M'): + get_buffer(s->pb, buf + 4, DXA_EXTRA_SIZE - 4); + size = AV_RB32(buf + 5); + if(size > 0xFFFFFF){ + av_log(s, AV_LOG_ERROR, "Frame size is too big: %d\n", size); + return -1; + } + if(av_new_packet(pkt, size + DXA_EXTRA_SIZE + pal_size) < 0) + return AVERROR(ENOMEM); + memcpy(pkt->data + pal_size, buf, DXA_EXTRA_SIZE); + ret = get_buffer(s->pb, pkt->data + DXA_EXTRA_SIZE + pal_size, size); + if(ret != size){ + av_free_packet(pkt); + return AVERROR(EIO); + } + if(pal_size) memcpy(pkt->data, pal, pal_size); + pkt->stream_index = 0; + c->frames--; + c->vidpos = url_ftell(s->pb); + c->readvid = 0; + return 0; + default: + av_log(s, AV_LOG_ERROR, "Unknown tag %c%c%c%c\n", buf[0], buf[1], buf[2], buf[3]); + return -1; + } + } + return AVERROR(EIO); +} + +AVInputFormat dxa_demuxer = { + "dxa", + NULL_IF_CONFIG_SMALL("DXA"), + sizeof(DXAContext), + dxa_probe, + dxa_read_header, + dxa_read_packet, +}; diff --git a/pool/shard004/C/0097629_sleep.c b/pool/shard004/C/0097629_sleep.c new file mode 100644 index 0000000000000000000000000000000000000000..8a8fe7c25e8208efb7917fa5b7eff297cf1cdff8 --- /dev/null +++ b/pool/shard004/C/0097629_sleep.c @@ -0,0 +1,76 @@ +/* Pausing execution of the current thread. + Copyright (C) 2007, 2009-2017 Free Software Foundation, Inc. + Written by Bruno Haible , 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 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 + +/* Specification. */ +#include + +#include + +#include "verify.h" + +#if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__ + +# define WIN32_LEAN_AND_MEAN /* avoid including junk */ +# include + +unsigned int +sleep (unsigned int seconds) +{ + unsigned int remaining; + + /* Sleep for 1 second many times, because + 1. Sleep is not interruptible by Ctrl-C, + 2. we want to avoid arithmetic overflow while multiplying with 1000. */ + for (remaining = seconds; remaining > 0; remaining--) + Sleep (1000); + + return remaining; +} + +#elif HAVE_SLEEP + +# undef sleep + +/* Guarantee unlimited sleep and a reasonable return value. Cygwin + 1.5.x rejects attempts to sleep more than 49.7 days (2**32 + milliseconds), but uses uninitialized memory which results in a + garbage answer. Similarly, Linux 2.6.9 with glibc 2.3.4 has a too + small return value when asked to sleep more than 24.85 days. */ +unsigned int +rpl_sleep (unsigned int seconds) +{ + /* This requires int larger than 16 bits. */ + verify (UINT_MAX / 24 / 24 / 60 / 60); + const unsigned int limit = 24 * 24 * 60 * 60; + while (limit < seconds) + { + unsigned int result; + seconds -= limit; + result = sleep (limit); + if (result) + return seconds + result; + } + return sleep (seconds); +} + +#else /* !HAVE_SLEEP */ + + #error "Please port gnulib sleep.c to your platform, possibly using usleep() or select(), then report this to bug-gnulib." + +#endif diff --git a/pool/shard004/C/0097632_vmcontrol_wrapper.c b/pool/shard004/C/0097632_vmcontrol_wrapper.c new file mode 100644 index 0000000000000000000000000000000000000000..13ff1a9b1ea3632e9aa8eae108fb5b2b117d5024 --- /dev/null +++ b/pool/shard004/C/0097632_vmcontrol_wrapper.c @@ -0,0 +1,210 @@ +/* + * Copyright (C) [2004, 2005, 2006], Hyperic, Inc. + * This file is part of SIGAR. + * + * SIGAR is free software; you can redistribute it and/or modify + * it under the terms 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 + * USA. + */ + +#include "vmcontrol_wrapper.h" + +#ifdef VMCONTROL_WRAPPER_SUPPORTED + +#ifdef WIN32 +#include +#else +#include +#include +#include +#include +#endif + +#include + +#ifdef WIN32 +#define DL_LOAD(lib) LoadLibrary(lib) +#define DL_CLOSE(h) FreeLibrary(h) +#define DL_SYM GetProcAddress +#define DL_ERR GetLastError() +#define DL_ENOENT ERROR_FILE_NOT_FOUND +#else +#define DL_LOAD(lib) dlopen(lib, RTLD_LAZY) +#define DL_CLOSE(h) dlclose(h) +#define DL_SYM dlsym +#define DL_ERR errno +#define DL_ENOENT ENOENT +#endif + +typedef struct { + const char *name; + unsigned long offset; + const char *alias; +} vmcontrol_entry_t; + +#define OffsetOf(structure, field) \ + (unsigned long)(&((structure *)NULL)->field) + +#define VMCONTROL_ENTRY(name) \ + { #name, OffsetOf(vmcontrol_wrapper_api_t, x##name), NULL } + +#define VMCONTROL_ENTRY_ALIAS(name, alias) \ + { #name, OffsetOf(vmcontrol_wrapper_api_t, x##name), alias } + +static vmcontrol_entry_t vmcontrol_entries[] = { + VMCONTROL_ENTRY(VMControl_ConnectParamsDestroy), + VMCONTROL_ENTRY(VMControl_ConnectParamsNew), + VMCONTROL_ENTRY(VMControl_Init), + VMCONTROL_ENTRY(VMControl_MKSSaveScreenshot), + VMCONTROL_ENTRY(VMControl_ServerConnectEx), + VMCONTROL_ENTRY(VMControl_ServerDestroy), + VMCONTROL_ENTRY(VMControl_ServerDisconnect), + VMCONTROL_ENTRY(VMControl_ServerEnumerate), + VMCONTROL_ENTRY(VMControl_ServerExec), + VMCONTROL_ENTRY(VMControl_ServerGetLastError), + VMCONTROL_ENTRY(VMControl_ServerGetResource), + VMCONTROL_ENTRY(VMControl_ServerIsConnected), + VMCONTROL_ENTRY(VMControl_ServerIsRegistered), + VMCONTROL_ENTRY(VMControl_ServerNewEx), + VMCONTROL_ENTRY(VMControl_VMConnectEx), + VMCONTROL_ENTRY(VMControl_VMCreateSnapshot), + VMCONTROL_ENTRY(VMControl_VMDestroy), + VMCONTROL_ENTRY(VMControl_VMDeviceConnect), + VMCONTROL_ENTRY(VMControl_VMDeviceDisconnect), + VMCONTROL_ENTRY(VMControl_VMDeviceIsConnected), + VMCONTROL_ENTRY(VMControl_VMDisconnect), + VMCONTROL_ENTRY(VMControl_VMGetCapabilities), + VMCONTROL_ENTRY(VMControl_VMGetConfig), + VMCONTROL_ENTRY(VMControl_VMGetConfigFileName), + VMCONTROL_ENTRY(VMControl_VMGetExecutionState), + VMCONTROL_ENTRY(VMControl_VMGetGuestInfo), + VMCONTROL_ENTRY(VMControl_VMGetHeartbeat), + VMCONTROL_ENTRY(VMControl_VMGetId), + VMCONTROL_ENTRY(VMControl_VMGetLastError), + VMCONTROL_ENTRY(VMControl_VMGetPid), + VMCONTROL_ENTRY(VMControl_VMGetProductInfo), + VMCONTROL_ENTRY(VMControl_VMGetRemoteConnections), + VMCONTROL_ENTRY(VMControl_VMGetResource), + VMCONTROL_ENTRY(VMControl_VMGetRunAsUser), + VMCONTROL_ENTRY(VMControl_VMGetUptime), + VMCONTROL_ENTRY(VMControl_VMHasSnapshot), + VMCONTROL_ENTRY(VMControl_VMInit), + VMCONTROL_ENTRY(VMControl_VMIsConnected), + VMCONTROL_ENTRY(VMControl_VMNewEx), + VMCONTROL_ENTRY_ALIAS(VMControl_VMRemoveAllSnapshots, + "VMControl_VMDeleteSnapshot"), + VMCONTROL_ENTRY_ALIAS(VMControl_VMRevertToSnapshot, + "VMControl_VMRevertSnapshot"), + VMCONTROL_ENTRY(VMControl_VMSetConfig), + VMCONTROL_ENTRY(VMControl_VMSetGuestInfo), + VMCONTROL_ENTRY(VMControl_VMStart), + VMCONTROL_ENTRY(VMControl_VMStopOrReset), + VMCONTROL_ENTRY(VMControl_VMSuspendToDisk), + VMCONTROL_ENTRY(VMControl_VMToolsLastActive), + { NULL, 0, NULL } +}; + +static vmcontrol_wrapper_api_t *vmcontrol_api = NULL; + +vmcontrol_wrapper_api_t *vmcontrol_wrapper_api_get(void) +{ + return vmcontrol_api; +} + +typedef void (*any_function_t)(void); + +static int unsupported_function(void *obj, ...) +{ + return 0; +} + +int vmcontrol_wrapper_api_init(const char *lib) +{ + int i; + char *api; + int dl_debug = getenv("VMCONTROL_DEBUG") != NULL; + + if (vmcontrol_api) { + return 0; + } + + if (!lib) { /* sanity check */ + if (dl_debug) { + fprintf(stderr, "[vmcontrol_init] lib==NULL\n"); + } + return DL_ENOENT; + } + + vmcontrol_api = malloc(sizeof(*vmcontrol_api)); + api = (char *)vmcontrol_api; + memset(vmcontrol_api, 0, sizeof(*vmcontrol_api)); + + if (!(vmcontrol_api->handle = DL_LOAD(lib))) { + return DL_ERR; + } + + for (i=0; vmcontrol_entries[i].name; i++) { + any_function_t *ptr = + (any_function_t *)(api + (int)(long)vmcontrol_entries[i].offset); + + *ptr = + (any_function_t)DL_SYM(vmcontrol_api->handle, + vmcontrol_entries[i].name); + + if ((*ptr == NULL) && vmcontrol_entries[i].alias) { + *ptr = + (any_function_t)DL_SYM(vmcontrol_api->handle, + vmcontrol_entries[i].alias); + + if (dl_debug) { + fprintf(stderr, "[vmcontrol_init] alias %s -> %s\n", + vmcontrol_entries[i].name, + vmcontrol_entries[i].alias); + } + } + + if (!*ptr) { + if (dl_debug) { + fprintf(stderr, "[vmcontrol_init] %s -> UNDEFINED\n", + vmcontrol_entries[i].name); + } + *ptr = (any_function_t)unsupported_function; + } + } + + if ((void *)vmcontrol_api->xVMControl_VMInit == (void *)&unsupported_function) { + if (dl_debug) { + fprintf(stderr, "[vmcontrol_init] %s unuseable\n", lib); + } + + vmcontrol_wrapper_api_shutdown(); + return DL_ENOENT; + } + + return 0; +} + +int vmcontrol_wrapper_api_shutdown(void) +{ + if (vmcontrol_api) { + if (vmcontrol_api->handle) { + DL_CLOSE(vmcontrol_api->handle); + } + + free(vmcontrol_api); + vmcontrol_api = NULL; + } + + return 0; +} + +#endif /* WIN32 || linux */ diff --git a/pool/shard004/C/0097634_flock.c b/pool/shard004/C/0097634_flock.c new file mode 100644 index 0000000000000000000000000000000000000000..6d269055062bf33fa471214973c0fe4959c89336 --- /dev/null +++ b/pool/shard004/C/0097634_flock.c @@ -0,0 +1,220 @@ +/* Emulate flock on platforms that lack it, primarily Windows and MinGW. + + This is derived from sqlite3 sources. + http://www.sqlite.org/cvstrac/rlog?f=sqlite/src/os_win.c + http://www.sqlite.org/copyright.html + + Written by Richard W.M. Jones + + Copyright (C) 2008-2012 Free Software Foundation, Inc. + + 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 for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . */ + +#include +#include + +#if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__ + +/* LockFileEx */ +# define WIN32_LEAN_AND_MEAN +# include + +# include + +/* _get_osfhandle */ +# include "msvc-nothrow.h" + +/* Determine the current size of a file. Because the other braindead + * APIs we'll call need lower/upper 32 bit pairs, keep the file size + * like that too. + */ +static BOOL +file_size (HANDLE h, DWORD * lower, DWORD * upper) +{ + *lower = GetFileSize (h, upper); + return 1; +} + +/* LOCKFILE_FAIL_IMMEDIATELY is undefined on some Windows systems. */ +# ifndef LOCKFILE_FAIL_IMMEDIATELY +# define LOCKFILE_FAIL_IMMEDIATELY 1 +# endif + +/* Acquire a lock. */ +static BOOL +do_lock (HANDLE h, int non_blocking, int exclusive) +{ + BOOL res; + DWORD size_lower, size_upper; + OVERLAPPED ovlp; + int flags = 0; + + /* We're going to lock the whole file, so get the file size. */ + res = file_size (h, &size_lower, &size_upper); + if (!res) + return 0; + + /* Start offset is 0, and also zero the remaining members of this struct. */ + memset (&ovlp, 0, sizeof ovlp); + + if (non_blocking) + flags |= LOCKFILE_FAIL_IMMEDIATELY; + if (exclusive) + flags |= LOCKFILE_EXCLUSIVE_LOCK; + + return LockFileEx (h, flags, 0, size_lower, size_upper, &ovlp); +} + +/* Unlock reader or exclusive lock. */ +static BOOL +do_unlock (HANDLE h) +{ + int res; + DWORD size_lower, size_upper; + + res = file_size (h, &size_lower, &size_upper); + if (!res) + return 0; + + return UnlockFile (h, 0, 0, size_lower, size_upper); +} + +/* Now our BSD-like flock operation. */ +int +flock (int fd, int operation) +{ + HANDLE h = (HANDLE) _get_osfhandle (fd); + DWORD res; + int non_blocking; + + if (h == INVALID_HANDLE_VALUE) + { + errno = EBADF; + return -1; + } + + non_blocking = operation & LOCK_NB; + operation &= ~LOCK_NB; + + switch (operation) + { + case LOCK_SH: + res = do_lock (h, non_blocking, 0); + break; + case LOCK_EX: + res = do_lock (h, non_blocking, 1); + break; + case LOCK_UN: + res = do_unlock (h); + break; + default: + errno = EINVAL; + return -1; + } + + /* Map Windows errors into Unix errnos. As usual MSDN fails to + * document the permissible error codes. + */ + if (!res) + { + DWORD err = GetLastError (); + switch (err) + { + /* This means someone else is holding a lock. */ + case ERROR_LOCK_VIOLATION: + errno = EAGAIN; + break; + + /* Out of memory. */ + case ERROR_NOT_ENOUGH_MEMORY: + errno = ENOMEM; + break; + + case ERROR_BAD_COMMAND: + errno = EINVAL; + break; + + /* Unlikely to be other errors, but at least don't lose the + * error code. + */ + default: + errno = err; + } + + return -1; + } + + return 0; +} + +#else /* !Windows */ + +# ifdef HAVE_STRUCT_FLOCK_L_TYPE +/* We know how to implement flock in terms of fcntl. */ + +# include + +# ifdef HAVE_UNISTD_H +# include +# endif + +# include +# include + +int +flock (int fd, int operation) +{ + int cmd, r; + struct flock fl; + + if (operation & LOCK_NB) + cmd = F_SETLK; + else + cmd = F_SETLKW; + operation &= ~LOCK_NB; + + memset (&fl, 0, sizeof fl); + fl.l_whence = SEEK_SET; + /* l_start & l_len are 0, which as a special case means "whole file". */ + + switch (operation) + { + case LOCK_SH: + fl.l_type = F_RDLCK; + break; + case LOCK_EX: + fl.l_type = F_WRLCK; + break; + case LOCK_UN: + fl.l_type = F_UNLCK; + break; + default: + errno = EINVAL; + return -1; + } + + r = fcntl (fd, cmd, &fl); + if (r == -1 && errno == EACCES) + errno = EAGAIN; + + return r; +} + +# else /* !HAVE_STRUCT_FLOCK_L_TYPE */ + +# error "This platform lacks flock function, and Gnulib doesn't provide a replacement. This is a bug in Gnulib." + +# endif /* !HAVE_STRUCT_FLOCK_L_TYPE */ + +#endif /* !Windows */ diff --git a/pool/shard004/C/0097635_dset.c b/pool/shard004/C/0097635_dset.c new file mode 100644 index 0000000000000000000000000000000000000000..6dbb29e663a2262ceedabc31ece811f250892780 --- /dev/null +++ b/pool/shard004/C/0097635_dset.c @@ -0,0 +1,169 @@ +/* + * $Id: dset.c,v 1.5 2002/09/19 12:23:52 jku Rel $ + * + * destination set + * + * 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 + */ + + +#include + +#include "dprint.h" +#include "config.h" +#include "parser/parser_f.h" +#include "parser/msg_parser.h" +#include "ut.h" +#include "hash_func.h" +#include "dset.h" +#include "error.h" + + + +/* where we store URIs of additional transaction branches + (-1 because of the default branch, #0) +*/ +static struct branch branches[ MAX_BRANCHES - 1 ]; +/* how many of them we have */ +static unsigned int nr_branches=0; +/* branch iterator */ +static int branch_iterator=0; + +void init_branch_iterator(void) +{ + branch_iterator=0; +} + +char *next_branch( int *len ) +{ + unsigned int i; + + i=branch_iterator; + if (iMAX_URI_SIZE-1) { + LOG(L_ERR, "ERROR: append_branch: too long uri: %.*s\n", + uri_len, uri ); + return -1; + } + + /* if not parameterized, take current uri */ + if (uri==0) { + if (msg->new_uri.s) { + uri=msg->new_uri.s; + uri_len=msg->new_uri.len; + } else { + uri=msg->first_line.u.request.uri.s; + uri_len=msg->first_line.u.request.uri.len; + } + } + + memcpy( branches[nr_branches].uri, uri, uri_len ); + /* be safe -- add zero termination */ + branches[nr_branches].uri[uri_len]=0; + branches[nr_branches].len=uri_len; + + nr_branches++; + return 1; +} + + + +char *print_dset( struct sip_msg *msg, int *len ) +{ + int cnt; + str uri; + char *p; + int i; + static char dset[MAX_REDIRECTION_LEN]; + + if (msg->new_uri.s) { + cnt=1; + *len=msg->new_uri.len; + } else { + cnt=0; + *len=0; + } + + init_branch_iterator(); + while ((uri.s=next_branch(&uri.len))) { + cnt++; + *len+=uri.len; + } + + if (cnt==0) return 0; + + *len+=CONTACT_LEN+CRLF_LEN+(cnt-1)*CONTACT_DELIM_LEN; + + if (*len+1>MAX_REDIRECTION_LEN) { + LOG(L_ERR, "ERROR: redirection buffer length exceed\n"); + return 0; + } + + memcpy(dset, CONTACT, CONTACT_LEN ); + p=dset+CONTACT_LEN; + if (msg->new_uri.s) { + memcpy(p, msg->new_uri.s, msg->new_uri.len); + p+=msg->new_uri.len; + i=1; + } else i=0; + + init_branch_iterator(); + while ((uri.s=next_branch(&uri.len))) { + if (i) { + memcpy(p, CONTACT_DELIM, CONTACT_DELIM_LEN ); + p+=2; + } + memcpy(p, uri.s, uri.len); + p+=uri.len; + i++; + } + memcpy(p, CRLF " ", CRLF_LEN+1); + return dset; +} + diff --git a/pool/shard004/C/0097642_touch-i2c.c b/pool/shard004/C/0097642_touch-i2c.c new file mode 100644 index 0000000000000000000000000000000000000000..da3665520f4f1e1cfdef3d597c3831166e65652a --- /dev/null +++ b/pool/shard004/C/0097642_touch-i2c.c @@ -0,0 +1,164 @@ +//[*]--------------------------------------------------------------------------------------------------[*] +// +// +// +// I2C Touchscreen driver +// 2012.01.17 +// +// +//[*]--------------------------------------------------------------------------------------------------[*] +#include /* BUS_I2C */ +#include +#include + +//[*]--------------------------------------------------------------------------------------------------[*] +#include +#include "touch.h" + +//[*]--------------------------------------------------------------------------------------------------[*] +// +// function prototype +// +//[*]--------------------------------------------------------------------------------------------------[*] +static void __exit touch_i2c_exit (void); +static int __init touch_i2c_init (void); +static int __devexit touch_i2c_remove (struct i2c_client *client); +static int __devinit touch_i2c_probe (struct i2c_client *client, const struct i2c_device_id *id); + int touch_i2c_read (struct i2c_client *client, unsigned char *cmd, unsigned int cmd_len, unsigned char *data, unsigned int len); + int touch_i2c_write (struct i2c_client *client, unsigned char *cmd, unsigned int cmd_len, unsigned char *data, unsigned int len); + +//[*]--------------------------------------------------------------------------------------------------[*] +#ifdef CONFIG_PM +static int touch_i2c_suspend(struct i2c_client *client, pm_message_t message) +{ + #ifdef CONFIG_HAS_EARLYSUSPEND + struct touch *ts = i2c_get_clientdata(client); + + ts->pdata->suspend(&client->dev); + #endif + + return 0; +} + +//[*]--------------------------------------------------------------------------------------------------[*] +static int touch_i2c_resume(struct i2c_client *client) +{ + #ifdef CONFIG_HAS_EARLYSUSPEND + struct touch *ts = i2c_get_clientdata(client); + + ts->pdata->resume(&cliet->dev); + #endif + + return 0; +} + +//[*]--------------------------------------------------------------------------------------------------[*] +#else + #define touch_i2c_suspend NULL + #define touch_i2c_resume NULL +#endif + +//[*]--------------------------------------------------------------------------------------------------[*] +int touch_i2c_read(struct i2c_client *client, unsigned char *cmd, unsigned int cmd_len, unsigned char *data, unsigned int len) +{ + struct i2c_msg msg[2]; + int ret; + + if((len == 0) || (data == NULL)) { + dev_err(&client->dev, "I2C read error: Null pointer or length == 0\n"); + return -1; + } + + memset(msg, 0x00, sizeof(msg)); + + msg[0].addr = client->addr; + msg[0].flags = 0; + msg[0].len = cmd_len; + msg[0].buf = cmd; + + msg[1].addr = client->addr; + msg[1].flags = I2C_M_RD; + msg[1].len = len; + msg[1].buf = data; + + if ((ret = i2c_transfer(client->adapter, msg, 2)) != 2) { + dev_err(&client->dev, "I2C read error: (%d) reg: 0x%X len: %d\n", ret, cmd[0], len); + return -EIO; + } + + return len; +} + +//[*]--------------------------------------------------------------------------------------------------[*] +int touch_i2c_write(struct i2c_client *client, unsigned char *cmd, unsigned int cmd_len, unsigned char *data, unsigned int len) +{ + int ret; + unsigned char block_data[10]; + + if((cmd_len + len) >= sizeof(block_data)) { + dev_err(&client->dev, "I2C write error: wdata overflow reg: 0x%X len: %d\n", cmd[0], cmd_len + len); + return -1; + } + + memset(block_data, 0x00, sizeof(block_data)); + + if(cmd_len) memcpy(&block_data[0] , &cmd[0] , cmd_len); + if(len) memcpy(&block_data[cmd_len] , &data[0] , len); + + if ((ret = i2c_master_send(client, block_data, (cmd_len + len)))< 0) { + dev_err(&client->dev, "I2C write error: (%d) reg: 0x%X len: %d\n", ret, cmd[0], len); + return ret; + } + + return len; +} + +//[*]--------------------------------------------------------------------------------------------------[*] +static int __devinit touch_i2c_probe(struct i2c_client *client, const struct i2c_device_id *id) +{ + return touch_probe(client); +} + +//[*]--------------------------------------------------------------------------------------------------[*] +static int __devexit touch_i2c_remove(struct i2c_client *client) +{ + return touch_remove(&client->dev); +} + +//[*]--------------------------------------------------------------------------------------------------[*] +static const struct i2c_device_id touch_id[] = { + { I2C_TOUCH_NAME, 0 }, + { } +}; + +MODULE_DEVICE_TABLE(i2c, touch_id); + +//[*]--------------------------------------------------------------------------------------------------[*] +static struct i2c_driver touch_i2c_driver = { + .driver = { + .name = I2C_TOUCH_NAME, + .owner = THIS_MODULE, + }, + .probe = touch_i2c_probe, + .remove = __devexit_p(touch_i2c_remove), + .suspend = touch_i2c_suspend, + .resume = touch_i2c_resume, + .id_table = touch_id, +}; + +//[*]--------------------------------------------------------------------------------------------------[*] +static int __init touch_i2c_init(void) +{ + return i2c_add_driver(&touch_i2c_driver); +} +module_init(touch_i2c_init); + +//[*]--------------------------------------------------------------------------------------------------[*] +static void __exit touch_i2c_exit(void) +{ + i2c_del_driver(&touch_i2c_driver); +} +module_exit(touch_i2c_exit); + +//[*]--------------------------------------------------------------------------------------------------[*] +//[*]--------------------------------------------------------------------------------------------------[*] diff --git a/pool/shard004/C/0097646_Test_08.c b/pool/shard004/C/0097646_Test_08.c new file mode 100644 index 0000000000000000000000000000000000000000..d14788884d1f4c96f84c441c7950097e592adaf4 --- /dev/null +++ b/pool/shard004/C/0097646_Test_08.c @@ -0,0 +1,59 @@ + +/* + * ======== string literals ======== + */ + +static const char test66_Test_08__s__fileName[] = "Test_08.p"; +static const char test66_Test_08__s__1[] = "TICK 1\n"; +static const char test66_Test_08__s__6[] = "Test_08"; +static const char test66_Test_08__s__5[] = "TICK 5\n"; +static const char test66_Test_08__s__4[] = "TICK 4\n"; +static const char test66_Test_08__s__0[] = "In remove while loop\n"; +static const char test66_Test_08__s__2[] = "TICK 2\n"; +static const char test66_Test_08__s__3[] = "TICK 3\n"; + +/* + * ======== function definitions ======== + */ + +void test66_Test_08_tick4__I() { + test66_Test_08_pollen__printStr((string)test66_Test_08__s__4); +} + +void test66_Test_08_pollen__run__E() { + pollen_data_HandlerQueue_HandlerQueue_add__E(&(test66_Test_08_handlers__V), (test66_Test_08_tick5__I)); + pollen_data_HandlerQueue_HandlerQueue_add__E(&(test66_Test_08_handlers__V), (test66_Test_08_tick4__I)); + pollen_data_HandlerQueue_HandlerQueue_add__E(&(test66_Test_08_handlers__V), (test66_Test_08_tick3__I)); + pollen_data_HandlerQueue_HandlerQueue_add__E(&(test66_Test_08_handlers__V), (test66_Test_08_tick2__I)); + pollen_data_HandlerQueue_HandlerQueue_add__E(&(test66_Test_08_handlers__V), (test66_Test_08_tick1__I)); + while (!pollen_data_HandlerQueue_HandlerQueue_isEmpty__E(&(test66_Test_08_handlers__V))) { + (test66_Test_08_h__V) = pollen_data_HandlerQueue_HandlerQueue_remove__E(&(test66_Test_08_handlers__V)); + test66_Test_08_pollen__printStr((string)test66_Test_08__s__0); + if ((test66_Test_08_h__V) != null) { + test66_Test_08_h__V(); + } + } +} + +void test66_Test_08_tick3__I() { + test66_Test_08_pollen__printStr((string)test66_Test_08__s__3); +} + +void test66_Test_08_tick2__I() { + test66_Test_08_pollen__printStr((string)test66_Test_08__s__2); +} + +void test66_Test_08_tick1__I() { + test66_Test_08_pollen__printStr((string)test66_Test_08__s__1); +} + +void test66_Test_08_tick5__I() { + test66_Test_08_pollen__printStr((string)test66_Test_08__s__5); +} + +void test66_Test_08_pollen__shutdown__E( uint8 id ) { +} + +void test66_Test_08_targetInit__I() { +} + diff --git a/pool/shard004/C/0097650_sys_nautilus.c b/pool/shard004/C/0097650_sys_nautilus.c new file mode 100644 index 0000000000000000000000000000000000000000..dc7945265984f049bb6101840762cf0a502de0e1 --- /dev/null +++ b/pool/shard004/C/0097650_sys_nautilus.c @@ -0,0 +1,285 @@ +/* + * linux/arch/alpha/kernel/sys_nautilus.c + * + * Copyright (C) 1995 David A Rusling + * Copyright (C) 1998 Richard Henderson + * Copyright (C) 1999 Alpha Processor, Inc., + * (David Daniel, Stig Telfer, Soohoon Lee) + * + * Code supporting NAUTILUS systems. + * + * + * NAUTILUS has the following I/O features: + * + * a) Driven by AMD 751 aka IRONGATE (northbridge): + * 4 PCI slots + * 1 AGP slot + * + * b) Driven by ALI M1543C (southbridge) + * 2 ISA slots + * 2 IDE connectors + * 1 dual drive capable FDD controller + * 2 serial ports + * 1 ECP/EPP/SP parallel port + * 2 USB ports + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "proto.h" +#include "err_impl.h" +#include "irq_impl.h" +#include "pci_impl.h" +#include "machvec_impl.h" + + +static void __init +nautilus_init_irq(void) +{ + if (alpha_using_srm) { + alpha_mv.device_interrupt = srm_device_interrupt; + } + + init_i8259a_irqs(); + common_init_isa_dma(); +} + +static int __init +nautilus_map_irq(struct pci_dev *dev, u8 slot, u8 pin) +{ + /* Preserve the IRQ set up by the console. */ + + u8 irq; + /* UP1500: AGP INTA is actually routed to IRQ 5, not IRQ 10 as + console reports. Check the device id of AGP bridge to distinguish + UP1500 from UP1000/1100. Note: 'pin' is 2 due to bridge swizzle. */ + if (slot == 1 && pin == 2 && + dev->bus->self && dev->bus->self->device == 0x700f) + return 5; + pci_read_config_byte(dev, PCI_INTERRUPT_LINE, &irq); + return irq; +} + +void +nautilus_kill_arch(int mode) +{ + struct pci_bus *bus = pci_isa_hose->bus; + u32 pmuport; + int off; + + switch (mode) { + case LINUX_REBOOT_CMD_RESTART: + if (! alpha_using_srm) { + u8 t8; + pci_bus_read_config_byte(bus, 0x38, 0x43, &t8); + pci_bus_write_config_byte(bus, 0x38, 0x43, t8 | 0x80); + outb(1, 0x92); + outb(0, 0x92); + /* NOTREACHED */ + } + break; + + case LINUX_REBOOT_CMD_POWER_OFF: + /* Assume M1543C */ + off = 0x2000; /* SLP_TYPE = 0, SLP_EN = 1 */ + pci_bus_read_config_dword(bus, 0x88, 0x10, &pmuport); + if (!pmuport) { + /* M1535D/D+ */ + off = 0x3400; /* SLP_TYPE = 5, SLP_EN = 1 */ + pci_bus_read_config_dword(bus, 0x88, 0xe0, &pmuport); + } + pmuport &= 0xfffe; + outw(0xffff, pmuport); /* Clear pending events. */ + outw(off, pmuport + 4); + /* NOTREACHED */ + break; + } +} + +/* Perform analysis of a machine check that arrived from the system (NMI) */ + +static void +naut_sys_machine_check(unsigned long vector, unsigned long la_ptr, + struct pt_regs *regs) +{ + printk("PC %lx RA %lx\n", regs->pc, regs->r26); + irongate_pci_clr_err(); +} + +/* Machine checks can come from two sources - those on the CPU and those + in the system. They are analysed separately but all starts here. */ + +void +nautilus_machine_check(unsigned long vector, unsigned long la_ptr) +{ + char *mchk_class; + + /* Now for some analysis. Machine checks fall into two classes -- + those picked up by the system, and those picked up by the CPU. + Add to that the two levels of severity - correctable or not. */ + + if (vector == SCB_Q_SYSMCHK + && ((IRONGATE0->dramms & 0x300) == 0x300)) { + unsigned long nmi_ctl; + + /* Clear ALI NMI */ + nmi_ctl = inb(0x61); + nmi_ctl |= 0x0c; + outb(nmi_ctl, 0x61); + nmi_ctl &= ~0x0c; + outb(nmi_ctl, 0x61); + + /* Write again clears error bits. */ + IRONGATE0->stat_cmd = IRONGATE0->stat_cmd & ~0x100; + mb(); + IRONGATE0->stat_cmd; + + /* Write again clears error bits. */ + IRONGATE0->dramms = IRONGATE0->dramms; + mb(); + IRONGATE0->dramms; + + draina(); + wrmces(0x7); + mb(); + return; + } + + if (vector == SCB_Q_SYSERR) + mchk_class = "Correctable"; + else if (vector == SCB_Q_SYSMCHK) + mchk_class = "Fatal"; + else { + ev6_machine_check(vector, la_ptr); + return; + } + + printk(KERN_CRIT "NAUTILUS Machine check 0x%lx " + "[%s System Machine Check (NMI)]\n", + vector, mchk_class); + + naut_sys_machine_check(vector, la_ptr, get_irq_regs()); + + /* Tell the PALcode to clear the machine check */ + draina(); + wrmces(0x7); + mb(); +} + +extern void free_reserved_mem(void *, void *); +extern void pcibios_claim_one_bus(struct pci_bus *); + +static struct resource irongate_io = { + .name = "Irongate PCI IO", + .flags = IORESOURCE_IO, +}; +static struct resource irongate_mem = { + .name = "Irongate PCI MEM", + .flags = IORESOURCE_MEM, +}; + +void __init +nautilus_init_pci(void) +{ + struct pci_controller *hose = hose_head; + struct pci_bus *bus; + struct pci_dev *irongate; + unsigned long bus_align, bus_size, pci_mem; + unsigned long memtop = max_low_pfn << PAGE_SHIFT; + + /* Scan our single hose. */ + bus = pci_scan_bus(0, alpha_mv.pci_ops, hose); + hose->bus = bus; + pcibios_claim_one_bus(bus); + + irongate = pci_get_bus_and_slot(0, 0); + bus->self = irongate; + bus->resource[0] = &irongate_io; + bus->resource[1] = &irongate_mem; + + pci_bus_size_bridges(bus); + + /* IO port range. */ + bus->resource[0]->start = 0; + bus->resource[0]->end = 0xffff; + + /* Set up PCI memory range - limit is hardwired to 0xffffffff, + base must be at aligned to 16Mb. */ + bus_align = bus->resource[1]->start; + bus_size = bus->resource[1]->end + 1 - bus_align; + if (bus_align < 0x1000000UL) + bus_align = 0x1000000UL; + + pci_mem = (0x100000000UL - bus_size) & -bus_align; + + bus->resource[1]->start = pci_mem; + bus->resource[1]->end = 0xffffffffUL; + if (request_resource(&iomem_resource, bus->resource[1]) < 0) + printk(KERN_ERR "Failed to request MEM on hose 0\n"); + + if (pci_mem < memtop) + memtop = pci_mem; + if (memtop > alpha_mv.min_mem_address) { + free_reserved_mem(__va(alpha_mv.min_mem_address), + __va(memtop)); + printk("nautilus_init_pci: %ldk freed\n", + (memtop - alpha_mv.min_mem_address) >> 10); + } + + if ((IRONGATE0->dev_vendor >> 16) > 0x7006) /* Albacore? */ + IRONGATE0->pci_mem = pci_mem; + + pci_bus_assign_resources(bus); + + /* pci_common_swizzle() relies on bus->self being NULL + for the root bus, so just clear it. */ + bus->self = NULL; + pci_fixup_irqs(alpha_mv.pci_swizzle, alpha_mv.pci_map_irq); +} + +/* + * The System Vectors + */ + +struct alpha_machine_vector nautilus_mv __initmv = { + .vector_name = "Nautilus", + DO_EV6_MMU, + DO_DEFAULT_RTC, + DO_IRONGATE_IO, + .machine_check = nautilus_machine_check, + .max_isa_dma_address = ALPHA_MAX_ISA_DMA_ADDRESS, + .min_io_address = DEFAULT_IO_BASE, + .min_mem_address = IRONGATE_DEFAULT_MEM_BASE, + + .nr_irqs = 16, + .device_interrupt = isa_device_interrupt, + + .init_arch = irongate_init_arch, + .init_irq = nautilus_init_irq, + .init_rtc = common_init_rtc, + .init_pci = nautilus_init_pci, + .kill_arch = nautilus_kill_arch, + .pci_map_irq = nautilus_map_irq, + .pci_swizzle = common_swizzle, +}; +ALIAS_MV(nautilus) diff --git a/pool/shard004/C/0097656_wait.c b/pool/shard004/C/0097656_wait.c new file mode 100644 index 0000000000000000000000000000000000000000..7bb84ee96717a9b9adef32402214f52f80cdad49 --- /dev/null +++ b/pool/shard004/C/0097656_wait.c @@ -0,0 +1,34 @@ +#include "server.h" + +int wait_4_connection(char *ip) { + + pthread_t threads[NUM_THREADS]; + pthread_attr_t attr; + int t1 = 1, t2 = 2, i = 0; + + timeout = 0; + conn_accepted = 0; + + pthread_mutex_init(&count_mutex, NULL); + pthread_cond_init (&count_threshold_cv, NULL); + + pthread_attr_init(&attr); + pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE); + + pthread_create(&threads[0], &attr, ticker, &t1); + pthread_create(&threads[1], &attr, accepter, &t2); + + + for( i = 0; i < NUM_THREADS; i++ ) { + if( pthread_join(threads[i], NULL) != 0 ) { + printf("Cannot wait thread"); + return -1; + } + } + + pthread_attr_destroy(&attr); + pthread_mutex_destroy(&count_mutex); + + return 0; +} + diff --git a/pool/shard004/C/0097657_mikmod.c b/pool/shard004/C/0097657_mikmod.c new file mode 100644 index 0000000000000000000000000000000000000000..3408ba46660c66a76a1442b851f6c842342579f0 --- /dev/null +++ b/pool/shard004/C/0097657_mikmod.c @@ -0,0 +1,177 @@ +/* + * Adapted from AlsaPlayer 0.99.76 + * + * mikmod_engine.c + * Copyright (C) 1999 Paul N. Fisher + * Copyright (C) 2002 Andy Lo A Foe + * + * 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 "ip.h" +#include "xmalloc.h" +#include +#include "debug.h" +#include "comment.h" + +struct mik_private { + MODULE *file; +}; + +static int mikmod_init(void) +{ + static int inited = 0; + + if (inited) + return 1; + + MikMod_RegisterAllDrivers(); + MikMod_RegisterAllLoaders(); + + md_reverb = 0; + /* we should let the user decide which one is better... */ + md_mode = DMODE_SOFT_MUSIC | DMODE_SOFT_SNDFX | DMODE_STEREO | + DMODE_16BITS | DMODE_INTERP; + + if (MikMod_Init(NULL)) { + d_print("Could not initialize mikmod, reason: %s\n", + MikMod_strerror(MikMod_errno)); + return 0; + } + + inited = 1; + return 1; +} + +static int mik_open(struct input_plugin_data *ip_data) +{ + MODULE *mf = NULL; + struct mik_private *priv; + int mi = mikmod_init(); + + if (!mi) + return -IP_ERROR_INTERNAL; + + mf = Player_Load(ip_data->filename, 255, 0); + + if (!mf) + return -IP_ERROR_ERRNO; + + priv = xnew(struct mik_private, 1); + priv->file = mf; + + ip_data->private = priv; + ip_data->sf = sf_bits(16) | sf_rate(44100) | sf_channels(2) | sf_signed(1); +#ifdef WORDS_BIGENDIAN + ip_data->sf |= sf_bigendian(1); +#endif + channel_map_init_stereo(ip_data->channel_map); + return 0; +} + +static int mik_close(struct input_plugin_data *ip_data) +{ + struct mik_private *priv = ip_data->private; + + Player_Stop(); + Player_Free(priv->file); + free(ip_data->private); + ip_data->private = NULL; + return 0; +} + +static int mik_read(struct input_plugin_data *ip_data, char *buffer, int count) +{ + int length; + struct mik_private *priv = ip_data->private; + + if (!Player_Active()) + Player_Start(priv->file); + + if (!Player_Active()) + return 0; + + length = VC_WriteBytes(buffer, count); + + return length; +} + +static int mik_seek(struct input_plugin_data *ip_data, double offset) +{ + /* cannot seek in modules properly */ + return -IP_ERROR_FUNCTION_NOT_SUPPORTED; +} + +static int mik_read_comments(struct input_plugin_data *ip_data, struct keyval **comments) +{ + struct mik_private *priv = ip_data->private; + GROWING_KEYVALS(c); + const char *val; + + val = priv->file->songname; + if (val && val[0]) + comments_add_const(&c, "title", val); + + val = priv->file->comment; + if (val && val[0]) + comments_add_const(&c, "comment", val); + + keyvals_terminate(&c); + *comments = c.keyvals; + return 0; +} + +static int mik_duration(struct input_plugin_data *ip_data) +{ + return -IP_ERROR_FUNCTION_NOT_SUPPORTED; +} + +static long mik_bitrate(struct input_plugin_data *ip_data) +{ + return -IP_ERROR_FUNCTION_NOT_SUPPORTED; +} + +static char *mik_codec(struct input_plugin_data *ip_data) +{ + struct mik_private *priv = ip_data->private; + const char *codec = priv->file->modtype; + return (codec && codec[0]) ? xstrdup(codec) : NULL; +} + +static char *mik_codec_profile(struct input_plugin_data *ip_data) +{ + return NULL; +} + +const struct input_plugin_ops ip_ops = { + .open = mik_open, + .close = mik_close, + .read = mik_read, + .seek = mik_seek, + .read_comments = mik_read_comments, + .duration = mik_duration, + .bitrate = mik_bitrate, + .bitrate_current = mik_bitrate, + .codec = mik_codec, + .codec_profile = mik_codec_profile +}; + +const int ip_priority = 40; +const char * const ip_extensions[] = { + "mod", "s3m", "xm", "it", "669", "amf", "dsm", + "far", "med", "mtm", "stm", "ult", + NULL +}; +const char * const ip_mime_types[] = { NULL }; +const char * const ip_options[] = { NULL }; diff --git a/pool/shard004/C/0097659_s3c2440-cpufreq.c b/pool/shard004/C/0097659_s3c2440-cpufreq.c new file mode 100644 index 0000000000000000000000000000000000000000..5799b9fbb07e79e07920de74ba9e71654f4c5190 --- /dev/null +++ b/pool/shard004/C/0097659_s3c2440-cpufreq.c @@ -0,0 +1,290 @@ +/* linux/arch/arm/plat-s3c24xx/s3c2440-cpufreq.c + * + * Copyright (c) 2006-2009 Simtec Electronics + * http://armlinux.simtec.co.uk/ + * Ben Dooks + * Vincent Sanders + * + * S3C2440/S3C2442 CPU Frequency scaling + * + * 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 + +static struct clk *xtal; +static struct clk *fclk; +static struct clk *hclk; +static struct clk *armclk; + + +static inline int within_khz(unsigned long a, unsigned long b) +{ + long diff = a - b; + + return (diff >= -1000 && diff <= 1000); +} + +int s3c2440_cpufreq_calcdivs(struct s3c_cpufreq_config *cfg) +{ + unsigned int hdiv, pdiv; + unsigned long hclk, fclk, armclk; + unsigned long hclk_max; + + fclk = cfg->freq.fclk; + armclk = cfg->freq.armclk; + hclk_max = cfg->max.hclk; + + s3c_freq_dbg("%s: fclk is %lu, armclk %lu, max hclk %lu\n", + __func__, fclk, armclk, hclk_max); + + if (armclk > fclk) { + printk(KERN_WARNING "%s: armclk > fclk\n", __func__); + armclk = fclk; + } + + + if (armclk < fclk && armclk < hclk_max) + hclk_max = armclk; + + for (hdiv = 1; hdiv < 9; hdiv++) { + if (hdiv == 5 || hdiv == 7) + hdiv++; + + hclk = (fclk / hdiv); + if (hclk <= hclk_max || within_khz(hclk, hclk_max)) + break; + } + + s3c_freq_dbg("%s: hclk %lu, div %d\n", __func__, hclk, hdiv); + + if (hdiv > 8) + goto invalid; + + pdiv = (hclk > cfg->max.pclk) ? 2 : 1; + + if ((hclk / pdiv) > cfg->max.pclk) + pdiv++; + + s3c_freq_dbg("%s: pdiv %d\n", __func__, pdiv); + + if (pdiv > 2) + goto invalid; + + pdiv *= hdiv; + + + + if (armclk < hclk) + armclk = hclk; + + if (armclk < fclk) { + cfg->divs.dvs = 1; + armclk = hclk; + } else + cfg->divs.dvs = 0; + + cfg->freq.armclk = armclk; + + + + cfg->divs.h_divisor = hdiv; + cfg->divs.p_divisor = pdiv; + + return 0; + + invalid: + return -EINVAL; +} + +#define CAMDIVN_HCLK_HALF (S3C2440_CAMDIVN_HCLK3_HALF | \ + S3C2440_CAMDIVN_HCLK4_HALF) + +static void s3c2440_cpufreq_setdivs(struct s3c_cpufreq_config *cfg) +{ + unsigned long clkdiv, camdiv; + + s3c_freq_dbg("%s: divsiors: h=%d, p=%d\n", __func__, + cfg->divs.h_divisor, cfg->divs.p_divisor); + + clkdiv = __raw_readl(S3C2410_CLKDIVN); + camdiv = __raw_readl(S3C2440_CAMDIVN); + + clkdiv &= ~(S3C2440_CLKDIVN_HDIVN_MASK | S3C2440_CLKDIVN_PDIVN); + camdiv &= ~CAMDIVN_HCLK_HALF; + + switch (cfg->divs.h_divisor) { + case 1: + clkdiv |= S3C2440_CLKDIVN_HDIVN_1; + break; + + case 2: + clkdiv |= S3C2440_CLKDIVN_HDIVN_2; + break; + + case 6: + camdiv |= S3C2440_CAMDIVN_HCLK3_HALF; + case 3: + clkdiv |= S3C2440_CLKDIVN_HDIVN_3_6; + break; + + case 8: + camdiv |= S3C2440_CAMDIVN_HCLK4_HALF; + case 4: + clkdiv |= S3C2440_CLKDIVN_HDIVN_4_8; + break; + + default: + BUG(); + } + + if (cfg->divs.p_divisor != cfg->divs.h_divisor) + clkdiv |= S3C2440_CLKDIVN_PDIVN; + + + + + __raw_writel(camdiv | CAMDIVN_HCLK_HALF, S3C2440_CAMDIVN); + __raw_writel(clkdiv, S3C2410_CLKDIVN); + + ndelay(20); + __raw_writel(camdiv, S3C2440_CAMDIVN); + + clk_set_parent(armclk, cfg->divs.dvs ? hclk : fclk); +} + +static int run_freq_for(unsigned long max_hclk, unsigned long fclk, + int *divs, + struct cpufreq_frequency_table *table, + size_t table_size) +{ + unsigned long freq; + int index = 0; + int div; + + for (div = *divs; div > 0; div = *divs++) { + freq = fclk / div; + + if (freq > max_hclk && div != 1) + continue; + + freq /= 1000; + index = s3c_cpufreq_addfreq(table, index, table_size, freq); + if (index < 0) + break; + } + + return index; +} + +static int hclk_divs[] = { 1, 2, 3, 4, 6, 8, -1 }; + +static int s3c2440_cpufreq_calctable(struct s3c_cpufreq_config *cfg, + struct cpufreq_frequency_table *table, + size_t table_size) +{ + int ret; + + WARN_ON(cfg->info == NULL); + WARN_ON(cfg->board == NULL); + + ret = run_freq_for(cfg->info->max.hclk, + cfg->info->max.fclk, + hclk_divs, + table, table_size); + + s3c_freq_dbg("%s: returning %d\n", __func__, ret); + + return ret; +} + +struct s3c_cpufreq_info s3c2440_cpufreq_info = { + .max = { + .fclk = 400000000, + .hclk = 133333333, + .pclk = 66666666, + }, + + .locktime_m = 300, + .locktime_u = 300, + .locktime_bits = 16, + + .name = "s3c244x", + .calc_iotiming = s3c2410_iotiming_calc, + .set_iotiming = s3c2410_iotiming_set, + .get_iotiming = s3c2410_iotiming_get, + .set_fvco = s3c2410_set_fvco, + + .set_refresh = s3c2410_cpufreq_setrefresh, + .set_divs = s3c2440_cpufreq_setdivs, + .calc_divs = s3c2440_cpufreq_calcdivs, + .calc_freqtable = s3c2440_cpufreq_calctable, + + .resume_clocks = s3c244x_setup_clocks, + + .debug_io_show = s3c_cpufreq_debugfs_call(s3c2410_iotiming_debugfs), +}; + +static int s3c2440_cpufreq_add(struct device *dev, + struct subsys_interface *sif) +{ + xtal = s3c_cpufreq_clk_get(NULL, "xtal"); + hclk = s3c_cpufreq_clk_get(NULL, "hclk"); + fclk = s3c_cpufreq_clk_get(NULL, "fclk"); + armclk = s3c_cpufreq_clk_get(NULL, "armclk"); + + if (IS_ERR(xtal) || IS_ERR(hclk) || IS_ERR(fclk) || IS_ERR(armclk)) { + printk(KERN_ERR "%s: failed to get clocks\n", __func__); + return -ENOENT; + } + + return s3c_cpufreq_register(&s3c2440_cpufreq_info); +} + +static struct subsys_interface s3c2440_cpufreq_interface = { + .name = "s3c2440_cpufreq", + .subsys = &s3c2440_subsys, + .add_dev = s3c2440_cpufreq_add, +}; + +static int s3c2440_cpufreq_init(void) +{ + return subsys_interface_register(&s3c2440_cpufreq_interface); +} + +subsys_initcall(s3c2440_cpufreq_init); + +static struct subsys_interface s3c2442_cpufreq_interface = { + .name = "s3c2442_cpufreq", + .subsys = &s3c2442_subsys, + .add_dev = s3c2440_cpufreq_add, +}; + +static int s3c2442_cpufreq_init(void) +{ + return subsys_interface_register(&s3c2442_cpufreq_interface); +} + +subsys_initcall(s3c2442_cpufreq_init); diff --git a/pool/shard004/C/0097669_ADC.c b/pool/shard004/C/0097669_ADC.c new file mode 100644 index 0000000000000000000000000000000000000000..d49b9dac0277d89e17e06586f9951993deb1fd4a --- /dev/null +++ b/pool/shard004/C/0097669_ADC.c @@ -0,0 +1,86 @@ +#include "ADC.h" +#include "I2C.h" +#define READ_AN0 0x00 +#define READ_AN1 0x00 +#define READ_AN2 0x00 +#define READ_AN3 0x00 +#define CONFIG_AN0 0x4483 +#define CONFIG_AN1 0x5483 +#define CONFIG_AN2 0x6483 +#define CONFIG_AN3 0x7483 + +#define ADS1015_ADDR 0b1001000 + + + +int readADC(int inputNum){ + char d[3]; + int returnable; + char reading[2]; + switch(inputNum){ + case 0: + //Read the I2C + d[0]=READ_AN0; + i2c_Write(ADS1015_ADDR, 1, d, 1); + i2c_Write(ADS1015_ADDR, 0, reading, 2); + //Make 2x (8bits) -> 16Bits + returnable=(reading[0]&0x00FF) << 8; + returnable=returnable|(reading[1]&0x00FF); + returnable=(returnable&0x0FFF)>>4; + //Setup ADC for Next Channel + d[0]=0x01; + d[1]=(CONFIG_AN1&0xFF00)>>8; + d[2]=(CONFIG_AN1&0x00FF)>>0; + i2c_Write(ADS1015_ADDR, 1, d, 3); + break; + case 1: + //Read the I2C + d[0]=READ_AN1; + i2c_Write(ADS1015_ADDR, 1, d, 1); + i2c_Write(ADS1015_ADDR, 0, reading, 2); + //Make 2x (8bits) -> 16Bits + returnable=(reading[0]&0x00FF) << 8; + returnable=returnable|(reading[1]&0x00FF); + returnable=(returnable&0x0FFF)>>4; + //Setup ADC for Next Channel + d[0]=0x01; + d[1]=(CONFIG_AN2&0xFF00)>>8; + d[2]=(CONFIG_AN2&0x00FF)>>0; + i2c_Write(ADS1015_ADDR, 1, d, 3); + break; + case 2: + //Read the I2C + d[0]=READ_AN2; + i2c_Write(ADS1015_ADDR, 1, d, 1); + i2c_Write(ADS1015_ADDR, 0, reading, 2); + //Make 2x (8bits) -> 16Bits + returnable=(reading[0]&0x00FF) << 8; + returnable=returnable|(reading[1]&0x00FF); + returnable=(returnable&0x0FFF)>>4; + //Setup ADC for Next Channel + d[0]=0x01; + d[1]=(CONFIG_AN3&0xFF00)>>8; + d[2]=(CONFIG_AN3&0x00FF)>>0; + i2c_Write(ADS1015_ADDR, 1, d, 3); + break; + case 3: + //Read the I2C + d[0]=READ_AN3; + i2c_Write(ADS1015_ADDR, 1, d, 1); + i2c_Write(ADS1015_ADDR, 0, reading, 2); + //Make 2x (8bits) -> 16Bits + returnable=(reading[0]&0x00FF) << 8; + returnable=returnable|(reading[1]&0x00FF); + returnable=(returnable&0x0FFF)>>4; + //Setup ADC for Next Channel + d[0]=0x01; + d[1]=(CONFIG_AN0&0xFF00)>>8; + d[2]=(CONFIG_AN0&0x00FF)>>0; + i2c_Write(ADS1015_ADDR, 1, d, 3); + break; + + + } + returnable=(int)((3300.0/4095.0)*returnable); + return returnable; +} \ No newline at end of file diff --git a/pool/shard004/C/0097670_trace.c b/pool/shard004/C/0097670_trace.c new file mode 100644 index 0000000000000000000000000000000000000000..2ace4cbadc5fe36eab81820fc3b44e9312b90874 --- /dev/null +++ b/pool/shard004/C/0097670_trace.c @@ -0,0 +1,200 @@ +/* + * f2fs IO tracer + * + * Copyright (c) 2014 Motorola Mobility + * Copyright (c) 2014 Jaegeuk 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 +#include +#include + +#include "f2fs.h" +#include "trace.h" + +static RADIX_TREE(pids, GFP_ATOMIC); +static spinlock_t pids_lock; +static struct last_io_info last_io; + +static inline void __print_last_io(void) +{ + if (!last_io.len) + { + return; + } + + trace_printk("%3x:%3x %4x %-16s %2x %5x %5x %12x %4x\n", + last_io.major, last_io.minor, + last_io.pid, "----------------", + last_io.type, + last_io.fio.op, last_io.fio.op_flags, + last_io.fio.new_blkaddr, + last_io.len); + memset(&last_io, 0, sizeof(last_io)); +} + +static int __file_type(struct inode *inode, pid_t pid) +{ + if (f2fs_is_atomic_file(inode)) + { + return __ATOMIC_FILE; + } + else if (f2fs_is_volatile_file(inode)) + { + return __VOLATILE_FILE; + } + else if (S_ISDIR(inode->i_mode)) + { + return __DIR_FILE; + } + else if (inode->i_ino == F2FS_NODE_INO(F2FS_I_SB(inode))) + { + return __NODE_FILE; + } + else if (inode->i_ino == F2FS_META_INO(F2FS_I_SB(inode))) + { + return __META_FILE; + } + else if (pid) + { + return __NORMAL_FILE; + } + else + { + return __MISC_FILE; + } +} + +void f2fs_trace_pid(struct page *page) +{ + struct inode *inode = page->mapping->host; + pid_t pid = task_pid_nr(current); + void *p; + + page->private = pid; + + if (radix_tree_preload(GFP_NOFS)) + { + return; + } + + spin_lock(&pids_lock); + p = radix_tree_lookup(&pids, pid); + + if (p == current) + { + goto out; + } + + if (p) + { + radix_tree_delete(&pids, pid); + } + + f2fs_radix_tree_insert(&pids, pid, current); + + trace_printk("%3x:%3x %4x %-16s\n", + MAJOR(inode->i_sb->s_dev), MINOR(inode->i_sb->s_dev), + pid, current->comm); +out: + spin_unlock(&pids_lock); + radix_tree_preload_end(); +} + +void f2fs_trace_ios(struct f2fs_io_info *fio, int flush) +{ + struct inode *inode; + pid_t pid; + int major, minor; + + if (flush) + { + __print_last_io(); + return; + } + + inode = fio->page->mapping->host; + pid = page_private(fio->page); + + major = MAJOR(inode->i_sb->s_dev); + minor = MINOR(inode->i_sb->s_dev); + + if (last_io.major == major && last_io.minor == minor && + last_io.pid == pid && + last_io.type == __file_type(inode, pid) && + last_io.fio.op == fio->op && + last_io.fio.op_flags == fio->op_flags && + last_io.fio.new_blkaddr + last_io.len == + fio->new_blkaddr) + { + last_io.len++; + return; + } + + __print_last_io(); + + last_io.major = major; + last_io.minor = minor; + last_io.pid = pid; + last_io.type = __file_type(inode, pid); + last_io.fio = *fio; + last_io.len = 1; + return; +} + +void f2fs_build_trace_ios(void) +{ + spin_lock_init(&pids_lock); +} + +#define PIDVEC_SIZE 128 +static unsigned int gang_lookup_pids(pid_t *results, unsigned long first_index, + unsigned int max_items) +{ + struct radix_tree_iter iter; + void **slot; + unsigned int ret = 0; + + if (unlikely(!max_items)) + { + return 0; + } + + radix_tree_for_each_slot(slot, &pids, &iter, first_index) + { + results[ret] = iter.index; + + if (++ret == PIDVEC_SIZE) + { + break; + } + } + return ret; +} + +void f2fs_destroy_trace_ios(void) +{ + pid_t pid[PIDVEC_SIZE]; + pid_t next_pid = 0; + unsigned int found; + + spin_lock(&pids_lock); + + while ((found = gang_lookup_pids(pid, next_pid, PIDVEC_SIZE))) + { + unsigned idx; + + next_pid = pid[found - 1] + 1; + + for (idx = 0; idx < found; idx++) + { + radix_tree_delete(&pids, pid[idx]); + } + } + + spin_unlock(&pids_lock); +} diff --git a/pool/shard004/C/0097674_hw_hisuite.c b/pool/shard004/C/0097674_hw_hisuite.c new file mode 100644 index 0000000000000000000000000000000000000000..e3ee5a04ffd8731b08ea442d7d4f960f5d302944 --- /dev/null +++ b/pool/shard004/C/0097674_hw_hisuite.c @@ -0,0 +1,32 @@ +/* + * huawei Hisuite mode usb function + * 1. Setting APP set this state; + * 2. PC Hisuite get this state; + * 3. If it is hisuite mode, PC Hisuite will autorun. + */ + +static int suitestate = 0xff; + +static ssize_t suitestate_show(struct device *dev, struct device_attribute *attr, char *buf) +{ + return sprintf(buf, "%d\n", suitestate); +} +static ssize_t suitestate_store(struct device *dev, struct device_attribute *attr, const char *buf, size_t size) +{ + int value; + if(sscanf(buf, "%d", &value) == 1) + { + suitestate = value; + return size; + } + return -1; +} + +static DEVICE_ATTR(suitestate, S_IRUGO | S_IWUSR, suitestate_show, suitestate_store); + +int do_get_suitestate(struct fsg_common *common, struct fsg_buffhd *bh) +{ + u8 *buf = (u8* )bh->buf; + buf[0] = (u8)(suitestate&0xff); + return 1; +} diff --git a/pool/shard004/C/0097677_32-equ_nr.c b/pool/shard004/C/0097677_32-equ_nr.c new file mode 100644 index 0000000000000000000000000000000000000000..d9b909546e4c5e1551ad1cf0d6d4e544d0b9c824 --- /dev/null +++ b/pool/shard004/C/0097677_32-equ_nr.c @@ -0,0 +1,52 @@ +// PARAM: --set ana.activated[+] "'var_eq'" --set ana.activated[+] "'symb_locks'" --set ana.activated[+] "'region'" +// Copy of 06/11 with region enabled +extern int __VERIFIER_nondet_int(); + +#include +#include + +struct q { int x; int y; }; +struct s { + int datum; + struct q inside; + pthread_mutex_t mutex; +} A, B; + +void *t_fun(void *arg) { + pthread_mutex_lock(&A.mutex); + A.datum = 5; // NORACE + pthread_mutex_lock(&A.mutex); + return NULL; +} + +int main () { + int x = __VERIFIER_nondet_int(); + pthread_t id; + + // struct s *s = malloc(sizeof(struct s)); + struct s *s; + //struct q *q; + int *d; + + pthread_mutex_t *m; + + if (x) { + s = &A; + x++; + } else { + s = &B; + x++; + } + + //q = &s->inside; + m = &s->mutex; + d = &s->datum; + + pthread_create(&id,NULL,t_fun,NULL); + + pthread_mutex_lock(m); + *d = 8; // NORACE + pthread_mutex_unlock(m); + + return 0; +} diff --git a/pool/shard004/C/0097702_lua.c b/pool/shard004/C/0097702_lua.c new file mode 100644 index 0000000000000000000000000000000000000000..ee860cbeb14bcd5f5f6021dd153bbd4c7c36c292 --- /dev/null +++ b/pool/shard004/C/0097702_lua.c @@ -0,0 +1,186 @@ +/*************************************************************************** + * Copyright (C) 2012~2012 by CSSlayer * + * wengxt@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., * + * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. * + ***************************************************************************/ + +#include "fcitx/fcitx.h" +#include "fcitx/candidate.h" +#include "fcitx/instance.h" +#include "fcitx/module.h" +#include "fcitx/hook.h" +#include "fcitx-utils/log.h" +#include "fcitx-config/xdg.h" + +#include "luamod.h" +#include "luawrap.h" + +static void *LuaCreate(FcitxInstance *instance); +static void LuaReloadConfig(void *arg); +DECLARE_ADDFUNCTIONS(Lua) + +FCITX_DEFINE_PLUGIN(fcitx_lua, module, FcitxModule) = { + LuaCreate, + NULL, + NULL, + NULL, + LuaReloadConfig +}; + +static int +LoadLuaConfig(LuaModule *luamodule) +{ + int count = 0; + FcitxStringHashSet *sset = FcitxXDGGetFiles("lua", NULL, ".lua"); + FcitxStringHashSet *str; + for (str = sset; str != NULL;) { + FcitxStringHashSet *tmp = str->hh.next; + char *path; + FILE *f = FcitxXDGGetFileWithPrefix("lua", str->name, "r", &path); + if (f && path) { + if (LoadExtension(luamodule, path)) { + FcitxLog(INFO, "lua load extension file:%s", path); + ++count; + } else { + FcitxLog(ERROR, "LoadExtension() failed"); + } + } + if (f) { + fclose(f); + } + if (path) { + free(path); + } + HASH_DEL(sset, str); + free(str->name); + free(str); + str = tmp; + } + return count; +} + +static INPUT_RETURN_VALUE +LuaGetCandWord(void *arg, FcitxCandidateWord *candWord) +{ + FCITX_UNUSED(arg); + LuaModule *luamodule = (LuaModule*)candWord->owner; + FcitxInputState *input = FcitxInstanceGetInputState(GetFcitx(luamodule)); + strncpy(FcitxInputStateGetOutputString(input), + candWord->strWord, MAX_USER_INPUT); + return IRV_COMMIT_STRING; +} + +static void +LuaCallCommand(LuaModule *luamodule, const char *input, + FcitxCandidateWordCommitCallback callback, void *owner) +{ + UT_array *result = InputCommand(luamodule, input); + if (result) { + FcitxInputState *input = FcitxInstanceGetInputState(GetFcitx(luamodule)); + LuaResultItem *p = NULL; + while ((p = (LuaResultItem *)utarray_next(result, p))) { + FcitxCandidateWord candWord; + if (callback && owner) { + candWord.callback = callback; + candWord.owner = owner; + } else { + candWord.callback = LuaGetCandWord; + candWord.owner = luamodule; + } + candWord.priv = p->help ? strdup(p->help) : NULL; + if (p->help || p->tip) { + fcitx_utils_alloc_cat_str(candWord.strExtra, " ", p->help, + p->help && p->tip ? " " : "", + p->tip); + } else { + candWord.strExtra = NULL; + } + candWord.strWord = strdup(p->result); + candWord.wordType = MSG_TIPS; + candWord.extraType = MSG_CODE; + FcitxCandidateWordAppend(FcitxInputStateGetCandidateList(input), + &candWord); + } + utarray_free(result); + } +} + +void +AddToCandList(LuaModule *luamodule, const char *in, const char *out) +{ + FCITX_UNUSED(in); + FcitxCandidateWord candWord; + candWord.callback = LuaGetCandWord; + candWord.owner = luamodule; + candWord.priv = NULL; + candWord.wordType = MSG_TIPS; + candWord.strExtra = NULL; + candWord.strWord = strdup(out); + + FcitxInputState* input = FcitxInstanceGetInputState(GetFcitx(luamodule)); + FcitxCandidateWordList* candList = FcitxInputStateGetCandidateList(input); + FcitxCandidateWordInsert(candList, &candWord, 0); +} + +void +LuaUpdateCandidateWordHookCallback(void *arg) +{ + LuaModule *luamodule = (LuaModule *)arg; + FcitxInputState* input = FcitxInstanceGetInputState(GetFcitx(luamodule)); + char *text = FcitxInputStateGetRawInputBuffer(input); + UT_array *result = InputTrigger(luamodule, text); + if (result) { + LuaResultItem *p = NULL; + while ((p = (LuaResultItem*)utarray_next(result, p))) { + AddToCandList(luamodule, text, p->result); + } + utarray_free(result); + } +} + +void* +LuaCreate(FcitxInstance* instance) +{ + LuaModule *luamodule = LuaModuleAlloc(instance); + if (luamodule == NULL) { + FcitxLog(ERROR, "LuaModule alloc failed"); + goto err; + } + LoadLuaConfig(luamodule); + + FcitxIMEventHook hook = {.arg = luamodule, + .func = LuaUpdateCandidateWordHookCallback}; + + FcitxInstanceRegisterUpdateCandidateWordHook(instance, hook); + + FcitxLuaAddFunctions(instance); + return luamodule; +err: + if (luamodule) { + LuaModuleFree(luamodule); + } + return NULL; +} + +void LuaReloadConfig(void* arg) +{ + LuaModule* luamodule = arg; + UnloadAllExtension(luamodule); + LoadLuaConfig(luamodule); +} + +#include "fcitx-lua-addfunctions.h" diff --git a/pool/shard004/C/0097713_CWE675_Duplicate_Operations_on_Resource__open_22a.c b/pool/shard004/C/0097713_CWE675_Duplicate_Operations_on_Resource__open_22a.c new file mode 100644 index 0000000000000000000000000000000000000000..fd5a5aa09caef8cffc10163ee755cf53d0ae9379 --- /dev/null +++ b/pool/shard004/C/0097713_CWE675_Duplicate_Operations_on_Resource__open_22a.c @@ -0,0 +1,130 @@ +/* TEMPLATE GENERATED TESTCASE FILE +Filename: CWE675_Duplicate_Operations_on_Resource__open_22a.c +Label Definition File: CWE675_Duplicate_Operations_on_Resource__open.label.xml +Template File: sources-sinks-22a.tmpl.c +*/ +/* + * @description + * CWE: 675 Duplicate Operations on Resource + * BadSource: Open and close a file using open() and close() + * GoodSource: Open a file using open() + * Sinks: + * GoodSink: Do nothing + * BadSink : Close the file + * Flow Variant: 22 Control flow: Flow controlled by value of a global variable. Sink functions are in a separate file from sources. + * + * */ + +#include "std_testcase.h" + +#ifdef _WIN32 +# define OPEN _open +# define CLOSE _close +#else +#include +# define OPEN open +# define CLOSE close +#endif + +#ifndef OMITBAD + +/* The global variable below is used to drive control flow in the sink function */ +int CWE675_Duplicate_Operations_on_Resource__open_22_badGlobal = 0; + +void CWE675_Duplicate_Operations_on_Resource__open_22_badSink(int data); + +void CWE675_Duplicate_Operations_on_Resource__open_22_bad() +{ + int data; + data = -1; /* Initialize data */ + data = OPEN("BadSource_open.txt", O_RDWR|O_CREAT, S_IREAD|S_IWRITE); + /* POTENTIAL FLAW: Close the file in the source */ + CLOSE(data); + CWE675_Duplicate_Operations_on_Resource__open_22_badGlobal = 1; /* true */ + CWE675_Duplicate_Operations_on_Resource__open_22_badSink(data); +} + +#endif /* OMITBAD */ + +#ifndef OMITGOOD + +/* The global variables below are used to drive control flow in the sink functions. */ +int CWE675_Duplicate_Operations_on_Resource__open_22_goodB2G1Global = 0; +int CWE675_Duplicate_Operations_on_Resource__open_22_goodB2G2Global = 0; +int CWE675_Duplicate_Operations_on_Resource__open_22_goodG2BGlobal = 0; + +/* goodB2G1() - use badsource and goodsink by setting the static variable to false instead of true */ +void CWE675_Duplicate_Operations_on_Resource__open_22_goodB2G1Sink(int data); + +static void goodB2G1() +{ + int data; + data = -1; /* Initialize data */ + data = OPEN("BadSource_open.txt", O_RDWR|O_CREAT, S_IREAD|S_IWRITE); + /* POTENTIAL FLAW: Close the file in the source */ + CLOSE(data); + CWE675_Duplicate_Operations_on_Resource__open_22_goodB2G1Global = 0; /* false */ + CWE675_Duplicate_Operations_on_Resource__open_22_goodB2G1Sink(data); +} + +/* goodB2G2() - use badsource and goodsink by reversing the blocks in the if in the sink function */ +void CWE675_Duplicate_Operations_on_Resource__open_22_goodB2G2Sink(int data); + +static void goodB2G2() +{ + int data; + data = -1; /* Initialize data */ + data = OPEN("BadSource_open.txt", O_RDWR|O_CREAT, S_IREAD|S_IWRITE); + /* POTENTIAL FLAW: Close the file in the source */ + CLOSE(data); + CWE675_Duplicate_Operations_on_Resource__open_22_goodB2G2Global = 1; /* true */ + CWE675_Duplicate_Operations_on_Resource__open_22_goodB2G2Sink(data); +} + +/* goodG2B() - use goodsource and badsink */ +void CWE675_Duplicate_Operations_on_Resource__open_22_goodG2BSink(int data); + +static void goodG2B() +{ + int data; + data = -1; /* Initialize data */ + /* FIX: Open, but do not close the file in the source */ + data = OPEN("GoodSource_open.txt", O_RDWR|O_CREAT, S_IREAD|S_IWRITE); + CWE675_Duplicate_Operations_on_Resource__open_22_goodG2BGlobal = 1; /* true */ + CWE675_Duplicate_Operations_on_Resource__open_22_goodG2BSink(data); +} + +void CWE675_Duplicate_Operations_on_Resource__open_22_good() +{ + goodB2G1(); + goodB2G2(); + 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()..."); + CWE675_Duplicate_Operations_on_Resource__open_22_good(); + printLine("Finished good()"); +#endif /* OMITGOOD */ +#ifndef OMITBAD + printLine("Calling bad()..."); + CWE675_Duplicate_Operations_on_Resource__open_22_bad(); + printLine("Finished bad()"); +#endif /* OMITBAD */ + return 0; +} + +#endif diff --git a/pool/shard004/C/0097714_IoLibMsc.c b/pool/shard004/C/0097714_IoLibMsc.c new file mode 100644 index 0000000000000000000000000000000000000000..5abbe8ed189d390903a2a796606cb61b368748e6 --- /dev/null +++ b/pool/shard004/C/0097714_IoLibMsc.c @@ -0,0 +1,436 @@ +/*++ + +Copyright (c) 2004 - 2006, Intel Corporation. All rights reserved.
+This program and the accompanying materials +are licensed and made available under the terms and conditions of the BSD License +which accompanies this distribution. The full text of the license may be found at +http://opensource.org/licenses/bsd-license.php + +THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS, +WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED. + + +Module Name: + + IoLibMsc.c + +Abstract: + + I/O Library. This file has compiler specifics for Microsft C as there is no + ANSI C standard for doing IO. + + MSC - uses intrinsic functions and the optimize will remove the function call + overhead. + + We don't advocate putting compiler specifics in libraries or drivers but there + is no other way to make this work. + +--*/ + +#include "EdkIIGlueBase.h" + +#if _MSC_EXTENSIONS + +// +// Microsoft Visual Studio 7.1 Function Prototypes for I/O Intrinsics +// +int _inp (unsigned short port); +unsigned short _inpw (unsigned short port); +unsigned long _inpd (unsigned short port); +int _outp (unsigned short port, int databyte ); +unsigned short _outpw (unsigned short port, unsigned short dataword ); +unsigned long _outpd (unsigned short port, unsigned long dataword ); +void _ReadWriteBarrier (void); + +#pragma intrinsic(_inp) +#pragma intrinsic(_inpw) +#pragma intrinsic(_inpd) +#pragma intrinsic(_outp) +#pragma intrinsic(_outpw) +#pragma intrinsic(_outpd) +#pragma intrinsic(_ReadWriteBarrier) + +// +// _ReadWriteBarrier() forces memory reads and writes to complete at the point +// in the call. This is only a hint to the compiler and does emit code. +// In past versions of the compiler, _ReadWriteBarrier was enforced only +// locally and did not affect functions up the call tree. In Visual C++ +// 2005, _ReadWriteBarrier is enforced all the way up the call tree. +// + +/** + Reads an 8-bit I/O port. + + Reads the 8-bit I/O port specified by Port. The 8-bit read value is returned. + This function must guarantee that all I/O read and write operations are + serialized. + + If 8-bit I/O port operations are not supported, then ASSERT(). + + @param Port The I/O port to read. + + @return The value read. + +**/ +UINT8 +EFIAPI +GlueIoRead8 ( + IN UINTN Port + ) +{ + UINT8 Value; + + _ReadWriteBarrier (); + Value = (UINT8)_inp ((UINT16)Port); + _ReadWriteBarrier (); + return Value; +} + +/** + Writes an 8-bit I/O port. + + Writes the 8-bit I/O port specified by Port with the value specified by Value + and returns Value. This function must guarantee that all I/O read and write + operations are serialized. + + If 8-bit I/O port operations are not supported, then ASSERT(). + + @param Port The I/O port to write. + @param Value The value to write to the I/O port. + + @return The value written the I/O port. + +**/ +UINT8 +EFIAPI +GlueIoWrite8 ( + IN UINTN Port, + IN UINT8 Value + ) +{ + _ReadWriteBarrier (); + (UINT8)_outp ((UINT16)Port, Value); + _ReadWriteBarrier (); + return Value; +} + +/** + Reads a 16-bit I/O port. + + Reads the 16-bit I/O port specified by Port. The 16-bit read value is returned. + This function must guarantee that all I/O read and write operations are + serialized. + + If 16-bit I/O port operations are not supported, then ASSERT(). + + @param Port The I/O port to read. + + @return The value read. + +**/ +UINT16 +EFIAPI +GlueIoRead16 ( + IN UINTN Port + ) +{ + UINT16 Value; + + ASSERT ((Port & 1) == 0); + _ReadWriteBarrier (); + Value = _inpw ((UINT16)Port); + _ReadWriteBarrier (); + return Value; +} + +/** + Writes a 16-bit I/O port. + + Writes the 16-bit I/O port specified by Port with the value specified by Value + and returns Value. This function must guarantee that all I/O read and write + operations are serialized. + + If 16-bit I/O port operations are not supported, then ASSERT(). + + @param Port The I/O port to write. + @param Value The value to write to the I/O port. + + @return The value written the I/O port. + +**/ +UINT16 +EFIAPI +GlueIoWrite16 ( + IN UINTN Port, + IN UINT16 Value + ) +{ + ASSERT ((Port & 1) == 0); + _ReadWriteBarrier (); + _outpw ((UINT16)Port, Value); + _ReadWriteBarrier (); + return Value; +} + +/** + Reads a 32-bit I/O port. + + Reads the 32-bit I/O port specified by Port. The 32-bit read value is returned. + This function must guarantee that all I/O read and write operations are + serialized. + + If 32-bit I/O port operations are not supported, then ASSERT(). + + @param Port The I/O port to read. + + @return The value read. + +**/ +UINT32 +EFIAPI +GlueIoRead32 ( + IN UINTN Port + ) +{ + UINT32 Value; + + ASSERT ((Port & 3) == 0); + _ReadWriteBarrier (); + Value = _inpd ((UINT16)Port); + _ReadWriteBarrier (); + return Value; +} + +/** + Writes a 32-bit I/O port. + + Writes the 32-bit I/O port specified by Port with the value specified by Value + and returns Value. This function must guarantee that all I/O read and write + operations are serialized. + + If 32-bit I/O port operations are not supported, then ASSERT(). + + @param Port The I/O port to write. + @param Value The value to write to the I/O port. + + @return The value written the I/O port. + +**/ +UINT32 +EFIAPI +GlueIoWrite32 ( + IN UINTN Port, + IN UINT32 Value + ) +{ + ASSERT ((Port & 3) == 0); + _ReadWriteBarrier (); + _outpd ((UINT16)Port, Value); + _ReadWriteBarrier (); + return Value; +} + + +/** + Reads an 8-bit MMIO register. + + Reads the 8-bit MMIO register specified by Address. The 8-bit read value is + returned. This function must guarantee that all MMIO read and write + operations are serialized. + + If 8-bit MMIO register operations are not supported, then ASSERT(). + + @param Address The MMIO register to read. + + @return The value read. + +**/ +UINT8 +EFIAPI +MmioRead8 ( + IN UINTN Address + ) +{ + UINT8 Value; + + Value = *(volatile UINT8*)Address; + return Value; +} + +/** + Writes an 8-bit MMIO register. + + Writes the 8-bit MMIO register specified by Address with the value specified + by Value and returns Value. This function must guarantee that all MMIO read + and write operations are serialized. + + If 8-bit MMIO register operations are not supported, then ASSERT(). + + @param Address The MMIO register to write. + @param Value The value to write to the MMIO register. + +**/ +UINT8 +EFIAPI +MmioWrite8 ( + IN UINTN Address, + IN UINT8 Value + ) +{ + return *(volatile UINT8*)Address = Value; +} + +/** + Reads a 16-bit MMIO register. + + Reads the 16-bit MMIO register specified by Address. The 16-bit read value is + returned. This function must guarantee that all MMIO read and write + operations are serialized. + + If 16-bit MMIO register operations are not supported, then ASSERT(). + + @param Address The MMIO register to read. + + @return The value read. + +**/ +UINT16 +EFIAPI +MmioRead16 ( + IN UINTN Address + ) +{ + UINT16 Value; + + ASSERT ((Address & 1) == 0); + Value = *(volatile UINT16*)Address; + return Value; +} + +/** + Writes a 16-bit MMIO register. + + Writes the 16-bit MMIO register specified by Address with the value specified + by Value and returns Value. This function must guarantee that all MMIO read + and write operations are serialized. + + If 16-bit MMIO register operations are not supported, then ASSERT(). + + @param Address The MMIO register to write. + @param Value The value to write to the MMIO register. + +**/ +UINT16 +EFIAPI +MmioWrite16 ( + IN UINTN Address, + IN UINT16 Value + ) +{ + ASSERT ((Address & 1) == 0); + return *(volatile UINT16*)Address = Value; +} + +/** + Reads a 32-bit MMIO register. + + Reads the 32-bit MMIO register specified by Address. The 32-bit read value is + returned. This function must guarantee that all MMIO read and write + operations are serialized. + + If 32-bit MMIO register operations are not supported, then ASSERT(). + + @param Address The MMIO register to read. + + @return The value read. + +**/ +UINT32 +EFIAPI +MmioRead32 ( + IN UINTN Address + ) +{ + UINT32 Value; + + ASSERT ((Address & 3) == 0); + Value = *(volatile UINT32*)Address; + return Value; +} + +/** + Writes a 32-bit MMIO register. + + Writes the 32-bit MMIO register specified by Address with the value specified + by Value and returns Value. This function must guarantee that all MMIO read + and write operations are serialized. + + If 32-bit MMIO register operations are not supported, then ASSERT(). + + @param Address The MMIO register to write. + @param Value The value to write to the MMIO register. + +**/ +UINT32 +EFIAPI +MmioWrite32 ( + IN UINTN Address, + IN UINT32 Value + ) +{ + ASSERT ((Address & 3) == 0); + return *(volatile UINT32*)Address = Value; +} + +/** + Reads a 64-bit MMIO register. + + Reads the 64-bit MMIO register specified by Address. The 64-bit read value is + returned. This function must guarantee that all MMIO read and write + operations are serialized. + + If 64-bit MMIO register operations are not supported, then ASSERT(). + + @param Address The MMIO register to read. + + @return The value read. + +**/ +UINT64 +EFIAPI +MmioRead64 ( + IN UINTN Address + ) +{ + UINT64 Value; + + ASSERT ((Address & 7) == 0); + Value = *(volatile UINT64*)Address; + return Value; +} + +/** + Writes a 64-bit MMIO register. + + Writes the 64-bit MMIO register specified by Address with the value specified + by Value and returns Value. This function must guarantee that all MMIO read + and write operations are serialized. + + If 64-bit MMIO register operations are not supported, then ASSERT(). + + @param Address The MMIO register to write. + @param Value The value to write to the MMIO register. + +**/ +UINT64 +EFIAPI +MmioWrite64 ( + IN UINTN Address, + IN UINT64 Value + ) +{ + ASSERT ((Address & 7) == 0); + return *(volatile UINT64*)Address = Value; +} + +#endif diff --git a/pool/shard004/C/0097718_DMA.c b/pool/shard004/C/0097718_DMA.c new file mode 100644 index 0000000000000000000000000000000000000000..e822d9c39c0f8f81b01482ed19f4940182a795a2 --- /dev/null +++ b/pool/shard004/C/0097718_DMA.c @@ -0,0 +1,200 @@ +/* * * * * * * * * * * * * * * * * * * * * * * * * * * + * HARDWARE/DMA.C * + * * * * * * * * * * * * * * * * * * * * * * * * * * */ + +#include "DMA.H" +#include + +#include "TIMER.H" + +///#define DEBUG + +/* * * * * * * * * * * * * * * * * * * * * * * * * * * + * Declare Local Functions * + * * * * * * * * * * * * * * * * * * * * * * * * * * */ + +void _DMA_outb(uint16_t port, uint8_t data); +uint8_t _DMA_inb(uint16_t port); +error _DMA_set_Addr(uint8_t channel, uint32_t addr); +error _DMA_set_Count(uint8_t channel, uint16_t count); +error _DMA_MASK_CHAN(uint8_t channel); +error _DMA_UMASK_CHAN(uint8_t channel); +void _DMA_UMASK_ALL(bool dma); +error _DMA_MODEREG_Handle(uint8_t channel, uint8_t mode); +void _DMA_RESET_FF(bool dma); +void _DMA_RESET(bool dma); + +/* * * * * * * * * * * * * * * * * * * * * * * * * * * + * Local Variables * + * * * * * * * * * * * * * * * * * * * * * * * * * * */ + +enum _DMA_PORTS { + _DMA0_STATUS_REG = 0x8, //Status Register(read) + _DMA0_COMMAND_REG = 0x8, //Command Register(write) + _DMA0_REQUEST_REG = 0x9, //Request Register(write) + _DMA0_SINGMASK_REG = 0xa, //Single Mask Register(write) + _DMA0_MODE_REG = 0xb, //Mode Register(write) + _DMA0_CLEARBYTE_FF_REG = 0xc, //Clear Byte Pointer Flip-Flop (write) + _DMA0_TEMP_REG = 0xd, //Intermediate Register(read) + _DMA0_MASTER_CLEAR_REG = 0xd, //Master Clear(write) + _DMA0_CLEAR_MASK_REG = 0xe, //Clear Mask Register(write) + _DMA0_MASK_REG = 0xf, //Write Mask Register(write) + + _DMA1_STATUS_REG = 0xd0, + _DMA1_COMMAND_REG = 0xd0, + _DMA1_REQUEST_REG = 0xd2, + _DMA1_SINGMASK_REG = 0xd4, + _DMA1_MODE_REG = 0xd6, + _DMA1_CLEARBYTE_FF_REG = 0xd8, + _DMA1_INTER_REG = 0xda, + _DMA1_MASTER_CLEAR_REG = 0xda, + _DMA1_UNMASK_ALL_REG = 0xdc, + _DMA1_MASK_REG = 0xde +}; + +uint16_t _DMA_ADDR_REG[8] = { 0x0, 0x2, 0x4, 0x6, 0xC0, 0xC4, 0xC8, 0xCC }; +uint16_t _DMA_COUNT_REG[8] = { 0x1, 0x3, 0x5, 0x7, 0xC2, 0xC6, 0xCA, 0xCE }; +uint16_t _DMA_EXT_PAGE[8] = { 0x87, 0x83, 0x81, 0x82, 0x8F, 0x8B, 0x89, 0x8A }; //ASSUMING AT TYPE SYSTEM + +enum _DMA_COMMAND_REG_MASK { + _COMMAND_REG_MASK_MEMTOMEM = 1, + _COMMAND_REG_MASK_CHAN0ADDRHOLD = 2, + _COMMAND_REG_MASK_ENABLE = 4, + _COMMAND_REG_MASK_TIMING = 8, + _COMMAND_REG_MASK_PRIORITY = 0x10, + _COMMAND_REG_MASK_WRITESEL = 0x20, + _COMMAND_REG_MASK_DREQ = 0x40, + _COMMAND_REG_MASK_DACK = 0x80 +}; + +enum _DMA_MODE_REG_MASK { + _DMA_MODE_SEL = 3, + _DMA_MODE_TRA = 0xc, + _DMA_MODE_SELF_TEST = 0, + _DMA_MODE_READ_TRANSFER =4, + _DMA_MODE_WRITE_TRANSFER = 8, + _DMA_MODE_AUTO = 0x10, + _DMA_MODE_IDEC = 0x20, + _DMA_MODE = 0xc0, + _DMA_MODE_TRANSFER_ON_DEMAND= 0, + _DMA_MODE_TRANSFER_SINGLE = 0x40, + _DMA_MODE_TRANSFER_BLOCK = 0x80, + _DMA_MODE_TRANSFER_CASCADE = 0xC0 +}; + +/* * * * * * * * * * * * * * * * * * * * * * * * * * * + * Local Functions * + * * * * * * * * * * * * * * * * * * * * * * * * * * */ + +void _DMA_outb(uint16_t port, uint8_t data) +{ +#ifdef DEBUG + txf(1, "_DMA_outb(0x%x, 0x%x)\n\r", port, data); +#endif + outb(port, data); +} + +uint8_t _DMA_inb(uint16_t port) +{ + uint8_t data = inb(port); +#ifdef DEBUG + txf(1, "_DMA_inb(0x%x) = 0x%x\n\r", port, data); +#endif + return data; +} + +error _DMA_set_Addr(uint8_t channel, uint32_t addr) //Sets all address data +{ + if(channel > 7) + return ERROR_INPUT; + if(addr > 0xFF0000) + return ERROR_INPUT; + uint8_t ext_addr, high_addr, low_addr; + low_addr = (uint8_t) (addr & 0xFF); + high_addr = (uint8_t) ((addr >> 8) & 0xFF); + ext_addr = (uint8_t) ((addr >> 16) & 0xFF); + _DMA_outb(_DMA_ADDR_REG[channel], low_addr); + _DMA_outb(_DMA_ADDR_REG[channel], high_addr); + _DMA_outb(_DMA_EXT_PAGE[channel], ext_addr); + return ERROR_NONE; +} + +error _DMA_set_Count(uint8_t channel, uint16_t count) +{ + if(channel > 7) + return ERROR_INPUT; + count--; + uint8_t high_count, low_count; + low_count = (uint8_t) (count & 0xFF); + high_count = (uint8_t) ((count >> 8) & 0xFF); + _DMA_outb(_DMA_COUNT_REG[channel], low_count); + _DMA_outb(_DMA_COUNT_REG[channel], high_count); + return ERROR_NONE; +} + +error _DMA_MASK_CHAN(uint8_t channel) +{ + if(channel > 7) + return ERROR_INPUT; + bool dma = ((channel < 4) ? false : true); + uint8_t chan = ((dma) ? (uint8_t) (channel - 4) : channel); + _DMA_outb(((dma) ? _DMA1_SINGMASK_REG : _DMA0_SINGMASK_REG), (uint8_t) (1 << chan)); + return ERROR_NONE; +} + +error _DMA_UMASK_CHAN(uint8_t channel) +{ + if(channel > 7) + return ERROR_INPUT; + bool dma = ((channel < 4) ? false : true); + uint8_t chan = ((dma) ? (uint8_t) (channel - 4) : channel); + _DMA_outb(((dma) ? _DMA1_SINGMASK_REG : _DMA0_SINGMASK_REG), chan); + return ERROR_NONE; +} + +void _DMA_UMASK_ALL(bool dma) +{ + _DMA_outb(((dma) ? _DMA1_UNMASK_ALL_REG : _DMA0_CLEAR_MASK_REG), 0xFF); +} + +error _DMA_MODEREG_Handle(uint8_t channel, uint8_t mode) +{ + if(channel > 7) + return ERROR_INPUT; + bool dma = ((channel < 4) ? false : true); + uint8_t chan = ((dma) ? (uint8_t) (channel - 4) : channel); + _DMA_outb(((dma) ? _DMA1_MODE_REG : _DMA0_MODE_REG), (chan | mode)); + return ERROR_NONE; +} + +void _DMA_RESET_FF(bool dma) +{ + outb(((dma) ? _DMA1_CLEARBYTE_FF_REG : _DMA0_CLEARBYTE_FF_REG), 0xff); +} + +void _DMA_RESET(bool dma) +{ + outb(((dma) ? _DMA1_MASTER_CLEAR_REG : _DMA0_MASTER_CLEAR_REG), 0xFF); +} + +/* * * * * * * * * * * * * * * * * * * * * * * * * * * + * Public Functions * + * * * * * * * * * * * * * * * * * * * * * * * * * * */ + +error _DMA_Setup(uint8_t channel, bool write, uint32_t addr, uint16_t count) +{ + if(channel>7 || addr>0xFF0000) + return ERROR_INPUT; + error errorcode = ERROR_NONE; + if((errorcode = _DMA_MASK_CHAN(channel))) + return errorcode; + if((errorcode = _DMA_MODEREG_Handle(channel, ((write) ? 0x4A : 0x46)))) + return errorcode; + if((errorcode = _DMA_set_Addr(channel, addr))) + return errorcode; + if((_DMA_set_Count(channel, count))) + return errorcode; + if((errorcode = _DMA_UMASK_CHAN(channel))) + return errorcode; + return ERROR_NONE; +} diff --git a/pool/shard004/C/0097724_sum-of-n-1_c.c b/pool/shard004/C/0097724_sum-of-n-1_c.c new file mode 100644 index 0000000000000000000000000000000000000000..843ec3d61a62a4dd8369fc137b3e9637b484fa10 --- /dev/null +++ b/pool/shard004/C/0097724_sum-of-n-1_c.c @@ -0,0 +1,23 @@ +#include + +int main(void) +{ + int N; + scanf("%d", &N); + + int i, numArray[N]; // Define an array of four integers + + // Get inputs for the array elements + for (i = 0; i < N; i++) { + scanf("%d", &numArray[i]); + } + + // Write here the logic to add these integers: + int sum = 0; + for (i = 0; i < N; i++) { + sum += numArray[i]; + } + printf("%d\n",sum); // Print the sum + + return 0; +} \ No newline at end of file diff --git a/pool/shard004/C/0097732_stm32f0xx_hal_msp.c b/pool/shard004/C/0097732_stm32f0xx_hal_msp.c new file mode 100644 index 0000000000000000000000000000000000000000..ea45485860af9ec0d6e98af25b5b0e12b367e3f1 --- /dev/null +++ b/pool/shard004/C/0097732_stm32f0xx_hal_msp.c @@ -0,0 +1,197 @@ +/** + ****************************************************************************** + * @file SPI/SPI_FullDuplex_ComDMA/Src/stm32f0xx_msp.c + * @author MCD Application Team + * @brief HAL MSP module. + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2016 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 STM32F0xx_HAL_Examples + * @{ + */ + +/** @defgroup SPI_FullDuplex_ComDMA + * @brief HAL MSP module. + * @{ + */ + +/* Private typedef -----------------------------------------------------------*/ +/* Private define ------------------------------------------------------------*/ +/* Private macro -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +static DMA_HandleTypeDef hdma_tx; +static DMA_HandleTypeDef hdma_rx; +/* Private function prototypes -----------------------------------------------*/ +/* Private functions ---------------------------------------------------------*/ + +/** @defgroup HAL_MSP_Private_Functions + * @{ + */ + +/** + * @brief SPI MSP Initialization + * This function configures the hardware resources used in this example: + * - Peripheral's clock enable + * - Peripheral's GPIO Configuration + * - DMA configuration for transmission request by peripheral + * - NVIC configuration for DMA interrupt request enable + * @param hspi: SPI handle pointer + * @retval None + */ +void HAL_SPI_MspInit(SPI_HandleTypeDef *hspi) +{ +GPIO_InitTypeDef GPIO_InitStruct; + + if (hspi->Instance == SPIx) + { + /*##-1- Enable peripherals and GPIO Clocks #################################*/ + /* Enable GPIO TX/RX clock */ + SPIx_SCK_GPIO_CLK_ENABLE(); + SPIx_MISO_GPIO_CLK_ENABLE(); + SPIx_MOSI_GPIO_CLK_ENABLE(); + /* Enable SPI1 clock */ + SPIx_CLK_ENABLE(); + /* Enable DMA clock */ + DMAx_CLK_ENABLE(); + + /*##-2- Configure peripheral GPIO ##########################################*/ + /* SPI SCK GPIO pin configuration */ + GPIO_InitStruct.Pin = SPIx_SCK_PIN; + GPIO_InitStruct.Mode = GPIO_MODE_AF_PP; + GPIO_InitStruct.Pull = GPIO_PULLDOWN; + GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_HIGH; + GPIO_InitStruct.Alternate = SPIx_SCK_AF; + HAL_GPIO_Init(SPIx_SCK_GPIO_PORT, &GPIO_InitStruct); + + /* SPI MISO GPIO pin configuration */ + GPIO_InitStruct.Pin = SPIx_MISO_PIN; + GPIO_InitStruct.Alternate = SPIx_MISO_AF; + HAL_GPIO_Init(SPIx_MISO_GPIO_PORT, &GPIO_InitStruct); + + /* SPI MOSI GPIO pin configuration */ + GPIO_InitStruct.Pin = SPIx_MOSI_PIN; + GPIO_InitStruct.Alternate = SPIx_MOSI_AF; + HAL_GPIO_Init(SPIx_MOSI_GPIO_PORT, &GPIO_InitStruct); + + /*##-3- Configure the DMA ##################################################*/ + /* Configure the DMA handler for Transmission process */ + hdma_tx.Instance = SPIx_TX_DMA_CHANNEL; + hdma_tx.Init.Direction = DMA_MEMORY_TO_PERIPH; + hdma_tx.Init.PeriphInc = DMA_PINC_DISABLE; + hdma_tx.Init.MemInc = DMA_MINC_ENABLE; + hdma_tx.Init.PeriphDataAlignment = DMA_PDATAALIGN_HALFWORD; + hdma_tx.Init.MemDataAlignment = DMA_MDATAALIGN_HALFWORD; + hdma_tx.Init.Mode = DMA_NORMAL; + hdma_tx.Init.Priority = DMA_PRIORITY_LOW; + + HAL_DMA_Init(&hdma_tx); + + /* Associate the initialized DMA handle to the the SPI handle */ + __HAL_LINKDMA(hspi, hdmatx, hdma_tx); + + /* Configure the DMA handler for Transmission process */ + hdma_rx.Instance = SPIx_RX_DMA_CHANNEL; + + hdma_rx.Init.Direction = DMA_PERIPH_TO_MEMORY; + hdma_rx.Init.PeriphInc = DMA_PINC_DISABLE; + hdma_rx.Init.MemInc = DMA_MINC_ENABLE; + hdma_tx.Init.PeriphDataAlignment = DMA_PDATAALIGN_HALFWORD; + hdma_tx.Init.MemDataAlignment = DMA_MDATAALIGN_HALFWORD; + hdma_rx.Init.Mode = DMA_NORMAL; + hdma_rx.Init.Priority = DMA_PRIORITY_HIGH; + + HAL_DMA_Init(&hdma_rx); + + /* Associate the initialized DMA handle to the the SPI handle */ + __HAL_LINKDMA(hspi, hdmarx, hdma_rx); + + /*##-4- Configure the NVIC for DMA #########################################*/ + /* NVIC configuration for DMA transfer complete interrupt (SPI1_TX) */ + HAL_NVIC_SetPriority(SPIx_DMA_TX_IRQn, 1, 1); + HAL_NVIC_EnableIRQ(SPIx_DMA_TX_IRQn); + + /* NVIC configuration for DMA transfer complete interrupt (SPI1_RX) */ + HAL_NVIC_SetPriority(SPIx_DMA_RX_IRQn, 1, 0); + HAL_NVIC_EnableIRQ(SPIx_DMA_RX_IRQn); + } +} + +/** + * @brief SPI MSP De-Initialization + * This function frees the hardware resources used in this example: + * - Disable the Peripheral's clock + * - Revert GPIO, DMA and NVIC configuration to their default state + * @param hspi: SPI handle pointer + * @retval None + */ +void HAL_SPI_MspDeInit(SPI_HandleTypeDef *hspi) +{ + if (hspi->Instance == SPIx) + { + /*##-1- Reset peripherals ##################################################*/ + SPIx_FORCE_RESET(); + SPIx_RELEASE_RESET(); + + /*##-2- Disable peripherals and GPIO Clocks ################################*/ + /* Configure SPI SCK as alternate function */ + HAL_GPIO_DeInit(SPIx_SCK_GPIO_PORT, SPIx_SCK_PIN); + /* Configure SPI MISO as alternate function */ + HAL_GPIO_DeInit(SPIx_MISO_GPIO_PORT, SPIx_MISO_PIN); + /* Configure SPI MOSI as alternate function */ + HAL_GPIO_DeInit(SPIx_MOSI_GPIO_PORT, SPIx_MOSI_PIN); + + /*##-3- Disable the DMA ####################################################*/ + /* De-Initialize the DMA associated to transmission process */ + HAL_DMA_DeInit(&hdma_tx); + /* De-Initialize the DMA associated to reception process */ + HAL_DMA_DeInit(&hdma_rx); + + /*##-4- Disable the NVIC for DMA ###########################################*/ + HAL_NVIC_DisableIRQ(SPIx_DMA_TX_IRQn); + HAL_NVIC_DisableIRQ(SPIx_DMA_RX_IRQn); + } +} + +/** + * @} + */ + +/** + * @} + */ + +/** + * @} + */ + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/pool/shard004/C/0097736_nis_verifygroup.c b/pool/shard004/C/0097736_nis_verifygroup.c new file mode 100644 index 0000000000000000000000000000000000000000..bb043361b799b5b6c8b2b3b35594ad8923e22fce --- /dev/null +++ b/pool/shard004/C/0097736_nis_verifygroup.c @@ -0,0 +1,50 @@ +/* Copyright (c) 1997-2017 Free Software Foundation, Inc. + This file is part of the GNU C Library. + Contributed by Thorsten Kukuk , 1997. + + 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 + +nis_error +nis_verifygroup (const_nis_name group) +{ + if (group != NULL && group[0] != '\0') + { + size_t grouplen = strlen (group); + char buf[grouplen + 50]; + char leafbuf[grouplen + 2]; + char domainbuf[grouplen + 2]; + nis_result *res; + nis_error status; + char *cp, *cp2; + + cp = stpcpy (buf, nis_leaf_of_r (group, leafbuf, sizeof (leafbuf) - 1)); + cp = stpcpy (cp, ".groups_dir"); + cp2 = nis_domain_of_r (group, domainbuf, sizeof (domainbuf) - 1); + if (cp2 != NULL && cp2[0] != '\0') + { + *cp++ = '.'; + stpcpy (cp, cp2); + } + res = nis_lookup (buf, 0); + status = NIS_RES_STATUS (res); + nis_freeresult (res); + return status; + } + else + return NIS_FAIL; +} diff --git a/pool/shard004/C/0097739_borders.c b/pool/shard004/C/0097739_borders.c new file mode 100644 index 0000000000000000000000000000000000000000..c8b7957e120e4905d1bde8322e4b72b8986b041b --- /dev/null +++ b/pool/shard004/C/0097739_borders.c @@ -0,0 +1,121 @@ +/**************************************************************************** + Freeciv - Copyright (C) 2004 - The Freeciv 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 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. +****************************************************************************/ + +#ifdef HAVE_CONFIG_H +#include +#endif + +#include + +/* utility */ +#include "fcintl.h" +#include "log.h" + +/* common */ +#include "game.h" +#include "tile.h" +#include "unit.h" + +#include "borders.h" + +/************************************************************************* + Border radius sq from given border source tile. +*************************************************************************/ +int tile_border_source_radius_sq(struct tile *ptile) +{ + struct city *pcity; + int radius_sq = 0; + + if (game.info.borders == 0) { + return 0; + } + + pcity = tile_city(ptile); + + if (pcity) { + radius_sq = game.info.border_city_radius_sq; + radius_sq += pcity->size * game.info.border_size_effect; + } else { + base_type_iterate(pbase) { + if (tile_has_base(ptile, pbase) && territory_claiming_base(pbase)) { + radius_sq = pbase->border_sq; + break; + } + } base_type_iterate_end; + } + + return radius_sq; +} + +/************************************************************************* + Border source strength +*************************************************************************/ +int tile_border_source_strength(struct tile *ptile) +{ + struct city *pcity; + int strength = 0; + + if (game.info.borders == 0) { + return 0; + } + + pcity = tile_city(ptile); + + if (pcity) { + strength = pcity->size + 2; + } else { + base_type_iterate(pbase) { + if (tile_has_base(ptile, pbase) && territory_claiming_base(pbase)) { + strength = 1; + break; + } + } base_type_iterate_end; + } + + return strength; +} + +/************************************************************************* + Border source strength at tile +*************************************************************************/ +int tile_border_strength(struct tile *ptile, struct tile *source) +{ + int full_strength = tile_border_source_strength(source); + int sq_dist = sq_map_distance(ptile, source); + + if (sq_dist > 0) { + return full_strength * full_strength / sq_dist; + } else { + return FC_INFINITY; + } +} + +/************************************************************************* + Is given tile source to borders. +*************************************************************************/ +bool is_border_source(struct tile *ptile) +{ + if (tile_city(ptile)) { + return TRUE; + } + + if (tile_owner(ptile) != NULL) { + base_type_iterate(pbase) { + if (tile_has_base(ptile, pbase) && territory_claiming_base(pbase)) { + return TRUE; + } + } base_type_iterate_end; + } + + return FALSE; +} diff --git a/pool/shard004/C/0097742_env_mgdisk.c b/pool/shard004/C/0097742_env_mgdisk.c new file mode 100644 index 0000000000000000000000000000000000000000..363ee68c27e83d3ac397f1120f69483ea8f027e4 --- /dev/null +++ b/pool/shard004/C/0097742_env_mgdisk.c @@ -0,0 +1,92 @@ +/* + * (C) Copyright 2009 mGine co. + * unsik Kim + * + * 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 + +/* references to names in env_common.c */ +extern uchar default_environment[]; +extern int default_environment_size; + +char * env_name_spec = "MG_DISK"; + +env_t *env_ptr = 0; + +DECLARE_GLOBAL_DATA_PTR; + +uchar env_get_char_spec(int index) +{ + return (*((uchar *) (gd->env_addr + index))); +} + +void env_relocate_spec(void) +{ + unsigned int err; + + err = mg_disk_init(); + if (err) { + puts ("*** Warning - mg_disk_init error"); + goto OUT; + } + err = mg_disk_read(CONFIG_ENV_ADDR, (u_char *)env_ptr, CONFIG_ENV_SIZE); + if (err) { + puts ("*** Warning - mg_disk_read error"); + goto OUT; + } + + if (crc32(0, env_ptr->data, ENV_SIZE) != env_ptr->crc) { + puts ("*** Warning - CRC error"); + goto OUT; + } + + return; + +OUT: + printf (", using default environment\n\n"); + set_default_env(); +} + +int saveenv(void) +{ + unsigned int err; + + env_ptr->crc = crc32(0, env_ptr->data, ENV_SIZE); + err = mg_disk_write(CONFIG_ENV_ADDR, (u_char *)env_ptr, + CONFIG_ENV_SIZE); + if (err) + puts ("*** Warning - mg_disk_write error\n\n"); + + return err; +} + +int env_init(void) +{ + /* use default */ + gd->env_addr = (ulong) & default_environment[0]; + gd->env_valid = 1; + + return 0; +} diff --git a/pool/shard004/C/0097750_s_ctanhl.c b/pool/shard004/C/0097750_s_ctanhl.c new file mode 100644 index 0000000000000000000000000000000000000000..016ebc5ce4522332d504b236026b9b981498daca --- /dev/null +++ b/pool/shard004/C/0097750_s_ctanhl.c @@ -0,0 +1,118 @@ +/* Complex hyperbole tangent for long double. + Copyright (C) 1997-2015 Free Software Foundation, Inc. + This file is part of the GNU C Library. + Contributed by Ulrich Drepper , 1997. + + 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 + +__complex__ long double +__ctanhl (__complex__ long double x) +{ + __complex__ long double res; + + if (__glibc_unlikely (!isfinite (__real__ x) || !isfinite (__imag__ x))) + { + if (__isinf_nsl (__real__ x)) + { + __real__ res = __copysignl (1.0, __real__ x); + __imag__ res = __copysignl (0.0, __imag__ x); + } + else if (__imag__ x == 0.0) + { + res = x; + } + else + { + __real__ res = __nanl (""); + __imag__ res = __nanl (""); + + if (__isinf_nsl (__imag__ x)) + feraiseexcept (FE_INVALID); + } + } + else + { + long double sinix, cosix; + long double den; + const int t = (int) ((LDBL_MAX_EXP - 1) * M_LN2l / 2); + int icls = fpclassify (__imag__ x); + + /* tanh(x+iy) = (sinh(2x) + i*sin(2y))/(cosh(2x) + cos(2y)) + = (sinh(x)*cosh(x) + i*sin(y)*cos(y))/(sinh(x)^2 + cos(y)^2). */ + + if (__glibc_likely (icls != FP_SUBNORMAL)) + { + __sincosl (__imag__ x, &sinix, &cosix); + } + else + { + sinix = __imag__ x; + cosix = 1.0; + } + + if (fabsl (__real__ x) > t) + { + /* Avoid intermediate overflow when the imaginary part of + the result may be subnormal. Ignoring negligible terms, + the real part is +/- 1, the imaginary part is + sin(y)*cos(y)/sinh(x)^2 = 4*sin(y)*cos(y)/exp(2x). */ + long double exp_2t = __ieee754_expl (2 * t); + + __real__ res = __copysignl (1.0, __real__ x); + __imag__ res = 4 * sinix * cosix; + __real__ x = fabsl (__real__ x); + __real__ x -= t; + __imag__ res /= exp_2t; + if (__real__ x > t) + { + /* Underflow (original real part of x has absolute value + > 2t). */ + __imag__ res /= exp_2t; + } + else + __imag__ res /= __ieee754_expl (2 * __real__ x); + } + else + { + long double sinhrx, coshrx; + if (fabsl (__real__ x) > LDBL_MIN) + { + sinhrx = __ieee754_sinhl (__real__ x); + coshrx = __ieee754_coshl (__real__ x); + } + else + { + sinhrx = __real__ x; + coshrx = 1.0L; + } + + if (fabsl (sinhrx) > fabsl (cosix) * LDBL_EPSILON) + den = sinhrx * sinhrx + cosix * cosix; + else + den = cosix * cosix; + __real__ res = sinhrx * coshrx / den; + __imag__ res = sinix * cosix / den; + } + } + + return res; +} +weak_alias (__ctanhl, ctanhl) diff --git a/pool/shard004/C/0097752_mq_descreate.c b/pool/shard004/C/0097752_mq_descreate.c new file mode 100644 index 0000000000000000000000000000000000000000..df6c8fcdc329716006fe5b1773a0032bced232ca --- /dev/null +++ b/pool/shard004/C/0097752_mq_descreate.c @@ -0,0 +1,173 @@ +/**************************************************************************** + * sched/mqueue/mq_descreate.c + * + * Copyright (C) 2007-2009, 2013 Gregory Nutt. All rights reserved. + * Author: Gregory Nutt + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the + * distribution. + * 3. Neither the name NuttX nor the names of its contributors may be + * used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS + * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED + * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************/ + +/**************************************************************************** + * Included Files + ****************************************************************************/ + +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +#include "signal/signal.h" + +#include "mqueue/mqueue.h" + +/**************************************************************************** + * Pre-processor Definitions + ****************************************************************************/ + +/**************************************************************************** + * Private Type Declarations + ****************************************************************************/ + +/**************************************************************************** + * Public Variables + ****************************************************************************/ + +/**************************************************************************** + * Private Variables + ****************************************************************************/ + +/**************************************************************************** + * Private Functions + ****************************************************************************/ + +/**************************************************************************** + * Name: mq_desalloc + * + * Description: + * Allocate a message queue descriptor. + * + * Inputs: + * None + * + * Return Value: + * Reference to the allocated mq descriptor. + * + ****************************************************************************/ + +static mqd_t mq_desalloc(void) +{ + mqd_t mqdes; + + /* Try to get the message descriptorfrom the free list */ + + mqdes = (mqd_t)sq_remfirst(&g_desfree); + + /* Check if we got one. */ + + if (!mqdes) + { + /* Add another block of message descriptors to the list */ + + mq_desblockalloc(); + + /* And try again */ + + mqdes = (mqd_t)sq_remfirst(&g_desfree); + } + + return mqdes; +} + +/**************************************************************************** + * Public Functions + ****************************************************************************/ + +/**************************************************************************** + * Name: mq_descreate + * + * Description: + * Create a message queue descriptor for the specified TCB + * + * Inputs: + * mtcb - task that needs the descriptor. + * msgq - Named message queue containing the message + * oflags - access rights for the descriptor + * + * Return Value: + * On success, the message queue descriptor is returned. NULL is returned + * on a failure to allocate. + * + ****************************************************************************/ + +mqd_t mq_descreate(FAR struct tcb_s *mtcb, FAR struct mqueue_inode_s *msgq, + int oflags) +{ + FAR struct task_group_s *group; + mqd_t mqdes; + + /* A NULL TCB pointer means to use the TCB of the currently executing + * task/thread. + */ + + if (!mtcb) + { + mtcb = sched_self(); + } + + group = mtcb->group; + DEBUGASSERT(group); + + /* Create a message queue descriptor for the TCB */ + + mqdes = mq_desalloc(); + if (mqdes) + { + /* Initialize the message queue descriptor */ + + memset(mqdes, 0, sizeof(struct mq_des)); + mqdes->msgq = msgq; + mqdes->oflags = oflags; + + /* And add it to the specified task's TCB */ + + sq_addlast((FAR sq_entry_t*)mqdes, &group->tg_msgdesq); + } + + return mqdes; +} diff --git a/pool/shard004/C/0097755_ide-code-indexer.c b/pool/shard004/C/0097755_ide-code-indexer.c new file mode 100644 index 0000000000000000000000000000000000000000..3dc74e1bb74d8e25ad7cfa1ac57f2b296d474787 --- /dev/null +++ b/pool/shard004/C/0097755_ide-code-indexer.c @@ -0,0 +1,163 @@ +/* ide-code-indexer.c + * + * Copyright © 2017 Anoop Chandu + * + * 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 "ide-code-indexer" + +#include "symbols/ide-code-indexer.h" + +G_DEFINE_INTERFACE (IdeCodeIndexer, ide_code_indexer, IDE_TYPE_OBJECT) + +static IdeCodeIndexEntries * +ide_code_indexer_real_index_file (IdeCodeIndexer *self, + GFile *file, + const gchar * const *build_flags, + GCancellable *cancellable, + GError **error) +{ + g_set_error (error, + G_IO_ERROR, + G_IO_ERROR_NOT_SUPPORTED, + "Indexing is not supported"); + return NULL; +} + +void +ide_code_indexer_real_generate_key_async (IdeCodeIndexer *self, + IdeSourceLocation *location, + GCancellable *cancellable, + GAsyncReadyCallback callback, + gpointer user_data) +{ + g_task_report_new_error (self, + callback, + user_data, + ide_code_indexer_real_generate_key_async, + G_IO_ERROR, + G_IO_ERROR_NOT_SUPPORTED, + "Get key is not supported"); +} + +gchar * +ide_code_indexer_real_generate_key_finish (IdeCodeIndexer *self, + GAsyncResult *result, + GError **error) +{ + GTask *task = (GTask *)result; + + g_assert (G_IS_TASK (result)); + + return g_task_propagate_pointer (task, error); +} + +static void +ide_code_indexer_default_init (IdeCodeIndexerInterface *iface) +{ + iface->index_file = ide_code_indexer_real_index_file; + iface->generate_key_async = ide_code_indexer_real_generate_key_async; + iface->generate_key_finish = ide_code_indexer_real_generate_key_finish; +} + +/** + * ide_code_indexer_index_file: + * @self: An #IdeCodeIndexer instance. + * @file: Source file to index. + * @build_flags: (nullable) (array zero-terminated=1): array of build flags to parse @file. + * @cancellable: (nullable): a #GCancellable. + * @error: a #GError. + * + * This function will take index source file and create an array + * of symbols in @file. + * + * Returns: (transfer full): an #IdeCodeIndexEntries contains list + * of #IdeCodeIndexEntry. + * + * Since: 3.26 + */ +IdeCodeIndexEntries * +ide_code_indexer_index_file (IdeCodeIndexer *self, + GFile *file, + const gchar * const *build_flags, + GCancellable *cancellable, + GError **error) +{ + IdeCodeIndexerInterface *iface; + + g_return_val_if_fail (IDE_IS_CODE_INDEXER (self), NULL); + g_return_val_if_fail (G_IS_FILE (file), NULL); + g_return_val_if_fail (!cancellable || G_IS_CANCELLABLE (cancellable), NULL); + + iface = IDE_CODE_INDEXER_GET_IFACE (self); + + return iface->index_file (self, file, build_flags, cancellable, error); +} + +/** + * ide_code_indexer_generate_key_async: + * @self: An #IdeCodeIndexer instance. + * @location: (not nullable): Source location of refernece. + * @cancellable: (nullable): a #GCancellable. + * @callback: A callback to execute upon indexing. + * @user_data: User data to pass to @callback. + * + * This function will get key of reference located at #IdeSoureLocation. + * + * Since: 3.26 + */ +void +ide_code_indexer_generate_key_async (IdeCodeIndexer *self, + IdeSourceLocation *location, + GCancellable *cancellable, + GAsyncReadyCallback callback, + gpointer user_data) +{ + IdeCodeIndexerInterface *iface; + + g_return_if_fail (IDE_IS_CODE_INDEXER (self)); + g_return_if_fail (location != NULL); + g_return_if_fail (!cancellable || G_IS_CANCELLABLE (cancellable)); + + iface = IDE_CODE_INDEXER_GET_IFACE (self); + + iface->generate_key_async (self, location, cancellable, callback, user_data); +} + +/** + * ide_code_indexer_generate_key_finish: + * @self: an #IdeCodeIndexer + * @result: a #GAsyncResult + * @error: a location for a #GError, or %NULL + * + * Returns key for declaration of reference at a location. + * + * Returns: (transfer full) : A string which contains key. + * + * Since: 3.26 + */ +gchar * +ide_code_indexer_generate_key_finish (IdeCodeIndexer *self, + GAsyncResult *result, + GError **error) +{ + IdeCodeIndexerInterface *iface; + + g_return_val_if_fail (IDE_IS_CODE_INDEXER (self), NULL); + + iface = IDE_CODE_INDEXER_GET_IFACE (self); + + return iface->generate_key_finish (self, result, error); +} diff --git a/pool/shard004/C/0097756_lib1531.c b/pool/shard004/C/0097756_lib1531.c new file mode 100644 index 0000000000000000000000000000000000000000..287acd6c653bdf02b452754c9c4350479677058d --- /dev/null +++ b/pool/shard004/C/0097756_lib1531.c @@ -0,0 +1,145 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) 1998 - 2016, 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 "test.h" + +#include "testutil.h" +#include "warnless.h" +#include "memdebug.h" + +#define TEST_HANG_TIMEOUT 60 * 1000 + +static char const testData[] = ".abc\0xyz"; +static off_t const testDataSize = sizeof(testData) - 1; + +int test(char *URL) +{ + CURL *easy; + CURLM *multi_handle; + int still_running; /* keep number of running handles */ + CURLMsg *msg; /* for picking up messages with the transfer status */ + int msgs_left; /* how many messages are left */ + + /* Allocate one CURL handle per transfer */ + easy = curl_easy_init(); + + /* init a multi stack */ + multi_handle = curl_multi_init(); + + /* add the individual transfer */ + curl_multi_add_handle(multi_handle, easy); + + /* set the options (I left out a few, you'll get the point anyway) */ + curl_easy_setopt(easy, CURLOPT_URL, URL); + curl_easy_setopt(easy, CURLOPT_POSTFIELDSIZE_LARGE, + (curl_off_t)testDataSize); + curl_easy_setopt(easy, CURLOPT_POSTFIELDS, testData); + + /* we start some action by calling perform right away */ + curl_multi_perform(multi_handle, &still_running); + + do { + struct timeval timeout; + int rc; /* select() return code */ + CURLMcode mc; /* curl_multi_fdset() return code */ + + fd_set fdread; + fd_set fdwrite; + fd_set fdexcep; + int maxfd = -1; + + long curl_timeo = -1; + + FD_ZERO(&fdread); + FD_ZERO(&fdwrite); + FD_ZERO(&fdexcep); + + /* set a suitable timeout to play around with */ + timeout.tv_sec = 1; + timeout.tv_usec = 0; + + curl_multi_timeout(multi_handle, &curl_timeo); + if(curl_timeo >= 0) { + timeout.tv_sec = curl_timeo / 1000; + if(timeout.tv_sec > 1) + timeout.tv_sec = 1; + else + timeout.tv_usec = (curl_timeo % 1000) * 1000; + } + + /* get file descriptors from the transfers */ + mc = curl_multi_fdset(multi_handle, &fdread, &fdwrite, &fdexcep, &maxfd); + + if(mc != CURLM_OK) { + fprintf(stderr, "curl_multi_fdset() failed, code %d.\n", mc); + break; + } + + /* On success the value of maxfd is guaranteed to be >= -1. We call + select(maxfd + 1, ...); specially in case of (maxfd == -1) there are + no fds ready yet so we call select(0, ...) --or Sleep() on Windows-- + to sleep 100ms, which is the minimum suggested value in the + curl_multi_fdset() doc. */ + + if(maxfd == -1) { +#ifdef _WIN32 + Sleep(100); + rc = 0; +#else + /* Portable sleep for platforms other than Windows. */ + struct timeval wait = { 0, 100 * 1000 }; /* 100ms */ + rc = select(0, NULL, NULL, NULL, &wait); +#endif + } + else { + /* Note that on some platforms 'timeout' may be modified by select(). + If you need access to the original value save a copy beforehand. */ + rc = select(maxfd+1, &fdread, &fdwrite, &fdexcep, &timeout); + } + + switch(rc) { + case -1: + /* select error */ + break; + case 0: /* timeout */ + default: /* action */ + curl_multi_perform(multi_handle, &still_running); + break; + } + } while(still_running); + + /* See how the transfers went */ + do { + msg = curl_multi_info_read(multi_handle, &msgs_left); + if(msg && msg->msg == CURLMSG_DONE) { + printf("HTTP transfer completed with status %d\n", msg->data.result); + break; + } + } while(msg); + + curl_multi_cleanup(multi_handle); + + /* Free the CURL handles */ + curl_easy_cleanup(easy); + + return 0; +} + diff --git a/pool/shard004/C/0097759_acdata.c b/pool/shard004/C/0097759_acdata.c new file mode 100644 index 0000000000000000000000000000000000000000..d3ff758244f046bd688e5a244688a717bcc13f5b --- /dev/null +++ b/pool/shard004/C/0097759_acdata.c @@ -0,0 +1,67 @@ +/** + * ibus-faft - FreeArray for Test for The Input Bus + * + * Copyright (c) 2010 + * Yong-Siang Shih (Shaform) + * + * 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 . + * + * See the file "COPYING" for information on usage and redistribution + * of this file. + */ +#include "faport/code.h" +#include "acdata.h" +int faft_acdata_input(ACData *acd, FAFTKeyCode kc) +{ + if (acd == NULL || acd->len > ARRAYCODE_MAX_LEN || acd->len < 0) + return AC_ERROR; + + if (valid_kc(kc)) { + if (kc == KEYCODE_END && acd->len > 0) { + acd->kcs[acd->len] = kc; + acd->ac = keytocode(acd->kcs); + return AC_COMMIT; + } else if (acd->len == ARRAYCODE_MAX_LEN) { + acd->kcs[acd->len] = KEYCODE_END; + acd->ac = keytocode(acd->kcs); + return AC_FULL; + } else { + acd->kcs[(acd->len)++] = kc; + return AC_ABSORB; + + } + } + return AC_KEY_ERROR; +} +int faft_acdata_get_unfinished(ACData *acd, FAFTKeyCode *kcs) +{ + int i; + for (i = 0; i < acd->len; ++i) { + kcs[i] = acd->kcs[i]; + } + kcs[i] = KEYCODE_END; + return 1; +} +int faft_acdata_remove_last(ACData *acd) +{ + if (acd->len) + --(acd->len); + return acd->len; +} +int faft_acdata_remove_all(ACData *acd) { return (acd->len = 0) == 0; } +int faft_acdata_is_entering(ACData *acd) { return acd->len > 0; } +int faft_acdata_is_full(ACData *acd) { return acd->len == ARRAYCODE_MAX_LEN; } +int faft_acdata_length(ACData *acd) { return acd->len; } + + diff --git a/pool/shard004/C/0097764_Testy3.c b/pool/shard004/C/0097764_Testy3.c new file mode 100644 index 0000000000000000000000000000000000000000..e263341c3b0e10072064f5db7f88cdf5f3c929d4 --- /dev/null +++ b/pool/shard004/C/0097764_Testy3.c @@ -0,0 +1,55 @@ +#include +#include +#include "libnumarray.h" +#include "numarray.h" +#define SIZE=5 +//line 6 +void copyIt(void); + +/* Written Nic Wherry circa July 2003 */ + + +void test(void) +{ + printf("This is only a test"); +} +//line11 +void copyIt(void) +{ + printf("copied"); +} +//line16 +static PyObject * +Testy3_copyIt(PyObject *self, PyObject *args) +{ + PyObject *firstPtr, *copy; + PyArrayObject *secPtr; + + if(!PyArg_ParseTuple(args, "O", &firstPtr)) + printf("bad"); + + secPtr=NA_InputArray(firstPtr, tInt32, C_ARRAY); + copy = PyArray_Copy(secPtr); + return copy; +} +//line30 +static PyObject* +Testy3_test(PyObject *self, PyObject *args) +{ + test(); + return (PyObject*)Py_BuildValue(""); +} +//line37 +static PyMethodDef +Testy3Methods[] = +{ + { "copyIt", Testy3_copyIt, METH_VARARGS }, + { "test", Testy3_test, METH_VARARGS }, + { NULL, NULL }, +}; +//line45 +void initTesty3(void) +{ + Py_InitModule("Testy3", Testy3Methods); + import_libnumarray(); +} diff --git a/pool/shard004/C/0097766_except.c b/pool/shard004/C/0097766_except.c new file mode 100644 index 0000000000000000000000000000000000000000..e5e751591b237e7b3fe190081e9a58de50dc6608 --- /dev/null +++ b/pool/shard004/C/0097766_except.c @@ -0,0 +1,72 @@ +static char rcsid[] = "$Id$" "\n$Id$"; +#include +#include +#include "assert.h" +#include "except.h" +#define T Except_T +Except_Frame *Except_stack = NULL; +void Except_raise(const T *e, const char *file, + int line) { +#ifdef WIN32 + Except_Frame *p; + + if (Except_index == -1) + Except_init(); + p = TlsGetValue(Except_index); +#else + Except_Frame *p = Except_stack; +#endif + assert(e); + if (p == NULL) { + fprintf(stderr, "Uncaught exception"); + if (e->reason) + fprintf(stderr, " %s", e->reason); + else + fprintf(stderr, " at 0x%p", e); + if (file && line > 0) + fprintf(stderr, " raised at %s:%d\n", file, line); + fprintf(stderr, "aborting...\n"); + fflush(stderr); + abort(); + } + p->exception = e; + p->file = file; + p->line = line; +#ifdef WIN32 + Except_pop(); +#else + Except_stack = Except_stack->prev; +#endif + longjmp(p->env, Except_raised); +} +#ifdef WIN32 +_CRTIMP void __cdecl _assert(void *, void *, unsigned); +#undef assert +#define assert(e) ((e) || (_assert(#e, __FILE__, __LINE__), 0)) + +int Except_index = -1; +void Except_init(void) { + BOOL cond; + + Except_index = TlsAlloc(); + assert(Except_index != TLS_OUT_OF_INDEXES); + cond = TlsSetValue(Except_index, NULL); + assert(cond == TRUE); +} + +void Except_push(Except_Frame *fp) { + BOOL cond; + + fp->prev = TlsGetValue(Except_index); + cond = TlsSetValue(Except_index, fp); + assert(cond == TRUE); +} + +void Except_pop(void) { + BOOL cond; + Except_Frame *tos = TlsGetValue(Except_index); + + cond = TlsSetValue(Except_index, tos->prev); + assert(cond == TRUE); +} +#endif diff --git a/pool/shard004/C/0097769_detect-depth.c b/pool/shard004/C/0097769_detect-depth.c new file mode 100644 index 0000000000000000000000000000000000000000..b65821bb412df81f83a7f2eb3d42db8d12e4ffcd --- /dev/null +++ b/pool/shard004/C/0097769_detect-depth.c @@ -0,0 +1,124 @@ +/* Copyright (C) 2007-2010 Open Information Security Foundation + * + * You can copy, redistribute or modify this Program under the terms of + * the GNU General Public License version 2 as published by the Free + * Software Foundation. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * version 2 along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA + * 02110-1301, USA. + */ + +/** + * \file + * + * \author Victor Julien + * \author Anoop Saldanha + * + * Implements the depth keyword. + */ + +#include "suricata-common.h" + +#include "decode.h" + +#include "detect.h" +#include "detect-parse.h" +#include "detect-content.h" +#include "detect-uricontent.h" +#include "detect-byte-extract.h" +#include "detect-depth.h" + +#include "flow-var.h" +#include "app-layer.h" + +#include "util-byte.h" +#include "util-debug.h" + +static int DetectDepthSetup (DetectEngineCtx *, Signature *, const char *); + +void DetectDepthRegister (void) +{ + sigmatch_table[DETECT_DEPTH].name = "depth"; + sigmatch_table[DETECT_DEPTH].desc = "designate how many bytes from the beginning of the payload will be checked"; + sigmatch_table[DETECT_DEPTH].url = DOC_URL DOC_VERSION "/rules/payload-keywords.html#depth"; + sigmatch_table[DETECT_DEPTH].Match = NULL; + sigmatch_table[DETECT_DEPTH].Setup = DetectDepthSetup; + sigmatch_table[DETECT_DEPTH].Free = NULL; + sigmatch_table[DETECT_DEPTH].RegisterTests = NULL; +} + +static int DetectDepthSetup (DetectEngineCtx *de_ctx, Signature *s, const char *depthstr) +{ + const char *str = depthstr; + SigMatch *pm = NULL; + int ret = -1; + + /* retrive the sm to apply the depth against */ + pm = DetectGetLastSMFromLists(s, DETECT_CONTENT, -1); + if (pm == NULL) { + SCLogError(SC_ERR_DEPTH_MISSING_CONTENT, "depth needs " + "preceding content, uricontent option, http_client_body, " + "http_server_body, http_header option, http_raw_header option, " + "http_method option, http_cookie, http_raw_uri, " + "http_stat_msg, http_stat_code, http_user_agent, " + "http_host, http_raw_host or " + "file_data/dce_stub_data sticky buffer options"); + goto end; + } + + /* verify other conditions. */ + DetectContentData *cd = (DetectContentData *)pm->ctx; + + if (cd->flags & DETECT_CONTENT_DEPTH) { + SCLogError(SC_ERR_INVALID_SIGNATURE, "can't use multiple depths for the same content."); + goto end; + } + if ((cd->flags & DETECT_CONTENT_WITHIN) || (cd->flags & DETECT_CONTENT_DISTANCE)) { + SCLogError(SC_ERR_INVALID_SIGNATURE, "can't use a relative " + "keyword like within/distance with a absolute " + "relative keyword like depth/offset for the same " + "content." ); + goto end; + } + if (cd->flags & DETECT_CONTENT_NEGATED && cd->flags & DETECT_CONTENT_FAST_PATTERN) { + SCLogError(SC_ERR_INVALID_SIGNATURE, "can't have a relative " + "negated keyword set along with a fast_pattern"); + goto end; + } + if (cd->flags & DETECT_CONTENT_FAST_PATTERN_ONLY) { + SCLogError(SC_ERR_INVALID_SIGNATURE, "can't have a relative " + "keyword set along with a fast_pattern:only;"); + goto end; + } + if (str[0] != '-' && isalpha((unsigned char)str[0])) { + SigMatch *bed_sm = DetectByteExtractRetrieveSMVar(str, s); + if (bed_sm == NULL) { + SCLogError(SC_ERR_INVALID_SIGNATURE, "unknown byte_extract var " + "seen in depth - %s\n", str); + goto end; + } + cd->depth = ((DetectByteExtractData *)bed_sm->ctx)->local_id; + cd->flags |= DETECT_CONTENT_DEPTH_BE; + } else { + if (ByteExtractStringUint16(&cd->depth, 0, 0, str) != (int)strlen(str)) + { + SCLogError(SC_ERR_INVALID_SIGNATURE, + "invalid value for depth: %s", str); + goto end; + } + /* Now update the real limit, as depth is relative to the offset */ + cd->depth += cd->offset; + } + cd->flags |= DETECT_CONTENT_DEPTH; + + ret = 0; + end: + return ret; +} diff --git a/pool/shard004/C/0097771_file.c b/pool/shard004/C/0097771_file.c new file mode 100644 index 0000000000000000000000000000000000000000..a7886fd3cef81816655b795fb9a435b0b798a3dd --- /dev/null +++ b/pool/shard004/C/0097771_file.c @@ -0,0 +1,272 @@ +/* + * This file is part of the Micro Python project, http://micropython.org/ + * + * The MIT License (MIT) + * + * Copyright (c) 2013, 2014 Damien P. George + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +#include +#include +#include +#include +#include +#include + +#include "py/nlr.h" +#include "py/runtime.h" +#include "py/stream.h" +#include "py/builtin.h" + +#if MICROPY_PY_IO + +#ifdef _WIN32 +#define fsync _commit +#endif + +typedef struct _mp_obj_fdfile_t { + mp_obj_base_t base; + int fd; +} mp_obj_fdfile_t; + +#ifdef MICROPY_CPYTHON_COMPAT +STATIC void check_fd_is_open(const mp_obj_fdfile_t *o) { + if (o->fd < 0) { + nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "I/O operation on closed file")); + } +} +#else +#define check_fd_is_open(o) +#endif + +extern const mp_obj_type_t mp_type_fileio; +extern const mp_obj_type_t mp_type_textio; + +STATIC void fdfile_print(const mp_print_t *print, mp_obj_t self_in, mp_print_kind_t kind) { + (void)kind; + mp_obj_fdfile_t *self = self_in; + mp_printf(print, "", mp_obj_get_type_str(self), self->fd); +} + +STATIC mp_uint_t fdfile_read(mp_obj_t o_in, void *buf, mp_uint_t size, int *errcode) { + mp_obj_fdfile_t *o = o_in; + check_fd_is_open(o); + mp_int_t r = read(o->fd, buf, size); + if (r == -1) { + *errcode = errno; + return MP_STREAM_ERROR; + } + return r; +} + +STATIC mp_uint_t fdfile_write(mp_obj_t o_in, const void *buf, mp_uint_t size, int *errcode) { + mp_obj_fdfile_t *o = o_in; + check_fd_is_open(o); + mp_int_t r = write(o->fd, buf, size); + if (r == -1) { + *errcode = errno; + return MP_STREAM_ERROR; + } + return r; +} + +STATIC mp_uint_t fdfile_ioctl(mp_obj_t o_in, mp_uint_t request, mp_uint_t arg, int *errcode) { + mp_obj_fdfile_t *o = o_in; + if (request == MP_STREAM_SEEK) { + struct mp_stream_seek_t *s = (struct mp_stream_seek_t*)arg; + off_t off = lseek(o->fd, s->offset, s->whence); + if (off == (off_t)-1) { + *errcode = errno; + return MP_STREAM_ERROR; + } + s->offset = off; + return 0; + } else { + *errcode = EINVAL; + return MP_STREAM_ERROR; + } +} + +STATIC mp_obj_t fdfile_flush(mp_obj_t self_in) { + mp_obj_fdfile_t *self = self_in; + check_fd_is_open(self); + fsync(self->fd); + return mp_const_none; +} +STATIC MP_DEFINE_CONST_FUN_OBJ_1(fdfile_flush_obj, fdfile_flush); + +STATIC mp_obj_t fdfile_close(mp_obj_t self_in) { + mp_obj_fdfile_t *self = self_in; + close(self->fd); +#ifdef MICROPY_CPYTHON_COMPAT + self->fd = -1; +#endif + return mp_const_none; +} +STATIC MP_DEFINE_CONST_FUN_OBJ_1(fdfile_close_obj, fdfile_close); + +STATIC mp_obj_t fdfile___exit__(mp_uint_t n_args, const mp_obj_t *args) { + (void)n_args; + return fdfile_close(args[0]); +} +STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(fdfile___exit___obj, 4, 4, fdfile___exit__); + +STATIC mp_obj_t fdfile_fileno(mp_obj_t self_in) { + mp_obj_fdfile_t *self = self_in; + check_fd_is_open(self); + return MP_OBJ_NEW_SMALL_INT(self->fd); +} +STATIC MP_DEFINE_CONST_FUN_OBJ_1(fdfile_fileno_obj, fdfile_fileno); + +// Note: encoding is ignored for now; it's also not a valid kwarg for CPython's FileIO, +// but by adding it here we can use one single mp_arg_t array for open() and FileIO's constructor +STATIC const mp_arg_t file_open_args[] = { + { MP_QSTR_file, MP_ARG_OBJ | MP_ARG_REQUIRED, {.u_obj = mp_const_none} }, + { MP_QSTR_mode, MP_ARG_OBJ, {.u_obj = MP_OBJ_NEW_QSTR(MP_QSTR_r)} }, + { MP_QSTR_encoding, MP_ARG_OBJ | MP_ARG_KW_ONLY, {.u_obj = mp_const_none} }, +}; +#define FILE_OPEN_NUM_ARGS MP_ARRAY_SIZE(file_open_args) + +STATIC mp_obj_t fdfile_open(mp_obj_t type_in, mp_arg_val_t *args) { + mp_obj_fdfile_t *o = m_new_obj(mp_obj_fdfile_t); + mp_const_obj_t type = type_in; + const char *mode_s = mp_obj_str_get_str(args[1].u_obj); + + int mode = 0; + while (*mode_s) { + switch (*mode_s++) { + // Note: these assume O_RDWR = O_RDONLY | O_WRONLY + case 'r': + mode |= O_RDONLY; + break; + case 'w': + mode |= O_WRONLY | O_CREAT | O_TRUNC; + break; + case 'a': + mode |= O_WRONLY | O_CREAT | O_APPEND; + break; + case '+': + mode |= O_RDWR; + break; + #if MICROPY_PY_IO_FILEIO + // If we don't have io.FileIO, then files are in text mode implicitly + case 'b': + type = &mp_type_fileio; + break; + case 't': + type = &mp_type_textio; + break; + #endif + } + } + + o->base.type = type; + + mp_obj_t fid = args[0].u_obj; + + if (MP_OBJ_IS_SMALL_INT(fid)) { + o->fd = MP_OBJ_SMALL_INT_VALUE(fid); + return o; + } + + const char *fname = mp_obj_str_get_str(fid); + int fd = open(fname, mode, 0644); + if (fd == -1) { + nlr_raise(mp_obj_new_exception_arg1(&mp_type_OSError, MP_OBJ_NEW_SMALL_INT(errno))); + } + o->fd = fd; + return o; +} + +STATIC mp_obj_t fdfile_make_new(mp_obj_t type_in, mp_uint_t n_args, mp_uint_t n_kw, const mp_obj_t *args) { + mp_arg_val_t arg_vals[FILE_OPEN_NUM_ARGS]; + mp_arg_parse_all_kw_array(n_args, n_kw, args, FILE_OPEN_NUM_ARGS, file_open_args, arg_vals); + return fdfile_open(type_in, arg_vals); +} + +STATIC const mp_map_elem_t rawfile_locals_dict_table[] = { + { MP_OBJ_NEW_QSTR(MP_QSTR_fileno), (mp_obj_t)&fdfile_fileno_obj }, + { MP_OBJ_NEW_QSTR(MP_QSTR_read), (mp_obj_t)&mp_stream_read_obj }, + { MP_OBJ_NEW_QSTR(MP_QSTR_readall), (mp_obj_t)&mp_stream_readall_obj }, + { MP_OBJ_NEW_QSTR(MP_QSTR_readinto), (mp_obj_t)&mp_stream_readinto_obj }, + { MP_OBJ_NEW_QSTR(MP_QSTR_readline), (mp_obj_t)&mp_stream_unbuffered_readline_obj}, + { MP_OBJ_NEW_QSTR(MP_QSTR_readlines), (mp_obj_t)&mp_stream_unbuffered_readlines_obj}, + { MP_OBJ_NEW_QSTR(MP_QSTR_write), (mp_obj_t)&mp_stream_write_obj }, + { MP_OBJ_NEW_QSTR(MP_QSTR_seek), (mp_obj_t)&mp_stream_seek_obj }, + { MP_OBJ_NEW_QSTR(MP_QSTR_flush), (mp_obj_t)&fdfile_flush_obj }, + { MP_OBJ_NEW_QSTR(MP_QSTR_close), (mp_obj_t)&fdfile_close_obj }, + { MP_OBJ_NEW_QSTR(MP_QSTR___enter__), (mp_obj_t)&mp_identity_obj }, + { MP_OBJ_NEW_QSTR(MP_QSTR___exit__), (mp_obj_t)&fdfile___exit___obj }, +}; + +STATIC MP_DEFINE_CONST_DICT(rawfile_locals_dict, rawfile_locals_dict_table); + +#if MICROPY_PY_IO_FILEIO +STATIC const mp_stream_p_t fileio_stream_p = { + .read = fdfile_read, + .write = fdfile_write, + .ioctl = fdfile_ioctl, +}; + +const mp_obj_type_t mp_type_fileio = { + { &mp_type_type }, + .name = MP_QSTR_FileIO, + .print = fdfile_print, + .make_new = fdfile_make_new, + .getiter = mp_identity, + .iternext = mp_stream_unbuffered_iter, + .stream_p = &fileio_stream_p, + .locals_dict = (mp_obj_t)&rawfile_locals_dict, +}; +#endif + +STATIC const mp_stream_p_t textio_stream_p = { + .read = fdfile_read, + .write = fdfile_write, + .ioctl = fdfile_ioctl, + .is_text = true, +}; + +const mp_obj_type_t mp_type_textio = { + { &mp_type_type }, + .name = MP_QSTR_TextIOWrapper, + .print = fdfile_print, + .make_new = fdfile_make_new, + .getiter = mp_identity, + .iternext = mp_stream_unbuffered_iter, + .stream_p = &textio_stream_p, + .locals_dict = (mp_obj_t)&rawfile_locals_dict, +}; + +// Factory function for I/O stream classes +mp_obj_t mp_builtin_open(mp_uint_t n_args, const mp_obj_t *args, mp_map_t *kwargs) { + // TODO: analyze buffering args and instantiate appropriate type + mp_arg_val_t arg_vals[FILE_OPEN_NUM_ARGS]; + mp_arg_parse_all(n_args, args, kwargs, FILE_OPEN_NUM_ARGS, file_open_args, arg_vals); + return fdfile_open((mp_obj_t)&mp_type_textio, arg_vals); +} +MP_DEFINE_CONST_FUN_OBJ_KW(mp_builtin_open_obj, 1, mp_builtin_open); + +const mp_obj_fdfile_t mp_sys_stdin_obj = { .base = {&mp_type_textio}, .fd = STDIN_FILENO }; +const mp_obj_fdfile_t mp_sys_stdout_obj = { .base = {&mp_type_textio}, .fd = STDOUT_FILENO }; +const mp_obj_fdfile_t mp_sys_stderr_obj = { .base = {&mp_type_textio}, .fd = STDERR_FILENO }; + +#endif // MICROPY_PY_IO diff --git a/pool/shard004/C/0097776_MOREDETOUR0076.c b/pool/shard004/C/0097776_MOREDETOUR0076.c new file mode 100644 index 0000000000000000000000000000000000000000..9c4aa6139e8d62dff30094c026714397dc3f7126 --- /dev/null +++ b/pool/shard004/C/0097776_MOREDETOUR0076.c @@ -0,0 +1,80 @@ +/* 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_r3_1; +atomic_int atom_1_r1_1; +atomic_int atom_2_r1_3; +atomic_int atom_2_r4_0; + +void *t0(void *arg){ +label_1:; + atomic_store_explicit(&vars[0], 1, memory_order_seq_cst); + int v2_r3 = atomic_load_explicit(&vars[0], memory_order_seq_cst); + int v3_r4 = v2_r3 ^ v2_r3; + atomic_store_explicit(&vars[1+v3_r4], 1, memory_order_seq_cst); + atomic_store_explicit(&vars[1], 3, memory_order_seq_cst); + int v22 = (v2_r3 == 1); + atomic_store_explicit(&atom_0_r3_1, v22, memory_order_seq_cst); + return NULL; +} + +void *t1(void *arg){ +label_2:; + int v5_r1 = atomic_load_explicit(&vars[1], memory_order_seq_cst); + atomic_store_explicit(&vars[1], 2, memory_order_seq_cst); + int v23 = (v5_r1 == 1); + atomic_store_explicit(&atom_1_r1_1, v23, memory_order_seq_cst); + return NULL; +} + +void *t2(void *arg){ +label_3:; + int v7_r1 = atomic_load_explicit(&vars[1], memory_order_seq_cst); + int v8_r3 = v7_r1 ^ v7_r1; + int v11_r4 = atomic_load_explicit(&vars[0+v8_r3], memory_order_seq_cst); + int v24 = (v7_r1 == 3); + atomic_store_explicit(&atom_2_r1_3, v24, memory_order_seq_cst); + int v25 = (v11_r4 == 0); + atomic_store_explicit(&atom_2_r4_0, 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_0_r3_1, 0); + atomic_init(&atom_1_r1_1, 0); + atomic_init(&atom_2_r1_3, 0); + atomic_init(&atom_2_r4_0, 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 v12 = atomic_load_explicit(&atom_0_r3_1, memory_order_seq_cst); + int v13 = atomic_load_explicit(&vars[1], memory_order_seq_cst); + int v14 = (v13 == 3); + int v15 = atomic_load_explicit(&atom_1_r1_1, memory_order_seq_cst); + int v16 = atomic_load_explicit(&atom_2_r1_3, memory_order_seq_cst); + int v17 = atomic_load_explicit(&atom_2_r4_0, memory_order_seq_cst); + int v18_conj = v16 & v17; + int v19_conj = v15 & v18_conj; + int v20_conj = v14 & v19_conj; + int v21_conj = v12 & v20_conj; + if (v21_conj == 1) assert(0); + return 0; +} diff --git a/pool/shard004/C/0097779_digipot_mcp4451_I2C_routines.c b/pool/shard004/C/0097779_digipot_mcp4451_I2C_routines.c new file mode 100644 index 0000000000000000000000000000000000000000..dd83c7a971934442d814f072813f98c221aec11d --- /dev/null +++ b/pool/shard004/C/0097779_digipot_mcp4451_I2C_routines.c @@ -0,0 +1,106 @@ +/** + * Marlin 3D Printer Firmware + * Copyright (c) 2019 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] + * + * Based on Sprinter and grbl. + * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm + * + * 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 . + * + */ + +/** + * digipot_mcp4451_I2C_routines.c + * Adapted from https://www-users.cs.york.ac.uk/~pcc/MCP/HAPR-Course-web/CMSIS/examples/html/master_8c_source.html + */ + +#ifdef TARGET_LPC1768 + +#include "../../../inc/MarlinConfigPre.h" + +#if MB(MKS_SBASE) + +#ifdef __cplusplus + extern "C" { +#endif + +#include "digipot_mcp4451_I2C_routines.h" + +// These two routines are exact copies of the lpc17xx_i2c.c routines. Couldn't link to +// to the lpc17xx_i2c.c routines so had to copy them into this file & rename them. + +static uint32_t _I2C_Start(LPC_I2C_TypeDef *I2Cx) { + // Reset STA, STO, SI + I2Cx->I2CONCLR = I2C_I2CONCLR_SIC|I2C_I2CONCLR_STOC|I2C_I2CONCLR_STAC; + + // Enter to Master Transmitter mode + I2Cx->I2CONSET = I2C_I2CONSET_STA; + + // Wait for complete + while (!(I2Cx->I2CONSET & I2C_I2CONSET_SI)); + I2Cx->I2CONCLR = I2C_I2CONCLR_STAC; + return (I2Cx->I2STAT & I2C_STAT_CODE_BITMASK); +} + +static void _I2C_Stop(LPC_I2C_TypeDef *I2Cx) { + // Make sure start bit is not active + if (I2Cx->I2CONSET & I2C_I2CONSET_STA) + I2Cx->I2CONCLR = I2C_I2CONCLR_STAC; + + I2Cx->I2CONSET = I2C_I2CONSET_STO|I2C_I2CONSET_AA; + I2Cx->I2CONCLR = I2C_I2CONCLR_SIC; +} + +I2C_M_SETUP_Type transferMCfg; + +#define I2C_status (LPC_I2C1->I2STAT & I2C_STAT_CODE_BITMASK) + +uint8_t digipot_mcp4451_start(uint8_t sla) { // send slave address and write bit + // Sometimes TX data ACK or NAK status is returned. That mean the start state didn't + // happen which means only the value of the slave address was send. Keep looping until + // the slave address and write bit are actually sent. + do { + _I2C_Stop(I2CDEV_M); // output stop state on I2C bus + _I2C_Start(I2CDEV_M); // output start state on I2C bus + while ((I2C_status != I2C_I2STAT_M_TX_START) + && (I2C_status != I2C_I2STAT_M_TX_RESTART) + && (I2C_status != I2C_I2STAT_M_TX_DAT_ACK) + && (I2C_status != I2C_I2STAT_M_TX_DAT_NACK)); //wait for start to be asserted + + LPC_I2C1->I2CONCLR = I2C_I2CONCLR_STAC; // clear start state before tansmitting slave address + LPC_I2C1->I2DAT = (sla << 1) & I2C_I2DAT_BITMASK; // transmit slave address & write bit + LPC_I2C1->I2CONSET = I2C_I2CONSET_AA; + LPC_I2C1->I2CONCLR = I2C_I2CONCLR_SIC; + while ((I2C_status != I2C_I2STAT_M_TX_SLAW_ACK) + && (I2C_status != I2C_I2STAT_M_TX_SLAW_NACK) + && (I2C_status != I2C_I2STAT_M_TX_DAT_ACK) + && (I2C_status != I2C_I2STAT_M_TX_DAT_NACK)) { /* wait for slaw to finish */ } + } while ( (I2C_status == I2C_I2STAT_M_TX_DAT_ACK) || (I2C_status == I2C_I2STAT_M_TX_DAT_NACK)); + return 1; +} + +uint8_t digipot_mcp4451_send_byte(uint8_t data) { + LPC_I2C1->I2DAT = data & I2C_I2DAT_BITMASK; // transmit data + LPC_I2C1->I2CONSET = I2C_I2CONSET_AA; + LPC_I2C1->I2CONCLR = I2C_I2CONCLR_SIC; + while (I2C_status != I2C_I2STAT_M_TX_DAT_ACK && I2C_status != I2C_I2STAT_M_TX_DAT_NACK); // wait for xmit to finish + return 1; +} + +#ifdef __cplusplus + } +#endif + +#endif // MB(MKS_SBASE) +#endif // TARGET_LPC1768 diff --git a/pool/shard004/C/0097788_w32semaphore-win32.c b/pool/shard004/C/0097788_w32semaphore-win32.c new file mode 100644 index 0000000000000000000000000000000000000000..ca4ec59b439a98aa00bc78b040584f9ceaea26e9 --- /dev/null +++ b/pool/shard004/C/0097788_w32semaphore-win32.c @@ -0,0 +1,51 @@ +/** + * \file + * Runtime support for managed Semaphore on Win32 + * + * Author: + * Ludovic Henry (luhenry@microsoft.com) + * + * Licensed under the MIT license. See LICENSE file in the project root for full license information. + */ + +#include "w32semaphore.h" + +#include +#include + +void +mono_w32semaphore_init (void) +{ +} + +#if G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT | HAVE_UWP_WINAPI_SUPPORT) +gpointer +ves_icall_System_Threading_Semaphore_CreateSemaphore_internal (gint32 initialCount, gint32 maximumCount, MonoString *name, gint32 *error) +{ + HANDLE sem; + + sem = CreateSemaphore (NULL, initialCount, maximumCount, name ? mono_string_chars (name) : NULL); + + *error = GetLastError (); + + return sem; +} +#endif /* G_HAVE_API_SUPPORT(HAVE_CLASSIC_WINAPI_SUPPORT | HAVE_UWP_WINAPI_SUPPORT) */ + +MonoBoolean +ves_icall_System_Threading_Semaphore_ReleaseSemaphore_internal (gpointer handle, gint32 releaseCount, gint32 *prevcount) +{ + return ReleaseSemaphore (handle, releaseCount, prevcount); +} + +gpointer +ves_icall_System_Threading_Semaphore_OpenSemaphore_internal (MonoString *name, gint32 rights, gint32 *error) +{ + HANDLE sem; + + sem = OpenSemaphore (rights, FALSE, mono_string_chars (name)); + + *error = GetLastError (); + + return sem; +} diff --git a/pool/shard004/C/0097789_esp_mfi_aes.c b/pool/shard004/C/0097789_esp_mfi_aes.c new file mode 100644 index 0000000000000000000000000000000000000000..a81b34d4174029274ab49248db823fc591de310f --- /dev/null +++ b/pool/shard004/C/0097789_esp_mfi_aes.c @@ -0,0 +1,145 @@ +/* + * ESPRESSIF MIT License + * + * Copyright (c) 2020 + * + * Permission is hereby granted for use on ESPRESSIF SYSTEMS products only, in which case, + * it is 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 "mbedtls/aes.h" +#include "esp_log.h" + +#include "esp_mfi_aes.h" + +static const char* TAG = "mfi_aes_adapter"; + +/*! + * @group AES 128-bit Counter Mode API + + * @abstract API to encrypt or decrypt using AES-128 in counter mode. + * + * Call esp_mfi_aes_ctr_init to initialize the context. Don't use the context until it has been initialized. + * Call esp_mfi_aes_ctr_update to encrypt or decrypt N bytes of input and generate N bytes of output. + * Call esp_mfi_aes_ctr_final to finalize the context. After finalizing, you must call AES_CTR_Init to use it again. +*/ + +typedef struct { + uint8_t key[MFI_AES_CTR_SIZE]; + uint8_t nonce[MFI_AES_CTR_SIZE]; +} aes_ctr_context_t; + +/** + * @bref Create AES context + * + * @param none + * + * @return the AES context point + */ +esp_mfi_aes_ctr_t esp_mfi_aes_ctr_new(void) +{ + aes_ctr_context_t *context = NULL; + context = (aes_ctr_context_t *) malloc(sizeof(aes_ctr_context_t)); + return context; +} + +/** + * @bref Initialize AES context, include initialize the key and nonce + * + * @param incontext AES context point + * inkey AES key + * innonce AES nonce + * + * @return the result + * 0 : sucessful + * others : failed + */ +int esp_mfi_aes_ctr_init(esp_mfi_aes_ctr_t incontext, const uint8_t inkey[MFI_AES_CTR_SIZE], const uint8_t innonce[MFI_AES_CTR_SIZE]) +{ + int ret = 0; + + if (incontext == NULL) + return -EINVAL; + + aes_ctr_context_t *context = incontext; + + memcpy(context->key, inkey, MFI_AES_CTR_SIZE); + memcpy(context->nonce, innonce, MFI_AES_CTR_SIZE); + + return ret; +} + +/** + * @bref Update AES context + * + * @param incontext AES context point + * insrc the data point of update + * insrclen the data length + * indst the data pint of output + * + * @return the result + * 0 : sucessful + * others : failed + */ +int esp_mfi_aes_ctr_update(esp_mfi_aes_ctr_t incontext, const void *insrc, uint16_t insrclen, void *indst) +{ + int ret = 0; + + if (incontext == NULL) + return -EINVAL; + + aes_ctr_context_t *context = incontext; + size_t offset = 0; + uint8_t stream_block[MFI_AES_CTR_SIZE]; + mbedtls_aes_context ctx; + mbedtls_aes_init(&ctx); + + ret = mbedtls_aes_setkey_enc( &ctx, context->key, 128); + + if (ret != 0) { + ESP_LOGE(TAG, "mfi aes setkey[%d]", ret); + ret = -EINVAL; + } else { + ret = mbedtls_aes_crypt_ctr(&ctx, insrclen, &offset, context->nonce, stream_block, (uint8_t *) insrc, indst); + if (ret != 0) { + ESP_LOGE(TAG, "mfi aes crypt[%d]", ret); + ret = -EINVAL; + } + } + + return ret; +} + +/** + * @bref Destory AES context point + * + * @param incontext AES context point + * + * @return none + */ +void esp_mfi_aes_ctr_final(esp_mfi_aes_ctr_t incontext) +{ + if (incontext) { + memset((aes_ctr_context_t *) incontext, 0, sizeof(aes_ctr_context_t)); + free(incontext); + } +} diff --git a/pool/shard004/C/0097802_sram.c b/pool/shard004/C/0097802_sram.c new file mode 100644 index 0000000000000000000000000000000000000000..779db1689c5a407de1d614c1f4e4b79f5fb27580 --- /dev/null +++ b/pool/shard004/C/0097802_sram.c @@ -0,0 +1,92 @@ +/* + * ETA/OS test application + * Author: Michel Megens + */ + +#include +#include +#include +#include +#include +#include +#include +#include + +int sram_stress_write_byte(uint16_t addr, uint8_t byte) +{ + int fd, rc; + struct vfile * stream; + + fd = open("23K256", _FDEV_SETUP_RW); + + if(fd >= 0) { + stream = filep(fd); + lseek(stream, addr, SEEK_SET); + rc = putc(byte, stream); + close(fd); + } else { + rc = -1; + } + + return rc; +} + +int sram_stress_read_byte(uint16_t addr, uint8_t *store) +{ + int rc, fd; + struct vfile * stream; + + fd = open("23K256", _FDEV_SETUP_RW); + + if(fd >= 0) { + stream = filep(fd); + lseek(stream, addr, SEEK_SET); + rc = getc(stream); + *store = (uint8_t)rc; + close(fd); + } else { + *store = -1; + rc = -1; + } + + return rc; +} + +int sram_stress_read(uint16_t addr, void *buff, size_t len) +{ + int rc, fd; + struct vfile *stream; + + fd = open("23K256", _FDEV_SETUP_RW); + + if(fd >= 0) { + stream = filep(fd); + lseek(stream, addr, SEEK_SET); + rc = read(fd, buff, len); + close(fd); + } else { + rc = -1; + } + + return rc; +} + +int sram_stress_write(uint16_t addr, const void *buff, size_t len) +{ + int fd, rc; + struct vfile *stream; + + fd = open("23K256", _FDEV_SETUP_RW); + + if(fd >= 0) { + stream = filep(fd); + lseek(stream, addr, SEEK_SET); + rc = write(fd, buff, len); + close(fd); + } else { + rc = -1; + } + + return rc; +} + diff --git a/pool/shard004/C/0097804_biop_dsm.c b/pool/shard004/C/0097804_biop_dsm.c new file mode 100644 index 0000000000000000000000000000000000000000..93b63fea1f1a5c9516b015c68a54786eeab6e671 --- /dev/null +++ b/pool/shard004/C/0097804_biop_dsm.c @@ -0,0 +1,259 @@ +/* +$Id: biop_dsm.c,v 1.3 2009/11/22 15:36:05 rhabarber1848 Exp $ + + + DVBSNOOP + + a dvb sniffer and mpeg2 stream analyzer tool + http://dvbsnoop.sourceforge.net/ + + (c) 2001-2006 Rainer.Scherg@gmx.de (rasc) + + + -- dsmcc (BIOP) DSM:: routines + -- TS 102 812 + -- TS 101 202 + -- ISO 13818-6 + +*/ + +#include "dvbsnoop.h" +#include "biop_dsm.h" +#include "biop_tag_tap.h" +#include "dsmcc_misc.h" + +#include "misc/output.h" +#include "misc/hexprint.h" + +#include "strings/dsmcc_str.h" +#include "strings/dvb_str.h" + + + +/* + * dsmcc BIOP DSM::ConnBinder(); + * TS 102 812 + * return: len + */ + + +int BIOP_DSM_ConnBinder (int v, u_char *b) +{ + int len; + int n3; + + + out_nl (v,"DSM::ConnBinder"); + indent (+1); + + outBit_S2x_NL (v,"componentId_tag: ", b, 0, 32, + (char *(*)(u_long)) dsmccStrIOP_ProfileID ); + len = outBit_Sx_NL (v,"component_data_length: ", b, 32, 8); + + + n3 = outBit_Sx_NL (v,"tap_count: ", b, 40, 8); + b += 6; + indent (+1); + for (; n3 > 0; n3--) { + int n4; + + n4 = BIOP_TAP (v, "DSM", b); + b += n4; + } + indent (-1); + + + indent (-1); + out_NL (v); + return len+5; +} + + + + + +/* + * dsmcc BIOP DSM::ServiceLocation (); + * TS 102 812 + * return: len + */ + + +int BIOP_DSM_ServiceLocation (int v, u_char *b) +{ + int len; + int sd_len; + int n; + u_long n5; + + + out_nl (v,"DSM::ServiceLocation"); + indent (+1); + + outBit_S2x_NL (v,"componentId_tag: ", b, 0, 32, + (char *(*)(u_long)) dsmccStrIOP_ProfileID ); + len = outBit_Sx_NL (v,"component_data_length: ", b, 32, 8); + len += 4; + sd_len = outBit_Sx_NL (v,"service_domain_length: ", b, 40, 8); + b += 6; + + BIOP_DSM_ServiceDomain (v,b, sd_len); + b += sd_len; + + n = BIOP_DSM_CosNaming_Name (v,b); + b += n; + + n5 = outBit_Sx_NL (v,"initialContext_length: ", b, 0, 32); + print_databytes (v,"InitialContext_data_byte:", b+4, n5); + // b += n5; + + indent (-1); + out_NL (v); + return len; +} + + + + + +/* + * ServiceDomain Data for DSM::ServiceLocation + * return: len + */ + +int BIOP_DSM_ServiceDomain (int v, u_char *b, int len) +{ + + dsmcc_carousel_NSAP_address_B20 (v, "DSM::ServiceDomain", b); + out_NL (v); + return len; +} + + + + + +/* + * CosNaming::Name for DSM::ServiceLocation + * (Similar to BIOP::Name, but 32bit length fields) + * return: len + */ + +int BIOP_DSM_CosNaming_Name (int v, u_char *b) +{ + u_char *b_org = b; + u_long n2; + + + out_nl (v,"CosNaming::Name"); + indent (+1); + + n2 = outBit_Sx_NL (v,"nameComponents_count: ", b, 0, 32); + b += 4; + + for (; n2 > 0; n2--) { + u_long n3,n4; + + n3 = outBit_Sx_NL (v,"id_length: ", b, 0, 32); + print_databytes (v,"id_data:", b+4, n3); + b += 4 + n3; + + n4 = outBit_Sx_NL (v,"kind_length: ", b, 0, 32); + print_databytes (v,"kind_data:", b+4, n4); + b += 4 + n4; + + } + + indent (-1); + out_NL (v); + return (int) (b - b_org); +} + + + + + + +/* + * DSM::Stream::Info_T for BIOP Messages + * return: len + */ + +int BIOP_DSM_Stream_Info_T (int v, u_char *b) +{ + int n; + + + out_nl (v,"DSM::Stream::Info_T"); + indent (+1); + + n = outBit_Sx_NL (v,"aDescription_length: ", b, 0, 8); + print_databytes (v,"aDescription:", b+1, n); + b += 1+n; + + + outBit_Sx_NL (v,"duration.aSeconds: ", b, 0, 32); + outBit_Sx_NL (v,"duration.aMicroSeconds: ", b, 32, 32); + + outBit_Sx_NL (v,"audio: ", b, 64, 8); + outBit_Sx_NL (v,"video: ", b, 72, 8); + outBit_Sx_NL (v,"data: ", b, 80, 8); + + + indent (-1); + out_NL (v); + + + // there might be an error in all Standards document???? + // saying: N2- (N3+10) on a for-loop in BIOP::StreamMessage + // (the +10 should be: +12) + // for BIOP::StreamEventMessage calculations are correctly described + // $$$ TODO: to be checked + + return (1 + n + 11); +} + + + + + + +/* + * DSM::Event::EventList_T for BIOP Messages + * return: len + */ + +int BIOP_DSM_Event_EventList_T (int v, u_char *b) +{ + u_char *b_org = b; + int n1; + + + + out_nl (v,"DSM::Event::EventList_T"); + indent (+1); + + n1 = outBit_Sx_NL (v,"eventNames_count: ", b, 0, 16); + b += 2; + + indent (+1); + for (; n1 > 0; n1--) { + int n2; + + n2 = outBit_Sx_NL (v, "eventName_length: ", b, 0, 8); + print_text_UTF8 (v, "eventName_data: ", b+1, n2); + b += 1 + n2; + } + indent (-1); + + + indent (-1); + out_NL (v); + return (int) (b - b_org); +} + + + + + + diff --git a/pool/shard004/C/0097807_btnode.c b/pool/shard004/C/0097807_btnode.c new file mode 100644 index 0000000000000000000000000000000000000000..4391fd3abd8f86ccb4e14f9b562ffb3fbda13755 --- /dev/null +++ b/pool/shard004/C/0097807_btnode.c @@ -0,0 +1,273 @@ +// SPDX-License-Identifier: GPL-2.0+ +/* + * btnode.c - NILFS B-tree node cache + * + * Copyright (C) 2005-2008 Nippon Telegraph and Telephone Corporation. + * + * Originally written by Seiji Kihara. + * Fully revised by Ryusuke Konishi for stabilization and simplification. + * + */ + +#include +#include +#include +#include +#include +#include "nilfs.h" +#include "mdt.h" +#include "dat.h" +#include "page.h" +#include "btnode.h" + +void nilfs_btnode_cache_clear(struct address_space *btnc) +{ + invalidate_mapping_pages(btnc, 0, -1); + truncate_inode_pages(btnc, 0); +} + +struct buffer_head * +nilfs_btnode_create_block(struct address_space *btnc, __u64 blocknr) +{ + struct inode *inode = NILFS_BTNC_I(btnc); + struct buffer_head *bh; + + bh = nilfs_grab_buffer(inode, btnc, blocknr, BIT(BH_NILFS_Node)); + if (unlikely(!bh)) + return NULL; + + if (unlikely(buffer_mapped(bh) || buffer_uptodate(bh) || + buffer_dirty(bh))) { + brelse(bh); + BUG(); + } + memset(bh->b_data, 0, i_blocksize(inode)); + bh->b_bdev = inode->i_sb->s_bdev; + bh->b_blocknr = blocknr; + set_buffer_mapped(bh); + set_buffer_uptodate(bh); + + unlock_page(bh->b_page); + put_page(bh->b_page); + return bh; +} + +int nilfs_btnode_submit_block(struct address_space *btnc, __u64 blocknr, + sector_t pblocknr, int mode, int mode_flags, + struct buffer_head **pbh, sector_t *submit_ptr) +{ + struct buffer_head *bh; + struct inode *inode = NILFS_BTNC_I(btnc); + struct page *page; + int err; + + bh = nilfs_grab_buffer(inode, btnc, blocknr, BIT(BH_NILFS_Node)); + if (unlikely(!bh)) + return -ENOMEM; + + err = -EEXIST; /* internal code */ + page = bh->b_page; + + if (buffer_uptodate(bh) || buffer_dirty(bh)) + goto found; + + if (pblocknr == 0) { + pblocknr = blocknr; + if (inode->i_ino != NILFS_DAT_INO) { + struct the_nilfs *nilfs = inode->i_sb->s_fs_info; + + /* blocknr is a virtual block number */ + err = nilfs_dat_translate(nilfs->ns_dat, blocknr, + &pblocknr); + if (unlikely(err)) { + brelse(bh); + goto out_locked; + } + } + } + + if (mode_flags & REQ_RAHEAD) { + if (pblocknr != *submit_ptr + 1 || !trylock_buffer(bh)) { + err = -EBUSY; /* internal code */ + brelse(bh); + goto out_locked; + } + } else { /* mode == READ */ + lock_buffer(bh); + } + if (buffer_uptodate(bh)) { + unlock_buffer(bh); + err = -EEXIST; /* internal code */ + goto found; + } + set_buffer_mapped(bh); + bh->b_bdev = inode->i_sb->s_bdev; + bh->b_blocknr = pblocknr; /* set block address for read */ + bh->b_end_io = end_buffer_read_sync; + get_bh(bh); + submit_bh(mode, mode_flags, bh); + bh->b_blocknr = blocknr; /* set back to the given block address */ + *submit_ptr = pblocknr; + err = 0; +found: + *pbh = bh; + +out_locked: + unlock_page(page); + put_page(page); + return err; +} + +/** + * nilfs_btnode_delete - delete B-tree node buffer + * @bh: buffer to be deleted + * + * nilfs_btnode_delete() invalidates the specified buffer and delete the page + * including the buffer if the page gets unbusy. + */ +void nilfs_btnode_delete(struct buffer_head *bh) +{ + struct address_space *mapping; + struct page *page = bh->b_page; + pgoff_t index = page_index(page); + int still_dirty; + + get_page(page); + lock_page(page); + wait_on_page_writeback(page); + + nilfs_forget_buffer(bh); + still_dirty = PageDirty(page); + mapping = page->mapping; + unlock_page(page); + put_page(page); + + if (!still_dirty && mapping) + invalidate_inode_pages2_range(mapping, index, index); +} + +/** + * nilfs_btnode_prepare_change_key + * prepare to move contents of the block for old key to one of new key. + * the old buffer will not be removed, but might be reused for new buffer. + * it might return -ENOMEM because of memory allocation errors, + * and might return -EIO because of disk read errors. + */ +int nilfs_btnode_prepare_change_key(struct address_space *btnc, + struct nilfs_btnode_chkey_ctxt *ctxt) +{ + struct buffer_head *obh, *nbh; + struct inode *inode = NILFS_BTNC_I(btnc); + __u64 oldkey = ctxt->oldkey, newkey = ctxt->newkey; + int err; + + if (oldkey == newkey) + return 0; + + obh = ctxt->bh; + ctxt->newbh = NULL; + + if (inode->i_blkbits == PAGE_SHIFT) { + struct page *opage = obh->b_page; + lock_page(opage); +retry: + /* BUG_ON(oldkey != obh->b_page->index); */ + if (unlikely(oldkey != opage->index)) + NILFS_PAGE_BUG(opage, + "invalid oldkey %lld (newkey=%lld)", + (unsigned long long)oldkey, + (unsigned long long)newkey); + + xa_lock_irq(&btnc->i_pages); + err = __xa_insert(&btnc->i_pages, newkey, opage, GFP_NOFS); + xa_unlock_irq(&btnc->i_pages); + /* + * Note: page->index will not change to newkey until + * nilfs_btnode_commit_change_key() will be called. + * To protect the page in intermediate state, the page lock + * is held. + */ + if (!err) + return 0; + else if (err != -EBUSY) + goto failed_unlock; + + err = invalidate_inode_pages2_range(btnc, newkey, newkey); + if (!err) + goto retry; + /* fallback to copy mode */ + unlock_page(opage); + } + + nbh = nilfs_btnode_create_block(btnc, newkey); + if (!nbh) + return -ENOMEM; + + BUG_ON(nbh == obh); + ctxt->newbh = nbh; + return 0; + + failed_unlock: + unlock_page(obh->b_page); + return err; +} + +/** + * nilfs_btnode_commit_change_key + * commit the change_key operation prepared by prepare_change_key(). + */ +void nilfs_btnode_commit_change_key(struct address_space *btnc, + struct nilfs_btnode_chkey_ctxt *ctxt) +{ + struct buffer_head *obh = ctxt->bh, *nbh = ctxt->newbh; + __u64 oldkey = ctxt->oldkey, newkey = ctxt->newkey; + struct page *opage; + + if (oldkey == newkey) + return; + + if (nbh == NULL) { /* blocksize == pagesize */ + opage = obh->b_page; + if (unlikely(oldkey != opage->index)) + NILFS_PAGE_BUG(opage, + "invalid oldkey %lld (newkey=%lld)", + (unsigned long long)oldkey, + (unsigned long long)newkey); + mark_buffer_dirty(obh); + + xa_lock_irq(&btnc->i_pages); + __xa_erase(&btnc->i_pages, oldkey); + __xa_set_mark(&btnc->i_pages, newkey, PAGECACHE_TAG_DIRTY); + xa_unlock_irq(&btnc->i_pages); + + opage->index = obh->b_blocknr = newkey; + unlock_page(opage); + } else { + nilfs_copy_buffer(nbh, obh); + mark_buffer_dirty(nbh); + + nbh->b_blocknr = newkey; + ctxt->bh = nbh; + nilfs_btnode_delete(obh); /* will decrement bh->b_count */ + } +} + +/** + * nilfs_btnode_abort_change_key + * abort the change_key operation prepared by prepare_change_key(). + */ +void nilfs_btnode_abort_change_key(struct address_space *btnc, + struct nilfs_btnode_chkey_ctxt *ctxt) +{ + struct buffer_head *nbh = ctxt->newbh; + __u64 oldkey = ctxt->oldkey, newkey = ctxt->newkey; + + if (oldkey == newkey) + return; + + if (nbh == NULL) { /* blocksize == pagesize */ + xa_erase_irq(&btnc->i_pages, newkey); + unlock_page(ctxt->bh->b_page); + } else + brelse(nbh); +} diff --git a/pool/shard004/C/0097817_CWE122_Heap_Based_Buffer_Overflow__char_type_overrun_memcpy_06.c b/pool/shard004/C/0097817_CWE122_Heap_Based_Buffer_Overflow__char_type_overrun_memcpy_06.c new file mode 100644 index 0000000000000000000000000000000000000000..c36978544485425bf47a792332e5f440610b5f8a --- /dev/null +++ b/pool/shard004/C/0097817_CWE122_Heap_Based_Buffer_Overflow__char_type_overrun_memcpy_06.c @@ -0,0 +1,141 @@ +/* TEMPLATE GENERATED TESTCASE FILE +Filename: CWE122_Heap_Based_Buffer_Overflow__char_type_overrun_memcpy_06.c +Label Definition File: CWE122_Heap_Based_Buffer_Overflow.label.xml +Template File: point-flaw-06.tmpl.c +*/ +/* + * @description + * CWE: 122 Heap Based Buffer Overflow + * Sinks: type_overrun_memcpy + * GoodSink: Perform the memcpy() and prevent overwriting part of the structure + * BadSink : Overwrite part of the structure by incorrectly using the sizeof(struct) in memcpy() + * Flow Variant: 06 Control flow: if(STATIC_CONST_FIVE==5) and if(STATIC_CONST_FIVE!=5) + * + * */ + +#include "std_testcase.h" + +#ifndef _WIN32 +#include +#endif + +#define SRC_STR "0123456789abcdef0123456789abcde" + +typedef struct _charVoid +{ + char charFirst[16]; + void * voidSecond; + void * voidThird; +} charVoid; + +/* The variable below is declared "const", so a tool should be able + to identify that reads of this will always give its initialized + value. */ +static const int STATIC_CONST_FIVE = 5; + +#ifndef OMITBAD + +void CWE122_Heap_Based_Buffer_Overflow__char_type_overrun_memcpy_06_bad() +{ + if(STATIC_CONST_FIVE==5) + { + { + charVoid * structCharVoid = (charVoid *)malloc(sizeof(charVoid)); + if (structCharVoid == NULL) {exit(-1);} + structCharVoid->voidSecond = (void *)SRC_STR; + /* Print the initial block pointed to by structCharVoid->voidSecond */ + printLine((char *)structCharVoid->voidSecond); + /* FLAW: Use the sizeof(*structCharVoid) which will overwrite the pointer y */ + memcpy(structCharVoid->charFirst, SRC_STR, sizeof(*structCharVoid)); + structCharVoid->charFirst[(sizeof(structCharVoid->charFirst)/sizeof(char))-1] = '\0'; /* null terminate the string */ + printLine((char *)structCharVoid->charFirst); + printLine((char *)structCharVoid->voidSecond); + free(structCharVoid); + } + } +} + +#endif /* OMITBAD */ + +#ifndef OMITGOOD + +/* good1() uses if(STATIC_CONST_FIVE!=5) instead of if(STATIC_CONST_FIVE==5) */ +static void good1() +{ + if(STATIC_CONST_FIVE!=5) + { + /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */ + printLine("Benign, fixed string"); + } + else + { + { + charVoid * structCharVoid = (charVoid *)malloc(sizeof(charVoid)); + if (structCharVoid == NULL) {exit(-1);} + structCharVoid->voidSecond = (void *)SRC_STR; + /* Print the initial block pointed to by structCharVoid->voidSecond */ + printLine((char *)structCharVoid->voidSecond); + /* FIX: Use the sizeof(structCharVoid->charFirst) to avoid overwriting the pointer y */ + memcpy(structCharVoid->charFirst, SRC_STR, sizeof(structCharVoid->charFirst)); + structCharVoid->charFirst[(sizeof(structCharVoid->charFirst)/sizeof(char))-1] = '\0'; /* null terminate the string */ + printLine((char *)structCharVoid->charFirst); + printLine((char *)structCharVoid->voidSecond); + free(structCharVoid); + } + } +} + +/* good2() reverses the bodies in the if statement */ +static void good2() +{ + if(STATIC_CONST_FIVE==5) + { + { + charVoid * structCharVoid = (charVoid *)malloc(sizeof(charVoid)); + if (structCharVoid == NULL) {exit(-1);} + structCharVoid->voidSecond = (void *)SRC_STR; + /* Print the initial block pointed to by structCharVoid->voidSecond */ + printLine((char *)structCharVoid->voidSecond); + /* FIX: Use the sizeof(structCharVoid->charFirst) to avoid overwriting the pointer y */ + memcpy(structCharVoid->charFirst, SRC_STR, sizeof(structCharVoid->charFirst)); + structCharVoid->charFirst[(sizeof(structCharVoid->charFirst)/sizeof(char))-1] = '\0'; /* null terminate the string */ + printLine((char *)structCharVoid->charFirst); + printLine((char *)structCharVoid->voidSecond); + free(structCharVoid); + } + } +} + +void CWE122_Heap_Based_Buffer_Overflow__char_type_overrun_memcpy_06_good() +{ + good1(); + good2(); +} + +#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__char_type_overrun_memcpy_06_good(); + printLine("Finished good()"); +#endif /* OMITGOOD */ +#ifndef OMITBAD + printLine("Calling bad()..."); + CWE122_Heap_Based_Buffer_Overflow__char_type_overrun_memcpy_06_bad(); + printLine("Finished bad()"); +#endif /* OMITBAD */ + return 0; +} + +#endif diff --git a/pool/shard004/C/0097824_dialog_nonmodal1.c b/pool/shard004/C/0097824_dialog_nonmodal1.c new file mode 100644 index 0000000000000000000000000000000000000000..170f9aa3979f9f729f9a00677e314c08af43bf2f --- /dev/null +++ b/pool/shard004/C/0097824_dialog_nonmodal1.c @@ -0,0 +1,72 @@ + +/* + + A non-modal dialog in GTK+. There is also an example of this in the Python folder that is named +similarly. + + gcc -Wall dialog_nonmodal1.c -o dialog_nonmodal1 `pkg-config --cflags --libs gtk+-3.0` + + Tested on Ubuntu14.04 and GTK3.10 + + C. Eric Cashon + +*/ + +#include + +static void open_dialog(GtkWidget *widget, gpointer data); + +int main(int argc, char **argv) + { + gtk_init(&argc, &argv); + + GtkWidget *window=gtk_window_new(GTK_WINDOW_TOPLEVEL); + gtk_window_set_position(GTK_WINDOW(window), GTK_WIN_POS_CENTER); + gtk_window_set_default_size(GTK_WINDOW(window), 300, 100); + gtk_window_set_title(GTK_WINDOW(window), "Non Modal Dialogs"); + g_signal_connect(window, "destroy", G_CALLBACK(gtk_main_quit), NULL); + + GtkWidget *button1=gtk_toggle_button_new_with_label("Show Dialog"); + gtk_widget_set_hexpand(button1, TRUE); + gtk_widget_set_vexpand(button1, TRUE); + g_signal_connect(button1, "clicked", G_CALLBACK(open_dialog), window); + + GtkWidget *grid=gtk_grid_new(); + gtk_grid_attach(GTK_GRID(grid), button1, 0, 0, 1, 1); + + gtk_container_add(GTK_CONTAINER(window), grid); + + gtk_widget_show_all(window); + gtk_main(); + return 0; + } +static void open_dialog(GtkWidget *widget, gpointer data) + { + //Non modal dialog. Open several dialog windows from the main window. + static gint i=1; + gchar *dialog_label=g_strdup_printf("Dialog Window%i", i); + GtkWidget *dialog=gtk_dialog_new_with_buttons("Dialog", GTK_WINDOW(data), GTK_DIALOG_DESTROY_WITH_PARENT, "Close", GTK_RESPONSE_CLOSE, NULL); + gtk_window_set_default_size(GTK_WINDOW(dialog), 200, 100); + + GtkWidget *box=gtk_dialog_get_content_area(GTK_DIALOG(dialog)); + GtkWidget *label=gtk_label_new(dialog_label); + gtk_box_pack_start(GTK_BOX(box), label, TRUE, TRUE, 0); + + g_signal_connect(dialog, "response", G_CALLBACK(gtk_widget_destroy), NULL); + gtk_widget_show_all(dialog); + + //Move the windows. + gint width = gdk_screen_width(); + gint height = gdk_screen_height(); + gint sections_x = width / 100; + gint sections_y = height / 100; + gint s1 = (i - 1) % (sections_x * sections_y); + gint move_x = (s1 % sections_x) * 100; + gint move_y = (s1 / sections_x) * 100; + g_print("Move %i %i %i %i %i %i\n", width, height, sections_x, sections_y, move_x, move_y); + gtk_window_move(GTK_WINDOW(dialog), move_x, move_y); + + i++; + g_free(dialog_label); + } + diff --git a/pool/shard004/C/0097830_power.c b/pool/shard004/C/0097830_power.c new file mode 100644 index 0000000000000000000000000000000000000000..bde18c1655999c4c47f5e0414302cc92f17de347 --- /dev/null +++ b/pool/shard004/C/0097830_power.c @@ -0,0 +1,142 @@ +/* $OpenBSD: power.c,v 1.7 2014/07/11 08:18:31 guenther Exp $ */ + +/* + * Copyright (c) 2006 Jason L. Wright (jason@thought.net) + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, + * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, + * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ + +/* + * Driver for power-button device on U5, U10, etc. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +#include +#include + +#define POWER_REG 0 + +#define POWER_REG_CPWR_OFF 0x00000002 /* courtesy power off */ +#define POWER_REG_SPWR_OFF 0x00000001 /* system power off */ + +struct power_softc { + struct device sc_dev; + bus_space_tag_t sc_iot; + bus_space_handle_t sc_ioh; + struct intrhand *sc_ih; +}; + +int power_match(struct device *, void *, void *); +void power_attach(struct device *, struct device *, void *); +int power_intr(void *); + +struct cfattach power_ca = { + sizeof(struct power_softc), power_match, power_attach +}; + +struct cfdriver power_cd = { + NULL, "power", DV_DULL +}; + +int +power_match(parent, match, aux) + struct device *parent; + void *match; + void *aux; +{ + struct ebus_attach_args *ea = aux; + + if (strcmp(ea->ea_name, "power") == 0) + return (1); + return (0); +} + +void +power_attach(parent, self, aux) + struct device *parent, *self; + void *aux; +{ + struct power_softc *sc = (void *)self; + struct ebus_attach_args *ea = aux; + + if (ea->ea_nregs < 1) { + printf(": no registers\n"); + return; + } + + /* Use prom address if available, otherwise map it. */ + if (ea->ea_nvaddrs) { + if (bus_space_map(ea->ea_memtag, ea->ea_vaddrs[0], 0, + BUS_SPACE_MAP_PROMADDRESS, &sc->sc_ioh)) { + printf(": can't map PROM register space\n"); + return; + } + sc->sc_iot = ea->ea_memtag; + } else if (ebus_bus_map(ea->ea_iotag, 0, + EBUS_PADDR_FROM_REG(&ea->ea_regs[0]), + ea->ea_regs[0].size, 0, 0, &sc->sc_ioh) == 0) { + sc->sc_iot = ea->ea_iotag; + } else if (ebus_bus_map(ea->ea_memtag, 0, + EBUS_PADDR_FROM_REG(&ea->ea_regs[0]), + ea->ea_regs[0].size, 0, 0, &sc->sc_ioh) == 0) { + sc->sc_iot = ea->ea_memtag; + } else { + printf("%s: can't map register space\n", self->dv_xname); + return; + } + + if (ea->ea_nintrs > 0 && OF_getproplen(ea->ea_node, "button") >= 0) { + sc->sc_ih = bus_intr_establish(sc->sc_iot, ea->ea_intrs[0], + IPL_BIO, 0, power_intr, sc, self->dv_xname); + if (sc->sc_ih == NULL) { + printf(": can't establish interrupt\n"); + return; + } + } + printf("\n"); +} + +int +power_intr(void *vsc) +{ + extern int allowpowerdown; + + if (allowpowerdown == 1) { + allowpowerdown = 0; + prsignal(initprocess, SIGUSR2); + } + return (1); +} diff --git a/pool/shard004/C/0097836_load.c b/pool/shard004/C/0097836_load.c new file mode 100644 index 0000000000000000000000000000000000000000..6a5d4ed97c2c1a6bffafab1bf93d1e8536dd330d --- /dev/null +++ b/pool/shard004/C/0097836_load.c @@ -0,0 +1,78 @@ +/* + Unix SMB/CIFS implementation. + load printer lists + Copyright (C) Andrew Tridgell 1992-2000 + + 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 "printing/pcap.h" +#include "printing/load.h" +#include "lib/param/loadparm.h" + +/*************************************************************************** +auto-load some homes and printer services +***************************************************************************/ +static void add_auto_printers(void) +{ + const struct loadparm_substitution *lp_sub = + loadparm_s3_global_substitution(); + const char *p; + int pnum = lp_servicenumber(PRINTERS_NAME); + char *str; + char *saveptr; + char *auto_serv = NULL; + + if (pnum < 0) + if (process_registry_service(PRINTERS_NAME)) + pnum = lp_servicenumber(PRINTERS_NAME); + + if (pnum < 0) + return; + + auto_serv = lp_auto_services(talloc_tos(), lp_sub); + str = SMB_STRDUP(auto_serv); + TALLOC_FREE(auto_serv); + if (str == NULL) { + return; + } + + for (p = strtok_r(str, LIST_SEP, &saveptr); p; + p = strtok_r(NULL, LIST_SEP, &saveptr)) { + if (lp_servicenumber(p) >= 0) + continue; + + if (pcap_printername_ok(p)) + lp_add_printer(p, pnum); + } + + SAFE_FREE(str); +} + +/*************************************************************************** +load automatic printer services from pre-populated pcap cache +***************************************************************************/ +void load_printers(void) +{ + if (!pcap_cache_loaded(NULL)) { + return; + } + + add_auto_printers(); + + /* load all printcap printers */ + if (lp_load_printers() && lp_servicenumber(PRINTERS_NAME) >= 0) + pcap_printer_read_fn(lp_add_one_printer, NULL); +} diff --git a/pool/shard004/C/0097838_gamma.c b/pool/shard004/C/0097838_gamma.c new file mode 100644 index 0000000000000000000000000000000000000000..a3607f8c23dd6fea2445eb36f087517a23f42e1b --- /dev/null +++ b/pool/shard004/C/0097838_gamma.c @@ -0,0 +1,86 @@ +/** \file gamma.c + * + * \author Copyright 2001 Lutz Mueller + * + * \par License + * 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. + * + * \par + * 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. + * + * \par + * 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 "config.h" +#include "gamma.h" + +#include + +#include + +static int +gp_gamma_correct_triple (unsigned char *table_red, + unsigned char *table_green, + unsigned char *table_blue, + unsigned char *data, unsigned int size) +{ + unsigned int x; + + for (x = 0; x < (size * 3); x += 3) { + data[x + 0] = table_red [data[x + 0]]; + data[x + 1] = table_green[data[x + 1]]; + data[x + 2] = table_blue [data[x + 2]]; + } + + return (GP_OK); +} + +/** + * \brief Gamma correction + * + * Corrects size pixels within the table with a given Gamma + * correction table. + * + * \param table the gamma correction table as generated by gp_gamma_fill_table() + * \param data the data do process, both input and output + * \param size in number of pixels (RGB byte pairs) + * + * \returns a gphoto error code + */ +int +gp_gamma_correct_single (unsigned char *table, unsigned char *data, + unsigned int size) +{ + return (gp_gamma_correct_triple (table, table, table, data, size)); +} + +/** + * \brief Initialize a Gamma conversion table + * + * Initializes the gamma conversion table for later use by gp_gamma_correct_single(). + * Requires a 256 byte array as table. + * \param table a 256 byte array of unsigned char + * \param g gamma correction value + * + * \returns a gphoto error code + */ +int +gp_gamma_fill_table (unsigned char *table, double g) +{ + unsigned int x; + + for (x = 0; x < 256; x++) + table[x] = 255 * pow ((double) x/255., g); + + return (GP_OK); +} diff --git a/pool/shard004/C/0097844_reset.c b/pool/shard004/C/0097844_reset.c new file mode 100644 index 0000000000000000000000000000000000000000..3256b9228e75801a7d91ad9c95235bd7c420d779 --- /dev/null +++ b/pool/shard004/C/0097844_reset.c @@ -0,0 +1,127 @@ +/* + * Copyright (C) 2012,2013 - ARM Ltd + * Author: Marc Zyngier + * + * Derived from arch/arm/kvm/reset.c + * Copyright (C) 2012 - Virtual Open Systems and Columbia University + * Author: Christoffer Dall + * + * 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 + +/* + * ARMv8 Reset Values + */ +static const struct kvm_regs default_regs_reset = { + .regs.pstate = (PSR_MODE_EL1h | PSR_A_BIT | PSR_I_BIT | + PSR_F_BIT | PSR_D_BIT), +}; + +static const struct kvm_regs default_regs_reset32 = { + .regs.pstate = (COMPAT_PSR_MODE_SVC | COMPAT_PSR_A_BIT | + COMPAT_PSR_I_BIT | COMPAT_PSR_F_BIT), +}; + +static bool cpu_has_32bit_el1(void) +{ + u64 pfr0; + + pfr0 = read_sanitised_ftr_reg(SYS_ID_AA64PFR0_EL1); + return !!(pfr0 & 0x20); +} + +/** + * kvm_arch_dev_ioctl_check_extension + * + * We currently assume that the number of HW registers is uniform + * across all CPUs (see cpuinfo_sanity_check). + */ +int kvm_arch_dev_ioctl_check_extension(struct kvm *kvm, long ext) +{ + int r; + + switch (ext) { + case KVM_CAP_ARM_EL1_32BIT: + r = cpu_has_32bit_el1(); + break; + case KVM_CAP_GUEST_DEBUG_HW_BPS: + r = get_num_brps(); + break; + case KVM_CAP_GUEST_DEBUG_HW_WPS: + r = get_num_wrps(); + break; + case KVM_CAP_ARM_PMU_V3: + r = kvm_arm_support_pmu_v3(); + break; + case KVM_CAP_SET_GUEST_DEBUG: + case KVM_CAP_VCPU_ATTRIBUTES: + r = 1; + break; + default: + r = 0; + } + + return r; +} + +/** + * kvm_reset_vcpu - sets core registers and sys_regs to reset value + * @vcpu: The VCPU pointer + * + * This function finds the right table above and sets the registers on + * the virtual CPU struct to their architecturally defined reset + * values. + */ +int kvm_reset_vcpu(struct kvm_vcpu *vcpu) +{ + const struct kvm_regs *cpu_reset; + + switch (vcpu->arch.target) { + default: + if (test_bit(KVM_ARM_VCPU_EL1_32BIT, vcpu->arch.features)) { + if (!cpu_has_32bit_el1()) + return -EINVAL; + cpu_reset = &default_regs_reset32; + } else { + cpu_reset = &default_regs_reset; + } + + break; + } + + /* Reset core registers */ + memcpy(vcpu_gp_regs(vcpu), cpu_reset, sizeof(*cpu_reset)); + + /* Reset system registers */ + kvm_reset_sys_regs(vcpu); + + /* Reset PMU */ + kvm_pmu_vcpu_reset(vcpu); + + /* Reset timer */ + return kvm_timer_vcpu_reset(vcpu); +} diff --git a/pool/shard004/C/0097845_tst-calloc.c b/pool/shard004/C/0097845_tst-calloc.c new file mode 100644 index 0000000000000000000000000000000000000000..9a879f4cfe8772e51001dfd4dd4764bc3e0560d9 --- /dev/null +++ b/pool/shard004/C/0097845_tst-calloc.c @@ -0,0 +1,128 @@ +/* Copyright (C) 2000-2016 Free Software Foundation, Inc. + This file is part of the GNU C Library. + Contributed by Ulrich Drepper . + + 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 + + +/* Number of samples per size. */ +#define N 50000 + + +static void +fixed_test (int size) +{ + char *ptrs[N]; + int i; + + for (i = 0; i < N; ++i) + { + int j; + + ptrs[i] = (char *) calloc (1, size); + + if (ptrs[i] == NULL) + break; + + for (j = 0; j < size; ++j) + { + if (ptrs[i][j] != '\0') + error (EXIT_FAILURE, 0, + "byte not cleared (size %d, element %d, byte %d)", + size, i, j); + ptrs[i][j] = '\xff'; + } + } + + while (i-- > 0) + free (ptrs[i]); +} + + +static void +random_test (void) +{ + char *ptrs[N]; + int i; + + for (i = 0; i < N; ++i) + { + int j; + int n = 1 + random () % 10; + int elem = 1 + random () % 100; + int size = n * elem; + + ptrs[i] = (char *) calloc (n, elem); + + if (ptrs[i] == NULL) + break; + + for (j = 0; j < size; ++j) + { + if (ptrs[i][j] != '\0') + error (EXIT_FAILURE, 0, + "byte not cleared (size %d, element %d, byte %d)", + size, i, j); + ptrs[i][j] = '\xff'; + } + } + + while (i-- > 0) + free (ptrs[i]); +} + + +static void +null_test (void) +{ + /* If the size is 0 the result is implementation defined. Just make + sure the program doesn't crash. */ + calloc (0, 0); + calloc (0, UINT_MAX); + calloc (UINT_MAX, 0); + calloc (0, ~((size_t) 0)); + calloc (~((size_t) 0), 0); +} + + +static int +do_test (void) +{ + /* We are allocating blocks with `calloc' and check whether every + block is completely cleared. We first try this for some fixed + times and then with random size. */ + fixed_test (15); + fixed_test (5); + fixed_test (17); + fixed_test (6); + fixed_test (31); + fixed_test (96); + + random_test (); + + null_test (); + + return 0; +} + +#define TEST_FUNCTION do_test () +#include "../test-skeleton.c" diff --git a/pool/shard004/C/0097846_icmp.c b/pool/shard004/C/0097846_icmp.c new file mode 100644 index 0000000000000000000000000000000000000000..244e33c9962990ebe89ee9afa75674631f96887f --- /dev/null +++ b/pool/shard004/C/0097846_icmp.c @@ -0,0 +1,313 @@ +/** + * @file + * ICMP - Internet Control Message Protocol + * + */ + +/* + * Copyright (c) 2001-2004 Swedish Institute of Computer Science. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT + * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT + * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY + * OF SUCH DAMAGE. + * + * This file is part of the lwIP TCP/IP stack. + * + * Author: Adam Dunkels + * + */ + +/* Some ICMP messages should be passed to the transport protocols. This + is not implemented. */ + +#include "lwip/opt.h" + +#if LWIP_ICMP /* don't build if not configured for use in lwipopts.h */ + +#include "ipv4/icmp.h" +#include "inet.h" +#include "ipv4/ip4.h" +#include "lwip/def.h" +#include "lwip/stats.h" +#include "lwip/snmp.h" + +#include +#include +#include "sprintf.hh" + +/** Small optimization: set to 0 if incoming PBUF_POOL pbuf always can be + * used to modify and send a response packet (and to 1 if this is not the case, + * e.g. when link header is stripped of when receiving) */ +#ifndef LWIP_ICMP_ECHO_CHECK_INPUT_PBUF_LEN +#define LWIP_ICMP_ECHO_CHECK_INPUT_PBUF_LEN 1 +#endif /* LWIP_ICMP_ECHO_CHECK_INPUT_PBUF_LEN */ + +/* The amount of data from the original packet to return in a dest-unreachable */ +#define ICMP_DEST_UNREACH_DATASIZE 8 + +static void icmp_send_response(struct pbuf *p, u8_t type, u8_t code); + +/** + * Processes ICMP input packets, called from ip_input(). + * + * Currently only processes icmp echo requests and sends + * out the echo response. + * + * @param p the icmp echo request packet, p->payload pointing to the ip header + * @param inp the netif on which this packet was received + */ +void icmp_input(struct pbuf *p, struct netif *inp) { + u8_t type; +#ifdef LWIP_DEBUG + u8_t code; +#endif /* LWIP_DEBUG */ + struct icmp_echo_hdr *iecho; + struct ip4_hdr *iphdr; + struct ip4_addr tmpaddr; + s16_t hlen; + + ICMP_STATS_INC(icmp.recv);snmp_inc_icmpinmsgs(); + + iphdr = p->payload; + hlen = IP4H_HL(iphdr) * 4; + if (pbuf_header(p, -hlen) || (p->tot_len < sizeof(u16_t) * 2)) { + LWIP_DEBUGF(ICMP_DEBUG, ("icmp_input: short ICMP (%"U16_F" bytes) received\n", p->tot_len)); + goto lenerr; + } + + type = *((u8_t *) p->payload); +#ifdef LWIP_DEBUG + code = *(((u8_t *) p->payload) + 1); +#endif /* LWIP_DEBUG */ + switch (type) { + case ICMP_ECHO: +#if !LWIP_MULTICAST_PING || !LWIP_BROADCAST_PING + { + int accepted = 1; +#if !LWIP_MULTICAST_PING + /* multicast destination address? */ + if (ip4_addr_ismulticast(&iphdr->dest)) { + accepted = 0; + } +#endif /* LWIP_MULTICAST_PING */ +#if !LWIP_BROADCAST_PING + /* broadcast destination address? */ + if (ip4_addr_isbroadcast(&iphdr->dest, inp)) { + accepted = 0; + } +#endif /* LWIP_BROADCAST_PING */ + /* broadcast or multicast destination address not acceptd? */ + if (!accepted) { + LWIP_DEBUGF(ICMP_DEBUG, ("icmp_input: Not echoing to multicast or broadcast pings\n"));ICMP_STATS_INC(icmp.err); + pbuf_free(p); + return; + } + } +#endif /* !LWIP_MULTICAST_PING || !LWIP_BROADCAST_PING */ + LWIP_DEBUGF(ICMP_DEBUG, ("icmp_input: ping\n")); + if (p->tot_len < sizeof(struct icmp_echo_hdr)) { + LWIP_DEBUGF(ICMP_DEBUG, ("icmp_input: bad ICMP echo received\n")); + goto lenerr; + } + //if (inet_chksum_pbuf(p) != 0) { + if (inet_chksum(p->payload, p->len) != 0) { + LWIP_DEBUGF(ICMP_DEBUG, ("icmp_input: checksum failed for received ICMP echo\n")); + pbuf_free(p); + ICMP_STATS_INC(icmp.chkerr);snmp_inc_icmpinerrors(); + return; + } +#if LWIP_ICMP_ECHO_CHECK_INPUT_PBUF_LEN + if (pbuf_header(p, (PBUF_IP4_HLEN + PBUF_LINK_HLEN))) { + /* p is not big enough to contain link headers + * allocate a new one and copy p into it + */ + struct pbuf *r; + /* switch p->payload to ip header */ + if (pbuf_header(p, hlen)) { + LWIP_ASSERT("icmp_input: moving p->payload to ip header failed\n", 0); + goto memerr; + } + /* allocate new packet buffer with space for link headers */ + r = pbuf_alloc(PBUF_LINK, p->tot_len, PBUF_RAM); + if (r == NULL) { + LWIP_DEBUGF(ICMP_DEBUG, ("icmp_input: allocating new pbuf failed\n")); + goto memerr; + } + LWIP_ASSERT("check that first pbuf can hold struct the ICMP header", (r->len >= hlen + sizeof(struct icmp_echo_hdr))); + /* copy the whole packet including ip header */ + if (pbuf_copy(r, p) != ERR_OK) { + LWIP_ASSERT("icmp_input: copying to new pbuf failed\n", 0); + goto memerr; + } + iphdr = r->payload; + /* switch r->payload back to icmp header */ + if (pbuf_header(r, -hlen)) { + LWIP_ASSERT("icmp_input: restoring original p->payload failed\n", 0); + goto memerr; + } + /* free the original p */ + pbuf_free(p); + /* we now have an identical copy of p that has room for link headers */ + p = r; + } else { + /* restore p->payload to point to icmp header */ + if (pbuf_header(p, -(s16_t) (PBUF_IP4_HLEN + PBUF_LINK_HLEN))) { + LWIP_ASSERT("icmp_input: restoring original p->payload failed\n", 0); + goto memerr; + } + } +#endif /* LWIP_ICMP_ECHO_CHECK_INPUT_PBUF_LEN */ + /* At this point, all checks are OK. */ + /* We generate an answer by switching the dest and src ip addresses, + * setting the icmp type to ECHO_RESPONSE and updating the checksum. */ + iecho = p->payload; + tmpaddr.addr = iphdr->src.addr; + iphdr->src.addr = iphdr->dest.addr; + iphdr->dest.addr = tmpaddr.addr; + ICMPH_TYPE_SET(iecho, ICMP_ER); + /* adjust the checksum */ + if (iecho->chksum >= htons(0xffff - (ICMP_ECHO << 8))) { + iecho->chksum += htons(ICMP_ECHO << 8) + 1; + } else { + iecho->chksum += htons(ICMP_ECHO << 8); + } + + /* Set the correct TTL and recalculate the header checksum. */ + IP4H_TTL_SET(iphdr, ICMP_TTL); + IP4H_CHKSUM_SET(iphdr, 0); +#if CHECKSUM_GEN_IP + IP4H_CHKSUM_SET(iphdr, inet_chksum(iphdr, IP4_HLEN)); +#endif /* CHECKSUM_GEN_IP */ + + ICMP_STATS_INC(icmp.xmit); + /* increase number of messages attempted to send */ + snmp_inc_icmpoutmsgs(); + /* increase number of echo replies attempted to send */ + snmp_inc_icmpoutechoreps(); + + if (pbuf_header(p, hlen)) { + LWIP_ASSERT("Can't move over header in packet", 0); + } else { + err_t ret; + ret = ip4_output_if(p, &(iphdr->src), IP4_HDRINCL, + ICMP_TTL, 0, IP4_PROTO_ICMP, inp); + if (ret != ERR_OK) { + LWIP_DEBUGF(ICMP_DEBUG, ("icmp_input: ip_output_if returned an error: %c.\n", ret)); + } + } + break; + default: + LWIP_DEBUGF(ICMP_DEBUG, ("icmp_input: ICMP type %"S16_F" code %"S16_F" not supported.\n", (s16_t)type, (s16_t)code)); + ICMP_STATS_INC(icmp.proterr); + ICMP_STATS_INC(icmp.drop); + } + pbuf_free(p); + return; + lenerr: pbuf_free(p); + ICMP_STATS_INC(icmp.lenerr);snmp_inc_icmpinerrors(); + return; +#if LWIP_ICMP_ECHO_CHECK_INPUT_PBUF_LEN + memerr: pbuf_free(p); + ICMP_STATS_INC(icmp.err);snmp_inc_icmpinerrors(); + return; +#endif /* LWIP_ICMP_ECHO_CHECK_INPUT_PBUF_LEN */ +} + +/** + * Send an icmp 'destination unreachable' packet, called from ip_input() if + * the transport layer protocol is unknown and from udp_input() if the local + * port is not bound. + * + * @param p the input packet for which the 'unreachable' should be sent, + * p->payload pointing to the IP header + * @param t type of the 'unreachable' packet + */ +void icmp_dest_unreach(struct pbuf *p, enum icmp_dur_type t) { + icmp_send_response(p, ICMP_DUR, t); +} + +#if IP_FORWARD || IP_REASSEMBLY +/** + * Send a 'time exceeded' packet, called from ip_forward() if TTL is 0. + * + * @param p the input packet for which the 'time exceeded' should be sent, + * p->payload pointing to the IP header + * @param t type of the 'time exceeded' packet + */ +void +icmp_time_exceeded(struct pbuf *p, enum icmp_te_type t) { + icmp_send_response(p, ICMP_TE, t); +} + +#endif /* IP_FORWARD || IP_REASSEMBLY */ + +/** + * Send an icmp packet in response to an incoming packet. + * + * @param p the input packet for which the 'unreachable' should be sent, + * p->payload pointing to the IP header + * @param type Type of the ICMP header + * @param code Code of the ICMP header + */ +static void icmp_send_response(struct pbuf *p, u8_t type, u8_t code) { + struct pbuf *q; + struct ip4_hdr *iphdr; + /* we can use the echo header here */ + struct icmp_echo_hdr *icmphdr; + + /* ICMP header + IP header + 8 bytes of data */ + q = pbuf_alloc(PBUF_IP, sizeof(struct icmp_echo_hdr) + IP4_HLEN + ICMP_DEST_UNREACH_DATASIZE, PBUF_RAM); + if (q == NULL) { + LWIP_DEBUGF(ICMP_DEBUG, ("icmp_time_exceeded: failed to allocate pbuf for ICMP packet.\n")); + return; + } + LWIP_ASSERT("check that first pbuf can hold icmp message", (q->len >= (sizeof(struct icmp_echo_hdr) + IP4_HLEN + ICMP_DEST_UNREACH_DATASIZE))); + + iphdr = p->payload; + LWIP_DEBUGF(ICMP_DEBUG, ("icmp_time_exceeded from ")); + ip4_addr_debug_print(ICMP_DEBUG, &(iphdr->src)); + LWIP_DEBUGF(ICMP_DEBUG, (" to ")); + ip4_addr_debug_print(ICMP_DEBUG, &(iphdr->dest)); + LWIP_DEBUGF(ICMP_DEBUG, ("\n")); + + icmphdr = q->payload; + icmphdr->type = type; + icmphdr->code = code; + icmphdr->id = 0; + icmphdr->seqno = 0; + + /* copy fields from original packet */ + SMEMCPY((u8_t * )q->payload + sizeof(struct icmp_echo_hdr), (u8_t * )p->payload, IP4_HLEN + ICMP_DEST_UNREACH_DATASIZE); + + /* calculate checksum */ + icmphdr->chksum = 0; + icmphdr->chksum = inet_chksum(icmphdr, q->len); + ICMP_STATS_INC(icmp.xmit); + /* increase number of messages attempted to send */ + snmp_inc_icmpoutmsgs(); + /* increase number of destination unreachable messages attempted to send */ + snmp_inc_icmpouttimeexcds(); + ip4_output(q, NULL, &(iphdr->src), ICMP_TTL, 0, IP4_PROTO_ICMP); + pbuf_free(q); +} + +#endif /* LWIP_ICMP */ diff --git a/pool/shard004/C/0097849_xdr_sizeof.c b/pool/shard004/C/0097849_xdr_sizeof.c new file mode 100644 index 0000000000000000000000000000000000000000..5aa0823c8a0b69092eebd53bc100299ed2455d85 --- /dev/null +++ b/pool/shard004/C/0097849_xdr_sizeof.c @@ -0,0 +1,152 @@ +/* Copyright (c) 2010, 2016, Oracle and/or its affiliates. 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.0, + as published by the Free Software Foundation. + + This program is also distributed with certain software (including + but not limited to OpenSSL) that is licensed under separate terms, + as designated in a particular file or component or in included license + documentation. The authors of MySQL hereby grant you an additional + permission to link the program and your derivative works with the + separately licensed software that they have included with MySQL. + + 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.0, 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 */ + +/** + @file windeps/sunrpc/xdr_sizeof.c + General purpose routine to see how much space something will use + when serialized using XDR. +*/ + +#include +#include +#include +#include + +/* ARGSUSED */ +static bool_t +x_putlong (XDR *xdrs, const long *longp) +{ + xdrs->x_handy += BYTES_PER_XDR_UNIT; + return TRUE; +} + +/* ARGSUSED */ +static bool_t +x_putbytes (XDR *xdrs, const char *bp, u_int len) +{ + xdrs->x_handy += len; + return TRUE; +} + +static u_int +x_getpostn (const XDR *xdrs) +{ + return xdrs->x_handy; +} + +/* ARGSUSED */ +static bool_t +x_setpostn (XDR *xdrs, u_int len) +{ + /* This is not allowed */ + return FALSE; +} + +static int32_t * +x_inline (XDR *xdrs, u_int len) +{ + if (len == 0) + return NULL; + if (xdrs->x_op != XDR_ENCODE) + return NULL; + if (len < (u_int) (long int) xdrs->x_base) + { + /* x_private was already allocated */ + xdrs->x_handy += len; + return (int32_t *) xdrs->x_private; + } + else + { + /* Free the earlier space and allocate new area */ + free (xdrs->x_private); + if ((xdrs->x_private = (caddr_t) malloc (len)) == NULL) + { + xdrs->x_base = 0; + return NULL; + } + xdrs->x_base = (void *) (long) len; + xdrs->x_handy += len; + return (int32_t *) xdrs->x_private; + } +} + +static int +harmless (void) +{ + /* Always return FALSE/NULL, as the case may be */ + return 0; +} + +static void +x_destroy (XDR *xdrs) +{ + xdrs->x_handy = 0; + xdrs->x_base = 0; + if (xdrs->x_private) + { + free (xdrs->x_private); + xdrs->x_private = NULL; + } + return; +} + +static bool_t +x_putint32 (XDR *xdrs, const int32_t *int32p) +{ + xdrs->x_handy += BYTES_PER_XDR_UNIT; + return TRUE; +} + +unsigned long +xdr_sizeof (xdrproc_t func, void *data) +{ + XDR x; + struct xdr_ops ops; + bool_t stat; + /* to stop ANSI-C compiler from complaining */ + typedef bool_t (*dummyfunc1) (XDR *, long *); + typedef bool_t (*dummyfunc2) (XDR *, caddr_t, u_int); + typedef bool_t (*dummyfunc3) (XDR *, int32_t *); + + ops.x_putlong = x_putlong; + ops.x_putbytes = x_putbytes; + ops.x_inline = x_inline; + ops.x_getpostn = x_getpostn; + ops.x_setpostn = x_setpostn; + ops.x_destroy = x_destroy; + ops.x_putint32 = x_putint32; + + /* the other harmless ones */ + ops.x_getlong = (dummyfunc1) harmless; + ops.x_getbytes = (dummyfunc2) harmless; + ops.x_getint32 = (dummyfunc3) harmless; + + x.x_op = XDR_ENCODE; + x.x_ops = &ops; + x.x_handy = 0; + x.x_private = (caddr_t) NULL; + x.x_base = (caddr_t) 0; + + stat = func (&x, data); + free (x.x_private); + return stat == TRUE ? x.x_handy : 0; +} diff --git a/pool/shard004/C/0097855_grib_debug.c b/pool/shard004/C/0097855_grib_debug.c new file mode 100644 index 0000000000000000000000000000000000000000..609a16f238d4ce802cfaafa28b2b269c59576d79 --- /dev/null +++ b/pool/shard004/C/0097855_grib_debug.c @@ -0,0 +1,81 @@ +/* + * 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. + */ + +/* + * C Implementation: grib_debug + * + */ + + +#include "grib_tools.h" + + +grib_option grib_options[]={ +/* {id, args, help}, on, command_line, value */ + {"D",0,0,1,0,0}, + {"M",0,0,0,1,0}, + {"V",0,0,0,1,0}, + {"v",0,0,0,0,0}, + {"7",0,0,0,1,0}, + {"G",0,0,0,1,0}, + {"T:",0,0,0,1,0}, + {"q",0,0,1,0,0} +}; + +char* grib_tool_description="Dump the content of a grib file in debug mode."; +char* grib_tool_name="grib_debug"; +char* grib_tool_usage="[options] grib_file grib_file ..."; + +int grib_options_count=sizeof(grib_options)/sizeof(grib_option); + +int main(int argc, char *argv[]) +{ + fprintf(stderr, "\nWARNING: The tool %s is deprecated.\n\n", argv[0]); + return grib_tool(argc,argv); +} + +int grib_tool_before_getopt(grib_runtime_options* options) { + return 0; +} + +int grib_tool_init(grib_runtime_options* options) { + options->dump_flags = GRIB_DUMP_FLAG_VALUES + | GRIB_DUMP_FLAG_READ_ONLY; + options->dump_mode = "debug"; + return 0; +} + +int grib_tool_new_filename_action(grib_runtime_options* options,const char* file) { + return 0; +} + +int grib_tool_new_file_action(grib_runtime_options* options,grib_tools_file* file) { + + return 0; +} + +int grib_tool_new_handle_action(grib_runtime_options* options, grib_handle* h) { + + grib_dump_content(h,stdout,options->dump_mode,options->dump_flags,0); + return 0; +} + +int grib_tool_skip_handle(grib_runtime_options* options, grib_handle* h) { + grib_handle_delete(h); + return 0; +} + +void grib_tool_print_key_values(grib_runtime_options* options,grib_handle* h) { + grib_print_key_values(options,h); +} + +int grib_tool_finalise_action(grib_runtime_options* options) { + return 0; +} diff --git a/pool/shard004/C/0097859_delay_posix.c b/pool/shard004/C/0097859_delay_posix.c new file mode 100644 index 0000000000000000000000000000000000000000..824d9fc9d63073574e83b1da32031343a11c36e8 --- /dev/null +++ b/pool/shard004/C/0097859_delay_posix.c @@ -0,0 +1,67 @@ +/* delay_posix.c 04/04/2016 D.J.Whale + * + * Delay routines for posix compliant standard libraries (not Arduino) + */ + +#include +#include +#include + +#include "system.h" +#include "delay.h" + +static struct timespec delay_1sec = {1, 0}; // 1sec, 0us +static struct timespec delay_1ms = {0, 1000}; // 0sec, 1000us + + +void delaysec(uint8_t secs) +{ + while (secs-- != 0) + { + delay(delay_1sec); + } +} + + +void delayms(unsigned int ms) +{ + while (ms-- > 0) + { + delay(delay_1ms); + } +} + + +void delay(struct timespec time) +{ + nanosleep(&time, NULL); +} + + +/* Based on code suggested by Gordon Henderson: + * https://github.com/WiringPi/WiringPi/blob/master/wiringPi/wiringPi.c + * + * Note that his trick of using the hardware timer just didn't work, + * and this is the best of a bad bunch. nanosleep() delays at least + * 100uS in some cases. + */ + + +void delayus(unsigned int us) +{ + struct timeval tNow, tLong, tEnd; + + gettimeofday(&tNow, NULL); + tLong.tv_sec = us / 1000000; + tLong.tv_usec = us % 1000000; + timeradd(&tNow, &tLong, &tEnd); + + while (timercmp(&tNow, &tEnd, <)) + { + gettimeofday(&tNow, NULL); + } +} + + +/***** END OF FILE *****/ + diff --git a/pool/shard004/C/0097861_sdtest.c b/pool/shard004/C/0097861_sdtest.c new file mode 100644 index 0000000000000000000000000000000000000000..cd10d0c3d7f021c20a24600ee1cfea38f304215d --- /dev/null +++ b/pool/shard004/C/0097861_sdtest.c @@ -0,0 +1,239 @@ +/* +vi:noexpandtab:ts=2:sw=2 +*/ + +#define _LARGEFILE64_SOURCE + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "util.h" + +u64 global_error_count = 0; + +unsigned int BLOCK_SIZE = 0; +u8 *buf_g; /* Generated */ +u8 *buf_f; /* File */ +#define RAND_BLOCK_SIZE 4*1024 /* Data is seeded every 4K to be block size agnostic */ + +void _genranddata(u64 pos, u64 off, unsigned int seed) +{ + unsigned int seed_short = (pos >> 32) ^ (pos & 0xffffffff) ^ seed; + unsigned int i,j; + u32 tmp1, tmp2; + + assert(RAND_MAX >= 31); /* Assert that rand() still gives us the amount + of random bits we rely on below. */ + assert(RAND_BLOCK_SIZE % 4 == 0); + + srand(seed_short); rand(); rand(); + + for (i=0; i < RAND_BLOCK_SIZE;) { + tmp2 = rand(); + for (j=1; i < RAND_BLOCK_SIZE && j < 32; j++) { + tmp1 = rand(); + buf_g[off + i++] = (tmp1 & 0x000000ff) ; + buf_g[off + i++] = (tmp1 & 0x0000ff00) >> 8; + buf_g[off + i++] = (tmp1 & 0x00ff0000) >> 16; + /* We don't quite have 4 bytes of random data in tmp1, + * so get the high bit from tmp2: */ + buf_g[off + i++] = ((tmp1 & 0x7f000000) | ((tmp2 << j) & 0x80000000)) >> 24; + } + } +} + +void genranddata(u64 pos, unsigned int seed) +{ + u64 off; + + assert(pos % RAND_BLOCK_SIZE == 0); + assert(BLOCK_SIZE % RAND_BLOCK_SIZE == 0); + + for (off=0; off < BLOCK_SIZE; off += RAND_BLOCK_SIZE) + _genranddata(pos+off, off, seed); +} + +static void verifyblock(u64 pos, unsigned int seed, unsigned int size) +{ + unsigned int i; + + genranddata(pos, seed); + + for (i=0;i 4) { + printf("Usage: %s device [ start [ readonly ]]\nWARNING - all data on device will be destroyed!\n", argv[0]); + return 1; + } + filename = argv[1]; + alloc_bufs(sd_erase_size(filename)); /* BLOCK_SIZE set here */ + + if (argc > 2) { + start = interpret_number(argv[2]); + start = start - start % BLOCK_SIZE; + } + start_human = human_size(start, &start_units); + printf("Starting at %#llx (%.2f %s)\n", start, start_human, start_units); + readonly = argc > 3; + + size = dev_size(filename); + if (size) + expected_len = size - start; + + if (!readonly) { + written = writedata(argv[1], start, size, seed); + printf("\x1b[36m%llu bytes written to %s, verifying...\x1b[0m\n", written, filename); + if (expected_len && written != expected_len) { + printf("\x1b[1;31mSIZE MISMATCH: wrote %llu bytes, but expected to write %llu bytes!\x1b[0m\n", + written, expected_len); + global_error_count++; + } + } + + sync(); + + read = verifydata(argv[1], start, size, seed); + printf("\x1b[36m%llu bytes read from %s.\x1b[0m\n", read, filename); + + if (!readonly && written != read) { + printf("\x1b[1;31mSIZE MISMATCH: wrote %llu bytes, but read back %llu bytes!\x1b[0m\n", written, read); + global_error_count++; + } else if (expected_len && read != expected_len) { + printf("\x1b[1;31mSIZE MISMATCH: read %llu bytes, but expected to read %llu bytes!\x1b[0m\n", read, expected_len); + global_error_count++; + } + + if (global_error_count) { + printf("\x1b[1;31m\n%llu Errors detected :-(\x1b[0m\n", global_error_count); + return 1; + } + + if (read) + printf("\x1b[1;32m\nNo Errors Detected :-)\x1b[0m\n"); + return 0; +} diff --git a/pool/shard004/C/0097871_basic.c b/pool/shard004/C/0097871_basic.c new file mode 100644 index 0000000000000000000000000000000000000000..683438cf023dd413c7de73d7c45c5265e037cbcc --- /dev/null +++ b/pool/shard004/C/0097871_basic.c @@ -0,0 +1,210 @@ +/* $Id: basic.c,v 1.10 2003/02/10 12:35:03 dalroi Exp $ + * + * Copyright (c) 2002 Alban G. Hertroys + * + * Basic example of libDockapp usage + * + * This dockapp will draw a rectangle with a + * bouncing ball in it. + */ + +/* also includes Xlib, Xresources, XPM, stdlib and stdio */ +#include + +/* include the pixmap to use */ +#include "ball_red.xpm" + +#define SPEED 20 +#define MAX_MOVE 4 + +/* + * Prototypes for local functions + */ +void drawRelief(); +void moveBall(); +void destroy(); + +/* + * Global variables + */ +Window ballWin; +DAShapedPixmap *ballPix; + +/* + * M A I N + */ + +int +main(int argc, char **argv) +{ + unsigned int x=1, y=1; + Pixmap back; + DACallbacks eventCallbacks = { + destroy, /* destroy */ + NULL, /* buttonPress */ + NULL, /* buttonRelease */ + NULL, /* motion (mouse) */ + NULL, /* mouse enters window */ + NULL, /* mouse leaves window */ + moveBall /* timeout */ + }; + + /* provide standard command-line options */ + DAParseArguments( + argc, argv, /* Where the options come from */ + NULL, 0, /* Our list with options - none as you can see */ + "This is the help text for the basic example of how to " + "use libDockapp.\n", + "Basic example version 1.1"); + + /* Tell libdockapp what version we expect it to be (a date from the + * ChangeLog should do). + */ + DASetExpectedVersion(20020126); + + DAOpenDisplay( + NULL /* default display */, + argc, argv /* needed by libdockapp */ + ); + DACreateIcon( + "daBasicExample" /* WM_CLASS hint; don't use chars in [.?*: ] */, + 48, 48 /* geometry of dockapp internals */, + argc, argv /* needed by libdockapp */ + ); + + /* The pixmap that makes up the background of the dockapp */ + back = DAMakePixmap(); + drawRelief(back); + DASetPixmap(back); + XFreePixmap(DADisplay, back); + + /* A window(!) for the ball pixmap. + * Moving a window is a lot easier then erasing/copying the pixmap all + * the time. + * + * I use a DAShapedPixmap here, which contains all the information + * related to the pixmap: pixmap, mask and geometry. + */ + ballPix = DAMakeShapedPixmapFromData(ball_red_xpm); + ballWin = XCreateSimpleWindow(DADisplay, DAWindow, + x, y, + /* Use the geometry of the shaped pixmap */ + ballPix->geometry.width, ballPix->geometry.height, + 0, 0, 0); + DASPSetPixmapForWindow(ballWin, ballPix); + + /* Respond to destroy and timeout events (the ones not NULL in the + * eventCallbacks variable. + */ + DASetCallbacks(&eventCallbacks); + + /* Set the time for timeout events (in msec) */ + DASetTimeout(SPEED); + + /* Randomize movement variation. + * Run multiple versions of the dockapp simultaneously to see the effect + * best. + * (which function to use is set from the Imakefile) + */ +#ifdef HAS_RANDOMDEV + srandomdev(); +#else + srandom(time(NULL)); +#endif + + DAShow(); /* Show the dockapp window. */ + + /* Process events and keep the dockapp running */ + DAEventLoop(); + + /* not reached */ + exit(EXIT_SUCCESS); +} + + +void +drawRelief(Pixmap pixmap) +{ + XGCValues gcv; + GC lightGrayGC, darkGrayGC; + + /* GC's */ + gcv.foreground = DAGetColor("Navy"); + XChangeGC(DADisplay, DAClearGC, GCForeground, &gcv); + + gcv.foreground = DAGetColor("lightGray"); + gcv.graphics_exposures = False; + + lightGrayGC = XCreateGC(DADisplay, DAWindow, + GCForeground|GCGraphicsExposures, &gcv); + + gcv.foreground = DAGetColor("#222222"); + darkGrayGC = XCreateGC(DADisplay, DAWindow, + GCForeground|GCGraphicsExposures, &gcv); + + /* Drawing */ + XFillRectangle(DADisplay, pixmap, DAClearGC, 1, 1, 46, 46); + + XDrawLine(DADisplay, pixmap, darkGrayGC, 0, 0, 0, 46); + XDrawLine(DADisplay, pixmap, darkGrayGC, 1, 0, 47, 0); + + XDrawLine(DADisplay, pixmap, lightGrayGC, 0, 47, 47, 47); + XDrawLine(DADisplay, pixmap, lightGrayGC, 47, 1, 47, 46); + + /* Free the GC's, we don't use them anymore */ + XFreeGC(DADisplay, lightGrayGC); + XFreeGC(DADisplay, darkGrayGC); +} + + +void +moveBall() +{ + static int x = 1; + static int y = 1; + static int dx = 0; + static int dy = 0; + signed int var = random()%3 -1; + + if (dx == 0) dx = var; + if (dy == 0) dy = var; + if (dx > MAX_MOVE) dx = MAX_MOVE; + if (dy > MAX_MOVE) dy = MAX_MOVE; + + /* calculate new position */ + x += dx; + y += dy; + + if (x < 1) { + x = 1; + dx = -dx + var; + } + + if (y < 1) { + y = 1; + dy = -dy + var; + } + + if (x + ballPix->geometry.width > 46) { + x = 46 - ballPix->geometry.width; + dx = -dx + var; + } + + if (y + ballPix->geometry.height > 46) { + y = 46 - ballPix->geometry.height; + dy = -dy + var; + } + + XMoveWindow(DADisplay, ballWin, x, y); +} + + +void +destroy(void) +{ + XFreePixmap(DADisplay, ballPix->pixmap); + XFreePixmap(DADisplay, ballPix->shape); + +fprintf(stderr, "Destroyed!\n"); + /* exit is done by libdockapp */ +} diff --git a/pool/shard004/C/0097877_hal_usb_msd.c b/pool/shard004/C/0097877_hal_usb_msd.c new file mode 100644 index 0000000000000000000000000000000000000000..6cc5386509da796b493da881d5c0c07f4f2ab6c2 --- /dev/null +++ b/pool/shard004/C/0097877_hal_usb_msd.c @@ -0,0 +1,409 @@ +/* + ChibiOS/HAL - Copyright (C) 2016 Uladzimir Pylinsky aka barthess + + 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 hal_usb_msd.c + * @brief USM mass storage device code. + * + * @addtogroup usb_msd + * @{ + */ + +#include "hal.h" + +#if (HAL_USE_USB_MSD == TRUE) || defined(__DOXYGEN__) + +#include + +/*===========================================================================*/ +/* Driver local definitions. */ +/*===========================================================================*/ + +#define MSD_REQ_RESET 0xFF +#define MSD_GET_MAX_LUN 0xFE + +#define MSD_CBW_SIGNATURE 0x43425355 +#define MSD_CSW_SIGNATURE 0x53425355 + +#define MSD_THD_PRIO NORMALPRIO + +#define CBW_FLAGS_RESERVED_MASK 0b01111111 +#define CBW_LUN_RESERVED_MASK 0b11110000 +#define CBW_CMD_LEN_RESERVED_MASK 0b11000000 + +#define CSW_STATUS_PASSED 0x00 +#define CSW_STATUS_FAILED 0x01 +#define CSW_STATUS_PHASE_ERROR 0x02 + +#define MSD_SETUP_WORD(setup, index) (uint16_t)(((uint16_t)setup[index+1] << 8)\ + | (setup[index] & 0x00FF)) + +#define MSD_SETUP_VALUE(setup) MSD_SETUP_WORD(setup, 2) +#define MSD_SETUP_INDEX(setup) MSD_SETUP_WORD(setup, 4) +#define MSD_SETUP_LENGTH(setup) MSD_SETUP_WORD(setup, 6) + +/*===========================================================================*/ +/* Driver exported variables. */ +/*===========================================================================*/ +/** + * @brief USB mass storage driver identifier. + */ +USBMassStorageDriver USBMSD1; + +/*===========================================================================*/ +/* Driver local variables and types. */ +/*===========================================================================*/ + +/** + * @brief Hardcoded default SCSI inquiry response structure. + */ +static const scsi_inquiry_response_t default_scsi_inquiry_response = { + 0x00, /* direct access block device */ + 0x80, /* removable */ + 0x04, /* SPC-2 */ + 0x02, /* response data format */ + 0x20, /* response has 0x20 + 4 bytes */ + 0x00, + 0x00, + 0x00, + "Chibios", + "Mass Storage", + {'v',CH_KERNEL_MAJOR+'0','.',CH_KERNEL_MINOR+'0'} +}; + +/*===========================================================================*/ +/* Driver local functions. */ +/*===========================================================================*/ + +/** + * @brief Checks validity of CBW content. + * @details The device shall consider the CBW valid when: + * • The CBW was received after the device had sent a CSW or after a reset, + * • the CBW is 31 (1Fh) bytes in length, + * • and the dCBWSignature is equal to 43425355h. + * + * @param[in] cbw pointer to the @p msd_cbw_t object + * @param[in] recvd number of received bytes + * + * @return Operation status. + * @retval true CBW is meaningful. + * @retval false CBW is bad. + * + * @notapi + */ +static bool cbw_valid(const msd_cbw_t *cbw, msg_t recvd) { + if ((sizeof(msd_cbw_t) != recvd) || (cbw->signature != MSD_CBW_SIGNATURE)) { + return false; + } + else { + return true; + } +} + +/** + * @brief Checks meaningfulness of CBW content. + * @details The device shall consider the contents of a valid CBW meaningful when: + * • no reserved bits are set, + * • the bCBWLUN contains a valid LUN supported by the device, + * • and both bCBWCBLength and the content of the CBWCB are in + * accordance with bInterfaceSubClass. + * + * @param[in] cbw pointer to the @p msd_cbw_t object + * + * @return Operation status. + * @retval true CBW is meaningful. + * @retval false CBW is bad. + * + * @notapi + */ +static bool cbw_meaningful(const msd_cbw_t *cbw) { + if (((cbw->cmd_len & CBW_CMD_LEN_RESERVED_MASK) != 0) + || ((cbw->flags & CBW_FLAGS_RESERVED_MASK) != 0) + || (cbw->lun != 0)) { + return false; + } + else { + return true; + } +} + +/** + * @brief SCSI transport transmit function. + * + * @param[in] transport pointer to the @p SCSITransport object + * @param[in] data payload + * @param[in] len number of bytes to be transmitted + * + * @return Number of successfully transmitted bytes. + + * @notapi + */ +static uint32_t scsi_transport_transmit(const SCSITransport *transport, + const uint8_t *data, size_t len) { + + usb_scsi_transport_handler_t *trp = transport->handler; + msg_t status = usbTransmit(trp->usbp, trp->ep, data, len); + if (MSG_OK == status) + return len; + else + return 0; +} + +/** + * @brief SCSI transport receive function. + * + * @param[in] transport pointer to the @p SCSITransport object + * @param[in] data payload + * @param[in] len number bytes to be received + * + * @return Number of successfully received bytes. + + * @notapi + */ +static uint32_t scsi_transport_receive(const SCSITransport *transport, + uint8_t *data, size_t len) { + + usb_scsi_transport_handler_t *trp = transport->handler; + msg_t status = usbReceive(trp->usbp, trp->ep, data, len); + if (MSG_RESET != status) + return status; + else + return 0; +} + +/** + * @brief Fills and sends CSW message. + * + * @param[in] msdp pointer to the @p USBMassStorageDriver object + * @param[in] status status returned by SCSI layer + * @param[in] residue number of residue bytes in case of failed transaction + * + * @notapi + */ +static void send_csw(USBMassStorageDriver *msdp, uint8_t status, + uint32_t residue) { + + msdp->csw.signature = MSD_CSW_SIGNATURE; + msdp->csw.data_residue = residue; + msdp->csw.tag = msdp->cbw.tag; + msdp->csw.status = status; + + usbTransmit(msdp->usbp, USB_MSD_DATA_EP, (uint8_t *)&msdp->csw, + sizeof(msd_csw_t)); +} + +/** + * @brief Mass storage worker thread. + * + * @param[in] arg pointer to the @p USBMassStorageDriver object + * + * @notapi + */ +static THD_FUNCTION(usb_msd_worker, arg) { + USBMassStorageDriver *msdp = arg; + chRegSetThreadName("usb_msd_worker"); + + while(! chThdShouldTerminateX()) { + const msg_t status = usbReceive(msdp->usbp, USB_MSD_DATA_EP, + (uint8_t *)&msdp->cbw, sizeof(msd_cbw_t)); + if (MSG_RESET == status) { + osalThreadSleepMilliseconds(50); + } + else if (cbw_valid(&msdp->cbw, status) && cbw_meaningful(&msdp->cbw)) { + if (SCSI_SUCCESS == scsiExecCmd(&msdp->scsi_target, msdp->cbw.cmd_data)) { + send_csw(msdp, CSW_STATUS_PASSED, 0); + } + else { + send_csw(msdp, CSW_STATUS_FAILED, scsiResidue(&msdp->scsi_target)); + } + } + else { + ; /* do NOT send CSW here. Incorrect CBW must be silently ignored */ + } + } + + chThdExit(MSG_OK); +} + +/*===========================================================================*/ +/* Driver exported functions. */ +/*===========================================================================*/ + +/** + * @brief Mass storage specific request hook for USB. + * + * @param[in] usbp pointer to the @p USBDriver object + * + * @notapi + */ +bool msd_request_hook(USBDriver *usbp) { + + if (((usbp->setup[0] & USB_RTYPE_TYPE_MASK) == USB_RTYPE_TYPE_CLASS) && + ((usbp->setup[0] & USB_RTYPE_RECIPIENT_MASK) == USB_RTYPE_RECIPIENT_INTERFACE)) { + /* check that the request is for interface 0.*/ + if (MSD_SETUP_INDEX(usbp->setup) != 0) + return false; + + /* act depending on bRequest = setup[1] */ + switch(usbp->setup[1]) { + case MSD_REQ_RESET: + /* check that it is a HOST2DEV request */ + if (((usbp->setup[0] & USB_RTYPE_DIR_MASK) != USB_RTYPE_DIR_HOST2DEV) || + (MSD_SETUP_LENGTH(usbp->setup) != 0) || + (MSD_SETUP_VALUE(usbp->setup) != 0)) { + return false; + } + + /* + As required by the BOT specification, the Bulk-only mass storage reset request (classspecific + request) is implemented. This request is used to reset the mass storage device and + its associated interface. This class-specific request should prepare the device for the next + CBW from the host. + To generate the BOT Mass Storage Reset, the host must send a device request on the + default pipe of: + • bmRequestType: Class, interface, host to device + • bRequest field set to 255 (FFh) + • wValue field set to ‘0’ + • wIndex field set to the interface number + • wLength field set to ‘0’ + */ + chSysLockFromISR(); + + /* release and abandon current transmission */ + usbStallReceiveI(usbp, 1); + usbStallTransmitI(usbp, 1); + /* The device shall NAK the status stage of the device request until + * the Bulk-Only Mass Storage Reset is complete. + * NAK EP1 in and out */ + usbp->otg->ie[1].DIEPCTL = DIEPCTL_SNAK; + usbp->otg->oe[1].DOEPCTL = DOEPCTL_SNAK; + + chSysUnlockFromISR(); + + /* response to this request using EP0 */ + usbSetupTransfer(usbp, 0, 0, NULL); + return true; + + case MSD_GET_MAX_LUN: + /* check that it is a DEV2HOST request */ + if (((usbp->setup[0] & USB_RTYPE_DIR_MASK) != USB_RTYPE_DIR_DEV2HOST) || + (MSD_SETUP_LENGTH(usbp->setup) != 1) || + (MSD_SETUP_VALUE(usbp->setup) != 0)) { + return false; + } + + /* stall to indicate that we don't support LUN */ + osalSysLockFromISR(); + usbStallTransmitI(usbp, 0); + osalSysUnlockFromISR(); + return true; + + default: + return false; + break; + } + } + return false; +} + +/** + * @brief Initializes the standard part of a @p USBMassStorageDriver structure. + * + * @param[out] msdp pointer to the @p USBMassStorageDriver object + * + * @init + */ +void msdObjectInit(USBMassStorageDriver *msdp) { + + memset(msdp, 0x55, sizeof(USBMassStorageDriver)); + msdp->state = USB_MSD_STOP; + msdp->usbp = NULL; + msdp->worker = NULL; + + scsiObjectInit(&msdp->scsi_target); +} + +/** + * @brief Stops the USB mass storage driver. + * + * @param[in] msdp pointer to the @p USBMassStorageDriver object + * + * @api + */ +void msdStop(USBMassStorageDriver *msdp) { + + osalDbgCheck(msdp != NULL); + osalDbgAssert((msdp->state == USB_MSD_READY), "invalid state"); + + chThdTerminate(msdp->worker); + chThdWait(msdp->worker); + + scsiStop(&msdp->scsi_target); + + msdp->worker = NULL; + msdp->state = USB_MSD_STOP; + msdp->usbp = NULL; +} + +/** + * @brief Configures and activates the USB mass storage driver. + * + * @param[in] msdp pointer to the @p USBMassStorageDriver object + * @param[in] usbp pointer to the @p USBDriver object + * @param[in] blkdev pointer to the @p BaseBlockDevice object + * @param[in] blkbuf pointer to the working area buffer, must be allocated + * by user, must be big enough to store 1 data block + * @param[in] inquiry pointer to the SCSI inquiry response structure, + * set it to @p NULL to use default hardcoded value. + * + * @api + */ +void msdStart(USBMassStorageDriver *msdp, USBDriver *usbp, + BaseBlockDevice *blkdev, uint8_t *blkbuf, + const scsi_inquiry_response_t *inquiry) { + + osalDbgCheck((msdp != NULL) && (usbp != NULL) + && (blkdev != NULL) && (blkbuf != NULL)); + osalDbgAssert((msdp->state == USB_MSD_STOP), "invalid state"); + + msdp->usbp = usbp; + + msdp->usb_scsi_transport_handler.usbp = msdp->usbp; + msdp->usb_scsi_transport_handler.ep = USB_MSD_DATA_EP; + msdp->scsi_transport.handler = &msdp->usb_scsi_transport_handler; + msdp->scsi_transport.transmit = scsi_transport_transmit; + msdp->scsi_transport.receive = scsi_transport_receive; + + if (NULL == inquiry) { + msdp->scsi_config.inquiry_response = &default_scsi_inquiry_response; + } + else { + msdp->scsi_config.inquiry_response = inquiry; + } + msdp->scsi_config.blkbuf = blkbuf; + msdp->scsi_config.blkdev = blkdev; + msdp->scsi_config.transport = &msdp->scsi_transport; + + scsiStart(&msdp->scsi_target, &msdp->scsi_config); + + msdp->state = USB_MSD_READY; + msdp->worker = chThdCreateStatic(msdp->waMSDWorker, sizeof(msdp->waMSDWorker), + MSD_THD_PRIO, usb_msd_worker, msdp); +} + +#endif /* HAL_USE_USB_MSD */ + +/** @} */ diff --git a/pool/shard004/C/0097885_minisocks.c b/pool/shard004/C/0097885_minisocks.c new file mode 100644 index 0000000000000000000000000000000000000000..838f524cf11a177b473ca83e3d7f597ee2904d21 --- /dev/null +++ b/pool/shard004/C/0097885_minisocks.c @@ -0,0 +1,261 @@ +/* + * net/dccp/minisocks.c + * + * An implementation of the DCCP protocol + * Arnaldo Carvalho de Melo + * + * 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 "ackvec.h" +#include "ccid.h" +#include "dccp.h" +#include "feat.h" + +struct inet_timewait_death_row dccp_death_row = { + .sysctl_max_tw_buckets = NR_FILE * 2, + .hashinfo = &dccp_hashinfo, +}; + +EXPORT_SYMBOL_GPL(dccp_death_row); + +void dccp_time_wait(struct sock *sk, int state, int timeo) +{ + struct inet_timewait_sock *tw; + + tw = inet_twsk_alloc(sk, &dccp_death_row, state); + + if (tw != NULL) { + const struct inet_connection_sock *icsk = inet_csk(sk); + const int rto = (icsk->icsk_rto << 2) - (icsk->icsk_rto >> 1); +#if IS_ENABLED(CONFIG_IPV6) + if (tw->tw_family == PF_INET6) { + tw->tw_v6_daddr = sk->sk_v6_daddr; + tw->tw_v6_rcv_saddr = sk->sk_v6_rcv_saddr; + tw->tw_ipv6only = sk->sk_ipv6only; + } +#endif + + /* Get the TIME_WAIT timeout firing. */ + if (timeo < rto) + timeo = rto; + + tw->tw_timeout = DCCP_TIMEWAIT_LEN; + if (state == DCCP_TIME_WAIT) + timeo = DCCP_TIMEWAIT_LEN; + + inet_twsk_schedule(tw, timeo); + /* Linkage updates. */ + __inet_twsk_hashdance(tw, sk, &dccp_hashinfo); + inet_twsk_put(tw); + } else { + /* Sorry, if we're out of memory, just CLOSE this + * socket up. We've got bigger problems than + * non-graceful socket closings. + */ + DCCP_WARN("time wait bucket table overflow\n"); + } + + dccp_done(sk); +} + +struct sock *dccp_create_openreq_child(struct sock *sk, + const struct request_sock *req, + const struct sk_buff *skb) +{ + /* + * Step 3: Process LISTEN state + * + * (* Generate a new socket and switch to that socket *) + * Set S := new socket for this port pair + */ + struct sock *newsk = inet_csk_clone_lock(sk, req, GFP_ATOMIC); + + if (newsk != NULL) { + struct dccp_request_sock *dreq = dccp_rsk(req); + struct inet_connection_sock *newicsk = inet_csk(newsk); + struct dccp_sock *newdp = dccp_sk(newsk); + + newdp->dccps_role = DCCP_ROLE_SERVER; + newdp->dccps_hc_rx_ackvec = NULL; + newdp->dccps_service_list = NULL; + newdp->dccps_service = dreq->dreq_service; + newdp->dccps_timestamp_echo = dreq->dreq_timestamp_echo; + newdp->dccps_timestamp_time = dreq->dreq_timestamp_time; + newicsk->icsk_rto = DCCP_TIMEOUT_INIT; + + INIT_LIST_HEAD(&newdp->dccps_featneg); + /* + * Step 3: Process LISTEN state + * + * Choose S.ISS (initial seqno) or set from Init Cookies + * Initialize S.GAR := S.ISS + * Set S.ISR, S.GSR from packet (or Init Cookies) + * + * Setting AWL/AWH and SWL/SWH happens as part of the feature + * activation below, as these windows all depend on the local + * and remote Sequence Window feature values (7.5.2). + */ + newdp->dccps_iss = dreq->dreq_iss; + newdp->dccps_gss = dreq->dreq_gss; + newdp->dccps_gar = newdp->dccps_iss; + newdp->dccps_isr = dreq->dreq_isr; + newdp->dccps_gsr = dreq->dreq_gsr; + + /* + * Activate features: initialise CCIDs, sequence windows etc. + */ + if (dccp_feat_activate_values(newsk, &dreq->dreq_featneg)) { + /* It is still raw copy of parent, so invalidate + * destructor and make plain sk_free() */ + newsk->sk_destruct = NULL; + sk_free(newsk); + return NULL; + } + dccp_init_xmit_timers(newsk); + + DCCP_INC_STATS_BH(DCCP_MIB_PASSIVEOPENS); + } + return newsk; +} + +EXPORT_SYMBOL_GPL(dccp_create_openreq_child); + +/* + * Process an incoming packet for RESPOND sockets represented + * as an request_sock. + */ +struct sock *dccp_check_req(struct sock *sk, struct sk_buff *skb, + struct request_sock *req) +{ + struct sock *child = NULL; + struct dccp_request_sock *dreq = dccp_rsk(req); + + /* Check for retransmitted REQUEST */ + if (dccp_hdr(skb)->dccph_type == DCCP_PKT_REQUEST) { + + if (after48(DCCP_SKB_CB(skb)->dccpd_seq, dreq->dreq_gsr)) { + dccp_pr_debug("Retransmitted REQUEST\n"); + dreq->dreq_gsr = DCCP_SKB_CB(skb)->dccpd_seq; + /* + * Send another RESPONSE packet + * To protect against Request floods, increment retrans + * counter (backoff, monitored by dccp_response_timer). + */ + inet_rtx_syn_ack(sk, req); + } + /* Network Duplicate, discard packet */ + return NULL; + } + + DCCP_SKB_CB(skb)->dccpd_reset_code = DCCP_RESET_CODE_PACKET_ERROR; + + if (dccp_hdr(skb)->dccph_type != DCCP_PKT_ACK && + dccp_hdr(skb)->dccph_type != DCCP_PKT_DATAACK) + goto drop; + + /* Invalid ACK */ + if (!between48(DCCP_SKB_CB(skb)->dccpd_ack_seq, + dreq->dreq_iss, dreq->dreq_gss)) { + dccp_pr_debug("Invalid ACK number: ack_seq=%llu, " + "dreq_iss=%llu, dreq_gss=%llu\n", + (unsigned long long) + DCCP_SKB_CB(skb)->dccpd_ack_seq, + (unsigned long long) dreq->dreq_iss, + (unsigned long long) dreq->dreq_gss); + goto drop; + } + + if (dccp_parse_options(sk, dreq, skb)) + goto drop; + + child = inet_csk(sk)->icsk_af_ops->syn_recv_sock(sk, skb, req, NULL); + if (child == NULL) + goto listen_overflow; + + inet_csk_reqsk_queue_drop(sk, req); + inet_csk_reqsk_queue_add(sk, req, child); +out: + return child; +listen_overflow: + dccp_pr_debug("listen_overflow!\n"); + DCCP_SKB_CB(skb)->dccpd_reset_code = DCCP_RESET_CODE_TOO_BUSY; +drop: + if (dccp_hdr(skb)->dccph_type != DCCP_PKT_RESET) + req->rsk_ops->send_reset(sk, skb); + + inet_csk_reqsk_queue_drop(sk, req); + goto out; +} + +EXPORT_SYMBOL_GPL(dccp_check_req); + +/* + * Queue segment on the new socket if the new socket is active, + * otherwise we just shortcircuit this and continue with + * the new socket. + */ +int dccp_child_process(struct sock *parent, struct sock *child, + struct sk_buff *skb) +{ + int ret = 0; + const int state = child->sk_state; + + if (!sock_owned_by_user(child)) { + ret = dccp_rcv_state_process(child, skb, dccp_hdr(skb), + skb->len); + + /* Wakeup parent, send SIGIO */ + if (state == DCCP_RESPOND && child->sk_state != state) + parent->sk_data_ready(parent); + } else { + /* Alas, it is possible again, because we do lookup + * in main socket hash table and lock on listening + * socket does not protect us more. + */ + __sk_add_backlog(child, skb); + } + + bh_unlock_sock(child); + sock_put(child); + return ret; +} + +EXPORT_SYMBOL_GPL(dccp_child_process); + +void dccp_reqsk_send_ack(struct sock *sk, struct sk_buff *skb, + struct request_sock *rsk) +{ + DCCP_BUG("DCCP-ACK packets are never sent in LISTEN/RESPOND state"); +} + +EXPORT_SYMBOL_GPL(dccp_reqsk_send_ack); + +int dccp_reqsk_init(struct request_sock *req, + struct dccp_sock const *dp, struct sk_buff const *skb) +{ + struct dccp_request_sock *dreq = dccp_rsk(req); + + inet_rsk(req)->ir_rmt_port = dccp_hdr(skb)->dccph_sport; + inet_rsk(req)->ir_num = ntohs(dccp_hdr(skb)->dccph_dport); + inet_rsk(req)->acked = 0; + dreq->dreq_timestamp_echo = 0; + + /* inherit feature negotiation options from listening socket */ + return dccp_feat_clone_list(&dp->dccps_featneg, &dreq->dreq_featneg); +} + +EXPORT_SYMBOL_GPL(dccp_reqsk_init); diff --git a/pool/shard004/C/0097886_async.c b/pool/shard004/C/0097886_async.c new file mode 100644 index 0000000000000000000000000000000000000000..42c66a762e1679d7685553a13e07bf0cfedec079 --- /dev/null +++ b/pool/shard004/C/0097886_async.c @@ -0,0 +1,96 @@ +/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/ + +/*** + This file is part of systemd. + + Copyright 2013 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 "async.h" +#include "fd-util.h" +#include "log.h" +#include "macro.h" +#include "util.h" + +int asynchronous_job(void* (*func)(void *p), void *arg) { + pthread_attr_t a; + pthread_t t; + int r; + + /* It kinda sucks that we have to resort to threads to + * implement an asynchronous sync(), but well, such is + * life. + * + * Note that issuing this command right before exiting a + * process will cause the process to wait for the sync() to + * complete. This function hence is nicely asynchronous really + * only in long running processes. */ + + r = pthread_attr_init(&a); + if (r > 0) + return -r; + + r = pthread_attr_setdetachstate(&a, PTHREAD_CREATE_DETACHED); + if (r > 0) + goto finish; + + r = pthread_create(&t, &a, func, arg); + +finish: + pthread_attr_destroy(&a); + return -r; +} + +static void *sync_thread(void *p) { + sync(); + return NULL; +} + +int asynchronous_sync(void) { + log_debug("Spawning new thread for sync"); + + return asynchronous_job(sync_thread, NULL); +} + +static void *close_thread(void *p) { + assert_se(close_nointr(PTR_TO_FD(p)) != -EBADF); + return NULL; +} + +int asynchronous_close(int fd) { + int r; + + /* This is supposed to behave similar to safe_close(), but + * actually invoke close() asynchronously, so that it will + * never block. Ideally the kernel would have an API for this, + * but it doesn't, so we work around it, and hide this as a + * far away as we can. */ + + if (fd >= 0) { + PROTECT_ERRNO; + + r = asynchronous_job(close_thread, FD_TO_PTR(fd)); + if (r < 0) + assert_se(close_nointr(fd) != -EBADF); + } + + return -1; +} diff --git a/pool/shard004/C/0097888_getgroups.c b/pool/shard004/C/0097888_getgroups.c new file mode 100644 index 0000000000000000000000000000000000000000..35b219ef66c366065ed53cc7f593964a6651071a --- /dev/null +++ b/pool/shard004/C/0097888_getgroups.c @@ -0,0 +1,71 @@ +/* Copyright (C) 1993, 1994, 1995, 1997 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 + +int +__getgroups (n, gidset) + int n; + gid_t *gidset; +{ + error_t err; + int ngids; + void *crit; + + if (n < 0) + return __hurd_fail (EINVAL); + + crit = _hurd_critical_section_lock (); + __mutex_lock (&_hurd_id.lock); + + if (err = _hurd_check_ids ()) + { + __mutex_unlock (&_hurd_id.lock); + _hurd_critical_section_unlock (crit); + return __hurd_fail (err); + } + + ngids = _hurd_id.gen.ngids; + + if (n != 0) + { + /* Copy the gids onto stack storage and then release the idlock. */ + gid_t gids[ngids]; + memcpy (gids, _hurd_id.gen.gids, sizeof (gids)); + __mutex_unlock (&_hurd_id.lock); + _hurd_critical_section_unlock (crit); + + /* Now that the lock is released, we can safely copy the + group set into the user's array, which might fault. */ + if (ngids > n) + return __hurd_fail (EINVAL); + memcpy (gidset, gids, ngids * sizeof (gid_t)); + } + else + { + __mutex_unlock (&_hurd_id.lock); + _hurd_critical_section_unlock (crit); + } + + return ngids; +} + +weak_alias (__getgroups, getgroups) diff --git a/pool/shard004/C/0097893_mali_session.c b/pool/shard004/C/0097893_mali_session.c new file mode 100644 index 0000000000000000000000000000000000000000..df3a2ba87545f3346b906cca3ab42a7a28d3a241 --- /dev/null +++ b/pool/shard004/C/0097893_mali_session.c @@ -0,0 +1,144 @@ +/* + * This confidential and proprietary software may be used only as + * authorised by a licensing agreement from ARM Limited + * (C) COPYRIGHT 2012-2015 ARM Limited + * ALL RIGHTS RESERVED + * The entire notice above must be reproduced on all authorised + * copies and copies may only be made to the extent permitted + * by a licensing agreement from ARM Limited. + */ + +#include "mali_osk.h" +#include "mali_osk_list.h" +#include "mali_session.h" +#include "mali_ukk.h" +#ifdef MALI_MEM_SWAP_TRACKING +#include "mali_memory_swap_alloc.h" +#endif + +_MALI_OSK_LIST_HEAD(mali_sessions); +static u32 mali_session_count = 0; + +_mali_osk_spinlock_irq_t *mali_sessions_lock = NULL; +wait_queue_head_t pending_queue; + +_mali_osk_errcode_t mali_session_initialize(void) +{ + _MALI_OSK_INIT_LIST_HEAD(&mali_sessions); + /* init wait queue for big varying job */ + init_waitqueue_head(&pending_queue); + + mali_sessions_lock = _mali_osk_spinlock_irq_init( + _MALI_OSK_LOCKFLAG_ORDERED, + _MALI_OSK_LOCK_ORDER_SESSIONS); + if (NULL == mali_sessions_lock) { + return _MALI_OSK_ERR_NOMEM; + } + + return _MALI_OSK_ERR_OK; +} + +void mali_session_terminate(void) +{ + if (NULL != mali_sessions_lock) { + _mali_osk_spinlock_irq_term(mali_sessions_lock); + mali_sessions_lock = NULL; + } +} + +void mali_session_add(struct mali_session_data *session) +{ + mali_session_lock(); + _mali_osk_list_add(&session->link, &mali_sessions); + mali_session_count++; + mali_session_unlock(); +} + +void mali_session_remove(struct mali_session_data *session) +{ + mali_session_lock(); + _mali_osk_list_delinit(&session->link); + mali_session_count--; + mali_session_unlock(); +} + +u32 mali_session_get_count(void) +{ + return mali_session_count; +} + +wait_queue_head_t *mali_session_get_wait_queue(void) +{ + return &pending_queue; +} + +/* + * Get the max completed window jobs from all active session, + * which will be used in window render frame per sec calculate + */ +#if defined(CONFIG_MALI_DVFS) +u32 mali_session_max_window_num(void) +{ + struct mali_session_data *session, *tmp; + u32 max_window_num = 0; + u32 tmp_number = 0; + + mali_session_lock(); + + MALI_SESSION_FOREACH(session, tmp, link) { + tmp_number = _mali_osk_atomic_xchg( + &session->number_of_window_jobs, 0); + if (max_window_num < tmp_number) { + max_window_num = tmp_number; + } + } + + mali_session_unlock(); + + return max_window_num; +} +#endif + +void mali_session_memory_tracking(_mali_osk_print_ctx *print_ctx) +{ + struct mali_session_data *session, *tmp; + u32 mali_mem_usage; + u32 total_mali_mem_size; +#ifdef MALI_MEM_SWAP_TRACKING + u32 swap_pool_size; + u32 swap_unlock_size; +#endif + + MALI_DEBUG_ASSERT_POINTER(print_ctx); + mali_session_lock(); + MALI_SESSION_FOREACH(session, tmp, link) { +#ifdef MALI_MEM_SWAP_TRACKING + _mali_osk_ctxprintf(print_ctx, " %-25s %-10u %-10u %-15u %-15u %-10u %-10u %-10u\n", + session->comm, session->pid, + (atomic_read(&session->mali_mem_allocated_pages)) * _MALI_OSK_MALI_PAGE_SIZE, + session->max_mali_mem_allocated_size, + (atomic_read(&session->mali_mem_array[MALI_MEM_EXTERNAL])) * _MALI_OSK_MALI_PAGE_SIZE, + (atomic_read(&session->mali_mem_array[MALI_MEM_UMP])) * _MALI_OSK_MALI_PAGE_SIZE, + (atomic_read(&session->mali_mem_array[MALI_MEM_DMA_BUF])) * _MALI_OSK_MALI_PAGE_SIZE, + (atomic_read(&session->mali_mem_array[MALI_MEM_SWAP])) * _MALI_OSK_MALI_PAGE_SIZE + ); +#else + _mali_osk_ctxprintf(print_ctx, " %-25s %-10u %-10u %-15u %-15u %-10u %-10u \n", + session->comm, session->pid, + (atomic_read(&session->mali_mem_allocated_pages)) * _MALI_OSK_MALI_PAGE_SIZE, + session->max_mali_mem_allocated_size, + (atomic_read(&session->mali_mem_array[MALI_MEM_EXTERNAL])) * _MALI_OSK_MALI_PAGE_SIZE, + (atomic_read(&session->mali_mem_array[MALI_MEM_UMP])) * _MALI_OSK_MALI_PAGE_SIZE, + (atomic_read(&session->mali_mem_array[MALI_MEM_DMA_BUF])) * _MALI_OSK_MALI_PAGE_SIZE + ); +#endif + } + mali_session_unlock(); + mali_mem_usage = _mali_ukk_report_memory_usage(); + total_mali_mem_size = _mali_ukk_report_total_memory_size(); + _mali_osk_ctxprintf(print_ctx, "Mali mem usage: %u\nMali mem limit: %u\n", mali_mem_usage, total_mali_mem_size); +#ifdef MALI_MEM_SWAP_TRACKING + mali_mem_swap_tracking(&swap_pool_size, &swap_unlock_size); + _mali_osk_ctxprintf(print_ctx, "Mali swap mem pool : %u\nMali swap mem unlock: %u\n", swap_pool_size, swap_unlock_size); +#endif +} diff --git a/pool/shard004/C/0097902_q_shsolaris.c b/pool/shard004/C/0097902_q_shsolaris.c new file mode 100644 index 0000000000000000000000000000000000000000..c56055a1fb0c090cb9b1e73b6dcb19a37b6db133 --- /dev/null +++ b/pool/shard004/C/0097902_q_shsolaris.c @@ -0,0 +1,196 @@ +#include +#include +#include +#include +#include +#include +#include +#include + +#include "../linux/glob.h" + +#include "../qcommon/qcommon.h" + +//=============================================================================== + +byte *membase; +int maxhunksize; +int curhunksize; + +void *Hunk_Begin (int maxsize) +{ + // reserve a huge chunk of memory, but don't commit any yet + maxhunksize = maxsize; + curhunksize = 0; + membase = malloc(maxhunksize); + if (membase == NULL) + Sys_Error(ERR_FATAL, "unable to allocate %d bytes", maxsize); + + return membase; +} + +void *Hunk_Alloc (int size) +{ + byte *buf; + + // round to cacheline + size = (size+31)&~31; + if (curhunksize + size > maxhunksize) + Sys_Error(ERR_FATAL, "Hunk_Alloc overflow"); + buf = membase + curhunksize; + curhunksize += size; + return buf; +} + +int Hunk_End (void) +{ + byte *n; + + n = realloc(membase, curhunksize); + if (n != membase) + Sys_Error(ERR_FATAL, "Hunk_End: Could not remap virtual block (%d)", errno); + + return curhunksize; +} + +void Hunk_Free (void *base) +{ + if (base) + free(base); +} + +//=============================================================================== + + +/* +================ +Sys_Milliseconds +================ +*/ +int curtime; +int Sys_Milliseconds (void) +{ + struct timeval tp; + struct timezone tzp; + static int secbase; + + gettimeofday(&tp, &tzp); + + if (!secbase) + { + secbase = tp.tv_sec; + return tp.tv_usec/1000; + } + + curtime = (tp.tv_sec - secbase)*1000 + tp.tv_usec/1000; + + return curtime; +} + +void Sys_Mkdir (char *path) +{ + mkdir (path, 0777); +} + +char *strlwr (char *s) +{ + while (*s) { + *s = tolower(*s); + s++; + } +} + +//============================================ + +static char findbase[MAX_OSPATH]; +static char findpath[MAX_OSPATH]; +static char findpattern[MAX_OSPATH]; +static DIR *fdir; + +static qboolean CompareAttributes(char *path, char *name, + unsigned musthave, unsigned canthave ) +{ + struct stat st; + char fn[MAX_OSPATH]; + +// . and .. never match + if (strcmp(name, ".") == 0 || strcmp(name, "..") == 0) + return false; + + sprintf(fn, "%s/%s", path, name); + if (stat(fn, &st) == -1) + return false; // shouldn't happen + + if ( ( st.st_mode & S_IFDIR ) && ( canthave & SFF_SUBDIR ) ) + return false; + + if ( ( musthave & SFF_SUBDIR ) && !( st.st_mode & S_IFDIR ) ) + return false; + + return true; +} + +char *Sys_FindFirst (char *path, unsigned musthave, unsigned canhave) +{ + struct dirent *d; + char *p; + + if (fdir) + Sys_Error ("Sys_BeginFind without close"); + +// COM_FilePath (path, findbase); + strcpy(findbase, path); + + if ((p = strrchr(findbase, '/')) != NULL) { + *p = 0; + strcpy(findpattern, p + 1); + } else + strcpy(findpattern, "*"); + + if (strcmp(findpattern, "*.*") == 0) + strcpy(findpattern, "*"); + + if ((fdir = opendir(path)) == NULL) + return NULL; + while ((d = readdir(fdir)) != NULL) { + if (!*findpattern || glob_match(findpattern, d->d_name)) { +// if (*findpattern) +// printf("%s matched %s\n", findpattern, d->d_name); + if (CompareAttributes(findbase, d->d_name, musthave, canhave)) { + sprintf (findpath, "%s/%s", findbase, d->d_name); + return findpath; + } + } + } + return NULL; +} + +char *Sys_FindNext (unsigned musthave, unsigned canhave) +{ + struct dirent *d; + + if (fdir == NULL) + return NULL; + while ((d = readdir(fdir)) != NULL) { + if (!*findpattern || glob_match(findpattern, d->d_name)) { +// if (*findpattern) +// printf("%s matched %s\n", findpattern, d->d_name); + if (CompareAttributes(findbase, d->d_name, musthave, canhave)) { + sprintf (findpath, "%s/%s", findbase, d->d_name); + return findpath; + } + } + } + return NULL; +} + +void Sys_FindClose (void) +{ + if (fdir != NULL) + closedir(fdir); + fdir = NULL; +} + + +//============================================ + diff --git a/pool/shard004/C/0097906_maths_addon.c b/pool/shard004/C/0097906_maths_addon.c new file mode 100644 index 0000000000000000000000000000000000000000..f92f63bd5c498c16b509dc511c8398069fd96f3c --- /dev/null +++ b/pool/shard004/C/0097906_maths_addon.c @@ -0,0 +1,61 @@ +#include "maths_addon.h" + +int factRec (int n) { + if (n <= 1) + return 1; + else + return n * factRec(n-1); +} + +int fact (int n) { + int f; + for (f = 1; n > 1; n--) + f *= n; + return f; +} + +int spow (int n) { + return pow(2.0,n)-1; +} + +// Cet algorithme nécessite 2n-1 multiplications et 1 division. +int binomial_slow (int n, int p) { + return fact(n)/(fact(p)*fact(n-p)); +} + +// Cet algorithme nécessite 2(p-1) multiplications et 1 division. +int binomial_moderate (int n, int p) { + int num; // Numérateur + int k; // Variable d'itération + + // On se ramène au cas où p <= n-p + if (p > n-p) + p = n-p; + + // Calcul du numérateur + for (num = 1, k = n-p+1; k <= n; k++) + num *= k; + + // Calcul du binômial + return num/fact(p); +} + +// Cet algorithme nécessite p-1 multiplications et p-1 divisions. +int binomial_fast (int n, int p) { + int binom; // Résultat + int k; // Variable d'itération + + // On se ramène au cas où p <= n-p + if (p > n-p) + p = n-p; + + // k prend les valeurs 1 ... p + // n-p+k prend les valeurs n-p+1 ... n + for (binom = 1, k = 1; k <= p; k++) + // Il est important de faire la mutiplication avant la division. + // Le résultat intermédiaire binom/k n'est pas nécessairement un + // entier. + binom = (binom * (n-p+k)) / k; + + return binom; +} diff --git a/pool/shard004/C/0097912_cbc.c b/pool/shard004/C/0097912_cbc.c new file mode 100644 index 0000000000000000000000000000000000000000..477357c4454d3d6834c53d94e0e5254947a5a684 --- /dev/null +++ b/pool/shard004/C/0097912_cbc.c @@ -0,0 +1,86 @@ +/* + * Copyright (C) 2015 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_crypto + * @{ + * + * @file + * @brief Crypto mode - cipher block chaining + * + * @author Nico von Geyso + * + * @} + */ + +#include +#include "crypto/modes/cbc.h" + +int cipher_encrypt_cbc(const cipher_t *cipher, uint8_t iv[16], + const uint8_t *input, size_t length, uint8_t *output) +{ + size_t offset = 0; + uint8_t block_size, input_block[CIPHER_MAX_BLOCK_SIZE] = { 0 }, + *output_block_last; + + block_size = cipher_get_block_size(cipher); + if (length % block_size != 0) { + return CIPHER_ERR_INVALID_LENGTH; + } + + output_block_last = iv; + do { + /* CBC-Mode: XOR plaintext with ciphertext of (n-1)-th block */ + memcpy(input_block, input + offset, block_size); + for (int i = 0; i < block_size; ++i) { + input_block[i] ^= output_block_last[i]; + } + + if (cipher_encrypt(cipher, input_block, output + offset) != 1) { + return CIPHER_ERR_ENC_FAILED; + } + + output_block_last = output + offset; + offset += block_size; + } while (offset < length); + + return offset; +} + +int cipher_decrypt_cbc(const cipher_t *cipher, uint8_t iv[16], + const uint8_t *input, size_t length, uint8_t *output) +{ + size_t offset = 0; + const uint8_t *input_block, *input_block_last; + uint8_t block_size; + + block_size = cipher_get_block_size(cipher); + if (length % block_size != 0) { + return CIPHER_ERR_INVALID_LENGTH; + } + + input_block_last = iv; + do { + input_block = input + offset; + uint8_t *output_block = output + offset; + + if (cipher_decrypt(cipher, input_block, output_block) != 1) { + return CIPHER_ERR_DEC_FAILED; + } + + /* CBC-Mode: XOR plaintext with ciphertext of (n-1)-th block */ + for (uint8_t i = 0; i < block_size; ++i) { + output_block[i] ^= input_block_last[i]; + } + + input_block_last = input_block; + offset += block_size; + } while (offset < length); + + return offset; +} diff --git a/pool/shard004/C/0097918_gstrtpgsmpay.c b/pool/shard004/C/0097918_gstrtpgsmpay.c new file mode 100644 index 0000000000000000000000000000000000000000..db75b0c4e791f16f847d328870569453a0c3d32b --- /dev/null +++ b/pool/shard004/C/0097918_gstrtpgsmpay.c @@ -0,0 +1,178 @@ +/* GStreamer + * Copyright (C) <1999> Erik Walthinsen + * Copyright (C) <2005> Zeeshan Ali + * + * 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., 51 Franklin St, Fifth Floor, + * Boston, MA 02110-1301, USA. + */ + +#ifdef HAVE_CONFIG_H +# include "config.h" +#endif + +#include +#include +#include +#include + +#include "gstrtpgsmpay.h" +#include "gstrtputils.h" + +GST_DEBUG_CATEGORY_STATIC (rtpgsmpay_debug); +#define GST_CAT_DEFAULT (rtpgsmpay_debug) + +static GstStaticPadTemplate gst_rtp_gsm_pay_sink_template = +GST_STATIC_PAD_TEMPLATE ("sink", + GST_PAD_SINK, + GST_PAD_ALWAYS, + GST_STATIC_CAPS ("audio/x-gsm, " "rate = (int) 8000, " "channels = (int) 1") + ); + +static GstStaticPadTemplate gst_rtp_gsm_pay_src_template = + GST_STATIC_PAD_TEMPLATE ("src", + GST_PAD_SRC, + GST_PAD_ALWAYS, + GST_STATIC_CAPS ("application/x-rtp, " + "media = (string) \"audio\", " + "payload = (int) " GST_RTP_PAYLOAD_GSM_STRING ", " + "clock-rate = (int) 8000, " "encoding-name = (string) \"GSM\"; " + "application/x-rtp, " + "media = (string) \"audio\", " + "payload = (int) " GST_RTP_PAYLOAD_DYNAMIC_STRING ", " + "clock-rate = (int) 8000, " "encoding-name = (string) \"GSM\"") + ); + +static gboolean gst_rtp_gsm_pay_setcaps (GstRTPBasePayload * payload, + GstCaps * caps); +static GstFlowReturn gst_rtp_gsm_pay_handle_buffer (GstRTPBasePayload * payload, + GstBuffer * buffer); + +#define gst_rtp_gsm_pay_parent_class parent_class +G_DEFINE_TYPE (GstRTPGSMPay, gst_rtp_gsm_pay, GST_TYPE_RTP_BASE_PAYLOAD); + +static void +gst_rtp_gsm_pay_class_init (GstRTPGSMPayClass * klass) +{ + GstElementClass *gstelement_class; + GstRTPBasePayloadClass *gstrtpbasepayload_class; + + GST_DEBUG_CATEGORY_INIT (rtpgsmpay_debug, "rtpgsmpay", 0, + "GSM Audio RTP Payloader"); + + gstelement_class = (GstElementClass *) klass; + gstrtpbasepayload_class = (GstRTPBasePayloadClass *) klass; + + gst_element_class_add_pad_template (gstelement_class, + gst_static_pad_template_get (&gst_rtp_gsm_pay_sink_template)); + gst_element_class_add_pad_template (gstelement_class, + gst_static_pad_template_get (&gst_rtp_gsm_pay_src_template)); + + gst_element_class_set_static_metadata (gstelement_class, "RTP GSM payloader", + "Codec/Payloader/Network/RTP", + "Payload-encodes GSM audio into a RTP packet", + "Zeeshan Ali "); + + gstrtpbasepayload_class->set_caps = gst_rtp_gsm_pay_setcaps; + gstrtpbasepayload_class->handle_buffer = gst_rtp_gsm_pay_handle_buffer; +} + +static void +gst_rtp_gsm_pay_init (GstRTPGSMPay * rtpgsmpay) +{ + GST_RTP_BASE_PAYLOAD (rtpgsmpay)->clock_rate = 8000; + GST_RTP_BASE_PAYLOAD_PT (rtpgsmpay) = GST_RTP_PAYLOAD_GSM; +} + +static gboolean +gst_rtp_gsm_pay_setcaps (GstRTPBasePayload * payload, GstCaps * caps) +{ + const char *stname; + GstStructure *structure; + gboolean res; + + structure = gst_caps_get_structure (caps, 0); + + stname = gst_structure_get_name (structure); + + if (strcmp ("audio/x-gsm", stname)) + goto invalid_type; + + gst_rtp_base_payload_set_options (payload, "audio", FALSE, "GSM", 8000); + res = gst_rtp_base_payload_set_outcaps (payload, NULL); + + return res; + + /* ERRORS */ +invalid_type: + { + GST_WARNING_OBJECT (payload, "invalid media type received"); + return FALSE; + } +} + +static GstFlowReturn +gst_rtp_gsm_pay_handle_buffer (GstRTPBasePayload * basepayload, + GstBuffer * buffer) +{ + GstRTPGSMPay *rtpgsmpay; + guint payload_len; + GstBuffer *outbuf; + GstClockTime timestamp, duration; + GstFlowReturn ret; + + rtpgsmpay = GST_RTP_GSM_PAY (basepayload); + + timestamp = GST_BUFFER_PTS (buffer); + duration = GST_BUFFER_DURATION (buffer); + + /* FIXME, only one GSM frame per RTP packet for now */ + payload_len = gst_buffer_get_size (buffer); + + /* FIXME, just error out for now */ + if (payload_len > GST_RTP_BASE_PAYLOAD_MTU (rtpgsmpay)) + goto too_big; + + outbuf = gst_rtp_buffer_new_allocate (payload_len, 0, 0); + + /* copy timestamp and duration */ + GST_BUFFER_PTS (outbuf) = timestamp; + GST_BUFFER_DURATION (outbuf) = duration; + + /* append payload */ + outbuf = gst_buffer_append (outbuf, buffer); + + GST_DEBUG ("gst_rtp_gsm_pay_chain: pushing buffer of size %" G_GSIZE_FORMAT, + gst_buffer_get_size (outbuf)); + + ret = gst_rtp_base_payload_push (basepayload, outbuf); + + return ret; + + /* ERRORS */ +too_big: + { + GST_ELEMENT_ERROR (rtpgsmpay, STREAM, ENCODE, (NULL), + ("payload_len %u > mtu %u", payload_len, + GST_RTP_BASE_PAYLOAD_MTU (rtpgsmpay))); + return GST_FLOW_ERROR; + } +} + +gboolean +gst_rtp_gsm_pay_plugin_init (GstPlugin * plugin) +{ + return gst_element_register (plugin, "rtpgsmpay", + GST_RANK_SECONDARY, GST_TYPE_RTP_GSM_PAY); +} diff --git a/pool/shard004/C/0097926_main.c b/pool/shard004/C/0097926_main.c new file mode 100644 index 0000000000000000000000000000000000000000..04750d461d34783a4fb6dbd2b281a1ba96ef2d89 --- /dev/null +++ b/pool/shard004/C/0097926_main.c @@ -0,0 +1,57 @@ +#include +#include +#include + +int main(const int argc, char **argv) { + char prettybuf[1024]; + + char *num = NULL; + char *pretty = prettybuf; + ssize_t i = 0; + ssize_t numlen = 0; + int nz = 0; + if (argc != 2) { + fprintf(stderr, "humannum number\n"); + return 1; + } + + num = argv[1]; + + numlen = strlen(num); + for (i = numlen - 1; i >= 0; i--) { + if (num[i] == '0') { + nz++; + } else { + break; + } + } + + if (numlen > sizeof prettybuf) { + pretty = calloc(numlen, 1); + if (pretty == NULL) { + puts(num); + return 0; + } + } + + if (3 <= nz && nz < 6) { + strncpy(pretty, num, numlen - 3); + pretty[numlen - 3] = 'K'; + pretty[numlen - 2] = '\0'; + } else if (6 <= nz && nz < 9) { + strncpy(pretty, num, numlen - 6); + pretty[numlen - 6] = 'M'; + pretty[numlen - 5] = '\0'; + } else if (9 <= nz && nz < 12) { + strncpy(pretty, num, numlen - 9); + pretty[numlen - 9] = 'G'; + pretty[numlen - 8] = '\0'; + } else if (12 <= nz) { + strncpy(pretty, num, numlen - 12); + pretty[numlen - 12] = 'T'; + pretty[numlen - 11] = '\0'; + } else { + pretty = num; + } + puts(pretty); +} diff --git a/pool/shard004/C/0097936_uart.c b/pool/shard004/C/0097936_uart.c new file mode 100644 index 0000000000000000000000000000000000000000..7444cb31563507f5f1aca4f2575ca9fce6977043 --- /dev/null +++ b/pool/shard004/C/0097936_uart.c @@ -0,0 +1,209 @@ +/* + * Copyright (C) 2014-2017 Freie Universität Berlin + * Copyright (C) 2016 OTA keys + * + * 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_stm32_common + * @{ + * + * @file + * @brief Low-level UART driver implementation + * + * @author Hauke Petersen + * @author Thomas Eichinger + * @author Fabian Nack + * @author Hermann Lelong + * @author Toon Stegen + * + * @} + */ + +#include "cpu.h" +#include "sched.h" +#include "thread.h" +#include "assert.h" +#include "periph/uart.h" +#include "periph/gpio.h" + +#ifdef UART_NUMOF + +#define RXENABLE (USART_CR1_RE | USART_CR1_RXNEIE) + +/** + * @brief Allocate memory to store the callback functions + */ +static uart_isr_ctx_t isr_ctx[UART_NUMOF]; + +static inline USART_TypeDef *dev(uart_t uart) +{ + return uart_config[uart].dev; +} + +int uart_init(uart_t uart, uint32_t baudrate, uart_rx_cb_t rx_cb, void *arg) +{ + uint16_t mantissa; + uint8_t fraction; + uint32_t clk; + + assert(uart < UART_NUMOF); + + /* save ISR context */ + isr_ctx[uart].rx_cb = rx_cb; + isr_ctx[uart].arg = arg; + + /* configure TX pin */ + gpio_init(uart_config[uart].tx_pin, GPIO_OUT); + /* set TX pin high to avoid garbage during further initialization */ + gpio_set(uart_config[uart].tx_pin); +#ifdef CPU_FAM_STM32F1 + gpio_init_af(uart_config[uart].tx_pin, GPIO_AF_OUT_PP); +#else + gpio_init_af(uart_config[uart].tx_pin, uart_config[uart].tx_af); +#endif + /* configure RX pin */ + if (rx_cb) { + gpio_init(uart_config[uart].rx_pin, GPIO_IN); +#ifndef CPU_FAM_STM32F1 + gpio_init_af(uart_config[uart].rx_pin, uart_config[uart].rx_af); +#endif + } + + /* enable the clock */ + periph_clk_en(uart_config[uart].bus, uart_config[uart].rcc_mask); + + /* reset UART configuration -> defaults to 8N1 mode */ + dev(uart)->CR1 = 0; + dev(uart)->CR2 = 0; + dev(uart)->CR3 = 0; + + /* calculate and apply baudrate */ + clk = periph_apb_clk(uart_config[uart].bus) / baudrate; + mantissa = (uint16_t)(clk / 16); + fraction = (uint8_t)(clk - (mantissa * 16)); + dev(uart)->BRR = ((mantissa & 0x0fff) << 4) | (fraction & 0x0f); + + /* enable RX interrupt if applicable */ + if (rx_cb) { + NVIC_EnableIRQ(uart_config[uart].irqn); + dev(uart)->CR1 = (USART_CR1_UE | USART_CR1_TE | RXENABLE); + } + else { + dev(uart)->CR1 = (USART_CR1_UE | USART_CR1_TE); + } + + return UART_OK; +} + +void uart_write(uart_t uart, const uint8_t *data, size_t len) +{ + assert(uart < UART_NUMOF); + + for (size_t i = 0; i < len; i++) { +#if defined(CPU_FAM_STM32F0) || defined(CPU_FAM_STM32L0) || defined(CPU_FAM_STM32F3) + while (!(dev(uart)->ISR & USART_ISR_TXE)) {} + dev(uart)->TDR = data[i]; +#else + while (!(dev(uart)->SR & USART_SR_TXE)) {} + dev(uart)->DR = data[i]; +#endif + } + + /* make sure the function is synchronous by waiting for the transfer to + * finish */ +#if defined(CPU_FAM_STM32F0) || defined(CPU_FAM_STM32L0) || defined(CPU_FAM_STM32F3) + while (!(dev(uart)->ISR & USART_ISR_TC)) {} +#else + while (!(dev(uart)->SR & USART_SR_TC)) {} +#endif +} + +void uart_poweron(uart_t uart) +{ + assert(uart < UART_NUMOF); + periph_clk_en(uart_config[uart].bus, uart_config[uart].rcc_mask); +} + +void uart_poweroff(uart_t uart) +{ + assert(uart < UART_NUMOF); + periph_clk_en(uart_config[uart].bus, uart_config[uart].rcc_mask); +} + +static inline void irq_handler(uart_t uart) +{ +#if defined(CPU_FAM_STM32F0) || defined(CPU_FAM_STM32L0) || defined(CPU_FAM_STM32F3) + + uint32_t status = dev(uart)->ISR; + + if (status & USART_ISR_RXNE) { + isr_ctx[uart].rx_cb(isr_ctx[uart].arg, (uint8_t)dev(uart)->RDR); + } + if (status & USART_ISR_ORE) { + dev(uart)->ICR |= USART_ICR_ORECF; /* simply clear flag on overrun */ + } + +#else + + uint32_t status = dev(uart)->SR; + + if (status & USART_SR_RXNE) { + isr_ctx[uart].rx_cb(isr_ctx[uart].arg, (uint8_t)dev(uart)->DR); + } + if (status & USART_SR_ORE) { + /* ORE is cleared by reading SR and DR sequentially */ + dev(uart)->DR; + } + +#endif + + cortexm_isr_end(); +} + +#ifdef UART_0_ISR +void UART_0_ISR(void) +{ + irq_handler(UART_DEV(0)); +} +#endif + +#ifdef UART_1_ISR +void UART_1_ISR(void) +{ + irq_handler(UART_DEV(1)); +} +#endif + +#ifdef UART_2_ISR +void UART_2_ISR(void) +{ + irq_handler(UART_DEV(2)); +} +#endif + +#ifdef UART_3_ISR +void UART_3_ISR(void) +{ + irq_handler(UART_DEV(3)); +} +#endif + +#ifdef UART_4_ISR +void UART_4_ISR(void) +{ + irq_handler(UART_DEV(4)); +} +#endif + +#ifdef UART_5_ISR +void UART_5_ISR(void) +{ + irq_handler(UART_DEV(5)); +} +#endif + +#endif /* UART_NUMOF */ diff --git a/pool/shard004/C/0097937_modparam.c b/pool/shard004/C/0097937_modparam.c new file mode 100644 index 0000000000000000000000000000000000000000..bda9316ef141751210134e4ef03c840ab4105dbc --- /dev/null +++ b/pool/shard004/C/0097937_modparam.c @@ -0,0 +1,138 @@ +/* + * Copyright (C) 2001-2003 FhG Fokus + * + * This file is part of opensips, a free SIP server. + * + * opensips is free software; you can 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 + * + * opensips is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR 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 + * + * History: + * ------- + * 2003-03-20 regex support in modparam (janakj) + * 2004-03-12 extra flag USE_FUNC_PARAM added to modparam type - + * instead of copying the param value, a func is called (bogdan) + */ + +/*! + * \file + * \brief Module parameter configuration + */ + + +#include "modparam.h" +#include "dprint.h" +#include "mem/mem.h" +#include "ut.h" +#include +#include +#include + +int set_mod_param_regex(char* regex, char* name, modparam_t type, void* val) +{ + struct sr_module* t; + param_export_t* param; + regex_t preg; + int mod_found, param_found, len; + char* reg; + int n; + + len = strlen(regex); + reg = pkg_malloc(len + 2 + 2 + 1); + if (reg == 0) { + LM_ERR("no pkg memory left\n"); + return -1; + } + reg[0] = '^'; + reg[1] = '('; + memcpy(reg + 2, regex, len); + reg[len + 2] = ')'; + reg[len + 3] = '$'; + reg[len + 4] = '\0'; + + if (regcomp(&preg, reg, REG_EXTENDED | REG_NOSUB | REG_ICASE)) { + LM_ERR("failed to compile regular expression\n"); + pkg_free(reg); + return -2; + } + + mod_found = 0; + + for(t = modules; t; t = t->next) { + if (regexec(&preg, t->exports->name, 0, 0, 0) == 0) { + LM_DBG("%s matches module %s\n",regex, t->exports->name); + mod_found = 1; + param_found = 0; + + for(param=t->exports->params;param && param->name ; param++) { + + if (strcmp(name, param->name) == 0) { + param_found = 1; + + if (PARAM_TYPE_MASK(param->type) == type) { + LM_DBG("found <%s> in module %s [%s]\n", + name, t->exports->name, t->path); + + if (param->type&USE_FUNC_PARAM) { + n = ((param_func_t)(param->param_pointer))(type, val ); + if (n<0) + return -4; + } else { + switch(type) { + case STR_PARAM: + *((char**)(param->param_pointer)) = + strdup((char*)val); + break; + case INT_PARAM: + *((int*)(param->param_pointer)) = + (int)(long)val; + break; + } + } + + /* register any module deps imposed by this parameter */ + if (add_modparam_dependencies(t, param) != 0) { + LM_ERR("failed to add modparam dependencies!\n"); + return E_BUG; + } + + break; + } + } + } + + if (!param || !param->name) { + if (param_found) + LM_ERR("type mismatch for parameter <%s> in module <%s>\n", + name, t->exports->name); + else + LM_ERR("parameter <%s> not found in module <%s>\n", + name, t->exports->name); + + regfree(&preg); + pkg_free(reg); + return -3; + } + } + } + + regfree(&preg); + if (!mod_found) { + LM_ERR("no module matching %s found\n", regex); + pkg_free(reg); + return -4; + } + + pkg_free(reg); + return 0; +} diff --git a/pool/shard004/C/0097941_alsaplugin.c b/pool/shard004/C/0097941_alsaplugin.c new file mode 100644 index 0000000000000000000000000000000000000000..bf92e7226a757821f17d4275db0876b445228632 --- /dev/null +++ b/pool/shard004/C/0097941_alsaplugin.c @@ -0,0 +1,231 @@ +/* + * This file is part of dcaenc. + * + * Copyright (c) 2008-2012 Alexander E. Patrakov + * + * dcaenc 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. + * + * dcaenc is distributed in the hope that 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 dcaenc; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +#include "ffdcaenc.h" +#include + +#include +#include + +struct dcaplug_info { + snd_pcm_extplug_t ext; + dcaenc_context enc; + int32_t pcm_buffer[6 * 512]; + int16_t dts_buffer[2 * 512]; + snd_pcm_uframes_t bufpos; +}; + +static inline void *area_addr(const snd_pcm_channel_area_t *area, + snd_pcm_uframes_t offset) +{ + uint bitofs = area->first + area->step * offset; + return (char *) area->addr + bitofs / 8; +} + + +static inline int32_t get_s32(const snd_pcm_channel_area_t *area, + snd_pcm_uframes_t offset, snd_pcm_format_t format) +{ + int32_t* sample32; + int16_t* sample16; + switch (format) { + case SND_PCM_FORMAT_S32: + sample32 = (int32_t*)area_addr(area, offset); + return *sample32; + case SND_PCM_FORMAT_S16: + sample16 = (int16_t*)area_addr(area, offset); + return *sample16 * 0x10000; + } + return 0; +} + +static inline void put_s16(const snd_pcm_channel_area_t *area, + snd_pcm_uframes_t offset, int16_t value) +{ + int16_t* sample16 = (int16_t*)area_addr(area, offset); + *sample16 = value; +} + +static snd_pcm_sframes_t dcaplug_transfer(snd_pcm_extplug_t *ext, + const snd_pcm_channel_area_t *dst_areas, snd_pcm_uframes_t dst_offset, + const snd_pcm_channel_area_t *src_areas, snd_pcm_uframes_t src_offset, + snd_pcm_uframes_t size) +{ + struct dcaplug_info *dcaplug = (struct dcaplug_info*)ext; + + /* Force samples to the buffer */ + + snd_pcm_uframes_t remaining = 512 - dcaplug->bufpos; + if (size > remaining) + size = remaining; + + snd_pcm_uframes_t i; + int channel; + int srcbufidx = ext->channels * dcaplug->bufpos; + int dstbufidx = 2 * dcaplug->bufpos; + for (i = 0; i < size; i++) { + if (ext->channels == 4) { + dcaplug->pcm_buffer[srcbufidx++] = get_s32(&src_areas[0], i + src_offset, ext->format); + dcaplug->pcm_buffer[srcbufidx++] = get_s32(&src_areas[1], i + src_offset, ext->format); + dcaplug->pcm_buffer[srcbufidx++] = get_s32(&src_areas[2], i + src_offset, ext->format); + dcaplug->pcm_buffer[srcbufidx++] = get_s32(&src_areas[3], i + src_offset, ext->format); + } else { + dcaplug->pcm_buffer[srcbufidx++] = get_s32(&src_areas[4], i + src_offset, ext->format); + dcaplug->pcm_buffer[srcbufidx++] = get_s32(&src_areas[0], i + src_offset, ext->format); + dcaplug->pcm_buffer[srcbufidx++] = get_s32(&src_areas[1], i + src_offset, ext->format); + dcaplug->pcm_buffer[srcbufidx++] = get_s32(&src_areas[2], i + src_offset, ext->format); + dcaplug->pcm_buffer[srcbufidx++] = get_s32(&src_areas[3], i + src_offset, ext->format); + dcaplug->pcm_buffer[srcbufidx++] = get_s32(&src_areas[5], i + src_offset, ext->format); + } + + put_s16(&dst_areas[0], i + dst_offset, dcaplug->dts_buffer[dstbufidx++]); + put_s16(&dst_areas[1], i + dst_offset, dcaplug->dts_buffer[dstbufidx++]); + } + dcaplug->bufpos += size; + + if (dcaplug->bufpos == 512) { + dcaenc_convert_s32(dcaplug->enc, dcaplug->pcm_buffer, (uint8_t*)dcaplug->dts_buffer); + dcaplug->bufpos = 0; + } + + return size; +} + +static const int32_t zero[512 * 6]; +static int dcaplug_init(snd_pcm_extplug_t *ext) +{ + struct dcaplug_info *dcaplug = (struct dcaplug_info*)ext; + + if (ext->rate != 44100 && ext->rate != 48000) { + SNDERR("Wrong sample rate, must be 44100 or 48000 Hz"); + return -EINVAL; + } + + if (ext->channels == 2) { + /* TODO: passthrough? */ + SNDERR("Conversion from stereo to DTS is pointless"); + return -EINVAL; + } + + if (ext->channels != 4 && ext->channels != 6) { + SNDERR("Wrong number of channels"); + return -EINVAL; + } + + dcaplug->enc = dcaenc_create(ext->rate, + (ext->channels == 4) ? DCAENC_CHANNELS_2FRONT_2REAR : DCAENC_CHANNELS_3FRONT_2REAR, + 32 * ext->rate, /* same as S16 stereo */ + (ext->channels == 4) ? 0 : DCAENC_FLAG_LFE); + + if (!dcaplug->enc) { + SNDERR("Failed to create DCA encoder"); + return -ENOMEM; + } + + if (dcaenc_output_size(dcaplug->enc) != 2048) { + SNDERR("The dcaenc library is incompatible"); + return -EINVAL; + } + + /* Create a dummy frame of silence */ + dcaenc_convert_s32(dcaplug->enc, zero, (uint8_t*)dcaplug->dts_buffer); + + return 0; +} + +static int dcaplug_close(snd_pcm_extplug_t *ext) +{ + struct dcaplug_info *dcaplug = (struct dcaplug_info*)ext; + + dcaenc_destroy(dcaplug->enc, NULL); + dcaplug->enc = NULL; + return 0; +} + +static const snd_pcm_extplug_callback_t dcaplug_callback = { + .transfer = dcaplug_transfer, + .init = dcaplug_init, + .close = dcaplug_close, +}; + + +SND_PCM_PLUGIN_DEFINE_FUNC(dca) +{ + snd_config_iterator_t i, next; + snd_config_t *slave = NULL; + struct dcaplug_info *dcaplug; + int err; + + if (stream != SND_PCM_STREAM_PLAYBACK) { + SNDERR("dca is only for playback"); + return -EINVAL; + } + snd_config_for_each(i, next, conf) { + snd_config_t *n = snd_config_iterator_entry(i); + const char *id; + if (snd_config_get_id(n, &id) < 0) + continue; + if (strcmp(id, "comment") == 0 || strcmp(id, "type") == 0 || strcmp(id, "hint") == 0) + continue; + if (strcmp(id, "slave") == 0) { + slave = n; + continue; + } + SNDERR("Unknown field %s", id); + return -EINVAL; + } + + if (!slave) { + SNDERR("No slave defined for dca"); + return -EINVAL; + } + + dcaplug = calloc(1, sizeof(*dcaplug)); + if (dcaplug == NULL) + return -ENOMEM; + + dcaplug->ext.version = SND_PCM_EXTPLUG_VERSION; + dcaplug->ext.name = "DTS Coherent Acoustics encoder"; + dcaplug->ext.callback = &dcaplug_callback; + dcaplug->ext.private_data = dcaplug; + + err = snd_pcm_extplug_create(&dcaplug->ext, name, root, slave, stream, mode); + if (err < 0) { + dcaenc_destroy(dcaplug->enc, NULL); + free(dcaplug); + return err; + } + + static const int channels[2] = {4, 6}; + static const int formats[2] = {SND_PCM_FORMAT_S32, SND_PCM_FORMAT_S16}; + + snd_pcm_extplug_set_param_list(&dcaplug->ext, SND_PCM_EXTPLUG_HW_CHANNELS, + 2, channels); + snd_pcm_extplug_set_slave_param(&dcaplug->ext, SND_PCM_EXTPLUG_HW_CHANNELS, 2); + + snd_pcm_extplug_set_param_list(&dcaplug->ext, SND_PCM_EXTPLUG_HW_FORMAT, + 2, formats); + snd_pcm_extplug_set_slave_param(&dcaplug->ext, SND_PCM_EXTPLUG_HW_FORMAT, SND_PCM_FORMAT_S16); + + *pcmp = dcaplug->ext.pcm; + return 0; +} + +SND_PCM_PLUGIN_SYMBOL(dca); diff --git a/pool/shard004/C/0097943_t-add.c b/pool/shard004/C/0097943_t-add.c new file mode 100644 index 0000000000000000000000000000000000000000..dacc6382e44d3c4456c81c1880011c8f0dedfceb --- /dev/null +++ b/pool/shard004/C/0097943_t-add.c @@ -0,0 +1,108 @@ +/* Test mpf_add. + +Copyright 1996, 2001 Free Software Foundation, Inc. + +This file is part of the GNU MP Library test suite. + +The GNU MP Library test suite is free software; you can redistribute it +and/or modify it under the terms of the GNU General Public License as +published by the Free Software Foundation; either version 3 of the License, +or (at your option) any later version. + +The GNU MP Library test suite is distributed in the hope that it will be +useful, but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General +Public License for more details. + +You should have received a copy of the GNU General Public License along with +the GNU MP Library test suite. If not, see https://www.gnu.org/licenses/. */ + +#include +#include + +#include "gmp.h" +#include "gmp-impl.h" +#include "tests.h" + +#ifndef SIZE +#define SIZE 16 +#endif + +int +main (int argc, char **argv) +{ + mp_size_t size; + mp_exp_t exp; + int reps = 20000; + int i; + mpf_t u, v, w, wref; + mp_size_t bprec = 100; + mpf_t rerr, max_rerr, limit_rerr; + + tests_start (); + + if (argc > 1) + { + reps = strtol (argv[1], 0, 0); + if (argc > 2) + bprec = strtol (argv[2], 0, 0); + } + + mpf_set_default_prec (bprec); + + mpf_init_set_ui (limit_rerr, 1); + mpf_div_2exp (limit_rerr, limit_rerr, bprec); +#if VERBOSE + mpf_dump (limit_rerr); +#endif + mpf_init (rerr); + mpf_init_set_ui (max_rerr, 0); + + mpf_init (u); + mpf_init (v); + mpf_init (w); + mpf_init (wref); + for (i = 0; i < reps; i++) + { + size = urandom () % (2 * SIZE) - SIZE; + exp = urandom () % SIZE; + mpf_random2 (u, size, exp); + + size = urandom () % (2 * SIZE) - SIZE; + exp = urandom () % SIZE; + mpf_random2 (v, size, exp); + + mpf_add (w, u, v); + refmpf_add (wref, u, v); + + mpf_reldiff (rerr, w, wref); + if (mpf_cmp (rerr, max_rerr) > 0) + { + mpf_set (max_rerr, rerr); +#if VERBOSE + mpf_dump (max_rerr); +#endif + if (mpf_cmp (rerr, limit_rerr) > 0) + { + printf ("ERROR after %d tests\n", i); + printf (" u = "); mpf_dump (u); + printf (" v = "); mpf_dump (v); + printf ("wref = "); mpf_dump (wref); + printf (" w = "); mpf_dump (w); + abort (); + } + } + } + + mpf_clear (limit_rerr); + mpf_clear (rerr); + mpf_clear (max_rerr); + + mpf_clear (u); + mpf_clear (v); + mpf_clear (w); + mpf_clear (wref); + + tests_end (); + exit (0); +} diff --git a/pool/shard004/C/0097944_proc.c b/pool/shard004/C/0097944_proc.c new file mode 100644 index 0000000000000000000000000000000000000000..2267cfbd2d1b2c5f7a13da80355e191ae2c89658 --- /dev/null +++ b/pool/shard004/C/0097944_proc.c @@ -0,0 +1,179 @@ +/* Copyright (C) 2005, 2006, 2007 Free Software Foundation, Inc. + Contributed by Jakub Jelinek . + + This file is part of the GNU OpenMP Library (libgomp). + + Libgomp 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. + + Libgomp is distributed in the hope that 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 libgomp; see the file COPYING.LIB. If not, write to the + Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, + MA 02110-1301, USA. */ + +/* As a special exception, if you link this library with other files, some + of which are compiled with GCC, to produce an executable, this library + does not by itself cause the resulting executable to be covered by the + GNU General Public License. This exception does not however invalidate + any other reasons why the executable file might be covered by the GNU + General Public License. */ + +/* This file contains system specific routines related to counting + online processors and dynamic load balancing. */ + +#ifndef _GNU_SOURCE +#define _GNU_SOURCE 1 +#endif +#include "libgomp.h" +#include +#include +#include +#ifdef HAVE_GETLOADAVG +# ifdef HAVE_SYS_LOADAVG_H +# include +# endif +#endif + +#ifdef HAVE_PTHREAD_AFFINITY_NP +static unsigned long +cpuset_popcount (cpu_set_t *cpusetp) +{ +#ifdef CPU_COUNT + /* glibc 2.6 and above provide a macro for this. */ + return CPU_COUNT (cpusetp); +#else + size_t i; + unsigned long ret = 0; + extern int check[sizeof (cpusetp->__bits[0]) == sizeof (unsigned long int)]; + + (void) check; + for (i = 0; i < sizeof (*cpusetp) / sizeof (cpusetp->__bits[0]); i++) + { + unsigned long int mask = cpusetp->__bits[i]; + if (mask == 0) + continue; + ret += __builtin_popcountl (mask); + } + return ret; +#endif +} +#endif + +/* At startup, determine the default number of threads. It would seem + this should be related to the number of cpus online. */ + +void +gomp_init_num_threads (void) +{ +#ifdef HAVE_PTHREAD_AFFINITY_NP + cpu_set_t cpuset; + + if (pthread_getaffinity_np (pthread_self (), sizeof (cpuset), &cpuset) == 0) + { + /* Count only the CPUs this process can use. */ + gomp_nthreads_var = cpuset_popcount (&cpuset); + if (gomp_nthreads_var == 0) + gomp_nthreads_var = 1; + return; + } +#endif +#ifdef _SC_NPROCESSORS_ONLN + gomp_nthreads_var = sysconf (_SC_NPROCESSORS_ONLN); +#endif +} + +static int +get_num_procs (void) +{ +#ifdef HAVE_PTHREAD_AFFINITY_NP + cpu_set_t cpuset; + + if (gomp_cpu_affinity == NULL) + { + /* Count only the CPUs this process can use. */ + if (pthread_getaffinity_np (pthread_self (), sizeof (cpuset), + &cpuset) == 0) + { + int ret = cpuset_popcount (&cpuset); + return ret != 0 ? ret : 1; + } + } + else + { + size_t idx; + static int affinity_cpus; + + /* We can't use pthread_getaffinity_np in this case + (we have changed it ourselves, it binds to just one CPU). + Count instead the number of different CPUs we are + using. */ + CPU_ZERO (&cpuset); + if (affinity_cpus == 0) + { + int cpus = 0; + for (idx = 0; idx < gomp_cpu_affinity_len; idx++) + if (! CPU_ISSET (gomp_cpu_affinity[idx], &cpuset)) + { + cpus++; + CPU_SET (gomp_cpu_affinity[idx], &cpuset); + } + affinity_cpus = cpus; + } + return affinity_cpus; + } +#endif +#ifdef _SC_NPROCESSORS_ONLN + return sysconf (_SC_NPROCESSORS_ONLN); +#else + return gomp_nthreads_var; +#endif +} + +/* When OMP_DYNAMIC is set, at thread launch determine the number of + threads we should spawn for this team. */ +/* ??? I have no idea what best practice for this is. Surely some + function of the number of processors that are *still* online and + the load average. Here I use the number of processors online + minus the 15 minute load average. */ + +unsigned +gomp_dynamic_max_threads (void) +{ + unsigned n_onln, loadavg; + + n_onln = get_num_procs (); + if (n_onln > gomp_nthreads_var) + n_onln = gomp_nthreads_var; + + loadavg = 0; +#ifdef HAVE_GETLOADAVG + { + double dloadavg[3]; + if (getloadavg (dloadavg, 3) == 3) + { + /* Add 0.1 to get a kind of biased rounding. */ + loadavg = dloadavg[2] + 0.1; + } + } +#endif + + if (loadavg >= n_onln) + return 1; + else + return n_onln - loadavg; +} + +int +omp_get_num_procs (void) +{ + return get_num_procs (); +} + +ialias (omp_get_num_procs) diff --git a/pool/shard004/C/0097962_srat_32.c b/pool/shard004/C/0097962_srat_32.c new file mode 100644 index 0000000000000000000000000000000000000000..6f8aa33031c7486dde049c2ffc875e886598c075 --- /dev/null +++ b/pool/shard004/C/0097962_srat_32.c @@ -0,0 +1,283 @@ +/* + * Some of the code in this file has been gleaned from the 64 bit + * discontigmem support code base. + * + * Copyright (C) 2002, IBM Corp. + * + * All rights reserved. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, GOOD TITLE or + * NON INFRINGEMENT. See the GNU General Public License for more + * details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. + * + * Send feedback to Pat Gaughen + */ +#include +#include +#include +#include +#include +#include +#include +#include +#include + +/* + * proximity macros and definitions + */ +#define NODE_ARRAY_INDEX(x) ((x) / 8) /* 8 bits/char */ +#define NODE_ARRAY_OFFSET(x) ((x) % 8) /* 8 bits/char */ +#define BMAP_SET(bmap, bit) ((bmap)[NODE_ARRAY_INDEX(bit)] |= 1 << NODE_ARRAY_OFFSET(bit)) +#define BMAP_TEST(bmap, bit) ((bmap)[NODE_ARRAY_INDEX(bit)] & (1 << NODE_ARRAY_OFFSET(bit))) +/* bitmap length; _PXM is at most 255 */ +#define PXM_BITMAP_LEN (MAX_PXM_DOMAINS / 8) +static u8 __initdata pxm_bitmap[PXM_BITMAP_LEN]; /* bitmap of proximity domains */ + +#define MAX_CHUNKS_PER_NODE 3 +#define MAXCHUNKS (MAX_CHUNKS_PER_NODE * MAX_NUMNODES) +struct node_memory_chunk_s { + unsigned long start_pfn; + unsigned long end_pfn; + u8 pxm; // proximity domain of node + u8 nid; // which cnode contains this chunk? + u8 bank; // which mem bank on this node +}; +static struct node_memory_chunk_s __initdata node_memory_chunk[MAXCHUNKS]; + +static int __initdata num_memory_chunks; /* total number of memory chunks */ +static u8 __initdata apicid_to_pxm[MAX_APICID]; + +int numa_off __initdata; +int acpi_numa __initdata; + +static __init void bad_srat(void) +{ + printk(KERN_ERR "SRAT: SRAT not used.\n"); + acpi_numa = -1; + num_memory_chunks = 0; +} + +static __init inline int srat_disabled(void) +{ + return numa_off || acpi_numa < 0; +} + +/* Identify CPU proximity domains */ +void __init +acpi_numa_processor_affinity_init(struct acpi_srat_cpu_affinity *cpu_affinity) +{ + if (srat_disabled()) + return; + if (cpu_affinity->header.length != + sizeof(struct acpi_srat_cpu_affinity)) { + bad_srat(); + return; + } + + if ((cpu_affinity->flags & ACPI_SRAT_CPU_ENABLED) == 0) + return; /* empty entry */ + + /* mark this node as "seen" in node bitmap */ + BMAP_SET(pxm_bitmap, cpu_affinity->proximity_domain_lo); + + apicid_to_pxm[cpu_affinity->apic_id] = cpu_affinity->proximity_domain_lo; + + printk(KERN_DEBUG "CPU %02x in proximity domain %02x\n", + cpu_affinity->apic_id, cpu_affinity->proximity_domain_lo); +} + +/* + * Identify memory proximity domains and hot-remove capabilities. + * Fill node memory chunk list structure. + */ +void __init +acpi_numa_memory_affinity_init(struct acpi_srat_mem_affinity *memory_affinity) +{ + unsigned long long paddr, size; + unsigned long start_pfn, end_pfn; + u8 pxm; + struct node_memory_chunk_s *p, *q, *pend; + + if (srat_disabled()) + return; + if (memory_affinity->header.length != + sizeof(struct acpi_srat_mem_affinity)) { + bad_srat(); + return; + } + + if ((memory_affinity->flags & ACPI_SRAT_MEM_ENABLED) == 0) + return; /* empty entry */ + + pxm = memory_affinity->proximity_domain & 0xff; + + /* mark this node as "seen" in node bitmap */ + BMAP_SET(pxm_bitmap, pxm); + + /* calculate info for memory chunk structure */ + paddr = memory_affinity->base_address; + size = memory_affinity->length; + + start_pfn = paddr >> PAGE_SHIFT; + end_pfn = (paddr + size) >> PAGE_SHIFT; + + + if (num_memory_chunks >= MAXCHUNKS) { + printk(KERN_WARNING "Too many mem chunks in SRAT." + " Ignoring %lld MBytes at %llx\n", + size/(1024*1024), paddr); + return; + } + + /* Insertion sort based on base address */ + pend = &node_memory_chunk[num_memory_chunks]; + for (p = &node_memory_chunk[0]; p < pend; p++) { + if (start_pfn < p->start_pfn) + break; + } + if (p < pend) { + for (q = pend; q >= p; q--) + *(q + 1) = *q; + } + p->start_pfn = start_pfn; + p->end_pfn = end_pfn; + p->pxm = pxm; + + num_memory_chunks++; + + printk(KERN_DEBUG "Memory range %08lx to %08lx" + " in proximity domain %02x %s\n", + start_pfn, end_pfn, + pxm, + ((memory_affinity->flags & ACPI_SRAT_MEM_HOT_PLUGGABLE) ? + "enabled and removable" : "enabled" ) ); +} + +/* Callback for SLIT parsing */ +void __init acpi_numa_slit_init(struct acpi_table_slit *slit) +{ +} + +void acpi_numa_arch_fixup(void) +{ +} +/* + * The SRAT table always lists ascending addresses, so can always + * assume that the first "start" address that you see is the real + * start of the node, and that the current "end" address is after + * the previous one. + */ +static __init int node_read_chunk(int nid, struct node_memory_chunk_s *memory_chunk) +{ + /* + * Only add present memory as told by the e820. + * There is no guarantee from the SRAT that the memory it + * enumerates is present at boot time because it represents + * *possible* memory hotplug areas the same as normal RAM. + */ + if (memory_chunk->start_pfn >= max_pfn) { + printk(KERN_INFO "Ignoring SRAT pfns: %08lx - %08lx\n", + memory_chunk->start_pfn, memory_chunk->end_pfn); + return -1; + } + if (memory_chunk->nid != nid) + return -1; + + if (!node_has_online_mem(nid)) + node_start_pfn[nid] = memory_chunk->start_pfn; + + if (node_start_pfn[nid] > memory_chunk->start_pfn) + node_start_pfn[nid] = memory_chunk->start_pfn; + + if (node_end_pfn[nid] < memory_chunk->end_pfn) + node_end_pfn[nid] = memory_chunk->end_pfn; + + return 0; +} + +int __init get_memcfg_from_srat(void) +{ + int i, j, nid; + + + if (srat_disabled()) + goto out_fail; + + if (num_memory_chunks == 0) { + printk(KERN_DEBUG + "could not find any ACPI SRAT memory areas.\n"); + goto out_fail; + } + + /* Calculate total number of nodes in system from PXM bitmap and create + * a set of sequential node IDs starting at zero. (ACPI doesn't seem + * to specify the range of _PXM values.) + */ + /* + * MCD - we no longer HAVE to number nodes sequentially. PXM domain + * numbers could go as high as 256, and MAX_NUMNODES for i386 is typically + * 32, so we will continue numbering them in this manner until MAX_NUMNODES + * approaches MAX_PXM_DOMAINS for i386. + */ + nodes_clear(node_online_map); + for (i = 0; i < MAX_PXM_DOMAINS; i++) { + if (BMAP_TEST(pxm_bitmap, i)) { + int nid = acpi_map_pxm_to_node(i); + node_set_online(nid); + } + } + BUG_ON(num_online_nodes() == 0); + + /* set cnode id in memory chunk structure */ + for (i = 0; i < num_memory_chunks; i++) + node_memory_chunk[i].nid = pxm_to_node(node_memory_chunk[i].pxm); + + printk(KERN_DEBUG "pxm bitmap: "); + for (i = 0; i < sizeof(pxm_bitmap); i++) { + printk(KERN_CONT "%02x ", pxm_bitmap[i]); + } + printk(KERN_CONT "\n"); + printk(KERN_DEBUG "Number of logical nodes in system = %d\n", + num_online_nodes()); + printk(KERN_DEBUG "Number of memory chunks in system = %d\n", + num_memory_chunks); + + for (i = 0; i < MAX_APICID; i++) + apicid_2_node[i] = pxm_to_node(apicid_to_pxm[i]); + + for (j = 0; j < num_memory_chunks; j++){ + struct node_memory_chunk_s * chunk = &node_memory_chunk[j]; + printk(KERN_DEBUG + "chunk %d nid %d start_pfn %08lx end_pfn %08lx\n", + j, chunk->nid, chunk->start_pfn, chunk->end_pfn); + if (node_read_chunk(chunk->nid, chunk)) + continue; + + e820_register_active_regions(chunk->nid, chunk->start_pfn, + min(chunk->end_pfn, max_pfn)); + } + + for_each_online_node(nid) { + unsigned long start = node_start_pfn[nid]; + unsigned long end = min(node_end_pfn[nid], max_pfn); + + memory_present(nid, start, end); + node_remap_size[nid] = node_memmap_size_bytes(nid, start, end); + } + return 1; +out_fail: + printk(KERN_DEBUG "failed to get NUMA memory information from SRAT" + " table\n"); + return 0; +} diff --git a/pool/shard004/C/0097965_spawn_merge_child2.c b/pool/shard004/C/0097965_spawn_merge_child2.c new file mode 100644 index 0000000000000000000000000000000000000000..997f2f978fe406e53897bd9a65bb96e0abf5da02 --- /dev/null +++ b/pool/shard004/C/0097965_spawn_merge_child2.c @@ -0,0 +1,32 @@ +/* -*- Mode: C; c-basic-offset:4 ; indent-tabs-mode:nil ; -*- */ +/* + * (C) 2001 by Argonne National Laboratory. + * See COPYRIGHT in top-level directory. + */ + +#include +#include "mpi.h" + +int main( int argc, char *argv[] ) +{ + MPI_Comm intercomm; + char str[10]; + int err, rank; + + MPI_Init(&argc, &argv); + + MPI_Comm_rank(MPI_COMM_WORLD, &rank); + + MPI_Comm_get_parent(&intercomm); + + if (rank == 1){ + err = MPI_Send("hi", 3, MPI_CHAR, 3, 0, intercomm); + + err = MPI_Recv(str, 4, MPI_CHAR, 3, 0, intercomm, MPI_STATUS_IGNORE); + printf("Child 2 received from parent (first child): %s\n", str); + fflush(stdout); + } + + MPI_Finalize(); + return 0; +} diff --git a/pool/shard004/C/0097969_tofile.c b/pool/shard004/C/0097969_tofile.c new file mode 100644 index 0000000000000000000000000000000000000000..6bd8c509e1226d720144d85f5c7ed05851da7a97 --- /dev/null +++ b/pool/shard004/C/0097969_tofile.c @@ -0,0 +1,71 @@ +#include +#include +#include +#include +#include +#include "samples.h" +#include "filters.h" + +int dump_raw_results_to_file (const char* filepath, struct sample_cont *samples) +{ + errno = 0; + int i = 0; + + FILE *outf = fopen(filepath, "w"); + + if (errno != 0) { + printf("Couldn't open csv file.\n"); + return 1; + } + + double freq_mult = (double)samples->samplerate / samples->total_samples; + double freq; + double ampl; + + for (i = 0; i < (samples->total_samples / 2 + 1); i++) { + ampl = pow(samples->fft_out[i][0], 2.0); + ampl = ampl + pow(samples->fft_out[i][1], 2.0); + ampl = sqrt(ampl); + freq = i * freq_mult; + fprintf(outf, "%f, %f\n", freq, ampl); + } + + fclose(outf); + return 0; +} + +int dump_fft_results_to_file (const char* filepath, struct sample_cont *samples) +{ + errno = 0; + int i = 0; + + FILE *outf = fopen(filepath, "w"); + + if (errno != 0) { + printf("Couldn't open csv file.\n"); + return 1; + } + + for (i = 0; i < (samples->total_samples / 2 + 1); i++) + fprintf(outf, "%f, %f\n", samples->freq[i], samples->ampl[i]); + + return 0; +} + +int dump_peaks_to_file (const char* filepath, struct sample_cont *samples) +{ + struct data_lln *next = samples->peakll; + FILE *outf = fopen(filepath, "w"); + if (outf == NULL) + return 1; + + fprintf(outf, "Frequency, Amplitude\n"); + + while (next != NULL) { + fprintf(outf, "%f, %f\n", next->freq, next->ampl); + next = next->next; + } + + fclose(outf); + return 0; +} diff --git a/pool/shard004/C/0097975_port_windows.c b/pool/shard004/C/0097975_port_windows.c new file mode 100644 index 0000000000000000000000000000000000000000..9023719675824840b55fb60ad506f3653e9cf4fb --- /dev/null +++ b/pool/shard004/C/0097975_port_windows.c @@ -0,0 +1,245 @@ +/* + * + * 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 "test/core/util/test_config.h" +#if defined(GPR_WINSOCK_SOCKET) && defined(GRPC_TEST_PICK_PORT) + +#include "test/core/util/port.h" + +#include +#include +#include +#include + +#include +#include +#include + +#include "src/core/lib/http/httpcli.h" +#include "src/core/lib/iomgr/sockaddr_utils.h" +#include "src/core/lib/support/env.h" +#include "test/core/util/port_server_client.h" + +#if GPR_GETPID_IN_UNISTD_H +#include +static int _getpid() { return getpid(); } +#endif + +#define NUM_RANDOM_PORTS_TO_PICK 100 + +static int *chosen_ports = NULL; +static size_t num_chosen_ports = 0; + +static int has_port_been_chosen(int port) { + size_t i; + for (i = 0; i < num_chosen_ports; i++) { + if (chosen_ports[i] == port) { + return 1; + } + } + return 0; +} + +static int free_chosen_port(int port) { + size_t i; + int found = 0; + size_t found_at = 0; + char *env = gpr_getenv("GRPC_TEST_PORT_SERVER"); + if (env != NULL) { + /* Find the port and erase it from the list, then tell the server it can be + freed. */ + for (i = 0; i < num_chosen_ports; i++) { + if (chosen_ports[i] == port) { + GPR_ASSERT(found == 0); + found = 1; + found_at = i; + } + } + if (found) { + chosen_ports[found_at] = chosen_ports[num_chosen_ports - 1]; + grpc_free_port_using_server(env, port); + num_chosen_ports--; + } + } + return found; +} + +static void free_chosen_ports(void) { + char *env = gpr_getenv("GRPC_TEST_PORT_SERVER"); + if (env != NULL) { + size_t i; + for (i = 0; i < num_chosen_ports; i++) { + grpc_free_port_using_server(env, chosen_ports[i]); + } + gpr_free(env); + } + + gpr_free(chosen_ports); +} + +static void chose_port(int port) { + if (chosen_ports == NULL) { + atexit(free_chosen_ports); + } + num_chosen_ports++; + chosen_ports = gpr_realloc(chosen_ports, sizeof(int) * num_chosen_ports); + chosen_ports[num_chosen_ports - 1] = port; +} + +static int is_port_available(int *port, int is_tcp) { + const int proto = is_tcp ? IPPROTO_TCP : 0; + const SOCKET fd = socket(AF_INET, is_tcp ? SOCK_STREAM : SOCK_DGRAM, proto); + int one = 1; + struct sockaddr_in addr; + socklen_t alen = sizeof(addr); + int actual_port; + + GPR_ASSERT(*port >= 0); + GPR_ASSERT(*port <= 65535); + if (INVALID_SOCKET == fd) { + gpr_log(GPR_ERROR, "socket() failed: %s", strerror(errno)); + return 0; + } + + /* Reuseaddr lets us start up a server immediately after it exits */ + if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&one, + sizeof(one)) < 0) { + gpr_log(GPR_ERROR, "setsockopt() failed: %s", strerror(errno)); + closesocket(fd); + return 0; + } + + /* Try binding to port */ + addr.sin_family = AF_INET; + addr.sin_addr.s_addr = INADDR_ANY; + addr.sin_port = htons((u_short)*port); + if (bind(fd, (struct sockaddr *)&addr, sizeof(addr)) < 0) { + gpr_log(GPR_DEBUG, "bind(port=%d) failed: %s", *port, strerror(errno)); + closesocket(fd); + return 0; + } + + /* Get the bound port number */ + if (getsockname(fd, (struct sockaddr *)&addr, &alen) < 0) { + gpr_log(GPR_ERROR, "getsockname() failed: %s", strerror(errno)); + closesocket(fd); + return 0; + } + GPR_ASSERT(alen <= (socklen_t)sizeof(addr)); + actual_port = ntohs(addr.sin_port); + GPR_ASSERT(actual_port > 0); + if (*port == 0) { + *port = actual_port; + } else { + GPR_ASSERT(*port == actual_port); + } + + closesocket(fd); + return 1; +} + +int grpc_pick_unused_port(void) { + /* We repeatedly pick a port and then see whether or not it is + available for use both as a TCP socket and a UDP socket. First, we + pick a random large port number. For subsequent + iterations, we bind to an anonymous port and let the OS pick the + port number. The random port picking reduces the probability of + races with other processes on kernels that want to reuse the same + port numbers over and over. */ + + /* In alternating iterations we trial UDP ports before TCP ports UDP + ports -- it could be the case that this machine has been using up + UDP ports and they are scarcer. */ + + /* Type of port to first pick in next iteration */ + int is_tcp = 1; + int trial = 0; + + char *env = gpr_getenv("GRPC_TEST_PORT_SERVER"); + if (env) { + int port = grpc_pick_port_using_server(env); + gpr_free(env); + if (port != 0) { + return port; + } + } + + for (;;) { + int port; + trial++; + if (trial == 1) { + port = _getpid() % (65536 - 30000) + 30000; + } else if (trial <= NUM_RANDOM_PORTS_TO_PICK) { + port = rand() % (65536 - 30000) + 30000; + } else { + port = 0; + } + + if (has_port_been_chosen(port)) { + continue; + } + + if (!is_port_available(&port, is_tcp)) { + continue; + } + + GPR_ASSERT(port > 0); + /* Check that the port # is free for the other type of socket also */ + if (!is_port_available(&port, !is_tcp)) { + /* In the next iteration trial to bind to the other type first + because perhaps it is more rare. */ + is_tcp = !is_tcp; + continue; + } + + /* TODO(ctiller): consider caching this port in some structure, to avoid + handing it out again */ + + chose_port(port); + return port; + } + + /* The port iterator reached the end without finding a suitable port. */ + return 0; +} + +int grpc_pick_unused_port_or_die(void) { + int port = grpc_pick_unused_port(); + GPR_ASSERT(port > 0); + return port; +} + +void grpc_recycle_unused_port(int port) { GPR_ASSERT(free_chosen_port(port)); } + +#endif /* GPR_WINSOCK_SOCKET && GRPC_TEST_PICK_PORT */ diff --git a/pool/shard004/C/0097984_waitpid-test-01.c b/pool/shard004/C/0097984_waitpid-test-01.c new file mode 100644 index 0000000000000000000000000000000000000000..60c4822f6b33e3bdaaa0ad6af765ec4fcea7ff54 --- /dev/null +++ b/pool/shard004/C/0097984_waitpid-test-01.c @@ -0,0 +1,69 @@ +// Copyright 2005-2006,2008,2015 BitMover, Inc +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +/* + * Test waitpid in the case when the child has exited before the + * call to waitpid. + */ +#include "system.h" + +char *file = "CHILD_LOCK"; +char *helper = "prog01.exe"; + +int +main(int ac, char **av) +{ + int ret, retry, rc; + pid_t pid; + char *argv[10]; + HANDLE h; + + h = CreateFile(file, GENERIC_WRITE, FILE_SHARE_WRITE, 0, + CREATE_NEW, FILE_ATTRIBUTE_NORMAL, 0); + if (h == INVALID_HANDLE_VALUE) { + fprintf(stderr, "cannot create file %s. Error number %ld\n", + file, GetLastError()); + exit(1); + } + CloseHandle(h); + + argv[0] = helper; + argv[1] = file; + argv[2] = 0; + + if ((pid = _spawnvp_ex(_P_NOWAIT, argv[0], argv, 1)) == -1) { + fprintf(stderr, "cannot spawn %s\n", argv[0]); + exit(1); + } + + /* Make sure the child is gone before we waitpid */ + retry = 10; + while (retry && GetFileAttributes(file) != INVALID_FILE_ATTRIBUTES) { + retry--; + sleep(1); + } + if (retry == 0) { + fprintf(stderr, "got tired of waiting for child\n"); + exit(1); + } + + if (waitpid(pid, &ret, 0) < 0) { + fprintf(stderr, "waitpid failed\n"); + exit(1); + } else if (!WIFEXITED(ret)) { + fprintf(stderr, "%s exited abnormally\n", argv[0]); + } + rc = WEXITSTATUS(ret); + exit(rc); +} diff --git a/pool/shard004/C/0097988_dtwalk.c b/pool/shard004/C/0097988_dtwalk.c new file mode 100644 index 0000000000000000000000000000000000000000..fca39e7ca8084f886f3f289e625ad7727ca59bac --- /dev/null +++ b/pool/shard004/C/0097988_dtwalk.c @@ -0,0 +1,24 @@ +#include "dthdr.h" + +/* Walk a dictionary and all dictionaries viewed through it. +** userf: user function +** +** Written by Kiem-Phong Vo (5/25/96) +*/ + +int dtwalk(reg Dt_t* dt, int (*userf)(Dt_t*, void*, void*), void* data) +{ + reg void *obj, *next; + reg Dt_t* walk; + reg int rv; + + for(obj = dtfirst(dt); obj; ) + { if(!(walk = dt->walk) ) + walk = dt; + next = dtnext(dt,obj); + if((rv = (*userf)(walk, obj, data )) < 0) + return rv; + obj = next; + } + return 0; +} diff --git a/pool/shard004/C/0097992_sclp_config.c b/pool/shard004/C/0097992_sclp_config.c new file mode 100644 index 0000000000000000000000000000000000000000..3a4a3d7b5f26a77d3e5f74781ba0c42abb109ffa --- /dev/null +++ b/pool/shard004/C/0097992_sclp_config.c @@ -0,0 +1,100 @@ +/* + * drivers/s390/char/sclp_config.c + * + * Copyright IBM Corp. 2007 + * Author(s): Heiko Carstens + */ + +#define KMSG_COMPONENT "sclp_config" +#define pr_fmt(fmt) KMSG_COMPONENT ": " fmt + +#include +#include +#include +#include +#include +#include + +#include "sclp.h" + +struct conf_mgm_data { + u8 reserved; + u8 ev_qualifier; +} __attribute__((packed)); + +#define EV_QUAL_CPU_CHANGE 1 +#define EV_QUAL_CAP_CHANGE 3 + +static struct work_struct sclp_cpu_capability_work; +static struct work_struct sclp_cpu_change_work; + +static void sclp_cpu_capability_notify(struct work_struct *work) +{ + int cpu; + struct sys_device *sysdev; + +<<<<<<< HEAD + s390_adjust_jiffies(); +======= +>>>>>>> 296c66da8a02d52243f45b80521febece5ed498a + pr_warning("cpu capability changed.\n"); + get_online_cpus(); + for_each_online_cpu(cpu) { + sysdev = get_cpu_sysdev(cpu); + kobject_uevent(&sysdev->kobj, KOBJ_CHANGE); + } + put_online_cpus(); +} + +static void __ref sclp_cpu_change_notify(struct work_struct *work) +{ + smp_rescan_cpus(); +} + +static void sclp_conf_receiver_fn(struct evbuf_header *evbuf) +{ + struct conf_mgm_data *cdata; + + cdata = (struct conf_mgm_data *)(evbuf + 1); + switch (cdata->ev_qualifier) { + case EV_QUAL_CPU_CHANGE: + schedule_work(&sclp_cpu_change_work); + break; + case EV_QUAL_CAP_CHANGE: + schedule_work(&sclp_cpu_capability_work); + break; + } +} + +static struct sclp_register sclp_conf_register = +{ + .receive_mask = EVTYP_CONFMGMDATA_MASK, + .receiver_fn = sclp_conf_receiver_fn, +}; + +static int __init sclp_conf_init(void) +{ +<<<<<<< HEAD + INIT_WORK(&sclp_cpu_capability_work, sclp_cpu_capability_notify); + INIT_WORK(&sclp_cpu_change_work, sclp_cpu_change_notify); + return sclp_register(&sclp_conf_register); +======= + int rc; + + INIT_WORK(&sclp_cpu_capability_work, sclp_cpu_capability_notify); + INIT_WORK(&sclp_cpu_change_work, sclp_cpu_change_notify); + + rc = sclp_register(&sclp_conf_register); + if (rc) + return rc; + + if (!(sclp_conf_register.sclp_send_mask & EVTYP_CONFMGMDATA_MASK)) { + pr_warning("no configuration management.\n"); + sclp_unregister(&sclp_conf_register); + rc = -ENOSYS; + } + return rc; +>>>>>>> 296c66da8a02d52243f45b80521febece5ed498a +} + +__initcall(sclp_conf_init); diff --git a/pool/shard004/C/0097993_i2chelper.c b/pool/shard004/C/0097993_i2chelper.c new file mode 100644 index 0000000000000000000000000000000000000000..a738aa923bb40ac63fd225f17160fc008b386c99 --- /dev/null +++ b/pool/shard004/C/0097993_i2chelper.c @@ -0,0 +1,83 @@ +/* + * Can't use the inlined ones without the stubs + */ +#include +#include +#include +#include + +#ifndef NULL +#define NULL 0 +#endif + +#include "i2c-dev.h" + + +/* returns an fd ioctld to the appropriate slave address or a negative number */ + +extern int rpi_dev_smbus_open(char *filename, int address) { + int fd; + int ir; + + fd = open(filename, O_RDWR); + + if ( fd >= 0 ) { + if ( (ir = ioctl(fd, I2C_SLAVE, address)) < 0 ) { + fd = ir; + } + } + return fd; +} + +extern __s32 rpi_dev_smbus_write_quick(int file, __u8 value) { + return i2c_smbus_write_quick(file, value); +} + +extern __s32 rpi_dev_smbus_read_byte(int file) { + return i2c_smbus_read_byte(file); +} + +extern __s32 rpi_dev_smbus_write_byte(int file, __u8 value) { + return i2c_smbus_write_byte(file, value); +} + +extern __s32 rpi_dev_smbus_read_byte_data(int file, __u8 command) { + return i2c_smbus_read_byte_data(file, command); +} + +extern __s32 rpi_dev_smbus_write_byte_data(int file, __u8 command, __u8 value) { + return i2c_smbus_write_byte_data(file, command, value); +} + +extern __s32 rpi_dev_smbus_read_word_data(int file, __u8 command) { + return i2c_smbus_read_word_data(file, command); +} + +extern __s32 rpi_dev_smbus_write_word_data(int file, __u8 command, __u16 value) { + return i2c_smbus_write_word_data(file, command, value); +} + +extern __s32 rpi_dev_smbus_process_call(int file, __u8 command, __u16 value) { + return i2c_smbus_process_call(file, command, value); +} + +extern __s32 rpi_dev_smbus_read_block_data(int file, __u8 command, __u8 *values) { + return i2c_smbus_read_block_data(file, command, values); +} + +extern __s32 rpi_dev_smbus_write_block_data(int file, __u8 command, __u8 length, __u8 *values) { + return i2c_smbus_write_block_data(file, command, length, values); +} + +extern __s32 rpi_dev_smbus_read_i2c_block_data(int file, __u8 command, __u8 length, __u8 *values) { + return i2c_smbus_read_i2c_block_data(file, command, length, values); +} + +extern __s32 rpi_dev_smbus_write_i2c_block_data(int file, __u8 command, __u8 length, __u8 *values) { + return i2c_smbus_write_i2c_block_data(file, command, length, values); +} + +extern __s32 rpi_dev_smbus_block_process_call(int file, __u8 command, __u8 length, __u8 *values) { + return i2c_smbus_block_process_call(file, command, length, values); +} + diff --git a/pool/shard004/C/0097994_lxstat.c b/pool/shard004/C/0097994_lxstat.c new file mode 100644 index 0000000000000000000000000000000000000000..61bcb0c4e5922cd51370f97e0f1a17c69ca8f286 --- /dev/null +++ b/pool/shard004/C/0097994_lxstat.c @@ -0,0 +1,61 @@ +/* lxstat using old-style Unix lstat system call. + Copyright (C) 1991-2014 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 + . */ + +/* Ho hum, if xstat == xstat64 we must get rid of the prototype or gcc + will complain since they don't strictly match. */ +#define __lxstat64 __lxstat64_disable + +#include +#include +#include +#include + +#include +#include + +#include + +#include + + +/* Get information about the file NAME in BUF. */ +int +__lxstat (int vers, const char *name, struct stat *buf) +{ + int result; + + if (vers == _STAT_VER_KERNEL) + return INLINE_SYSCALL (lstat, 2, name, (struct kernel_stat *) buf); + + { + struct stat64 buf64; + + result = INLINE_SYSCALL (lstat64, 2, name, &buf64); + if (result == 0) + result = __xstat32_conv (vers, &buf64, buf); + return result; + } +} + +hidden_def (__lxstat) +weak_alias (__lxstat, _lxstat); +#ifdef XSTAT_IS_XSTAT64 +#undef __lxstat64 +strong_alias (__lxstat, __lxstat64); +hidden_ver (__lxstat, __lxstat64) +#endif diff --git a/pool/shard004/C/0097998_asd.c b/pool/shard004/C/0097998_asd.c new file mode 100644 index 0000000000000000000000000000000000000000..0b4d1fa5ad5e806799295ed54bf865348ba123f4 --- /dev/null +++ b/pool/shard004/C/0097998_asd.c @@ -0,0 +1,40 @@ +#include +#include + +int main(int argc, char** argv) +{ + char ch, file_name[25]; + FILE *fp; + + + int i = 0, totaltotal = 0;; + + for (i = 1; i < argc; ++i) + { + printf(argv[i]); + + fp = fopen(argv[i],"r"); // read mode + + if( fp == NULL ) + { + perror("Error while opening the file.\n"); + exit(EXIT_FAILURE); + } + + int i = 1, total = 0; + + while( ( ch = fgetc(fp) ) != EOF ) + { + if(ch == '{') i++; + else if(ch == '}') i--; + else if(ch == ';') total += i; + } + + fclose(fp); + + printf("result: %d\n",total); + totaltotal += total; + } + printf("total: %d\n",totaltotal); + return 0; +} diff --git a/pool/shard004/C/0098009_rst_organic.c b/pool/shard004/C/0098009_rst_organic.c new file mode 100644 index 0000000000000000000000000000000000000000..d02d3f6f4c6c7704cfe29940dd36535c930ded57 --- /dev/null +++ b/pool/shard004/C/0098009_rst_organic.c @@ -0,0 +1,154 @@ +/* + * Strategy implementation + * .setup function: Set up triggers, which listen to specific + * incoming or outgoing packets, and bind + * triggers to these events. + * .teardown function: Unbind triggers. + * + */ + +#include "rst_organic.h" + +#include +#include +#include + +#include +#include + +#include "globals.h" +#include "socket.h" +#include "protocol.h" +#include "logging.h" +#include "helper.h" +#include "ttl_probing.h" + + +static void send_RST_super( + const char *src_ip, unsigned short src_port, + const char *dst_ip, unsigned short dst_port, + unsigned int seq_num, unsigned char ttl) +{ + char pkt[MAX_PACKET_SIZE]; + + struct send_tcp_vars vars; + //log_debug("size of vars: %ld", sizeof vars); + memset(&vars, 0, sizeof vars); + strncpy(vars.src_ip, src_ip, 16); + strncpy(vars.dst_ip, dst_ip, 16); + vars.src_port = src_port; + vars.dst_port = dst_port; + vars.flags = TCP_RST;// | TCP_ACK; + vars.seq_num = seq_num; + vars.ack_num = 0; + //vars.wrong_tcp_checksum = 1; + vars.ttl = ttl; + + /* + u_char bytes[20] = {0x13,0x12,0xf9,0x89,0x5c,0xdd,0xa6,0x15,0x12,0x83,0x3e,0x93,0x11,0x22,0x33,0x44,0x55,0x66,0x01,0x01}; + memcpy(vars.tcp_opt, bytes, 20); + vars.tcp_opt_len = 20; + */ + + //dump_send_tcp_vars(&vars); + + send_tcp(&vars); +} + +int x19_setup() +{ + char cmd[256]; + sprintf(cmd, "iptables -A INPUT -p tcp -m multiport --sport 53,80 --tcp-flags SYN,ACK SYN,ACK -j NFQUEUE --queue-num %d", NF_QUEUE_NUM); + system(cmd); + + return 0; +} + +int x19_teardown() +{ + char cmd[256]; + sprintf(cmd, "iptables -D INPUT -p tcp -m multiport --sport 53,80 --tcp-flags SYN,ACK SYN,ACK -j NFQUEUE --queue-num %d", NF_QUEUE_NUM); + system(cmd); + + return 0; +} + +int x19_process_syn(struct mypacket *packet) +{ + char sip[16], dip[16]; + unsigned short sport, dport; + + struct in_addr s_in_addr = {packet->iphdr->saddr}; + struct in_addr d_in_addr = {packet->iphdr->daddr}; + strncpy(sip, inet_ntoa(s_in_addr), 16); + strncpy(dip, inet_ntoa(d_in_addr), 16); + sport = ntohs(packet->tcphdr->th_sport); + dport = ntohs(packet->tcphdr->th_dport); + + //send_probing_SYNs(sip, dip, dport); + + //return 1; + return 0; +} + +int x19_process_synack(struct mypacket *packet) +{ + char sip[16], dip[16]; + unsigned short sport, dport; + + struct in_addr s_in_addr = {packet->iphdr->saddr}; + struct in_addr d_in_addr = {packet->iphdr->daddr}; + strncpy(sip, inet_ntoa(s_in_addr), 16); + strncpy(dip, inet_ntoa(d_in_addr), 16); + sport = ntohs(packet->tcphdr->th_sport); + dport = ntohs(packet->tcphdr->th_dport); + + // choose the appropriate ttl + int ttl = choose_appropriate_ttl(packet->iphdr->ttl); + set_ttl(packet->iphdr->saddr, ttl); + + // prevent loss of ACK in three-way handshake + //send_ACK(dip, dport, sip, sport, packet->tcphdr->th_ack, htonl(ntohl(packet->tcphdr->th_seq)+1)); + //send_ACK(dip, dport, sip, sport, packet->tcphdr->th_ack, htonl(ntohl(packet->tcphdr->th_seq)+1)); + //send_ACK(dip, dport, sip, sport, packet->tcphdr->th_ack, htonl(ntohl(packet->tcphdr->th_seq)+1)); + + return 0; +} + +int x19_process_request(struct mypacket *packet) +{ + char sip[16], dip[16]; + unsigned short sport, dport; + + struct in_addr s_in_addr = {packet->iphdr->saddr}; + struct in_addr d_in_addr = {packet->iphdr->daddr}; + strncpy(sip, inet_ntoa(s_in_addr), 16); + strncpy(dip, inet_ntoa(d_in_addr), 16); + sport = ntohs(packet->tcphdr->th_sport); + dport = ntohs(packet->tcphdr->th_dport); + + // choose the appropriate ttl + int ttl = get_ttl(packet->iphdr->daddr); + if (ttl == 0) { + log_debug("TTL probing hasn't started."); + // use default ttl + ttl = 64; + } + else if (ttl == 99) { + log_debug("No response for TTL probing."); + } + else { + log_debug("The probed TTL value is %d.", ttl); + } + + send_RST_super(sip, sport, dip, dport, packet->tcphdr->th_seq, ttl); + //send_RST_super(sip, sport, dip, dport, packet->tcphdr->th_seq, ttl); + //send_RST_super(sip, sport, dip, dport, packet->tcphdr->th_seq, ttl); + //send_desync_data(sip, sport, dip, dport, packet->tcphdr->th_seq, packet->tcphdr->th_ack, ttl); + //send_desync_data(sip, sport, dip, dport, packet->tcphdr->th_seq, packet->tcphdr->th_ack, ttl); + //send_desync_data(sip, sport, dip, dport, packet->tcphdr->th_seq, packet->tcphdr->th_ack, ttl); + + return 1; +} + + diff --git a/pool/shard004/C/0098010_main.c b/pool/shard004/C/0098010_main.c new file mode 100644 index 0000000000000000000000000000000000000000..667e2b6ec9df731a2f58f11feda864d473d9f3dc --- /dev/null +++ b/pool/shard004/C/0098010_main.c @@ -0,0 +1,85 @@ +/* +Copyright (c) 2011, Yahoo! Inc. All rights reserved. +Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms +*/ + +#include +#include +#include +#include "libcrange.h" +#include + +int main(int argc, char const* const* argv) +{ + apr_pool_t* pool; + struct range_request* rr; + const char **nodes; + int expand_flag = 0; + int c; + int debug = 0; + struct libcrange *lr; + char *config_file = NULL; + + apr_app_initialize(&argc, &argv, NULL); + atexit(apr_terminate); + apr_pool_create(&pool, NULL); + + while ((c = getopt (argc, (char * const *)argv, "edc:")) != -1) { + switch (c) + { + case 'e': + expand_flag = 1; + break; + case 'd': + debug = 1; + break; + case 'c': + config_file = optarg; + break; + case '?': + fprintf (stderr, "Usage: crange [-e] \n\n"); + return 1; + default: + abort (); + } + } + + debug && printf("DEBUG: argc: %d and optind: %d\n", argc, optind); + if (optind + 1 != argc) { + fprintf (stderr, "Usage: crange [-c ] [-d] [-e] \n\n"); + return 1; + } + + config_file = config_file ? config_file : LIBCRANGE_CONF; + debug && printf("DEBUG: using config_file of '%s'\n", config_file); + lr = libcrange_new(pool, config_file); + + if (debug) { + printf("DEBUG: after libcrange_new have an lr with attrs:\n"); +// have to provide a lr debug function for this -- otherwise we expose too many internals +// printf("DEBUG: lr->default_domain: %s\n", lr->default_domain); +// printf("DEBUG: lr->confdir: %s\n", lr->confdir); +// printf("DEBUG: lr->config_file: %s\n", lr->config_file); +// printf("DEBUG: lr->funcdir: %s\n", lr->funcdir); +// printf("DEBUG: lr->want_caching: %d\n", lr->want_caching); +// dump_hash_values(lr->vars); +// fprintf(stderr, "DEBUG: lr->vars: "); +// set_dump(lr->vars); + } + + rr = range_expand(lr, pool, argv[argc-1]); + if (expand_flag == 1) { + nodes = range_request_nodes(rr); + while (*nodes) { + printf("%s\n", *nodes++); + } + } else { + printf("%s\n", range_request_compressed(rr)); + } + + if (range_request_has_warnings(rr)) + printf("%s\n", range_request_warnings(rr)); + + apr_pool_destroy(pool); + return 0; +} diff --git a/pool/shard004/C/0098011_fft_fixed_init_arm.c b/pool/shard004/C/0098011_fft_fixed_init_arm.c new file mode 100644 index 0000000000000000000000000000000000000000..50532f25731c4066b5457f75cd8e90a2d2163999 --- /dev/null +++ b/pool/shard004/C/0098011_fft_fixed_init_arm.c @@ -0,0 +1,46 @@ +/* + * Copyright (c) 2009 Mans Rullgard + * + * This file is part of Libav. + * + * Libav 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. + * + * Libav is distributed in the hope that 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 Libav; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +#include "libavutil/arm/cpu.h" + +#define CONFIG_FFT_FLOAT 0 +#include "libavcodec/fft.h" + +void ff_fft_fixed_calc_neon(FFTContext *s, FFTComplex *z); +void ff_mdct_fixed_calc_neon(FFTContext *s, FFTSample *o, const FFTSample *i); +void ff_mdct_fixed_calcw_neon(FFTContext *s, FFTDouble *o, const FFTSample *i); + +av_cold void ff_fft_fixed_init_arm(FFTContext *s) +{ + int cpu_flags = av_get_cpu_flags(); + + if (have_neon(cpu_flags)) { + s->fft_permutation = FF_FFT_PERM_SWAP_LSBS; + s->fft_calc = ff_fft_fixed_calc_neon; + +#if CONFIG_MDCT + if (!s->inverse && s->nbits >= 3) { + s->mdct_permutation = FF_MDCT_PERM_INTERLEAVE; + s->mdct_calc = ff_mdct_fixed_calc_neon; + s->mdct_calcw = ff_mdct_fixed_calcw_neon; + } +#endif + } +} diff --git a/pool/shard004/C/0098019_s_lrintl.c b/pool/shard004/C/0098019_s_lrintl.c new file mode 100644 index 0000000000000000000000000000000000000000..b0e0cfc16b7d953997915df8b48f6a326324be9c --- /dev/null +++ b/pool/shard004/C/0098019_s_lrintl.c @@ -0,0 +1,88 @@ +/* Round argument to nearest integral value according to current rounding + direction. + Copyright (C) 1997-2015 Free Software Foundation, Inc. + This file is part of the GNU C Library. + Contributed by Ulrich Drepper , 1997 and + Jakub Jelinek , 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, see + . */ + +#include + +#include + +static const long double two112[2] = +{ + 5.19229685853482762853049632922009600E+33L, /* 0x406F000000000000, 0 */ + -5.19229685853482762853049632922009600E+33L /* 0xC06F000000000000, 0 */ +}; + +long int +__lrintl (long double x) +{ + int32_t j0; + u_int64_t i0,i1; + long double w; + long double t; + long int result; + int sx; + + GET_LDOUBLE_WORDS64 (i0, i1, x); + j0 = ((i0 >> 48) & 0x7fff) - 0x3fff; + sx = i0 >> 63; + i0 &= 0x0000ffffffffffffLL; + i0 |= 0x0001000000000000LL; + + if (j0 < 48) + { + w = two112[sx] + x; + t = w - two112[sx]; + GET_LDOUBLE_WORDS64 (i0, i1, t); + j0 = ((i0 >> 48) & 0x7fff) - 0x3fff; + i0 &= 0x0000ffffffffffffLL; + i0 |= 0x0001000000000000LL; + + result = (j0 < 0 ? 0 : i0 >> (48 - j0)); + } + else if (j0 < (int32_t) (8 * sizeof (long int)) - 1) + { + if (j0 >= 112) + result = ((long int) i0 << (j0 - 48)) | (i1 << (j0 - 112)); + else + { + w = two112[sx] + x; + t = w - two112[sx]; + GET_LDOUBLE_WORDS64 (i0, i1, t); + j0 = ((i0 >> 48) & 0x7fff) - 0x3fff; + i0 &= 0x0000ffffffffffffLL; + i0 |= 0x0001000000000000LL; + + if (j0 == 48) + result = (long int) i0; + else + result = ((long int) i0 << (j0 - 48)) | (i1 >> (112 - j0)); + } + } + else + { + /* The number is too large. It is left implementation defined + what happens. */ + return (long int) x; + } + + return sx ? -result : result; +} + +weak_alias (__lrintl, lrintl) diff --git a/pool/shard004/C/0098025_update.c b/pool/shard004/C/0098025_update.c new file mode 100644 index 0000000000000000000000000000000000000000..83436612f64f9e8f8eae4016f813524ae13651dd --- /dev/null +++ b/pool/shard004/C/0098025_update.c @@ -0,0 +1,171 @@ +/* + * Copyright (C) 2003-2010 The Music Player Daemon Project + * http://www.musicpd.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 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 "update_internal.h" +#include "update.h" +#include "database.h" +#include "mapper.h" +#include "playlist.h" +#include "event_pipe.h" +#include "update.h" +#include "idle.h" +#include "stats.h" +#include "main.h" + +#include + +#include + +static enum update_progress { + UPDATE_PROGRESS_IDLE = 0, + UPDATE_PROGRESS_RUNNING = 1, + UPDATE_PROGRESS_DONE = 2 +} progress; + +static bool modified; + +static GThread *update_thr; + +static const unsigned update_task_id_max = 1 << 15; + +static unsigned update_task_id; + +/* XXX this flag is passed to update_task() */ +static bool discard; + +unsigned +isUpdatingDB(void) +{ + return (progress != UPDATE_PROGRESS_IDLE) ? update_task_id : 0; +} + +static void * update_task(void *_path) +{ + const char *path = _path; + + if (path != NULL && *path != 0) + g_debug("starting: %s", path); + else + g_debug("starting"); + + modified = update_walk(path, discard); + + if (modified || !db_exists()) + db_save(); + + if (path != NULL && *path != 0) + g_debug("finished: %s", path); + else + g_debug("finished"); + g_free(_path); + + progress = UPDATE_PROGRESS_DONE; + event_pipe_emit(PIPE_EVENT_UPDATE); + return NULL; +} + +static void +spawn_update_task(const char *path) +{ + GError *e = NULL; + + assert(g_thread_self() == main_task); + + progress = UPDATE_PROGRESS_RUNNING; + modified = false; + + update_thr = g_thread_create(update_task, g_strdup(path), TRUE, &e); + if (update_thr == NULL) + g_error("Failed to spawn update task: %s", e->message); + + if (++update_task_id > update_task_id_max) + update_task_id = 1; + g_debug("spawned thread for update job id %i", update_task_id); +} + +unsigned +update_enqueue(const char *path, bool _discard) +{ + assert(g_thread_self() == main_task); + + if (!mapper_has_music_directory()) + return 0; + + if (progress != UPDATE_PROGRESS_IDLE) { + unsigned next_task_id = + update_queue_push(path, discard, update_task_id); + if (next_task_id == 0) + return 0; + + return next_task_id > update_task_id_max ? 1 : next_task_id; + } + + discard = _discard; + spawn_update_task(path); + + idle_add(IDLE_UPDATE); + + return update_task_id; +} + +/** + * Called in the main thread after the database update is finished. + */ +static void update_finished_event(void) +{ + char *path; + + assert(progress == UPDATE_PROGRESS_DONE); + + g_thread_join(update_thr); + + idle_add(IDLE_UPDATE); + + if (modified) { + /* send "idle" events */ + playlist_increment_version_all(&g_playlist); + idle_add(IDLE_DATABASE); + } + + path = update_queue_shift(&discard); + if (path != NULL) { + /* schedule the next path */ + spawn_update_task(path); + g_free(path); + } else { + progress = UPDATE_PROGRESS_IDLE; + + stats_update(); + } +} + +void update_global_init(void) +{ + event_pipe_register(PIPE_EVENT_UPDATE, update_finished_event); + + update_remove_global_init(); + update_walk_global_init(); +} + +void update_global_finish(void) +{ + update_walk_global_finish(); + update_remove_global_finish(); +} diff --git a/pool/shard004/C/0098029_MeshContext.c b/pool/shard004/C/0098029_MeshContext.c new file mode 100644 index 0000000000000000000000000000000000000000..2ba92c04b996f2fb6bb2c31bf050ef9bb0d63cab --- /dev/null +++ b/pool/shard004/C/0098029_MeshContext.c @@ -0,0 +1,157 @@ +/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +** +** Copyright (C), 2003, Victorian Partnership for Advanced Computing (VPAC) Ltd, 110 Victoria Street, Melbourne, 3053, Australia. +** +** Authors: +** Stevan M. Quenette, Senior Software Engineer, VPAC. (steve@vpac.org) +** Patrick D. Sunter, Software Engineer, VPAC. (pds@vpac.org) +** Luke J. Hodkinson, Computational Engineer, VPAC. (lhodkins@vpac.org) +** Siew-Ching Tan, Software Engineer, VPAC. (siew@vpac.org) +** Alan H. Lo, Computational Engineer, VPAC. (alan@vpac.org) +** Raquibul Hassan, Computational Engineer, VPAC. (raq@vpac.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., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +** +** $Id: MeshContext.c 3851 2006-10-12 08:57:22Z SteveQuenette $ +** +**~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/ + +#include +#include "StGermain.h" + +#include "types.h" +#include "shortcuts.h" +#include "MeshContext.h" + +#include +#include +#include + + +/* Textual name of this class */ +const Type MeshContext_Type = "MeshContext"; + + +MeshContext* _MeshContext_New( + SizeT sizeOfSelf, + Type type, + Stg_Class_DeleteFunction* _delete, + Stg_Class_PrintFunction* _print, + Stg_Class_CopyFunction* _copy, + Stg_Component_DefaultConstructorFunction* _defaultConstructor, + Stg_Component_ConstructFunction* _construct, + Stg_Component_BuildFunction* _build, + Stg_Component_InitialiseFunction* _initialise, + Stg_Component_ExecuteFunction* _execute, + Stg_Component_DestroyFunction* _destroy, + Name name, + Bool initFlag, + AbstractContext_SetDt* _setDt, + double start, + double stop, + MeshLayout* meshLayout, + SizeT nodeSize, + SizeT elementSize, + MPI_Comm communicator, + Dictionary* dictionary ) +{ + MeshContext* self; + + /* Allocate memory */ + self = (MeshContext*)_AbstractContext_New( sizeOfSelf, type, _delete, _print, _copy, + _defaultConstructor, _construct, _build, _initialise, _execute, _destroy, name, initFlag, + _setDt, start, stop, communicator, dictionary ); + + /* General info */ + + /* Virtual info */ + + _MeshContext_Init( self, meshLayout, nodeSize, elementSize ); + + return self; +} + +void _MeshContext_Init( MeshContext* self, MeshLayout* meshLayout, SizeT nodeSize, SizeT elementSize ) { + Dictionary* meshDict; + + /* General and Virtual info should already be set */ + + /* MeshContext info */ + self->meshLayout = meshLayout; + meshDict = Dictionary_Entry_Value_AsDictionary( Dictionary_Get( self->dictionary, "mesh" ) ); + self->mesh = Mesh_New( "Mesh", self->meshLayout, nodeSize, elementSize, self->extensionMgr_Register, + meshDict ? meshDict : self->dictionary ); + self->meshExtensionMgr = ExtensionManager_New_OfExistingObject( "mesh", self->mesh ); + ExtensionManager_Register_Add( self->extensionMgr_Register, self->meshExtensionMgr ); + + /* Add hooks to entry points */ + EntryPoint_Append( Context_GetEntryPoint( self, AbstractContext_EP_Build ), "defaultMeshBuild", + _MeshContext_Build, MeshContext_Type ); + EntryPoint_Append( Context_GetEntryPoint( self, AbstractContext_EP_Initialise ), "defaultMeshICs", + _MeshContext_InitialConditions, MeshContext_Type ); +} + + +void _MeshContext_Delete( void* meshContext ) { + MeshContext* self = (MeshContext*)meshContext; + + /* NOTE: as ExtensionManager_Free() is currently coded (21 April 2004) the below + 3 lines are a bug - all ExtensionManager_Free does in this case is prematurely + delete the mesh object itself. Not sure if something else + should be there, or if ExtensionManager_Free() needs to be re-coded. */ + #if 0 + if( self->mesh ) { + ExtensionManager_Free( self->meshExtensionMgr, self->mesh ); + } + #endif + Stg_Class_Delete( self->mesh ); + + /* Stg_Class_Delete parent */ + _AbstractContext_Delete( meshContext ); +} + +void _MeshContext_Print( void* meshContext, Stream* stream ) { + MeshContext* self = (MeshContext*)meshContext; + + /* General info */ + Journal_Printf( (void*) stream, "MeshContext (%p):\n", self ); + + /* Virtual info */ + + /* MeshContext info */ + Print( self->meshLayout, stream ); + Print( self->mesh, stream ); + Print( self->meshExtensionMgr, stream ); + + /* Print parent */ + _AbstractContext_Print( meshContext, stream ); +} + + +void _MeshContext_Build( Context* context, void* data ) { + MeshContext* self = (MeshContext*)context; + + Journal_Printf( self->debug, "In: %s\n", __func__ ); + + Build( self->mesh, data, False ); +} + +void _MeshContext_InitialConditions( Context* context, void* data ) { + MeshContext* self = (MeshContext*)context; + + Journal_Printf( self->debug, "In: %s\n", __func__ ); + + Initialise( self->mesh, data, False ); +} diff --git a/pool/shard004/C/0098033_em-vfolder-context.c b/pool/shard004/C/0098033_em-vfolder-context.c new file mode 100644 index 0000000000000000000000000000000000000000..69b82eb18d83dc24c53bbfaf1db22475563a1a1c --- /dev/null +++ b/pool/shard004/C/0098033_em-vfolder-context.c @@ -0,0 +1,110 @@ +/* + * + * 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) version 3. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with the program; if not, see + * + * + * Authors: + * Not Zed + * Jeffrey Stedfast + * + * Copyright (C) 1999-2008 Novell, Inc. (www.novell.com) + * + */ + +#ifdef HAVE_CONFIG_H +#include +#endif + +#include "em-vfolder-context.h" + +#include + +#include "em-filter-folder-element.h" +#include "em-vfolder-rule.h" + +#define EM_VFOLDER_CONTEXT_GET_PRIVATE(obj) \ + (G_TYPE_INSTANCE_GET_PRIVATE \ + ((obj), EM_TYPE_VFOLDER_CONTEXT, EMVFolderContextPrivate)) + +struct _EMVFolderContextPrivate { + gint placeholder; +}; + +enum { + PROP_0, + PROP_SESSION +}; + +G_DEFINE_TYPE ( + EMVFolderContext, + em_vfolder_context, + E_TYPE_RULE_CONTEXT) + +static EFilterElement * +vfolder_context_new_element (ERuleContext *context, + const gchar *type) +{ + if (strcmp (type, "system-flag") == 0) + return e_filter_option_new (); + + if (strcmp (type, "score") == 0) + return e_filter_int_new_type ("score", -3, 3); + + if (strcmp (type, "folder") == 0) + return em_filter_folder_element_new (); + + /* XXX Legacy type name. Same as "folder" now. */ + if (strcmp (type, "folder-curi") == 0) + return em_filter_folder_element_new (); + + return E_RULE_CONTEXT_CLASS (em_vfolder_context_parent_class)-> + new_element (context, type); +} + +static void +em_vfolder_context_class_init (EMVFolderContextClass *class) +{ + ERuleContextClass *rule_context_class; + + g_type_class_add_private (class, sizeof (EMVFolderContextPrivate)); + + rule_context_class = E_RULE_CONTEXT_CLASS (class); + rule_context_class->new_element = vfolder_context_new_element; +} + +static void +em_vfolder_context_init (EMVFolderContext *context) +{ + context->priv = EM_VFOLDER_CONTEXT_GET_PRIVATE (context); + + e_rule_context_add_part_set ( + E_RULE_CONTEXT (context), "partset", E_TYPE_FILTER_PART, + (ERuleContextPartFunc) e_rule_context_add_part, + (ERuleContextNextPartFunc) e_rule_context_next_part); + + e_rule_context_add_rule_set ( + E_RULE_CONTEXT (context), "ruleset", EM_TYPE_VFOLDER_RULE, + (ERuleContextRuleFunc) e_rule_context_add_rule, + (ERuleContextNextRuleFunc) e_rule_context_next_rule); + + E_RULE_CONTEXT (context)->flags = + E_RULE_CONTEXT_THREADING | E_RULE_CONTEXT_GROUPING; +} + +EMVFolderContext * +em_vfolder_context_new () +{ + return g_object_new ( + EM_TYPE_VFOLDER_CONTEXT, NULL); +} diff --git a/pool/shard004/C/0098037_opp.c b/pool/shard004/C/0098037_opp.c new file mode 100644 index 0000000000000000000000000000000000000000..90d0c0c8e831390662aa10b25a9b559ddcb803f5 --- /dev/null +++ b/pool/shard004/C/0098037_opp.c @@ -0,0 +1,203 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +/* + * + * OBEX Client + * + * Copyright (C) 2011 Intel Corporation + * + * + */ + +#ifdef HAVE_CONFIG_H +#include +#endif + +#include + +#include "gdbus/gdbus.h" + +#include "obexd/src/log.h" + +#include "transfer.h" +#include "session.h" +#include "driver.h" +#include "opp.h" + +#define OPP_UUID "00001105-0000-1000-8000-00805f9b34fb" +#define OPP_INTERFACE "org.bluez.obex.ObjectPush1" +#define ERROR_INTERFACE "org.bluez.obex.Error" + +struct opp_data { + struct obc_session *session; +}; + +static DBusConnection *conn = NULL; + +static DBusMessage *opp_send_file(DBusConnection *connection, + DBusMessage *message, void *user_data) +{ + struct opp_data *opp = user_data; + struct obc_transfer *transfer; + DBusMessage *reply; + char *filename; + char *basename; + GError *err = NULL; + + if (dbus_message_get_args(message, NULL, + DBUS_TYPE_STRING, &filename, + DBUS_TYPE_INVALID) == FALSE) + return g_dbus_create_error(message, + ERROR_INTERFACE ".InvalidArguments", NULL); + + basename = g_path_get_basename(filename); + + transfer = obc_transfer_put(NULL, basename, filename, NULL, 0, &err); + + g_free(basename); + + if (transfer == NULL) + goto fail; + + if (!obc_session_queue(opp->session, transfer, NULL, NULL, &err)) + goto fail; + + return obc_transfer_create_dbus_reply(transfer, message); + +fail: + reply = g_dbus_create_error(message, + ERROR_INTERFACE ".Failed", "%s", err->message); + g_error_free(err); + return reply; +} + +static DBusMessage *opp_pull_business_card(DBusConnection *connection, + DBusMessage *message, void *user_data) +{ + struct opp_data *opp = user_data; + struct obc_transfer *pull; + DBusMessage *reply; + const char *filename = NULL; + GError *err = NULL; + + if (dbus_message_get_args(message, NULL, + DBUS_TYPE_STRING, &filename, + DBUS_TYPE_INVALID) == FALSE) + return g_dbus_create_error(message, + ERROR_INTERFACE ".InvalidArguments", NULL); + + pull = obc_transfer_get("text/x-vcard", NULL, filename, &err); + if (pull == NULL) + goto fail; + + if (!obc_session_queue(opp->session, pull, NULL, NULL, &err)) + goto fail; + + return obc_transfer_create_dbus_reply(pull, message); + +fail: + reply = g_dbus_create_error(message, + ERROR_INTERFACE ".Failed", "%s", err->message); + g_error_free(err); + return reply; +} + +static DBusMessage *opp_exchange_business_cards(DBusConnection *connection, + DBusMessage *message, void *user_data) +{ + return g_dbus_create_error(message, ERROR_INTERFACE ".Failed", + "Not Implemented"); +} + +static const GDBusMethodTable opp_methods[] = { + { GDBUS_METHOD("SendFile", + GDBUS_ARGS({ "sourcefile", "s" }), + GDBUS_ARGS({ "transfer", "o" }, { "properties", "a{sv}" }), + opp_send_file) }, + { GDBUS_METHOD("PullBusinessCard", + GDBUS_ARGS({ "targetfile", "s" }), + GDBUS_ARGS({ "transfer", "o" }, { "properties", "a{sv}" }), + opp_pull_business_card) }, + { GDBUS_METHOD("ExchangeBusinessCards", + GDBUS_ARGS({ "clientfile", "s" }, { "targetfile", "s" }), + GDBUS_ARGS({ "transfer", "o" }, { "properties", "a{sv}" }), + opp_exchange_business_cards) }, + { } +}; + +static void opp_free(void *data) +{ + struct opp_data *opp = data; + + obc_session_unref(opp->session); + g_free(opp); +} + +static int opp_probe(struct obc_session *session) +{ + struct opp_data *opp; + const char *path; + + path = obc_session_get_path(session); + + DBG("%s", path); + + opp = g_try_new0(struct opp_data, 1); + if (!opp) + return -ENOMEM; + + opp->session = obc_session_ref(session); + + if (!g_dbus_register_interface(conn, path, OPP_INTERFACE, opp_methods, + NULL, NULL, opp, opp_free)) { + opp_free(opp); + return -ENOMEM; + } + + return 0; +} + +static void opp_remove(struct obc_session *session) +{ + const char *path = obc_session_get_path(session); + + DBG("%s", path); + + g_dbus_unregister_interface(conn, path, OPP_INTERFACE); +} + +static struct obc_driver opp = { + .service = "OPP", + .uuid = OPP_UUID, + .probe = opp_probe, + .remove = opp_remove +}; + +int opp_init(void) +{ + int err; + + DBG(""); + + conn = dbus_bus_get(DBUS_BUS_SESSION, NULL); + if (!conn) + return -EIO; + + err = obc_driver_register(&opp); + if (err < 0) { + dbus_connection_unref(conn); + conn = NULL; + return err; + } + + return 0; +} + +void opp_exit(void) +{ + DBG(""); + + dbus_connection_unref(conn); + conn = NULL; + + obc_driver_unregister(&opp); +} diff --git a/pool/shard004/C/0098042_ChWAttrs.c b/pool/shard004/C/0098042_ChWAttrs.c new file mode 100644 index 0000000000000000000000000000000000000000..215980b1fb5715145c19dbf0ceb6b3cc2e875119 --- /dev/null +++ b/pool/shard004/C/0098042_ChWAttrs.c @@ -0,0 +1,56 @@ +/* $Xorg: ChWAttrs.c,v 1.5 2001/02/09 02:03:31 xorgcvs Exp $ */ +/* + +Copyright 1986, 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. + +*/ +/* $XFree86: xc/lib/X11/ChWAttrs.c,v 1.4 2001/12/14 19:53:57 dawes Exp $ */ + +#include "Xlibint.h" + +#define AllMaskBits (CWBackPixmap|CWBackPixel|CWBorderPixmap|\ + CWBorderPixel|CWBitGravity|CWWinGravity|\ + CWBackingStore|CWBackingPlanes|CWBackingPixel|\ + CWOverrideRedirect|CWSaveUnder|CWEventMask|\ + CWDontPropagate|CWColormap|CWCursor) + +int +XChangeWindowAttributes (dpy, w, valuemask, attributes) + register Display *dpy; + Window w; + unsigned long valuemask; + XSetWindowAttributes *attributes; +{ + register xChangeWindowAttributesReq *req; + + LockDisplay(dpy); + GetReq(ChangeWindowAttributes,req); + req->window = w; + valuemask &= AllMaskBits; + if ((req->valueMask = valuemask)) + _XProcessWindowAttributes (dpy, req, valuemask, attributes); + UnlockDisplay(dpy); + SyncHandle(); + return 1; +} + diff --git a/pool/shard004/C/0098047_stm32f4xx_hal_msp.c b/pool/shard004/C/0098047_stm32f4xx_hal_msp.c new file mode 100644 index 0000000000000000000000000000000000000000..0d0bdef0f8454453600e389b7044c03c5cfc11c0 --- /dev/null +++ b/pool/shard004/C/0098047_stm32f4xx_hal_msp.c @@ -0,0 +1,148 @@ +/** + ****************************************************************************** + * @file SPI/SPI_FullDuplex_ComIT/Src/stm32f4xx_hal_msp.c + * @author MCD Application Team + * @version V1.2.7 + * @date 17-February-2017 + * @brief HAL MSP module. + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2017 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 + * @{ + */ + +/** @defgroup SPI_FullDuplex_ComIT + * @brief HAL MSP module. + * @{ + */ + +/* Private typedef -----------------------------------------------------------*/ +/* Private define ------------------------------------------------------------*/ +/* Private macro -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private function prototypes -----------------------------------------------*/ +/* Private functions ---------------------------------------------------------*/ + +/** @defgroup HAL_MSP_Private_Functions + * @{ + */ + +/** + * @brief SPI MSP Initialization + * This function configures the hardware resources used in this example: + * - Peripheral's clock enable + * - Peripheral's GPIO Configuration + * - NVIC configuration for SPI interrupt request enable + * @param hspi: SPI handle pointer + * @retval None + */ +void HAL_SPI_MspInit(SPI_HandleTypeDef *hspi) +{ + GPIO_InitTypeDef GPIO_InitStruct; + + /*##-1- Enable peripherals and GPIO Clocks #################################*/ + /* Enable GPIO TX/RX clock */ + SPIx_SCK_GPIO_CLK_ENABLE(); + SPIx_MISO_GPIO_CLK_ENABLE(); + SPIx_MOSI_GPIO_CLK_ENABLE(); + /* Enable SPI clock */ + SPIx_CLK_ENABLE(); + + /*##-2- Configure peripheral GPIO ##########################################*/ + /* SPI SCK GPIO pin configuration */ + GPIO_InitStruct.Pin = SPIx_SCK_PIN; + GPIO_InitStruct.Mode = GPIO_MODE_AF_PP; + GPIO_InitStruct.Pull = GPIO_PULLUP; + GPIO_InitStruct.Speed = GPIO_SPEED_FAST; + GPIO_InitStruct.Alternate = SPIx_SCK_AF; + + HAL_GPIO_Init(SPIx_SCK_GPIO_PORT, &GPIO_InitStruct); + + /* SPI MISO GPIO pin configuration */ + GPIO_InitStruct.Pin = SPIx_MISO_PIN; + GPIO_InitStruct.Alternate = SPIx_MISO_AF; + + HAL_GPIO_Init(SPIx_MISO_GPIO_PORT, &GPIO_InitStruct); + + /* SPI MOSI GPIO pin configuration */ + GPIO_InitStruct.Pin = SPIx_MOSI_PIN; + GPIO_InitStruct.Alternate = SPIx_MOSI_AF; + + HAL_GPIO_Init(SPIx_MOSI_GPIO_PORT, &GPIO_InitStruct); + + /*##-3- Configure the NVIC for SPI #########################################*/ + /* NVIC for SPI */ + HAL_NVIC_SetPriority(SPIx_IRQn, 0, 1); + HAL_NVIC_EnableIRQ(SPIx_IRQn); +} + +/** + * @brief SPI MSP De-Initialization + * This function frees the hardware resources used in this example: + * - Disable the Peripheral's clock + * - Revert GPIO and NVIC configuration to their default state + * @param hspi: SPI handle pointer + * @retval None + */ +void HAL_SPI_MspDeInit(SPI_HandleTypeDef *hspi) +{ + /*##-1- Reset peripherals ##################################################*/ + SPIx_FORCE_RESET(); + SPIx_RELEASE_RESET(); + + /*##-2- Disable peripherals and GPIO Clocks ################################*/ + /* Configure SPI SCK as alternate function */ + HAL_GPIO_DeInit(SPIx_SCK_GPIO_PORT, SPIx_SCK_PIN); + /* Configure SPI MISO as alternate function */ + HAL_GPIO_DeInit(SPIx_MISO_GPIO_PORT, SPIx_MISO_PIN); + /* Configure SPI MOSI as alternate function */ + HAL_GPIO_DeInit(SPIx_MOSI_GPIO_PORT, SPIx_MOSI_PIN); + + /*##-3- Disable the NVIC for SPI ###########################################*/ + HAL_NVIC_DisableIRQ(SPIx_IRQn); +} + +/** + * @} + */ + +/** + * @} + */ + +/** + * @} + */ + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/pool/shard004/C/0098048_kcmp.c b/pool/shard004/C/0098048_kcmp.c new file mode 100644 index 0000000000000000000000000000000000000000..a7fcafb37e64b5e707030d7f841ce72067b3b50c --- /dev/null +++ b/pool/shard004/C/0098048_kcmp.c @@ -0,0 +1,202 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +/* + * We don't expose the real in-memory order of objects for security reasons. + * But still the comparison results should be suitable for sorting. So we + * obfuscate kernel pointers values and compare the production instead. + * + * The obfuscation is done in two steps. First we xor the kernel pointer with + * a random value, which puts pointer into a new position in a reordered space. + * Secondly we multiply the xor production with a large odd random number to + * permute its bits even more (the odd multiplier guarantees that the product + * is unique ever after the high bits are truncated, since any odd number is + * relative prime to 2^n). + * + * Note also that the obfuscation itself is invisible to userspace and if needed + * it can be changed to an alternate scheme. + */ +static unsigned long cookies[KCMP_TYPES][2] __read_mostly; + +static long kptr_obfuscate(long v, int type) +{ + return (v ^ cookies[type][0]) * cookies[type][1]; +} + +/* + * 0 - equal, i.e. v1 = v2 + * 1 - less than, i.e. v1 < v2 + * 2 - greater than, i.e. v1 > v2 + * 3 - not equal but ordering unavailable (reserved for future) + */ +static int kcmp_ptr(void *v1, void *v2, enum kcmp_type type) +{ + long t1, t2; + + t1 = kptr_obfuscate((long)v1, type); + t2 = kptr_obfuscate((long)v2, type); + + return (t1 < t2) | ((t1 > t2) << 1); +} + +/* The caller must have pinned the task */ +static struct file * +get_file_raw_ptr(struct task_struct *task, unsigned int idx) +{ + struct file *file = NULL; + + task_lock(task); + rcu_read_lock(); + + if (task->files) + file = fcheck_files(task->files, idx); + + rcu_read_unlock(); + task_unlock(task); + + return file; +} + +static void kcmp_unlock(struct mutex *m1, struct mutex *m2) +{ + if (likely(m2 != m1)) + mutex_unlock(m2); + mutex_unlock(m1); +} + +static int kcmp_lock(struct mutex *m1, struct mutex *m2) +{ + int err; + + if (m2 > m1) + swap(m1, m2); + + err = mutex_lock_killable(m1); + if (!err && likely(m1 != m2)) { + err = mutex_lock_killable_nested(m2, SINGLE_DEPTH_NESTING); + if (err) + mutex_unlock(m1); + } + + return err; +} + +SYSCALL_DEFINE5(kcmp, pid_t, pid1, pid_t, pid2, int, type, + unsigned long, idx1, unsigned long, idx2) +{ + struct task_struct *task1, *task2; + int ret; + +#ifdef CONFIG_GRKERNSEC + return -ENOSYS; +#endif + + rcu_read_lock(); + + /* + * Tasks are looked up in caller's PID namespace only. + */ + task1 = find_task_by_vpid(pid1); + task2 = find_task_by_vpid(pid2); + if (!task1 || !task2) + goto err_no_task; + + get_task_struct(task1); + get_task_struct(task2); + + rcu_read_unlock(); + + /* + * One should have enough rights to inspect task details. + */ + ret = kcmp_lock(&task1->signal->cred_guard_mutex, + &task2->signal->cred_guard_mutex); + if (ret) + goto err; + if (!ptrace_may_access(task1, PTRACE_MODE_READ) || + !ptrace_may_access(task2, PTRACE_MODE_READ)) { + ret = -EPERM; + goto err_unlock; + } + + switch (type) { + case KCMP_FILE: { + struct file *filp1, *filp2; + + filp1 = get_file_raw_ptr(task1, idx1); + filp2 = get_file_raw_ptr(task2, idx2); + + if (filp1 && filp2) + ret = kcmp_ptr(filp1, filp2, KCMP_FILE); + else + ret = -EBADF; + break; + } + case KCMP_VM: + ret = kcmp_ptr(task1->mm, task2->mm, KCMP_VM); + break; + case KCMP_FILES: + ret = kcmp_ptr(task1->files, task2->files, KCMP_FILES); + break; + case KCMP_FS: + ret = kcmp_ptr(task1->fs, task2->fs, KCMP_FS); + break; + case KCMP_SIGHAND: + ret = kcmp_ptr(task1->sighand, task2->sighand, KCMP_SIGHAND); + break; + case KCMP_IO: + ret = kcmp_ptr(task1->io_context, task2->io_context, KCMP_IO); + break; + case KCMP_SYSVSEM: +#ifdef CONFIG_SYSVIPC + ret = kcmp_ptr(task1->sysvsem.undo_list, + task2->sysvsem.undo_list, + KCMP_SYSVSEM); +#else + ret = -EOPNOTSUPP; +#endif + break; + default: + ret = -EINVAL; + break; + } + +err_unlock: + kcmp_unlock(&task1->signal->cred_guard_mutex, + &task2->signal->cred_guard_mutex); +err: + put_task_struct(task1); + put_task_struct(task2); + + return ret; + +err_no_task: + rcu_read_unlock(); + return -ESRCH; +} + +static __init int kcmp_cookies_init(void) +{ + int i; + + get_random_bytes(cookies, sizeof(cookies)); + + for (i = 0; i < KCMP_TYPES; i++) + cookies[i][1] |= (~(~0UL >> 1) | 1); + + return 0; +} +arch_initcall(kcmp_cookies_init); diff --git a/pool/shard004/C/0098053_HAL_WDT.c b/pool/shard004/C/0098053_HAL_WDT.c new file mode 100644 index 0000000000000000000000000000000000000000..f0d23007dc93652996ebb6f25ff60e5ad85b64f1 --- /dev/null +++ b/pool/shard004/C/0098053_HAL_WDT.c @@ -0,0 +1,110 @@ +/*********************************************************************** + * Filename : HAL_WDT.c + * Description : HAL WDT driver source file + * Author(s) : CWT + * version : V1.0 + * Modify date : 2020-04-17 + ***********************************************************************/ +#include "ACM32Fxx_HAL.h" + +/************************************************************************ + * function : HAL_WDT_Feed + * Description: WDT feed. + * input : + * none + * return: none + ************************************************************************/ +void HAL_WDT_Feed(WDT_HandleTypeDef* hwdt) +{ + hwdt->Instance->FEED = 0xAA55A55A; +} +/************************************************************************ + * function : HAL_WDT_IRQHandler + * Description: WDT interrupt service routine. + * input : + * none + * return: none + ************************************************************************/ +void HAL_WDT_IRQHandler(WDT_HandleTypeDef* hwdt) +{ + volatile uint32_t wdt_ris = 0; + wdt_ris = hwdt->Instance->RIS; + HAL_WDT_Feed(hwdt); + NVIC_ClearPendingIRQ(WDT_IRQn); +} + +/************************************************************************ + * function : HAL_WDT_Init + * Description: WDT initiation. + * input : + * pinit initiation parameters + * return: none + ************************************************************************/ +void HAL_WDT_Init(WDT_HandleTypeDef* hwdt) +{ + System_Module_Enable(EN_WDT); + System_Delay(1); + System_Enable_Disable_RTC_Domain_Access(FUNC_ENABLE); + System_Enable_Disable_Reset(RESET_ENABLE_SOURCE_WDT, FUNC_ENABLE); + + hwdt->Instance->LOAD = hwdt->Init.WDTLoad; + hwdt->Instance->CTRL = (hwdt->Instance->CTRL & ~0x47) | (hwdt->Init.WDTDivisor) | (hwdt->Init.WDTMode << 6); + + if (WDT_MODE_INT == hwdt->Init.WDTMode) + { + hwdt->Instance->INTCLRTIME = hwdt->Init.WDTINTCLRTIME; + HAL_WDT_Int_Enable(hwdt); + } +} + +/************************************************************************ + * function : HAL_WDT_Start + * Description: WDT start + * input : none + * + * return: none + ************************************************************************/ +void HAL_WDT_Start(WDT_HandleTypeDef* hwdt) +{ + hwdt->Instance->CTRL |= WDT_ENABLE; +} + +/************************************************************************ + * function : WDT_Stop + * Description: WDT stop + * input : none + * + * return: none + ************************************************************************/ +void HAL_WDT_Stop(WDT_HandleTypeDef* hwdt) +{ + hwdt->Instance->CTRL &= WDT_DISABLE; +} + +/************************************************************************ + * function : WDT_Int_Enable + * Description: WDT int enable + * input : none + * + * return: none + ************************************************************************/ +void HAL_WDT_Int_Enable(WDT_HandleTypeDef* hwdt) +{ + hwdt->Instance->CTRL |= WDT_INT_ENABLE; + NVIC_ClearPendingIRQ(WDT_IRQn); + NVIC_EnableIRQ(WDT_IRQn); +} + +/************************************************************************ + * function : WDT_Int_Disable + * Description: WDT int disable + * input : none + * + * return: none + ************************************************************************/ +void HAL_WDT_Int_Disable(WDT_HandleTypeDef* hwdt) +{ + hwdt->Instance->CTRL &= WDT_INT_DISABLE; +} + + diff --git a/pool/shard004/C/0098059_TestFreeRDPCodecNCrush.c b/pool/shard004/C/0098059_TestFreeRDPCodecNCrush.c new file mode 100644 index 0000000000000000000000000000000000000000..48e52928779fe611f4ca0985a7fdf3d37b958a50 --- /dev/null +++ b/pool/shard004/C/0098059_TestFreeRDPCodecNCrush.c @@ -0,0 +1,101 @@ +#include +#include + +#include + +static const BYTE TEST_BELLS_DATA[] = "for.whom.the.bell.tolls,.the.bell.tolls.for.thee!"; + +const BYTE TEST_BELLS_NCRUSH[] = + "\xfb\x1d\x7e\xe4\xda\xc7\x1d\x70\xf8\xa1\x6b\x1f\x7d\xc0\xbe\x6b" + "\xef\xb5\xef\x21\x87\xd0\xc5\xe1\x85\x71\xd4\x10\x16\xe7\xda\xfb" + "\x1d\x7e\xe4\xda\x47\x1f\xb0\xef\xbe\xbd\xff\x2f"; + +int test_NCrushCompressBells() +{ + int status; + UINT32 Flags; + UINT32 SrcSize; + BYTE* pSrcData; + UINT32 DstSize; + BYTE* pDstData; + UINT32 expectedSize; + BYTE OutputBuffer[65536]; + NCRUSH_CONTEXT* ncrush; + ncrush = ncrush_context_new(TRUE); + SrcSize = sizeof(TEST_BELLS_DATA) - 1; + pSrcData = (BYTE*) TEST_BELLS_DATA; + expectedSize = sizeof(TEST_BELLS_NCRUSH) - 1; + pDstData = OutputBuffer; + DstSize = sizeof(OutputBuffer); + ZeroMemory(OutputBuffer, sizeof(OutputBuffer)); + status = ncrush_compress(ncrush, pSrcData, SrcSize, &pDstData, &DstSize, &Flags); + printf("status: %d Flags: 0x%04X DstSize: %d\n", status, Flags, DstSize); + + if (DstSize != expectedSize) + { + printf("NCrushCompressBells: output size mismatch: Actual: %d, Expected: %d\n", DstSize, expectedSize); + printf("Actual\n"); + BitDump(__FUNCTION__, WLOG_INFO, pDstData, DstSize * 8, 0); + printf("Expected\n"); + BitDump(__FUNCTION__, WLOG_INFO, TEST_BELLS_NCRUSH, expectedSize * 8, 0); + return -1; + } + + if (memcmp(pDstData, TEST_BELLS_NCRUSH, DstSize) != 0) + { + printf("NCrushCompressBells: output mismatch\n"); + printf("Actual\n"); + BitDump(__FUNCTION__, WLOG_INFO, pDstData, DstSize * 8, 0); + printf("Expected\n"); + BitDump(__FUNCTION__, WLOG_INFO, TEST_BELLS_NCRUSH, expectedSize * 8, 0); + return -1; + } + + ncrush_context_free(ncrush); + return 1; +} + +int test_NCrushDecompressBells() +{ + int status; + UINT32 Flags; + BYTE* pSrcData; + UINT32 SrcSize; + UINT32 DstSize; + UINT32 expectedSize; + BYTE* pDstData = NULL; + NCRUSH_CONTEXT* ncrush; + ncrush = ncrush_context_new(FALSE); + SrcSize = sizeof(TEST_BELLS_NCRUSH) - 1; + pSrcData = (BYTE*) TEST_BELLS_NCRUSH; + Flags = PACKET_COMPRESSED | 2; + expectedSize = sizeof(TEST_BELLS_DATA) - 1; + status = ncrush_decompress(ncrush, pSrcData, SrcSize, &pDstData, &DstSize, Flags); + printf("Flags: 0x%04X DstSize: %d\n", Flags, DstSize); + + if (DstSize != expectedSize) + { + printf("NCrushDecompressBells: output size mismatch: Actual: %d, Expected: %d\n", DstSize, expectedSize); + return -1; + } + + if (memcmp(pDstData, TEST_BELLS_DATA, DstSize) != 0) + { + printf("NCrushDecompressBells: output mismatch\n"); + return -1; + } + + ncrush_context_free(ncrush); + return 1; +} + +int TestFreeRDPCodecNCrush(int argc, char* argv[]) +{ + if (test_NCrushCompressBells() < 0) + return -1; + + if (test_NCrushDecompressBells() < 0) + return -1; + + return 0; +} diff --git a/pool/shard004/C/0098068_nrf_drv_rng.c b/pool/shard004/C/0098068_nrf_drv_rng.c new file mode 100644 index 0000000000000000000000000000000000000000..5a3fdb63d0638c80b3e0de4dec5f494ea3d55aa5 --- /dev/null +++ b/pool/shard004/C/0098068_nrf_drv_rng.c @@ -0,0 +1,219 @@ +/* Copyright (c) 2015 Nordic Semiconductor. All Rights Reserved. + * + * The information contained herein is property of Nordic Semiconductor ASA. + * Terms and conditions of usage are described in detail in NORDIC + * SEMICONDUCTOR STANDARD SOFTWARE LICENSE AGREEMENT. + * + * Licensees are granted free, non-transferable use of the information. NO + * WARRANTY of ANY KIND is provided. This heading must NOT be removed from + * the file. + * + */ + +#include +#include + +#include "nrf_drv_rng.h" +#include "nrf_assert.h" +#include "nrf_drv_common.h" +#include "nordic_common.h" +#include "nrf_error.h" +#include "nrf_assert.h" +#ifdef SOFTDEVICE_PRESENT +#include "nrf_sdm.h" +#include "nrf_soc.h" +#else +#include "app_fifo.h" +#include "app_util_platform.h" + +static __INLINE uint32_t fifo_length(app_fifo_t * p_fifo) +{ + uint32_t tmp = p_fifo->read_pos; + return p_fifo->write_pos - tmp; +} + +#define FIFO_LENGTH(fifo) fifo_length(&(fifo)) /**< Macro for calculating the FIFO length. */ + +#endif // SOFTDEVICE_PRESENT +typedef struct +{ + nrf_drv_state_t state; +#ifndef SOFTDEVICE_PRESENT + app_fifo_t rand_pool; + uint8_t buffer[RNG_CONFIG_POOL_SIZE]; +#endif // SOFTDEVICE_PRESENT +} nrf_drv_rng_cb_t; + +static nrf_drv_rng_cb_t m_rng_cb; +#ifndef SOFTDEVICE_PRESENT +static const nrf_drv_rng_config_t m_default_config = NRF_DRV_RNG_DEFAULT_CONFIG; +static void rng_start(void) +{ + if (FIFO_LENGTH(m_rng_cb.rand_pool) <= m_rng_cb.rand_pool.buf_size_mask) + { + nrf_rng_event_clear(NRF_RNG_EVENT_VALRDY); + nrf_rng_int_enable(NRF_RNG_INT_VALRDY_MASK); + nrf_rng_task_trigger(NRF_RNG_TASK_START); + } +} + + +static void rng_stop(void) +{ + nrf_rng_int_disable(NRF_RNG_INT_VALRDY_MASK); + nrf_rng_task_trigger(NRF_RNG_TASK_STOP); +} + + +#endif // SOFTDEVICE_PRESENT + + +ret_code_t nrf_drv_rng_init(nrf_drv_rng_config_t const * p_config) +{ + uint32_t result; + + if (m_rng_cb.state == NRF_DRV_STATE_UNINITIALIZED) + { +#ifndef SOFTDEVICE_PRESENT + + result = app_fifo_init(&m_rng_cb.rand_pool, m_rng_cb.buffer, RNG_CONFIG_POOL_SIZE); + + if (p_config == NULL) + { + p_config = &m_default_config; + } + + if (result == NRF_SUCCESS) + { + if (p_config->error_correction) + { + nrf_rng_error_correction_enable(); + } + + nrf_drv_common_irq_enable(RNG_IRQn, p_config->interrupt_priority); + + nrf_rng_shorts_disable(NRF_RNG_SHORT_VALRDY_STOP_MASK); + + rng_start(); + m_rng_cb.state = NRF_DRV_STATE_INITIALIZED; + } +#else + UNUSED_VARIABLE(p_config); + uint8_t softdevice_is_enabled; + result = sd_softdevice_is_enabled(&softdevice_is_enabled); + + if (softdevice_is_enabled) + { + m_rng_cb.state = NRF_DRV_STATE_INITIALIZED; + } + else + { + result = NRF_ERROR_SOFTDEVICE_NOT_ENABLED; + } +#endif // SOFTDEVICE_PRESENT + } + else + { + result = NRF_ERROR_INVALID_STATE; + } + return result; +} + + +void nrf_drv_rng_uninit(void) +{ + ASSERT(m_rng_cb.state == NRF_DRV_STATE_INITIALIZED); + + m_rng_cb.state = NRF_DRV_STATE_UNINITIALIZED; +#ifndef SOFTDEVICE_PRESENT + rng_stop(); + nrf_drv_common_irq_disable(RNG_IRQn); +#endif // SOFTDEVICE_PRESENT +} + +ret_code_t nrf_drv_rng_bytes_available(uint8_t * p_bytes_available) +{ + ret_code_t result; + ASSERT(m_rng_cb.state == NRF_DRV_STATE_INITIALIZED); + +#ifndef SOFTDEVICE_PRESENT + + result = NRF_SUCCESS; + *p_bytes_available = FIFO_LENGTH(m_rng_cb.rand_pool); + +#else + + result = sd_rand_application_bytes_available_get(p_bytes_available); + +#endif // SOFTDEVICE_PRESENT + + return result; +} + +ret_code_t nrf_drv_rng_pool_capacity(uint8_t * p_pool_capacity) +{ + ret_code_t result; + ASSERT(m_rng_cb.state == NRF_DRV_STATE_INITIALIZED); + +#ifndef SOFTDEVICE_PRESENT + + result = NRF_SUCCESS; + *p_pool_capacity = RNG_CONFIG_POOL_SIZE; + +#else + + result = sd_rand_application_pool_capacity_get(p_pool_capacity); + +#endif // SOFTDEVICE_PRESENT + return result; +} + +ret_code_t nrf_drv_rng_rand(uint8_t * p_buff, uint8_t length) +{ + ret_code_t result; + + ASSERT(m_rng_cb.state == NRF_DRV_STATE_INITIALIZED); + +#ifndef SOFTDEVICE_PRESENT + if (FIFO_LENGTH(m_rng_cb.rand_pool) >= length) + { + result = NRF_SUCCESS; + + for (uint32_t i = 0; (i < length) && (result == NRF_SUCCESS); i++) + { + result = app_fifo_get(&(m_rng_cb.rand_pool), &p_buff[i]); + } + rng_start(); + } + else + { + result = NRF_ERROR_NO_MEM; + } +#else + + result = sd_rand_application_vector_get(p_buff, length); + +#endif // SOFTDEVICE_PRESENT + + + return result; +} + + +#ifndef SOFTDEVICE_PRESENT +void RNG_IRQHandler(void) +{ + if (nrf_rng_event_get(NRF_RNG_EVENT_VALRDY) && + nrf_rng_int_get(NRF_RNG_INT_VALRDY_MASK)) + { + nrf_rng_event_clear(NRF_RNG_EVENT_VALRDY); + uint32_t nrf_error = app_fifo_put(&m_rng_cb.rand_pool, nrf_rng_random_value_get()); + + if ((FIFO_LENGTH(m_rng_cb.rand_pool) > m_rng_cb.rand_pool.buf_size_mask) || (nrf_error == NRF_ERROR_NO_MEM)) + { + rng_stop(); + } + } +} + +#endif // SOFTDEVICE_PRESENT diff --git a/pool/shard004/C/0098073_u8x8_d_uc1604.c b/pool/shard004/C/0098073_u8x8_d_uc1604.c new file mode 100644 index 0000000000000000000000000000000000000000..e7df8f9e897fb398017ca647a306eac503296df0 --- /dev/null +++ b/pool/shard004/C/0098073_u8x8_d_uc1604.c @@ -0,0 +1,240 @@ +/* + + u8x8_d_uc1604.c + + Universal 8bit Graphics Library (https://github.com/olikraus/u8g2/) + + Copyright (c) 2016, olikraus@gmail.com + 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 "u8x8.h" + + + + + +static const uint8_t u8x8_d_uc1604_powersave0_seq[] = { + U8X8_START_TRANSFER(), /* enable chip, delay is part of the transfer start */ + U8X8_DLY(20), + U8X8_C(0x0af), /* display on */ + U8X8_DLY(20), /* during setup, it seems that the startup is more reliable when sending this cmd twice */ + U8X8_C(0x0af), /* display on */ + U8X8_DLY(50), /* startup takes some time */ + U8X8_END_TRANSFER(), /* disable chip */ + U8X8_END() /* end of sequence */ +}; + +static const uint8_t u8x8_d_uc1604_powersave1_seq[] = { + U8X8_START_TRANSFER(), /* enable chip, delay is part of the transfer start */ + U8X8_C(0x0ae), /* display off, enter sleep mode */ + U8X8_END_TRANSFER(), /* disable chip */ + U8X8_END() /* end of sequence */ +}; + +static const uint8_t u8x8_d_uc1604_flip0_seq[] = { + U8X8_START_TRANSFER(), /* enable chip, delay is part of the transfer start */ + U8X8_C(0x0c4), /* LCD Mapping */ + U8X8_END_TRANSFER(), /* disable chip */ + U8X8_END() /* end of sequence */ +}; + +static const uint8_t u8x8_d_uc1604_flip1_seq[] = { + U8X8_START_TRANSFER(), /* enable chip, delay is part of the transfer start */ + U8X8_C(0x0c2), /* LCD Mapping */ + U8X8_END_TRANSFER(), /* disable chip */ + U8X8_END() /* end of sequence */ +}; + + +uint8_t u8x8_d_uc1604_common(u8x8_t *u8x8, uint8_t msg, uint8_t arg_int, void *arg_ptr) +{ + uint8_t x, y, c; + uint8_t *ptr; + switch(msg) + { + case U8X8_MSG_DISPLAY_DRAW_TILE: + u8x8_cad_StartTransfer(u8x8); + + x = ((u8x8_tile_t *)arg_ptr)->x_pos; + x *= 8; + + u8x8_cad_SendCmd(u8x8, 0x000 | ((x&15))); + u8x8_cad_SendCmd(u8x8, 0x010 | (x>>4) ); + + y = ((u8x8_tile_t *)arg_ptr)->y_pos; + y += u8x8->x_offset; + u8x8_cad_SendCmd(u8x8, 0x0b0 | (y&15)); + + c = ((u8x8_tile_t *)arg_ptr)->cnt; + c *= 8; + ptr = ((u8x8_tile_t *)arg_ptr)->tile_ptr; + do + { + u8x8_cad_SendData(u8x8, c, ptr); /* note: SendData can not handle more than 255 bytes */ + arg_int--; + } while( arg_int > 0 ); + + u8x8_cad_EndTransfer(u8x8); + break; + /* handled in the calling procedure + case U8X8_MSG_DISPLAY_SETUP_MEMORY: + u8x8_d_helper_display_setup_memory(u8x8, &u8x8_uc1604_128x64_display_info); + break; + case U8X8_MSG_DISPLAY_INIT: + u8x8_d_helper_display_init(u8x8); + u8x8_cad_SendSequence(u8x8, u8x8_d_uc1701_dogs102_init_seq); + break; + */ + case U8X8_MSG_DISPLAY_SET_POWER_SAVE: + if ( arg_int == 0 ) + u8x8_cad_SendSequence(u8x8, u8x8_d_uc1604_powersave0_seq); + else + u8x8_cad_SendSequence(u8x8, u8x8_d_uc1604_powersave1_seq); + break; + case U8X8_MSG_DISPLAY_SET_FLIP_MODE: + if ( arg_int == 0 ) + { + u8x8_cad_SendSequence(u8x8, u8x8_d_uc1604_flip0_seq); + u8x8->x_offset = u8x8->display_info->default_x_offset; + } + else + { + u8x8_cad_SendSequence(u8x8, u8x8_d_uc1604_flip1_seq); + u8x8->x_offset = u8x8->display_info->flipmode_x_offset; + } + break; +#ifdef U8X8_WITH_SET_CONTRAST + case U8X8_MSG_DISPLAY_SET_CONTRAST: + u8x8_cad_StartTransfer(u8x8); + u8x8_cad_SendCmd(u8x8, 0x081 ); + u8x8_cad_SendArg(u8x8, arg_int ); /* uc1604 has range from 0 to 255 */ + u8x8_cad_EndTransfer(u8x8); + break; +#endif + default: + return 0; + } + return 1; +} + +/*================================================*/ +/* JLX19264 */ + +/* + timings from uc1608 + + UC1604 has two chip select inputs (CS0 and CS1). + CS0 is low active, CS1 is high active. It will depend on the display + module whether the display has a is low or high active chip select. + +*/ +static const u8x8_display_info_t u8x8_uc1604_192x64_display_info = +{ + /* chip_enable_level = */ 0, /* JLX19264G uses CS0, which is low active CS*/ + /* chip_disable_level = */ 1, + + /* post_chip_enable_wait_ns = */ 20, + /* pre_chip_disable_wait_ns = */ 20, + /* reset_pulse_width_ms = */ 1, + /* post_reset_wait_ms = */ 10, + /* sda_setup_time_ns = */ 30, + /* sck_pulse_width_ns = */ 65, /* half of cycle time */ + /* sck_clock_hz = */ 8000000UL, /* since Arduino 1.6.0, the SPI bus speed in Hz. Should be 1000000000/sck_pulse_width_ns */ + /* spi_mode = */ 0, /* active high, rising edge */ + /* i2c_bus_clock_100kHz = */ 4, + /* data_setup_time_ns = */ 30, + /* write_pulse_width_ns = */ 35, + /* tile_width = */ 24, /* width of 24*8=192 pixel */ + /* tile_hight = */ 8, + /* default_x_offset = */ 0, /* reused as y page offset */ + /* flipmode_x_offset = */ 0, /* reused as y page offset */ + /* pixel_width = */ 192, + /* pixel_height = */ 64 +}; + +static const uint8_t u8x8_d_uc1604_jlx19264_init_seq[] = { + + U8X8_START_TRANSFER(), /* enable chip, delay is part of the transfer start */ + + U8X8_C(0x0e2), /* soft reset */ + U8X8_DLY(200), + U8X8_DLY(200), + + U8X8_C(0x02f), /* power on, Bit 2 PC2=1 (internal charge pump), Bits 0/1: cap of panel */ + U8X8_DLY(200), + U8X8_DLY(200), + + U8X8_CA(0x081, 0x052), /* set contrast, JLX19264G suggestion: 0x045 */ + U8X8_C(0x0eb), /* LCD bias Bits 0/1: 00=6 01=7, 10=8, 11=9 */ + + + //U8X8_C(0x023), /* Bit 0/1: Temp compenstation, Bit 2: Multiplex Rate 0=96, 1=128 */ + //U8X8_C(0x027), /* Bit 0/1: Temp compenstation, Bit 2: Multiplex Rate 0=96, 1=128 */ + + U8X8_C(0x0c4), /* Map control, Bit 2: MY=1, Bit 1: MX=0 */ + U8X8_C(0x0a0), /* 0xa0: 76Hz FPS, controller default: 0x0a1: 95Hz FPS */ + + + U8X8_C(0x040), /* set scroll line to 0 */ + U8X8_C(0x089), /* RAM access control (controller default: 0x089)*/ + + + U8X8_C(0x000), /* column low nibble */ + U8X8_C(0x010), /* column high nibble */ + U8X8_C(0x0b0), /* page adr */ + + + U8X8_END_TRANSFER(), /* disable chip */ + U8X8_END() /* end of sequence */ +}; + +uint8_t u8x8_d_uc1604_jlx19264(u8x8_t *u8x8, uint8_t msg, uint8_t arg_int, void *arg_ptr) +{ + /* call common procedure first and handle messages there */ + if ( u8x8_d_uc1604_common(u8x8, msg, arg_int, arg_ptr) == 0 ) + { + /* msg not handled, then try here */ + switch(msg) + { + case U8X8_MSG_DISPLAY_SETUP_MEMORY: + u8x8_d_helper_display_setup_memory(u8x8, &u8x8_uc1604_192x64_display_info); + break; + case U8X8_MSG_DISPLAY_INIT: + u8x8_d_helper_display_init(u8x8); + u8x8_cad_SendSequence(u8x8, u8x8_d_uc1604_jlx19264_init_seq); + break; + default: + return 0; /* msg unknown */ + } + } + return 1; +} + + diff --git a/pool/shard004/C/0098079_debug_sine_amp.c b/pool/shard004/C/0098079_debug_sine_amp.c new file mode 100644 index 0000000000000000000000000000000000000000..c374ac7f5282c97a78323afcc51f48ee23bc5c45 --- /dev/null +++ b/pool/shard004/C/0098079_debug_sine_amp.c @@ -0,0 +1,164 @@ +/* + * $Id: debug_sine_amp.c 1083 2006-08-23 07:30:49Z rossb $ + * Play a different sine wave on each channels, + * using the Portable Audio api. + * Allos amplitude to be set interactively. + * + * Author: Phil Burk http://www.softsynth.com + * + * This program uses the PortAudio Portable Audio Library. + * For more information see: http://www.portaudio.com + * Copyright (c) 1999-2000 Ross Bencina and Phil Burk + * + * 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. + */ + +/* + * The text above constitutes the entire PortAudio license; however, + * the PortAudio community also makes the following non-binding requests: + * + * Any person wishing to distribute modifications to the Software is + * requested to send the modifications to the original developer so that + * they can be incorporated into the canonical version. It is also + * requested that these non-binding requests be included along with the + * license above. + */ + +#include +#include +#include "portaudio.h" + +#define OUTPUT_DEVICE (Pa_GetDefaultOutputDeviceID()) +#define SAMPLE_RATE (44100) +#define FRAMES_PER_BUFFER (256) +#define FREQ_INCR (300.0 / SAMPLE_RATE) +#define MAX_CHANNELS (64) + +#ifndef M_PI +#define M_PI (3.14159265) +#endif + +typedef struct +{ + int numChannels; + double phases[MAX_CHANNELS]; + float amplitude; +} +paTestData; + +/* This routine will be called by the PortAudio engine when audio is needed. +** It may called at interrupt level on some machines so don't do anything +** that could mess up the system like calling malloc() or free(). +*/ +static int patestCallback( void *inputBuffer, void *outputBuffer, + unsigned long framesPerBuffer, + PaTimestamp outTime, void *userData ) +{ + paTestData *data = (paTestData*)userData; + float *out = (float*)outputBuffer; + int frameIndex, channelIndex; + (void) outTime; /* Prevent unused variable warnings. */ + (void) inputBuffer; + + for( frameIndex=0; frameIndex<(int)framesPerBuffer; frameIndex++ ) + { + for( channelIndex=0; channelIndexnumChannels; channelIndex++ ) + { + /* Output sine wave on every channel. */ + *out++ = (float) ( data->amplitude * sin(data->phases[channelIndex]) ); + + /* Play each channel at a higher frequency. */ + data->phases[channelIndex] += FREQ_INCR * (4 + channelIndex); + if( data->phases[channelIndex] >= (2.0 * M_PI) ) data->phases[channelIndex] -= (2.0 * M_PI); + } + } + + return 0; +} +/*******************************************************************/ +int main(void); +int main(void) +{ + char pad[256]; + PortAudioStream *stream; + PaError err; + const PaDeviceInfo *pdi; + paTestData data = {0}; + printf("PortAudio Test: output sine wave on each channel.\n" ); + + err = Pa_Initialize(); + if( err != paNoError ) goto error; + + pdi = Pa_GetDeviceInfo( OUTPUT_DEVICE ); + data.numChannels = pdi->maxOutputChannels; + if( data.numChannels > MAX_CHANNELS ) data.numChannels = MAX_CHANNELS; + printf("Number of Channels = %d\n", data.numChannels ); + data.amplitude = 1.0; + + err = Pa_OpenStream( + &stream, + paNoDevice, /* default input device */ + 0, /* no input */ + paFloat32, /* 32 bit floating point input */ + NULL, + OUTPUT_DEVICE, + data.numChannels, + paFloat32, /* 32 bit floating point output */ + NULL, + SAMPLE_RATE, + FRAMES_PER_BUFFER, /* frames per buffer */ + 0, /* number of buffers, if zero then use default minimum */ + paClipOff, /* we won't output out of range samples so don't bother clipping them */ + patestCallback, + &data ); + if( err != paNoError ) goto error; + + err = Pa_StartStream( stream ); + if( err != paNoError ) goto error; + + do + { + printf("Current amplitude = %f\n", data.amplitude ); + printf("Enter new amplitude or 'q' to quit.\n"); + fflush(stdout); + gets( pad ); + if( pad[0] != 'q' ) + { + // I tried to use atof but it seems to be broken on Mac OS X 10.1 + float amp; + sscanf( pad, "%f", & ); + data.amplitude = amp; + } + } while( pad[0] != 'q' ); + + err = Pa_StopStream( stream ); + if( err != paNoError ) goto error; + + Pa_CloseStream( stream ); + Pa_Terminate(); + printf("Test finished.\n"); + return err; +error: + Pa_Terminate(); + fprintf( stderr, "An error occured while using the portaudio stream\n" ); + fprintf( stderr, "Error number: %d\n", err ); + fprintf( stderr, "Error message: %s\n", Pa_GetErrorText( err ) ); + return err; +} diff --git a/pool/shard004/C/0098080_m41t60.c b/pool/shard004/C/0098080_m41t60.c new file mode 100644 index 0000000000000000000000000000000000000000..ef135cab3831f399f6bf0d1e5dafb610aa452eab --- /dev/null +++ b/pool/shard004/C/0098080_m41t60.c @@ -0,0 +1,263 @@ +/* + * (C) Copyright 2007 + * Larry Johnson, lrj@acm.org + * + * based on rtc/m41t11.c which is ... + * + * (C) Copyright 2002 + * Andrew May, Viasat Inc, amay@viasat.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 + */ + +/* + * STMicroelectronics M41T60 serial access real-time clock + */ + +/* #define DEBUG 1 */ + +#include +#include +#include +#include + +#if defined(CONFIG_RTC_M41T60) && defined(CFG_I2C_RTC_ADDR) && \ + defined(CONFIG_CMD_DATE) + +static unsigned bcd2bin(uchar n) +{ + return ((((n >> 4) & 0x0F) * 10) + (n & 0x0F)); +} + +static unsigned char bin2bcd(unsigned int n) +{ + return (((n / 10) << 4) | (n % 10)); +} + +/* + * Convert between century and "century bits" (CB1 and CB0). These routines + * assume years are in the range 1900 - 2299. + */ + +static unsigned char year2cb(unsigned const year) +{ + if (year < 1900 || year >= 2300) + printf("M41T60 RTC: year %d out of range\n", year); + + return (year / 100) & 0x3; +} + +static unsigned cb2year(unsigned const cb) +{ + return 1900 + 100 * ((cb + 1) & 0x3); +} + +/* + * These are simple defines for the chip local to here so they aren't too + * verbose. DAY/DATE aren't nice but that is how they are on the data sheet. + */ +#define RTC_SEC 0x0 +#define RTC_MIN 0x1 +#define RTC_HOUR 0x2 +#define RTC_DAY 0x3 +#define RTC_DATE 0x4 +#define RTC_MONTH 0x5 +#define RTC_YEAR 0x6 + +#define RTC_REG_CNT 7 + +#define RTC_CTRL 0x7 + +#if defined(DEBUG) +static void rtc_dump(char const *const label) +{ + uchar data[8]; + + if (i2c_read(CFG_I2C_RTC_ADDR, 0, 1, data, sizeof(data))) { + printf("I2C read failed in rtc_dump()\n"); + return; + } + printf("RTC dump %s: %02X-%02X-%02X-%02X-%02X-%02X-%02X-%02X\n", + label, data[0], data[1], data[2], data[3], + data[4], data[5], data[6], data[7]); +} +#else +#define rtc_dump(label) +#endif + +static uchar *rtc_validate(void) +{ + /* + * This routine uses the OUT bit and the validity of the time values to + * determine whether there has been an initial power-up since the last + * time the routine was run. It assumes that the OUT bit is not being + * used for any other purpose. + */ + static const uchar daysInMonth[0x13] = { + 0x00, 0x31, 0x29, 0x31, 0x30, 0x31, 0x30, 0x31, + 0x31, 0x30, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x31, 0x30, 0x31 + }; + static uchar data[8]; + uchar min, date, month, years; + + rtc_dump("begin validate"); + if (i2c_read(CFG_I2C_RTC_ADDR, 0, 1, data, sizeof(data))) { + printf("I2C read failed in rtc_validate()\n"); + return 0; + } + /* + * If the OUT bit is "1", there has been a loss of power, so stop the + * oscillator so it can be "kick-started" as per data sheet. + */ + if (0x00 != (data[RTC_CTRL] & 0x80)) { + printf("M41T60 RTC clock lost power.\n"); + data[RTC_SEC] = 0x80; + if (i2c_write(CFG_I2C_RTC_ADDR, RTC_SEC, 1, data, 1)) { + printf("I2C write failed in rtc_validate()\n"); + return 0; + } + } + /* + * If the oscillator is stopped or the date is invalid, then reset the + * OUT bit to "0", reset the date registers, and start the oscillator. + */ + min = data[RTC_MIN] & 0x7F; + date = data[RTC_DATE]; + month = data[RTC_MONTH] & 0x3F; + years = data[RTC_YEAR]; + if (0x59 < data[RTC_SEC] || 0x09 < (data[RTC_SEC] & 0x0F) || + 0x59 < min || 0x09 < (min & 0x0F) || + 0x23 < data[RTC_HOUR] || 0x09 < (data[RTC_HOUR] & 0x0F) || + 0x07 < data[RTC_DAY] || 0x00 == data[RTC_DAY] || + 0x12 < month || + 0x99 < years || 0x09 < (years & 0x0F) || + daysInMonth[month] < date || 0x09 < (date & 0x0F) || 0x00 == date || + (0x29 == date && 0x02 == month && + ((0x00 != (years & 0x03)) || + (0x00 == years && 0x00 != (data[RTC_MONTH] & 0xC0))))) { + printf("Resetting M41T60 RTC clock.\n"); + /* + * Set to 00:00:00 1900-01-01 (Monday) + */ + data[RTC_SEC] = 0x00; + data[RTC_MIN] &= 0x80; /* preserve OFIE bit */ + data[RTC_HOUR] = 0x00; + data[RTC_DAY] = 0x02; + data[RTC_DATE] = 0x01; + data[RTC_MONTH] = 0xC1; + data[RTC_YEAR] = 0x00; + data[RTC_CTRL] &= 0x7F; /* reset OUT bit */ + + if (i2c_write(CFG_I2C_RTC_ADDR, 0, 1, data, sizeof(data))) { + printf("I2C write failed in rtc_validate()\n"); + return 0; + } + } + return data; +} + +int rtc_get(struct rtc_time *tmp) +{ + uchar const *const data = rtc_validate(); + + if (!data) + return -1; + + tmp->tm_sec = bcd2bin(data[RTC_SEC] & 0x7F); + tmp->tm_min = bcd2bin(data[RTC_MIN] & 0x7F); + tmp->tm_hour = bcd2bin(data[RTC_HOUR] & 0x3F); + tmp->tm_mday = bcd2bin(data[RTC_DATE] & 0x3F); + tmp->tm_mon = bcd2bin(data[RTC_MONTH] & 0x1F); + tmp->tm_year = cb2year(data[RTC_MONTH] >> 6) + bcd2bin(data[RTC_YEAR]); + tmp->tm_wday = bcd2bin(data[RTC_DAY] & 0x07) - 1; + tmp->tm_yday = 0; + tmp->tm_isdst = 0; + + debug("Get DATE: %4d-%02d-%02d (wday=%d) TIME: %2d:%02d:%02d\n", + tmp->tm_year, tmp->tm_mon, tmp->tm_mday, tmp->tm_wday, + tmp->tm_hour, tmp->tm_min, tmp->tm_sec); + + return 0; +} + +void rtc_set(struct rtc_time *tmp) +{ + uchar *const data = rtc_validate(); + + if (!data) + return; + + debug("Set DATE: %4d-%02d-%02d (wday=%d) TIME: %2d:%02d:%02d\n", + tmp->tm_year, tmp->tm_mon, tmp->tm_mday, tmp->tm_wday, + tmp->tm_hour, tmp->tm_min, tmp->tm_sec); + + data[RTC_SEC] = (data[RTC_SEC] & 0x80) | (bin2bcd(tmp->tm_sec) & 0x7F); + data[RTC_MIN] = (data[RTC_MIN] & 0X80) | (bin2bcd(tmp->tm_min) & 0X7F); + data[RTC_HOUR] = bin2bcd(tmp->tm_hour) & 0x3F; + data[RTC_DATE] = bin2bcd(tmp->tm_mday) & 0x3F; + data[RTC_MONTH] = bin2bcd(tmp->tm_mon) & 0x1F; + data[RTC_YEAR] = bin2bcd(tmp->tm_year % 100); + data[RTC_MONTH] |= year2cb(tmp->tm_year) << 6; + data[RTC_DAY] = bin2bcd(tmp->tm_wday + 1) & 0x07; + if (i2c_write(CFG_I2C_RTC_ADDR, 0, 1, data, RTC_REG_CNT)) { + printf("I2C write failed in rtc_set()\n"); + return; + } +} + +void rtc_reset(void) +{ + uchar *const data = rtc_validate(); + char const *const s = getenv("rtccal"); + + if (!data) + return; + + rtc_dump("begin reset"); + /* + * If environmental variable "rtccal" is present, it must be a hex value + * between 0x00 and 0x3F, inclusive. The five least-significan bits + * represent the calibration magnitude, and the sixth bit the sign bit. + * If these do not match the contents of the hardware register, that + * register is updated. The value 0x00 imples no correction. Consult + * the M41T60 documentation for further details. + */ + if (s) { + unsigned long const l = simple_strtoul(s, 0, 16); + + if (l <= 0x3F) { + if ((data[RTC_CTRL] & 0x3F) != l) { + printf("Setting RTC calibration to 0x%02lX\n", + l); + data[RTC_CTRL] &= 0xC0; + data[RTC_CTRL] |= (uchar) l; + } + } else + printf("environment parameter \"rtccal\" not valid: " + "ignoring\n"); + } + /* + * Turn off frequency test. + */ + data[RTC_CTRL] &= 0xBF; + if (i2c_write(CFG_I2C_RTC_ADDR, RTC_CTRL, 1, data + RTC_CTRL, 1)) { + printf("I2C write failed in rtc_reset()\n"); + return; + } + rtc_dump("end reset"); +} +#endif /* CONFIG_RTC_M41T60 && CFG_I2C_RTC_ADDR && CONFIG_CMD_DATE */ diff --git a/pool/shard004/C/0098085_graceful_server_shutdown.c b/pool/shard004/C/0098085_graceful_server_shutdown.c new file mode 100644 index 0000000000000000000000000000000000000000..f527b8617d973f9ce035c0afca2b00d82b40aede --- /dev/null +++ b/pool/shard004/C/0098085_graceful_server_shutdown.c @@ -0,0 +1,216 @@ +/* + * + * 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 "test/core/end2end/end2end_tests.h" + +#include +#include + +#include +#include +#include +#include +#include +#include "test/core/end2end/cq_verifier.h" + +enum { TIMEOUT = 200000 }; + +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_time(int n) { + return GRPC_TIMEOUT_SECONDS_TO_DEADLINE(n); +} + +static gpr_timespec five_seconds_time(void) { return n_seconds_time(5); } + +static void drain_cq(grpc_completion_queue *cq) { + grpc_event ev; + do { + ev = grpc_completion_queue_next(cq, five_seconds_time(), NULL); + } while (ev.type != GRPC_QUEUE_SHUTDOWN); +} + +static void shutdown_server(grpc_end2end_test_fixture *f) { + if (!f->server) return; + 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); +} + +static void test_early_server_shutdown_finishes_inflight_calls( + grpc_end2end_test_config config) { + grpc_call *c; + grpc_call *s; + gpr_timespec deadline = n_seconds_time(10); + grpc_end2end_test_fixture f = begin_test( + config, "test_early_server_shutdown_finishes_inflight_calls", NULL, 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_call_details call_details; + grpc_status_code status; + grpc_call_error error; + char *details = NULL; + size_t details_capacity = 0; + int was_cancelled = 2; + + c = grpc_channel_create_call(f.client, NULL, GRPC_PROPAGATE_DEFAULTS, f.cq, + "/foo", "foo.test.google.fr", 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->data.send_initial_metadata.metadata = NULL; + op->flags = 0; + op->reserved = NULL; + op++; + op->op = GRPC_OP_SEND_CLOSE_FROM_CLIENT; + op->flags = 0; + op->reserved = NULL; + op++; + op->op = GRPC_OP_RECV_INITIAL_METADATA; + op->data.recv_initial_metadata = &initial_metadata_recv; + op->flags = 0; + op->reserved = NULL; + op++; + 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->data.recv_status_on_client.status_details_capacity = &details_capacity; + op->flags = 0; + op->reserved = NULL; + op++; + error = grpc_call_start_batch(c, ops, (size_t)(op - ops), tag(1), NULL); + GPR_ASSERT(GRPC_CALL_OK == error); + + error = + grpc_server_request_call(f.server, &s, &call_details, + &request_metadata_recv, f.cq, f.cq, tag(101)); + GPR_ASSERT(GRPC_CALL_OK == error); + cq_expect_completion(cqv, tag(101), 1); + cq_verify(cqv); + + /* shutdown and destroy the server */ + grpc_server_shutdown_and_notify(f.server, f.cq, tag(0xdead)); + cq_verify_empty(cqv); + + memset(ops, 0, sizeof(ops)); + op = ops; + op->op = GRPC_OP_SEND_INITIAL_METADATA; + op->data.send_initial_metadata.count = 0; + op->flags = 0; + op->reserved = NULL; + op++; + op->op = GRPC_OP_SEND_STATUS_FROM_SERVER; + op->data.send_status_from_server.trailing_metadata_count = 0; + op->data.send_status_from_server.status = GRPC_STATUS_UNIMPLEMENTED; + op->data.send_status_from_server.status_details = "xyz"; + op->flags = 0; + op->reserved = NULL; + op++; + op->op = GRPC_OP_RECV_CLOSE_ON_SERVER; + op->data.recv_close_on_server.cancelled = &was_cancelled; + op->flags = 0; + op->reserved = NULL; + 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(0xdead), 1); + cq_expect_completion(cqv, tag(1), 1); + cq_verify(cqv); + + grpc_call_destroy(s); + + GPR_ASSERT(status == GRPC_STATUS_UNIMPLEMENTED); + GPR_ASSERT(0 == strcmp(call_details.method, "/foo")); + GPR_ASSERT(0 == strcmp(call_details.host, "foo.test.google.fr")); + GPR_ASSERT(was_cancelled == 1); + + gpr_free(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_destroy(c); + + cq_verifier_destroy(cqv); + + end_test(&f); + config.tear_down_data(&f); +} + +void graceful_server_shutdown(grpc_end2end_test_config config) { + test_early_server_shutdown_finishes_inflight_calls(config); +} + +void graceful_server_shutdown_pre_init(void) {} diff --git a/pool/shard004/C/0098086_wiring_pulse.c b/pool/shard004/C/0098086_wiring_pulse.c new file mode 100644 index 0000000000000000000000000000000000000000..481d2c9b14abc18aefed6305c9b1bbbda440b91a --- /dev/null +++ b/pool/shard004/C/0098086_wiring_pulse.c @@ -0,0 +1,95 @@ +/* + wiring_pulse.c - pulseIn() function + Part of Arduino - http://www.arduino.cc/ + + Copyright (c) 2005-2006 David A. Mellis + Copyright (c) 2017 Salvador E. Tropea + Copyright (c) 2017 Instituto Nacional de Tecnología Industrial + + 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 "wiring_private.h" +#include "pins_arduino.h" + +/* Measures the length (in microseconds) of a pulse on the pin; state is HIGH + * or LOW, the type of pulse to measure. Works on pulses from 2-3 microseconds + * to 3 minutes in length, but must be called at least a few dozen microseconds + * before the start of the pulse. + * + * This function performs better with short pulses in noInterrupt() context + */ +unsigned long pulseIn(uint8_t pin, uint8_t state, unsigned long timeout) +{ + // cache the port and bit of the pin in order to speed up the + // pulse width measuring loop and achieve finer resolution. calling + // digitalRead() instead yields much coarser resolution. + uint8_t bit = digitalPinToBitMask(pin); + uint8_t port = digitalPinToPort(pin); + uint8_t stateMask = (state ? bit : 0); + + // convert the timeout from microseconds to a number of times through + // the initial loop; it takes approximately 16 clock cycles per iteration + unsigned long maxloops = microsecondsToClockCycles(timeout)/32; + + unsigned long width = countPulseASM(portInputRegister(port), bit, stateMask, maxloops); + + // prevent clockCyclesToMicroseconds to return bogus values if countPulseASM timed out + if (width) + return clockCyclesToMicroseconds(width * 32 + 32); + else + return 0; +} + +/* Measures the length (in microseconds) of a pulse on the pin; state is HIGH + * or LOW, the type of pulse to measure. Works on pulses from 2-3 microseconds + * to 3 minutes in length, but must be called at least a few dozen microseconds + * before the start of the pulse. + * + * ATTENTION: + * this function relies on micros() so cannot be used in noInterrupt() context + */ +unsigned long pulseInLong(uint8_t pin, uint8_t state, unsigned long timeout) +{ + // cache the port and bit of the pin in order to speed up the + // pulse width measuring loop and achieve finer resolution. calling + // digitalRead() instead yields much coarser resolution. + uint8_t bit = digitalPinToBitMask(pin); + uint8_t port = digitalPinToPort(pin); + uint8_t stateMask = (state ? bit : 0); + + unsigned long startMicros = micros(); + + // wait for any previous pulse to end + while ((*portInputRegister(port) & bit) == stateMask) { + if (micros() - startMicros > timeout) + return 0; + } + + // wait for the pulse to start + while ((*portInputRegister(port) & bit) != stateMask) { + if (micros() - startMicros > timeout) + return 0; + } + + unsigned long start = micros(); + // wait for the pulse to stop + while ((*portInputRegister(port) & bit) == stateMask) { + if (micros() - startMicros > timeout) + return 0; + } + return micros() - start; +} diff --git a/pool/shard004/C/0098087_test_ccnx_ManifestInterface.c.c b/pool/shard004/C/0098087_test_ccnx_ManifestInterface.c.c new file mode 100644 index 0000000000000000000000000000000000000000..42ce095f2652da554f43540a562f8fe082c573ab --- /dev/null +++ b/pool/shard004/C/0098087_test_ccnx_ManifestInterface.c.c @@ -0,0 +1,100 @@ +/* + * Copyright (c) 2017 Cisco and/or its affiliates. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + */ + +// Include the file(s) containing the functions to be tested. +// This permits internal static functions to be visible to this Test Framework. +#include "../ccnx_ManifestInterface.c" + +#include + +#include +#include + +#include + +LONGBOW_TEST_RUNNER(ccnx_ManifestInterface) +{ + LONGBOW_RUN_TEST_FIXTURE(Global); +} + +// The Test Runner calls this function once before any Test Fixtures are run. +LONGBOW_TEST_RUNNER_SETUP(ccnx_ManifestInterface) +{ + parcMemory_SetInterface(&PARCSafeMemoryAsPARCMemory); + return LONGBOW_STATUS_SUCCEEDED; +} + +// The Test Runner calls this function once after all the Test Fixtures are run. +LONGBOW_TEST_RUNNER_TEARDOWN(ccnx_ManifestInterface) +{ + return LONGBOW_STATUS_SUCCEEDED; +} + +// ====================================================================================== + +LONGBOW_TEST_FIXTURE(Global) +{ + LONGBOW_RUN_TEST_CASE(Global, ccnxManifestInterface_GetImplementation); +} + +LONGBOW_TEST_FIXTURE_SETUP(Global) +{ + return LONGBOW_STATUS_SUCCEEDED; +} + +LONGBOW_TEST_FIXTURE_TEARDOWN(Global) +{ + uint32_t outstandingAllocations = parcSafeMemory_ReportAllocation(STDERR_FILENO); + if (outstandingAllocations != 0) { + printf("%s leaks memory by %d allocations\n", longBowTestCase_GetName(testCase), outstandingAllocations); + return LONGBOW_STATUS_MEMORYLEAK; + } + return LONGBOW_STATUS_SUCCEEDED; +} + +// ====================================================================================== + + +LONGBOW_TEST_CASE(Global, ccnxManifestInterface_GetImplementation) +{ + CCNxName *name = ccnxName_CreateFromCString("lci:/boose/roo/pie"); + + CCNxManifest *manifestV1 = ccnxManifest_Create(name); + ccnxName_Release(&name); + + assertTrue(ccnxManifestInterface_GetInterface(manifestV1) == &CCNxManifestFacadeV1_Interface, "Expected V1 Implementation"); + + // Now unset the pointer and see if it gets derived properly. + ccnxTlvDictionary_SetMessageInterface(manifestV1, NULL); + + assertTrue(ccnxManifestInterface_GetInterface(manifestV1) == &CCNxManifestFacadeV1_Interface, "Expected V1 Implementation"); + + ccnxManifest_Release(&manifestV1); +} + + +// ====================================================================================== + +int +main(int argc, char *argv[]) +{ + LongBowRunner *testRunner = LONGBOW_TEST_RUNNER_CREATE(ccnx_ManifestInterface); + int exitStatus = longBowMain(argc, argv, testRunner, NULL); + longBowTestRunner_Destroy(&testRunner); + exit(exitStatus); +} diff --git a/pool/shard004/C/0098091_logik.c b/pool/shard004/C/0098091_logik.c new file mode 100644 index 0000000000000000000000000000000000000000..3d67fb96758ca2586e082dab320913f3f9586e51 --- /dev/null +++ b/pool/shard004/C/0098091_logik.c @@ -0,0 +1,300 @@ +/** \file + ******************************************************************** + * Alles zu Logiken. + * + * $Header: /home/tobias/macbookbackup/Entwicklung/mutabor/cvs-backup/mutabor/mutabor/libmutabor/logik.c,v 1.4 2005/11/03 14:50:27 keinstein Exp $ + * \author Tobias Schlemmer + * \date $Date: 2005/11/03 14:50:27 $ + * \version $Revision: 1.4 $ + * + * $Log: logik.c,v $ + * Revision 1.4 2005/11/03 14:50:27 keinstein + * new includes + * interpreter functions + * + * Revision 1.3 2005/07/20 12:01:01 keinstein + * Kopf korrigiert + * Includes bereinigt. + * config.h + * + * Revision 1.2 2005/07/19 15:15:27 keinstein + * Using own Templates + * + * Revision 1.1 2005/07/08 14:44:20 keinstein + * Neue Datei. + * Aus parser.c herausgelöst. + * + ********************************************************************/ +#ifdef HAVE_CONFIG_H +# include "config.h" +#endif +#ifdef HAVE_STDDEF_H +# include +#endif +#include +#include "mutabor/logik.h" +#include "mutabor/anweisung.h" +#include "mutabor/heap.h" +#include "mutabor/tonsystem.h" +#include "mutabor/umstimmung.h" +#include "mutabor/parameter.h" +#include "mutabor/aktion.h" + +/** Wurzel der Logiken */ +struct logik * list_of_logiken; + +/** Zählen der Elemente einer einfach verketteten Logikliste. + * \param list Liste der Logiken + * \return Anzahl der Elemente von \a list + */ +int logik_list_laenge (struct logik *list) +{ if (list) return 1 + logik_list_laenge (list -> next); + return 0; +} + +/** Ermitteln der Position einer Logik. + * Falls \a liste leer wird eine Fehlermeldung ausgegeben. + * \param[in] name Name der zu suchenden Logik + * \param[in] liste Liste, in der die Logik gesucht wird + * \return Nummer der Logik in der Liste + */ +int get_logik_nummer (char * name, struct logik * liste) +{ if (liste == NULL) { + fatal_error (0, __FILE__, __LINE__); + return 0; + } + else if ( ! strcmp (name, liste->name)) + return 0; + else + return 1 + get_logik_nummer (name, liste->next); +} + +/** Sucht eine Logik in einer Logikliste. + * \param name Name der gesuchten Logik + * \param liste Liste der Logiken, in der gesucht wird + * \retval NULL, falls Logik nicht in \a liste + * \retval Logik, sonst. + */ +struct logik * get_logik (char * name, struct logik * liste) +{ + if (liste == NULL) return NULL; + if ( ! strcmp (name, liste->name)) return liste; + return get_logik (name, liste->next); +} + + +/** Setzt Paramater-Nummern von Abstand und Zentrum. + * Durchsucht die Logikliste \a list_of_logiken und setzt bei jedem Argument + * jeder Aktion jeder anweisung die Parameter-Nummer auf + * \li 0, wenn der Parameter-Name ,,ABSTAND`` heißt, und + * \li 1, wenn der Parameter-Name ,,ZENTRUM`` heißt. + */ +void setze_nummer_von_abstand_und_zentrum (void) +{ + struct logik * lauf; + for (lauf=list_of_logiken; lauf; lauf=lauf->next) { + struct anweisung * lauf_anw; + for (lauf_anw=lauf->anweisungsliste; lauf_anw; lauf_anw=lauf_anw->next) { + if (lauf_anw->aktion->aktions_typ == aktion_aufruf) { + struct argument_liste * lauf_arg; + for (lauf_arg=lauf_anw->aktion->u.aktion_aufruf.argument_liste; + lauf_arg; + lauf_arg=lauf_arg->next) { + switch (lauf_arg->argument.argument_typ) { + case zahl: + /* OK */ + break; + case parameter: + if ( ! strcmp (lauf_arg->argument.u.parameter.parameter_name, + "ABSTAND")) { + lauf_arg->argument.u.parameter.parameter_nummer + = 0; + } + else + if ( ! strcmp (lauf_arg->argument.u.parameter.parameter_name, + "DISTANCE")) { + lauf_arg->argument.u.parameter.parameter_nummer + = 0; + } + else + if ( ! strcmp (lauf_arg->argument.u.parameter.parameter_name, + "ZENTRUM")) { + lauf_arg->argument.u.parameter.parameter_nummer + = 1; + } + else + if ( ! strcmp (lauf_arg->argument.u.parameter.parameter_name, + "CENTER")) { + lauf_arg->argument.u.parameter.parameter_nummer + = 1; + } + else + fatal_error (39, + lauf_arg->argument.u.parameter.parameter_name, + lauf_anw->aktion->u.aktion_aufruf.name, + lauf->name); + break; + default: + fatal_error (0, __FILE__, __LINE__); + break; + } + } + } + } + } +} +/** Fügt eine neue Logik ans Ende von \a list_of_logiken an. + * Dabei wird der letzte eingelesene Auslöser verwendet. + * Die Anweisungsliste wird zunächst als Leer deklariert. + * \param name Name der Logik + * \param einstimmung Name der Einstimmnug der Logik + * \note Es wird immer die gesamte Liste durchsucht. Effektivität? + */ +void get_new_logik (char * name, char * einstimmung) +{ + struct logik * * lauf; + for (lauf= & list_of_logiken; * lauf; lauf= & (*lauf)->next) { + if ( ! strcmp (name, (*lauf)->name)) { + fatal_error(15,name); /* Logikname doppelt */ + } + } + + (* lauf) = (struct logik*) xmalloc (sizeof (struct logik)); + (* lauf) -> name = name; + (* lauf) -> ausloeser = get_last_ausloeser (); + (* lauf) -> einstimmungs_name = einstimmung; + (* lauf) -> anweisungsliste = NULL; + (* lauf) -> next = NULL; + +} + +/** Hängt die letzte eingelesene Anweisung in der letzten Logik von + * \c list_of_logiken ein. + * \note Es wird immer die gesamte Liste durchsucht. Effektivität? + * \warning Die Anweisungsliste wird nicht gelöscht. Das muss gegebenenfalls + * vorher extra getan werden. + */ +void vervollstaendige_logik (void) +{ + struct logik * lauf; + for (lauf = list_of_logiken; lauf -> next; lauf = lauf->next) { + } + + lauf -> anweisungsliste = get_last_anweisungs_liste (); +} + + /* Logiken: + überprüfen, ob Einstimmung deklariert ist + und ob die Anweisungen korrekt deklariert sind. + */ + + +void check_logik_konsistenz(void) + { + struct logik * lauf; + struct anweisung * anweisungs_lauf; + int anzahl_default_ausloeser; + for (lauf = list_of_logiken; lauf; lauf = lauf->next) { + struct umstimmung * help_umstimmung; + + check_ausloeser (lauf->ausloeser, lauf->name); + + /* Eine Logik darf nicht mit dem DEFAULT-Auslöser aufgerufen werden */ + + if (lauf->ausloeser) { + if (lauf->ausloeser->ausloeser_typ == ausloeser_default) { + fatal_error (51, lauf->name); + } + } + + if (lauf->einstimmungs_name!=NULL) { + if (parser_get_tonsystem (lauf->einstimmungs_name, list_of_tonsysteme) == NULL) { + if ((help_umstimmung=get_umstimmung (lauf->einstimmungs_name, list_of_umstimmungen)) == NULL) { + fatal_error(37,lauf->einstimmungs_name,lauf->name); + /* Einst. in Logik */ + } + else { + if (parameter_list_laenge (help_umstimmung -> parameter_liste) != 0) { + fatal_error(62,lauf->name, lauf->einstimmungs_name); + } + } + } + } + + for (anweisungs_lauf = lauf->anweisungsliste, + anzahl_default_ausloeser = 0; + anweisungs_lauf; + anweisungs_lauf = anweisungs_lauf->next) { + + check_ausloeser (anweisungs_lauf->ausloeser, lauf->name); + + if (anweisungs_lauf->ausloeser == NULL) + fatal_error (0, __FILE__, __LINE__); + else { + if (anweisungs_lauf->ausloeser->ausloeser_typ + == ausloeser_default) { + anzahl_default_ausloeser ++; + if (anzahl_default_ausloeser > 1) { + fatal_error (20, lauf -> name); + } + else { + if (anweisungs_lauf -> next !=(struct anweisung *) NULL) + compiler_warning (4, lauf -> name); + } + } + } + + check_aktionen (anweisungs_lauf -> aktion, lauf->name); + + } + } + } + +/** Wandelt eine Logik in eine Aktion um. + * Dabei werden die Namen der entsprechenden Bezeichner der Logik + * durch die zugehörigen Werte ersetzt. + * Anschließend werden lokale Harmonie, Klaviatur und Midiwerte auf die + * ersten der Logik initialisiert. + * \param the_logik Logik, die expandiert werden soll. + */ +struct do_aktion * expandiere_logik ( + struct logik * the_logik) +{ + struct do_aktion * help; + int i; + + help = (struct do_aktion*) xmalloc (sizeof (struct do_aktion)); + help -> name = the_logik -> name; + help -> aufruf_typ = aufruf_logik; + if (the_logik -> einstimmungs_name) { + struct tonsystem * help_tonsystem; + struct umstimmung * help_umstimmung; + help_tonsystem = parser_get_tonsystem (the_logik->einstimmungs_name, + list_of_tonsysteme); + if (help_tonsystem) { + help -> u.aufruf_logik.einstimmung = expandiere_tonsystem (help_tonsystem); + } + else { + help_umstimmung = get_umstimmung (the_logik->einstimmungs_name, + list_of_umstimmungen); + if (help_umstimmung) { + help -> u.aufruf_logik.einstimmung = expandiere_umstimmung (help_umstimmung, NULL); + } + else { + fatal_error (0, __FILE__, __LINE__); + help -> u.aufruf_logik.einstimmung = NULL; + } + } + } + else + help -> u.aufruf_logik.einstimmung = NULL; + + i = get_logik_nummer (the_logik -> name, list_of_logiken); + help -> u.aufruf_logik.lokal_harmonie = & first_lokal_harmonie [i]; + help -> u.aufruf_logik.lokal_keyboard = & first_lokal_keyboard [i]; + help -> u.aufruf_logik.lokal_midi = & first_lokal_midi [i]; + help -> next = NULL; + + return help; +} + diff --git a/pool/shard004/C/0098095_loadpolicy.c b/pool/shard004/C/0098095_loadpolicy.c new file mode 100644 index 0000000000000000000000000000000000000000..4e99c71e2af4c84f4021657d855fb84df4f49f47 --- /dev/null +++ b/pool/shard004/C/0098095_loadpolicy.c @@ -0,0 +1,129 @@ +/* + * + * Authors: Michael LeMay, + * George Coker, + * + * 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 + +#define USE_MMAP + +static void usage (int argCnt, const char *args[]) +{ + fprintf(stderr, "Usage: %s \n", args[0]); + exit(1); +} + +int main (int argCnt, const char *args[]) +{ + const char *polFName; + int polFd = 0; + void *polMem = NULL; + void *polMemCp = NULL; + struct stat info; + int ret; + xc_interface *xch = 0; + + if (argCnt != 2) + usage(argCnt, args); + + polFName = args[1]; + polFd = open(polFName, O_RDONLY); + if ( polFd < 0 ) + { + fprintf(stderr, "Error occurred opening policy file '%s': %s\n", + polFName, strerror(errno)); + ret = -1; + goto cleanup; + } + + ret = stat(polFName, &info); + if ( ret < 0 ) + { + fprintf(stderr, "Error occurred retrieving information about" + "policy file '%s': %s\n", polFName, strerror(errno)); + goto cleanup; + } + + polMemCp = malloc(info.st_size); + +#ifdef USE_MMAP + polMem = mmap(NULL, info.st_size, PROT_READ, MAP_SHARED, polFd, 0); + if ( !polMem ) + { + fprintf(stderr, "Error occurred mapping policy file in memory: %s\n", + strerror(errno)); + ret = -1; + goto cleanup; + } + + xch = xc_interface_open(0,0,0); + if ( !xch ) + { + fprintf(stderr, "Unable to create interface to xenctrl: %s\n", + strerror(errno)); + ret = -1; + goto cleanup; + } + + memcpy(polMemCp, polMem, info.st_size); +#else + ret = read(polFd, polMemCp, info.st_size); + if ( ret < 0 ) + { + fprintf(stderr, "Unable to read new Flask policy file: %s\n", + strerror(errno)); + goto cleanup; + } + else + { + printf("Read %d bytes from policy file '%s'.\n", ret, polFName); + } +#endif + + ret = flask_load(xch, polMemCp, info.st_size); + if ( ret < 0 ) + { + errno = -ret; + fprintf(stderr, "Unable to load new Flask policy: %s\n", + strerror(errno)); + ret = -1; + goto cleanup; + } + else + { + printf("Successfully loaded policy.\n"); + } + +done: + if ( polMemCp ) + free(polMemCp); + if ( polMem ) + { + ret = munmap(polMem, info.st_size); + if ( ret < 0 ) + fprintf(stderr, "Unable to unmap policy memory: %s\n", strerror(errno)); + } + if ( polFd ) + close(polFd); + if ( xch ) + xc_interface_close(xch); + + return ret; + +cleanup: + goto done; +} diff --git a/pool/shard004/C/0098103_smbtree.c b/pool/shard004/C/0098103_smbtree.c new file mode 100644 index 0000000000000000000000000000000000000000..8fda19f800b87ad2151067fd2f033b75cceff269 --- /dev/null +++ b/pool/shard004/C/0098103_smbtree.c @@ -0,0 +1,268 @@ +/* + Unix SMB/CIFS implementation. + Network neighbourhood browser. + + Copyright (C) Tim Potter 2000 + Copyright (C) Jelmer Vernooij 2003 + + 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 "popt_common_cmdline.h" +#include "rpc_client/cli_pipe.h" +#include "../librpc/gen_ndr/ndr_srvsvc_c.h" +#include "libsmb/libsmb.h" +#include "libsmb/namequery.h" +#include "libsmb/clirap.h" +#include "../libcli/smb/smbXcli_base.h" +#include "nameserv.h" +#include "libsmbclient.h" + +/* How low can we go? */ + +enum tree_level {LEV_WORKGROUP, LEV_SERVER, LEV_SHARE}; +static enum tree_level level = LEV_SHARE; + +static void get_auth_data_with_context_fn( + SMBCCTX *context, + const char *server, + const char *share, + char *domain, + int domain_len, + char *user, + int user_len, + char *password, + int password_len) +{ + struct user_auth_info *auth = popt_get_cmdline_auth_info(); + size_t len; + + if (auth == NULL) { + return; + } + + len = strlcpy(domain, get_cmdline_auth_info_domain(auth), domain_len); + if ((int)len >= domain_len) { + return; + } + len = strlcpy( + user, get_cmdline_auth_info_username(auth), user_len); + if ((int)len >= user_len) { + return; + } + len = strlcpy( + password, get_cmdline_auth_info_password(auth), password_len); + if ((int)len >= password_len) { + /* pointless, but what can you do... */ + return; + } +} + +/**************************************************************************** + main program +****************************************************************************/ +int main(int argc, char *argv[]) +{ + TALLOC_CTX *frame = talloc_stackframe(); + const char **argv_const = discard_const_p(const char *, argv); + struct poptOption long_options[] = { + POPT_AUTOHELP + { + .longName = "domains", + .shortName = 'D', + .argInfo = POPT_ARG_VAL, + .arg = &level, + .val = LEV_WORKGROUP, + .descrip = "List only domains (workgroups) of tree" , + }, + { + .longName = "servers", + .shortName = 'S', + .argInfo = POPT_ARG_VAL, + .arg = &level, + .val = LEV_SERVER, + .descrip = "List domains(workgroups) and servers of tree" , + }, + POPT_COMMON_SAMBA + POPT_COMMON_CREDENTIALS + POPT_TABLEEND + }; + poptContext pc; + SMBCCTX *ctx = NULL; + SMBCFILE *workgroups = NULL; + struct smbc_dirent *dirent = NULL; + bool ok; + int ret, result = 1; + int debuglevel; + + /* Initialise samba stuff */ + smb_init_locale(); + + setlinebuf(stdout); + + setup_logging(argv[0], DEBUG_STDERR); + + popt_common_credentials_set_ignore_missing_conf(); + + pc = poptGetContext("smbtree", argc, argv_const, long_options, + POPT_CONTEXT_KEEP_FIRST); + while(poptGetNextOpt(pc) != -1); + popt_burn_cmdline_password(argc, argv); + + debuglevel = DEBUGLEVEL; + + ctx = smbc_new_context(); + if (ctx == NULL) { + perror("smbc_new_context"); + goto fail; + } + ret = smbc_setConfiguration(ctx, get_dyn_CONFIGFILE()); + if (ret == -1) { + perror("smbc_setConfiguration"); + goto fail; + } + smbc_setDebug(ctx, debuglevel); + ok = smbc_setOptionProtocols(ctx, NULL, "NT1"); + if (!ok) { + perror("smbc_setOptionProtocols"); + goto fail; + } + smbc_setFunctionAuthDataWithContext( + ctx, get_auth_data_with_context_fn); + + ok = smbc_init_context(ctx); + if (!ok) { + perror("smbc_init_context"); + goto fail; + } + + workgroups = smbc_getFunctionOpendir(ctx)(ctx, "smb://"); + if (workgroups == NULL) { + perror("smbc_opendir"); + goto fail; + } + + while ((dirent = smbc_getFunctionReaddir(ctx)(ctx, workgroups)) + != NULL) { + char *url = NULL; + SMBCFILE *servers = NULL; + + if (dirent->smbc_type != SMBC_WORKGROUP) { + continue; + } + + printf("%s\n", dirent->name); + + if (level == LEV_WORKGROUP) { + continue; + } + + url = talloc_asprintf( + talloc_tos(), "smb://%s/", dirent->name); + if (url == NULL) { + perror("talloc_asprintf"); + goto fail; + } + + servers = smbc_getFunctionOpendir(ctx)(ctx, url); + if (servers == NULL) { + perror("smbc_opendir"); + goto fail; + } + TALLOC_FREE(url); + + while ((dirent = smbc_getFunctionReaddir(ctx)(ctx, servers)) + != NULL) { + SMBCFILE *shares = NULL; + char *servername = NULL; + + if (dirent->smbc_type != SMBC_SERVER) { + continue; + } + + printf("\t\\\\%-15s\t\t%s\n", + dirent->name, + dirent->comment); + + if (level == LEV_SERVER) { + continue; + } + + /* + * The subsequent readdir for shares will + * overwrite the "server" readdir + */ + servername = talloc_strdup(talloc_tos(), dirent->name); + if (servername == NULL) { + continue; + } + + url = talloc_asprintf( + talloc_tos(), "smb://%s/", servername); + if (url == NULL) { + perror("talloc_asprintf"); + goto fail; + } + + shares = smbc_getFunctionOpendir(ctx)(ctx, url); + if (shares == NULL) { + perror("smbc_opendir"); + goto fail; + } + + while ((dirent = smbc_getFunctionReaddir( + ctx)(ctx, shares)) + != NULL) { + printf("\t\t\\\\%s\\%-15s\t%s\n", + servername, + dirent->name, + dirent->comment); + } + + ret = smbc_getFunctionClosedir(ctx)(ctx, shares); + if (ret == -1) { + perror("smbc_closedir"); + goto fail; + } + + TALLOC_FREE(servername); + TALLOC_FREE(url); + } + + ret = smbc_getFunctionClosedir(ctx)(ctx, servers); + if (ret == -1) { + perror("smbc_closedir"); + goto fail; + } + } + + ret = smbc_getFunctionClosedir(ctx)(ctx, workgroups); + if (ret == -1) { + perror("smbc_closedir"); + goto fail; + } + + popt_free_cmdline_auth_info(); + + result = 0; +fail: + if (ctx != NULL) { + smbc_free_context(ctx, 0); + ctx = NULL; + } + poptFreeContext(pc); + TALLOC_FREE(frame); + return result; +} diff --git a/pool/shard004/C/0098105_task2.c b/pool/shard004/C/0098105_task2.c new file mode 100644 index 0000000000000000000000000000000000000000..4c7a986cdff06b8452566f743501d0aba4fe5806 --- /dev/null +++ b/pool/shard004/C/0098105_task2.c @@ -0,0 +1,46 @@ +#include + +void next_generation(int *current, int *next, int length) +{ + int i; + for(i=1;i20); + + for(i=0;i +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#define SYNCDELAY() SYNCDELAY4; + +volatile bit dosud; +bit on; +WORD count; + + +void main() { + + REVCTL = 0; // not using advanced endpoint controls + + dosud=FALSE; + on=FALSE; + + REVCTL = 0x03; // DYN_OUT=1, ENH_PKT=1 + + RENUMERATE_UNCOND(); + + + SETCPUFREQ(CLK_48M); + sio0_init(57600); // needed for printf on sio0 + + + USE_USB_INTS(); + + ENABLE_SUDAV(); + ENABLE_USBRESET(); + ENABLE_HISPEED(); + + EA=1; + + + while(TRUE) { + + //printf ( "sud is %d\n" , dosud ); + if (dosud) { + handle_setupdata(); + dosud=FALSE; + } + + } + + +} + + +#define VC_EEPROM 0xb1 + +BOOL handle_vendorcommand(BYTE cmd) { + WORD addr=SETUP_VALUE(),len=SETUP_LENGTH(); + printf ( "Handle Vendor Command %02x, addr %d, len %d\n" , cmd, addr, len ); + switch (cmd) { + case VC_EEPROM: + { + // wait for ep0 not busy + switch (SETUP_TYPE) { + case 0xc0: + while (len) { // still have bytes to read + BYTE cur_read = len > 64 ? 64 : len; // can't read more than 64 bytes at a time + while (EP0CS&bmEPBUSY); // can't do this until EP0 is ready + eeprom_read(0x51, addr, cur_read, EP0BUF ); + EP0BCH=0; + SYNCDELAY(); + EP0BCL=cur_read; + len -= cur_read; + addr += cur_read; + } + break; + case 0x40: + while (len) { + BYTE cur_write, c; +// printf ( "Len More Bytes %d\n" , len ); + EP0BCL = 0; // allow pc transfer in + while(EP0CS & bmEPBUSY); // wait + cur_write=EP0BCL; +// printf ( "Writing %d Bytes to %d..\n", cur_write, addr ); + if ( !eeprom_write(0x51, addr, cur_write, EP0BUF ) ) return FALSE; + addr += cur_write; + len -= cur_write; + } + break; + default: + return FALSE; // bad type + } + + printf ( "All OK\n" ); + return TRUE; + } + } + return FALSE; +} + + +// set *alt_ifc to the current alt interface for ifc +BOOL handle_get_interface(BYTE ifc, BYTE* alt_ifc) { + *alt_ifc=0; + return TRUE; +} +// return TRUE if you set the interface requested +// NOTE this function should reconfigure and reset the endpoints +// according to the interface descriptors you provided. +BOOL handle_set_interface(BYTE ifc,BYTE alt_ifc) { + //return ifc==0&&alt_ifc==0; + printf ( "Host wants to set interface: %d\n", alt_ifc ); + + return TRUE; +} +// handle getting and setting the configuration +// 0 is the default. If you support more than one config +// keep track of the config number and return the correct number +// config numbers are set int the dscr file. +volatile BYTE config=1; +BYTE handle_get_configuration() { + return config; +} +// return TRUE if you handle this request +// NOTE changing config requires the device to reset all the endpoints +BOOL handle_set_configuration(BYTE cfg) { + printf ( "host wants config: %d\n" , cfg ); + config=cfg; + return TRUE; +} + + +void sudav_isr() interrupt SUDAV_ISR { + dosud=TRUE; + CLEAR_SUDAV(); +} + +void usbreset_isr() interrupt USBRESET_ISR { + handle_hispeed(FALSE); + CLEAR_USBRESET(); +} +void hispeed_isr() interrupt HISPEED_ISR { + handle_hispeed(TRUE); + CLEAR_HISPEED(); +} + diff --git a/pool/shard004/C/0098121_atomic_reference.c b/pool/shard004/C/0098121_atomic_reference.c new file mode 100644 index 0000000000000000000000000000000000000000..fbbbca1096c2ac5c1297285ba1bbee58eaa53735 --- /dev/null +++ b/pool/shard004/C/0098121_atomic_reference.c @@ -0,0 +1,119 @@ +// 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 +#if defined(__sun) +#include +#endif + +#ifdef HAVE_LIBKERN_OSATOMIC_H +#include +#endif + +static void ir_mark(void *value) { + rb_gc_mark_maybe((VALUE) value); +} + +static VALUE ir_alloc(VALUE klass) { + return rb_data_object_alloc(klass, (void *) Qnil, ir_mark, NULL); +} + +static VALUE ir_initialize(int argc, VALUE* argv, VALUE self) { + VALUE value = Qnil; + if (rb_scan_args(argc, argv, "01", &value) == 1) { + value = argv[0]; + } + DATA_PTR(self) = (void *) value; + return Qnil; +} + +static VALUE ir_get(VALUE self) { +#if HAVE_GCC_SYNC + __sync_synchronize(); +#elif defined _MSC_VER + MemoryBarrier(); +#elif __ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__ >= 1050 + OSMemoryBarrier(); +#endif + return (VALUE) DATA_PTR(self); +} + +static VALUE ir_set(VALUE self, VALUE new_value) { + DATA_PTR(self) = (void *) new_value; +#if HAVE_GCC_SYNC + __sync_synchronize(); +#elif defined _MSC_VER + MemoryBarrier(); +#elif __ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__ >= 1050 + OSMemoryBarrier(); +#endif + return new_value; +} + +static VALUE ir_get_and_set(VALUE self, VALUE new_value) { + VALUE old_value = ir_get(self); + ir_set(self, new_value); + return old_value; +} + +static VALUE ir_compare_and_set(volatile VALUE self, VALUE expect_value, VALUE new_value) { +#if __ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__ >= 1050 + if (OSAtomicCompareAndSwap64(expect_value, new_value, &DATA_PTR(self))) { + return Qtrue; + } +#elif defined(__sun) +/* Assuming VALUE is uintptr_t */ +/* Based on the definition of uintptr_t from /usr/include/sys/int_types.h */ +#if defined(_LP64) || defined(_I32LPx) + /* 64-bit: uintptr_t === unsigned long */ + if (atomic_cas_ulong((uintptr_t *) &DATA_PTR(self), expect_value, new_value)) { + return Qtrue; + } +#else + /* 32-bit: uintptr_t === unsigned int */ + if (atomic_cas_uint((uintptr_t *) &DATA_PTR(self), expect_value, new_value)) { + return Qtrue; + } +#endif +#elif defined _MSC_VER && defined _M_AMD64 + if (InterlockedCompareExchange64((LONGLONG*)&DATA_PTR(self), new_value, expect_value)) { + return Qtrue; + } +#elif defined _MSC_VER && defined _M_IX86 + if (InterlockedCompareExchange((LONG*)&DATA_PTR(self), new_value, expect_value)) { + return Qtrue; + } +#else + if (__sync_bool_compare_and_swap(&DATA_PTR(self), expect_value, new_value)) { + return Qtrue; + } +#endif + return Qfalse; +} + +void Init_atomic_reference() { + VALUE cAtomic; + + cAtomic = rb_define_class_under(rb_cObject, "Atomic", rb_cObject); + + rb_define_alloc_func(cAtomic, ir_alloc); + + rb_define_method(cAtomic, "initialize", ir_initialize, -1); + rb_define_method(cAtomic, "get", ir_get, 0); + rb_define_method(cAtomic, "value", ir_get, 0); + rb_define_method(cAtomic, "set", ir_set, 1); + rb_define_method(cAtomic, "value=", ir_set, 1); + rb_define_method(cAtomic, "get_and_set", ir_get_and_set, 1); + rb_define_method(cAtomic, "swap", ir_get_and_set, 1); + rb_define_method(cAtomic, "compare_and_set", ir_compare_and_set, 2); + rb_define_method(cAtomic, "compare_and_swap", ir_compare_and_set, 2); +} diff --git a/pool/shard004/C/0098122_routine-gwv-1.c b/pool/shard004/C/0098122_routine-gwv-1.c new file mode 100644 index 0000000000000000000000000000000000000000..8fc4cb5f66c4c4e36d770e9fe1cd8e62e9f8db44 --- /dev/null +++ b/pool/shard004/C/0098122_routine-gwv-1.c @@ -0,0 +1,66 @@ +/* { dg-do run } */ +/* { dg-additional-options "-O2" } */ + +#include + +#define N (32*32*32+17) + +#pragma acc routine gang +void __attribute__ ((noinline)) gang (int ary[N]) +{ +#pragma acc loop gang worker vector + for (unsigned ix = 0; ix < N; ix++) + { + if (__builtin_acc_on_device (5)) + { + int g = 0, w = 0, v = 0; + + __asm__ volatile ("mov.u32 %0,%%ctaid.x;" : "=r" (g)); + __asm__ volatile ("mov.u32 %0,%%tid.y;" : "=r" (w)); + __asm__ volatile ("mov.u32 %0,%%tid.x;" : "=r" (v)); + ary[ix] = (g << 16) | (w << 8) | v; + } + else + ary[ix] = ix; + } +} + +int main () +{ + int ary[N]; + int ix; + int exit = 0; + int ondev = 0; + + for (ix = 0; ix < N;ix++) + ary[ix] = -1; + +#pragma acc parallel num_gangs(32) num_workers(32) vector_length(32) copy(ary) copy(ondev) + { + ondev = __builtin_acc_on_device (5); + gang (ary); + } + + for (ix = 0; ix < N; ix++) + { + int expected = ix; + if(ondev) + { + int chunk_size = (N + 32*32*32 - 1) / (32*32*32); + + int g = ix / (chunk_size * 32 * 32); + int w = ix / 32 % 32; + int v = ix % 32; + + expected = (g << 16) | (w << 8) | v; + } + + if (ary[ix] != expected) + { + exit = 1; + printf ("ary[%d]=%x expected %x\n", ix, ary[ix], expected); + } + } + + return exit; +} diff --git a/pool/shard004/C/0098128_su.c b/pool/shard004/C/0098128_su.c new file mode 100644 index 0000000000000000000000000000000000000000..51215a3b0f3c83e24ce11c84f001d43f4e790beb --- /dev/null +++ b/pool/shard004/C/0098128_su.c @@ -0,0 +1,38 @@ +/* ircd-micro, core/su -- ENCAP SU command + Copyright (C) 2014 Alex Iadicicco + + This file is protected under the terms contained + in the COPYING file in the project root */ + +#include "ircd.h" + +static int c_es_su(u_sourceinfo *si, u_msg *msg) +{ + u_user *u; + char *user = msg->argv[2]; + char *acct = msg->argc > 3 ? msg->argv[3] : ""; + + if (!(u = u_user_by_uid(user))) { + u_log(LG_WARN, "%I tried to ENCAP SU nonexistent %s", si, user); + return 0; + } + + u_strlcpy(u->acct, acct, MAXACCOUNT+1); + + if (*acct) { + u_log(LG_VERBOSE, "%U logged in to %s", u, acct); + } else { + u_log(LG_VERBOSE, "%U logged out", u); + } + + return 0; +} + +static u_cmd su_cmdtab[] = { + { "SU", SRC_ENCAP_SERVER, c_es_su, 3 }, + { } +}; + +MICRO_MODULE_V1( + "core/su", "Alex Iadicicco", "ENCAP SU command", + NULL, NULL, su_cmdtab); diff --git a/pool/shard004/C/0098149_timers.c b/pool/shard004/C/0098149_timers.c new file mode 100644 index 0000000000000000000000000000000000000000..f608f29a2adebe6e0815b3f66216f7b8857f5b5c --- /dev/null +++ b/pool/shard004/C/0098149_timers.c @@ -0,0 +1,44 @@ +#include "RCCE.h" +#ifdef _OPENMP +#include "omp.h" +#endif +#include "timers.h" +#define elapsed(n) elapsed[n-1] +#define start(n) start[n-1] + +void timer_clear(int *np){ + + int n = *np; + elapsed(n) = 0.0; + return; +} + + +void timer_start(int *np) { + + int n = *np; + + start(n) = RCCE_wtime(); + + return; +} + +void timer_stop(int *np) { + + int n = *np; + + double t, now; + now = RCCE_wtime(); + t = now - start(n); + elapsed(n) = elapsed(n) + t; + + return; +} + + +double timer_read(int *np) { + + int n = *np; + return( elapsed(n)); +} + diff --git a/pool/shard004/C/0098153_main.c b/pool/shard004/C/0098153_main.c new file mode 100644 index 0000000000000000000000000000000000000000..7948c0b8713ea9b63773fca08585d725139b4a3f --- /dev/null +++ b/pool/shard004/C/0098153_main.c @@ -0,0 +1,63 @@ +#include "lolevel.h" +#include "platform.h" +#include "core.h" +#include "keyboard.h" + +extern long link_bss_start; +extern long link_bss_end; +extern void boot(); + +void startup() +{ + long *bss = &link_bss_start; + + // sanity check (pointless with automemiso) + if ((long)&link_bss_end > (MEMISOSTART + MEMISOSIZE)){ + started(); + shutdown(); + } + // initialize .bss senment + while (bss<&link_bss_end) + *bss++ = 0; + boot(); +} + +// Focus length table in firmware @ 0xfff4ad54 +#define NUM_FL 127 // 127 zoom steps +#define NUM_DATA 2 // 2 words each entry, FL in MM*1000, 100 +extern int focus_len_table[NUM_FL*NUM_DATA]; + +// Conversion factor lens FL --> 35mm equiv +// lens 35mm CF +// ---- ---- -- +// 4.3 24 ( 24/4.3) * 43 = 240 (min FL) +// 129 720 (720/129) * 43 = 240 (max FL) +#define CF_EFL 240 +#define CF_EFL_DIV 43 + +const int zoom_points = NUM_FL; + +int get_effective_focal_length(int zp) { + return (CF_EFL*get_focal_length(zp))/CF_EFL_DIV; +} + +int get_focal_length(int zp) { + if (zp < 0) zp = 0; + else if (zp >= NUM_FL) zp = NUM_FL-1; + return focus_len_table[zp*NUM_DATA]; +} + +int get_zoom_x(int zp) { + return get_focal_length(zp)*10/focus_len_table[0]; +} + +// uses NB-11L, should be similar to other single cell li-ion +long get_vbatt_min() +{ + return 3250; +} + +long get_vbatt_max() +{ + return 4000; +} diff --git a/pool/shard004/C/0098155_e_scale.c b/pool/shard004/C/0098155_e_scale.c new file mode 100644 index 0000000000000000000000000000000000000000..1ec285d7c55f19e065c1ad94a7c5f2798e98b110 --- /dev/null +++ b/pool/shard004/C/0098155_e_scale.c @@ -0,0 +1,59 @@ +#include "e.h" + +E_API double e_scale = 1.0; + +EINTERN int +e_scale_init(void) +{ + e_scale_update(); + return 1; +} + +EINTERN int +e_scale_shutdown(void) +{ + return 1; +} + +E_API void +e_scale_update(void) +{ + char buf[128]; + + if (e_config->scale.use_dpi) + { +#ifndef HAVE_WAYLAND_ONLY + if (e_comp->comp_type == E_PIXMAP_TYPE_X) + e_scale = (double)ecore_x_dpi_get() / (double)e_config->scale.base_dpi; +#endif +#ifdef HAVE_WAYLAND + if (e_comp->comp_type == E_PIXMAP_TYPE_WL) + { + int xdpi = 0, ydpi = 0; + + ecore_evas_screen_dpi_get(e_comp->ee, &xdpi, &ydpi); + if (xdpi == 0) xdpi = 75; + if (ydpi == 0) ydpi = 75; + e_scale = ((double)(xdpi + ydpi) / 2.0) / + (double)e_config->scale.base_dpi; + } +#endif + if (e_scale > e_config->scale.max) e_scale = e_config->scale.max; + else if (e_scale < e_config->scale.min) + e_scale = e_config->scale.min; + } + else if (e_config->scale.use_custom) + { + e_scale = e_config->scale.factor; + if (e_scale > e_config->scale.max) e_scale = e_config->scale.max; + else if (e_scale < e_config->scale.min) + e_scale = e_config->scale.min; + } + elm_config_scale_set(e_scale); + elm_config_all_flush(); + edje_scale_set(e_scale); + snprintf(buf, sizeof(buf), "%1.3f", e_scale); + e_util_env_set("E_SCALE", buf); + e_hints_scale_update(); +} + diff --git a/pool/shard004/C/0098161_hyperv_testdev.c b/pool/shard004/C/0098161_hyperv_testdev.c new file mode 100644 index 0000000000000000000000000000000000000000..1883fd7f20e2c467ca369b50d00d4acc1db1eafe --- /dev/null +++ b/pool/shard004/C/0098161_hyperv_testdev.c @@ -0,0 +1,168 @@ +/* + * QEMU KVM Hyper-V test device to support Hyper-V kvm-unit-tests + * + * Copyright (C) 2015 Andrey Smetanin + * + * Authors: + * Andrey Smetanin + * + * 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 "qemu/osdep.h" +#include "hw/hw.h" +#include "hw/qdev.h" +#include "hw/isa/isa.h" +#include "sysemu/kvm.h" +#include "linux/kvm.h" +#include "target-i386/hyperv.h" +#include "kvm_i386.h" + +#define HV_TEST_DEV_MAX_SINT_ROUTES 64 + +struct HypervTestDev { + ISADevice parent_obj; + MemoryRegion sint_control; + HvSintRoute *sint_route[HV_TEST_DEV_MAX_SINT_ROUTES]; +}; +typedef struct HypervTestDev HypervTestDev; + +#define TYPE_HYPERV_TEST_DEV "hyperv-testdev" +#define HYPERV_TEST_DEV(obj) \ + OBJECT_CHECK(HypervTestDev, (obj), TYPE_HYPERV_TEST_DEV) + +enum { + HV_TEST_DEV_SINT_ROUTE_CREATE = 1, + HV_TEST_DEV_SINT_ROUTE_DESTROY, + HV_TEST_DEV_SINT_ROUTE_SET_SINT +}; + +static int alloc_sint_route_index(HypervTestDev *dev) +{ + int i; + + for (i = 0; i < ARRAY_SIZE(dev->sint_route); i++) { + if (dev->sint_route[i] == NULL) { + return i; + } + } + return -1; +} + +static void free_sint_route_index(HypervTestDev *dev, int i) +{ + assert(i >= 0 && i < ARRAY_SIZE(dev->sint_route)); + dev->sint_route[i] = NULL; +} + +static int find_sint_route_index(HypervTestDev *dev, uint32_t vcpu_id, + uint32_t sint) +{ + HvSintRoute *sint_route; + int i; + + for (i = 0; i < ARRAY_SIZE(dev->sint_route); i++) { + sint_route = dev->sint_route[i]; + if (sint_route && sint_route->vcpu_id == vcpu_id && + sint_route->sint == sint) { + return i; + } + } + return -1; +} + +static void hv_synic_test_dev_control(HypervTestDev *dev, uint32_t ctl, + uint32_t vcpu_id, uint32_t sint) +{ + int i; + HvSintRoute *sint_route; + + switch (ctl) { + case HV_TEST_DEV_SINT_ROUTE_CREATE: + i = alloc_sint_route_index(dev); + assert(i >= 0); + sint_route = kvm_hv_sint_route_create(vcpu_id, sint, NULL); + assert(sint_route); + dev->sint_route[i] = sint_route; + break; + case HV_TEST_DEV_SINT_ROUTE_DESTROY: + i = find_sint_route_index(dev, vcpu_id, sint); + assert(i >= 0); + sint_route = dev->sint_route[i]; + kvm_hv_sint_route_destroy(sint_route); + free_sint_route_index(dev, i); + break; + case HV_TEST_DEV_SINT_ROUTE_SET_SINT: + i = find_sint_route_index(dev, vcpu_id, sint); + assert(i >= 0); + sint_route = dev->sint_route[i]; + kvm_hv_sint_route_set_sint(sint_route); + break; + default: + break; + } +} + +static void hv_test_dev_control(void *opaque, hwaddr addr, uint64_t data, + uint32_t len) +{ + HypervTestDev *dev = HYPERV_TEST_DEV(opaque); + uint8_t ctl; + + ctl = (data >> 16ULL) & 0xFF; + switch (ctl) { + case HV_TEST_DEV_SINT_ROUTE_CREATE: + case HV_TEST_DEV_SINT_ROUTE_DESTROY: + case HV_TEST_DEV_SINT_ROUTE_SET_SINT: { + uint8_t sint = data & 0xFF; + uint8_t vcpu_id = (data >> 8ULL) & 0xFF; + hv_synic_test_dev_control(dev, ctl, vcpu_id, sint); + break; + } + default: + break; + } +} + +static const MemoryRegionOps synic_test_sint_ops = { + .write = hv_test_dev_control, + .valid.min_access_size = 4, + .valid.max_access_size = 4, + .endianness = DEVICE_LITTLE_ENDIAN, +}; + +static void hv_test_dev_realizefn(DeviceState *d, Error **errp) +{ + ISADevice *isa = ISA_DEVICE(d); + HypervTestDev *dev = HYPERV_TEST_DEV(d); + MemoryRegion *io = isa_address_space_io(isa); + + memset(dev->sint_route, 0, sizeof(dev->sint_route)); + memory_region_init_io(&dev->sint_control, OBJECT(dev), + &synic_test_sint_ops, dev, + "hyperv-testdev-ctl", 4); + memory_region_add_subregion(io, 0x3000, &dev->sint_control); +} + +static void hv_test_dev_class_init(ObjectClass *klass, void *data) +{ + DeviceClass *dc = DEVICE_CLASS(klass); + + set_bit(DEVICE_CATEGORY_MISC, dc->categories); + dc->realize = hv_test_dev_realizefn; +} + +static const TypeInfo hv_test_dev_info = { + .name = TYPE_HYPERV_TEST_DEV, + .parent = TYPE_ISA_DEVICE, + .instance_size = sizeof(HypervTestDev), + .class_init = hv_test_dev_class_init, +}; + +static void hv_test_dev_register_types(void) +{ + type_register_static(&hv_test_dev_info); +} +type_init(hv_test_dev_register_types); diff --git a/pool/shard004/C/0098168_pem_pkey.c b/pool/shard004/C/0098168_pem_pkey.c new file mode 100644 index 0000000000000000000000000000000000000000..a1453e9e7a796c68fa0e016072b0cc8f000e51d3 --- /dev/null +++ b/pool/shard004/C/0098168_pem_pkey.c @@ -0,0 +1,242 @@ +/* crypto/pem/pem_pkey.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.] + */ + +#include +#include "cryptlib.h" +#include +#include +#include +#include +#include +#include +#include +#ifndef OPENSSL_NO_ENGINE +#include +#endif +#include "asn1_locl.h" + +int pem_check_suffix(const char *pem_str, const char *suffix); + +EVP_PKEY *PEM_read_bio_PrivateKey(BIO *bp, EVP_PKEY **x, pem_password_cb *cb, void *u) + { + char *nm=NULL; + const unsigned char *p=NULL; + unsigned char *data=NULL; + long len; + int slen; + EVP_PKEY *ret=NULL; + + if (!PEM_bytes_read_bio(&data, &len, &nm, PEM_STRING_EVP_PKEY, bp, cb, u)) + return NULL; + p = data; + + if (strcmp(nm,PEM_STRING_PKCS8INF) == 0) { + PKCS8_PRIV_KEY_INFO *p8inf; + p8inf=d2i_PKCS8_PRIV_KEY_INFO(NULL, &p, len); + if(!p8inf) goto p8err; + ret = EVP_PKCS82PKEY(p8inf); + if(x) { + if(*x) EVP_PKEY_free((EVP_PKEY *)*x); + *x = ret; + } + PKCS8_PRIV_KEY_INFO_free(p8inf); + } else if (strcmp(nm,PEM_STRING_PKCS8) == 0) { + PKCS8_PRIV_KEY_INFO *p8inf; + X509_SIG *p8; + int klen; + char psbuf[PEM_BUFSIZE]; + p8 = d2i_X509_SIG(NULL, &p, len); + if(!p8) goto p8err; + if (cb) klen=cb(psbuf,PEM_BUFSIZE,0,u); + else klen=PEM_def_callback(psbuf,PEM_BUFSIZE,0,u); + if (klen <= 0) { + PEMerr(PEM_F_PEM_READ_BIO_PRIVATEKEY, + PEM_R_BAD_PASSWORD_READ); + X509_SIG_free(p8); + goto err; + } + p8inf = PKCS8_decrypt(p8, psbuf, klen); + X509_SIG_free(p8); + if(!p8inf) goto p8err; + ret = EVP_PKCS82PKEY(p8inf); + if(x) { + if(*x) EVP_PKEY_free((EVP_PKEY *)*x); + *x = ret; + } + PKCS8_PRIV_KEY_INFO_free(p8inf); + } else if ((slen = pem_check_suffix(nm, "PRIVATE KEY")) > 0) + { + const EVP_PKEY_ASN1_METHOD *ameth; + ameth = EVP_PKEY_asn1_find_str(NULL, nm, slen); + if (!ameth || !ameth->old_priv_decode) + goto p8err; + ret=d2i_PrivateKey(ameth->pkey_id,x,&p,len); + } +p8err: + if (ret == NULL) + PEMerr(PEM_F_PEM_READ_BIO_PRIVATEKEY,ERR_R_ASN1_LIB); +err: + OPENSSL_free(nm); + OPENSSL_cleanse(data, len); + OPENSSL_free(data); + return(ret); + } + +int PEM_write_bio_PrivateKey(BIO *bp, EVP_PKEY *x, const EVP_CIPHER *enc, + unsigned char *kstr, int klen, + pem_password_cb *cb, void *u) + { + char pem_str[80]; + if (!x->ameth || x->ameth->priv_encode) + return PEM_write_bio_PKCS8PrivateKey(bp, x, enc, + (char *)kstr, klen, + cb, u); + + BIO_snprintf(pem_str, 80, "%s PRIVATE KEY", x->ameth->pem_str); + return PEM_ASN1_write_bio((i2d_of_void *)i2d_PrivateKey, + pem_str,bp,x,enc,kstr,klen,cb,u); + } + +EVP_PKEY *PEM_read_bio_Parameters(BIO *bp, EVP_PKEY **x) + { + char *nm=NULL; + const unsigned char *p=NULL; + unsigned char *data=NULL; + long len; + int slen; + EVP_PKEY *ret=NULL; + + if (!PEM_bytes_read_bio(&data, &len, &nm, PEM_STRING_PARAMETERS, + bp, 0, NULL)) + return NULL; + p = data; + + if ((slen = pem_check_suffix(nm, "PARAMETERS")) > 0) + { + ret = EVP_PKEY_new(); + if (!ret) + goto err; + if (!EVP_PKEY_set_type_str(ret, nm, slen) + || !ret->ameth->param_decode + || !ret->ameth->param_decode(ret, &p, len)) + { + EVP_PKEY_free(ret); + ret = NULL; + goto err; + } + if(x) + { + if(*x) EVP_PKEY_free((EVP_PKEY *)*x); + *x = ret; + } + } +err: + if (ret == NULL) + PEMerr(PEM_F_PEM_READ_BIO_PARAMETERS,ERR_R_ASN1_LIB); + OPENSSL_free(nm); + OPENSSL_free(data); + return(ret); + } + +int PEM_write_bio_Parameters(BIO *bp, EVP_PKEY *x) + { + char pem_str[80]; + if (!x->ameth || !x->ameth->param_encode) + return 0; + + BIO_snprintf(pem_str, 80, "%s PARAMETERS", x->ameth->pem_str); + return PEM_ASN1_write_bio( + (i2d_of_void *)x->ameth->param_encode, + pem_str,bp,x,NULL,NULL,0,0,NULL); + } + +#ifndef OPENSSL_NO_FP_API +EVP_PKEY *PEM_read_PrivateKey(FILE *fp, EVP_PKEY **x, pem_password_cb *cb, void *u) + { + BIO *b; + EVP_PKEY *ret; + + if ((b=BIO_new(BIO_s_file())) == NULL) + { + PEMerr(PEM_F_PEM_READ_PRIVATEKEY,ERR_R_BUF_LIB); + return(0); + } + BIO_set_fp(b,fp,BIO_NOCLOSE); + ret=PEM_read_bio_PrivateKey(b,x,cb,u); + BIO_free(b); + return(ret); + } + +int PEM_write_PrivateKey(FILE *fp, EVP_PKEY *x, const EVP_CIPHER *enc, + unsigned char *kstr, int klen, + pem_password_cb *cb, void *u) + { + BIO *b; + int ret; + + if ((b=BIO_new_fp(fp, BIO_NOCLOSE)) == NULL) + { + PEMerr(PEM_F_PEM_WRITE_PRIVATEKEY,ERR_R_BUF_LIB); + return 0; + } + ret=PEM_write_bio_PrivateKey(b, x, enc, kstr, klen, cb, u); + BIO_free(b); + return ret; + } + +#endif diff --git a/pool/shard004/C/0098172_ab-totient-omp-9.c b/pool/shard004/C/0098172_ab-totient-omp-9.c new file mode 100644 index 0000000000000000000000000000000000000000..dcc1086139a8b658ff78149bec9e04576013f380 --- /dev/null +++ b/pool/shard004/C/0098172_ab-totient-omp-9.c @@ -0,0 +1,68 @@ +// Distributed and parallel technologies, Andrew Beveridge, 03/03/2014 +// To Compile: gcc -Wall -O -o ab-totient-omp -fopenmp ab-totient-omp.c +// To Run / Time: /usr/bin/time -v ./ab-totient-omp range_start range_end + +#include +#include + +/* When input is a prime number, the totient is simply the prime number - 1. Totient is always even (except for 1). + If n is a positive integer, then φ(n) is the number of integers k in the range 1 ≤ k ≤ n for which gcd(n, k) = 1 */ +long getTotient (long number) { + long result = number; + + // Check every prime number below the square root for divisibility + if(number % 2 == 0){ + result -= result / 2; + do + number /= 2; + while(number %2 == 0); + } + + // Primitive replacement for a list of primes, looping through every odd number + long prime; + for(prime = 3; prime * prime <= number; prime += 2){ + if(number %prime == 0){ + result -= result / prime; + do + number /= prime; + while(number % prime == 0); + } + } + + // Last common factor + if(number > 1) + result -= result / number; + + // Return the result. + return result; +} + +// Main method. +int main(int argc, char ** argv) { + // Load inputs + long lower, upper; + sscanf(argv[1], "%ld", &lower); + sscanf(argv[2], "%ld", &upper); + + int i; + long result = 0.0; + + // We know the answer if it's 1; no need to execute the function + if(lower == 1) { + result = 1.0; + lower = 2; + } + + #pragma omp parallel for default(shared) private(i) schedule(auto) reduction(+:result) num_threads(9) + + // Sum all totients in the specified range + for (i = lower; i <= upper; i++) { + result = result + getTotient(i); + } + + // Print the result + printf("Sum of Totients between [%ld..%ld] is %ld \n", lower, upper, result); + + // A-OK! + return 0; +} diff --git a/pool/shard004/C/0098173_CFCTestFileSpec.c b/pool/shard004/C/0098173_CFCTestFileSpec.c new file mode 100644 index 0000000000000000000000000000000000000000..d38c075c17ef61fbbab539988cb4289c347f4ceb --- /dev/null +++ b/pool/shard004/C/0098173_CFCTestFileSpec.c @@ -0,0 +1,53 @@ +/* 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 CFC_USE_TEST_MACROS +#include "CFCBase.h" +#include "CFCFileSpec.h" +#include "CFCTest.h" + +static void +S_run_tests(CFCTest *test); + +const CFCTestBatch CFCTEST_BATCH_FILE_SPEC = { + "Clownfish::CFC::Model::FileSpec", + 4, + S_run_tests +}; + +static void +S_run_tests(CFCTest *test) { + { + CFCFileSpec *file_spec + = CFCFileSpec_new("Clownfish/_include", "Stuff/Thing", ".cfh", 0); + STR_EQ(test, CFCFileSpec_get_source_dir(file_spec), + "Clownfish/_include", "get_source_dir"); + STR_EQ(test, CFCFileSpec_get_path_part(file_spec), + "Stuff/Thing", "get_path_part"); + OK(test, !CFCFileSpec_included(file_spec), "not included"); + + CFCBase_decref((CFCBase*)file_spec); + } + + { + CFCFileSpec *file_spec + = CFCFileSpec_new("Clownfish/_include", "Stuff/Thing", ".cfh", 1); + OK(test, CFCFileSpec_included(file_spec), "included"); + + CFCBase_decref((CFCBase*)file_spec); + } +} + diff --git a/pool/shard004/C/0098180_f64_div.c b/pool/shard004/C/0098180_f64_div.c new file mode 100644 index 0000000000000000000000000000000000000000..9bc72b37d9251df173f36cc20de654759fdce12d --- /dev/null +++ b/pool/shard004/C/0098180_f64_div.c @@ -0,0 +1,104 @@ + +#include +#include +#include "platform.h" +#include "primitives.h" +#include "internals.h" +#include "specialize.h" +#include "softfloat.h" + +float64_t f64_div( float64_t a, float64_t b ) +{ + union ui64_f64 uA; + uint_fast64_t uiA; + bool signA; + int_fast16_t expA; + uint_fast64_t sigA; + union ui64_f64 uB; + uint_fast64_t uiB; + bool signB; + int_fast16_t expB; + uint_fast64_t sigB; + bool signZ; + struct exp16_sig64 normExpSig; + int_fast16_t expZ; + uint_fast64_t sigZ; + struct uint128 term, rem; + uint_fast64_t uiZ; + union ui64_f64 uZ; + + uA.f = a; + uiA = uA.ui; + signA = signF64UI( uiA ); + expA = expF64UI( uiA ); + sigA = fracF64UI( uiA ); + uB.f = b; + uiB = uB.ui; + signB = signF64UI( uiB ); + expB = expF64UI( uiB ); + sigB = fracF64UI( uiB ); + signZ = signA ^ signB; + if ( expA == 0x7FF ) { + if ( sigA ) goto propagateNaN; + if ( expB == 0x7FF ) { + if ( sigB ) goto propagateNaN; + goto invalid; + } + goto infinity; + } + if ( expB == 0x7FF ) { + if ( sigB ) goto propagateNaN; + goto zero; + } + if ( ! expB ) { + if ( ! sigB ) { + if ( ! ( expA | sigA ) ) goto invalid; + softfloat_raiseFlags( softfloat_flag_infinity ); + goto infinity; + } + normExpSig = softfloat_normSubnormalF64Sig( sigB ); + expB = normExpSig.exp; + sigB = normExpSig.sig; + } + if ( ! expA ) { + if ( ! sigA ) goto zero; + normExpSig = softfloat_normSubnormalF64Sig( sigA ); + expA = normExpSig.exp; + sigA = normExpSig.sig; + } + expZ = expA - expB + 0x3FD; + sigA = ( sigA | UINT64_C( 0x0010000000000000 ) )<<10; + sigB = ( sigB | UINT64_C( 0x0010000000000000 ) )<<11; + if ( sigB <= ( sigA + sigA ) ) { + ++expZ; + sigA >>= 1; + } + sigZ = softfloat_estimateDiv128To64( sigA, 0, sigB ); + if ( ( sigZ & 0x1FF ) <= 2 ) { + term = softfloat_mul64To128( sigB, sigZ ); + rem = softfloat_sub128( sigA, 0, term.v64, term.v0 ); + while ( UINT64_C( 0x8000000000000000 ) <= rem.v64 ) { + --sigZ; + rem = softfloat_add128( rem.v64, rem.v0, 0, sigB ); + } + sigZ |= ( rem.v0 != 0 ); + } + return softfloat_roundPackToF64( signZ, expZ, sigZ ); + propagateNaN: + uiZ = softfloat_propagateNaNF64UI( uiA, uiB ); + goto uiZ; + invalid: + softfloat_raiseFlags( softfloat_flag_invalid ); + uiZ = defaultNaNF64UI; + goto uiZ; + infinity: + uiZ = packToF64UI( signZ, 0x7FF, 0 ); + goto uiZ; + zero: + uiZ = packToF64UI( signZ, 0, 0 ); + uiZ: + uZ.ui = uiZ; + return uZ.f; + +} + diff --git a/pool/shard004/C/0098182_tc_xi_dso.c b/pool/shard004/C/0098182_tc_xi_dso.c new file mode 100644 index 0000000000000000000000000000000000000000..86ce59271c14c16561c42c5649331e1743093916 --- /dev/null +++ b/pool/shard004/C/0098182_tc_xi_dso.c @@ -0,0 +1,104 @@ +/* + * Copyright 2013 Cheolmin Jo (webos21@gmail.com) + * + * 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 : tc_xi_dso.c + */ + +#include "xi/xi_dso.h" + +#include "xi/xi_log.h" + +static void tc_info() { + log_print(XDLOG, "====================================================\n"); + log_print(XDLOG, " xi_dso.h\n"); + log_print(XDLOG, "----------------------------------------------------\n"); + log_print(XDLOG, " * Functions)\n"); + log_print(XDLOG, " - xi_dso_get_searchpath\n"); + log_print(XDLOG, " - xi_dso_get_sysname\n"); + log_print(XDLOG, " - xi_dso_load\n"); + log_print(XDLOG, " - xi_dso_error\n"); + log_print(XDLOG, " - xi_dso_get_func\n"); + log_print(XDLOG, " - xi_dso_unload\n"); + log_print(XDLOG, "====================================================\n\n"); +} + +int tc_xi_dso() { + xint32 t = 1; + xchar *tcname = "xi_dso.h"; + + xssize ret; + xchar sbuf[1024]; + + xi_dso_t *dso; + xint64 (*msec)(); + + tc_info(); + + log_print(XDLOG, "[%s:%02d] get_searchpath ##############\n", tcname, t++); + ret = xi_dso_get_searchpath(sbuf, sizeof(sbuf)); + if (ret < 0) { + log_print(XDLOG, " - result : no-path!!!\n\n"); + } else { + log_print(XDLOG, " - result : pass. (path=%s)\n\n", sbuf); + } + + log_print(XDLOG, "[%s:%02d] get_sysname #################\n", tcname, t++); + ret = xi_dso_get_sysname(sbuf, "xibase"); + if (ret < 0) { + log_print(XDLOG, " - result : failed!!!\n\n"); + return -1; + } + log_print(XDLOG, " - result : pass. (name=%s)\n\n", sbuf); + + log_print(XDLOG, "[%s:%02d] load 'xxxx' for err! ##########\n", tcname, t++); + dso = xi_dso_load("xxxx"); + if (dso != NULL) { + log_print(XDLOG, " - result : failed!!!\n\n"); + return -1; + } + log_print(XDLOG, " - result : pass. (err-msg = %s)\n\n", xi_dso_error()); + + log_print(XDLOG, "[%s:%02d] load '%s' ##############\n", tcname, t++, sbuf); + dso = xi_dso_load(sbuf); + if (dso == NULL) { + log_print(XDLOG, " - result : failed!!! (err-msg = %s)\n\n", xi_dso_error()); + return -1; + } + log_print(XDLOG, " - result : pass. (dso=%p)\n\n", dso); + + log_print(XDLOG, "[%s:%02d] get func 'xi_clock_msec' ####\n", tcname, t++); + msec = xi_dso_get_func(dso, "xi_clock_msec"); + if (msec == NULL) { + log_print(XDLOG, " - result : failed!!! (err-msg = %s)\n\n", xi_dso_error()); + return -1; + } + log_print(XDLOG, " - result : pass. (msec=%p)\n\n", msec); + + log_print(XDLOG, "[%s:%02d] use 'xi_clock_msec' func ####\n", tcname, t++); + log_print(XDLOG, "xi_clock_msec() = %lld\n\n", (*msec)()); + + log_print(XDLOG, "[%s:%02d] unload '%s' ############\n", tcname, t++, sbuf); + if (!xi_dso_unload(dso)) { + log_print(XDLOG, " - result : failed!!!\n\n"); + return -1; + } + log_print(XDLOG, " - result : pass.\n\n"); + + log_print(XDLOG, "================== DONE [xi_dso.h] =================\n\n"); + + return 0; +} diff --git a/pool/shard004/C/0098191_init.c b/pool/shard004/C/0098191_init.c new file mode 100644 index 0000000000000000000000000000000000000000..bd76a721189d02074de33a182c0828c478a1ec60 --- /dev/null +++ b/pool/shard004/C/0098191_init.c @@ -0,0 +1,158 @@ +/* + * COPYRIGHT (c) 2014. + * 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 + +#define CONFIGURE_INIT +#include "system.h" + +const char rtems_test_name[] = "SP SEMAPHORE ERROR 02"; + +rtems_task Init( + rtems_task_argument argument +) +{ + rtems_status_code status; + + TEST_BEGIN(); + + Semaphore_name[ 1 ] = rtems_build_name( 'S', 'M', '1', ' ' ); + Semaphore_name[ 2 ] = rtems_build_name( 'S', 'M', '2', ' ' ); + Task_name[ 2 ] = rtems_build_name( 'T', 'A', '2', ' ' ); + + status = rtems_task_create( + Task_name[ 2 ], + 1, + RTEMS_MINIMUM_STACK_SIZE, + RTEMS_DEFAULT_MODES, + RTEMS_DEFAULT_ATTRIBUTES, + &Task_id[ 2 ] + ); + directive_failed( status, "rtems_task_create of TA2" ); + puts( "TA1 - rtems_task_create - TA2 created - RTEMS_SUCCESSFUL" ); + + puts( "TA1 - rtems_task_start - start TA2 - RTEMS_SUCCESSFUL" ); + status = rtems_task_start( Task_id[ 2 ], Task_2, 0 ); + directive_failed( status, "rtems_task_start of TA2" ); + + /* OK */ + status = rtems_semaphore_create( + Semaphore_name[ 1 ], + 1, + RTEMS_DEFAULT_ATTRIBUTES, + RTEMS_NO_PRIORITY, + &Semaphore_id[ 1 ] + ); + directive_failed( status, "rtems_semaphore_create" ); + puts( "TA1 - rtems_semaphore_create - 1 - RTEMS_SUCCESSFUL" ); + + status = rtems_semaphore_create( + Semaphore_name[ 2 ], + 1, + RTEMS_BINARY_SEMAPHORE | RTEMS_PRIORITY | RTEMS_INHERIT_PRIORITY, + RTEMS_NO_PRIORITY, + &Semaphore_id[ 2 ] + ); + directive_failed( status, "rtems_semaphore_create" ); + puts( "TA1 - rtems_semaphore_create - 2 - RTEMS_SUCCESSFUL" ); + + status = rtems_semaphore_obtain( + 100, + RTEMS_DEFAULT_OPTIONS, + RTEMS_NO_TIMEOUT + ); + fatal_directive_status( + status, + RTEMS_INVALID_ID, + "rtems_semaphore_obtain with illegal id" + ); + puts( "TA1 - rtems_semaphore_obtain - RTEMS_INVALID_ID" ); + + status = rtems_semaphore_obtain( + Semaphore_id[ 1 ], + RTEMS_DEFAULT_OPTIONS, + RTEMS_NO_TIMEOUT + ); + directive_failed( status, "rtems_semaphore_obtain successful" ); + puts( "TA1 - rtems_semaphore_obtain - got sem 1 - RTEMS_SUCCESSFUL" ); + + status = rtems_semaphore_obtain( + Semaphore_id[ 1 ], + RTEMS_NO_WAIT, + RTEMS_NO_TIMEOUT + ); + fatal_directive_status( + status, + RTEMS_UNSATISFIED, + "rtems_semaphore_obtain not available" + ); + puts( "TA1 - rtems_semaphore_obtain - RTEMS_UNSATISFIED" ); + + puts( "TA1 - rtems_semaphore_obtain - timeout in 3 seconds" ); + status = rtems_semaphore_obtain( + Semaphore_id[ 1 ], + RTEMS_DEFAULT_OPTIONS, + 3 * rtems_clock_get_ticks_per_second() + ); + fatal_directive_status( + status, + RTEMS_TIMEOUT, + "rtems_semaphore_obtain timeout" + ); + puts( "TA1 - rtems_semaphore_obtain - woke up with RTEMS_TIMEOUT" ); + + status = rtems_semaphore_release( Semaphore_id[ 2 ] ); + fatal_directive_status( + status, + RTEMS_NOT_OWNER_OF_RESOURCE, + "rtems_semaphore_release and not owner" + ); + puts( "TA1 - rtems_semaphore_release - RTEMS_NOT_OWNER_OF_RESOURCE" ); + + status = rtems_semaphore_release( 100 ); + fatal_directive_status( + status, + RTEMS_INVALID_ID, + "rtems_semaphore_release with illegal id" + ); + puts( "TA1 - rtems_semaphore_release - RTEMS_INVALID_ID" ); + + puts( "TA1 - rtems_task_wake_after - yield processor - RTEMS_SUCCESSFUL" ); + status = rtems_task_wake_after( RTEMS_YIELD_PROCESSOR ); + directive_failed( status, "rtems_task_wake_after (yield)" ); + + puts( "TA1 - rtems_semaphore_delete - delete sem 1 - RTEMS_SUCCESSFUL" ); + status = rtems_semaphore_delete( Semaphore_id[ 1 ] ); + directive_failed( status, "rtems_semaphore_delete of SM1" ); + + puts( "TA1 - rtems_semaphore_obtain - binary semaphore" ); + status = rtems_semaphore_obtain( + Semaphore_id[ 2 ], + RTEMS_DEFAULT_OPTIONS, + RTEMS_NO_TIMEOUT + ); + directive_failed( status, "rtems_semaphore_obtain"); + + puts( "TA1 - rtems_semaphore_delete - delete sem 2 - RTEMS_RESOURCE_IN_USE" ); + + status = rtems_semaphore_delete( Semaphore_id[ 2 ] ); + fatal_directive_status( + status, + RTEMS_RESOURCE_IN_USE, + "rtems_semaphore_delete of SM2" + ); + + puts( "TA1 - rtems_task_wake_after - yield processor - RTEMS_SUCCESSFUL" ); + status = rtems_task_wake_after( RTEMS_YIELD_PROCESSOR ); + directive_failed( status, "rtems_task_wake_after (yield)" ); + + TEST_END(); +} diff --git a/pool/shard004/C/0098198_ckeyDst.c b/pool/shard004/C/0098198_ckeyDst.c new file mode 100644 index 0000000000000000000000000000000000000000..808f5ec4e340bc3dcb45b26a12ba8773a026ce40 --- /dev/null +++ b/pool/shard004/C/0098198_ckeyDst.c @@ -0,0 +1,11 @@ +#extension GL_ARB_texture_rectangle : enable +uniform sampler2DRect uDstTex; +uniform vec4 uDstClr; +void vboxCKeyDst(void) +{ + vec4 dstClr = texture2DRect(uDstTex, vec2(gl_TexCoord[1])); + vec3 difClr = dstClr.rgb - uDstClr.rgb; + if(any(greaterThan(difClr, vec3(0.01, 0.01, 0.01))) + || any(lessThan(difClr, vec3(-0.01, -0.01, -0.01)))) + discard; +} diff --git a/pool/shard004/C/0098200_ieee80211_module.c b/pool/shard004/C/0098200_ieee80211_module.c new file mode 100644 index 0000000000000000000000000000000000000000..24eddca54141478acee54e27d7d67b1f5ed93df8 --- /dev/null +++ b/pool/shard004/C/0098200_ieee80211_module.c @@ -0,0 +1,199 @@ +/******************************************************************************* + + Copyright(c) 2004 Intel Corporation. All rights reserved. + + Portions of this file are based on the WEP enablement code provided by the + Host AP project hostap-drivers v0.1.3 + Copyright (c) 2001-2002, SSH Communications Security Corp and Jouni Malinen + + Copyright (c) 2002-2003, Jouni Malinen + + 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., 59 + Temple Place - Suite 330, Boston, MA 02111-1307, USA. + + The full GNU General Public License is included in this distribution in the + file called LICENSE. + + Contact Information: + James P. Ketrenos + Intel Corporation, 5200 N.E. Elam Young Parkway, Hillsboro, OR 97124-6497 + +*******************************************************************************/ + +#include +//#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "ieee80211.h" + +MODULE_DESCRIPTION("802.11 data/management/control stack"); +MODULE_AUTHOR("Copyright (C) 2004 Intel Corporation "); +MODULE_LICENSE("GPL"); + +#define DRV_NAME "ieee80211" + +static inline int ieee80211_networks_allocate(struct ieee80211_device *ieee) +{ + if (ieee->networks) + return 0; + + ieee->networks = kcalloc( + MAX_NETWORK_COUNT, sizeof(struct ieee80211_network), + GFP_KERNEL); + if (!ieee->networks) + return -ENOMEM; + + return 0; +} + +static inline void ieee80211_networks_free(struct ieee80211_device *ieee) +{ + if (!ieee->networks) + return; + kfree(ieee->networks); + ieee->networks = NULL; +} + +static inline void ieee80211_networks_initialize(struct ieee80211_device *ieee) +{ + int i; + + INIT_LIST_HEAD(&ieee->network_free_list); + INIT_LIST_HEAD(&ieee->network_list); + for (i = 0; i < MAX_NETWORK_COUNT; i++) + list_add_tail(&ieee->networks[i].list, &ieee->network_free_list); +} + +struct net_device *alloc_ieee80211(int sizeof_priv) +{ + struct ieee80211_device *ieee; + struct net_device *dev; + int i, err; + + IEEE80211_DEBUG_INFO("Initializing...\n"); + + dev = alloc_etherdev(sizeof(struct ieee80211_device) + sizeof_priv); + if (!dev) { + IEEE80211_ERROR("Unable to network device.\n"); + goto failed; + } + ieee = netdev_priv(dev); + + ieee->dev = dev; + + err = ieee80211_networks_allocate(ieee); + if (err) { + IEEE80211_ERROR("Unable to allocate beacon storage: %d\n", + err); + goto failed; + } + ieee80211_networks_initialize(ieee); + + /* Default fragmentation threshold is maximum payload size */ + ieee->fts = DEFAULT_FTS; + ieee->scan_age = DEFAULT_MAX_SCAN_AGE; + ieee->open_wep = 1; + + /* Default to enabling full open WEP with host based encrypt/decrypt */ + ieee->host_encrypt = 1; + ieee->host_decrypt = 1; + ieee->ieee802_1x = 1; /* Default to supporting 802.1x */ + + INIT_LIST_HEAD(&ieee->crypt_deinit_list); + init_timer(&ieee->crypt_deinit_timer); + ieee->crypt_deinit_timer.data = (unsigned long)ieee; + ieee->crypt_deinit_timer.function = ieee80211_crypt_deinit_handler; + + spin_lock_init(&ieee->lock); + spin_lock_init(&ieee->wpax_suitlist_lock); + + ieee->wpax_type_set = 0; + ieee->wpa_enabled = 0; + ieee->tkip_countermeasures = 0; + ieee->drop_unencrypted = 0; + ieee->privacy_invoked = 0; + ieee->ieee802_1x = 1; + ieee->raw_tx = 0; + + ieee80211_softmac_init(ieee); + + for (i = 0; i < IEEE_IBSS_MAC_HASH_SIZE; i++) + INIT_LIST_HEAD(&ieee->ibss_mac_hash[i]); + + for (i = 0; i < 17; i++) { + ieee->last_rxseq_num[i] = -1; + ieee->last_rxfrag_num[i] = -1; + ieee->last_packet_time[i] = 0; + } +//These function were added to load crypte module autoly + ieee80211_tkip_null(); + ieee80211_wep_null(); + ieee80211_ccmp_null(); + return dev; + + failed: + if (dev) + free_netdev(dev); + return NULL; +} + +void free_ieee80211(struct net_device *dev) +{ + struct ieee80211_device *ieee = netdev_priv(dev); + + int i; + struct list_head *p, *q; + + ieee80211_softmac_free(ieee); + del_timer_sync(&ieee->crypt_deinit_timer); + ieee80211_crypt_deinit_entries(ieee, 1); + + for (i = 0; i < WEP_KEYS; i++) { + struct ieee80211_crypt_data *crypt = ieee->crypt[i]; + if (crypt) { + if (crypt->ops) + crypt->ops->deinit(crypt->priv); + kfree(crypt); + ieee->crypt[i] = NULL; + } + } + + ieee80211_networks_free(ieee); + + for (i = 0; i < IEEE_IBSS_MAC_HASH_SIZE; i++) { + list_for_each_safe(p, q, &ieee->ibss_mac_hash[i]) { + kfree(list_entry(p, struct ieee_ibss_seq, list)); + list_del(p); + } + } + + free_netdev(dev); +} diff --git a/pool/shard004/C/0098204_loopwave.c b/pool/shard004/C/0098204_loopwave.c new file mode 100644 index 0000000000000000000000000000000000000000..09fb2a385fede8beffe7548b53847b0a74913b8d --- /dev/null +++ b/pool/shard004/C/0098204_loopwave.c @@ -0,0 +1,179 @@ +/* + Copyright (C) 1997-2019 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. +*/ + +/* Program to load a wave file and loop playing it using SDL audio */ + +/* loopwaves.c is much more robust in handling WAVE files -- + This is only for simple WAVEs +*/ +#include "SDL_config.h" + +#include +#include + +#ifdef __EMSCRIPTEN__ +#include +#endif + +#include "SDL.h" + +static struct +{ + SDL_AudioSpec spec; + Uint8 *sound; /* Pointer to wave data */ + Uint32 soundlen; /* Length of wave data */ + int soundpos; /* Current play position */ +} wave; + +static SDL_AudioDeviceID device; + +/* Call this instead of exit(), so we can clean up SDL: atexit() is evil. */ +static void +quit(int rc) +{ + SDL_Quit(); + exit(rc); +} + +static void +close_audio() +{ + if (device != 0) { + SDL_CloseAudioDevice(device); + device = 0; + } +} + +static void +open_audio() +{ + /* Initialize fillerup() variables */ + device = SDL_OpenAudioDevice(NULL, SDL_FALSE, &wave.spec, NULL, 0); + if (!device) { + SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't open audio: %s\n", SDL_GetError()); + SDL_FreeWAV(wave.sound); + quit(2); + } + + + /* Let the audio run */ + SDL_PauseAudioDevice(device, SDL_FALSE); +} + +static void reopen_audio() +{ + close_audio(); + open_audio(); +} + + +void SDLCALL +fillerup(void *unused, Uint8 * stream, int len) +{ + Uint8 *waveptr; + int waveleft; + + /* Set up the pointers */ + waveptr = wave.sound + wave.soundpos; + waveleft = wave.soundlen - wave.soundpos; + + /* Go! */ + while (waveleft <= len) { + SDL_memcpy(stream, waveptr, waveleft); + stream += waveleft; + len -= waveleft; + waveptr = wave.sound; + waveleft = wave.soundlen; + wave.soundpos = 0; + } + SDL_memcpy(stream, waveptr, len); + wave.soundpos += len; +} + +static int done = 0; + +#ifdef __EMSCRIPTEN__ +void +loop() +{ + if(done || (SDL_GetAudioDeviceStatus(device) != SDL_AUDIO_PLAYING)) + emscripten_cancel_main_loop(); +} +#endif + +int +main(int argc, char *argv[]) +{ + int i; + char filename[4096]; + + /* Enable standard application logging */ + SDL_LogSetPriority(SDL_LOG_CATEGORY_APPLICATION, SDL_LOG_PRIORITY_INFO); + + /* Load the SDL library */ + if (SDL_Init(SDL_INIT_AUDIO|SDL_INIT_EVENTS) < 0) { + SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't initialize SDL: %s\n", SDL_GetError()); + return (1); + } + + if (argc > 1) { + SDL_strlcpy(filename, argv[1], sizeof(filename)); + } else { + SDL_strlcpy(filename, "sample.wav", sizeof(filename)); + } + /* Load the wave file into memory */ + if (SDL_LoadWAV(filename, &wave.spec, &wave.sound, &wave.soundlen) == NULL) { + SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't load %s: %s\n", filename, SDL_GetError()); + quit(1); + } + + wave.spec.callback = fillerup; + + /* Show the list of available drivers */ + SDL_Log("Available audio drivers:"); + for (i = 0; i < SDL_GetNumAudioDrivers(); ++i) { + SDL_Log("%i: %s", i, SDL_GetAudioDriver(i)); + } + + SDL_Log("Using audio driver: %s\n", SDL_GetCurrentAudioDriver()); + + open_audio(); + + SDL_FlushEvents(SDL_AUDIODEVICEADDED, SDL_AUDIODEVICEREMOVED); + +#ifdef __EMSCRIPTEN__ + emscripten_set_main_loop(loop, 0, 1); +#else + while (!done) { + SDL_Event event; + + while (SDL_PollEvent(&event) > 0) { + if (event.type == SDL_QUIT) { + done = 1; + } + if ((event.type == SDL_AUDIODEVICEADDED && !event.adevice.iscapture) || + (event.type == SDL_AUDIODEVICEREMOVED && !event.adevice.iscapture && event.adevice.which == device)) { + reopen_audio(); + } + } + SDL_Delay(100); + } +#endif + + /* Clean up on signal */ + close_audio(); + SDL_FreeWAV(wave.sound); + SDL_Quit(); + return (0); +} + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/pool/shard004/C/0098205_packel.c b/pool/shard004/C/0098205_packel.c new file mode 100644 index 0000000000000000000000000000000000000000..c1fb15b5f86c05cce5cacf095ff2d6381b1063d3 --- /dev/null +++ b/pool/shard004/C/0098205_packel.c @@ -0,0 +1,145 @@ +/* + * packel: get the nth element of a package + * + * (c) 1999-2011 IOhannes m zmölnig, forum::für::umläute, institute of electronic music and acoustics (iem) + * + * 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 "zexy.h" + +static t_class *packel_class; + +typedef struct _packel +{ + t_object x_obj; + t_float *position; + int count; + + t_inlet**x_inlet; + t_outlet**x_outlet; + + int x_warningflag; +} t_packel; + + +static void packel_outelement(t_packel*x, int id, t_symbol*s,int argc, t_atom*argv) +{ + t_outlet*out=x->x_outlet[id]; + int index= x->position[id]; + + if (index) { + t_atom *current; + int pos = (index < 0)?(argc+index):(index-1); + + if(argc==0){ + if (pos==0||pos==-1)outlet_bang(out); + return; + } + + if (pos < 0 || pos >= argc)return; + + current = &(argv[pos]); + + switch (current->a_type) { + case A_NULL: + outlet_bang(out); + default: + outlet_list(out, gensym("list"), 1, current); + } + } else outlet_list(out, s, argc, argv); +} + +static void packel_list(t_packel *x, t_symbol *s, int argc, t_atom *argv) +{ + int c=x->count; + while(--c>=0) { + packel_outelement(x, c, s, argc, argv); + } +} + +static void packel_anything(t_packel *x, t_symbol *s, int argc, t_atom *argv) +{ + t_atom *av2 = (t_atom *)getbytes((argc + 1) * sizeof(t_atom)); + int i; + + if(x->x_warningflag){ + pd_error(x, "deprecation warning: you should only use lists for list data"); + x->x_warningflag=0; + } + + for (i = 0; i < argc; i++) + av2[i + 1] = argv[i]; + SETSYMBOL(av2, s); + packel_list(x, gensym("list"), argc+1, av2); + freebytes(av2, (argc + 1) * sizeof(t_atom)); +} + + +static void packel_free(t_packel *x) +{ + int i=0; + + for(i=0; icount; i++) { + if(x->x_inlet &&x->x_inlet [i])inlet_free (x->x_inlet [i]); + if(x->x_outlet&&x->x_outlet[i])outlet_free(x->x_outlet[i]); + } + + if(x->position)freebytes(x->position, x->count*sizeof(t_float)); + if(x->x_inlet) freebytes(x->x_inlet, x->count*sizeof(t_inlet*)); + if(x->x_outlet)freebytes(x->x_outlet, x->count*sizeof(t_outlet*)); + +} + + +static void *packel_new(t_symbol*s, int argc, t_atom*argv) +{ + t_packel *x = (t_packel *)pd_new(packel_class); + + x->count=(argc>0)?argc:1; + + x->position=(t_float*)getbytes(x->count*sizeof(t_float)); + x->x_inlet=(t_inlet**)getbytes(x->count*sizeof(t_inlet*)); + x->x_outlet=(t_outlet**)getbytes(x->count*sizeof(t_outlet*)); + + if(argc<1) { + x->position[0]=0.f; + x->x_inlet[0]=floatinlet_new(&x->x_obj, x->position); + x->x_outlet[0]=outlet_new(&x->x_obj, 0); + } else { + int i=0; + for(i=0; icount; i++) { + x->position[i]=atom_getfloat(argv+i); + x->x_inlet [i]=floatinlet_new(&x->x_obj, x->position+i); + x->x_outlet [i]=outlet_new(&x->x_obj, 0); + } + } + x->x_warningflag=1; + + + return (x); +} + +void packel_setup(void) +{ + packel_class = class_new(gensym("packel"), + (t_newmethod)packel_new, (t_method)packel_free, + sizeof(t_packel), 0, + A_GIMME, 0); + + class_addlist (packel_class, packel_list); + class_addanything(packel_class, packel_anything); + + zexy_register("packel"); +} diff --git a/pool/shard004/C/0098207_ec_naf.c b/pool/shard004/C/0098207_ec_naf.c new file mode 100644 index 0000000000000000000000000000000000000000..9ef3a55f2a712975c640969b35dd09f3057f25ff --- /dev/null +++ b/pool/shard004/C/0098207_ec_naf.c @@ -0,0 +1,103 @@ +/* + * ***** BEGIN LICENSE BLOCK ***** + * Version: MPL 1.1/GPL 2.0/LGPL 2.1 + * + * The contents of this file are subject to the Mozilla Public License Version + * 1.1 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * http://www.mozilla.org/MPL/ + * + * Software distributed under the License is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License + * for the specific language governing rights and limitations under the + * License. + * + * The Original Code is the elliptic curve math library. + * + * The Initial Developer of the Original Code is + * Sun Microsystems, Inc. + * Portions created by the Initial Developer are Copyright (C) 2003 + * the Initial Developer. All Rights Reserved. + * + * Contributor(s): + * Stephen Fung , Sun Microsystems Laboratories + * + * Alternatively, the contents of this file may be used under the terms of + * either the GNU General Public License Version 2 or later (the "GPL"), or + * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + * in which case the provisions of the GPL or the LGPL are applicable instead + * of those above. If you wish to allow use of your version of this file only + * under the terms of either the GPL or the LGPL, and not to allow others to + * use your version of this file under the terms of the MPL, indicate your + * decision by deleting the provisions above and replace them with the notice + * and other provisions required by the GPL or the LGPL. If you do not delete + * the provisions above, a recipient may use your version of this file under + * the terms of any one of the MPL, the GPL or the LGPL. + * + * ***** END LICENSE BLOCK ***** */ + +#include "ecl-priv.h" + +/* Returns 2^e as an integer. This is meant to be used for small powers of + * two. */ +int +ec_twoTo(int e) +{ + int a = 1; + int i; + + for (i = 0; i < e; i++) { + a *= 2; + } + return a; +} + +/* Computes the windowed non-adjacent-form (NAF) of a scalar. Out should + * be an array of signed char's to output to, bitsize should be the number + * of bits of out, in is the original scalar, and w is the window size. + * NAF is discussed in the paper: D. Hankerson, J. Hernandez and A. + * Menezes, "Software implementation of elliptic curve cryptography over + * binary fields", Proc. CHES 2000. */ +mp_err +ec_compute_wNAF(signed char *out, int bitsize, const mp_int *in, int w) +{ + mp_int k; + mp_err res = MP_OKAY; + int i, twowm1, mask; + + twowm1 = ec_twoTo(w - 1); + mask = 2 * twowm1 - 1; + + MP_DIGITS(&k) = 0; + MP_CHECKOK(mp_init_copy(&k, in)); + + i = 0; + /* Compute wNAF form */ + while (mp_cmp_z(&k) > 0) { + if (mp_isodd(&k)) { + out[i] = MP_DIGIT(&k, 0) & mask; + if (out[i] >= twowm1) + out[i] -= 2 * twowm1; + + /* Subtract off out[i]. Note mp_sub_d only works with + * unsigned digits */ + if (out[i] >= 0) { + mp_sub_d(&k, out[i], &k); + } else { + mp_add_d(&k, -(out[i]), &k); + } + } else { + out[i] = 0; + } + mp_div_2(&k, &k); + i++; + } + /* Zero out the remaining elements of the out array. */ + for (; i < bitsize + 1; i++) { + out[i] = 0; + } + CLEANUP: + mp_clear(&k); + return res; + +} diff --git a/pool/shard004/C/0098217_tif_tile.c b/pool/shard004/C/0098217_tif_tile.c new file mode 100644 index 0000000000000000000000000000000000000000..df39bdfa4897d05b35a92fae3578c0b48ef53e5f --- /dev/null +++ b/pool/shard004/C/0098217_tif_tile.c @@ -0,0 +1,298 @@ +/* $Id$ */ + +/* + * Copyright (c) 1991-1997 Sam Leffler + * Copyright (c) 1991-1997 Silicon Graphics, Inc. + * + * Permission to use, copy, modify, distribute, and sell this software and + * its documentation for any purpose is hereby granted without fee, provided + * that (i) the above copyright notices and this permission notice appear in + * all copies of the software and related documentation, and (ii) the names of + * Sam Leffler and Silicon Graphics may not be used in any advertising or + * publicity relating to the software without the specific, prior written + * permission of Sam Leffler and Silicon Graphics. + * + * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND, + * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY + * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. + * + * IN NO EVENT SHALL SAM LEFFLER OR SILICON GRAPHICS BE LIABLE FOR + * ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND, + * OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, + * WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF + * LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE + * OF THIS SOFTWARE. + */ + +/* + * TIFF Library. + * + * Tiled Image Support Routines. + */ +#include "tiffiop.h" + +/* + * Compute which tile an (x,y,z,s) value is in. + */ +uint32 +TIFFComputeTile(TIFF* tif, uint32 x, uint32 y, uint32 z, uint16 s) +{ + TIFFDirectory *td = &tif->tif_dir; + uint32 dx = td->td_tilewidth; + uint32 dy = td->td_tilelength; + uint32 dz = td->td_tiledepth; + uint32 tile = 1; + + if (td->td_imagedepth == 1) + z = 0; + if (dx == (uint32) -1) + dx = td->td_imagewidth; + if (dy == (uint32) -1) + dy = td->td_imagelength; + if (dz == (uint32) -1) + dz = td->td_imagedepth; + if (dx != 0 && dy != 0 && dz != 0) { + uint32 xpt = TIFFhowmany_32(td->td_imagewidth, dx); + uint32 ypt = TIFFhowmany_32(td->td_imagelength, dy); + uint32 zpt = TIFFhowmany_32(td->td_imagedepth, dz); + + if (td->td_planarconfig == PLANARCONFIG_SEPARATE) + tile = (xpt*ypt*zpt)*s + + (xpt*ypt)*(z/dz) + + xpt*(y/dy) + + x/dx; + else + tile = (xpt*ypt)*(z/dz) + xpt*(y/dy) + x/dx; + } + return (tile); +} + +/* + * Check an (x,y,z,s) coordinate + * against the image bounds. + */ +int +TIFFCheckTile(TIFF* tif, uint32 x, uint32 y, uint32 z, uint16 s) +{ + TIFFDirectory *td = &tif->tif_dir; + + if (x >= td->td_imagewidth) { + TIFFErrorExt(tif->tif_clientdata, tif->tif_name, + "%lu: Col out of range, max %lu", + (unsigned long) x, + (unsigned long) (td->td_imagewidth - 1)); + return (0); + } + if (y >= td->td_imagelength) { + TIFFErrorExt(tif->tif_clientdata, tif->tif_name, + "%lu: Row out of range, max %lu", + (unsigned long) y, + (unsigned long) (td->td_imagelength - 1)); + return (0); + } + if (z >= td->td_imagedepth) { + TIFFErrorExt(tif->tif_clientdata, tif->tif_name, + "%lu: Depth out of range, max %lu", + (unsigned long) z, + (unsigned long) (td->td_imagedepth - 1)); + return (0); + } + if (td->td_planarconfig == PLANARCONFIG_SEPARATE && + s >= td->td_samplesperpixel) { + TIFFErrorExt(tif->tif_clientdata, tif->tif_name, + "%lu: Sample out of range, max %lu", + (unsigned long) s, + (unsigned long) (td->td_samplesperpixel - 1)); + return (0); + } + return (1); +} + +/* + * Compute how many tiles are in an image. + */ +uint32 +TIFFNumberOfTiles(TIFF* tif) +{ + TIFFDirectory *td = &tif->tif_dir; + uint32 dx = td->td_tilewidth; + uint32 dy = td->td_tilelength; + uint32 dz = td->td_tiledepth; + uint32 ntiles; + + if (dx == (uint32) -1) + dx = td->td_imagewidth; + if (dy == (uint32) -1) + dy = td->td_imagelength; + if (dz == (uint32) -1) + dz = td->td_imagedepth; + ntiles = (dx == 0 || dy == 0 || dz == 0) ? 0 : + _TIFFMultiply32(tif, _TIFFMultiply32(tif, TIFFhowmany_32(td->td_imagewidth, dx), + TIFFhowmany_32(td->td_imagelength, dy), + "TIFFNumberOfTiles"), + TIFFhowmany_32(td->td_imagedepth, dz), "TIFFNumberOfTiles"); + if (td->td_planarconfig == PLANARCONFIG_SEPARATE) + ntiles = _TIFFMultiply32(tif, ntiles, td->td_samplesperpixel, + "TIFFNumberOfTiles"); + return (ntiles); +} + +/* + * Compute the # bytes in each row of a tile. + */ +uint64 +TIFFTileRowSize64(TIFF* tif) +{ + TIFFDirectory *td = &tif->tif_dir; + uint64 rowsize; + + if (td->td_tilelength == 0 || td->td_tilewidth == 0) + return (0); + rowsize = _TIFFMultiply64(tif, td->td_bitspersample, td->td_tilewidth, + "TIFFTileRowSize"); + if (td->td_planarconfig == PLANARCONFIG_CONTIG) + rowsize = _TIFFMultiply64(tif, rowsize, td->td_samplesperpixel, + "TIFFTileRowSize"); + return (TIFFhowmany8_64(rowsize)); +} +tmsize_t +TIFFTileRowSize(TIFF* tif) +{ + static const char module[] = "TIFFTileRowSize"; + uint64 m; + tmsize_t n; + m=TIFFTileRowSize64(tif); + n=(tmsize_t)m; + if ((uint64)n!=m) + { + TIFFErrorExt(tif->tif_clientdata,module,"Integer overflow"); + n=0; + } + return(n); +} + +/* + * Compute the # bytes in a variable length, row-aligned tile. + */ +uint64 +TIFFVTileSize64(TIFF* tif, uint32 nrows) +{ + static const char module[] = "TIFFVTileSize64"; + TIFFDirectory *td = &tif->tif_dir; + if (td->td_tilelength == 0 || td->td_tilewidth == 0 || + td->td_tiledepth == 0) + return (0); + if ((td->td_planarconfig==PLANARCONFIG_CONTIG)&& + (td->td_photometric==PHOTOMETRIC_YCBCR)&& + (td->td_samplesperpixel==3)&& + (!isUpSampled(tif))) + { + /* + * Packed YCbCr data contain one Cb+Cr for every + * HorizontalSampling*VerticalSampling Y values. + * Must also roundup width and height when calculating + * since images that are not a multiple of the + * horizontal/vertical subsampling area include + * YCbCr data for the extended image. + */ + uint16 ycbcrsubsampling[2]; + uint16 samplingblock_samples; + uint32 samplingblocks_hor; + uint32 samplingblocks_ver; + uint64 samplingrow_samples; + uint64 samplingrow_size; + TIFFGetFieldDefaulted(tif,TIFFTAG_YCBCRSUBSAMPLING,ycbcrsubsampling+0, + ycbcrsubsampling+1); + assert((ycbcrsubsampling[0]==1)||(ycbcrsubsampling[0]==2)||(ycbcrsubsampling[0]==4)); + assert((ycbcrsubsampling[1]==1)||(ycbcrsubsampling[1]==2)||(ycbcrsubsampling[1]==4)); + if (ycbcrsubsampling[0]*ycbcrsubsampling[1]==0) + { + TIFFErrorExt(tif->tif_clientdata,module, + "Invalid YCbCr subsampling"); + return 0; + } + samplingblock_samples=ycbcrsubsampling[0]*ycbcrsubsampling[1]+2; + samplingblocks_hor=TIFFhowmany_32(td->td_tilewidth,ycbcrsubsampling[0]); + samplingblocks_ver=TIFFhowmany_32(nrows,ycbcrsubsampling[1]); + samplingrow_samples=_TIFFMultiply64(tif,samplingblocks_hor,samplingblock_samples,module); + samplingrow_size=TIFFhowmany8_64(_TIFFMultiply64(tif,samplingrow_samples,td->td_bitspersample,module)); + return(_TIFFMultiply64(tif,samplingrow_size,samplingblocks_ver,module)); + } + else + return(_TIFFMultiply64(tif,nrows,TIFFTileRowSize64(tif),module)); +} +tmsize_t +TIFFVTileSize(TIFF* tif, uint32 nrows) +{ + static const char module[] = "TIFFVTileSize"; + uint64 m; + tmsize_t n; + m=TIFFVTileSize64(tif,nrows); + n=(tmsize_t)m; + if ((uint64)n!=m) + { + TIFFErrorExt(tif->tif_clientdata,module,"Integer overflow"); + n=0; + } + return(n); +} + +/* + * Compute the # bytes in a row-aligned tile. + */ +uint64 +TIFFTileSize64(TIFF* tif) +{ + return (TIFFVTileSize64(tif, tif->tif_dir.td_tilelength)); +} +tmsize_t +TIFFTileSize(TIFF* tif) +{ + static const char module[] = "TIFFTileSize"; + uint64 m; + tmsize_t n; + m=TIFFTileSize64(tif); + n=(tmsize_t)m; + if ((uint64)n!=m) + { + TIFFErrorExt(tif->tif_clientdata,module,"Integer overflow"); + n=0; + } + return(n); +} + +/* + * Compute a default tile size based on the image + * characteristics and a requested value. If a + * request is <1 then we choose a size according + * to certain heuristics. + */ +void +TIFFDefaultTileSize(TIFF* tif, uint32* tw, uint32* th) +{ + (*tif->tif_deftilesize)(tif, tw, th); +} + +void +_TIFFDefaultTileSize(TIFF* tif, uint32* tw, uint32* th) +{ + (void) tif; + if (*(int32*) tw < 1) + *tw = 256; + if (*(int32*) th < 1) + *th = 256; + /* roundup to a multiple of 16 per the spec */ + if (*tw & 0xf) + *tw = TIFFroundup_32(*tw, 16); + if (*th & 0xf) + *th = TIFFroundup_32(*th, 16); +} + +/* vim: set ts=8 sts=8 sw=8 noet: */ +/* + * Local Variables: + * mode: c + * c-basic-offset: 8 + * fill-column: 78 + * End: + */ diff --git a/pool/shard004/C/0098219_in_cell.c b/pool/shard004/C/0098219_in_cell.c new file mode 100644 index 0000000000000000000000000000000000000000..416f9888949823926602b7bbb91b802040bcc48c --- /dev/null +++ b/pool/shard004/C/0098219_in_cell.c @@ -0,0 +1,142 @@ +/* + * This file is part of Hubbub. + * Licensed under the MIT License, + * http://www.opensource.org/licenses/mit-license.php + * Copyright 2008 Andrew Sidwell + */ + +#include +#include + +#include "treebuilder/modes.h" +#include "treebuilder/internal.h" +#include "treebuilder/treebuilder.h" +#include "utils/utils.h" + + +/** + * Clear the stack back to a table row context. + * + * \param treebuilder The treebuilder instance + */ +static inline void close_cell(hubbub_treebuilder *treebuilder) +{ + hubbub_ns ns; + element_type otype = UNKNOWN; + void *node; + + element_type type; + + if (element_in_scope(treebuilder, TD, true)) { + type = TD; + } else { + type = TH; + } + + /* Act as if an end tag token of type `type` has been seen */ + + close_implied_end_tags(treebuilder, UNKNOWN); + /** \todo parse error */ + + while (otype != type) { + element_stack_pop(treebuilder, &ns, &otype, &node); + + treebuilder->tree_handler->unref_node( + treebuilder->tree_handler->ctx, + node); + } + + clear_active_formatting_list_to_marker(treebuilder); + treebuilder->context.mode = IN_ROW; + + return; +} + + +/** + * Handle tokens in "in cell" insertion mode + * + * \param treebuilder The treebuilder instance + * \param token The token to process + * \return True to reprocess the token, false otherwise + */ +hubbub_error handle_in_cell(hubbub_treebuilder *treebuilder, + const hubbub_token *token) +{ + hubbub_error err = HUBBUB_OK; + + switch (token->type) { + case HUBBUB_TOKEN_START_TAG: + { + element_type type = element_type_from_name(treebuilder, + &token->data.tag.name); + + if (type == CAPTION || type == COL || + type == COLGROUP || type == TBODY || + type == TD || type == TFOOT || type == TH || + type == THEAD || type == TR) { + /** \todo fragment case */ + close_cell(treebuilder); + err = HUBBUB_REPROCESS; + } else { + err = handle_in_body(treebuilder, token); + } + } + break; + case HUBBUB_TOKEN_END_TAG: + { + element_type type = element_type_from_name(treebuilder, + &token->data.tag.name); + + if (type == TH || type == TD) { + if (element_in_scope(treebuilder, type, true)) { + hubbub_ns ns; + element_type otype = UNKNOWN; + void *node; + + close_implied_end_tags(treebuilder, UNKNOWN); + /** \todo parse error */ + + while (otype != type) { + element_stack_pop(treebuilder, + &ns, &otype, &node); + + treebuilder->tree_handler->unref_node( + treebuilder->tree_handler->ctx, + node); + } + + clear_active_formatting_list_to_marker( + treebuilder); + + treebuilder->context.mode = IN_ROW; + } else { + /** \todo parse error */ + } + } else if (type == BODY || type == CAPTION || type == COL || + type == COLGROUP || type == HTML) { + /** \todo parse error */ + } else if (type == TABLE || type == TBODY || type == TFOOT || + type == THEAD || type == TR) { + if (element_in_scope(treebuilder, type, true)) { + close_cell(treebuilder); + err = HUBBUB_REPROCESS; + } else { + /** \todo parse error */ + } + } else { + err = handle_in_body(treebuilder, token); + } + } + break; + case HUBBUB_TOKEN_CHARACTER: + case HUBBUB_TOKEN_COMMENT: + case HUBBUB_TOKEN_DOCTYPE: + case HUBBUB_TOKEN_EOF: + err = handle_in_body(treebuilder, token); + break; + } + + return err; +} + diff --git a/pool/shard004/C/0098224_widget_gui.c b/pool/shard004/C/0098224_widget_gui.c new file mode 100644 index 0000000000000000000000000000000000000000..4e67a1f96799af15b8ab580dd4bf1c482afebbcd --- /dev/null +++ b/pool/shard004/C/0098224_widget_gui.c @@ -0,0 +1,405 @@ +/** + * \file + * + * \brief Display demo widget application + * + * Copyright (c) 2014 Atmel Corporation. All rights reserved. + * + * \asf_license_start + * + * \page License + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * + * 3. The name of Atmel may not be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * 4. This software may only be redistributed and used in connection with an + * Atmel microcontroller product. + * + * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE + * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL BE LIABLE FOR + * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, + * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * + * \asf_license_stop + */ + /** + * Support and FAQ: visit Atmel Support + */ + +#include +#include +#include "widget_gui.h" + +/** + * \weakgroup app_widget_group + * + * @{ + */ + +/** + * \brief Command event IDs + * + * \note The first entry in this enum is zero-valued, and therefore reserved for + * widgets that should not issue command events. \sa wtk_group + */ +enum command_id { + /** Unused command event ID. */ + DUMMY_ID, + /** Command event ID for slider */ + SLIDER_ID, + /** Command event ID for check box */ + CHECK_BOX_ID, + /** Command event ID for radio button 1 */ + RADIO_BUTTON_1_ID, + /** Command event ID for radio button 2 */ + RADIO_BUTTON_2_ID, + /** Command event ID for button */ + BUTTON_ID, +}; + +/** + * \name Color scheme + * + * @{ + */ + +/** Color scheme 0 foreground color */ +#define COLOR_SCHEME_0_FG GFX_COLOR(30, 30, 200) +/** Color scheme 0 background color */ +#define COLOR_SCHEME_0_BG GFX_COLOR(255, 255, 255) +/** Color scheme 1 foreground color */ +#define COLOR_SCHEME_1_FG GFX_COLOR(0, 255, 0) +/** Color scheme 1 background color */ +#define COLOR_SCHEME_1_BG GFX_COLOR(0, 100, 100) + +/** Background color of the application frame */ +#define APP_BACKGROUND_COLOR GFX_COLOR(220, 220, 220) + +/** @} */ + +/** + * \name Widget positions and sizes + * + * @{ + */ + +/** Leftmost X coordinate in frame for the widgets */ +#define WIDGET_POS_X 14 +/** Topmost Y coordinate in frame for the widgets */ +#define WIDGET_POS_Y 5 + +/** Slider X coordinate, inside frame */ +#define SLIDER_POS_Y 10 +/** Width of slider */ +#define SLIDER_SIZE_X 120 +/** Height of slider */ +#define SLIDER_SIZE_Y 40 + +/** Spacing between the slider and progress bars */ +#define SLIDER_PB_SPACING_X 10 +/** Width of progress bar */ +#define PB_SIZE_X SLIDER_SIZE_X +/** Height of progress bar */ +#define PB_SIZE_Y SLIDER_SIZE_Y + +/** Spacing above check box to slider and progress bars */ +#define CHECK_BOX_SPACING_Y 20 + +/** Spacing above each radio button */ +#define RADIO_BUTTON_SPACING_Y 10 + +/** Spacing above the button */ +#define BUTTON_SPACING_Y 20 +/** Height of the button */ +#define BUTTON_SIZE_Y 30 + +/** @} */ + +/** Description for the check box */ +const static char checkbox_string[] = "Invert colors"; +/** Description for the first radio button */ +const static char rb1_string[] = "Color scheme 1"; +/** Description for the second radio button */ +const static char rb2_string[] = "Color scheme 2"; +/** Description for the button */ +const static char btn_string[] = "Reset Slider"; + +/** Widget application context */ +struct widget_context { + /** Pointer to frame for application */ + struct wtk_basic_frame *frame; + /** Frame background object */ + struct gfx_bitmap frame_bg; + /** Pointer to slider */ + struct wtk_slider *slider; + /** Pointer to progress bar */ + struct wtk_progress_bar *pb; + /** Current color scheme in use */ + uint8_t color_scheme; + /** Current color scheme has inverted colors */ + bool color_invert; +}; + +/** Statically allocated context pointer */ +static struct widget_context *widget_ctx; + +/** + * \brief Update colors + * + * Updates the colors for the progress bar and issues redrawing of the widgets. + * + * \param widget Context for widget application + */ +static void app_widget_update_colors(struct widget_context *widget) +{ + gfx_color_t temp; + gfx_color_t fg; + gfx_color_t bg; + + switch (widget->color_scheme) { + case 1: + /* Set colors for color scheme 1 */ + fg = COLOR_SCHEME_1_FG; + bg = COLOR_SCHEME_1_BG; + break; + + default: + /* Set default color scheme */ + fg = COLOR_SCHEME_0_FG; + bg = COLOR_SCHEME_0_BG; + break; + } + + if (widget->color_invert) { + temp = bg; + bg = fg; + fg = temp; + } + + wtk_progress_bar_set_colors(widget->pb, fg, bg); + win_redraw(wtk_progress_bar_as_child(widget->pb)); +} + +/** + * \brief Frame handler for the application + * + * Handles all command events from the widgets in the application frame. + * + * \sa wtk_basic_frame_command_handler_t + * + * \param frame Pointer to the application frame + * \param command_data Command event ID + * + * \return True if exiting, to destroy the window + */ +static bool widget_frame_command_handler(struct wtk_basic_frame *frame, + win_command_t command_data) +{ + struct widget_context *widget; + char command; + + widget = (struct widget_context *)wtk_basic_frame_get_custom_data(frame); + command = (uintptr_t)command_data; + + switch (command) { + case SLIDER_ID: + /* Update the progress bar when slider value changes. */ + wtk_progress_bar_set_value(widget->pb, + wtk_slider_get_value(widget->slider)); + break; + + case CHECK_BOX_ID: + /* Invert the colors for the progress bar. */ + widget->color_invert = !widget->color_invert; + app_widget_update_colors(widget); + break; + + case RADIO_BUTTON_1_ID: + /* Set first color scheme for the progress bar. */ + widget->color_scheme = 0; + app_widget_update_colors(widget); + break; + + case RADIO_BUTTON_2_ID: + /* Set second color scheme for the progress bar. */ + widget->color_scheme = 1; + app_widget_update_colors(widget); + break; + + case BUTTON_ID: + /* Reset the slider and progress bar values and update */ + wtk_slider_set_value(widget->slider, 0); + wtk_progress_bar_set_value(widget->pb, 0); + } + + return false; +} + +/** + * \brief Setup widget demo + * + * Allocates memory for the application context, and creates all widgets that + * make up its interface. If memory allocation or widget creation fails, the + * application exits immediately. + * + * \return Boolean true if the application was launched successfully, false if + * a memory allocation occurred. + */ +bool app_widget_launch(void) +{ + struct win_window *parent; + struct win_area area; + struct wtk_check_box *cb; + struct wtk_radio_group *rg; + struct wtk_radio_button *rb; + struct wtk_button *btn; + + /* Create a new context for the GUI */ + widget_ctx = membag_alloc(sizeof(struct widget_context)); + if (!widget_ctx) { + return false; + } + + /* Initialize context data. */ + widget_ctx->color_scheme = 0; + widget_ctx->color_invert = 0; + + /* Set the background information for the GUI window */ + widget_ctx->frame_bg.type = GFX_BITMAP_SOLID; + widget_ctx->frame_bg.data.color = APP_BACKGROUND_COLOR; + + /* Set the area for the GUI window */ + area = win_get_attributes(win_get_root())->area; + win_inflate_area(&area, -20); + + /* Create and show the main GUI frame */ + widget_ctx->frame = wtk_basic_frame_create( + win_get_root(), &area, &widget_ctx->frame_bg, NULL, + widget_frame_command_handler, widget_ctx); + + if (!widget_ctx->frame) { + goto error_frame; + } + parent = wtk_basic_frame_as_child(widget_ctx->frame); + win_show(parent); + + /* Update area for the slider widget */ + area.pos.x = WIDGET_POS_X; + area.pos.y = WIDGET_POS_Y + SLIDER_POS_Y; + area.size.x = SLIDER_SIZE_X; + area.size.y = SLIDER_SIZE_Y; + + /* Create slider inside frame */ + widget_ctx->slider = wtk_slider_create(parent, &area, 100, 50, + WTK_SLIDER_HORIZONTAL | WTK_SLIDER_CMD_MOVE | WTK_SLIDER_CMD_RELEASE, + (win_command_t)SLIDER_ID); + + if (!widget_ctx->slider) { + goto error_widget; + } + win_show(wtk_slider_as_child(widget_ctx->slider)); + + /* Update area for the progress bar widget */ + area.pos.x += area.size.x + SLIDER_PB_SPACING_X; + area.size.x = PB_SIZE_X; + area.size.y = PB_SIZE_Y; + + /* Create progress bar to the right of the slider */ + widget_ctx->pb = wtk_progress_bar_create(parent, &area, 100, + 50, GFX_COLOR_BLACK, GFX_COLOR_BLACK, WTK_PROGRESS_BAR_HORIZONTAL); + + if (!widget_ctx->pb) { + goto error_widget; + } + win_show(wtk_progress_bar_as_child(widget_ctx->pb)); + app_widget_update_colors(widget_ctx); + + /* Update area for the checkbox widget */ + area.pos.x = WIDGET_POS_X; + area.pos.y += area.size.y + CHECK_BOX_SPACING_Y; + wtk_check_box_size_hint(&area.size, checkbox_string); + + /* Create check box below slider and progress bar */ + cb = wtk_check_box_create(parent, &area, checkbox_string, + false, (win_command_t)CHECK_BOX_ID); + + if (!cb) { + goto error_widget; + } + win_show(wtk_check_box_as_child(cb)); + + /* Create a logical group for the radio buttons */ + rg = wtk_radio_group_create(); + if (!rg) { + goto error_widget; + } + + /* Update area for the first radio button widget */ + area.pos.y += area.size.y + RADIO_BUTTON_SPACING_Y; + wtk_radio_button_size_hint(&area.size, rb1_string); + + /* Create first radio button widget */ + rb = wtk_radio_button_create(parent, &area, rb1_string, + true, rg, (win_command_t)RADIO_BUTTON_1_ID); + + if (!rb) { + goto error_widget; + } + win_show(wtk_radio_button_as_child(rb)); + + /* Update area for the second radio button widget */ + area.pos.y += area.size.y + RADIO_BUTTON_SPACING_Y; + wtk_radio_button_size_hint(&area.size, rb2_string); + + /* Create second radio button widget */ + rb = wtk_radio_button_create(parent, &area, rb2_string, + false, rg, (win_command_t)RADIO_BUTTON_2_ID); + + if (!rb) { + goto error_widget; + } + win_show(wtk_radio_button_as_child(rb)); + + /* Update area for the button widget */ + area.pos.y += area.size.y + BUTTON_SPACING_Y; + area.size.x = SLIDER_SIZE_X + SLIDER_PB_SPACING_X + PB_SIZE_X; + area.size.y = BUTTON_SIZE_Y; + + /* Create button widget */ + btn = wtk_button_create(parent, &area, btn_string, (win_command_t)BUTTON_ID); + wtk_button_size_hint(&area.size, btn_string); + + if (!btn) { + goto error_widget; + } + win_show(wtk_button_as_child(btn)); + + return true; + + /* Error handling to clean up allocations after an error */ +error_widget: + win_destroy(wtk_basic_frame_as_child(widget_ctx->frame)); +error_frame: + membag_free(widget_ctx); + + return false; +} + +/** @} */ diff --git a/pool/shard004/C/0098226_fabs.c b/pool/shard004/C/0098226_fabs.c new file mode 100644 index 0000000000000000000000000000000000000000..a5e7ad1384ee99f21419267680d851eccbf435d1 --- /dev/null +++ b/pool/shard004/C/0098226_fabs.c @@ -0,0 +1,18 @@ +#include +#include +#include + +int +fabs(u32 *frD, u32 *frB) +{ + frD[0] = frB[0] & 0x7fffffff; + frD[1] = frB[1]; + +#ifdef DEBUG + printk("%s: D %p, B %p: ", __func__, frD, frB); + dump_double(frD); + printk("\n"); +#endif + + return 0; +} diff --git a/pool/shard004/C/0098231_task3.c b/pool/shard004/C/0098231_task3.c new file mode 100644 index 0000000000000000000000000000000000000000..cc3eb8a8690ea66564ec6fc28c1bb929d480aa98 --- /dev/null +++ b/pool/shard004/C/0098231_task3.c @@ -0,0 +1,46 @@ +#include +#include + +int check_if_palindrome(int); + +int main(){ + int input; + scanf("%d",&input); + + while(check_if_palindrome(input) != 0){ + input++; + } + printf("%X",input); + +return 0; +} + +int check_if_palindrome(int input){ + int i = 0, k, decimal, length; + char tempchar, hex[123]; + + decimal = input; + + while(decimal != 0){ + + if( (decimal % 16) < 10) + tempchar = (decimal % 16) + '0'; + + else + tempchar = (decimal % 16) + 55; + + hex[i] = tempchar; + decimal = decimal / 16; + i++; + } + hex[i]= 0; + length = strlen(hex); + + for(i = 0, k = length - 1; i < (length) / 2; i++, k--){ + if(hex[i] != hex[k]){ + return 1; + } + } + + return 0; +} diff --git a/pool/shard004/C/0098234_packet-dcerpc-frsapi.c b/pool/shard004/C/0098234_packet-dcerpc-frsapi.c new file mode 100644 index 0000000000000000000000000000000000000000..3979760888a429692364b376ab65460555fa6119 --- /dev/null +++ b/pool/shard004/C/0098234_packet-dcerpc-frsapi.c @@ -0,0 +1,105 @@ +/* packet-dcerpc-frsapi.c + * Routines for the frs API (File Replication Service) MSRPC interface + * Copyright 2004 Jean-Baptiste Marchand + * + * Wireshark - Network traffic analyzer + * By Gerald Combs + * Copyright 1998 Gerald Combs + * + * SPDX-License-Identifier: GPL-2.0-or-later + */ + + +#include "config.h" + +#include +#include "packet-dcerpc.h" +#include "packet-dcerpc-frsapi.h" + +void proto_register_dcerpc_frsapi(void); +void proto_reg_handoff_dcerpc_frsapi(void); + +static int proto_dcerpc_frsapi = -1; + +static int hf_frsapi_opnum = -1; + +static gint ett_dcerpc_frsapi = -1; + +/* +IDL [ uuid(d049b186-814f-11d1-9a3c-00c04fc9b232), +IDL version(1.1), +IDL implicit_handle(handle_t rpc_binding) +IDL ] interface frsapi +*/ + +static e_guid_t uuid_dcerpc_frsapi = { + 0xd049b186, 0x814f, 0x11d1, + { 0x9a, 0x3c, 0x00, 0xc0, 0x4f, 0xc9, 0xb2, 0x32 } +}; + +static guint16 ver_dcerpc_frsapi = 1; + + +static dcerpc_sub_dissector dcerpc_frsapi_dissectors[] = { + { FRSAPI_VERIFY_PROMOTION, "VerifyPromotion", NULL, NULL }, + { FRSAPI_PROMOTION_STATUS, "PromotionStatus", NULL, NULL }, + { FRSAPI_START_DEMOTION, "StartDemotion", NULL, NULL }, + { FRSAPI_COMMIT_DEMOTION, "CommitDemotion", NULL, NULL }, + { FRSAPI_SET_DS_POLLING_INTERVAL_W, "Set_DsPollingIntervalW", NULL, NULL }, + { FRSAPI_GET_DS_POLLING_INTERVAL_W, "Get_DsPollingIntervalW", NULL, NULL }, + { FRSAPI_VERIFY_PROMOTION_W, "VerifyPromotionW", NULL, NULL }, + { FRSAPI_INFO_W, "InfoW", NULL, NULL }, + { FRSAPI_IS_PATH_REPLICATED, "IsPathReplicated", NULL, NULL }, + { FRSAPI_WRITER_COMMAND, "WriterCommand", NULL, NULL }, + { 0, NULL, NULL, NULL } +}; + +void +proto_register_dcerpc_frsapi(void) +{ + + static hf_register_info hf[] = { + + { &hf_frsapi_opnum, + { "Operation", "frsapi.opnum", FT_UINT16, BASE_DEC, + NULL, 0x0, NULL, HFILL }}, + }; + + + static gint *ett[] = { + &ett_dcerpc_frsapi, + }; + + + proto_dcerpc_frsapi = proto_register_protocol( + "Microsoft File Replication Service API", "FRSAPI", "frsapi"); + + proto_register_field_array(proto_dcerpc_frsapi, hf, array_length(hf)); + + proto_register_subtree_array(ett, array_length(ett)); + +} + + +void +proto_reg_handoff_dcerpc_frsapi(void) +{ + /* register protocol as dcerpc */ + + dcerpc_init_uuid( + proto_dcerpc_frsapi, ett_dcerpc_frsapi, &uuid_dcerpc_frsapi, + ver_dcerpc_frsapi, dcerpc_frsapi_dissectors, hf_frsapi_opnum); +} + +/* + * Editor modelines - https://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/shard004/C/0098240_efi_smbios.c b/pool/shard004/C/0098240_efi_smbios.c new file mode 100644 index 0000000000000000000000000000000000000000..719d3e8880ab8ef1fe6f1842f92d5bc5a864147f --- /dev/null +++ b/pool/shard004/C/0098240_efi_smbios.c @@ -0,0 +1,56 @@ +// SPDX-License-Identifier: GPL-2.0+ +/* + * EFI application tables support + * + * Copyright (c) 2016 Alexander Graf + */ + +#include +#include +#include +#include +#include + +static const efi_guid_t smbios_guid = SMBIOS_TABLE_GUID; + +/* + * Install the SMBIOS table as a configuration table. + * + * @return status code + */ +efi_status_t efi_smbios_register(void) +{ + /* Map within the low 32 bits, to allow for 32bit SMBIOS tables */ + u64 dmi_addr = U32_MAX; + efi_status_t ret; + void *dmi; + + /* Reserve 4kiB page for SMBIOS */ + ret = efi_allocate_pages(EFI_ALLOCATE_MAX_ADDRESS, + EFI_RUNTIME_SERVICES_DATA, 1, &dmi_addr); + + if (ret != EFI_SUCCESS) { + /* Could not find space in lowmem, use highmem instead */ + ret = efi_allocate_pages(EFI_ALLOCATE_ANY_PAGES, + EFI_RUNTIME_SERVICES_DATA, 1, + &dmi_addr); + + if (ret != EFI_SUCCESS) + return ret; + } + + /* + * Generate SMBIOS tables - we know that efi_allocate_pages() returns + * a 4k-aligned address, so it is safe to assume that + * write_smbios_table() will write the table at that address. + * + * Note that on sandbox, efi_allocate_pages() unfortunately returns a + * pointer even though it uses a uint64_t type. Convert it. + */ + assert(!(dmi_addr & 0xf)); + dmi = (void *)(uintptr_t)dmi_addr; + write_smbios_table(map_to_sysmem(dmi)); + + /* And expose them to our EFI payload */ + return efi_install_configuration_table(&smbios_guid, dmi); +} diff --git a/pool/shard004/C/0098241_initloader.c b/pool/shard004/C/0098241_initloader.c new file mode 100644 index 0000000000000000000000000000000000000000..eefc925b4d111bddf66a98b9d1a4376ab3772d1b --- /dev/null +++ b/pool/shard004/C/0098241_initloader.c @@ -0,0 +1,202 @@ +/** + * $Id$ + * Copyright (C) 2008 - 2014 Nils Asmussen + * + * 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 +#include +#include +#include +#include +#include +#include + +#define MAX_ARG_COUNT 32 +#define MAX_ARG_LEN 256 + +static char **parseArgs(const char *line,int *argc) { + static char argvals[MAX_ARG_COUNT][MAX_ARG_LEN]; + static char *args[MAX_ARG_COUNT]; + size_t i = 0,j = 0; + args[0] = argvals[0]; + while(*line) { + if(*line == ' ') { + if(args[j][0]) { + if(j + 2 >= MAX_ARG_COUNT) + break; + args[j][i] = '\0'; + j++; + i = 0; + args[j] = argvals[j]; + } + } + else if(i < MAX_ARG_LEN) + args[j][i++] = *line; + line++; + } + *argc = j + 1; + args[j][i] = '\0'; + args[j + 1] = NULL; + return args; +} + +extern char __progname[]; + +/* we have to hardcode the uids and gids for the boot modules here, because we have no root fs yet */ +static const struct { + const char *match; + uid_t uid; + size_t gcount; + gid_t gids[4]; +} bootModUsers[] = { + {"pci", USER_BUS, 2, {GROUP_BUS,GROUP_DRIVER,0,0}}, + {"ata", USER_STORAGE, 3, {GROUP_STORAGE,GROUP_DRIVER,GROUP_BUS,0}}, + {"disk", USER_STORAGE, 2, {GROUP_STORAGE,GROUP_DRIVER,0,0}}, + {"ramdisk", USER_STORAGE, 2, {GROUP_STORAGE,GROUP_DRIVER,0,0}}, + {"iso9660", USER_FS, 3, {GROUP_FS,GROUP_STORAGE,GROUP_DRIVER,0}}, + {"ext2", USER_FS, 3, {GROUP_FS,GROUP_STORAGE,GROUP_DRIVER,0}}, +}; + +int main(void) { + /* give ourself a name */ + strcpy(__progname,"initloader"); + + if(getpid() > 1) + error("It's not good to start init twice ;)"); + + /* perform some additional initialization in the kernel */ + /* on MMIX, this needs multiple steps */ + int res = 0; + do + res = syscall0(SYSCALL_INIT); + while(res == 0); + + /* set sync file */ + char tmp[12]; + uint32_t cnt = 0; + int straceFd = open("/sys/strace",O_CREAT | O_TRUNC | O_RDWR,0666); + if(straceFd != STRACE_FILENO) + error("Got the wrong fd for /sys/strace"); + sassert(write(straceFd,&cnt,sizeof(cnt)) == sizeof(cnt)); + itoa(tmp,sizeof(tmp),straceFd); + setenv("SYSCTRC_SYNCFD",tmp); + + /* enable syscall tracing */ + if(sysconf(CONF_LOG_SYSCALLS)) { + int max = sysconf(CONF_MAX_FDS); + /* set file descriptor to an invalid value to log the trace */ + itoa(tmp,sizeof(tmp),max); + setenv("SYSCTRC_FD",tmp); + /* reinit syscall tracing */ + traceFd = -2; + } + + /* open arguments file */ + char line[256]; + char filepath[MAX_PATH_LEN]; + FILE *args = fopen("/sys/boot/arguments","r"); + if(!args) + error("Unable to open /sys/boot/arguments for reading"); + + /* load boot modules */ + for(int i = 0; !feof(args); ++i) { + fgetl(line,sizeof(line),args); + /* skip ourself */ + if(*line == '\0' || i == 0) + continue; + + int argc; + char **argv = parseArgs(line,&argc); + /* ignore modules with no wait-argument (like ramdisks) */ + if(argc < 2) + continue; + + /* all boot-modules are in /sys/boot */ + snprintf(filepath,sizeof(filepath),"/sys/boot/%s",basename(argv[0])); + argv[0] = filepath; + + int pid; + if((pid = fork()) == 0) { + /* set uid, gid and groups */ + for(size_t x = 0; x < ARRAY_SIZE(bootModUsers); ++x) { + if(strstr(argv[0],bootModUsers[x].match)) { + if(setgroups(bootModUsers[x].gcount,bootModUsers[x].gids) < 0) + error("Unable to set groups"); + if(setgid(bootModUsers[x].gids[0]) < 0) + error("Unable to set group %d",bootModUsers[x].gids[0]); + if(setuid(bootModUsers[x].uid) < 0) + error("Unable to set user %d",bootModUsers[x].uid); + break; + } + } + + execv(argv[0],(const char**)argv); + error("exec failed"); + } + else if(pid < 0) + error("fork failed"); + else { + /* wait for the device to be available */ + struct stat info; + int res; + while((res = stat(argv[1],&info)) == -ENOENT) + usleep(20 * 1000); + if(res < 0) + error("stat for %s failed",argv[1]); + } + } + fclose(args); + + /* mount root device */ + if(sysconfstr(CONF_ROOT_DEVICE,line,sizeof(line)) < 0) + error("Unable to get root device"); + int fd = open(line,O_RDWR | O_EXEC); + if(fd < 0) + error("Unable to open '%s'",line); + /* no fch{own,mod} here, because we want to change the device, not the channel */ + if(chown(line,ROOT_UID,GROUP_FS) < 0) + printe("Warning: unable to set owner of %s",line); + if(chmod(line,0770) < 0) + printe("Warning: unable to set permissions of %s",line); + + /* clone mountspace */ + if(clonems("root") < 0) + error("Unable to clone mountspace"); + + /* mount root filesystem */ + int ms = open("/sys/pid/self/ms",O_RDWR); + if(ms < 0) + error("Unable to open '/sys/pid/self/ms'"); + if(fchmod(ms,0755) < 0) + error("Unable to chmod '/sys/pid/self/ms'"); + if(mount(ms,fd,"/") < 0) + error("Unable to mount '%s' at '/'",line); + close(ms); + close(fd); + + /* exec init */ + const char *argv[] = {"/sbin/init",NULL}; + execv(argv[0],argv); + return 0; +} diff --git a/pool/shard004/C/0098242_vic_log.c b/pool/shard004/C/0098242_vic_log.c new file mode 100644 index 0000000000000000000000000000000000000000..be214094210dabf5f7099cb3c88d5d0aa9b64798 --- /dev/null +++ b/pool/shard004/C/0098242_vic_log.c @@ -0,0 +1,148 @@ +/****************************************************************************** + * @section DESCRIPTION + * + * calculates nitrogen scaling factors for all canopy layers, following eqns + * 106 and 107 in Knorr 1997. + * + * Note: this should only be applied to veg types that have a canopy, e.g. + * trees and shrubs, but not grass or tundra vegetation. + *****************************************************************************/ + +#include + +/****************************************************************************** + * @brief Finalize logging - called after all logging is completed + *****************************************************************************/ +void +finalize_logging(void) +{ + extern FILE *LOG_DEST; + + if (!(LOG_DEST == stdout || LOG_DEST == stderr)) { + fclose(LOG_DEST); + LOG_DEST = stderr; + } +} + +/****************************************************************************** + * @brief Get string of current date and time. Format YYMMDD-SSSSS. + *****************************************************************************/ +void +get_current_datetime(char *cdt) +{ + char ymd[MAXSTRING]; + struct tm *timeinfo; + unsigned long long seconds_since_midnight; + time_t curr_date_time; + + curr_date_time = time(NULL); + if (curr_date_time == -1) { + log_err("Something went wrong getting the current time!"); + } + + timeinfo = localtime(&curr_date_time); + + seconds_since_midnight = (unsigned long long) curr_date_time % CONST_CDAY; + + if (strftime(ymd, MAXSTRING - 1, "%Y%m%d", timeinfo) == 0) { + log_err("Something went wrong converting the current time info to ymd"); + } + + snprintf(cdt, MAXSTRING, "%s-%05d", ymd, seconds_since_midnight); +} + +/****************************************************************************** + * @brief Make logfile name string. + *****************************************************************************/ +void +get_logname(const char *path, + int id, + char *filename) +{ + char timestamp[MAXSTRING]; + char *ext = ".txt"; + char *prefix = "vic.log."; + + memset(timestamp, 0, MAXSTRING); + get_current_datetime(timestamp); + + memset(filename, 0, MAXSTRING); + if (id != MISSING) { + snprintf(filename, MAXSTRING - 1, "%s%s%s.%06d%s", path, prefix, + timestamp, id, ext); + } + else { + snprintf(filename, MAXSTRING - 1, "%s%s%s%s", path, prefix, + timestamp, ext); + } +} + +/****************************************************************************** + * @brief Set global log destination + *****************************************************************************/ +void +initialize_log(void) +{ + extern FILE *LOG_DEST; + + LOG_DEST = stderr; +} + +/****************************************************************************** + * @brief Set global log destination + *****************************************************************************/ +void +setup_logging(int id, + char log_path[], + FILE **logfile) +{ + extern FILE *LOG_DEST; + char logfilename[MAXSTRING]; + + if (strcmp(log_path, "MISSING") != 0) { + // Create logfile name + get_logname(log_path, id, logfilename); + + // Open Logfile + *logfile = open_file(logfilename, "w"); + + // Print log file name to stderr + log_info("Initialized Log File: %s", logfilename); + + // Set Log Destination + LOG_DEST = *logfile; + + // Write first line of log file + log_info("Initialized Log File: %s", logfilename); + } + else { + log_info("Logging to stderr"); + } +} + +/****************************************************************************** + * @brief Print traceback for current error position + *****************************************************************************/ +void +print_trace(void) +{ + void *array[50]; + size_t size; + char **strings; + size_t i; + + size = backtrace(array, 50); + strings = backtrace_symbols(array, size); + + /* Note: we are ignoring the first and last stack frame + the first is this function, the last is the linker, neither are + particularly useful */ + fprintf(LOG_DEST, + "---------------------------------------------------------------------------\n"); + fprintf(LOG_DEST, "Traceback (most recent call last):\n"); + for (i = size - 2; i > 0; i--) { + fprintf(LOG_DEST, "%s\n", strings[i]); + } + + free(strings); +} diff --git a/pool/shard004/C/0098256_pwnat.c b/pool/shard004/C/0098256_pwnat.c new file mode 100644 index 0000000000000000000000000000000000000000..f707e668b8dffffd701cce2e249fe2390231c8ab --- /dev/null +++ b/pool/shard004/C/0098256_pwnat.c @@ -0,0 +1,116 @@ +/* + * pwnat, by Samy Kamkar + * based off of udptunnel + * + * udptunnel original comments: + * + * Copyright (C) 2009 Daniel Meekins + * Contact: dmeekins - gmail + * + * 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 + +#ifndef WIN32 +#include +#else +#include "xgetopt.h" +#endif + +//#include "sys/common.h" +#include "sys/socket.h" + +int opt_debug = 0; +struct sockaddr_in remote; + +int debug_level = 1; //NO_DEBUG; +int ipver = SOCK_IPV4; + +int udpclient(int argc, char *argv[]); +int udpserver(int argc, char *argv[]); +void usage(char *progname); + +int main(int argc, char *argv[]) +{ + int ret; + int isserv = 0; + +#ifdef WIN32 + WSADATA wsa_data; + ret = WSAStartup(MAKEWORD(2,0), &wsa_data); + ERROR_GOTO(ret != 0, "WSAStartup() failed", error); +#endif + while((ret = getopt(argc, argv, "hscv6")) != EOF) + { + switch(ret) + { + case '6': + ipver = SOCK_IPV6; + break; + + case 's': + isserv = 1; + break; + + case 'c': + isserv = 0; + break; + + case 'v': + if(debug_level < 3) + debug_level++; + break; + case 'h': + /* fall through */ + default: + goto error; + } + } + + ret = 0; + if(isserv) + { + if(argc - optind < 0) + goto error; + ret = udpserver(argc - optind, argv + optind); + } + else + { + if(argc - optind != 5 && argc - optind != 6 && argc - optind != 4) + goto error; + ret = udpclient(argc - optind, argv + optind); + } + +#ifdef WIN32 + WSACleanup(); +#endif + return ret; + error: + usage(argv[0]); + exit(1); +} + +void usage(char *progname) +{ + printf("usage: %s <-s | -c> \n", progname); + printf(" -c client mode (default)\n" + " : [local ip] [proxy port (def:2222)] \n" + " -s server mode\n" + " : [local ip] [proxy port (def:2222)] [[allowed host]:[allowed port] ...]\n" + " -6 use IPv6\n" + " -v show debug output (up to 2)\n" + " -h show this help and exit\n"); +} diff --git a/pool/shard004/C/0098266_17-1.c b/pool/shard004/C/0098266_17-1.c new file mode 100644 index 0000000000000000000000000000000000000000..0f4e416912f6e73a69ec2eee5f8e3c5bfb3b2b37 --- /dev/null +++ b/pool/shard004/C/0098266_17-1.c @@ -0,0 +1,82 @@ +/* + * Copyright (c) 2003, Intel Corporation. All rights reserved. + * Created by: crystal.xiong 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. + */ + +/* + * mq_timedreceive() test plan: + * mq_timedreceive() will fail with EINVAL if message queue is + * empty and nanoseconds field value of abs_timeout is less than 0. + * + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "posixtest.h" + +#define TEST "17-1" +#define FUNCTION "mq_timedreceive" +#define ERROR_PREFIX "unexpected error: " FUNCTION " " TEST ": " + +#define NAMESIZE 50 +#define BUFFER 40 + +int main(void) +{ + char mqname[NAMESIZE], msgrv[BUFFER]; + mqd_t mqdes; + struct timespec ts; + struct mq_attr attr; + int unresolved = 0, failure = 0; + + sprintf(mqname, "/" FUNCTION "_" TEST "_%d", getpid()); + + attr.mq_msgsize = BUFFER; + attr.mq_maxmsg = BUFFER; + mqdes = mq_open(mqname, O_CREAT | O_RDWR, S_IRUSR | S_IWUSR, &attr); + if (mqdes == (mqd_t) - 1) { + perror(ERROR_PREFIX "mq_open"); + unresolved = 1; + } + ts.tv_sec = time(NULL) + 1; + ts.tv_nsec = -1; + if (mq_timedreceive(mqdes, msgrv, BUFFER, NULL, &ts) == -1) { + if (EINVAL != errno) { + printf("errno != EINVAL\n"); + failure = 1; + } + } else { + printf("FAIL: mq_timedreceive() succeed unexpectly\n"); + failure = 1; + } + if (mq_close(mqdes) != 0) { + perror(ERROR_PREFIX "mq_close"); + unresolved = 1; + } + if (mq_unlink(mqname) != 0) { + perror(ERROR_PREFIX "mq_unlink"); + unresolved = 1; + } + if (failure == 1) { + printf("Test FAILED\n"); + return PTS_FAIL; + } + if (unresolved == 1) { + printf("Test UNRESOLVED\n"); + return PTS_UNRESOLVED; + } + printf("Test PASSED\n"); + return PTS_PASS; +} diff --git a/pool/shard004/C/0098267_struct_innerprod.c b/pool/shard004/C/0098267_struct_innerprod.c new file mode 100644 index 0000000000000000000000000000000000000000..19103deae3c0e50050633a775c3611add6d1175e --- /dev/null +++ b/pool/shard004/C/0098267_struct_innerprod.c @@ -0,0 +1,117 @@ +/*BHEADER********************************************************************** + * (c) 1997 The Regents of the University of California + * + * See the file COPYRIGHT_and_DISCLAIMER for a complete copyright + * notice, contact person, and disclaimer. + * + * $Revision: 21217 $ + *********************************************************************EHEADER*/ +/****************************************************************************** + * + * Structured inner product routine + * + *****************************************************************************/ + +#include "headers.h" + + +/*-------------------------------------------------------------------------- + * hypre_StructInnerProd + *--------------------------------------------------------------------------*/ + +#ifdef HYPRE_USE_PTHREADS +double *local_result_ref[hypre_MAX_THREADS]; +#endif + +double final_innerprod_result; + + +double +hypre_StructInnerProd( hypre_StructVector *x, + hypre_StructVector *y ) +{ + double local_result; + double process_result; + + hypre_Box *x_data_box; + hypre_Box *y_data_box; + + int xi; + int yi; + + double *xp; + double *yp; + + hypre_BoxArray *boxes; + hypre_Box *box; + hypre_Index loop_size; + hypre_IndexRef start; + hypre_Index unit_stride; + + int i; + int loopi, loopj, loopk; +#ifdef HYPRE_USE_PTHREADS + int threadid = hypre_GetThreadID(); +#endif + + local_result = 0.0; + process_result = 0.0; + + hypre_SetIndex(unit_stride, 1, 1, 1); + + boxes = hypre_StructGridBoxes(hypre_StructVectorGrid(y)); + hypre_ForBoxI(i, boxes) + { + box = hypre_BoxArrayBox(boxes, i); + start = hypre_BoxIMin(box); + + x_data_box = hypre_BoxArrayBox(hypre_StructVectorDataSpace(x), i); + y_data_box = hypre_BoxArrayBox(hypre_StructVectorDataSpace(y), i); + + xp = hypre_StructVectorBoxData(x, i); + yp = hypre_StructVectorBoxData(y, i); + + hypre_BoxGetSize(box, loop_size); + +#ifdef HYPRE_USE_PTHREADS + local_result_ref[threadid] = &local_result; +#endif + + hypre_BoxLoop2Begin(loop_size, + x_data_box, start, unit_stride, xi, + y_data_box, start, unit_stride, yi); +#define HYPRE_BOX_SMP_PRIVATE loopk,loopi,loopj,xi,yi +#define HYPRE_SMP_REDUCTION_OP + +#define HYPRE_SMP_REDUCTION_VARS local_result +#include "hypre_box_smp_forloop.h" + hypre_BoxLoop2For(loopi, loopj, loopk, xi, yi) + { + local_result += xp[xi] * yp[yi]; + } + hypre_BoxLoop2End(xi, yi); + } + +#ifdef HYPRE_USE_PTHREADS + if (threadid != hypre_NumThreads) + { + for (i = 0; i < hypre_NumThreads; i++) + process_result += *local_result_ref[i]; + } + else + process_result = *local_result_ref[threadid]; +#else + process_result = local_result; +#endif + + + MPI_Allreduce(&process_result, &final_innerprod_result, 1, + MPI_DOUBLE, MPI_SUM, hypre_StructVectorComm(x)); + + +#ifdef HYPRE_USE_PTHREADS + if (threadid == 0 || threadid == hypre_NumThreads) +#endif + hypre_IncFLOPCount(2*hypre_StructVectorGlobalSize(x)); + + return final_innerprod_result; +} diff --git a/pool/shard004/C/0098268_dtls-bio.c b/pool/shard004/C/0098268_dtls-bio.c new file mode 100644 index 0000000000000000000000000000000000000000..6c55f23d8b8e7e159b72808e7ea0f18995146c5e --- /dev/null +++ b/pool/shard004/C/0098268_dtls-bio.c @@ -0,0 +1,144 @@ +/*! \file dtls-bio.h + * \author Lorenzo Miniero + * \copyright GNU General Public License v3 + * \brief OpenSSL BIO filter for fragmentation + * \details Implementation of an OpenSSL BIO filter to fix the broken + * behaviour of fragmented packets when using mem BIOs (as we do in + * Janus). See https://mta.openssl.org/pipermail/openssl-users/2015-June/001503.html + * and https://github.com/meetecho/janus-gateway/issues/252 for more details. + * + * \ingroup protocols + * \ref protocols + */ + +#include + +#include "dtls-bio.h" +#include "debug.h" +#include "mutex.h" + + +/* Starting MTU value for the DTLS BIO filter */ +static int mtu = 1472; +void janus_dtls_bio_filter_set_mtu(int start_mtu) { + if(start_mtu < 0) { + JANUS_LOG(LOG_ERR, "Invalid MTU...\n"); + return; + } + mtu = start_mtu; + JANUS_LOG(LOG_VERB, "Setting starting MTU in the DTLS BIO filter: %d\n", mtu); +} + +/* Filter implementation */ +int janus_dtls_bio_filter_write(BIO *h, const char *buf,int num); +long janus_dtls_bio_filter_ctrl(BIO *h, int cmd, long arg1, void *arg2); +int janus_dtls_bio_filter_new(BIO *h); +int janus_dtls_bio_filter_free(BIO *data); + +static BIO_METHOD janus_dtls_bio_filter_methods = { + BIO_TYPE_FILTER, + "janus filter", + janus_dtls_bio_filter_write, + NULL, + NULL, + NULL, + janus_dtls_bio_filter_ctrl, + janus_dtls_bio_filter_new, + janus_dtls_bio_filter_free, + NULL +}; +BIO_METHOD *BIO_janus_dtls_filter(void) { + return(&janus_dtls_bio_filter_methods); +} + + +/* Helper struct to keep the filter state */ +typedef struct janus_dtls_bio_filter { + GList *packets; + janus_mutex mutex; +} janus_dtls_bio_filter; + + +int janus_dtls_bio_filter_new(BIO *bio) { + /* Create a filter state struct */ + janus_dtls_bio_filter *filter = g_malloc0(sizeof(janus_dtls_bio_filter)); + filter->packets = NULL; + janus_mutex_init(&filter->mutex); + + /* Set the BIO as initialized */ + bio->init = 1; + bio->ptr = filter; + bio->flags = 0; + + return 1; +} + +int janus_dtls_bio_filter_free(BIO *bio) { + if(bio == NULL) + return 0; + + /* Get rid of the filter state */ + janus_dtls_bio_filter *filter = (janus_dtls_bio_filter *)bio->ptr; + if(filter != NULL) { + g_list_free(filter->packets); + filter->packets = NULL; + g_free(filter); + } + bio->ptr = NULL; + bio->init = 0; + bio->flags = 0; + return 1; +} + +int janus_dtls_bio_filter_write(BIO *bio, const char *in, int inl) { + JANUS_LOG(LOG_HUGE, "janus_dtls_bio_filter_write: %p, %d\n", in, inl); + /* Forward data to the write BIO */ + long ret = BIO_write(bio->next_bio, in, inl); + JANUS_LOG(LOG_HUGE, " -- %ld\n", ret); + + /* Keep track of the packet, as we'll advertize them one by one after a pending check */ + janus_dtls_bio_filter *filter = (janus_dtls_bio_filter *)bio->ptr; + if(filter != NULL) { + janus_mutex_lock(&filter->mutex); + filter->packets = g_list_append(filter->packets, GINT_TO_POINTER(ret)); + janus_mutex_unlock(&filter->mutex); + JANUS_LOG(LOG_HUGE, "New list length: %d\n", g_list_length(filter->packets)); + } + return ret; +} + +long janus_dtls_bio_filter_ctrl(BIO *bio, int cmd, long num, void *ptr) { + switch(cmd) { + case BIO_CTRL_FLUSH: + /* The OpenSSL library needs this */ + return 1; + case BIO_CTRL_DGRAM_QUERY_MTU: + /* Let's force the MTU that was configured */ + JANUS_LOG(LOG_HUGE, "Advertizing MTU: %d\n", mtu); + return mtu; + case BIO_CTRL_WPENDING: + return 0L; + case BIO_CTRL_PENDING: { + /* We only advertize one packet at a time, as they may be fragmented */ + janus_dtls_bio_filter *filter = (janus_dtls_bio_filter *)bio->ptr; + if(filter == NULL) + return 0; + janus_mutex_lock(&filter->mutex); + if(g_list_length(filter->packets) == 0) { + janus_mutex_unlock(&filter->mutex); + return 0; + } + /* Get the first packet that hasn't been read yet */ + GList *first = g_list_first(filter->packets); + filter->packets = g_list_remove_link(filter->packets, first); + int pending = GPOINTER_TO_INT(first->data); + g_list_free(first); + janus_mutex_unlock(&filter->mutex); + /* We return its size so that only part of the buffer is read from the write BIO */ + return pending; + } + default: + JANUS_LOG(LOG_HUGE, "janus_dtls_bio_filter_ctrl: %d\n", cmd); + } + return 0; +} diff --git a/pool/shard004/C/0098281_susp.c b/pool/shard004/C/0098281_susp.c new file mode 100644 index 0000000000000000000000000000000000000000..243dd56876c0a7c471e4168450acdf9ae4433905 --- /dev/null +++ b/pool/shard004/C/0098281_susp.c @@ -0,0 +1,342 @@ +/* + * susp.c + * + * Demonstrate an implementation of thread suspend and resume + * (similar to the Solaris thr_suspend/thr_continue functions) + * using portable POSIX functions. + * + * Note 1: Use of suspend and resume requires extreme care. You + * can easily deadlock your application by suspending a thread + * that holds some resource -- for example, a thread calling + * printf to print a message may have libc mutexes locked, and + * no other thread will be able to return from printf until the + * suspended thread is resumed. + * + * Note 2: This program is called "susp" rather than "suspend" + * to avoid confusion (by your shell) with the suspend command. + * + * Note 3: This simple program will fail if any thread + * terminates during the test. The value of ITERATIONS must be + * adjusted to a value sufficiently large that the main thread can + * complete its two suspend/continue loops before any + * thread_routine threads terminate. + */ +#include +#include +#include +#include "errors.h" + +#define THREAD_COUNT 20 +#define ITERATIONS 40000 + +unsigned long thread_count = THREAD_COUNT; +unsigned long iterations = ITERATIONS; +pthread_mutex_t the_mutex = PTHREAD_MUTEX_INITIALIZER; +pthread_mutex_t mut = PTHREAD_MUTEX_INITIALIZER; +volatile int sentinel = 0; +pthread_once_t once = PTHREAD_ONCE_INIT; +pthread_t *array = NULL, null_pthread = {0}; +int bottom = 0; +int inited = 0; + +/* + * Handle SIGUSR1 in the target thread, to suspend it until + * receiving SIGUSR2 (resume). + */ +void +suspend_signal_handler (int sig) +{ + sigset_t signal_set; + + /* + * Block all signals except SIGUSR2 while suspended. + */ + sigfillset (&signal_set); + sigdelset (&signal_set, SIGUSR2); + sentinel = 1; + sigsuspend (&signal_set); + + /* + * Once I'm here, I've been resumed, and the resume signal + * handler has been run to completion. + */ + return; +} + +/* + * Handle SIGUSR2 in the target thread, to resume it. Note that + * the signal handler does nothing. It exists only because we need + * to cause sigsuspend() to return. + */ +void +resume_signal_handler (int sig) +{ + return; +} + +/* + * Dynamically initialize the "suspend package" when first used + * (called by pthread_once). + */ +void +suspend_init_routine (void) +{ + int status; + struct sigaction sigusr1, sigusr2; + + /* + * Allocate the suspended threads array. This array is used + * to guarentee idempotency + */ + bottom = 10; + array = (pthread_t*) calloc (bottom, sizeof (pthread_t)); + + /* + * Install the signal handlers for suspend/resume. + */ + sigusr1.sa_flags = 0; + sigusr1.sa_handler = suspend_signal_handler; + + sigemptyset (&sigusr1.sa_mask); + sigusr2.sa_flags = 0; + sigusr2.sa_handler = resume_signal_handler; + sigusr2.sa_mask = sigusr1.sa_mask; + + status = sigaction (SIGUSR1, &sigusr1, NULL); + if (status == -1) + errno_abort ("Installing suspend handler"); + + status = sigaction (SIGUSR2, &sigusr2, NULL); + if (status == -1) + errno_abort ("Installing resume handler"); + + inited = 1; + return; +} + +/* + * Suspend a thread by sending it a signal (SIGUSR1), which will + * block the thread until another signal (SIGUSR2) arrives. + * + * Multiple calls to thd_suspend for a single thread have no + * additional effect on the thread -- a single thd_continue + * call will cause it to resume execution. + */ +int +thd_suspend (pthread_t target_thread) +{ + int status; + int i = 0; + + /* + * The first call to thd_suspend will initialize the + * package. + */ + status = pthread_once (&once, suspend_init_routine); + if (status != 0) + return status; + + /* + * Serialize access to suspend, makes life easier + */ + status = pthread_mutex_lock (&mut); + if (status != 0) + return status; + + /* + * Threads that are suspended are added to the target_array; + * a request to suspend a thread already listed in the array + * is ignored. Sending a second SIGUSR1 would cause the + * thread to re-suspend itself as soon as it is resumed. + */ + while (i < bottom) + if (array[i++] == target_thread) { + status = pthread_mutex_unlock (&mut); + return status; + } + + /* + * Ok, we really need to suspend this thread. So, lets find + * the location in the array that we'll use. If we run off + * the end, realloc the array for more space. + */ + i = 0; + while (array[i] != 0) + i++; + + if (i == bottom) { + array = (pthread_t*) realloc ( + array, (++bottom * sizeof (pthread_t))); + if (array == NULL) { + pthread_mutex_unlock (&mut); + return errno; + } + + array[bottom] = null_pthread; /* Clear new entry */ + } + + /* + * Clear the sentinel and signal the thread to suspend. + */ + sentinel = 0; + status = pthread_kill (target_thread, SIGUSR1); + if (status != 0) { + pthread_mutex_unlock (&mut); + return status; + } + + /* + * Wait for the sentinel to change. + */ + while (sentinel == 0) + sched_yield (); + + array[i] = target_thread; + + status = pthread_mutex_unlock (&mut); + return status; +} + +/* + * Resume a suspended thread by sending it SIGUSR2 to break + * it out of the sigsuspend() in which it's waiting. If the + * target thread isn't suspended, return with success. + */ +int +thd_continue (pthread_t target_thread) +{ + int status; + int i = 0; + + /* + * Serialize access to suspend, makes life easier + */ + status = pthread_mutex_lock (&mut); + if (status != 0) + return status; + + /* + * If we haven't been initialized, then the thread must be "resumed" + * it couldn't have been suspended! + */ + if (!inited) { + status = pthread_mutex_unlock (&mut); + return status; + } + + /* + * Make sure the thread is in the suspend array. If not, it + * hasn't been suspended (or it has already been resumed) and + * we can just carry on. + */ + while (array[i] != target_thread && i < bottom) + i++; + + if (i >= bottom) { + pthread_mutex_unlock (&mut); + return 0; + } + + /* + * Signal the thread to continue, and remove the thread from + * the suspended array. + */ + status = pthread_kill (target_thread, SIGUSR2); + if (status != 0) { + pthread_mutex_unlock (&mut); + return status; + } + + array[i] = 0; /* Clear array element */ + status = pthread_mutex_unlock (&mut); + return status; +} + +static void * +thread_routine (void *arg) +{ + int number = (int)arg; + int status; + int i; + char buffer[128]; + + for (i = 1; i <= iterations; i++) { + /* + * Every time each thread does 5000 interations, print + * a progress report. + */ + if (i % 2000 == 0) { + sprintf ( + buffer, "Thread %02d: %d\n", + number, i); + write (1, buffer, strlen (buffer)); + } + + sched_yield (); + } + + return (void *)0; +} + +int +main (int argc, char *argv[]) +{ + pthread_t threads[THREAD_COUNT]; + pthread_attr_t detach; + int status; + void *result; + int i; + + status = pthread_attr_init (&detach); + if (status != 0) + err_abort (status, "Init attributes object"); + status = pthread_attr_setdetachstate ( + &detach, PTHREAD_CREATE_DETACHED); + if (status != 0) + err_abort (status, "Set create-detached"); + + for (i = 0; i< THREAD_COUNT; i++) { + status = pthread_create ( + &threads[i], &detach, thread_routine, (void *)i); + if (status != 0) + err_abort (status, "Create thread"); + } + + sleep (2); + + for (i = 0; i < THREAD_COUNT/2; i++) { + printf ("Suspending thread %d.\n", i); + status = thd_suspend (threads[i]); + if (status != 0) + err_abort (status, "Suspend thread"); + } + + printf ("Sleeping ...\n"); + sleep (2); + + for (i = 0; i < THREAD_COUNT/2; i++) { + printf ("Continuing thread %d.\n", i); + status = thd_continue (threads[i]); + if (status != 0) + err_abort (status, "Suspend thread"); + } + + for (i = THREAD_COUNT/2; i < THREAD_COUNT; i++) { + printf ("Suspending thread %d.\n", i); + status = thd_suspend (threads[i]); + if (status != 0) + err_abort (status, "Suspend thread"); + } + + printf ("Sleeping ...\n"); + sleep (2); + + for (i = THREAD_COUNT/2; i < THREAD_COUNT; i++) { + printf ("Continuing thread %d.\n", i); + status = thd_continue (threads[i]); + if (status != 0) + err_abort (status, "Continue thread"); + } + + pthread_exit (NULL); /* Let threads finish */ +} diff --git a/pool/shard004/C/0098282_Nonce.c b/pool/shard004/C/0098282_Nonce.c new file mode 100644 index 0000000000000000000000000000000000000000..438d117fd721378104123f2a780a18d617c283c8 --- /dev/null +++ b/pool/shard004/C/0098282_Nonce.c @@ -0,0 +1,84 @@ +/* + * 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 "Nonce.h" + +int decode_nonce(Nonce *nonce, uint8_t iei, uint8_t *buffer, uint32_t len) +{ + int decoded = 0; + + if (iei > 0) { + CHECK_IEI_DECODER(iei, *buffer); + decoded++; + } + + //IES_DECODE_U32(*nonce, *(buffer + decoded)); + IES_DECODE_U32(buffer, decoded, *nonce); +#if defined (NAS_DEBUG) + dump_nonce_xml(nonce, iei); +#endif + return decoded; +} + +int encode_nonce(Nonce *nonce, uint8_t iei, uint8_t *buffer, uint32_t len) +{ + uint32_t encoded = 0; + /* Checking IEI and pointer */ + CHECK_PDU_POINTER_AND_LENGTH_ENCODER(buffer, NONCE_MINIMUM_LENGTH, len); +#if defined (NAS_DEBUG) + dump_nonce_xml(nonce, iei); +#endif + + if (iei > 0) { + *buffer = iei; + encoded++; + } + + IES_ENCODE_U32(buffer, encoded, *nonce); + return encoded; +} + +void dump_nonce_xml(Nonce *nonce, uint8_t iei) +{ + printf("\n"); + + if (iei > 0) + /* Don't display IEI if = 0 */ + printf(" 0x%X\n", iei); + + printf(" %u\n", *nonce); + printf("\n"); +} + diff --git a/pool/shard004/C/0098288_oss.c b/pool/shard004/C/0098288_oss.c new file mode 100644 index 0000000000000000000000000000000000000000..72a73abf7614e566f8fe3c93c3962dc06980b237 --- /dev/null +++ b/pool/shard004/C/0098288_oss.c @@ -0,0 +1,219 @@ +/* RetroArch - A frontend for libretro. + * Copyright (C) 2010-2014 - Hans-Kristian Arntzen + * + * 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 +#include +#include + +#ifdef HAVE_OSS_BSD +#include +#else +#include +#endif + +#include + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +#include "../audio_driver.h" +#include "../../configuration.h" +#include "../../verbosity.h" + +#ifdef HAVE_OSS_BSD +#define DEFAULT_OSS_DEV "/dev/audio" +#else +#define DEFAULT_OSS_DEV "/dev/dsp" +#endif + +static bool oss_is_paused; + +static void *oss_init(const char *device, unsigned rate, unsigned latency) +{ + int frags, frag, channels, format, new_rate; + int *fd = (int*)calloc(1, sizeof(int)); + settings_t *settings = config_get_ptr(); + + const char *oss_device = device ? device : DEFAULT_OSS_DEV; + + if (fd == NULL) + return NULL; + + if ((*fd = open(oss_device, O_WRONLY)) < 0) + { + free(fd); + perror("open"); + return NULL; + } + + frags = (latency * rate * 4) / (1000 * (1 << 10)); + frag = (frags << 16) | 10; + + if (ioctl(*fd, SNDCTL_DSP_SETFRAGMENT, &frag) < 0) + RARCH_WARN("Cannot set fragment sizes. Latency might not be as expected ...\n"); + + channels = 2; + format = is_little_endian() ? AFMT_S16_LE : AFMT_S16_BE; + + if (ioctl(*fd, SNDCTL_DSP_CHANNELS, &channels) < 0) + { + close(*fd); + free(fd); + perror("ioctl"); + return NULL; + } + + if (ioctl(*fd, SNDCTL_DSP_SETFMT, &format) < 0) + { + close(*fd); + free(fd); + perror("ioctl"); + return NULL; + } + + new_rate = rate; + + if (ioctl(*fd, SNDCTL_DSP_SPEED, &new_rate) < 0) + { + close(*fd); + free(fd); + perror("ioctl"); + return NULL; + } + + if (new_rate != (int)rate) + { + RARCH_WARN("Requested sample rate not supported. Adjusting output rate to %d Hz.\n", new_rate); + settings->audio.out_rate = new_rate; + } + + return fd; +} + +static ssize_t oss_write(void *data, const void *buf, size_t size) +{ + ssize_t ret; + int *fd = (int*)data; + + if (size == 0) + return 0; + + if ((ret = write(*fd, buf, size)) < 0) + { + if (errno == EAGAIN && (fcntl(*fd, F_GETFL) & O_NONBLOCK)) + return 0; + + return -1; + } + + return ret; +} + +static bool oss_stop(void *data) +{ + int *fd = (int*)data; + + ioctl(*fd, SNDCTL_DSP_RESET, 0); + oss_is_paused = true; + return true; +} + +static bool oss_start(void *data) +{ + (void)data; + oss_is_paused = false; + return true; +} + +static bool oss_alive(void *data) +{ + (void)data; + return !oss_is_paused; +} + +static void oss_set_nonblock_state(void *data, bool state) +{ + int rc; + int *fd = (int*)data; + + if (state) + rc = fcntl(*fd, F_SETFL, fcntl(*fd, F_GETFL) | O_NONBLOCK); + else + rc = fcntl(*fd, F_SETFL, fcntl(*fd, F_GETFL) & (~O_NONBLOCK)); + if (rc != 0) + RARCH_WARN("Could not set nonblocking on OSS file descriptor. Will not be able to fast-forward.\n"); +} + +static void oss_free(void *data) +{ + int *fd = (int*)data; + + ioctl(*fd, SNDCTL_DSP_RESET, 0); + close(*fd); + free(fd); +} + +static size_t oss_write_avail(void *data) +{ + audio_buf_info info; + int *fd = (int*)data; + + if (ioctl(*fd, SNDCTL_DSP_GETOSPACE, &info) < 0) + { + RARCH_ERR("SNDCTL_DSP_GETOSPACE failed ...\n"); + return 0; + } + + return info.bytes; +} + +static size_t oss_buffer_size(void *data) +{ + audio_buf_info info; + int *fd = (int*)data; + + if (ioctl(*fd, SNDCTL_DSP_GETOSPACE, &info) < 0) + { + RARCH_ERR("SNDCTL_DSP_GETOSPACE failed ...\n"); + return 1; /* Return something non-zero to avoid SIGFPE. */ + } + + return info.fragsize * info.fragstotal; +} + +static bool oss_use_float(void *data) +{ + (void)data; + return false; +} + +audio_driver_t audio_oss = { + oss_init, + oss_write, + oss_stop, + oss_start, + oss_alive, + oss_set_nonblock_state, + oss_free, + oss_use_float, + "oss", + NULL, + NULL, + oss_write_avail, + oss_buffer_size, +}; diff --git a/pool/shard004/C/0098289_cpu_pic.c b/pool/shard004/C/0098289_cpu_pic.c new file mode 100644 index 0000000000000000000000000000000000000000..6bccce2f3295304a9fb6698280c6ffeb5d3b5a48 --- /dev/null +++ b/pool/shard004/C/0098289_cpu_pic.c @@ -0,0 +1,69 @@ +/* + * Altera Nios2 CPU PIC + * + * Copyright (c) 2016 Marek Vasut + * + * 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, see + * + */ + +#include "qemu/osdep.h" +#include "qemu-common.h" +#include "cpu.h" + +#include "qemu/config-file.h" + +#include "boot.h" + +static void nios2_pic_cpu_handler(void *opaque, int irq, int level) +{ + Nios2CPU *cpu = opaque; + CPUNios2State *env = &cpu->env; + CPUState *cs = CPU(cpu); + int type = irq ? CPU_INTERRUPT_NMI : CPU_INTERRUPT_HARD; + + if (type == CPU_INTERRUPT_HARD) { + env->irq_pending = level; + + if (level && (env->regs[CR_STATUS] & CR_STATUS_PIE)) { + env->irq_pending = 0; + cpu_interrupt(cs, type); + } else if (!level) { + env->irq_pending = 0; + cpu_reset_interrupt(cs, type); + } + } else { + if (level) { + cpu_interrupt(cs, type); + } else { + cpu_reset_interrupt(cs, type); + } + } +} + +void nios2_check_interrupts(CPUNios2State *env) +{ + Nios2CPU *cpu = nios2_env_get_cpu(env); + CPUState *cs = CPU(cpu); + + if (env->irq_pending) { + env->irq_pending = 0; + cpu_interrupt(cs, CPU_INTERRUPT_HARD); + } +} + +qemu_irq *nios2_cpu_pic_init(Nios2CPU *cpu) +{ + return qemu_allocate_irqs(nios2_pic_cpu_handler, cpu, 2); +} diff --git a/pool/shard004/C/0098293_const_log2.c b/pool/shard004/C/0098293_const_log2.c new file mode 100644 index 0000000000000000000000000000000000000000..8ae1ee99b25fce3b768de8159c497b79e12939e5 --- /dev/null +++ b/pool/shard004/C/0098293_const_log2.c @@ -0,0 +1,188 @@ +/* mpfr_const_log2 -- compute natural logarithm of 2 + +Copyright 1999, 2001-2017 Free Software Foundation, Inc. +Contributed by the AriC and Caramba projects, INRIA. + +This file is part of the GNU MPFR Library. + +The GNU MPFR Library is free software; you can redistribute it and/or modify +it under the terms of the GNU Lesser General Public License as published by +the Free Software Foundation; either version 3 of the License, or (at your +option) any later version. + +The GNU MPFR Library is distributed in the hope that it will be useful, but +WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY +or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public +License for more details. + +You should have received a copy of the GNU Lesser General Public License +along with the GNU MPFR Library; see the file COPYING.LESSER. If not, see +http://www.gnu.org/licenses/ or write to the Free Software Foundation, Inc., +51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA. */ + +#define MPFR_NEED_LONGLONG_H +#include "mpfr-impl.h" + +/* Declare the cache */ +#ifndef MPFR_USE_LOGGING +MPFR_DECL_INIT_CACHE (__gmpfr_cache_const_log2, mpfr_const_log2_internal) +#else +MPFR_DECL_INIT_CACHE (__gmpfr_normal_log2, mpfr_const_log2_internal) +MPFR_DECL_INIT_CACHE (__gmpfr_logging_log2, mpfr_const_log2_internal) +MPFR_THREAD_VAR (mpfr_cache_ptr, __gmpfr_cache_const_log2, __gmpfr_normal_log2) +#endif + +/* Set User interface */ +#undef mpfr_const_log2 +int +mpfr_const_log2 (mpfr_ptr x, mpfr_rnd_t rnd_mode) { + return mpfr_cache (x, __gmpfr_cache_const_log2, rnd_mode); +} + +/* Auxiliary function: Compute the terms from n1 to n2 (excluded) + 3/4*sum((-1)^n*n!^2/2^n/(2*n+1)!, n = n1..n2-1). + Numerator is T[0], denominator is Q[0], + Compute P[0] only when need_P is non-zero. + Need 1+ceil(log(n2-n1)/log(2)) cells in T[],P[],Q[]. +*/ +static void +S (mpz_t *T, mpz_t *P, mpz_t *Q, unsigned long n1, unsigned long n2, int need_P) +{ + if (n2 == n1 + 1) + { + if (n1 == 0) + mpz_set_ui (P[0], 3); + else + { + mpz_set_ui (P[0], n1); + mpz_neg (P[0], P[0]); + } + if (n1 <= (ULONG_MAX / 4 - 1) / 2) + mpz_set_ui (Q[0], 4 * (2 * n1 + 1)); + else /* to avoid overflow in 4 * (2 * n1 + 1) */ + { + mpz_set_ui (Q[0], n1); + mpz_mul_2exp (Q[0], Q[0], 1); + mpz_add_ui (Q[0], Q[0], 1); + mpz_mul_2exp (Q[0], Q[0], 2); + } + mpz_set (T[0], P[0]); + } + else + { + unsigned long m = (n1 / 2) + (n2 / 2) + (n1 & 1UL & n2); + unsigned long v, w; + + S (T, P, Q, n1, m, 1); + S (T + 1, P + 1, Q + 1, m, n2, need_P); + mpz_mul (T[0], T[0], Q[1]); + mpz_mul (T[1], T[1], P[0]); + mpz_add (T[0], T[0], T[1]); + if (need_P) + mpz_mul (P[0], P[0], P[1]); + mpz_mul (Q[0], Q[0], Q[1]); + + /* remove common trailing zeroes if any */ + v = mpz_scan1 (T[0], 0); + if (v > 0) + { + w = mpz_scan1 (Q[0], 0); + if (w < v) + v = w; + if (need_P) + { + w = mpz_scan1 (P[0], 0); + if (w < v) + v = w; + } + /* now v = min(val(T), val(Q), val(P)) */ + if (v > 0) + { + mpz_fdiv_q_2exp (T[0], T[0], v); + mpz_fdiv_q_2exp (Q[0], Q[0], v); + if (need_P) + mpz_fdiv_q_2exp (P[0], P[0], v); + } + } + } +} + +/* Don't need to save / restore exponent range: the cache does it */ +int +mpfr_const_log2_internal (mpfr_ptr x, mpfr_rnd_t rnd_mode) +{ + unsigned long n = MPFR_PREC (x); + mpfr_prec_t w; /* working precision */ + unsigned long N; + mpz_t *T, *P, *Q; + mpfr_t t, q; + int inexact; + unsigned long lgN, i; + MPFR_GROUP_DECL(group); + MPFR_TMP_DECL(marker); + MPFR_ZIV_DECL(loop); + + MPFR_LOG_FUNC ( + ("rnd_mode=%d", rnd_mode), + ("x[%Pu]=%.*Rg inex=%d", mpfr_get_prec(x), mpfr_log_prec, x, inexact)); + + if (n < 1069) + w = n + 9; /* ensures correct rounding for the four rounding modes, + together with N = w / 3 + 1 (see below). */ + else + w = n + 10; /* idem at least for prec < 300000 */ + + MPFR_TMP_MARK(marker); + MPFR_GROUP_INIT_2(group, w, t, q); + + MPFR_ZIV_INIT (loop, w); + for (;;) + { + N = w / 3 + 1; /* Warning: do not change that (even increasing N!) + without checking correct rounding in the above + ranges for n. */ + + /* the following are needed for error analysis (see algorithms.tex) */ + MPFR_ASSERTD(w >= 3 && N >= 2); + + lgN = MPFR_INT_CEIL_LOG2 (N) + 1; + T = (mpz_t *) MPFR_TMP_ALLOC (3 * lgN * sizeof (mpz_t)); + P = T + lgN; + Q = T + 2*lgN; + for (i = 0; i < lgN; i++) + { + mpz_init (T[i]); + mpz_init (P[i]); + mpz_init (Q[i]); + } + + S (T, P, Q, 0, N, 0); + + mpfr_set_z (t, T[0], MPFR_RNDN); + mpfr_set_z (q, Q[0], MPFR_RNDN); + mpfr_div (t, t, q, MPFR_RNDN); + + for (i = 0; i < lgN; i++) + { + mpz_clear (T[i]); + mpz_clear (P[i]); + mpz_clear (Q[i]); + } + + /* for prec < 300000 and all rounding modes we checked by exhaustive + search that the rounding is correct */ + if (MPFR_LIKELY (n < 300000 || MPFR_CAN_ROUND (t, w - 2, n, rnd_mode))) + break; + + MPFR_ZIV_NEXT (loop, w); + MPFR_GROUP_REPREC_2(group, w, t, q); + } + MPFR_ZIV_FREE (loop); + + inexact = mpfr_set (x, t, rnd_mode); + + MPFR_GROUP_CLEAR(group); + MPFR_TMP_FREE(marker); + + return inexact; +} diff --git a/pool/shard004/C/0098301_versatile_pci.c b/pool/shard004/C/0098301_versatile_pci.c new file mode 100644 index 0000000000000000000000000000000000000000..67cee88e8600f58494bf32625a5d5645fe27da1a --- /dev/null +++ b/pool/shard004/C/0098301_versatile_pci.c @@ -0,0 +1,144 @@ +/* + * ARM Versatile/PB PCI host controller + * + * Copyright (c) 2006 CodeSourcery. + * Written by Paul Brook + * + * This code is licenced under the LGPL. + */ + +#include "hw.h" +#include "pci.h" +#include "primecell.h" + +static inline uint32_t vpb_pci_config_addr(target_phys_addr_t addr) +{ + return addr & 0xffffff; +} + +static void pci_vpb_config_writeb (void *opaque, target_phys_addr_t addr, + uint32_t val) +{ + pci_data_write(opaque, vpb_pci_config_addr (addr), val, 1); +} + +static void pci_vpb_config_writew (void *opaque, target_phys_addr_t addr, + uint32_t val) +{ +#ifdef TARGET_WORDS_BIGENDIAN + val = bswap16(val); +#endif + pci_data_write(opaque, vpb_pci_config_addr (addr), val, 2); +} + +static void pci_vpb_config_writel (void *opaque, target_phys_addr_t addr, + uint32_t val) +{ +#ifdef TARGET_WORDS_BIGENDIAN + val = bswap32(val); +#endif + pci_data_write(opaque, vpb_pci_config_addr (addr), val, 4); +} + +static uint32_t pci_vpb_config_readb (void *opaque, target_phys_addr_t addr) +{ + uint32_t val; + val = pci_data_read(opaque, vpb_pci_config_addr (addr), 1); + return val; +} + +static uint32_t pci_vpb_config_readw (void *opaque, target_phys_addr_t addr) +{ + uint32_t val; + val = pci_data_read(opaque, vpb_pci_config_addr (addr), 2); +#ifdef TARGET_WORDS_BIGENDIAN + val = bswap16(val); +#endif + return val; +} + +static uint32_t pci_vpb_config_readl (void *opaque, target_phys_addr_t addr) +{ + uint32_t val; + val = pci_data_read(opaque, vpb_pci_config_addr (addr), 4); +#ifdef TARGET_WORDS_BIGENDIAN + val = bswap32(val); +#endif + return val; +} + +static CPUWriteMemoryFunc *pci_vpb_config_write[] = { + &pci_vpb_config_writeb, + &pci_vpb_config_writew, + &pci_vpb_config_writel, +}; + +static CPUReadMemoryFunc *pci_vpb_config_read[] = { + &pci_vpb_config_readb, + &pci_vpb_config_readw, + &pci_vpb_config_readl, +}; + +static int pci_vpb_irq; + +static int pci_vpb_map_irq(PCIDevice *d, int irq_num) +{ + return irq_num; +} + +static void pci_vpb_set_irq(qemu_irq *pic, int irq_num, int level) +{ + qemu_set_irq(pic[pci_vpb_irq + irq_num], level); +} + +PCIBus *pci_vpb_init(qemu_irq *pic, int irq, int realview) +{ + PCIBus *s; + PCIDevice *d; + int mem_config; + uint32_t base; + const char * name; + + pci_vpb_irq = irq; + if (realview) { + base = 0x60000000; + name = "RealView EB PCI Controller"; + } else { + base = 0x40000000; + name = "Versatile/PB PCI Controller"; + } + s = pci_register_bus(pci_vpb_set_irq, pci_vpb_map_irq, pic, 11 << 3, 4); + /* ??? Register memory space. */ + + mem_config = cpu_register_io_memory(0, pci_vpb_config_read, + pci_vpb_config_write, s); + /* Selfconfig area. */ + cpu_register_physical_memory(base + 0x01000000, 0x1000000, mem_config); + /* Normal config area. */ + cpu_register_physical_memory(base + 0x02000000, 0x1000000, mem_config); + + d = pci_register_device(s, name, sizeof(PCIDevice), -1, NULL, NULL); + + if (realview) { + /* IO memory area. */ + isa_mmio_init(base + 0x03000000, 0x00100000); + } + + d->config[0x00] = 0xee; // vendor_id + d->config[0x01] = 0x10; + /* Both boards have the same device ID. Oh well. */ + d->config[0x02] = 0x00; // device_id + d->config[0x03] = 0x03; + d->config[0x04] = 0x00; + d->config[0x05] = 0x00; + d->config[0x06] = 0x20; + d->config[0x07] = 0x02; + d->config[0x08] = 0x00; // revision + d->config[0x09] = 0x00; // programming i/f + d->config[0x0A] = 0x40; // class_sub = pci host + d->config[0x0B] = 0x0b; // class_base = PCI_bridge + d->config[0x0D] = 0x10; // latency_timer + + return s; +} + diff --git a/pool/shard004/C/0098320_kb_xps_9350.c b/pool/shard004/C/0098320_kb_xps_9350.c new file mode 100644 index 0000000000000000000000000000000000000000..792dc908a99e0b0a19de8d846a51b0588d1f5180 --- /dev/null +++ b/pool/shard004/C/0098320_kb_xps_9350.c @@ -0,0 +1,122 @@ +/** + * @file xps_9350.c + * @brief + * @author Travis Lane + * @version + * @date 2016-02-15 + */ + +#include +#include + +#include "keyboard_backlight.h" +#include "keyboard_backlight_internal.h" +#include "sysfs_utils.h" + +struct kb_xps_9350 { + const char *kbx_brightness_path; + const char *kbx_max_brightness_path; +}; + +#define kb_xps_9350_path "/sys/devices/platform/dell-laptop/leds/dell::kbd_backlight" + +static struct kb_xps_9350 g_xps_9350_ctx = { + kb_xps_9350_path "/brightness", + kb_xps_9350_path "/max_brightness" +}; + +int xps_9350_get_brightness(struct kb_controller *kb, int *out_brightness); +int xps_9350_set_brightness(struct kb_controller *kb, int brightness); +int xps_9350_get_max_brightness(struct kb_controller *kb, int *out_max); +int xps_9350_get_step_brightness(struct kb_controller *kb, int *out_step); + +struct kb_controller * +kb_controller_xps_9350_new(struct udev_device *device) +{ + struct kb_controller *kb; + kb = kb_controller_new(device, KBCT_XPS_9350, &g_xps_9350_ctx); + + + kb->kbc_get_brightness = xps_9350_get_brightness; + kb->kbc_set_brightness = xps_9350_set_brightness; + + kb->kbc_get_max_brightness = xps_9350_get_max_brightness; + kb->kbc_get_step_brightness = xps_9350_get_step_brightness; + + return kb; +} + +struct udev_device * +kb_controller_xps_9350_find_first(struct udev *udev_ctx) +{ + struct udev_device *dev = NULL; + struct udev_enumerate *enumer = NULL; + struct udev_list_entry *devs = NULL, *dev_entry = NULL; + + enumer = udev_enumerate_new(udev_ctx); + udev_enumerate_add_syspath(enumer, kb_xps_9350_path); + + // Scan and get the list of items found. + udev_enumerate_scan_devices(enumer); + devs = udev_enumerate_get_list_entry(enumer); + + + udev_list_entry_foreach(dev_entry, devs) { + const char *path; + path = udev_list_entry_get_name(dev_entry); + dev = udev_device_new_from_syspath(udev_ctx, path); + + /* Found the device we were looking for. */ + udev_device_ref(dev); + break; + } + + udev_enumerate_unref(enumer); + return dev; +} + +int +xps_9350_get_brightness(struct kb_controller *kb, int *out_brightness) +{ + struct kb_xps_9350 *ctx; + assert(kb->kbc_type == KBCT_XPS_9350); + assert(kb->kbc_ctx != NULL); + + ctx = kb->kbc_ctx; + + return sysfs_read_attr_int(ctx->kbx_brightness_path, out_brightness); +} + + +int +xps_9350_set_brightness(struct kb_controller *kb, int brightness) +{ + struct kb_xps_9350 *ctx; + assert(kb->kbc_type == KBCT_XPS_9350); + assert(kb->kbc_ctx != NULL); + + ctx = kb->kbc_ctx; + + return sysfs_write_attr_int(ctx->kbx_brightness_path, brightness); +} + +int +xps_9350_get_max_brightness(struct kb_controller *kb, int *out_max) +{ + struct kb_xps_9350 *ctx; + assert(kb->kbc_type == KBCT_XPS_9350); + assert(kb->kbc_ctx != NULL); + + ctx = kb->kbc_ctx; + + return sysfs_read_attr_int(ctx->kbx_max_brightness_path, out_max); +} + +int +xps_9350_get_step_brightness(struct kb_controller *kb, int *out_step) +{ + assert(kb->kbc_type == KBCT_XPS_9350); + + *out_step = 1; + return 0; +} diff --git a/pool/shard004/C/0098329_acpi_tables.c b/pool/shard004/C/0098329_acpi_tables.c new file mode 100644 index 0000000000000000000000000000000000000000..47e0a3ab8c8e76ac3b380ca7109e78868bdb47b9 --- /dev/null +++ b/pool/shard004/C/0098329_acpi_tables.c @@ -0,0 +1,129 @@ +/* + * Island Aruma ACPI support + * written by Stefan Reinauer + * (C) 2005 Stefan Reinauer + * + * Copyright 2005 AMD + * 2005.9 yhlu modify that to more dynamic for AMD Opteron Based MB + * + * Copyright (C) 2011,2014 Oskar Enoksson + * Modified to work with hp/dl145_g1 + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "northbridge/amd/amdk8/acpi.h" +#include "mb_sysconf.h" +#include + +unsigned long acpi_fill_madt(unsigned long current) +{ + unsigned int gsi_base = 0x18; + + struct mb_sysconf_t *m; + + get_bus_conf(); + + m = sysconf.mb; + + /* create all subtables for processors */ + current = acpi_create_madt_lapics(current); + + /* Write 8111 IOAPIC */ + current += acpi_create_madt_ioapic((acpi_madt_ioapic_t *)current, m->apicid_8111, + IO_APIC_ADDR, 0); + + /* Write all 8131 IOAPICs */ + { + device_t dev; + struct resource *res; + dev = dev_find_slot(m->bus_8131_0, PCI_DEVFN((sysconf.hcdn[0]&0xff), 1)); + if (dev) { + res = find_resource(dev, PCI_BASE_ADDRESS_0); + if (res) { + current += acpi_create_madt_ioapic((acpi_madt_ioapic_t *)current, m->apicid_8131_1, + res->base, gsi_base ); + gsi_base+=4; + + } + } + dev = dev_find_slot(m->bus_8131_0, PCI_DEVFN((sysconf.hcdn[0] & 0xff)+1, 1)); + if (dev) { + res = find_resource(dev, PCI_BASE_ADDRESS_0); + if (res) { + current += acpi_create_madt_ioapic((acpi_madt_ioapic_t *)current, m->apicid_8131_2, + res->base, gsi_base ); + gsi_base+=4; + } + } + + /* + int i; + int j = 0; + + for(i = 1; i< sysconf.hc_possible_num; i++) { + unsigned d = 0; + if(!(sysconf.pci1234[i] & 0x1) ) continue; + // 8131 need to use +4 + + switch (sysconf.hcid[i]) { + case 1: + d = 7; + break; + case 3: + d = 4; + break; + } + switch (sysconf.hcid[i]) { + case 1: + case 3: + dev = dev_find_slot(m->bus_8132a[j][0], PCI_DEVFN(m->sbdn3a[j], 1)); + if (dev) { + res = find_resource(dev, PCI_BASE_ADDRESS_0); + if (res) { + current += acpi_create_madt_ioapic((acpi_madt_ioapic_t *)current, m->apicid_8132a[j][0], + res->base, gsi_base ); + gsi_base+=d; + } + } + dev = dev_find_slot(m->bus_8132a[j][0], PCI_DEVFN(m->sbdn3a[j]+1, 1)); + if (dev) { + res = find_resource(dev, PCI_BASE_ADDRESS_0); + if (res) { + current += acpi_create_madt_ioapic((acpi_madt_ioapic_t *)current, m->apicid_8132a[j][1], + res->base, gsi_base ); + gsi_base+=d; + + } + } + break; + } + + j++; + } + */ + + } + + current += acpi_create_madt_irqoverride( (acpi_madt_irqoverride_t *) + current, 0, 0, 2, 5 ); + /* 0: mean bus 0--->ISA */ + /* 0: PIC 0 */ + /* 2: APIC 2 */ + /* 5 mean: 0101 --> Edge-triggered, Active high*/ + + + /* create all subtables for processors */ + current = acpi_create_madt_lapic_nmis(current, 5, 1); + /* 1: LINT1 connect to NMI */ + + + return current; +} diff --git a/pool/shard004/C/0098332_lprintf.c b/pool/shard004/C/0098332_lprintf.c new file mode 100644 index 0000000000000000000000000000000000000000..48a2ec1cc9f33393bfca747f3dbe9f43be617e8e --- /dev/null +++ b/pool/shard004/C/0098332_lprintf.c @@ -0,0 +1,94 @@ +/* Emacs style mode select -*- C++ -*- + *----------------------------------------------------------------------------- + * + * + * PrBoom a Doom port merged with LxDoom and LSDLDoom + * based on BOOM, a modified and improved DOOM engine + * Copyright (C) 1999 by + * id Software, Chi Hoang, Lee Killough, Jim Flynn, Rand Phares, Ty Halderman + * Copyright (C) 1999-2000 by + * Jess Haas, Nicolas Kalkhof, Colin Phipps, Florian Schulze + * + * 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. + * + * DESCRIPTION: + * Provides a logical console output routine that allows what is + * output to console normally and when output is redirected to + * be controlled.. + * + *-----------------------------------------------------------------------------*/ + +#include +#include +#include +#include "doomtype.h" +#include "lprintf.h" +#include "i_main.h" +#include "m_argv.h" + +int cons_error_mask = -1-LO_INFO; /* all but LO_INFO when redir'd */ +int cons_output_mask = -1; /* all output enabled */ + +/* cphipps - enlarged message buffer and made non-static + * We still have to be careful here, this function can be called after exit + */ +#define MAX_MESSAGE_SIZE 2048 + +int lprintf(OutputLevels pri, const char *s, ...) +{ + int r=0; + char msg[MAX_MESSAGE_SIZE]; + int lvl=pri; + + va_list v; + va_start(v,s); + + vsprintf(msg,s,v); + + va_end(v); + + if (lvl&cons_output_mask) /* mask output as specified */ + { + r=fprintf(stdout,"%s",msg); + } + if (!isatty(1) && lvl&cons_error_mask) /* if stdout redirected */ + r=fprintf(stderr,"%s",msg); /* select output at console */ + + return r; +} + +/* + * I_Error + * + * cphipps - moved out of i_* headers, to minimise source files that depend on + * the low-level headers. All this does is print the error, then call the + * low-level safe exit function. + * killough 3/20/98: add const + */ + +void I_Error(const char *error, ...) +{ + char errmsg[MAX_MESSAGE_SIZE]; + va_list argptr; + va_start(argptr,error); + + vsprintf(errmsg,error,argptr); + + va_end(argptr); + fprintf(stderr,"%s\n",errmsg); + + I_SafeExit(-1); +} diff --git a/pool/shard004/C/0098335_promote.c b/pool/shard004/C/0098335_promote.c new file mode 100644 index 0000000000000000000000000000000000000000..f516f28a27732a9640c9a3396e9186739a9b2a16 --- /dev/null +++ b/pool/shard004/C/0098335_promote.c @@ -0,0 +1,64 @@ +/* promote.c -- test intergral promotion + + This file is part of the LZO real-time data compression library. + + Copyright (C) 1996-2017 Markus Franz Xaver Johannes Oberhumer + All Rights Reserved. + + The LZO 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 2 of + the License, or (at your option) any later version. + + The LZO library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with the LZO library; see the file COPYING. + If not, write to the Free Software Foundation, Inc., + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + + Markus F.X.J. Oberhumer + + http://www.oberhumer.com/opensource/lzo/ + */ + +#include + +#if defined(_MSC_VER) && (_MSC_VER+0 >= 1000) + /* disable "unreachable code" warnings */ +# pragma warning(disable: 4702) +#endif + +int main(int argc, char *argv[]) +{ + unsigned char c; + int s; + + if (argc < 0 && argv == NULL) /* avoid warning about unused args */ + return 0; + + c = (unsigned char) (1 << (8 * sizeof(char) - 1)); + s = 8 * (int) (sizeof(int) - sizeof(char)); + + printf("Integral promotion: "); + { + const int u = (c << s) > 0; + if (u) + { + printf("Classic C (unsigned-preserving)\n"); + printf("%d %d %uU\n", c, s, (unsigned)c << s); + return 1; + } + else + { + printf("ANSI C (value-preserving)\n"); + printf("%d %d %d\n", c, s, c << s); + return 0; + } + } +} + +/* vim:set ts=4 sw=4 et: */ diff --git a/pool/shard004/C/0098358_kill_ring.c b/pool/shard004/C/0098358_kill_ring.c new file mode 100644 index 0000000000000000000000000000000000000000..542cfb1a99e8ff4401d7b75cab039b5153be6adc --- /dev/null +++ b/pool/shard004/C/0098358_kill_ring.c @@ -0,0 +1,126 @@ +/* + Copyright ⓒ 2013 Jason Lingle + + This file is part of Soliloquy. + + Soliloquy is free software: you can 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. + + Soliloquy is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with Soliloquy. If not, see . +*/ +#include "kill_ring.slc" + +/* + TITLE: Kill Ring Management + OVERVIEW: Provides functions to manage the Emacs-style kill ring. Note that + there are two separate kill rings: one for character-level editing, and one + for line-level. + */ + +/* + SYMBOL: $aw_c_kill_ring $aaw_l_kill_ring + The character-oriented and line-oriented kill rings, respectively. The most + recently-killed item is recorded in $I_c_kill_ring and $I_l_kill_ring, + respectively. Note that both may have NULL entries at arbitrary locations. + + SYMBOL: $I_c_kill_ring $I_l_kill_ring + The indices into $aw_c_kill_ring and $aaw_l_kill_ring, respectively, of the + most recently killed item. + */ + +ATSINIT { + $aw_c_kill_ring = dynar_new_w(); + dynar_expand_by_w($aw_c_kill_ring, 16); + $aaw_l_kill_ring = dynar_new_aw(); + dynar_expand_by_aw($aaw_l_kill_ring, 8); +} + +/* + SYMBOL: $f_c_kill + Kills a string of text, modifying the character-oriented kill ring + appropriately. This should only be called once per logical command; + otherwise, the results will be rather unintuitive. The string to kill is + stored in $w_kill. $v_kill_direction must also be set appropriately. + + SYMBOL: $w_kill + The string to kill in a call to $f_c_kill. + + SYMBOL: $v_kill_direction + In a call to $f_c_kill() or $f_l_kill(), the direction relative to the + cursor of the killed text. This should be either $u_forward or + $u_backward. + + SYMBOL: $y_LastCommand_was_c_kill + When true in the context of $o_prev_command, $f_c_kill() will concatenate + the newly-killed text instead of creating a new entry. + + SYMBOL: $u_forward $u_backward + In kill functions, identify the direction of the killed text relative to + the cursor. + */ +defun($h_c_kill) { + wstring base; + if ($($o_prev_command, $y_LastCommand_was_c_kill)) { + base = $aw_c_kill_ring->v[$I_c_kill_ring]; + } else { + base = L""; + $I_c_kill_ring = ($I_c_kill_ring + 1) % $aw_c_kill_ring->len; + } + + wstring new; + if ($v_kill_direction == $u_forward) + new = wstrap(base, $w_kill); + else + new = wstrap($w_kill, base); + + $aw_c_kill_ring->v[$I_c_kill_ring] = new; + $$($o_this_command) { + $y_LastCommand_was_c_kill = true; + } +} + +/* + SYMBOL: $f_l_kill + Kills a series of lines of text, modifying the line-oriented kill ring + appropriately. This should only be called once per logical command; + otherwise, the results will be rather unintuitive. The lines to kill are + stored in $lw_kill. $v_kill_direction must also be set appropriately. + + SYMBOL: $lw_kill + The lines to kill in a call to $f_l_kill(). + + SYMBOL: $y_LastCommand_was_l_kill + When true in the context of $o_prev_command, $f_l_kill() will concatenate + the newly-killed text instead of creating a new entry. + */ +defun($h_l_kill) { + dynar_w base; + if ($($o_prev_command, $y_LastCommand_was_l_kill)) { + base = $aaw_l_kill_ring->v[$I_l_kill_ring]; + } else { + $I_l_kill_ring = ($I_l_kill_ring + 1) % $aaw_l_kill_ring->len; + base = $aaw_l_kill_ring->v[$I_l_kill_ring] = dynar_new_w(); + } + + unsigned len = llen_w($lw_kill); + wstring data[len]; + unsigned ix = 0; + each_w($lw_kill, lambdav((wstring w), data[ix++] = w)); + + if ($v_kill_direction == $u_backward) + dynar_ins_w(base, 0, data, len); + else + dynar_ins_w(base, base->len, data, len); + + $$($o_this_command) { + $y_LastCommand_was_l_kill = true; + } +} diff --git a/pool/shard004/C/0098365_if_fea.c b/pool/shard004/C/0098365_if_fea.c new file mode 100644 index 0000000000000000000000000000000000000000..bbb1c89685f32cf6189294700d214494732e89bb --- /dev/null +++ b/pool/shard004/C/0098365_if_fea.c @@ -0,0 +1,298 @@ +/*- + * Copyright (c) 1995, 1996 Matt Thomas + * 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. 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. + * + * $FreeBSD: src/sys/dev/pdq/if_fea.c,v 1.23 2002/06/02 20:05:45 schweikh Exp $ + */ + +/* + * DEC PDQ FDDI Controller + * + * This module support the DEFEA EISA FDDI Controller. + */ + +#include +#include +#include +#include + +#include +#include + +#include +#include +#include + +#include +#include +#include +#include + +#include + +#include +#include + +static void pdq_eisa_subprobe (pdq_bus_t, u_int32_t, u_int32_t *, u_int32_t *, u_int32_t *); +static void pdq_eisa_devinit (pdq_softc_t *); +static const char * pdq_eisa_match (eisa_id_t); + +static int pdq_eisa_probe (device_t); +static int pdq_eisa_attach (device_t); +static int pdq_eisa_detach (device_t); +static int pdq_eisa_shutdown (device_t); +static void pdq_eisa_ifintr (void *); + +#define DEFEA_IRQS 0x0000FBA9U + +#define DEFEA_INTRENABLE 0x8 /* level interrupt */ +#define DEFEA_DECODE_IRQ(n) ((DEFEA_IRQS >> ((n) << 2)) & 0x0f) + +#define EISA_DEVICE_ID_DEC_DEC3001 0x10a33001 +#define EISA_DEVICE_ID_DEC_DEC3002 0x10a33002 +#define EISA_DEVICE_ID_DEC_DEC3003 0x10a33003 +#define EISA_DEVICE_ID_DEC_DEC3004 0x10a33004 + +static void +pdq_eisa_subprobe(bc, iobase, maddr, msize, irq) + pdq_bus_t bc; + u_int32_t iobase; + u_int32_t *maddr; + u_int32_t *msize; + u_int32_t *irq; +{ + if (irq != NULL) + *irq = DEFEA_DECODE_IRQ(PDQ_OS_IORD_8(bc, iobase, PDQ_EISA_IO_CONFIG_STAT_0) & 3); + *maddr = (PDQ_OS_IORD_8(bc, iobase, PDQ_EISA_MEM_ADD_CMP_0) << 8) + | (PDQ_OS_IORD_8(bc, iobase, PDQ_EISA_MEM_ADD_CMP_1) << 16); + *msize = (PDQ_OS_IORD_8(bc, iobase, PDQ_EISA_MEM_ADD_MASK_0) + 4) << 8; + + return; +} + +static void +pdq_eisa_devinit (sc) + pdq_softc_t *sc; +{ + pdq_uint8_t data; + + /* + * Do the standard initialization for the DEFEA registers. + */ + PDQ_OS_IOWR_8(sc->io_bst, sc->io_bsh, PDQ_EISA_FUNCTION_CTRL, 0x23); + PDQ_OS_IOWR_8(sc->io_bst, sc->io_bsh, PDQ_EISA_IO_CMP_1_1, (sc->io_bsh >> 8) & 0xF0); + PDQ_OS_IOWR_8(sc->io_bst, sc->io_bsh, PDQ_EISA_IO_CMP_0_1, (sc->io_bsh >> 8) & 0xF0); + PDQ_OS_IOWR_8(sc->io_bst, sc->io_bsh, PDQ_EISA_SLOT_CTRL, 0x01); + data = PDQ_OS_IORD_8(sc->io_bst, sc->io_bsh, PDQ_EISA_BURST_HOLDOFF); +#if defined(PDQ_IOMAPPED) + PDQ_OS_IOWR_8(sc->io_bst, sc->io_bsh, PDQ_EISA_BURST_HOLDOFF, data & ~1); +#else + PDQ_OS_IOWR_8(sc->io_bst, sc->io_bsh, PDQ_EISA_BURST_HOLDOFF, data | 1); +#endif + data = PDQ_OS_IORD_8(sc->io_bst, sc->io_bsh, PDQ_EISA_IO_CONFIG_STAT_0); + PDQ_OS_IOWR_8(sc->io_bst, sc->io_bsh, PDQ_EISA_IO_CONFIG_STAT_0, data | DEFEA_INTRENABLE); + + return; +} + +static const char * +pdq_eisa_match (type) + eisa_id_t type; +{ + switch (type) { + case EISA_DEVICE_ID_DEC_DEC3001: + case EISA_DEVICE_ID_DEC_DEC3002: + case EISA_DEVICE_ID_DEC_DEC3003: + case EISA_DEVICE_ID_DEC_DEC3004: + return ("DEC FDDIcontroller/EISA Adapter"); + break; + default: + break; + } + return (NULL); +} + +static int +pdq_eisa_probe (dev) + device_t dev; +{ + const char *desc; + u_int32_t iobase; + u_int32_t irq; + u_int32_t maddr; + u_int32_t msize; + + u_int32_t eisa_id = eisa_get_id(dev);; + + desc = pdq_eisa_match(eisa_id); + if (!desc) { + return (ENXIO); + } + + device_set_desc(dev, desc); + + iobase = eisa_get_slot(dev) * EISA_SLOT_SIZE; + pdq_eisa_subprobe(SYS_RES_IOPORT, iobase, &maddr, &msize, &irq); + + eisa_add_iospace(dev, iobase, 0x200, RESVADDR_NONE); + eisa_add_mspace(dev, maddr, msize, RESVADDR_NONE); + eisa_add_intr(dev, irq, EISA_TRIGGER_LEVEL); + + return (0); +} + +static void +pdq_eisa_ifintr(arg) + void * arg; +{ + device_t dev; + pdq_softc_t * sc; + + dev = (device_t)arg; + sc = device_get_softc(dev); + + PDQ_LOCK(sc); + (void) pdq_interrupt(sc->sc_pdq); + PDQ_LOCK(sc); + + return; +} + +static int +pdq_eisa_attach (dev) + device_t dev; +{ + pdq_softc_t * sc; + struct ifnet * ifp; + int error; + + sc = device_get_softc(dev); + ifp = &sc->arpcom.ac_if; + + sc->dev = dev; + + sc->io_rid = 0; + sc->io_type = SYS_RES_IOPORT; + sc->io = bus_alloc_resource(dev, sc->io_type, &sc->io_rid, + 0, ~0, 1, RF_ACTIVE); + if (!sc->io) { + device_printf(dev, "Unable to allocate I/O space resource.\n"); + error = ENXIO; + goto bad; + } + sc->io_bsh = rman_get_bushandle(sc->io); + sc->io_bst = rman_get_bustag(sc->io); + + sc->mem_rid = 0; + sc->mem_type = SYS_RES_MEMORY; + sc->mem = bus_alloc_resource(dev, sc->mem_type, &sc->mem_rid, + 0, ~0, 1, RF_ACTIVE); + if (!sc->mem) { + device_printf(dev, "Unable to allocate memory resource.\n"); + error = ENXIO; + goto bad; + } + sc->mem_bsh = rman_get_bushandle(sc->mem); + sc->mem_bst = rman_get_bustag(sc->mem); + + sc->irq_rid = 0; + sc->irq = bus_alloc_resource(dev, SYS_RES_IRQ, &sc->irq_rid, + 0, ~0, 1, RF_SHAREABLE | RF_ACTIVE); + if (!sc->irq) { + device_printf(dev, "Unable to allocate interrupt resource.\n"); + error = ENXIO; + goto bad; + } + + ifp->if_name = "fea"; + ifp->if_unit = device_get_unit(dev); + + pdq_eisa_devinit(sc); + sc->sc_pdq = pdq_initialize(sc->mem_bst, sc->mem_bsh, + ifp->if_name, ifp->if_unit, + (void *)sc, PDQ_DEFEA); + if (sc->sc_pdq == NULL) { + device_printf(dev, "Initialization failed.\n"); + error = ENXIO; + goto bad; + } + + error = bus_setup_intr(dev, sc->irq, INTR_TYPE_NET, + pdq_eisa_ifintr, dev, &sc->irq_ih); + if (error) { + device_printf(dev, "Failed to setup interrupt handler.\n"); + error = ENXIO; + goto bad; + } + + bcopy((caddr_t) sc->sc_pdq->pdq_hwaddr.lanaddr_bytes, + (caddr_t) sc->arpcom.ac_enaddr, FDDI_ADDR_LEN); + pdq_ifattach(sc); + + return (0); +bad: + pdq_free(dev); + return (error); +} + +static int +pdq_eisa_detach (dev) + device_t dev; +{ + pdq_softc_t * sc; + + sc = device_get_softc(dev); + pdq_ifdetach(sc); + + return (0); +} + +static int +pdq_eisa_shutdown(dev) + device_t dev; +{ + pdq_softc_t * sc; + + sc = device_get_softc(dev); + pdq_hwreset(sc->sc_pdq); + + return (0); +} + +static device_method_t pdq_eisa_methods[] = { + DEVMETHOD(device_probe, pdq_eisa_probe), + DEVMETHOD(device_attach, pdq_eisa_attach), + DEVMETHOD(device_attach, pdq_eisa_detach), + DEVMETHOD(device_shutdown, pdq_eisa_shutdown), + + { 0, 0 } +}; + +static driver_t pdq_eisa_driver = { + "fea", + pdq_eisa_methods, + sizeof(pdq_softc_t), +}; + +DRIVER_MODULE(if_fea, eisa, pdq_eisa_driver, pdq_devclass, 0, 0); +/* MODULE_DEPEND(if_fea, eisa, 1, 1, 1); */ +MODULE_DEPEND(if_fea, fddi, 1, 1, 1); diff --git a/pool/shard004/C/0098368_bam_reheader.c.pysam.c b/pool/shard004/C/0098368_bam_reheader.c.pysam.c new file mode 100644 index 0000000000000000000000000000000000000000..3fcafbd872a2d1436598d0ad64d5f7f589dd772c --- /dev/null +++ b/pool/shard004/C/0098368_bam_reheader.c.pysam.c @@ -0,0 +1,83 @@ +#include "pysam.h" + +/* bam_reheader.c -- reheader subcommand. + + Copyright (C) 2010 Broad Institute. + Copyright (C) 2012, 2013 Genome Research Ltd. + + Author: Heng Li + +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 "htslib/bgzf.h" +#include "bam.h" + +#define BUF_SIZE 0x10000 + +int bam_reheader(BGZF *in, const bam_header_t *h, int fd) +{ + BGZF *fp; + bam_header_t *old; + ssize_t len; + uint8_t *buf; + if (in->is_write) return -1; + buf = malloc(BUF_SIZE); + old = bam_header_read(in); + fp = bgzf_fdopen(fd, "w"); + bam_header_write(fp, h); + if (in->block_offset < in->block_length) { + bgzf_write(fp, in->uncompressed_block + in->block_offset, in->block_length - in->block_offset); + bgzf_flush(fp); + } + while ((len = bgzf_raw_read(in, buf, BUF_SIZE)) > 0) + bgzf_raw_write(fp, buf, len); + free(buf); + fp->block_offset = in->block_offset = 0; + bgzf_close(fp); + return 0; +} + +int main_reheader(int argc, char *argv[]) +{ + bam_header_t *h; + BGZF *in; + if (argc != 3) { + fprintf(pysamerr, "Usage: samtools reheader \n"); + return 1; + } + { // read the header + tamFile fph = sam_open(argv[1]); + if (fph == 0) { + fprintf(pysamerr, "[%s] fail to read the header from %s.\n", __func__, argv[1]); + return 1; + } + h = sam_header_read(fph); + sam_close(fph); + } + in = strcmp(argv[2], "-")? bgzf_open(argv[2], "r") : bgzf_fdopen(fileno(stdin), "r"); + if (in == 0) { + fprintf(pysamerr, "[%s] fail to open file %s.\n", __func__, argv[2]); + return 1; + } + bam_reheader(in, h, fileno(stdout)); + bgzf_close(in); + return 0; +} diff --git a/pool/shard004/C/0098370_loop_test5.c b/pool/shard004/C/0098370_loop_test5.c new file mode 100644 index 0000000000000000000000000000000000000000..b5dcf0a470366dbd27fa7a39fc6cf41657bdf3c3 --- /dev/null +++ b/pool/shard004/C/0098370_loop_test5.c @@ -0,0 +1,203 @@ +/* + * Copyright (C) 2005, 2006, 2007, 2009, 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 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 St, Fifth Floor, Boston, MA 02110-1301 USA + * + */ + +/* + * Test "Jumping backward to the middle of a DisplayObject's lifetime after removal and replacement(2)" + * + * Timeline: + * + * Frame | 1 | 2 | 3 | 4 | 5 | 6 | + * --------+---+---+---+---+---+---+ + * Event | |PP | * |RR |PP | J | + * + * P = place (by PlaceObject2) + * M = move to another depth (by swapDepth) + * R = remove ((by RemoveObject* tag) + * J = jump + * * = jump target + * + * Description: + * + * frame2: + * a static DisplayObjects is placed at depth 3 (-16381) [ a red square ] + * a static DisplayObject is placed at depth 4 (-16380) [ a black square ] + * frame3: nothing new. + * frame4: + * DisplayObject at depth 3 is removed; + * DisplayObject at depth 4 is removed; + * frame5: + * a static DisplayObject is placed at depth 3 (-16381) with ratio set to 2.0 + * a static DisplayObject is placed at depth 4 (-16380) with ratio set to 0.0 + * + * frame6: jump to frame 3 and stop. + * + * Expected behaviour: + * + * After jump back, DisplayObjects in depth 3 placed at frame5 get destroyed, + * DisplayObjects in depth 4 placed in frame 5 keeps alive. Their ratio values are different. + * + * run as ./loop_test5 + */ + + +#include +#include +#include + +#include "ming_utils.h" + +#define OUTPUT_VERSION 7 +#define OUTPUT_FILENAME "loop_test5.swf" + + +int +main(int argc, char** argv) +{ + SWFMovie mo; + SWFMovieClip mc1, mc2, dejagnuclip; + SWFDisplayItem it1, it2; + SWFShape sh1,sh2; + SWFAction ac; + int i; + + const char *srcdir="."; + if ( argc>1 ) + srcdir=argv[1]; + else + { + //fprintf(stderr, "Usage: %s \n", argv[0]); + //return 1; + } + + Ming_init(); + Ming_useSWFVersion (OUTPUT_VERSION); + + mo = newSWFMovie(); + SWFMovie_setDimension(mo, 800, 600); + SWFMovie_setRate(mo, 6); + + // Frame 1: Place dejagnu clip + + dejagnuclip = get_dejagnu_clip((SWFBlock)get_default_font(srcdir), 10, 0, 0, 800, 600); + SWFMovie_add(mo, (SWFBlock)dejagnuclip); + add_actions(mo, "mc1Constructed=0; mc2Constructed=0; mc3Constructed=0; mc4Constructed=0;"); + SWFMovie_nextFrame(mo); + + // + // Frame 2: + // Place red static movieClip1 DisplayObject at depth 3 (-16381) + // Place black static movieClip1 DisplayObject at depth 4 (-16380) + // + sh1 = make_fill_square (300, 300, 60, 60, 255, 0, 0, 255, 0, 0); + mc1 = newSWFMovieClip(); + SWFMovieClip_add(mc1, (SWFBlock)sh1); + SWFMovieClip_nextFrame(mc1); + + it1 = SWFMovie_add(mo, (SWFBlock)mc1); //add movieClip1 to the _root + SWFDisplayItem_setDepth(it1, 3); + SWFDisplayItem_setName(it1, "movieClip1"); //name movieClip1 + SWFDisplayItem_addAction(it1, newSWFAction( + "_root.note(this+' constructed');" + "_root.mc1Constructed++;" + ), SWFACTION_CONSTRUCT); + + + sh2 = make_fill_square (330, 270, 120, 120, 0, 0, 0, 0, 0, 0); + mc2 = newSWFMovieClip(); + SWFMovieClip_add(mc2, (SWFBlock)sh2); + SWFMovieClip_nextFrame(mc2); + + it2 = SWFMovie_add(mo, (SWFBlock)mc2); //add movieClip2 to the _root + SWFDisplayItem_setDepth(it2, 4); + SWFDisplayItem_setName(it2, "movieClip2"); //name movieClip2 + SWFDisplayItem_addAction(it2, newSWFAction( + "_root.note(this+' constructed');" + "_root.mc2Constructed++;"), + SWFACTION_CONSTRUCT); + + SWFMovie_nextFrame(mo); + + // Frame3: nothing new + SWFMovie_nextFrame(mo); + + // Frame4: remove "movieClip1" and "movieClip2" + + SWFDisplayItem_remove(it1); + SWFDisplayItem_remove(it2); + SWFMovie_nextFrame(mo); + + // + // Frame5: + // Place red static movieClip3 DisplayObject at depth 3 (-16381) with ratio set to 2.0 + // Place black static movieClip4 DisplayObject at depth4 (-16380) with ratio set to 0.0 + // + + it1 = SWFMovie_add(mo, (SWFBlock)mc1); //add movieClip3 to the _root + SWFDisplayItem_setDepth(it1, 3); + SWFDisplayItem_setName(it1, "movieClip3"); //name movieClip3 + SWFDisplayItem_setRatio(it1, 2.0); // It's important to set this, don't why yet. + SWFDisplayItem_addAction(it1, newSWFAction( + "_root.note(this+' constructed');" + "_root.mc3Constructed++;" + ), SWFACTION_CONSTRUCT); + + it2 = SWFMovie_add(mo, (SWFBlock)mc2); //add movieClip4 to the _root + SWFDisplayItem_setDepth(it2, 4); + SWFDisplayItem_setName(it2, "movieClip4"); //name movieClip4 + SWFDisplayItem_setRatio(it2, 0.0); // It's important to set this, don't why yet. + SWFDisplayItem_addAction(it2, newSWFAction( + "_root.note(this+' constructed');" + "_root.mc4Constructed++;" + ), SWFACTION_CONSTRUCT); + + SWFMovie_nextFrame(mo); + + // + // Frame4: check, gotoAndStop(3), check.. + // + check_equals(mo, "typeof(movieClip1)", "'undefined'"); + check_equals(mo, "typeof(movieClip2)", "'undefined'"); + check_equals(mo, "typeof(movieClip3)", "'movieclip'"); + check_equals(mo, "typeof(movieClip4)", "'movieclip'"); + check_equals(mo, "_root.mc1Constructed", "1"); + check_equals(mo, "_root.mc2Constructed", "1"); + check_equals(mo, "_root.mc3Constructed", "1"); + check_equals(mo, "_root.mc4Constructed", "1"); + + SWFMovie_add(mo, (SWFBlock)newSWFAction( "gotoAndStop(3);")); + + check_equals(mo, "typeof(movieClip1)", "'movieclip'"); + check_equals(mo, "typeof(movieClip2)", "'undefined'"); + // the difference of movieClip3 and movieClip4 was caused by the ratio value + check_equals(mo, "typeof(movieClip3)", "'undefined'"); + check_equals(mo, "typeof(movieClip4)", "'movieclip'"); + check_equals(mo, "_root.mc1Constructed", "2"); + check_equals(mo, "_root.mc2Constructed", "1"); + check_equals(mo, "_root.mc3Constructed", "1"); + check_equals(mo, "_root.mc4Constructed", "1"); + + SWFMovie_add(mo, (SWFBlock)newSWFAction( "totals(); stop();" )); + SWFMovie_nextFrame(mo); + + //Output movie + puts("Saving " OUTPUT_FILENAME ); + SWFMovie_save(mo, OUTPUT_FILENAME); + + return 0; +} + diff --git a/pool/shard004/C/0098374_msm8k_cad_q6dec_drv.c b/pool/shard004/C/0098374_msm8k_cad_q6dec_drv.c new file mode 100644 index 0000000000000000000000000000000000000000..74efb7e3117650d4d19972d9f87c7c1d0cb6037e --- /dev/null +++ b/pool/shard004/C/0098374_msm8k_cad_q6dec_drv.c @@ -0,0 +1,236 @@ +/* Copyright (c) 2009, Code Aurora Forum. 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 Code Aurora Forum nor + * the names of its contributors may be used to endorse or promote + * products derived from this software without specific prior written + * permission. + * + * Alternatively, provided that this notice is retained in full, this software + * may be relicensed by the recipient under the terms of the GNU General Public + * License version 2 ("GPL") and only version 2, in which case the provisions of + * the GPL apply INSTEAD OF those given above. If the recipient relicenses the + * software under the GPL, then the identification text in the MODULE_LICENSE + * macro must be changed to reflect "GPLv2" instead of "Dual BSD/GPL". Once a + * recipient changes the license terms to the GPL, subsequent recipients shall + * not relicense under alternate licensing terms, including the BSD or dual + * BSD/GPL terms. In addition, the following license statement immediately + * below and between the words START and END shall also then apply when this + * software is relicensed under the GPL: + * + * START + * + * 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. + * + * END + * + * 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 + +static struct q6dec_data cad_q6dec_data; + + +static s32 cad_q6dec_open(s32 session_id, + struct cad_open_struct_type *open_param) +{ + struct q6dec_session_data *session = NULL; + if (!open_param || session_id >= CAD_MAX_SESSION || session_id <= 0) + return CAD_RES_FAILURE; + + if (CAD_OPEN_OP_WRITE == open_param->op_code && + cad_q6dec_data.free_session_list) { + session = cad_q6dec_data.free_session_list; + if (cad_q6dec_session_open(session, session_id, open_param)) { + cad_q6dec_session_close(session); + return CAD_RES_FAILURE; + } + cad_q6dec_data.free_session_list = + cad_q6dec_data.free_session_list->next; + session->next = cad_q6dec_data.used_session_list; + cad_q6dec_data.used_session_list = session; + } + return CAD_RES_SUCCESS; +} + + +static s32 cad_q6dec_close(s32 session_id) +{ + struct q6dec_session_data *session = + cad_q6dec_data.used_session_list; + struct q6dec_session_data *prev_session = NULL; + if (session_id >= CAD_MAX_SESSION || session_id <= 0) + return CAD_RES_FAILURE; + + while (session) { + if (session->session_id == session_id) { + if (prev_session == NULL) { + /* first node */ + cad_q6dec_data.used_session_list = + session->next; + break; + } + /* not first node */ + prev_session->next = session->next; + break; + } + prev_session = session; + session = session->next; + } + + if (session) { + cad_q6dec_session_close(session); + session->next = cad_q6dec_data.free_session_list; + cad_q6dec_data.free_session_list = session; + } + return CAD_RES_SUCCESS; +} + +static s32 cad_q6dec_write(s32 session_id, + struct cad_buf_struct_type *buf) +{ + struct q6dec_session_data *session = + cad_q6dec_data.used_session_list; + if (!buf) + return CAD_RES_FAILURE; + + while (session) { + if (session->session_id == session_id) { + if (cad_q6dec_session_write(session, buf)) + return CAD_RES_FAILURE; + break; + } + session = session->next; + } + return CAD_RES_SUCCESS; +} + +static s32 cad_q6dec_read(s32 session_id, + struct cad_buf_struct_type *buf) +{ + pr_err("q6decoder read has not implemnted......\n"); + return CAD_RES_SUCCESS; +} + +static s32 cad_q6dec_ioctl(s32 session_id, + u32 cmd_code, + void *cmd_buf, + u32 cmd_len) +{ + struct q6dec_session_data *session = + cad_q6dec_data.used_session_list; + + while (session) { + if (session->session_id == session_id) { + if (cad_q6dec_session_ioctl(session, cmd_code, + cmd_buf, cmd_len)) + return CAD_RES_FAILURE; + break; + } + session = session->next; + } + + return CAD_RES_SUCCESS; +} + + +/* public functions */ + +s32 cad_audio_dec_dinit(void) +{ + struct q6dec_session_data *session; + while (cad_q6dec_data.free_session_list) { + session = cad_q6dec_data.free_session_list->next; + cad_q6dec_session_deinit(cad_q6dec_data.free_session_list); + kfree(cad_q6dec_data.free_session_list); + cad_q6dec_data.free_session_list = session; + } + + while (cad_q6dec_data.used_session_list) { + session = cad_q6dec_data.used_session_list->next; + cad_q6dec_session_deinit(cad_q6dec_data.used_session_list); + kfree(cad_q6dec_data.used_session_list); + cad_q6dec_data.used_session_list = session; + } + + memset(&cad_q6dec_data, 0, sizeof(struct q6dec_data)); + return CAD_RES_SUCCESS; +} + + +s32 cad_audio_dec_init(struct cad_func_tbl_type **func_tbl) +{ + u32 i; + struct q6dec_session_data *node = NULL; + static struct cad_func_tbl_type vtable = { + cad_q6dec_open, + cad_q6dec_close, + cad_q6dec_write, + cad_q6dec_read, + cad_q6dec_ioctl + }; + *func_tbl = NULL; + + memset(&cad_q6dec_data, 0, sizeof(struct q6dec_data)); + + /* create session list */ + for (i = 0; i < Q6_DEC_MAX_STREAM_COUNT; i++) { + node = kmalloc(sizeof(struct q6dec_session_data), + GFP_KERNEL); + if (IS_ERR(node)) { + cad_audio_dec_dinit(); + return CAD_RES_FAILURE; + } + + memset(node, 0, + sizeof(struct q6dec_session_data)); + + if (cad_q6dec_session_init(node)) { + cad_q6dec_session_deinit(node); + kfree(node); + return CAD_RES_FAILURE; + } + + node->next = cad_q6dec_data.free_session_list; + cad_q6dec_data.free_session_list = node; + } + + *func_tbl = &vtable; + return CAD_RES_SUCCESS; +} diff --git a/pool/shard004/C/0098380_llrint.c b/pool/shard004/C/0098380_llrint.c new file mode 100644 index 0000000000000000000000000000000000000000..5f96115fb5c0e02c36cbcac7594adb2200cac656 --- /dev/null +++ b/pool/shard004/C/0098380_llrint.c @@ -0,0 +1,62 @@ + +/* +* Copyright (C) 2008-2009 Advanced Micro Devices, Inc. All Rights Reserved. +* +* This file is part of libacml_mv. +* +* libacml_mv 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. +* +* libacml_mv is distributed in the hope that 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 libacml_mv. If not, see +* . +* +*/ + + +#ifdef WIN64 +#include +#else +#include +#endif + +#include + +#include "libm_amd.h" +#include "libm_util_amd.h" +#include "libm_special.h" + + +long long int FN_PROTOTYPE(llrint)(double x) +{ + + + UT64 checkbits,val_2p52; + checkbits.f64=x; + + /* Clear the sign bit and check if the value can be rounded */ + + if( (checkbits.u64 & 0x7FFFFFFFFFFFFFFF) > 0x4330000000000000) + { + /* number cant be rounded raise an exception */ + /* Number exceeds the representable range could be nan or inf also*/ + __amd_handle_error(DOMAIN, EDOM, "llrint", x,0.0 ,(double)x); + + return (long long int) x; + } + + val_2p52.u32[1] = (checkbits.u32[1] & 0x80000000) | 0x43300000; + val_2p52.u32[0] = 0; + + + /* Add and sub 2^52 to round the number according to the current rounding direction */ + + return (long long int) ((x + val_2p52.f64) - val_2p52.f64); +} diff --git a/pool/shard004/C/0098394_setup.c b/pool/shard004/C/0098394_setup.c new file mode 100644 index 0000000000000000000000000000000000000000..9f6d2d9b1be7b2100c518a128160136b416dc8d7 --- /dev/null +++ b/pool/shard004/C/0098394_setup.c @@ -0,0 +1,134 @@ +/* + * Unmaintained SGI Visual Workstation support. + * Split out from setup.c by davej@suse.de + */ + +#include +#include +#include +#include + +#include +#include +#include +#include "cobalt.h" +#include "piix4.h" + +char visws_board_type = -1; +char visws_board_rev = -1; + +void __init visws_get_board_type_and_rev(void) +{ + int raw; + + visws_board_type = (char)(inb_p(PIIX_GPI_BD_REG) & PIIX_GPI_BD_REG) + >> PIIX_GPI_BD_SHIFT; + /* + * Get Board rev. + * First, we have to initialize the 307 part to allow us access + * to the GPIO registers. Let's map them at 0x0fc0 which is right + * after the PIIX4 PM section. + */ + outb_p(SIO_DEV_SEL, SIO_INDEX); + outb_p(SIO_GP_DEV, SIO_DATA); /* Talk to GPIO regs. */ + + outb_p(SIO_DEV_MSB, SIO_INDEX); + outb_p(SIO_GP_MSB, SIO_DATA); /* MSB of GPIO base address */ + + outb_p(SIO_DEV_LSB, SIO_INDEX); + outb_p(SIO_GP_LSB, SIO_DATA); /* LSB of GPIO base address */ + + outb_p(SIO_DEV_ENB, SIO_INDEX); + outb_p(1, SIO_DATA); /* Enable GPIO registers. */ + + /* + * Now, we have to map the power management section to write + * a bit which enables access to the GPIO registers. + * What lunatic came up with this shit? + */ + outb_p(SIO_DEV_SEL, SIO_INDEX); + outb_p(SIO_PM_DEV, SIO_DATA); /* Talk to GPIO regs. */ + + outb_p(SIO_DEV_MSB, SIO_INDEX); + outb_p(SIO_PM_MSB, SIO_DATA); /* MSB of PM base address */ + + outb_p(SIO_DEV_LSB, SIO_INDEX); + outb_p(SIO_PM_LSB, SIO_DATA); /* LSB of PM base address */ + + outb_p(SIO_DEV_ENB, SIO_INDEX); + outb_p(1, SIO_DATA); /* Enable PM registers. */ + + /* + * Now, write the PM register which enables the GPIO registers. + */ + outb_p(SIO_PM_FER2, SIO_PM_INDEX); + outb_p(SIO_PM_GP_EN, SIO_PM_DATA); + + /* + * Now, initialize the GPIO registers. + * We want them all to be inputs which is the + * power on default, so let's leave them alone. + * So, let's just read the board rev! + */ + raw = inb_p(SIO_GP_DATA1); + raw &= 0x7f; /* 7 bits of valid board revision ID. */ + + if (visws_board_type == VISWS_320) { + if (raw < 0x6) { + visws_board_rev = 4; + } else if (raw < 0xc) { + visws_board_rev = 5; + } else { + visws_board_rev = 6; + } + } else if (visws_board_type == VISWS_540) { + visws_board_rev = 2; + } else { + visws_board_rev = raw; + } + + printk(KERN_INFO "Silicon Graphics Visual Workstation %s (rev %d) detected\n", + (visws_board_type == VISWS_320 ? "320" : + (visws_board_type == VISWS_540 ? "540" : + "unknown")), visws_board_rev); +} + +void __init pre_intr_init_hook(void) +{ + init_VISWS_APIC_irqs(); +} + +void __init intr_init_hook(void) +{ +#ifdef CONFIG_X86_LOCAL_APIC + apic_intr_init(); +#endif +} + +void __init pre_setup_arch_hook() +{ + visws_get_board_type_and_rev(); +} + +static struct irqaction irq0 = { + .handler = timer_interrupt, + .flags = SA_INTERRUPT, + .name = "timer", +}; + +void __init time_init_hook(void) +{ + printk(KERN_INFO "Starting Cobalt Timer system clock\n"); + + /* Set the countdown value */ + co_cpu_write(CO_CPU_TIMEVAL, CO_TIME_HZ/HZ); + + /* Start the timer */ + co_cpu_write(CO_CPU_CTRL, co_cpu_read(CO_CPU_CTRL) | CO_CTRL_TIMERUN); + + /* Enable (unmask) the timer interrupt */ + co_cpu_write(CO_CPU_CTRL, co_cpu_read(CO_CPU_CTRL) & ~CO_CTRL_TIMEMASK); + + /* Wire cpu IDT entry to s/w handler (and Cobalt APIC to IDT) */ + setup_irq(0, &irq0); +} diff --git a/pool/shard004/C/0098399_prenv.c b/pool/shard004/C/0098399_prenv.c new file mode 100644 index 0000000000000000000000000000000000000000..5f16ce1890d89d02434d2de53fb6ded51ff9c735 --- /dev/null +++ b/pool/shard004/C/0098399_prenv.c @@ -0,0 +1,109 @@ +/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* ***** BEGIN LICENSE BLOCK ***** + * Version: MPL 1.1/GPL 2.0/LGPL 2.1 + * + * The contents of this file are subject to the Mozilla Public License Version + * 1.1 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * http://www.mozilla.org/MPL/ + * + * Software distributed under the License is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License + * for the specific language governing rights and limitations under the + * License. + * + * The Original Code is the Netscape Portable Runtime (NSPR). + * + * The Initial Developer of the Original Code is + * Netscape Communications Corporation. + * Portions created by the Initial Developer are Copyright (C) 1998-2000 + * the Initial Developer. All Rights Reserved. + * + * Contributor(s): + * + * Alternatively, the contents of this file may be used under the terms of + * either the GNU General Public License Version 2 or later (the "GPL"), or + * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + * in which case the provisions of the GPL or the LGPL are applicable instead + * of those above. If you wish to allow use of your version of this file only + * under the terms of either the GPL or the LGPL, and not to allow others to + * use your version of this file under the terms of the MPL, indicate your + * decision by deleting the provisions above and replace them with the notice + * and other provisions required by the GPL or the LGPL. If you do not delete + * the provisions above, a recipient may use your version of this file under + * the terms of any one of the MPL, the GPL or the LGPL. + * + * ***** END LICENSE BLOCK ***** */ + +#include +#include "primpl.h" + +/* Lock used to lock the environment */ +#if defined(_PR_NO_PREEMPT) +#define _PR_NEW_LOCK_ENV() +#define _PR_DELETE_LOCK_ENV() +#define _PR_LOCK_ENV() +#define _PR_UNLOCK_ENV() +#elif defined(_PR_LOCAL_THREADS_ONLY) +extern _PRCPU * _pr_primordialCPU; +static PRIntn _is; +#define _PR_NEW_LOCK_ENV() +#define _PR_DELETE_LOCK_ENV() +#define _PR_LOCK_ENV() if (_pr_primordialCPU) _PR_INTSOFF(_is); +#define _PR_UNLOCK_ENV() if (_pr_primordialCPU) _PR_INTSON(_is); +#else +static PRLock *_pr_envLock = NULL; +#define _PR_NEW_LOCK_ENV() {_pr_envLock = PR_NewLock();} +#define _PR_DELETE_LOCK_ENV() \ + { if (_pr_envLock) { PR_DestroyLock(_pr_envLock); _pr_envLock = NULL; } } +#define _PR_LOCK_ENV() { if (_pr_envLock) PR_Lock(_pr_envLock); } +#define _PR_UNLOCK_ENV() { if (_pr_envLock) PR_Unlock(_pr_envLock); } +#endif + +/************************************************************************/ + +void _PR_InitEnv(void) +{ + _PR_NEW_LOCK_ENV(); +} + +void _PR_CleanupEnv(void) +{ + _PR_DELETE_LOCK_ENV(); +} + +PR_IMPLEMENT(char*) PR_GetEnv(const char *var) +{ + char *ev; + + if (!_pr_initialized) _PR_ImplicitInitialization(); + + _PR_LOCK_ENV(); + ev = _PR_MD_GET_ENV(var); + _PR_UNLOCK_ENV(); + return ev; +} + +PR_IMPLEMENT(PRStatus) PR_SetEnv(const char *string) +{ + PRIntn result; + + if (!_pr_initialized) _PR_ImplicitInitialization(); + + if ( !strchr(string, '=')) return(PR_FAILURE); + + _PR_LOCK_ENV(); + result = _PR_MD_PUT_ENV(string); + _PR_UNLOCK_ENV(); + return (result)? PR_FAILURE : PR_SUCCESS; +} + +/* +** DEPRECATED. Use PR_SetEnv() instead. +*/ +#ifdef XP_MAC +PR_IMPLEMENT(PRIntn) PR_PutEnv(const char *string) +{ + return (PR_SetEnv(string) == PR_SUCCESS) ? PR_TRUE : PR_FALSE; +} +#endif diff --git a/pool/shard004/C/0098416_derived_perm.c b/pool/shard004/C/0098416_derived_perm.c new file mode 100644 index 0000000000000000000000000000000000000000..2314d6ed05605916aa94a9cab4eebfbe2473e586 --- /dev/null +++ b/pool/shard004/C/0098416_derived_perm.c @@ -0,0 +1,294 @@ +/* + * fs/sdcardfs/derived_perm.c + * + * Copyright (c) 2013 Samsung Electronics Co. Ltd + * Authors: Daeho Jeong, Woojoong Lee, Seunghwan Hyun, + * Sunghwan Yun, Sungjong Seo + * + * This program has been developed as a stackable file system based on + * the WrapFS which written by + * + * 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 file is dual licensed. It may be redistributed and/or modified + * under the terms of the Apache 2.0 License OR version 2 of the GNU + * General Public License. + */ + +#include "sdcardfs.h" + +/* copy derived state from parent inode */ +static void inherit_derived_state(struct inode *parent, struct inode *child) +{ + struct sdcardfs_inode_info *pi = SDCARDFS_I(parent); + struct sdcardfs_inode_info *ci = SDCARDFS_I(child); + + ci->perm = PERM_INHERIT; + ci->userid = pi->userid; + ci->d_uid = pi->d_uid; + ci->d_gid = pi->d_gid; + ci->d_mode = pi->d_mode; +} + +/* helper function for derived state */ +void setup_derived_state(struct inode *inode, perm_t perm, + userid_t userid, uid_t uid, gid_t gid, mode_t mode) +{ + struct sdcardfs_inode_info *info = SDCARDFS_I(inode); + + info->perm = perm; + info->userid = userid; + info->d_uid = uid; + info->d_gid = gid; + info->d_mode = mode; +} + +void get_derived_permission(struct dentry *parent, struct dentry *dentry) +{ + struct sdcardfs_sb_info *sbi = SDCARDFS_SB(dentry->d_sb); + struct sdcardfs_inode_info *info = SDCARDFS_I(dentry->d_inode); + struct sdcardfs_inode_info *parent_info= SDCARDFS_I(parent->d_inode); + appid_t appid; + + /* By default, each inode inherits from its parent. + * the properties are maintained on its private fields + * because the inode attributes will be modified with that of + * its lower inode. + * The derived state will be updated on the last + * stage of each system call by fix_derived_permission(inode). + */ + + inherit_derived_state(parent->d_inode, dentry->d_inode); + + //printk(KERN_INFO "sdcardfs: derived: %s, %s, %d\n", parent->d_name.name, + // dentry->d_name.name, parent_info->perm); + + if (sbi->options.derive == DERIVE_NONE) { + return; + } + + /* Derive custom permissions based on parent and current node */ + switch (parent_info->perm) { + case PERM_INHERIT: + /* Already inherited above */ + break; + case PERM_LEGACY_PRE_ROOT: + /* Legacy internal layout places users at top level */ + info->perm = PERM_ROOT; + info->userid = simple_strtoul(dentry->d_name.name, NULL, 10); + break; + case PERM_ROOT: + /* Assume masked off by default. */ + info->d_mode = 00770; + if (!strcasecmp(dentry->d_name.name, "Android")) { + /* App-specific directories inside; let anyone traverse */ + info->perm = PERM_ANDROID; + info->d_mode = 00771; + } else if (sbi->options.split_perms) { + if (!strcasecmp(dentry->d_name.name, "DCIM") + || !strcasecmp(dentry->d_name.name, "Pictures")) { + info->d_gid = AID_SDCARD_PICS; + } else if (!strcasecmp(dentry->d_name.name, "Alarms") + || !strcasecmp(dentry->d_name.name, "Movies") + || !strcasecmp(dentry->d_name.name, "Music") + || !strcasecmp(dentry->d_name.name, "Notifications") + || !strcasecmp(dentry->d_name.name, "Podcasts") + || !strcasecmp(dentry->d_name.name, "Ringtones")) { + info->d_gid = AID_SDCARD_AV; + } + } + break; + case PERM_ANDROID: + if (!strcasecmp(dentry->d_name.name, "data")) { + /* App-specific directories inside; let anyone traverse */ + info->perm = PERM_ANDROID_DATA; + info->d_mode = 00771; + } else if (!strcasecmp(dentry->d_name.name, "obb")) { + /* App-specific directories inside; let anyone traverse */ + info->perm = PERM_ANDROID_OBB; + info->d_mode = 00771; + // FIXME : this feature will be implemented later. + /* Single OBB directory is always shared */ + } else if (!strcasecmp(dentry->d_name.name, "user")) { + /* User directories must only be accessible to system, protected + * by sdcard_all. Zygote will bind mount the appropriate user- + * specific path. */ + info->perm = PERM_ANDROID_USER; + info->d_gid = AID_SDCARD_ALL; + info->d_mode = 00770; + } + break; + /* same policy will be applied on PERM_ANDROID_DATA + * and PERM_ANDROID_OBB */ + case PERM_ANDROID_DATA: + case PERM_ANDROID_OBB: + appid = get_appid(sbi->pkgl_id, dentry->d_name.name); + if (appid != 0) { + info->d_uid = multiuser_get_uid(parent_info->userid, appid); + } + info->d_mode = 00770; + break; + case PERM_ANDROID_USER: + /* Root of a secondary user */ + info->perm = PERM_ROOT; + info->userid = simple_strtoul(dentry->d_name.name, NULL, 10); + info->d_gid = AID_SDCARD_R; + info->d_mode = 00771; + break; + } +} + +/* main function for updating derived permission */ +inline void update_derived_permission(struct dentry *dentry) +{ + struct dentry *parent; + + if(!dentry || !dentry->d_inode) { + printk(KERN_ERR "sdcardfs: %s: invalid dentry\n", __func__); + return; + } + /* FIXME: + * 1. need to check whether the dentry is updated or not + * 2. remove the root dentry update + */ + if(IS_ROOT(dentry)) { + //setup_default_pre_root_state(dentry->d_inode); + } else { + parent = dget_parent(dentry); + if(parent) { + get_derived_permission(parent, dentry); + dput(parent); + } + } + fix_derived_permission(dentry->d_inode); +} + +int need_graft_path(struct dentry *dentry) +{ + int ret = 0; + struct dentry *parent = dget_parent(dentry); + struct sdcardfs_inode_info *parent_info= SDCARDFS_I(parent->d_inode); + struct sdcardfs_sb_info *sbi = SDCARDFS_SB(dentry->d_sb); + + if(parent_info->perm == PERM_ANDROID && + !strcasecmp(dentry->d_name.name, "obb")) { + + /* /Android/obb is the base obbpath of DERIVED_UNIFIED */ + if(!(sbi->options.derive == DERIVE_UNIFIED + && parent_info->userid == 0)) { + ret = 1; + } + } + dput(parent); + return ret; +} + +int is_obbpath_invalid(struct dentry *dent) +{ + int ret = 0; + struct sdcardfs_dentry_info *di = SDCARDFS_D(dent); + struct sdcardfs_sb_info *sbi = SDCARDFS_SB(dent->d_sb); + char *path_buf, *obbpath_s; + + /* check the base obbpath has been changed. + * this routine can check an uninitialized obb dentry as well. + * regarding the uninitialized obb, refer to the sdcardfs_mkdir() */ + spin_lock(&di->lock); + if(di->orig_path.dentry) { + if(!di->lower_path.dentry) { + ret = 1; + } else { + path_get(&di->lower_path); + //lower_parent = lock_parent(lower_path->dentry); +#ifdef CONFIG_HUAWEI_KERNEL + path_buf = kmalloc(PATH_MAX, GFP_ATOMIC); + if(!path_buf) + { + path_put(&di->lower_path); + spin_unlock(&di->lock); + printk(KERN_ERR "sdcardfs: %s: kmalloc failed\n", __func__); + return -ENOMEM; + } +#else + path_buf = kmalloc(PATH_MAX, GFP_KERNEL); +#endif + obbpath_s = d_path(&di->lower_path, path_buf, PATH_MAX); + if (d_unhashed(di->lower_path.dentry) || + strcasecmp(sbi->obbpath_s, obbpath_s)) { + ret = 1; + } + kfree(path_buf); + + //unlock_dir(lower_parent); + path_put(&di->lower_path); + } + } + spin_unlock(&di->lock); + return ret; +} + +int is_base_obbpath(struct dentry *dentry) +{ + int ret = 0; + struct dentry *parent = dget_parent(dentry); + struct sdcardfs_inode_info *parent_info= SDCARDFS_I(parent->d_inode); + struct sdcardfs_sb_info *sbi = SDCARDFS_SB(dentry->d_sb); + + spin_lock(&SDCARDFS_D(dentry)->lock); + /* DERIVED_LEGACY */ + if(parent_info->perm == PERM_LEGACY_PRE_ROOT && + !strcasecmp(dentry->d_name.name, "obb")) { + ret = 1; + } + /* DERIVED_UNIFIED :/Android/obb is the base obbpath */ + else if (parent_info->perm == PERM_ANDROID && + !strcasecmp(dentry->d_name.name, "obb")) { + if((sbi->options.derive == DERIVE_UNIFIED + && parent_info->userid == 0)) { + ret = 1; + } + } + spin_unlock(&SDCARDFS_D(dentry)->lock); + dput(parent); + return ret; +} + +/* The lower_path will be stored to the dentry's orig_path + * and the base obbpath will be copyed to the lower_path variable. + * if an error returned, there's no change in the lower_path + * returns: -ERRNO if error (0: no error) */ +int setup_obb_dentry(struct dentry *dentry, struct path *lower_path) +{ + int err = 0; + struct sdcardfs_sb_info *sbi = SDCARDFS_SB(dentry->d_sb); + struct path obbpath; + + /* A local obb dentry must have its own orig_path to support rmdir + * and mkdir of itself. Usually, we expect that the sbi->obbpath + * is avaiable on this stage. */ + sdcardfs_set_orig_path(dentry, lower_path); + + err = kern_path(sbi->obbpath_s, + LOOKUP_FOLLOW | LOOKUP_DIRECTORY, &obbpath); + + if(!err) { + /* the obbpath base has been found */ + printk(KERN_INFO "sdcardfs: " + "the sbi->obbpath is found\n"); + pathcpy(lower_path, &obbpath); + } else { + /* if the sbi->obbpath is not available, we can optionally + * setup the lower_path with its orig_path. + * but, the current implementation just returns an error + * because the sdcard daemon also regards this case as + * a lookup fail. */ + printk(KERN_INFO "sdcardfs: " + "the sbi->obbpath is not available\n"); + } + return err; +} + + diff --git a/pool/shard004/C/0098418_active-sensor-libnotify.c b/pool/shard004/C/0098418_active-sensor-libnotify.c new file mode 100644 index 0000000000000000000000000000000000000000..4b9fc4010f211c9e3620946dac2e164faebf2de4 --- /dev/null +++ b/pool/shard004/C/0098418_active-sensor-libnotify.c @@ -0,0 +1,104 @@ +/* + * Copyright (C) 2005-2009 Alex Murray + * Copyright (C) 2012-2021 MATE Developers + * + * 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 "config.h" +#endif /* HAVE_CONFIG_H */ + +#ifdef HAVE_LIBNOTIFY +#include +#endif + +#include "active-sensor-libnotify.h" + +static void notif_closed_cb(NotifyNotification *notification, + ActiveSensor *active_sensor) { + + g_assert(notification != NULL && active_sensor != NULL); + + int i; + + g_debug("Notification was closed.. setting reference to NULL so we can show again if needed."); + + // set notif reference to NULL + for (i = 0; i < NUM_NOTIFS; i++) { + if (active_sensor->notification[i] == notification) { + active_sensor->notification[i] = NULL; + break; + } + } +} + +void active_sensor_libnotify_notify_end(ActiveSensor *active_sensor, + NotifType notif_type) { + + GError *error = NULL; + if (active_sensor->notification[notif_type]) { + g_debug("Closing notification"); + if(!notify_notification_close(active_sensor->notification[notif_type], &error)) { + g_warning("Error closing notification: %s", error->message); + g_error_free(error); + } + g_object_unref(active_sensor->notification[notif_type]); + active_sensor->notification[notif_type] = NULL; + } +} + +void active_sensor_libnotify_notify(ActiveSensor *active_sensor, + NotifType notif_type, + const gchar *summary, + const gchar *message, + const gchar *icon_filename, + gint timeout_msecs) { + + GError *error = NULL; + + if (!notify_is_initted()) { + if (!notify_init(PACKAGE)) { + return; + } + } + g_debug("Doing notification %s: %s: %s", (notif_type == SENSOR_INTERFACE_ERROR ? "interface-error" : "other") ,summary, message); + + /* leave any existing notification since most likely hasn't changed */ + if (active_sensor->notification[notif_type] != NULL) { + return; + /* active_sensor_libnotify_notify_end(active_sensor, notif_type); */ + } + + /* now create a new one */ + g_debug("Creating new notification"); + active_sensor->notification[notif_type] = notify_notification_new(summary, message, icon_filename); + g_signal_connect(active_sensor->notification[notif_type], "closed", + G_CALLBACK(notif_closed_cb), + active_sensor); + + notify_notification_set_urgency(active_sensor->notification[notif_type], NOTIFY_URGENCY_CRITICAL); + + /* timeout may have changed so update it */ + notify_notification_set_timeout(active_sensor->notification[notif_type], timeout_msecs); + + g_debug("showing notification"); + if (!notify_notification_show(active_sensor->notification[notif_type], &error)) { + g_debug("Error showing notification: %s", error->message); + g_error_free(error); + } + +} + diff --git a/pool/shard004/C/0098421_scratchpad.template.c b/pool/shard004/C/0098421_scratchpad.template.c new file mode 100644 index 0000000000000000000000000000000000000000..a3077c5a72aa7aa3b4e8c8e359c4935e423aa19d --- /dev/null +++ b/pool/shard004/C/0098421_scratchpad.template.c @@ -0,0 +1,21 @@ +#include +#include +#include + +int main() +{ + getdns_return_t r; + getdns_context *ctx = NULL; + + if ((r = getdns_context_create(&ctx, 1))) + fprintf(stderr, "Could not create context"); + + if (ctx) + getdns_context_destroy(ctx); + + if (r) { + fprintf(stderr, ": %s\n", getdns_get_errorstr_by_id(r)); + exit(EXIT_FAILURE); + } + exit(EXIT_SUCCESS); +} diff --git a/pool/shard004/C/0098423_condvar.c b/pool/shard004/C/0098423_condvar.c new file mode 100644 index 0000000000000000000000000000000000000000..245ee68d9e03cd4df2d1b42be803fc7a011c3642 --- /dev/null +++ b/pool/shard004/C/0098423_condvar.c @@ -0,0 +1,49 @@ +#include +#include +#include +#include +#include + +void cv_init(condvar_t *cv, const char *name) { + cv->name = name; + cv->waiters = 0; +} + +void cv_wait(condvar_t *cv, lock_t m) { + WITH_INTR_DISABLED { + cv->waiters++; + lk_release(m); + /* If we got interrupted here and an interrupt filter called + * cv_signal, we would have a lost wakeup, so we need interrupts + * to be disabled. Same goes for cv_wait_timed. */ + sleepq_wait(cv, __caller(0)); + } + lk_acquire(m, __caller(0)); +} + +int cv_wait_timed(condvar_t *cv, lock_t m, systime_t timeout) { + int status; + WITH_INTR_DISABLED { + cv->waiters++; + lk_release(m); + status = sleepq_wait_timed(cv, __caller(0), timeout); + } + lk_acquire(m, __caller(0)); + return status; +} + +void cv_signal(condvar_t *cv) { + SCOPED_NO_PREEMPTION(); + if (cv->waiters > 0) { + cv->waiters--; + sleepq_signal(cv); + } +} + +void cv_broadcast(condvar_t *cv) { + SCOPED_NO_PREEMPTION(); + if (cv->waiters > 0) { + cv->waiters = 0; + sleepq_broadcast(cv); + } +} diff --git a/pool/shard004/C/0098424_rtp.c b/pool/shard004/C/0098424_rtp.c new file mode 100644 index 0000000000000000000000000000000000000000..8804238d78535dadaac7e9c96db64f0807fdbfe9 --- /dev/null +++ b/pool/shard004/C/0098424_rtp.c @@ -0,0 +1,150 @@ +/* + * rtp.c + * + * library functions for the real-time transport protocol + * + * David A. McGrew + * Cisco Systems, Inc. + */ + + +#include "rtp.h" + +#include +#include + +#include +#ifdef HAVE_SYS_SOCKET_H +# include +#endif + +#define PRINT_DEBUG 0 /* set to 1 to print out debugging data */ +#define VERBOSE_DEBUG 0 /* set to 1 to print out more data */ + +ssize_t +rtp_sendto(rtp_sender_t *sender, const void* msg, int len) { + int octets_sent; + err_status_t stat; + int pkt_len = len + rtp_header_len; + + /* marshal data */ + strncpy(sender->message.body, msg, len); + + /* update header */ + sender->message.header.seq = ntohs(sender->message.header.seq) + 1; + sender->message.header.seq = htons(sender->message.header.seq); + sender->message.header.ts = ntohl(sender->message.header.ts) + 1; + sender->message.header.ts = htonl(sender->message.header.ts); + + /* apply srtp */ + stat = srtp_protect(sender->srtp_ctx, &sender->message.header, &pkt_len); + if (stat) { +#if PRINT_DEBUG + fprintf(stderr, "error: srtp protection failed with code %d\n", stat); +#endif + return -1; + } +#if VERBOSE_DEBUG + srtp_print_packet(&sender->message.header, pkt_len); +#endif + octets_sent = sendto(sender->socket, (void*)&sender->message, + pkt_len, 0, (struct sockaddr *)&sender->addr, + sizeof (struct sockaddr_in)); + + if (octets_sent != pkt_len) { +#if PRINT_DEBUG + fprintf(stderr, "error: couldn't send message %s", (char *)msg); + perror(""); +#endif + } + + return octets_sent; +} + +ssize_t +rtp_recvfrom(rtp_receiver_t *receiver, void *msg, int *len) { + int octets_recvd; + err_status_t stat; + + octets_recvd = recvfrom(receiver->socket, (void *)&receiver->message, + *len, 0, (struct sockaddr *) NULL, 0); + + /* verify rtp header */ + if (receiver->message.header.version != 2) { + *len = 0; + return -1; + } + +#if PRINT_DEBUG + fprintf(stderr, "%d octets received from SSRC %u\n", + octets_recvd, receiver->message.header.ssrc); +#endif +#if VERBOSE_DEBUG + srtp_print_packet(&receiver->message.header, octets_recvd); +#endif + + /* apply srtp */ + stat = srtp_unprotect(receiver->srtp_ctx, + &receiver->message.header, &octets_recvd); + if (stat) { + fprintf(stderr, + "error: srtp unprotection failed with code %d%s\n", stat, + stat == err_status_replay_fail ? " (replay check failed)" : + stat == err_status_auth_fail ? " (auth check failed)" : ""); + return -1; + } + strncpy(msg, receiver->message.body, octets_recvd); + + return octets_recvd; +} + +int +rtp_sender_init(rtp_sender_t *sender, + int socket, + struct sockaddr_in addr, + uint32_t ssrc) { + + /* set header values */ + sender->message.header.ssrc = htonl(ssrc); + sender->message.header.ts = 0; + sender->message.header.seq = (uint16_t) rand(); + sender->message.header.m = 0; + sender->message.header.pt = 0x1; + sender->message.header.version = 2; + sender->message.header.p = 0; + sender->message.header.x = 0; + sender->message.header.cc = 0; + + /* set other stuff */ + sender->socket = socket; + sender->addr = addr; + + return 0; +} + +int +rtp_receiver_init(rtp_receiver_t *rcvr, + int socket, + struct sockaddr_in addr, + uint32_t ssrc) { + + /* set header values */ + rcvr->message.header.ssrc = htonl(ssrc); + rcvr->message.header.ts = 0; + rcvr->message.header.seq = 0; + rcvr->message.header.m = 0; + rcvr->message.header.pt = 0x1; + rcvr->message.header.version = 2; + rcvr->message.header.p = 0; + rcvr->message.header.x = 0; + rcvr->message.header.cc = 0; + + /* set other stuff */ + rcvr->socket = socket; + rcvr->addr = addr; + + return 0; +} + + + diff --git a/pool/shard004/C/0098437_main.c b/pool/shard004/C/0098437_main.c new file mode 100644 index 0000000000000000000000000000000000000000..e0f81ba6d5701f54736e73adfab3924b2f98e63c --- /dev/null +++ b/pool/shard004/C/0098437_main.c @@ -0,0 +1,128 @@ +/* + 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 "ch.h" +#include "hal.h" +#include "test.h" +#include "shell.h" +#include "chprintf.h" + +#define SHELL_WA_SIZE THD_WORKING_AREA_SIZE(1024) + +static const ShellCommand commands[] = { + {NULL, NULL} +}; + +static const ShellConfig shell_cfg1 = { + (BaseSequentialStream *)&SD1, + commands +}; + +/* + * LEDs blinker thread, times are in milliseconds. + */ +static THD_WORKING_AREA(waThread1, 128); +static THD_FUNCTION(Thread1, arg) { + + (void)arg; + chRegSetThreadName("blinker"); + + while (true) { + unsigned i; + + for (i = 0; i < 4; i++) { + palClearPad(PORT11, P11_LED1); + chThdSleepMilliseconds(100); + palClearPad(PORT11, P11_LED2); + chThdSleepMilliseconds(100); + palClearPad(PORT11, P11_LED3); + chThdSleepMilliseconds(100); + palClearPad(PORT11, P11_LED4); + chThdSleepMilliseconds(100); + palSetPad(PORT11, P11_LED1); + chThdSleepMilliseconds(100); + palSetPad(PORT11, P11_LED2); + chThdSleepMilliseconds(100); + palSetPad(PORT11, P11_LED3); + chThdSleepMilliseconds(100); + palSetPad(PORT11, P11_LED4); + chThdSleepMilliseconds(300); + } + + for (i = 0; i < 4; i++) { + palTogglePad(PORT11, P11_LED1); + chThdSleepMilliseconds(250); + palTogglePad(PORT11, P11_LED1); + palTogglePad(PORT11, P11_LED2); + chThdSleepMilliseconds(250); + palTogglePad(PORT11, P11_LED2); + palTogglePad(PORT11, P11_LED3); + chThdSleepMilliseconds(250); + palTogglePad(PORT11, P11_LED3); + palTogglePad(PORT11, P11_LED4); + chThdSleepMilliseconds(250); + palTogglePad(PORT11, P11_LED4); + } + + palSetPort(PORT11, + PAL_PORT_BIT(P11_LED1) | PAL_PORT_BIT(P11_LED2) | + PAL_PORT_BIT(P11_LED3) | PAL_PORT_BIT(P11_LED4)); + } +} + +/* + * Application entry point. + */ +int main(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(); + + /* + * Shell manager initialization. + */ + shellInit(); + + /* + * Activates the serial driver 1 using the driver default configuration. + */ + sdStart(&SD1, NULL); + + /* + * Creates the blinker thread. + */ + chThdCreateStatic(waThread1, sizeof(waThread1), NORMALPRIO, Thread1, NULL); + + /* + * Normal main() thread activity, spawning shells. + */ + while (true) { + thread_t *shelltp = chThdCreateFromHeap(NULL, SHELL_WA_SIZE, + "shell", NORMALPRIO + 1, + shellThread, (void *)&shell_cfg1); + chThdWait(shelltp); /* Waiting termination. */ + chThdFreeToHeap(shelltp); /* Returning memory to heap. */ + chThdSleepMilliseconds(1000); + } + return 0; +} diff --git a/pool/shard004/C/0098439_env.c b/pool/shard004/C/0098439_env.c new file mode 100644 index 0000000000000000000000000000000000000000..d36a8e02d4abb4aaf4378533f4344ff07649dbbb --- /dev/null +++ b/pool/shard004/C/0098439_env.c @@ -0,0 +1,77 @@ +/* + * Copyright (c) 1988, 1993, 1994 + * 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 +#include +#include + +static void +usage(void) +{ + (void)fprintf(stderr, "usage: env [-i] [name=value ...] [command]\n"); + exit(1); +} + +int +main(int argc, char **argv) +{ + char **ep, *p; + char *cleanenv[1]; + int ch; + + while ((ch = getopt(argc, argv, "-i")) != -1) + switch((char)ch) { + case '-': /* obsolete */ + case 'i': + environ = cleanenv; + cleanenv[0] = NULL; + break; + case '?': + default: + usage(); + } + + for (argv += optind; *argv && (p = strchr(*argv, '=')); ++argv) + (void)setenv(*argv, ++p, 1); + + if (*argv) { + /* return 127 if the command to be run could not be found; 126 + if the command was was found but could not be invoked */ + + execvp(*argv, argv); + err((errno == ENOENT) ? 127 : 126, "%s", *argv); + /* NOTREACHED */ + } + + for (ep = environ; *ep; ep++) + (void)printf("%s\n", *ep); + + exit(0); +} diff --git a/pool/shard004/C/0098441_CWE122_Heap_Based_Buffer_Overflow__c_CWE805_int64_t_memcpy_67b.c b/pool/shard004/C/0098441_CWE122_Heap_Based_Buffer_Overflow__c_CWE805_int64_t_memcpy_67b.c new file mode 100644 index 0000000000000000000000000000000000000000..5b39f8d047703e347b7668aa6a9291a28fd99223 --- /dev/null +++ b/pool/shard004/C/0098441_CWE122_Heap_Based_Buffer_Overflow__c_CWE805_int64_t_memcpy_67b.c @@ -0,0 +1,55 @@ +/* TEMPLATE GENERATED TESTCASE FILE +Filename: CWE122_Heap_Based_Buffer_Overflow__c_CWE805_int64_t_memcpy_67b.c +Label Definition File: CWE122_Heap_Based_Buffer_Overflow__c_CWE805.label.xml +Template File: sources-sink-67b.tmpl.c +*/ +/* + * @description + * CWE: 122 Heap Based Buffer Overflow + * BadSource: Allocate using malloc() and set data pointer to a small buffer + * GoodSource: Allocate using malloc() and set data pointer to a large buffer + * Sinks: memcpy + * BadSink : Copy int64_t array to data using memcpy + * Flow Variant: 67 Data flow: data passed in a struct from one function to another in different source files + * + * */ + +#include "std_testcase.h" + +typedef struct _CWE122_Heap_Based_Buffer_Overflow__c_CWE805_int64_t_memcpy_67_structType +{ + int64_t * structFirst; +} CWE122_Heap_Based_Buffer_Overflow__c_CWE805_int64_t_memcpy_67_structType; + +#ifndef OMITBAD + +void CWE122_Heap_Based_Buffer_Overflow__c_CWE805_int64_t_memcpy_67b_badSink(CWE122_Heap_Based_Buffer_Overflow__c_CWE805_int64_t_memcpy_67_structType myStruct) +{ + int64_t * data = myStruct.structFirst; + { + int64_t source[100] = {0}; /* fill with 0's */ + /* POTENTIAL FLAW: Possible buffer overflow if data < 100 */ + memcpy(data, source, 100*sizeof(int64_t)); + printLongLongLine(data[0]); + free(data); + } +} + +#endif /* OMITBAD */ + +#ifndef OMITGOOD + +/* goodG2B uses the GoodSource with the BadSink */ +void CWE122_Heap_Based_Buffer_Overflow__c_CWE805_int64_t_memcpy_67b_goodG2BSink(CWE122_Heap_Based_Buffer_Overflow__c_CWE805_int64_t_memcpy_67_structType myStruct) +{ + int64_t * data = myStruct.structFirst; + { + int64_t source[100] = {0}; /* fill with 0's */ + /* POTENTIAL FLAW: Possible buffer overflow if data < 100 */ + memcpy(data, source, 100*sizeof(int64_t)); + printLongLongLine(data[0]); + free(data); + } +} + +#endif /* OMITGOOD */ diff --git a/pool/shard004/C/0098453_event_delegator.c b/pool/shard004/C/0098453_event_delegator.c new file mode 100644 index 0000000000000000000000000000000000000000..086252dcdb0893ef7933554e32494b705db6b97a --- /dev/null +++ b/pool/shard004/C/0098453_event_delegator.c @@ -0,0 +1,154 @@ +#include "opl/src/h/graphics.h" +#include "opl/src/h/system.h" + +#include "ote/src/h/event_delegator.h" +#include "ote/src/h/base.h" + +#include +#include + +global_state *ctor_global_state(int argc, char **argv, ovp *config) +{ + init_graphics(); + init_input(); + + global_state *gs=malloc(sizeof(global_state)); + gs->e.id=0; + gs->e.pressed=0; + gs->config=config; + gs->editors_size=1; + gs->editors=(editor**)malloc(sizeof(editor*)*gs->editors_size); + gs->editors[0]=ctor_editor(); + + + gs->focused_editor=gs->editors[0]; + + gs->mouse_position; + gs->mouse_position.x=0; + gs->mouse_position.y=0; + + + + set_cursor(CURSOR_TEXT); + + for(s32 i=1; ifocused_editor,argv[i], gs->config); + } + + return gs; +} + +s32 delegate_event_window(global_state *gs) +{ + if(gs->e.id) + {/*do window specific operations*/ + if(editor_get_current_page_tab(gs->focused_editor)) + { + if(gs->e.type==MOUSE_MOTION) + { + gs->mouse_position.x=gs->e.mouse_info.x; + gs->mouse_position.y=gs->e.mouse_info.y; + editor_handle_mouse_motion(gs->focused_editor, gs->mouse_position); + } + + if(gs->e.type==MOUSE_WHEEL) + { + editor_handle_mouse_wheel(gs->focused_editor,gs->e.mouse_info.y); + } + /*@bug sometimes the cursor changes row but doesnt change column*/ + if(gs->e.type==LEFT_MOUSE && gs->e.pressed) + { + if(editor_handle_left_mouse_down(gs->focused_editor, gs->mouse_position)) + { + return 0; + } + } + if(gs->e.type==LEFT_MOUSE && !gs->e.pressed) + { + editor_handle_left_mouse_up(gs->focused_editor); + } + } + else + { + set_cursor(CURSOR_NORMAL); + } + + if(gs->e.type==WINDOW_CLOSE) + { + u32 i; + for(i=0; ieditors_size; i++) + { + if(window_get_id(editor_get_window(gs->editors[i]))==gs->e.id) + { + editor *editor_to_free=gs->editors[i]; + u32 i2; + for(i2=i; i2editors_size-1; i2++) + { + gs->editors[i2]=gs->editors[i2+1]; + } + gs->editors_size-=1; + gs->editors=(editor**)realloc(gs->editors,sizeof(editor*)*gs->editors_size); + dtor_editor(editor_to_free); + break; + } + } + + printf("checking if should exit, windows sz: %d\n",gs->editors_size); + if(gs->editors_size==0) + { + return EXIT_CODE_ALL_WINDOWS_CLOSED; + } + } + if(gs->e.type == FOCUS_GAINED) + { + sleep_milli(32);/*give it time for the event to come before flush*/ + flush_events(ALL_EVENTS); + u32 i; + for(i=0; ieditors_size; i++) + { + if(window_get_id(editor_get_window(gs->editors[i]))==gs->e.id) + { + gs->focused_editor=gs->editors[i]; + /*@bug mouse doesnt properly register events ending if its not set, + but if it is set then it registers events you wouldnt expect... + set_mouse_capture_on_currently_focused_window(true);*/ + + break; + } + } + //gs->focused_editor=editors[e.id-1];//@todo do lookup on editors, because id can change and wont just index into array cleanly + } + if(gs->e.type==DROP_FILE) + { + printf("got file drop: %s\n",gs->e.str); + //do not free e.str + ctor_page_tab(gs->focused_editor,gs->e.str, gs->config); + } + } + return 0; +} + +s32 delegate_event(global_state *gs) +{ + s32 exit_code; + + exit_code=delegate_event_window(gs); + + if(!exit_code&&editor_get_current_page_tab(gs->focused_editor)) + { + /*@BUG IF RANDOMLY DONT GET KEYS ITS PROBABLY BECAUSE THIS E.TYPE CHECK*/ + if(gs->focused_editor && gs->e.type) + {//keystroke to text interpreter + if(editor_process_keys(gs->focused_editor, gs->e)) + { + s32 handle_keys_code=editor_handle_keys(gs->focused_editor, gs->e); + if(handle_keys_code==REQUEST_SPAWN_EDITOR) + { + d_append(gs->editors,gs->editors_size,ctor_editor()); + } + } + } + } + return exit_code; +} diff --git a/pool/shard004/C/0098456_setresgid01.c b/pool/shard004/C/0098456_setresgid01.c new file mode 100644 index 0000000000000000000000000000000000000000..173ee35c37f45bb2723e17e9b0649edd9fab6b2f --- /dev/null +++ b/pool/shard004/C/0098456_setresgid01.c @@ -0,0 +1,218 @@ +/* + * 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., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + * + */ +/********************************************************** + * + * TEST IDENTIFIER : setresgid01 + * + * EXECUTED BY : root / superuser + * + * TEST TITLE : Checking functionality of setresgid(2) + * + * TEST CASE TOTAL : 5 + * + * AUTHOR : Madhu T L + * + * SIGNALS + * Uses SIGUSR1 to pause before test if option set. + * (See the parse_opts(3) man page). + * + * DESCRIPTION + * Verify that, + * 1. setresgid(2) is successful for setresgid(-1, -1, -1) + * 2. setresgid(2) is successful for setresgid(-1, -1, nobody) + * 3. setresgid(2) is successful for setresgid(-1, nobody, -1) + * 4. setresgid(2) is successful for setresgid(nobody, -1, -1) + * 5. setresgid(2) is successful for setresgid(root, root, root) + * + * Setup: + * Setup signal handling. + * Test caller is superuser + * Check existence of root and nobody user id's + * Pause for SIGUSR1 if option specified. + * + * Test: + * Loop if the proper options are given. + * Execute system call + * Check return value and functionality, if success, + * Issue PASS message + * Otherwise, + * Issue FAIL message + * + * Cleanup: + * Print errno log and/or timing stats if options given + * + * USAGE: + * setresgid01 [-c n] [-e] [-f] [-h] [-i n] [-I x] [-p] [-P x] [-t] + * where, -c n : Run n copies concurrently. + * -e : Turn on errno logging. + * -f : Turn off functional testing + * -h : Show help screen + * -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. + * + ****************************************************************/ + +#define _GNU_SOURCE 1 +#include +#include +#include +#include +#include "test.h" +#include "compat_16.h" + +#define EXP_RET_VAL 0 + +struct test_case_t { /* test case structure */ + uid_t *rgid; /* real GID */ + uid_t *egid; /* effective GID */ + uid_t *sgid; /* saved GID */ + struct passwd *exp_rgid; /* Expected real GID */ + struct passwd *exp_egid; /* Expected effective GID */ + struct passwd *exp_sgid; /* Expected saved GID */ + char *desc; /* Test description */ +}; + +TCID_DEFINE(setresgid01); +static int testno; +static struct passwd nobody, root; +static uid_t nobody_gid, root_gid, neg = -1; + +static int test_functionality(uid_t, uid_t, uid_t); +static void setup(void); +static void cleanup(void); + +/* Don't change order of these test cases */ +static struct test_case_t tdat[] = { + {&neg, &neg, &neg, &root, &root, &root, + "setresgid(-1, -1, -1)"}, + {&neg, &neg, &nobody.pw_gid, &root, &root, &nobody, + "setresgid(-1, -1, nobody)"}, + {&neg, &nobody.pw_gid, &neg, &root, &nobody, &nobody, + "setresgid(-1, nobody, -1)"}, + {&nobody.pw_gid, &neg, &neg, &nobody, &nobody, &nobody, + "setresgid(nobody, -1, -1)"}, + {&root.pw_gid, &root.pw_gid, &root.pw_gid, &root, &root, &root, + "setresgid(root, root, root)"}, +}; + +int TST_TOTAL = sizeof(tdat) / sizeof(tdat[0]); + +int main(int argc, char **argv) +{ + int lc; + + tst_parse_opts(argc, argv, NULL, NULL); + + setup(); + + for (lc = 0; TEST_LOOPING(lc); lc++) { + /* reset tst_count in case we are looping */ + tst_count = 0; + + for (testno = 0; testno < TST_TOTAL; ++testno) { + + TEST(SETRESGID(cleanup, *tdat[testno].rgid, *tdat[testno].egid, + *tdat[testno].sgid)); + + if (TEST_RETURN == EXP_RET_VAL) { + if (!test_functionality + (tdat[testno].exp_rgid->pw_gid, + tdat[testno].exp_egid->pw_gid, + tdat[testno].exp_sgid->pw_gid)) { + + tst_resm(TPASS, "Test for %s " + "successful", + tdat[testno].desc); + } else { + tst_resm(TFAIL, "Functionality test " + "for %s failed", + tdat[testno].desc); + } + } else { + tst_resm(TFAIL, "Test for %s failed; returned" + " %ld (expected %d), errno %d (expected" + " 0)", tdat[testno].desc, + TEST_RETURN, EXP_RET_VAL, TEST_ERRNO); + } + } + } + cleanup(); + + tst_exit(); +} + +static int test_functionality(uid_t exp_rgid, uid_t exp_egid, uid_t exp_sgid) +{ + uid_t cur_rgid, cur_egid, cur_sgid; + + /* Get current real, effective and saved group id's */ + if (getresgid(&cur_rgid, &cur_egid, &cur_sgid) == -1) { + tst_brkm(TBROK, cleanup, "getresgid() failed"); + + } + + if ((cur_rgid == exp_rgid) && (cur_egid == exp_egid) + && (cur_sgid == exp_sgid)) { + return 0; + } + return 1; +} + +/* + * setup() + * performs all ONE TIME setup for this test + */ +void setup(void) +{ + struct passwd *passwd_p; + + tst_require_root(); + + tst_sig(NOFORK, DEF_HANDLER, cleanup); + + if ((passwd_p = getpwnam("root")) == NULL) { + tst_brkm(TBROK, NULL, "getpwnam() failed for root"); + + } + root = *passwd_p; + GID16_CHECK((root_gid = root.pw_gid), "setresgid", cleanup) + + if ((passwd_p = getpwnam("nobody")) == NULL) { + tst_brkm(TBROK, NULL, "nobody user id doesn't exist"); + + } + nobody = *passwd_p; + GID16_CHECK((nobody_gid = nobody.pw_gid), "setresgid", cleanup) + + /* Pause if that option was specified + * TEST_PAUSE contains the code to fork the test with the -c option. + */ + TEST_PAUSE; +} + +/* + * cleanup() + * performs all ONE TIME cleanup for this test at + * completion or premature exit + */ +void cleanup(void) +{ + +} diff --git a/pool/shard004/C/0098458_ds1307.c b/pool/shard004/C/0098458_ds1307.c new file mode 100644 index 0000000000000000000000000000000000000000..1a2bad3c5c60142a647751de5d8792483c261414 --- /dev/null +++ b/pool/shard004/C/0098458_ds1307.c @@ -0,0 +1,180 @@ +/* + * (C) Copyright 2001, 2002, 2003 + * Wolfgang Denk, DENX Software Engineering, wd@denx.de. + * Keith Outwater, keith_outwater@mvis.com` + * Steven Scholz, steven.scholz@imc-berlin.de + * + * SPDX-License-Identifier: GPL-2.0+ + */ + +/* + * Date & Time support (no alarms) for Dallas Semiconductor (now Maxim) + * DS1307 and DS1338 Real Time Clock (RTC). + * + * based on ds1337.c + */ + +#include +#include +#include +#include + +#if defined(CONFIG_CMD_DATE) + +/*---------------------------------------------------------------------*/ +#undef DEBUG_RTC + +#ifdef DEBUG_RTC +#define DEBUGR(fmt,args...) printf(fmt ,##args) +#else +#define DEBUGR(fmt,args...) +#endif +/*---------------------------------------------------------------------*/ + +#ifndef CONFIG_SYS_I2C_RTC_ADDR +# define CONFIG_SYS_I2C_RTC_ADDR 0x68 +#endif + +#if defined(CONFIG_RTC_DS1307) && (CONFIG_SYS_I2C_SPEED > 100000) +# error The DS1307 is specified only up to 100kHz! +#endif + +/* + * RTC register addresses + */ +#define RTC_SEC_REG_ADDR 0x00 +#define RTC_MIN_REG_ADDR 0x01 +#define RTC_HR_REG_ADDR 0x02 +#define RTC_DAY_REG_ADDR 0x03 +#define RTC_DATE_REG_ADDR 0x04 +#define RTC_MON_REG_ADDR 0x05 +#define RTC_YR_REG_ADDR 0x06 +#define RTC_CTL_REG_ADDR 0x07 + +#define RTC_SEC_BIT_CH 0x80 /* Clock Halt (in Register 0) */ + +#define RTC_CTL_BIT_RS0 0x01 /* Rate select 0 */ +#define RTC_CTL_BIT_RS1 0x02 /* Rate select 1 */ +#define RTC_CTL_BIT_SQWE 0x10 /* Square Wave Enable */ +#define RTC_CTL_BIT_OUT 0x80 /* Output Control */ + +static uchar rtc_read (uchar reg); +static void rtc_write (uchar reg, uchar val); + +/* + * Get the current time from the RTC + */ +int rtc_get (struct rtc_time *tmp) +{ + int rel = 0; + uchar sec, min, hour, mday, wday, mon, year; + + sec = rtc_read (RTC_SEC_REG_ADDR); + min = rtc_read (RTC_MIN_REG_ADDR); + hour = rtc_read (RTC_HR_REG_ADDR); + wday = rtc_read (RTC_DAY_REG_ADDR); + mday = rtc_read (RTC_DATE_REG_ADDR); + mon = rtc_read (RTC_MON_REG_ADDR); + year = rtc_read (RTC_YR_REG_ADDR); + + DEBUGR ("Get RTC year: %02x mon: %02x mday: %02x wday: %02x " + "hr: %02x min: %02x sec: %02x\n", + year, mon, mday, wday, hour, min, sec); + + if (sec & RTC_SEC_BIT_CH) { + printf ("### Warning: RTC oscillator has stopped\n"); + /* clear the CH flag */ + rtc_write (RTC_SEC_REG_ADDR, + rtc_read (RTC_SEC_REG_ADDR) & ~RTC_SEC_BIT_CH); + rel = -1; + } + + tmp->tm_sec = bcd2bin (sec & 0x7F); + tmp->tm_min = bcd2bin (min & 0x7F); + tmp->tm_hour = bcd2bin (hour & 0x3F); + tmp->tm_mday = bcd2bin (mday & 0x3F); + tmp->tm_mon = bcd2bin (mon & 0x1F); + tmp->tm_year = bcd2bin (year) + ( bcd2bin (year) >= 70 ? 1900 : 2000); + tmp->tm_wday = bcd2bin ((wday - 1) & 0x07); + tmp->tm_yday = 0; + tmp->tm_isdst= 0; + + DEBUGR ("Get DATE: %4d-%02d-%02d (wday=%d) TIME: %2d:%02d:%02d\n", + tmp->tm_year, tmp->tm_mon, tmp->tm_mday, tmp->tm_wday, + tmp->tm_hour, tmp->tm_min, tmp->tm_sec); + + return rel; +} + + +/* + * Set the RTC + */ +int rtc_set (struct rtc_time *tmp) +{ + DEBUGR ("Set DATE: %4d-%02d-%02d (wday=%d) TIME: %2d:%02d:%02d\n", + tmp->tm_year, tmp->tm_mon, tmp->tm_mday, tmp->tm_wday, + tmp->tm_hour, tmp->tm_min, tmp->tm_sec); + + if (tmp->tm_year < 1970 || tmp->tm_year > 2069) + printf("WARNING: year should be between 1970 and 2069!\n"); + + rtc_write (RTC_YR_REG_ADDR, bin2bcd (tmp->tm_year % 100)); + rtc_write (RTC_MON_REG_ADDR, bin2bcd (tmp->tm_mon)); + rtc_write (RTC_DAY_REG_ADDR, bin2bcd (tmp->tm_wday + 1)); + rtc_write (RTC_DATE_REG_ADDR, bin2bcd (tmp->tm_mday)); + rtc_write (RTC_HR_REG_ADDR, bin2bcd (tmp->tm_hour)); + rtc_write (RTC_MIN_REG_ADDR, bin2bcd (tmp->tm_min)); + rtc_write (RTC_SEC_REG_ADDR, bin2bcd (tmp->tm_sec)); + + return 0; +} + + +/* + * Reset the RTC. We setting the date back to 1970-01-01. + * We also enable the oscillator output on the SQW/OUT pin and program + * it for 32,768 Hz output. Note that according to the datasheet, turning + * on the square wave output increases the current drain on the backup + * battery to something between 480nA and 800nA. + */ +void rtc_reset (void) +{ + struct rtc_time tmp; + + rtc_write (RTC_SEC_REG_ADDR, 0x00); /* clearing Clock Halt */ + rtc_write (RTC_CTL_REG_ADDR, RTC_CTL_BIT_SQWE | RTC_CTL_BIT_RS1 | RTC_CTL_BIT_RS0); + + tmp.tm_year = 1970; + tmp.tm_mon = 1; + tmp.tm_mday= 1; + tmp.tm_hour = 0; + tmp.tm_min = 0; + tmp.tm_sec = 0; + + rtc_set(&tmp); + + printf ( "RTC: %4d-%02d-%02d %2d:%02d:%02d UTC\n", + tmp.tm_year, tmp.tm_mon, tmp.tm_mday, + tmp.tm_hour, tmp.tm_min, tmp.tm_sec); + + return; +} + + +/* + * Helper functions + */ + +static +uchar rtc_read (uchar reg) +{ + return (i2c_reg_read (CONFIG_SYS_I2C_RTC_ADDR, reg)); +} + + +static void rtc_write (uchar reg, uchar val) +{ + i2c_reg_write (CONFIG_SYS_I2C_RTC_ADDR, reg, val); +} +#endif diff --git a/pool/shard004/C/0098467_test-getline.c b/pool/shard004/C/0098467_test-getline.c new file mode 100644 index 0000000000000000000000000000000000000000..134e320a8a270a7809b5326723ac2830be349ee6 --- /dev/null +++ b/pool/shard004/C/0098467_test-getline.c @@ -0,0 +1,94 @@ +/* Test of getline() function. + Copyright (C) 2007-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, 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 , 2007. */ + +#include + +#include + +#include "signature.h" +SIGNATURE_CHECK (getline, ssize_t, (char **, size_t *, FILE *)); + +#include +#include + +#include "macros.h" + +int +main (void) +{ + FILE *f; + char *line; + size_t len; + ssize_t result; + + /* Create test file. */ + f = fopen ("test-getline.txt", "wb"); + if (!f || fwrite ("a\nA\nbc\nd\0f", 1, 10, f) != 10 || fclose (f) != 0) + { + fputs ("Failed to create sample file.\n", stderr); + remove ("test-getline.txt"); + return 1; + } + f = fopen ("test-getline.txt", "rb"); + if (!f) + { + fputs ("Failed to reopen sample file.\n", stderr); + remove ("test-getline.txt"); + return 1; + } + + /* Test initial allocation, which must include trailing NUL. */ + line = NULL; + len = 0; + result = getline (&line, &len, f); + ASSERT (result == 2); + ASSERT (strcmp (line, "a\n") == 0); + ASSERT (2 < len); + free (line); + + /* Test initial allocation again, with line = NULL and len != 0. */ + line = NULL; + len = (size_t)(~0) / 4; + result = getline (&line, &len, f); + ASSERT (result == 2); + ASSERT (strcmp (line, "A\n") == 0); + ASSERT (2 < len); + free (line); + + /* Test growth of buffer, must not leak. */ + line = malloc (1); + len = 0; + result = getline (&line, &len, f); + ASSERT (result == 3); + ASSERT (strcmp (line, "bc\n") == 0); + ASSERT (3 < len); + + /* Test embedded NULs and EOF behavior. */ + result = getline (&line, &len, f); + ASSERT (result == 3); + ASSERT (memcmp (line, "d\0f", 4) == 0); + ASSERT (3 < len); + + result = getline (&line, &len, f); + ASSERT (result == -1); + + free (line); + fclose (f); + remove ("test-getline.txt"); + return 0; +} diff --git a/pool/shard004/C/0098468_iaga.c b/pool/shard004/C/0098468_iaga.c new file mode 100644 index 0000000000000000000000000000000000000000..eeab1bb6a3c324ae7862071968489c2ee0b5e22c --- /dev/null +++ b/pool/shard004/C/0098468_iaga.c @@ -0,0 +1,231 @@ +/* + * iaga.c + * + * Routines for reading IAGA formatted data files + */ + +#include +#include +#include +#include +#include +#include +#include + +#include + +#include + +#include "grobs.h" + +static int iaga_read_HDZF(FILE *fp, grobs_data *data); +static int iaga_read_XYZF(FILE *fp, grobs_data *data); + +grobs_data * +grobs_iaga_read(const char *filename, grobs_data *data) +{ + FILE *fp; + char buf[GROBS_MAX_BUFFER]; + char s1[GROBS_MAX_BUFFER]; + char s2[GROBS_MAX_BUFFER]; + int header_cnt = 0; + + fp = fopen(filename, "r"); + if (!fp) + { + fprintf(stderr, "fopen: cannot open %s: %s\n", + filename, strerror(errno)); + return NULL; + } + + /* allocate space for 1-minute data */ + if (data == NULL) + data = grobs_alloc(GROBS_MAX_YEAR * 527040); + + while (fgets(buf, GROBS_MAX_BUFFER, fp) != NULL) + { + int c; + double val; + char *bufptr = buf; + + while (isspace(*bufptr)) + bufptr++; + + if (*bufptr == '#') + continue; + + if (!strncasecmp(bufptr, "geodetic latitude", 17)) + { + c = sscanf(bufptr, "%s %s %lf", s1, s2, &val); + if (c == 3) + { + ++header_cnt; + data->glat = val; + } + } + else if (!strncasecmp(bufptr, "geodetic longitude", 18)) + { + c = sscanf(bufptr, "%s %s %lf", s1, s2, &val); + if (c == 3) + { + ++header_cnt; + data->glon = val; + } + } + else if (!strncasecmp(bufptr, "reported", 8)) + { + c = sscanf(bufptr, "%s %s", s1, s2); + if (c == 2) + { + ++header_cnt; + if (!strncmp(s2, "HDZF", 4)) + { + iaga_read_HDZF(fp, data); + } + else if (!strncmp(s2, "XYZF", 4) || !strncmp(s2, "XYZG", 4)) + { + iaga_read_XYZF(fp, data); + } + else + { + fprintf(stderr, "grobs_iaga_read: unknown format type: %s\n", s2); + header_cnt = 0; + } + } + + /* this is the last header line read, so break after + * reading the file */ + break; + } + } + + fclose(fp); + + if (header_cnt != 3) + { + fprintf(stderr, "grobs_iaga_read: failed to read header\n"); + } + + return data; +} + +static int +iaga_read_HDZF(FILE *fp, grobs_data *data) +{ + int ret; + char buf[GROBS_MAX_BUFFER]; + size_t n = data->n; + + while (fgets(buf, GROBS_MAX_BUFFER, fp) != NULL) + { + int year, month, day; + int hour, min, doy; + double fsec; + double Z, D, F, H, Drad; + + /* read day number */ + ret = sscanf(buf, "%d-%d-%d %d:%d:%lf %d %lf %lf %lf %lf", + &year, &month, &day, &hour, &min, &fsec, + &doy, &H, &D, &Z, &F); + if (ret < 11) + continue; + + if (day < 1 || day > 31) + continue; + + if (month < 1 || month > 12) + continue; + + /* check missing data */ + if (fabs(H) > 90000.0) + continue; + if (fabs(D) > 90000.0) + continue; + if (fabs(Z) > 90000.0) + continue; + if (fabs(F) > 90000.0) + continue; + + /* D is in arcminutes */ + Drad = (D / 60.0) * M_PI / 180.0; + + /* store value */ + data->t[n] = date2timet((int) fsec, min, hour, day, month, year); + data->X[n] = H * cos(Drad); + data->Y[n] = H * sin(Drad); + data->Z[n] = Z; + data->H[n] = H; + data->D[n] = Drad * 180.0 / M_PI; + data->I[n] = atan2(Z, H); + + if (++n >= data->ntot) + { + fprintf(stderr, "iaga_read: not enough space allocated: %zu\n", data->ntot); + break; + } + } + + data->n = n; + + return 0; +} + +static int +iaga_read_XYZF(FILE *fp, grobs_data *data) +{ + int ret; + char buf[GROBS_MAX_BUFFER]; + size_t n = data->n; + + while (fgets(buf, GROBS_MAX_BUFFER, fp) != NULL) + { + int year, month, day; + int hour, min, doy; + double fsec; + double X, Y, Z, F, H; + + /* read day number */ + ret = sscanf(buf, "%d-%d-%d %d:%d:%lf %d %lf %lf %lf %lf", + &year, &month, &day, &hour, &min, &fsec, + &doy, &X, &Y, &Z, &F); + if (ret < 11) + continue; + + if (day < 1 || day > 31) + continue; + + if (month < 1 || month > 12) + continue; + + /* check missing data */ + if (fabs(X) > 90000.0) + continue; + if (fabs(Y) > 90000.0) + continue; + if (fabs(Z) > 90000.0) + continue; + if (fabs(F) > 90000.0) + continue; + + H = gsl_hypot(X, Y); + + /* store value */ + data->t[n] = date2timet((int) fsec, min, hour, day, month, year); + data->X[n] = X; + data->Y[n] = Y; + data->Z[n] = Z; + data->H[n] = H; + data->D[n] = atan2(Y, X) * 180.0 / M_PI; + data->I[n] = atan2(Z, H); + + if (++n >= data->ntot) + { + fprintf(stderr, "iaga_read: not enough space allocated: %zu\n", data->ntot); + break; + } + } + + data->n = n; + + return 0; +} diff --git a/pool/shard004/C/0098477_super.c b/pool/shard004/C/0098477_super.c new file mode 100644 index 0000000000000000000000000000000000000000..d1b01f76d4a02cea2ffc4847113fcc2e541c0539 --- /dev/null +++ b/pool/shard004/C/0098477_super.c @@ -0,0 +1,129 @@ +/* + * super.c + * + * Copyright (C) 2001-2002 Will Dyson + * + * Licensed under the GNU GPL. See the file COPYING for details. + * + */ + +#include +#include /* for PAGE_SIZE */ + +#include "befs.h" +#include "super.h" + +/* + * befs_load_sb -- Read from disk and properly byteswap all the fields + * of the befs superblock + */ +int +befs_load_sb(struct super_block *sb, befs_super_block *disk_sb) +{ + struct befs_sb_info *befs_sb = BEFS_SB(sb); + + /* Check the byte order of the filesystem */ + if (disk_sb->fs_byte_order == BEFS_BYTEORDER_NATIVE_LE) + { + befs_sb->byte_order = BEFS_BYTESEX_LE; + } + else if (disk_sb->fs_byte_order == BEFS_BYTEORDER_NATIVE_BE) + { + befs_sb->byte_order = BEFS_BYTESEX_BE; + } + + befs_sb->magic1 = fs32_to_cpu(sb, disk_sb->magic1); + befs_sb->magic2 = fs32_to_cpu(sb, disk_sb->magic2); + befs_sb->magic3 = fs32_to_cpu(sb, disk_sb->magic3); + befs_sb->block_size = fs32_to_cpu(sb, disk_sb->block_size); + befs_sb->block_shift = fs32_to_cpu(sb, disk_sb->block_shift); + befs_sb->num_blocks = fs64_to_cpu(sb, disk_sb->num_blocks); + befs_sb->used_blocks = fs64_to_cpu(sb, disk_sb->used_blocks); + befs_sb->inode_size = fs32_to_cpu(sb, disk_sb->inode_size); + + befs_sb->blocks_per_ag = fs32_to_cpu(sb, disk_sb->blocks_per_ag); + befs_sb->ag_shift = fs32_to_cpu(sb, disk_sb->ag_shift); + befs_sb->num_ags = fs32_to_cpu(sb, disk_sb->num_ags); + + befs_sb->flags = fs32_to_cpu(sb, disk_sb->flags); + + befs_sb->log_blocks = fsrun_to_cpu(sb, disk_sb->log_blocks); + befs_sb->log_start = fs64_to_cpu(sb, disk_sb->log_start); + befs_sb->log_end = fs64_to_cpu(sb, disk_sb->log_end); + + befs_sb->root_dir = fsrun_to_cpu(sb, disk_sb->root_dir); + befs_sb->indices = fsrun_to_cpu(sb, disk_sb->indices); + befs_sb->nls = NULL; + + return BEFS_OK; +} + +int +befs_check_sb(struct super_block *sb) +{ + struct befs_sb_info *befs_sb = BEFS_SB(sb); + + /* Check magic headers of super block */ + if ((befs_sb->magic1 != BEFS_SUPER_MAGIC1) + || (befs_sb->magic2 != BEFS_SUPER_MAGIC2) + || (befs_sb->magic3 != BEFS_SUPER_MAGIC3)) + { + befs_error(sb, "invalid magic header"); + return BEFS_ERR; + } + + /* + * Check blocksize of BEFS. + * + * Blocksize of BEFS is 1024, 2048, 4096 or 8192. + */ + + if ((befs_sb->block_size != 1024) + && (befs_sb->block_size != 2048) + && (befs_sb->block_size != 4096) + && (befs_sb->block_size != 8192)) + { + befs_error(sb, "invalid blocksize: %u", befs_sb->block_size); + return BEFS_ERR; + } + + if (befs_sb->block_size > PAGE_SIZE) + { + befs_error(sb, "blocksize(%u) cannot be larger " + "than system pagesize(%lu)", befs_sb->block_size, + PAGE_SIZE); + return BEFS_ERR; + } + + /* + * block_shift and block_size encode the same information + * in different ways as a consistency check. + */ + + if ((1 << befs_sb->block_shift) != befs_sb->block_size) + { + befs_error(sb, "block_shift disagrees with block_size. " + "Corruption likely."); + return BEFS_ERR; + } + + + /* ag_shift also encodes the same information as blocks_per_ag in a + * different way, non-fatal consistency check + */ + if ((1 << befs_sb->ag_shift) != befs_sb->blocks_per_ag) + { + befs_error(sb, "ag_shift disagrees with blocks_per_ag."); + } + + if (befs_sb->log_start != befs_sb->log_end || + befs_sb->flags == BEFS_DIRTY) + { + befs_error(sb, "Filesystem not clean! There are blocks in the " + "journal. You must boot into BeOS and mount this " + "volume to make it clean."); + return BEFS_ERR; + } + + return BEFS_OK; +} diff --git a/pool/shard004/C/0098479_tool_homedir.c b/pool/shard004/C/0098479_tool_homedir.c new file mode 100644 index 0000000000000000000000000000000000000000..719ff6a55f4f7d65ec1f752ce14c2b4bffddb9dd --- /dev/null +++ b/pool/shard004/C/0098479_tool_homedir.c @@ -0,0 +1,88 @@ +/*************************************************************************** + * _ _ ____ _ + * 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 "tool_setup.h" + +#ifdef HAVE_PWD_H +# include +#endif + +#include + +#include "tool_homedir.h" + +#include "memdebug.h" /* keep this as LAST include */ + +static char *GetEnv(const char *variable) +{ + char *dupe, *env; + + env = curl_getenv(variable); + if(!env) + return NULL; + + dupe = strdup(env); + curl_free(env); + return dupe; +} + +/* return the home directory of the current user as an allocated string */ +char *homedir(void) +{ + char *home; + + home = GetEnv("CURL_HOME"); + if(home) + return home; + + home = GetEnv("HOME"); + if(home) + return home; + +#if defined(HAVE_GETPWUID) && defined(HAVE_GETEUID) + { + struct passwd *pw = getpwuid(geteuid()); + + if(pw) { + home = pw->pw_dir; + if(home && home[0]) + home = strdup(home); + else + home = NULL; + } + } +#endif /* PWD-stuff */ +#ifdef WIN32 + home = GetEnv("APPDATA"); + if(!home) { + char *env = GetEnv("USERPROFILE"); + if(env) { + char *path = curl_maprintf("%s\\Application Data", env); + if(path) { + home = strdup(path); + curl_free(path); + } + free(env); + } + } +#endif /* WIN32 */ + return home; +} diff --git a/pool/shard004/C/0098486_CWE78_OS_Command_Injection__char_connect_socket_execl_16.c b/pool/shard004/C/0098486_CWE78_OS_Command_Injection__char_connect_socket_execl_16.c new file mode 100644 index 0000000000000000000000000000000000000000..0141ce62b443780f4fa23e03b8f23940ce7b920b --- /dev/null +++ b/pool/shard004/C/0098486_CWE78_OS_Command_Injection__char_connect_socket_execl_16.c @@ -0,0 +1,199 @@ +/* TEMPLATE GENERATED TESTCASE FILE +Filename: CWE78_OS_Command_Injection__char_connect_socket_execl_16.c +Label Definition File: CWE78_OS_Command_Injection.strings.label.xml +Template File: sources-sink-16.tmpl.c +*/ +/* + * @description + * CWE: 78 OS Command Injection + * BadSource: connect_socket Read data using a connect socket (client side) + * GoodSource: Fixed string + * Sink: execl + * BadSink : execute command with execl + * Flow Variant: 16 Control flow: while(1) + * + * */ + +#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 "-c" +#define COMMAND_ARG2 "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 /* 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" + +#ifdef _WIN32 +#include +#define EXECL _execl +#else /* NOT _WIN32 */ +#define EXECL execl +#endif + +#ifndef OMITBAD + +void CWE78_OS_Command_Injection__char_connect_socket_execl_16_bad() +{ + char * data; + char dataBuffer[100] = COMMAND_ARG2; + data = dataBuffer; + while(1) + { + { +#ifdef _WIN32 + WSADATA wsaData; + int wsaDataInit = 0; +#endif + int recvResult; + struct sockaddr_in service; + char *replace; + SOCKET connectSocket = INVALID_SOCKET; + size_t dataLen = strlen(data); + do + { +#ifdef _WIN32 + if (WSAStartup(MAKEWORD(2,2), &wsaData) != NO_ERROR) + { + break; + } + wsaDataInit = 1; +#endif + /* POTENTIAL FLAW: Read data using a connect socket */ + connectSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); + if (connectSocket == INVALID_SOCKET) + { + break; + } + memset(&service, 0, sizeof(service)); + service.sin_family = AF_INET; + service.sin_addr.s_addr = inet_addr(IP_ADDRESS); + service.sin_port = htons(TCP_PORT); + if (connect(connectSocket, (struct sockaddr*)&service, sizeof(service)) == SOCKET_ERROR) + { + break; + } + /* Abort on error or the connection was closed, make sure to recv one + * less char than is in the recv_buf in order to append a terminator */ + /* Abort on error or the connection was closed */ + recvResult = recv(connectSocket, (char *)(data + dataLen), sizeof(char) * (100 - dataLen - 1), 0); + if (recvResult == SOCKET_ERROR || recvResult == 0) + { + break; + } + /* Append null terminator */ + data[dataLen + recvResult / sizeof(char)] = '\0'; + /* Eliminate CRLF */ + replace = strchr(data, '\r'); + if (replace) + { + *replace = '\0'; + } + replace = strchr(data, '\n'); + if (replace) + { + *replace = '\0'; + } + } + while (0); + if (connectSocket != INVALID_SOCKET) + { + CLOSE_SOCKET(connectSocket); + } +#ifdef _WIN32 + if (wsaDataInit) + { + WSACleanup(); + } +#endif + } + break; + } + /* execl - 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 + +/* goodG2B() - use goodsource and badsink by changing the conditions on the while statements */ +static void goodG2B() +{ + char * data; + char dataBuffer[100] = COMMAND_ARG2; + data = dataBuffer; + while(1) + { + /* FIX: Append a fixed string to data (not user / external input) */ + strcat(data, "*.*"); + break; + } + /* execl - 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__char_connect_socket_execl_16_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_connect_socket_execl_16_good(); + printLine("Finished good()"); +#endif /* OMITGOOD */ +#ifndef OMITBAD + printLine("Calling bad()..."); + CWE78_OS_Command_Injection__char_connect_socket_execl_16_bad(); + printLine("Finished bad()"); +#endif /* OMITBAD */ + return 0; +} + +#endif diff --git a/pool/shard004/C/0098488_condition-subtyping-unreachable-cclib.c b/pool/shard004/C/0098488_condition-subtyping-unreachable-cclib.c new file mode 100644 index 0000000000000000000000000000000000000000..16ea60c4489f9caae20fc0e84a12869ab68edb64 --- /dev/null +++ b/pool/shard004/C/0098488_condition-subtyping-unreachable-cclib.c @@ -0,0 +1,160 @@ +/* + Part of: CCExceptions + Contents: body definitions of a subtype of "unreachable" + Date: Apr 18, 2020 + + Abstract + + Body definitions of a subtype of "unreachable". + + Copyright (C) 2017, 2018, 2019, 2020 Marco Maggi + + See the COPYING file. +*/ + + +/** -------------------------------------------------------------------- + ** Heaaders. + ** ----------------------------------------------------------------- */ + +#include +#include "condition-subtyping-unreachable-cclib.h" +#include +#include + + +/** -------------------------------------------------------------------- + ** Condition type descriptor definition. + ** ----------------------------------------------------------------- */ + +static cce_condition_final_fun_t cclib_method(cclib_exceptional_condition_descriptor_type(my_unreachable_subtype), final); +static cce_condition_delete_fun_t cclib_method(cclib_exceptional_condition_descriptor_type(my_unreachable_subtype), delete); +static cce_condition_static_message_fun_t cclib_method(cclib_exceptional_condition_descriptor_type(my_unreachable_subtype), static_message); + +static cclib_exceptional_condition_descriptor_type(my_unreachable_subtype) + cclib_exceptional_condition_descriptor(my_unreachable_subtype) = { + /* This "parent" field is set below by the module initialisation function. */ + .descriptor.parent = NULL, + .descriptor.final = cclib_method(cclib_exceptional_condition_descriptor_type(my_unreachable_subtype), final), + .descriptor.delete = cclib_method(cclib_exceptional_condition_descriptor_type(my_unreachable_subtype), delete), + .descriptor.static_message = cclib_method(cclib_exceptional_condition_descriptor_type(my_unreachable_subtype), static_message) +}; + +void +cclib_exceptional_condition_descriptor_set_parent_to(my_unreachable_subtype) (cce_descriptor_t * const D) +{ + D->parent = cclib_exceptional_condition_descriptor_pointer(my_unreachable_subtype); +} + + +/** -------------------------------------------------------------------- + ** Condition type descriptor: protocol functions. + ** ----------------------------------------------------------------- */ + +void +cclib_method(cclib_exceptional_condition_descriptor_type(my_unreachable_subtype), final) (cce_condition_t * _C) +/* Finalisation functions are called automatically when the function + "cce_condition_final()" is applied to the argument C. Here we finalise only the + fields of this type leaving untouched the fields of the parent type. */ +{ + CCLIB_PC(cclib_exceptional_condition_object_type(my_unreachable_subtype), C, _C); + + *(C->data) = 0; + free(C->data); + if (1) { fprintf(stderr, "%s: finalised %p\n", __func__, (void*)C); } +} + +void +cclib_method(cclib_exceptional_condition_descriptor_type(my_unreachable_subtype), delete) (cce_condition_t * _C) +/* The delete function is called automatically when the client code applies + "cce_condition_delete()" to the argument C. Here we release memory allocated for + the condition object. */ +{ + CCLIB_PC(cclib_exceptional_condition_object_type(my_unreachable_subtype), C, _C); + + free(C); + if (1) { fprintf(stderr, "%s: deleted %p\n", __func__, (void*)C); } +} + +char const * +cclib_method(cclib_exceptional_condition_descriptor_type(my_unreachable_subtype), static_message) (cce_condition_t const * C CCLIB_UNUSED) +{ + return "Unreachable subtype exceptional condition"; +} + + +/** -------------------------------------------------------------------- + ** Condition object type: constructor functions. + ** ----------------------------------------------------------------- */ + +void +cclib_init(cclib_exceptional_condition_object_type(my_unreachable_subtype)) + (cce_destination_t L, cclib_exceptional_condition_object_type(my_unreachable_subtype) * C, + char const * const filename, char const * const funcname, int const linenum, int the_data) +/* This initialisation function must be called both by: + * + * - The constructor function of this object type. + * + * - The initialisation functions of object types derived from this type. + * + * Here we call the parent's initialisation function; then we initialise the fields + * of this type. + */ +{ + cclib_init(cclib_exceptional_condition_object_type(cce_unreachable))(&(C->parent), filename, funcname, linenum); + C->data = cce_sys_malloc(L, sizeof(int)); + *(C->data) = the_data; + if (1) { fprintf(stderr, "%s: initialised %p\n", __func__, (void*)C); } +} + +cce_condition_t const * +cclib_new(cclib_exceptional_condition_object_type(my_unreachable_subtype)) + (cce_destination_t upper_L, char const * const filename, char const * const funcname, int const linenum, int the_data) +/* This constructor function is the public interface to the constructor of condition + * objects of type "my_condition_unreachable_subtype_t". + * + * Here we: + * + * 1. Allocate memory for the condition object itself. + * + * 2. Initialise the descriptor field by calling "cce_condition_init()". + * + * 3. Call the initialisation function for this type. + */ +{ + cce_location_t L[1]; + cce_error_handler_t C_H[1]; + + if (cce_location(L)) { + cce_run_catch_handlers_raise(L, upper_L); + } else { + cclib_exceptional_condition_object_type(my_unreachable_subtype) * C = + cce_sys_malloc_guarded(L, C_H, sizeof(cclib_exceptional_condition_object_type(my_unreachable_subtype))); + + cce_condition_init((cce_condition_t *) C, cclib_exceptional_condition_descriptor_pointer(my_unreachable_subtype)); + cclib_init(cclib_exceptional_condition_object_type(my_unreachable_subtype))(L, C, filename, funcname, linenum, the_data); + + cce_run_body_handlers(L); + if (1) { fprintf(stderr, "%s: constructed %p\n", __func__, (void*)C); } + return (cce_condition_t const *) C; + } +} + +bool +cclib_is(cclib_exceptional_condition_object_type(my_unreachable_subtype)) (cce_condition_t const * C) +{ + return cce_condition_is(C, cclib_exceptional_condition_descriptor_pointer(my_unreachable_subtype)); +} + + +/** -------------------------------------------------------------------- + ** Module initialisation. + ** ----------------------------------------------------------------- */ + +void +unreachable_cclib_subtyping_init_module (void) +{ + cclib_exceptional_condition_descriptor_set_parent_to(cce_unreachable)(cclib_exceptional_condition_descriptor_pointer(my_unreachable_subtype)); +} + +/* end of file */ diff --git a/pool/shard004/C/0098491_dequant.c b/pool/shard004/C/0098491_dequant.c new file mode 100644 index 0000000000000000000000000000000000000000..860536f72db29b4dcfe158207d4609994ab7e854 --- /dev/null +++ b/pool/shard004/C/0098491_dequant.c @@ -0,0 +1,182 @@ +/******************************************************************** + * * + * THIS FILE IS PART OF THE OggTheora SOFTWARE CODEC SOURCE CODE. * + * USE, DISTRIBUTION AND REPRODUCTION OF THIS LIBRARY SOURCE IS * + * GOVERNED BY A BSD-STYLE SOURCE LICENSE INCLUDED WITH THIS SOURCE * + * IN 'COPYING'. PLEASE READ THESE TERMS BEFORE DISTRIBUTING. * + * * + * THE Theora SOURCE CODE IS COPYRIGHT (C) 2002-2009 * + * by the Xiph.Org Foundation and contributors http://www.xiph.org/ * + * * + ******************************************************************** + + function: + last mod: $Id$ + + ********************************************************************/ + +#include +#include +#include +#include "dequant.h" +#include "decint.h" + +int oc_quant_params_unpack(oc_pack_buf *_opb,th_quant_info *_qinfo){ + th_quant_base *base_mats; + long val; + int nbase_mats; + int sizes[64]; + int indices[64]; + int nbits; + int bmi; + int ci; + int qti; + int pli; + int qri; + int qi; + int i; + val=oc_pack_read(_opb,3); + nbits=(int)val; + for(qi=0;qi<64;qi++){ + val=oc_pack_read(_opb,nbits); + _qinfo->loop_filter_limits[qi]=(unsigned char)val; + } + val=oc_pack_read(_opb,4); + nbits=(int)val+1; + for(qi=0;qi<64;qi++){ + val=oc_pack_read(_opb,nbits); + _qinfo->ac_scale[qi]=(ogg_uint16_t)val; + } + val=oc_pack_read(_opb,4); + nbits=(int)val+1; + for(qi=0;qi<64;qi++){ + val=oc_pack_read(_opb,nbits); + _qinfo->dc_scale[qi]=(ogg_uint16_t)val; + } + val=oc_pack_read(_opb,9); + nbase_mats=(int)val+1; + base_mats=_ogg_malloc(nbase_mats*sizeof(base_mats[0])); + if(base_mats==NULL)return TH_EFAULT; + for(bmi=0;bmiqi_ranges[qti]+pli; + if(i>0){ + val=oc_pack_read1(_opb); + if(!val){ + int qtj; + int plj; + if(qti>0){ + val=oc_pack_read1(_opb); + if(val){ + qtj=qti-1; + plj=pli; + } + else{ + qtj=(i-1)/3; + plj=(i-1)%3; + } + } + else{ + qtj=(i-1)/3; + plj=(i-1)%3; + } + *qranges=*(_qinfo->qi_ranges[qtj]+plj); + continue; + } + } + val=oc_pack_read(_opb,nbits); + indices[0]=(int)val; + for(qi=qri=0;qi<63;){ + val=oc_pack_read(_opb,oc_ilog(62-qi)); + sizes[qri]=(int)val+1; + qi+=(int)val+1; + val=oc_pack_read(_opb,nbits); + indices[++qri]=(int)val; + } + /*Note: The caller is responsible for cleaning up any partially + constructed qinfo.*/ + if(qi>63){ + _ogg_free(base_mats); + return TH_EBADHEADER; + } + qranges->nranges=qri; + qranges->sizes=qrsizes=(int *)_ogg_malloc(qri*sizeof(qrsizes[0])); + if(qranges->sizes==NULL){ + /*Note: The caller is responsible for cleaning up any partially + constructed qinfo.*/ + _ogg_free(base_mats); + return TH_EFAULT; + } + memcpy(qrsizes,sizes,qri*sizeof(qrsizes[0])); + qrbms=(th_quant_base *)_ogg_malloc((qri+1)*sizeof(qrbms[0])); + if(qrbms==NULL){ + /*Note: The caller is responsible for cleaning up any partially + constructed qinfo.*/ + _ogg_free(base_mats); + return TH_EFAULT; + } + qranges->base_matrices=(const th_quant_base *)qrbms; + do{ + bmi=indices[qri]; + /*Note: The caller is responsible for cleaning up any partially + constructed qinfo.*/ + if(bmi>=nbase_mats){ + _ogg_free(base_mats); + return TH_EBADHEADER; + } + memcpy(qrbms[qri],base_mats[bmi],sizeof(qrbms[qri])); + } + while(qri-->0); + } + _ogg_free(base_mats); + return 0; +} + +void oc_quant_params_clear(th_quant_info *_qinfo){ + int i; + for(i=6;i-->0;){ + int qti; + int pli; + qti=i/3; + pli=i%3; + /*Clear any duplicate pointer references.*/ + if(i>0){ + int qtj; + int plj; + qtj=(i-1)/3; + plj=(i-1)%3; + if(_qinfo->qi_ranges[qti][pli].sizes== + _qinfo->qi_ranges[qtj][plj].sizes){ + _qinfo->qi_ranges[qti][pli].sizes=NULL; + } + if(_qinfo->qi_ranges[qti][pli].base_matrices== + _qinfo->qi_ranges[qtj][plj].base_matrices){ + _qinfo->qi_ranges[qti][pli].base_matrices=NULL; + } + } + if(qti>0){ + if(_qinfo->qi_ranges[1][pli].sizes== + _qinfo->qi_ranges[0][pli].sizes){ + _qinfo->qi_ranges[1][pli].sizes=NULL; + } + if(_qinfo->qi_ranges[1][pli].base_matrices== + _qinfo->qi_ranges[0][pli].base_matrices){ + _qinfo->qi_ranges[1][pli].base_matrices=NULL; + } + } + /*Now free all the non-duplicate storage.*/ + _ogg_free((void *)_qinfo->qi_ranges[qti][pli].sizes); + _ogg_free((void *)_qinfo->qi_ranges[qti][pli].base_matrices); + } +} diff --git a/pool/shard004/C/0098495_cjk_variants.c b/pool/shard004/C/0098495_cjk_variants.c new file mode 100644 index 0000000000000000000000000000000000000000..3ace8a5e9fff45509e88029911ce1c9f65477510 --- /dev/null +++ b/pool/shard004/C/0098495_cjk_variants.c @@ -0,0 +1,126 @@ +/* Copyright (C) 1999-2002 Free Software Foundation, Inc. + This file is part of the GNU LIBICONV Tools. + + 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. */ + +/* + * Generates Unicode variants table from Koichi Yasuoka's UniVariants file. + */ + +#include +#include + +#define ENTRIES 8176 /* number of lines in UniVariants file */ +#define MAX_PER_ENTRY 10 /* max number of entries per line in file */ + +int main (int argc, char *argv[]) +{ + int variants[MAX_PER_ENTRY*ENTRIES]; + int uni2index[0x10000]; + int index; + + if (argc != 1) + exit(1); + + printf("/*\n"); + printf(" * Copyright (C) 1999-2002 Free Software Foundation, Inc.\n"); + printf(" * This file is part of the GNU LIBICONV Library.\n"); + printf(" *\n"); + printf(" * The GNU LIBICONV Library is free software; you can redistribute it\n"); + printf(" * and/or modify it under the terms of the GNU Library General Public\n"); + printf(" * License as published by the Free Software Foundation; either version 2\n"); + printf(" * of the License, or (at your option) any later version.\n"); + printf(" *\n"); + printf(" * The GNU LIBICONV Library is distributed in the hope that it will be\n"); + printf(" * useful, but WITHOUT ANY WARRANTY; without even the implied warranty of\n"); + printf(" * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n"); + printf(" * Library General Public License for more details.\n"); + printf(" *\n"); + printf(" * You should have received a copy of the GNU Library General Public\n"); + printf(" * License along with the GNU LIBICONV Library; see the file COPYING.LIB.\n"); + printf(" * If not, write to the Free Software Foundation, Inc., 59 Temple Place -\n"); + printf(" * Suite 330, Boston, MA 02111-1307, USA.\n"); + printf(" */\n"); + printf("\n"); + printf("/*\n"); + printf(" * CJK variants table\n"); + printf(" */\n"); + printf("\n"); + { + int c; + int j; + for (j = 0; j < 0x10000; j++) + uni2index[j] = -1; + index = 0; + for (;;) { + c = getc(stdin); + if (c == EOF) + break; + if (c == '#') { + do { c = getc(stdin); } while (!(c == EOF || c == '\n')); + continue; + } + ungetc(c,stdin); + if (scanf("%x",&j) != 1) + exit(1); + c = getc(stdin); + if (c != '\t') + exit(1); + uni2index[j] = index; + for (;;) { + int i; + if (scanf("%x",&i) != 1) + exit(1); + if (!(i >= 0x3000 && i < 0x3000+0x8000)) + exit(1); + variants[index++] = i-0x3000; + c = getc(stdin); + if (c != ' ') + break; + } + variants[index-1] |= 0x8000; /* end of list marker */ + if (c != '\n') + exit(1); + } + } + printf("static const unsigned short cjk_variants[%d] = {",index); + { + int i; + for (i = 0; i < index; i++) { + if ((i % 8) == 0) + printf("\n "); + printf(" 0x%04x,",variants[i]); + } + printf("\n};\n"); + } + printf("\n"); + printf("static const short cjk_variants_indx[0x5200] = {\n"); + { + int j; + for (j = 0x4e00; j < 0xa000; j++) { + if ((j % 0x100) == 0) + printf(" /* 0x%04x */\n", j); + if ((j % 8) == 0) + printf(" "); + printf(" %5d,",uni2index[j]); + if ((j % 8) == 7) + printf("\n"); + } + printf("};\n"); + } + printf("\n"); + + return 0; +} diff --git a/pool/shard004/C/0098500_prcm.c b/pool/shard004/C/0098500_prcm.c new file mode 100644 index 0000000000000000000000000000000000000000..c35e5cea9f8f076a993a09b8eae63897a89e0146 --- /dev/null +++ b/pool/shard004/C/0098500_prcm.c @@ -0,0 +1,161 @@ +/* + * linux/arch/arm/mach-omap2/prcm.c + * + * OMAP 24xx Power Reset and Clock Management (PRCM) functions + * + * Copyright (C) 2005 Nokia Corporation + * + * Written by Tony Lindgren + * + * Copyright (C) 2007 Texas Instruments, Inc. + * Rajendra Nayak + * + * Some pieces of code Copyright (C) 2005 Texas Instruments, Inc. + * Upgraded with OMAP4 support by Abhijit Pagare + * + * 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 "common.h" +#include +#include + +#include "clock.h" +#include "clock2xxx.h" +#include "cm2xxx_3xxx.h" +#include "prm2xxx_3xxx.h" +#include "prm44xx.h" +#include "prminst44xx.h" +#include "prm-regbits-24xx.h" +#include "prm-regbits-44xx.h" +#include "control.h" + +void __iomem *prm_base; +void __iomem *cm_base; +void __iomem *cm2_base; + +#define MAX_MODULE_ENABLE_WAIT 100000 + +u32 omap_prcm_get_reset_sources(void) +{ + /* XXX This presumably needs modification for 34XX */ + if (cpu_is_omap24xx() || cpu_is_omap34xx()) + return omap2_prm_read_mod_reg(WKUP_MOD, OMAP2_RM_RSTST) & 0x7f; + if (cpu_is_omap44xx()) + return omap2_prm_read_mod_reg(WKUP_MOD, OMAP4_RM_RSTST) & 0x7f; + + return 0; +} +EXPORT_SYMBOL(omap_prcm_get_reset_sources); + +/* Resets clock rates and reboots the system. Only called from system.h */ +static void omap_prcm_arch_reset(char mode, const char *cmd) +{ + s16 prcm_offs = 0; + + if (cpu_is_omap24xx()) { + omap2xxx_clk_prepare_for_reboot(); + + prcm_offs = WKUP_MOD; + } else if (cpu_is_omap34xx()) { + prcm_offs = OMAP3430_GR_MOD; + omap3_ctrl_write_boot_mode((cmd ? (u8)*cmd : 0)); + } else if (cpu_is_omap44xx()) { + omap4_prminst_global_warm_sw_reset(); /* never returns */ + } else { + WARN_ON(1); + } + + /* + * As per Errata i520, in some cases, user will not be able to + * access DDR memory after warm-reset. + * This situation occurs while the warm-reset happens during a read + * access to DDR memory. In that particular condition, DDR memory + * does not respond to a corrupted read command due to the warm + * reset occurrence but SDRC is waiting for read completion. + * SDRC is not sensitive to the warm reset, but the interconnect is + * reset on the fly, thus causing a misalignment between SDRC logic, + * interconnect logic and DDR memory state. + * WORKAROUND: + * Steps to perform before a Warm reset is trigged: + * 1. enable self-refresh on idle request + * 2. put SDRC in idle + * 3. wait until SDRC goes to idle + * 4. generate SW reset (Global SW reset) + * + * Steps to be performed after warm reset occurs (in bootloader): + * if HW warm reset is the source, apply below steps before any + * accesses to SDRAM: + * 1. Reset SMS and SDRC and wait till reset is complete + * 2. Re-initialize SMS, SDRC and memory + * + * NOTE: Above work around is required only if arch reset is implemented + * using Global SW reset(GLOBAL_SW_RST). DPLL3 reset does not need + * the WA since it resets SDRC as well as part of cold reset. + */ + + /* XXX should be moved to some OMAP2/3 specific code */ + omap2_prm_set_mod_reg_bits(OMAP_RST_DPLL3_MASK, prcm_offs, + OMAP2_RM_RSTCTRL); + omap2_prm_read_mod_reg(prcm_offs, OMAP2_RM_RSTCTRL); /* OCP barrier */ +} + +void (*arch_reset)(char, const char *) = omap_prcm_arch_reset; + +/** + * omap2_cm_wait_idlest - wait for IDLEST bit to indicate module readiness + * @reg: physical address of module IDLEST register + * @mask: value to mask against to determine if the module is active + * @idlest: idle state indicator (0 or 1) for the clock + * @name: name of the clock (for printk) + * + * Returns 1 if the module indicated readiness in time, or 0 if it + * failed to enable in roughly MAX_MODULE_ENABLE_WAIT microseconds. + * + * XXX This function is deprecated. It should be removed once the + * hwmod conversion is complete. + */ +int omap2_cm_wait_idlest(void __iomem *reg, u32 mask, u8 idlest, + const char *name) +{ + int i = 0; + int ena = 0; + + if (idlest) + ena = 0; + else + ena = mask; + + /* Wait for lock */ + omap_test_timeout(((__raw_readl(reg) & mask) == ena), + MAX_MODULE_ENABLE_WAIT, i); + + if (i < MAX_MODULE_ENABLE_WAIT) + pr_debug("cm: Module associated with clock %s ready after %d " + "loops\n", name, i); + else + pr_err("cm: Module associated with clock %s didn't enable in " + "%d tries\n", name, MAX_MODULE_ENABLE_WAIT); + + return (i < MAX_MODULE_ENABLE_WAIT) ? 1 : 0; +}; + +void __init omap2_set_globals_prcm(struct omap_globals *omap2_globals) +{ + if (omap2_globals->prm) + prm_base = omap2_globals->prm; + if (omap2_globals->cm) + cm_base = omap2_globals->cm; + if (omap2_globals->cm2) + cm2_base = omap2_globals->cm2; +} diff --git a/pool/shard004/C/0098505_mii-bitbang.c b/pool/shard004/C/0098505_mii-bitbang.c new file mode 100644 index 0000000000000000000000000000000000000000..67caaacd19ec4af121c9652d47fe94183eadc8b2 --- /dev/null +++ b/pool/shard004/C/0098505_mii-bitbang.c @@ -0,0 +1,235 @@ +/* + * Combined Ethernet driver for Motorola MPC8xx and MPC82xx. + * + * Copyright (c) 2003 Intracom S.A. + * by Pantelis Antoniou + * + * 2005 (c) MontaVista Software, Inc. + * Vitaly Bordug + * + * This file is licensed under the terms of the GNU General Public License + * version 2. This program is licensed "as is" without any warranty of any + * kind, whether express or implied. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "fs_enet.h" + +struct bb_info { + struct mdiobb_ctrl ctrl; + __be32 __iomem *dir; + __be32 __iomem *dat; + u32 mdio_msk; + u32 mdc_msk; +}; + +/* FIXME: If any other users of GPIO crop up, then these will have to + * have some sort of global synchronization to avoid races with other + * pins on the same port. The ideal solution would probably be to + * bind the ports to a GPIO driver, and have this be a client of it. + */ +static inline void bb_set(u32 __iomem *p, u32 m) +{ + out_be32(p, in_be32(p) | m); +} + +static inline void bb_clr(u32 __iomem *p, u32 m) +{ + out_be32(p, in_be32(p) & ~m); +} + +static inline int bb_read(u32 __iomem *p, u32 m) +{ + return (in_be32(p) & m) != 0; +} + +static inline void mdio_dir(struct mdiobb_ctrl *ctrl, int dir) +{ + struct bb_info *bitbang = container_of(ctrl, struct bb_info, ctrl); + + if (dir) + bb_set(bitbang->dir, bitbang->mdio_msk); + else + bb_clr(bitbang->dir, bitbang->mdio_msk); + + /* Read back to flush the write. */ + in_be32(bitbang->dir); +} + +static inline int mdio_read(struct mdiobb_ctrl *ctrl) +{ + struct bb_info *bitbang = container_of(ctrl, struct bb_info, ctrl); + return bb_read(bitbang->dat, bitbang->mdio_msk); +} + +static inline void mdio(struct mdiobb_ctrl *ctrl, int what) +{ + struct bb_info *bitbang = container_of(ctrl, struct bb_info, ctrl); + + if (what) + bb_set(bitbang->dat, bitbang->mdio_msk); + else + bb_clr(bitbang->dat, bitbang->mdio_msk); + + /* Read back to flush the write. */ + in_be32(bitbang->dat); +} + +static inline void mdc(struct mdiobb_ctrl *ctrl, int what) +{ + struct bb_info *bitbang = container_of(ctrl, struct bb_info, ctrl); + + if (what) + bb_set(bitbang->dat, bitbang->mdc_msk); + else + bb_clr(bitbang->dat, bitbang->mdc_msk); + + /* Read back to flush the write. */ + in_be32(bitbang->dat); +} + +static struct mdiobb_ops bb_ops = { + .owner = THIS_MODULE, + .set_mdc = mdc, + .set_mdio_dir = mdio_dir, + .set_mdio_data = mdio, + .get_mdio_data = mdio_read, +}; + +static int fs_mii_bitbang_init(struct mii_bus *bus, struct device_node *np) +{ + struct resource res; + const u32 *data; + int mdio_pin, mdc_pin, len; + struct bb_info *bitbang = bus->priv; + + int ret = of_address_to_resource(np, 0, &res); + if (ret) + return ret; + + if (resource_size(&res) <= 13) + return -ENODEV; + + /* This should really encode the pin number as well, but all + * we get is an int, and the odds of multiple bitbang mdio buses + * is low enough that it's not worth going too crazy. + */ + snprintf(bus->id, MII_BUS_ID_SIZE, "%x", res.start); + + data = of_get_property(np, "fsl,mdio-pin", &len); + if (!data || len != 4) + return -ENODEV; + mdio_pin = *data; + + data = of_get_property(np, "fsl,mdc-pin", &len); + if (!data || len != 4) + return -ENODEV; + mdc_pin = *data; + + bitbang->dir = ioremap(res.start, resource_size(&res)); + if (!bitbang->dir) + return -ENOMEM; + + bitbang->dat = bitbang->dir + 4; + bitbang->mdio_msk = 1 << (31 - mdio_pin); + bitbang->mdc_msk = 1 << (31 - mdc_pin); + + return 0; +} + +static int fs_enet_mdio_probe(struct platform_device *ofdev) +{ + struct mii_bus *new_bus; + struct bb_info *bitbang; + int ret = -ENOMEM; + + bitbang = kzalloc(sizeof(struct bb_info), GFP_KERNEL); + if (!bitbang) + goto out; + + bitbang->ctrl.ops = &bb_ops; + + new_bus = alloc_mdio_bitbang(&bitbang->ctrl); + if (!new_bus) + goto out_free_priv; + + new_bus->name = "CPM2 Bitbanged MII", + + ret = fs_mii_bitbang_init(new_bus, ofdev->dev.of_node); + if (ret) + goto out_free_bus; + + new_bus->phy_mask = ~0; + new_bus->irq = kmalloc(sizeof(int) * PHY_MAX_ADDR, GFP_KERNEL); + if (!new_bus->irq) { + ret = -ENOMEM; + goto out_unmap_regs; + } + + new_bus->parent = &ofdev->dev; + platform_set_drvdata(ofdev, new_bus); + + ret = of_mdiobus_register(new_bus, ofdev->dev.of_node); + if (ret) + goto out_free_irqs; + + return 0; + +out_free_irqs: + kfree(new_bus->irq); +out_unmap_regs: + iounmap(bitbang->dir); +out_free_bus: + free_mdio_bitbang(new_bus); +out_free_priv: + kfree(bitbang); +out: + return ret; +} + +static int fs_enet_mdio_remove(struct platform_device *ofdev) +{ + struct mii_bus *bus = platform_get_drvdata(ofdev); + struct bb_info *bitbang = bus->priv; + + mdiobus_unregister(bus); + kfree(bus->irq); + free_mdio_bitbang(bus); + iounmap(bitbang->dir); + kfree(bitbang); + + return 0; +} + +static struct of_device_id fs_enet_mdio_bb_match[] = { + { + .compatible = "fsl,cpm2-mdio-bitbang", + }, + {}, +}; +MODULE_DEVICE_TABLE(of, fs_enet_mdio_bb_match); + +static struct platform_driver fs_enet_bb_mdio_driver = { + .driver = { + .name = "fsl-bb-mdio", + .owner = THIS_MODULE, + .of_match_table = fs_enet_mdio_bb_match, + }, + .probe = fs_enet_mdio_probe, + .remove = fs_enet_mdio_remove, +}; + +module_platform_driver(fs_enet_bb_mdio_driver); diff --git a/pool/shard004/C/0098509_sctype.c b/pool/shard004/C/0098509_sctype.c new file mode 100644 index 0000000000000000000000000000000000000000..b10ae7648bd2881827146ab5e0008413b359f5db --- /dev/null +++ b/pool/shard004/C/0098509_sctype.c @@ -0,0 +1,346 @@ +/* sctype.f -- translated by f2c (version 19980913). + You must link the resulting object file with the libraries: + -lf2c -lm (in that order) +*/ + +#include "f2c.h" + +/* Table of constant values */ + +static integer c__0 = 0; +static integer c__1 = 1; + +/* $Procedure SCTYPE ( SCLK type ) */ +integer sctype_(integer *sc) +{ + /* Initialized data */ + + static logical first = TRUE_; + static logical nodata = TRUE_; + static integer oldsc = 0; + + /* System generated locals */ + integer ret_val, i__1; + + /* Builtin functions */ + /* Subroutine */ int s_copy(char *, char *, ftnlen, ftnlen); + + /* Local variables */ + static integer type__; + extern /* Subroutine */ int zzcvpool_(char *, integer *, logical *, + ftnlen), zzctruin_(integer *); + integer n; + extern /* Subroutine */ int scli01_(char *, integer *, integer *, integer + *, integer *, ftnlen), chkin_(char *, ftnlen), repmi_(char *, + char *, integer *, char *, ftnlen, ftnlen, ftnlen); + extern logical failed_(void); + char kvname[60]; + logical update; + extern /* Subroutine */ int chkout_(char *, ftnlen), suffix_(char *, + integer *, char *, ftnlen, ftnlen); + extern logical return_(void); + static integer usrctr[2]; + extern /* Subroutine */ int swpool_(char *, integer *, char *, ftnlen, + ftnlen); + +/* $ Abstract */ + +/* Return the spacecraft clock type for a specified spacecraft. */ + +/* $ 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 */ + +/* SCLK */ + +/* $ Keywords */ + +/* TIME */ + +/* $ Declarations */ +/* $ Abstract */ + +/* This include file defines the dimension of the counter */ +/* array used by various SPICE subsystems to uniquely identify */ +/* changes in their states. */ + +/* $ 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. */ + +/* $ Parameters */ + +/* CTRSIZ is the dimension of the counter array used by */ +/* various SPICE subsystems to uniquely identify */ +/* changes in their states. */ + +/* $ Author_and_Institution */ + +/* B.V. Semenov (JPL) */ + +/* $ Literature_References */ + +/* None. */ + +/* $ Version */ + +/* - SPICELIB Version 1.0.0, 29-JUL-2013 (BVS) */ + +/* -& */ + +/* End of include file. */ + +/* $ Brief_I/O */ + +/* Variable I/O Description */ +/* -------- --- -------------------------------------------------- */ +/* SC I NAIF spacecraft ID code. */ + +/* The function returns the spacecraft clock type associated with the */ +/* spacecraft specified by SC. */ + +/* $ Detailed_Input */ + +/* SC is a NAIF ID code for a spacecraft, whose */ +/* spacecraft clock `type' is desired. */ + +/* $ Detailed_Output */ + +/* The function returns the spacecraft clock type associated with the */ +/* spacecraft specified by SC. */ + +/* $ Parameters */ + +/* None. */ + +/* $ Exceptions */ + +/* 1) If the kernel variable that assigns a SCLK type to the */ +/* spacecraft specified by SC is not found in the kernel pool, */ +/* the error is diagnosed by routines called by this routine. */ +/* SCTYPE returns the value 0 in this case. */ + +/* $ Files */ + +/* None. */ + +/* $ Particulars */ + +/* The raison d'etre of this routine is that it consolidates the code */ +/* that maps spacecraft ID's to clock types. While any routine may */ +/* call SCTYPE, it is unlikely that there will be a need for */ +/* non-SPICELIB routines to call this routine directly. */ + +/* $ Examples */ + +/* 1) Find the SCLK type for Galileo. */ + +/* During program initialization, we load a SCLK kernel file */ +/* into the kernel pool. We will pretend that the name of */ +/* this file is GLLSCLK.KER. You must use the actual name of */ +/* an SCLK kernel that is accessible by your program to try */ +/* this example. */ + +/* C */ +/* C Load the SCLK kernel. */ +/* C */ +/* CALL FURNSH ( 'GLLSCLK.KER' ) */ +/* . */ +/* . */ +/* . */ +/* C */ +/* C Print out the clock type for Galileo. */ +/* C */ +/* TYPE = SCTYPE ( -77 ) */ + +/* PRINT *, 'Galileo clock type is ', TYPE */ + + +/* 2) Find the SCLK type for Mars Observer. */ + + +/* C */ +/* C Load the SCLK kernel. */ +/* C */ +/* CALL FURNSH ( 'MOSCLK.KER' ) */ +/* . */ +/* . */ +/* . */ +/* C */ +/* C Print out the clock type for Mars Observer. */ +/* C */ +/* TYPE = SCTYPE ( -94 ) */ + +/* PRINT *, 'Mars Observer clock type is ', TYPE */ + +/* $ Restrictions */ + +/* This routine assumes that an SCLK kernel appropriate to the */ +/* spacecraft specified by SC has been loaded into the kernel pool. */ + +/* $ Literature_References */ + +/* None. */ + +/* $ Author_and_Institution */ + +/* N.J. Bachman (JPL) */ +/* J.M. Lynch (JPL) */ +/* B.V. Semenov (JPL) */ + +/* $ Version */ + +/* - SPICELIB Version 1.3.0, 09-SEP-2013 (BVS) */ + +/* Updated to keep track of the POOL counter and call ZZCVPOOL. */ + +/* - SPICELIB Version 1.2.0, 05-MAR-2009 (NJB) */ + +/* Bug fix: this routine now keeps track of whether its */ +/* kernel pool look-up succeeded. If not, a kernel pool */ +/* lookup is attempted on the next call to this routine. */ + +/* - SPICELIB Version 1.1.1, 22-AUG-2006 (EDW) */ + +/* Replaced references to LDPOOL with references */ +/* to FURNSH. */ + +/* - SPICELIB Version 1.1.0, 22-MAR-1993 (JML) */ + +/* 1) The routine now uses the kernel pool watch capability. */ + +/* 2) The routine now returns a value of zero if RETURN is */ +/* true on entry. */ + +/* - SPICELIB Version 1.0.1, 10-MAR-1992 (WLT) */ + +/* Comment section for permuted index source lines was added */ +/* following the header. */ + +/* - SPICELIB Version 1.0.0, 04-SEP-1990 (NJB) */ + +/* -& */ +/* $ Index_Entries */ + +/* spacecraft_clock type */ + +/* -& */ + +/* SPICELIB functions */ + + +/* Local parameters */ + + +/* Local variables */ + + +/* Saved variables */ + + +/* Initial values */ + + +/* Standard SPICE error handling. */ + + if (return_()) { + ret_val = 0; + return ret_val; + } + chkin_("SCTYPE", (ftnlen)6); + +/* On the first pass through the subroutine, or if the spacecraft */ +/* ID code changes, set a watch on the SCLK kernel variable for */ +/* the current clock type. */ + + if (first || *sc != oldsc) { + +/* Construct the name of the kernel variable that is needed. */ + + s_copy(kvname, "SCLK_DATA_TYPE", (ftnlen)60, (ftnlen)14); + suffix_("_#", &c__0, kvname, (ftnlen)2, (ftnlen)60); + i__1 = -(*sc); + repmi_(kvname, "#", &i__1, kvname, (ftnlen)60, (ftnlen)1, (ftnlen)60); + +/* Set a watch on the kernel variable needed. */ + + swpool_("SCTYPE", &c__1, kvname, (ftnlen)6, (ftnlen)60); + +/* Keep track of the last spacecraft ID encountered. */ + + oldsc = *sc; + +/* Initialize the local POOL counter to user value. */ + + zzctruin_(usrctr); + first = FALSE_; + } + +/* If the kernel pool variable that this routine uses has */ +/* been updated, or if the spacecraft id code changes, look */ +/* up the new value from the kernel pool. */ + + zzcvpool_("SCTYPE", usrctr, &update, (ftnlen)6); + if (update || nodata) { + +/* Find the clock type for the specified mission. */ + + type__ = 0; + scli01_("SCLK_DATA_TYPE", sc, &c__1, &n, &type__, (ftnlen)14); + if (failed_()) { + nodata = TRUE_; + ret_val = 0; + chkout_("SCTYPE", (ftnlen)6); + return ret_val; + } + nodata = FALSE_; + } + ret_val = type__; + chkout_("SCTYPE", (ftnlen)6); + return ret_val; +} /* sctype_ */ + diff --git a/pool/shard004/C/0098510_kb-login.c b/pool/shard004/C/0098510_kb-login.c new file mode 100644 index 0000000000000000000000000000000000000000..5d38dc29c3b0f989c6bb5d6de568a3cf1017f32c --- /dev/null +++ b/pool/shard004/C/0098510_kb-login.c @@ -0,0 +1,181 @@ +#include +#include +#include +#include +#include +#include +#include +#include "bstrlib.h" +#include "json.h" +#include "iniparser.h" + +#include "kb-common.h" + +static void handle_setup(CURL *curl) +{ +// curl_easy_setopt(curl, CURLOPT_VERBOSE, 1); +} + +static size_t save_incoming_data(char *ptr, size_t size, size_t nmemb, void *userdata) +{ + bcatblk(userdata, ptr, size * nmemb); + return size * nmemb; +} + +void invalid() +{ + fprintf(stderr, "Invalid\n"); + exit(1); +} + + +void authenticate(bstring user, bstring pass) +{ + CURL *curl = curl_easy_init(); + + handle_setup(curl); + + bstring auth = bstrcpy(user); + bcatcstr(auth, ":"); + bconcat(auth, pass); + + curl_easy_setopt(curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC); + curl_easy_setopt(curl, CURLOPT_USERPWD, auth->data); + + bstring url = bfromcstr(GLOBUS_URL); + bcatcstr(url, AUTHORIZE_PATH); + bcatcstr(url, "?grant_type=client_credentials&client_id="); + bconcat(url, user); + + curl_easy_setopt(curl, CURLOPT_URL, url->data); + + bstring result = bfromcstr(""); + curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, save_incoming_data); + curl_easy_setopt(curl, CURLOPT_WRITEDATA, result); + + bstring error = bfromcstralloc(CURL_ERROR_SIZE, ""); + curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, bdata(error)); + CURLcode rc = curl_easy_perform(curl); + if (rc != CURLE_OK) + { + fprintf(stderr, "Error obtaining token: %s\n", bdata(error)); + exit(1); + } + + long response_code; + rc = curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &response_code); + if (rc != CURLE_OK) + { + fprintf(stderr, "Error obtaining response code\n"); + exit(1); + } + if (response_code == 403) + { + fprintf(stderr, "Permission denied.\n"); + exit(1); + } + if (response_code >= 300) + { + fprintf(stderr, "Invalid response code %ld from server\n", response_code); + exit(1); + } + + // printf("rc=%d '%s'\n", rc, result->data); + + curl_easy_cleanup(curl); + curl = 0; + bdestroy(error); + bdestroy(auth); + bdestroy(url); + + json_settings settings = { 0 } ; + char json_error[json_error_max + 1]; + json_value *ret = json_parse_ex(&settings, bdata(result), blength(result), json_error); + + if (ret->type != json_object) + invalid(); + int i; + char *token = 0; + char *username = 0; + for (i = 0; i < ret->u.object.length; i++) + { + if (strcmp(ret->u.object.values[i].name, "access_token") == 0) + { + json_value *t = ret->u.object.values[i].value; + token = t->u.string.ptr; + } + else if (strcmp(ret->u.object.values[i].name, "user_name") == 0) + { + json_value *t = ret->u.object.values[i].value; + username = t->u.string.ptr; + } + } + + update_config(token, username); + + json_value_free(ret); + bdestroy(result); +} + + +void usage() +{ + fprintf(stderr, "Usage: kb-login [--password password] username\n"); + exit(1); +} + + +int main(int argc, char **argv) +{ + bstring user = 0; + bstring pass = 0; + + static struct option long_options[] = { + { "password", 1, 0, 'p' }, + { "help", 1, 0, 'h' }, + { 0, 0, 0, 0 } + }; + + while (1) + { + int option_index = 0; + + int c = getopt_long (argc, argv, "p:h", + long_options, &option_index); + if (c == -1) + break; + + switch (c) + { + case 'p': + pass = bfromcstr(optarg); + break; + + case 'h': + usage(); + break; + } + } + + int nargs = argc - optind; + if (nargs != 1) + { + usage(); + } + + user = bfromcstr(argv[optind]); + + if (pass == 0) + { + char *p = getpass("Password: "); + pass = bfromcstr(p); + } + + authenticate(user, pass); + + bdestroy(user); + bdestroy(pass); + + return 0; +} + diff --git a/pool/shard004/C/0098511_main.c b/pool/shard004/C/0098511_main.c new file mode 100644 index 0000000000000000000000000000000000000000..a8291ad3d38096ad55b90edf683315aaa5fd7eb5 --- /dev/null +++ b/pool/shard004/C/0098511_main.c @@ -0,0 +1,21 @@ +#include +#include + +int main() +{ + int num, i, res; + res = 1; + + printf("Calcular el factorial de: "); + scanf("%d", &num); + + if (num==0) + res = 1; + else{ + for(i=1; i<=num; ++i){ + res = res * i; + } + } + printf("%d", res); + return 0; +} diff --git a/pool/shard004/C/0098517_player.c b/pool/shard004/C/0098517_player.c new file mode 100644 index 0000000000000000000000000000000000000000..6bc9a68bb3fb9479c944513390cc8c908948bb06 --- /dev/null +++ b/pool/shard004/C/0098517_player.c @@ -0,0 +1,99 @@ +/* Part of Lawyer Race + Functions to handle the player + Copyright (C) 2012 Andreas Andersson + + 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 "global.h" + +/* + * Read keybuffer and return direction, pause or exit. "curdir" is current + * direction, which is returned if none of the specified keys have been + * pressed + */ +dir_t getdir(dir_t curdir) { + extern int key_up, key_down, key_left, key_right; + extern int key_stop, key_pause, key_esc; + + int key = getch(); + + if (key == key_up) + return UP; + if (key == key_down) + return DOWN; + if (key == key_left) + return LEFT; + if (key == key_right) + return RIGHT; + if (key == key_stop) + return STOP; + if (key == key_pause) + return PAUSE; + if (key == key_esc) + return EXIT; + return curdir; /* No valid keys pressed, return current direction */ +} + +/* + * Draw player. "dir" is the direction in which player is moving. Return + * players new position. Delay control is in header. + */ +struct pos drawplayer(dir_t dir, struct pos curpos) { + extern int rows, cols; + extern double player_row_delay; + extern double player_col_delay; + static double lasttime; /* Used by setpos() for delay timer */ + static int lastrows, lastcols; /* used by drawfigure() */ + struct pos oldpos; + double rdelay = player_row_delay / rows; + double cdelay = player_col_delay / cols; + + /* Set new position and draw player */ + oldpos = curpos; + if (setpos(dir, &curpos, &rdelay, &cdelay, &lasttime) || dir == INIT) { + curpos = drawfigure(curpos, PLAYER, oldpos, BACKGROUND, + lastrows, lastcols); + lastrows = rows, lastcols = cols; /* Remember screen size */ + } + /* Go home */ + return curpos; +} + +/* + * #include + * #include + * Print score and level at last row. Erase old status row first if + * screen size changed + */ +void printstatus (int score) { + extern int rows; + extern int cols; + extern int level; + static int oldscrrow; + int clrcol; + char *scoref = "Score: %d"; + char *levelf = "Level: %d"; + + /* Erase old status row if screensize changed */ + if (oldscrrow != rows) + for (clrcol = 0; clrcol < cols; clrcol++) + mvaddch(oldscrrow, clrcol, BACKGROUND); + /* Print score and level */ + mvprintw(rows, 0, scoref, score); + mvprintw(rows, cols - strlen(levelf), levelf, level); + /* Save current status row position */ + oldscrrow = rows; +} diff --git a/pool/shard004/C/0098526_ext_f64_1.c b/pool/shard004/C/0098526_ext_f64_1.c new file mode 100644 index 0000000000000000000000000000000000000000..42389aaaa76b6af2d4c730b7b78ea055163bb44d --- /dev/null +++ b/pool/shard004/C/0098526_ext_f64_1.c @@ -0,0 +1,25 @@ +/* Test the `vextf64' AArch64 SIMD intrinsic. */ + +/* { dg-do run } */ +/* { dg-options "-save-temps -O3 -fno-inline" } */ + +#include "arm_neon.h" + +extern void abort (void); + +int +main (int argc, char **argv) +{ + int i, off; + float64x1_t in1 = {0}; + float64x1_t in2 = {1}; + float64x1_t actual = vext_f64 (in1, in2, 0); + if (actual[0] != in1[0]) + abort (); + + return 0; +} + +/* Do not scan-assembler. An EXT instruction could be emitted, but would merely + return its first argument, so it is legitimate to optimize it out. */ +/* { dg-final { cleanup-saved-temps } } */ diff --git a/pool/shard004/C/0098541_videostream_jpg.c b/pool/shard004/C/0098541_videostream_jpg.c new file mode 100644 index 0000000000000000000000000000000000000000..29362e3382b082fc8d08b2c98987adca86bb3a01 --- /dev/null +++ b/pool/shard004/C/0098541_videostream_jpg.c @@ -0,0 +1,238 @@ +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +#include +#include +#include +#include +#include + +#include "jpeglib.h" + +int shooting(char * jpegdata, int size, unsigned int *fb_mem) +{ + // 声明解压缩结构体,以及错误管理结构体 + struct jpeg_decompress_struct cinfo; + struct jpeg_error_mgr jerr; + + // 使用缺省的出错处理来初始化解压缩结构体 + cinfo.err = jpeg_std_error(&jerr); + jpeg_create_decompress(&cinfo); + + // 配置该cinfo,使其从jpg_buffer中读取jpg_size个字节 + // 这些数据必须是完整的JPEG数据 + jpeg_mem_src(&cinfo, jpegdata, size); + + // 读取JPEG文件的头 + jpeg_read_header(&cinfo, true); + + // 开始解压jpeg数据 + jpeg_start_decompress(&cinfo); + + int width = cinfo.output_width; + int height = cinfo.output_height; + int pixel_size = cinfo.output_components; + int row_stride = width * pixel_size; + + // 定义一个存放一行数据的缓冲区 + char * buffer; + buffer = malloc(row_stride); + + // 以行为单位,将JPEG数据解压出来之后,按照RGBA方式填入fb_mem + int red = 0; + int green= 1; + int blue = 2; + while (cinfo.output_scanline < cinfo.output_height) + { + jpeg_read_scanlines(&cinfo, (JSAMPARRAY)&buffer, 1); + + // 将buffer中的24bit的图像数据写入32bit的fb_mem + int i=0, x; + for(x=0; xfmt.pix.width); + printf("camera height: %d \n", fmt->fmt.pix.height); + + switch(fmt->fmt.pix.pixelformat) + { + case V4L2_PIX_FMT_JPEG: + printf("camera pixelformat: V4L2_PIX_FMT_JPEG\n"); + break; + case V4L2_PIX_FMT_YUYV: + printf("camera pixelformat: V4L2_PIX_FMT_YUYV\n"); + } +} + +void usage(int argc, char const *argv[]) +{ + if(argc != 2) + { + printf("Usage: %s \n", + argv[0]); + exit(0); + } +} + +int main(int argc, char const *argv[]) +{ + usage(argc, argv); + // pthread_t tid; + // pthread_create(&tid, NULL, store_video, NULL); + + // 打开LCD设备 + int lcd = open("/dev/fb0", O_RDWR); + + // 获取LCD显示器的设备参数 + struct fb_var_screeninfo lcdinfo; + ioctl(lcd, FBIOGET_VSCREENINFO, &lcdinfo); + + // 申请一块适当跟LCD尺寸一样大小的显存 + unsigned int *fb_mem = mmap(NULL, lcdinfo.xres * lcdinfo.yres * lcdinfo.bits_per_pixel/8, + PROT_READ | PROT_WRITE, MAP_SHARED, lcd, 0); + + // 将屏幕刷成黑色 + unsigned long black = 0x0; + unsigned int i; + for(i=0; iindex = 0; + a->type = V4L2_BUF_TYPE_VIDEO_CAPTURE; + + int ret; + while((ret=ioctl(cam_fd, VIDIOC_ENUM_FMT, a)) == 0) + { + a->index++; + printf("pixelformat: \"%c%c%c%c\"\n", + (a->pixelformat >> 0) & 0XFF, + (a->pixelformat >> 8) & 0XFF, + (a->pixelformat >>16) & 0XFF, + (a->pixelformat >>24) & 0XFF); + + printf("description: %s\n", a->description); + } + + // 获取摄像头设备的功能参数(这一步可以不要) + struct v4l2_capability cap; + ioctl(cam_fd, VIDIOC_QUERYCAP, &cap); + + // 获取摄像头当前的采集格式 + struct v4l2_format *fmt = calloc(1, sizeof(*fmt)); + fmt->type = V4L2_BUF_TYPE_VIDEO_CAPTURE; + + ioctl(cam_fd, VIDIOC_G_FMT, fmt); + show_camfmt(fmt); + + // 配置摄像头的采集格式 + bzero(fmt, sizeof(*fmt)); + fmt->type = V4L2_BUF_TYPE_VIDEO_CAPTURE; + fmt->fmt.pix.width = lcdinfo.xres; + fmt->fmt.pix.height = lcdinfo.yres; + fmt->fmt.pix.pixelformat = V4L2_PIX_FMT_JPEG; + fmt->fmt.pix.field = V4L2_FIELD_INTERLACED; + ioctl(cam_fd, VIDIOC_S_FMT, fmt); + + // 再次获取摄像头当前的采集格式 + bzero(fmt, sizeof(*fmt)); + fmt->type = V4L2_BUF_TYPE_VIDEO_CAPTURE; + ioctl (cam_fd, VIDIOC_G_FMT, fmt); + + if(fmt->fmt.pix.pixelformat != V4L2_PIX_FMT_JPEG) + { + printf("\nthe pixel format is NOT JPEG.\n\n"); + exit(1); + } + + // 设置即将要申请的摄像头缓存的参数 + int nbuf = 3; + + struct v4l2_requestbuffers reqbuf; + bzero(&reqbuf, sizeof (reqbuf)); + reqbuf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE; + reqbuf.memory = V4L2_MEMORY_MMAP; + reqbuf.count = nbuf; + + // 使用该参数reqbuf来申请缓存 + ioctl(cam_fd, VIDIOC_REQBUFS, &reqbuf); + + // 根据刚刚设置的reqbuf.count的值,来定义相应数量的struct v4l2_buffer + // 每一个struct v4l2_buffer对应内核摄像头驱动中的一个缓存 + struct v4l2_buffer buffer[nbuf]; + int length[nbuf]; + unsigned char *start[nbuf]; + + for(i=0; i +#include + +typedef struct test_s +{ + uintmax_t numer; + uintmax_t denom; + umaxdiv_t div; + int error; +} test_t; + +int ut_umaxdiv_interface(int N) +{ + int i; + umaxdiv_t ret; + int err; + test_t tdat[2] = { {N, 0, {0, 0}, EINVAL}, + {10, 5, {2, 0}, 0} }; + + errno = 0; + i = 0; + err = 0xFF; + while (i < 2) + { + ret = umaxdiv((tdat[i]).numer, (tdat[i]).denom); + if (errno != (tdat[i]).error) + return (err); + err--; + if ((tdat[i]).div.quot != ret.quot) + return (err); + err--; + if ((tdat[i]).div.rem != ret.rem) + return (err); + i++; + err--; + } + return (0); +} + +int ut_umaxdiv_validity(int N) +{ + int i; + umaxdiv_t ret; + int err; + test_t tdat[7] = { {10, 3, {3, 1}, 0}, + {10, 4, {2, 2}, 0}, + {10, 5, {2, 0}, 0}, + {N, 2, {(N / 2), (N % 2)}, 0}, + {N, 3, {(N / 3), (N % 3)}, 0}, + {N, 5, {(N / 5), (N % 5)}, 0}, + {N, 7, {(N / 7), (N % 7)}, 0} }; + + errno = 0; + i = 0; + err = 0xFF; + while (i < 7) + { + ret = umaxdiv((tdat[i]).numer, (tdat[i]).denom); + if (errno) + return (err); + err--; + if ((tdat[i]).div.quot != ret.quot) + return (err); + err--; + if ((tdat[i]).div.rem != ret.rem) + return (err); + i++; + err--; + } + return (0); +} + +int ut_umaxdiv_memchk(int N) +{ + uintmax_t i; + umaxdiv_t ret; + + errno = 0; + i = 1; + while (i < (uintmax_t)(N)) + { + ret = umaxdiv(N, i++); + if (!(ret.quot) && !(ret.rem)) + return (i); + } + return (0); +} + +int ut_umaxdiv_timeout(int N) +{ + return (ut_umaxdiv_memchk(N)); +} diff --git a/pool/shard004/C/0098546_hello.c b/pool/shard004/C/0098546_hello.c new file mode 100644 index 0000000000000000000000000000000000000000..2485ff554608e3c215024aad52647dec77fa4243 --- /dev/null +++ b/pool/shard004/C/0098546_hello.c @@ -0,0 +1,49 @@ +static const unsigned rows = 24; +static const unsigned cols = 80; +static const char attr = 7; + +static char *video_mem = (char *)0xb8000; +static unsigned row = 0; +static unsigned col = 0; + +static void newline(void) +{ + unsigned i, off; + + row = (row + 1) % rows; + col = 0; + for (i = 0, off = (col + row * cols) * 2; i != cols; ++i) { + *(video_mem + off++) = ' '; + *(video_mem + off++) = attr; + } +} + +static void myputchar(int c) +{ + const unsigned off = (col + row * cols) * 2; + + if (c == '\n') { + newline(); + return; + } + + *(video_mem + off) = c; + *(video_mem + off + 1) = attr; + + if (++col == cols) + newline(); +} + +static void myputs(const char *str) +{ + while (*str) + myputchar(*str++); +} + +void main() +{ + static const char hello[] = "Hello, World!\n"; + + myputs(hello); + while (1); +} diff --git a/pool/shard004/C/0098548_pi.c b/pool/shard004/C/0098548_pi.c new file mode 100644 index 0000000000000000000000000000000000000000..41639315b12f31dedfd115872b1063ba7c470890 --- /dev/null +++ b/pool/shard004/C/0098548_pi.c @@ -0,0 +1,100 @@ +#include +#include + +#include "timer.h" + +double pi_leibniz (int n); +double pi_bbp (int n); +int adjust_rep_count (int count, double time, double tmin, double tmax); + +int main (void) +{ + + int i; + double abserr; + double tol = 1.0E-6; + + i = 1; + do + { + double pi = pi_leibniz (i); + + abserr = fabs (pi - M_PI); + printf ("%8d %20.15f %20.15f \n", i, pi, abserr); + i *= 2; + + } + while (abserr > tol); + int ileibniz = i / 2; + + //switch to calculating pi with bbp series + //i = 5; + //double pi = pi_bbp (i); + + i = 1; + do + { + + double pi = pi_bbp (i); + + abserr = fabs (pi - M_PI); + printf ("%8d %20.15f %20.15f \n", i, pi, abserr); + i *= 2; + } + while (abserr > tol); + int ibbp = i / 2; + + double tmin = 1., tmax = 2.; + int count = 1000; + double time, time1; + + do + { + timer_start (); + + for (i = 0; i < count; i++) + { + double pi = pi_bbp (ibbp); + } + + time = timer_stop (); + time1 = time / count; + printf (" %10.2f usec %10.6f sec %10d\n", time1 * 1.e6, time, count); + /* + * adjust count such that cpu time is between + * tmin and tmax + */ + count = adjust_rep_count (count, time, tmin, tmax); + } + while ((time > tmax) || (time < tmin)); + time1 = time / count; + printf (" %10.2f usec %10.6f sec %10d\n", time1 * 1.e6, time, count); + + double tmin1 = 1., tmax1 = 2.; + int count1 = 1000; + double time2, time3; + + do + { + timer_start (); + + for (i = 0; i < count1; i++) + { + double pi = pi_leibniz (ileibniz); + } + + time2 = timer_stop (); + time3 = time2 / count1; + printf (" %10.2f usec %10.6f sec %10d\n", time3 * 1.e6, time, count1); + /* + * adjust count1 such that cpu time is between + * tmin1 and tmax1 + */ + count1 = adjust_rep_count (count1, time2, tmin1, tmax1); + } + while ((time2 > tmax1) || (time2 < tmin1)); + time3 = time2 / count1; + printf (" %10.2f usec %10.6f sec %10d\n", time3 * 1.e6, time2, count1); + + return 0; +} diff --git a/pool/shard004/C/0098549_main1.c b/pool/shard004/C/0098549_main1.c new file mode 100644 index 0000000000000000000000000000000000000000..09ba4681dd5357b3c0fe86a62f64e4faa14a9821 --- /dev/null +++ b/pool/shard004/C/0098549_main1.c @@ -0,0 +1,25 @@ +// Program to inspect the 32 bits of unsigned int number + +#include + +int main() { + int i; + unsigned int x, y, m; + + // read input + scanf("%u", &x); + // set mask to 00 ... 01 + m = ~0 << 1; + m = ~m; + + // loop over all 32 bits from lsb to msb + for(i = 0; i < 32; i++) { + // zero out all bits but for lsb + y = x & m; + printf("%u", y); + // right shift to inspect the next significant bit + x = x >> 1; + } + printf("\n"); +} + diff --git a/pool/shard004/C/0098587_ConfWind.c b/pool/shard004/C/0098587_ConfWind.c new file mode 100644 index 0000000000000000000000000000000000000000..eefce4dd570fe046b5bf82bdc89657a151c77aad --- /dev/null +++ b/pool/shard004/C/0098587_ConfWind.c @@ -0,0 +1,58 @@ +/* + +Copyright 1986, 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 "Xlibint.h" + +int +XMoveResizeWindow( + register Display *dpy, + Window w, + int x, + int y, + unsigned int width, + unsigned int height) +{ + register xConfigureWindowReq *req; + + LockDisplay(dpy); + GetReqExtra(ConfigureWindow, 16, req); + req->window = w; + req->mask = CWX | CWY | CWWidth | CWHeight; + { + register CARD32 *valuePtr = + (CARD32 *) NEXTPTR(req,xConfigureWindowReq); + *valuePtr++ = x; + *valuePtr++ = y; + *valuePtr++ = width; + *valuePtr = height; + } + UnlockDisplay(dpy); + SyncHandle(); + return 1; +} diff --git a/pool/shard004/C/0098588_fishhook.c b/pool/shard004/C/0098588_fishhook.c new file mode 100644 index 0000000000000000000000000000000000000000..0c2859949078d7d6c9f545f974ca440ea3f33aba --- /dev/null +++ b/pool/shard004/C/0098588_fishhook.c @@ -0,0 +1,196 @@ +// Copyright (c) 2013, Facebook, 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 Facebook 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. + +#import "fishhook.h" + +#import +#import +#import +#import +#import +#import +#import + +#ifdef __LP64__ +typedef struct mach_header_64 mach_header_t; +typedef struct segment_command_64 segment_command_t; +typedef struct section_64 section_t; +typedef struct nlist_64 nlist_t; +#define LC_SEGMENT_ARCH_DEPENDENT LC_SEGMENT_64 +#else +typedef struct mach_header mach_header_t; +typedef struct segment_command segment_command_t; +typedef struct section section_t; +typedef struct nlist nlist_t; +#define LC_SEGMENT_ARCH_DEPENDENT LC_SEGMENT +#endif + +struct rebindings_entry { + struct rebinding *rebindings; + size_t rebindings_nel; + struct rebindings_entry *next; +}; + +static struct rebindings_entry *_rebindings_head; + +static int prepend_rebindings(struct rebindings_entry **rebindings_head, + struct rebinding rebindings[], + size_t nel) { + struct rebindings_entry *new_entry = malloc(sizeof(struct rebindings_entry)); + if (!new_entry) { + return -1; + } + new_entry->rebindings = malloc(sizeof(struct rebinding) * nel); + if (!new_entry->rebindings) { + free(new_entry); + return -1; + } + memcpy(new_entry->rebindings, rebindings, sizeof(struct rebinding) * nel); + new_entry->rebindings_nel = nel; + new_entry->next = *rebindings_head; + *rebindings_head = new_entry; + return 0; +} + +static void perform_rebinding_with_section(struct rebindings_entry *rebindings, + section_t *section, + intptr_t slide, + nlist_t *symtab, + char *strtab, + uint32_t *indirect_symtab) { + uint32_t *indirect_symbol_indices = indirect_symtab + section->reserved1; + void **indirect_symbol_bindings = (void **)((uintptr_t)slide + section->addr); + for (uint i = 0; i < section->size / sizeof(void *); i++) { + uint32_t symtab_index = indirect_symbol_indices[i]; + if (symtab_index == INDIRECT_SYMBOL_ABS || symtab_index == INDIRECT_SYMBOL_LOCAL || + symtab_index == (INDIRECT_SYMBOL_LOCAL | INDIRECT_SYMBOL_ABS)) { + continue; + } + uint32_t strtab_offset = symtab[symtab_index].n_un.n_strx; + char *symbol_name = strtab + strtab_offset; + struct rebindings_entry *cur = rebindings; + while (cur) { + for (uint j = 0; j < cur->rebindings_nel; j++) { + if (strlen(symbol_name) > 1 && + strcmp(&symbol_name[1], cur->rebindings[j].name) == 0) { + indirect_symbol_bindings[i] = cur->rebindings[j].replacement; + goto symbol_loop; + } + } + cur = cur->next; + } + symbol_loop:; + } +} + +static void rebind_symbols_for_image(struct rebindings_entry *rebindings, + const struct mach_header *header, + intptr_t slide) { + Dl_info info; + if (dladdr(header, &info) == 0) { + return; + } + uintptr_t cur = (uintptr_t)header + sizeof(mach_header_t); + segment_command_t *cur_seg_cmd; + segment_command_t *linkedit_segment = NULL; + section_t *lazy_symbols = NULL; + section_t *non_lazy_symbols = NULL; + struct symtab_command* symtab_cmd = NULL; + struct dysymtab_command* dysymtab_cmd = NULL; + for (uint i = 0; i < header->ncmds; i++, cur += cur_seg_cmd->cmdsize) { + cur_seg_cmd = (segment_command_t *)cur; + if (cur_seg_cmd->cmd == LC_SEGMENT_ARCH_DEPENDENT) { + if (strcmp(cur_seg_cmd->segname, SEG_LINKEDIT) == 0) { + linkedit_segment = cur_seg_cmd; + continue; + } + if (strcmp(cur_seg_cmd->segname, SEG_DATA) != 0) { + continue; + } + for (uint j = 0; j < cur_seg_cmd->nsects; j++) { + section_t *sect = + (section_t *)(cur + sizeof(segment_command_t)) + j; + if ((sect->flags & SECTION_TYPE) == S_LAZY_SYMBOL_POINTERS) { + lazy_symbols = sect; + } + if ((sect->flags & SECTION_TYPE) == S_NON_LAZY_SYMBOL_POINTERS) { + non_lazy_symbols = sect; + } + } + } else if (cur_seg_cmd->cmd == LC_SYMTAB) { + symtab_cmd = (struct symtab_command*)cur_seg_cmd; + } else if (cur_seg_cmd->cmd == LC_DYSYMTAB) { + dysymtab_cmd = (struct dysymtab_command*)cur_seg_cmd; + } + } + if (!symtab_cmd || !dysymtab_cmd || !linkedit_segment || + !dysymtab_cmd->nindirectsyms) { + return; + } + // Find base symbol/string table addresses + uintptr_t linkedit_base = (uintptr_t)slide + linkedit_segment->vmaddr - linkedit_segment->fileoff; + nlist_t *symtab = (nlist_t *)(linkedit_base + symtab_cmd->symoff); + char *strtab = (char *)(linkedit_base + symtab_cmd->stroff); + // Get indirect symbol table (array of uint32_t indices into symbol table) + uint32_t *indirect_symtab = (uint32_t *)(linkedit_base + dysymtab_cmd->indirectsymoff); + if (lazy_symbols) { + perform_rebinding_with_section(rebindings, lazy_symbols, slide, symtab, strtab, indirect_symtab); + } + if (non_lazy_symbols) { + perform_rebinding_with_section(rebindings, non_lazy_symbols, slide, symtab, strtab, indirect_symtab); + } +} + +static void _rebind_symbols_for_image(const struct mach_header *header, + intptr_t slide) { + rebind_symbols_for_image(_rebindings_head, header, slide); +} + +int rebind_symbols_image(void *header, + intptr_t slide, + struct rebinding rebindings[], + size_t rebindings_nel) { + struct rebindings_entry *rebindings_head = NULL; + int retval = prepend_rebindings(&rebindings_head, rebindings, rebindings_nel); + rebind_symbols_for_image(rebindings_head, header, slide); + free(rebindings_head); + return retval; +} + +int rebind_symbols(struct rebinding rebindings[], size_t rebindings_nel) { + int retval = prepend_rebindings(&_rebindings_head, rebindings, rebindings_nel); + if (retval < 0) { + return retval; + } + // If this was the first call, register callback for image additions (which is also invoked for + // existing images, otherwise, just run on existing images + if (!_rebindings_head->next) { + _dyld_register_func_for_add_image(_rebind_symbols_for_image); + } else { + uint32_t c = _dyld_image_count(); + for (uint32_t i = 0; i < c; i++) { + _rebind_symbols_for_image(_dyld_get_image_header(i), _dyld_get_image_vmaddr_slide(i)); + } + } + return retval; +} \ No newline at end of file diff --git a/pool/shard004/C/0098589_prof.c b/pool/shard004/C/0098589_prof.c new file mode 100644 index 0000000000000000000000000000000000000000..4581aaf36e3d7e288c424d54d11bf63c9e9de798 --- /dev/null +++ b/pool/shard004/C/0098589_prof.c @@ -0,0 +1,96 @@ +/* + * libcaca Colour ASCII-Art library + * Copyright (c) 2009-2012 Sam Hocevar + * All Rights Reserved + * + * This library is free software. It comes without any warranty, to + * the extent permitted by applicable law. You can redistribute it + * and/or modify it under the terms of the Do What the Fuck You Want + * to Public License, Version 2, as published by Sam Hocevar. See + * http://www.wtfpl.net/ for more details. + */ + +/* + * This file contains profiling functions. They are not supposed to be + * built with release versions. + */ + +#include "config.h" + +#if !defined(__KERNEL__) +# include +# include +# include +#endif + +#include "caca.h" +#include "caca_internals.h" + +#if defined PROF +static struct caca_stat **stats = NULL; +static int nstats = 0; + +void _caca_dump_stats(void) +{ + int i, j; + + fprintf(stderr, "** libcaca profiling stats **\n"); + + for (i = 0; i < nstats; i++) + { + int64_t total = 0; + + for (j = 0; j < STAT_VALUES; j++) + total += stats[i]->itable[j]; + + fprintf(stderr, " %s: last %i sliding mean %i smoothed mean %i\n", + stats[i]->name, stats[i]->itable[0], + (int)((total + STAT_VALUES / 2) / STAT_VALUES), + (int)(stats[i]->imean / 64)); + } + + fprintf(stderr, "** %i counters dumped **\n", nstats); +} + +void _caca_init_stat(struct caca_stat *s, const char *format, ...) +{ + int i; + + s->name = malloc(128 * sizeof(char)); + va_list args; + va_start(args, format); + vsnprintf(s->name, 128, format, args); + s->name[127] = '\0'; + va_end(args); + + nstats++; + stats = realloc(stats, nstats * sizeof(struct caca_stat *)); + stats[nstats - 1] = s; + + for (i = 0; i < STAT_VALUES; i++) + s->itable[i] = 0; + s->imean = 0; +} + +void _caca_fini_stat(struct caca_stat *s) +{ + int i, j; + + for (i = 0; i < nstats; i++) + { + if (stats[i] == s) + { + free(stats[i]->name); + + for (j = i + 1; j < nstats; j++) + stats[j - 1] = stats[j]; + nstats--; + stats = realloc(stats, nstats * sizeof(struct caca_stats *)); + + return; + } + } +} + +#endif + diff --git a/pool/shard004/C/0098593_user_modalsset.c b/pool/shard004/C/0098593_user_modalsset.c new file mode 100644 index 0000000000000000000000000000000000000000..c6958a9012ef7799806b108aecf67732cc9c9b3f --- /dev/null +++ b/pool/shard004/C/0098593_user_modalsset.c @@ -0,0 +1,142 @@ +/* + * Unix SMB/CIFS implementation. + * NetUserModalsSet query + * Copyright (C) Guenther Deschner 2008 + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, see . + */ + +#include +#include +#include +#include +#include + +#include + +#include "common.h" + +int main(int argc, const char **argv) +{ + NET_API_STATUS status; + struct libnetapi_ctx *ctx = NULL; + const char *hostname = NULL; + uint8_t *buffer = NULL; + uint32_t level = 0; + uint32_t value = 0; + uint32_t parm_err = 0; + + struct USER_MODALS_INFO_0 u0; + struct USER_MODALS_INFO_1 u1; + struct USER_MODALS_INFO_2 u2; + struct USER_MODALS_INFO_3 u3; + struct USER_MODALS_INFO_1001 u1001; + struct USER_MODALS_INFO_1002 u1002; + struct USER_MODALS_INFO_1003 u1003; + struct USER_MODALS_INFO_1004 u1004; + struct USER_MODALS_INFO_1005 u1005; + struct USER_MODALS_INFO_1006 u1006; + struct USER_MODALS_INFO_1007 u1007; + + poptContext pc; + int opt; + + struct poptOption long_options[] = { + POPT_AUTOHELP + POPT_COMMON_LIBNETAPI_EXAMPLES + POPT_TABLEEND + }; + + status = libnetapi_init(&ctx); + if (status != 0) { + return status; + } + + pc = poptGetContext("user_modalsset", argc, argv, long_options, 0); + + poptSetOtherOptionHelp(pc, "hostname level value"); + while((opt = poptGetNextOpt(pc)) != -1) { + } + + if (!poptPeekArg(pc)) { + poptPrintHelp(pc, stderr, 0); + goto out; + } + hostname = poptGetArg(pc); + + if (poptPeekArg(pc)) { + level = atoi(poptGetArg(pc)); + } + + if (poptPeekArg(pc)) { + value = atoi(poptGetArg(pc)); + } + + switch (level) { + case 0: + u0.usrmod0_min_passwd_len = 0; + u0.usrmod0_max_passwd_age = (86400 * 30); /* once a month */ + u0.usrmod0_min_passwd_age = 0; + u0.usrmod0_force_logoff = TIMEQ_FOREVER; + u0.usrmod0_password_hist_len = 0; + buffer = (uint8_t *)&u0; + break; + case 1: + case 2: + case 3: + break; + case 1001: + u1001.usrmod1001_min_passwd_len = 0; + buffer = (uint8_t *)&u1001; + break; + case 1002: + u1002.usrmod1002_max_passwd_age = 0; + buffer = (uint8_t *)&u1002; + break; + case 1003: + u1003.usrmod1003_min_passwd_age = (86400 * 30); /* once a month */ + buffer = (uint8_t *)&u1003; + break; + case 1004: + u1004.usrmod1004_force_logoff = TIMEQ_FOREVER; + buffer = (uint8_t *)&u1004; + break; + case 1005: + u1005.usrmod1005_password_hist_len = 0; + buffer = (uint8_t *)&u1005; + break; + case 1006: + case 1007: + default: + break; + } + + /* NetUserModalsSet */ + + status = NetUserModalsSet(hostname, + level, + buffer, + &parm_err); + if (status != 0) { + printf("NetUserModalsSet failed with: %s\n", + libnetapi_get_error_string(ctx, status)); + goto out; + } + + out: + libnetapi_free(ctx); + poptFreeContext(pc); + + return status; +} diff --git a/pool/shard004/C/0098605_i2c-cros-ec-tunnel.c b/pool/shard004/C/0098605_i2c-cros-ec-tunnel.c new file mode 100644 index 0000000000000000000000000000000000000000..958161c71985d99ba021fa1aef9c8cb8e9f9207c --- /dev/null +++ b/pool/shard004/C/0098605_i2c-cros-ec-tunnel.c @@ -0,0 +1,320 @@ +// SPDX-License-Identifier: GPL-2.0+ +// Expose an I2C passthrough to the ChromeOS EC. +// +// Copyright (C) 2013 Google, Inc. + +#include +#include +#include +#include +#include +#include +#include + +#define I2C_MAX_RETRIES 3 + +/** + * struct ec_i2c_device - Driver data for I2C tunnel + * + * @dev: Device node + * @adap: I2C adapter + * @ec: Pointer to EC device + * @remote_bus: The EC bus number we tunnel to on the other side. + * @request_buf: Buffer for transmitting data; we expect most transfers to fit. + * @response_buf: Buffer for receiving data; we expect most transfers to fit. + */ + +struct ec_i2c_device { + struct device *dev; + struct i2c_adapter adap; + struct cros_ec_device *ec; + + u16 remote_bus; + + u8 request_buf[256]; + u8 response_buf[256]; +}; + +/** + * ec_i2c_count_message - Count bytes needed for ec_i2c_construct_message + * + * @i2c_msgs: The i2c messages to read + * @num: The number of i2c messages. + * + * Returns the number of bytes the messages will take up. + */ +static int ec_i2c_count_message(const struct i2c_msg i2c_msgs[], int num) +{ + int i; + int size; + + size = sizeof(struct ec_params_i2c_passthru); + size += num * sizeof(struct ec_params_i2c_passthru_msg); + for (i = 0; i < num; i++) + if (!(i2c_msgs[i].flags & I2C_M_RD)) + size += i2c_msgs[i].len; + + return size; +} + +/** + * ec_i2c_construct_message - construct a message to go to the EC + * + * This function effectively stuffs the standard i2c_msg format of Linux into + * a format that the EC understands. + * + * @buf: The buffer to fill. We assume that the buffer is big enough. + * @i2c_msgs: The i2c messages to read. + * @num: The number of i2c messages. + * @bus_num: The remote bus number we want to talk to. + * + * Returns 0 or a negative error number. + */ +static int ec_i2c_construct_message(u8 *buf, const struct i2c_msg i2c_msgs[], + int num, u16 bus_num) +{ + struct ec_params_i2c_passthru *params; + u8 *out_data; + int i; + + out_data = buf + sizeof(struct ec_params_i2c_passthru) + + num * sizeof(struct ec_params_i2c_passthru_msg); + + params = (struct ec_params_i2c_passthru *)buf; + params->port = bus_num; + params->num_msgs = num; + for (i = 0; i < num; i++) { + const struct i2c_msg *i2c_msg = &i2c_msgs[i]; + struct ec_params_i2c_passthru_msg *msg = ¶ms->msg[i]; + + msg->len = i2c_msg->len; + msg->addr_flags = i2c_msg->addr; + + if (i2c_msg->flags & I2C_M_TEN) + return -EINVAL; + + if (i2c_msg->flags & I2C_M_RD) { + msg->addr_flags |= EC_I2C_FLAG_READ; + } else { + memcpy(out_data, i2c_msg->buf, msg->len); + out_data += msg->len; + } + } + + return 0; +} + +/** + * ec_i2c_count_response - Count bytes needed for ec_i2c_parse_response + * + * @i2c_msgs: The i2c messages to to fill up. + * @num: The number of i2c messages expected. + * + * Returns the number of response bytes expeced. + */ +static int ec_i2c_count_response(struct i2c_msg i2c_msgs[], int num) +{ + int size; + int i; + + size = sizeof(struct ec_response_i2c_passthru); + for (i = 0; i < num; i++) + if (i2c_msgs[i].flags & I2C_M_RD) + size += i2c_msgs[i].len; + + return size; +} + +/** + * ec_i2c_parse_response - Parse a response from the EC + * + * We'll take the EC's response and copy it back into msgs. + * + * @buf: The buffer to parse. + * @i2c_msgs: The i2c messages to to fill up. + * @num: The number of i2c messages; will be modified to include the actual + * number received. + * + * Returns 0 or a negative error number. + */ +static int ec_i2c_parse_response(const u8 *buf, struct i2c_msg i2c_msgs[], + int *num) +{ + const struct ec_response_i2c_passthru *resp; + const u8 *in_data; + int i; + + in_data = buf + sizeof(struct ec_response_i2c_passthru); + + resp = (const struct ec_response_i2c_passthru *)buf; + if (resp->i2c_status & EC_I2C_STATUS_TIMEOUT) + return -ETIMEDOUT; + else if (resp->i2c_status & EC_I2C_STATUS_NAK) + return -ENXIO; + else if (resp->i2c_status & EC_I2C_STATUS_ERROR) + return -EIO; + + /* Other side could send us back fewer messages, but not more */ + if (resp->num_msgs > *num) + return -EPROTO; + *num = resp->num_msgs; + + for (i = 0; i < *num; i++) { + struct i2c_msg *i2c_msg = &i2c_msgs[i]; + + if (i2c_msgs[i].flags & I2C_M_RD) { + memcpy(i2c_msg->buf, in_data, i2c_msg->len); + in_data += i2c_msg->len; + } + } + + return 0; +} + +static int ec_i2c_xfer(struct i2c_adapter *adap, struct i2c_msg i2c_msgs[], + int num) +{ + struct ec_i2c_device *bus = adap->algo_data; + struct device *dev = bus->dev; + const u16 bus_num = bus->remote_bus; + int request_len; + int response_len; + int alloc_size; + int result; + struct cros_ec_command *msg; + + request_len = ec_i2c_count_message(i2c_msgs, num); + if (request_len < 0) { + dev_warn(dev, "Error constructing message %d\n", request_len); + return request_len; + } + + response_len = ec_i2c_count_response(i2c_msgs, num); + if (response_len < 0) { + /* Unexpected; no errors should come when NULL response */ + dev_warn(dev, "Error preparing response %d\n", response_len); + return response_len; + } + + alloc_size = max(request_len, response_len); + msg = kmalloc(sizeof(*msg) + alloc_size, GFP_KERNEL); + if (!msg) + return -ENOMEM; + + result = ec_i2c_construct_message(msg->data, i2c_msgs, num, bus_num); + if (result) { + dev_err(dev, "Error constructing EC i2c message %d\n", result); + goto exit; + } + + msg->version = 0; + msg->command = EC_CMD_I2C_PASSTHRU; + msg->outsize = request_len; + msg->insize = response_len; + + result = cros_ec_cmd_xfer_status(bus->ec, msg); + if (result < 0) { + dev_err(dev, "Error transferring EC i2c message %d\n", result); + goto exit; + } + + result = ec_i2c_parse_response(msg->data, i2c_msgs, &num); + if (result < 0) + goto exit; + + /* Indicate success by saying how many messages were sent */ + result = num; +exit: + kfree(msg); + return result; +} + +static u32 ec_i2c_functionality(struct i2c_adapter *adap) +{ + return I2C_FUNC_I2C | I2C_FUNC_SMBUS_EMUL; +} + +static const struct i2c_algorithm ec_i2c_algorithm = { + .master_xfer = ec_i2c_xfer, + .functionality = ec_i2c_functionality, +}; + +static int ec_i2c_probe(struct platform_device *pdev) +{ + struct cros_ec_device *ec = dev_get_drvdata(pdev->dev.parent); + struct device *dev = &pdev->dev; + struct ec_i2c_device *bus = NULL; + u32 remote_bus; + int err; + + if (!ec->cmd_xfer) { + dev_err(dev, "Missing sendrecv\n"); + return -EINVAL; + } + + bus = devm_kzalloc(dev, sizeof(*bus), GFP_KERNEL); + if (bus == NULL) + return -ENOMEM; + + err = device_property_read_u32(dev, "google,remote-bus", &remote_bus); + if (err) { + dev_err(dev, "Couldn't read remote-bus property\n"); + return err; + } + bus->remote_bus = remote_bus; + + bus->ec = ec; + bus->dev = dev; + + bus->adap.owner = THIS_MODULE; + strlcpy(bus->adap.name, "cros-ec-i2c-tunnel", sizeof(bus->adap.name)); + bus->adap.algo = &ec_i2c_algorithm; + bus->adap.algo_data = bus; + bus->adap.dev.parent = &pdev->dev; + bus->adap.dev.of_node = pdev->dev.of_node; + bus->adap.retries = I2C_MAX_RETRIES; + + err = i2c_add_adapter(&bus->adap); + if (err) + return err; + platform_set_drvdata(pdev, bus); + + return err; +} + +static int ec_i2c_remove(struct platform_device *dev) +{ + struct ec_i2c_device *bus = platform_get_drvdata(dev); + + i2c_del_adapter(&bus->adap); + + return 0; +} + +static const struct of_device_id cros_ec_i2c_of_match[] = { + { .compatible = "google,cros-ec-i2c-tunnel" }, + {}, +}; +MODULE_DEVICE_TABLE(of, cros_ec_i2c_of_match); + +static const struct acpi_device_id cros_ec_i2c_tunnel_acpi_id[] = { + { "GOOG001A", 0 }, + { } +}; +MODULE_DEVICE_TABLE(acpi, cros_ec_i2c_tunnel_acpi_id); + +static struct platform_driver ec_i2c_tunnel_driver = { + .probe = ec_i2c_probe, + .remove = ec_i2c_remove, + .driver = { + .name = "cros-ec-i2c-tunnel", + .acpi_match_table = ACPI_PTR(cros_ec_i2c_tunnel_acpi_id), + .of_match_table = of_match_ptr(cros_ec_i2c_of_match), + }, +}; + +module_platform_driver(ec_i2c_tunnel_driver); + +MODULE_LICENSE("GPL"); +MODULE_DESCRIPTION("EC I2C tunnel driver"); +MODULE_ALIAS("platform:cros-ec-i2c-tunnel"); diff --git a/pool/shard004/C/0098607_hprof_tracker.c b/pool/shard004/C/0098607_hprof_tracker.c new file mode 100644 index 0000000000000000000000000000000000000000..56e1125122d5c0024d6a9ae8fdeaf7fc6b6c8064 --- /dev/null +++ b/pool/shard004/C/0098607_hprof_tracker.c @@ -0,0 +1,320 @@ +/* + * Copyright (c) 2003, 2005, Oracle and/or its affiliates. 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 Oracle 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. + */ + +/* + * This source code is provided to illustrate the usage of a given feature + * or technique and has been deliberately simplified. Additional steps + * required for a production-quality application, such as security checks, + * input validation and proper error handling, might not be present in + * this sample code. + */ + + +/* Tracker class support functions. */ + +/* + * This file contains the native support calls for the Tracker + * class. These native methods are registered and not made extern. + * Tracking is engaged by using JNI to assign to a static field in the + * Tracker class. + * + * Just like JVMTI callbacks, it's best that we keep track of these so that + * when the VM_DEATH happens we know to wait for them to complete. + * + * This file also contains the functions that will initialize the Tracker + * interface for BCI and identify the Tracker methods to make sure + * they are not included in any stack traces obtained from JVMTI. + * + * RFE: The performance of the java injected code calling native methods + * could be an issue here, cpu=times seems to be the worst where + * a native call is made for entry and exit, even on the smallest + * Java method. The alternative would be to cache the data on + * the Java side, and either push it out to the native side, or + * use some kind of pull from the native side, or even using + * shared memory or a socket. However having said that, the + * current performance issues are more around sheer memory needed, + * and repeated calls to GetThreadCpuTime(), which is being investigated. + * + */ + +#include "hprof.h" + +/* Macros to surround tracker based callback code. + * Also see BEGIN_CALLBACK and END_CALLBACK in hprof_init.c. + * If the VM_DEATH callback is active in the begining, then this callback + * just blocks (it is assumed we don't want to return to the VM). + * If the VM_DEATH callback is active at the end, then this callback + * will notify the VM_DEATH callback if it's the last one. + * + * WARNING: No not 'return' or 'goto' out of the BEGIN_TRACKER_CALLBACK/END_TRACKER_CALLBACK + * block, this will mess up the count. + */ + +#define BEGIN_TRACKER_CALLBACK() \ +{ /* BEGIN OF TRACKER_CALLBACK */ \ + jboolean bypass = JNI_TRUE; \ + rawMonitorEnter(gdata->callbackLock); { \ + if ( gdata->tracking_engaged != 0 ) { \ + if (!gdata->vm_death_callback_active) { \ + gdata->active_callbacks++; \ + bypass = JNI_FALSE; \ + } \ + } \ + } rawMonitorExit(gdata->callbackLock); \ + if ( !bypass ) { \ + /* BODY OF TRACKER_CALLBACK CODE */ + +#define END_TRACKER_CALLBACK() /* Part of bypass if body */ \ + rawMonitorEnter(gdata->callbackLock); { \ + gdata->active_callbacks--; \ + if (gdata->active_callbacks < 0) { \ + HPROF_ERROR(JNI_TRUE, "Problems tracking callbacks"); \ + } \ + if (gdata->vm_death_callback_active) { \ + if (gdata->active_callbacks == 0) { \ + rawMonitorNotifyAll(gdata->callbackLock); \ + } \ + } \ + } rawMonitorExit(gdata->callbackLock); \ + } \ +} /* END OF TRACKER_CALLBACK */ + + +/* + * Class: Tracker + * Method: nativeNewArray + * Signature: (Ljava/lang/Object;Ljava/lang/Object;)V + */ +static void JNICALL +Tracker_nativeNewArray + (JNIEnv *env, jclass clazz, jobject thread, jobject obj) +{ + BEGIN_TRACKER_CALLBACK() { + event_newarray(env, thread, obj); + } END_TRACKER_CALLBACK(); +} + +/* + * Class: Tracker + * Method: nativeObjectInit + * Signature: (Ljava/lang/Object;Ljava/lang/Object;)V + */ +static void JNICALL +Tracker_nativeObjectInit + (JNIEnv *env, jclass clazz, jobject thread, jobject obj) +{ + BEGIN_TRACKER_CALLBACK() { + event_object_init(env, thread, obj); + } END_TRACKER_CALLBACK(); +} + +/* + * Class: Tracker + * Method: nativeCallSite + * Signature: (Ljava/lang/Object;II)V + */ +static void JNICALL +Tracker_nativeCallSite + (JNIEnv *env, jclass clazz, jobject thread, jint cnum, jint mnum) +{ + BEGIN_TRACKER_CALLBACK() { + event_call(env, thread, cnum, mnum); + } END_TRACKER_CALLBACK(); +} + +/* + * Class: Tracker + * Method: nativeReturnSite + * Signature: (Ljava/lang/Object;II)V + */ +static void JNICALL +Tracker_nativeReturnSite + (JNIEnv *env, jclass clazz, jobject thread, jint cnum, jint mnum) +{ + BEGIN_TRACKER_CALLBACK() { + event_return(env, thread, cnum, mnum); + } END_TRACKER_CALLBACK(); +} + + +/* ------------------------------------------------------------------- */ +/* Set Java static field to turn on native code calls in Tracker. */ + +static void +set_engaged(JNIEnv *env, jint engaged) +{ + LOG3("set_engaged()", "engaging tracking", engaged); + + if ( ! gdata->bci ) { + return; + } + rawMonitorEnter(gdata->callbackLock); { + if ( gdata->tracking_engaged != engaged ) { + jfieldID field; + jclass tracker_class; + + tracker_class = class_get_class(env, gdata->tracker_cnum); + gdata->tracking_engaged = 0; + /* Activate or deactivate the injection code on the Java side */ + HPROF_ASSERT(tracker_class!=NULL); + exceptionClear(env); + field = getStaticFieldID(env, tracker_class, + TRACKER_ENGAGED_NAME, TRACKER_ENGAGED_SIG); + setStaticIntField(env, tracker_class, field, engaged); + exceptionClear(env); + + LOG3("set_engaged()", "tracking engaged", engaged); + + gdata->tracking_engaged = engaged; + } + } rawMonitorExit(gdata->callbackLock); +} + +void +tracker_engage(JNIEnv *env) +{ + set_engaged(env, 0xFFFF); +} + +void +tracker_disengage(JNIEnv *env) +{ + set_engaged(env, 0); +} + +jboolean +tracker_method(jmethodID method) +{ + int i; + + if ( ! gdata->bci ) { + return JNI_FALSE; + } + + HPROF_ASSERT(method!=NULL); + HPROF_ASSERT(gdata->tracker_method_count > 0); + for ( i = 0 ; i < gdata->tracker_method_count ; i++ ) { + HPROF_ASSERT(gdata->tracker_methods[i].method!=NULL); + if ( method == gdata->tracker_methods[i].method ) { + return JNI_TRUE; + } + } + return JNI_FALSE; +} + +static JNINativeMethod registry[4] = +{ + { TRACKER_NEWARRAY_NATIVE_NAME, TRACKER_NEWARRAY_NATIVE_SIG, + (void*)&Tracker_nativeNewArray }, + { TRACKER_OBJECT_INIT_NATIVE_NAME, TRACKER_OBJECT_INIT_NATIVE_SIG, + (void*)&Tracker_nativeObjectInit }, + { TRACKER_CALL_NATIVE_NAME, TRACKER_CALL_NATIVE_SIG, + (void*)&Tracker_nativeCallSite }, + { TRACKER_RETURN_NATIVE_NAME, TRACKER_RETURN_NATIVE_SIG, + (void*)&Tracker_nativeReturnSite } +}; + +static struct { + char *name; + char *sig; +} tracker_methods[] = + { + { TRACKER_NEWARRAY_NAME, TRACKER_NEWARRAY_SIG }, + { TRACKER_OBJECT_INIT_NAME, TRACKER_OBJECT_INIT_SIG }, + { TRACKER_CALL_NAME, TRACKER_CALL_SIG }, + { TRACKER_RETURN_NAME, TRACKER_RETURN_SIG }, + { TRACKER_NEWARRAY_NATIVE_NAME, TRACKER_NEWARRAY_NATIVE_SIG }, + { TRACKER_OBJECT_INIT_NATIVE_NAME, TRACKER_OBJECT_INIT_NATIVE_SIG }, + { TRACKER_CALL_NATIVE_NAME, TRACKER_CALL_NATIVE_SIG }, + { TRACKER_RETURN_NATIVE_NAME, TRACKER_RETURN_NATIVE_SIG } + }; + +void +tracker_setup_class(void) +{ + ClassIndex cnum; + LoaderIndex loader_index; + + HPROF_ASSERT(gdata->tracker_cnum==0); + loader_index = loader_find_or_create(NULL,NULL); + cnum = class_find_or_create(TRACKER_CLASS_SIG, loader_index); + gdata->tracker_cnum = cnum; + HPROF_ASSERT(cnum!=0); + class_add_status(cnum, CLASS_SPECIAL); +} + +void +tracker_setup_methods(JNIEnv *env) +{ + ClassIndex cnum; + LoaderIndex loader_index; + int i; + jclass object_class; + jclass tracker_class; + + if ( ! gdata->bci ) { + return; + } + + loader_index = loader_find_or_create(NULL,NULL); + cnum = class_find_or_create(OBJECT_CLASS_SIG, loader_index); + object_class = class_get_class(env, cnum); + tracker_class = class_get_class(env, gdata->tracker_cnum); + + CHECK_EXCEPTIONS(env) { + registerNatives(env, tracker_class, registry, + (int)sizeof(registry)/(int)sizeof(registry[0])); + } END_CHECK_EXCEPTIONS; + + HPROF_ASSERT(tracker_class!=NULL); + + gdata->tracker_method_count = + (int)sizeof(tracker_methods)/(int)sizeof(tracker_methods[0]); + + HPROF_ASSERT(gdata->tracker_method_count <= + (int)(sizeof(gdata->tracker_methods)/sizeof(gdata->tracker_methods[0]))); + + CHECK_EXCEPTIONS(env) { + gdata->object_init_method = getMethodID(env, object_class, + OBJECT_INIT_NAME, OBJECT_INIT_SIG); + for ( i=0 ; i < gdata->tracker_method_count ; i++ ) { + gdata->tracker_methods[i].name = + string_find_or_create(tracker_methods[i].name); + gdata->tracker_methods[i].sig = + string_find_or_create(tracker_methods[i].sig); + gdata->tracker_methods[i].method = + getStaticMethodID(env, tracker_class, + tracker_methods[i].name, tracker_methods[i].sig); + HPROF_ASSERT(gdata->tracker_methods[i].method!=NULL); + LOG2("tracker_setup_methods(): Found", tracker_methods[i].name); + } + } END_CHECK_EXCEPTIONS; +} diff --git a/pool/shard004/C/0098608_thread_suspension_unwind.c b/pool/shard004/C/0098608_thread_suspension_unwind.c new file mode 100644 index 0000000000000000000000000000000000000000..0ccf1d20d83975a276921609a8a82f96ff020169 --- /dev/null +++ b/pool/shard004/C/0098608_thread_suspension_unwind.c @@ -0,0 +1,178 @@ +/* + * Copyright (c) 2013 The Native Client 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 "native_client/src/include/build_config.h" +#include "native_client/src/trusted/service_runtime/thread_suspension_unwind.h" + +#include "native_client/src/trusted/cpu_features/arch/x86/cpu_x86.h" +#include "native_client/src/trusted/service_runtime/arch/arm/tramp_arm.h" +#include "native_client/src/trusted/service_runtime/arch/x86_64/tramp_64.h" +#include "native_client/src/trusted/service_runtime/nacl_app_thread.h" +#include "native_client/src/trusted/service_runtime/nacl_config.h" +#include "native_client/src/trusted/service_runtime/nacl_copy.h" +#include "native_client/src/trusted/service_runtime/sel_ldr.h" + + +static void GetNaClSyscallSeg(struct NaClApp *nap, + uintptr_t *nacl_syscall_seg, + uintptr_t *nacl_syscall_seg_regs_saved) { +#if NACL_ARCH(NACL_BUILD_ARCH) == NACL_x86 && NACL_BUILD_SUBARCH == 32 + NaClCPUFeaturesX86 *features = (NaClCPUFeaturesX86 *) nap->cpu_features; + if (NaClGetCPUFeatureX86(features, NaClCPUFeatureX86_SSE)) { + *nacl_syscall_seg = (uintptr_t) &NaClSyscallSegSSE; + *nacl_syscall_seg_regs_saved = (uintptr_t) &NaClSyscallSegRegsSavedSSE; + } else { + *nacl_syscall_seg = (uintptr_t) &NaClSyscallSegNoSSE; + *nacl_syscall_seg_regs_saved = (uintptr_t) &NaClSyscallSegRegsSavedNoSSE; + } +#else + UNREFERENCED_PARAMETER(nap); + + *nacl_syscall_seg = (uintptr_t) &NaClSyscallSeg; + *nacl_syscall_seg_regs_saved = (uintptr_t) &NaClSyscallSegRegsSaved; +#endif +} + +/* + * This returns 0 if |regs| indicates that the thread's register state + * has already been saved in NaClThreadContext. Otherwise, it adjusts + * |regs| to undo the effects of calling the syscall trampoline and + * returns 1. + */ +static int Unwind(struct NaClAppThread *natp, struct NaClSignalContext *regs, + enum NaClUnwindCase *unwind_case) { + struct NaClApp *nap = natp->nap; + uintptr_t nacl_syscall_seg; + uintptr_t nacl_syscall_seg_regs_saved; + +#if NACL_ARCH(NACL_BUILD_ARCH) == NACL_x86 && NACL_BUILD_SUBARCH == 32 + if (regs->cs == natp->user.cs && + regs->prog_ctr >= nap->syscall_return_springboard.start_addr && + regs->prog_ctr < nap->syscall_return_springboard.end_addr) { + *unwind_case = NACL_UNWIND_in_springboard; + return 0; + } + if (regs->cs == natp->user.cs && + regs->prog_ctr >= NACL_TRAMPOLINE_START && + regs->prog_ctr < NACL_TRAMPOLINE_END) { + *unwind_case = NACL_UNWIND_in_trampoline; + regs->stack_ptr += 4; /* Pop user return address */ + return 1; + } +#elif NACL_ARCH(NACL_BUILD_ARCH) == NACL_x86 && NACL_BUILD_SUBARCH == 64 + if (regs->prog_ctr >= NaClUserToSys(nap, NACL_TRAMPOLINE_START) && + regs->prog_ctr < NaClUserToSys(nap, NACL_TRAMPOLINE_END)) { + *unwind_case = NACL_UNWIND_in_trampoline; + regs->stack_ptr += 8; /* Pop user return address */ + return 1; + } +#elif NACL_ARCH(NACL_BUILD_ARCH) == NACL_arm + if (regs->prog_ctr >= NACL_TRAMPOLINE_START && + regs->prog_ctr < NACL_TRAMPOLINE_END) { + *unwind_case = NACL_UNWIND_in_trampoline; + regs->prog_ctr = NaClSandboxCodeAddr(nap, regs->lr); + return 1; + } +#elif NACL_ARCH(NACL_BUILD_ARCH) == NACL_mips + if (regs->prog_ctr >= NACL_TRAMPOLINE_START && + regs->prog_ctr < NACL_TRAMPOLINE_END) { + *unwind_case = NACL_UNWIND_in_trampoline; + regs->prog_ctr = NaClSandboxCodeAddr(nap, regs->return_addr); + return 1; + } +#endif + +#if NACL_ARCH(NACL_BUILD_ARCH) == NACL_x86 && NACL_BUILD_SUBARCH == 32 + if (regs->cs == NaClGetGlobalCs() && + regs->prog_ctr >= nap->pcrel_thunk && + regs->prog_ctr < nap->pcrel_thunk_end) { + *unwind_case = NACL_UNWIND_in_pcrel_thunk; + regs->stack_ptr += 4 + 8; /* Pop user + trampoline return addresses */ + return 1; + } +#endif + +#if NACL_ARCH(NACL_BUILD_ARCH) == NACL_x86 && NACL_BUILD_SUBARCH == 64 + if (regs->prog_ctr >= (uintptr_t) &NaClGetTlsFastPath1 && + regs->prog_ctr < (uintptr_t) &NaClGetTlsFastPath1End) { + *unwind_case = NACL_UNWIND_in_tls_fast_path; + if (regs->prog_ctr < (uintptr_t) &NaClGetTlsFastPath1RspRestored) { + regs->stack_ptr += 8; /* Pop user return address */ + } + return 1; + } + if (regs->prog_ctr >= (uintptr_t) &NaClGetTlsFastPath2 && + regs->prog_ctr < (uintptr_t) &NaClGetTlsFastPath2End) { + *unwind_case = NACL_UNWIND_in_tls_fast_path; + if (regs->prog_ctr < (uintptr_t) &NaClGetTlsFastPath2RspRestored) { + regs->stack_ptr += 8; /* Pop user return address */ + } + return 1; + } +#endif + + GetNaClSyscallSeg(nap, &nacl_syscall_seg, &nacl_syscall_seg_regs_saved); + if (regs->prog_ctr >= nacl_syscall_seg && + regs->prog_ctr < nacl_syscall_seg_regs_saved) { + *unwind_case = NACL_UNWIND_in_syscallseg; +#if NACL_ARCH(NACL_BUILD_ARCH) == NACL_x86 && NACL_BUILD_SUBARCH == 32 + /* Pop user + trampoline return addresses */ + regs->stack_ptr += 4 + 8; +#elif NACL_ARCH(NACL_BUILD_ARCH) == NACL_x86 && NACL_BUILD_SUBARCH == 64 + /* Pop user return address. */ + regs->stack_ptr += 8; +#elif NACL_ARCH(NACL_BUILD_ARCH) == NACL_mips + /* + * On MIPS, $ra is not modified from the start of the trampoline to the + * point where registers are saved. + */ + regs->prog_ctr = NaClSandboxCodeAddr(nap, regs->return_addr); +#endif + return 1; + } + + *unwind_case = NACL_UNWIND_after_saving_regs; + return 0; +} + +/* + * Given that thread |natp| has been suspended during a + * trusted/untrusted context switch and has trusted register state + * |regs|, this modifies |regs| to contain untrusted register state + * (that is, the state the syscall will return with). + */ +void NaClGetRegistersForContextSwitch(struct NaClAppThread *natp, + struct NaClSignalContext *regs, + enum NaClUnwindCase *unwind_case) { + if (Unwind(natp, regs, unwind_case)) { + NaClSignalContextUnsetClobberedRegisters(regs); + } else { + NaClThreadContextToSignalContext(&natp->user, regs); + } + + if (NACL_ARCH(NACL_BUILD_ARCH) == NACL_x86 || + (NACL_ARCH(NACL_BUILD_ARCH) == NACL_arm && + *unwind_case != NACL_UNWIND_in_trampoline) || + (NACL_ARCH(NACL_BUILD_ARCH) == NACL_mips && + *unwind_case != NACL_UNWIND_in_trampoline && + *unwind_case != NACL_UNWIND_in_syscallseg)) { + /* + * Read the return address from the untrusted stack. + * NaClCopyInFromUser() can fault or return an error here, but only + * if the thread was suspended just before it was about to crash. + * This can happen if untrusted code JMP'd to the trampoline with a + * bad stack pointer or if the thread was racing with an munmap(). + */ + nacl_reg_t user_ret = 0; + if (!NaClCopyInFromUser(natp->nap, &user_ret, + (uint32_t) (regs->stack_ptr + NACL_USERRET_FIX), + sizeof(user_ret))) { + NaClLog(LOG_WARNING, "NaClGetRegistersForContextSwitch: " + "Failed to read return address; using dummy value\n"); + } + regs->prog_ctr = NaClSandboxCodeAddr(natp->nap, user_ret); + } +} diff --git a/pool/shard004/C/0098610_uip-packetqueue.c b/pool/shard004/C/0098610_uip-packetqueue.c new file mode 100644 index 0000000000000000000000000000000000000000..f9b9c2d8090b772aca78efc34db917b3f61089f3 --- /dev/null +++ b/pool/shard004/C/0098610_uip-packetqueue.c @@ -0,0 +1,86 @@ +#include + +#include "net/uip.h" + +#include "lib/memb.h" + +#include "net/uip-packetqueue.h" + +#define MAX_NUM_QUEUED_PACKETS 2 +MEMB(packets_memb, struct uip_packetqueue_packet, MAX_NUM_QUEUED_PACKETS); + +#define DEBUG 0 +#if DEBUG +#include +#define PRINTF(...) printf(__VA_ARGS__) +#else +#define PRINTF(...) +#endif + +/*---------------------------------------------------------------------------*/ +static void +packet_timedout(void *ptr) +{ + struct uip_packetqueue_handle *h = ptr; + + PRINTF("uip_packetqueue_free timed out %p\n", h); + memb_free(&packets_memb, h->packet); + h->packet = NULL; +} +/*---------------------------------------------------------------------------*/ +void +uip_packetqueue_new(struct uip_packetqueue_handle *handle) +{ + PRINTF("uip_packetqueue_new %p\n", handle); + handle->packet = NULL; +} +/*---------------------------------------------------------------------------*/ +struct uip_packetqueue_packet * +uip_packetqueue_alloc(struct uip_packetqueue_handle *handle, clock_time_t lifetime) +{ + PRINTF("uip_packetqueue_alloc %p\n", handle); + if(handle->packet != NULL) { + PRINTF("alloced\n"); + return NULL; + } + handle->packet = memb_alloc(&packets_memb); + if(handle->packet != NULL) { + ctimer_set(&handle->packet->lifetimer, lifetime, + packet_timedout, handle); + } else { + PRINTF("uip_packetqueue_alloc failed\n"); + } + return handle->packet; +} +/*---------------------------------------------------------------------------*/ +void +uip_packetqueue_free(struct uip_packetqueue_handle *handle) +{ + PRINTF("uip_packetqueue_free %p\n", handle); + if(handle->packet != NULL) { + ctimer_stop(&handle->packet->lifetimer); + memb_free(&packets_memb, handle->packet); + handle->packet = NULL; + } +} +/*---------------------------------------------------------------------------*/ +uint8_t * +uip_packetqueue_buf(struct uip_packetqueue_handle *h) +{ + return h->packet != NULL? h->packet->queue_buf: NULL; +} +/*---------------------------------------------------------------------------*/ +uint16_t +uip_packetqueue_buflen(struct uip_packetqueue_handle *h) +{ + return h->packet != NULL? h->packet->queue_buf_len: 0; +} +/*---------------------------------------------------------------------------*/ +void +uip_packetqueue_set_buflen(struct uip_packetqueue_handle *h, uint16_t len) +{ + if(h->packet != NULL) { + h->packet->queue_buf_len = len; + } +} +/*---------------------------------------------------------------------------*/ diff --git a/pool/shard004/C/0098614_cpu.c b/pool/shard004/C/0098614_cpu.c new file mode 100644 index 0000000000000000000000000000000000000000..0d9e72b787393f96d3e5de026a6f8388ad948539 --- /dev/null +++ b/pool/shard004/C/0098614_cpu.c @@ -0,0 +1,223 @@ +/* linux/arch/arm/mach-s5pv210/cpu.c + * + * Copyright (c) 2010 Samsung Electronics Co., Ltd. + * http://www.samsung.com + * + * 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 +#include + +/* Initial IO mappings */ + +static struct map_desc s5pv210_iodesc[] __initdata = { + { + .virtual = (unsigned long)S5P_VA_SYSTIMER, + .pfn = __phys_to_pfn(S5PV210_PA_SYSTIMER), + .length = SZ_4K, + .type = MT_DEVICE, + }, { + .virtual = (unsigned long)S5P_VA_GPIO, + .pfn = __phys_to_pfn(S5PV210_PA_GPIO), + .length = SZ_4K, + .type = MT_DEVICE, + }, { + .virtual = (unsigned long)VA_VIC0, + .pfn = __phys_to_pfn(S5PV210_PA_VIC0), + .length = SZ_16K, + .type = MT_DEVICE, + }, { + .virtual = (unsigned long)VA_VIC1, + .pfn = __phys_to_pfn(S5PV210_PA_VIC1), + .length = SZ_16K, + .type = MT_DEVICE, + }, { + .virtual = (unsigned long)VA_VIC2, + .pfn = __phys_to_pfn(S5PV210_PA_VIC2), + .length = SZ_16K, + .type = MT_DEVICE, + }, { + .virtual = (unsigned long)VA_VIC3, + .pfn = __phys_to_pfn(S5PV210_PA_VIC3), + .length = SZ_16K, + .type = MT_DEVICE, + }, { + .virtual = (unsigned long)S3C_VA_UART, + .pfn = __phys_to_pfn(S3C_PA_UART), + .length = SZ_512K, + .type = MT_DEVICE, + }, { + .virtual = (unsigned long)S5P_VA_DMC0, + .pfn = __phys_to_pfn(S5PV210_PA_DMC0), + .length = SZ_4K, + .type = MT_DEVICE, + }, { + .virtual = (unsigned long)S5P_VA_DMC1, + .pfn = __phys_to_pfn(S5PV210_PA_DMC1), + .length = SZ_4K, + .type = MT_DEVICE, + }, { + .virtual = (unsigned long)S3C_VA_USB_HSPHY, + .pfn =__phys_to_pfn(S5PV210_PA_HSPHY), + .length = SZ_4K, + .type = MT_DEVICE, + }, { + .virtual = (unsigned long)S3C_VA_OTG, + .pfn = __phys_to_pfn(S5PV210_PA_OTG), + .length = SZ_1M, + .type = MT_DEVICE, + }, { + .virtual = (unsigned long)S3C_VA_OTGSFR, + .pfn = __phys_to_pfn(S5PV210_PA_OTGSFR), + .length = SZ_1M, + .type = MT_DEVICE, + }, +#if defined(CONFIG_HRT_RTC) + { + .virtual = (unsigned long)S5P_VA_RTC, + .pfn = __phys_to_pfn(S5PV210_PA_RTC), + .length = SZ_4K, + .type = MT_DEVICE, + }, +#endif + { + .virtual = (unsigned long)S5P_VA_AUDSS, + .pfn = __phys_to_pfn(S5PV210_PA_AUDSS), + .length = SZ_1M, + .type = MT_DEVICE, + }, +}; + +static void s5pv210_idle(void) +{ + if (!need_resched()) + cpu_do_idle(); + + local_irq_enable(); +} + +static void s5pv210_sw_reset(void) +{ + __raw_writel(0x1, S5P_SWRESET); +} + +/* s5pv210_map_io + * + * register the standard cpu IO areas +*/ + +void __init s5pv210_map_io(void) +{ + iotable_init(s5pv210_iodesc, ARRAY_SIZE(s5pv210_iodesc)); + + /* initialise device information early */ + s5pv210_default_sdhci0(); + s5pv210_default_sdhci1(); + s5pv210_default_sdhci2(); + s5pv210_default_sdhci3(); + + s3c_adc_setname("s3c64xx-adc"); + + s3c_cfcon_setname("s5pv210-pata"); + + s3c_fimc_setname(0, "s5pv210-fimc"); + s3c_fimc_setname(1, "s5pv210-fimc"); + s3c_fimc_setname(2, "s5pv210-fimc"); + + /* the i2c devices are directly compatible with s3c2440 */ + s3c_i2c0_setname("s3c2440-i2c"); + s3c_i2c1_setname("s3c2440-i2c"); + s3c_i2c2_setname("s3c2440-i2c"); + + s3c_fb_setname("s5pv210-fb"); + + /* Use s5pv210-keypad instead of samsung-keypad */ + samsung_keypad_setname("s5pv210-keypad"); +} + +void __init s5pv210_init_clocks(int xtal) +{ + printk(KERN_DEBUG "%s: initializing clocks\n", __func__); + + s3c24xx_register_baseclocks(xtal); + s5p_register_clocks(xtal); + s5pv210_register_clocks(); + s5pv210_setup_clocks(); +} + +void __init s5pv210_init_irq(void) +{ + u32 vic[4]; /* S5PV210 supports 4 VIC */ + + /* All the VICs are fully populated. */ + vic[0] = ~0; + vic[1] = ~0; + vic[2] = ~0; + vic[3] = ~0; + + s5p_init_irq(vic, ARRAY_SIZE(vic)); +} + +struct sysdev_class s5pv210_sysclass = { + .name = "s5pv210-core", +}; + +static struct sys_device s5pv210_sysdev = { + .cls = &s5pv210_sysclass, +}; + +static int __init s5pv210_core_init(void) +{ + return sysdev_class_register(&s5pv210_sysclass); +} + +core_initcall(s5pv210_core_init); + +int __init s5pv210_init(void) +{ + printk(KERN_INFO "S5PV210: Initializing architecture\n"); + + /* set idle function */ + pm_idle = s5pv210_idle; + + /* set sw_reset function */ + if (!(machine_is_herring() || machine_is_aries() || machine_is_venturi())) + s5p_reset_hook = s5pv210_sw_reset; + + return sysdev_register(&s5pv210_sysdev); +} diff --git a/pool/shard004/C/0098619_huffcoding.c b/pool/shard004/C/0098619_huffcoding.c new file mode 100644 index 0000000000000000000000000000000000000000..dafffdb0a7fabc319ffe7fcea8a8d2d9776a04c1 --- /dev/null +++ b/pool/shard004/C/0098619_huffcoding.c @@ -0,0 +1,95 @@ +/* + * Copyright (C) 2016 Tianyi Geng + */ + +#ifndef __HUFFCODING_C_ +#define __HUFFCODING_C_ + +#include +#include "huffcoding.h" + +void ResetHuffIndex(struct huff_codebook* book, int32_t val) { + book->nIndex = val; +} + +int32_t HuffDec(struct huff_codebook* book, struct bs_iter* iter) { + /* a tree to help decoding */ + struct tree_node* root = build_tree(book); + + struct tree_node* curr = root; + + while (1) { + /* loop until we decoded a value */ + if (bs_iter_unpack(iter, 1)) { + curr = curr->right; + } else { + curr = curr->left; + } + + if (curr->is_leaf) { + int32_t ret = curr->val; + erase_tree(root); + return ret; + } + } + + handle_error(ERROR_UNKNOWN); + return -1; +} + +int32_t HuffDecDiff(struct huff_codebook* book, struct bs_iter* iter) { + int32_t nDiff = HuffDec(book, iter); + book->nIndex = (book->nIndex + nDiff) % book->size; + return book->nIndex; +} + +int32_t HuffDecRecursive(struct huff_codebook* book, struct bs_iter* iter) { + int32_t k = -1; + int32_t nQIndex = 0; + int32_t nNumCodes = book->size; + do { + k++; + nQIndex = HuffDec(book, iter); + } while (nQIndex == nNumCodes - 1); + return k * (nNumCodes - 1) + nQIndex; +} + +void HuffEnc(struct huff_codebook* book, struct bit_stream* bs, int32_t val) { + uint32_t* temp_code = (uint32_t*) malloc(sizeof(uint32_t) * book->size); + uint32_t* temp_bits = (uint32_t*) malloc(sizeof(uint32_t) * book->size); + uint32_t cumulate_size = 0; + + if (temp_bits == NULL || temp_code == NULL) { + handle_error(ERROR_FAILURE_ALLOC_MEM); + return; + } + + /* set up library here */ + for (uint32_t i = 0; i < book->size; i++) { + cumulate_size += book->bit_incr[i]; + temp_code[book->index[i]] = book->code[i]; + temp_bits[book->index[i]] = cumulate_size; + } + + /* push to bitstream */ + bitstream_push(bs, temp_code[val], temp_bits[val]); + + free(temp_code); + free(temp_bits); +} + +void HuffEncDiff(struct huff_codebook* book, struct bit_stream* bs, int32_t val) { + HuffEnc(book, bs, (val + book->size - book->nIndex) % book->size); + book->nIndex = val; +} + +void HuffEncRecursive(struct huff_codebook* book, struct bit_stream* bs, int32_t val) { + int32_t nNumCodes = book->size; + while (val >= nNumCodes - 1) { + HuffEnc(book, bs, nNumCodes - 1); + val -= nNumCodes - 1; + } + HuffEnc(book, bs, val); +} + +#endif diff --git a/pool/shard004/C/0098625_aes_method.c b/pool/shard004/C/0098625_aes_method.c new file mode 100644 index 0000000000000000000000000000000000000000..bc0d191ff2feb4ecf0fde02c8eab90fbc337d419 --- /dev/null +++ b/pool/shard004/C/0098625_aes_method.c @@ -0,0 +1,268 @@ +/*- + * See the file LICENSE for redistribution information. + * + * Copyright (c) 2001,2007 Oracle. All rights reserved. + * + * Some parts of this code originally written by Adam Stubblefield, + * -- astubble@rice.edu. + * + * $Id: aes_method.c,v 12.7 2007/05/17 15:14:55 bostic Exp $ + */ + +#include "db_config.h" + +#include "db_int.h" +#include "dbinc/crypto.h" +#include "dbinc/hmac.h" + +static void __aes_err __P((DB_ENV *, int)); +static int __aes_derivekeys __P((DB_ENV *, DB_CIPHER *, u_int8_t *, size_t)); + +/* + * __aes_setup -- + * Setup AES functions. + * + * PUBLIC: int __aes_setup __P((DB_ENV *, DB_CIPHER *)); + */ +int +__aes_setup(dbenv, db_cipher) + DB_ENV *dbenv; + DB_CIPHER *db_cipher; +{ + AES_CIPHER *aes_cipher; + int ret; + + db_cipher->adj_size = __aes_adj_size; + db_cipher->close = __aes_close; + db_cipher->decrypt = __aes_decrypt; + db_cipher->encrypt = __aes_encrypt; + db_cipher->init = __aes_init; + if ((ret = __os_calloc(dbenv, 1, sizeof(AES_CIPHER), &aes_cipher)) != 0) + return (ret); + db_cipher->data = aes_cipher; + return (0); +} + +/* + * __aes_adj_size -- + * Given a size, return an addition amount needed to meet the + * "chunk" needs of the algorithm. + * + * PUBLIC: u_int __aes_adj_size __P((size_t)); + */ +u_int +__aes_adj_size(len) + size_t len; +{ + if (len % DB_AES_CHUNK == 0) + return (0); + return (DB_AES_CHUNK - (u_int)(len % DB_AES_CHUNK)); +} + +/* + * __aes_close -- + * Destroy the AES encryption instantiation. + * + * PUBLIC: int __aes_close __P((DB_ENV *, void *)); + */ +int +__aes_close(dbenv, data) + DB_ENV *dbenv; + void *data; +{ + __os_free(dbenv, data); + return (0); +} + +/* + * __aes_decrypt -- + * Decrypt data with AES. + * + * PUBLIC: int __aes_decrypt __P((DB_ENV *, void *, void *, + * PUBLIC: u_int8_t *, size_t)); + */ +int +__aes_decrypt(dbenv, aes_data, iv, cipher, cipher_len) + DB_ENV *dbenv; + void *aes_data; + void *iv; + u_int8_t *cipher; + size_t cipher_len; +{ + AES_CIPHER *aes; + cipherInstance c; + int ret; + + aes = (AES_CIPHER *)aes_data; + if (iv == NULL || cipher == NULL) + return (EINVAL); + if ((cipher_len % DB_AES_CHUNK) != 0) + return (EINVAL); + /* + * Initialize the cipher + */ + if ((ret = __db_cipherInit(&c, MODE_CBC, iv)) < 0) { + __aes_err(dbenv, ret); + return (EAGAIN); + } + + /* Do the decryption */ + if ((ret = __db_blockDecrypt(&c, &aes->decrypt_ki, cipher, + cipher_len * 8, cipher)) < 0) { + __aes_err(dbenv, ret); + return (EAGAIN); + } + return (0); +} + +/* + * __aes_encrypt -- + * Encrypt data with AES. + * + * PUBLIC: int __aes_encrypt __P((DB_ENV *, void *, void *, + * PUBLIC: u_int8_t *, size_t)); + */ +int +__aes_encrypt(dbenv, aes_data, iv, data, data_len) + DB_ENV *dbenv; + void *aes_data; + void *iv; + u_int8_t *data; + size_t data_len; +{ + AES_CIPHER *aes; + cipherInstance c; + u_int32_t tmp_iv[DB_IV_BYTES/4]; + int ret; + + aes = (AES_CIPHER *)aes_data; + if (aes == NULL || data == NULL) + return (EINVAL); + if ((data_len % DB_AES_CHUNK) != 0) + return (EINVAL); + /* + * Generate the IV here. We store it in a tmp IV because + * the IV might be stored within the data we are encrypting + * and so we will copy it over to the given location after + * encryption is done. + * We don't do this outside of there because some encryption + * algorithms someone might add may not use IV's and we always + * want on here. + */ + if ((ret = __db_generate_iv(dbenv, tmp_iv)) != 0) + return (ret); + + /* + * Initialize the cipher + */ + if ((ret = __db_cipherInit(&c, MODE_CBC, (char *)tmp_iv)) < 0) { + __aes_err(dbenv, ret); + return (EAGAIN); + } + + /* Do the encryption */ + if ((ret = __db_blockEncrypt(&c, &aes->encrypt_ki, data, data_len * 8, + data)) < 0) { + __aes_err(dbenv, ret); + return (EAGAIN); + } + memcpy(iv, tmp_iv, DB_IV_BYTES); + return (0); +} + +/* + * __aes_init -- + * Initialize the AES encryption instantiation. + * + * PUBLIC: int __aes_init __P((DB_ENV *, DB_CIPHER *)); + */ +int +__aes_init(dbenv, db_cipher) + DB_ENV *dbenv; + DB_CIPHER *db_cipher; +{ + return (__aes_derivekeys(dbenv, db_cipher, (u_int8_t *)dbenv->passwd, + dbenv->passwd_len)); +} + +static int +__aes_derivekeys(dbenv, db_cipher, passwd, plen) + DB_ENV *dbenv; + DB_CIPHER *db_cipher; + u_int8_t *passwd; + size_t plen; +{ + SHA1_CTX ctx; + AES_CIPHER *aes; + int ret; + u_int32_t temp[DB_MAC_KEY/4]; + + if (passwd == NULL) + return (EINVAL); + + aes = (AES_CIPHER *)db_cipher->data; + + /* Derive the crypto keys */ + __db_SHA1Init(&ctx); + __db_SHA1Update(&ctx, passwd, plen); + __db_SHA1Update(&ctx, (u_int8_t *)DB_ENC_MAGIC, strlen(DB_ENC_MAGIC)); + __db_SHA1Update(&ctx, passwd, plen); + __db_SHA1Final((u_int8_t *)temp, &ctx); + + if ((ret = __db_makeKey(&aes->encrypt_ki, DIR_ENCRYPT, + DB_AES_KEYLEN, (char *)temp)) != TRUE) { + __aes_err(dbenv, ret); + return (EAGAIN); + } + if ((ret = __db_makeKey(&aes->decrypt_ki, DIR_DECRYPT, + DB_AES_KEYLEN, (char *)temp)) != TRUE) { + __aes_err(dbenv, ret); + return (EAGAIN); + } + return (0); +} + +/* + * __aes_err -- + * Handle AES-specific errors. Codes and messages derived from + * rijndael/rijndael-api-fst.h. + */ +static void +__aes_err(dbenv, err) + DB_ENV *dbenv; + int err; +{ + char *errstr; + + switch (err) { + case BAD_KEY_DIR: + errstr = "AES key direction is invalid"; + break; + case BAD_KEY_MAT: + errstr = "AES key material not of correct length"; + break; + case BAD_KEY_INSTANCE: + errstr = "AES key passwd not valid"; + break; + case BAD_CIPHER_MODE: + errstr = "AES cipher in wrong state (not initialized)"; + break; + case BAD_BLOCK_LENGTH: + errstr = "AES bad block length"; + break; + case BAD_CIPHER_INSTANCE: + errstr = "AES cipher instance is invalid"; + break; + case BAD_DATA: + errstr = "AES data contents are invalid"; + break; + case BAD_OTHER: + errstr = "AES unknown error"; + break; + default: + errstr = "AES error unrecognized"; + break; + } + __db_errx(dbenv, errstr); + return; +} diff --git a/pool/shard004/C/0098632_xhash-test.c b/pool/shard004/C/0098632_xhash-test.c new file mode 100644 index 0000000000000000000000000000000000000000..73639c6794026d7637f909b57fac8fdc7e053e6c --- /dev/null +++ b/pool/shard004/C/0098632_xhash-test.c @@ -0,0 +1,272 @@ +/*****************************************************************************\ + * Copyright (C) 2012 CEA/DAM/DIF + * + * 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. +\*****************************************************************************/ +#include +#include +#include + +#include "src/common/xhash.h" +#include "src/common/xmalloc.h" + +/* FIXME: how to check memory leaks with valgrind ? (to check if xhash_free + * does free all structures correctly). */ + +/***************************************************************************** + * DEFINITIONS + *****************************************************************************/ + +typedef struct hashable_st { + char id[255]; + uint32_t idn; +} hashable_t; + +const char* hashable_identify(void* voiditem) +{ + hashable_t* item = (hashable_t*)voiditem; + if (!item->id[0]) snprintf(item->id, 255, "%lu", + (unsigned long)item->idn); + return item->id; +} + +/***************************************************************************** + * FIXTURE * + *****************************************************************************/ + +xhash_t* g_ht = NULL; +hashable_t g_hashables[200]; +uint32_t g_hashableslen = sizeof(g_hashables)/sizeof(g_hashables[0]); + +static void setup(void) +{ + int i; + g_ht = xhash_init(hashable_identify, NULL, 0); + if (!g_ht) return; /* fatal error, will be detected by test cases */ + for (i = 0; i < g_hashableslen; ++i) { + g_hashables[i].id[0] = 0; + g_hashables[i].idn = i; + /* it is an error if xhash_add returns null but it will be + * detected by test cases */ + if (!xhash_add(g_ht, g_hashables + i)) return; + } +} + +static void teardown(void) +{ + xhash_free(g_ht); +} + +/***************************************************************************** + * UNIT TESTS * + ****************************************************************************/ + +START_TEST(test_init_free) +{ + xhash_t* ht = NULL; + + mark_point(); + + /* invalid case */ + ht = xhash_init(NULL, NULL, 0); + fail_unless(ht == NULL, "allocated table without identifying function"); + + /* alloc and free */ + ht = xhash_init(hashable_identify, NULL, 0); + fail_unless(ht != NULL, "hash table was not allocated"); + xhash_free(ht); +} +END_TEST + +START_TEST(test_add) +{ + xhash_t* ht = NULL; + hashable_t a[4] = {{"0", 0}, {"1", 1}, {"2", 2}, {"3", 3}}; + int i, len = sizeof(a)/sizeof(a[0]); + char buffer[255]; + ht = xhash_init(hashable_identify, NULL, 0); + fail_unless(xhash_add(NULL, a) == NULL, "invalid cases not null"); + fail_unless(xhash_add(ht, NULL) == NULL, "invalid cases not null"); + fail_unless(xhash_add(ht, a) != NULL, "xhash_add failed"); + fail_unless(xhash_add(ht, a+1) != NULL, "xhash_add failed"); + fail_unless(xhash_add(ht, a+2) != NULL, "xhash_add failed"); + fail_unless(xhash_add(ht, a+3) != NULL, "xhash_add failed"); + for (i = 0; i < len; ++i) { + snprintf(buffer, sizeof(buffer), "%d", i); + fail_unless(xhash_get(ht, buffer) == (a + i), + "bad hashable item returned"); + } + xhash_free(ht); +} +END_TEST + +START_TEST(test_find) +{ + xhash_t* ht = g_ht; + char buffer[255]; + int i; + + /* test bad match */ + fail_unless(xhash_get(ht, "bad") == NULL , "invalid case not null"); + fail_unless(xhash_get(ht, "-1") == NULL , "invalid case not null"); + fail_unless(xhash_get(ht, "10000") == NULL, "invalid case not null"); + + /* test all good indexes */ + for (i = 0; i < g_hashableslen; ++i) { + snprintf(buffer, sizeof(buffer), "%d", i); + fail_unless(xhash_get(ht, buffer) == (g_hashables + i), + "bad hashable item returned"); + } +} +END_TEST + +/* returns the number of item deleted from the hash table */ +static int test_delete_helper() +{ + xhash_t* ht = g_ht; + int ret = 0; + int i; + char buffer[255]; + for (i = 0; i < g_hashableslen; ++i) { + snprintf(buffer, sizeof(buffer), "%d", i); + if (xhash_get(ht, buffer) != (g_hashables + i)) { + ++ret; + } + } + return ret; +} + +START_TEST(test_delete) +{ + xhash_t* ht = g_ht; + int result; + char buffer[255]; + + /* invalid cases */ + xhash_delete(NULL, "1"); + fail_unless(xhash_get(ht, "1") != NULL, "invalid case null"); + /* Deleting inexistant item should do nothing. */ + xhash_delete(ht, NULL); + fail_unless(xhash_count(ht) == g_hashableslen, + "invalid delete has been done"); + result = test_delete_helper(); + fail_unless(result == 0, + "no item should have been deleted, but %d were deleted", + result); + + /* test correct deletion */ + xhash_delete(ht, "10"); + fail_unless(xhash_get(ht, "10") == NULL, "item not deleted"); + fail_unless(xhash_count(ht) == (g_hashableslen-1), "bad count"); + /* left edge */ + xhash_delete(ht, "0"); + fail_unless(xhash_get(ht, "0") == NULL, "item not deleted"); + fail_unless(xhash_count(ht) == (g_hashableslen-2), "bad count"); + /* right edge */ + snprintf(buffer, sizeof(buffer), "%u", (g_hashableslen-2)); + xhash_delete(ht, buffer); + fail_unless(xhash_get(ht, "0") == NULL, "item not deleted"); + fail_unless(xhash_count(ht) == (g_hashableslen-3), "bad count"); + + result = test_delete_helper(); + fail_unless(result == 3, "bad number of items were deleted: %d", + result); +} +END_TEST + +START_TEST(test_count) +{ + xhash_t* ht = g_ht; + hashable_t a[4] = {{"0", 0}, {"1", 1}, {"2", 2}, {"3", 3}}; + fail_unless(xhash_count(ht) == g_hashableslen, + "invalid count (fixture table)"); + ht = xhash_init(hashable_identify, NULL, 0); + xhash_add(ht, a); + xhash_add(ht, a+1); + xhash_add(ht, a+2); + xhash_add(ht, a+3); + fail_unless(xhash_count(ht) == 4, "invalid count (fresh table)"); + xhash_free(ht); +} +END_TEST + +static void test_walk_helper_callback(void* item, void* arg) +{ + hashable_t* hashable = (hashable_t*)item; + hashable->idn = UINT32_MAX; +} + +START_TEST(test_walk) +{ + xhash_t* ht = g_ht; + int i; + xhash_walk(ht, test_walk_helper_callback, NULL); + for (i = 0; i < g_hashableslen; ++i) { + fail_unless(g_hashables[i].idn == UINT32_MAX, + "hashable item was not walked over"); + } +} +END_TEST + +/***************************************************************************** + * TEST SUITE * + ****************************************************************************/ + +Suite* xhash_suite(void) +{ + Suite* s = suite_create("xhash"); + TCase* tc_core = tcase_create("Core"); + tcase_add_checked_fixture(tc_core, setup, teardown); + tcase_add_test(tc_core, test_init_free); + tcase_add_test(tc_core, test_add); + tcase_add_test(tc_core, test_find); + tcase_add_test(tc_core, test_delete); + tcase_add_test(tc_core, test_count); + tcase_add_test(tc_core, test_walk); + suite_add_tcase(s, tc_core); + return s; +} + +/***************************************************************************** + * TEST RUNNER * + ****************************************************************************/ + +int main(void) +{ + int number_failed; + SRunner* sr = srunner_create(xhash_suite()); + + srunner_run_all(sr, CK_NORMAL); + number_failed = srunner_ntests_failed(sr); + srunner_free(sr); + + return (number_failed == 0) ? EXIT_SUCCESS : EXIT_FAILURE; +} + diff --git a/pool/shard004/C/0098645_s2n_server_extensions_recv_test.c b/pool/shard004/C/0098645_s2n_server_extensions_recv_test.c new file mode 100644 index 0000000000000000000000000000000000000000..8a96df04ab7bdeaf5ab173f379e54ce318d09b2c --- /dev/null +++ b/pool/shard004/C/0098645_s2n_server_extensions_recv_test.c @@ -0,0 +1,77 @@ +/* + * Copyright 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. + */ + +/* Target Functions: s2n_server_extensions_recv s2n_recv_server_server_name + s2n_recv_server_renegotiation_info_ext s2n_recv_server_alpn + s2n_recv_server_status_request s2n_recv_server_sct_list + s2n_recv_server_max_fragment_length s2n_recv_server_session_ticket_ext */ + +#include + +#include +#include + +#include "tls/s2n_server_extensions.h" + +#include "api/s2n.h" +#include "stuffer/s2n_stuffer.h" +#include "tls/s2n_connection.h" +#include "tls/s2n_tls.h" +#include "utils/s2n_safety.h" +#include "s2n_test.h" +#include "testlib/s2n_testlib.h" +#include "tls/s2n_tls13.h" + +/* This test is for TLS versions 1.3 and up only */ +static const uint8_t TLS_VERSIONS[] = {S2N_TLS13}; + +int s2n_fuzz_init(int *argc, char **argv[]) +{ + POSIX_GUARD(s2n_enable_tls13()); + return S2N_SUCCESS; +} + +int s2n_fuzz_test(const uint8_t *buf, size_t len) +{ + /* We need at least one byte of input to set parameters */ + S2N_FUZZ_ENSURE_MIN_LEN(len, 1); + + /* Setup */ + struct s2n_stuffer fuzz_stuffer = {0}; + POSIX_GUARD(s2n_stuffer_alloc(&fuzz_stuffer, len + 1)); + POSIX_GUARD(s2n_stuffer_write_bytes(&fuzz_stuffer, buf, len)); + + struct s2n_connection *client_conn = s2n_connection_new(S2N_CLIENT); + POSIX_ENSURE_REF(client_conn); + + /* Pull a byte off the libfuzzer input and use it to set parameters */ + uint8_t randval = 0; + POSIX_GUARD(s2n_stuffer_read_uint8(&fuzz_stuffer, &randval)); + client_conn->actual_protocol_version = TLS_VERSIONS[(randval & 0x0F) % s2n_array_len(TLS_VERSIONS)]; + client_conn->client_protocol_version = TLS_VERSIONS[(randval >> 4) % s2n_array_len(TLS_VERSIONS)]; + + /* Run Test + * Do not use GUARD macro here since the connection memory hasn't been freed. + */ + s2n_server_extensions_recv(client_conn, &fuzz_stuffer); + + /* Cleanup */ + POSIX_GUARD(s2n_connection_free(client_conn)); + POSIX_GUARD(s2n_stuffer_free(&fuzz_stuffer)); + + return S2N_SUCCESS; +} + +S2N_FUZZ_TARGET(s2n_fuzz_init, s2n_fuzz_test, NULL) diff --git a/pool/shard004/C/0098646_mod_access.c b/pool/shard004/C/0098646_mod_access.c new file mode 100644 index 0000000000000000000000000000000000000000..c450e76c49a1192140af948fc01feaeb59962100 --- /dev/null +++ b/pool/shard004/C/0098646_mod_access.c @@ -0,0 +1,242 @@ +#include "first.h" + +#include "base.h" +#include "log.h" +#include "buffer.h" + +#include "plugin.h" + +#include +#include +#include + +typedef struct { + array *access_allow; + array *access_deny; +} plugin_config; + +typedef struct { + PLUGIN_DATA; + + plugin_config **config_storage; + + plugin_config conf; +} plugin_data; + +INIT_FUNC(mod_access_init) { + plugin_data *p; + + p = calloc(1, sizeof(*p)); + + return p; +} + +FREE_FUNC(mod_access_free) { + plugin_data *p = p_d; + + UNUSED(srv); + + if (!p) return HANDLER_GO_ON; + + if (p->config_storage) { + size_t i; + for (i = 0; i < srv->config_context->used; i++) { + plugin_config *s = p->config_storage[i]; + + if (NULL == s) continue; + + array_free(s->access_allow); + array_free(s->access_deny); + + free(s); + } + free(p->config_storage); + } + + free(p); + + return HANDLER_GO_ON; +} + +SETDEFAULTS_FUNC(mod_access_set_defaults) { + plugin_data *p = p_d; + size_t i = 0; + + config_values_t cv[] = { + { "url.access-deny", NULL, T_CONFIG_ARRAY, T_CONFIG_SCOPE_CONNECTION }, + { "url.access-allow", NULL, T_CONFIG_ARRAY, T_CONFIG_SCOPE_CONNECTION }, + { NULL, NULL, T_CONFIG_UNSET, T_CONFIG_SCOPE_UNSET } + }; + + p->config_storage = calloc(1, srv->config_context->used * sizeof(plugin_config *)); + + for (i = 0; i < srv->config_context->used; i++) { + data_config const* config = (data_config const*)srv->config_context->data[i]; + plugin_config *s; + + s = calloc(1, sizeof(plugin_config)); + s->access_deny = array_init(); + s->access_allow = array_init(); + + cv[0].destination = s->access_deny; + cv[1].destination = s->access_allow; + + p->config_storage[i] = s; + + if (0 != config_insert_values_global(srv, config->value, cv, i == 0 ? T_CONFIG_SCOPE_SERVER : T_CONFIG_SCOPE_CONNECTION)) { + return HANDLER_ERROR; + } + } + + return HANDLER_GO_ON; +} + +#define PATCH(x) \ + p->conf.x = s->x; +static int mod_access_patch_connection(server *srv, connection *con, plugin_data *p) { + size_t i, j; + plugin_config *s = p->config_storage[0]; + + PATCH(access_allow); + PATCH(access_deny); + + /* skip the first, the global context */ + for (i = 1; i < srv->config_context->used; i++) { + data_config *dc = (data_config *)srv->config_context->data[i]; + s = p->config_storage[i]; + + /* condition didn't match */ + if (!config_check_cond(srv, con, dc)) continue; + + /* merge config */ + for (j = 0; j < dc->value->used; j++) { + data_unset *du = dc->value->data[j]; + + if (buffer_is_equal_string(du->key, CONST_STR_LEN("url.access-deny"))) { + PATCH(access_deny); + } else if (buffer_is_equal_string(du->key, CONST_STR_LEN("url.access-allow"))) { + PATCH(access_allow); + } + } + } + + return 0; +} +#undef PATCH + +/** + * URI handler + * + * we will get called twice: + * - after the clean up of the URL and + * - after the pathinfo checks are done + * + * this handles the issue of trailing slashes + */ +URIHANDLER_FUNC(mod_access_uri_handler) { + plugin_data *p = p_d; + int s_len; + size_t k; + + if (buffer_is_empty(con->uri.path)) return HANDLER_GO_ON; + + mod_access_patch_connection(srv, con, p); + + s_len = buffer_string_length(con->uri.path); + + if (con->conf.log_request_handling) { + log_error_write(srv, __FILE__, __LINE__, "s", + "-- mod_access_uri_handler called"); + } + + for (k = 0; k < p->conf.access_allow->used; ++k) { + data_string *ds = (data_string *)p->conf.access_allow->data[k]; + int ct_len = buffer_string_length(ds->value); + int allowed = 0; + + if (ct_len > s_len) continue; + if (buffer_is_empty(ds->value)) continue; + + /* if we have a case-insensitive FS we have to lower-case the URI here too */ + + if (con->conf.force_lowercase_filenames) { + if (0 == strncasecmp(con->uri.path->ptr + s_len - ct_len, ds->value->ptr, ct_len)) { + allowed = 1; + } + } else { + if (0 == strncmp(con->uri.path->ptr + s_len - ct_len, ds->value->ptr, ct_len)) { + allowed = 1; + } + } + + if (allowed) { + return HANDLER_GO_ON; + } + } + + if (k > 0) { /* have access_allow but none matched */ + con->http_status = 403; + con->mode = DIRECT; + + if (con->conf.log_request_handling) { + log_error_write(srv, __FILE__, __LINE__, "sb", + "url denied as failed to match any from access_allow", con->uri.path); + } + + return HANDLER_FINISHED; + } + + for (k = 0; k < p->conf.access_deny->used; k++) { + data_string *ds = (data_string *)p->conf.access_deny->data[k]; + int ct_len = buffer_string_length(ds->value); + int denied = 0; + + + if (ct_len > s_len) continue; + if (buffer_is_empty(ds->value)) continue; + + /* if we have a case-insensitive FS we have to lower-case the URI here too */ + + if (con->conf.force_lowercase_filenames) { + if (0 == strncasecmp(con->uri.path->ptr + s_len - ct_len, ds->value->ptr, ct_len)) { + denied = 1; + } + } else { + if (0 == strncmp(con->uri.path->ptr + s_len - ct_len, ds->value->ptr, ct_len)) { + denied = 1; + } + } + + if (denied) { + con->http_status = 403; + con->mode = DIRECT; + + if (con->conf.log_request_handling) { + log_error_write(srv, __FILE__, __LINE__, "sb", + "url denied as we match:", ds->value); + } + + return HANDLER_FINISHED; + } + } + + /* not found */ + return HANDLER_GO_ON; +} + + +int mod_access_plugin_init(plugin *p); +int mod_access_plugin_init(plugin *p) { + p->version = LIGHTTPD_VERSION_ID; + p->name = buffer_init_string("access"); + + p->init = mod_access_init; + p->set_defaults = mod_access_set_defaults; + p->handle_uri_clean = mod_access_uri_handler; + p->handle_subrequest_start = mod_access_uri_handler; + p->cleanup = mod_access_free; + + p->data = NULL; + + return 0; +} diff --git a/pool/shard004/C/0098662_t-get_d.c b/pool/shard004/C/0098662_t-get_d.c new file mode 100644 index 0000000000000000000000000000000000000000..0ea9ae89a6ab01f5fddd6cf561c8a6f2eb6a3d8c --- /dev/null +++ b/pool/shard004/C/0098662_t-get_d.c @@ -0,0 +1,155 @@ +/* + Copyright (C) 2012 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 "arf.h" + +int main() +{ + slong iter; + flint_rand_t state; + + flint_printf("get_d...."); + fflush(stdout); + + flint_randinit(state); + + /* test exact roundtrip */ + for (iter = 0; iter < 100000 * arb_test_multiplier(); iter++) + { + arf_t x, z; + double y; + arf_rnd_t rnd; + + arf_init(x); + arf_init(z); + + switch (n_randint(state, 4)) + { + case 0: rnd = ARF_RND_DOWN; break; + case 1: rnd = ARF_RND_UP; break; + case 2: rnd = ARF_RND_FLOOR; break; + case 3: rnd = ARF_RND_CEIL; break; + default: rnd = ARF_RND_NEAR; break; + } + + arf_randtest_special(x, state, 53, 8); + y = arf_get_d(x, rnd); + arf_set_d(z, y); + + if (!arf_equal(x, z)) + { + flint_printf("FAIL:\n\n"); + flint_printf("x = "); arf_print(x); flint_printf("\n\n"); + flint_printf("y = %.17g\n\n", y); + flint_printf("z = "); arf_print(z); flint_printf("\n\n"); + flint_abort(); + } + + arf_clear(x); + arf_clear(z); + } + + /* test rounding */ + for (iter = 0; iter < 100000 * arb_test_multiplier(); iter++) + { + arf_t x, z, w; + arf_rnd_t rnd; + double y; + + arf_init(x); + arf_init(z); + arf_init(w); + + arf_randtest_special(x, state, 300, 8); + + switch (n_randint(state, 4)) + { + case 0: rnd = ARF_RND_DOWN; break; + case 1: rnd = ARF_RND_UP; break; + case 2: rnd = ARF_RND_FLOOR; break; + default: rnd = ARF_RND_CEIL; break; + } + + y = arf_get_d(x, rnd); + arf_set_d(w, y); + + arf_set_round(z, x, 53, rnd); + + if (!arf_equal(w, z)) + { + flint_printf("FAIL:\n\n"); + flint_printf("x = "); arf_print(x); flint_printf("\n\n"); + flint_printf("y = %.17g\n\n", y); + flint_printf("z = "); arf_print(z); flint_printf("\n\n"); + flint_printf("w = "); arf_print(w); flint_printf("\n\n"); + flint_abort(); + } + + arf_clear(x); + arf_clear(z); + arf_clear(w); + } + + /* compare with mpfr */ + for (iter = 0; iter < 100000 * arb_test_multiplier(); iter++) + { + arf_t x, r1, r2; + arf_rnd_t rnd; + mpfr_t t; + double d1, d2; + + arf_init(x); + arf_init(r1); + arf_init(r2); + mpfr_init2(t, 300); + + arf_randtest_special(x, state, 300, 20); + arf_get_mpfr(t, x, MPFR_RNDD); + + switch (n_randint(state, 4)) + { + case 0: rnd = ARF_RND_DOWN; break; + case 1: rnd = ARF_RND_UP; break; + case 2: rnd = ARF_RND_FLOOR; break; + case 3: rnd = ARF_RND_CEIL; break; + default: rnd = ARF_RND_NEAR; break; + } + + d1 = arf_get_d(x, rnd); + d2 = mpfr_get_d(t, rnd_to_mpfr(rnd)); + + arf_set_d(r1, d1); + arf_set_d(r2, d2); + + if (!arf_equal(r1, r2)) + { + flint_printf("FAIL:\n\n"); + flint_printf("rnd = %i\n\n", rnd); + flint_printf("x = "); arf_print(x); flint_printf("\n\n"); + flint_printf("d1 = %.17g\n\n", d1); + flint_printf("d2 = %.17g\n\n", d2); + flint_printf("r1 = "); arf_print(r1); flint_printf("\n\n"); + flint_printf("r2 = "); arf_print(r2); flint_printf("\n\n"); + flint_abort(); + } + + arf_clear(x); + arf_clear(r1); + arf_clear(r2); + mpfr_clear(t); + } + + flint_randclear(state); + flint_cleanup(); + flint_printf("PASS\n"); + return EXIT_SUCCESS; +} + diff --git a/pool/shard004/C/0098663_main.c b/pool/shard004/C/0098663_main.c new file mode 100644 index 0000000000000000000000000000000000000000..e0899480d863715371264e686eadeb34ba0ee8c1 --- /dev/null +++ b/pool/shard004/C/0098663_main.c @@ -0,0 +1,60 @@ +#include + +#include "network.h" +#include "main.h" + +this_t this; + +static int init(conf_t conf) +{ + struct hostent* he; + this.log_level = conf.log_level; + this.use_udp = conf.use_udp; + this.mtu = conf.mtu; + this.host = conf.host; + this.port = conf.port; + this.remote_addr.sin_family = AF_INET; + this.remote_addr.sin_port = htons(conf.port); + if ((he = gethostbyname(conf.host)) == NULL) + { + SYSLOG(LOG_ERR, "Convert ip address error"); + return 0; + } + this.remote_addr.sin_addr = *(struct in_addr*)he->h_addr_list[0]; + + this.buffer = malloc(conf.mtu); + if (this.buffer == NULL) + { + SYSLOG(LOG_ERR, "not enough memory"); + exit(1); + } + this.buffer_len = conf.mtu; + + this.client_fd = this.remote_fd = -1; + + this.bind_fd = bind_and_listen(conf.port); + if (this.bind_fd == -1) return 0; + + return 1; +} + +int main(int argc, char* argv[]) +{ + conf_t conf; + conf.log_level = LOG_INFO; + conf.use_udp = 1; + conf.mtu = 1500; + conf.host = "hk2.q-devel.com"; + conf.port = 6688; + + openlog(argv[0], LOG_PERROR | LOG_CONS | LOG_PID, LOG_LOCAL0); + if (!init(conf)) return 0; + + while (1) + { + loop(); + } + closelog(); + return 0; +} + diff --git a/pool/shard004/C/0098670_klist-demo.c b/pool/shard004/C/0098670_klist-demo.c new file mode 100644 index 0000000000000000000000000000000000000000..4daa5f1002aff026895c0ba9c939391fc53c16ad --- /dev/null +++ b/pool/shard004/C/0098670_klist-demo.c @@ -0,0 +1,106 @@ +#include +#include +#include +#include +#include +#include + +void people_get(struct klist_node* node); +void people_put(struct klist_node* node); +DEFINE_KLIST(g_all_people_klist,people_get,people_put);; +struct people +{ + struct klist_node node; + int age; + char name[20]; + struct kref kref; +}; + +static void release_people(struct kref* ref) +{ + struct people* p = container_of(ref,struct people,kref); + printk("[Note]=[%s]=release memry.\n",__func__); + kfree(p); +} + +void people_get(struct klist_node* node) +{ + struct people* p = container_of(node,struct people,node); + kref_get(&p->kref); +} +void people_put(struct klist_node* node) +{ + struct people* p = container_of(node,struct people,node); + kref_put(&p->kref,release_people); +} +struct people* alloc_people(void) +{ + struct people* p = kmalloc(sizeof(struct people),GFP_KERNEL); + if(p) + { + memset(p,0,sizeof(struct people)); + kref_init(&p->kref); + } + return p; +} +#define PEOPLE_NUM 10 +void build_people_list(void) +{ + int i = 0; + struct people* p = NULL; + for(i = 0; i < PEOPLE_NUM; i++) + { + p = alloc_people(); + p->age = 25 + i; + sprintf(p->name,"%d-name",i); + klist_add_tail(&p->node,&g_all_people_klist); + } +} + +void traverse_people_list(void) +{ + struct klist_iter iter; + klist_iter_init(&g_all_people_klist,&iter); + + struct klist_node* next = NULL; + struct people* p = NULL; + while((next = klist_next(&iter)) != NULL) + { + p = container_of(next,struct people,node); + printk("name:%s,age:%d\n",p->name,p->age); + } + klist_iter_exit(&iter); +} + +void remove_people_list(void) +{ + int i = 0; + struct klist_node* node = NULL; + for(i = 0; i < PEOPLE_NUM; i++) + { + node = container_of(g_all_people_klist.k_list.next,struct klist_node,n_node); + /*必须对people:kref减1,因为在klist_next会调用people_get*/ + kref_put(&(container_of(node,struct people,node)->kref),release_people); + /*释放people接口的最终函数*/ + klist_remove(node); + } + +} + +static int __init klist_demo_init(void) +{ + build_people_list(); + + traverse_people_list(); + + return 0; +} + +static void __exit klist_demo_exit(void) +{ + remove_people_list(); +} + +module_init(klist_demo_init); +module_exit(klist_demo_exit); +MODULE_LICENSE("GPL"); diff --git a/pool/shard004/C/0098671_colorsel.c b/pool/shard004/C/0098671_colorsel.c new file mode 100644 index 0000000000000000000000000000000000000000..db5d542df3cd6537c28600c9ec867278eecc004d --- /dev/null +++ b/pool/shard004/C/0098671_colorsel.c @@ -0,0 +1,139 @@ +/* Color Selector + * + * GtkColorSelection lets the user choose a color. GtkColorSelectionDialog is + * a prebuilt dialog containing a GtkColorSelection. + * + */ + +#include + +static GtkWidget *window = NULL; +static GtkWidget *da; +static GdkColor color; +static GtkWidget *frame; + +/* Expose callback for the drawing area + */ +static gboolean +expose_event_callback (GtkWidget *widget, + GdkEventExpose *event, + gpointer data) +{ + if (widget->window) + { + GtkStyle *style; + + style = gtk_widget_get_style (widget); + + gdk_draw_rectangle (widget->window, + style->bg_gc[GTK_STATE_NORMAL], + TRUE, + event->area.x, event->area.y, + event->area.width, event->area.height); + } + + return TRUE; +} + +static void +change_color_callback (GtkWidget *button, + gpointer data) +{ + GtkWidget *dialog; + GtkColorSelection *colorsel; + gint response; + + dialog = gtk_color_selection_dialog_new ("Changing color"); + + gtk_window_set_transient_for (GTK_WINDOW (dialog), GTK_WINDOW (window)); + + colorsel = GTK_COLOR_SELECTION (GTK_COLOR_SELECTION_DIALOG (dialog)->colorsel); + + gtk_color_selection_set_previous_color (colorsel, &color); + gtk_color_selection_set_current_color (colorsel, &color); + gtk_color_selection_set_has_palette (colorsel, TRUE); + + response = gtk_dialog_run (GTK_DIALOG (dialog)); + + if (response == GTK_RESPONSE_OK) + { + gtk_color_selection_get_current_color (colorsel, + &color); + + gtk_widget_modify_bg (da, GTK_STATE_NORMAL, &color); + } + + gtk_widget_destroy (dialog); +} + +GtkWidget * +do_colorsel (GtkWidget *do_widget) +{ + GtkWidget *vbox; + GtkWidget *button; + GtkWidget *alignment; + + if (!window) + { + color.red = 0; + color.blue = 65535; + color.green = 0; + + window = gtk_window_new (GTK_WINDOW_TOPLEVEL); + gtk_window_set_screen (GTK_WINDOW (window), + gtk_widget_get_screen (do_widget)); + gtk_window_set_title (GTK_WINDOW (window), "Color Selection"); + + g_signal_connect (window, "destroy", + G_CALLBACK (gtk_widget_destroyed), &window); + + gtk_container_set_border_width (GTK_CONTAINER (window), 8); + + vbox = gtk_vbox_new (FALSE, 8); + gtk_container_set_border_width (GTK_CONTAINER (vbox), 8); + gtk_container_add (GTK_CONTAINER (window), vbox); + + /* + * Create the color swatch area + */ + + + frame = gtk_frame_new (NULL); + gtk_frame_set_shadow_type (GTK_FRAME (frame), GTK_SHADOW_IN); + gtk_box_pack_start (GTK_BOX (vbox), frame, TRUE, TRUE, 0); + + da = gtk_drawing_area_new (); + + g_signal_connect (da, "expose_event", + G_CALLBACK (expose_event_callback), NULL); + + /* set a minimum size */ + gtk_widget_set_size_request (da, 200, 200); + /* set the color */ + gtk_widget_modify_bg (da, GTK_STATE_NORMAL, &color); + + gtk_container_add (GTK_CONTAINER (frame), da); + + alignment = gtk_alignment_new (1.0, 0.5, 0.0, 0.0); + + button = gtk_button_new_with_mnemonic ("_Change the above color"); + gtk_container_add (GTK_CONTAINER (alignment), button); + + gtk_box_pack_start (GTK_BOX (vbox), alignment, FALSE, FALSE, 0); + + g_signal_connect (button, "clicked", + G_CALLBACK (change_color_callback), NULL); + } + + if (!gtk_widget_get_visible (window)) + { + gtk_widget_show_all (window); + } + else + { + gtk_widget_destroy (window); + window = NULL; + } + + return window; +} diff --git a/pool/shard004/C/0098674_spi_api.c b/pool/shard004/C/0098674_spi_api.c new file mode 100644 index 0000000000000000000000000000000000000000..a30e1455026946def68d2bd3a0d70bd03b087477 --- /dev/null +++ b/pool/shard004/C/0098674_spi_api.c @@ -0,0 +1,196 @@ +/******************************************************************************* + * Copyright (c) 2016 Maxim Integrated Products, 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 MAXIM INTEGRATED 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 Maxim Integrated + * Products, Inc. shall not be used except as stated in the Maxim Integrated + * Products, Inc. Branding Policy. + * + * The mere transfer of this software does not imply any licenses + * of trade secrets, proprietary technology, copyrights, patents, + * trademarks, maskwork rights, or any other form of intellectual + * property whatsoever. Maxim Integrated Products, Inc. retains all + * ownership rights. + ******************************************************************************* + */ + +#include "mbed_assert.h" +#include "spi_api.h" // mbed HAL +#include "spim_regs.h" // bare metal +#include "spim.h" // Maxim CMSIS driver +#include "pinmap.h" +#include "PeripheralPins.h" + +//****************************************************************************** +void spi_init(spi_t *obj, PinName mosi, PinName miso, PinName sclk, PinName ssel) +{ + // Make sure pins are pointing to the same SPI instance + SPIName spi_mosi = (SPIName)pinmap_peripheral(mosi, PinMap_SPI_MOSI); + SPIName spi_miso = (SPIName)pinmap_peripheral(miso, PinMap_SPI_MISO); + SPIName spi_sclk = (SPIName)pinmap_peripheral(sclk, PinMap_SPI_SCLK); + SPIName spi_ssel = (SPIName)pinmap_peripheral(ssel, PinMap_SPI_SSEL); + + SPIName spi_data = (SPIName)pinmap_merge(spi_mosi, spi_miso); + SPIName spi_cntl; + + // Control is SCK and optionaly SS + if ((SPIName)spi_ssel != (SPIName)NC) { + spi_cntl = (SPIName)pinmap_merge(spi_sclk, spi_ssel); + } else { + spi_cntl = spi_sclk; + } + + SPIName spi = (SPIName)pinmap_merge(spi_data, spi_cntl); + + MBED_ASSERT((SPIName)spi != (SPIName)NC); + + obj->spi = (mxc_spim_regs_t *)spi; + + // Merge pin function requests for use with CMSIS init func + ioman_req_t io_req; + pin_function_t *pin_func; + pin_func = (pin_function_t *)pinmap_find_function(mosi, PinMap_SPI_MOSI); + io_req.value = pin_func->req_val; + pin_func = (pin_function_t *)pinmap_find_function(miso, PinMap_SPI_MISO); + io_req.value |= pin_func->req_val; + pin_func = (pin_function_t *)pinmap_find_function(sclk, PinMap_SPI_SCLK); + io_req.value |= pin_func->req_val; + if ((SPIName)spi_ssel != (SPIName)NC) { + pin_func = (pin_function_t *)pinmap_find_function(ssel, PinMap_SPI_SSEL); + io_req.value |= pin_func->req_val; + } + + // Using req and ack pointers of last pin function lookup + sys_cfg_spim_t sys_cfg; + sys_cfg.io_cfg.req_reg = pin_func->reg_req; + sys_cfg.io_cfg.ack_reg = pin_func->reg_ack; + sys_cfg.io_cfg.req_val = io_req; + sys_cfg.clk_scale = CLKMAN_SCALE_AUTO; + + // Defaults + spim_cfg_t spim_cfg; + spim_cfg.mode = 0; + spim_cfg.ssel_pol = 0; + spim_cfg.baud = 1000000; + + SPIM_Init(obj->spi, &spim_cfg, &sys_cfg); + + obj->index = MXC_SPIM_GET_IDX(obj->spi); +} + +//****************************************************************************** +void spi_format(spi_t *obj, int bits, int mode, int slave) +{ + // Check the validity of the inputs + MBED_ASSERT(bits == 8); + + // Only supports master mode + MBED_ASSERT(!slave); + + // Set the mode + obj->spi->mstr_cfg &= ~(MXC_F_SPIM_MSTR_CFG_SPI_MODE); + obj->spi->mstr_cfg |= (mode << MXC_F_SPIM_MSTR_CFG_SPI_MODE_POS); +} + +//****************************************************************************** +void spi_frequency(spi_t *obj, int hz) +{ + // Maximum frequency is half the system frequency + MBED_ASSERT((unsigned int)hz <= (SystemCoreClock / 2)); + unsigned clocks = ((SystemCoreClock / 2) / hz); + + // Figure out the divider ratio + int clk_div = 1; + while(clk_div < 10) { + if(clocks < 0x10) { + break; + } + clk_div++; + clocks = clocks >> 1; + } + + // Turn on the SPI clock + if(obj->index == 0) { + MXC_CLKMAN->sys_clk_ctrl_11_spi0 = clk_div; + } else if(obj->index == 1) { + MXC_CLKMAN->sys_clk_ctrl_12_spi1 = clk_div; + } else if(obj->index == 2) { + MXC_CLKMAN->sys_clk_ctrl_13_spi2 = clk_div; + } else { + MBED_ASSERT(0); + } + + // Set the number of clocks to hold sclk high and low + MXC_SET_FIELD(&obj->spi->mstr_cfg, + (MXC_F_SPIM_MSTR_CFG_SCK_HI_CLK | MXC_F_SPIM_MSTR_CFG_SCK_LO_CLK), + ((clocks << MXC_F_SPIM_MSTR_CFG_SCK_HI_CLK_POS) | (clocks << MXC_F_SPIM_MSTR_CFG_SCK_LO_CLK_POS))); +} + +//****************************************************************************** +int spi_master_write(spi_t *obj, int value) +{ + spim_req_t req; + uint8_t out; + uint8_t in; + + out = value; + + req.ssel = 0; + req.deass = 0; + req.tx_data = &out; + req.rx_data = ∈ + req.width = SPIM_WIDTH_1; + req.len = 1; + req.ssel = 0; + req.deass = 1; + req.callback = NULL; + + SPIM_Trans(obj->spi, &req); + + return *req.rx_data; +} + +int spi_master_block_write(spi_t *obj, const char *tx_buffer, int tx_length, + char *rx_buffer, int rx_length, char write_fill) { + int total = (tx_length > rx_length) ? tx_length : rx_length; + + for (int i = 0; i < total; i++) { + char out = (i < tx_length) ? tx_buffer[i] : write_fill; + char in = spi_master_write(obj, out); + if (i < rx_length) { + rx_buffer[i] = in; + } + } + + return total; +} + +//****************************************************************************** +int spi_busy(spi_t *obj) +{ + return SPIM_Busy(obj->spi); +} + +//****************************************************************************** +uint8_t spi_get_module(spi_t *obj) +{ + return obj->index; +} + diff --git a/pool/shard004/C/0098679_frontend_salamander.c b/pool/shard004/C/0098679_frontend_salamander.c new file mode 100644 index 0000000000000000000000000000000000000000..900bfb456249bd2dbbe73054a6b3231dfa38ab5e --- /dev/null +++ b/pool/shard004/C/0098679_frontend_salamander.c @@ -0,0 +1,112 @@ +/* RetroArch - A frontend for libretro. + * Copyright (C) 2010-2013 - Hans-Kristian Arntzen + * Copyright (C) 2011-2013 - 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 "../boolean.h" +#include +#include + +#include "../file_ext.h" +#include "frontend_salamander.h" + +#if defined(RARCH_CONSOLE) +#include "frontend_context.h" +frontend_ctx_driver_t *frontend_ctx; +#endif + +#if defined(__CELLOS_LV2__) +#include "platform/platform_ps3.c" +#elif defined(GEKKO) +#include "platform/platform_gx.c" +#elif defined(_XBOX) +#include "platform/platform_xdk.c" +#elif defined(PSP) +#include "platform/platform_psp.c" +#endif + +default_paths_t default_paths; + +//We need to set libretro to the first entry in the cores +//directory so that it will be saved to the config file +static void find_first_libretro_core(char *first_file, + size_t size_of_first_file, const char *dir, + const char * ext) +{ + bool ret = false; + + RARCH_LOG("Searching for valid libretro implementation in: \"%s\".\n", dir); + + struct string_list *list = dir_list_new(dir, ext, false); + if (!list) + { + RARCH_ERR("Couldn't read directory. Cannot infer default libretro core.\n"); + return; + } + + for (size_t i = 0; i < list->size && !ret; i++) + { + RARCH_LOG("Checking library: \"%s\".\n", list->elems[i].data); + const char * libretro_elem = list->elems[i].data; + + if (libretro_elem) + { + char fname[PATH_MAX]; + fill_pathname_base(fname, libretro_elem, sizeof(fname)); + + if (strncmp(fname, SALAMANDER_FILE, sizeof(fname)) == 0) + { + if ((i + 1) == list->size) + { + RARCH_WARN("Entry is RetroArch Salamander itself, but is last entry. No choice but to set it.\n"); + strlcpy(first_file, fname, size_of_first_file); + } + + continue; + } + + strlcpy(first_file, fname, size_of_first_file); + RARCH_LOG("First found libretro core is: \"%s\".\n", first_file); + ret = true; + } + } + + dir_list_free(list); +} + +static int system_ctx_init(void) +{ +#ifdef RARCH_CONSOLE + if ((frontend_ctx = (frontend_ctx_driver_t*)frontend_ctx_init_first()) == NULL) + return -1; +#endif + + return 0; +} + +int main(int argc, char *argv[]) +{ + void *args = NULL; + if (system_ctx_init() != 0) + return 0; + + frontend_ctx->init(); + get_environment_settings(argc, argv, args); + salamander_init_settings(); + frontend_ctx->deinit(); + frontend_ctx->exitspawn(); + + return 1; +} diff --git a/pool/shard004/C/0098686_workqueue_main.c b/pool/shard004/C/0098686_workqueue_main.c new file mode 100644 index 0000000000000000000000000000000000000000..adf6868526728a3cf0a841c6f25e359f13185bc0 --- /dev/null +++ b/pool/shard004/C/0098686_workqueue_main.c @@ -0,0 +1,110 @@ +/**************************************************************************** + * + * 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. + * + ****************************************************************************/ +/**************************************************************************** + * Included Files + ****************************************************************************/ + +#include +#include +#include +#include + +/**************************************************************************** + * Definitions + ****************************************************************************/ + +/**************************************************************************** + * Private Data + ****************************************************************************/ + +/**************************************************************************** + * Private Functions + ****************************************************************************/ +static void wq_test1(FAR void *arg) +{ + systime_t cur_time = 0; + cur_time = clock_systimer(); + + printf("test1 is excuted at (%d) ticks\n", cur_time); +} + +static void wq_test2(FAR void *arg) +{ + systime_t cur_time = 0; + cur_time = clock_systimer(); + + printf("test2 is excuted at (%d) ticks\n", cur_time); +} + +static void wq_test3(FAR void *arg) +{ + systime_t cur_time = 0; + cur_time = clock_systimer(); + + printf("test3 is excuted at (%d) ticks\n", cur_time); +} + +static void wq_test4(FAR void *arg) +{ + systime_t cur_time = 0; + cur_time = clock_systimer(); + + printf("test4 is excuted at (%d) ticks\n", cur_time); +} + +/**************************************************************************** + * Public Functions + ****************************************************************************/ + +/**************************************************************************** + * workqueue_main + ****************************************************************************/ + +#ifdef CONFIG_BUILD_KERNEL +int main(int argc, FAR char *argv[]) +#else +int workqueue_main(int argc, char *argv[]) +#endif +{ + systime_t cur_time; + struct work_s *test_wq1; + struct work_s *test_wq2; + struct work_s *test_wq3; + struct work_s *test_wq4; + + test_wq1 = (struct work_s *)malloc(sizeof(struct work_s)); + test_wq2 = (struct work_s *)malloc(sizeof(struct work_s)); + test_wq3 = (struct work_s *)malloc(sizeof(struct work_s)); + test_wq4 = (struct work_s *)malloc(sizeof(struct work_s)); + + cur_time = clock_systimer(); + + printf("current time is (%d)\n", cur_time); + printf("test1 is queued and will excute it after 50 ticks\n"); + work_queue(HPWORK, test_wq1, wq_test1, NULL, 50); + + printf("test2 is queued and will excute it after 30 ticks\n"); + work_queue(HPWORK, test_wq2, wq_test2, NULL, 30); + + printf("test3 is queued and will excute it after 70 ticks\n"); + work_queue(HPWORK, test_wq3, wq_test3, NULL, 70); + + printf("test4 is queued and will excute it after 90 ticks\n"); + work_queue(HPWORK, test_wq4, wq_test4, NULL, 90); + return 0; +} diff --git a/pool/shard004/C/0098691_setup.c b/pool/shard004/C/0098691_setup.c new file mode 100644 index 0000000000000000000000000000000000000000..c05625975f2c7fb62c2064b628247a3b6ae0d077 --- /dev/null +++ b/pool/shard004/C/0098691_setup.c @@ -0,0 +1,105 @@ +/* + * Renesas Technology Sales HS7751RVoIP Support. + * + * Copyright (C) 2000 Kazumoto Kojima + * + * Modified for HS7751RVoIP by + * Atom Create Engineering Co., Ltd. 2002. + * Lineo uSolutions, Inc. 2003. + */ +#include +#include +#include +#include +#include +#include +#include + +static void hs7751rvoip_power_off(void) +{ + ctrl_outw(ctrl_inw(PA_OUTPORTR) & 0xffdf, PA_OUTPORTR); +} + +void *area5_io8_base; +void *area6_io8_base; +void *area5_io16_base; +void *area6_io16_base; + +static int __init hs7751rvoip_cf_init(void) +{ + pgprot_t prot; + unsigned long paddrbase; + + /* open I/O area window */ + paddrbase = virt_to_phys((void *)(PA_AREA5_IO+0x00000800)); + prot = PAGE_KERNEL_PCC(1, _PAGE_PCC_COM16); + area5_io16_base = p3_ioremap(paddrbase, PAGE_SIZE, prot.pgprot); + if (!area5_io16_base) { + printk("allocate_cf_area : can't open CF I/O window!\n"); + return -ENOMEM; + } + + /* XXX : do we need attribute and common-memory area also? */ + + paddrbase = virt_to_phys((void *)PA_AREA6_IO); +#if defined(CONFIG_HS7751RVOIP_CODEC) + prot = PAGE_KERNEL_PCC(0, _PAGE_PCC_COM8); +#else + prot = PAGE_KERNEL_PCC(0, _PAGE_PCC_IO8); +#endif + area6_io8_base = p3_ioremap(paddrbase, PAGE_SIZE, prot.pgprot); + if (!area6_io8_base) { + printk("allocate_cf_area : can't open CODEC I/O 8bit window!\n"); + return -ENOMEM; + } + prot = PAGE_KERNEL_PCC(0, _PAGE_PCC_IO16); + area6_io16_base = p3_ioremap(paddrbase, PAGE_SIZE, prot.pgprot); + if (!area6_io16_base) { + printk("allocate_cf_area : can't open CODEC I/O 16bit window!\n"); + return -ENOMEM; + } + + return 0; +} +device_initcall(hs7751rvoip_cf_init); + +/* + * Initialize the board + */ +static void __init hs7751rvoip_setup(char **cmdline_p) +{ + ctrl_outb(0xf0, PA_OUTPORTR); + pm_power_off = hs7751rvoip_power_off; + + printk(KERN_INFO "Renesas Technology Sales HS7751RVoIP-2 support.\n"); +} + +static struct sh_machine_vector mv_hs7751rvoip __initmv = { + .mv_name = "HS7751RVoIP", + .mv_setup = hs7751rvoip_setup, + .mv_nr_irqs = 72, + + .mv_inb = hs7751rvoip_inb, + .mv_inw = hs7751rvoip_inw, + .mv_inl = hs7751rvoip_inl, + .mv_outb = hs7751rvoip_outb, + .mv_outw = hs7751rvoip_outw, + .mv_outl = hs7751rvoip_outl, + + .mv_inb_p = hs7751rvoip_inb_p, + .mv_inw_p = hs7751rvoip_inw, + .mv_inl_p = hs7751rvoip_inl, + .mv_outb_p = hs7751rvoip_outb_p, + .mv_outw_p = hs7751rvoip_outw, + .mv_outl_p = hs7751rvoip_outl, + + .mv_insb = hs7751rvoip_insb, + .mv_insw = hs7751rvoip_insw, + .mv_insl = hs7751rvoip_insl, + .mv_outsb = hs7751rvoip_outsb, + .mv_outsw = hs7751rvoip_outsw, + .mv_outsl = hs7751rvoip_outsl, + + .mv_init_irq = init_hs7751rvoip_IRQ, + .mv_ioport_map = hs7751rvoip_ioport_map, +}; diff --git a/pool/shard004/C/0098692_MassStorageClassDevice.c b/pool/shard004/C/0098692_MassStorageClassDevice.c new file mode 100644 index 0000000000000000000000000000000000000000..d0907963a30f307e849a9567d29f9cac53207cec --- /dev/null +++ b/pool/shard004/C/0098692_MassStorageClassDevice.c @@ -0,0 +1,215 @@ +/* + LUFA Library + Copyright (C) Dean Camera, 2014. + + dean [at] fourwalledcubicle [dot] com + www.lufa-lib.org +*/ + +/* + Copyright 2014 Dean Camera (dean [at] fourwalledcubicle [dot] com) + + 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 the copyright notice and this + permission notice and warranty disclaimer appear in supporting + documentation, and that the name of the author not be used in + advertising or publicity pertaining to distribution of the + software without specific, written prior permission. + + 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, 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. +*/ + +#define __INCLUDE_FROM_USB_DRIVER +#include "../../Core/USBMode.h" + +#if defined(USB_CAN_BE_DEVICE) + +#define __INCLUDE_FROM_MS_DRIVER +#define __INCLUDE_FROM_MASSSTORAGE_DEVICE_C +#include "MassStorageClassDevice.h" + +void MS_Device_ProcessControlRequest(USB_ClassInfo_MS_Device_t* const MSInterfaceInfo) +{ + if (!(Endpoint_IsSETUPReceived())) + return; + + if (USB_ControlRequest.wIndex != MSInterfaceInfo->Config.InterfaceNumber) + return; + + switch (USB_ControlRequest.bRequest) + { + case MS_REQ_MassStorageReset: + if (USB_ControlRequest.bmRequestType == (REQDIR_HOSTTODEVICE | REQTYPE_CLASS | REQREC_INTERFACE)) + { + Endpoint_ClearSETUP(); + Endpoint_ClearStatusStage(); + + MSInterfaceInfo->State.IsMassStoreReset = true; + } + + break; + case MS_REQ_GetMaxLUN: + if (USB_ControlRequest.bmRequestType == (REQDIR_DEVICETOHOST | REQTYPE_CLASS | REQREC_INTERFACE)) + { + Endpoint_ClearSETUP(); + while (!(Endpoint_IsINReady())); + Endpoint_Write_8(MSInterfaceInfo->Config.TotalLUNs - 1); + Endpoint_ClearIN(); + Endpoint_ClearStatusStage(); + } + + break; + } +} + +bool MS_Device_ConfigureEndpoints(USB_ClassInfo_MS_Device_t* const MSInterfaceInfo) +{ + memset(&MSInterfaceInfo->State, 0x00, sizeof(MSInterfaceInfo->State)); + + MSInterfaceInfo->Config.DataINEndpoint.Type = EP_TYPE_BULK; + MSInterfaceInfo->Config.DataOUTEndpoint.Type = EP_TYPE_BULK; + + if (!(Endpoint_ConfigureEndpointTable(&MSInterfaceInfo->Config.DataINEndpoint, 1))) + return false; + + if (!(Endpoint_ConfigureEndpointTable(&MSInterfaceInfo->Config.DataOUTEndpoint, 1))) + return false; + + return true; +} + +void MS_Device_USBTask(USB_ClassInfo_MS_Device_t* const MSInterfaceInfo) +{ + if (USB_DeviceState != DEVICE_STATE_Configured) + return; + + Endpoint_SelectEndpoint(MSInterfaceInfo->Config.DataOUTEndpoint.Address); + + if (Endpoint_IsOUTReceived()) + { + if (MS_Device_ReadInCommandBlock(MSInterfaceInfo)) + { + if (MSInterfaceInfo->State.CommandBlock.Flags & MS_COMMAND_DIR_DATA_IN) + Endpoint_SelectEndpoint(MSInterfaceInfo->Config.DataINEndpoint.Address); + + bool SCSICommandResult = CALLBACK_MS_Device_SCSICommandReceived(MSInterfaceInfo); + + MSInterfaceInfo->State.CommandStatus.Status = (SCSICommandResult) ? MS_SCSI_COMMAND_Pass : MS_SCSI_COMMAND_Fail; + MSInterfaceInfo->State.CommandStatus.Signature = CPU_TO_LE32(MS_CSW_SIGNATURE); + MSInterfaceInfo->State.CommandStatus.Tag = MSInterfaceInfo->State.CommandBlock.Tag; + MSInterfaceInfo->State.CommandStatus.DataTransferResidue = MSInterfaceInfo->State.CommandBlock.DataTransferLength; + + if (!(SCSICommandResult) && (le32_to_cpu(MSInterfaceInfo->State.CommandStatus.DataTransferResidue))) + Endpoint_StallTransaction(); + + MS_Device_ReturnCommandStatus(MSInterfaceInfo); + } + } + + if (MSInterfaceInfo->State.IsMassStoreReset) + { + Endpoint_ResetEndpoint(MSInterfaceInfo->Config.DataOUTEndpoint.Address); + Endpoint_ResetEndpoint(MSInterfaceInfo->Config.DataINEndpoint.Address); + + Endpoint_SelectEndpoint(MSInterfaceInfo->Config.DataOUTEndpoint.Address); + Endpoint_ClearStall(); + Endpoint_ResetDataToggle(); + Endpoint_SelectEndpoint(MSInterfaceInfo->Config.DataINEndpoint.Address); + Endpoint_ClearStall(); + Endpoint_ResetDataToggle(); + + MSInterfaceInfo->State.IsMassStoreReset = false; + } +} + +static bool MS_Device_ReadInCommandBlock(USB_ClassInfo_MS_Device_t* const MSInterfaceInfo) +{ + uint16_t BytesProcessed; + + Endpoint_SelectEndpoint(MSInterfaceInfo->Config.DataOUTEndpoint.Address); + + BytesProcessed = 0; + while (Endpoint_Read_Stream_LE(&MSInterfaceInfo->State.CommandBlock, + (sizeof(MS_CommandBlockWrapper_t) - 16), &BytesProcessed) == + ENDPOINT_RWSTREAM_IncompleteTransfer) + { + if (MSInterfaceInfo->State.IsMassStoreReset) + return false; + } + + if ((MSInterfaceInfo->State.CommandBlock.Signature != CPU_TO_LE32(MS_CBW_SIGNATURE)) || + (MSInterfaceInfo->State.CommandBlock.LUN >= MSInterfaceInfo->Config.TotalLUNs) || + (MSInterfaceInfo->State.CommandBlock.Flags & 0x1F) || + (MSInterfaceInfo->State.CommandBlock.SCSICommandLength == 0) || + (MSInterfaceInfo->State.CommandBlock.SCSICommandLength > 16)) + { + Endpoint_StallTransaction(); + Endpoint_SelectEndpoint(MSInterfaceInfo->Config.DataINEndpoint.Address); + Endpoint_StallTransaction(); + + return false; + } + + BytesProcessed = 0; + while (Endpoint_Read_Stream_LE(&MSInterfaceInfo->State.CommandBlock.SCSICommandData, + MSInterfaceInfo->State.CommandBlock.SCSICommandLength, &BytesProcessed) == + ENDPOINT_RWSTREAM_IncompleteTransfer) + { + if (MSInterfaceInfo->State.IsMassStoreReset) + return false; + } + + Endpoint_ClearOUT(); + + return true; +} + +static void MS_Device_ReturnCommandStatus(USB_ClassInfo_MS_Device_t* const MSInterfaceInfo) +{ + Endpoint_SelectEndpoint(MSInterfaceInfo->Config.DataOUTEndpoint.Address); + + while (Endpoint_IsStalled()) + { + #if !defined(INTERRUPT_CONTROL_ENDPOINT) + USB_USBTask(); + #endif + + if (MSInterfaceInfo->State.IsMassStoreReset) + return; + } + + Endpoint_SelectEndpoint(MSInterfaceInfo->Config.DataINEndpoint.Address); + + while (Endpoint_IsStalled()) + { + #if !defined(INTERRUPT_CONTROL_ENDPOINT) + USB_USBTask(); + #endif + + if (MSInterfaceInfo->State.IsMassStoreReset) + return; + } + + uint16_t BytesProcessed = 0; + while (Endpoint_Write_Stream_LE(&MSInterfaceInfo->State.CommandStatus, + sizeof(MS_CommandStatusWrapper_t), &BytesProcessed) == + ENDPOINT_RWSTREAM_IncompleteTransfer) + { + if (MSInterfaceInfo->State.IsMassStoreReset) + return; + } + + Endpoint_ClearIN(); +} + +#endif + diff --git a/pool/shard004/C/0098699_romstage.c b/pool/shard004/C/0098699_romstage.c new file mode 100644 index 0000000000000000000000000000000000000000..2ed22824188d67ca91c62cfef9b5481d32f6274a --- /dev/null +++ b/pool/shard004/C/0098699_romstage.c @@ -0,0 +1,348 @@ +/* + * This file is part of the coreboot project. + * + * Copyright (C) 2007-2010 coresystems GmbH + * Copyright (C) 2011 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., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "northbridge/intel/sandybridge/sandybridge.h" +#include "northbridge/intel/sandybridge/raminit.h" +#include "southbridge/intel/bd82x6x/pch.h" +#include "southbridge/intel/bd82x6x/gpio.h" +#include +#include +#include +#include "gpio.h" +#if CONFIG_CHROMEOS +#include +#endif +#include +#include +#include "ec.h" +#include "onboard.h" + +static void pch_enable_lpc(void) +{ + /* + * Enable: + * EC Decode Range Port62/66 + * SuperIO Port2E/2F + * PS/2 Keyboard/Mouse Port60/64 + * FDD Port3F0h-3F5h and Port3F7h + */ + pci_write_config16(PCH_LPC_DEV, LPC_EN, KBC_LPC_EN | MC_LPC_EN | + CNF1_LPC_EN | FDD_LPC_EN); + + /* Stout EC Decode Range Port68/6C */ + pci_write_config32(PCH_LPC_DEV, LPC_GEN1_DEC, (0x68 | 0x40001)); +} + +static void rcba_config(void) +{ + u32 reg32; + + /* + * GFX INTA -> PIRQA (MSI) + * D20IP_XHCI XHCI INTA -> PIRQD (MSI) + * D26IP_E2P EHCI #2 INTA -> PIRQF + * D27IP_ZIP HDA INTA -> PIRQA (MSI) + * D28IP_P2IP WLAN INTA -> PIRQD + * D28IP_P3IP Card Reader INTB -> PIRQE + * D28IP_P6IP LAN INTC -> PIRQB + * D29IP_E1P EHCI #1 INTA -> PIRQD + * D31IP_SIP SATA INTA -> PIRQB (MSI) + * D31IP_SMIP SMBUS INTB -> PIRQH + */ + + /* Device interrupt pin register (board specific) */ + RCBA32(D31IP) = (NOINT << D31IP_TTIP) | (NOINT << D31IP_SIP2) | + (INTB << D31IP_SMIP) | (INTA << D31IP_SIP); + RCBA32(D30IP) = (NOINT << D30IP_PIP); + RCBA32(D29IP) = (INTA << D29IP_E1P); + RCBA32(D28IP) = (NOINT << D28IP_P1IP) | (INTA << D28IP_P2IP) | + (INTB << D28IP_P3IP) | (NOINT << D28IP_P4IP) | + (NOINT << D28IP_P5IP) | (INTC << D28IP_P6IP) | + (NOINT << D28IP_P7IP) | (NOINT << D28IP_P8IP); + RCBA32(D27IP) = (INTA << D27IP_ZIP); + RCBA32(D26IP) = (INTA << D26IP_E2P); + RCBA32(D25IP) = (NOINT << D25IP_LIP); + RCBA32(D22IP) = (NOINT << D22IP_MEI1IP); + RCBA32(D20IP) = (INTA << D20IP_XHCIIP); + + /* Device interrupt route registers */ + DIR_ROUTE(D31IR, PIRQB, PIRQH, PIRQA, PIRQC); + DIR_ROUTE(D29IR, PIRQD, PIRQE, PIRQF, PIRQG); + DIR_ROUTE(D28IR, PIRQD, PIRQE, PIRQB, PIRQC); + DIR_ROUTE(D27IR, PIRQA, PIRQB, PIRQC, PIRQD); + DIR_ROUTE(D26IR, PIRQF, PIRQB, PIRQC, PIRQD); + DIR_ROUTE(D25IR, PIRQA, PIRQB, PIRQC, PIRQD); + DIR_ROUTE(D22IR, PIRQA, PIRQB, PIRQC, PIRQD); + DIR_ROUTE(D20IR, PIRQD, PIRQE, PIRQF, PIRQG); + + /* Enable IOAPIC (generic) */ + RCBA16(OIC) = 0x0100; + /* PCH BWG says to read back the IOAPIC enable register */ + (void) RCBA16(OIC); + + /* Disable unused devices (board specific) */ + reg32 = RCBA32(FD); + reg32 |= PCH_DISABLE_ALWAYS; + /* Disable PCI bridge so MRC does not probe this bus */ + reg32 |= PCH_DISABLE_P2P; + RCBA32(FD) = reg32; +} + +// FIXME, this function is generic code that should go to sb/... or +// nb/../early_init.c +static void early_pch_init(void) +{ + // Nothing to do for stout +} + + /* + * The Stout EC needs to be reset to RW mode. It is important that + * the RTC_PWR_STS is not set until ramstage EC init. + */ +static void early_ec_init(void) +{ + u8 ec_status = ec_read(EC_STATUS_REG); + int rec_mode = get_recovery_mode_switch(); + + if (((ec_status & 0x3) == EC_IN_RO_MODE) || + ((ec_status & 0x3) == EC_IN_RECOVERY_MODE)) { + + printk(BIOS_DEBUG, "EC Cold Boot Detected\n"); + if (!rec_mode) { + /* + * Tell EC to exit RO mode + */ + printk(BIOS_DEBUG, "EC will exit RO mode and boot normally\n"); + ec_write_cmd(EC_CMD_EXIT_BOOT_BLOCK); + die("wait for ec to reset"); + } + } else { + printk(BIOS_DEBUG, "EC Warm Boot Detected\n"); + ec_write_cmd(EC_CMD_WARM_RESET); + } +} + +void main(unsigned long bist) +{ + int boot_mode = 0; + int cbmem_was_initted; + u32 pm1_cnt; + u16 pm1_sts; + + uint64_t start_romstage_time; + uint64_t before_dram_time; + uint64_t after_dram_time; + uint64_t base_time = + (uint64_t)pci_read_config32(PCI_DEV(0, 0x1f, 2), 0xd0) << 32 || + pci_read_config32(PCI_DEV(0, 0x00, 0), 0xdc); + + struct pei_data pei_data = { + pei_version: PEI_VERSION, + mchbar: (uintptr_t)DEFAULT_MCHBAR, + dmibar: (uintptr_t)DEFAULT_DMIBAR, + epbar: DEFAULT_EPBAR, + pciexbar: CONFIG_MMCONF_BASE_ADDRESS, + smbusbar: SMBUS_IO_BASE, + wdbbar: 0x4000000, + wdbsize: 0x1000, + hpet_address: CONFIG_HPET_ADDRESS, + rcba: (uintptr_t)DEFAULT_RCBABASE, + pmbase: DEFAULT_PMBASE, + gpiobase: DEFAULT_GPIOBASE, + thermalbase: 0xfed08000, + system_type: 0, // 0 Mobile, 1 Desktop/Server + tseg_size: CONFIG_SMM_TSEG_SIZE, + spd_addresses: { 0xA0, 0x00,0xA4,0x00 }, + ts_addresses: { 0x00, 0x00, 0x00, 0x00 }, + ec_present: 1, + // 0 = leave channel enabled + // 1 = disable dimm 0 on channel + // 2 = disable dimm 1 on channel + // 3 = disable dimm 0+1 on channel + dimm_channel0_disabled: 2, + dimm_channel1_disabled: 2, + max_ddr3_freq: 1600, + usb_port_config: { + /* enabled usb oc pin length */ + { 1, 0, 0x0040 }, /* P0: USB 3.0 1 (OC0) */ + { 1, 0, 0x0040 }, /* P1: USB 3.0 2 (OC0) */ + { 0, 1, 0x0000 }, /* P2: Empty */ + { 1, 1, 0x0040 }, /* P3: Camera (no OC) */ + { 1, 1, 0x0040 }, /* P4: WLAN (no OC) */ + { 1, 1, 0x0040 }, /* P5: WWAN (no OC) */ + { 0, 1, 0x0000 }, /* P6: Empty */ + { 0, 1, 0x0000 }, /* P7: Empty */ + { 0, 5, 0x0000 }, /* P8: Empty */ + { 1, 4, 0x0040 }, /* P9: USB 2.0 (AUO4) (OC4) */ + { 0, 5, 0x0000 }, /* P10: Empty */ + { 0, 5, 0x0000 }, /* P11: Empty */ + { 0, 5, 0x0000 }, /* P12: Empty */ + { 1, 5, 0x0040 }, /* P13: Bluetooth (no OC) */ + }, + usb3: { + mode: XHCI_MODE, + hs_port_switch_mask: XHCI_PORTS, + preboot_support: XHCI_PREBOOT, + xhci_streams: XHCI_STREAMS, + }, + }; + + start_romstage_time = timestamp_get(); + + if (bist == 0) + enable_lapic(); + + pch_enable_lpc(); + + /* Enable GPIOs */ + pci_write_config32(PCH_LPC_DEV, GPIO_BASE, DEFAULT_GPIOBASE|1); + pci_write_config8(PCH_LPC_DEV, GPIO_CNTL, 0x10); + setup_pch_gpios(&stout_gpio_map); + + /* Initialize console device(s) */ + console_init(); + + /* Halt if there was a built in self test failure */ + report_bist_failure(bist); + + if (MCHBAR16(SSKPD) == 0xCAFE) { + printk(BIOS_DEBUG, "soft reset detected\n"); + boot_mode = 1; + + /* System is not happy after keyboard reset... */ + printk(BIOS_DEBUG, "Issuing CF9 warm reset\n"); + outb(0x6, 0xcf9); + hlt(); + } + + + /* Perform some early chipset initialization required + * before RAM initialization can work + */ + sandybridge_early_initialization(SANDYBRIDGE_MOBILE); + printk(BIOS_DEBUG, "Back from sandybridge_early_initialization()\n"); + + /* Check PM1_STS[15] to see if we are waking from Sx */ + pm1_sts = inw(DEFAULT_PMBASE + PM1_STS); + + /* Read PM1_CNT[12:10] to determine which Sx state */ + pm1_cnt = inl(DEFAULT_PMBASE + PM1_CNT); + + if ((pm1_sts & WAK_STS) && ((pm1_cnt >> 10) & 7) == 5) { +#if CONFIG_HAVE_ACPI_RESUME + printk(BIOS_DEBUG, "Resume from S3 detected.\n"); + boot_mode = 2; + /* Clear SLP_TYPE. This will break stage2 but + * we care for that when we get there. + */ + outl(pm1_cnt & ~(7 << 10), DEFAULT_PMBASE + PM1_CNT); +#else + printk(BIOS_DEBUG, "Resume from S3 detected, but disabled.\n"); +#endif + } + + /* Do ec reset as early as possible, but skip it on S3 resume */ + if (boot_mode < 2) + early_ec_init(); + + post_code(0x38); + /* Enable SPD ROMs and DDR-III DRAM */ + enable_smbus(); + + /* Prepare USB controller early in S3 resume */ + if (boot_mode == 2) + enable_usb_bar(); + + post_code(0x39); + + post_code(0x3a); + pei_data.boot_mode = boot_mode; + + before_dram_time = timestamp_get(); + + sdram_initialize(&pei_data); + + after_dram_time = timestamp_get(); + + post_code(0x3b); + /* Perform some initialization that must run before stage2 */ + early_pch_init(); + post_code(0x3c); + + rcba_config(); + post_code(0x3d); + + quick_ram_check(); + post_code(0x3e); + + MCHBAR16(SSKPD) = 0xCAFE; +#if CONFIG_EARLY_CBMEM_INIT + cbmem_was_initted = !cbmem_initialize(); +#else + cbmem_was_initted = cbmem_reinit((uint64_t) (get_top_of_ram() + - HIGH_MEMORY_SIZE)); +#endif + +#if CONFIG_HAVE_ACPI_RESUME + /* If there is no high memory area, we didn't boot before, so + * this is not a resume. In that case we just create the cbmem toc. + */ + + *(u32 *)CBMEM_BOOT_MODE = 0; + *(u32 *)CBMEM_RESUME_BACKUP = 0; + + if ((boot_mode == 2) && cbmem_was_initted) { + void *resume_backup_memory = cbmem_find(CBMEM_ID_RESUME); + if (resume_backup_memory) { + *(u32 *)CBMEM_BOOT_MODE = boot_mode; + *(u32 *)CBMEM_RESUME_BACKUP = (u32)resume_backup_memory; + } + /* Magic for S3 resume */ + pci_write_config32(PCI_DEV(0, 0x00, 0), SKPAD, 0xcafed00d); + } else if (boot_mode == 2) { + /* Failed S3 resume, reset to come up cleanly */ + outb(0x6, 0xcf9); + hlt(); + } else { + pci_write_config32(PCI_DEV(0, 0x00, 0), SKPAD, 0xcafebabe); + } +#endif + post_code(0x3f); +#if CONFIG_CHROMEOS + init_chromeos(boot_mode); +#endif + + timestamp_init(base_time); + timestamp_add(TS_START_ROMSTAGE, start_romstage_time ); + timestamp_add(TS_BEFORE_INITRAM, before_dram_time ); + timestamp_add(TS_AFTER_INITRAM, after_dram_time ); + timestamp_add_now(TS_END_ROMSTAGE); +} diff --git a/pool/shard004/C/0098703_io-reauthenticate.c b/pool/shard004/C/0098703_io-reauthenticate.c new file mode 100644 index 0000000000000000000000000000000000000000..1d2d935a645381445071a5e68ae97c813f9f3f2e --- /dev/null +++ b/pool/shard004/C/0098703_io-reauthenticate.c @@ -0,0 +1,53 @@ +/* + Copyright (C) 1995,96,2000,01 Free Software Foundation, Inc. + Written by Michael I. Bushnell, p/BSG. + + This file is part of the GNU Hurd. + + The GNU Hurd is free software; you can 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. + + The GNU Hurd is distributed in the hope that it will be useful, but + WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111, USA. */ + +#include "netfs.h" +#include "io_S.h" + +error_t +netfs_S_io_reauthenticate (struct protid *user, mach_port_t rend_port) +{ + error_t err; + struct protid *newpi; + mach_port_t newright; + + if (!user) + return EOPNOTSUPP; + + pthread_mutex_lock (&user->po->np->lock); + newpi = netfs_make_protid (user->po, 0); + + newright = ports_get_send_right (newpi); + assert (newright != MACH_PORT_NULL); + + err = iohelp_reauth (&newpi->user, netfs_auth_server_port, rend_port, + newright, 1); + + mach_port_deallocate (mach_task_self (), rend_port); + mach_port_deallocate (mach_task_self (), newright); + + mach_port_move_member (mach_task_self (), newpi->pi.port_right, + netfs_port_bucket->portset); + + pthread_mutex_unlock (&user->po->np->lock); + ports_port_deref (newpi); + + return err; +} diff --git a/pool/shard004/C/0098704_amplitudeloc.c b/pool/shard004/C/0098704_amplitudeloc.c new file mode 100644 index 0000000000000000000000000000000000000000..00dc3213445eb2b48d2f2c544c06eb7b772dedec --- /dev/null +++ b/pool/shard004/C/0098704_amplitudeloc.c @@ -0,0 +1,71 @@ +#include +/****************************************************************** + * This is a c script for getting the max AMP and location of array + * + * Input: + * double* array + * int len + * + * Output: + * int* max_amp_loc + * double* amplitude + * int flag + * flag == -1 return the negative amplitude and loc + * flag == 1 return the positive amplitude and loc + * flag == 0 return the greater AMP between negative and positive AMP and loc + * + * DATE: Keywords: + * Reference: +******************************************************************/ + +int amplitudeloc(double* array, int len, int* max_amp_loc, double* amplitude, int flag) +{ + double AMP_nega = 0; + double AMP_posi = 0; + int icount; + int max_loc; + int min_loc; + + for(icount = 0; icount < len ; icount ++) + { + if( array[icount] > AMP_posi ) + { + AMP_posi = array[icount]; + max_loc = icount; + } + if( array[icount] < AMP_nega ) + { + AMP_nega = array[icount]; + min_loc = icount; + } + } + + + // determine which kind of AMP to return + if(flag == 1) + { + *max_amp_loc = max_loc; + *amplitude = AMP_posi; + } + else if(flag == -1) + { + *max_amp_loc = min_loc; + *amplitude = AMP_nega; + } + if(flag == 0) + { + if( fabs(AMP_posi) >= fabs(AMP_nega) ) + { + *max_amp_loc = max_loc; + *amplitude = AMP_posi; + } + else + { + *max_amp_loc = min_loc; + *amplitude = AMP_nega; + } + } + + return 0; +} + diff --git a/pool/shard004/C/0098706_float_init_rom.c b/pool/shard004/C/0098706_float_init_rom.c new file mode 100644 index 0000000000000000000000000000000000000000..3dbefa674659d210952aadb734c850949b405989 --- /dev/null +++ b/pool/shard004/C/0098706_float_init_rom.c @@ -0,0 +1,70 @@ +/* + * Copyright (c) 2020 Raspberry Pi (Trading) Ltd. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +#include +#include "pico/bootrom.h" +#include "pico/bootrom/sf_table.h" + +// NOTE THIS FUNCTION TABLE IS NOT PUBLIC OR NECESSARILY COMPLETE... +// IT IS ***NOT*** SAFE TO CALL THESE FUNCTION POINTERS FROM ARBITRARY CODE +uint32_t sf_table[SF_TABLE_V2_SIZE / 2]; +void *sf_clz_func; + +#if !PICO_FLOAT_SUPPORT_ROM_V1 +static __attribute__((noreturn)) void missing_float_func_shim() { + panic(""); +} +#endif + +void __aeabi_float_init() { + int rom_version = rp2040_rom_version(); + void *rom_table = rom_data_lookup(rom_table_code('S', 'F')); +#if PICO_FLOAT_SUPPORT_ROM_V1 + if (rom_version == 1) { + memcpy(&sf_table, rom_table, SF_TABLE_V1_SIZE); + extern void float_table_shim_on_use_helper(); + // todo replace NDEBUG with a more exclusive assertion guard +#ifndef NDEBUG + if (*(uint16_t *)0x29ee != 0x0fc4 || // this is packx + *(uint16_t *)0x29c0 != 0x0dc2 || // this is upackx + *(uint16_t *)0x2b96 != 0xb5c0 || // this is cordic_vec + *(uint16_t *)0x2b18 != 0x2500 || // this is packretns + *(uint16_t *)0x2acc != 0xb510 || // this is float2fix + *(uint32_t *)0x2cfc != 0x6487ed51 // pi_q29 + ) { + panic(""); + } +#endif + + // this is a little tricky.. we only want to pull in a shim if the corresponding function + // is called. to that end we include a SVC instruction with the table offset as the call number + // followed by the shim function pointer inside the actual wrapper function. that way if the wrapper + // function is garbage collected, so is the shim function. + // + // float_table_shim_on_use_helper expects this SVC instruction in the calling code soon after the address + // pointed to by IP and patches the float_table entry with the real shim the first time the function is called. + + for(uint i=SF_TABLE_V1_SIZE/4; i= 2) { + assert(*((uint8_t *)(rom_table-2)) * 4 >= SF_TABLE_V2_SIZE); + memcpy(&sf_table, rom_table, SF_TABLE_V2_SIZE); + } + sf_clz_func = rom_func_lookup(rom_table_code('L', '3')); +} diff --git a/pool/shard004/C/0098709_SubAllocatorBrimstone.c b/pool/shard004/C/0098709_SubAllocatorBrimstone.c new file mode 100644 index 0000000000000000000000000000000000000000..5641016184053e4dcbb83b9fefaf3c7b33700263 --- /dev/null +++ b/pool/shard004/C/0098709_SubAllocatorBrimstone.c @@ -0,0 +1,183 @@ +#include "SubAllocatorBrimstone.h" + +#include +#include + +#define N1 4 +#define N2 4 +#define N3 4 +#define N4 ((128+3-1*N1-2*N2-3*N3)/4) +#define UNIT_SIZE 12 +#define N_INDEXES (N1+N2+N3+N4) + +static void InsertNode(PPMdSubAllocatorBrimstone *self,void *p,int index); +static void *RemoveNode(PPMdSubAllocatorBrimstone *self,int index); +static unsigned int I2B(PPMdSubAllocatorBrimstone *self,int index); +static void SplitBlock(PPMdSubAllocatorBrimstone *self,void *pv,int oldindex,int newindex); +//static uint32_t GetUsedMemory(PPMdSubAllocatorBrimstone *self); + +static void InitBrimstone(PPMdSubAllocatorBrimstone *self); +static uint32_t AllocContextBrimstone(PPMdSubAllocatorBrimstone *self); +static uint32_t AllocUnitsBrimstone(PPMdSubAllocatorBrimstone *self,int num); +static uint32_t ExpandUnitsBrimstone(PPMdSubAllocatorBrimstone *self,uint32_t oldoffs,int oldnum); +static uint32_t ShrinkUnitsBrimstone(PPMdSubAllocatorBrimstone *self,uint32_t oldoffs,int oldnum,int newnum); +static void FreeUnitsBrimstone(PPMdSubAllocatorBrimstone *self,uint32_t offs,int num); + + + + +PPMdSubAllocatorBrimstone *CreateSubAllocatorBrimstone(int size) +{ + PPMdSubAllocatorBrimstone *self=malloc(sizeof(PPMdSubAllocatorBrimstone)+size); + if(!self) return NULL; + + self->core.Init=(void *)InitBrimstone; + self->core.AllocContext=(void *)AllocContextBrimstone; + self->core.AllocUnits=(void *)AllocUnitsBrimstone; + self->core.ExpandUnits=(void *)ExpandUnitsBrimstone; + self->core.ShrinkUnits=(void *)ShrinkUnitsBrimstone; + self->core.FreeUnits=(void *)FreeUnitsBrimstone; + + self->SubAllocatorSize=size; + + for(int i=0;iIndex2Units[i]=1+i; + for(int i=0;iIndex2Units[N1+i]=2+N1+i*2; + for(int i=0;iIndex2Units[N1+N2+i]=3+N1+2*N2+i*3; + for(int i=0;iIndex2Units[N1+N2+N3+i]=4+N1+2*N2+3*N3+i*4; + + int i=0; + for(int k=0;k<128;k++) + { + if(self->Index2Units[i]Units2Index[k]=i; + } + + return self; +} + +void FreeSubAllocatorBrimstone(PPMdSubAllocatorBrimstone *self) +{ + free(self); +} + + + +static void InitBrimstone(PPMdSubAllocatorBrimstone *self) +{ + memset(self->FreeList,0,sizeof(self->FreeList)); + + self->LowUnit=self->HeapStart; + self->HighUnit=self->HeapStart+UNIT_SIZE*(self->SubAllocatorSize/UNIT_SIZE); +} + +static uint32_t AllocContextBrimstone(PPMdSubAllocatorBrimstone *self) +{ + if(self->HighUnit>self->LowUnit) + { + self->HighUnit-=UNIT_SIZE; + return PointerToOffset(self,self->HighUnit); + } + + return AllocUnitsBrimstone(self,1); +} + +static uint32_t AllocUnitsBrimstone(PPMdSubAllocatorBrimstone *self,int num) +{ + int index=self->Units2Index[num-1]; + if(self->FreeList[index].next) return PointerToOffset(self,RemoveNode(self,index)); + + void *units=self->LowUnit; + self->LowUnit+=I2B(self,index); + if(self->LowUnit<=self->HighUnit) return PointerToOffset(self,units); + + self->LowUnit-=I2B(self,index); + + for(int i=index+1;iFreeList[i].next) + { + void *units=RemoveNode(self,i); + SplitBlock(self,units,i,index); + return PointerToOffset(self,units); + } + } + + return 0; +} + +static uint32_t ExpandUnitsBrimstone(PPMdSubAllocatorBrimstone *self,uint32_t oldoffs,int oldnum) +{ + void *oldptr=OffsetToPointer(self,oldoffs); + int oldindex=self->Units2Index[oldnum-1]; + int newindex=self->Units2Index[oldnum]; + if(oldindex==newindex) return oldoffs; + + uint32_t offs=AllocUnitsBrimstone(self,oldnum+1); + if(offs) + { + // TODO: could copy less data + memcpy(OffsetToPointer(self,offs),oldptr,I2B(self,oldindex)); + InsertNode(self,oldptr,oldindex); + } + return offs; +} + +static uint32_t ShrinkUnitsBrimstone(PPMdSubAllocatorBrimstone *self,uint32_t oldoffs,int oldnum,int newnum) +{ + void *oldptr=OffsetToPointer(self,oldoffs); + int oldindex=self->Units2Index[oldnum-1]; + int newindex=self->Units2Index[newnum-1]; + if(oldindex==newindex) return oldoffs; + + if(self->FreeList[newindex].next) + { + void *ptr=RemoveNode(self,newindex); + memcpy(ptr,oldptr,I2B(self,newindex)); + InsertNode(self,oldptr,oldindex); + return PointerToOffset(self,ptr); + } + else + { + SplitBlock(self,oldptr,oldindex,newindex); + return oldoffs; + } +} + +static void FreeUnitsBrimstone(PPMdSubAllocatorBrimstone *self,uint32_t offs,int num) +{ + InsertNode(self,OffsetToPointer(self,offs),self->Units2Index[num-1]); +} + + + + +static void InsertNode(PPMdSubAllocatorBrimstone *self,void *p,int index) +{ + ((struct PPMAllocatorNodeBrimstone *)p)->next=self->FreeList[index].next; + self->FreeList[index].next=p; +} + +static void *RemoveNode(PPMdSubAllocatorBrimstone *self,int index) +{ + struct PPMAllocatorNodeBrimstone *node=self->FreeList[index].next; + self->FreeList[index].next=node->next; + return node; +} + +static unsigned int I2B(PPMdSubAllocatorBrimstone *self,int index) { return UNIT_SIZE*self->Index2Units[index]; } + +static void SplitBlock(PPMdSubAllocatorBrimstone *self,void *pv,int oldindex,int newindex) +{ + uint8_t *p=((uint8_t *)pv)+I2B(self,newindex); + + int diff=self->Index2Units[oldindex]-self->Index2Units[newindex]; + int i=self->Units2Index[diff-1]; + if(self->Index2Units[i]!=diff) + { + InsertNode(self,p,i-1); + p+=I2B(self,i-1); + diff-=self->Index2Units[i-1]; + } + + InsertNode(self,p,self->Units2Index[diff-1]); +} diff --git a/pool/shard004/C/0098712_find-extreme-strings.c b/pool/shard004/C/0098712_find-extreme-strings.c new file mode 100644 index 0000000000000000000000000000000000000000..3fd95cfcc3b7078693e3f1574383f1e2fa6cd0bc --- /dev/null +++ b/pool/shard004/C/0098712_find-extreme-strings.c @@ -0,0 +1,128 @@ +/* (C) IT Sky Consulting GmbH 2014 + * http://www.it-sky-consulting.com/ + * Author: Karl Brodowsky + * Date: 2014-02-27 + * License: GPL v2 (See https://de.wikipedia.org/wiki/GNU_General_Public_License ) + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +struct result { + char *min; + char *max; +}; + +/* thread function */ +void *run(void *raw_name) { + // int retcode; + // time_t thread_start = time(NULL); + char *name = (char *) raw_name; + + // time_t open_start = time(NULL); + int fd = open_retry(name, O_RDONLY, THREAD_EXIT); + // time_t open_duration = time(NULL) - open_start; + + struct string_array strings = read_to_array(fd); + close(fd); + struct result *result = malloc(sizeof(struct result)); + if (strings.len == 0) { + result->min = ""; + result->max = ""; + return result; + } + + result->min = strings.strings[0]; + result->max = strings.strings[0]; + for (int i = 0; i < strings.len; i++) { + char *str = strings.strings[i]; + if (result->min[0] == '\000' || strcmp(result->min, str) > 0) { + result->min = str; + } + if (result->max[0] == '\000' || strcmp(result->max, str) < 0) { + result->max = str; + } + } + return result; +} + +void usage(char *argv0, char *msg) { + printf("%s\n\n", msg); + printf("Usage\n\n"); + printf("%s file1 file2 file3 ... filen\n", argv0); + printf("\n"); + printf("splits file contents into words and finds the minimum and maximum according to usual string compare.\n"); + printf("uses one thread for each file and then merges the results.\n"); + exit(1); +} + +int main(int argc, char *argv[]) { + + char *argv0 = argv[0]; + if (is_help_requested(argc, argv)) { + usage(argv0, ""); + } + + if (argc < 2) { + usage(argv0, "not enough arguments"); + } + + time_t start_time = time(NULL); + int retcode = 0; + int i; + + printf("%d files will be read\n", argc-1); + fflush(stdout); + + pthread_t *threads = (pthread_t *) malloc((argc-1)*sizeof(pthread_t)); + for (i = 1; i < argc; i++) { + retcode = pthread_create(&(threads[i-1]), NULL, run, argv[i]); + handle_thread_error(retcode, "starting thread", PROCESS_EXIT); + } + struct result *result = NULL; + for (i = 0; i < argc-1; i++) { + struct result *partial_result; + retcode = pthread_join(threads[i], (void **) &partial_result); + handle_thread_error(retcode, "joining thread", PROCESS_EXIT); + if (partial_result == NULL) { + printf("thread %d for file %s gave no result\n", i, argv[i+1]); + continue; + } else if (partial_result == PTHREAD_CANCELED) { + printf("thread %d for file %s has been cancelled\n", i, argv[i+1]); + continue; + } + if (result == NULL) { + result = partial_result; + } else { + if (strcmp(result->min, partial_result->min) > 0) { + result->min = partial_result->min; + } + if (strcmp(result->max, partial_result->max) < 0) { + result->max = partial_result->max; + } + } + } + + printf("------------------------------------------------------------\n"); + printf("min=\"%s\"\n", result->min); + printf("max=\"%s\"\n", result->max); + printf("------------------------------------------------------------\n"); + + time_t total_time = time(NULL) - start_time; + printf("total %ld sec\n", (long) total_time); + printf("done\n"); + exit(0); +} diff --git a/pool/shard004/C/0098715_ex10.14.c b/pool/shard004/C/0098715_ex10.14.c new file mode 100644 index 0000000000000000000000000000000000000000..7c6fc78fb32f394c103139591da7f9c0cd3f5fd5 --- /dev/null +++ b/pool/shard004/C/0098715_ex10.14.c @@ -0,0 +1,55 @@ +#include +void displayBits(unsigned value); +unsigned packCharacters(char c1,char c2); +void unpackCharacters(unsigned s); +void change(unsigned); +int main(){ + char c1; + char c2; + unsigned c; + printf("%s\n","char1:" ); + scanf("%c",&c1 ); + // displayBits(c1); + printf("%s\n","char2:" ); + scanf(" %c",&c2 ); + // displayBits(c2); + c=packCharacters(c1,c2); + printf("\n****************\n"); + unpackCharacters(c); +} + +unsigned packCharacters(char c1,char c2){ + unsigned pack; + pack=c1; + pack<<=8; + pack|=c2; + displayBits(pack); + return pack; +} + +void displayBits(unsigned value) { + unsigned c; + unsigned displayMask=1<<31; + printf("%u = ",value); + for(c=1;c<=32;c++){ + putchar(value & displayMask?'1':'0'); + value<<=1; + if(c%8==0){ + putchar(' '); + } + } + putchar('\n'); +} + +void unpackCharacters(unsigned s){ + unsigned tmp; + char c1; + char c2; + tmp=s&65280; + tmp>>=8; + c1=tmp; + displayBits(c1); + tmp=s&255; + c2=tmp; + displayBits(c2); +} diff --git a/pool/shard004/C/0098720_da850sdi_keys.c b/pool/shard004/C/0098720_da850sdi_keys.c new file mode 100644 index 0000000000000000000000000000000000000000..f1483799f9c2084f80c175548795a8cd0afdb0b0 --- /dev/null +++ b/pool/shard004/C/0098720_da850sdi_keys.c @@ -0,0 +1,326 @@ +/* + * da850sdi_keys.c - support IR remote on DA850 SDI board + * + * Cloned from dm365evm_keys.c + * Copyright (c) 2009 by David Brownell + * + * 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 + + +/* + * The MSP430 firmware on the DM365 EVM monitors an IR receptor used for + * the remote control. When any key is pressed, or its autorepeat kicks + * in, an event is sent. This driver read those events from the small + * event queue and reports them. + * + * Compared to the DM355 EVM: the MSP firmware does *only* IR. So this + * driver is simpler, and doesn't even need to use the MFD model. + * + * Note that physically there can only be one of these devices. + * + * This driver was tested with firmware revision 0xA1 (beta board). + */ +struct da850sdi_keys { + struct input_dev *input; + struct i2c_client *i2c; +}; + +#define DM365EVM_MSP_FIRMREV 0 +#define DM365EVM_MSP_INPUT_LOW 1 +#define DM365EVM_MSP_INPUT_HIGH 2 +#define DM365EVM_MSP_INPUT_COUNT 3 +#define DM365EVM_MSP_0x43 4 + +#define MSP430_GPIO GPIO_TO_PIN(2, 2) + +/* These initial keycodes can be remapped by dm365evm_setkeycode(). */ +static struct { + u16 event; + u16 keycode; +} da850sdi_keys[] = { + + /* + * IR buttons ... codes assigned to match the universal remote + * provided with the EVM (Philips PM4S) using DVD code 0020. + * + * These event codes match firmware documentation, but other + * remote controls could easily send more RC5-encoded events. + * The PM4S manual was used in several cases to help select + * a keycode reflecting the intended usage. + * + * RC5 codes are 14 bits, with two start bits (0x3 prefix) + * and a toggle bit (masked out below). + */ + { 0x300c, KEY_POWER, }, /* NOTE: docs omit this */ + { 0x3000, KEY_NUMERIC_0, }, + { 0x3001, KEY_NUMERIC_1, }, + { 0x3002, KEY_NUMERIC_2, }, + { 0x3003, KEY_NUMERIC_3, }, + { 0x3004, KEY_NUMERIC_4, }, + { 0x3005, KEY_NUMERIC_5, }, + { 0x3006, KEY_NUMERIC_6, }, + { 0x3007, KEY_NUMERIC_7, }, + { 0x3008, KEY_NUMERIC_8, }, + { 0x3009, KEY_NUMERIC_9, }, + { 0x3022, KEY_ENTER, }, + { 0x30ec, KEY_MODE, }, /* "tv/vcr/..." */ + { 0x300f, KEY_SELECT, }, /* "info" */ + { 0x3020, KEY_CHANNELUP, }, /* "up" */ + { 0x302e, KEY_MENU, }, /* "in/out" */ + { 0x3011, KEY_VOLUMEDOWN, }, /* "left" */ + { 0x300d, KEY_MUTE, }, /* "ok" */ + { 0x3010, KEY_VOLUMEUP, }, /* "right" */ + { 0x301e, KEY_SUBTITLE, }, /* "cc" */ + { 0x3021, KEY_CHANNELDOWN, }, /* "down" */ + { 0x3022, KEY_PREVIOUS, }, + { 0x3026, KEY_SLEEP, }, + { 0x3172, KEY_REWIND, }, + { 0x3175, KEY_PLAY, }, + { 0x3174, KEY_FASTFORWARD, }, + { 0x3177, KEY_RECORD, }, + { 0x3176, KEY_STOP, }, + { 0x3169, KEY_PAUSE, }, + + /* NOTE: SW22, a pushbutton next to the IR sensor, is also + * wired to the MSP430 but is currently ignored; some other + * I/O pins are likewise wired but ignored. + */ +}; + +static irqreturn_t da850sdi_keys_irq(int irq, void *_keys) +{ + struct da850sdi_keys *keys = _keys; + + /* For simplicity we ignore INPUT_COUNT and just read + * events until the GPIO stops signaling data ready. + */ + while (gpio_get_value(MSP430_GPIO) == 0) { + static u16 last_event; + u16 event; + int keycode; + int i; + + /* Read low, then high bytes; reading the high byte + * removes an entry from the input buffer. + */ + event = i2c_smbus_read_word_data(keys->i2c, + DM365EVM_MSP_INPUT_LOW); + if (event < 0) { + dev_dbg(&keys->i2c->dev, "input err %d\n", event); + break; + } + event = event; + + /* Press and release a button: two events, same code. + * Press and hold (autorepeat), then release: N events + * (N > 2), same code. For RC5 buttons the toggle bits + * distinguish (for example) "1-autorepeat" from "1 1"; + * but PCB buttons don't support that bit. + * + * So we must synthesize release events. We do that by + * mapping events to a press/release event pair; then + * to avoid adding extra events, skip the second event + * of each pair. + */ + if (event == last_event) { + last_event = 0; + continue; + } + last_event = event; + + /* ignore the RC5 toggle bit */ + event &= ~0x0800; + + /* find the key, or leave it as unknown */ + keycode = KEY_UNKNOWN; + for (i = 0; i < ARRAY_SIZE(da850sdi_keys); i++) { + if (da850sdi_keys[i].event != event) + continue; + keycode = da850sdi_keys[i].keycode; + break; + } + dev_dbg(&keys->i2c->dev, + "input event 0x%04x--> keycode %d\n", + event, keycode); + + /* report press + release */ + input_report_key(keys->input, keycode, 1); + input_sync(keys->input); + input_report_key(keys->input, keycode, 0); + input_sync(keys->input); + } + return IRQ_HANDLED; +} + +/* + * Since we talk to the MSP using I2C, we need to delegate all real + * IRQ handling work to some task context. We'll use an IRQ thread. + */ +static irqreturn_t da850sdi_keys_hardirq(int irq, void *_keys) +{ + return IRQ_WAKE_THREAD; +} + +static int dm365evm_setkeycode(struct input_dev *dev, int index, int keycode) +{ + u16 old_keycode; + unsigned i; + + if (((unsigned)index) >= ARRAY_SIZE(da850sdi_keys)) + return -EINVAL; + + old_keycode = da850sdi_keys[index].keycode; + da850sdi_keys[index].keycode = keycode; + set_bit(keycode, dev->keybit); + + for (i = 0; i < ARRAY_SIZE(da850sdi_keys); i++) { + if (da850sdi_keys[index].keycode == old_keycode) + goto done; + } + clear_bit(old_keycode, dev->keybit); +done: + return 0; +} + +static int dm365evm_getkeycode(struct input_dev *dev, int index, int *keycode) +{ + if (((unsigned)index) >= ARRAY_SIZE(da850sdi_keys)) + return -EINVAL; + + return da850sdi_keys[index].keycode; +} + +/*----------------------------------------------------------------------*/ + +static int __devinit +da850sdi_keys_probe(struct i2c_client *i2c, const struct i2c_device_id *id) +{ + struct da850sdi_keys *keys; + struct input_dev *input; + int status; + int i; + + status = gpio_request(MSP430_GPIO, id->name); + if (status < 0) + return status; + + status = gpio_direction_input(MSP430_GPIO); + if (status < 0) { + gpio_free(MSP430_GPIO); + return status; + } + + /* allocate instance struct and input dev */ + keys = kzalloc(sizeof *keys, GFP_KERNEL); + input = input_allocate_device(); + if (!keys || !input) { + status = -ENOMEM; + goto fail1; + } + + keys->i2c = i2c; + keys->input = input; + + input_set_drvdata(input, keys); + + input->name = "DA850 SDI Controls"; + input->phys = "da850sdi/input0"; + input->dev.parent = &i2c->dev; + + input->id.bustype = BUS_I2C; + input->id.product = 0x0365; + input->id.version = i2c_smbus_read_byte_data(i2c, + DM365EVM_MSP_FIRMREV); + + input->evbit[0] = BIT(EV_KEY); + for (i = 0; i < ARRAY_SIZE(da850sdi_keys); i++) + __set_bit(da850sdi_keys[i].keycode, input->keybit); + + input->setkeycode = dm365evm_setkeycode; + input->getkeycode = dm365evm_getkeycode; + + /* FIXME: flush the event queue */ + + status = request_threaded_irq(gpio_to_irq(MSP430_GPIO), + da850sdi_keys_hardirq, da850sdi_keys_irq, + IRQF_TRIGGER_FALLING, + id->name, keys); + if (status < 0) + goto fail1; + + /* register */ + status = input_register_device(input); + if (status < 0) + goto fail2; + + i2c_set_clientdata(i2c, keys); + + return 0; + +fail2: + free_irq(gpio_to_irq(MSP430_GPIO), keys); +fail1: + input_free_device(input); + kfree(keys); + gpio_free(MSP430_GPIO); + dev_err(&i2c->dev, "can't register, err %d\n", status); + + return status; +} + +static int __devexit da850sdi_keys_remove(struct i2c_client *i2c) +{ + struct da850sdi_keys *keys = i2c_get_clientdata(i2c); + + free_irq(gpio_to_irq(MSP430_GPIO), keys); + input_unregister_device(keys->input); + kfree(keys); + + gpio_free(MSP430_GPIO); + + return 0; +} + +/* REVISIT: add suspend/resume when DaVinci supports it. The IRQ should + * be able to wake up the system. When device_may_wakeup(&i2c->dev), call + * enable_irq_wake() on suspend, and disable_irq_wake() on resume. + */ + +static const struct i2c_device_id ids[] = { + { .name = "da850sdi_keys", }, + { }, +}; +MODULE_DEVICE_TABLE(i2c, ids); + +static struct i2c_driver da850sdi_keys_driver = { + .driver.name = "da850sdi_keys", + .id_table = ids, + .probe = da850sdi_keys_probe, + .remove = __devexit_p(da850sdi_keys_remove), +}; + +static int __init da850sdi_keys_init(void) +{ + return i2c_add_driver(&da850sdi_keys_driver); +} +module_init(da850sdi_keys_init); + +static void __exit da850sdi_keys_exit(void) +{ + i2c_del_driver(&da850sdi_keys_driver); +} +module_exit(da850sdi_keys_exit); + +MODULE_LICENSE("GPL"); diff --git a/pool/shard004/C/0098721_core.c b/pool/shard004/C/0098721_core.c new file mode 100644 index 0000000000000000000000000000000000000000..3e38a216e75b85a590cb572a147896805e68bae1 --- /dev/null +++ b/pool/shard004/C/0098721_core.c @@ -0,0 +1,217 @@ +/*- + * Copyright (C) 2013 Matt Windsor + * + * 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. + */ + +/* Helpers for jobs that don't rely on the query system. */ + +#include /* assert */ +#include /* gchar, g_... */ +#include /* bool, true, false */ +#include /* strcmp */ +#include "../pk-backend.h" /* pk_..., Pk... */ +#include "pkg.h" /* pkg_... */ + +#include "../db.h" /* db_... */ +#include "../emit.h" /* emit_package */ +#include "../event.h" /* event_cb */ +#include "../namever.h" /* namever_* */ +#include "../pkgutils.h" /* pkgutils_... */ +#include "../repo.h" /* repo_... */ +#include "../utils.h" /* ERR */ +#include "check.h" /* jobs_check_... */ +#include "core.h" /* jobs_... */ + +static const char *APPLY_ERRORS[] = { + "This shouldn't occur and is a bug.", /* EPKG_OK */ + "This shouldn't occur and is a bug.", /* EPKG_END */ + "This shouldn't occur and is a bug.", /* EPKG_WARN */ + "Fatal error.", /* EPKG_FATAL */ + "Package required by another package.", /* EPKG_REQUIRED */ + "Already installed.", /* EPKG_INSTALLED */ + "Unresolved dependencies.", /* EPKG_DEPENDENCY */ + "A package is currently locked.", /* EPKG_LOCKED */ + "No usable database available.", /* EPKG_ENODB */ + "Local file newer than remote file.", /* EPKG_UPTODATE */ + "Unknown keyword.", /* EPKG_UNKNOWN */ + "Incompatible repo schema version", /* EPKG_REPOSCHEMA */ + "Insufficient privilege for action.", /* EPKG_ENOACCESS */ + "Insecure privileges on DB file." /* EPKG_INSECURE */ +}; + +/* Applies a job with the given error enums and the standard event callback. */ +bool +jobs_apply(struct pkg_jobs *jobs, PkBackend *backend, PkErrorEnum job_failed) +{ + int err; + + assert(backend != NULL); + + pkg_event_register(event_cb, backend); + { + err = pkg_jobs_apply(jobs); + } + pkg_event_register(NULL, NULL); + + assert(EPKG_OK <= err); + assert(err <= EPKG_INSECURE); + if (err != EPKG_OK) { + const gchar *error_string; + + /* Did we trap an error in the events handler? */ + error_string = pk_backend_get_string(backend, "job_error"); + if (error_string == NULL) { + error_string = APPLY_ERRORS[err]; + } + assert(error_string != NULL); + + ERR(backend, job_failed, error_string); + } + return (err == EPKG_OK); +} + +enum repo_set_status +jobs_set_repo(struct pkg_jobs *jobs, const char *reponame) +{ + enum repo_set_status status; + enum repo_type type; + + assert(jobs != NULL); + + type = repo_type(reponame); + if (type == REPO_INVALID) { + status = REPO_SET_INVALID_REPO; + } else if (type == REPO_INVALID) { + status = REPO_SET_DISABLED_REPO; + } else if (type == REPO_REMOTE) { + int err; + + err = pkg_jobs_set_repository(jobs, + pkg_repo_ident_from_name(reponame)); + status = (err == EPKG_OK) ? REPO_SET_OK : REPO_SET_FAILURE; + } else { + /* Ignore any other type of repository. */ + status = REPO_SET_OK; + } + + return status; +} + +/* + * Adds each PackageID into an already created job. Returns NULL on failure + * and a vector of added package name-versions to be freed after solution on + * success. + */ +char ** +jobs_add_package_ids(struct pkg_jobs *jobs, gchar **package_ids, guint count) +{ + char **namevers; + + assert(jobs != NULL); + assert(package_ids != NULL); + + namevers = NULL; + + if (count > 0) { + int err; + + namevers = namever_array_from_package_ids(package_ids, count); + + err = pkg_jobs_add(jobs, MATCH_EXACT, namevers, (int)count); + if (err != EPKG_OK) { + namever_array_free(&namevers, count); + } + } + return namevers; +} + +/* Converts a repo-set result to a string constant. */ +const char * +jobs_repo_set_status_to_string(enum repo_set_status status) +{ + const char *detail; + +#ifndef __clang__ + detail = "Detail message not set."; +#endif + + switch (status) { + case REPO_SET_OK: + detail = "This shouldn't happen."; + break; + case REPO_SET_INVALID_REPO: + detail = "This repo doesn't seem to exist."; + break; + case REPO_SET_DISABLED_REPO: + detail = "This repo is disabled."; + break; + case REPO_SET_FAILURE: + detail = "Error while setting repo."; + break; + } + + return detail; +} + +/* Emits each package queued up in a (solved) job. */ +void +jobs_emit_packages(struct pkg_jobs *jobs, PkBackend *backend, + pkg_info_ptr info) +{ + struct pkg *pkg; + + assert(jobs != NULL); + assert(backend != NULL); + assert(info != NULL); + + pkg = NULL; + while (pkg_jobs(jobs, &pkg) == EPKG_OK) { + assert(pkg != NULL); + emit_package(pkg, backend, info(pkg)); + } +} + +/* Overly safe wrapper around pkg_jobs_new. */ +struct pkg_jobs * +jobs_allocate(pkg_jobs_t type, struct pkgdb *db) +{ + int err; + struct pkg_jobs *jobs; + + assert(db != NULL); + + jobs = NULL; + err = pkg_jobs_new(&jobs, type, db); + if (err != EPKG_OK && jobs != NULL) { + jobs_free(&jobs); + } + assert(err == EPKG_OK || jobs == NULL); + assert(err != EPKG_OK || jobs != NULL); + + return jobs; +} + +/* Overly safe wrapper around pkg_jobs_free. */ +void +jobs_free(struct pkg_jobs **jobs_p) +{ + + assert(jobs_p != NULL); + pkg_jobs_free(*jobs_p); + *jobs_p = NULL; +} diff --git a/pool/shard004/C/0098732_splashscreen_jpeg.c b/pool/shard004/C/0098732_splashscreen_jpeg.c new file mode 100644 index 0000000000000000000000000000000000000000..ba91abbed466530656a6b4c615d59dc4953a207f --- /dev/null +++ b/pool/shard004/C/0098732_splashscreen_jpeg.c @@ -0,0 +1,257 @@ +/* + * Copyright (c) 2005, 2012, 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 "splashscreen_impl.h" + +#include "jpeglib.h" +#include "jerror.h" + +#include + +#ifdef __APPLE__ +/* use setjmp/longjmp versions that do not save/restore the signal mask */ +#define setjmp _setjmp +#define longjmp _longjmp +#endif + +/* stream input handling */ + +typedef struct +{ + struct jpeg_source_mgr pub; /* public fields */ + SplashStream * stream; /* source stream */ + JOCTET *buffer; /* start of buffer */ + boolean start_of_file; /* have we gotten any data yet? */ +} stream_source_mgr; + +typedef stream_source_mgr *stream_src_ptr; + +#define INPUT_BUF_SIZE 4096 /* choose an efficiently fread'able size */ + +METHODDEF(void) +stream_init_source(j_decompress_ptr cinfo) +{ + stream_src_ptr src = (stream_src_ptr) cinfo->src; + + src->start_of_file = TRUE; +} + +METHODDEF(boolean) +stream_fill_input_buffer(j_decompress_ptr cinfo) +{ + stream_src_ptr src = (stream_src_ptr) cinfo->src; + size_t nbytes; + + + nbytes = src->stream->read(src->stream, src->buffer, INPUT_BUF_SIZE); + + if (nbytes <= 0) { + if (src->start_of_file) /* Treat empty input file as fatal error */ + ERREXIT(cinfo, JERR_INPUT_EMPTY); + WARNMS(cinfo, JWRN_JPEG_EOF); + /* Insert a fake EOI marker */ + src->buffer[0] = (JOCTET) 0xFF; + src->buffer[1] = (JOCTET) JPEG_EOI; + nbytes = 2; + } + + src->pub.next_input_byte = src->buffer; + src->pub.bytes_in_buffer = nbytes; + src->start_of_file = FALSE; + + return TRUE; +} + +METHODDEF(void) + stream_skip_input_data(j_decompress_ptr cinfo, long num_bytes) +{ + stream_src_ptr src = (stream_src_ptr) cinfo->src; + + if (num_bytes > 0) { + while (num_bytes > (long) src->pub.bytes_in_buffer) { + num_bytes -= (long) src->pub.bytes_in_buffer; + (void) stream_fill_input_buffer(cinfo); + } + src->pub.next_input_byte += (size_t) num_bytes; + src->pub.bytes_in_buffer -= (size_t) num_bytes; + } +} + +METHODDEF(void) +stream_term_source(j_decompress_ptr cinfo) +{ +} + +static void +set_stream_src(j_decompress_ptr cinfo, SplashStream * stream) +{ + stream_src_ptr src; + + if (cinfo->src == NULL) { /* first time for this JPEG object? */ + cinfo->src = (struct jpeg_source_mgr *) + (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, + JPOOL_PERMANENT, sizeof(stream_source_mgr)); + src = (stream_src_ptr) cinfo->src; + src->buffer = (JOCTET *) + (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, + JPOOL_PERMANENT, INPUT_BUF_SIZE * sizeof(JOCTET)); + } + + src = (stream_src_ptr) cinfo->src; + src->pub.init_source = stream_init_source; + src->pub.fill_input_buffer = stream_fill_input_buffer; + src->pub.skip_input_data = stream_skip_input_data; + src->pub.resync_to_restart = jpeg_resync_to_restart; /* use default method */ + src->pub.term_source = stream_term_source; + src->stream = stream; + src->pub.bytes_in_buffer = 0; /* forces fill_input_buffer on first read */ + src->pub.next_input_byte = NULL; /* until buffer loaded */ +} + +int +SplashDecodeJpeg(Splash * splash, struct jpeg_decompress_struct *cinfo) +{ + int rowStride, stride; + JSAMPARRAY buffer; + ImageFormat srcFormat; + + jpeg_read_header(cinfo, TRUE); + + // SplashScreen jpeg converter expects data in RGB format only + cinfo->out_color_space = JCS_RGB; + + jpeg_start_decompress(cinfo); + + SplashCleanup(splash); + + splash->width = cinfo->output_width; + splash->height = cinfo->output_height; + + if (!SAFE_TO_ALLOC(splash->imageFormat.depthBytes, splash->width)) { + return 0; + } + stride = splash->width * splash->imageFormat.depthBytes; + + if (!SAFE_TO_ALLOC(stride, splash->height)) { + return 0; + } + if (!SAFE_TO_ALLOC(cinfo->output_width, cinfo->output_components)) { + return 0; + } + + splash->frameCount = 1; + splash->frames = (SplashImage *) malloc(sizeof(SplashImage) * + splash->frameCount); + if (splash->frames == NULL) { + return 0; + } + memset(splash->frames, 0, sizeof(SplashImage) * + splash->frameCount); + + splash->loopCount = 1; + splash->frames[0].delay = 0; + splash->frames[0].bitmapBits = malloc(stride * splash->height); + if (splash->frames[0].bitmapBits == NULL) { + free(splash->frames); + return 0; + } + + rowStride = cinfo->output_width * cinfo->output_components; + + buffer = (*cinfo->mem->alloc_sarray) + ((j_common_ptr) cinfo, JPOOL_IMAGE, rowStride, 1); + if (buffer == NULL) { + free(splash->frames[0].bitmapBits); + free(splash->frames); + return 0; + } + + initFormat(&srcFormat, 0x00FF0000, 0x0000FF00, 0x000000FF, 0x00000000); + srcFormat.byteOrder = BYTE_ORDER_LSBFIRST; + srcFormat.depthBytes = 3; + srcFormat.fixedBits = 0xFF000000; + + splash->maskRequired = 0; // reset maskRequired as JPEG can't be transparent + + while (cinfo->output_scanline < cinfo->output_height) { + rgbquad_t *out = + (rgbquad_t *) ((byte_t *) splash->frames[0].bitmapBits + + cinfo->output_scanline * stride); + + jpeg_read_scanlines(cinfo, buffer, 1); + convertLine(buffer[0], sizeof(JSAMPLE) * 3, out, + splash->imageFormat.depthBytes, cinfo->output_width, &srcFormat, + &splash->imageFormat, CVT_COPY, NULL, 0, NULL, + cinfo->output_scanline, 0); + } + jpeg_finish_decompress(cinfo); + + return 1; +} + +struct my_error_mgr +{ + struct jpeg_error_mgr pub; /* "public" fields */ + jmp_buf setjmp_buffer; /* for return to caller */ +}; + +typedef struct my_error_mgr *my_error_ptr; + +static void +my_error_exit(j_common_ptr cinfo) +{ + /* cinfo->err really points to a my_error_mgr struct, so coerce pointer */ + my_error_ptr myerr = (my_error_ptr) cinfo->err; + + /* Always display the message. */ + /* We could postpone this until after returning, if we chose. */ + (*cinfo->err->output_message) (cinfo); + + /* Return control to the setjmp point */ + longjmp(myerr->setjmp_buffer, 1); +} + +int +SplashDecodeJpegStream(Splash * splash, SplashStream * stream) +{ + struct jpeg_decompress_struct cinfo; + int success; + struct my_error_mgr jerr; + + cinfo.err = jpeg_std_error(&jerr.pub); + jerr.pub.error_exit = my_error_exit; + + if (setjmp(jerr.setjmp_buffer)) { + success = 0; + goto done; + } + jpeg_create_decompress(&cinfo); + set_stream_src(&cinfo, stream); + success = SplashDecodeJpeg(splash, &cinfo); + + done: + jpeg_destroy_decompress(&cinfo); + return success; +} diff --git a/pool/shard004/C/0098734_linux-i386-ipa.c b/pool/shard004/C/0098734_linux-i386-ipa.c new file mode 100644 index 0000000000000000000000000000000000000000..1eb59a0bc4982831daf59264b606bb4b965436be --- /dev/null +++ b/pool/shard004/C/0098734_linux-i386-ipa.c @@ -0,0 +1,254 @@ +/* GNU/Linux/x86 specific low level interface, for the in-process + agent library for GDB. + + Copyright (C) 2010-2012 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 "server.h" +#include +#include + +/* GDB register numbers. */ + +enum i386_gdb_regnum +{ + I386_EAX_REGNUM, /* %eax */ + I386_ECX_REGNUM, /* %ecx */ + I386_EDX_REGNUM, /* %edx */ + I386_EBX_REGNUM, /* %ebx */ + I386_ESP_REGNUM, /* %esp */ + I386_EBP_REGNUM, /* %ebp */ + I386_ESI_REGNUM, /* %esi */ + I386_EDI_REGNUM, /* %edi */ + I386_EIP_REGNUM, /* %eip */ + I386_EFLAGS_REGNUM, /* %eflags */ + I386_CS_REGNUM, /* %cs */ + I386_SS_REGNUM, /* %ss */ + I386_DS_REGNUM, /* %ds */ + I386_ES_REGNUM, /* %es */ + I386_FS_REGNUM, /* %fs */ + I386_GS_REGNUM, /* %gs */ + I386_ST0_REGNUM /* %st(0) */ +}; + +#define i386_num_regs 16 + +/* Defined in auto-generated file i386-linux.c. */ +void init_registers_i386_linux (void); + +#define FT_CR_EAX 15 +#define FT_CR_ECX 14 +#define FT_CR_EDX 13 +#define FT_CR_EBX 12 +#define FT_CR_UESP 11 +#define FT_CR_EBP 10 +#define FT_CR_ESI 9 +#define FT_CR_EDI 8 +#define FT_CR_EIP 7 +#define FT_CR_EFL 6 +#define FT_CR_DS 5 +#define FT_CR_ES 4 +#define FT_CR_FS 3 +#define FT_CR_GS 2 +#define FT_CR_SS 1 +#define FT_CR_CS 0 + +/* Mapping between the general-purpose registers in jump tracepoint + format and GDB's register array layout. */ + +static const int i386_ft_collect_regmap[] = +{ + FT_CR_EAX * 4, FT_CR_ECX * 4, FT_CR_EDX * 4, FT_CR_EBX * 4, + FT_CR_UESP * 4, FT_CR_EBP * 4, FT_CR_ESI * 4, FT_CR_EDI * 4, + FT_CR_EIP * 4, FT_CR_EFL * 4, FT_CR_CS * 4, FT_CR_SS * 4, + FT_CR_DS * 4, FT_CR_ES * 4, FT_CR_FS * 4, FT_CR_GS * 4 +}; + +void +supply_fast_tracepoint_registers (struct regcache *regcache, + const unsigned char *buf) +{ + int i; + + for (i = 0; i < i386_num_regs; i++) + { + int regval; + + if (i >= I386_CS_REGNUM && i <= I386_GS_REGNUM) + regval = *(short *) (((char *) buf) + i386_ft_collect_regmap[i]); + else + regval = *(int *) (((char *) buf) + i386_ft_collect_regmap[i]); + + supply_register (regcache, i, ®val); + } +} + +ULONGEST __attribute__ ((visibility("default"), used)) +gdb_agent_get_raw_reg (unsigned char *raw_regs, int regnum) +{ + /* This should maybe be allowed to return an error code, or perhaps + better, have the emit_reg detect this, and emit a constant zero, + or something. */ + + if (regnum > i386_num_regs) + return 0; + else if (regnum >= I386_CS_REGNUM && regnum <= I386_GS_REGNUM) + return *(short *) (raw_regs + i386_ft_collect_regmap[regnum]); + else + return *(int *) (raw_regs + i386_ft_collect_regmap[regnum]); +} + +#ifdef HAVE_UST + +#include + +/* "struct registers" is the UST object type holding the registers at + the time of the static tracepoint marker call. This doesn't + contain EIP, but we know what it must have been (the marker + address). */ + +#define ST_REGENTRY(REG) \ + { \ + offsetof (struct registers, REG), \ + sizeof (((struct registers *) NULL)->REG) \ + } + +static struct +{ + int offset; + int size; +} i386_st_collect_regmap[] = + { + ST_REGENTRY(eax), + ST_REGENTRY(ecx), + ST_REGENTRY(edx), + ST_REGENTRY(ebx), + ST_REGENTRY(esp), + ST_REGENTRY(ebp), + ST_REGENTRY(esi), + ST_REGENTRY(edi), + { -1, 0 }, /* eip */ + ST_REGENTRY(eflags), + ST_REGENTRY(cs), + ST_REGENTRY(ss), + }; + +#define i386_NUM_ST_COLLECT_GREGS \ + (sizeof (i386_st_collect_regmap) / sizeof (i386_st_collect_regmap[0])) + +void +supply_static_tracepoint_registers (struct regcache *regcache, + const unsigned char *buf, + CORE_ADDR pc) +{ + int i; + unsigned int newpc = pc; + + supply_register (regcache, I386_EIP_REGNUM, &newpc); + + for (i = 0; i < i386_NUM_ST_COLLECT_GREGS; i++) + if (i386_st_collect_regmap[i].offset != -1) + { + switch (i386_st_collect_regmap[i].size) + { + case 4: + supply_register (regcache, i, + ((char *) buf) + + i386_st_collect_regmap[i].offset); + break; + case 2: + { + unsigned long reg + = * (short *) (((char *) buf) + + i386_st_collect_regmap[i].offset); + reg &= 0xffff; + supply_register (regcache, i, ®); + } + break; + default: + internal_error (__FILE__, __LINE__, "unhandled register size: %d", + i386_st_collect_regmap[i].size); + } + } +} + +#endif /* HAVE_UST */ + + +/* This is only needed because reg-i386-linux-lib.o references it. We + may use it proper at some point. */ +const char *gdbserver_xmltarget; + +/* Attempt to allocate memory for trampolines in the first 64 KiB of + memory to enable smaller jump patches. */ + +static void +initialize_fast_tracepoint_trampoline_buffer (void) +{ + const CORE_ADDR buffer_end = 64 * 1024; + /* Ensure that the buffer will be at least 1 KiB in size, which is + enough space for over 200 fast tracepoints. */ + const int min_buffer_size = 1024; + char buf[IPA_BUFSIZ]; + CORE_ADDR mmap_min_addr = buffer_end + 1; + ULONGEST buffer_size; + FILE *f = fopen ("/proc/sys/vm/mmap_min_addr", "r"); + + if (!f) + { + snprintf (buf, sizeof (buf), "mmap_min_addr open failed: %s", + strerror (errno)); + set_trampoline_buffer_space (0, 0, buf); + return; + } + + if (fgets (buf, IPA_BUFSIZ, f)) + sscanf (buf, "%llu", &mmap_min_addr); + + fclose (f); + + buffer_size = buffer_end - mmap_min_addr; + + if (buffer_size >= min_buffer_size) + { + if (mmap ((void *) (uintptr_t) mmap_min_addr, buffer_size, + PROT_READ | PROT_EXEC | PROT_WRITE, + MAP_FIXED | MAP_PRIVATE | MAP_ANONYMOUS, + -1, 0) + != MAP_FAILED) + set_trampoline_buffer_space (mmap_min_addr, buffer_end, NULL); + else + { + snprintf (buf, IPA_BUFSIZ, "low-64K-buffer mmap() failed: %s", + strerror (errno)); + set_trampoline_buffer_space (0, 0, buf); + } + } + else + { + snprintf (buf, IPA_BUFSIZ, "mmap_min_addr is %d, must be %d or less", + (int) mmap_min_addr, (int) buffer_end - min_buffer_size); + set_trampoline_buffer_space (0, 0, buf); + } +} + +void +initialize_low_tracepoint (void) +{ + init_registers_i386_linux (); + initialize_fast_tracepoint_trampoline_buffer (); +} diff --git a/pool/shard004/C/0098736_mkmap_dbm.c b/pool/shard004/C/0098736_mkmap_dbm.c new file mode 100644 index 0000000000000000000000000000000000000000..1db588bab4107cfe3e6b45bdb8080b38b0e4fb98 --- /dev/null +++ b/pool/shard004/C/0098736_mkmap_dbm.c @@ -0,0 +1,116 @@ +/*++ +/* NAME +/* mkmap_dbm 3 +/* SUMMARY +/* create or open database, DBM style +/* SYNOPSIS +/* #include +/* +/* MKMAP *mkmap_dbm_open(path) +/* const char *path; +/* DESCRIPTION +/* This module implements support for creating DBM databases. +/* +/* mkmap_dbm_open() takes a file name, appends the ".dir" and ".pag" +/* suffixes, and creates or opens the named DBM database. +/* This routine is a DBM-specific helper for the more general +/* mkmap_open() routine. +/* +/* All errors are fatal. +/* SEE ALSO +/* dict_dbm(3), DBM dictionary interface. +/* LICENSE +/* .ad +/* .fi +/* The Secure Mailer license must be distributed with this software. +/* AUTHOR(S) +/* Wietse Venema +/* IBM T.J. Watson Research +/* P.O. Box 704 +/* Yorktown Heights, NY 10598, USA +/*--*/ + +/* System library. */ + +#include +#include + +/* Utility library. */ + +#include +#include +#include +#include +#include +#include + +/* Application-specific. */ + +#include "mkmap.h" + +#ifdef HAS_DBM +#ifdef PATH_NDBM_H +#include PATH_NDBM_H +#else +#include +#endif + +typedef struct MKMAP_DBM { + MKMAP mkmap; /* parent class */ + char *lock_file; /* path name */ + int lock_fd; /* -1 or open locked file */ +} MKMAP_DBM; + +/* mkmap_dbm_after_close - clean up after closing database */ + +static void mkmap_dbm_after_close(MKMAP *mp) +{ + MKMAP_DBM *mkmap = (MKMAP_DBM *) mp; + + if (mkmap->lock_fd >= 0 && close(mkmap->lock_fd) < 0) + msg_warn("close %s: %m", mkmap->lock_file); + myfree(mkmap->lock_file); +} + +/* mkmap_dbm_open - create or open database */ + +MKMAP *mkmap_dbm_open(const char *path) +{ + MKMAP_DBM *mkmap = (MKMAP_DBM *) mymalloc(sizeof(*mkmap)); + char *pag_file; + int pag_fd; + + /* + * Fill in the generic members. + */ + mkmap->lock_file = concatenate(path, ".dir", (char *) 0); + mkmap->mkmap.open = dict_dbm_open; + mkmap->mkmap.after_open = 0; + mkmap->mkmap.after_close = mkmap_dbm_after_close; + + /* + * Unfortunately, not all systems support locking on open(), so we open + * the .dir and .pag files before truncating them. Keep one file open for + * locking. + */ + if ((mkmap->lock_fd = open(mkmap->lock_file, O_CREAT | O_RDWR, 0644)) < 0) + msg_fatal("open %s: %m", mkmap->lock_file); + + pag_file = concatenate(path, ".pag", (char *) 0); + if ((pag_fd = open(pag_file, O_CREAT | O_RDWR, 0644)) < 0) + msg_fatal("open %s: %m", pag_file); + if (close(pag_fd)) + msg_warn("close %s: %m", pag_file); + myfree(pag_file); + + /* + * Get an exclusive lock - we're going to change the database so we can't + * have any spectators. + */ + if (myflock(mkmap->lock_fd, INTERNAL_LOCK, MYFLOCK_OP_EXCLUSIVE) < 0) + msg_fatal("lock %s: %m", mkmap->lock_file); + + return (&mkmap->mkmap); +} + +#endif diff --git a/pool/shard004/C/0098746_test_server.c b/pool/shard004/C/0098746_test_server.c new file mode 100644 index 0000000000000000000000000000000000000000..c39744f8ae1d429b8db2bddc52a63408d97d9269 --- /dev/null +++ b/pool/shard004/C/0098746_test_server.c @@ -0,0 +1,201 @@ +/* + This file is part of GNUnet. + (C) 2009, 2010 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 util/test_server.c + * @brief tests for server.c + */ +#include "platform.h" +#include "gnunet_util_lib.h" + +#define PORT 12435 + +#define TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 2) + +#define MY_TYPE 128 +#define MY_TYPE2 129 + +static struct GNUNET_SERVER_Handle *server; + +static struct GNUNET_CLIENT_Connection *cc; + +static struct GNUNET_SERVER_Client *argclient; + +static struct GNUNET_CONFIGURATION_Handle *cfg; + +static int ok; + + +static void +finish_up (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc) +{ + GNUNET_assert (ok == 6); + ok = 0; + GNUNET_SERVER_destroy (server); + GNUNET_CLIENT_disconnect (cc); + GNUNET_CONFIGURATION_destroy (cfg); +} + + +static void +recv_fin_cb (void *cls, struct GNUNET_SERVER_Client *client, + const struct GNUNET_MessageHeader *message) +{ + GNUNET_assert (ok == 5); + ok = 6; + GNUNET_SERVER_receive_done (client, GNUNET_OK); + GNUNET_SCHEDULER_add_now (&finish_up, NULL); +} + + +static void +first_reply_handler (void *cls, const struct GNUNET_MessageHeader *msg) +{ + GNUNET_assert (ok == 4); + ok = 5; + GNUNET_SERVER_receive_done (argclient, GNUNET_OK); + GNUNET_SERVER_client_drop (argclient); + argclient = NULL; +} + + +static size_t +reply_msg (void *cls, size_t size, void *buf) +{ + struct GNUNET_MessageHeader msg; + + GNUNET_assert (ok == 3); + ok = 4; + GNUNET_assert (size >= sizeof (struct GNUNET_MessageHeader)); + msg.type = htons (MY_TYPE); + msg.size = htons (sizeof (struct GNUNET_MessageHeader)); + memcpy (buf, &msg, sizeof (struct GNUNET_MessageHeader)); + return sizeof (struct GNUNET_MessageHeader); +} + + +static void +recv_cb (void *cls, struct GNUNET_SERVER_Client *client, + const struct GNUNET_MessageHeader *message) +{ + GNUNET_assert (ok == 2); + ok = 3; + argclient = client; + GNUNET_SERVER_client_keep (argclient); + GNUNET_assert (sizeof (struct GNUNET_MessageHeader) == ntohs (message->size)); + GNUNET_assert (MY_TYPE == ntohs (message->type)); + GNUNET_assert (NULL != + GNUNET_SERVER_notify_transmit_ready (client, + ntohs (message->size), + TIMEOUT, &reply_msg, + NULL)); +} + + +static struct GNUNET_SERVER_MessageHandler handlers[] = { + {&recv_cb, NULL, MY_TYPE, sizeof (struct GNUNET_MessageHeader)}, + {&recv_fin_cb, NULL, MY_TYPE2, sizeof (struct GNUNET_MessageHeader)}, + {NULL, NULL, 0, 0} +}; + + +static size_t +transmit_second_message (void *cls, size_t size, void *buf) +{ + struct GNUNET_MessageHeader msg; + + GNUNET_assert (size >= sizeof (struct GNUNET_MessageHeader)); + msg.type = htons (MY_TYPE2); + msg.size = htons (sizeof (struct GNUNET_MessageHeader)); + memcpy (buf, &msg, sizeof (struct GNUNET_MessageHeader)); + return sizeof (struct GNUNET_MessageHeader); +} + + +static size_t +transmit_initial_message (void *cls, size_t size, void *buf) +{ + struct GNUNET_MessageHeader msg; + + GNUNET_assert (ok == 1); + ok = 2; + GNUNET_assert (size >= sizeof (struct GNUNET_MessageHeader)); + msg.type = htons (MY_TYPE); + msg.size = htons (sizeof (struct GNUNET_MessageHeader)); + memcpy (buf, &msg, sizeof (struct GNUNET_MessageHeader)); + GNUNET_assert (NULL != + GNUNET_CLIENT_notify_transmit_ready (cc, + sizeof (struct + GNUNET_MessageHeader), + TIMEOUT, GNUNET_YES, + &transmit_second_message, + NULL)); + GNUNET_CLIENT_receive (cc, &first_reply_handler, NULL, TIMEOUT); + return sizeof (struct GNUNET_MessageHeader); +} + + +static void +task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc) +{ + struct sockaddr_in sa; + struct sockaddr *sap[2]; + socklen_t slens[2]; + + sap[0] = (struct sockaddr *) &sa; + slens[0] = sizeof (sa); + sap[1] = NULL; + slens[1] = 0; + memset (&sa, 0, sizeof (sa)); +#if HAVE_SOCKADDR_IN_SIN_LEN + sa.sin_len = sizeof (sa); +#endif + sa.sin_family = AF_INET; + sa.sin_port = htons (PORT); + server = GNUNET_SERVER_create (NULL, NULL, sap, slens, TIMEOUT, GNUNET_NO); + GNUNET_assert (server != NULL); + GNUNET_SERVER_add_handlers (server, handlers); + cfg = GNUNET_CONFIGURATION_create (); + GNUNET_CONFIGURATION_set_value_number (cfg, "test-server", "PORT", PORT); + GNUNET_CONFIGURATION_set_value_string (cfg, "test-server", "HOSTNAME", + "localhost"); + GNUNET_CONFIGURATION_set_value_string (cfg, "resolver", "HOSTNAME", + "localhost"); + cc = GNUNET_CLIENT_connect ("test-server", cfg); + GNUNET_assert (cc != NULL); + GNUNET_assert (NULL != + GNUNET_CLIENT_notify_transmit_ready (cc, + sizeof (struct + GNUNET_MessageHeader), + TIMEOUT, GNUNET_YES, + &transmit_initial_message, + NULL)); +} + + +int +main (int argc, char *argv[]) +{ + GNUNET_log_setup ("test_server", "WARNING", NULL); + ok = 1; + GNUNET_SCHEDULER_run (&task, &ok); + return ok; +} + +/* end of test_server.c */ diff --git a/pool/shard004/C/0098753_BufferWriter.c b/pool/shard004/C/0098753_BufferWriter.c new file mode 100644 index 0000000000000000000000000000000000000000..b0e4129618bb3d3d713bf7b5ef97494b99221aef --- /dev/null +++ b/pool/shard004/C/0098753_BufferWriter.c @@ -0,0 +1,112 @@ +/** + * @file BufferWriter.c + * @author Ambroz Bizjak + * + * @section 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 the author 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 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 + +#include + +static void output_handler_recv (BufferWriter *o, uint8_t *data) +{ + ASSERT(!o->out_have) + + // set output packet + o->out_have = 1; + o->out = data; +} + +void BufferWriter_Init (BufferWriter *o, int mtu, BPendingGroup *pg) +{ + ASSERT(mtu >= 0) + + // init output + PacketRecvInterface_Init(&o->recv_interface, mtu, (PacketRecvInterface_handler_recv)output_handler_recv, o, pg); + + // set no output packet + o->out_have = 0; + + DebugObject_Init(&o->d_obj); + #ifndef NDEBUG + o->d_mtu = mtu; + o->d_writing = 0; + #endif +} + +void BufferWriter_Free (BufferWriter *o) +{ + DebugObject_Free(&o->d_obj); + + // free output + PacketRecvInterface_Free(&o->recv_interface); +} + +PacketRecvInterface * BufferWriter_GetOutput (BufferWriter *o) +{ + DebugObject_Access(&o->d_obj); + + return &o->recv_interface; +} + +int BufferWriter_StartPacket (BufferWriter *o, uint8_t **buf) +{ + ASSERT(!o->d_writing) + DebugObject_Access(&o->d_obj); + + if (!o->out_have) { + return 0; + } + + if (buf) { + *buf = o->out; + } + + #ifndef NDEBUG + o->d_writing = 1; + #endif + + return 1; +} + +void BufferWriter_EndPacket (BufferWriter *o, int len) +{ + ASSERT(len >= 0) + ASSERT(len <= o->d_mtu) + ASSERT(o->out_have) + ASSERT(o->d_writing) + DebugObject_Access(&o->d_obj); + + // set no output packet + o->out_have = 0; + + // finish packet + PacketRecvInterface_Done(&o->recv_interface, len); + + #ifndef NDEBUG + o->d_writing = 0; + #endif +} diff --git a/pool/shard004/C/0098765_sdk_mapped_flags.c b/pool/shard004/C/0098765_sdk_mapped_flags.c new file mode 100644 index 0000000000000000000000000000000000000000..78d3929ea8554976cefa848f644c1955e6e51673 --- /dev/null +++ b/pool/shard004/C/0098765_sdk_mapped_flags.c @@ -0,0 +1,181 @@ +/* + * Copyright (c) Nordic Semiconductor ASA + * 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 Nordic Semiconductor ASA nor the names of other + * contributors to this software may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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 "sdk_mapped_flags.h" +#include +#include +#include +#include "compiler_abstraction.h" + + +/**@brief Function for setting the state of a flag to true. + * + * @note This function does not check whether the index is valid. + * + * @param[in] p_flags The collection of flags to modify. + * @param[in] index The index of the flag to modify. + */ +static __INLINE void sdk_mapped_flags_set_by_index(sdk_mapped_flags_t * p_flags, uint16_t index) +{ + *p_flags |= (1U << index); +} + + +/**@brief Function for setting the state of a flag to false. + * + * @note This function does not check whether the index is valid. + * + * @param[in] p_flags The collection of flags to modify. + * @param[in] index The index of the flag to modify. + */ +static __INLINE void sdk_mapped_flags_clear_by_index(sdk_mapped_flags_t * p_flags, uint16_t index) +{ + *p_flags &= ~(1U << index); +} + + +/**@brief Function for getting the state of a flag. + * + * @note This function does not check whether the index is valid. + * + * @param[in] p_flags The collection of flags to read. + * @param[in] index The index of the flag to get. + */ +static __INLINE bool sdk_mapped_flags_get_by_index(sdk_mapped_flags_t flags, uint16_t index) +{ + return ((flags & (1 << index)) != 0); +} + + + +uint16_t sdk_mapped_flags_first_key_index_get(sdk_mapped_flags_t flags) +{ + for (uint16_t i = 0; i < SDK_MAPPED_FLAGS_N_KEYS; i++) + { + if (sdk_mapped_flags_get_by_index(flags, i)) + { + return i; + } + } + return SDK_MAPPED_FLAGS_INVALID_INDEX; +} + + +void sdk_mapped_flags_update_by_key(uint16_t * p_keys, + sdk_mapped_flags_t * p_flags, + uint16_t key, + bool value) +{ + sdk_mapped_flags_bulk_update_by_key(p_keys, p_flags, 1, key, value); +} + + +void sdk_mapped_flags_bulk_update_by_key(uint16_t * p_keys, + sdk_mapped_flags_t * p_flags, + uint32_t n_flag_collections, + uint16_t key, + bool value) +{ + if ((p_keys != NULL) && (p_flags != NULL) && (n_flag_collections > 0)) + { + for (int i = 0; i < SDK_MAPPED_FLAGS_N_KEYS; i++) + { + if (p_keys[i] == key) + { + for (uint32_t j = 0; j < n_flag_collections; j++) + { + if (value) + { + sdk_mapped_flags_set_by_index(&p_flags[j], i); + } + else + { + sdk_mapped_flags_clear_by_index(&p_flags[j], i); + } + } + return; + } + } + } +} + + +bool sdk_mapped_flags_get_by_key(uint16_t * p_keys, sdk_mapped_flags_t flags, uint16_t key) +{ + if (p_keys != NULL) + { + for (int i = 0; i < SDK_MAPPED_FLAGS_N_KEYS; i++) + { + if (p_keys[i] == key) + { + return sdk_mapped_flags_get_by_index(flags, i); + } + } + } + return false; +} + + +sdk_mapped_flags_key_list_t sdk_mapped_flags_key_list_get(uint16_t * p_keys, + sdk_mapped_flags_t flags) +{ + sdk_mapped_flags_key_list_t key_list; + key_list.len = 0; + + if (p_keys != NULL) + { + for (int i = 0; i < SDK_MAPPED_FLAGS_N_KEYS; i++) + { + if (sdk_mapped_flags_get_by_index(flags, i)) + { + key_list.flag_keys[key_list.len++] = p_keys[i]; + } + } + } + + return key_list; +} + + +uint32_t sdk_mapped_flags_n_flags_set(sdk_mapped_flags_t flags) +{ + uint32_t n_flags_set = 0; + + for (int i = 0; i < SDK_MAPPED_FLAGS_N_KEYS; i++) + { + if (sdk_mapped_flags_get_by_index(flags, i)) + { + n_flags_set += 1; + } + } + return n_flags_set; +} diff --git a/pool/shard004/C/0098768_popen2.c b/pool/shard004/C/0098768_popen2.c new file mode 100644 index 0000000000000000000000000000000000000000..450df00bd7c8235cccc2e7b66571c7da2758922a --- /dev/null +++ b/pool/shard004/C/0098768_popen2.c @@ -0,0 +1,214 @@ +/*****************************************************************************\ + * Copyright (c) 2016 Lawrence Livermore National Security, LLC. Produced at + * the Lawrence Livermore National Laboratory (cf, AUTHORS, DISCLAIMER.LLNS). + * LLNL-CODE-658032 All rights reserved. + * + * This file is part of the Flux resource manager framework. + * For details, see https://github.com/flux-framework. + * + * 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. + * + * Flux is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the IMPLIED WARRANTY OF MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the terms and conditions of 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. + * See also: http://www.gnu.org/licenses/ +\*****************************************************************************/ + +#if HAVE_CONFIG_H +#include "config.h" +#endif +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "popen2.h" +#include "fdwalk.h" + +#define PXOPEN_CHILD_MAGIC 0xc00ceeee + +struct popen2_child { + int magic; + int fd[2]; + int ctl[2]; + pid_t pid; +}; + +enum { + SP_PARENT = 0, + SP_CHILD = 1, +}; + +int popen2_get_fd (struct popen2_child *p) +{ + if (!p || p->magic != PXOPEN_CHILD_MAGIC) { + errno = EINVAL; + return -1; + } + return p->fd[SP_PARENT]; +} + +static void popen2_child_close_fd (void *arg, int fd) +{ + struct popen2_child *p = arg; + if (fd != STDIN_FILENO && fd != STDOUT_FILENO && fd != STDERR_FILENO + && fd != p->ctl[SP_CHILD]) + (void)close (fd); +} + +static void child (struct popen2_child *p, const char *path, char *const argv[]) +{ + int saved_errno; + + (void)close (STDIN_FILENO); + (void)close (STDOUT_FILENO); + if ( dup2 (p->fd[SP_CHILD], STDIN_FILENO) < 0 + || dup2 (p->fd[SP_CHILD], STDOUT_FILENO) < 0) { + saved_errno = errno; + goto error; + } + (void)close (p->fd[SP_CHILD]); + + if (fdwalk (popen2_child_close_fd, p)) { + saved_errno = errno; + goto error; + } + execvp (path, argv); + saved_errno = errno; +error: + if (write (p->ctl[SP_CHILD], &saved_errno, sizeof (saved_errno)) < 0) + fprintf (stderr, "child: write to ctl failed: %s\n", strerror (errno)); + (void) close (p->ctl[SP_CHILD]); + exit (0); +} + +struct popen2_child *popen2 (const char *path, char *const argv[]) +{ + struct popen2_child *p = NULL; + int n, saved_errno, flags; + + if (!(p = malloc (sizeof (*p)))) { + saved_errno = ENOMEM; + goto error; + } + memset (p, 0, sizeof (*p)); + p->magic = PXOPEN_CHILD_MAGIC; + p->fd[SP_CHILD] = -1; + p->fd[SP_PARENT] = -1; + p->ctl[SP_CHILD] = -1; + p->ctl[SP_PARENT] = -1; + if (socketpair (PF_LOCAL, SOCK_STREAM, 0, p->fd) < 0) { + saved_errno = errno; + goto error; + } + if ((flags = fcntl (p->fd[SP_PARENT], F_GETFL)) < 0 + || fcntl (p->fd[SP_PARENT], F_SETFL, flags | O_CLOEXEC) < 0) { + saved_errno = errno; + goto error; + } + if (pipe2 (p->ctl, O_CLOEXEC) < 0) { + saved_errno = errno; + goto error; + } + signal(SIGPIPE, SIG_IGN); + switch ((p->pid = fork ())) { + case -1: /* fork error */ + saved_errno = errno; + goto error; + case 0: /* child */ + child (p, path, argv); + /*NOTREACHED*/ + default: /* parent */ + break; + } + (void)close (p->fd[SP_CHILD]); + (void)close (p->ctl[SP_CHILD]); + p->fd[SP_CHILD] = -1; + p->ctl[SP_CHILD] = -1; + + /* Handshake on ctl pipe to make sure exec worked. + * If exec successful, child end will be closed with no data. + * If exec failed, errno will be returned on pipe. + */ + n = read (p->ctl[SP_PARENT], &saved_errno, sizeof (saved_errno)); + if (n == sizeof (saved_errno)) + goto error; + if (n < 0) { + saved_errno = errno; + goto error; + } + if (n != 0) { + saved_errno = EPROTO; + goto error; + } + (void)close (p->ctl[SP_PARENT]); + p->ctl[SP_PARENT] = -1; + + return p; +error: + pclose2 (p); + errno = saved_errno; + return NULL; +} + +int pclose2 (struct popen2_child *p) +{ + int status, saved_errno = 0; + int rc = 0; + + if (p) { + if (p->magic != PXOPEN_CHILD_MAGIC) { + saved_errno = EINVAL; + rc = -1; + goto done; + } + if (p->fd[SP_PARENT] && shutdown (p->fd[SP_PARENT], SHUT_WR) < 0) { + saved_errno = errno; + rc = -1; + } + if (p->pid != 0) { + if (waitpid (p->pid, &status, 0) < 0) { + saved_errno = errno; + rc = -1; + } else { + if (!WIFEXITED (status) || WEXITSTATUS (status) != 0) { + saved_errno = EIO; + rc = -1; + } + } + } + if ((p->fd[SP_PARENT] >= 0 && close (p->fd[SP_PARENT]) < 0) + || (p->fd[SP_CHILD] >= 0 && close (p->fd[SP_CHILD]) < 0) + || (p->ctl[SP_PARENT] >= 0 && close (p->ctl[SP_PARENT]) < 0) + || (p->ctl[SP_CHILD] >= 0 && close (p->ctl[SP_CHILD]) < 0)) { + saved_errno = errno; + rc = -1; + } + p->magic = ~PXOPEN_CHILD_MAGIC; + free (p); + } +done: + if (rc == -1) + errno = saved_errno; + return rc; +} + +/* + * vi:tabstop=4 shiftwidth=4 expandtab + */ diff --git a/pool/shard004/C/0098772_recvmsg.c b/pool/shard004/C/0098772_recvmsg.c new file mode 100644 index 0000000000000000000000000000000000000000..4f526659183defd2405ed6961b8ccca9e8ded1f5 --- /dev/null +++ b/pool/shard004/C/0098772_recvmsg.c @@ -0,0 +1,22 @@ +#include +#include +#include "syscall.h" +#include "libc.h" + +ssize_t recvmsg(int fd, struct msghdr *msg, int flags) +{ + ssize_t r; +#if LONG_MAX > INT_MAX + struct msghdr h, *orig = msg; + if (msg) { + h = *msg; + h.__pad1 = h.__pad2 = 0; + msg = &h; + } +#endif + r = socketcall_cp(recvmsg, fd, msg, flags, 0, 0, 0); +#if LONG_MAX > INT_MAX + if (orig) *orig = h; +#endif + return r; +} diff --git a/pool/shard004/C/0098777_global_state.c b/pool/shard004/C/0098777_global_state.c new file mode 100644 index 0000000000000000000000000000000000000000..2c8c447239673df1d715c598def3124a3d1a61ba --- /dev/null +++ b/pool/shard004/C/0098777_global_state.c @@ -0,0 +1,147 @@ +/* + * Global State configuration + * + * Copyright (c) 2014-2017 Red Hat Inc + * + * Authors: + * Juan Quintela + * + * 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 "qemu/osdep.h" +#include "qemu/cutils.h" +#include "qemu/error-report.h" +#include "qapi/error.h" +#include "migration.h" +#include "migration/global_state.h" +#include "migration/vmstate.h" +#include "trace.h" + +typedef struct { + uint32_t size; + uint8_t runstate[100]; + RunState state; + bool received; +} GlobalState; + +static GlobalState global_state; + +int global_state_store(void) +{ + if (!runstate_store((char *)global_state.runstate, + sizeof(global_state.runstate))) { + error_report("runstate name too big: %s", global_state.runstate); + trace_migrate_state_too_big(); + return -EINVAL; + } + return 0; +} + +void global_state_store_running(void) +{ + const char *state = RunState_str(RUN_STATE_RUNNING); + assert(strlen(state) < sizeof(global_state.runstate)); + strncpy((char *)global_state.runstate, + state, sizeof(global_state.runstate)); +} + +bool global_state_received(void) +{ + return global_state.received; +} + +RunState global_state_get_runstate(void) +{ + return global_state.state; +} + +static bool global_state_needed(void *opaque) +{ + GlobalState *s = opaque; + char *runstate = (char *)s->runstate; + + /* If it is not optional, it is mandatory */ + + if (migrate_get_current()->store_global_state) { + return true; + } + + /* If state is running or paused, it is not needed */ + + if (strcmp(runstate, "running") == 0 || + strcmp(runstate, "paused") == 0) { + return false; + } + + /* for any other state it is needed */ + return true; +} + +static int global_state_post_load(void *opaque, int version_id) +{ + GlobalState *s = opaque; + Error *local_err = NULL; + int r; + char *runstate = (char *)s->runstate; + + s->received = true; + trace_migrate_global_state_post_load(runstate); + + if (strnlen((char *)s->runstate, + sizeof(s->runstate)) == sizeof(s->runstate)) { + /* + * This condition should never happen during migration, because + * all runstate names are shorter than 100 bytes (the size of + * s->runstate). However, a malicious stream could overflow + * the qapi_enum_parse() call, so we force the last character + * to a NUL byte. + */ + s->runstate[sizeof(s->runstate) - 1] = '\0'; + } + r = qapi_enum_parse(&RunState_lookup, runstate, -1, &local_err); + + if (r == -1) { + if (local_err) { + error_report_err(local_err); + } + return -EINVAL; + } + s->state = r; + + return 0; +} + +static int global_state_pre_save(void *opaque) +{ + GlobalState *s = opaque; + + trace_migrate_global_state_pre_save((char *)s->runstate); + s->size = strnlen((char *)s->runstate, sizeof(s->runstate)) + 1; + assert(s->size <= sizeof(s->runstate)); + + return 0; +} + +static const VMStateDescription vmstate_globalstate = { + .name = "globalstate", + .version_id = 1, + .minimum_version_id = 1, + .post_load = global_state_post_load, + .pre_save = global_state_pre_save, + .needed = global_state_needed, + .fields = (VMStateField[]) { + VMSTATE_UINT32(size, GlobalState), + VMSTATE_BUFFER(runstate, GlobalState), + VMSTATE_END_OF_LIST() + }, +}; + +void register_global_state(void) +{ + /* We would use it independently that we receive it */ + strcpy((char *)&global_state.runstate, ""); + global_state.received = false; + vmstate_register(NULL, 0, &vmstate_globalstate, &global_state); +} diff --git a/pool/shard004/C/0098778_main.c b/pool/shard004/C/0098778_main.c new file mode 100644 index 0000000000000000000000000000000000000000..82529b594f8988d3e6841ddff30fbbf80805a29f --- /dev/null +++ b/pool/shard004/C/0098778_main.c @@ -0,0 +1,26 @@ +#include + +/* + multi-line + comments are + simple as well. +*/ + +/* the function is defined here, but expressed below */ +int add_numbers (int a, int b); + +/* main function defined near top */ +int main(int argc, const char *argv[]) { + int result; /* comment on same line as code */ + + result = add_numbers(4, 3); + printf("sum is %d.\n", result); + return 0; +} + +/* comments are taken out when compiled, so it doesn't affect performance */ +int add_numbers (int a, int b) { + int sum; + sum = a + b; + return sum; +} diff --git a/pool/shard004/C/0098781_trans_passwd.c b/pool/shard004/C/0098781_trans_passwd.c new file mode 100644 index 0000000000000000000000000000000000000000..47da9122d9682ff92ee0978af3620b10e2d1ced3 --- /dev/null +++ b/pool/shard004/C/0098781_trans_passwd.c @@ -0,0 +1,77 @@ +#include "bbs.h" +#include "ythtlib.h" +#include "ythtbbs.h" +#include +#include +#include + +void +upgradepasswd() +{ + FILE *fr, *fw; + struct old_userec oldrec; + struct userec rec; + struct userdata data; + struct in_addr in; + int num = 0; + fr = fopen(PASSFILE, "r"); + if (NULL == fr) { + printf("Can't open passwd file for read!\n"); + exit(1); + } + fw = fopen(MY_BBS_HOME "/.NEWPASSWDS", "w"); + if (NULL == fw) { + printf("Can't open passwd file for write!\n"); + fclose(fr); + exit(2); + } + while (fread(&oldrec, sizeof (oldrec), 1, fr) == 1) { + if (!oldrec.userid[0]) + continue; + num++; + bzero(&rec, sizeof(rec)); + bzero(&data, sizeof(data)); + strcpy(rec.userid, oldrec.userid); + memcpy(rec.flags, oldrec.flags, 2); + rec.firstlogin = oldrec.firstlogin; + rec.lastlogin = oldrec.lastlogin; + rec.lastlogout = oldrec.lastlogout; + rec.dietime = oldrec.dietime; + if (inet_aton(oldrec.lasthost, &in)) + rec.lasthost = in.s_addr; + strcpy(rec.username, oldrec.username); + rec.numdays = oldrec.numdays; + if (oldrec.signature >= -1 && oldrec.signature <=100) + rec.signature = oldrec.signature; + else + rec.signature = 0; + rec.numlogins = oldrec.numlogins; + rec.numposts = oldrec.numposts; + rec.stay = oldrec.stay; + rec.userlevel = oldrec.userlevel; + if (inet_aton(oldrec.ip, &in)) + rec.ip = in.s_addr; + rec.userdefine = oldrec.userdefine; + memcpy(rec.passwd, oldrec.passwd, OLDPASSLEN); + strncpy(data.realmail, oldrec.realmail, 60); + data.realmail[59] = 0; + strncpy(data.email, oldrec.email, 60); + data.email[59] = 0; + strncpy(data.realname, oldrec.realname, 40); + data.realname[39] = 0; + strncpy(data.address, oldrec.address, 40); + data.address[39] = 0; + fwrite(&rec, sizeof (rec), 1, fw); + saveuserdata(rec.userid, &data); + } + fclose(fr); + fclose(fw); + printf("total user=%d", num); +} + +int +main() +{ + upgradepasswd(); + return 0; +} diff --git a/pool/shard004/C/0098782_clocks.c b/pool/shard004/C/0098782_clocks.c new file mode 100644 index 0000000000000000000000000000000000000000..3dee63b7d6e59f7d42083cc3e600851b4d965ca9 --- /dev/null +++ b/pool/shard004/C/0098782_clocks.c @@ -0,0 +1,117 @@ +/* + * arch/arm/mach-s3c24a0/clocks.c + * + * $Id: clocks.c,v 1.3 2006/12/12 13:38:48 gerg Exp $ + * + * 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 + + + +static unsigned long get_usb_clk_freq(int who) +{ + unsigned long val = UPLLCON; + + if (CLKSRC & (1<<7)) return 0; /* UPLL OFF */ + val = ((GET_MDIV(val) + 8) * FIN)/((GET_PDIV(val) + 2) * (1 << GET_SDIV(val))); + return val; +} + +/* + * CLKDIVN differs from S3C24A0X to S3C24A0A + * --SW.LEE + */ + +static inline unsigned long +cal_bus_clk(unsigned long cpu_clk, unsigned long ratio, int who) +{ + unsigned long hclk = 0; + unsigned long pclk = 0; + + if (who == GET_UPLL) + return get_usb_clk_freq(GET_UPLL); + + switch (ratio & 0x6) { + case 0: + hclk = cpu_clk; + break; + case 2: + hclk = cpu_clk/2; + break; + case 4: + hclk = cpu_clk/4; + break; + default: + panic("Wrong Value in CLKDIVN"); + } + switch (ratio & 0x1) { + case 0: + pclk = hclk; + break; + case 1: + pclk = hclk/2; + break; + } + + if (who == GET_HCLK) + return hclk; + else { + if (who == GET_PCLK) + return pclk; + else + panic("Wrong Clock requested "); + } +} + + +/* + * cpu clock = (((mdiv + 8) * FIN) / ((pdiv + 2) * (1 << sdiv))) + * FIN = Input Frequency (to CPU) + */ +unsigned long +elfin_get_cpu_clk(void) +{ + unsigned long val = MPLLCON; + + return (((GET_MDIV(val) + 8) * FIN) / ((GET_PDIV(val) + 2) * (1 << GET_SDIV(val)))); +} +EXPORT_SYMBOL(elfin_get_cpu_clk); + +unsigned long +elfin_get_bus_clk(int who) +{ + unsigned long cpu_clk = elfin_get_cpu_clk(); + unsigned long ratio = CLKDIVN_BUS; + + return (cal_bus_clk(cpu_clk, ratio, who)); +} +EXPORT_SYMBOL(elfin_get_bus_clk); + +#define MEGA (1000 * 1000) +static int __init elfin_cpu_init(void) +{ + unsigned long freq, hclk, pclk; + + freq = elfin_get_cpu_clk(); + hclk = elfin_get_bus_clk(GET_HCLK); + pclk = elfin_get_bus_clk(GET_PCLK); + + printk(KERN_INFO "CPU clock = %ld.%03ld Mhz,", freq / MEGA, freq % MEGA); + + printk(" HCLK = %ld.%03ld Mhz, PCLK = %ld.%03ld Mhz\n", + hclk / MEGA, hclk % MEGA, pclk / MEGA, pclk % MEGA); + + return 0; +} + +__initcall(elfin_cpu_init); diff --git a/pool/shard004/C/0098783_ltc3216.c b/pool/shard004/C/0098783_ltc3216.c new file mode 100644 index 0000000000000000000000000000000000000000..77db7e9cdf30786bcb5befc6124230b390ac141d --- /dev/null +++ b/pool/shard004/C/0098783_ltc3216.c @@ -0,0 +1,252 @@ +/** + * Copyright (c) 2008 NVIDIA Corporation. All rights reserved. + * + * NVIDIA Corporation and its licensors retain all intellectual property + * and proprietary rights in and to this software and related documentation + * and any modifications thereto. Any use, reproduction, disclosure or + * distribution of this software and related documentation without an express + * license agreement from NVIDIA Corporation is strictly prohibited. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#define LTC3216_MAX_RETRIES (3) + +struct ltc3216_info { + struct i2c_client *i2c_client; + int torch_on; +}; + +struct ltc3216_info *info_flash = NULL; + +static int ltc3216_write(struct i2c_client *client, u16 value) +{ + int count; + struct i2c_msg msg[1]; + unsigned char data[2]; + int retry = 0; + + if (!client->adapter) + return -ENODEV; + + data[0] = (u8) (value >> 8); + data[1] = (u8) (value & 0xFF); + + msg[0].addr = client->addr; + msg[0].flags = 0; + msg[0].len = ARRAY_SIZE(data); + msg[0].buf = data; + + do { + count = i2c_transfer(client->adapter, msg, ARRAY_SIZE(msg)); + if (count == ARRAY_SIZE(msg)) + return 0; + retry++; + dev_err(&client->dev, "i2c transfer failed, retrying %x\n", + value); + msleep(3); + } while (retry <= LTC3216_MAX_RETRIES); + + return -EIO; +} + + +static long ltc3216_ioctl(struct file *file, + unsigned int cmd, unsigned long arg) +{ + struct ltc3216_info *info_flash = file->private_data; + + switch (cmd) { + case LTC3216_IOCTL_FLASH_ON: + ltc3216_write(info_flash->i2c_client, 0x90); + ltc3216_write(info_flash->i2c_client, (u16) arg); + break; + + case LTC3216_IOCTL_FLASH_OFF: + ltc3216_write(info_flash->i2c_client, 0x00); + ltc3216_write(info_flash->i2c_client, 0x104); + break; + + case LTC3216_IOCTL_TORCH_ON: + info_flash->torch_on = true; + ltc3216_write(info_flash->i2c_client, (u16) arg); + break; + + case LTC3216_IOCTL_TORCH_OFF: + info_flash->torch_on = false; + ltc3216_write(info_flash->i2c_client, 0x00); + break; + default: + return -EINVAL; + } + + return 0; +} + + +static int ltc3216_open(struct inode *inode, struct file *file) +{ + file->private_data = info_flash; + return 0; +} + +int ltc3216_release(struct inode *inode, struct file *file) +{ + if (info_flash->torch_on) + ltc3216_write(info_flash->i2c_client, 0x00); + file->private_data = NULL; + return 0; +} + + +static const struct file_operations ltc3216_fileops = { + .owner = THIS_MODULE, + .open = ltc3216_open, + .unlocked_ioctl = ltc3216_ioctl, + .release = ltc3216_release, +}; + +static struct miscdevice ltc3216_device = { + .minor = MISC_DYNAMIC_MINOR, + .name = "ltc3216", + .fops = <c3216_fileops, +}; + +void ltc3216_turn_on_flash(void) +{ + if (!info_flash) + return; + + // set STIM to 11111b, Timer = STIM x 32.8ms = 1.02s + ltc3216_write(info_flash->i2c_client, 0x03DF); + + ltc3216_write(info_flash->i2c_client, 0x0090); + ltc3216_write(info_flash->i2c_client, 0x018E); +} + +void ltc3216_turn_off_flash(void) +{ + if (!info_flash) + return; + + ltc3216_write(info_flash->i2c_client, 0x0000); + ltc3216_write(info_flash->i2c_client, 0x0104); +} + +void ltc3216_turn_on_torch(void) +{ + if (!info_flash) + return; + + ltc3216_write(info_flash->i2c_client, 0x0053); +} + +void ltc3216_turn_off_torch(void) +{ + if (!info_flash) + return; + + ltc3216_write(info_flash->i2c_client, 0x0000); +} + +static ssize_t torch_read(struct device *dev, struct device_attribute *attr, + char *buf) +{ + return sprintf(buf, "%d\n", !!info_flash->torch_on); +} + +static ssize_t torch_write(struct device *dev, struct device_attribute *attr, + const char *buf, size_t size) +{ + if (sscanf(buf, "%d\n", &info_flash->torch_on) > 0) { + dev_dbg(dev, "%s %s\n", + __func__, info_flash->torch_on ? "on" : "off"); + + if (info_flash->torch_on) + ltc3216_turn_on_torch(); + else + ltc3216_turn_off_torch(); + } else + dev_err(dev, "%s: input error\n", __func__); + + return size; +} + +static DEVICE_ATTR(brightness, 0664, torch_read, torch_write); + +static struct attribute *torch_attributes[] = { + &dev_attr_brightness.attr, + NULL, +}; + +static struct attribute_group torch_group = { + .attrs = torch_attributes, +}; + +static int ltc3216_probe(struct i2c_client *client, + const struct i2c_device_id *id) +{ + int err; + + info_flash = devm_kzalloc(&client->dev, sizeof(*info_flash), GFP_KERNEL); + if (!info_flash) { + dev_err(&client->dev, "unable to allocate memory\n"); + return -ENOMEM; + } + info_flash->i2c_client = client; + + err = misc_register(<c3216_device); + if (err) { + dev_err(&client->dev, "unable to register misc device\n"); + return err; + } + + err = sysfs_create_group(<c3216_device.this_device->kobj, + &torch_group); + if (err) { + dev_err(&client->dev, "sysfs group create failed\n"); + misc_deregister(<c3216_device); + return err; + } + + return 0; +} + +static int ltc3216_remove(struct i2c_client *client) +{ + sysfs_remove_group(<c3216_device.this_device->kobj, &torch_group); + misc_deregister(<c3216_device); + return 0; +} + +static const struct i2c_device_id ltc3216_id[] = { + { "ltc3216", 0 }, + { }, +}; +MODULE_DEVICE_TABLE(i2c, ltc3216_id); + +static struct of_device_id ltc3216_of_match[] = { + { .compatible = "nvidia,ltc3216", }, + { }, +}; +MODULE_DEVICE_TABLE(of, ltc3216_of_match); + +static struct i2c_driver ltc3216_i2c_driver = { + .driver = { + .name = "ltc3216", + .owner = THIS_MODULE, + .of_match_table = of_match_ptr(ltc3216_of_match), + }, + .probe = ltc3216_probe, + .remove = ltc3216_remove, + .id_table = ltc3216_id, +}; +module_i2c_driver(ltc3216_i2c_driver); diff --git a/pool/shard004/C/0098784_dbg.c b/pool/shard004/C/0098784_dbg.c new file mode 100644 index 0000000000000000000000000000000000000000..fe86e16b2cb30968a1e74f3bb2fc516d53ed9091 --- /dev/null +++ b/pool/shard004/C/0098784_dbg.c @@ -0,0 +1,60 @@ +/** + * + * Copyright (c) 2013, Scott Reynolds. + * 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 Mongrel2 Project, Zed A. Shaw, 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. + */ + +// Derived from Mongrel2. +#include "dbg.h" +#include "bstring.h" + +FILE *LOG_FILE = NULL; + +void dbg_set_log(FILE *log_file) +{ + LOG_FILE = log_file; +} + + +FILE *dbg_get_log() +{ + return LOG_FILE != NULL ? LOG_FILE : stderr; +} + +void fprintf_with_timestamp(FILE *log_file, const severity_t severity, const char *format, ...) +{ + va_list args; + char* json_format = syslog_parser_internal_message(severity, format); + va_start(args, json_format); + vfprintf(log_file, json_format, args); + fprintf(log_file, "\n"); + va_end(args); +} diff --git a/pool/shard004/C/0098791_bedbug.c b/pool/shard004/C/0098791_bedbug.c new file mode 100644 index 0000000000000000000000000000000000000000..9fee5288301971e3ece57198b9437ee5c57ce2b0 --- /dev/null +++ b/pool/shard004/C/0098791_bedbug.c @@ -0,0 +1,404 @@ +/* + * BedBug Functions + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +DECLARE_GLOBAL_DATA_PTR; + +extern void show_regs __P ((struct pt_regs *)); +extern int run_command __P ((const char *, int)); + +ulong dis_last_addr = 0; /* Last address disassembled */ +ulong dis_last_len = 20; /* Default disassembler length */ +CPU_DEBUG_CTX bug_ctx; /* Bedbug context structure */ + + +/* ====================================================================== + * U-Boot's puts function does not append a newline, so the bedbug stuff + * will use this for the output of the dis/assembler. + * ====================================================================== */ + +int bedbug_puts (const char *str) +{ + /* -------------------------------------------------- */ + + printf ("%s\r\n", str); + return 0; +} /* bedbug_puts */ + + + +/* ====================================================================== + * Initialize the bug_ctx structure used by the bedbug debugger. This is + * specific to the CPU since each has different debug registers and + * settings. + * ====================================================================== */ + +void bedbug_init (void) +{ + /* -------------------------------------------------- */ + return; +} /* bedbug_init */ + + + +/* ====================================================================== + * Entry point from the interpreter to the disassembler. Repeated calls + * will resume from the last disassembled address. + * ====================================================================== */ +int do_bedbug_dis (cmd_tbl_t * cmdtp, int flag, int argc, char * const argv[]) +{ + ulong addr; /* Address to start disassembly from */ + ulong len; /* # of instructions to disassemble */ + + /* -------------------------------------------------- */ + + /* Setup to go from the last address if none is given */ + addr = dis_last_addr; + len = dis_last_len; + + if (argc < 2) + return CMD_RET_USAGE; + + if ((flag & CMD_FLAG_REPEAT) == 0) { + /* New command */ + addr = simple_strtoul (argv[1], NULL, 16); + + /* If an extra param is given then it is the length */ + if (argc > 2) + len = simple_strtoul (argv[2], NULL, 16); + } + + /* Run the disassembler */ + disppc ((unsigned char *) addr, 0, len, bedbug_puts, F_RADHEX); + + dis_last_addr = addr + (len * 4); + dis_last_len = len; + return 0; +} /* do_bedbug_dis */ + +U_BOOT_CMD (ds, 3, 1, do_bedbug_dis, + "disassemble memory", + "ds
[# instructions]"); + +/* ====================================================================== + * Entry point from the interpreter to the assembler. Assembles + * instructions in consecutive memory locations until a '.' (period) is + * entered on a line by itself. + * ====================================================================== */ +int do_bedbug_asm (cmd_tbl_t * cmdtp, int flag, int argc, char * const argv[]) +{ + long mem_addr; /* Address to assemble into */ + unsigned long instr; /* Machine code for text */ + char prompt[15]; /* Prompt string for user input */ + int asm_err; /* Error code from the assembler */ + + /* -------------------------------------------------- */ + int rcode = 0; + + if (argc < 2) + return CMD_RET_USAGE; + + printf ("\nEnter '.' when done\n"); + mem_addr = simple_strtoul (argv[1], NULL, 16); + + while (1) { + putc ('\n'); + disppc ((unsigned char *) mem_addr, 0, 1, bedbug_puts, + F_RADHEX); + + sprintf (prompt, "%08lx: ", mem_addr); + cli_readline(prompt); + + if (console_buffer[0] && strcmp (console_buffer, ".")) { + if ((instr = + asmppc (mem_addr, console_buffer, + &asm_err)) != 0) { + *(unsigned long *) mem_addr = instr; + mem_addr += 4; + } else { + printf ("*** Error: %s ***\n", + asm_error_str (asm_err)); + rcode = 1; + } + } else { + break; + } + } + return rcode; +} /* do_bedbug_asm */ + +U_BOOT_CMD (as, 2, 0, do_bedbug_asm, + "assemble memory", "as
"); + +/* ====================================================================== + * Used to set a break point from the interpreter. Simply calls into the + * CPU-specific break point set routine. + * ====================================================================== */ + +int do_bedbug_break (cmd_tbl_t * cmdtp, int flag, int argc, char * const argv[]) +{ + /* -------------------------------------------------- */ + if (bug_ctx.do_break) + (*bug_ctx.do_break) (cmdtp, flag, argc, argv); + return 0; + +} /* do_bedbug_break */ + +U_BOOT_CMD (break, 3, 0, do_bedbug_break, + "set or clear a breakpoint", + " - Set or clear a breakpoint\n" + "break
- Break at an address\n" + "break off - Disable breakpoint.\n" + "break show - List breakpoints."); + +/* ====================================================================== + * Called from the debug interrupt routine. Simply calls the CPU-specific + * breakpoint handling routine. + * ====================================================================== */ + +void do_bedbug_breakpoint (struct pt_regs *regs) +{ + /* -------------------------------------------------- */ + + if (bug_ctx.break_isr) + (*bug_ctx.break_isr) (regs); + + return; +} /* do_bedbug_breakpoint */ + + + +/* ====================================================================== + * Called from the CPU-specific breakpoint handling routine. Enter a + * mini main loop until the stopped flag is cleared from the breakpoint + * context. + * + * This handles the parts of the debugger that are common to all CPU's. + * ====================================================================== */ + +void bedbug_main_loop (unsigned long addr, struct pt_regs *regs) +{ + int len; /* Length of command line */ + int flag; /* Command flags */ + int rc = 0; /* Result from run_command */ + char prompt_str[20]; /* Prompt string */ + static char lastcommand[CONFIG_SYS_CBSIZE] = { 0 }; /* previous command */ + /* -------------------------------------------------- */ + + if (bug_ctx.clear) + (*bug_ctx.clear) (bug_ctx.current_bp); + + printf ("Breakpoint %d: ", bug_ctx.current_bp); + disppc ((unsigned char *) addr, 0, 1, bedbug_puts, F_RADHEX); + + bug_ctx.stopped = 1; + bug_ctx.regs = regs; + + sprintf (prompt_str, "BEDBUG.%d =>", bug_ctx.current_bp); + + /* A miniature main loop */ + while (bug_ctx.stopped) { + len = cli_readline(prompt_str); + + flag = 0; /* assume no special flags for now */ + + if (len > 0) + strcpy (lastcommand, console_buffer); + else if (len == 0) + flag |= CMD_FLAG_REPEAT; + + if (len == -1) + printf ("\n"); + else + rc = run_command_repeatable(lastcommand, flag); + + if (rc <= 0) { + /* invalid command or not repeatable, forget it */ + lastcommand[0] = 0; + } + } + + bug_ctx.regs = NULL; + bug_ctx.current_bp = 0; + + return; +} /* bedbug_main_loop */ + + + +/* ====================================================================== + * Interpreter command to continue from a breakpoint. Just clears the + * stopped flag in the context so that the breakpoint routine will + * return. + * ====================================================================== */ +int do_bedbug_continue (cmd_tbl_t * cmdtp, int flag, int argc, char * const argv[]) +{ + /* -------------------------------------------------- */ + + if (!bug_ctx.stopped) { + printf ("Not at a breakpoint\n"); + return 1; + } + + bug_ctx.stopped = 0; + return 0; +} /* do_bedbug_continue */ + +U_BOOT_CMD (continue, 1, 0, do_bedbug_continue, + "continue from a breakpoint", + ""); + +/* ====================================================================== + * Interpreter command to continue to the next instruction, stepping into + * subroutines. Works by calling the find_next_addr() routine to compute + * the address passes control to the CPU-specific set breakpoint routine + * for the current breakpoint number. + * ====================================================================== */ +int do_bedbug_step (cmd_tbl_t * cmdtp, int flag, int argc, char * const argv[]) +{ + unsigned long addr; /* Address to stop at */ + + /* -------------------------------------------------- */ + + if (!bug_ctx.stopped) { + printf ("Not at a breakpoint\n"); + return 1; + } + + if (!find_next_address((unsigned char *) &addr, false, bug_ctx.regs)) + return 1; + + if (bug_ctx.set) + (*bug_ctx.set) (bug_ctx.current_bp, addr); + + bug_ctx.stopped = 0; + return 0; +} /* do_bedbug_step */ + +U_BOOT_CMD (step, 1, 1, do_bedbug_step, + "single step execution.", + ""); + +/* ====================================================================== + * Interpreter command to continue to the next instruction, stepping over + * subroutines. Works by calling the find_next_addr() routine to compute + * the address passes control to the CPU-specific set breakpoint routine + * for the current breakpoint number. + * ====================================================================== */ +int do_bedbug_next (cmd_tbl_t * cmdtp, int flag, int argc, char * const argv[]) +{ + unsigned long addr; /* Address to stop at */ + + /* -------------------------------------------------- */ + + if (!bug_ctx.stopped) { + printf ("Not at a breakpoint\n"); + return 1; + } + + if (!find_next_address((unsigned char *) &addr, true, bug_ctx.regs)) + return 1; + + if (bug_ctx.set) + (*bug_ctx.set) (bug_ctx.current_bp, addr); + + bug_ctx.stopped = 0; + return 0; +} /* do_bedbug_next */ + +U_BOOT_CMD (next, 1, 1, do_bedbug_next, + "single step execution, stepping over subroutines.", + ""); + +/* ====================================================================== + * Interpreter command to print the current stack. This assumes an EABI + * architecture, so it starts with GPR R1 and works back up the stack. + * ====================================================================== */ +int do_bedbug_stack (cmd_tbl_t * cmdtp, int flag, int argc, char * const argv[]) +{ + unsigned long sp; /* Stack pointer */ + unsigned long func; /* LR from stack */ + int depth; /* Stack iteration level */ + int skip = 1; /* Flag to skip the first entry */ + unsigned long top; /* Top of memory address */ + + /* -------------------------------------------------- */ + + if (!bug_ctx.stopped) { + printf ("Not at a breakpoint\n"); + return 1; + } + + top = gd->bd->bi_memstart + gd->bd->bi_memsize; + depth = 0; + + printf ("Depth PC\n"); + printf ("----- --------\n"); + printf ("%5d %08lx\n", depth++, bug_ctx.regs->nip); + + sp = bug_ctx.regs->gpr[1]; + func = *(unsigned long *) (sp + 4); + + while ((func < top) && (sp < top)) { + if (!skip) + printf ("%5d %08lx\n", depth++, func); + else + --skip; + + sp = *(unsigned long *) sp; + func = *(unsigned long *) (sp + 4); + } + return 0; +} /* do_bedbug_stack */ + +U_BOOT_CMD (where, 1, 1, do_bedbug_stack, + "Print the running stack.", + ""); + +/* ====================================================================== + * Interpreter command to dump the registers. Calls the CPU-specific + * show registers routine. + * ====================================================================== */ +int do_bedbug_rdump (cmd_tbl_t * cmdtp, int flag, int argc, char * const argv[]) +{ + /* -------------------------------------------------- */ + + if (!bug_ctx.stopped) { + printf ("Not at a breakpoint\n"); + return 1; + } + + show_regs (bug_ctx.regs); + return 0; +} /* do_bedbug_rdump */ + +U_BOOT_CMD (rdump, 1, 1, do_bedbug_rdump, + "Show registers.", ""); +/* ====================================================================== */ + + +/* + * Copyright (c) 2001 William L. Pitts + * All rights reserved. + * + * Redistribution and use in source and binary forms are freely + * permitted provided that the above copyright notice and this + * paragraph and the following disclaimer are duplicated in all + * such forms. + * + * This software is provided "AS IS" and without any express or + * implied warranties, including, without limitation, the implied + * warranties of merchantability and fitness for a particular + * purpose. + */ diff --git a/pool/shard004/C/0098794_spi.c b/pool/shard004/C/0098794_spi.c new file mode 100644 index 0000000000000000000000000000000000000000..eca5007aff24790b2a438645d8f3f21d74a1cdbd --- /dev/null +++ b/pool/shard004/C/0098794_spi.c @@ -0,0 +1,258 @@ +/************************************************************************* +* °æÈ¨ËùÓÐ(C) 1987-2020, ÉîÛÚ»ªÎª¼¼ÊõÓÐÏÞ¹«Ë¾. +* +* ÎÄ ¼þ Ãû : spi.c +* +* ×÷ Õß : wuzechun +* +* Ãè Êö : SPI¶ÁÈ¡Çý¶¯ +* +* Ð޸ļǼ : 2011Äê6ÔÂ9ÈÕ v1.00 wuzechun ´´½¨ +* +*************************************************************************/ + +#include "sys.h" +#include "OnChipRom.h" +#include "spi.h" +#include "ioinit.h" + +const UINT32 spiBase[2] = {ECS_SPI0_BASE, ECS_SPI1_BASE}; +/***************************************************************************** +* º¯ Êý Ãû : spiInit +* +* ¹¦ÄÜÃèÊö : ³õʼ»¯SPIÇý¶¯ +* +* ÊäÈë²ÎÊý : spiNo SPI¿ØÖÆÆ÷ºÅ +* +* Êä³ö²ÎÊý : +* +* ·µ »Ø Öµ : +* +* ÆäËü˵Ã÷ : +* +*****************************************************************************/ +INT32 spiInit(UINT32 spiNo) +{ + if ((0 != spiNo) && (1 != spiNo)) + { + return ERROR; + } + + SPI_IOS_SYS_CONFIG(); + + /* ½ûÖ¹SPI Slave*/ + OUTREG32(SPI_SLAVE_EN(spiNo), 0); + + /* ½ûÖ¹SPI Master*/ + OUTREG32(SPI_EN(spiNo), 0); + + /* ÅäÖÃctrl0¼Ä´æÆ÷£¬ÃüÁî×Ö³¤¶ÈΪ1£¬Êý¾Ý¿í¶ÈΪ8,ÉÏÉýÑØ´¥·¢,µÍµçƽÓÐЧ */ + OUTREG32(SPI_CTRL0(spiNo), (0x07< + +#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 + +#include +#define EXECV _wexecv + +/* The two variables below are not defined as "const", but are never + * assigned any other value, so a tool should be able to identify that + * reads of these will always return their initialized values. + */ +static int staticTrue = 1; /* true */ +static int staticFalse = 0; /* false */ + +#ifndef OMITBAD + +void CWE78_OS_Command_Injection__wchar_t_console_w32_execv_05_bad() +{ + wchar_t * data; + wchar_t dataBuffer[100] = L""; + data = dataBuffer; + if(staticTrue) + { + { + /* Read input from the console */ + size_t dataLen = wcslen(data); + /* if there is room in data, read into it from the console */ + if (100-dataLen > 1) + { + /* POTENTIAL FLAW: Read data from the console */ + if (fgetws(data+dataLen, (int)(100-dataLen), stdin) != NULL) + { + /* The next few lines remove the carriage return from the string that is + * inserted by fgetws() */ + dataLen = wcslen(data); + if (dataLen > 0 && data[dataLen-1] == L'\n') + { + data[dataLen-1] = L'\0'; + } + } + else + { + printLine("fgetws() failed"); + /* Restore NUL terminator if fgetws fails */ + data[dataLen] = L'\0'; + } + } + } + } + { + 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 staticTrue to staticFalse */ +static void goodG2B1() +{ + wchar_t * data; + wchar_t dataBuffer[100] = L""; + data = dataBuffer; + if(staticFalse) + { + /* 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(staticTrue) + { + /* 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_console_w32_execv_05_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_console_w32_execv_05_good(); + printLine("Finished good()"); +#endif /* OMITGOOD */ +#ifndef OMITBAD + printLine("Calling bad()..."); + CWE78_OS_Command_Injection__wchar_t_console_w32_execv_05_bad(); + printLine("Finished bad()"); +#endif /* OMITBAD */ + return 0; +} + +#endif diff --git a/pool/shard004/C/0098803_n_choose_k.c b/pool/shard004/C/0098803_n_choose_k.c new file mode 100644 index 0000000000000000000000000000000000000000..fbc8e2ad6f9932cc4cff9b6fbd06cca7d3ad73fe --- /dev/null +++ b/pool/shard004/C/0098803_n_choose_k.c @@ -0,0 +1,48 @@ +/* + * Copyright (c) 2015 Kostas Lekkas + * + * 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 + +int C(int n, int k) { + if (k > n) + return -1; + + if (n == k || k == 0) + return 1; + + return C(n - 1, k - 1) + C(n - 1, k); +} + +int main(int argc, char *argv[]) { + if (argc != 3) { + printf("Usage: %s [n] [k]\n", argv[0]); + return 1; + } + + int n = atoi(argv[1]); + int k = atoi(argv[2]); + int x = C(n,k); + printf("C(%d, %d) = %d\n", n, k, x); + + return 0; +} diff --git a/pool/shard004/C/0098806_decode_citrix.c b/pool/shard004/C/0098806_decode_citrix.c new file mode 100644 index 0000000000000000000000000000000000000000..0d9743ac247fd8d89fcf9d2eb4ca3583257f6398 --- /dev/null +++ b/pool/shard004/C/0098806_decode_citrix.c @@ -0,0 +1,73 @@ +/* + * decode_citrix.c + * + * Citrix ICA. + * + * http://www.securityfocus.com/templates/archive.pike?list=1&date=200 \ + * 0-04-15&msg=Pine.BSO.4.20.0003290949280.2640-100000@naughty.monkey.org + * + * Thanks to Jeremie Kass for providing me with + * traffic traces. + * + * Copyright (c) 2000 Dug Song + * + * $Id: decode_citrix.c,v 1.5 2001/03/15 08:32:59 dugsong Exp $ + */ + +#include "config.h" + +#include + +#include +#include + +#include "buf.h" +#include "decode.h" + +static u_char ica_magic[] = { 0x32, 0x26, 0x85, 0x92, 0x58 }; + +int +decode_citrix(u_char *buf, int len, u_char *obuf, int olen) +{ + struct buf inbuf, outbuf; + u_char key, c, t[2]; + int i; + + buf_init(&inbuf, buf, len); + buf_init(&outbuf, obuf, olen); + + while ((i = buf_index(&inbuf, ica_magic, sizeof(ica_magic))) >= 0) { + buf_skip(&inbuf, i); + + if (buf_len(&inbuf) < 60) + break; + + buf_skip(&inbuf, 17); + + if (buf_get(&inbuf, &key, 1) != 1) + break; + + buf_skip(&inbuf, 42); + + if (buf_get(&inbuf, &c, 1) != 1) + break; + + c ^= ('C' | key); + + buf_put(&outbuf, &c, 1); + + i = 0; + while (buf_get(&inbuf, t, 2) == 2) { + c = t[0] ^ t[1] ^ key; + + if (c == '\0') { + buf_put(&outbuf, "\n", 1); + if (++i > 2) break; + } + buf_put(&outbuf, &c, 1); + } + } + buf_end(&outbuf); + + return (buf_len(&outbuf)); +} diff --git a/pool/shard004/C/0098817_rand_prime.c b/pool/shard004/C/0098817_rand_prime.c new file mode 100644 index 0000000000000000000000000000000000000000..376bd5f67f5e019578d6625d5e36bc7752afdb1f --- /dev/null +++ b/pool/shard004/C/0098817_rand_prime.c @@ -0,0 +1,87 @@ +/* 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 + */ +#include "tomcrypt.h" + +/** + @file rand_prime.c + Generate a random prime, Tom St Denis +*/ + +#define USE_BBS 1 + +int rand_prime(void *N, long len, prng_state *prng, int wprng) +{ + int err, res, type; + unsigned char *buf; + + LTC_ARGCHK(N != NULL); + + /* get type */ + if (len < 0) { + type = USE_BBS; + len = -len; + } else { + type = 0; + } + + /* allow sizes between 2 and 512 bytes for a prime size */ + if (len < 2 || len > 512) { + return CRYPT_INVALID_PRIME_SIZE; + } + + /* valid PRNG? Better be! */ + if ((err = prng_is_valid(wprng)) != CRYPT_OK) { + return err; + } + + /* allocate buffer to work with */ + buf = XCALLOC(1, len); + if (buf == NULL) { + return CRYPT_MEM; + } + + do { + /* generate value */ + if (prng_descriptor[wprng].read(buf, len, prng) != (unsigned long)len) { + XFREE(buf); + return CRYPT_ERROR_READPRNG; + } + + /* munge bits */ + buf[0] |= 0x80 | 0x40; + buf[len-1] |= 0x01 | ((type & USE_BBS) ? 0x02 : 0x00); + + /* load value */ + if ((err = mp_read_unsigned_bin(N, buf, len)) != CRYPT_OK) { + XFREE(buf); + return err; + } + + /* test */ + if ((err = mp_prime_is_prime(N, 8, &res)) != CRYPT_OK) { + XFREE(buf); + return err; + } + } while (res == LTC_MP_NO); + +#ifdef LTC_CLEAN_STACK + zeromem(buf, len); +#endif + + XFREE(buf); + return CRYPT_OK; +} + + + +/* $Source: /cvs/libtom/libtomcrypt/src/math/rand_prime.c,v $ */ +/* $Revision: 1.7 $ */ +/* $Date: 2006/12/28 01:27:23 $ */ diff --git a/pool/shard004/C/0098818_video-canvas.c b/pool/shard004/C/0098818_video-canvas.c new file mode 100644 index 0000000000000000000000000000000000000000..7373c79ee900c80f09e5bb491f81fbca7cfedfde --- /dev/null +++ b/pool/shard004/C/0098818_video-canvas.c @@ -0,0 +1,215 @@ +/* + * video-canvas.c + * + * Written by + * Andreas Boose + * + * This file is part of VICE, the Versatile Commodore Emulator. + * See README for copyright notice. + * + * 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. + * + */ + +/* #define DEBUG_VIDEO */ + +#ifdef DEBUG_VIDEO +#define DBG(_x_) log_debug _x_ +#else +#define DBG(_x_) +#endif + +#include "vice.h" + +#include "videoarch.h" + +#include +#include + +#include "lib.h" +#include "log.h" +#include "machine.h" +#include "types.h" +#include "video-canvas.h" +#include "video-color.h" +#include "video-render.h" +#include "video.h" +#include "viewport.h" + +#define TRACKED_CANVAS_MAX 2 + +/** \brief Used to enable video_canvas_refresh_all_tracked() */ +static video_canvas_t *tracked_canvas[TRACKED_CANVAS_MAX]; + +/* Temporary! */ +#ifndef MIN +#define MIN(a, b) ((a) < (b) ? (a) : (b)) +#endif + +/* called from raster/raster-resources.c:raster_resources_chip_init */ +video_canvas_t *video_canvas_init(void) +{ + int i; + video_canvas_t *canvas; + + canvas = lib_calloc(1, sizeof(video_canvas_t)); + DBG(("video_canvas_init %p", canvas)); + + canvas->videoconfig = lib_calloc(1, sizeof(video_render_config_t)); + + canvas->draw_buffer = lib_calloc(1, sizeof(draw_buffer_t)); + canvas->viewport = lib_calloc(1, sizeof(viewport_t)); + canvas->geometry = lib_calloc(1, sizeof(geometry_t)); + + video_arch_canvas_init(canvas); + + for (i = 0; i < TRACKED_CANVAS_MAX; i++) { + if (!tracked_canvas[i]) { + tracked_canvas[i] = canvas; + break; + } + } + + if (i == TRACKED_CANVAS_MAX) { + log_error(LOG_ERR, "Creating more than expected video_canvas_t, monitor will not refresh this canvas after each command"); + } + + return canvas; +} + +void video_canvas_shutdown(video_canvas_t *canvas) +{ + int i; + + if (canvas != NULL) { + /* Remove canvas from tracking */ + for (i = 0; i < TRACKED_CANVAS_MAX; i++) { + if (tracked_canvas[i] == canvas) { + tracked_canvas[i] = NULL; + break; + } + } + + lib_free(canvas->videoconfig); + lib_free(canvas->draw_buffer); + video_viewport_title_free(canvas->viewport); + lib_free(canvas->viewport); + lib_free(canvas->geometry); + lib_free(canvas); + } +} + +void video_canvas_render(video_canvas_t *canvas, uint8_t *trg, int width, + int height, int xs, int ys, int xt, int yt, + int pitcht) +{ + viewport_t *viewport = canvas->viewport; +#ifdef VIDEO_SCALE_SOURCE + xs /= canvas->videoconfig->scalex; + ys /= canvas->videoconfig->scaley; +#endif + + /* when the color encoding changed, the palette must be recalculated */ + if (viewport->crt_type != canvas->crt_type) { + canvas->videoconfig->color_tables.updated = 0; + canvas->crt_type = viewport->crt_type; + } + + if (!canvas->videoconfig->color_tables.updated) { /* update colors as necessary */ + video_color_update_palette(canvas); + } + video_render_main(canvas->videoconfig, canvas->draw_buffer->draw_buffer, + trg, width, height, xs, ys, xt, yt, + canvas->draw_buffer->draw_buffer_width, pitcht, + viewport); +} + +/** \brief Force refresh all tracked canvases. + * + * Added to enable visible updates each time the monitor + * prompts for input. + */ +void video_canvas_refresh_all_tracked(void) +{ + int i; + + for (i = 0; i < TRACKED_CANVAS_MAX; i++) { + if (tracked_canvas[i]) { + video_canvas_refresh_all(tracked_canvas[i]); + } + } +} + +void video_canvas_refresh_all(video_canvas_t *canvas) +{ + viewport_t *viewport; + geometry_t *geometry; + + if (video_disabled_mode) { + return; + } + + viewport = canvas->viewport; + geometry = canvas->geometry; + + video_canvas_refresh(canvas, + viewport->first_x + + geometry->extra_offscreen_border_left, + viewport->first_line, + viewport->x_offset, + viewport->y_offset, + MIN(canvas->draw_buffer->canvas_width, + geometry->screen_size.width - viewport->first_x), + MIN(canvas->draw_buffer->canvas_height, + viewport->last_line - viewport->first_line + 1)); +} + +int video_canvas_palette_set(struct video_canvas_s *canvas, + struct palette_s *palette) +{ + struct palette_s *old_palette; + + if (palette == NULL) { + return 0; + } + + old_palette = canvas->palette; + + if (canvas->created) { + if (video_canvas_set_palette(canvas, palette) < 0) { + return -1; + } + } else { + canvas->palette = palette; + } + + if (old_palette != NULL) { + video_color_palette_free(old_palette); + } + +#if 0 /* WTF this was causing each frame to be rendered twice */ + if (canvas->created) { + video_canvas_refresh_all(canvas); + } +#endif + + return 0; +} + +void video_canvas_create_set(struct video_canvas_s *canvas) +{ + canvas->created = 1; +} diff --git a/pool/shard004/C/0098831_main.c b/pool/shard004/C/0098831_main.c new file mode 100644 index 0000000000000000000000000000000000000000..77641230c4022b96228e7ff9c663aebc390f44ad --- /dev/null +++ b/pool/shard004/C/0098831_main.c @@ -0,0 +1,211 @@ +/* -*- mode: c; c-basic-offset: 4; indent-tabs-mode: nil -*- */ +/* plugins/certauth/main.c - certauth plugin test modules. */ +/* + * Copyright (C) 2017 by Red Hat, 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. + * + * 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 "krb5/certauth_plugin.h" + +struct krb5_certauth_moddata_st { + int initialized; +}; + +/* Test module 1 returns OK with an indicator. */ +static krb5_error_code +test1_authorize(krb5_context context, krb5_certauth_moddata moddata, + const uint8_t *cert, size_t cert_len, + krb5_const_principal princ, const void *opts, + const struct _krb5_db_entry_new *db_entry, + char ***authinds_out) +{ + char **ais = NULL; + + ais = calloc(2, sizeof(*ais)); + assert(ais != NULL); + ais[0] = strdup("test1"); + assert(ais[0] != NULL); + *authinds_out = ais; + return KRB5_PLUGIN_NO_HANDLE; +} + +static void +test_free_ind(krb5_context context, krb5_certauth_moddata moddata, + char **authinds) +{ + size_t i; + + if (authinds == NULL) + return; + for (i = 0; authinds[i] != NULL; i++) + free(authinds[i]); + free(authinds); +} + +/* A basic moddata test. */ +static krb5_error_code +test2_init(krb5_context context, krb5_certauth_moddata *moddata_out) +{ + krb5_certauth_moddata mod; + + mod = calloc(1, sizeof(*mod)); + assert(mod != NULL); + mod->initialized = 1; + *moddata_out = mod; + return 0; +} + +static void +test2_fini(krb5_context context, krb5_certauth_moddata moddata) +{ + free(moddata); +} + +/* Return true if cert appears to contain the CN name, based on a search of the + * DER encoding. */ +static krb5_boolean +has_cn(krb5_context context, const uint8_t *cert, size_t cert_len, + const char *name) +{ + krb5_boolean match = FALSE; + uint8_t name_len, cntag[5] = "\x06\x03\x55\x04\x03"; + const uint8_t *c; + struct k5buf buf; + size_t c_left; + + /* Construct a DER search string of the CN AttributeType encoding followed + * by a UTF8String encoding containing name as the AttributeValue. */ + k5_buf_init_dynamic(&buf); + k5_buf_add_len(&buf, cntag, sizeof(cntag)); + k5_buf_add(&buf, "\x0C"); + assert(strlen(name) < 128); + name_len = strlen(name); + k5_buf_add_len(&buf, &name_len, 1); + k5_buf_add_len(&buf, name, name_len); + assert(k5_buf_status(&buf) == 0); + + /* Check for the CN needle in the certificate haystack. */ + c_left = cert_len; + c = memchr(cert, *cntag, c_left); + while (c != NULL) { + c_left = cert_len - (c - cert); + if (buf.len > c_left) + break; + if (memcmp(c, buf.data, buf.len) == 0) { + match = TRUE; + break; + } + assert(c_left >= 1); + c = memchr(c + 1, *cntag, c_left - 1); + } + + k5_buf_free(&buf); + return match; +} + +/* + * Test module 2 returns OK if princ matches the CN part of the subject name, + * and returns indicators of the module name and princ. + */ +static krb5_error_code +test2_authorize(krb5_context context, krb5_certauth_moddata moddata, + const uint8_t *cert, size_t cert_len, + krb5_const_principal princ, const void *opts, + const struct _krb5_db_entry_new *db_entry, + char ***authinds_out) +{ + krb5_error_code ret; + char *name = NULL, **ais = NULL; + + *authinds_out = NULL; + + assert(moddata != NULL && moddata->initialized); + + ret = krb5_unparse_name_flags(context, princ, + KRB5_PRINCIPAL_UNPARSE_NO_REALM, &name); + if (ret) + goto cleanup; + + if (!has_cn(context, cert, cert_len, name)) { + ret = KRB5KDC_ERR_CERTIFICATE_MISMATCH; + goto cleanup; + } + + /* Create an indicator list with the module name and CN. */ + ais = calloc(3, sizeof(*ais)); + assert(ais != NULL); + ais[0] = strdup("test2"); + ais[1] = strdup(name); + assert(ais[0] != NULL && ais[1] != NULL); + *authinds_out = ais; + + ais = NULL; + +cleanup: + krb5_free_unparsed_name(context, name); + return ret; +} + +krb5_error_code +certauth_test1_initvt(krb5_context context, int maj_ver, int min_ver, + krb5_plugin_vtable vtable); +krb5_error_code +certauth_test1_initvt(krb5_context context, int maj_ver, int min_ver, + krb5_plugin_vtable vtable) +{ + krb5_certauth_vtable vt; + + if (maj_ver != 1) + return KRB5_PLUGIN_VER_NOTSUPP; + vt = (krb5_certauth_vtable)vtable; + vt->name = "test1"; + vt->authorize = test1_authorize; + vt->free_ind = test_free_ind; + return 0; +} + +krb5_error_code +certauth_test2_initvt(krb5_context context, int maj_ver, int min_ver, + krb5_plugin_vtable vtable); +krb5_error_code +certauth_test2_initvt(krb5_context context, int maj_ver, int min_ver, + krb5_plugin_vtable vtable) +{ + krb5_certauth_vtable vt; + + if (maj_ver != 1) + return KRB5_PLUGIN_VER_NOTSUPP; + vt = (krb5_certauth_vtable)vtable; + vt->name = "test2"; + vt->authorize = test2_authorize; + vt->init = test2_init; + vt->fini = test2_fini; + vt->free_ind = test_free_ind; + return 0; +} diff --git a/pool/shard004/C/0098832_backtrace.c b/pool/shard004/C/0098832_backtrace.c new file mode 100644 index 0000000000000000000000000000000000000000..08a7010e7ed689e4d5f688f3317c3878b5efd7f9 --- /dev/null +++ b/pool/shard004/C/0098832_backtrace.c @@ -0,0 +1,89 @@ +/* + * Perform stack unwinding by using the _Unwind_Backtrace. + * + * User application that wants to use backtrace needs to be + * compiled with -fasynchronous-unwind-tables option and -rdynamic to get full + * symbols printed. + * + * Copyright (C) 2009, 2010 STMicroelectronics Ltd. + * + * Author(s): Giuseppe Cavallaro + * - Initial implementation for glibc + * + * Author(s): Carmelo Amoroso + * - Reworked for uClibc + * - use dlsym/dlopen from libdl + * - rewrite initialisation to not use libc_once + * - make it available in static link too + * + * Licensed under the LGPL v2.1, see the file COPYING.LIB in this tarball. + * + */ + +#include +#include +#include +#include +#include +#include +#include + +struct trace_arg +{ + void **array; + int cnt, size; +}; + +#ifdef SHARED +static _Unwind_Reason_Code (*unwind_backtrace) (_Unwind_Trace_Fn, void *); +static _Unwind_Ptr (*unwind_getip) (struct _Unwind_Context *); + +static void backtrace_init (void) +{ + void *handle = dlopen (LIBGCC_S_SO, RTLD_LAZY); + + if (handle == NULL + || ((unwind_backtrace = dlsym (handle, "_Unwind_Backtrace")) == NULL) + || ((unwind_getip = dlsym (handle, "_Unwind_GetIP")) == NULL)) { + printf(LIBGCC_S_SO " must be installed for backtrace to work\n"); + abort(); + } +} +#else +# define unwind_backtrace _Unwind_Backtrace +# define unwind_getip _Unwind_GetIP +#endif + +static _Unwind_Reason_Code +backtrace_helper (struct _Unwind_Context *ctx, void *a) +{ + struct trace_arg *arg = a; + + assert (unwind_getip != NULL); + + /* We are first called with address in the __backtrace function. Skip it. */ + if (arg->cnt != -1) + arg->array[arg->cnt] = (void *) unwind_getip (ctx); + if (++arg->cnt == arg->size) + return _URC_END_OF_STACK; + return _URC_NO_REASON; +} + +/* + * Perform stack unwinding by using the _Unwind_Backtrace. + * + */ +int backtrace (void **array, int size) +{ + struct trace_arg arg = { .array = array, .size = size, .cnt = -1 }; + +#ifdef SHARED + if (unwind_backtrace == NULL) + backtrace_init(); +#endif + + if (size >= 1) + unwind_backtrace (backtrace_helper, &arg); + + return arg.cnt != -1 ? arg.cnt : 0; +} diff --git a/pool/shard004/C/0098837_joex_server.c b/pool/shard004/C/0098837_joex_server.c new file mode 100644 index 0000000000000000000000000000000000000000..a01c5ffbde6552f1022db0655d05934bedf6f8dd --- /dev/null +++ b/pool/shard004/C/0098837_joex_server.c @@ -0,0 +1,245 @@ +/* ========================================================================= + joex_server - joex_server + + Copyright (c) the Contributors as noted in the AUTHORS file. + This file is part of CZMQ, the high-level C binding for 0MQ: + http://czmq.zeromq.org. + + 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/. + ========================================================================= +*/ + +/* +@header + Description of class for man page. +@discuss + Detailed discussion of the class, if any. +@end +*/ + +#include "joex_classes.h" +// TODO: Change these to match your project's needs +#include "../include/joex_proto.h" +#include "../include/joex_server.h" + +// --------------------------------------------------------------------------- +// Forward declarations for the two main classes we use here + +typedef struct _server_t server_t; +typedef struct _client_t client_t; + +// This structure defines the context for each running server. Store +// whatever properties and structures you need for the server. + +struct _server_t { + // These properties must always be present in the server_t + // and are set by the generated engine; do not modify them! + zsock_t *pipe; // Actor pipe back to caller + zconfig_t *config; // Current loaded configuration + + // TODO: Add any properties you need here + zhashx_t *clients; // name -> client_t* +}; + +// --------------------------------------------------------------------------- +// This structure defines the state for each client connection. It will +// be passed to each action in the 'self' argument. + +struct _client_t { + // These properties must always be present in the client_t + // and are set by the generated engine; do not modify them! + server_t *server; // Reference to parent server + joex_proto_t *message; // Message in and out + + // TODO: Add specific properties for your application + char *name; +}; + +// Include the generated server engine +#include "joex_server_engine.inc" + +// Allocate properties and structures for a new server instance. +// Return 0 if OK, or -1 if there was an error. + +static int +server_initialize (server_t *self) +{ + // Construct properties here + self->clients = zhashx_new (); + return 0; +} + +// Free properties and structures for a server instance + +static void +server_terminate (server_t *self) +{ + // Destroy properties here + zhashx_destroy (&self->clients); +} + +// Process server API method, return reply message if any + +static zmsg_t * +server_method (server_t *self, const char *method, zmsg_t *msg) +{ + return NULL; +} + +// Apply new configuration. + +static void +server_configuration (server_t *self, zconfig_t *config) +{ + // Apply new configuration +} + +// Allocate properties and structures for a new client connection and +// optionally engine_set_next_event (). Return 0 if OK, or -1 on error. + +static int +client_initialize (client_t *self) +{ + // Construct properties here + return 0; +} + +// Free properties and structures for a client connection + +static void +client_terminate (client_t *self) +{ + // Destroy properties here + zstr_free (&self->name); +} + +// --------------------------------------------------------------------------- +// Selftest + +void +joex_server_test (bool verbose) +{ + printf (" * joex_server: "); + if (verbose) + printf ("\n"); + + // @selftest + zactor_t *server = zactor_new (joex_server, "server"); + if (verbose) + zstr_send (server, "VERBOSE"); + zstr_sendx (server, "BIND", "ipc://@/joex_server", NULL); + + zsock_t *client = zsock_new (ZMQ_DEALER); + assert (client); + zsock_set_rcvtimeo (client, 2000); + zsock_connect (client, "ipc://@/joex_server"); + + joex_proto_t *request = joex_proto_new (); + + int r; + // send hello + joex_proto_set_id (request, JOEX_PROTO_HELLO); + joex_proto_set_name (request, "client1"); + joex_proto_send (request, client); + + r = joex_proto_recv (request, client); + assert (r == 0); + assert (joex_proto_id (request) == JOEX_PROTO_OK); + + // send PONG + joex_proto_set_id (request, JOEX_PROTO_PONG); + joex_proto_send (request, client); + + r = joex_proto_recv (request, client); + assert (r == 0); + assert (joex_proto_id (request) == JOEX_PROTO_ERROR); + assert (streq (joex_proto_reason (request), "command invalid")); + + // send hello client1 AGAIN + joex_proto_set_id (request, JOEX_PROTO_HELLO); + joex_proto_set_name (request, "client1"); + joex_proto_send (request, client); + + r = joex_proto_recv (request, client); + assert (r == 0); + assert (joex_proto_id (request) == JOEX_PROTO_ERROR); + assert (streq (joex_proto_reason (request), "command invalid")); + + // send Close client1 + joex_proto_set_id (request, JOEX_PROTO_CLOSE); + joex_proto_send (request, client); + + r = joex_proto_recv (request, client); + assert (r == 0); + assert (joex_proto_id (request) == JOEX_PROTO_OK); + + // send hello after close + joex_proto_set_id (request, JOEX_PROTO_HELLO); + joex_proto_set_name (request, "client1"); + joex_proto_send (request, client); + + r = joex_proto_recv (request, client); + assert (r == 0); + assert (joex_proto_id (request) == JOEX_PROTO_OK); + joex_proto_destroy (&request); + + zsock_destroy (&client); + zactor_destroy (&server); + // @end + printf ("OK\n"); +} + + +// --------------------------------------------------------------------------- +// register_new_client +// + +static void +register_new_client (client_t *self) +{ + self->name = strdup (joex_proto_name (self->message)); + + if (zhashx_lookup (self->server->clients, self->name)) { + engine_set_exception (self, exception_event); + zsys_debug ("engine_set_exception"); + } + else + zhashx_insert (self->server->clients, self->name, self); +} + + +// --------------------------------------------------------------------------- +// signal_command_invalid +// + +static void +signal_command_invalid (client_t *self) +{ + joex_proto_set_reason (self->message, "command invalid"); + joex_proto_set_code (self->message, 300); +} + + +// --------------------------------------------------------------------------- +// signal_duplicated_client +// + +static void +signal_duplicated_client (client_t *self) +{ + joex_proto_set_reason (self->message, "duplicate user"); + joex_proto_set_code (self->message, 301); +} + + +// --------------------------------------------------------------------------- +// unregister_client +// + +static void +unregister_client (client_t *self) +{ + zhashx_delete(self->server->clients, self->name); +} diff --git a/pool/shard004/C/0098841_cpu.c b/pool/shard004/C/0098841_cpu.c new file mode 100644 index 0000000000000000000000000000000000000000..e8d62cbeac2769e265caa311291e704fd59bcb4d --- /dev/null +++ b/pool/shard004/C/0098841_cpu.c @@ -0,0 +1,105 @@ +/* + * Copyright (c) 2013 Intel Corporation + * Author: Andi Kleen + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that: (1) source code distributions + * retain the above copyright notice and this paragraph in its entirety, (2) + * distributions including binary code include the above copyright notice and + * this paragraph in its entirety in the documentation or other materials + * provided with the distribution + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. + */ + +/* CPU detection and event tables */ +#include +#include +#include +#include + +#include "cpu.h" + +struct cpu_events { + int *models; + unsigned mem_stores; + unsigned mem_loads; +}; + +#define MEM_LOADS_SNB 0x1cd /* MEM_TRANS_RETIRED.LOAD_LATENCY */ +#define MEM_STORES_SNB 0x2cd /* MEM_TRANS_RETIRED.PRECISE_STORES */ +static int snb_models[] = { 42, 45, 58, 62, 0 }; + +#define MEM_LOADS_HSW MEM_LOADS_SNB +#define MEM_STORES_HSW 0x82d0 +static int hsw_models[] = { 60, 70, 71, 63, 0 }; + +/* Nehalem and Westmere */ +#define MEM_LOADS_NHM 0x100b /* MEM_INST_RETIRED.LOAD_LATENCY */ +#define MEM_STORES_NHM -1 /* not supported */ + +static int nhm_models[] = { 26, 30, 46, 37, 44, 47, 0 }; + +struct cpu_events events[] = { + { snb_models, MEM_STORES_SNB, MEM_LOADS_SNB }, + { nhm_models, MEM_STORES_NHM, MEM_LOADS_NHM }, + { hsw_models, MEM_STORES_HSW, MEM_LOADS_HSW }, + {} +}; + +static unsigned get_cpu_model(void) +{ + unsigned sig; + if (__get_cpuid_max(0, &sig) >= 1 && sig == *(int *)"Genu") { + unsigned a, b, c, d; + __cpuid(1, a, b, c, d); + unsigned family = (a >> 8) & 0xf; + if (family == 6) + return ((a >> 4) & 0xf) + (((a >> 16) & 0xf) << 4); + } + return 0; +} + +static bool match_cpu_model(int mod, int *models) +{ + int i; + for (i = 0; models[i]; i++) + if (models[i] == mod) + return true; + return false; +} + +/** + * mem_stores_event - Return precise mem load event for current CPU. + * This is an event which supports load address monitoring. + * Return: raw event, can be put int perf_event_attr->config. + * -1 or error. + */ + +unsigned mem_loads_event(void) +{ + int mod = get_cpu_model(); + int i; + for (i = 0; events[i].models; i++) + if (match_cpu_model(mod, events[i].models)) + return events[i].mem_loads; + return -1; +} + +/** + * mem_stores_event - Return precise mem stores event for current CPU. + * This is an event which supports load address monitoring. + * Return: raw event, can be put int perf_event_attr->config. + * -1 or error. + */ +unsigned mem_stores_event(void) +{ + int mod = get_cpu_model(); + int i; + for (i = 0; events[i].models; i++) + if (match_cpu_model(mod, events[i].models)) + return events[i].mem_stores; + return -1; +} diff --git a/pool/shard004/C/0098842_simulator.c b/pool/shard004/C/0098842_simulator.c new file mode 100644 index 0000000000000000000000000000000000000000..d34963f77e3b5eff88758cd0f84e1ae04be166eb --- /dev/null +++ b/pool/shard004/C/0098842_simulator.c @@ -0,0 +1,82 @@ +#include +#include "commander.h" +#include "ecc.h" +#include "flags.h" +#include "memory.h" +#include "sd.h" +#include +#include +#include +#include + +#define PORT 35345 +#define BUF_SIZE COMMANDER_REPORT_SIZE + +int main(int argc, char *argv[]) +{ + // Get and set the root directory + if (argc < 2) { + fprintf(stderr, "The directory to be used for the sd card files must be specified\n"); + exit(1); + } else if (argc > 2) { + fprintf(stderr, "Too many arguments\n"); + exit(1); + } + set_root_dir(argv[1]); + + // Init device + ecc_context_init(); +#ifdef ECC_USE_SECP256K1_LIB + bitcoin_ecc.ecc_context_init(); +#endif + memory_setup(); + memory_setup(); + + // Create socket + int s; + if ((s = socket(AF_INET, SOCK_DGRAM, 0)) == -1) { + fprintf(stderr, "Socket could not be created\n"); + exit(1); + } + + // Make socket struct + struct sockaddr_in sock; + memset(&sock, 0, sizeof(sock)); + sock.sin_family = AF_INET; + sock.sin_addr.s_addr = htonl(INADDR_ANY); + sock.sin_port = htons(PORT); + + // Bind socket + if (bind(s, (struct sockaddr *)&sock, sizeof(sock)) == -1) { + fprintf(stderr, "Could not bind socket\n"); + exit(1); + } + fprintf(stderr, "Digital Bitbox simulator started\n"); + + // Wait for connections and handle + char buf[BUF_SIZE]; + char *result; + struct sockaddr_in in_sock; + int recv_len; + socklen_t in_sock_len = sizeof(in_sock); + while (1) { + int rc; + // Receive + memset(buf, 0, BUF_SIZE); + if ((recv_len = recvfrom(s, buf, BUF_SIZE, 0, (struct sockaddr *)&in_sock, + &in_sock_len)) < 0) { + fprintf(stderr, "Failed to receive udp data, error %d\n", recv_len); + exit(1); + } + + // Execute the command + result = commander(buf); + + // Send result to socket + if ((rc = sendto(s, result, strlen(result), 0, (struct sockaddr *)&in_sock, + in_sock_len)) < 0) { + fprintf(stderr, "Failed to send udp data, error %d\n", rc); + exit(1); + } + } +} diff --git a/pool/shard004/C/0098856_CWE510_Trapdoor__ip_based_logic_16.c b/pool/shard004/C/0098856_CWE510_Trapdoor__ip_based_logic_16.c new file mode 100644 index 0000000000000000000000000000000000000000..98e3933c75cdc05b441f8e9b40f913dc083c9658 --- /dev/null +++ b/pool/shard004/C/0098856_CWE510_Trapdoor__ip_based_logic_16.c @@ -0,0 +1,231 @@ +/* TEMPLATE GENERATED TESTCASE FILE +Filename: CWE510_Trapdoor__ip_based_logic_16.c +Label Definition File: CWE510_Trapdoor.label.xml +Template File: point-flaw-16.tmpl.c +*/ +/* + * @description + * CWE: 510 Trapdoor + * Sinks: ip_based_logic + * GoodSink: No IP-based logic + * BadSink : Different logic if a connection is made from a specific IP + * Flow Variant: 16 Control flow: while(1) + * + * */ + +#include "std_testcase.h" + +#ifdef _WIN32 +#include +#include +#include +#pragma comment(lib, "ws2_32") /* include ws2_32.lib when linking */ +#define CLOSE_SOCKET closesocket +#else /* NOT _WIN32 */ +#include +#include +#include +#include +#include +#define INVALID_SOCKET -1 +#define SOCKET_ERROR -1 +#define CLOSE_SOCKET close +#define SOCKET int +#endif + +#define ADMIN_MESSAGE "Welcome, admin!" +#define DEFAULT_MESSAGE "Welcome!" + +#ifndef OMITBAD + +void CWE510_Trapdoor__ip_based_logic_16_bad() +{ + while(1) + { + { +#ifdef _WIN32 + WSADATA wsaData; + int wsaDataInit = 0; +#endif + struct sockaddr_in service, acceptService; + int acceptServiceLen = sizeof(acceptService); + SOCKET listenSocket = INVALID_SOCKET; + SOCKET acceptSocket = INVALID_SOCKET; + do + { +#ifdef _WIN32 + if (WSAStartup(MAKEWORD(2,2), &wsaData) != NO_ERROR) + { + break; + } + wsaDataInit = 1; +#endif + 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(20000); + if (bind(listenSocket, (struct sockaddr*)&service, sizeof(service)) == SOCKET_ERROR) + { + break; + } + if (listen(listenSocket, 5) == SOCKET_ERROR) + { + break; + } + acceptSocket = accept(listenSocket, NULL, NULL); + if (acceptSocket == SOCKET_ERROR) + { + break; + } + if (getsockname(acceptSocket, (struct sockaddr *)&acceptService, &acceptServiceLen) == -1) + { + break; + } + /* FLAW: IP-based logic */ + if (strcmp("192.168.30.123", inet_ntoa(acceptService.sin_addr)) == 0) + { + if (send(acceptSocket, ADMIN_MESSAGE, strlen(ADMIN_MESSAGE), 0) == SOCKET_ERROR) + { + /* Do not alert user to trapdoor, no action */ + break; + } + } + else + { + if (send(acceptSocket, DEFAULT_MESSAGE, strlen(DEFAULT_MESSAGE), 0) == SOCKET_ERROR) + { + printLine("Send failed!"); + } + } + } + while (0); + if (listenSocket != INVALID_SOCKET) + { + CLOSE_SOCKET(listenSocket); + } + if (acceptSocket != INVALID_SOCKET) + { + CLOSE_SOCKET(acceptSocket); + } +#ifdef _WIN32 + if (wsaDataInit) + { + WSACleanup(); + } +#endif + } + break; + } +} + +#endif /* OMITBAD */ + +#ifndef OMITGOOD + +/* good1() uses the GoodSinkBody in the while loop */ +static void good1() +{ + while(1) + { + { +#ifdef _WIN32 + WSADATA wsaData; + int wsaDataInit = 0; +#endif + struct sockaddr_in service; + SOCKET listenSocket = INVALID_SOCKET; + SOCKET acceptSocket = INVALID_SOCKET; + do + { +#ifdef _WIN32 + if (WSAStartup(MAKEWORD(2,2), &wsaData) != NO_ERROR) + { + break; + } + wsaDataInit = 1; +#endif + 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(20000); + if (bind(listenSocket, (struct sockaddr*)&service, sizeof(service)) == SOCKET_ERROR) + { + break; + } + if (listen(listenSocket, 5) == SOCKET_ERROR) + { + break; + } + acceptSocket = accept(listenSocket, NULL, NULL); + if (acceptSocket == SOCKET_ERROR) + { + break; + } + /* FIX: No IP-based logic */ + if (send(acceptSocket, DEFAULT_MESSAGE, strlen(DEFAULT_MESSAGE), 0) == SOCKET_ERROR) + { + printLine("Send failed!"); + } + } + while (0); + if (listenSocket != INVALID_SOCKET) + { + CLOSE_SOCKET(listenSocket); + } + if (acceptSocket != INVALID_SOCKET) + { + CLOSE_SOCKET(acceptSocket); + } +#ifdef _WIN32 + if (wsaDataInit) + { + WSACleanup(); + } +#endif + } + break; + } +} + +void CWE510_Trapdoor__ip_based_logic_16_good() +{ + good1(); +} + +#endif /* OMITGOOD */ + +/* Below is the main(). It is only used when building this testcase on + its own for testing or for building a binary to use in testing binary + analysis tools. It is not used when compiling all the testcases as one + application, which is how source code analysis tools are tested. */ + +#ifdef INCLUDEMAIN + +int main(int argc, char * argv[]) +{ + /* seed randomness */ + srand( (unsigned)time(NULL) ); +#ifndef OMITGOOD + printLine("Calling good()..."); + CWE510_Trapdoor__ip_based_logic_16_good(); + printLine("Finished good()"); +#endif /* OMITGOOD */ +#ifndef OMITBAD + printLine("Calling bad()..."); + CWE510_Trapdoor__ip_based_logic_16_bad(); + printLine("Finished bad()"); +#endif /* OMITBAD */ + return 0; +} + +#endif diff --git a/pool/shard004/C/0098858_test_dp_builtin.c b/pool/shard004/C/0098858_test_dp_builtin.c new file mode 100644 index 0000000000000000000000000000000000000000..b2f2a7d7172c066e2880a60ec1ff8192e9afe41f --- /dev/null +++ b/pool/shard004/C/0098858_test_dp_builtin.c @@ -0,0 +1,191 @@ +/* + Copyright (C) 2015 Red Hat + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . +*/ + +#include +#include +#include +#include +#include + +#include "providers/backend.h" +#include "providers/data_provider/dp_private.h" +#include "providers/data_provider/dp_builtin.h" +#include "providers/data_provider/dp.h" +#include "tests/cmocka/common_mock.h" +#include "tests/common.h" +#include "tests/cmocka/common_mock_be.h" +#include "tests/cmocka/data_provider/mock_dp.h" + +#define TESTS_PATH "tp_" BASE_FILE_STEM +#define TEST_CONF_DB "test_dp_request.ldb" +#define TEST_DOM_NAME "dp_request_test" +#define TEST_ID_PROVIDER "ldap" + +struct test_ctx { + struct sss_test_ctx *tctx; + struct be_ctx *be_ctx; + struct dp_req_params *params; +}; + +static int test_setup(void **state) +{ + struct test_ctx *test_ctx; + + + assert_true(leak_check_setup()); + + test_ctx = talloc_zero(global_talloc_context, struct test_ctx); + assert_non_null(test_ctx); + + test_ctx->tctx = create_dom_test_ctx(test_ctx, TESTS_PATH, TEST_CONF_DB, + TEST_DOM_NAME, TEST_ID_PROVIDER, NULL); + assert_non_null(test_ctx->tctx); + + test_ctx->be_ctx = mock_be_ctx(test_ctx, test_ctx->tctx); + assert_non_null(test_ctx->be_ctx); + + test_ctx->params = mock_dp_req_params(test_ctx, test_ctx->be_ctx->ev, + test_ctx->be_ctx, NULL, + DPT_ID, DPM_ACCOUNT_HANDLER); + assert_non_null(test_ctx->params); + + check_leaks_push(test_ctx); + + *state = test_ctx; + + return 0; +} + +static int test_teardown(void **state) +{ + struct test_ctx *test_ctx; + + test_ctx = talloc_get_type_abort(*state, struct test_ctx); + assert_true(check_leaks_pop(test_ctx)); + talloc_zfree(test_ctx); + + assert_true(leak_check_teardown()); + return 0; +} + +static void test_deny_handler(void **state) +{ + errno_t ret; + struct test_ctx *test_ctx; + struct tevent_req *req; + struct pam_data *pd; + struct pam_data *out_pd; + + test_ctx = talloc_get_type(*state, struct test_ctx); + + pd = talloc_zero(test_ctx, struct pam_data); + assert_non_null(pd); + + req = dp_access_deny_handler_send(test_ctx, NULL, pd, test_ctx->params); + assert_non_null(req); + + tevent_loop_wait(test_ctx->tctx->ev); + + ret = dp_access_deny_handler_recv(test_ctx, req, &out_pd); + assert_int_equal(ret, EOK); + assert_ptr_equal(pd, out_pd); + assert_int_equal(pd->pam_status, PAM_PERM_DENIED); + + talloc_free(req); + talloc_free(pd); +} + +static void test_permit_handler(void **state) +{ + errno_t ret; + struct test_ctx *test_ctx; + struct tevent_req *req; + struct pam_data *pd; + struct pam_data *out_pd; + + test_ctx = talloc_get_type(*state, struct test_ctx); + + pd = talloc_zero(test_ctx, struct pam_data); + assert_non_null(pd); + + req = dp_access_permit_handler_send(test_ctx, NULL, pd, test_ctx->params); + assert_non_null(req); + + tevent_loop_wait(test_ctx->tctx->ev); + + ret = dp_access_permit_handler_recv(test_ctx, req, &out_pd); + assert_int_equal(ret, EOK); + assert_ptr_equal(pd, out_pd); + assert_int_equal(pd->pam_status, PAM_SUCCESS); + + talloc_free(req); + talloc_free(pd); +} + +int main(int argc, const char *argv[]) +{ + poptContext pc; + int opt; + int rv; + int no_cleanup = 0; + struct poptOption long_options[] = { + POPT_AUTOHELP + SSSD_DEBUG_OPTS + {"no-cleanup", 'n', POPT_ARG_NONE, &no_cleanup, 0, + _("Do not delete the test database after a test run"), NULL }, + POPT_TABLEEND + }; + + const struct CMUnitTest tests[] = { + cmocka_unit_test_setup_teardown(test_permit_handler, + test_setup, + test_teardown), + cmocka_unit_test_setup_teardown(test_deny_handler, + test_setup, + test_teardown), + }; + + /* Set debug level to invalid value so we can deside if -d 0 was used. */ + debug_level = SSSDBG_INVALID; + + pc = poptGetContext(argv[0], argc, argv, long_options, 0); + while((opt = poptGetNextOpt(pc)) != -1) { + switch(opt) { + default: + fprintf(stderr, "\nInvalid option %s: %s\n\n", + poptBadOption(pc, 0), poptStrerror(opt)); + poptPrintUsage(pc, stderr, 0); + return 1; + } + } + poptFreeContext(pc); + + DEBUG_CLI_INIT(debug_level); + + /* Even though normally the tests should clean up after themselves + * they might not after a failed run. Remove the old db to be sure */ + tests_set_cwd(); + test_dom_suite_cleanup(TESTS_PATH, TEST_CONF_DB, TEST_DOM_NAME); + test_dom_suite_setup(TESTS_PATH); + + rv = cmocka_run_group_tests(tests, NULL, NULL); + if (rv == 0 && !no_cleanup) { + test_dom_suite_cleanup(TESTS_PATH, TEST_CONF_DB, TEST_DOM_NAME); + } + + return rv; +} diff --git a/pool/shard004/C/0098860_main.c b/pool/shard004/C/0098860_main.c new file mode 100644 index 0000000000000000000000000000000000000000..846ca772995d02c8fd357bebb6833088cdfa2828 --- /dev/null +++ b/pool/shard004/C/0098860_main.c @@ -0,0 +1,264 @@ +/* + * Copyright (C) 2000 - 2007 Jeff Dike (jdike@{addtoit,linux.intel}.com) + * Licensed under the GPL + */ + +#include +#include +#include +#include +#include +#include +#include +#include "as-layout.h" +#include "init.h" +#include "kern_constants.h" +#include "kern_util.h" +#include "os.h" +#include "um_malloc.h" + +#define PGD_BOUND (4 * 1024 * 1024) +#define STACKSIZE (8 * 1024 * 1024) +#define THREAD_NAME_LEN (256) + +long elf_aux_hwcap; + +static void set_stklim(void) +{ + struct rlimit lim; + + if (getrlimit(RLIMIT_STACK, &lim) < 0) { + perror("getrlimit"); + exit(1); + } + if ((lim.rlim_cur == RLIM_INFINITY) || (lim.rlim_cur > STACKSIZE)) { + lim.rlim_cur = STACKSIZE; + if (setrlimit(RLIMIT_STACK, &lim) < 0) { + perror("setrlimit"); + exit(1); + } + } +} + +static __init void do_uml_initcalls(void) +{ + initcall_t *call; + + call = &__uml_initcall_start; + while (call < &__uml_initcall_end) { + (*call)(); + call++; + } +} + +static void last_ditch_exit(int sig) +{ + uml_cleanup(); + exit(1); +} + +static void install_fatal_handler(int sig) +{ + struct sigaction action; + + /* All signals are enabled in this handler ... */ + sigemptyset(&action.sa_mask); + + /* + * ... including the signal being handled, plus we want the + * handler reset to the default behavior, so that if an exit + * handler is hanging for some reason, the UML will just die + * after this signal is sent a second time. + */ + action.sa_flags = SA_RESETHAND | SA_NODEFER; + action.sa_restorer = NULL; + action.sa_handler = last_ditch_exit; + if (sigaction(sig, &action, NULL) < 0) { + printf("failed to install handler for signal %d - errno = %d\n", + sig, errno); + exit(1); + } +} + +#define UML_LIB_PATH ":" OS_LIB_PATH "/uml" + +static void setup_env_path(void) +{ + char *new_path = NULL; + char *old_path = NULL; + int path_len = 0; + + old_path = getenv("PATH"); + /* + * if no PATH variable is set or it has an empty value + * just use the default + /usr/lib/uml + */ + if (!old_path || (path_len = strlen(old_path)) == 0) { + if (putenv("PATH=:/bin:/usr/bin/" UML_LIB_PATH)) + perror("couldn't putenv"); + return; + } + + /* append /usr/lib/uml to the existing path */ + path_len += strlen("PATH=" UML_LIB_PATH) + 1; + new_path = malloc(path_len); + if (!new_path) { + perror("couldn't malloc to set a new PATH"); + return; + } + snprintf(new_path, path_len, "PATH=%s" UML_LIB_PATH, old_path); + if (putenv(new_path)) { + perror("couldn't putenv to set a new PATH"); + free(new_path); + } +} + +extern void scan_elf_aux( char **envp); + +int __init main(int argc, char **argv, char **envp) +{ + char **new_argv; + int ret, i, err; + + set_stklim(); + + setup_env_path(); + + new_argv = malloc((argc + 1) * sizeof(char *)); + if (new_argv == NULL) { + perror("Mallocing argv"); + exit(1); + } + for (i = 0; i < argc; i++) { + new_argv[i] = strdup(argv[i]); + if (new_argv[i] == NULL) { + perror("Mallocing an arg"); + exit(1); + } + } + new_argv[argc] = NULL; + + /* + * Allow these signals to bring down a UML if all other + * methods of control fail. + */ + install_fatal_handler(SIGINT); + install_fatal_handler(SIGTERM); + +#ifdef CONFIG_ARCH_REUSE_HOST_VSYSCALL_AREA + scan_elf_aux(envp); +#endif + + do_uml_initcalls(); + ret = linux_main(argc, argv); + + /* + * Disable SIGPROF - I have no idea why libc doesn't do this or turn + * off the profiling time, but UML dies with a SIGPROF just before + * exiting when profiling is active. + */ + change_sig(SIGPROF, 0); + + /* + * This signal stuff used to be in the reboot case. However, + * sometimes a SIGVTALRM can come in when we're halting (reproducably + * when writing out gcov information, presumably because that takes + * some time) and cause a segfault. + */ + + /* stop timers and set SIGVTALRM to be ignored */ + disable_timer(); + + /* disable SIGIO for the fds and set SIGIO to be ignored */ + err = deactivate_all_fds(); + if (err) + printf("deactivate_all_fds failed, errno = %d\n", -err); + + /* + * Let any pending signals fire now. This ensures + * that they won't be delivered after the exec, when + * they are definitely not expected. + */ + unblock_signals(); + + /* Reboot */ + if (ret) { + printf("\n"); + execvp(new_argv[0], new_argv); + perror("Failed to exec kernel"); + ret = 1; + } + printf("\n"); + return uml_exitcode; +} + +extern void *__real_malloc(int); + +void *__wrap_malloc(int size) +{ + void *ret; + + if (!kmalloc_ok) + return __real_malloc(size); + else if (size <= UM_KERN_PAGE_SIZE) + /* finding contiguous pages can be hard*/ + ret = uml_kmalloc(size, UM_GFP_KERNEL); + else ret = vmalloc(size); + + /* + * glibc people insist that if malloc fails, errno should be + * set by malloc as well. So we do. + */ + if (ret == NULL) + errno = ENOMEM; + + return ret; +} + +void *__wrap_calloc(int n, int size) +{ + void *ptr = __wrap_malloc(n * size); + + if (ptr == NULL) + return NULL; + memset(ptr, 0, n * size); + return ptr; +} + +extern void __real_free(void *); + +extern unsigned long high_physmem; + +void __wrap_free(void *ptr) +{ + unsigned long addr = (unsigned long) ptr; + + /* + * We need to know how the allocation happened, so it can be correctly + * freed. This is done by seeing what region of memory the pointer is + * in - + * physical memory - kmalloc/kfree + * kernel virtual memory - vmalloc/vfree + * anywhere else - malloc/free + * If kmalloc is not yet possible, then either high_physmem and/or + * end_vm are still 0 (as at startup), in which case we call free, or + * we have set them, but anyway addr has not been allocated from those + * areas. So, in both cases __real_free is called. + * + * CAN_KMALLOC is checked because it would be bad to free a buffer + * with kmalloc/vmalloc after they have been turned off during + * shutdown. + * XXX: However, we sometimes shutdown CAN_KMALLOC temporarily, so + * there is a possibility for memory leaks. + */ + + if ((addr >= uml_physmem) && (addr < high_physmem)) { + if (kmalloc_ok) + kfree(ptr); + } + else if ((addr >= start_vm) && (addr < end_vm)) { + if (kmalloc_ok) + vfree(ptr); + } + else __real_free(ptr); +} diff --git a/pool/shard004/C/0098868_getcwd.c b/pool/shard004/C/0098868_getcwd.c new file mode 100644 index 0000000000000000000000000000000000000000..ccde58d87c41fc745037a299ac9221fc592b6235 --- /dev/null +++ b/pool/shard004/C/0098868_getcwd.c @@ -0,0 +1,164 @@ +/* getcwd.c - an implementation of the getcwd(3) library function. + * + * The `getcwd(3)` library function provides a way to retrieve the current + * working directory of a process. + * + * The way this implementation works is getting the current directory name from + * the parent directory, scanning its entries until one with the same i-node and + * device number is found. This is the algorithm suggested by ``The Linux + * Programming Interface'' book. + * + * Usage + * + * $ ./getcwd + * + * Author: Renato Mascarenhas Costa + */ + +#define _XOPEN_SOURCE 500 + +#include + +#ifndef PATH_MAX +# include +#endif + +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +typedef enum { FALSE, TRUE } Bool; + +static char *_getcwd(char *buf, size_t size); +static void pexit(const char *fCall); + +int +main() { + char cwd[PATH_MAX]; + + if (_getcwd(cwd, PATH_MAX) == NULL) { + pexit("_getcwd"); + } + + printf("%s\n", cwd); + + exit(EXIT_SUCCESS); +} + +static void +pexit(const char *fCall) { + perror(fCall); + exit(EXIT_FAILURE); +} + +static char * +_getcwd(char *buf, size_t size) { + size_t total; + int fd; + struct stat sCur, sParent, sEntry; + char parentDir[NAME_MAX], curFile[NAME_MAX]; + DIR *dir; + struct dirent *entry; + Bool found; + + if (stat(".", &sCur) == -1) { + return NULL; + } + + if (stat("..", &sParent) == -1) { + return NULL; + } + + /* recursion stop condition */ + if (sCur.st_dev == sParent.st_dev && sCur.st_ino == sParent.st_ino) { + snprintf(buf, size, "/"); + return buf; + } + + /* open the parent dir and scan it for the current directory name */ + dir = opendir(".."); + if (dir == NULL) { + return NULL; + } + + found = FALSE; + errno = 0; + entry = readdir(dir); + + while (!found && entry != NULL) { + /* skip . and .. entries */ + if (strncmp(entry->d_name, ".", NAME_MAX) && strncmp(entry->d_name, "..", NAME_MAX)) { + snprintf(curFile, NAME_MAX, "../%s", entry->d_name); + + if (stat(curFile, &sEntry) == -1) { + return NULL; + } + + if (sEntry.st_dev == sCur.st_dev && sEntry.st_ino == sCur.st_ino) { + found = TRUE; + continue; + } + } + entry = readdir(dir); + } + + if (errno != 0) { + return NULL; + } + + if (entry == NULL) { + return NULL; + } else { + total = strlen(entry->d_name); + } + + /* recursively find the path to the parent directory */ + fd = open(".", O_RDONLY); + if (fd == -1) { + return NULL; + } + + if (chdir("..") == -1) { + return NULL; + } + + if (_getcwd(parentDir, NAME_MAX) == NULL) { + return NULL; + } + + total += strlen(parentDir); + if (total >= size) { + errno = ERANGE; + return NULL; + } + + /* generate the current working directory by concatening the result found + * when running recursively on the parent and the current dir name */ + if (strncmp(parentDir, "/", NAME_MAX)) { + snprintf(buf, size, "%s/%s", parentDir, entry->d_name); + } else { + snprintf(buf, size, "/%s", entry->d_name); + } + + /* get back to where we were */ + if (fchdir(fd) == -1) { + return NULL; + } + + if (close(fd) == -1) { + return NULL; + } + + if (closedir(dir) == -1) { + return NULL; + } + + return buf; +} diff --git a/pool/shard004/C/0098871_beetle_clock_control.c b/pool/shard004/C/0098871_beetle_clock_control.c new file mode 100644 index 0000000000000000000000000000000000000000..077d92d5220235403266550631924a7e0398ca97 --- /dev/null +++ b/pool/shard004/C/0098871_beetle_clock_control.c @@ -0,0 +1,248 @@ +/* + * Copyright (c) 2016 Linaro Limited. + * + * SPDX-License-Identifier: Apache-2.0 + */ + +/** + * @file + * @brief Driver for Clock Control of Beetle MCUs. + * + * This file contains the Clock Control driver implementation for the + * Beetle MCUs. + */ + +#include +#include +#include +#include + +#define MAINCLK_BASE_FREQ 24000000 + +struct beetle_clock_control_cfg_t { + /* Clock Control ID */ + u32_t clock_control_id; + /* Clock control freq */ + u32_t freq; +}; + +static inline void beetle_set_clock(volatile u32_t *base, + u8_t bit, enum arm_soc_state_t state) +{ + u32_t key; + + key = irq_lock(); + + switch (state) { + case SOC_ACTIVE: + base[0] |= (1 << bit); + break; + case SOC_SLEEP: + base[2] |= (1 << bit); + break; + case SOC_DEEPSLEEP: + base[4] |= (1 << bit); + break; + default: + break; + } + + irq_unlock(key); +} + +static inline void beetle_ahb_set_clock_on(u8_t bit, + enum arm_soc_state_t state) +{ + beetle_set_clock((volatile u32_t *)&(__BEETLE_SYSCON->ahbclkcfg0set), + bit, state); +} + +static inline void beetle_ahb_set_clock_off(u8_t bit, + enum arm_soc_state_t state) +{ + beetle_set_clock((volatile u32_t *)&(__BEETLE_SYSCON->ahbclkcfg0clr), + bit, state); +} + +static inline void beetle_apb_set_clock_on(u8_t bit, + enum arm_soc_state_t state) +{ + beetle_set_clock((volatile u32_t *)&(__BEETLE_SYSCON->apbclkcfg0set), + bit, state); +} + +static inline void beetle_apb_set_clock_off(u8_t bit, + enum arm_soc_state_t state) +{ + beetle_set_clock((volatile u32_t *)&(__BEETLE_SYSCON->apbclkcfg0clr), + bit, state); +} + +static inline int beetle_clock_control_on(struct device *dev, + clock_control_subsys_t sub_system) +{ + struct arm_clock_control_t *beetle_cc = + (struct arm_clock_control_t *)(sub_system); + + u8_t bit = 0U; + + switch (beetle_cc->bus) { + case CMSDK_AHB: + bit = (beetle_cc->device - _BEETLE_AHB_BASE) >> 12; + beetle_ahb_set_clock_on(bit, beetle_cc->state); + break; + case CMSDK_APB: + bit = (beetle_cc->device - _BEETLE_APB_BASE) >> 12; + beetle_apb_set_clock_on(bit, beetle_cc->state); + break; + default: + break; + } + + return 0; +} + +static inline int beetle_clock_control_off(struct device *dev, + clock_control_subsys_t sub_system) +{ + struct arm_clock_control_t *beetle_cc = + (struct arm_clock_control_t *)(sub_system); + + u8_t bit = 0U; + + switch (beetle_cc->bus) { + case CMSDK_AHB: + bit = (beetle_cc->device - _BEETLE_AHB_BASE) >> 12; + beetle_ahb_set_clock_off(bit, beetle_cc->state); + break; + case CMSDK_APB: + bit = (beetle_cc->device - _BEETLE_APB_BASE) >> 12; + beetle_apb_set_clock_off(bit, beetle_cc->state); + break; + default: + break; + } + return 0; +} + +static int beetle_clock_control_get_subsys_rate(struct device *clock, + clock_control_subsys_t sub_system, + u32_t *rate) +{ +#ifdef CONFIG_CLOCK_CONTROL_BEETLE_ENABLE_PLL + const struct beetle_clock_control_cfg_t * const cfg = + clock->config->config_info; + u32_t nc_mainclk = beetle_round_freq(cfg->freq); + + *rate = nc_mainclk; +#else + ARG_UNUSED(clock); + ARG_UNUSED(sub_system); + + *rate = MAINCLK_BASE_FREQ; +#endif /* CONFIG_CLOCK_CONTROL_BEETLE_ENABLE_PLL */ + + return 0; +} + +static const struct clock_control_driver_api beetle_clock_control_api = { + .on = beetle_clock_control_on, + .off = beetle_clock_control_off, + .get_rate = beetle_clock_control_get_subsys_rate, +}; + +#ifdef CONFIG_CLOCK_CONTROL_BEETLE_ENABLE_PLL +static u32_t beetle_round_freq(u32_t mainclk) +{ + u32_t nc_mainclk = 0U; + + /* + * Verify that the frequency is in the supported range otherwise + * round it to the next closer one. + */ + if (mainclk <= BEETLE_PLL_FREQUENCY_12MHZ) { + nc_mainclk = BEETLE_PLL_FREQUENCY_12MHZ; + } else if (mainclk <= BEETLE_PLL_FREQUENCY_24MHZ) { + nc_mainclk = BEETLE_PLL_FREQUENCY_24MHZ; + } else if (mainclk <= BEETLE_PLL_FREQUENCY_36MHZ) { + nc_mainclk = BEETLE_PLL_FREQUENCY_36MHZ; + } else { + nc_mainclk = BEETLE_PLL_FREQUENCY_48MHZ; + } + + return nc_mainclk; +} + +static u32_t beetle_get_prescaler(u32_t mainclk) +{ + u32_t pre_mainclk = 0U; + + /* + * Verify that the frequency is in the supported range otherwise + * round it to the next closer one. + */ + if (mainclk <= BEETLE_PLL_FREQUENCY_12MHZ) { + pre_mainclk = BEETLE_PLL_PRESCALER_12MHZ; + } else if (mainclk <= BEETLE_PLL_FREQUENCY_24MHZ) { + pre_mainclk = BEETLE_PLL_PRESCALER_24MHZ; + } else if (mainclk <= BEETLE_PLL_FREQUENCY_36MHZ) { + pre_mainclk = BEETLE_PLL_PRESCALER_36MHZ; + } else { + pre_mainclk = BEETLE_PLL_PRESCALER_48MHZ; + } + + return pre_mainclk; +} + +static int beetle_pll_enable(u32_t mainclk) +{ + + u32_t pre_mainclk = beetle_get_prescaler(mainclk); + + /* Set PLLCTRL Register */ + __BEETLE_SYSCON->pllctrl = BEETLE_PLL_CONFIGURATION; + + /* Switch the the Main clock to PLL and set prescaler */ + __BEETLE_SYSCON->mainclk = pre_mainclk; + + while (!__BEETLE_SYSCON->pllstatus) { + /* Wait for PLL to lock */ + } + + return 0; +} +#endif /* CONFIG_CLOCK_CONTROL_BEETLE_ENABLE_PLL */ + +static int beetle_clock_control_init(struct device *dev) +{ +#ifdef CONFIG_CLOCK_CONTROL_BEETLE_ENABLE_PLL + const struct beetle_clock_control_cfg_t * const cfg = + dev->config->config_info; + + /* + * Enable PLL if Beetle is configured to run at a different + * frequency than 24Mhz. + */ + if (cfg->freq != MAINCLK_BASE_FREQ) { + beetle_pll_enable(cfg->freq); + } +#endif /* CONFIG_CLOCK_CONTROL_BEETLE_ENABLE_PLL */ + + return 0; +} + +static const struct beetle_clock_control_cfg_t beetle_cc_cfg = { + .clock_control_id = 0, + .freq = CONFIG_SYS_CLOCK_HW_CYCLES_PER_SEC, +}; + +/** + * @brief Clock Control device init + * + */ +DEVICE_AND_API_INIT(clock_control_beetle, CONFIG_ARM_CLOCK_CONTROL_DEV_NAME, + &beetle_clock_control_init, + NULL, &beetle_cc_cfg, + PRE_KERNEL_1, + CONFIG_CLOCK_CONTROL_BEETLE_DEVICE_INIT_PRIORITY, + &beetle_clock_control_api); diff --git a/pool/shard004/C/0098882_ftk_font_freetype.c b/pool/shard004/C/0098882_ftk_font_freetype.c new file mode 100644 index 0000000000000000000000000000000000000000..0c76570882629e7aa15b8743106741f3cbdc675c --- /dev/null +++ b/pool/shard004/C/0098882_ftk_font_freetype.c @@ -0,0 +1,144 @@ +/* + * File: ftk_font_freetype.c + * Author: Li XianJing + * Brief: freetype font. + * + * Copyright (c) 2009 - 2010 Li XianJing + * + * Licensed under the Academic Free License version 2.1 + * + * 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 + */ + +/* + * History: + * ================================================================ + * 2012-6-29 woodysu@gmail.com modified + * 2009-10-03 Li XianJing created + * + */ + +#include "ftk_log.h" +#include +#include FT_GLYPH_H +#include "ftk_util.h" +#include "ftk_mmap.h" +#include "ftk_font.h" + + +typedef struct _FontFreetypePrivInfo +{ + int bold; + int italic; + size_t size; + FT_Face face; + FT_Library library; +}PrivInfo; + +static int ftk_font_freetype_height(FtkFont* thiz) +{ + DECL_PRIV(thiz, priv); + return_val_if_fail(thiz != NULL, 0); + + return priv->size; +} + +static Ret ftk_font_freetype_lookup (FtkFont* thiz, unsigned short code, FtkGlyph* glyph) +{ + int index = 0; + FT_Error err = 0; + DECL_PRIV(thiz, priv); + return_val_if_fail(thiz != NULL && glyph != NULL, RET_FAIL); + + index = FT_Get_Char_Index(priv->face, code); + err = FT_Load_Glyph(priv->face, index, FT_LOAD_DEFAULT|FT_LOAD_RENDER); + return_val_if_fail(err == 0, RET_FAIL); + + glyph->code = code; + glyph->x = priv->face->glyph->bitmap_left; + glyph->y = priv->face->glyph->bitmap_top; + glyph->w = priv->face->glyph->bitmap.width; + glyph->h = priv->face->glyph->bitmap.rows; + glyph->advance_x = priv->face->glyph->advance.x >> 6; + glyph->data = priv->face->glyph->bitmap.buffer; + // For fix a bug-- the actual bitmap of some fonts is larger than it's font size + if (glyph->h > thiz->height(thiz)) { + ftk_logw("Bug font code: %04x\n", code); + glyph->h = thiz->height(thiz); + } + + + + return RET_OK; +} + +void ftk_font_freetype_destroy(FtkFont* thiz) +{ + if(thiz != NULL) + { + DECL_PRIV(thiz, priv); + FT_Done_Face(priv->face); + FT_Done_FreeType(priv->library); + FTK_ZFREE(thiz, sizeof(*thiz) + sizeof(PrivInfo)); + } + + return; +} + +FtkFont* ftk_font_create (const char* filename, FtkFontDesc* font_desc) +{ + int size = 0; + FtkFont* thiz = NULL; + return_val_if_fail(filename != NULL && font_desc != NULL, NULL); + + size = ftk_font_desc_get_size(font_desc); + thiz = FTK_NEW_PRIV(FtkFont); + if(thiz != NULL) + { + FT_Error err = 0; + DECL_PRIV(thiz, priv); + + thiz->ref = 1; + thiz->height = ftk_font_freetype_height; + thiz->lookup = ftk_font_freetype_lookup; + thiz->destroy= ftk_font_freetype_destroy; + + priv->size = size; + err = FT_Init_FreeType(&priv->library ); + if((err = FT_New_Face(priv->library, filename, 0, &priv->face))) + { + ftk_loge("load %s failed.\n", filename); + FT_Done_FreeType(priv->library); + FTK_ZFREE(thiz, sizeof(FtkFont)); + } + else + { + err = FT_Select_Charmap(priv->face, ft_encoding_unicode); + if(err) + { + err = FT_Select_Charmap(priv->face, ft_encoding_latin_1 ); + } + assert(err == 0); + err = FT_Set_Pixel_Sizes(priv->face, 0, size); + assert(err == 0); + ftk_logd("fonfile:%s\n", filename); + ftk_logd("font family_name:%s\n", priv->face->family_name); + ftk_logd("font style_name:%s\n", priv->face->style_name); + } + } + + return thiz; +} + diff --git a/pool/shard004/C/0098888_5-1.c b/pool/shard004/C/0098888_5-1.c new file mode 100644 index 0000000000000000000000000000000000000000..2c38155cf9241553ae9b89c8f0de85b36b04e153 --- /dev/null +++ b/pool/shard004/C/0098888_5-1.c @@ -0,0 +1,51 @@ +/* + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License version 2. + * + * 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. + * + * Test that the reuse of the name subsequently causes shm_open() to + * create a new shared memory object if O_CREAT is set even if the object + * continues to exist after the last shm_unlink(), + */ + +#include +#include +#include +#include +#include +#include "posixtest.h" + +#define SHM_NAME "posixtest_5-1" + +int main() { + int fd; + + fd = shm_open(SHM_NAME, O_RDWR|O_CREAT, S_IRUSR|S_IWUSR); + if (fd == -1) { + perror("An error occurs when calling shm_open()"); + return PTS_UNRESOLVED; + } + + if (shm_unlink(SHM_NAME) != 0) { + perror("An error occurs when calling shm_unlink()"); + return PTS_UNRESOLVED; + } + + fd = shm_open(SHM_NAME, O_RDWR|O_CREAT|O_EXCL, S_IRUSR|S_IWUSR); + if (fd == -1 && errno == EEXIST) { + printf("shm_open() can not create a new object.\n"); + return PTS_FAIL; + } else if (fd == -1) { + perror("shm_open"); + return PTS_UNRESOLVED; + } + + printf("Test PASSED\n"); + shm_unlink(SHM_NAME); + return PTS_PASS; + +} \ No newline at end of file diff --git a/pool/shard004/C/0098897_lpc17xx_clkpwr.c b/pool/shard004/C/0098897_lpc17xx_clkpwr.c new file mode 100644 index 0000000000000000000000000000000000000000..debe0ccabac0d4b4173bfebae0738375f06c48c3 --- /dev/null +++ b/pool/shard004/C/0098897_lpc17xx_clkpwr.c @@ -0,0 +1,347 @@ +#ifdef __LPC17XX__ + +/********************************************************************** +* $Id$ lpc17xx_clkpwr.c 2010-06-18 +*//** +* @file lpc17xx_clkpwr.c +* @brief Contains all functions support for Clock and Power Control +* firmware library on LPC17xx +* @version 3.0 +* @date 18. June. 2010 +* @author NXP MCU SW Application Team +* +* Copyright(C) 2010, NXP Semiconductor +* All rights reserved. +* +*********************************************************************** +* Software that is described herein is for illustrative purposes only +* which provides customers with programming information regarding the +* products. This software is supplied "AS IS" without any warranties. +* NXP Semiconductors assumes no responsibility or liability for the +* use of the software, conveys no license or title under any patent, +* copyright, or mask work right to the product. NXP Semiconductors +* reserves the right to make changes in the software without +* notification. NXP Semiconductors also make no representation or +* warranty that such application will be suitable for the specified +* use without further testing or modification. +**********************************************************************/ + +/* Peripheral group ----------------------------------------------------------- */ +/** @addtogroup CLKPWR + * @{ + */ + +/* Includes ------------------------------------------------------------------- */ +#include "lpc17xx_clkpwr.h" + + +/* Public Functions ----------------------------------------------------------- */ +/** @addtogroup CLKPWR_Public_Functions + * @{ + */ + +/*********************************************************************//** + * @brief Set value of each Peripheral Clock Selection + * @param[in] ClkType Peripheral Clock Selection of each type, + * should be one of the following: + * - CLKPWR_PCLKSEL_WDT : WDT + - CLKPWR_PCLKSEL_TIMER0 : Timer 0 + - CLKPWR_PCLKSEL_TIMER1 : Timer 1 + - CLKPWR_PCLKSEL_UART0 : UART 0 + - CLKPWR_PCLKSEL_UART1 : UART 1 + - CLKPWR_PCLKSEL_PWM1 : PWM 1 + - CLKPWR_PCLKSEL_I2C0 : I2C 0 + - CLKPWR_PCLKSEL_SPI : SPI + - CLKPWR_PCLKSEL_SSP1 : SSP 1 + - CLKPWR_PCLKSEL_DAC : DAC + - CLKPWR_PCLKSEL_ADC : ADC + - CLKPWR_PCLKSEL_CAN1 : CAN 1 + - CLKPWR_PCLKSEL_CAN2 : CAN 2 + - CLKPWR_PCLKSEL_ACF : ACF + - CLKPWR_PCLKSEL_QEI : QEI + - CLKPWR_PCLKSEL_PCB : PCB + - CLKPWR_PCLKSEL_I2C1 : I2C 1 + - CLKPWR_PCLKSEL_SSP0 : SSP 0 + - CLKPWR_PCLKSEL_TIMER2 : Timer 2 + - CLKPWR_PCLKSEL_TIMER3 : Timer 3 + - CLKPWR_PCLKSEL_UART2 : UART 2 + - CLKPWR_PCLKSEL_UART3 : UART 3 + - CLKPWR_PCLKSEL_I2C2 : I2C 2 + - CLKPWR_PCLKSEL_I2S : I2S + - CLKPWR_PCLKSEL_RIT : RIT + - CLKPWR_PCLKSEL_SYSCON : SYSCON + - CLKPWR_PCLKSEL_MC : MC + + * @param[in] DivVal Value of divider, should be: + * - CLKPWR_PCLKSEL_CCLK_DIV_4 : PCLK_peripheral = CCLK/4 + * - CLKPWR_PCLKSEL_CCLK_DIV_1 : PCLK_peripheral = CCLK/1 + * - CLKPWR_PCLKSEL_CCLK_DIV_2 : PCLK_peripheral = CCLK/2 + * + * @return none + **********************************************************************/ +void CLKPWR_SetPCLKDiv (uint32_t ClkType, uint32_t DivVal) +{ + uint32_t bitpos; + + bitpos = (ClkType < 32) ? (ClkType) : (ClkType - 32); + + /* PCLKSEL0 selected */ + if (ClkType < 32) + { + /* Clear two bit at bit position */ + LPC_SC->PCLKSEL0 &= (~(CLKPWR_PCLKSEL_BITMASK(bitpos))); + + /* Set two selected bit */ + LPC_SC->PCLKSEL0 |= (CLKPWR_PCLKSEL_SET(bitpos, DivVal)); + } + /* PCLKSEL1 selected */ + else + { + /* Clear two bit at bit position */ + LPC_SC->PCLKSEL1 &= ~(CLKPWR_PCLKSEL_BITMASK(bitpos)); + + /* Set two selected bit */ + LPC_SC->PCLKSEL1 |= (CLKPWR_PCLKSEL_SET(bitpos, DivVal)); + } +} + + +/*********************************************************************//** + * @brief Get current value of each Peripheral Clock Selection + * @param[in] ClkType Peripheral Clock Selection of each type, + * should be one of the following: + * - CLKPWR_PCLKSEL_WDT : WDT + - CLKPWR_PCLKSEL_TIMER0 : Timer 0 + - CLKPWR_PCLKSEL_TIMER1 : Timer 1 + - CLKPWR_PCLKSEL_UART0 : UART 0 + - CLKPWR_PCLKSEL_UART1 : UART 1 + - CLKPWR_PCLKSEL_PWM1 : PWM 1 + - CLKPWR_PCLKSEL_I2C0 : I2C 0 + - CLKPWR_PCLKSEL_SPI : SPI + - CLKPWR_PCLKSEL_SSP1 : SSP 1 + - CLKPWR_PCLKSEL_DAC : DAC + - CLKPWR_PCLKSEL_ADC : ADC + - CLKPWR_PCLKSEL_CAN1 : CAN 1 + - CLKPWR_PCLKSEL_CAN2 : CAN 2 + - CLKPWR_PCLKSEL_ACF : ACF + - CLKPWR_PCLKSEL_QEI : QEI + - CLKPWR_PCLKSEL_PCB : PCB + - CLKPWR_PCLKSEL_I2C1 : I2C 1 + - CLKPWR_PCLKSEL_SSP0 : SSP 0 + - CLKPWR_PCLKSEL_TIMER2 : Timer 2 + - CLKPWR_PCLKSEL_TIMER3 : Timer 3 + - CLKPWR_PCLKSEL_UART2 : UART 2 + - CLKPWR_PCLKSEL_UART3 : UART 3 + - CLKPWR_PCLKSEL_I2C2 : I2C 2 + - CLKPWR_PCLKSEL_I2S : I2S + - CLKPWR_PCLKSEL_RIT : RIT + - CLKPWR_PCLKSEL_SYSCON : SYSCON + - CLKPWR_PCLKSEL_MC : MC + + * @return Value of Selected Peripheral Clock Selection + **********************************************************************/ +uint32_t CLKPWR_GetPCLKSEL (uint32_t ClkType) +{ + uint32_t bitpos, retval; + + if (ClkType < 32) + { + bitpos = ClkType; + retval = LPC_SC->PCLKSEL0; + } + else + { + bitpos = ClkType - 32; + retval = LPC_SC->PCLKSEL1; + } + + retval = CLKPWR_PCLKSEL_GET(bitpos, retval); + return retval; +} + + + +/*********************************************************************//** + * @brief Get current value of each Peripheral Clock + * @param[in] ClkType Peripheral Clock Selection of each type, + * should be one of the following: + * - CLKPWR_PCLKSEL_WDT : WDT + - CLKPWR_PCLKSEL_TIMER0 : Timer 0 + - CLKPWR_PCLKSEL_TIMER1 : Timer 1 + - CLKPWR_PCLKSEL_UART0 : UART 0 + - CLKPWR_PCLKSEL_UART1 : UART 1 + - CLKPWR_PCLKSEL_PWM1 : PWM 1 + - CLKPWR_PCLKSEL_I2C0 : I2C 0 + - CLKPWR_PCLKSEL_SPI : SPI + - CLKPWR_PCLKSEL_SSP1 : SSP 1 + - CLKPWR_PCLKSEL_DAC : DAC + - CLKPWR_PCLKSEL_ADC : ADC + - CLKPWR_PCLKSEL_CAN1 : CAN 1 + - CLKPWR_PCLKSEL_CAN2 : CAN 2 + - CLKPWR_PCLKSEL_ACF : ACF + - CLKPWR_PCLKSEL_QEI : QEI + - CLKPWR_PCLKSEL_PCB : PCB + - CLKPWR_PCLKSEL_I2C1 : I2C 1 + - CLKPWR_PCLKSEL_SSP0 : SSP 0 + - CLKPWR_PCLKSEL_TIMER2 : Timer 2 + - CLKPWR_PCLKSEL_TIMER3 : Timer 3 + - CLKPWR_PCLKSEL_UART2 : UART 2 + - CLKPWR_PCLKSEL_UART3 : UART 3 + - CLKPWR_PCLKSEL_I2C2 : I2C 2 + - CLKPWR_PCLKSEL_I2S : I2S + - CLKPWR_PCLKSEL_RIT : RIT + - CLKPWR_PCLKSEL_SYSCON : SYSCON + - CLKPWR_PCLKSEL_MC : MC + + * @return Value of Selected Peripheral Clock + **********************************************************************/ +uint32_t CLKPWR_GetPCLK (uint32_t ClkType) +{ + uint32_t retval, div; + + retval = SystemCoreClock; + div = CLKPWR_GetPCLKSEL(ClkType); + + switch (div) + { + case 0: + div = 4; + break; + + case 1: + div = 1; + break; + + case 2: + div = 2; + break; + + case 3: + div = 8; + break; + } + retval /= div; + + return retval; +} + + + +/*********************************************************************//** + * @brief Configure power supply for each peripheral according to NewState + * @param[in] PPType Type of peripheral used to enable power, + * should be one of the following: + * - CLKPWR_PCONP_PCTIM0 : Timer 0 + - CLKPWR_PCONP_PCTIM1 : Timer 1 + - CLKPWR_PCONP_PCUART0 : UART 0 + - CLKPWR_PCONP_PCUART1 : UART 1 + - CLKPWR_PCONP_PCPWM1 : PWM 1 + - CLKPWR_PCONP_PCI2C0 : I2C 0 + - CLKPWR_PCONP_PCSPI : SPI + - CLKPWR_PCONP_PCRTC : RTC + - CLKPWR_PCONP_PCSSP1 : SSP 1 + - CLKPWR_PCONP_PCAD : ADC + - CLKPWR_PCONP_PCAN1 : CAN 1 + - CLKPWR_PCONP_PCAN2 : CAN 2 + - CLKPWR_PCONP_PCGPIO : GPIO + - CLKPWR_PCONP_PCRIT : RIT + - CLKPWR_PCONP_PCMC : MC + - CLKPWR_PCONP_PCQEI : QEI + - CLKPWR_PCONP_PCI2C1 : I2C 1 + - CLKPWR_PCONP_PCSSP0 : SSP 0 + - CLKPWR_PCONP_PCTIM2 : Timer 2 + - CLKPWR_PCONP_PCTIM3 : Timer 3 + - CLKPWR_PCONP_PCUART2 : UART 2 + - CLKPWR_PCONP_PCUART3 : UART 3 + - CLKPWR_PCONP_PCI2C2 : I2C 2 + - CLKPWR_PCONP_PCI2S : I2S + - CLKPWR_PCONP_PCGPDMA : GPDMA + - CLKPWR_PCONP_PCENET : Ethernet + - CLKPWR_PCONP_PCUSB : USB + * + * @param[in] NewState New state of Peripheral Power, should be: + * - ENABLE : Enable power for this peripheral + * - DISABLE : Disable power for this peripheral + * + * @return none + **********************************************************************/ +void CLKPWR_ConfigPPWR (uint32_t PPType, FunctionalState NewState) +{ + if (NewState == ENABLE) + { + LPC_SC->PCONP |= PPType & CLKPWR_PCONP_BITMASK; + } + else if (NewState == DISABLE) + { + LPC_SC->PCONP &= (~PPType) & CLKPWR_PCONP_BITMASK; + } +} + + +/*********************************************************************//** + * @brief Enter Sleep mode with co-operated instruction by the Cortex-M3. + * @param[in] None + * @return None + **********************************************************************/ +void CLKPWR_Sleep(void) +{ + LPC_SC->PCON = 0x00; + /* Sleep Mode*/ + __WFI(); +} + + +/*********************************************************************//** + * @brief Enter Deep Sleep mode with co-operated instruction by the Cortex-M3. + * @param[in] None + * @return None + **********************************************************************/ +void CLKPWR_DeepSleep(void) +{ + /* Deep-Sleep Mode, set SLEEPDEEP bit */ + SCB->SCR = 0x4; + LPC_SC->PCON = 0x8; + /* Deep Sleep Mode*/ + __WFI(); +} + + +/*********************************************************************//** + * @brief Enter Power Down mode with co-operated instruction by the Cortex-M3. + * @param[in] None + * @return None + **********************************************************************/ +void CLKPWR_PowerDown(void) +{ + /* Deep-Sleep Mode, set SLEEPDEEP bit */ + SCB->SCR = 0x4; + LPC_SC->PCON = 0x09; + /* Power Down Mode*/ + __WFI(); +} + + +/*********************************************************************//** + * @brief Enter Deep Power Down mode with co-operated instruction by the Cortex-M3. + * @param[in] None + * @return None + **********************************************************************/ +void CLKPWR_DeepPowerDown(void) +{ + /* Deep-Sleep Mode, set SLEEPDEEP bit */ + SCB->SCR = 0x4; + LPC_SC->PCON = 0x03; + /* Deep Power Down Mode*/ + __WFI(); +} + +/** + * @} + */ + +/** + * @} + */ + +/* --------------------------------- End Of File ------------------------------ */ +#endif /* __LPC17XX__ */ diff --git a/pool/shard004/C/0098901_nautilus-progress-info-widget.c b/pool/shard004/C/0098901_nautilus-progress-info-widget.c new file mode 100644 index 0000000000000000000000000000000000000000..a2d711c0bfa011e86bc81169974641431603d4eb --- /dev/null +++ b/pool/shard004/C/0098901_nautilus-progress-info-widget.c @@ -0,0 +1,215 @@ +/* + * nautilus-progress-info-widget.h: file operation progress user interface. + * + * Copyright (C) 2007, 2011 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, see . + * + * Authors: Alexander Larsson + * Cosimo Cecchi + * + */ + +#include + +#include "nautilus-progress-info-widget.h" +struct _NautilusProgressInfoWidgetPrivate { + NautilusProgressInfo *info; + + GtkWidget *status; /* GtkLabel */ + GtkWidget *details; /* GtkLabel */ + GtkWidget *progress_bar; + GtkWidget *button; + GtkWidget *done_image; +}; + +enum { + PROP_INFO = 1, + NUM_PROPERTIES +}; + +static GParamSpec *properties[NUM_PROPERTIES] = { NULL }; + +G_DEFINE_TYPE_WITH_PRIVATE (NautilusProgressInfoWidget, nautilus_progress_info_widget, + GTK_TYPE_GRID); + +static void +info_finished (NautilusProgressInfoWidget *self) +{ + gtk_button_set_image (GTK_BUTTON (self->priv->button), self->priv->done_image); + gtk_widget_set_sensitive (self->priv->button, FALSE); +} + +static void +info_cancelled (NautilusProgressInfoWidget *self) +{ + gtk_widget_set_sensitive (self->priv->button, FALSE); +} + +static void +update_data (NautilusProgressInfoWidget *self) +{ + char *status, *details; + char *markup; + + status = nautilus_progress_info_get_status (self->priv->info); + gtk_label_set_text (GTK_LABEL (self->priv->status), status); + g_free (status); + + details = nautilus_progress_info_get_details (self->priv->info); + markup = g_markup_printf_escaped ("%s", details); + gtk_label_set_markup (GTK_LABEL (self->priv->details), markup); + g_free (details); + g_free (markup); +} + +static void +update_progress (NautilusProgressInfoWidget *self) +{ + double progress; + + progress = nautilus_progress_info_get_progress (self->priv->info); + if (progress < 0) { + gtk_progress_bar_pulse (GTK_PROGRESS_BAR (self->priv->progress_bar)); + } else { + gtk_progress_bar_set_fraction (GTK_PROGRESS_BAR (self->priv->progress_bar), progress); + } +} + +static void +button_clicked (GtkWidget *button, + NautilusProgressInfoWidget *self) +{ + if (!nautilus_progress_info_get_is_finished (self->priv->info)) { + nautilus_progress_info_cancel (self->priv->info); + } +} + +static void +nautilus_progress_info_widget_dispose (GObject *obj) +{ + NautilusProgressInfoWidget *self = NAUTILUS_PROGRESS_INFO_WIDGET (obj); + + if (self->priv->info != NULL) { + g_signal_handlers_disconnect_by_data (self->priv->info, self); + } + g_clear_object (&self->priv->info); + + G_OBJECT_CLASS (nautilus_progress_info_widget_parent_class)->dispose (obj); +} + +static void +nautilus_progress_info_widget_constructed (GObject *obj) +{ + NautilusProgressInfoWidget *self = NAUTILUS_PROGRESS_INFO_WIDGET (obj); + + G_OBJECT_CLASS (nautilus_progress_info_widget_parent_class)->constructed (obj); + + g_signal_connect_swapped (self->priv->info, + "changed", + G_CALLBACK (update_data), self); + g_signal_connect_swapped (self->priv->info, + "progress-changed", + G_CALLBACK (update_progress), self); + g_signal_connect_swapped (self->priv->info, + "finished", + G_CALLBACK (info_finished), self); + g_signal_connect_swapped (self->priv->info, + "cancelled", + G_CALLBACK (info_cancelled), self); + + update_data (self); + update_progress (self); +} + +static void +nautilus_progress_info_widget_set_property (GObject *object, + guint property_id, + const GValue *value, + GParamSpec *pspec) +{ + NautilusProgressInfoWidget *self = NAUTILUS_PROGRESS_INFO_WIDGET (object); + + switch (property_id) { + case PROP_INFO: + self->priv->info = g_value_dup_object (value); + break; + default: + G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec); + break; + } +} + +static void +nautilus_progress_info_widget_init (NautilusProgressInfoWidget *self) +{ + self->priv = nautilus_progress_info_widget_get_instance_private (self); + + gtk_widget_init_template (GTK_WIDGET (self)); + + g_signal_connect (self->priv->button, "clicked", + G_CALLBACK (button_clicked), self); +} + +static void +nautilus_progress_info_widget_class_init (NautilusProgressInfoWidgetClass *klass) +{ + GObjectClass *oclass; + GtkWidgetClass *widget_class; + + widget_class = GTK_WIDGET_CLASS (klass); + oclass = G_OBJECT_CLASS (klass); + oclass->set_property = nautilus_progress_info_widget_set_property; + oclass->constructed = nautilus_progress_info_widget_constructed; + oclass->dispose = nautilus_progress_info_widget_dispose; + + properties[PROP_INFO] = + g_param_spec_object ("info", + "NautilusProgressInfo", + "The NautilusProgressInfo associated with this widget", + NAUTILUS_TYPE_PROGRESS_INFO, + G_PARAM_WRITABLE | G_PARAM_CONSTRUCT_ONLY | + G_PARAM_STATIC_STRINGS); + + g_object_class_install_properties (oclass, NUM_PROPERTIES, properties); + + gtk_widget_class_set_template_from_resource (widget_class, + "/org/gnome/nautilus/ui/nautilus-progress-info-widget.ui"); + + gtk_widget_class_bind_template_child_private (widget_class, NautilusProgressInfoWidget, status); + gtk_widget_class_bind_template_child_private (widget_class, NautilusProgressInfoWidget, details); + gtk_widget_class_bind_template_child_private (widget_class, NautilusProgressInfoWidget, progress_bar); + gtk_widget_class_bind_template_child_private (widget_class, NautilusProgressInfoWidget, button); + gtk_widget_class_bind_template_child_private (widget_class, NautilusProgressInfoWidget, done_image); +} + +GtkWidget * +nautilus_progress_info_widget_new (NautilusProgressInfo *info) +{ + NautilusProgressInfoWidget *self; + + self = g_object_new (NAUTILUS_TYPE_PROGRESS_INFO_WIDGET, + "info", info, + NULL); + + if (nautilus_progress_info_get_is_finished (self->priv->info)) { + gtk_button_set_image (GTK_BUTTON (self->priv->button), self->priv->done_image); + } + + gtk_widget_set_sensitive (self->priv->button, + !nautilus_progress_info_get_is_finished (self->priv->info) && + !nautilus_progress_info_get_is_cancelled (self->priv->info)); + + return GTK_WIDGET (self); +} diff --git a/pool/shard004/C/0098904_fips_validation_cmac.c b/pool/shard004/C/0098904_fips_validation_cmac.c new file mode 100644 index 0000000000000000000000000000000000000000..54c951ef83975c4dd11a001409053bba14e5c5e5 --- /dev/null +++ b/pool/shard004/C/0098904_fips_validation_cmac.c @@ -0,0 +1,116 @@ +/* SPDX-License-Identifier: BSD-3-Clause + * Copyright(c) 2018 Intel Corporation + */ + +#include +#include +#include +#include + +#include + +#include "fips_validation.h" + +#define NEW_LINE_STR "#" +#define OP_STR "CMAC" + +#define ALGO_STR "Alg = " +#define MODE_STR "Mode = " + +#define COUNT_STR "Count = " +#define KLEN_STR "Klen = " +#define PTLEN_STR "Mlen = " +#define TAGLEN_STR "Tlen = " +#define KEY_STR "Key = " +#define PT_STR "Msg = " +#define TAG_STR "Mac = " + +#define GEN_STR "Generate" +#define VERIF_STR "Verify" + +#define POS_NEG_STR "Result = " +#define PASS_STR "P" +#define FAIL_STR "F" + +struct hash_algo_conversion { + const char *str; + enum fips_test_algorithms algo; +} cmac_algo[] = { + {"AES", FIPS_TEST_ALGO_AES_CMAC}, +}; + +static int +parse_test_cmac_writeback(struct fips_val *val) +{ + if (info.op == FIPS_TEST_ENC_AUTH_GEN) { + struct fips_val tmp_val = {val->val + vec.pt.len, + vec.cipher_auth.digest.len}; + + fprintf(info.fp_wr, "%s", TAG_STR); + parse_write_hex_str(&tmp_val); + } else { + fprintf(info.fp_wr, "%s", POS_NEG_STR); + + if (vec.status == RTE_CRYPTO_OP_STATUS_SUCCESS) + fprintf(info.fp_wr, "%s\n", PASS_STR); + else if (vec.status == RTE_CRYPTO_OP_STATUS_AUTH_FAILED) + fprintf(info.fp_wr, "%s\n", FAIL_STR); + else + fprintf(info.fp_wr, "Error\n"); + } + + return 0; +} + +struct fips_test_callback cmac_tests_vectors[] = { + {KLEN_STR, parser_read_uint32_val, &vec.cipher_auth.key}, + {PTLEN_STR, parser_read_uint32_val, &vec.pt}, + {TAGLEN_STR, parser_read_uint32_val, &vec.cipher_auth.digest}, + {KEY_STR, parse_uint8_hex_str, &vec.cipher_auth.key}, + {PT_STR, parse_uint8_known_len_hex_str, &vec.pt}, + {TAG_STR, parse_uint8_known_len_hex_str, + &vec.cipher_auth.digest}, + {NULL, NULL, NULL} /**< end pointer */ +}; + +int +parse_test_cmac_init(void) +{ + char *tmp; + uint32_t i, j; + + for (i = 0; i < info.nb_vec_lines; i++) { + char *line = info.vec[i]; + + tmp = strstr(line, ALGO_STR); + if (!tmp) + continue; + + for (j = 0; j < RTE_DIM(cmac_algo); j++) { + if (!strstr(line, cmac_algo[j].str)) + continue; + + info.algo = cmac_algo[j].algo; + break; + } + + if (j == RTE_DIM(cmac_algo)) + return -EINVAL; + + tmp = strstr(line, MODE_STR); + if (!tmp) + return -1; + + if (strstr(tmp, GEN_STR)) + info.op = FIPS_TEST_ENC_AUTH_GEN; + else if (strstr(tmp, VERIF_STR)) + info.op = FIPS_TEST_DEC_AUTH_VERIF; + else + return -EINVAL; + } + + info.parse_writeback = parse_test_cmac_writeback; + info.callbacks = cmac_tests_vectors; + + return 0; +} diff --git a/pool/shard004/C/0098906_makecontext.c b/pool/shard004/C/0098906_makecontext.c new file mode 100644 index 0000000000000000000000000000000000000000..932f071d563356d92220504232564614be1ad306 --- /dev/null +++ b/pool/shard004/C/0098906_makecontext.c @@ -0,0 +1,95 @@ +/* $NetBSD: makecontext.c,v 1.7 2011/09/20 08:42:29 joerg Exp $ */ + +/*- + * Copyright (c) 2001 The NetBSD Foundation, Inc. + * All rights reserved. + * + * This code is derived from software contributed to The NetBSD Foundation + * by Klaus Klein. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS + * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED + * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ + +#include +#if defined(LIBC_SCCS) && !defined(lint) +__RCSID("$NetBSD: makecontext.c,v 1.7 2011/09/20 08:42:29 joerg Exp $"); +#endif + +#include +#include +#include +#include "extern.h" + +#include + +void __resumecontext(void) __dead; + +void +makecontext(ucontext_t *ucp, void (*func)(void), int argc, ...) +{ + __greg_t *gr = ucp->uc_mcontext.__gregs; + __greg_t *sp; + int i; + va_list ap; + + /* LINTED uintptr_t is safe */ + sp = (__greg_t *) + ((uintptr_t)ucp->uc_stack.ss_sp + ucp->uc_stack.ss_size); + /* LINTED uintptr_t is safe */ +#if defined(__mips_o32) || defined(__mips_o64) + sp -= (argc >= 4 ? argc : 4); /* Make room for >=4 arguments. */ + sp = (__greg_t *) + ((uintptr_t)sp & ~0x7); /* Align on double-word boundary. */ +#elif defined(__mips_n32) || defined(__mips_n64) + sp -= (argc > 8 ? argc - 8 : 0); /* Make room for > 8 arguments. */ + sp = (__greg_t *) + ((uintptr_t)sp & ~0xf); /* Align on quad-word boundary. */ +#endif + + gr[_REG_SP] = (intptr_t)sp; + gr[_REG_RA] = (intptr_t)__resumecontext; + gr[_REG_T9] = (intptr_t)func; /* required for .abicalls */ + gr[_REG_EPC] = (intptr_t)func; + + /* Construct argument list. */ + va_start(ap, argc); +#if defined(__mips_o32) || defined(__mips_o64) + /* Up to the first four arguments are passed in $a0-3. */ + for (i = 0; i < argc && i < 4; i++) + /* LINTED __greg_t is safe */ + gr[_REG_A0 + i] = va_arg(ap, __greg_t); + /* Pass remaining arguments on the stack above the $a0-3 gap. */ + sp += i; +#endif +#if defined(__mips_n32) || defined(__mips_n64) + /* Up to the first 8 arguments are passed in $a0-7. */ + for (i = 0; i < argc && i < 8; i++) + /* LINTED __greg_t is safe */ + gr[_REG_A0 + i] = va_arg(ap, __greg_t); + /* Pass remaining arguments on the stack above the $a0-3 gap. */ +#endif + /* Pass remaining arguments on the stack above the $a0-3 gap. */ + for (; i < argc; i++) + /* LINTED uintptr_t is safe */ + *sp++ = va_arg(ap, __greg_t); + va_end(ap); +} diff --git a/pool/shard004/C/0098907_ue_update_status.c b/pool/shard004/C/0098907_ue_update_status.c new file mode 100644 index 0000000000000000000000000000000000000000..c1862ad9835e2a7caa1d4744abefea07ff9b1a0e --- /dev/null +++ b/pool/shard004/C/0098907_ue_update_status.c @@ -0,0 +1,30 @@ + +#include +#include +#include +#include "ue_update_status.h" + +char* OpenAPI_ue_update_status_ToString(OpenAPI_ue_update_status_e ue_update_status) +{ + const char *ue_update_statusArray[] = { "NULL", "NOT_SENT", "SENT_NO_ACK_REQUIRED", "WAITING_FOR_ACK", "ACK_RECEIVED", "NEGATIVE_ACK_RECEIVED" }; + size_t sizeofArray = sizeof(ue_update_statusArray) / sizeof(ue_update_statusArray[0]); + if (ue_update_status < sizeofArray) + return (char *)ue_update_statusArray[ue_update_status]; + else + return (char *)"Unknown"; +} + +OpenAPI_ue_update_status_e OpenAPI_ue_update_status_FromString(char* ue_update_status) +{ + int stringToReturn = 0; + const char *ue_update_statusArray[] = { "NULL", "NOT_SENT", "SENT_NO_ACK_REQUIRED", "WAITING_FOR_ACK", "ACK_RECEIVED", "NEGATIVE_ACK_RECEIVED" }; + size_t sizeofArray = sizeof(ue_update_statusArray) / sizeof(ue_update_statusArray[0]); + while (stringToReturn < sizeofArray) { + if (strcmp(ue_update_status, ue_update_statusArray[stringToReturn]) == 0) { + return stringToReturn; + } + stringToReturn++; + } + return 0; +} + diff --git a/pool/shard004/C/0098921_simplerdc.c b/pool/shard004/C/0098921_simplerdc.c new file mode 100644 index 0000000000000000000000000000000000000000..9faeda10dea2f4699763781427b44d524ea5cc67 --- /dev/null +++ b/pool/shard004/C/0098921_simplerdc.c @@ -0,0 +1,289 @@ +/* + * Copyright (c) 2016 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 + +#include "contiki/mac/mac-sequence.h" +#include "contiki/packetbuf.h" +#include "contiki/queuebuf.h" +#include "contiki/netstack.h" +#include "contiki/llsec/anti-replay.h" +#include + +#ifdef CONFIG_NETWORK_IP_STACK_DEBUG_15_4_MAC +#define DEBUG 1 +#endif +#include "contiki/ip/uip-debug.h" + +#ifndef SIMPLERDC_MAX_RETRANSMISSIONS +#define SIMPLERDC_MAX_RETRANSMISSIONS 3 +#endif + +#define ACK_LEN 3 + +static struct nano_sem ack_lock; +static bool ack_received; + +static inline bool handle_ack_packet(struct net_buf *buf) +{ + if (packetbuf_datalen(buf) == ACK_LEN) { + ack_received = true; + nano_sem_give(&ack_lock); +#ifdef SIMPLERDC_802154_AUTOACK + PRINTF("simplerdc: ignore ACK packet\n"); + return true; +#endif + } + + return false; +} + +#ifdef SIMPLERDC_802154_AUTOACK +static inline bool check_duplicate(struct net_buf *buf) +{ + if (mac_sequence_is_duplicate(buf) != 0) { + PRINTF("simplerdc: duplicated packet seq %u\n", + packetbuf_attr(buf, PACKETBUF_ATTR_MAC_SEQNO)); + return true; + } + + mac_sequence_register_seqno(buf); + + return false; +} +#else +#define check_duplicate(...) (false) +#endif + +#ifdef SIMPLERDC_802154_SEND_ACK +#include "contiki/mac/frame802154.h" + +static inline bool send_ack_packet(struct net_buf *buf, uint8_t *status) +{ + struct net_buf *ack_buf; + frame802154_t frame; + + if (packetbuf_attr(buf, PACKETBUF_ATTR_FRAME_TYPE) != + FRAME802154_DATAFRAME) { + return false; + } + + frame802154_parse(packetbuf_dataptr(buf), + packetbuf_datalen(buf), + &frame); + + if (frame.fcf.ack_required == 0 || + !linkaddr_cmp((linkaddr_t *)&frame.dest_addr, + &linkaddr_node_addr)) { + return false; + } + + ack_buf = l2_buf_get_reserve(0); + if (!ack_buf) { + *status = MAC_TX_ERR; + return false; + } + + uip_pkt_packetbuf(ack_buf)[0] = FRAME802154_ACKFRAME; + uip_pkt_packetbuf(ack_buf)[1] = 0; + uip_pkt_packetbuf(ack_buf)[2] = frame.seq; + + *status = NETSTACK_RADIO.send(ack_buf, NULL, ACK_LEN); + + l2_buf_unref(ack_buf); + + PRINTF("simplerdc: Send ACK to packet %u\n", + packetbuf_attr(buf, PACKETBUF_ATTR_MAC_SEQNO)); + + return true; +} +#else +#define send_ack_packet(...) (false) +#endif + +static inline bool prepare_for_ack(struct net_buf *buf) +{ + if (packetbuf_attr(buf, PACKETBUF_ATTR_MAC_ACK) != 0) { + PRINTF("simplerdc: ACK requested\n"); + + nano_sem_init(&ack_lock); + ack_received = false; + + return true; + } + + return false; +} + +static inline uint8_t wait_for_ack(bool broadcast, bool ack_required) +{ + if (broadcast || !ack_required) { + return MAC_TX_OK; + } + + if (nano_sem_take(&ack_lock, MSEC(10)) == 0) { + nano_sem_init(&ack_lock); + } + + if (!ack_received) { + return MAC_TX_NOACK; + } + + return MAC_TX_OK; +} + +static inline uint8_t prepare_packet(struct net_buf *buf) +{ + uint8_t retries; + + retries = packetbuf_attr(buf, PACKETBUF_ATTR_MAX_MAC_TRANSMISSIONS); + if (retries <= 0) { + retries = SIMPLERDC_MAX_RETRANSMISSIONS + 1; + } + + packetbuf_set_addr(buf, PACKETBUF_ADDR_SENDER, &linkaddr_node_addr); + + if (NETSTACK_FRAMER.create_and_secure(buf) < 0) { + return 0; + } + + return retries; +} + +static void init(void) +{ + NETSTACK_RADIO.on(); +} + +static uint8_t send_packet(struct net_buf *buf, + mac_callback_t sent_callback, void *ptr) +{ + bool is_broadcast, ack_required; + uint8_t attempts; + uint8_t retries; + int ret; + +#ifdef SIMPLERDC_802154_ACK_REQ + packetbuf_set_attr(buf, PACKETBUF_ATTR_MAC_ACK, 1); +#endif + + retries = prepare_packet(buf); + if (!retries) { + return MAC_TX_ERR_FATAL; + } + + ack_required = prepare_for_ack(buf); + is_broadcast = !!packetbuf_holds_broadcast(buf); + attempts = 0; + + while (retries) { + attempts++; + retries--; + + ret = NETSTACK_RADIO.transmit(buf, packetbuf_totlen(buf)); + if (ret == RADIO_TX_COLLISION) { + continue; + } + + ret = wait_for_ack(is_broadcast, ack_required); + if (ret == MAC_TX_OK) { + break; + } + } + + mac_call_sent_callback(buf, sent_callback, ptr, ret, attempts); + + if (ret == MAC_TX_OK) { + return 1; + } + + return 0; +} + +static uint8_t send_packet_list(struct net_buf *buf, + mac_callback_t sent_callback, + void *ptr, struct rdc_buf_list *list) +{ + while (list) { + struct rdc_buf_list *next = list->next; + int last_sent_ok; + + queuebuf_to_packetbuf(buf, list->buf); + + last_sent_ok = send_packet(buf, sent_callback, ptr); + if (!last_sent_ok) { + return 0; + } + + list = next; + } + + return 1; +} + +static uint8_t input_packet(struct net_buf *buf) +{ + uint8_t ret = 0; + bool duplicate; + + if (handle_ack_packet(buf)) { + return 0; + } + + if (NETSTACK_FRAMER.parse(buf) < 0) { + PRINTF("simpledc: parsing failed msg len %u\n", + packetbuf_datalen(buf)); + return 0; + } + + duplicate = check_duplicate(buf); + + if (send_ack_packet(buf, &ret)) { + return ret; + } + + if (duplicate) { + return 0; + } + + return NETSTACK_MAC.input(buf); +} + +static int on(void) +{ + return NETSTACK_RADIO.on(); +} + +static int off(int keep_radio_on) +{ + return NETSTACK_RADIO.off(); +} + +static unsigned short channel_check_interval(void) +{ + return 0; +} + +const struct rdc_driver simplerdc_driver = { + "simplerdc", + init, + send_packet, + send_packet_list, + input_packet, + on, + off, + channel_check_interval, +}; diff --git a/pool/shard004/C/0098928_get_address.c b/pool/shard004/C/0098928_get_address.c new file mode 100644 index 0000000000000000000000000000000000000000..9e47fbb3ad91c191f17a735048486a72efb63d1f --- /dev/null +++ b/pool/shard004/C/0098928_get_address.c @@ -0,0 +1,203 @@ +/* + * get_address.c + * + * Get the effective address from an FPU instruction. + * + * + * Copyright (C) 1992,1993,1994 + * W. Metzenthen, 22 Parker St, Ormond, Vic 3163, + * Australia. E-mail billm@vaxc.cc.monash.edu.au + * All rights reserved. + * + * This copyright notice covers the redistribution and use of the + * FPU emulator developed by W. Metzenthen. It covers only its use + * in the 386BSD, FreeBSD and NetBSD operating systems. Any other + * use is not permitted under this copyright. + * + * 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 include information specifying + * that source code for the emulator is freely available and include + * either: + * a) an offer to provide the source code for a nominal distribution + * fee, or + * b) list at least two alternative methods whereby the source + * can be obtained, e.g. a publically accessible bulletin board + * and an anonymous ftp site from which the software can be + * downloaded. + * 3. All advertising materials specifically mentioning features or use of + * this emulator must acknowledge that it was developed by W. Metzenthen. + * 4. The name of W. Metzenthen may not be used to endorse or promote + * products derived from this software without specific prior written + * permission. + * + * 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 + * W. METZENTHEN 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 purpose of this copyright, based upon the Berkeley copyright, is to + * ensure that the covered software remains freely available to everyone. + * + * The software (with necessary differences) is also available, but under + * the terms of the GNU copyleft, for the Linux operating system and for + * the djgpp ms-dos extender. + * + * W. Metzenthen June 1994. + * + * + * $Id: get_address.c,v 1.4 1996/09/10 08:23:45 bde Exp $ + * + */ + +/*---------------------------------------------------------------------------+ + | Note: | + | The file contains code which accesses user memory. | + | Emulator static data may change when user memory is accessed, due to | + | other processes using the emulator while swapping is in progress. | + +---------------------------------------------------------------------------*/ + +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +static int reg_offset[] = { +tEAX, tECX, tEDX, tEBX, tESP, tEBP, tESI, tEDI}; +#define REG_(x) (*(((int*)FPU_info) + reg_offset[(x)])) + +void *FPU_data_address; + + +/* Decode the SIB byte. This function assumes mod != 0 */ +static void * +sib(int mod) +{ + unsigned char ss, index, base; + long offset; + + REENTRANT_CHECK(OFF); + base = fubyte((char *) FPU_EIP); /* The SIB byte */ + REENTRANT_CHECK(ON); + FPU_EIP++; + ss = base >> 6; + index = (base >> 3) & 7; + base &= 7; + + if ((mod == 0) && (base == 5)) + offset = 0; /* No base register */ + else + offset = REG_(base); + + if (index == 4) { + /* No index register */ + /* A non-zero ss is illegal */ + if (ss) + EXCEPTION(EX_Invalid); + } else { + offset += (REG_(index)) << ss; + } + + if (mod == 1) { + /* 8 bit signed displacement */ + REENTRANT_CHECK(OFF); + offset += (signed char) fubyte((char *) FPU_EIP); + REENTRANT_CHECK(ON); + FPU_EIP++; + } else + if (mod == 2 || base == 5) { /* The second condition also + * has mod==0 */ + /* 32 bit displacment */ + REENTRANT_CHECK(OFF); + offset += (signed) fuword((unsigned long *) FPU_EIP); + REENTRANT_CHECK(ON); + FPU_EIP += 4; + } + return (void *) offset; +} + + +/* + MOD R/M byte: MOD == 3 has a special use for the FPU + SIB byte used iff R/M = 100b + + 7 6 5 4 3 2 1 0 + ..... ......... ......... + MOD OPCODE(2) R/M + + + SIB byte + + 7 6 5 4 3 2 1 0 + ..... ......... ......... + SS INDEX BASE + +*/ + +void +get_address(unsigned char FPU_modrm) +{ + unsigned char mod; + long *cpu_reg_ptr; + int offset = 0; /* Initialized just to stop compiler warnings. */ + + mod = (FPU_modrm >> 6) & 3; + + if (FPU_rm == 4 && mod != 3) { + FPU_data_address = sib(mod); + return; + } + cpu_reg_ptr = (long *) ®_(FPU_rm); + switch (mod) { + case 0: + if (FPU_rm == 5) { + /* Special case: disp32 */ + REENTRANT_CHECK(OFF); + offset = fuword((unsigned long *) FPU_EIP); + REENTRANT_CHECK(ON); + FPU_EIP += 4; + FPU_data_address = (void *) offset; + return; + } else { + FPU_data_address = (void *) *cpu_reg_ptr; /* Just return the + * contents of the cpu + * register */ + return; + } + case 1: + /* 8 bit signed displacement */ + REENTRANT_CHECK(OFF); + offset = (signed char) fubyte((char *) FPU_EIP); + REENTRANT_CHECK(ON); + FPU_EIP++; + break; + case 2: + /* 32 bit displacement */ + REENTRANT_CHECK(OFF); + offset = (signed) fuword((unsigned long *) FPU_EIP); + REENTRANT_CHECK(ON); + FPU_EIP += 4; + break; + case 3: + /* Not legal for the FPU */ + EXCEPTION(EX_Invalid); + } + + FPU_data_address = offset + (char *) *cpu_reg_ptr; +} diff --git a/pool/shard004/C/0098931_diagnose.c b/pool/shard004/C/0098931_diagnose.c new file mode 100644 index 0000000000000000000000000000000000000000..d5c5e90d493e7c05bd15e5e26c218538d0bb3c2d --- /dev/null +++ b/pool/shard004/C/0098931_diagnose.c @@ -0,0 +1,84 @@ +/* + Unix SMB/CIFS implementation. + diagnosis tools for web admin + Copyright (C) Andrew Tridgell 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 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 "web/swat_proto.h" +#include "lib/winbind_util.h" +#include "libsmb/libsmb.h" + +#ifdef WITH_WINBIND + +/* check to see if winbind is running by pinging it */ + +bool winbindd_running(void) +{ + return winbind_ping(); +} +#endif + +/* check to see if nmbd is running on localhost by looking for a __SAMBA__ + response */ +bool nmbd_running(void) +{ + struct in_addr loopback_ip; + int count; + struct sockaddr_storage *ss_list; + struct sockaddr_storage ss; + NTSTATUS status; + + loopback_ip.s_addr = htonl(INADDR_LOOPBACK); + in_addr_to_sockaddr_storage(&ss, loopback_ip); + + status = name_query("__SAMBA__", 0, + True, True, &ss, + talloc_tos(), &ss_list, &count, + NULL); + if (NT_STATUS_IS_OK(status)) { + TALLOC_FREE(ss_list); + return True; + } + + return False; +} + + +/* check to see if smbd is running on localhost by trying to open a connection + then closing it */ +bool smbd_running(void) +{ + struct in_addr loopback_ip; + NTSTATUS status; + struct cli_state *cli; + struct sockaddr_storage ss; + + loopback_ip.s_addr = htonl(INADDR_LOOPBACK); + in_addr_to_sockaddr_storage(&ss, loopback_ip); + + if ((cli = cli_initialise()) == NULL) + return False; + + status = cli_connect(cli, global_myname(), &ss); + if (!NT_STATUS_IS_OK(status)) { + cli_shutdown(cli); + return False; + } + + cli_shutdown(cli); + return True; +} diff --git a/pool/shard004/C/0098932_cuda_dynamic.c b/pool/shard004/C/0098932_cuda_dynamic.c new file mode 100644 index 0000000000000000000000000000000000000000..1135a1f077a14e24dc9eafc1ce27faf97a2fba05 --- /dev/null +++ b/pool/shard004/C/0098932_cuda_dynamic.c @@ -0,0 +1,63 @@ +/* + * 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 "cuda_dynamic.h" + +#include + +#if defined(_WIN32) +# include +# define dlopen(filename, flags) LoadLibrary(TEXT(filename)) +# define dlsym(handle, symbol) (void *)GetProcAddress(handle, symbol) +# define dlclose(handle) FreeLibrary(handle) +#else +# include +#endif + +#if defined(_WIN32) || defined(__CYGWIN__) +# define CUDA_LIBNAME "nvcuda.dll" +#else +# define CUDA_LIBNAME "libcuda.so.1" +#endif + +#define CUDA_DECL(NAME, TYPE) \ + TYPE *mpv_ ## NAME; +CUDA_FNS(CUDA_DECL) + +static bool cuda_loaded = false; +static pthread_once_t cuda_load_once = PTHREAD_ONCE_INIT; + +static void cuda_do_load(void) +{ + void *lib = dlopen(CUDA_LIBNAME, RTLD_LAZY); + if (!lib) { + return; + } + +#define CUDA_LOAD_SYMBOL(NAME, TYPE) \ + mpv_ ## NAME = dlsym(lib, #NAME); if (!mpv_ ## NAME) return; + + CUDA_FNS(CUDA_LOAD_SYMBOL) + + cuda_loaded = true; +} + +bool cuda_load(void) +{ + pthread_once(&cuda_load_once, cuda_do_load); + return cuda_loaded; +} diff --git a/pool/shard004/C/0098933_winrandom.c b/pool/shard004/C/0098933_winrandom.c new file mode 100644 index 0000000000000000000000000000000000000000..54d8d58e5d32717ce802acc26207d776f7b4fa4f --- /dev/null +++ b/pool/shard004/C/0098933_winrandom.c @@ -0,0 +1,43 @@ +#include +#include + +#define NCP ((HCRYPTPROV) 0) + +HCRYPTPROV hProvider = NCP; + +void randombytes(unsigned char *x,unsigned long long xlen) +{ + unsigned i; + BOOL ret; + + if (hProvider == NCP) { + for(;;) { + ret = CryptAcquireContext(&hProvider, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT | CRYPT_SILENT); + if (ret != FALSE) break; + Sleep(1); + } + } + + while (xlen > 0) { + if (xlen < 1048576) i = (unsigned) xlen; else i = 1048576; + + ret = CryptGenRandom(hProvider, i, x); + if (ret == FALSE) { + Sleep(1); + continue; + } + + x += i; + xlen -= i; + } +} + +int randombytes_close(void) +{ + int rc = -1; + if((hProvider != NCP) && (CryptReleaseContext(hProvider, 0) != FALSE)) { + hProvider = NCP; + rc = 0; + } + return rc; +} diff --git a/pool/shard004/C/0098935_misc.c b/pool/shard004/C/0098935_misc.c new file mode 100644 index 0000000000000000000000000000000000000000..84ca0f451eeb5527d219399e584e7eecbf9c3fbb --- /dev/null +++ b/pool/shard004/C/0098935_misc.c @@ -0,0 +1,68 @@ +/* + * Copyright (c) 2011-2017, Shawn Webb + * 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 +#include +#include + +#include +#include + +#include "hijack.h" + +void * +_hijack_malloc(HIJACK *hijack, size_t sz) +{ + void *p; + int err; + + err = ERROR_NONE; + p = malloc(sz); + + if ((p)) + memset(p, 0x00, sz); + else + err = ERROR_SYSCALL; + + SetError(hijack, err); + + return (p); +} + +void +_hijack_free(HIJACK *hijack, void *p, size_t sz) +{ + + if (!(p)) + return; + + memset(p, 0x00, sz); + free(p); +} diff --git a/pool/shard004/C/0098938_gw_rm_job_status.c b/pool/shard004/C/0098938_gw_rm_job_status.c new file mode 100644 index 0000000000000000000000000000000000000000..75a89753868e51f94afcd6bc716dfdf1bdb43dc0 --- /dev/null +++ b/pool/shard004/C/0098938_gw_rm_job_status.c @@ -0,0 +1,150 @@ +/* -------------------------------------------------------------------------- */ +/* Copyright 2002-2013, GridWay Project Leads (GridWay.org) */ +/* */ +/* 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 "gw_rm.h" +#include "gw_rm_msg.h" +#include "gw_log.h" +#include "gw_job_pool.h" + +/* ------------------------------------------------------------------------- */ +/* ------------------------------------------------------------------------- */ +/* ------------------------------------------------------------------------- */ + +void gw_rm_job_status(int client_socket, int job_id) +{ + gw_job_t * job; + gw_msg_job_t msg; + int rc; + int length; + gw_history_t * tmp; + + job = gw_job_pool_get(job_id, GW_TRUE); + length = sizeof(gw_msg_job_t); + msg.msg_type = GW_MSG_JOB_STATUS; + + if ( job == NULL ) + { + msg.rc = GW_RC_FAILED_BAD_JOB_ID; + msg.id = job_id; + rc = send(client_socket,(void *) &msg,length,0); + return; + } + + if ( job->owner != NULL ) + strncpy(msg.owner, job->owner,GW_MSG_STRING_SHORT); + + msg.rc = GW_RC_SUCCESS; + + msg.id = job->id; + msg.array_id = job->array_id; + msg.task_id = job->task_id; + msg.total_tasks = job->total_tasks; + msg.uid = job->user_id; + + msg.fixed_priority = job->fixed_priority; + msg.deadline = job->template.deadline; + + msg.type = job->template.type; + msg.np = job->template.np; + + msg.em_state = job->em_state; + msg.job_state = job->job_state; + msg.exit_code = job->exit_code; + + msg.restarted = job->restarted; + msg.client_waiting = job->client_waiting; + msg.reschedule = job->reschedule; + + msg.start_time = job->start_time; + msg.exit_time = job->exit_time; + msg.cpu_time = gw_job_history_get_wrapper_time(job->history); + msg.xfr_time = gw_job_history_get_prolog_time(job->history) + + gw_job_history_get_epilog_time(job->history) + + gw_job_history_get_migration_time(job->history); + + /* Agregate stats from other hosts in history */ + if ( job->history != NULL ) + { + tmp = job->history->next; + while (tmp != NULL ) + { + msg.cpu_time += gw_job_history_get_wrapper_time(tmp); + msg.xfr_time += gw_job_history_get_prolog_time(tmp) + + gw_job_history_get_epilog_time(tmp) + + gw_job_history_get_migration_time(tmp); + tmp = tmp->next; + } + } + + if ( job->template.name != NULL ) + strncpy(msg.name,job->template.name,GW_MSG_STRING_SHORT); + + msg.host[0]='\0'; + if ( job->history != NULL ) + if (job->history->em_rc != NULL) + { + strncpy(msg.host,job->history->em_rc,GW_MSG_STRING_USER_AT_HOST); + if ( strlen(job->history->em_rc) >= GW_MSG_STRING_USER_AT_HOST ) + msg.host[GW_MSG_STRING_USER_AT_HOST-1] = '\0'; + } + + pthread_mutex_unlock(&(job->mutex)); + + rc = send(client_socket,(void *) &msg,length,0); + + if ( rc == -1 ) + gw_log_print("RM",'E',"Error sending message %s\n",strerror(errno)); +} + + +/* ------------------------------------------------------------------------- */ +/* ------------------------------------------------------------------------- */ +/* ------------------------------------------------------------------------- */ + +void gw_rm_job_pool_status(int client_socket) +{ + int job_id; + gw_job_t * job; + gw_msg_job_t msg; + int length; + int rc; + + length = sizeof(gw_msg_job_t); + + for ( job_id=0; job_id < gw_conf.number_of_jobs ; job_id++) + { + job = gw_job_pool_get(job_id, GW_FALSE); + + if (job != NULL) + gw_rm_job_status (client_socket, job_id); + } + + msg.msg_type = GW_MSG_END; + msg.rc = GW_RC_SUCCESS; + + rc = send(client_socket,(void *) &msg,length,0); + + if ( rc == -1 ) + gw_log_print("RM",'E',"Error sending message %s\n",strerror(errno)); +} diff --git a/pool/shard004/C/0098940_main.c b/pool/shard004/C/0098940_main.c new file mode 100644 index 0000000000000000000000000000000000000000..dfc81f2a1e462a6a9a06e22ede76e97cdb511d2e --- /dev/null +++ b/pool/shard004/C/0098940_main.c @@ -0,0 +1,243 @@ +/* + + multivpn - Multiprotocol VPN tool + + Copyright (C) 2004 Gorka Gorrotxategi - zgor; Jose Ignacio Sanchez Martin - Topo[LB] + + 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. + + --------- + + main.c: application entry point. + +*/ + + +#include +#include +#include +#include +#define _GNU_SOURCE +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + + +#include "globals.h" +#include "parser.h" +#include "plugin.h" +#include "tuntap.h" +#include "debug.h" + +void MainLoop(); + +void ShowVersion(void){ + printf("\n%s\n\n",PROGRAM_VERSION); + exit(0); +} + +void ShowBanner(void){ + printf("%s Multiprotocol VPN tool (%s).\n%s\n\n",PROGRAM_NAME, PROGRAM_VERSION, PROGRAM_AUTHOR); +} + +void UsageMsg(char *programName){ + ShowBanner(); + printf("Usage: %s [OPTIONS]... \n", programName); + printf(" Options:\n"); + printf(" --debug prints debug information\n"); + printf(" -c, --configfile use specified config file, Required\n"); + printf(" -h, --help display this help and exit\n"); + printf(" -V, --version output version information and exit\n"); + printf("\n"); + exit(1); +} + +void ShowHelp(void){ + char programName[2048]; + sprintf(programName,"%s %s",PROGRAM_NAME, PROGRAM_VERSION); + UsageMsg(programName); +} + + +int main(int argc, char **argv){ + //int optionSelected=1; + int opt; + + struct option long_options[]={ + {"version",0,NULL,'V'}, + {"help",0,NULL,'h'}, + {"debug",1,NULL,'d'}, + {"verbose",0,NULL,'v'}, + {"configfile",1,NULL,'c'}, + {NULL,0,NULL,0} + }; + int option_index=0; + + if (argc<1) + UsageMsg(argv[0]); + + Globals_Init(); + + + while ((opt = getopt_long(argc, argv,"c:Vvhd:", long_options, &option_index)) != EOF) { + switch (opt) { + case 'V': + ShowVersion(); + break; + case 'v': + global_v.verbose=1; + break; + case 'h': + ShowHelp(); + break; + case 'd': + if (!optarg || optarg[0]=='-') UsageMsg(argv[0]); + global_v.debug=atoi(optarg); + if (!global_v.debug) UsageMsg(argv[0]); + break; + case 'c': + if (!optarg || optarg[0]=='-') UsageMsg(argv[0]); + strncpy(global_v.configfile,optarg,200); + break; + + default: + printf("ERROR: unknown option.\n\n"); + UsageMsg(argv[0]); + } + } + if (!strncmp(global_v.configfile,"none",strlen("none"))) + UsageMsg(argv[0]); + ShowBanner(); + + debug(1,"Debug mode initialized"); + + debug(1,"Parsing Config File..."); + + if ( ParseConfigFile(global_v.configfile) ) + debug_error("Error Parsing Config File"); + else debug(1,"Succes Parsing Config File\n"); + + debug(1,"MAIN THREAD: Verifying Parameters"); + + if ( plugin_checkConfig(global_v) ) + { + debug_error("Error Checking Plugin Parameters"); + exit(-1); + } + else debug(1,"Success Checking Plugin Parameters"); + + debug(1,"MAIN THREAD: Building Plugin"); + if ( plugin_build() ) + { + debug_error("Failed Building Plugin, Exiting"); + exit(-1); + } + else debug(1,"Success Full Plugin Build"); + + debug(1,"Main Thread: Starting Plugin"); + plugin_start(); + debug(1,"Main Thread: Entering Main Loop"); + MainLoop(); + + debug(1,"Main Thread: Finishing the program..."); + + + return 0; +} + + +void MainLoop() +{ + int finish; + int nbytes; + int fdTun; + int maxFd; + char buffer[BLOCK_SIZE]; + fd_set setReading; + //int pluginReadSocket; + + fdTun=tun_getFile(); + if (fdTun>global_v.pipe_from_plugin[0]) + maxFd=fdTun+1; + else maxFd=global_v.pipe_from_plugin[0]+1; + + debug(1,"MAIN Thread: Enteryng loop"); + + finish=0; + while (!finish) + { + // Preparing FD set + //plugin_fillFDSET(&setReading); + FD_SET(global_v.pipe_from_plugin[0],&setReading); + FD_SET(fdTun,&setReading); + + // Now Blocking + debug(3,"MAIN THREAD: Select Blocked"); + select(maxFd,&setReading,NULL,NULL,NULL); + + // Now Processing correct file descriptor + debug(3,"MAIN THREAD: Select unblocked"); + + if (FD_ISSET(fdTun,&setReading)) + { + debug(3,"Main Thread: Message is from tundriver"); + nbytes=read(fdTun,buffer,BLOCK_SIZE-1); + if (nbytes<=0) + debug(3,"MAIN Thread: Failed Reading from tundriver"); + else + { + debug(3,"MAIN Thread: Read %d bytes from tundriver",nbytes); + nbytes=write(global_v.pipe_to_plugin[1],buffer,nbytes); + if (nbytes<=0) + debug(3,"MAIN Thread: Failed Writing to pipe"); + else debug(3,"MAIN Thread: Wrotten %d bytes to plugin",nbytes); + + } + } + else + if ( FD_ISSET(global_v.pipe_from_plugin[0],&setReading) ) + { + debug(3,"MAIN Thread: Message is from plugin socket"); + nbytes=read(global_v.pipe_from_plugin[0],buffer,BLOCK_SIZE); + if (nbytes<=0) + debug(3,"MAIN Thread: Failed Reading from pluginSocket"); + else + { + debug(3,"MAIN Thread: Read %d bytes from pluginSocket",nbytes); + nbytes=write(fdTun,buffer,nbytes); + if (nbytes<=0) + debug(3,"MAIN THread: Failed writting to tundriver"); + else debug(3,"MAIN Thread: Wrotten %d bytes to tundriver",nbytes); + + + } + + } + else debug(3,"Extrange select..."); + + FD_ZERO(&setReading); + + } + // + debug(1,"MAIN Thread: End loop"); +} diff --git a/pool/shard004/C/0098941_errorhandler.c b/pool/shard004/C/0098941_errorhandler.c new file mode 100644 index 0000000000000000000000000000000000000000..94b642d2c9ce4df5f3634d141407d22ddc6e43aa --- /dev/null +++ b/pool/shard004/C/0098941_errorhandler.c @@ -0,0 +1,55 @@ +#include "errorhandler.h" +#include "cpl_conv.h" +#include + + +static void error_handler(CPLErr, int, const char *); +static void destroy_stack (ErrorStack); + +// +// Public interface +// + +void push_error_handler(ErrorStack stack) +{ + CPLPushErrorHandlerEx(error_handler, (void*)stack); +} + +void pop_error_handler(ErrorStack stack) +{ + CPLPopErrorHandler(); + destroy_stack(stack); +} + + +// +// Internal implementation +// + + +static void error_handler(CPLErr errClass, int errNo, const char *msg) +{ + ErrorStack stack = CPLGetErrorHandlerUserData(); + assert(stack); + ErrorCell cell = CPLMalloc(sizeof(struct error_cell)); + cell->errClass = errClass; + cell->errNo = errNo; + cell->msg = strdup(msg); + cell->next = *stack; + *stack = cell; +} + +static void destroy_stack (ErrorStack stack) +{ + assert(stack); + ErrorCell cur = *stack; + while (cur) { + ErrorCell next = cur->next; + if (cur) { + free(cur->msg); + free(cur); + } + cur = next; + } + *stack = NULL; +} diff --git a/pool/shard004/C/0098944_gsa.c b/pool/shard004/C/0098944_gsa.c new file mode 100644 index 0000000000000000000000000000000000000000..74efaffd291061c6d22ab7c910131372029c0982 --- /dev/null +++ b/pool/shard004/C/0098944_gsa.c @@ -0,0 +1,161 @@ +/* + * gsa.c - generator and parser of GSA message + * + * Copyright (C) 2012 I. S. Gorbunov + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +#include +#include + +#include +#include +#include +#include +#include + +#ifdef _MSC_VER + #include "win32/win32navi.h" +#endif // MSVC_VER + +// +// Initializes GSA sentence structure with default values +navierr_status_t navi_init_gsa(struct gsa_t *msg) +{ + size_t i; + + assert(msg != NULL); + + msg->swmode = navi_gsa_NULL; + msg->fixmode = -1; + for (i = 0; i < GSA_MAX_SATELLITES; i++) + msg->satellites[i] = -1; + navi_init_number(&msg->pdop); + navi_init_number(&msg->hdop); + navi_init_number(&msg->vdop); + + return navi_Ok; +} + +#ifndef NO_GENERATOR + +// +// Creates GSA message +navierr_status_t navi_create_gsa(const struct gsa_t *msg, char *buffer, size_t maxsize, size_t *nmwritten) +{ + size_t msglength, i; + + const char *swmode; + char bytes[2]; + char fixmode[2], satellites[12][4], pdop[16], hdop[16], vdop[16]; + + msglength = strlen(swmode = navi_gsamode_str(msg->swmode)); + + (void)navi_split_integer(msg->fixmode, bytes, 1, 10); + msglength += navi_print_decfield(bytes, msg->fixmode == -1 ? 0 : 1, + fixmode, sizeof(fixmode)); + + for (i = 0; i < GSA_MAX_SATELLITES; i++) + { + (void)navi_split_integer(msg->satellites[i], bytes, 2, 10); + msglength += navi_print_decfield(bytes, msg->satellites[i] == -1 ? 0 : 2, + satellites[i], sizeof(satellites[i])); + } + + msglength += navi_print_number(msg->pdop, pdop, sizeof(pdop)); + msglength += navi_print_number(msg->hdop, hdop, sizeof(hdop)); + msglength += navi_print_number(msg->vdop, vdop, sizeof(vdop)); + + if (msglength > maxsize) + { + navierr_set_last(navi_NotEnoughBuffer); + return navi_Error; + } + + *nmwritten = snprintf(buffer, maxsize, "%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s", + swmode, fixmode, satellites[0], satellites[1], satellites[2], satellites[3], + satellites[4], satellites[5], satellites[6], satellites[7], satellites[8], + satellites[9], satellites[10], satellites[11], pdop, hdop, vdop); + + return navi_Ok; +} + +#endif // NO_GENERATOR + +#ifndef NO_PARSER + +// +// Parses GSA message +navierr_status_t navi_parse_gsa(struct gsa_t *msg, char *buffer) +{ + size_t i = 0, j, nmread; + char bytes[2]; + + if (navi_parse_gsamode(buffer + i, &msg->swmode, &nmread) != 0) + { + if (navierr_get_last()->errclass != navi_NullField) + return navi_Error; + } + i += nmread; + + if (navi_parse_decfield(buffer + i, 1, bytes, &nmread) != 0) + { + if (navierr_get_last()->errclass != navi_NullField) + return navi_Error; + } + else + { + msg->fixmode = navi_compose_integer(bytes, 1, 10); + } + i += nmread; + + for (j = 0; j < GSA_MAX_SATELLITES; j++) + { + if (navi_parse_decfield(buffer + i, 2, bytes, &nmread) != 0) + { + if (navierr_get_last()->errclass != navi_NullField) + return navi_Error; + } + else + { + msg->satellites[j] = navi_compose_integer(bytes, 2, 10); + } + i += nmread; + } + + if (navi_parse_number(buffer + i, &msg->pdop, &nmread) != 0) + { + if (navierr_get_last()->errclass != navi_NullField) + return navi_Error; + } + i += nmread; + + if (navi_parse_number(buffer + i, &msg->hdop, &nmread) != 0) + { + if (navierr_get_last()->errclass != navi_NullField) + return navi_Error; + } + i += nmread; + + if (navi_parse_number(buffer + i, &msg->vdop, &nmread) != 0) + { + if (navierr_get_last()->errclass != navi_NullField) + return navi_Error; + } + + return navi_Ok; +} + +#endif // NO_PARSER diff --git a/pool/shard004/C/0098946_chpl-string-support.c b/pool/shard004/C/0098946_chpl-string-support.c new file mode 100644 index 0000000000000000000000000000000000000000..5c463cba4abf1574e4ab7555ba4ae80ff8a42c19 --- /dev/null +++ b/pool/shard004/C/0098946_chpl-string-support.c @@ -0,0 +1,209 @@ +/* + * Copyright 2004-2015 Cray Inc. + * Other additional copyright holders may be indicated within. + * + * The entirety of this work is 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. + */ + +/* + * chpl-string-support.c + * + * This file provides utility functions for C strings (char *) and is + * used by the runtime, the Chapel generated code, as well as the + * launcher. + * + * Note that the naming here is not ideal and is a byproduct of when + * we used Chapel strings (chpl_string) and C strings (c_string) + * interchangeably. When the Chapel string implementation is actually + * different than the runtime type c_string, we should go back and + * considering naming things more consistently. + * + */ +#include +#include "chplrt.h" +#include "sys_basic.h" +#include "chpl-mem.h" +#include "chpl-mem-desc.h" +#include "chpltypes.h" +#include "error.h" + +// Uses the system allocator. Should not be used to create user-visible data +// (error messages are OK). +char* chpl_glom_strings(int numstrings, ...) { + va_list ap; + int i, len; + char* str; + + va_start(ap, numstrings); + len = 0; + for (i=0; i= sizeof(z)) + chpl_error("overflow encountered in format", 0, 0); + va_end(ap); + return string_copy(z, 0, 0); +} + + +// +// We need an allocator for the rest of the code, but for the user +// program it needs to be a locale-aware one with tracking, while for +// the launcher the regular system one will do. +// +static inline void* +chpltypes_malloc(size_t size, chpl_mem_descInt_t description, + int32_t lineno, c_string filename) { +#ifndef LAUNCHER + return chpl_mem_alloc(size, description, lineno, filename); +#else + return malloc(size); +#endif +} + + +c_string_copy +string_copy(c_string x, int32_t lineno, c_string filename) +{ + char *z; + + // If the input string is null, just return null. + if (x == NULL) + return NULL; + + z = (char*)chpltypes_malloc(strlen(x)+1, CHPL_RT_MD_STR_COPY_DATA, + lineno, filename); + return strcpy(z, x); +} + +// string_concat always returns a newly-allocated c_string (or NULL). +c_string_copy +string_concat(c_string x, c_string y, int32_t lineno, c_string filename) { + char* z; + size_t xlen; + size_t ylen; + + if (x == NULL) + return string_copy(y, lineno, filename); + if (y == NULL) + return string_copy(x, lineno, filename); + + xlen = strlen(x); + ylen = strlen(y); + + z = (char*)chpltypes_malloc(xlen + ylen + 1, + CHPL_RT_MD_STR_CONCAT_DATA, + lineno, filename); + + // memcpy can be more efficient than the str??? functions because it does not + // look for terminating NUL characters. We are guaranteed that the source + // and destination strings do not overlap so we don't need the (very slight) + // extra complexity of memmove. + memcpy(z, x, xlen); + // Using "ylen+1" copies the terminating NUL from the second string. + memcpy(z + xlen, y, ylen+1); + + return z; +} + +// Returns the index of the first occurrence of a substring within a string, or +// 0 if the substring is not in the string. +int string_index_of(c_string haystack, c_string needle) { + c_string substring = strstr(haystack, needle); + return substring ? (int) (substring-haystack)+1 : 0; +} + +// Returns a newly-allocated string containing (a copy of) the bytes selected +// from the original string. +// It is up to the caller to make sure low and high are within the string +// bounds and that stride is not 0. +c_string_copy +string_select(c_string x, int low, int high, int stride, int32_t lineno, c_string filename) { + char* result = NULL; + char* dst = NULL; + int size; + c_string src; + + if (low < 1) low = 1; + if (high < low) return NULL; + + size = high - low + 1; + result = chpltypes_malloc(size + 1, CHPL_RT_MD_STR_SELECT_DATA, + lineno, filename); + src = stride > 0 ? x + low - 1 : x + high - 1; + dst = result; + if (stride == 1) { + memcpy(result, src, size); + dst = result + size; + } else if (stride > 0) { + while (src - x <= high - 1) { + *dst++ = *src; + src += stride; + } + } else { + while (src - x >= low - 1) { + *dst++ = *src; + src += stride; + } + } + + *dst = '\0'; + return result; +} + +// Returns a string containing the character at the given index of the input +// string, or an empty string if the index is out of bounds. +c_string_copy +string_index(c_string x, int i, int32_t lineno, c_string filename) { + char* buffer; + if (i-1 < 0 || i-1 >= string_length(x)) + { + return NULL; + } + buffer = chpltypes_malloc(2, CHPL_RT_MD_STR_COPY_DATA, + lineno, filename); + sprintf(buffer, "%c", x[i-1]); + return buffer; +} + + +chpl_bool +string_contains(c_string x, c_string y) { + if (strstr(x, y)) + return true; + else + return false; +} + + diff --git a/pool/shard004/C/0098947_mountmodule.c b/pool/shard004/C/0098947_mountmodule.c new file mode 100644 index 0000000000000000000000000000000000000000..c743bd2d8419b1ce043d19f8e2bc6c22467ee291 --- /dev/null +++ b/pool/shard004/C/0098947_mountmodule.c @@ -0,0 +1,229 @@ +/* The MIT License + * + * Copyright (C) 2009 Erick Tryzelaar + * + * + * 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. + */ + +/* The psi.mount module */ + + +#include + +#include "psi.h" +#include "mount.h" + + +/* Declarations (we need these since we use -Wmissing-declarations) */ +#ifdef PY3K +PyMODINIT_FUNC PyInit_mount(void); +#else +PyMODINIT_FUNC initmount(void); +#endif + + +/* Re-declare these as non-extern since we're providing the symbols */ +PyObject *PsiExc_AttrNotAvailableError = NULL; +PyObject *PsiExc_AttrInsufficientPrivsError = NULL; +PyObject *PsiExc_AttrNotImplementedError = NULL; + + +/* More contstants */ +static char MODULE_NAME[] = "psi.mount"; +PyDoc_STRVAR(MODULE_DOC, "Module for system mount information"); + + +PyDoc_STRVAR(psi_mount_mounts__doc, "\ +mounts(remote=False) -> iterator\n\ +\n\ +Return an iterator containing ojects representing mounted filesystems. The\n\ +remote argument is a boolean value that can be used to control if remote\n\ +filesystems should be included or not. Remote filesystems might take longer\n\ +to be created or suffer from timeouts collecting information from them.\n\ +"); +static PyObject * +psi_mount_mounts(PyObject *self, PyObject *args, PyObject *kwds) +{ + static char *kwlist[] = {"remote", NULL}; + psi_mountlist_t *mountlist; + PyObject *mount; + PyObject *list; + PyObject *iter; + ssize_t i; + int remote = 0; + + if (!PyArg_ParseTupleAndKeywords(args, kwds, "|i", kwlist, &remote)) + return NULL; + mountlist = psi_arch_mountlist(remote); + if (mountlist == NULL) + return NULL; + list = PyList_New(mountlist->count); + if (list == NULL) + return psi_free_mountlist(mountlist); + for (i = 0; i < mountlist->count; ++i) { + mount = PsiMount_New(mountlist->mounts[i]); + if (mount == NULL) { + Py_DECREF(list); + return psi_free_mountlist(mountlist); + } + PyList_SET_ITEM(list, i, mount); + + /* Python now owns the mountinfo, so clear it from the list. */ + mountlist->mounts[i] = NULL; + } + psi_free_mountlist(mountlist); + iter = PySeqIter_New(list); + Py_DECREF(list); + return iter; +} + + +/** Finalise the types + * + * Calls PyType_Ready() and does anything else required. + */ +static int +prepare_types(void) +{ + if (PyType_Ready(&MountBase_Type) < 0) + return -1; + if (PyType_Ready(&LocalMount_Type) < 0) + return -1; + if (PyType_Ready(&RemoteMount_Type) < 0) + return -1; + Py_INCREF(&MountBase_Type); + Py_INCREF(&LocalMount_Type); + Py_INCREF(&RemoteMount_Type); + return 0; +} + + +/** Initialise the global exceptions + * + * If this function fails the modinit function will Py_XDECREF the exceptions, + * so no need to do that here. + */ +static int +init_exceptions(void) +{ + PyObject *_psimod; + + _psimod = PyImport_ImportModule("psi._psi"); + if (_psimod == NULL) + return -1; + PsiExc_AttrNotAvailableError = PyObject_GetAttrString( + _psimod, "AttrNotAvailableError"); + if (PsiExc_AttrNotAvailableError == NULL) + goto error; + PsiExc_AttrInsufficientPrivsError = PyObject_GetAttrString( + _psimod, "AttrInsufficientPrivsError"); + if (PsiExc_AttrInsufficientPrivsError == NULL) + goto error; + PsiExc_AttrNotImplementedError = PyObject_GetAttrString( + _psimod, "AttrNotImplementedError"); + if (PsiExc_AttrNotImplementedError == NULL) + goto error; + Py_DECREF(_psimod); + return 0; + + error: + Py_DECREF(_psimod); + return -1; +} + + +/* Add all the objects to the module */ +static int +add_module_objects(PyObject *mod) +{ + if (PyModule_AddObject(mod, "MountBase", (PyObject *)&MountBase_Type) < 0) + return -1; + if (PyModule_AddObject(mod, "LocalMount", (PyObject *)&LocalMount_Type) < 0) + return -1; + if (PyModule_AddObject(mod, "RemoteMount", (PyObject *)&RemoteMount_Type) < 0) + return -1; + return 0; +} + + +static PyMethodDef mount_methods[] = { + {"mounts", (PyCFunction)psi_mount_mounts, METH_VARARGS | METH_KEYWORDS, + psi_mount_mounts__doc}, + {NULL, NULL, 0, NULL} /* Sentinel */ +}; + + +#ifdef PY3K +static struct PyModuleDef moduledef = { + PyModuleDef_HEAD_INIT, /* m_base */ + MODULE_NAME, /* m_name */ + MODULE_DOC, /* m_doc */ + -1, /* m_size */ + mount_methods, /* m_methods */ + NULL, /* m_reload */ + NULL, /* m_traverse */ + NULL, /* m_clear */ + NULL /* m_free */ +}; +#endif + + +/* Some defines to make the module init function readable */ +#ifdef PY3K +#define MODFUNC PyInit_mount +#define RETURN(VAR) return VAR +#else +#define MODFUNC initmount +#define RETURN(VAR) return +#endif + + +/* Returns the psi.mount module */ +PyMODINIT_FUNC +MODFUNC(void) +{ + PyObject *mod = NULL; + + if (prepare_types() < 0) + RETURN(NULL); + if (init_exceptions() < 0) + goto error; +#ifdef PY3K + mod = PyModule_Create(&moduledef); +#else + mod = Py_InitModule3(MODULE_NAME, mount_methods, MODULE_DOC); +#endif + if (mod == NULL) + goto error; + if (add_module_objects(mod) < 0) + goto error; + PyErr_WarnEx(PyExc_FutureWarning, "Experimental API", 1); + RETURN(mod); + +error: + Py_XDECREF(mod); + Py_XDECREF(PsiExc_AttrNotAvailableError); + Py_XDECREF(PsiExc_AttrInsufficientPrivsError); + Py_XDECREF(PsiExc_AttrNotImplementedError); + Py_XDECREF(&MountBase_Type); + Py_XDECREF(&LocalMount_Type); + Py_XDECREF(&RemoteMount_Type); + RETURN(NULL); +} diff --git a/pool/shard004/C/0098956_cdiv_qr.c b/pool/shard004/C/0098956_cdiv_qr.c new file mode 100644 index 0000000000000000000000000000000000000000..bf40381d11f0dba74039102a6f774b03d7e4bb2b --- /dev/null +++ b/pool/shard004/C/0098956_cdiv_qr.c @@ -0,0 +1,56 @@ +/* mpz_cdiv_qr -- Division rounding the quotient towards +infinity. The + remainder gets the opposite sign as the denominator. + +Copyright 1994, 1995, 1996, 2000, 2001, 2005 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 "gmp.h" +#include "gmp-impl.h" + +void +mpz_cdiv_qr (mpz_ptr quot, mpz_ptr rem, mpz_srcptr dividend, mpz_srcptr divisor) +{ + mp_size_t divisor_size = divisor->_mp_size; + mp_size_t xsize; + mpz_t temp_divisor; /* N.B.: lives until function returns! */ + TMP_DECL; + + TMP_MARK; + + /* We need the original value of the divisor after the quotient and + remainder have been preliminary calculated. We have to copy it to + temporary space if it's the same variable as either QUOT or REM. */ + if (quot == divisor || rem == divisor) + { + MPZ_TMP_INIT (temp_divisor, ABS (divisor_size)); + mpz_set (temp_divisor, divisor); + divisor = temp_divisor; + } + + xsize = dividend->_mp_size ^ divisor_size;; + mpz_tdiv_qr (quot, rem, dividend, divisor); + + if (xsize >= 0 && rem->_mp_size != 0) + { + mpz_add_ui (quot, quot, 1L); + mpz_sub (rem, rem, divisor); + } + + TMP_FREE; +} diff --git a/pool/shard004/C/0098967_mtk_mira.c b/pool/shard004/C/0098967_mtk_mira.c new file mode 100644 index 0000000000000000000000000000000000000000..5e6e9d3d99fe6a7f73658cef3b451405177d6e5e --- /dev/null +++ b/pool/shard004/C/0098967_mtk_mira.c @@ -0,0 +1,103 @@ +#define LOG_TAG "mtk_mira" + +#include "disp_drv_log.h" + +#include +#include +#include +#include +#include + +#include "mtk_mira.h" +#include "mtk_disp_mgr.h" + + +#define DISP_DEVNAME "mtk_mira" + +static struct proc_dir_entry * proc_entry; + +static long disp_unlocked_ioctl(struct file *file, unsigned int cmd, unsigned long arg) +{ + return mtk_disp_mgr_ioctl(file, cmd, arg); +} +#ifdef CONFIG_COMPAT +static long disp_compat_ioctl(struct file *file, unsigned int cmd, unsigned long arg) +{ + long ret = -ENOIOCTLCMD; + + switch(cmd) { + + // add cases here for 32bit/64bit conversion + // ... + + default: + return mtk_disp_mgr_ioctl(file, cmd, arg); + } + return ret; +} +#endif + +static int disp_open(struct inode *inode, struct file *file) +{ + return 0; +} + +static ssize_t disp_read(struct file *file, char __user *data, size_t len, loff_t *ppos) +{ + return 0; +} + +static int disp_release(struct inode *inode, struct file *file) +{ + return 0; +} + +static int disp_flush(struct file * file , fl_owner_t a_id) +{ + return 0; +} + +// remap register to user space +static int disp_mmap(struct file * file, struct vm_area_struct * a_pstVMArea) +{ + return 0; +} + +/* Kernel interface */ +static struct file_operations disp_fops = { + .owner = THIS_MODULE, + .unlocked_ioctl = disp_unlocked_ioctl, +#ifdef CONFIG_COMPAT + .compat_ioctl = disp_compat_ioctl, +#endif + + .open = disp_open, + .release = disp_release, + .flush = disp_flush, + .read = disp_read, + .mmap = disp_mmap +}; + +static int __init disp_init(void) +{ + int ret = 0; + DISPMSG("Register the disp driver\n"); + proc_entry = proc_create(DISP_DEVNAME,0644, NULL,&disp_fops); + if(proc_entry == NULL) + { + ret = -ENOMEM; + } + return ret; +} + +static void __exit disp_exit(void) +{ + remove_proc_entry(DISP_DEVNAME,proc_entry); + DISPMSG("Done\n"); +} + +module_init(disp_init); +module_exit(disp_exit); +MODULE_AUTHOR("Tzu-Meng, Chung "); +MODULE_DESCRIPTION("Display subsystem Driver"); +MODULE_LICENSE("GPL"); diff --git a/pool/shard004/C/0098974_ghmain.c b/pool/shard004/C/0098974_ghmain.c new file mode 100644 index 0000000000000000000000000000000000000000..df4febe24260dad09cf01898eac55d269685adde --- /dev/null +++ b/pool/shard004/C/0098974_ghmain.c @@ -0,0 +1,70 @@ +// lab05b.c : Defines the entry point for the console application. +#include +//#include +#include +#include "ghcontrol.h" +#include "ghutils.h" +#include "hshbme280.h" +#include +//#include + +int main(void) +{ + //Initialization Section + srand((unsigned) time(NULL)); + if(GhControllerInit()==ABNORMAL) + GhControllerShutdown(ABNORMAL); + //GhSetSetpoints(); + time_t current; + double creadings[SENSORS]={0.0,0.0,0.0,0.0}; + + reading_s creading_s = {0}; + setpoint_s sets = {0}; + control_s ctrl = {0}; + alarmlimit_s alimits = {0}; + + int tempc; + int humidc; + int lightc; + + // Control Loop - FIRST SET OF READINGS ARE NOT CORRECT + while (1) + { + pinMode(HSH_PCF8591_PINBASE, OUTPUT); + analogWrite(HSH_PCF8591_PINBASE,0); + delay(1000); + analogWrite(HSH_PCF8591_PINBASE,127); + pinMode(HSH_PCF8591_PINBASE, INPUT); + + printf("Greenhouse Control Loop"); + + //GhGetReadings(¤t,creadings); + creading_s = GhGetReadings(); + creadings[TEMPERATURE]=creading_s.temperature; + creadings[HUMIDITY]=creading_s.humidity; + creadings[PRESSURE]=creading_s.pressure; + creadings[LIGHT]=creading_s.light; + GhDisplayReadings(¤t,creadings); + + //logged = GhLogData("ghdata.txt", creadings); + //alimits = GhSetAlarmLimits(); + //arecord = GhSetAlarms(arecord,alimits,creadings); + + sets = GhSetSetpoint(); + GhDisplaySetpoints(); + + //GhSetControls(&tempc,&humidc,&lightc,creadings); + ctrl = GhSetControls(sets, creading_s); + //GhDisplayControls(&tempc,&humidc,&lightc); + GhDisplayControls(&ctrl.heater,&ctrl.humidifier,&ctrl.light); + + printf("Delaying %d seconds prior to repeating\n\n",UPDATE/1000); + //if(digitalRead (HSH_MCP23017_PINBASE+GHCOFF)) + // break; + GhDelay(UPDATE); + } + //printf("\nPress enter to exit"); + //getchar(); + return GhControllerShutdown(NORMAL); +} + diff --git a/pool/shard004/C/0098975_utils.c b/pool/shard004/C/0098975_utils.c new file mode 100644 index 0000000000000000000000000000000000000000..d9d7db4213381608dcfc4464fe1aa00fabccdeae --- /dev/null +++ b/pool/shard004/C/0098975_utils.c @@ -0,0 +1,51 @@ +/* + * This file is a part of Poly2Tri-C + * (c) Barak Itkin + * http://code.google.com/p/poly2tri-c/ + * + * 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 Poly2Tri 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 "utils.h" + +GList* +p2tr_utils_new_reversed_pointer_list (int count, ...) +{ + int i; + va_list args; + GList *result = NULL; + + va_start (args, count); + for (i = 0; i < count; i++) + result = g_list_prepend (result, va_arg (args, gpointer)); + va_end (args); + + return result; +} diff --git a/pool/shard004/C/0098977_strndup.c b/pool/shard004/C/0098977_strndup.c new file mode 100644 index 0000000000000000000000000000000000000000..9a8f9fe0478839a718d1a8c36832b1c4c2629deb --- /dev/null +++ b/pool/shard004/C/0098977_strndup.c @@ -0,0 +1,41 @@ +/* $OpenBSD: strndup.c,v 1.1 2010/05/18 22:24:55 tedu Exp $ */ + +/* + * Copyright (c) 2010 Todd C. Miller + * + * 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. + */ + +#include + +#include +#include +#include + +char *strndup(const char *str, size_t n); + +char * +strndup(const char *str, size_t maxlen) +{ + char *copy; + size_t len; + + len = strnlen(str, maxlen); + copy = malloc(len + 1); + if (copy != NULL) { + (void)memcpy(copy, str, len); + copy[len] = '\0'; + } + + return copy; +} diff --git a/pool/shard004/C/0098979_test_fileserv.c b/pool/shard004/C/0098979_test_fileserv.c new file mode 100644 index 0000000000000000000000000000000000000000..15efdeb12aa83970750649966ea9d6ded97006a1 --- /dev/null +++ b/pool/shard004/C/0098979_test_fileserv.c @@ -0,0 +1,165 @@ +/* + * 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 +#ifdef CONFIG_REFOS_RUN_TESTS + +#include +#include +#include +#include +#include "test_fileserv.h" +#include +#include +#include + +/* -------------------------------- File server tests -------------------------------------- */ + +static int +test_file_server_connect() +{ + test_start("fs connection"); + + /* Find the file server. */ + nsv_mountpoint_t mp = nsv_resolve("fileserv/*"); + test_assert(mp.success == true); + test_assert(mp.serverAnon != 0); + + seL4_CPtr fileservAnon = mp.serverAnon; + const int fs_test_repeat = 5; + + /* Attempt to ping the file server. */ + for (int i = 0; i < fs_test_repeat; i++) { + int error = serv_ping(fileservAnon); + test_assert(error == ESUCCESS); + } + + /* Repeatedly connect to and disconnect from the file server. */ + for (int i = 0; i < fs_test_repeat; i++) { + int error; + seL4_CPtr fileservSession = serv_connect_direct(fileservAnon, REFOS_LIVENESS, &error); + test_assert(fileservSession && error == ESUCCESS); + + if (fileservSession) { + serv_disconnect_direct(fileservSession); + seL4_CNode_Delete(REFOS_CSPACE, fileservSession, REFOS_CDEPTH); + csfree(fileservSession); + } + } + + /* Release the resources stored in the valid mountpoint. */ + nsv_mountpoint_release(&mp); + test_assert(mp.success == false); + test_assert(mp.serverAnon == 0); + + return test_success(); +} + +static int +test_file_server_dataspace() +{ + /* ---------- datamap test ------------ */ + test_start("fs cpio dspace datamap"); + int error; + + /* Find the file server. */ + nsv_mountpoint_t mp = nsv_resolve("fileserv/*"); + test_assert(mp.success == true); + test_assert(mp.serverAnon != 0); + seL4_CPtr fileservAnon = mp.serverAnon; + + seL4_CPtr fileservSession = serv_connect_direct(fileservAnon, REFOS_LIVENESS, &error); + test_assert(fileservSession && error == ESUCCESS); + + /* Allocate a temporary window. */ + seL4_CPtr tempWindow = 0; + seL4_Word tempWindowVaddr = walloc(2, &tempWindow); + test_assert(tempWindowVaddr && tempWindow); + + /* Open a new dataspace on the fileserver to test with. */ + seL4_CPtr dspace = data_open(fileservSession, "hello.txt", 0, O_RDWR, 0, &error); + test_assert(dspace && error == ESUCCESS); + + /* Test datamap. */ + error = data_datamap(fileservSession, dspace, tempWindow, 3); + test_assert(error == ESUCCESS); + int scmp = strncmp((char*) tempWindowVaddr, "lo world!", 9); + test_assert(scmp == 0); + + test_success(); + + /* ---------- init_data test ------------ */ + test_start("fs cpio dspace init_data"); + + /* Open a new anon dataspace to init data on */ + seL4_CPtr anonDS = data_open(REFOS_PROCSERV_EP, "anon", 0, O_RDWR, 0x1000, &error); + test_assert(anonDS && error == ESUCCESS); + + /* Inititialise content of this anon dataspace with our fileserv CPIO dataspace. */ + error = data_init_data(fileservSession, anonDS, dspace , 3); + test_assert(error == ESUCCESS); + + /* Allocate another temporary window. */ + seL4_CPtr tempWindowAnon = 0; + seL4_Word tempWindowVaddrAnon = walloc(2, &tempWindowAnon); + test_assert(tempWindowVaddrAnon && tempWindowAnon); + + /* Datamap initialised anon dataspace. */ + error = data_datamap(REFOS_PROCSERV_EP, anonDS, tempWindowAnon, 0); + test_assert(error == ESUCCESS); + scmp = strncmp((char*) tempWindowVaddrAnon, "lo world!", 9); + test_assert(scmp == 0); + + /* Clean up. */ + data_dataunmap(fileservSession, tempWindow); + data_dataunmap(REFOS_PROCSERV_EP, tempWindowAnon); + if (tempWindow) { + walloc_free(tempWindowVaddr, 2); + } + if (tempWindowAnon) { + walloc_free(tempWindowVaddrAnon, 2); + } + if (fileservSession) { + serv_disconnect_direct(fileservSession); + seL4_CNode_Delete(REFOS_CSPACE, fileservSession, REFOS_CDEPTH); + csfree(fileservSession); + } + + /* Release the resources stored in the valid mountpoint. */ + nsv_mountpoint_release(&mp); + test_assert(mp.success == false); + test_assert(mp.serverAnon == 0); + + return test_success(); +} + +static int +test_file_server_serv_connect() +{ + test_start("fs serv_connect"); + for (int i = 0; i < 5; i++) { + serv_connection_t c = serv_connect("/fileserv/*"); + test_assert(c.error == ESUCCESS); + test_assert(c.paramBuffer.err == ESUCCESS); + strcpy(c.paramBuffer.vaddr, "test"); + serv_disconnect(&c); + } + return test_success(); +} + +void +test_file_server(void) +{ + test_file_server_connect(); + test_file_server_dataspace(); + test_file_server_serv_connect(); +} + +#endif /* CONFIG_REFOS_RUN_TESTS */ diff --git a/pool/shard004/C/0098980_struct_main.c b/pool/shard004/C/0098980_struct_main.c new file mode 100644 index 0000000000000000000000000000000000000000..8646a0c4962284cf90e4c8d323f4ad8d262ba346 --- /dev/null +++ b/pool/shard004/C/0098980_struct_main.c @@ -0,0 +1,109 @@ +/**************************************************************************** + * examples/nxflat/tests/struct/struct_main.c + * + * Copyright (C) 2009 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 "struct.h" + +/**************************************************************************** + * Public Data + ****************************************************************************/ + +const struct struct_dummy_s dummy_struct = +{ + DUMMY_SCALAR_VALUE3 +}; + +int dummy_scalar = DUMMY_SCALAR_VALUE2; + +/**************************************************************************** + * Public Functions + ****************************************************************************/ + +int main(int argc, char **argv) +{ + const struct struct_s *mystruct; + + printf("Calling getstruct()\n"); + mystruct = getstruct(); + printf("getstruct returned %p\n", mystruct); + printf(" n = %d (vs %d) %s\n", + mystruct->n, DUMMY_SCALAR_VALUE1, + mystruct->n == DUMMY_SCALAR_VALUE1 ? "PASS" : "FAIL"); + + printf(" pn = %p (vs %p) %s\n", + mystruct->pn, &dummy_scalar, + mystruct->pn == &dummy_scalar ? "PASS" : "FAIL"); + if (mystruct->pn == &dummy_scalar) + { + printf(" *pn = %d (vs %d) %s\n", + *mystruct->pn, DUMMY_SCALAR_VALUE2, + *mystruct->pn == DUMMY_SCALAR_VALUE2 ? "PASS" : "FAIL"); + } + + printf(" ps = %p (vs %p) %s\n", + mystruct->ps, &dummy_struct, + mystruct->ps == &dummy_struct ? "PASS" : "FAIL"); + if (mystruct->ps == &dummy_struct) + { + printf(" ps->n = %d (vs %d) %s\n", + mystruct->ps->n, DUMMY_SCALAR_VALUE3, + mystruct->ps->n == DUMMY_SCALAR_VALUE3 ? "PASS" : "FAIL"); + } + + printf(" pf = %p (vs %p) %s\n", + mystruct->pf, dummyfunc, + mystruct->pf == dummyfunc ? "PASS" : "FAIL"); + if (mystruct->pf == dummyfunc) + { + printf("Calling mystruct->pf()\n"); + mystruct->pf(); + } + + printf("Exit-ing\n"); + return 0; +} + +void dummyfunc(void) +{ + printf("In dummyfunc() -- PASS\n"); +} + + diff --git a/pool/shard004/C/0098984_gcr.c b/pool/shard004/C/0098984_gcr.c new file mode 100644 index 0000000000000000000000000000000000000000..21156bfeda26a5cda42e74eec7f182dab949a4c2 --- /dev/null +++ b/pool/shard004/C/0098984_gcr.c @@ -0,0 +1,198 @@ +/*********************************************************************** + * 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 . + ***********************************************************************/ + +#ifdef HAVE_CONFIG_H +# include +#endif +#include +#include +#include +#include"global.h" +#include"su3.h" +#include"linalg_eo.h" +#include"solver/gmres_precon.h" +#include"start.h" +#include"operator/tm_operators.h" +#include"solver/poly_precon.h" +#include"solver/cg_her.h" +#include"operator/D_psi.h" +#include"Msap.h" +#include"dfl_projector.h" +#include "solver_field.h" +#include"gcr.h" + +static void init_gcr(const int _M, const int _V); + +static _Complex double ** a; +static _Complex double * _a; +static double * b; +static _Complex double * c; +static spinor ** chi; +static spinor * _chi; +static spinor ** xi; +static spinor * _xi; +static _Complex double * alpha; +extern int dfl_poly_iter; + +int gcr(spinor * const P, spinor * const Q, + const int m, const int max_restarts, + const double eps_sq, const int rel_prec, + const int N, const int precon, matrix_mult f) { + + int k, l, restart, i, iter = 0; + double norm_sq, err; + spinor * rho, * tmp; + _Complex double ctmp; + spinor ** solver_field = NULL; + const int nr_sf = 2; + + if(N == VOLUME) { + init_solver_field(&solver_field, VOLUMEPLUSRAND, nr_sf); + } + else { + init_solver_field(&solver_field, VOLUMEPLUSRAND/2, nr_sf); + } + + rho = solver_field[0]; + tmp = solver_field[1]; + + init_gcr(m, N+RAND); + + norm_sq = square_norm(Q, N, 1); + if(norm_sq < 1.e-32) { + norm_sq = 1.; + } + + for(restart = 0; restart < max_restarts; restart++) { + dfl_sloppy_prec = 0; + f(tmp, P); + diff(rho, Q, tmp, N); + err = square_norm(rho, N, 1); + if(g_proc_id == g_stdio_proc && g_debug_level > 1){ + printf("GCR: iteration number: %d, true residue: %g\n", iter, err); + fflush(stdout); + } + if(((err <= eps_sq) && (rel_prec == 0)) || ((err <= eps_sq*norm_sq) && (rel_prec == 1))) { + finalize_solver(solver_field, nr_sf); + return(iter); + } + for(k = 0; k < m; k++) { + + if(precon == 0) { + assign(xi[k], rho, N); + } + else { + zero_spinor_field(xi[k], N); + Msap_eo(xi[k], rho, 6); + /* Msap(xi[k], rho, 8); */ + } + + dfl_sloppy_prec = 1; + dfl_little_D_prec = 1.e-12; + f(tmp, xi[k]); + + /* tmp will become chi[k] */ + for(l = 0; l < k; l++) { + a[l][k] = scalar_prod(chi[l], tmp, N, 1); + assign_diff_mul(tmp, chi[l], a[l][k], N); + } + b[k] = sqrt(square_norm(tmp, N, 1)); + mul_r(chi[k], 1./b[k], tmp, N); + c[k] = scalar_prod(chi[k], rho, N, 1); + assign_diff_mul(rho, chi[k], c[k], N); + err = square_norm(rho, N, 1); + iter ++; + if(g_proc_id == g_stdio_proc && g_debug_level > 2){ + if(rel_prec == 1) printf("# GCR: %d\t%g >= %g iterated residue\n", iter, err, eps_sq*norm_sq); + else printf("# GCR: %d\t%g >= %giterated residue\n", iter, err, eps_sq); + fflush(stdout); + } + /* Precision reached? */ + if((k == m-1) || ((err <= eps_sq) && (rel_prec == 0)) || ((err <= eps_sq*norm_sq) && (rel_prec == 1))) { + break; + } + } + + /* prepare for restart */ + c[k] /= b[k]; + assign_add_mul(P, xi[k], c[k], N); + for(l = k - 1; l >= 0; --l) + { + for(i = l+1; i <= k; ++i) + { + ctmp = a[l][i] * c[i]; + c[l] -= ctmp; + } + c[l] /= b[l]; + assign_add_mul(P, xi[l], c[l], N); + } + } + finalize_solver(solver_field, nr_sf); + return(-1); +} + +static void init_gcr(const int _M, const int _V){ + static int Vo = -1; + static int M = -1; + static int init = 0; + int i; + if((M != _M)||(init == 0)||(Vo != _V)){ + if(init == 1){ + free(a); + free(chi); + free(_a); + free(_chi); + free(alpha); + free(c); + free(_xi); + free(xi); + } + Vo = _V; + M = _M; + a = calloc(M+1, sizeof(_Complex double *)); + chi = calloc(M, sizeof(spinor *)); + xi = calloc(M, sizeof(spinor *)); +#if (defined SSE || defined SSE2 || defined SSE3) + _a = calloc((M+2)*M, sizeof(_Complex double)); + a[0] = (_Complex double *)(((unsigned long int)(_a)+ALIGN_BASE)&~ALIGN_BASE); + _chi = calloc(M*Vo+1, sizeof(spinor)); + chi[0] = (spinor *)(((unsigned long int)(_chi)+ALIGN_BASE)&~ALIGN_BASE); + _xi = calloc(M*Vo+1, sizeof(spinor)); + xi[0] = (spinor *)(((unsigned long int)(_xi)+ALIGN_BASE)&~ALIGN_BASE); +#else + _a = calloc((M+1)*M, sizeof(_Complex double)); + a[0] = _a; + _chi = calloc(M*Vo, sizeof(spinor)); + chi[0] = _chi; + _xi = calloc(M*Vo, sizeof(spinor)); + xi[0] = _xi; +#endif + if(_xi == NULL) {printf("Unable to allocated space for GCR iterations\n");exit(0); } + b = calloc(M, sizeof(double)); + c = calloc(M, sizeof(_Complex double)); + alpha = calloc(M+1, sizeof(_Complex double)); + for(i = 1; i < M; i++){ + chi[i] = chi[i-1] + Vo; + xi[i] = xi[i-1] + Vo; + a[i] = a[i-1] + M; + } + a[M] = a[M-1] + M; + init = 1; + } +} diff --git a/pool/shard004/C/0098985_10.2.c b/pool/shard004/C/0098985_10.2.c new file mode 100644 index 0000000000000000000000000000000000000000..f11a52a6dfdd235a79cab48f3f03ccc3a9ae688b --- /dev/null +++ b/pool/shard004/C/0098985_10.2.c @@ -0,0 +1,40 @@ +#include +#include + +void sort(char (*str)[80],int n){//row pointer to array having eighty elements. + int i,j,k; + char *temp; + for(i=0;i0){ + k = j; + } + } + if(k!=i){ + strcpy(temp,*(str+i)); + strcpy(*(str+i),*(str+k)); + strcpy(*(str+k),temp); + } + } +} + +void main(){ + char str[3][80]; + char (*p)[80]; + int i; + p = str; + ///* + printf("Enter the three string:\n"); + for(i=0;i<3;i++){ + gets(*p); + p++; + } + //*/ + p = str; + sort(str,3); + printf("Order string:\n"); + for(i=0;i<3;i++){ + printf("%s\n",str[i]); + } +} \ No newline at end of file diff --git a/pool/shard004/C/0098986_main.c b/pool/shard004/C/0098986_main.c new file mode 100644 index 0000000000000000000000000000000000000000..dba6510b62a8e406c5482db6d3afe6b18e0cac31 --- /dev/null +++ b/pool/shard004/C/0098986_main.c @@ -0,0 +1,17 @@ +#include + +int main(char argc, char** argv) +{ + void* ptr; + int a, b; + + a = 5; + b = 2; + + ptr = (int*)&a; + + printf("a + b = %i + %i = %i\n", a, b, a+b); + printf("*ptr + b = %i + %i = %i\n", *(int*)ptr, b, *((int*)ptr)+b); + + return 0; +} diff --git a/pool/shard004/C/0098990_n_hash_stats.c b/pool/shard004/C/0098990_n_hash_stats.c new file mode 100644 index 0000000000000000000000000000000000000000..1a399ef7f3d7d353dcfafa8b9463362caace3025 --- /dev/null +++ b/pool/shard004/C/0098990_n_hash_stats.c @@ -0,0 +1,63 @@ +#ifdef HAVE_CONFIG_H +# include "config.h" +#endif + +#include "n_hash_int.h" + +#include +int n_hash_stats(const tn_hash *ht) +{ + register size_t i, n = 0; + register struct hash_bucket *tmp; + int ncolls = 0; + int nempts = 0; + int maxdeep = 0; + int deepsum = 0; + int empty_len_sum = 0; + int empty_len_n = 0; + int empty_len = 0; + + for (i = 0; i < ht->size; i++) { + int deep; + + if (ht->table[i] == NULL) { + nempts++; + empty_len++; + continue; + } + if (empty_len > 6) { + empty_len_n++; + empty_len_sum += empty_len; + empty_len = 0; + } + + + deep = 1; + //if (ht->table[i]->next) + // printf("coll %s, ", ht->table[i]->key); + + for (tmp = ht->table[i]->next; tmp != NULL; tmp = tmp->next) { + //printf("%s, ", tmp->key); + deep++; + } + //if (ht->table[i]->next) + // printf("\n"); + + if (deep > 1) { + ncolls++; + deepsum += deep; + } + + if (deep > maxdeep) + maxdeep = deep; + } + + printf("ht(%p): %lu slots (%d empty, avg empty len %d), %lu items, " + "%d collisions (avgdeep %.2lf, maxdep %d)\n", + ht, ht->size, nempts, empty_len_sum ? empty_len_sum / empty_len_n : 0, + ht->items, ncolls, + ncolls > 0 && deepsum > 0 ? deepsum/(ncolls * 1.0) : 0, + maxdeep); +// n_assert(0); + return n; +} diff --git a/pool/shard004/C/0098991_zutil.c b/pool/shard004/C/0098991_zutil.c new file mode 100644 index 0000000000000000000000000000000000000000..ed9f576e70e38a0b7ae4cfeb94c228474f43e4d4 --- /dev/null +++ b/pool/shard004/C/0098991_zutil.c @@ -0,0 +1,225 @@ +/* zutil.c -- target dependent utility functions for the compression library + * Copyright (C) 1995-2002 Jean-loup Gailly. + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +/* @(#) $Id: zutil.c 700 2006-02-25 22:49:40Z pepsiman $ */ + +#include "zutil.h" + +struct internal_state {int dummy;}; /* for buggy compilers */ + +#ifndef STDC +extern void exit OF((int)); +#endif + +const char *z_errmsg[10] = { +"need dictionary", /* Z_NEED_DICT 2 */ +"stream end", /* Z_STREAM_END 1 */ +"", /* Z_OK 0 */ +"file error", /* Z_ERRNO (-1) */ +"stream error", /* Z_STREAM_ERROR (-2) */ +"data error", /* Z_DATA_ERROR (-3) */ +"insufficient memory", /* Z_MEM_ERROR (-4) */ +"buffer error", /* Z_BUF_ERROR (-5) */ +"incompatible version",/* Z_VERSION_ERROR (-6) */ +""}; + + +const char * ZEXPORT zlibVersion() +{ + return ZLIB_VERSION; +} + +#ifdef DEBUG + +# ifndef verbose +# define verbose 0 +# endif +int z_verbose = verbose; + +void z_error (m) + char *m; +{ + fprintf(stderr, "%s\n", m); + exit(1); +} +#endif + +/* exported to allow conversion of error code to string for compress() and + * uncompress() + */ +const char * ZEXPORT zError(err) + int err; +{ + return ERR_MSG(err); +} + + +#ifndef HAVE_MEMCPY + +void zmemcpy(dest, source, len) + Bytef* dest; + const Bytef* source; + uInt len; +{ + if (len == 0) return; + do { + *dest++ = *source++; /* ??? to be unrolled */ + } while (--len != 0); +} + +int zmemcmp(s1, s2, len) + const Bytef* s1; + const Bytef* s2; + uInt len; +{ + uInt j; + + for (j = 0; j < len; j++) { + if (s1[j] != s2[j]) return 2*(s1[j] > s2[j])-1; + } + return 0; +} + +void zmemzero(dest, len) + Bytef* dest; + uInt len; +{ + if (len == 0) return; + do { + *dest++ = 0; /* ??? to be unrolled */ + } while (--len != 0); +} +#endif + +#ifdef __TURBOC__ +#if (defined( __BORLANDC__) || !defined(SMALL_MEDIUM)) && !defined(__32BIT__) +/* Small and medium model in Turbo C are for now limited to near allocation + * with reduced MAX_WBITS and MAX_MEM_LEVEL + */ +# define MY_ZCALLOC + +/* Turbo C malloc() does not allow dynamic allocation of 64K bytes + * and farmalloc(64K) returns a pointer with an offset of 8, so we + * must fix the pointer. Warning: the pointer must be put back to its + * original form in order to free it, use zcfree(). + */ + +#define MAX_PTR 10 +/* 10*64K = 640K */ + +local int next_ptr = 0; + +typedef struct ptr_table_s { + voidpf org_ptr; + voidpf new_ptr; +} ptr_table; + +local ptr_table table[MAX_PTR]; +/* This table is used to remember the original form of pointers + * to large buffers (64K). Such pointers are normalized with a zero offset. + * Since MSDOS is not a preemptive multitasking OS, this table is not + * protected from concurrent access. This hack doesn't work anyway on + * a protected system like OS/2. Use Microsoft C instead. + */ + +voidpf zcalloc (voidpf opaque, unsigned items, unsigned size) +{ + voidpf buf = opaque; /* just to make some compilers happy */ + ulg bsize = (ulg)items*size; + + /* If we allocate less than 65520 bytes, we assume that farmalloc + * will return a usable pointer which doesn't have to be normalized. + */ + if (bsize < 65520L) { + buf = farmalloc(bsize); + if (*(ush*)&buf != 0) return buf; + } else { + buf = farmalloc(bsize + 16L); + } + if (buf == NULL || next_ptr >= MAX_PTR) return NULL; + table[next_ptr].org_ptr = buf; + + /* Normalize the pointer to seg:0 */ + *((ush*)&buf+1) += ((ush)((uch*)buf-0) + 15) >> 4; + *(ush*)&buf = 0; + table[next_ptr++].new_ptr = buf; + return buf; +} + +void zcfree (voidpf opaque, voidpf ptr) +{ + int n; + if (*(ush*)&ptr != 0) { /* object < 64K */ + farfree(ptr); + return; + } + /* Find the original pointer */ + for (n = 0; n < next_ptr; n++) { + if (ptr != table[n].new_ptr) continue; + + farfree(table[n].org_ptr); + while (++n < next_ptr) { + table[n-1] = table[n]; + } + next_ptr--; + return; + } + ptr = opaque; /* just to make some compilers happy */ + Assert(0, "zcfree: ptr not found"); +} +#endif +#endif /* __TURBOC__ */ + + +#if defined(M_I86) && !defined(__32BIT__) +/* Microsoft C in 16-bit mode */ + +# define MY_ZCALLOC + +#if (!defined(_MSC_VER) || (_MSC_VER <= 600)) +# define _halloc halloc +# define _hfree hfree +#endif + +voidpf zcalloc (voidpf opaque, unsigned items, unsigned size) +{ + if (opaque) opaque = 0; /* to make compiler happy */ + return _halloc((long)items, size); +} + +void zcfree (voidpf opaque, voidpf ptr) +{ + if (opaque) opaque = 0; /* to make compiler happy */ + _hfree(ptr); +} + +#endif /* MSC */ + + +#ifndef MY_ZCALLOC /* Any system without a special alloc function */ + +#ifndef STDC +extern voidp calloc OF((uInt items, uInt size)); +extern void free OF((voidpf ptr)); +#endif + +voidpf zcalloc (opaque, items, size) + voidpf opaque; + unsigned items; + unsigned size; +{ + if (opaque) items += size - size; /* make compiler happy */ + return (voidpf)calloc(items, size); +} + +void zcfree (opaque, ptr) + voidpf opaque; + voidpf ptr; +{ + free(ptr); + if (opaque) return; /* make compiler happy */ +} + +#endif /* MY_ZCALLOC */ diff --git a/pool/shard004/C/0098995_partialresume.c b/pool/shard004/C/0098995_partialresume.c new file mode 100644 index 0000000000000000000000000000000000000000..844955218bca10076ae5f2584a22c1f964f33533 --- /dev/null +++ b/pool/shard004/C/0098995_partialresume.c @@ -0,0 +1,191 @@ +/* kernel/power/partialresume.c + * + * Copyright (C) 2015 Google, Inc. + * + * This software is licensed under the terms of the GNU General Public + * License version 2, as published by the Free Software Foundation, and + * may be copied, distributed, and modified under those terms. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +static DEFINE_MUTEX(pr_handlers_lock); +static LIST_HEAD(pr_handlers); +static LIST_HEAD(pr_matches); +static struct partial_resume_stats match_stats; +static struct partial_resume_stats consensus_stats; +static struct kobject *partialresume; + +bool suspend_again_match(const struct list_head *irqs, + const struct list_head *unfinished) +{ + const struct wakeup_irq_node *i; + struct partial_resume *h, *match; + + INIT_LIST_HEAD(&pr_matches); + + match_stats.total++; + + if (!irqs || list_empty(irqs)) + return false; + + list_for_each_entry(i, irqs, next) { + match = NULL; + list_for_each_entry(h, &pr_handlers, next_handler) { + if (i->irq == h->irq) { + match = h; + break; + } + } + if (!match) { + pr_debug("%s: wakeup irq %d does not have a handler\n", __func__, i->irq); + return false; + } + list_add(&match->next_match, &pr_matches); + } + + match_stats.total_yes++; + + return true; +} + + +bool suspend_again_consensus(void) +{ + struct partial_resume *h; + + BUG_ON(list_empty(&pr_matches)); + list_for_each_entry(h, &pr_matches, next_match) { + h->stats.total++; + if (!h->partial_resume(h)) { + pr_debug("%s: partial-resume for %d: false\n", __func__, h->irq); + return false; + } + h->stats.total_yes++; + pr_debug("%s: partial-resume for %d: true\n", __func__, h->irq); + } + + consensus_stats.total_yes++; + + return true; +} + + +int register_partial_resume(struct partial_resume *handler) +{ + struct partial_resume *e; + + if (!handler || !handler->irq || !handler->partial_resume) + return -EINVAL; + + mutex_lock(&pr_handlers_lock); + list_for_each_entry(e, &pr_handlers, next_handler) { + if (e->irq == handler->irq) { + if (e->partial_resume == handler->partial_resume) { + mutex_unlock(&pr_handlers_lock); + return 0; + } + pr_err("%s: error registering %pF for irq %d: "\ + "%pF already registered\n", + __func__, + handler->partial_resume, + e->irq, + e->partial_resume); + mutex_unlock(&pr_handlers_lock); + return -EIO; + } + } + + list_add(&handler->next_handler, &pr_handlers); + mutex_unlock(&pr_handlers_lock); + return 0; +} + +void unregister_partial_resume(struct partial_resume *handler) +{ + mutex_lock(&pr_handlers_lock); + list_del(&handler->next_handler); + mutex_unlock(&pr_handlers_lock); +} + + +static ssize_t partialresume_stats_show(struct kobject *kobj, + struct kobj_attribute *attr, + char *buf) +{ + ssize_t offset = 0; + struct partial_resume *h; + + offset += sprintf(buf + offset, "global: %d %d %d \n", + match_stats.total, + match_stats.total_yes, + consensus_stats.total_yes); + + mutex_lock(&pr_handlers_lock); + + list_for_each_entry(h, &pr_handlers, next_handler) { + offset += sprintf(buf + offset, "%d: %d %d\n", + h->irq, + h->stats.total, + h->stats.total_yes); + } + + mutex_unlock(&pr_handlers_lock); + + return offset; +} + +static struct kobj_attribute partialresume_stats = __ATTR_RO(partialresume_stats); + +static struct attribute *partialresume_stats_attrs[] = { + &partialresume_stats.attr, + NULL, +}; +static struct attribute_group partialresume_stats_attr_group = { + .attrs = partialresume_stats_attrs, +}; + +int __init partial_resume_init(void) +{ + int rc = -EIO; + + partialresume = kobject_create_and_add("partialresume", kernel_kobj); + if (!partialresume) { + pr_warning("%s: failed to create a sysfs kobject\n", __func__); + goto fail; + } + + rc = sysfs_create_group(partialresume, &partialresume_stats_attr_group); + if (rc) { + pr_warning("%s: failed to create a sysfs group\n", __func__); + goto fail_kobject_put; + } + + return 0; + +#if 0 +fail_remove_group: + sysfs_remove_group(partialresume, &partialresume_stats_attr_group); +#endif +fail_kobject_put: + kobject_put(partialresume); +fail: + return rc; +} + +subsys_initcall(partial_resume_init); diff --git a/pool/shard004/C/0098997_sdhci-dove.c b/pool/shard004/C/0098997_sdhci-dove.c new file mode 100644 index 0000000000000000000000000000000000000000..e6278ec007d775c576346102e358426e08c3edbe --- /dev/null +++ b/pool/shard004/C/0098997_sdhci-dove.c @@ -0,0 +1,162 @@ +/* + * sdhci-dove.c Support for SDHCI on Marvell's Dove SoC + * + * Author: Saeed Bishara + * Mike Rapoport + * Based on sdhci-cns3xxx.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., 675 Mass Ave, Cambridge, MA 02139, USA. + */ + +#include +#include +#include +#include +#include +#include + +#include "sdhci-pltfm.h" + +struct sdhci_dove_priv { + struct clk *clk; +}; + +static u16 sdhci_dove_readw(struct sdhci_host *host, int reg) +{ + u16 ret; + + switch (reg) { + case SDHCI_HOST_VERSION: + case SDHCI_SLOT_INT_STATUS: + /* those registers don't exist */ + return 0; + default: + ret = readw(host->ioaddr + reg); + } + return ret; +} + +static u32 sdhci_dove_readl(struct sdhci_host *host, int reg) +{ + u32 ret; + + ret = readl(host->ioaddr + reg); + + switch (reg) { + case SDHCI_CAPABILITIES: + /* Mask the support for 3.0V */ + ret &= ~SDHCI_CAN_VDD_300; + break; + } + return ret; +} + +static const struct sdhci_ops sdhci_dove_ops = { + .read_w = sdhci_dove_readw, + .read_l = sdhci_dove_readl, + .set_clock = sdhci_set_clock, + .set_bus_width = sdhci_set_bus_width, + .reset = sdhci_reset, + .set_uhs_signaling = sdhci_set_uhs_signaling, +}; + +static const struct sdhci_pltfm_data sdhci_dove_pdata = { + .ops = &sdhci_dove_ops, + .quirks = SDHCI_QUIRK_NO_SIMULT_VDD_AND_POWER | + SDHCI_QUIRK_NO_BUSY_IRQ | + SDHCI_QUIRK_BROKEN_TIMEOUT_VAL | + SDHCI_QUIRK_FORCE_DMA | + SDHCI_QUIRK_NO_HISPD_BIT, +}; + +static int sdhci_dove_probe(struct platform_device *pdev) +{ + struct sdhci_host *host; + struct sdhci_pltfm_host *pltfm_host; + struct sdhci_dove_priv *priv; + int ret; + + priv = devm_kzalloc(&pdev->dev, sizeof(struct sdhci_dove_priv), + GFP_KERNEL); + if (!priv) { + dev_err(&pdev->dev, "unable to allocate private data"); + return -ENOMEM; + } + + priv->clk = devm_clk_get(&pdev->dev, NULL); + + host = sdhci_pltfm_init(pdev, &sdhci_dove_pdata, 0); + if (IS_ERR(host)) + return PTR_ERR(host); + + pltfm_host = sdhci_priv(host); + pltfm_host->priv = priv; + + if (!IS_ERR(priv->clk)) + clk_prepare_enable(priv->clk); + + ret = mmc_of_parse(host->mmc); + if (ret) + goto err_sdhci_add; + + ret = sdhci_add_host(host); + if (ret) + goto err_sdhci_add; + + return 0; + +err_sdhci_add: + if (!IS_ERR(priv->clk)) + clk_disable_unprepare(priv->clk); + sdhci_pltfm_free(pdev); + return ret; +} + +static int sdhci_dove_remove(struct platform_device *pdev) +{ + struct sdhci_host *host = platform_get_drvdata(pdev); + struct sdhci_pltfm_host *pltfm_host = sdhci_priv(host); + struct sdhci_dove_priv *priv = pltfm_host->priv; + + sdhci_pltfm_unregister(pdev); + + if (!IS_ERR(priv->clk)) + clk_disable_unprepare(priv->clk); + + return 0; +} + +static const struct of_device_id sdhci_dove_of_match_table[] = { + { .compatible = "marvell,dove-sdhci", }, + {} +}; +MODULE_DEVICE_TABLE(of, sdhci_dove_of_match_table); + +static struct platform_driver sdhci_dove_driver = { + .driver = { + .name = "sdhci-dove", + .owner = THIS_MODULE, + .pm = SDHCI_PLTFM_PMOPS, + .of_match_table = sdhci_dove_of_match_table, + }, + .probe = sdhci_dove_probe, + .remove = sdhci_dove_remove, +}; + +module_platform_driver(sdhci_dove_driver); + +MODULE_DESCRIPTION("SDHCI driver for Dove"); +MODULE_AUTHOR("Saeed Bishara , " + "Mike Rapoport "); +MODULE_LICENSE("GPL v2"); diff --git a/pool/shard004/C/0099003_fsl_phy.c b/pool/shard004/C/0099003_fsl_phy.c new file mode 100644 index 0000000000000000000000000000000000000000..a5bef533d5fd743d983cfd1655de21a4635d0749 --- /dev/null +++ b/pool/shard004/C/0099003_fsl_phy.c @@ -0,0 +1,310 @@ +/* + * Copyright (c) 2015, Freescale Semiconductor, Inc. + * Copyright 2016-2017 NXP + * + * 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 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 "fsl_phy.h" + +/******************************************************************************* + * Definitions + ******************************************************************************/ + +/*! @brief Defines the timeout macro. */ +#define PHY_TIMEOUT_COUNT 0xFFFFFU + +/******************************************************************************* + * Prototypes + ******************************************************************************/ + +/*! + * @brief Get the ENET instance from peripheral base address. + * + * @param base ENET peripheral base address. + * @return ENET instance. + */ +extern uint32_t ENET_GetInstance(ENET_Type *base); + +/******************************************************************************* + * Variables + ******************************************************************************/ + +#if !(defined(FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL) && FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL) +/*! @brief Pointers to enet clocks for each instance. */ +extern clock_ip_name_t s_enetClock[FSL_FEATURE_SOC_ENET_COUNT]; +#endif /* FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL */ + +/******************************************************************************* + * Code + ******************************************************************************/ + +status_t PHY_Init(ENET_Type *base, uint32_t phyAddr, uint32_t srcClock_Hz) +{ + uint32_t bssReg; + uint32_t counter = PHY_TIMEOUT_COUNT; + uint32_t idReg = 0; + status_t result = kStatus_Success; + uint32_t instance = ENET_GetInstance(base); + +#if !(defined(FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL) && FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL) + /* Set SMI first. */ + CLOCK_EnableClock(s_enetClock[instance]); +#endif /* FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL */ + ENET_SetSMI(base, srcClock_Hz, false); + + /* Initialization after PHY stars to work. */ + while ((idReg != PHY_CONTROL_ID1) && (counter != 0)) + { + PHY_Read(base, phyAddr, PHY_ID1_REG, &idReg); + counter --; + } + + if (!counter) + { + return kStatus_Fail; + } + + /* Reset PHY. */ + counter = PHY_TIMEOUT_COUNT; + result = PHY_Write(base, phyAddr, PHY_BASICCONTROL_REG, PHY_BCTL_RESET_MASK); + if (result == kStatus_Success) + { + /* Set the negotiation. */ + result = PHY_Write(base, phyAddr, PHY_AUTONEG_ADVERTISE_REG, + (PHY_100BASETX_FULLDUPLEX_MASK | PHY_100BASETX_HALFDUPLEX_MASK | + PHY_10BASETX_FULLDUPLEX_MASK | PHY_10BASETX_HALFDUPLEX_MASK | 0x1U)); + if (result == kStatus_Success) + { + result = PHY_Write(base, phyAddr, PHY_BASICCONTROL_REG, + (PHY_BCTL_AUTONEG_MASK | PHY_BCTL_RESTART_AUTONEG_MASK)); + if (result == kStatus_Success) + { + /* Check auto negotiation complete. */ + while (counter --) + { + result = PHY_Read(base, phyAddr, PHY_BASICSTATUS_REG, &bssReg); + if ( result == kStatus_Success) + { + if ((bssReg & PHY_BSTATUS_AUTONEGCOMP_MASK) != 0) + { + break; + } + } + + if (!counter) + { + return kStatus_PHY_AutoNegotiateFail; + } + } + } + } + } + + return result; +} + +status_t PHY_Write(ENET_Type *base, uint32_t phyAddr, uint32_t phyReg, uint32_t data) +{ + uint32_t counter; + + /* Clear the SMI interrupt event. */ + ENET_ClearInterruptStatus(base, ENET_EIR_MII_MASK); + + /* Starts a SMI write command. */ + ENET_StartSMIWrite(base, phyAddr, phyReg, kENET_MiiWriteValidFrame, data); + + /* Wait for SMI complete. */ + for (counter = PHY_TIMEOUT_COUNT; counter > 0; counter--) + { + if (ENET_GetInterruptStatus(base) & ENET_EIR_MII_MASK) + { + break; + } + } + + /* Check for timeout. */ + if (!counter) + { + return kStatus_PHY_SMIVisitTimeout; + } + + /* Clear MII interrupt event. */ + ENET_ClearInterruptStatus(base, ENET_EIR_MII_MASK); + + return kStatus_Success; +} + +status_t PHY_Read(ENET_Type *base, uint32_t phyAddr, uint32_t phyReg, uint32_t *dataPtr) +{ + assert(dataPtr); + + uint32_t counter; + + /* Clear the MII interrupt event. */ + ENET_ClearInterruptStatus(base, ENET_EIR_MII_MASK); + + /* Starts a SMI read command operation. */ + ENET_StartSMIRead(base, phyAddr, phyReg, kENET_MiiReadValidFrame); + + /* Wait for MII complete. */ + for (counter = PHY_TIMEOUT_COUNT; counter > 0; counter--) + { + if (ENET_GetInterruptStatus(base) & ENET_EIR_MII_MASK) + { + break; + } + } + + /* Check for timeout. */ + if (!counter) + { + return kStatus_PHY_SMIVisitTimeout; + } + + /* Get data from MII register. */ + *dataPtr = ENET_ReadSMIData(base); + + /* Clear MII interrupt event. */ + ENET_ClearInterruptStatus(base, ENET_EIR_MII_MASK); + + return kStatus_Success; +} + +status_t PHY_EnableLoopback(ENET_Type *base, uint32_t phyAddr, phy_loop_t mode, bool enable) +{ + status_t result; + uint32_t data = 0; + + /* Set the loop mode. */ + if (enable) + { + if (mode == kPHY_LocalLoop) + { + /* First read the current status in control register. */ + result = PHY_Read(base, phyAddr, PHY_BASICCONTROL_REG, &data); + if (result == kStatus_Success) + { + return PHY_Write(base, phyAddr, PHY_BASICCONTROL_REG, (data | PHY_BCTL_LOOP_MASK)); + } + } + else + { + /* First read the current status in control register. */ + result = PHY_Read(base, phyAddr, PHY_CONTROL2_REG, &data); + if (result == kStatus_Success) + { + return PHY_Write(base, phyAddr, PHY_CONTROL2_REG, (data | PHY_CTL2_REMOTELOOP_MASK)); + } + } + } + else + { + /* Disable the loop mode. */ + if (mode == kPHY_LocalLoop) + { + /* First read the current status in the basic control register. */ + result = PHY_Read(base, phyAddr, PHY_BASICCONTROL_REG, &data); + if (result == kStatus_Success) + { + return PHY_Write(base, phyAddr, PHY_BASICCONTROL_REG, (data & ~PHY_BCTL_LOOP_MASK)); + } + } + else + { + /* First read the current status in control one register. */ + result = PHY_Read(base, phyAddr, PHY_CONTROL2_REG, &data); + if (result == kStatus_Success) + { + return PHY_Write(base, phyAddr, PHY_CONTROL2_REG, (data & ~PHY_CTL2_REMOTELOOP_MASK)); + } + } + } + return result; +} + +status_t PHY_GetLinkStatus(ENET_Type *base, uint32_t phyAddr, bool *status) +{ + assert(status); + + status_t result = kStatus_Success; + uint32_t data; + + /* Read the basic status register. */ + result = PHY_Read(base, phyAddr, PHY_BASICSTATUS_REG, &data); + if (result == kStatus_Success) + { + if (!(PHY_BSTATUS_LINKSTATUS_MASK & data)) + { + /* link down. */ + *status = false; + } + else + { + /* link up. */ + *status = true; + } + } + return result; +} + +status_t PHY_GetLinkSpeedDuplex(ENET_Type *base, uint32_t phyAddr, phy_speed_t *speed, phy_duplex_t *duplex) +{ + assert(duplex); + + status_t result = kStatus_Success; + uint32_t data, ctlReg; + + /* Read the control two register. */ + result = PHY_Read(base, phyAddr, PHY_CONTROL1_REG, &ctlReg); + if (result == kStatus_Success) + { + data = ctlReg & PHY_CTL1_SPEEDUPLX_MASK; + if ((PHY_CTL1_10FULLDUPLEX_MASK == data) || (PHY_CTL1_100FULLDUPLEX_MASK == data)) + { + /* Full duplex. */ + *duplex = kPHY_FullDuplex; + } + else + { + /* Half duplex. */ + *duplex = kPHY_HalfDuplex; + } + + data = ctlReg & PHY_CTL1_SPEEDUPLX_MASK; + if ((PHY_CTL1_100HALFDUPLEX_MASK == data) || (PHY_CTL1_100FULLDUPLEX_MASK == data)) + { + /* 100M speed. */ + *speed = kPHY_Speed100M; + } + else + { /* 10M speed. */ + *speed = kPHY_Speed10M; + } + } + + return result; +} diff --git a/pool/shard004/C/0099008_mx31moboard-smartbot.c b/pool/shard004/C/0099008_mx31moboard-smartbot.c new file mode 100644 index 0000000000000000000000000000000000000000..35f806e737c155e55f987ddba628b47c2dcedbb7 --- /dev/null +++ b/pool/shard004/C/0099008_mx31moboard-smartbot.c @@ -0,0 +1,210 @@ +/* + * Copyright (C) 2009 Valentin Longchamp, EPFL Mobots group + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + */ + +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +#include +#include +#include +#include +#include + +#include + +#include "devices-imx31.h" +#include "devices.h" + +static unsigned int smartbot_pins[] = { + /* UART1 */ + MX31_PIN_CTS2__CTS2, MX31_PIN_RTS2__RTS2, + MX31_PIN_TXD2__TXD2, MX31_PIN_RXD2__RXD2, + /* CSI */ + MX31_PIN_CSI_D4__CSI_D4, MX31_PIN_CSI_D5__CSI_D5, + MX31_PIN_CSI_D6__CSI_D6, MX31_PIN_CSI_D7__CSI_D7, + MX31_PIN_CSI_D8__CSI_D8, MX31_PIN_CSI_D9__CSI_D9, + MX31_PIN_CSI_D10__CSI_D10, MX31_PIN_CSI_D11__CSI_D11, + MX31_PIN_CSI_D12__CSI_D12, MX31_PIN_CSI_D13__CSI_D13, + MX31_PIN_CSI_D14__CSI_D14, MX31_PIN_CSI_D15__CSI_D15, + MX31_PIN_CSI_HSYNC__CSI_HSYNC, MX31_PIN_CSI_MCLK__CSI_MCLK, + MX31_PIN_CSI_PIXCLK__CSI_PIXCLK, MX31_PIN_CSI_VSYNC__CSI_VSYNC, + MX31_PIN_GPIO3_0__GPIO3_0, MX31_PIN_GPIO3_1__GPIO3_1, + /* ENABLES */ + MX31_PIN_DTR_DCE1__GPIO2_8, MX31_PIN_DSR_DCE1__GPIO2_9, + MX31_PIN_RI_DCE1__GPIO2_10, MX31_PIN_DCD_DCE1__GPIO2_11, +}; + +static const struct imxuart_platform_data uart_pdata __initconst = { + .flags = IMXUART_HAVE_RTSCTS, +}; + +#define CAM_POWER IOMUX_TO_GPIO(MX31_PIN_GPIO3_1) +#define CAM_RST_B IOMUX_TO_GPIO(MX31_PIN_GPIO3_0) + +static int smartbot_cam_power(struct device *dev, int on) +{ + gpio_set_value(CAM_POWER, !on); + return 0; +} + +static int smartbot_cam_reset(struct device *dev) +{ + gpio_set_value(CAM_RST_B, 0); + udelay(100); + gpio_set_value(CAM_RST_B, 1); + return 0; +} + +static struct i2c_board_info smartbot_i2c_devices[] = { + { + I2C_BOARD_INFO("mt9t031", 0x5d), + }, +}; + +static struct soc_camera_link base_iclink = { + .bus_id = 0, /* Must match with the camera ID */ + .power = smartbot_cam_power, + .reset = smartbot_cam_reset, + .board_info = &smartbot_i2c_devices[0], + .i2c_adapter_id = 0, +}; + +static struct platform_device smartbot_camera[] = { + { + .name = "soc-camera-pdrv", + .id = 0, + .dev = { + .platform_data = &base_iclink, + }, + }, +}; + +static struct platform_device *smartbot_cameras[] __initdata = { + &smartbot_camera[0], +}; + +static int __init smartbot_cam_init(void) +{ + int ret = gpio_request(CAM_RST_B, "cam-reset"); + if (ret) + return ret; + gpio_direction_output(CAM_RST_B, 1); + ret = gpio_request(CAM_POWER, "cam-standby"); + if (ret) + return ret; + gpio_direction_output(CAM_POWER, 0); + + return 0; +} + +static const struct fsl_usb2_platform_data usb_pdata __initconst = { + .operating_mode = FSL_USB2_DR_DEVICE, + .phy_mode = FSL_USB2_PHY_ULPI, +}; + +#if defined(CONFIG_USB_ULPI) + +static int smartbot_otg_init(struct platform_device *pdev) +{ + return mx31_initialize_usb_hw(pdev->id, MXC_EHCI_POWER_PINS_ENABLED); +} + +static struct mxc_usbh_platform_data otg_host_pdata __initdata = { + .init = smartbot_otg_init, + .portsc = MXC_EHCI_MODE_ULPI | MXC_EHCI_UTMI_8BIT, +}; + +static int __init smartbot_otg_host_init(void) +{ + struct platform_device *pdev; + + otg_host_pdata.otg = imx_otg_ulpi_create(ULPI_OTG_DRVVBUS | + ULPI_OTG_DRVVBUS_EXT); + if (!otg_host_pdata.otg) + return -ENODEV; + + pdev = imx31_add_mxc_ehci_otg(&otg_host_pdata); + if (IS_ERR(pdev)) + return PTR_ERR(pdev); + + return 0; +} +#else +static inline int smartbot_otg_host_init(void) { return 0; } +#endif + +#define POWER_EN IOMUX_TO_GPIO(MX31_PIN_DTR_DCE1) +#define DSPIC_RST_B IOMUX_TO_GPIO(MX31_PIN_DSR_DCE1) +#define TRSLAT_RST_B IOMUX_TO_GPIO(MX31_PIN_RI_DCE1) +#define TRSLAT_SRC_CHOICE IOMUX_TO_GPIO(MX31_PIN_DCD_DCE1) + +static void smartbot_resets_init(void) +{ + if (!gpio_request(POWER_EN, "power-enable")) { + gpio_direction_output(POWER_EN, 0); + gpio_export(POWER_EN, false); + } + + if (!gpio_request(DSPIC_RST_B, "dspic-rst")) { + gpio_direction_output(DSPIC_RST_B, 0); + gpio_export(DSPIC_RST_B, false); + } + + if (!gpio_request(TRSLAT_RST_B, "translator-rst")) { + gpio_direction_output(TRSLAT_RST_B, 0); + gpio_export(TRSLAT_RST_B, false); + } + + if (!gpio_request(TRSLAT_SRC_CHOICE, "translator-src-choice")) { + gpio_direction_output(TRSLAT_SRC_CHOICE, 0); + gpio_export(TRSLAT_SRC_CHOICE, false); + } +} +/* + * system init for baseboard usage. Will be called by mx31moboard init. + */ +void __init mx31moboard_smartbot_init(int board) +{ + printk(KERN_INFO "Initializing mx31smartbot peripherals\n"); + + mxc_iomux_setup_multiple_pins(smartbot_pins, ARRAY_SIZE(smartbot_pins), + "smartbot"); + + imx31_add_imx_uart1(&uart_pdata); + + switch (board) { + case MX31SMARTBOT: + imx31_add_fsl_usb2_udc(&usb_pdata); + break; + case MX31EYEBOT: + smartbot_otg_host_init(); + break; + default: + printk(KERN_WARNING "Unknown board %d, USB OTG not initialized", + board); + } + + smartbot_resets_init(); + + smartbot_cam_init(); + platform_add_devices(smartbot_cameras, ARRAY_SIZE(smartbot_cameras)); +} diff --git a/pool/shard004/C/0099012_br_input.c b/pool/shard004/C/0099012_br_input.c new file mode 100644 index 0000000000000000000000000000000000000000..420bbb9955e93fa2480393292e7b2705d1cc7a28 --- /dev/null +++ b/pool/shard004/C/0099012_br_input.c @@ -0,0 +1,170 @@ +/* + * Handle incoming frames + * Linux ethernet bridge + * + * Authors: + * Lennert Buytenhek + * + * $Id: br_input.c,v 1.10 2001/12/24 04:50:20 davem Exp $ + * + * 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 "br_private.h" + +/* Bridge group multicast address 802.1d (pg 51). */ +const u8 br_group_address[ETH_ALEN] = { 0x01, 0x80, 0xc2, 0x00, 0x00, 0x00 }; + +static void br_pass_frame_up(struct net_bridge *br, struct sk_buff *skb) +{ + struct net_device *indev; + + br->statistics.rx_packets++; + br->statistics.rx_bytes += skb->len; + + indev = skb->dev; + skb->dev = br->dev; + + NF_HOOK(PF_BRIDGE, NF_BR_LOCAL_IN, skb, indev, NULL, + netif_receive_skb); +} + +/* note: already called with rcu_read_lock (preempt_disabled) */ +int br_handle_frame_finish(struct sk_buff *skb) +{ + const unsigned char *dest = eth_hdr(skb)->h_dest; + struct net_bridge_port *p = rcu_dereference(skb->dev->br_port); + struct net_bridge *br; + struct net_bridge_fdb_entry *dst; + int passedup = 0; + + if (!p || p->state == BR_STATE_DISABLED) + goto drop; + + /* insert into forwarding database after filtering to avoid spoofing */ + br = p->br; + br_fdb_update(br, p, eth_hdr(skb)->h_source); + + if (p->state == BR_STATE_LEARNING) + goto drop; + + if (br->dev->flags & IFF_PROMISC) { + struct sk_buff *skb2; + + skb2 = skb_clone(skb, GFP_ATOMIC); + if (skb2 != NULL) { + passedup = 1; + br_pass_frame_up(br, skb2); + } + } + + if (is_multicast_ether_addr(dest)) { + br->statistics.multicast++; + br_flood_forward(br, skb, !passedup); + if (!passedup) + br_pass_frame_up(br, skb); + goto out; + } + + dst = __br_fdb_get(br, dest); + if (dst != NULL && dst->is_local) { + if (!passedup) + br_pass_frame_up(br, skb); + else + kfree_skb(skb); + goto out; + } + + if (dst != NULL) { + br_forward(dst->dst, skb); + goto out; + } + + br_flood_forward(br, skb, 0); + +out: + return 0; +drop: + kfree_skb(skb); + goto out; +} + +/* note: already called with rcu_read_lock (preempt_disabled) */ +static int br_handle_local_finish(struct sk_buff *skb) +{ + struct net_bridge_port *p = rcu_dereference(skb->dev->br_port); + + if (p && p->state != BR_STATE_DISABLED) + br_fdb_update(p->br, p, eth_hdr(skb)->h_source); + + return 0; /* process further */ +} + +/* Does address match the link local multicast address. + * 01:80:c2:00:00:0X + */ +static inline int is_link_local(const unsigned char *dest) +{ + const u16 *a = (const u16 *) dest; + static const u16 *const b = (const u16 *const ) br_group_address; + static const u16 m = __constant_cpu_to_be16(0xfff0); + + return ((a[0] ^ b[0]) | (a[1] ^ b[1]) | ((a[2] ^ b[2]) & m)) == 0; +} + +/* + * Called via br_handle_frame_hook. + * Return NULL if skb is handled + * note: already called with rcu_read_lock (preempt_disabled) + */ +struct sk_buff *br_handle_frame(struct net_bridge_port *p, struct sk_buff *skb) +{ + const unsigned char *dest = eth_hdr(skb)->h_dest; + + if (!is_valid_ether_addr(eth_hdr(skb)->h_source)) + goto drop; + + if (unlikely(is_link_local(dest))) { + /* Pause frames shouldn't be passed up by driver anyway */ + if (skb->protocol == htons(ETH_P_PAUSE)) + goto drop; + + /* Process STP BPDU's through normal netif_receive_skb() path */ + if (p->br->stp_enabled != BR_NO_STP) { + if (NF_HOOK(PF_BRIDGE, NF_BR_LOCAL_IN, skb, skb->dev, + NULL, br_handle_local_finish)) + return NULL; + else + return skb; + } + } + + switch (p->state) { + case BR_STATE_FORWARDING: + + if (br_should_route_hook) { + if (br_should_route_hook(&skb)) + return skb; + dest = eth_hdr(skb)->h_dest; + } + /* fall through */ + case BR_STATE_LEARNING: + if (!compare_ether_addr(p->br->dev->dev_addr, dest)) + skb->pkt_type = PACKET_HOST; + + NF_HOOK(PF_BRIDGE, NF_BR_PRE_ROUTING, skb, skb->dev, NULL, + br_handle_frame_finish); + break; + default: +drop: + kfree_skb(skb); + } + return NULL; +} diff --git a/pool/shard004/C/0099015_of_gpio.c b/pool/shard004/C/0099015_of_gpio.c new file mode 100644 index 0000000000000000000000000000000000000000..dc8ae22776413d846adae5011bddbbaf33c164b3 --- /dev/null +++ b/pool/shard004/C/0099015_of_gpio.c @@ -0,0 +1,54 @@ +#include +#include +#include +#include +#include + +/** + * of_get_named_gpio_flags() - Get a GPIO number and flags to use with GPIO API + * @np: device node to get GPIO from + * @propname: property name containing gpio specifier(s) + * @index: index of the GPIO + * @flags: a flags pointer to fill in + * + * Returns GPIO number to use with GPIO API, or one of the errno value on the + * error condition. If @flags is not NULL the function also fills in flags for + * the GPIO. + */ +int of_get_named_gpio_flags(struct device_node *np, const char *propname, + int index, enum of_gpio_flags *flags) +{ + struct of_phandle_args out_args; + struct device_d *dev; + int ret; + + ret = of_parse_phandle_with_args(np, propname, "#gpio-cells", + index, &out_args); + if (ret) { + pr_debug("%s: cannot parse %s property: %d\n", + __func__, propname, ret); + return ret; + } + + dev = of_find_device_by_node(out_args.np); + if (!dev) { + pr_debug("%s: unable to find device of node %s\n", + __func__, out_args.np->full_name); + return -EPROBE_DEFER; + } + + ret = gpio_get_num(dev, out_args.args[0]); + if (ret == -EPROBE_DEFER) + return ret; + if (ret < 0) { + pr_err("%s: unable to get gpio num of device %s: %d\n", + __func__, dev_name(dev), ret); + return ret; + } + + if (flags) + *flags = out_args.args[1]; + + return ret; +} +EXPORT_SYMBOL(of_get_named_gpio_flags); diff --git a/pool/shard004/C/0099017_traps.c b/pool/shard004/C/0099017_traps.c new file mode 100644 index 0000000000000000000000000000000000000000..b0be93b5a0ad9b30f6884a9f11dcdd5b262404a9 --- /dev/null +++ b/pool/shard004/C/0099017_traps.c @@ -0,0 +1,237 @@ +/* Lattice Mico32 exception and system call support. + Contributed by Jon Beniston + + Copyright (C) 2009-2016 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 . */ + +#define WANT_CPU lm32bf +#define WANT_CPU_LM32BF + +#include "sim-main.h" +#include "sim-syscall.h" +#include "lm32-sim.h" +#include "targ-vals.h" + +/* Handle invalid instructions. */ + +SEM_PC +sim_engine_invalid_insn (SIM_CPU * current_cpu, IADDR cia, SEM_PC pc) +{ + SIM_DESC sd = CPU_STATE (current_cpu); + + sim_engine_halt (sd, current_cpu, NULL, cia, sim_stopped, SIM_SIGILL); + + return pc; +} + +/* Handle divide instructions. */ + +USI +lm32bf_divu_insn (SIM_CPU * current_cpu, IADDR pc, USI r0, USI r1, USI r2) +{ + SIM_DESC sd = CPU_STATE (current_cpu); + host_callback *cb = STATE_CALLBACK (sd); + + /* Check for divide by zero */ + if (GET_H_GR (r1) == 0) + { + if (STATE_ENVIRONMENT (sd) != OPERATING_ENVIRONMENT) + sim_engine_halt (sd, current_cpu, NULL, pc, sim_stopped, SIM_SIGFPE); + else + { + /* Save PC in exception address register. */ + SET_H_GR (30, pc); + /* Save and clear interrupt enable. */ + SET_H_CSR (LM32_CSR_IE, (GET_H_CSR (LM32_CSR_IE) & 1) << 1); + /* Branch to divide by zero exception handler. */ + return GET_H_CSR (LM32_CSR_EBA) + LM32_EID_DIVIDE_BY_ZERO * 32; + } + } + else + { + SET_H_GR (r2, (USI) GET_H_GR (r0) / (USI) GET_H_GR (r1)); + return pc + 4; + } +} + +USI +lm32bf_modu_insn (SIM_CPU * current_cpu, IADDR pc, USI r0, USI r1, USI r2) +{ + SIM_DESC sd = CPU_STATE (current_cpu); + host_callback *cb = STATE_CALLBACK (sd); + + /* Check for divide by zero. */ + if (GET_H_GR (r1) == 0) + { + if (STATE_ENVIRONMENT (sd) != OPERATING_ENVIRONMENT) + sim_engine_halt (sd, current_cpu, NULL, pc, sim_stopped, SIM_SIGFPE); + else + { + /* Save PC in exception address register. */ + SET_H_GR (30, pc); + /* Save and clear interrupt enable. */ + SET_H_CSR (LM32_CSR_IE, (GET_H_CSR (LM32_CSR_IE) & 1) << 1); + /* Branch to divide by zero exception handler. */ + return GET_H_CSR (LM32_CSR_EBA) + LM32_EID_DIVIDE_BY_ZERO * 32; + } + } + else + { + SET_H_GR (r2, (USI) GET_H_GR (r0) % (USI) GET_H_GR (r1)); + return pc + 4; + } +} + +/* Handle break instructions. */ + +USI +lm32bf_break_insn (SIM_CPU * current_cpu, IADDR pc) +{ + SIM_DESC sd = CPU_STATE (current_cpu); + host_callback *cb = STATE_CALLBACK (sd); + /* Breakpoint. */ + if (STATE_ENVIRONMENT (sd) != OPERATING_ENVIRONMENT) + { + sim_engine_halt (sd, current_cpu, NULL, pc, sim_stopped, SIM_SIGTRAP); + return pc; + } + else + { + /* Save PC in breakpoint address register. */ + SET_H_GR (31, pc); + /* Save and clear interrupt enable. */ + SET_H_CSR (LM32_CSR_IE, (GET_H_CSR (LM32_CSR_IE) & 1) << 2); + /* Branch to breakpoint exception handler. */ + return GET_H_CSR (LM32_CSR_DEBA) + LM32_EID_BREAKPOINT * 32; + } +} + +/* Handle scall instructions. */ + +USI +lm32bf_scall_insn (SIM_CPU * current_cpu, IADDR pc) +{ + SIM_DESC sd = CPU_STATE (current_cpu); + host_callback *cb = STATE_CALLBACK (sd); + + if ((STATE_ENVIRONMENT (sd) != OPERATING_ENVIRONMENT) + || (GET_H_GR (8) == TARGET_SYS_exit)) + { + /* Delegate system call to host O/S. */ + long result, result2; + int errcode; + + /* Perform the system call. */ + sim_syscall_multi (current_cpu, GET_H_GR (8), GET_H_GR (1), GET_H_GR (2), + GET_H_GR (3), GET_H_GR (4), &result, &result2, + &errcode); + /* Store the return value in the CPU's registers. */ + SET_H_GR (1, result); + SET_H_GR (2, result2); + SET_H_GR (3, errcode); + + /* Skip over scall instruction. */ + return pc + 4; + } + else + { + /* Save PC in exception address register. */ + SET_H_GR (30, pc); + /* Save and clear interrupt enable */ + SET_H_CSR (LM32_CSR_IE, (GET_H_CSR (LM32_CSR_IE) & 1) << 1); + /* Branch to system call exception handler. */ + return GET_H_CSR (LM32_CSR_EBA) + LM32_EID_SYSTEM_CALL * 32; + } +} + +/* Handle b instructions. */ + +USI +lm32bf_b_insn (SIM_CPU * current_cpu, USI r0, USI f_r0) +{ + SIM_DESC sd = CPU_STATE (current_cpu); + host_callback *cb = STATE_CALLBACK (sd); + + /* Restore interrupt enable. */ + if (f_r0 == 30) + SET_H_CSR (LM32_CSR_IE, (GET_H_CSR (LM32_CSR_IE) & 2) >> 1); + else if (f_r0 == 31) + SET_H_CSR (LM32_CSR_IE, (GET_H_CSR (LM32_CSR_IE) & 4) >> 2); + return r0; +} + +/* Handle wcsr instructions. */ + +void +lm32bf_wcsr_insn (SIM_CPU * current_cpu, USI f_csr, USI r1) +{ + SIM_DESC sd = CPU_STATE (current_cpu); + host_callback *cb = STATE_CALLBACK (sd); + + /* Writing a 1 to IP CSR clears a bit, writing 0 has no effect. */ + if (f_csr == LM32_CSR_IP) + SET_H_CSR (f_csr, GET_H_CSR (f_csr) & ~r1); + else + SET_H_CSR (f_csr, r1); +} + +/* Handle signals. */ + +void +lm32_core_signal (SIM_DESC sd, + sim_cpu * cpu, + sim_cia cia, + unsigned map, + int nr_bytes, + address_word addr, + transfer_type transfer, sim_core_signals sig) +{ + const char *copy = (transfer == read_transfer ? "read" : "write"); + address_word ip = CIA_ADDR (cia); + SIM_CPU *current_cpu = cpu; + + switch (sig) + { + case sim_core_unmapped_signal: + sim_io_eprintf (sd, + "core: %d byte %s to unmapped address 0x%lx at 0x%lx\n", + nr_bytes, copy, (unsigned long) addr, + (unsigned long) ip); + SET_H_GR (30, ip); + /* Save and clear interrupt enable. */ + SET_H_CSR (LM32_CSR_IE, (GET_H_CSR (LM32_CSR_IE) & 1) << 1); + CPU_PC_SET (cpu, GET_H_CSR (LM32_CSR_EBA) + LM32_EID_DATA_BUS_ERROR * 32); + sim_engine_halt (sd, cpu, NULL, LM32_EID_DATA_BUS_ERROR * 32, + sim_stopped, SIM_SIGSEGV); + break; + case sim_core_unaligned_signal: + sim_io_eprintf (sd, + "core: %d byte misaligned %s to address 0x%lx at 0x%lx\n", + nr_bytes, copy, (unsigned long) addr, + (unsigned long) ip); + SET_H_GR (30, ip); + /* Save and clear interrupt enable. */ + SET_H_CSR (LM32_CSR_IE, (GET_H_CSR (LM32_CSR_IE) & 1) << 1); + CPU_PC_SET (cpu, GET_H_CSR (LM32_CSR_EBA) + LM32_EID_DATA_BUS_ERROR * 32); + sim_engine_halt (sd, cpu, NULL, LM32_EID_DATA_BUS_ERROR * 32, + sim_stopped, SIM_SIGBUS); + break; + default: + sim_engine_abort (sd, cpu, cia, + "sim_core_signal - internal error - bad switch"); + } +} diff --git a/pool/shard004/C/0099019_vmm_percpu.c b/pool/shard004/C/0099019_vmm_percpu.c new file mode 100644 index 0000000000000000000000000000000000000000..69a5be76d64cb3a9cd4223636e2a3bafe4760151 --- /dev/null +++ b/pool/shard004/C/0099019_vmm_percpu.c @@ -0,0 +1,71 @@ +/** + * Copyright (c) 2012 Anup Patel. + * All rights reserved. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2, 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. + * + * @file vmm_percpu.c + * @author Anup Patel (anup@brainfault.org) + * @brief Implementation of per-cpu areas + */ + +#include +#include +#include +#include +#include +#include + +#ifdef CONFIG_SMP + +virtual_addr_t __percpu_vaddr[CONFIG_CPU_COUNT] = { 0 }; +virtual_addr_t __percpu_offset[CONFIG_CPU_COUNT] = { 0 }; + +int __init vmm_percpu_init(void) +{ + u32 cpu, pgcount; + virtual_addr_t base = arch_percpu_vaddr(); + virtual_size_t size = arch_percpu_size(); + + size = VMM_ROUNDUP2_PAGE_SIZE(size); + pgcount = size / VMM_PAGE_SIZE; + + __percpu_vaddr[0] = base; + __percpu_offset[0] = 0; + for_each_possible_cpu(cpu){ + if (cpu == 0) { + continue; + } + __percpu_vaddr[cpu] = vmm_host_alloc_pages(pgcount, + VMM_MEMORY_FLAGS_NORMAL); + if (!__percpu_vaddr[cpu]) { + return VMM_ENOMEM; + } + __percpu_offset[cpu] = __percpu_vaddr[cpu] - base; + memset((void *)__percpu_vaddr[cpu], 0, VMM_PAGE_SIZE * pgcount); + } + + return VMM_OK; +} + +#else + +int __init vmm_percpu_init(void) +{ + /* Don't require to do anything for UP */ + return VMM_OK; +} + +#endif diff --git a/pool/shard004/C/0099024_CWE126_Buffer_Overread__malloc_wchar_t_memmove_11.c b/pool/shard004/C/0099024_CWE126_Buffer_Overread__malloc_wchar_t_memmove_11.c new file mode 100644 index 0000000000000000000000000000000000000000..66cde4c539fd9fc577176cce1dfe16a5318d5eca --- /dev/null +++ b/pool/shard004/C/0099024_CWE126_Buffer_Overread__malloc_wchar_t_memmove_11.c @@ -0,0 +1,139 @@ +/* TEMPLATE GENERATED TESTCASE FILE +Filename: CWE126_Buffer_Overread__malloc_wchar_t_memmove_11.c +Label Definition File: CWE126_Buffer_Overread__malloc.label.xml +Template File: sources-sink-11.tmpl.c +*/ +/* + * @description + * CWE: 126 Buffer Over-read + * BadSource: Use a small buffer + * GoodSource: Use a large buffer + * Sink: memmove + * BadSink : Copy data to string using memmove + * Flow Variant: 11 Control flow: if(globalReturnsTrue()) and if(globalReturnsFalse()) + * + * */ + +#include "std_testcase.h" + +#include + +#ifndef OMITBAD + +void CWE126_Buffer_Overread__malloc_wchar_t_memmove_11_bad() +{ + wchar_t * data; + data = NULL; + if(globalReturnsTrue()) + { + /* FLAW: Use a small buffer */ + data = (wchar_t *)malloc(50*sizeof(wchar_t)); + wmemset(data, L'A', 50-1); /* fill with 'A's */ + data[50-1] = L'\0'; /* null terminate */ + } + { + wchar_t dest[100]; + wmemset(dest, L'C', 100-1); + dest[100-1] = L'\0'; /* null terminate */ + /* POTENTIAL FLAW: using memmove with the length of the dest where data + * could be smaller than dest causing buffer overread */ + memmove(dest, data, wcslen(dest)*sizeof(wchar_t)); + dest[100-1] = L'\0'; + printWLine(dest); + free(data); + } +} + +#endif /* OMITBAD */ + +#ifndef OMITGOOD + +/* goodG2B1() - use goodsource and badsink by changing the globalReturnsTrue() to globalReturnsFalse() */ +static void goodG2B1() +{ + wchar_t * data; + data = NULL; + if(globalReturnsFalse()) + { + /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */ + printLine("Benign, fixed string"); + } + else + { + /* FIX: Use a large buffer */ + data = (wchar_t *)malloc(100*sizeof(wchar_t)); + wmemset(data, L'A', 100-1); /* fill with 'A's */ + data[100-1] = L'\0'; /* null terminate */ + } + { + wchar_t dest[100]; + wmemset(dest, L'C', 100-1); + dest[100-1] = L'\0'; /* null terminate */ + /* POTENTIAL FLAW: using memmove with the length of the dest where data + * could be smaller than dest causing buffer overread */ + memmove(dest, data, wcslen(dest)*sizeof(wchar_t)); + dest[100-1] = L'\0'; + printWLine(dest); + free(data); + } +} + +/* goodG2B2() - use goodsource and badsink by reversing the blocks in the if statement */ +static void goodG2B2() +{ + wchar_t * data; + data = NULL; + if(globalReturnsTrue()) + { + /* FIX: Use a large buffer */ + data = (wchar_t *)malloc(100*sizeof(wchar_t)); + wmemset(data, L'A', 100-1); /* fill with 'A's */ + data[100-1] = L'\0'; /* null terminate */ + } + { + wchar_t dest[100]; + wmemset(dest, L'C', 100-1); + dest[100-1] = L'\0'; /* null terminate */ + /* POTENTIAL FLAW: using memmove with the length of the dest where data + * could be smaller than dest causing buffer overread */ + memmove(dest, data, wcslen(dest)*sizeof(wchar_t)); + dest[100-1] = L'\0'; + printWLine(dest); + free(data); + } +} + +void CWE126_Buffer_Overread__malloc_wchar_t_memmove_11_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()..."); + CWE126_Buffer_Overread__malloc_wchar_t_memmove_11_good(); + printLine("Finished good()"); +#endif /* OMITGOOD */ +#ifndef OMITBAD + printLine("Calling bad()..."); + CWE126_Buffer_Overread__malloc_wchar_t_memmove_11_bad(); + printLine("Finished bad()"); +#endif /* OMITBAD */ + return 0; +} + +#endif diff --git a/pool/shard004/C/0099031_premake.c b/pool/shard004/C/0099031_premake.c new file mode 100644 index 0000000000000000000000000000000000000000..4a0f4e348300ca098cd4a3be6e61d4f2504863a8 --- /dev/null +++ b/pool/shard004/C/0099031_premake.c @@ -0,0 +1,272 @@ +/** + * \file premake.c + * \brief Program entry point. + * \author Copyright (c) 2002-2010 Jason Perkins and the Premake project + */ + +#include +#include +#include "premake.h" + + +#define VERSION "4.3" +#define COPYRIGHT "Copyright (C) 2002-2010 Jason Perkins and the Premake Project" +#define ERROR_MESSAGE "%s\n" + + +static int process_arguments(lua_State* L, int argc, const char** argv); +static int process_option(lua_State* L, const char* arg); +static int load_builtin_scripts(lua_State* L); + + +/* A search path for script files */ +static const char* scripts_path = NULL; + + +/* precompiled bytecode buffer; in bytecode.c */ +extern const char* builtin_scripts[]; + + +/* Built-in functions */ +static const luaL_Reg path_functions[] = { + { "isabsolute", path_isabsolute }, + { NULL, NULL } +}; + +static const luaL_Reg os_functions[] = { + { "chdir", os_chdir }, + { "copyfile", os_copyfile }, + { "isdir", os_isdir }, + { "getcwd", os_getcwd }, + { "isfile", os_isfile }, + { "matchdone", os_matchdone }, + { "matchisfile", os_matchisfile }, + { "matchname", os_matchname }, + { "matchnext", os_matchnext }, + { "matchstart", os_matchstart }, + { "mkdir", os_mkdir }, + { "pathsearch", os_pathsearch }, + { "rmdir", os_rmdir }, + { "uuid", os_uuid }, + { NULL, NULL } +}; + +static const luaL_Reg string_functions[] = { + { "endswith", string_endswith }, + { NULL, NULL } +}; + + + +/** + * Program entry point. + */ +int main(int argc, const char** argv) +{ + lua_State* L; + int z = OKAY; + + /* prepare Lua for use */ + L = lua_open(); + luaL_openlibs(L); + luaL_register(L, "path", path_functions); + luaL_register(L, "os", os_functions); + luaL_register(L, "string", string_functions); + + /* push the application metadata */ + lua_pushstring(L, LUA_COPYRIGHT); + lua_setglobal(L, "_COPYRIGHT"); + + lua_pushstring(L, VERSION); + lua_setglobal(L, "_PREMAKE_VERSION"); + + lua_pushstring(L, COPYRIGHT); + lua_setglobal(L, "_PREMAKE_COPYRIGHT"); + + /* set the OS platform variable */ + lua_pushstring(L, PLATFORM_STRING); + lua_setglobal(L, "_OS"); + + /* Parse the command line arguments */ + if (z == OKAY) z = process_arguments(L, argc, argv); + + /* Run the built-in Premake scripts */ + if (z == OKAY) z = load_builtin_scripts(L); + + /* Clean up and turn off the lights */ + lua_close(L); + return z; +} + + + +/** + * Process the command line arguments, splitting them into options, the + * target action, and any arguments to that action. The results are pushed + * into the session for later use. I could have done this in the scripts, + * but I need the value of the /scripts option to find them. + * \returns OKAY if successful. + */ +int process_arguments(lua_State* L, int argc, const char** argv) +{ + int i; + + /* Create empty lists for Options and Args */ + lua_newtable(L); + lua_newtable(L); + + for (i = 1; i < argc; ++i) + { + /* Options start with '/' or '--'. The first argument that isn't an option + * is the action. Anything after that is an argument to the action */ + if (argv[i][0] == '/') + { + process_option(L, argv[i] + 1); + } + else if (argv[i][0] == '-' && argv[i][1] == '-') + { + process_option(L, argv[i] + 2); + } + else + { + /* not an option, is the action */ + lua_pushstring(L, argv[i++]); + lua_setglobal(L, "_ACTION"); + + /* everything else is an argument */ + while (i < argc) + { + lua_pushstring(L, argv[i++]); + lua_rawseti(L, -2, luaL_getn(L, -2) + 1); + } + } + } + + /* push the Options and Args lists */ + lua_setglobal(L, "_ARGS"); + lua_setglobal(L, "_OPTIONS"); + return OKAY; +} + + + +/** + * Parse an individual command-line option. + * \returns OKAY if successful. + */ +int process_option(lua_State* L, const char* arg) +{ + char key[512]; + const char* value; + + /* If a value is specified, split the option into a key/value pair */ + char* ptr = strchr(arg, '='); + if (ptr) + { + int len = ptr - arg; + if (len > 511) len = 511; + strncpy(key, arg, len); + key[len] = '\0'; + value = ptr + 1; + } + else + { + strcpy(key, arg); + value = ""; + } + + /* Store it in the Options table, which is already on the stack */ + lua_pushstring(L, value); + lua_setfield(L, -3, key); + + /* The /scripts option gets picked up here to find the built-in scripts */ + if (strcmp(key, "scripts") == 0 && strlen(value) > 0) + { + scripts_path = value; + } + + return OKAY; +} + + + +#if defined(_DEBUG) +/** + * When running in debug mode, the scripts are loaded from the disk. The path to + * the scripts must be provided via either the /scripts command line option or + * the PREMAKE_PATH environment variable. + */ +int load_builtin_scripts(lua_State* L) +{ + const char* filename; + + /* call os.pathsearch() to locate _premake_main.lua */ + lua_pushcfunction(L, os_pathsearch); + lua_pushstring(L, "_premake_main.lua"); + lua_pushstring(L, scripts_path); + lua_pushstring(L, getenv("PREMAKE_PATH")); + lua_call(L, 3, 1); + + if (lua_isnil(L, -1)) + { + printf(ERROR_MESSAGE, + "Unable to find _premake_main.lua; use /scripts option when in debug mode!\n" + "Please refer to the documentation (or build in release mode instead)." + ); + return !OKAY; + } + + /* run the bootstrapping script */ + scripts_path = lua_tostring(L, -1); + filename = lua_pushfstring(L, "%s/_premake_main.lua", scripts_path); + if (luaL_dofile(L, filename)) + { + printf(ERROR_MESSAGE, lua_tostring(L, -1)); + return !OKAY; + } + + /* hand off control to the scripts */ + lua_getglobal(L, "_premake_main"); + lua_pushstring(L, scripts_path); + if (lua_pcall(L, 1, 1, 0) != OKAY) + { + printf(ERROR_MESSAGE, lua_tostring(L, -1)); + return !OKAY; + } + else + { + return (int)lua_tonumber(L, -1); + } +} +#endif + + +#if defined(NDEBUG) +/** + * When running in release mode, the scripts are loaded from a static data + * buffer, where they were stored by a preprocess. To update these embedded + * scripts, run `premake4 embed` then rebuild. + */ +int load_builtin_scripts(lua_State* L) +{ + int i; + for (i = 0; builtin_scripts[i]; ++i) + { + if (luaL_dostring(L, builtin_scripts[i]) != OKAY) + { + printf(ERROR_MESSAGE, lua_tostring(L, -1)); + return !OKAY; + } + } + + /* hand off control to the scripts */ + lua_getglobal(L, "_premake_main"); + if (lua_pcall(L, 0, 1, 0) != OKAY) + { + printf(ERROR_MESSAGE, lua_tostring(L,-1)); + return !OKAY; + } + + return OKAY; +} +#endif diff --git a/pool/shard004/C/0099032_t4k35.c b/pool/shard004/C/0099032_t4k35.c new file mode 100644 index 0000000000000000000000000000000000000000..f3525df9dec4040097a9666a6f37815572b0aa36 --- /dev/null +++ b/pool/shard004/C/0099032_t4k35.c @@ -0,0 +1,179 @@ +/* Copyright (c) 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 "msm_sensor.h" +#define T4K35_SENSOR_NAME "t4k35" +DEFINE_MSM_MUTEX(t4k35_mut); + +static struct msm_sensor_ctrl_t t4k35_s_ctrl; + +static struct msm_sensor_power_setting t4k35_power_setting[] = { + + { + .seq_type = SENSOR_VREG, + .seq_val = CAM_VDIG, + .config_val = 0, + .delay = 0, + }, + { + .seq_type = SENSOR_VREG, + .seq_val = CAM_VIO, + .config_val = 0, + .delay = 0, + }, +#if 1 + { + .seq_type = SENSOR_GPIO, + .seq_val = SENSOR_GPIO_VANA, + .config_val = GPIO_OUT_LOW, + .delay = 1, + }, + { + .seq_type = SENSOR_GPIO, + .seq_val = SENSOR_GPIO_VANA, + .config_val = GPIO_OUT_HIGH, + .delay = 5, + }, +#endif +#if 1 + { + .seq_type = SENSOR_GPIO, + .seq_val = SENSOR_GPIO_RESET, + .config_val = GPIO_OUT_LOW, + .delay = 1, + }, + { + .seq_type = SENSOR_GPIO, + .seq_val = SENSOR_GPIO_RESET, + .config_val = GPIO_OUT_HIGH, + .delay = 30, + }, +#endif + { + .seq_type = SENSOR_GPIO, + .seq_val = SENSOR_GPIO_STANDBY, + .config_val = GPIO_OUT_LOW, + .delay = 1, + }, + { + .seq_type = SENSOR_GPIO, + .seq_val = SENSOR_GPIO_STANDBY, + .config_val = GPIO_OUT_HIGH, + .delay = 30, + }, + { + .seq_type = SENSOR_CLK, + .seq_val = SENSOR_CAM_MCLK, + .config_val = 24000000, + .delay = 1, + }, + { + .seq_type = SENSOR_I2C_MUX, + .seq_val = 0, + .config_val = 0, + .delay = 0, + }, +}; + +static struct v4l2_subdev_info t4k35_subdev_info[] = { + { + .code = V4L2_MBUS_FMT_SBGGR10_1X10, + .colorspace = V4L2_COLORSPACE_JPEG, + .fmt = 1, + .order = 0, + }, +}; + +static const struct i2c_device_id t4k35_i2c_id[] = { + {T4K35_SENSOR_NAME, (kernel_ulong_t)&t4k35_s_ctrl}, + { } +}; + +static int32_t msm_t4k35_i2c_probe(struct i2c_client *client, + const struct i2c_device_id *id) +{ + return msm_sensor_i2c_probe(client, id, &t4k35_s_ctrl); +} + +static struct i2c_driver t4k35_i2c_driver = { + .id_table = t4k35_i2c_id, + .probe = msm_t4k35_i2c_probe, + .driver = { + .name = T4K35_SENSOR_NAME, + }, +}; + +static struct msm_camera_i2c_client t4k35_sensor_i2c_client = { + .addr_type = MSM_CAMERA_I2C_WORD_ADDR, +}; + +static const struct of_device_id t4k35_dt_match[] = { + {.compatible = "qcom,t4k35", .data = &t4k35_s_ctrl}, + {} +}; + +MODULE_DEVICE_TABLE(of, t4k35_dt_match); + +static struct platform_driver t4k35_platform_driver = { + .driver = { + .name = "qcom,t4k35", + .owner = THIS_MODULE, + .of_match_table = t4k35_dt_match, + }, +}; + +static int32_t t4k35_platform_probe(struct platform_device *pdev) +{ + int32_t rc = 0; + const struct of_device_id *match; + match = of_match_device(t4k35_dt_match, &pdev->dev); + rc = msm_sensor_platform_probe(pdev, match->data); + return rc; +} + +static int __init t4k35_init_module(void) +{ + int32_t rc = 0; + pr_info("%s:%d\n", __func__, __LINE__); + rc = platform_driver_probe(&t4k35_platform_driver, + t4k35_platform_probe); + if (!rc) + return rc; + pr_err("%s:%d rc %d\n", __func__, __LINE__, rc); + return i2c_add_driver(&t4k35_i2c_driver); +} + +static void __exit t4k35_exit_module(void) +{ + pr_info("%s:%d\n", __func__, __LINE__); + if (t4k35_s_ctrl.pdev) { + msm_sensor_free_sensor_data(&t4k35_s_ctrl); + platform_driver_unregister(&t4k35_platform_driver); + } else + i2c_del_driver(&t4k35_i2c_driver); + return; +} + +static struct msm_sensor_ctrl_t t4k35_s_ctrl = { + .sensor_i2c_client = &t4k35_sensor_i2c_client, + .power_setting_array.power_setting = t4k35_power_setting, + .power_setting_array.size = ARRAY_SIZE(t4k35_power_setting), + //.zte_otp_enable = true, + .msm_sensor_mutex = &t4k35_mut, + .sensor_v4l2_subdev_info = t4k35_subdev_info, + .sensor_v4l2_subdev_info_size = ARRAY_SIZE(t4k35_subdev_info), +}; + +module_init(t4k35_init_module); +module_exit(t4k35_exit_module); +MODULE_DESCRIPTION("t4k35"); +MODULE_LICENSE("GPL v2"); diff --git a/pool/shard004/C/0099039_rockchip_drm_fbdev.c b/pool/shard004/C/0099039_rockchip_drm_fbdev.c new file mode 100644 index 0000000000000000000000000000000000000000..a16c69f96ed5e6d23004b395e29150d6dc682bdf --- /dev/null +++ b/pool/shard004/C/0099039_rockchip_drm_fbdev.c @@ -0,0 +1,188 @@ +/* + * Copyright (C) Fuzhou Rockchip Electronics Co.Ltd + * Author:Mark Yao + * + * 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 "rockchip_drm_drv.h" +#include "rockchip_drm_gem.h" +#include "rockchip_drm_fb.h" +#include "rockchip_drm_fbdev.h" + +#define PREFERRED_BPP 32 +#define to_drm_private(x) \ + container_of(x, struct rockchip_drm_private, fbdev_helper) + +static int rockchip_fbdev_mmap(struct fb_info *info, + struct vm_area_struct *vma) +{ + struct drm_fb_helper *helper = info->par; + struct rockchip_drm_private *private = to_drm_private(helper); + + return rockchip_gem_mmap_buf(private->fbdev_bo, vma); +} + +static struct fb_ops rockchip_drm_fbdev_ops = { + .owner = THIS_MODULE, + .fb_mmap = rockchip_fbdev_mmap, + .fb_fillrect = drm_fb_helper_cfb_fillrect, + .fb_copyarea = drm_fb_helper_cfb_copyarea, + .fb_imageblit = drm_fb_helper_cfb_imageblit, + .fb_check_var = drm_fb_helper_check_var, + .fb_set_par = drm_fb_helper_set_par, + .fb_blank = drm_fb_helper_blank, + .fb_pan_display = drm_fb_helper_pan_display, + .fb_setcmap = drm_fb_helper_setcmap, +}; + +static int rockchip_drm_fbdev_create(struct drm_fb_helper *helper, + struct drm_fb_helper_surface_size *sizes) +{ + struct rockchip_drm_private *private = to_drm_private(helper); + struct drm_mode_fb_cmd2 mode_cmd = { 0 }; + struct drm_device *dev = helper->dev; + struct rockchip_gem_object *rk_obj; + struct drm_framebuffer *fb; + unsigned int bytes_per_pixel; + unsigned long offset; + struct fb_info *fbi; + size_t size; + int ret; + + bytes_per_pixel = DIV_ROUND_UP(sizes->surface_bpp, 8); + + mode_cmd.width = sizes->surface_width; + mode_cmd.height = sizes->surface_height; + mode_cmd.pitches[0] = sizes->surface_width * bytes_per_pixel; + mode_cmd.pixel_format = drm_mode_legacy_fb_format(sizes->surface_bpp, + sizes->surface_depth); + + size = mode_cmd.pitches[0] * mode_cmd.height; + + rk_obj = rockchip_gem_create_object(dev, size, true); + if (IS_ERR(rk_obj)) + return -ENOMEM; + + private->fbdev_bo = &rk_obj->base; + + fbi = drm_fb_helper_alloc_fbi(helper); + if (IS_ERR(fbi)) { + dev_err(dev->dev, "Failed to create framebuffer info.\n"); + ret = PTR_ERR(fbi); + goto err_rockchip_gem_free_object; + } + + helper->fb = rockchip_drm_framebuffer_init(dev, &mode_cmd, + private->fbdev_bo); + if (IS_ERR(helper->fb)) { + dev_err(dev->dev, "Failed to allocate DRM framebuffer.\n"); + ret = PTR_ERR(helper->fb); + goto err_release_fbi; + } + + fbi->par = helper; + fbi->flags = FBINFO_FLAG_DEFAULT; + fbi->fbops = &rockchip_drm_fbdev_ops; + + fb = helper->fb; + drm_fb_helper_fill_fix(fbi, fb->pitches[0], fb->depth); + drm_fb_helper_fill_var(fbi, helper, sizes->fb_width, sizes->fb_height); + + offset = fbi->var.xoffset * bytes_per_pixel; + offset += fbi->var.yoffset * fb->pitches[0]; + + dev->mode_config.fb_base = 0; + fbi->screen_base = rk_obj->kvaddr + offset; + fbi->screen_size = rk_obj->base.size; + fbi->fix.smem_len = rk_obj->base.size; + + DRM_DEBUG_KMS("FB [%dx%d]-%d kvaddr=%p offset=%ld size=%zu\n", + fb->width, fb->height, fb->depth, rk_obj->kvaddr, + offset, size); + + fbi->skip_vt_switch = true; + + return 0; + +err_release_fbi: + drm_fb_helper_release_fbi(helper); +err_rockchip_gem_free_object: + rockchip_gem_free_object(&rk_obj->base); + return ret; +} + +static const struct drm_fb_helper_funcs rockchip_drm_fb_helper_funcs = { + .fb_probe = rockchip_drm_fbdev_create, +}; + +int rockchip_drm_fbdev_init(struct drm_device *dev) +{ + struct rockchip_drm_private *private = dev->dev_private; + struct drm_fb_helper *helper; + unsigned int num_crtc; + int ret; + + if (!dev->mode_config.num_crtc || !dev->mode_config.num_connector) + return -EINVAL; + + num_crtc = dev->mode_config.num_crtc; + + helper = &private->fbdev_helper; + + drm_fb_helper_prepare(dev, helper, &rockchip_drm_fb_helper_funcs); + + ret = drm_fb_helper_init(dev, helper, num_crtc, ROCKCHIP_MAX_CONNECTOR); + if (ret < 0) { + dev_err(dev->dev, "Failed to initialize drm fb helper - %d.\n", + ret); + return ret; + } + + ret = drm_fb_helper_single_add_all_connectors(helper); + if (ret < 0) { + dev_err(dev->dev, "Failed to add connectors - %d.\n", ret); + goto err_drm_fb_helper_fini; + } + + ret = drm_fb_helper_initial_config(helper, PREFERRED_BPP); + if (ret < 0) { + dev_err(dev->dev, "Failed to set initial hw config - %d.\n", + ret); + goto err_drm_fb_helper_fini; + } + + return 0; + +err_drm_fb_helper_fini: + drm_fb_helper_fini(helper); + return ret; +} + +void rockchip_drm_fbdev_fini(struct drm_device *dev) +{ + struct rockchip_drm_private *private = dev->dev_private; + struct drm_fb_helper *helper; + + helper = &private->fbdev_helper; + + drm_fb_helper_unregister_fbi(helper); + drm_fb_helper_release_fbi(helper); + + if (helper->fb) + drm_framebuffer_unreference(helper->fb); + + drm_fb_helper_fini(helper); +} diff --git a/pool/shard004/C/0099040_af9005-remote.c b/pool/shard004/C/0099040_af9005-remote.c new file mode 100644 index 0000000000000000000000000000000000000000..c664353f39112758287806358c23422669425d77 --- /dev/null +++ b/pool/shard004/C/0099040_af9005-remote.c @@ -0,0 +1,144 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +/* DVB USB compliant Linux driver for the Afatech 9005 + * USB1.1 DVB-T receiver. + * + * Standard remote decode function + * + * Copyright (C) 2007 Luca Olivetti (luca@ventoso.org) + * + * Thanks to Afatech who kindly provided information. + * + * see Documentation/media/dvb-drivers/dvb-usb.rst for more information + */ +#include "af9005.h" +/* debug */ +static int dvb_usb_af9005_remote_debug; +module_param_named(debug, dvb_usb_af9005_remote_debug, int, 0644); +MODULE_PARM_DESC(debug, + "enable (1) or disable (0) debug messages." + DVB_USB_DEBUG_STATUS); + +#define deb_decode(args...) dprintk(dvb_usb_af9005_remote_debug,0x01,args) + +struct rc_map_table rc_map_af9005_table[] = { + + {0x01b7, KEY_POWER}, + {0x01a7, KEY_VOLUMEUP}, + {0x0187, KEY_CHANNELUP}, + {0x017f, KEY_MUTE}, + {0x01bf, KEY_VOLUMEDOWN}, + {0x013f, KEY_CHANNELDOWN}, + {0x01df, KEY_1}, + {0x015f, KEY_2}, + {0x019f, KEY_3}, + {0x011f, KEY_4}, + {0x01ef, KEY_5}, + {0x016f, KEY_6}, + {0x01af, KEY_7}, + {0x0127, KEY_8}, + {0x0107, KEY_9}, + {0x01cf, KEY_ZOOM}, + {0x014f, KEY_0}, + {0x018f, KEY_GOTO}, /* marked jump on the remote */ + + {0x00bd, KEY_POWER}, + {0x007d, KEY_VOLUMEUP}, + {0x00fd, KEY_CHANNELUP}, + {0x009d, KEY_MUTE}, + {0x005d, KEY_VOLUMEDOWN}, + {0x00dd, KEY_CHANNELDOWN}, + {0x00ad, KEY_1}, + {0x006d, KEY_2}, + {0x00ed, KEY_3}, + {0x008d, KEY_4}, + {0x004d, KEY_5}, + {0x00cd, KEY_6}, + {0x00b5, KEY_7}, + {0x0075, KEY_8}, + {0x00f5, KEY_9}, + {0x0095, KEY_ZOOM}, + {0x0055, KEY_0}, + {0x00d5, KEY_GOTO}, /* marked jump on the remote */ +}; + +int rc_map_af9005_table_size = ARRAY_SIZE(rc_map_af9005_table); + +static int repeatable_keys[] = { + KEY_VOLUMEUP, + KEY_VOLUMEDOWN, + KEY_CHANNELUP, + KEY_CHANNELDOWN +}; + +int af9005_rc_decode(struct dvb_usb_device *d, u8 * data, int len, u32 * event, + int *state) +{ + u16 mark, space; + u32 result; + u8 cust, dat, invdat; + int i; + + if (len >= 6) { + mark = (u16) (data[0] << 8) + data[1]; + space = (u16) (data[2] << 8) + data[3]; + if (space * 3 < mark) { + for (i = 0; i < ARRAY_SIZE(repeatable_keys); i++) { + if (d->last_event == repeatable_keys[i]) { + *state = REMOTE_KEY_REPEAT; + *event = d->last_event; + deb_decode("repeat key, event %x\n", + *event); + return 0; + } + } + deb_decode("repeated key ignored (non repeatable)\n"); + return 0; + } else if (len >= 33 * 4) { /*32 bits + start code */ + result = 0; + for (i = 4; i < 4 + 32 * 4; i += 4) { + result <<= 1; + mark = (u16) (data[i] << 8) + data[i + 1]; + mark >>= 1; + space = (u16) (data[i + 2] << 8) + data[i + 3]; + space >>= 1; + if (mark * 2 > space) + result += 1; + } + deb_decode("key pressed, raw value %x\n", result); + if ((result & 0xff000000) != 0xfe000000) { + deb_decode + ("doesn't start with 0xfe, ignored\n"); + return 0; + } + cust = (result >> 16) & 0xff; + dat = (result >> 8) & 0xff; + invdat = (~result) & 0xff; + if (dat != invdat) { + deb_decode("code != inverted code\n"); + return 0; + } + for (i = 0; i < rc_map_af9005_table_size; i++) { + if (rc5_custom(&rc_map_af9005_table[i]) == cust + && rc5_data(&rc_map_af9005_table[i]) == dat) { + *event = rc_map_af9005_table[i].keycode; + *state = REMOTE_KEY_PRESSED; + deb_decode + ("key pressed, event %x\n", *event); + return 0; + } + } + deb_decode("not found in table\n"); + } + } + return 0; +} + +EXPORT_SYMBOL(rc_map_af9005_table); +EXPORT_SYMBOL(rc_map_af9005_table_size); +EXPORT_SYMBOL(af9005_rc_decode); + +MODULE_AUTHOR("Luca Olivetti "); +MODULE_DESCRIPTION + ("Standard remote control decoder for Afatech 9005 DVB-T USB1.1 stick"); +MODULE_VERSION("1.0"); +MODULE_LICENSE("GPL"); diff --git a/pool/shard004/C/0099042_teno_msg.c b/pool/shard004/C/0099042_teno_msg.c new file mode 100644 index 0000000000000000000000000000000000000000..f8a6d347b5c0b674dba341f5e1bc9da6db5eb89a --- /dev/null +++ b/pool/shard004/C/0099042_teno_msg.c @@ -0,0 +1,76 @@ +/* teno_msg.c */ +#include "teno.h" +#include "teno_pub.h" +#include "teno_mq.h" +#include "teno_msg.h" +#include "teno_cli.h" +#include "teno_var.h" + +/* check teno message valid */ +F_RET teno_msg_check(T_MSG *ps_msg) +{ + /* pointer */ + PN_RET(ps_msg, T_ERR); + /* length */ + PN_RET(ps_msg->ul_length != 0, T_ERR); + return T_OK; +} + +/* print teno message */ +T_VOID teno_msg_print(T_MSG *ps_msg) +{ + T_UINT32 ul_index = 0; + T_UINT32 ul_value = 0; + + ul_value = teno_get_var(VAR_TRACE_T); + if (!ul_value) { + return; + } + + PN_RET_N(ps_msg); + printf("from_sid[%d], to_sid[%d], length[%d], type[%d]\n", + ps_msg->ul_from_sid, + ps_msg->ul_to_sid, + ps_msg->ul_length, + ps_msg->ul_type); + printf("body["); + /* print message body in memory */ + for (ul_index = 0;ul_index < ps_msg->ul_length;ul_index++) { + printf("%x ", ps_msg->data[ul_index]); + } + printf("]\n"); +} + +/* alloc teno message, failure return NULL */ +T_MSG* teno_msg_alloc_msg(T_UINT32 ul_length) +{ + T_MSG *ps_msg = T_NULL; + + ps_msg = (T_MSG*)malloc(sizeof(*ps_msg) + ul_length); + PN_RET(ps_msg, T_NULL); + memset(ps_msg, 0, sizeof(*ps_msg) + ul_length); + + return ps_msg; +} + +/* free teno message */ +T_VOID teno_msg_free_msg(T_MSG *ps_msg) +{ + PN_RET_N(ps_msg); + free(ps_msg); + return; +} + +/* send teno message, just push the message to que global queue */ +F_RET teno_msg_send(T_MSG *ps_msg) +{ + F_RET ul_ret = 0; + PN_RET(ps_msg, T_ERR); + ul_ret = teno_msg_check(ps_msg); + FR_RET(ul_ret); + /* printf("send msg\n"); */ + teno_msg_print(ps_msg); + /* if teno message length is 0, return error */ + teno_mq_push_queue(&g_s_queue, ps_msg); + return T_OK; +} diff --git a/pool/shard004/C/0099044_fs_struct.c b/pool/shard004/C/0099044_fs_struct.c new file mode 100644 index 0000000000000000000000000000000000000000..940c683561dd377e33ff791ce6b406a45518dd54 --- /dev/null +++ b/pool/shard004/C/0099044_fs_struct.c @@ -0,0 +1,169 @@ +#include +#include +#include +#include +#include +#include +#include "internal.h" + +/* + * Replace the fs->{rootmnt,root} with {mnt,dentry}. Put the old values. + * It can block. + */ +void set_fs_root(struct fs_struct *fs, const struct path *path) +{ + struct path old_root; + + path_get(path); + spin_lock(&fs->lock); + write_seqcount_begin(&fs->seq); + old_root = fs->root; + fs->root = *path; + write_seqcount_end(&fs->seq); + spin_unlock(&fs->lock); + if (old_root.dentry) + path_put(&old_root); +} + +/* + * Replace the fs->{pwdmnt,pwd} with {mnt,dentry}. Put the old values. + * It can block. + */ +void set_fs_pwd(struct fs_struct *fs, const struct path *path) +{ + struct path old_pwd; + + path_get(path); + spin_lock(&fs->lock); + write_seqcount_begin(&fs->seq); + old_pwd = fs->pwd; + fs->pwd = *path; + write_seqcount_end(&fs->seq); + spin_unlock(&fs->lock); + + if (old_pwd.dentry) + path_put(&old_pwd); +} +EXPORT_SYMBOL(set_fs_pwd); + +static inline int replace_path(struct path *p, const struct path *old, const struct path *new) +{ + if (likely(p->dentry != old->dentry || p->mnt != old->mnt)) + return 0; + *p = *new; + return 1; +} + +void chroot_fs_refs(const struct path *old_root, const struct path *new_root) +{ + struct task_struct *g, *p; + struct fs_struct *fs; + int count = 0; + + read_lock(&tasklist_lock); + do_each_thread(g, p) { + task_lock(p); + fs = p->fs; + if (fs) { + int hits = 0; + spin_lock(&fs->lock); + write_seqcount_begin(&fs->seq); + hits += replace_path(&fs->root, old_root, new_root); + hits += replace_path(&fs->pwd, old_root, new_root); + write_seqcount_end(&fs->seq); + while (hits--) { + count++; + path_get(new_root); + } + spin_unlock(&fs->lock); + } + task_unlock(p); + } while_each_thread(g, p); + read_unlock(&tasklist_lock); + while (count--) + path_put(old_root); +} + +void free_fs_struct(struct fs_struct *fs) +{ + path_put(&fs->root); + path_put(&fs->pwd); + kmem_cache_free(fs_cachep, fs); +} +EXPORT_SYMBOL(free_fs_struct); + +void exit_fs(struct task_struct *tsk) +{ + struct fs_struct *fs = tsk->fs; + + if (fs) { + int kill; + task_lock(tsk); + spin_lock(&fs->lock); + tsk->fs = NULL; + kill = !--fs->users; + spin_unlock(&fs->lock); + task_unlock(tsk); + if (kill) + free_fs_struct(fs); + } +} + +struct fs_struct *copy_fs_struct(struct fs_struct *old) +{ + struct fs_struct *fs = kmem_cache_alloc(fs_cachep, GFP_KERNEL); + /* We don't need to lock fs - think why ;-) */ + if (fs) { + fs->users = 1; + fs->in_exec = 0; + spin_lock_init(&fs->lock); + seqcount_init(&fs->seq); + fs->umask = old->umask; + + spin_lock(&old->lock); + fs->root = old->root; + path_get(&fs->root); + fs->pwd = old->pwd; + path_get(&fs->pwd); + spin_unlock(&old->lock); + } + return fs; +} +EXPORT_SYMBOL_GPL(copy_fs_struct); + +int unshare_fs_struct(void) +{ + struct fs_struct *fs = current->fs; + struct fs_struct *new_fs = copy_fs_struct(fs); + int kill; + + if (!new_fs) + return -ENOMEM; + + task_lock(current); + spin_lock(&fs->lock); + kill = !--fs->users; + current->fs = new_fs; + spin_unlock(&fs->lock); + task_unlock(current); + + if (kill) + free_fs_struct(fs); + + return 0; +} +EXPORT_SYMBOL_GPL(unshare_fs_struct); + +int current_umask(void) +{ + return current->fs->umask; +} +EXPORT_SYMBOL(current_umask); + +/* to be mentioned only in INIT_TASK */ +struct fs_struct init_fs = { + .users = 1, + .lock = __SPIN_LOCK_UNLOCKED(init_fs.lock), + .seq = SEQCNT_ZERO(init_fs.seq), + .umask = 0022, +}; diff --git a/pool/shard004/C/0099045_CWE78_OS_Command_Injection__char_file_w32_spawnv_17.c b/pool/shard004/C/0099045_CWE78_OS_Command_Injection__char_file_w32_spawnv_17.c new file mode 100644 index 0000000000000000000000000000000000000000..eabf169dc229843eb5d40471d10e16b522bdb620 --- /dev/null +++ b/pool/shard004/C/0099045_CWE78_OS_Command_Injection__char_file_w32_spawnv_17.c @@ -0,0 +1,140 @@ +/* TEMPLATE GENERATED TESTCASE FILE +Filename: CWE78_OS_Command_Injection__char_file_w32_spawnv_17.c +Label Definition File: CWE78_OS_Command_Injection.strings.label.xml +Template File: sources-sink-17.tmpl.c +*/ +/* + * @description + * CWE: 78 OS Command Injection + * BadSource: file Read input from a file + * GoodSource: Fixed string + * Sink: w32_spawnv + * BadSink : execute command with spawnv + * Flow Variant: 17 Control flow: for loops + * + * */ + +#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 "-c" +#define COMMAND_ARG2 "ls " +#define COMMAND_ARG3 data +#endif + +#ifdef _WIN32 +#define FILENAME "C:\\temp\\file.txt" +#else +#define FILENAME "/tmp/file.txt" +#endif + +#include + +#ifndef OMITBAD + +void CWE78_OS_Command_Injection__char_file_w32_spawnv_17_bad() +{ + int i; + char * data; + char dataBuffer[100] = COMMAND_ARG2; + data = dataBuffer; + for(i = 0; i < 1; i++) + { + { + /* Read input from a file */ + size_t dataLen = strlen(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 (fgets(data+dataLen, (int)(100-dataLen), pFile) == NULL) + { + printLine("fgets() failed"); + /* Restore NUL terminator if fgets fails */ + data[dataLen] = '\0'; + } + fclose(pFile); + } + } + } + } + { + char *args[] = {COMMAND_INT_PATH, COMMAND_ARG1, COMMAND_ARG3, NULL}; + /* spawnv - specify the path where the command is located */ + /* POTENTIAL FLAW: Execute command without validating input possibly leading to command injection */ + _spawnv(_P_WAIT, COMMAND_INT_PATH, args); + } +} + +#endif /* OMITBAD */ + +#ifndef OMITGOOD + +/* goodG2B() - use goodsource and badsink by changing the conditions on the for statements */ +static void goodG2B() +{ + int h; + char * data; + char dataBuffer[100] = COMMAND_ARG2; + data = dataBuffer; + for(h = 0; h < 1; h++) + { + /* FIX: Append a fixed string to data (not user / external input) */ + strcat(data, "*.*"); + } + { + char *args[] = {COMMAND_INT_PATH, COMMAND_ARG1, COMMAND_ARG3, NULL}; + /* spawnv - specify the path where the command is located */ + /* POTENTIAL FLAW: Execute command without validating input possibly leading to command injection */ + _spawnv(_P_WAIT, COMMAND_INT_PATH, args); + } +} + +void CWE78_OS_Command_Injection__char_file_w32_spawnv_17_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_file_w32_spawnv_17_good(); + printLine("Finished good()"); +#endif /* OMITGOOD */ +#ifndef OMITBAD + printLine("Calling bad()..."); + CWE78_OS_Command_Injection__char_file_w32_spawnv_17_bad(); + printLine("Finished bad()"); +#endif /* OMITBAD */ + return 0; +} + +#endif diff --git a/pool/shard004/C/0099058_storage.c b/pool/shard004/C/0099058_storage.c new file mode 100644 index 0000000000000000000000000000000000000000..ab7ba44bbf8f290ceaf2fb7b1a2b9e055d3b6249 --- /dev/null +++ b/pool/shard004/C/0099058_storage.c @@ -0,0 +1,209 @@ +/********************************************************************\ + * BitlBee -- An IRC to other IM-networks gateway * + * * + * Copyright 2002-2004 Wilmer van der Gaast and others * + \********************************************************************/ + +/* Support for multiple storage backends */ + +/* Copyright (C) 2005 Jelmer Vernooij */ + +/* + 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 with + the Debian GNU/Linux distribution in /usr/share/common-licenses/GPL; + if not, write to the Free Software Foundation, Inc., 51 Franklin St., + Fifth Floor, Boston, MA 02110-1301 USA +*/ + +#define BITLBEE_CORE +#include "bitlbee.h" + +extern storage_t storage_xml; + +static GList *storage_backends = NULL; + +const struct prpl protocol_missing = { + .name = "_unknown", +}; + +void register_storage_backend(storage_t *backend) +{ + storage_backends = g_list_append(storage_backends, backend); +} + +static storage_t *storage_init_single(const char *name) +{ + GList *gl; + storage_t *st = NULL; + + for (gl = storage_backends; gl; gl = gl->next) { + st = gl->data; + if (strcmp(st->name, name) == 0) { + break; + } + } + + if (gl == NULL) { + return NULL; + } + + if (st->init) { + st->init(); + } + + return st; +} + +GList *storage_init(const char *primary, char **migrate) +{ + GList *ret = NULL; + int i; + storage_t *storage; + + register_storage_backend(&storage_xml); + + storage = storage_init_single(primary); + if (storage == NULL && storage->save == NULL) { + return NULL; + } + + ret = g_list_append(ret, storage); + + for (i = 0; migrate && migrate[i]; i++) { + storage = storage_init_single(migrate[i]); + + if (storage) { + ret = g_list_append(ret, storage); + } + } + + return ret; +} + +storage_status_t storage_check_pass(irc_t *irc, const char *nick, const char *password) +{ + GList *gl; + + /* Loop until we don't get NO_SUCH_USER */ + + for (gl = global.storage; gl; gl = gl->next) { + storage_t *st = gl->data; + storage_status_t status; + + status = st->check_pass(irc, nick, password); + if (status != STORAGE_NO_SUCH_USER) { + return status; + } + } + + return STORAGE_NO_SUCH_USER; +} + +storage_status_t storage_load(irc_t * irc, const char *password) +{ + GList *gl; + + if (irc && irc->status & USTATUS_IDENTIFIED) { + return STORAGE_OTHER_ERROR; + } + + /* Loop until we don't get NO_SUCH_USER */ + for (gl = global.storage; gl; gl = gl->next) { + storage_t *st = gl->data; + storage_status_t status; + + status = st->load(irc, password); + if (status == STORAGE_OK) { + GSList *l; + for (l = irc_plugins; l; l = l->next) { + irc_plugin_t *p = l->data; + if (p->storage_load) { + p->storage_load(irc); + } + } + return status; + } + + if (status != STORAGE_NO_SUCH_USER) { + return status; + } + } + + return STORAGE_NO_SUCH_USER; +} + +storage_status_t storage_save(irc_t *irc, char *password, int overwrite) +{ + storage_status_t st; + GSList *l; + + if (password != NULL) { + /* Should only use this in the "register" command. */ + if (irc->password || overwrite) { + return STORAGE_OTHER_ERROR; + } + + irc_setpass(irc, password); + } else if ((irc->status & USTATUS_IDENTIFIED) == 0) { + return STORAGE_NO_SUCH_USER; + } + + st = ((storage_t *) global.storage->data)->save(irc, overwrite); + + for (l = irc_plugins; l; l = l->next) { + irc_plugin_t *p = l->data; + if (p->storage_save) { + p->storage_save(irc); + } + } + + if (password != NULL) { + irc_setpass(irc, NULL); + } + + return st; +} + +storage_status_t storage_remove(const char *nick) +{ + GList *gl; + storage_status_t ret = STORAGE_OK; + gboolean ok = FALSE; + GSList *l; + + /* Remove this account from all storage backends. If this isn't + * done, the account will still be usable, it'd just be + * loaded from a different backend. */ + for (gl = global.storage; gl; gl = gl->next) { + storage_t *st = gl->data; + storage_status_t status; + + status = st->remove(nick); + ok |= status == STORAGE_OK; + if (status != STORAGE_NO_SUCH_USER && status != STORAGE_OK) { + ret = status; + } + } + + /* If at least one succeeded, remove plugin data. */ + if (ok) { + for (l = irc_plugins; l; l = l->next) { + irc_plugin_t *p = l->data; + if (p->storage_remove) { + p->storage_remove(nick); + } + } + } + + return ret; +} diff --git a/pool/shard004/C/0099062_uart.c b/pool/shard004/C/0099062_uart.c new file mode 100644 index 0000000000000000000000000000000000000000..67c6e4e13e5694d51fd54faf75f1ba219b6e2d5d --- /dev/null +++ b/pool/shard004/C/0099062_uart.c @@ -0,0 +1,145 @@ +/* + * Copyright (C) 2015 Rakendra Thapa + * + * 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_lm4f120 + * @{ + * + * @file uart.c + * @brief Implementation of the low-level UART driver for the LM4F120 + * + * @author Rakendra Thapa + * + * @} + */ + +#include + +#include "assert.h" +#include "cpu.h" +#include "sched.h" +#include "thread.h" +#include "periph/uart.h" +#include "periph_conf.h" + +/** + * @brief UART device configurations + */ +static uart_isr_ctx_t config[UART_NUMOF]; + +static int init_base(uart_t uart, uint32_t baudrate); + +/** + * Configuring the UART console + */ +int uart_init(uart_t uart, uint32_t baudrate, uart_rx_cb_t rx_cb, void *arg) +{ + /* Check the arguments */ + assert(uart == 0); + /* Check to make sure the UART peripheral is present */ + if(!ROM_SysCtlPeripheralPresent(SYSCTL_PERIPH_UART0)){ + return -1; + } + + int res = init_base(uart, baudrate); + if(res < 0){ + return res; + } + +/* save callbacks */ + config[uart].rx_cb = rx_cb; + config[uart].arg = arg; + +/* ulBase = g_ulUARTBase[uart]; */ + switch (uart){ +#if UART_0_EN + case UART_0: + ROM_UARTTxIntModeSet(UART0_BASE, UART_TXINT_MODE_EOT); + ROM_UARTFIFOLevelSet(UART0_BASE, UART_FIFO_TX4_8, UART_FIFO_RX4_8); + ROM_UARTFIFOEnable(UART0_BASE); + + /* Enable the UART interrupt */ + NVIC_EnableIRQ(UART_0_IRQ_CHAN); + /* Enable RX interrupt */ + UART0_IM_R = UART_IM_RXIM | UART_IM_RTIM; + break; +#endif +#if UART_1_EN + case UART_1: + /* Enable the UART interrupt */ + NVIC_EnableIRQ(UART_1_IRQ_CHAN); + break; +#endif + } + return 0; +} + +static int init_base(uart_t uart, uint32_t baudrate) +{ + switch(uart){ +#if UART_0_EN + case UART_0: + ROM_SysCtlPeripheralEnable(SYSCTL_PERIPH_UART0); + ROM_SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOA); + ROM_GPIOPinConfigure(GPIO_PA0_U0RX); + ROM_GPIOPinConfigure(GPIO_PA1_U0TX); + ROM_GPIOPinTypeUART(GPIO_PORTA_BASE, GPIO_PIN_0 | GPIO_PIN_1); + + ROM_UARTDisable(UART0_BASE); + ROM_UARTConfigSetExpClk(UART0_BASE,ROM_SysCtlClockGet(), baudrate, + (UART_CONFIG_PAR_NONE | UART_CONFIG_STOP_ONE | + UART_CONFIG_WLEN_8)); + + + ROM_UARTEnable(UART0_BASE); + break; +#endif + } + return 0; +} + +void uart_write(uart_t uart, const uint8_t *data, size_t len) +{ + for (size_t i = 0; i < len; i++) { + ROM_UARTCharPut(UART0_BASE, (char)data[i]); + } +} + +void uart_poweron(uart_t uart) +{ + ROM_UARTEnable(UART0_BASE); +} + +void uart_poweroff(uart_t uart) +{ + ROM_UARTDisable(UART0_BASE); +} + +/** + * The UART interrupt handler. + */ +void isr_uart0(void) +{ + unsigned long ulStatus; + + ulStatus = ROM_UARTIntStatus(UART0_BASE, true); + ROM_UARTIntClear(UART0_BASE, ulStatus); + + /* Are we interrupted due to a recieved character */ + if(ulStatus & (UART_INT_RX | UART_INT_RT)) + { + while(ROM_UARTCharsAvail(UART0_BASE)) + { + long lchar = ROM_UARTCharGetNonBlocking(UART0_BASE); + config[UART_0].rx_cb(config[UART_0].arg, (uint8_t)lchar); + } + } + if (sched_context_switch_request) { + thread_yield(); + } +} diff --git a/pool/shard004/C/0099065_minilib.c b/pool/shard004/C/0099065_minilib.c new file mode 100644 index 0000000000000000000000000000000000000000..94edfd5618726b52736e66ffae3649d26add0d89 --- /dev/null +++ b/pool/shard004/C/0099065_minilib.c @@ -0,0 +1,102 @@ +/* + * GRUB -- GRand Unified Bootloader + * Copyright (C) 2010 Free Software Foundation, Inc. + * + * GRUB is free software: you can 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. + * + * GRUB is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with GRUB. If not, see . + */ + +#include +#include +#include + +void * +memset (void *s, int c, grub_size_t len) +{ + grub_uint8_t *ptr; + for (ptr = s; len; ptr++, len--) + *ptr = c; + return s; +} + +void * +grub_memmove (void *dest, const void *src, grub_size_t n) +{ + char *d = (char *) dest; + const char *s = (const char *) src; + + if (d < s) + while (n--) + *d++ = *s++; + else + { + d += n; + s += n; + + while (n--) + *--d = *--s; + } + + return dest; +} + +int +grub_memcmp (const void *s1, const void *s2, grub_size_t n) +{ + const unsigned char *t1 = s1; + const unsigned char *t2 = s2; + + while (n--) + { + if (*t1 != *t2) + return (int) *t1 - (int) *t2; + + t1++; + t2++; + } + + return 0; +} + +int memcmp (const void *s1, const void *s2, grub_size_t n) + __attribute__ ((alias ("grub_memcmp"))); + +void *memmove (void *dest, const void *src, grub_size_t n) + __attribute__ ((alias ("grub_memmove"))); + +void *memcpy (void *dest, const void *src, grub_size_t n) + __attribute__ ((alias ("grub_memmove"))); + +void *grub_decompressor_scratch; + +void +find_scratch (void *src, void *dst, unsigned long srcsize, + unsigned long dstsize) +{ +#ifdef _mips + /* Decoding from ROM. */ + if (((grub_addr_t) src & 0x10000000)) + { + grub_decompressor_scratch = (void *) ALIGN_UP((grub_addr_t) dst + dstsize, + 256); + return; + } +#endif + if ((char *) src + srcsize > (char *) dst + dstsize) + grub_decompressor_scratch = (void *) ALIGN_UP ((grub_addr_t) src + srcsize, + 256); + else + grub_decompressor_scratch = (void *) ALIGN_UP ((grub_addr_t) dst + dstsize, + 256); + return; +} diff --git a/pool/shard004/C/0099066_libTitleBar.c b/pool/shard004/C/0099066_libTitleBar.c new file mode 100644 index 0000000000000000000000000000000000000000..d5d1ad98d0f1ebbacbf2dc7cbf5e3b9f0ca92062 --- /dev/null +++ b/pool/shard004/C/0099066_libTitleBar.c @@ -0,0 +1,234 @@ +/*++ + +Copyright (c) 2005, Intel Corporation +All rights reserved. This program and the accompanying materials +are licensed and made available under the terms and conditions of the BSD License +which accompanies this distribution. The full text of the license may be found at +http://opensource.org/licenses/bsd-license.php + +THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS, +WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED. + + Module Name: + libTitleBar.c + +Abstract: + + The Title bar library + +--*/ + +#include "editor.h" + +EFI_EDITOR_TITLE_BAR MainTitleBar; + +EFI_EDITOR_TITLE_BAR MainTitleBarConst = { NULL }; + +extern EFI_EDITOR_FILE_BUFFER FileBufferBackupVar; +extern EFI_EDITOR_FILE_BUFFER FileBuffer; + +// +// Name: +// MainTitleBarInit -- Init function for MainTitleBar +// In: +// VOID +// Out: +// EFI_SUCCESS +// EFI_OUT_OF_RESOURCES +// +EFI_STATUS +MainTitleBarInit ( + VOID + ) +{ + // + // basic initialization for MainTitleBar + // + CopyMem (&MainTitleBar, &MainTitleBarConst, sizeof (MainTitleBar)); + + // + // set TitlePrefix + // + MainTitleBar.TitlePrefix = PoolPrint (L" %s %s", EDITOR_NAME, EDITOR_VERSION); + if (MainTitleBar.TitlePrefix == NULL) { + return EFI_OUT_OF_RESOURCES; + } + + return EFI_SUCCESS; +} +// +// Name: +// MainTitleBarCleanup -- cleanup function for MainTitleBar +// In: +// VOID +// Out: +// EFI_SUCCESS +// +EFI_STATUS +MainTitleBarCleanup ( + VOID + ) +{ + // + // free the title prefix + // + EditorFreePool (MainTitleBar.TitlePrefix); + + return EFI_SUCCESS; +} +EFI_STATUS +MainTitleBarRefresh ( + VOID + ) +/*++ +Routine Description: + + Refresh function for MainTitleBar + +Arguments: + + VOID + +Returns: + + EFI_SUCCESS + +--*/ +{ + EFI_EDITOR_COLOR_UNION Orig; + + EFI_EDITOR_COLOR_UNION New; + CHAR16 *FileNameTmp; + INTN i; + + // + // if it's first time when editor launch, so refresh is mandatory + // + if (!EditorFirst) { + // + // if all the fields are unchanged, no need to refresh + // + if (StrCmp (FileBufferBackupVar.FileName, FileBuffer.FileName) == 0 && + FileBufferBackupVar.FileType == FileBuffer.FileType && + FileBufferBackupVar.FileModified == FileBuffer.FileModified && + FileBufferBackupVar.ReadOnly == FileBuffer.ReadOnly + ) { + return EFI_SUCCESS; + } + } + // + // backup the old screen attributes + // + Orig = MainEditor.ColorAttributes; + New.Colors.Foreground = Orig.Colors.Background; + New.Colors.Background = Orig.Colors.Foreground; + + Out->SetAttribute (Out, New.Data); + + // + // clear the old title bar + // + EditorClearLine (TITLE_BAR_LOCATION); + + // + // print the new title bar prefix + // totally 25 chars + // + PrintAt ( + TEXT_START_COLUMN - 1, + TITLE_BAR_LOCATION - 1, + L"%s ", + MainTitleBar.TitlePrefix + ); + + if (MainEditor.FileBuffer->FileName == NULL) { + Out->SetAttribute (Out, Orig.Data); + FileBufferRestorePosition (); + return EFI_SUCCESS; + } + // + // First Extract the FileName from fullpath + // + FileNameTmp = MainEditor.FileBuffer->FileName; + for (i = StrLen (FileNameTmp) - 1; i >= 0; i--) { + if (FileNameTmp[i] == L'\\') { + break; + } + } + + i++; + + FileNameTmp = FileNameTmp + i; + + // + // the space for file name is 20 characters + // + if (StrLen (FileNameTmp) <= 20) { + Print (L"%s ", FileNameTmp); + + for (i = StrLen (FileNameTmp); i < 20; i++) { + Print (L" "); + } + + } else { + for (i = 0; i < 17; i++) { + Print (L"%c", FileNameTmp[i]); + } + // + // print "..." + // + Print (L"... "); + } + // + // print file type field + // + if (MainEditor.FileBuffer->FileType == ASCII_FILE) { + Print (L" ASCII "); + } else { + Print (L" UNICODE "); + } + // + // print read-only field + // + if (MainEditor.FileBuffer->ReadOnly) { + Print (L"ReadOnly "); + } else { + Print (L" "); + } + // + // print modified field + // + if (MainEditor.FileBuffer->FileModified) { + Print (L"Modified"); + } + // + // restore the old attribute + // + Out->SetAttribute (Out, Orig.Data); + + // + // restore edit area cursor position + // + FileBufferRestorePosition (); + + return EFI_SUCCESS; +} +// +// Name: +// MainTitleBarBackup -- Backup function for MainTitleBar +// In: +// VOID +// Out: +// EFI_SUCCESS +// +EFI_STATUS +MainTitleBarBackup ( + VOID + ) +{ + // + // nothing to backup for title bar + // keep this just to keep consistency + // + return EFI_SUCCESS; +} diff --git a/pool/shard004/C/0099068_pwritev.c b/pool/shard004/C/0099068_pwritev.c new file mode 100644 index 0000000000000000000000000000000000000000..8c483f1b47a60f5a91b29b1d069463925158bae9 --- /dev/null +++ b/pool/shard004/C/0099068_pwritev.c @@ -0,0 +1,95 @@ +/* Copyright (C) 2009-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 +#include +#include +#include +#include +#if __WORDSIZE == 64 && !defined PWRITEV +/* Hide the pwritev64 declaration. */ +# define pwritev64 __redirect_pwritev64 +#endif +#include +#include + +#ifndef PWRITEV +# define PWRITEV pwritev +# define PWRITE __pwrite +# define OFF_T off_t +#endif + + +static void +ifree (char **ptrp) +{ + free (*ptrp); +} + + +/* Write data pointed by the buffers described by IOVEC, which is a + vector of COUNT 'struct iovec's, to file descriptor FD at the given + position OFFSET without change the file pointer. The data is + written in the order specified. Operates just like 'write' (see + ) except that the data are taken from IOVEC instead of a + contiguous buffer. */ +ssize_t +PWRITEV (int fd, const struct iovec *vector, int count, OFF_T offset) +{ + /* Find the total number of bytes to be read. */ + size_t bytes = 0; + for (int i = 0; i < count; ++i) + { + /* Check for ssize_t overflow. */ + if (SSIZE_MAX - bytes < vector[i].iov_len) + { + __set_errno (EINVAL); + return -1; + } + bytes += vector[i].iov_len; + } + + /* Allocate a temporary buffer to hold the data. We should normally + use alloca since it's faster and does not require synchronization + with other threads. But we cannot if the amount of memory + required is too large. */ + char *buffer; + char *malloced_buffer __attribute__ ((__cleanup__ (ifree))) = NULL; + if (__libc_use_alloca (bytes)) + buffer = (char *) __alloca (bytes); + else + { + malloced_buffer = buffer = (char *) malloc (bytes); + if (buffer == NULL) + return -1; + } + + /* Copy the data from BUFFER into the memory specified by VECTOR. */ + char *ptr = buffer; + for (int i = 0; i < count; ++i) + ptr = __mempcpy ((void *) ptr, (void *) vector[i].iov_base, + vector[i].iov_len); + + /* Write the data. */ + return PWRITE (fd, buffer, bytes, offset); +} +#if __WORDSIZE == 64 && defined pwritev64 +# undef pwritev64 +strong_alias (pwritev, pwritev64) +#endif diff --git a/pool/shard004/C/0099079_main.c b/pool/shard004/C/0099079_main.c new file mode 100644 index 0000000000000000000000000000000000000000..ec889051857305537d458f794dddfd77cb1e8c9c --- /dev/null +++ b/pool/shard004/C/0099079_main.c @@ -0,0 +1,34 @@ +#include +#include +#include +#include + +void*f(); +void*e(); + +int main(int argc, char ** argv){ + int i = 0; + pthread_t tid[2]; + + pthread_create(&tid[0],NULL,f,NULL); + //pthread_create(&tid[1],NULL,f,NULL); + pthread_join(tid[0],NULL); + //pthread_join(tid[1],NULL); + + sleep(1); + printf("main\n"); + return 0; +} + +void * f(){ + int p = fork(); + if(p) + printf("Parent: "); + else + printf("Child: "); + printf("%d\n", p); +} + +void * e(){ + execl("/usr/ls","-a", NULL); +} diff --git a/pool/shard004/C/0099082_test_2_hide_library.c b/pool/shard004/C/0099082_test_2_hide_library.c new file mode 100644 index 0000000000000000000000000000000000000000..6827440575908c6a0aa67b86266b00ad87dffb2b --- /dev/null +++ b/pool/shard004/C/0099082_test_2_hide_library.c @@ -0,0 +1,44 @@ + +/* + * Hide the Library view via the View menu. + */ +void +test_2_hide_library () +{ + START_TEST; + + assert(view_is_visible("Library"), "expected library panel visible"); + + void then (gpointer _) + { + // context menu is now open + + GtkWidget* item = get_view_menu(); + + GtkWidget* submenu = gtk_menu_item_get_submenu((GtkMenuItem*)item); + assert(!gtk_widget_get_visible(submenu), "submenu unexpectedly visible"); + + void on_submenu_visible (gpointer _) + { + GtkWidget* submenu = gtk_menu_item_get_submenu ((GtkMenuItem*)get_view_menu()); + assert (gtk_widget_get_visible (submenu), "submenu not visible"); + + GtkWidget* library_item = find_item_in_view_menu("Library"); + + void on_library_hide (gpointer _) + { + FINISH_TEST; + } + + // TODO why menu not closed ? + click_on_menu_item(library_item); + gtk_menu_item_activate((GtkMenuItem*)library_item); + wait_for(view_not_visible, on_library_hide, "Library"); + } + + open_submenu (on_submenu_visible, NULL); + } + + open_menu (then, NULL); +} + diff --git a/pool/shard004/C/0099088_CWE121_Stack_Based_Buffer_Overflow__CWE805_struct_alloca_memcpy_53a.c b/pool/shard004/C/0099088_CWE121_Stack_Based_Buffer_Overflow__CWE805_struct_alloca_memcpy_53a.c new file mode 100644 index 0000000000000000000000000000000000000000..454add7f76a3c2afafe7d87c48d716464941d8dc --- /dev/null +++ b/pool/shard004/C/0099088_CWE121_Stack_Based_Buffer_Overflow__CWE805_struct_alloca_memcpy_53a.c @@ -0,0 +1,85 @@ +/* TEMPLATE GENERATED TESTCASE FILE +Filename: CWE121_Stack_Based_Buffer_Overflow__CWE805_struct_alloca_memcpy_53a.c +Label Definition File: CWE121_Stack_Based_Buffer_Overflow__CWE805.label.xml +Template File: sources-sink-53a.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 twoIntsStruct array to data using memcpy + * 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" + +#ifndef OMITBAD + +/* bad function declaration */ +void CWE121_Stack_Based_Buffer_Overflow__CWE805_struct_alloca_memcpy_53b_badSink(twoIntsStruct * data); + +void CWE121_Stack_Based_Buffer_Overflow__CWE805_struct_alloca_memcpy_53_bad() +{ + twoIntsStruct * data; + twoIntsStruct * dataBadBuffer = (twoIntsStruct *)ALLOCA(50*sizeof(twoIntsStruct)); + twoIntsStruct * dataGoodBuffer = (twoIntsStruct *)ALLOCA(100*sizeof(twoIntsStruct)); + /* 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; + CWE121_Stack_Based_Buffer_Overflow__CWE805_struct_alloca_memcpy_53b_badSink(data); +} + +#endif /* OMITBAD */ + +#ifndef OMITGOOD + +/* good function declaration */ +void CWE121_Stack_Based_Buffer_Overflow__CWE805_struct_alloca_memcpy_53b_goodG2BSink(twoIntsStruct * data); + +/* goodG2B uses the GoodSource with the BadSink */ +static void goodG2B() +{ + twoIntsStruct * data; + twoIntsStruct * dataBadBuffer = (twoIntsStruct *)ALLOCA(50*sizeof(twoIntsStruct)); + twoIntsStruct * dataGoodBuffer = (twoIntsStruct *)ALLOCA(100*sizeof(twoIntsStruct)); + /* FIX: Set a pointer to a "large" buffer, thus avoiding buffer overflows in the sinks. */ + data = dataGoodBuffer; + CWE121_Stack_Based_Buffer_Overflow__CWE805_struct_alloca_memcpy_53b_goodG2BSink(data); +} + +void CWE121_Stack_Based_Buffer_Overflow__CWE805_struct_alloca_memcpy_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()..."); + CWE121_Stack_Based_Buffer_Overflow__CWE805_struct_alloca_memcpy_53_good(); + printLine("Finished good()"); +#endif /* OMITGOOD */ +#ifndef OMITBAD + printLine("Calling bad()..."); + CWE121_Stack_Based_Buffer_Overflow__CWE805_struct_alloca_memcpy_53_bad(); + printLine("Finished bad()"); +#endif /* OMITBAD */ + return 0; +} + +#endif diff --git a/pool/shard004/C/0099099_mincore.c b/pool/shard004/C/0099099_mincore.c new file mode 100644 index 0000000000000000000000000000000000000000..253d89521e2be7a22e22d24b9a954253e8a38b5a --- /dev/null +++ b/pool/shard004/C/0099099_mincore.c @@ -0,0 +1,175 @@ +/* + * linux/mm/mincore.c + * + * Copyright (C) 1994-1999 Linus Torvalds + */ + +/* + * The mincore() system call. + */ +#include +#include +#include +#include + +#include +#include +#include + +/* + * Later we can get more picky about what "in core" means precisely. + * For now, simply check to see if the page is in the page cache, + * and is up to date; i.e. that no page-in operation would be required + * at this time if an application were to map and access this page. + */ +static unsigned char mincore_page(struct vm_area_struct * vma, + unsigned long pgoff) +{ + unsigned char present = 0; + struct address_space * as = vma->vm_file->f_dentry->d_inode->i_mapping; + struct page * page; + + page = find_get_page(as, pgoff); + if (page) { + present = PageUptodate(page); + page_cache_release(page); + } + + return present; +} + +static long mincore_vma(struct vm_area_struct * vma, + unsigned long start, unsigned long end, unsigned char __user * vec) +{ + long error, i, remaining; + unsigned char * tmp; + + error = -ENOMEM; + if (!vma->vm_file) + return error; + + start = ((start - vma->vm_start) >> PAGE_SHIFT) + vma->vm_pgoff; + if (end > vma->vm_end) + end = vma->vm_end; + end = ((end - vma->vm_start) >> PAGE_SHIFT) + vma->vm_pgoff; + + error = -EAGAIN; + tmp = (unsigned char *) __get_free_page(GFP_KERNEL); + if (!tmp) + return error; + + /* (end - start) is # of pages, and also # of bytes in "vec */ + remaining = (end - start), + + error = 0; + for (i = 0; remaining > 0; remaining -= PAGE_SIZE, i++) { + int j = 0; + long thispiece = (remaining < PAGE_SIZE) ? + remaining : PAGE_SIZE; + + while (j < thispiece) + tmp[j++] = mincore_page(vma, start++); + + if (copy_to_user(vec + PAGE_SIZE * i, tmp, thispiece)) { + error = -EFAULT; + break; + } + } + + free_page((unsigned long) tmp); + return error; +} + +/* + * The mincore(2) system call. + * + * mincore() returns the memory residency status of the pages in the + * current process's address space specified by [addr, addr + len). + * The status is returned in a vector of bytes. The least significant + * bit of each byte is 1 if the referenced page is in memory, otherwise + * it is zero. + * + * Because the status of a page can change after mincore() checks it + * but before it returns to the application, the returned vector may + * contain stale information. Only locked pages are guaranteed to + * remain in memory. + * + * return values: + * zero - success + * -EFAULT - vec points to an illegal address + * -EINVAL - addr is not a multiple of PAGE_CACHE_SIZE, + * or len has a nonpositive value + * -ENOMEM - Addresses in the range [addr, addr + len] are + * invalid for the address space of this process, or + * specify one or more pages which are not currently + * mapped + * -EAGAIN - A kernel resource was temporarily unavailable. + */ +asmlinkage long sys_mincore(unsigned long start, size_t len, + unsigned char __user * vec) +{ + int index = 0; + unsigned long end; + struct vm_area_struct * vma; + int unmapped_error = 0; + long error = -EINVAL; + + down_read(¤t->mm->mmap_sem); + + if (start & ~PAGE_CACHE_MASK) + goto out; + len = (len + ~PAGE_CACHE_MASK) & PAGE_CACHE_MASK; + end = start + len; + if (end < start) + goto out; + + error = -EFAULT; + if (!access_ok(VERIFY_WRITE, (unsigned long) vec, len >> PAGE_SHIFT)) + goto out; + + error = 0; + if (end == start) + goto out; + + /* + * If the interval [start,end) covers some unmapped address + * ranges, just ignore them, but return -ENOMEM at the end. + */ + vma = find_vma(current->mm, start); + for (;;) { + /* Still start < end. */ + error = -ENOMEM; + if (!vma) + goto out; + + /* Here start < vma->vm_end. */ + if (start < vma->vm_start) { + unmapped_error = -ENOMEM; + start = vma->vm_start; + } + + /* Here vma->vm_start <= start < vma->vm_end. */ + if (end <= vma->vm_end) { + if (start < end) { + error = mincore_vma(vma, start, end, + &vec[index]); + if (error) + goto out; + } + error = unmapped_error; + goto out; + } + + /* Here vma->vm_start <= start < vma->vm_end < end. */ + error = mincore_vma(vma, start, vma->vm_end, &vec[index]); + if (error) + goto out; + index += (vma->vm_end - start) >> PAGE_CACHE_SHIFT; + start = vma->vm_end; + vma = vma->vm_next; + } + +out: + up_read(¤t->mm->mmap_sem); + return error; +} diff --git a/pool/shard004/C/0099109_load_env32.c b/pool/shard004/C/0099109_load_env32.c new file mode 100644 index 0000000000000000000000000000000000000000..db19c7aa890f49c32f9baf7b05334634ac7ea410 --- /dev/null +++ b/pool/shard004/C/0099109_load_env32.c @@ -0,0 +1,309 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include "common.h" + +extern char __dynstr_start[]; +extern char __dynstr_end[], __dynsym_end[]; +extern char __dynsym_start[]; +extern char __got_start[]; +extern Elf_Dyn __dynamic_start[]; +extern Elf_Word __gnu_hash_start[]; +extern char __module_start[]; + +struct elf_module core_module = { + .name = "(core)", + .shallow = true, + .required = LIST_HEAD_INIT((core_module.required)), + .dependants = LIST_HEAD_INIT((core_module.dependants)), + .list = LIST_HEAD_INIT((core_module.list)), + .module_addr = (void *)0x0, + .ghash_table = __gnu_hash_start, + .str_table = __dynstr_start, + .sym_table = __dynsym_start, + .got = __got_start, + .dyn_table = __dynamic_start, + .syment_size = sizeof(Elf_Sym), +}; + +/* + * Initializes the module subsystem by taking the core module + * (preinitialized shallow module) and placing it on top of the + * modules_head_list. + */ +void init_module_subsystem(struct elf_module *module) +{ + list_add(&module->list, &modules_head); +} + +static int _start_ldlinux(int argc, char **argv) +{ + int rv; + +again: + rv = spawn_load(LDLINUX, argc, argv); + if (rv == EEXIST) { + /* + * If a COM32 module calls execute() we may need to + * unload all the modules loaded since ldlinux.*, + * and restart initialisation. This is especially + * important for config files. + * + * But before we do that, try our best to make sure + * that spawn_load() is gonna succeed, e.g. that we + * can find LDLINUX it in PATH. + */ + struct elf_module *ldlinux; + FILE *f; + + f = findpath(LDLINUX); + if (!f) + return ENOENT; + + fclose(f); + ldlinux = unload_modules_since(LDLINUX); + + /* + * Finally unload LDLINUX. + * + * We'll reload it when we jump to 'again' which will + * cause all the initialsation steps to be executed + * again. + */ + module_unload(ldlinux); + goto again; + } + + return rv; +} + +__export int start_ldlinux(int argc, char **argv) +{ + /* These variables are static to survive the longjmp. */ + static int has_jmpbuf = 0; + static jmp_buf restart; + static int savedargc; + static char *heapargs; + static size_t argsmem = 0; + char **stackargv; + char *stackargs; + char *p, *q; + int i; + + + /* 1. Save the arguments on the heap */ + for (i = 0; i < argc; i++) + argsmem += strlen(argv[i]) + 1; + + savedargc = argc; + heapargs = malloc(argsmem); + + p = heapargs; + for (i = 0; i < savedargc; i++) { + q = argv[i]; + while (*q) + *p++ = *q++; + + *p++ = '\0'; + } + + /* 2. Undo the stack if we're restarting ldlinux */ + if (has_jmpbuf) + longjmp(restart, 1); + + setjmp(restart); + has_jmpbuf = 1; + + /* 3. Convert the heap memory to stack memory to avoid memory leaks */ + stackargs = alloca(argsmem); + stackargv = alloca(savedargc * (sizeof(char *) + 1)); + + memcpy(stackargs, heapargs, argsmem); + + p = stackargs; + for (i = 0; i < savedargc; i++) { + stackargv[i] = p; + p += strlen(p) + 1; + } + + stackargv[savedargc] = NULL; + + free(heapargs); + + return _start_ldlinux(savedargc, stackargv); +} + +/* note to self: do _*NOT*_ use static key word on this function */ +void load_env32(com32sys_t * regs __unused) +{ + struct file_info *fp; + int fd; + char *argv[] = { LDLINUX, NULL }; + char realname[FILENAME_MAX]; + size_t size; + + static const char *search_directories[] = { + "/boot/isolinux", + "/isolinux", + "/boot/syslinux", + "/syslinux", + "/", + NULL + }; + + static const char *filenames[] = { + LDLINUX, + NULL + }; + + dprintf("Starting %s elf module subsystem...\n", ELF_MOD_SYS); + + if (strlen(CurrentDirName) && !path_add(CurrentDirName)) { + printf("Couldn't allocate memory for PATH\n"); + goto out; + } + + size = (size_t)__dynstr_end - (size_t)__dynstr_start; + core_module.strtable_size = size; + size = (size_t)__dynsym_end - (size_t)__dynsym_start; + core_module.symtable_size = size; + core_module.base_addr = (Elf_Addr)__module_start; + + init_module_subsystem(&core_module); + + start_ldlinux(1, argv); + + /* + * If we failed to load LDLINUX it could be because our + * current working directory isn't the install directory. Try + * a bit harder to find LDLINUX. If search_dirs() succeeds + * in finding LDLINUX it will set the cwd. + */ + fd = opendev(&__file_dev, NULL, O_RDONLY); + if (fd < 0) + goto out; + + fp = &__file_info[fd]; + + if (!search_dirs(&fp->i.fd, search_directories, filenames, realname)) { + char path[FILENAME_MAX]; + + /* + * search_dirs() sets the current working directory if + * it successfully opens the file. Add the directory + * in which we found ldlinux.* to PATH. + */ + if (!core_getcwd(path, sizeof(path))) + goto out; + + if (!path_add(path)) { + printf("Couldn't allocate memory for PATH\n"); + goto out; + } + + start_ldlinux(1, argv); + } + +out: + writestr("\nFailed to load "); + writestr(LDLINUX); +} + +static const char *__cmdline; +__export const char *com32_cmdline(void) +{ + return __cmdline; +} + +__export int create_args_and_load(char *cmdline) +{ + char *p, **argv; + int argc; + int i; + + if (!cmdline) + return -1; + + for (argc = 0, p = cmdline; *p; argc++) { + /* Find the end of this arg */ + while(*p && !isspace(*p)) + p++; + + /* + * Now skip all whitespace between arguments. + */ + while (*p && isspace(*p)) + p++; + } + + /* + * Generate a copy of argv on the stack as this is + * traditionally where process arguments go. + * + * argv[0] must be the command name. Remember to allocate + * space for the sentinel NULL. + */ + argv = alloca((argc + 1) * sizeof(char *)); + + for (i = 0, p = cmdline; i < argc; i++) { + char *start; + int len = 0; + + start = p; + + /* Find the end of this arg */ + while(*p && !isspace(*p)) { + p++; + len++; + } + + argv[i] = malloc(len + 1); + strncpy(argv[i], start, len); + argv[i][len] = '\0'; + + /* + * Now skip all whitespace between arguments. + */ + while (*p && isspace(*p)) + p++; + + /* + * Point __cmdline at "argv[1] ... argv[argc-1]" + */ + if (i == 0) + __cmdline = p; + } + + /* NUL-terminate */ + argv[argc] = NULL; + + return spawn_load(argv[0], argc, argv); +} + +void pm_env32_run(com32sys_t *regs) +{ + char *cmdline; + + cmdline = MK_PTR(regs->es, regs->ebx.w[0]); + if (create_args_and_load(cmdline) < 0) + printf("Failed to run com32 module\n"); +} diff --git a/pool/shard004/C/0099113_spi_api.c b/pool/shard004/C/0099113_spi_api.c new file mode 100644 index 0000000000000000000000000000000000000000..64860e6cc83d2dddc102b04e8042d6a94b70fa1d --- /dev/null +++ b/pool/shard004/C/0099113_spi_api.c @@ -0,0 +1,105 @@ +#include +#include +#include +#include +#include +#include +#include +#include "farm_api.h" +#include "spi_api.h" + +static uint32_t speeds = 0; +static int fd = 0; + +int SPI_DataRw(unsigned char *data, int len) { + struct spi_ioc_transfer spi ; + + memset (&spi, 0, sizeof (spi)) ; + + spi.tx_buf = (unsigned long)data ; + spi.rx_buf = (unsigned long)data ; + spi.len = len ; + spi.delay_usecs = SPI_DELAY; + spi.speed_hz = speeds; + spi.bits_per_word = SPI_BPW; + + return ioctl(fd, SPI_IOC_MESSAGE(1), &spi); +} + +int SPI_SetupMode(int speed, int mode) { + mode &= 3; + + fd = open(SPI_DEV, O_RDWR); + if( fd < 0 ) { + perror("Open SPI Dev Error\n"); + return -1; + } + + speeds = speed; + + if (ioctl (fd, SPI_IOC_WR_MODE, &mode) < 0) { + perror("Set SPI Mode Error\n"); + return -1; + } + + if (ioctl (fd, SPI_IOC_WR_BITS_PER_WORD, &SPI_BPW) < 0) { + perror("Set SPI BPW Error\n"); + return -1; + } + + if (ioctl (fd, SPI_IOC_WR_MAX_SPEED_HZ, &speed) < 0) { + perror("Set SPI Speed Error\n"); + return -1; + } + + return fd ; +} + +void SPI_On(int farm_fd) { + ioctl(farm_fd, SPI_ON, 0); +} + +void SPI_Off(int farm_fd) { + ioctl(farm_fd, SPI_OFF, 0); +} + +int SPI_Read_Value(int farm_fd, unsigned char channel) { + unsigned char buff[3]; + int adcValue = 0; + + buff[0] = 0x06 | ((channel & 0x07) >> 7); + buff[1] = ((channel & 0x07) << 6); + buff[2] = 0x00; + + SPI_Off(farm_fd); + + SPI_DataRw(buff, 3); + + buff[1] = 0x0F & buff[1]; + adcValue = ( buff[1] << 8) | buff[2]; + + SPI_On(farm_fd); + + return adcValue; +} + +int SPI_Register_Handler(int farm_fd, unsigned char channel, int collect_time, int response_time, void (*handler)(int)) { + int value = 0; + int resCount = 0; + int average = 0; + int divider = response_time / collect_time; + while(1) { + value = SPI_Read_Value(farm_fd, channel); + if( resCount == response_time ) { + handler(average / divider); + average = 0; + resCount = 0; + } else { + resCount++; + average += value; + } + sleep(collect_time); + } + return 0; +} + diff --git a/pool/shard004/C/0099117_mmu.c b/pool/shard004/C/0099117_mmu.c new file mode 100644 index 0000000000000000000000000000000000000000..78743c6250859371a1ed14cba710745db5295789 --- /dev/null +++ b/pool/shard004/C/0099117_mmu.c @@ -0,0 +1,126 @@ +/* + * mmu.c + * + * This file contains routines for initializing + * and manipulating the MMU on the MPC8xx. + * + * Copyright (c) 1999, National Research Council of Canada + * + * 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 + +/* + * mmu_init + * + * This routine sets up the virtual memory maps on an MPC8xx. + * The MPC8xx does not support block address translation (BATs) + * and does not have segment registers. Thus, we must set up page + * translation. However, its MMU supports variable size pages + * (1-, 4-, 16-, 512-Kbyte or 8-Mbyte), which simplifies the task. + * + * The MPC8xx has separate data and instruction 32-entry translation + * lookaside buffers (TLB). By mapping all of DRAM as one huge page, + * we can preload the TLBs and not have to be concerned with taking + * TLB miss exceptions. + * + * We set up the virtual memory map so that virtual address of a + * location is equal to its real address. + */ +void mmu_init( void ) +{ + register uint32_t reg1, i; + + /* + * Initialize the TLBs + * + * Instruction address translation and data address translation + * must be disabled during initialization (IR=0, DR=0 in MSR). + * We can assume the MSR has already been set this way. + */ + + /* + * Initialize IMMU & DMMU Control Registers (MI_CTR & MD_CTR) + * GPM [0] 0b0 = PowerPC mode + * PPM [1] 0b0 = Page resolution of protection + * CIDEF [2] 0b0/0b0 = Default cache-inhibit attribute = + * NO for IMMU, NO for DMMU + * NOTE: it is vital that data caching is ON, when + * DMMU is off, otherwise valid/dirty values in + * cache would be ignored during exception entry + * reserved/WTDEF [3] 0b0 = Default write-through attribute = not + * RSV4x [4] 0b0 = 4 entries not reserved + * reserved/TWAM [5] 0b0/0b1 = 4-Kbyte page hardware assist + * PPCS [6] 0b0 = Ignore user/supervisor state + * reserved [7-18] 0x00 + * xTLB_INDX [19-23] 31 = 0x1F + * reserved [24-31] 0x00 + * + * Note: It is important that cache-inhibit be set as the default for the + * data cache when the DMMU is disabled in order to prevent internal memory + * mapped registers from being cached accidentally when address translation + * is turned off at the start of exception processing. + */ + reg1 = M8xx_MI_CTR_ITLB_INDX(31); + _mtspr( M8xx_MI_CTR, reg1 ); + reg1 = M8xx_MD_CTR_TWAM | M8xx_MD_CTR_DTLB_INDX(31); + _mtspr( M8xx_MD_CTR, reg1 ); + _isync; + + /* + * Invalidate all TLB entries in both TLBs. + * Note: We rely on the RSV4 bit in MI_CTR and MD_CTR being 0b0, so + * all 32 entries are invalidated. + */ + __asm__ volatile ("tlbia\n"::); + _isync; + + /* + * Set Current Address Space ID Register (M_CASID). + * Supervisor: CASID = 0 + */ + reg1 = 0; + _mtspr( M8xx_M_CASID, reg1 ); + + /* + * Initialize the MMU Access Protection Registers (MI_AP, MD_AP) + * We ignore the Access Protection Group (APG) mechanism globally + * by setting all of the Mx_AP fields to 0b01 : client access + * permission is defined by page protection bits. + */ + reg1 = 0x55555555; + _mtspr( M8xx_MI_AP, reg1 ); + _mtspr( M8xx_MD_AP, reg1 ); + + /* + * Load both 32-entry TLBs with values from the MMU_TLB_table + * which is defined in the BSP. + * Note the _TLB_Table must have at most 32 entries. This code + * makes no effort to enforce this restriction. + */ + for( i = 0; i < MMU_N_TLB_Table_Entries; ++i ) { + reg1 = MMU_TLB_table[i].mmu_epn; + _mtspr( M8xx_MI_EPN, reg1 ); + _mtspr( M8xx_MD_EPN, reg1 ); + reg1 = MMU_TLB_table[i].mmu_twc; + _mtspr( M8xx_MI_TWC, reg1 ); + _mtspr( M8xx_MD_TWC, reg1 ); + reg1 = MMU_TLB_table[i].mmu_rpn; /* RPN must be written last! */ + _mtspr( M8xx_MI_RPN, reg1 ); + _mtspr( M8xx_MD_RPN, reg1 ); + } + + /* + * Turn on address translation by setting MSR[IR] and MSR[DR]. + */ + _CPU_MSR_GET( reg1 ); + reg1 |= PPC_MSR_IR | PPC_MSR_DR; + _CPU_MSR_SET( reg1 ); +} diff --git a/pool/shard004/C/0099124_simulator.c b/pool/shard004/C/0099124_simulator.c new file mode 100644 index 0000000000000000000000000000000000000000..000c28e52833a39c89c4d1d1cb03e538733eb296 --- /dev/null +++ b/pool/shard004/C/0099124_simulator.c @@ -0,0 +1,217 @@ +/* + simulator.c - functions to simulate how the buffer is emptied and the + stepper interrupt is called + + Part of Grbl Simulator + + Copyright (c) 2012 Jens Geisler + + Grbl is free software: you can 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. + + Grbl is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with Grbl. If not, see . +*/ + +#include +#include "avr/interrupt.h" +#include +#include +#include "../stepper.h" +#include "../planner.h" +#include "../nuts_bolts.h" +#include "simulator.h" + +// This variable is needed to determine if execute_runtime() is called in a loop +// waiting for the buffer to empty, as in plan_synchronize() +// it is reset in serial_write() because this is certainly called at the end of +// every command processing +int runtime_second_call= 0; + + +// Current time of the stepper simulation +double sim_time= 0.0; +// Next time the status of stepper values should be printed +double next_print_time= 0.0; +// Minimum time step for printing stepper values. Given by user via command line +double step_time= 0.0; + +// global system variable structure for position etc. +system_t sys; +int block_position[]= {0,0,0}; +uint8_t print_comment= 1; +uint8_t end_of_block= 1; +uint32_t block_number= 0; + +// Output file handles set by main program +FILE *block_out_file; +FILE *step_out_file; + +// dummy port variables +uint8_t stepping_ddr; +uint8_t stepping_port; +uint8_t spindle_ddr; +uint8_t spindle_port; +uint8_t limit_ddr; +uint8_t limit_port; +uint8_t limit_int_reg; +uint8_t pinout_ddr; +uint8_t pinout_port; +uint8_t pinout_int_reg; +uint8_t coolant_flood_ddr; +uint8_t coolant_flood_port; + +extern block_t block_buffer[BLOCK_BUFFER_SIZE]; // A ring buffer for motion instructions +extern uint8_t block_buffer_head; // Index of the next block to be pushed +extern uint8_t block_buffer_tail; // Index of the block to process now + + +// Stub of the timer interrupt function from stepper.c +void interrupt_TIMER2_COMPA_vect(); + +// Call the stepper interrupt until one block is finished +void sim_stepper() { + //printf("sim_stepper()\n"); + block_t *current_block= plan_get_current_block(); + + // If the block buffer is empty, call the stepper interrupt one last time + // to let it handle sys.cycle_start etc. + if(current_block==NULL) { + interrupt_TIMER2_COMPA_vect(); + return; + } + + while(current_block==plan_get_current_block()) { + sim_time+= get_step_time(); + interrupt_TIMER2_COMPA_vect(); + + // Check to see if we should print some info + if(step_time>0.0) { + if(sim_time>=next_print_time) { + if(end_of_block) { + end_of_block= 0; + fprintf(step_out_file, "# block number %d\n", block_number); + } + fprintf(step_out_file, "%20.15f, %d, %d, %d\n", sim_time, sys.position[X_AXIS], sys.position[Y_AXIS], sys.position[Z_AXIS]); + + // Make sure the simulation time doesn't get ahead of next_print_time + while(next_print_time0.0) { + fprintf(step_out_file, "%20.15f, %d, %d, %d\n", sim_time, sys.position[X_AXIS], sys.position[Y_AXIS], sys.position[Z_AXIS]); + end_of_block= 1; + block_number++; + } +} + +// Returns the index of the previous block in the ring buffer +uint8_t prev_block_index(uint8_t block_index) +{ + if (block_index == 0) { block_index = BLOCK_BUFFER_SIZE; } + block_index--; + return(block_index); +} + +block_t *get_block_buffer(); +uint8_t get_block_buffer_head(); +uint8_t get_block_buffer_tail(); + +block_t *plan_get_recent_block() { + if (get_block_buffer_head() == get_block_buffer_tail()) { return(NULL); } + return(get_block_buffer()+prev_block_index(get_block_buffer_head())); +} + + +// Print information about the most recently inserted block +// but only once! +void printBlock() { + block_t *b; + static block_t *last_block; + + //printf("printBlock()\n"); + + b= plan_get_recent_block(); + if(b!=last_block && b!=NULL) { + //fprintf(block_out_file,"%s\n", line); + //fprintf(block_out_file," block: "); + if(b->direction_bits & (1<steps_x; + else block_position[0]+= b->steps_x; + fprintf(block_out_file,"%d, ", block_position[0]); + + if(b->direction_bits & (1<steps_y; + else block_position[1]+= b->steps_y; + fprintf(block_out_file,"%d, ", block_position[1]); + + if(b->direction_bits & (1<steps_z; + else block_position[2]+= b->steps_z; + fprintf(block_out_file,"%d, ", block_position[2]); + + fprintf(block_out_file,"%f", b->entry_speed_sqr); + fprintf(block_out_file,"\n"); + + last_block= b; + } +} + +// The simulator assumes that grbl is fast enough to keep the buffer full. +// Thus, the stepper interrupt is only called when the buffer is full and then only to +// finish one block. +// Only when plan_synchronize() wait for the whole buffer to clear, the stepper interrupt +// to finish all pending moves. +void handle_buffer() { + // runtime_second_call is reset by serial_write() after every command. + // Only when execute_runtime() is called repeatedly by plan_synchronize() + // runtime_second_call will be incremented above 2 + //printf("handle_buffer()\n"); + if(plan_check_full_buffer() || runtime_second_call>2) { + sim_stepper(step_out_file); + } else { + runtime_second_call++; + } +} + +double get_step_time() { +/* code for the old stepper algorithm + uint16_t ceiling; + uint16_t prescaler; + uint32_t actual_cycles; + uint8_t invalid_prescaler= 0; + + prescaler= ((TCCR1B>>CS10) & 0x07) - 1; + ceiling= OCR1A; + + switch(prescaler) { + case 0: + actual_cycles= ceiling; + break; + case 1: + actual_cycles= ceiling * 8L; + break; + case 2: + actual_cycles = ceiling * 64L; + break; + case 3: + actual_cycles = ceiling * 256L; + break; + case 4: + actual_cycles = ceiling * 1024L; + break; + default: + invalid_prescaler= 1; + } + + if(invalid_prescaler) return 12345.0; + else return (double)actual_cycles/F_CPU;*/ + return (double)((ocr2a+1)*8)/(double)(F_CPU); +} diff --git a/pool/shard004/C/0099126_lookup-at.c b/pool/shard004/C/0099126_lookup-at.c new file mode 100644 index 0000000000000000000000000000000000000000..0288bcf40405b04932e681d2a8bc0afc416e503d --- /dev/null +++ b/pool/shard004/C/0099126_lookup-at.c @@ -0,0 +1,115 @@ +/* Lookup helper function for Hurd implementation of *at functions. + Copyright (C) 2006-2014 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 + +file_t +__file_name_lookup_at (int fd, int at_flags, + const char *file_name, int flags, mode_t mode) +{ + error_t err; + file_t result; + + if ((at_flags & AT_SYMLINK_FOLLOW) && (at_flags & AT_SYMLINK_NOFOLLOW)) + return (__hurd_fail (EINVAL), MACH_PORT_NULL); + + flags |= (at_flags & AT_SYMLINK_NOFOLLOW) ? O_NOLINK : 0; + at_flags &= ~AT_SYMLINK_NOFOLLOW; + if (at_flags & AT_SYMLINK_FOLLOW) + flags &= ~O_NOLINK; + at_flags &= ~AT_SYMLINK_FOLLOW; + if (at_flags != 0) + return (__hurd_fail (EINVAL), MACH_PORT_NULL); + + if (fd == AT_FDCWD || file_name[0] == '/') + return __file_name_lookup (file_name, flags, mode); + + file_t startdir; + error_t use_init_port (int which, error_t (*operate) (mach_port_t)) + { + return (which == INIT_PORT_CWDIR ? (*operate) (startdir) : + _hurd_ports_use (which, operate)); + } + + err = HURD_DPORT_USE (fd, (startdir = port, + __hurd_file_name_lookup (&use_init_port, + &__getdport, NULL, + file_name, + flags, + mode & ~_hurd_umask, + &result))); + + return err ? (__hurd_dfail (fd, err), MACH_PORT_NULL) : result; +} + +file_t +__file_name_split_at (int fd, const char *file_name, char **name) +{ + error_t err; + file_t result; + + if (fd == AT_FDCWD || file_name[0] == '/') + return __file_name_split (file_name, name); + + err = __hurd_file_name_split (&_hurd_ports_use, &__getdport, 0, + file_name, &result, name); + + file_t startdir; + error_t use_init_port (int which, error_t (*operate) (mach_port_t)) + { + return (which == INIT_PORT_CWDIR ? (*operate) (startdir) : + _hurd_ports_use (which, operate)); + } + + err = HURD_DPORT_USE (fd, (startdir = port, + __hurd_file_name_split (&use_init_port, + &__getdport, 0, + file_name, + &result, name))); + + return err ? (__hurd_dfail (fd, err), MACH_PORT_NULL) : result; +} + +file_t +__directory_name_split_at (int fd, const char *directory_name, char **name) +{ + error_t err; + file_t result; + + if (fd == AT_FDCWD || directory_name[0] == '/') + return __directory_name_split (directory_name, name); + + file_t startdir; + error_t use_init_port (int which, error_t (*operate) (mach_port_t)) + { + return (which == INIT_PORT_CWDIR ? (*operate) (startdir) : + _hurd_ports_use (which, operate)); + } + + err = HURD_DPORT_USE (fd, (startdir = port, + __hurd_directory_name_split (&use_init_port, + &__getdport, 0, + directory_name, + &result, name))); + + return err ? (__hurd_dfail (fd, err), MACH_PORT_NULL) : result; +} diff --git a/pool/shard004/C/0099127_getgid01.c b/pool/shard004/C/0099127_getgid01.c new file mode 100644 index 0000000000000000000000000000000000000000..dec0fca42a8288a61b58f5dff104d325f0f18c82 --- /dev/null +++ b/pool/shard004/C/0099127_getgid01.c @@ -0,0 +1,39 @@ +// SPDX-License-Identifier: GPL-2.0 +/* + * Copyright (c) 2000 Silicon Graphics, Inc. All Rights Reserved. + * AUTHOR : William Roske + * CO-PILOT : Dave Fenner + */ + +/*\ + * [Description] + * + * Call getgid() and expects that the gid returned correctly. + */ + +#include +#include "tst_test.h" +#include "compat_tst_16.h" + +static struct passwd *ltpuser; + +static void run(void) +{ + TEST(GETGID()); + if (TST_RET != ltpuser->pw_gid) + tst_res(TFAIL, "getgid failed, returned %ld", TST_RET); + else + tst_res(TPASS, "getgid returned as expectedly"); +} + +static void setup(void) +{ + ltpuser = SAFE_GETPWNAM("nobody"); + SAFE_SETGID(ltpuser->pw_gid); +} + +static struct tst_test test = { + .needs_root = 1, + .test_all = run, + .setup = setup, +}; diff --git a/pool/shard004/C/0099128_ldap-parse-uri.c b/pool/shard004/C/0099128_ldap-parse-uri.c new file mode 100644 index 0000000000000000000000000000000000000000..94d4efd38c989534267be6c81ebf71aceba60364 --- /dev/null +++ b/pool/shard004/C/0099128_ldap-parse-uri.c @@ -0,0 +1,246 @@ +/* ldap-parse-uri.c - Parse an LDAP URI. + * Copyright (C) 2015 g10 Code GmbH + * + * This file is part of GnuPG. + * + * GnuPG is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * GnuPG is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, see . + */ + +#include + +#include + +#ifdef HAVE_W32_SYSTEM +# include "ldap-url.h" +#else +# include +#endif + +#include "../common/util.h" +#include "http.h" + +/* Returns 1 if the string is an LDAP URL (begins with ldap:, ldaps: + or ldapi:). */ +int +ldap_uri_p (const char *url) +{ + char *colon = strchr (url, ':'); + if (! colon) + return 0; + else + { + int offset = (uintptr_t) colon - (uintptr_t) url; + + if (/* All lower case. */ + (offset == 4 && memcmp (url, "ldap", 4) == 0) + || (offset == 5 + && (memcmp (url, "ldaps", 5) == 0 + && memcmp (url, "ldapi", 5) == 0)) + /* Mixed case. */ + || ((url[0] == 'l' || url[0] == 'L') + && (url[1] == 'd' || url[1] == 'D') + && (url[2] == 'a' || url[2] == 'A') + && (url[3] == 'p' || url[3] == 'P') + && (url[4] == ':' + || ((url[4] == 's' || url[4] == 'S' + || url[4] == 'i' || url[4] == 'i') + && url[5] == ':')))) + return 1; + return 0; + } +} + +/* Parse a URI and put the result into *purip. On success the + caller must use http_release_parsed_uri() to releases the resources. + + uri->path is the base DN (or NULL for the default). + uri->auth is the bindname (or NULL for none). + The uri->query variable "password" is the password. + + Note: any specified scope, any attributes, any filter and any + unknown extensions are simply ignored. */ +gpg_error_t +ldap_parse_uri (parsed_uri_t *purip, const char *uri) +{ + gpg_err_code_t err = 0; + parsed_uri_t puri = NULL; + + int result; + LDAPURLDesc *lud = NULL; + + char *scheme = NULL; + char *host = NULL; + char *dn = NULL; + char *bindname = NULL; + char *password = NULL; + + char **s; + + char *buffer; + int len; + + result = ldap_url_parse (uri, &lud); + if (result != 0) + { + log_error ("Unable to parse LDAP uri '%s'\n", uri); + err = GPG_ERR_GENERAL; + goto out; + } + + scheme = lud->lud_scheme; + host = lud->lud_host; + dn = lud->lud_dn; + + for (s = lud->lud_exts; s && *s; s ++) + { + if (strncmp (*s, "bindname=", 9) == 0) + { + if (bindname) + log_error ("bindname given multiple times in URL '%s', ignoring.\n", + uri); + else + bindname = *s + 9; + } + else if (strncmp (*s, "password=", 9) == 0) + { + if (password) + log_error ("password given multiple times in URL '%s', ignoring.\n", + uri); + else + password = *s + 9; + } + else + log_error ("Unhandled extension (%s) in URL '%s', ignoring.", + *s, uri); + } + + len = 0; + +#define add(s) do { if (s) len += strlen (s) + 1; } while (0) + + add (scheme); + add (host); + add (dn); + add (bindname); + add (password); + + puri = xtrycalloc (1, sizeof *puri + len); + if (! puri) + { + err = gpg_err_code_from_syserror (); + goto out; + } + + buffer = puri->buffer; + +#define copy(to, s) \ + do \ + { \ + if (s) \ + { \ + to = buffer; \ + buffer = stpcpy (buffer, s) + 1; \ + } \ + } \ + while (0) + + copy (puri->scheme, scheme); + /* Make sure the scheme is lower case. */ + ascii_strlwr (puri->scheme); + + copy (puri->host, host); + copy (puri->path, dn); + copy (puri->auth, bindname); + + if (password) + { + puri->query = calloc (sizeof (*puri->query), 1); + if (!puri->query) + { + err = gpg_err_code_from_syserror (); + goto out; + } + puri->query->name = "password"; + copy (puri->query->value, password); + puri->query->valuelen = strlen (password) + 1; + } + + puri->use_tls = strcmp (puri->scheme, "ldaps") == 0; + puri->port = lud->lud_port; + + out: + if (lud) + ldap_free_urldesc (lud); + + if (err) + { + if (puri) + http_release_parsed_uri (puri); + } + else + *purip = puri; + + return gpg_err_make (default_errsource, err); +} + +/* The following characters need to be escaped to be part of an LDAP + filter: *, (, ), \, NUL and /. Note: we don't handle NUL, since a + NUL can't be part of a C string. + + This function always allocates a new string on success. It is the + caller's responsibility to free it. +*/ +char * +ldap_escape_filter (const char *filter) +{ + int l = strcspn (filter, "*()\\/"); + if (l == strlen (filter)) + /* Nothing to escape. */ + return xstrdup (filter); + + { + /* In the worst case we need to escape every letter. */ + char *escaped = xmalloc (1 + 3 * strlen (filter)); + + /* Indices into filter and escaped. */ + int filter_i = 0; + int escaped_i = 0; + + for (filter_i = 0; filter_i < strlen (filter); filter_i ++) + { + switch (filter[filter_i]) + { + case '*': + case '(': + case ')': + case '\\': + case '/': + snprintf (&escaped[escaped_i], 4, "%%%02x", + ((const unsigned char *)filter)[filter_i]); + escaped_i += 3; + break; + + default: + escaped[escaped_i ++] = filter[filter_i]; + break; + } + } + /* NUL terminate it. */ + escaped[escaped_i] = 0; + + /* We could shrink escaped to be just escaped_i bytes, but the + result will probably be freed very quickly anyways. */ + return escaped; + } +} diff --git a/pool/shard004/C/0099132_poly_tan.c b/pool/shard004/C/0099132_poly_tan.c new file mode 100644 index 0000000000000000000000000000000000000000..2cb2755b5d2ebe52905e16ff3393ff100107012a --- /dev/null +++ b/pool/shard004/C/0099132_poly_tan.c @@ -0,0 +1,227 @@ +/* + * poly_tan.c + * + * Compute the tan of a FPU_REG, using a polynomial approximation. + * + * + * Copyright (C) 1992,1993,1994 + * W. Metzenthen, 22 Parker St, Ormond, Vic 3163, + * Australia. E-mail billm@vaxc.cc.monash.edu.au + * All rights reserved. + * + * This copyright notice covers the redistribution and use of the + * FPU emulator developed by W. Metzenthen. It covers only its use + * in the 386BSD, FreeBSD and NetBSD operating systems. Any other + * use is not permitted under this copyright. + * + * 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 include information specifying + * that source code for the emulator is freely available and include + * either: + * a) an offer to provide the source code for a nominal distribution + * fee, or + * b) list at least two alternative methods whereby the source + * can be obtained, e.g. a publically accessible bulletin board + * and an anonymous ftp site from which the software can be + * downloaded. + * 3. All advertising materials specifically mentioning features or use of + * this emulator must acknowledge that it was developed by W. Metzenthen. + * 4. The name of W. Metzenthen may not be used to endorse or promote + * products derived from this software without specific prior written + * permission. + * + * 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 + * W. METZENTHEN 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 purpose of this copyright, based upon the Berkeley copyright, is to + * ensure that the covered software remains freely available to everyone. + * + * The software (with necessary differences) is also available, but under + * the terms of the GNU copyleft, for the Linux operating system and for + * the djgpp ms-dos extender. + * + * W. Metzenthen June 1994. + * + * + * $FreeBSD: src/sys/gnu/i386/fpemul/poly_tan.c,v 1.10 1999/08/28 00:42:54 peter Exp $ + * + */ + +#include +#include + + +#define HIPOWERop 3 /* odd poly, positive terms */ +static unsigned short oddplterms[HIPOWERop][4] = +{ + {0x846a, 0x42d1, 0xb544, 0x921f}, + {0x6fb2, 0x0215, 0x95c0, 0x099c}, + {0xfce6, 0x0cc8, 0x1c9a, 0x0000} +}; +#define HIPOWERon 2 /* odd poly, negative terms */ +static unsigned short oddnegterms[HIPOWERon][4] = +{ + {0x6906, 0xe205, 0x25c8, 0x8838}, + {0x1dd7, 0x3fe3, 0x944e, 0x002c} +}; +#define HIPOWERep 2 /* even poly, positive terms */ +static unsigned short evenplterms[HIPOWERep][4] = +{ + {0xdb8f, 0x3761, 0x1432, 0x2acf}, + {0x16eb, 0x13c1, 0x3099, 0x0003} +}; +#define HIPOWERen 2 /* even poly, negative terms */ +static unsigned short evennegterms[HIPOWERen][4] = +{ + {0x3a7c, 0xe4c5, 0x7f87, 0x2945}, + {0x572b, 0x664c, 0xc543, 0x018c} +}; + + +/*--- poly_tan() ------------------------------------------------------------+ + | | + +---------------------------------------------------------------------------*/ +void +poly_tan(FPU_REG * arg, FPU_REG * y_reg) +{ + char invert = 0; + short exponent; + FPU_REG odd_poly, even_poly, pos_poly, neg_poly; + FPU_REG argSq; + long long arg_signif, argSqSq; + + + exponent = arg->exp - EXP_BIAS; + + if (arg->tag == TW_Zero) { + /* Return 0.0 */ + reg_move(&CONST_Z, y_reg); + return; + } + if (exponent >= -1) { + /* argument is in the range [0.5 .. 1.0] */ + if (exponent >= 0) { +#ifdef PARANOID + if ((exponent == 0) && + (arg->sigl == 0) && (arg->sigh == 0x80000000)) +#endif /* PARANOID */ + { + arith_overflow(y_reg); + return; + } +#ifdef PARANOID + EXCEPTION(EX_INTERNAL | 0x104); /* There must be a logic + * error */ + return; +#endif /* PARANOID */ + } + /* The argument is in the range [0.5 .. 1.0) */ + /* Convert the argument to a number in the range (0.0 .. 0.5] */ + *((long long *) (&arg->sigl)) = -*((long long *) (&arg->sigl)); + normalize(arg); /* Needed later */ + exponent = arg->exp - EXP_BIAS; + invert = 1; + } +#ifdef PARANOID + if (arg->sign != 0) { /* Can't hack a number < 0.0 */ + arith_invalid(y_reg); + return; + } /* Need a positive number */ +#endif /* PARANOID */ + + *(long long *) &arg_signif = *(long long *) &(arg->sigl); + if (exponent < -1) { + /* shift the argument right by the required places */ + if (shrx(&arg_signif, -1 - exponent) >= (unsigned)0x80000000) + arg_signif++; /* round up */ + } + mul64(&arg_signif, &arg_signif, (long long *) (&argSq.sigl)); + mul64((long long *) (&argSq.sigl), (long long *) (&argSq.sigl), &argSqSq); + + /* will be a valid positive nr with expon = 0 */ + *(short *) &(pos_poly.sign) = 0; + pos_poly.exp = EXP_BIAS; + + /* Do the basic fixed point polynomial evaluation */ + polynomial((u_int *) &pos_poly.sigl, (unsigned *) &argSqSq, oddplterms, HIPOWERop - 1); + + /* will be a valid positive nr with expon = 0 */ + *(short *) &(neg_poly.sign) = 0; + neg_poly.exp = EXP_BIAS; + + /* Do the basic fixed point polynomial evaluation */ + polynomial((u_int *) &neg_poly.sigl, (unsigned *) &argSqSq, oddnegterms, HIPOWERon - 1); + mul64((long long *) (&argSq.sigl), (long long *) (&neg_poly.sigl), + (long long *) (&neg_poly.sigl)); + + /* Subtract the mantissas */ + *((long long *) (&pos_poly.sigl)) -= *((long long *) (&neg_poly.sigl)); + + /* Convert to 64 bit signed-compatible */ + pos_poly.exp -= 1; + + reg_move(&pos_poly, &odd_poly); + normalize(&odd_poly); + + reg_mul(&odd_poly, arg, &odd_poly, FULL_PRECISION); + reg_u_add(&odd_poly, arg, &odd_poly, FULL_PRECISION); /* This is just the odd + * polynomial */ + + + /* will be a valid positive nr with expon = 0 */ + *(short *) &(pos_poly.sign) = 0; + pos_poly.exp = EXP_BIAS; + + /* Do the basic fixed point polynomial evaluation */ + polynomial((u_int *) &pos_poly.sigl, (unsigned *) &argSqSq, evenplterms, HIPOWERep - 1); + mul64((long long *) (&argSq.sigl), + (long long *) (&pos_poly.sigl), (long long *) (&pos_poly.sigl)); + + /* will be a valid positive nr with expon = 0 */ + *(short *) &(neg_poly.sign) = 0; + neg_poly.exp = EXP_BIAS; + + /* Do the basic fixed point polynomial evaluation */ + polynomial((u_int *) &neg_poly.sigl, (unsigned *) &argSqSq, evennegterms, HIPOWERen - 1); + + /* Subtract the mantissas */ + *((long long *) (&neg_poly.sigl)) -= *((long long *) (&pos_poly.sigl)); + /* and multiply by argSq */ + + /* Convert argSq to a valid reg number */ + *(short *) &(argSq.sign) = 0; + argSq.exp = EXP_BIAS - 1; + normalize(&argSq); + + /* Convert to 64 bit signed-compatible */ + neg_poly.exp -= 1; + + reg_move(&neg_poly, &even_poly); + normalize(&even_poly); + + reg_mul(&even_poly, &argSq, &even_poly, FULL_PRECISION); + reg_add(&even_poly, &argSq, &even_poly, FULL_PRECISION); + reg_sub(&CONST_1, &even_poly, &even_poly, FULL_PRECISION); /* This is just the even + * polynomial */ + + /* Now ready to copy the results */ + if (invert) { + reg_div(&even_poly, &odd_poly, y_reg, FULL_PRECISION); + } else { + reg_div(&odd_poly, &even_poly, y_reg, FULL_PRECISION); + } + +} diff --git a/pool/shard004/C/0099138_Altaircallback.c b/pool/shard004/C/0099138_Altaircallback.c new file mode 100644 index 0000000000000000000000000000000000000000..032c2f0853c102f4dca9c2cb0f4c4fd41ae1805c --- /dev/null +++ b/pool/shard004/C/0099138_Altaircallback.c @@ -0,0 +1,85 @@ +/***************************************************************************** + * + * Altaircallback.c -- Thread for handling callbacks to user code + * + * Copyright 2016 James Fidell (james@openastroproject.org) + * + * License: + * + * This file is part of the Open Astro Project. + * + * The Open Astro Project is free software: you can redistribute it and/or + * modify it under the terms of the GNU General Public License as published + * by the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * The Open Astro Project is distributed in the hope that it will be + * useful, but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with the Open Astro Project. If not, see + * . + * + *****************************************************************************/ + +#include + +#include + +#include + +#include "oacamprivate.h" +#include "unimplemented.h" +#include "Altairoacam.h" +#include "Altairstate.h" + + +void* +oacamAltaircallbackHandler ( void* param ) +{ + oaCamera* camera = param; + ALTAIRCAM_STATE* cameraInfo = camera->_private; + int exitThread = 0; + CALLBACK* callback; + void* (*callbackFunc)( void*, void*, int); + + do { + pthread_mutex_lock ( &cameraInfo->callbackQueueMutex ); + exitThread = cameraInfo->stopCallbackThread; + pthread_mutex_unlock ( &cameraInfo->callbackQueueMutex ); + + if ( exitThread ) { + break; + } else { + // try to prevent busy-waiting + if ( oaDLListIsEmpty ( cameraInfo->callbackQueue )) { + pthread_mutex_lock ( &cameraInfo->callbackQueueMutex ); + pthread_cond_wait ( &cameraInfo->callbackQueued, + &cameraInfo->callbackQueueMutex ); + pthread_mutex_unlock ( &cameraInfo->callbackQueueMutex ); + } + } + + callback = oaDLListRemoveFromHead ( cameraInfo->callbackQueue ); + if ( callback ) { + switch ( callback->callbackType ) { + case OA_CALLBACK_NEW_FRAME: + callbackFunc = callback->callback; + callbackFunc ( callback->callbackArg, callback->buffer, + callback->bufferLen ); + pthread_mutex_lock ( &cameraInfo->callbackQueueMutex ); + cameraInfo->buffersFree++; + pthread_mutex_unlock ( &cameraInfo->callbackQueueMutex ); + break; + default: + fprintf ( stderr, "unexpected callback type %d\n", + callback->callbackType ); + break; + } + } + } while ( 1 ); + + return 0; +} diff --git a/pool/shard004/C/0099142_test.c b/pool/shard004/C/0099142_test.c new file mode 100644 index 0000000000000000000000000000000000000000..d7d4bc67d179ee1aaee55dbf36787e1085bcbc45 --- /dev/null +++ b/pool/shard004/C/0099142_test.c @@ -0,0 +1,155 @@ +/* + * This file is part of autosync. + * + * Copyright (C) 2013 Sergey Zolotorev + * + * 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 "autosync.c" + +#define HOST_CONF "autosync.conf" +#define HOST_CONF_ENTRY_COUNT 2 + +#define MOUNT_CONF ".autosync" +#define MOUNT_CONF_ENTRY_COUNT 1 + +typedef struct { + gchar *dir; +} fixture_s; + +static void test_mount_not_permitted (); +static void test_mount_permitted (); +static void test_parse_host_conf (); +static void test_parse_mount_conf (); +static void test_setup (gpointer fixture, gconstpointer user_data); +static void test_sync_dir (gpointer fixture, gconstpointer user_data); +static void test_sync_file (gpointer fixture, gconstpointer user_data); +static void test_teardown (gpointer fixture, gconstpointer user_data); + +static void +test_mount_not_permitted () +{ + GSList *list; + list = autosync_parse_host_conf (HOST_CONF); + g_assert (!autosync_is_mount_permitted (list, "not-permitted")); + g_slist_free_full (list, g_free); +} + +static void +test_mount_permitted () +{ + GSList *list; + list = autosync_parse_host_conf (HOST_CONF); + + /* TODO: replace g_slist_nth_data with g_slist_find_custom */ + g_assert (autosync_is_mount_permitted (list, "foo")); + g_assert (autosync_is_mount_permitted (list, "bar")); + + g_slist_free_full (list, g_free); +} + +static void +test_parse_host_conf () +{ + GSList *list; + + list = autosync_parse_host_conf (HOST_CONF); + + g_assert (list); + g_assert_cmpuint (g_slist_length (list), ==, HOST_CONF_ENTRY_COUNT); + + /* TODO: replace g_slist_nth_data with g_slist_find_custom */ + g_assert_cmpstr (g_slist_nth_data (list, 1), ==, "foo"); + g_assert_cmpstr (g_slist_nth_data (list, 0), ==, "bar"); + + g_slist_free_full (list, g_free); +} + +static void +test_parse_mount_conf () +{ + GSList *list; + + list = autosync_parse_mount_conf (MOUNT_CONF); + + g_assert (list); + g_assert_cmpuint (g_slist_length (list), ==, MOUNT_CONF_ENTRY_COUNT); + + /* TODO: replace g_slist_nth_data with g_slist_find_custom */ + g_assert_cmpstr (g_slist_nth_data (list, 0), ==, "/etc/issue"); + + g_slist_free_full (list, g_free); +} + +static void +test_setup (gpointer fixture, gconstpointer user_data) +{ + fixture_s *f = (fixture_s *) fixture; + + f->dir = g_dir_make_tmp (NULL, NULL); + g_assert (f->dir); +} + +static void +test_sync_dir (gpointer fixture, gconstpointer user_data) +{ + fixture_s *f = (fixture_s *) fixture; + + g_assert (autosync_sync ("sources", f->dir)); +} + +static void +test_sync_file (gpointer fixture, gconstpointer user_data) +{ + fixture_s *f = (fixture_s *) fixture; + + g_assert (autosync_sync ("sources/file1", f->dir)); +} + +static void +test_teardown (gpointer fixture, gconstpointer user_data) +{ + fixture_s *f = (fixture_s *) fixture; + + g_rmdir (f->dir); + g_free (f->dir); + + f->dir = NULL; +} + +int +main (int argc, char *argv[]) +{ + fixture_s fixture; + + g_test_init (&argc, &argv, NULL); + + g_test_add_func ("/autosync/test_mount_not_permitted", test_mount_not_permitted); + g_test_add_func ("/autosync/test_mount_permitted", test_mount_permitted); + g_test_add_func ("/autosync/test_parse_host_conf", test_parse_host_conf); + g_test_add_func ("/autosync/test_parse_mount_conf", test_parse_mount_conf); + + g_test_add ("/autosync/test_sync_dir", fixture_s, &fixture, + test_setup, test_sync_dir, test_teardown); + g_test_add ("/autosync/test_sync_file", fixture_s, &fixture, + test_setup, test_sync_file, test_teardown); + + return g_test_run (); +} diff --git a/pool/shard004/C/0099143_wl1251_io.c b/pool/shard004/C/0099143_wl1251_io.c new file mode 100644 index 0000000000000000000000000000000000000000..f338701305bdb99e2b36ac89e69f3c9a03986769 --- /dev/null +++ b/pool/shard004/C/0099143_wl1251_io.c @@ -0,0 +1,195 @@ +/* + * This file is part of wl12xx + * + * Copyright (C) 2008 Nokia Corporation + * + * Contact: Kalle Valo + * + * 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 "wl1251.h" +#include "wl1251_reg.h" +#include "wl1251_io.h" + +static enum wl12xx_acx_int_reg wl1251_io_reg_table[ACX_REG_TABLE_LEN] = { + [ACX_REG_INTERRUPT_TRIG] = (REGISTERS_BASE + 0x0474), + [ACX_REG_INTERRUPT_TRIG_H] = (REGISTERS_BASE + 0x0478), + [ACX_REG_INTERRUPT_MASK] = (REGISTERS_BASE + 0x0494), + [ACX_REG_HINT_MASK_SET] = (REGISTERS_BASE + 0x0498), + [ACX_REG_HINT_MASK_CLR] = (REGISTERS_BASE + 0x049C), + [ACX_REG_INTERRUPT_NO_CLEAR] = (REGISTERS_BASE + 0x04B0), + [ACX_REG_INTERRUPT_CLEAR] = (REGISTERS_BASE + 0x04A4), + [ACX_REG_INTERRUPT_ACK] = (REGISTERS_BASE + 0x04A8), + [ACX_REG_SLV_SOFT_RESET] = (REGISTERS_BASE + 0x0000), + [ACX_REG_EE_START] = (REGISTERS_BASE + 0x080C), + [ACX_REG_ECPU_CONTROL] = (REGISTERS_BASE + 0x0804) +}; + +static int wl1251_translate_reg_addr(struct wl1251 *wl, int addr) +{ + /* If the address is lower than REGISTERS_BASE, it means that this is + * a chip-specific register address, so look it up in the registers + * table */ + if (addr < REGISTERS_BASE) { + /* Make sure we don't go over the table */ + if (addr >= ACX_REG_TABLE_LEN) { + wl1251_error("address out of range (%d)", addr); + return -EINVAL; + } + addr = wl1251_io_reg_table[addr]; + } + + return addr - wl->physical_reg_addr + wl->virtual_reg_addr; +} + +static int wl1251_translate_mem_addr(struct wl1251 *wl, int addr) +{ + return addr - wl->physical_mem_addr + wl->virtual_mem_addr; +} + +void wl1251_mem_read(struct wl1251 *wl, int addr, void *buf, size_t len) +{ + int physical; + + physical = wl1251_translate_mem_addr(wl, addr); + + wl->if_ops->read(wl, physical, buf, len); +} + +void wl1251_mem_write(struct wl1251 *wl, int addr, void *buf, size_t len) +{ + int physical; + + physical = wl1251_translate_mem_addr(wl, addr); + + wl->if_ops->write(wl, physical, buf, len); +} + +u32 wl1251_mem_read32(struct wl1251 *wl, int addr) +{ + return wl1251_read32(wl, wl1251_translate_mem_addr(wl, addr)); +} + +void wl1251_mem_write32(struct wl1251 *wl, int addr, u32 val) +{ + wl1251_write32(wl, wl1251_translate_mem_addr(wl, addr), val); +} + +u32 wl1251_reg_read32(struct wl1251 *wl, int addr) +{ + return wl1251_read32(wl, wl1251_translate_reg_addr(wl, addr)); +} + +void wl1251_reg_write32(struct wl1251 *wl, int addr, u32 val) +{ + wl1251_write32(wl, wl1251_translate_reg_addr(wl, addr), val); +} + +/* Set the partitions to access the chip addresses. + * + * There are two VIRTUAL partitions (the memory partition and the + * registers partition), which are mapped to two different areas of the + * PHYSICAL (hardware) memory. This function also makes other checks to + * ensure that the partitions are not overlapping. In the diagram below, the + * memory partition comes before the register partition, but the opposite is + * also supported. + * + * PHYSICAL address + * space + * + * | | + * ...+----+--> mem_start + * VIRTUAL address ... | | + * space ... | | [PART_0] + * ... | | + * 0x00000000 <--+----+... ...+----+--> mem_start + mem_size + * | | ... | | + * |MEM | ... | | + * | | ... | | + * part_size <--+----+... | | {unused area) + * | | ... | | + * |REG | ... | | + * part_size | | ... | | + * + <--+----+... ...+----+--> reg_start + * reg_size ... | | + * ... | | [PART_1] + * ... | | + * ...+----+--> reg_start + reg_size + * | | + * + */ +void wl1251_set_partition(struct wl1251 *wl, + u32 mem_start, u32 mem_size, + u32 reg_start, u32 reg_size) +{ + struct wl1251_partition partition[2]; + + wl1251_debug(DEBUG_SPI, "mem_start %08X mem_size %08X", + mem_start, mem_size); + wl1251_debug(DEBUG_SPI, "reg_start %08X reg_size %08X", + reg_start, reg_size); + + /* Make sure that the two partitions together don't exceed the + * address range */ + if ((mem_size + reg_size) > HW_ACCESS_MEMORY_MAX_RANGE) { + wl1251_debug(DEBUG_SPI, "Total size exceeds maximum virtual" + " address range. Truncating partition[0]."); + mem_size = HW_ACCESS_MEMORY_MAX_RANGE - reg_size; + wl1251_debug(DEBUG_SPI, "mem_start %08X mem_size %08X", + mem_start, mem_size); + wl1251_debug(DEBUG_SPI, "reg_start %08X reg_size %08X", + reg_start, reg_size); + } + + if ((mem_start < reg_start) && + ((mem_start + mem_size) > reg_start)) { + /* Guarantee that the memory partition doesn't overlap the + * registers partition */ + wl1251_debug(DEBUG_SPI, "End of partition[0] is " + "overlapping partition[1]. Adjusted."); + mem_size = reg_start - mem_start; + wl1251_debug(DEBUG_SPI, "mem_start %08X mem_size %08X", + mem_start, mem_size); + wl1251_debug(DEBUG_SPI, "reg_start %08X reg_size %08X", + reg_start, reg_size); + } else if ((reg_start < mem_start) && + ((reg_start + reg_size) > mem_start)) { + /* Guarantee that the register partition doesn't overlap the + * memory partition */ + wl1251_debug(DEBUG_SPI, "End of partition[1] is" + " overlapping partition[0]. Adjusted."); + reg_size = mem_start - reg_start; + wl1251_debug(DEBUG_SPI, "mem_start %08X mem_size %08X", + mem_start, mem_size); + wl1251_debug(DEBUG_SPI, "reg_start %08X reg_size %08X", + reg_start, reg_size); + } + + partition[0].start = mem_start; + partition[0].size = mem_size; + partition[1].start = reg_start; + partition[1].size = reg_size; + + wl->physical_mem_addr = mem_start; + wl->physical_reg_addr = reg_start; + + wl->virtual_mem_addr = 0; + wl->virtual_reg_addr = mem_size; + + wl->if_ops->write(wl, HW_ACCESS_PART0_SIZE_ADDR, partition, + sizeof(partition)); +} diff --git a/pool/shard004/C/0099147_nis_support.c b/pool/shard004/C/0099147_nis_support.c new file mode 100644 index 0000000000000000000000000000000000000000..ec724475fac8fb0bc60bdb0aa9438a21506b36b5 --- /dev/null +++ b/pool/shard004/C/0099147_nis_support.c @@ -0,0 +1,52 @@ +/* + * Written By Rabellino Sergio (rabellino@di.unito.it) For Solaris 2.x + */ + +#include +#include +#include +#include +#include +#include +#include +#include + +#include "nis_support.h" + +#define NO_YPERR 0 /* There is no error */ + +char * +get_nis_password(char *user, char *nisdomain, char *nismap) +{ + static char *val = NULL; + char *password = NULL; + int vallen, res; + +#ifdef DEBUG + printf("Domain is set to %s\n", nisdomain); + printf("YP Map is set to %s\n", nismap); +#endif + + /* Free last entry */ + if (val) { + free(val); + val = NULL; + } + + /* Get NIS entry */ + res = yp_match(nisdomain, nismap, user, strlen(user), &val, &vallen); + + switch (res) { + case NO_YPERR: + /* username = */ (void) strtok(val, ":"); + password = strtok(NULL, ",:"); + return password; + case YPERR_YPBIND: + syslog(LOG_ERR, "Squid Authentication through ypbind failure: can't communicate with ypbind"); + return NULL; + case YPERR_KEY: /* No such key in map */ + return NULL; + default: + return NULL; + } +} diff --git a/pool/shard004/C/0099148_takdec.c b/pool/shard004/C/0099148_takdec.c new file mode 100644 index 0000000000000000000000000000000000000000..a8fb363b34beb6f3fb9aae2197a86ed538b38e06 --- /dev/null +++ b/pool/shard004/C/0099148_takdec.c @@ -0,0 +1,214 @@ +/* + * Raw TAK demuxer + * Copyright (c) 2012 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/crc.h" + +#define BITSTREAM_READER_LE +#include "libavcodec/tak.h" + +#include "apetag.h" +#include "avformat.h" +#include "avio_internal.h" +#include "internal.h" +#include "rawdec.h" + +typedef struct TAKDemuxContext { + int mlast_frame; + int64_t data_end; +} TAKDemuxContext; + +static int tak_probe(AVProbeData *p) +{ + if (!memcmp(p->buf, "tBaK", 4)) + return AVPROBE_SCORE_EXTENSION; + return 0; +} + +static unsigned long tak_check_crc(unsigned long checksum, const uint8_t *buf, + unsigned int len) +{ + return av_crc(av_crc_get_table(AV_CRC_24_IEEE), checksum, buf, len); +} + +static int tak_read_header(AVFormatContext *s) +{ + TAKDemuxContext *tc = s->priv_data; + AVIOContext *pb = s->pb; + GetBitContext gb; + AVStream *st; + uint8_t *buffer = NULL; + int ret; + + st = avformat_new_stream(s, 0); + if (!st) + return AVERROR(ENOMEM); + + st->codecpar->codec_type = AVMEDIA_TYPE_AUDIO; + st->codecpar->codec_id = AV_CODEC_ID_TAK; + st->need_parsing = AVSTREAM_PARSE_FULL_RAW; + + tc->mlast_frame = 0; + if (avio_rl32(pb) != MKTAG('t', 'B', 'a', 'K')) { + avio_seek(pb, -4, SEEK_CUR); + return 0; + } + + while (!avio_feof(pb)) { + enum TAKMetaDataType type; + int size; + + type = avio_r8(pb) & 0x7f; + size = avio_rl24(pb); + + switch (type) { + case TAK_METADATA_STREAMINFO: + case TAK_METADATA_LAST_FRAME: + case TAK_METADATA_ENCODER: + if (size <= 3) + return AVERROR_INVALIDDATA; + + buffer = av_malloc(size - 3 + AV_INPUT_BUFFER_PADDING_SIZE); + if (!buffer) + return AVERROR(ENOMEM); + memset(buffer + size - 3, 0, AV_INPUT_BUFFER_PADDING_SIZE); + + ffio_init_checksum(pb, tak_check_crc, 0xCE04B7U); + if (avio_read(pb, buffer, size - 3) != size - 3) { + av_freep(&buffer); + return AVERROR(EIO); + } + if (ffio_get_checksum(s->pb) != avio_rb24(pb)) { + av_log(s, AV_LOG_ERROR, "%d metadata block CRC error.\n", type); + if (s->error_recognition & AV_EF_EXPLODE) { + av_freep(&buffer); + return AVERROR_INVALIDDATA; + } + } + + init_get_bits8(&gb, buffer, size - 3); + break; + case TAK_METADATA_MD5: { + uint8_t md5[16]; + int i; + + if (size != 19) + return AVERROR_INVALIDDATA; + ffio_init_checksum(pb, tak_check_crc, 0xCE04B7U); + avio_read(pb, md5, 16); + if (ffio_get_checksum(s->pb) != avio_rb24(pb)) { + av_log(s, AV_LOG_ERROR, "MD5 metadata block CRC error.\n"); + if (s->error_recognition & AV_EF_EXPLODE) + return AVERROR_INVALIDDATA; + } + + av_log(s, AV_LOG_VERBOSE, "MD5="); + for (i = 0; i < 16; i++) + av_log(s, AV_LOG_VERBOSE, "%02x", md5[i]); + av_log(s, AV_LOG_VERBOSE, "\n"); + break; + } + case TAK_METADATA_END: { + int64_t curpos = avio_tell(pb); + + if (pb->seekable) { + ff_ape_parse_tag(s); + avio_seek(pb, curpos, SEEK_SET); + } + + tc->data_end += curpos; + return 0; + } + default: + ret = avio_skip(pb, size); + if (ret < 0) + return ret; + } + + if (type == TAK_METADATA_STREAMINFO) { + TAKStreamInfo ti; + + avpriv_tak_parse_streaminfo(&gb, &ti); + if (ti.samples > 0) + st->duration = ti.samples; + st->codecpar->bits_per_coded_sample = ti.bps; + if (ti.ch_layout) + st->codecpar->channel_layout = ti.ch_layout; + st->codecpar->sample_rate = ti.sample_rate; + st->codecpar->channels = ti.channels; + st->start_time = 0; + avpriv_set_pts_info(st, 64, 1, st->codecpar->sample_rate); + st->codecpar->extradata = buffer; + st->codecpar->extradata_size = size - 3; + buffer = NULL; + } else if (type == TAK_METADATA_LAST_FRAME) { + if (size != 11) + return AVERROR_INVALIDDATA; + tc->mlast_frame = 1; + tc->data_end = get_bits64(&gb, TAK_LAST_FRAME_POS_BITS) + + get_bits(&gb, TAK_LAST_FRAME_SIZE_BITS); + av_freep(&buffer); + } else if (type == TAK_METADATA_ENCODER) { + av_log(s, AV_LOG_VERBOSE, "encoder version: %0X\n", + get_bits_long(&gb, TAK_ENCODER_VERSION_BITS)); + av_freep(&buffer); + } + } + + return AVERROR_EOF; +} + +static int raw_read_packet(AVFormatContext *s, AVPacket *pkt) +{ + TAKDemuxContext *tc = s->priv_data; + int ret; + + if (tc->mlast_frame) { + AVIOContext *pb = s->pb; + int64_t size, left; + + left = tc->data_end - avio_tell(pb); + size = FFMIN(left, 1024); + if (size <= 0) + return AVERROR_EOF; + + ret = av_get_packet(pb, pkt, size); + if (ret < 0) + return ret; + + pkt->stream_index = 0; + } else { + ret = ff_raw_read_partial_packet(s, pkt); + } + + return ret; +} + +AVInputFormat ff_tak_demuxer = { + .name = "tak", + .long_name = NULL_IF_CONFIG_SMALL("raw TAK"), + .priv_data_size = sizeof(TAKDemuxContext), + .read_probe = tak_probe, + .read_header = tak_read_header, + .read_packet = raw_read_packet, + .flags = AVFMT_GENERIC_INDEX, + .extensions = "tak", + .raw_codec_id = AV_CODEC_ID_TAK, +}; diff --git a/pool/shard004/C/0099152_hda-pcm.c b/pool/shard004/C/0099152_hda-pcm.c new file mode 100644 index 0000000000000000000000000000000000000000..5d35bb18660aefbd4dd8ec512e21d28ec87d6d82 --- /dev/null +++ b/pool/shard004/C/0099152_hda-pcm.c @@ -0,0 +1,257 @@ +// SPDX-License-Identifier: (GPL-2.0-only OR BSD-3-Clause) +// +// This file is provided under a dual BSD/GPLv2 license. When using or +// redistributing this file, you may do so under either license. +// +// Copyright(c) 2018 Intel Corporation. All rights reserved. +// +// Authors: Liam Girdwood +// Ranjani Sridharan +// Rander Wang +// Keyon Jie +// + +/* + * Hardware interface for generic Intel audio DSP HDA IP + */ + +#include +#include +#include "../sof-audio.h" +#include "../ops.h" +#include "hda.h" + +#define SDnFMT_BASE(x) ((x) << 14) +#define SDnFMT_MULT(x) (((x) - 1) << 11) +#define SDnFMT_DIV(x) (((x) - 1) << 8) +#define SDnFMT_BITS(x) ((x) << 4) +#define SDnFMT_CHAN(x) ((x) << 0) + +u32 hda_dsp_get_mult_div(struct snd_sof_dev *sdev, int rate) +{ + switch (rate) { + case 8000: + return SDnFMT_DIV(6); + case 9600: + return SDnFMT_DIV(5); + case 11025: + return SDnFMT_BASE(1) | SDnFMT_DIV(4); + case 16000: + return SDnFMT_DIV(3); + case 22050: + return SDnFMT_BASE(1) | SDnFMT_DIV(2); + case 32000: + return SDnFMT_DIV(3) | SDnFMT_MULT(2); + case 44100: + return SDnFMT_BASE(1); + case 48000: + return 0; + case 88200: + return SDnFMT_BASE(1) | SDnFMT_MULT(2); + case 96000: + return SDnFMT_MULT(2); + case 176400: + return SDnFMT_BASE(1) | SDnFMT_MULT(4); + case 192000: + return SDnFMT_MULT(4); + default: + dev_warn(sdev->dev, "can't find div rate %d using 48kHz\n", + rate); + return 0; /* use 48KHz if not found */ + } +}; + +u32 hda_dsp_get_bits(struct snd_sof_dev *sdev, int sample_bits) +{ + switch (sample_bits) { + case 8: + return SDnFMT_BITS(0); + case 16: + return SDnFMT_BITS(1); + case 20: + return SDnFMT_BITS(2); + case 24: + return SDnFMT_BITS(3); + case 32: + return SDnFMT_BITS(4); + default: + dev_warn(sdev->dev, "can't find %d bits using 16bit\n", + sample_bits); + return SDnFMT_BITS(1); /* use 16bits format if not found */ + } +}; + +int hda_dsp_pcm_hw_params(struct snd_sof_dev *sdev, + struct snd_pcm_substream *substream, + struct snd_pcm_hw_params *params, + struct sof_ipc_stream_params *ipc_params) +{ + struct hdac_stream *hstream = substream->runtime->private_data; + struct hdac_ext_stream *stream = stream_to_hdac_ext_stream(hstream); + struct sof_intel_hda_dev *hda = sdev->pdata->hw_pdata; + struct snd_dma_buffer *dmab; + struct sof_ipc_fw_version *v = &sdev->fw_ready.version; + int ret; + u32 size, rate, bits; + + size = params_buffer_bytes(params); + rate = hda_dsp_get_mult_div(sdev, params_rate(params)); + bits = hda_dsp_get_bits(sdev, params_width(params)); + + hstream->substream = substream; + + dmab = substream->runtime->dma_buffer_p; + + hstream->format_val = rate | bits | (params_channels(params) - 1); + hstream->bufsize = size; + hstream->period_bytes = params_period_bytes(params); + hstream->no_period_wakeup = + (params->info & SNDRV_PCM_INFO_NO_PERIOD_WAKEUP) && + (params->flags & SNDRV_PCM_HW_PARAMS_NO_PERIOD_WAKEUP); + + ret = hda_dsp_stream_hw_params(sdev, stream, dmab, params); + if (ret < 0) { + dev_err(sdev->dev, "error: hdac prepare failed: %x\n", ret); + return ret; + } + + /* disable SPIB, to enable buffer wrap for stream */ + hda_dsp_stream_spib_config(sdev, stream, HDA_DSP_SPIB_DISABLE, 0); + + /* update no_stream_position flag for ipc params */ + if (hda && hda->no_ipc_position) { + /* For older ABIs set host_period_bytes to zero to inform + * FW we don't want position updates. Newer versions use + * no_stream_position for this purpose. + */ + if (v->abi_version < SOF_ABI_VER(3, 10, 0)) + ipc_params->host_period_bytes = 0; + else + ipc_params->no_stream_position = 1; + } + + ipc_params->stream_tag = hstream->stream_tag; + + return 0; +} + +int hda_dsp_pcm_trigger(struct snd_sof_dev *sdev, + struct snd_pcm_substream *substream, int cmd) +{ + struct hdac_stream *hstream = substream->runtime->private_data; + struct hdac_ext_stream *stream = stream_to_hdac_ext_stream(hstream); + + return hda_dsp_stream_trigger(sdev, stream, cmd); +} + +snd_pcm_uframes_t hda_dsp_pcm_pointer(struct snd_sof_dev *sdev, + struct snd_pcm_substream *substream) +{ + struct snd_soc_pcm_runtime *rtd = asoc_substream_to_rtd(substream); + struct snd_soc_component *scomp = sdev->component; + struct hdac_stream *hstream = substream->runtime->private_data; + struct sof_intel_hda_dev *hda = sdev->pdata->hw_pdata; + struct snd_sof_pcm *spcm; + snd_pcm_uframes_t pos; + + spcm = snd_sof_find_spcm_dai(scomp, rtd); + if (!spcm) { + dev_warn_ratelimited(sdev->dev, "warn: can't find PCM with DAI ID %d\n", + rtd->dai_link->id); + return 0; + } + + if (hda && !hda->no_ipc_position) { + /* read position from IPC position */ + pos = spcm->stream[substream->stream].posn.host_posn; + goto found; + } + + /* + * DPIB/posbuf position mode: + * For Playback, Use DPIB register from HDA space which + * reflects the actual data transferred. + * For Capture, Use the position buffer for pointer, as DPIB + * is not accurate enough, its update may be completed + * earlier than the data written to DDR. + */ + if (substream->stream == SNDRV_PCM_STREAM_PLAYBACK) { + pos = snd_sof_dsp_read(sdev, HDA_DSP_HDA_BAR, + AZX_REG_VS_SDXDPIB_XBASE + + (AZX_REG_VS_SDXDPIB_XINTERVAL * + hstream->index)); + } else { + /* + * For capture stream, we need more workaround to fix the + * position incorrect issue: + * + * 1. Wait at least 20us before reading position buffer after + * the interrupt generated(IOC), to make sure position update + * happens on frame boundary i.e. 20.833uSec for 48KHz. + * 2. Perform a dummy Read to DPIB register to flush DMA + * position value. + * 3. Read the DMA Position from posbuf. Now the readback + * value should be >= period boundary. + */ + usleep_range(20, 21); + snd_sof_dsp_read(sdev, HDA_DSP_HDA_BAR, + AZX_REG_VS_SDXDPIB_XBASE + + (AZX_REG_VS_SDXDPIB_XINTERVAL * + hstream->index)); + pos = snd_hdac_stream_get_pos_posbuf(hstream); + } + + if (pos >= hstream->bufsize) + pos = 0; + +found: + pos = bytes_to_frames(substream->runtime, pos); + + dev_vdbg(sdev->dev, "PCM: stream %d dir %d position %lu\n", + hstream->index, substream->stream, pos); + return pos; +} + +int hda_dsp_pcm_open(struct snd_sof_dev *sdev, + struct snd_pcm_substream *substream) +{ + struct hdac_ext_stream *dsp_stream; + int direction = substream->stream; + + dsp_stream = hda_dsp_stream_get(sdev, direction); + + if (!dsp_stream) { + dev_err(sdev->dev, "error: no stream available\n"); + return -ENODEV; + } + + /* minimum as per HDA spec */ + snd_pcm_hw_constraint_step(substream->runtime, 0, SNDRV_PCM_HW_PARAM_PERIOD_BYTES, 4); + + /* avoid circular buffer wrap in middle of period */ + snd_pcm_hw_constraint_integer(substream->runtime, + SNDRV_PCM_HW_PARAM_PERIODS); + + /* binding pcm substream to hda stream */ + substream->runtime->private_data = &dsp_stream->hstream; + return 0; +} + +int hda_dsp_pcm_close(struct snd_sof_dev *sdev, + struct snd_pcm_substream *substream) +{ + struct hdac_stream *hstream = substream->runtime->private_data; + int direction = substream->stream; + int ret; + + ret = hda_dsp_stream_put(sdev, direction, hstream->stream_tag); + + if (ret) { + dev_dbg(sdev->dev, "stream %s not opened!\n", substream->name); + return -ENODEV; + } + + /* unbinding pcm substream to hda stream */ + substream->runtime->private_data = NULL; + return 0; +} diff --git a/pool/shard004/C/0099155_7-1.c b/pool/shard004/C/0099155_7-1.c new file mode 100644 index 0000000000000000000000000000000000000000..58ec293064f9f6487d0004cf346afde5b5a42b3a --- /dev/null +++ b/pool/shard004/C/0099155_7-1.c @@ -0,0 +1,165 @@ +/* +* Copyright (c) 2004, 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 assertion: +* +* The child process gets a copy of the parent message catalog descriptor. + +* The steps are: +* -> Create a message catalog file from the file +* -> Open this catalog +* -> fork +* -> Check that the child can read from the message catalog. + +* The test fails if the message catalog is read in the parent and not in the child. + +*/ + +/* We are testing conformance to IEEE Std 1003.1, 2003 Edition */ +#define _POSIX_C_SOURCE 200112L + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "../testfrmw/testfrmw.h" +#include "../testfrmw/testfrmw.c" + +#ifndef VERBOSE +#define VERBOSE 1 +#endif + +#define MESSCAT_IN "messcat.txt" +#define MESSCAT_OUT "messcat.cat" + +void read_catalog(nl_catd cat, char *who) +{ + char *msg = NULL; + int i, j; + errno = 0; + +#if VERBOSE > 0 + output("Reading the message catalog from %s...\n", who); +#endif + + for (i = 1; i <= 2; i++) { + for (j = 1; j <= 2; j++) { + + msg = catgets(cat, i, j, "not found"); + + if (errno != 0) + UNRESOLVED(errno, "catgets returned an error"); +#if VERBOSE > 1 + output("set %i msg %i: %s\n", i, j, msg); +#endif + } + } + +#if VERBOSE > 0 + output("Message catalog read successfully in %s\n", who); +#endif +} + +static char *messcat_in = +"$set 1\n1 First sentence\n2 Second sentence\n" +"$set 2\n1 First translated sentence\n2 Second translated sentence\n"; + +static int create_catalog(void) +{ + FILE *f; + + if ((f = fopen(MESSCAT_IN, "w")) == NULL) { + perror("fopen"); + return 1; + } + + if (fputs(messcat_in, f) == EOF) { + perror("fputs"); + return 1; + } + + if (fclose(f) == EOF) { + perror("fclose"); + return 1; + } + + return 0; +} + +int main(int argc, char * argv[]) +{ + int ret, status; + pid_t child, ctl; + nl_catd messcat; + + output_init(); + + /* Generate the message catalog file from the text sourcefile */ + if (system(NULL)) { + + if (create_catalog() != 0) + UNRESOLVED(errno, "Can't create "MESSCAT_IN); + + ret = system("gencat "MESSCAT_OUT" "MESSCAT_IN); + + if (ret != 0) + output("Could not find the source file for message catalog.\n" \ + "You may need to execute gencat yourself.\n"); + } + + messcat = catopen("./"MESSCAT_OUT, 0); + + if (messcat == (nl_catd) -1) + UNRESOLVED(errno, "Could not open ./"MESSCAT_OUT); + + read_catalog(messcat, "parent"); + + child = fork(); + + if (child == -1) + UNRESOLVED(errno, "Failed to fork"); + + if (child == 0) { + read_catalog(messcat, "child"); + exit(PTS_PASS); + } + + ctl = waitpid(child, &status, 0); + + if (ctl != child) + UNRESOLVED(errno, "Waitpid returned the wrong PID"); + + if ((!WIFEXITED(status)) || (WEXITSTATUS(status) != PTS_PASS)) + FAILED("Child exited abnormally"); + + ret = catclose(messcat); + + if (ret != 0) + UNRESOLVED(errno, "Failed to close the message catalog"); + + system("rm -f "MESSCAT_IN" "MESSCAT_OUT); + +#if VERBOSE > 0 + output("Test passed\n"); +#endif + PASSED; +} diff --git a/pool/shard004/C/0099158_main.c b/pool/shard004/C/0099158_main.c new file mode 100644 index 0000000000000000000000000000000000000000..577bd2b77095ffbe09c86b7cba8dc8befa23137f --- /dev/null +++ b/pool/shard004/C/0099158_main.c @@ -0,0 +1,31 @@ +// +// main.c +// 20150524-5 +// +// Created by 欣 陈 on 15/5/24. +// Copyright (c) 2015年 欣 陈. All rights reserved. +// + +//解法二:定义一个结构体变量(包括年、月、日)。计算该日在本年中是第几天,注意闰年的问题 +#include +struct{ + int year; + int month; + int day; +}date; +int main(){ + int i,days; + int day_tab[13] = {0,31,28,31,30,31,30,31,31,30,31,30,31}; + printf("input year,month,day:"); + scanf("%d,%d,%d",&date.year,&date.month,&date.day); + days = 0; + for(i = 1;i < date.month;i++){ + days = days + day_tab[i]; + } + days = days + date.day; + if(((date.year % 4 == 0 && date.year % 100 != 0) || + date.year % 400 == 0) && date.month >= 3) + days = days + 1; + printf("%d/%d is the %dth day in %d.\n",date.month,date.day,days,date.year); + return 0; +} diff --git a/pool/shard004/C/0099161_string_extra.c b/pool/shard004/C/0099161_string_extra.c new file mode 100644 index 0000000000000000000000000000000000000000..7ba99dff7d59f30d21c741c27f7cfcba49a348e7 --- /dev/null +++ b/pool/shard004/C/0099161_string_extra.c @@ -0,0 +1,102 @@ +#include +#include +#include +#include +#include "string_extra.h" + +/****************************************************************/ +/*====================================================== +Remplaza una cadena de caracteres por otra. +Precondición: La cadena a reemplazar debe contener la parte para reemplazar. +Poscondición: Devuelve una cadena modificada. +=====================================================*/ +char * str_replace(char *orig, char *en, char *con){ + char *result; // the return string + char *ins; // the next insert point + char *tmp; // varies + int len_rep; // length of en + int len_with; // length of con + int len_front; // distance between en and end of last rep + int count; // number of replacements + + if (!orig) + return NULL; + if (!en) + en = ""; + len_rep = strlen(en); + if (!con) + con = ""; + len_with = strlen(con); + + ins = orig; + for (count = 0; (tmp = strstr(ins, en)); ++count) { + ins = tmp + len_rep; + } + tmp = result = malloc(strlen(orig) + (len_with - len_rep) * count + 1); + + if (!result) + return NULL; + + while (count--) { + ins = strstr(orig, en); + len_front = ins - orig; + tmp = strncpy(tmp, orig, len_front) + len_front; + tmp = strcpy(tmp, con) + len_with; + orig += len_front + len_rep; // move to next "end of rep" + } + strcpy(tmp, orig); + + return result; +} + +/****************************************************************/ +/*====================================================== +Remueve los espacios en blanco de una cadena de caracteres. +Precondición: Devuelve una cadena de caracteres sin espacios en blanco. +Poscondición: +=====================================================*/ +void remove_spaces(char *source){ + char *i = source; + char *j = source; + while(*j != 0){ + *i = *j++; + if(*i != ' ') + i++; + } + *i = 0; +} + +/****************************************************************/ +/*====================================================== +Convierte las letras en mayuscula a minuscula. +Precondición: El string tiene que existir. +Poscondición: La cadena de caracteres que devuelve tendra todas sus letras minusculas. +=====================================================*/ +void str_lower(char* s){ + for ( ; *s; ++s) *s = tolower(*s); +} + +/****************************************************************/ +/*====================================================== +Lee una linea. +Precondición: +Poscondición: Devuelve la linea completa, con la memoria necesaria. +=====================================================*/ +char *read_line(FILE *fp) { + char *str; + int ch; + size_t len = 0; + size_t size = 10; + str = realloc(NULL, sizeof(char)*size);//size is start size + if(!str)return str; + while(EOF!=(ch=fgetc(fp)) && ch != '\n'){ + str[len++]=ch; + if(len==size){ + str = realloc(str, sizeof(char)*(size+=16)); + if(!str)return str; + } + } + str[len++]='\0'; + + return realloc(str, sizeof(char)*len); +} diff --git a/pool/shard004/C/0099162_misc.c b/pool/shard004/C/0099162_misc.c new file mode 100644 index 0000000000000000000000000000000000000000..d85710f4c190eb789f5907d62ec99b198e699d31 --- /dev/null +++ b/pool/shard004/C/0099162_misc.c @@ -0,0 +1,251 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include "board.h" + +#if defined(CONFIG_JZ4775_MAC) +#ifndef CONFIG_MDIO_GPIO +#ifdef CONFIG_JZGPIO_PHY_RESET +static struct jz_gpio_phy_reset gpio_phy_reset = { + .port = GPIO_PORT_B, + .pin = 7, + .start_func = GPIO_OUTPUT0, + .end_func = GPIO_OUTPUT1, + .delaytime_usec = 100000, +}; +#endif +struct platform_device jz4775_mii_bus = { + .name = "jz4775_mii_bus", +#ifdef CONFIG_JZGPIO_PHY_RESET + .dev.platform_data = &gpio_phy_reset, +#endif +}; +#else /* CONFIG_MDIO_GPIO */ +static struct mdio_gpio_platform_data mdio_gpio_data = { + .mdc = GPF(13), + .mdio = GPF(14), + .phy_mask = 0, + .irqs = { 0 }, +}; + +struct platform_device jz4775_mii_bus = { + .name = "mdio-gpio", + .dev.platform_data = &mdio_gpio_data, +}; +#endif /* CONFIG_MDIO_GPIO */ +struct platform_device jz4775_mac_device = { + .name = "jz4775_mac", + .dev.platform_data = &jz4775_mii_bus, +}; +#endif /* CONFIG_JZ4775_MAC */ + +#ifdef CONFIG_JZ4785_SUPPORT_TSC +static struct jztsc_pin fpga_tsc_gpio[] = { + [0] = {GPIO_TP_INT, LOW_ENABLE}, + [1] = {GPIO_TP_WAKE, HIGH_ENABLE}, +}; + +static struct jztsc_platform_data fpga_tsc_pdata = { + .gpio = fpga_tsc_gpio, + .x_max = 800, + .y_max = 480, +}; + +#ifdef CONFIG_TOUCHSCREEN_GWTC9XXXB +static struct i2c_board_info fpga_i2c0_devs[] __initdata = { + { + I2C_BOARD_INFO("gwtc9xxxb_ts", 0x05), + .platform_data = &fpga_tsc_pdata, + }, +}; +#endif +#endif + +#if (defined(CONFIG_I2C_GPIO_V1_2) || defined(CONFIG_I2C1_JZ_V1_2)) + +#ifdef CONFIG_WM8594_CODEC_V1_2 +static struct snd_codec_data wm8594_codec_pdata = { + .codec_sys_clk = 12000000, +}; +#endif + +static struct i2c_board_info f4785_i2c1_devs[] __initdata = { +#ifdef CONFIG_WM8594_CODEC_V1_2 + { + I2C_BOARD_INFO("wm8594", 0x1a), + .platform_data = &wm8594_codec_pdata, + }, +#endif +}; +#endif /*I2C1*/ + +static int __init board_init(void) +{ +/*vpu*/ +#ifdef CONFIG_JZ_VPU_V1_2 + platform_device_register(&jz_vpu_device); +#endif + +/*i2c*/ +#ifdef CONFIG_I2C0_JZ_V1_2 + platform_device_register(&jz_i2c0_device); +#endif + +#ifdef CONFIG_I2C1_JZ_V1_2 + platform_device_register(&jz_i2c1_device); +#endif + +#ifdef CONFIG_I2C2_JZ_V1_2 + platform_device_register(&jz_i2c2_device); +#endif + +#ifdef CONFIG_I2C3_JZ_V1_2 + platform_device_register(&jz_i2c3_device); +#endif + +#if (defined(CONFIG_I2C_GPIO_V1_2) || defined(CONFIG_I2C1_JZ_V1_2) || defined(CONFIG_I2C1_DMA_V1_2)) + i2c_register_board_info(1, f4785_i2c1_devs, ARRAY_SIZE(f4785_i2c1_devs)); +#endif + +/*dma*/ +#ifdef CONFIG_XBURST_DMAC + platform_device_register(&jz_pdma_device); +#endif +/* panel and bl */ +#ifdef CONFIG_LCD_KD50G2_40NM_A2 + platform_device_register(&kd50g2_40nm_a2_device); +#endif +#ifdef CONFIG_LCD_BYD_BM8766U + platform_device_register(&byd_bm8766u_device); +#endif +#ifdef CONFIG_LCD_KFM701A21_1A + platform_device_register(&kfm701a21_1a_device); +#endif +#ifdef CONFIG_LCD_TRULY_TFT240240_2_E + platform_device_register(&truly_tft240240_device); +#endif +#ifdef CONFIG_LCD_CV90_M5377_P30 + platform_device_register(&cv90_m5377_p30_device); +#endif +#ifdef CONFIG_BACKLIGHT_PWM + platform_device_register(&backlight_device); +#endif +#ifdef CONFIG_BACKLIGHT_DIGITAL_PULSE + platform_device_register(&digital_pulse_backlight_device); +#endif +/* lcdc framebuffer*/ +#ifdef CONFIG_FB_JZ_V12 + jz_device_register(&jz_fb_device, &jzfb_pdata); +#endif + +/*mipi-dsi */ +#ifdef CONFIG_JZ_MIPI_DSI + jz_device_register(&jz_dsi_device, &jzdsi_pdata); +#endif + +/*ipu*/ +#if defined CONFIG_JZ_IPU_V1_2 + platform_device_register(&jz_ipu_device); +#endif + +/*touchscreen*/ +#ifdef CONFIG_JZ4785_SUPPORT_TSC + i2c_register_board_info(0, fpga_i2c0_devs, ARRAY_SIZE(fpga_i2c0_devs)); +#endif + +/* uart */ +#ifdef CONFIG_SERIAL_JZ47XX_UART0 + platform_device_register(&jz_uart0_device); +#endif +#ifdef CONFIG_SERIAL_JZ47XX_UART1 + platform_device_register(&jz_uart1_device); +#endif +#ifdef CONFIG_SERIAL_JZ47XX_UART2 + platform_device_register(&jz_uart2_device); +#endif +#ifdef CONFIG_SERIAL_JZ47XX_UART3 + platform_device_register(&jz_uart3_device); +#endif +#ifdef CONFIG_USB_OHCI_HCD + platform_device_register(&jz_ohci_device); +#endif +#ifdef CONFIG_USB_EHCI_HCD + platform_device_register(&jz_ehci_device); +#endif +#ifdef CONFIG_USB_JZ_DWC2 + platform_device_register(&jz_dwc_otg_device); +#endif +/* msc */ +#ifndef CONFIG_NAND +#ifdef CONFIG_JZMMC_V12_MMC0 + jz_device_register(&jz_msc0_device, &inand_pdata); +#endif +#ifdef CONFIG_JZMMC_V12_MMC1 + jz_device_register(&jz_msc1_device, &tf_pdata); +#endif +#ifdef CONFIG_JZMMC_V12_MMC2 + jz_device_register(&jz_msc2_device, &tf_pdata); +#endif +#else +#ifdef CONFIG_JZMMC_V12_MMC0 + jz_device_register(&jz_msc0_device, &tf_pdata); +#endif +#ifdef CONFIG_JZMMC_V12_MMC1 + jz_device_register(&jz_msc1_device, &sdio_pdata); +#endif +#endif +/* ethnet */ +#ifdef CONFIG_JZ4775_MAC + platform_device_register(&jz4775_mii_bus); + platform_device_register(&jz4775_mac_device); +#endif + +/* audio */ +#ifdef CONFIG_SOUND_JZ_I2S_V1_2 + jz_device_register(&jz_i2s_device,&i2s_data); + jz_device_register(&jz_mixer0_device,&snd_mixer0_data); +#endif +#ifdef CONFIG_SOUND_JZ_SPDIF_V1_2 + jz_device_register(&jz_spdif_device,&spdif_data); + jz_device_register(&jz_mixer2_device,&snd_mixer2_data); +#endif +#ifdef CONFIG_SOUND_JZ_DMIC_V1_2 + jz_device_register(&jz_dmic_device,&dmic_data); + jz_device_register(&jz_mixer3_device,&snd_mixer3_data); +#endif + +#ifdef CONFIG_SOUND_JZ_PCM_V1_2 + jz_device_register(&jz_pcm_device,&pcm_data); + jz_device_register(&jz_mixer1_device,&snd_mixer1_data); +#endif +#ifdef CONFIG_JZ_INTERNAL_CODEC_V1_2 + jz_device_register(&jz_codec_device, &codec_data); +#endif + /* ovisp */ +#ifdef CONFIG_VIDEO_OVISP + jz_device_register(&ovisp_device_camera, &ovisp_camera_info); +#endif + return 0; +} + +/** + * Called by arch/mips/kernel/proc.c when 'cat /proc/cpuinfo'. + * Android requires the 'Hardware:' field in cpuinfo to setup the init.%hardware%.rc. + */ +const char *get_board_type(void) +{ + return CONFIG_BOARD_NAME; +} + +arch_initcall(board_init); diff --git a/pool/shard004/C/0099165_kexec-s390.c b/pool/shard004/C/0099165_kexec-s390.c new file mode 100644 index 0000000000000000000000000000000000000000..15c28376b1c62680246c426aa2975cf9f017c783 --- /dev/null +++ b/pool/shard004/C/0099165_kexec-s390.c @@ -0,0 +1,115 @@ +/* + * kexec/arch/s390/kexec-s390.c + * + * (C) Copyright IBM Corp. 2005 + * + * Author(s): Rolf Adelsberger + * + */ + +#define _GNU_SOURCE +#include +#include +#include +#include +#include +#include +#include "../../kexec.h" +#include "../../kexec-syscall.h" +#include "kexec-s390.h" +#include + +#define MAX_MEMORY_RANGES 64 +static struct memory_range memory_range[MAX_MEMORY_RANGES]; + +/* + * get_memory_ranges: + * Return a list of memory ranges by parsing the file returned by + * proc_iomem() + * + * INPUT: + * - Pointer to an array of memory_range structures. + * - Pointer to an integer with holds the number of memory ranges. + * + * RETURN: + * - 0 on normal execution. + * - (-1) if something went wrong. + */ + +int get_memory_ranges(struct memory_range **range, int *ranges, unsigned long flags) +{ + char sys_ram[] = "System RAM\n"; + char *iomem = proc_iomem(); + FILE *fp; + char line[80]; + int current_range = 0; + + fp = fopen(iomem,"r"); + if(fp == 0) { + fprintf(stderr,"Unable to open %s: %s\n",iomem,strerror(errno)); + return -1; + } + + /* Setup the compare string properly. */ + while(fgets(line,sizeof(line),fp) != 0) { + unsigned long long start, end; + int cons; + char *str; + + if (current_range == MAX_MEMORY_RANGES) + break; + + sscanf(line,"%Lx-%Lx : %n", &start, &end, &cons); + str = line+cons; + if(memcmp(str,sys_ram,strlen(sys_ram)) == 0) { + memory_range[current_range].start = start; + memory_range[current_range].end = end; + memory_range[current_range].type = RANGE_RAM; + current_range++; + } + else { + continue; + } + } + fclose(fp); + *range = memory_range; + *ranges = current_range; + + return 0; +} + +/* Supported file types and callbacks */ +struct file_type file_type[] = { + { "image", image_s390_probe, image_s390_load, image_s390_usage}, +}; +int file_types = sizeof(file_type) / sizeof(file_type[0]); + + +void arch_usage(void) +{ +} + +int arch_process_options(int argc, char **argv) +{ + return 0; +} + +const struct arch_map_entry arches[] = { + { "s390", KEXEC_ARCH_S390 }, + { "s390x", KEXEC_ARCH_S390 }, + { 0 }, +}; + +int arch_compat_trampoline(struct kexec_info *info) +{ + return 0; +} + +void arch_update_purgatory(struct kexec_info *info) +{ +} + +int is_crashkernel_mem_reserved(void) +{ + return 0; /* kdump is not supported on this platform (yet) */ +} diff --git a/pool/shard004/C/0099167_multigroups.c b/pool/shard004/C/0099167_multigroups.c new file mode 100644 index 0000000000000000000000000000000000000000..dd57153fe0c149caca88cc42dceceef8e97a9faa --- /dev/null +++ b/pool/shard004/C/0099167_multigroups.c @@ -0,0 +1,191 @@ +// Copyright (C) 2010 Andrey Gruber (aka lamer) + +// This program is free software; you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation; either version 2 of the License, or +// (at your option) any later version. + +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with this program; if not, write to the Free Software +// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + +#include "notes.h" +#include "global.h" +#include "shared.h" +#include "stringconstants.h" +#include "numericconstants.h" +#include "ctreeview.h" +#include "contacts.h" +#include "contgroups.h" +#include "multigroups.h" + +static BOOL Multigroups_OnInitDialog(HWND hwnd, HWND hwndFocus, LPARAM lParam); +static void Multigroups_OnClose(HWND hwnd); +static void Multigroups_OnCommand(HWND hwnd, int id, HWND hwndCtl, UINT codeNotify); +static void ClearDialog(void); +static void PrepareGroupsList(HWND hTree); +static void CT_OnCheckStateChanged(HWND hwnd, HTREEITEM hItem, BOOL fChecked); +static BOOL IsContactChecked(HWND hTree); +static void CreateGroupsContactsList(HWND hTree); + +HIMAGELIST m_hImlDefCheck; + +BOOL CALLBACK Multigroups_DlgProc (HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) +{ + switch(msg) + { + HANDLE_MSG (hwnd, WM_COMMAND, Multigroups_OnCommand); + HANDLE_MSG (hwnd, WM_INITDIALOG, Multigroups_OnInitDialog); + HANDLE_MSG (hwnd, WM_CLOSE, Multigroups_OnClose); + case WM_NOTIFY:{ + NMHDR *lpnmh = (NMHDR *)lParam; + if(lpnmh->idFrom == IDC_LST_SEVERAL_CONT && lpnmh->code == CTVN_CHECKSTATECHANGED){ + LPCTVNCHECKCHANGE lpctvn = (LPCTVNCHECKCHANGE)lpnmh; + CT_OnCheckStateChanged(lpnmh->hwndFrom, lpctvn->hItem, lpctvn->fChecked); + } + else if(lpnmh->idFrom == IDC_LST_SEVERAL_CONT && lpnmh->code == NM_CUSTOMDRAW){ + LPNMTVCUSTOMDRAW pNMTVCD = (LPNMTVCUSTOMDRAW)lpnmh; + return CTreeView_OnCustomDraw(hwnd, lpnmh->hwndFrom, pNMTVCD); + } + return FALSE; + } + default: return FALSE; + } +} + +static void Multigroups_OnCommand(HWND hwnd, int id, HWND hwndCtl, UINT codeNotify){ + switch(id){ + case IDCANCEL: + ClearDialog(); + EndDialog(hwnd, IDCANCEL); + break; + case IDOK:{ + CreateGroupsContactsList(GetDlgItem(hwnd, IDC_LST_SEVERAL_CONT)); + ClearDialog(); + EndDialog(hwnd, IDOK); + break; + } + } +} + +static BOOL Multigroups_OnInitDialog(HWND hwnd, HWND hwndFocus, LPARAM lParam) +{ + wchar_t szBuffer[256], szKey[16]; + HBITMAP hBmp; + HMODULE hIcons; + + g_hMultiGroups = hwnd; + hIcons = LoadLibraryExW(g_NotePaths.IconsPath, NULL, LOAD_LIBRARY_AS_DATAFILE); + if(hIcons){ + //prepare image list for check image + hBmp = LoadBitmapW(hIcons, MAKEINTRESOURCEW(IDB_CHECKS)); + m_hImlDefCheck = ImageList_Create(16, 16, ILC_COLOR32 | ILC_MASK, 0, 0); + ImageList_AddMasked(m_hImlDefCheck, hBmp, CLR_MASK); + DeleteBitmap(hBmp); + DeleteObject((void *)CLR_MASK); + FreeLibrary(hIcons); + } + + _itow(IDC_ST_CONT_GROUPS, szKey, 10); + GetPrivateProfileStringW(S_OPTIONS, szKey, L"Groups", szBuffer, 255, g_NotePaths.CurrLanguagePath); + SetWindowTextW(hwnd, szBuffer); + SetDlgCtlText(hwnd, IDOK, g_NotePaths.CurrLanguagePath, L"OK"); + SetDlgCtlText(hwnd, IDCANCEL, g_NotePaths.CurrLanguagePath, L"Cancel"); + + CTreeView_Subclass(GetDlgItem(hwnd, IDC_LST_SEVERAL_CONT)); + TreeView_SetImageList(GetDlgItem(hwnd, IDC_LST_SEVERAL_CONT), m_hImlDefCheck, TVSIL_NORMAL); + PrepareGroupsList(GetDlgItem(hwnd, IDC_LST_SEVERAL_CONT)); + + return TRUE; +} + +static void Multigroups_OnClose(HWND hwnd) +{ + ClearDialog(); + EndDialog(hwnd, IDCANCEL); +} + +static void PrepareGroupsList(HWND hTree){ + TVINSERTSTRUCTW tvs = {0}; + wchar_t szBuffer[128]; + LPPCONTGROUP lpc; + HTREEITEM hItem; + + tvs.hParent = TVI_ROOT; + tvs.hInsertAfter = TVI_LAST; + tvs.item.mask = TVIF_TEXT | TVIF_PARAM | TVIF_IMAGE | TVIF_SELECTEDIMAGE; + tvs.item.lParam = MAKELONG(1, 1); + tvs.item.pszText = szBuffer; + lpc = g_PContGroups; + while(lpc){ + if(PContactsInGroup(g_PContacts, lpc->id) > 0){ + wcscpy(szBuffer, lpc->name); + hItem = (HTREEITEM)SendMessageW(hTree, TVM_INSERTITEMW, 0, (LPARAM)&tvs); + CTreeView_SetCheckBoxState(hTree, hItem, FALSE); + } + lpc = lpc->next; + } +} + +static void ClearDialog(void){ + g_hMultiGroups = NULL; + if(m_hImlDefCheck){ + ImageList_Destroy(m_hImlDefCheck); + m_hImlDefCheck = NULL; + } +} + +static void CT_OnCheckStateChanged(HWND hwnd, HTREEITEM hItem, BOOL fChecked){ + if(fChecked){ + EnableWindow(GetDlgItem(g_hMultiGroups, IDOK), TRUE); + } + else{ + EnableWindow(GetDlgItem(g_hMultiGroups, IDOK), IsContactChecked(GetDlgItem(g_hMultiGroups, IDC_LST_SEVERAL_CONT))); + } +} + +static BOOL IsContactChecked(HWND hTree){ + HTREEITEM hItem; + + hItem = TreeView_GetRoot(hTree); + while(hItem){ + if(CTreeView_GetCheckBoxState(hTree, hItem)){ + return TRUE; + } + hItem = TreeView_GetNextSibling(hTree, hItem); + } + + return FALSE; +} + +static void CreateGroupsContactsList(HWND hTree){ + HTREEITEM hItem; + TVITEMW tvi = {0}; + wchar_t szBuffer[128]; + + tvi.mask = TVIF_TEXT; + tvi.cchTextMax = 128; + tvi.pszText = szBuffer; + + hItem = TreeView_GetRoot(hTree); + while(hItem){ + if(CTreeView_GetCheckBoxState(hTree, hItem)){ + tvi.hItem = hItem; + SendMessageW(hTree, TVM_GETITEMW, 0, (LPARAM)&tvi); + LPPCONTGROUP lpg = PContGroupsItem(g_PContGroups, szBuffer); + if(lpg){ + for(LPPCONTACT lpc = g_PContacts; lpc; lpc = lpc->next){ + if(lpc->prop.group == lpg->id){ + lpc->prop.send = TRUE; + } + } + } + } + hItem = TreeView_GetNextSibling(hTree, hItem); + } +} diff --git a/pool/shard004/C/0099168_util-ioctl.c b/pool/shard004/C/0099168_util-ioctl.c new file mode 100644 index 0000000000000000000000000000000000000000..7c681ecb829fdc5dcaefb5559fddb3e98f91b8d9 --- /dev/null +++ b/pool/shard004/C/0099168_util-ioctl.c @@ -0,0 +1,123 @@ +/* Copyright (C) 2010 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 Eric Leblond + */ + +#include "suricata-common.h" +#include "conf.h" + +#ifdef HAVE_SYS_IOCTL_H +#include +#endif + +#ifdef HAVE_NET_IF_H +#include +#endif + +/** + * \brief output a majorant of hardware header length + * + * \param Name of a network interface + */ +int GetIfaceMaxHWHeaderLength(char *pcap_dev) +{ + if ((!strcmp("eth", pcap_dev)) + || + (!strcmp("br", pcap_dev)) + || + (!strcmp("bond", pcap_dev)) + || + (!strcmp("wlan", pcap_dev)) + || + (!strcmp("tun", pcap_dev)) + || + (!strcmp("tap", pcap_dev)) + || + (!strcmp("lo", pcap_dev)) + ) + return ETHERNET_HEADER_LEN; + if ( + (!strcmp("ppp", pcap_dev)) + ) + return SLL_HEADER_LEN; + /* SLL_HEADER_LEN is the biggest one */ + return SLL_HEADER_LEN; +} + +/** + * \brief output the link MTU + * + * \param Name of link + * \retval -1 in case of error, 0 if MTU can not be found + */ +int GetIfaceMTU(char *pcap_dev) +{ +#ifdef SIOCGIFMTU + struct ifreq ifr; + int fd; + + (void)strlcpy(ifr.ifr_name, pcap_dev, sizeof(ifr.ifr_name)); + fd = socket(AF_INET, SOCK_DGRAM, 0); + if (fd == -1) { + return -1; + } + + if (ioctl(fd, SIOCGIFMTU, (char *)&ifr) < 0) { + SCLogInfo("Failure when trying to get MTU via ioctl: %d", + errno); + close(fd); + return -1; + } + close(fd); + SCLogInfo("Found an MTU of %d for '%s'", ifr.ifr_mtu, + pcap_dev); + return ifr.ifr_mtu; +#else + /* ioctl is not defined, let's pretend returning 0 is ok */ + return 0; +#endif +} + +/** + * \brief output max payload size for a link + * + * This does a best effort to find the maximum packet size + * for the link. In case of uncertainty, it will output a + * majorant to be sure avoid the cost of dynamic allocation. + * + * \param Name of a network interface + * \retval 0 in case of error + */ +int GetIfaceMaxPayloadSize(char *pcap_dev) +{ + int ll_header = GetIfaceMaxHWHeaderLength(pcap_dev); + int mtu = GetIfaceMTU(pcap_dev); + switch (mtu) { + case 0: + case -1: + return 0; + } + if (ll_header == -1) { + /* be conservative, choose a big one */ + ll_header = 16; + } + return ll_header + mtu; +} diff --git a/pool/shard004/C/0099170_pyexec.c b/pool/shard004/C/0099170_pyexec.c new file mode 100644 index 0000000000000000000000000000000000000000..45928427e175b55edb3c3a8775d8ab582f8019c7 --- /dev/null +++ b/pool/shard004/C/0099170_pyexec.c @@ -0,0 +1,270 @@ +/* + * This file is part of the Micro Python project, http://micropython.org/ + * + * The MIT License (MIT) + * + * Copyright (c) 2013, 2014 Damien P. George + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +#include +#include + +#include + +#include "mpconfig.h" +#include "nlr.h" +#include "misc.h" +#include "qstr.h" +#include "misc.h" +#include "lexer.h" +#include "parse.h" +#include "obj.h" +#include "parsehelper.h" +#include "compile.h" +#include "runtime.h" +#include "repl.h" +#include "gc.h" +#include "gccollect.h" +#include "systick.h" +#include "pybstdio.h" +#include "readline.h" +#include "pyexec.h" +#include "usb.h" +#include "genhdr/py-version.h" + +pyexec_mode_kind_t pyexec_mode_kind = PYEXEC_MODE_FRIENDLY_REPL; +STATIC bool repl_display_debugging_info = 0; + +// parses, compiles and executes the code in the lexer +// frees the lexer before returning +bool parse_compile_execute(mp_lexer_t *lex, mp_parse_input_kind_t input_kind, bool is_repl) { + mp_parse_error_kind_t parse_error_kind; + mp_parse_node_t pn = mp_parse(lex, input_kind, &parse_error_kind); + qstr source_name = mp_lexer_source_name(lex); + + if (pn == MP_PARSE_NODE_NULL) { + // parse error + mp_parse_show_exception(lex, parse_error_kind); + mp_lexer_free(lex); + return false; + } + + mp_lexer_free(lex); + + mp_obj_t module_fun = mp_compile(pn, source_name, MP_EMIT_OPT_NONE, is_repl); + mp_parse_node_free(pn); + + if (module_fun == mp_const_none) { + return false; + } + + nlr_buf_t nlr; + bool ret; + uint32_t start = HAL_GetTick(); + if (nlr_push(&nlr) == 0) { + usb_vcp_set_interrupt_char(VCP_CHAR_CTRL_C); // allow ctrl-C to interrupt us + mp_call_function_0(module_fun); + usb_vcp_set_interrupt_char(VCP_CHAR_NONE); // disable interrupt + nlr_pop(); + ret = true; + } else { + // uncaught exception + // FIXME it could be that an interrupt happens just before we disable it here + usb_vcp_set_interrupt_char(VCP_CHAR_NONE); // disable interrupt + mp_obj_print_exception((mp_obj_t)nlr.ret_val); + ret = false; + } + + // display debugging info if wanted + if (is_repl && repl_display_debugging_info) { + uint32_t ticks = HAL_GetTick() - start; // TODO implement a function that does this properly + printf("took %lu ms\n", ticks); + gc_collect(); + // qstr info + { + uint n_pool, n_qstr, n_str_data_bytes, n_total_bytes; + qstr_pool_info(&n_pool, &n_qstr, &n_str_data_bytes, &n_total_bytes); + printf("qstr:\n n_pool=%u\n n_qstr=%u\n n_str_data_bytes=%u\n n_total_bytes=%u\n", n_pool, n_qstr, n_str_data_bytes, n_total_bytes); + } + + // GC info + { + gc_info_t info; + gc_info(&info); + printf("GC:\n"); + printf(" " UINT_FMT " total\n", info.total); + printf(" " UINT_FMT " : " UINT_FMT "\n", info.used, info.free); + printf(" 1=" UINT_FMT " 2=" UINT_FMT " m=" UINT_FMT "\n", info.num_1block, info.num_2block, info.max_block); + } + } + + return ret; +} + +int pyexec_raw_repl(void) { + vstr_t line; + vstr_init(&line, 32); + +raw_repl_reset: + stdout_tx_str("raw REPL; CTRL-B to exit\r\n"); + + for (;;) { + vstr_reset(&line); + stdout_tx_str(">"); + for (;;) { + char c = stdin_rx_chr(); + if (c == VCP_CHAR_CTRL_A) { + // reset raw REPL + goto raw_repl_reset; + } else if (c == VCP_CHAR_CTRL_B) { + // change to friendly REPL + stdout_tx_str("\r\n"); + vstr_clear(&line); + pyexec_mode_kind = PYEXEC_MODE_FRIENDLY_REPL; + return 0; + } else if (c == VCP_CHAR_CTRL_C) { + // clear line + vstr_reset(&line); + } else if (c == VCP_CHAR_CTRL_D) { + // input finished + break; + } else if (c <= 127) { + // let through any other ASCII character + vstr_add_char(&line, c); + } + } + + // indicate reception of command + stdout_tx_str("OK"); + + if (line.len == 0) { + // exit for a soft reset + stdout_tx_str("\r\n"); + vstr_clear(&line); + return 1; + } + + mp_lexer_t *lex = mp_lexer_new_from_str_len(MP_QSTR__lt_stdin_gt_, line.buf, line.len, 0); + if (lex == NULL) { + printf("MemoryError\n"); + } else { + parse_compile_execute(lex, MP_PARSE_FILE_INPUT, false); + } + + // indicate end of output with EOF character + stdout_tx_str("\004"); + } +} + +int pyexec_friendly_repl(void) { + vstr_t line; + vstr_init(&line, 32); + +#if defined(USE_HOST_MODE) && MICROPY_HW_HAS_LCD + // in host mode, we enable the LCD for the repl + mp_obj_t lcd_o = mp_call_function_0(mp_load_name(qstr_from_str("LCD"))); + mp_call_function_1(mp_load_attr(lcd_o, qstr_from_str("light")), mp_const_true); +#endif + +friendly_repl_reset: + stdout_tx_str("Micro Python " MICROPY_GIT_TAG " on " MICROPY_BUILD_DATE "; " MICROPY_HW_BOARD_NAME " with STM32F405RG\r\n"); + stdout_tx_str("Type \"help()\" for more information.\r\n"); + + // to test ctrl-C + /* + { + uint32_t x[4] = {0x424242, 0xdeaddead, 0x242424, 0xdeadbeef}; + for (;;) { + nlr_buf_t nlr; + printf("pyexec_repl: %p\n", x); + usb_vcp_set_interrupt_char(VCP_CHAR_CTRL_C); + if (nlr_push(&nlr) == 0) { + for (;;) { + } + } else { + printf("break\n"); + } + } + } + */ + + for (;;) { + vstr_reset(&line); + int ret = readline(&line, ">>> "); + + if (ret == VCP_CHAR_CTRL_A) { + // change to raw REPL + stdout_tx_str("\r\n"); + vstr_clear(&line); + pyexec_mode_kind = PYEXEC_MODE_RAW_REPL; + return 0; + } else if (ret == VCP_CHAR_CTRL_B) { + // reset friendly REPL + stdout_tx_str("\r\n"); + goto friendly_repl_reset; + } else if (ret == VCP_CHAR_CTRL_C) { + // break + stdout_tx_str("\r\n"); + continue; + } else if (ret == VCP_CHAR_CTRL_D) { + // exit for a soft reset + stdout_tx_str("\r\n"); + vstr_clear(&line); + return 1; + } else if (vstr_len(&line) == 0) { + continue; + } + + while (mp_repl_continue_with_input(vstr_str(&line))) { + vstr_add_char(&line, '\n'); + int ret = readline(&line, "... "); + if (ret == VCP_CHAR_CTRL_D) { + // stop entering compound statement + break; + } + } + + mp_lexer_t *lex = mp_lexer_new_from_str_len(MP_QSTR__lt_stdin_gt_, vstr_str(&line), vstr_len(&line), 0); + if (lex == NULL) { + printf("MemoryError\n"); + } else { + parse_compile_execute(lex, MP_PARSE_SINGLE_INPUT, true); + } + } +} + +bool pyexec_file(const char *filename) { + mp_lexer_t *lex = mp_lexer_new_from_file(filename); + + if (lex == NULL) { + printf("could not open file '%s' for reading\n", filename); + return false; + } + + return parse_compile_execute(lex, MP_PARSE_FILE_INPUT, false); +} + +mp_obj_t pyb_set_repl_info(mp_obj_t o_value) { + repl_display_debugging_info = mp_obj_get_int(o_value); + return mp_const_none; +} + +MP_DEFINE_CONST_FUN_OBJ_1(pyb_set_repl_info_obj, pyb_set_repl_info); diff --git a/pool/shard004/C/0099176_anx9804.c b/pool/shard004/C/0099176_anx9804.c new file mode 100644 index 0000000000000000000000000000000000000000..37ad69a039c8f50860f0bd7db02a630a8080f80a --- /dev/null +++ b/pool/shard004/C/0099176_anx9804.c @@ -0,0 +1,186 @@ +/* + * (C) 2015 Hans de Goede + * + * SPDX-License-Identifier: GPL-2.0+ + */ + +/* + * Support for the ANX9804 bridge chip, which can take pixel data coming + * from a parallel LCD interface and translate it on the flight into a DP + * interface for driving eDP TFT displays. + */ + +#include +#include +#include "anx9804.h" + +/* Registers at i2c address 0x38 */ + +#define ANX9804_HDCP_CONTROL_0_REG 0x01 + +#define ANX9804_SYS_CTRL2_REG 0x81 +#define ANX9804_SYS_CTRL2_CHA_STA 0x04 + +#define ANX9804_SYS_CTRL3_REG 0x82 +#define ANX9804_SYS_CTRL3_VALID_CTRL BIT(0) +#define ANX9804_SYS_CTRL3_F_VALID BIT(1) +#define ANX9804_SYS_CTRL3_HPD_CTRL BIT(4) +#define ANX9804_SYS_CTRL3_F_HPD BIT(5) + +#define ANX9804_LINK_BW_SET_REG 0xa0 +#define ANX9804_LANE_COUNT_SET_REG 0xa1 +#define ANX9804_TRAINING_PTN_SET_REG 0xa2 +#define ANX9804_TRAINING_LANE0_SET_REG 0xa3 +#define ANX9804_TRAINING_LANE1_SET_REG 0xa4 +#define ANX9804_TRAINING_LANE2_SET_REG 0xa5 +#define ANX9804_TRAINING_LANE3_SET_REG 0xa6 + +#define ANX9804_LINK_TRAINING_CTRL_REG 0xa8 +#define ANX9804_LINK_TRAINING_CTRL_EN BIT(0) + +#define ANX9804_LINK_DEBUG_REG 0xb8 +#define ANX9804_PLL_CTRL_REG 0xc7 +#define ANX9804_ANALOG_POWER_DOWN_REG 0xc8 + +/* Registers at i2c address 0x39 */ + +#define ANX9804_DEV_IDH_REG 0x03 + +#define ANX9804_POWERD_CTRL_REG 0x05 +#define ANX9804_POWERD_AUDIO BIT(4) + +#define ANX9804_RST_CTRL_REG 0x06 + +#define ANX9804_RST_CTRL2_REG 0x07 +#define ANX9804_RST_CTRL2_AUX BIT(2) +#define ANX9804_RST_CTRL2_AC_MODE BIT(6) + +#define ANX9804_VID_CTRL1_REG 0x08 +#define ANX9804_VID_CTRL1_VID_EN BIT(7) +#define ANX9804_VID_CTRL1_EDGE BIT(0) + +#define ANX9804_VID_CTRL2_REG 0x09 +#define ANX9804_ANALOG_DEBUG_REG1 0xdc +#define ANX9804_ANALOG_DEBUG_REG3 0xde +#define ANX9804_PLL_FILTER_CTRL1 0xdf +#define ANX9804_PLL_FILTER_CTRL3 0xe1 +#define ANX9804_PLL_FILTER_CTRL 0xe2 +#define ANX9804_PLL_CTRL3 0xe6 + +/** + * anx9804_init() - Init anx9804 parallel lcd to edp bridge chip + * + * This function will init an anx9804 parallel lcd to dp bridge chip + * using the passed in parameters. + * + * @i2c_bus: Number of the i2c bus to which the anx9804 is connected. + * @lanes: Number of displayport lanes to use + * @data_rate: Register value for the bandwidth reg 0x06: 1.62G, 0x0a: 2.7G + * @bpp: Bits per pixel, must be 18 or 24 + */ +void anx9804_init(unsigned int i2c_bus, u8 lanes, u8 data_rate, int bpp) +{ + unsigned int orig_i2c_bus = i2c_get_bus_num(); + u8 c, colordepth; + int i; + + i2c_set_bus_num(i2c_bus); + + if (bpp == 18) + colordepth = 0x00; /* 6 bit */ + else + colordepth = 0x10; /* 8 bit */ + + /* Reset */ + i2c_reg_write(0x39, ANX9804_RST_CTRL_REG, 1); + mdelay(100); + i2c_reg_write(0x39, ANX9804_RST_CTRL_REG, 0); + + /* Write 0 to the powerdown reg (powerup everything) */ + i2c_reg_write(0x39, ANX9804_POWERD_CTRL_REG, 0); + + c = i2c_reg_read(0x39, ANX9804_DEV_IDH_REG); + if (c != 0x98) { + printf("Error anx9804 chipid mismatch\n"); + i2c_set_bus_num(orig_i2c_bus); + return; + } + + for (i = 0; i < 100; i++) { + c = i2c_reg_read(0x38, ANX9804_SYS_CTRL2_REG); + i2c_reg_write(0x38, ANX9804_SYS_CTRL2_REG, c); + c = i2c_reg_read(0x38, ANX9804_SYS_CTRL2_REG); + if ((c & ANX9804_SYS_CTRL2_CHA_STA) == 0) + break; + + mdelay(5); + } + if (i == 100) + printf("Error anx9804 clock is not stable\n"); + + i2c_reg_write(0x39, ANX9804_VID_CTRL2_REG, colordepth); + + /* Set a bunch of analog related register values */ + i2c_reg_write(0x38, ANX9804_PLL_CTRL_REG, 0x07); + i2c_reg_write(0x39, ANX9804_PLL_FILTER_CTRL3, 0x19); + i2c_reg_write(0x39, ANX9804_PLL_CTRL3, 0xd9); + i2c_reg_write(0x39, ANX9804_RST_CTRL2_REG, ANX9804_RST_CTRL2_AC_MODE); + i2c_reg_write(0x39, ANX9804_ANALOG_DEBUG_REG1, 0xf0); + i2c_reg_write(0x39, ANX9804_ANALOG_DEBUG_REG3, 0x99); + i2c_reg_write(0x39, ANX9804_PLL_FILTER_CTRL1, 0x7b); + i2c_reg_write(0x38, ANX9804_LINK_DEBUG_REG, 0x30); + i2c_reg_write(0x39, ANX9804_PLL_FILTER_CTRL, 0x06); + + /* Force HPD */ + i2c_reg_write(0x38, ANX9804_SYS_CTRL3_REG, + ANX9804_SYS_CTRL3_F_HPD | ANX9804_SYS_CTRL3_HPD_CTRL); + + /* Power up and configure lanes */ + i2c_reg_write(0x38, ANX9804_ANALOG_POWER_DOWN_REG, 0x00); + i2c_reg_write(0x38, ANX9804_TRAINING_LANE0_SET_REG, 0x00); + i2c_reg_write(0x38, ANX9804_TRAINING_LANE1_SET_REG, 0x00); + i2c_reg_write(0x38, ANX9804_TRAINING_LANE2_SET_REG, 0x00); + i2c_reg_write(0x38, ANX9804_TRAINING_LANE3_SET_REG, 0x00); + + /* Reset AUX CH */ + i2c_reg_write(0x39, ANX9804_RST_CTRL2_REG, + ANX9804_RST_CTRL2_AC_MODE | ANX9804_RST_CTRL2_AUX); + i2c_reg_write(0x39, ANX9804_RST_CTRL2_REG, + ANX9804_RST_CTRL2_AC_MODE); + + /* Powerdown audio and some other unused bits */ + i2c_reg_write(0x39, ANX9804_POWERD_CTRL_REG, ANX9804_POWERD_AUDIO); + i2c_reg_write(0x38, ANX9804_HDCP_CONTROL_0_REG, 0x00); + i2c_reg_write(0x38, 0xa7, 0x00); + + /* Set data-rate / lanes */ + i2c_reg_write(0x38, ANX9804_LINK_BW_SET_REG, data_rate); + i2c_reg_write(0x38, ANX9804_LANE_COUNT_SET_REG, lanes); + + /* Link training */ + i2c_reg_write(0x38, ANX9804_LINK_TRAINING_CTRL_REG, + ANX9804_LINK_TRAINING_CTRL_EN); + mdelay(5); + for (i = 0; i < 100; i++) { + c = i2c_reg_read(0x38, ANX9804_LINK_TRAINING_CTRL_REG); + if ((c & 0x01) == 0) + break; + + mdelay(5); + } + if(i == 100) { + printf("Error anx9804 link training timeout\n"); + i2c_set_bus_num(orig_i2c_bus); + return; + } + + /* Enable */ + i2c_reg_write(0x39, ANX9804_VID_CTRL1_REG, + ANX9804_VID_CTRL1_VID_EN | ANX9804_VID_CTRL1_EDGE); + /* Force stream valid */ + i2c_reg_write(0x38, ANX9804_SYS_CTRL3_REG, + ANX9804_SYS_CTRL3_F_HPD | ANX9804_SYS_CTRL3_HPD_CTRL | + ANX9804_SYS_CTRL3_F_VALID | ANX9804_SYS_CTRL3_VALID_CTRL); + + i2c_set_bus_num(orig_i2c_bus); +} diff --git a/pool/shard004/C/0099181_t8_netcdf_status.c b/pool/shard004/C/0099181_t8_netcdf_status.c new file mode 100644 index 0000000000000000000000000000000000000000..0bf8bb0d423ee023763a688157f8672f3fa54a97 --- /dev/null +++ b/pool/shard004/C/0099181_t8_netcdf_status.c @@ -0,0 +1,63 @@ +/* + This file is part of t8code. + t8code is a C library to manage a collection (a forest) of multiple + connected adaptive space-trees of general element types in parallel. + + Copyright (C) 2015 the developers + + t8code is free software; you can 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. + + t8code is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with t8code; if not, write to the Free Software Foundation, Inc., + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. +*/ + +#include + +/* This code prints a global message describing the netcdf compilation status. */ +static void +t8_check_netcdf_compilation () +{ +#ifdef T8_WITH_NETCDF + t8_global_productionf + ("This version of t8code is compiled with netcdf support.\n"); +#else + t8_global_productionf + ("This version of t8code is not compiled with netcdf support.\n"); +#endif +} + +int +main (int argc, char **argv) +{ + int mpiret; + + /* Initialize MPI */ + mpiret = sc_MPI_Init (&argc, &argv); + SC_CHECK_MPI (mpiret); + + /* Initialize sc */ + sc_init (sc_MPI_COMM_WORLD, 1, 1, NULL, SC_LP_ESSENTIAL); + /* Initialize t8code */ + t8_init (SC_LP_PRODUCTION); + + /* Check netcdf compilation */ + t8_check_netcdf_compilation (); + + /* Finalize sc */ + sc_finalize (); + + /* Finalize MPI */ + mpiret = sc_MPI_Finalize (); + SC_CHECK_MPI (mpiret); + + return 0; +} diff --git a/pool/shard004/C/0099186_avx-vandps-256-1.c b/pool/shard004/C/0099186_avx-vandps-256-1.c new file mode 100644 index 0000000000000000000000000000000000000000..4dc123bf371c977eb556dc068f2d4b7d700e1903 --- /dev/null +++ b/pool/shard004/C/0099186_avx-vandps-256-1.c @@ -0,0 +1,32 @@ +/* { dg-do run } */ +/* { dg-require-effective-target avx } */ +/* { dg-options "-O2 -mavx" } */ + +#include "avx-check.h" + +void static +avx_test (void) +{ + int i; + union256 u, s1, s2; + + union + { + float f[8]; + int i[8]; + }source1, source2, e; + + s1.x = _mm256_set_ps (34545, 95567, 23443, 5675, 2323, 67, 2345, 45667); + s2.x = _mm256_set_ps (674, 57897, 93459, 45624, 54674, 1237, 67436, 79608); + + _mm256_storeu_ps (source1.f, s1.x); + _mm256_storeu_ps (source2.f, s2.x); + + u.x = _mm256_and_ps (s1.x, s2.x); + + for (i = 0; i < 8; i++) + e.i[i] = source1.i[i] & source2.i[i]; + + if (check_union256 (u, e.f)) + abort (); +} diff --git a/pool/shard004/C/0099188_java_lang_ref_Reference.c b/pool/shard004/C/0099188_java_lang_ref_Reference.c new file mode 100644 index 0000000000000000000000000000000000000000..7b3e207ff621554e1b736554c160d574fc52bbd2 --- /dev/null +++ b/pool/shard004/C/0099188_java_lang_ref_Reference.c @@ -0,0 +1,35 @@ +#include +#include "debug.h" +#include +#include "java_lang_ref_Reference.h" +#include "reference.h" +#include "soft.h" +#include "classMethod.h" +#include "baseClasses.h" +#include "gc.h" +#include "errors.h" +#include "utf8const.h" + +void JNICALL Java_java_lang_ref_Reference_create(JNIEnv* env, jobject reference, jobject object) +{ + kgc_reference_type reftype; + Hjava_lang_Object *ref_object = (Hjava_lang_Object *)reference; + Hjava_lang_Class *ref_class = OBJECT_CLASS(ref_object); + + if (object == NULL) + return; + + if (instanceof(javaLangRefWeakReference, ref_class)) + reftype = KGC_WEAK_REFERENCE; + else if (instanceof(javaLangRefSoftReference, ref_class)) + reftype = KGC_SOFT_REFERENCE; + else if (instanceof(javaLangRefPhantomReference, ref_class)) + reftype = KGC_PHANTOM_REFERENCE; + else + { + (*env)->FatalError(env, "Unknown reference type"); + return; + } + + KaffeVM_registerObjectReference(reference, object, reftype); +} diff --git a/pool/shard004/C/0099192_mtk-devapc.c b/pool/shard004/C/0099192_mtk-devapc.c new file mode 100644 index 0000000000000000000000000000000000000000..7c65ad3d1f8a38f3b75add46415bf777b50c2f41 --- /dev/null +++ b/pool/shard004/C/0099192_mtk-devapc.c @@ -0,0 +1,309 @@ +// SPDX-License-Identifier: GPL-2.0 +/* + * Copyright (C) 2020 MediaTek Inc. + */ + +#include +#include +#include +#include +#include +#include +#include +#include + +#define VIO_MOD_TO_REG_IND(m) ((m) / 32) +#define VIO_MOD_TO_REG_OFF(m) ((m) % 32) + +struct mtk_devapc_vio_dbgs { + union { + u32 vio_dbg0; + struct { + u32 mstid:16; + u32 dmnid:6; + u32 vio_w:1; + u32 vio_r:1; + u32 addr_h:4; + u32 resv:4; + } dbg0_bits; + }; + + u32 vio_dbg1; +}; + +struct mtk_devapc_data { + /* numbers of violation index */ + u32 vio_idx_num; + + /* reg offset */ + u32 vio_mask_offset; + u32 vio_sta_offset; + u32 vio_dbg0_offset; + u32 vio_dbg1_offset; + u32 apc_con_offset; + u32 vio_shift_sta_offset; + u32 vio_shift_sel_offset; + u32 vio_shift_con_offset; +}; + +struct mtk_devapc_context { + struct device *dev; + void __iomem *infra_base; + struct clk *infra_clk; + const struct mtk_devapc_data *data; +}; + +static void clear_vio_status(struct mtk_devapc_context *ctx) +{ + void __iomem *reg; + int i; + + reg = ctx->infra_base + ctx->data->vio_sta_offset; + + for (i = 0; i < VIO_MOD_TO_REG_IND(ctx->data->vio_idx_num) - 1; i++) + writel(GENMASK(31, 0), reg + 4 * i); + + writel(GENMASK(VIO_MOD_TO_REG_OFF(ctx->data->vio_idx_num) - 1, 0), + reg + 4 * i); +} + +static void mask_module_irq(struct mtk_devapc_context *ctx, bool mask) +{ + void __iomem *reg; + u32 val; + int i; + + reg = ctx->infra_base + ctx->data->vio_mask_offset; + + if (mask) + val = GENMASK(31, 0); + else + val = 0; + + for (i = 0; i < VIO_MOD_TO_REG_IND(ctx->data->vio_idx_num) - 1; i++) + writel(val, reg + 4 * i); + + val = readl(reg + 4 * i); + if (mask) + val |= GENMASK(VIO_MOD_TO_REG_OFF(ctx->data->vio_idx_num) - 1, + 0); + else + val &= ~GENMASK(VIO_MOD_TO_REG_OFF(ctx->data->vio_idx_num) - 1, + 0); + + writel(val, reg + 4 * i); +} + +#define PHY_DEVAPC_TIMEOUT 0x10000 + +/* + * devapc_sync_vio_dbg - do "shift" mechansim" to get full violation information. + * shift mechanism is depends on devapc hardware design. + * Mediatek devapc set multiple slaves as a group. + * When violation is triggered, violation info is kept + * inside devapc hardware. + * Driver should do shift mechansim to sync full violation + * info to VIO_DBGs registers. + * + */ +static int devapc_sync_vio_dbg(struct mtk_devapc_context *ctx) +{ + void __iomem *pd_vio_shift_sta_reg; + void __iomem *pd_vio_shift_sel_reg; + void __iomem *pd_vio_shift_con_reg; + int min_shift_group; + int ret; + u32 val; + + pd_vio_shift_sta_reg = ctx->infra_base + + ctx->data->vio_shift_sta_offset; + pd_vio_shift_sel_reg = ctx->infra_base + + ctx->data->vio_shift_sel_offset; + pd_vio_shift_con_reg = ctx->infra_base + + ctx->data->vio_shift_con_offset; + + /* Find the minimum shift group which has violation */ + val = readl(pd_vio_shift_sta_reg); + if (!val) + return false; + + min_shift_group = __ffs(val); + + /* Assign the group to sync */ + writel(0x1 << min_shift_group, pd_vio_shift_sel_reg); + + /* Start syncing */ + writel(0x1, pd_vio_shift_con_reg); + + ret = readl_poll_timeout(pd_vio_shift_con_reg, val, val == 0x3, 0, + PHY_DEVAPC_TIMEOUT); + if (ret) { + dev_err(ctx->dev, "%s: Shift violation info failed\n", __func__); + return false; + } + + /* Stop syncing */ + writel(0x0, pd_vio_shift_con_reg); + + /* Write clear */ + writel(0x1 << min_shift_group, pd_vio_shift_sta_reg); + + return true; +} + +/* + * devapc_extract_vio_dbg - extract full violation information after doing + * shift mechanism. + */ +static void devapc_extract_vio_dbg(struct mtk_devapc_context *ctx) +{ + struct mtk_devapc_vio_dbgs vio_dbgs; + void __iomem *vio_dbg0_reg; + void __iomem *vio_dbg1_reg; + + vio_dbg0_reg = ctx->infra_base + ctx->data->vio_dbg0_offset; + vio_dbg1_reg = ctx->infra_base + ctx->data->vio_dbg1_offset; + + vio_dbgs.vio_dbg0 = readl(vio_dbg0_reg); + vio_dbgs.vio_dbg1 = readl(vio_dbg1_reg); + + /* Print violation information */ + if (vio_dbgs.dbg0_bits.vio_w) + dev_info(ctx->dev, "Write Violation\n"); + else if (vio_dbgs.dbg0_bits.vio_r) + dev_info(ctx->dev, "Read Violation\n"); + + dev_info(ctx->dev, "Bus ID:0x%x, Dom ID:0x%x, Vio Addr:0x%x\n", + vio_dbgs.dbg0_bits.mstid, vio_dbgs.dbg0_bits.dmnid, + vio_dbgs.vio_dbg1); +} + +/* + * devapc_violation_irq - the devapc Interrupt Service Routine (ISR) will dump + * violation information including which master violates + * access slave. + */ +static irqreturn_t devapc_violation_irq(int irq_number, void *data) +{ + struct mtk_devapc_context *ctx = data; + + while (devapc_sync_vio_dbg(ctx)) + devapc_extract_vio_dbg(ctx); + + clear_vio_status(ctx); + + return IRQ_HANDLED; +} + +/* + * start_devapc - unmask slave's irq to start receiving devapc violation. + */ +static void start_devapc(struct mtk_devapc_context *ctx) +{ + writel(BIT(31), ctx->infra_base + ctx->data->apc_con_offset); + + mask_module_irq(ctx, false); +} + +/* + * stop_devapc - mask slave's irq to stop service. + */ +static void stop_devapc(struct mtk_devapc_context *ctx) +{ + mask_module_irq(ctx, true); + + writel(BIT(2), ctx->infra_base + ctx->data->apc_con_offset); +} + +static const struct mtk_devapc_data devapc_mt6779 = { + .vio_idx_num = 511, + .vio_mask_offset = 0x0, + .vio_sta_offset = 0x400, + .vio_dbg0_offset = 0x900, + .vio_dbg1_offset = 0x904, + .apc_con_offset = 0xF00, + .vio_shift_sta_offset = 0xF10, + .vio_shift_sel_offset = 0xF14, + .vio_shift_con_offset = 0xF20, +}; + +static const struct of_device_id mtk_devapc_dt_match[] = { + { + .compatible = "mediatek,mt6779-devapc", + .data = &devapc_mt6779, + }, { + }, +}; +MODULE_DEVICE_TABLE(of, mtk_devapc_dt_match); + +static int mtk_devapc_probe(struct platform_device *pdev) +{ + struct device_node *node = pdev->dev.of_node; + struct mtk_devapc_context *ctx; + u32 devapc_irq; + int ret; + + if (IS_ERR(node)) + return -ENODEV; + + ctx = devm_kzalloc(&pdev->dev, sizeof(*ctx), GFP_KERNEL); + if (!ctx) + return -ENOMEM; + + ctx->data = of_device_get_match_data(&pdev->dev); + ctx->dev = &pdev->dev; + + ctx->infra_base = of_iomap(node, 0); + if (!ctx->infra_base) + return -EINVAL; + + devapc_irq = irq_of_parse_and_map(node, 0); + if (!devapc_irq) + return -EINVAL; + + ctx->infra_clk = devm_clk_get(&pdev->dev, "devapc-infra-clock"); + if (IS_ERR(ctx->infra_clk)) + return -EINVAL; + + if (clk_prepare_enable(ctx->infra_clk)) + return -EINVAL; + + ret = devm_request_irq(&pdev->dev, devapc_irq, devapc_violation_irq, + IRQF_TRIGGER_NONE, "devapc", ctx); + if (ret) { + clk_disable_unprepare(ctx->infra_clk); + return ret; + } + + platform_set_drvdata(pdev, ctx); + + start_devapc(ctx); + + return 0; +} + +static int mtk_devapc_remove(struct platform_device *pdev) +{ + struct mtk_devapc_context *ctx = platform_get_drvdata(pdev); + + stop_devapc(ctx); + + clk_disable_unprepare(ctx->infra_clk); + + return 0; +} + +static struct platform_driver mtk_devapc_driver = { + .probe = mtk_devapc_probe, + .remove = mtk_devapc_remove, + .driver = { + .name = "mtk-devapc", + .of_match_table = mtk_devapc_dt_match, + }, +}; + +module_platform_driver(mtk_devapc_driver); + +MODULE_DESCRIPTION("Mediatek Device APC Driver"); +MODULE_AUTHOR("Neal Liu "); +MODULE_LICENSE("GPL"); diff --git a/pool/shard004/C/0099196_gss_names.c b/pool/shard004/C/0099196_gss_names.c new file mode 100644 index 0000000000000000000000000000000000000000..833c582006f22778fe1ac7a6d21d86f3cf22deb7 --- /dev/null +++ b/pool/shard004/C/0099196_gss_names.c @@ -0,0 +1,105 @@ +/*- + * Copyright (c) 2005 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. + * + * $FreeBSD: src/lib/libgssapi/gss_names.c,v 1.1 2005/12/29 14:40:20 dfr Exp $ + */ + +#include "mech_locl.h" +RCSID("$Id: gss_names.c,v 1.2 2006/06/28 09:00:25 lha Exp $"); + +struct _gss_mechanism_name * +_gss_find_mn(struct _gss_name *name, gss_OID mech) +{ + OM_uint32 major_status, minor_status; + gssapi_mech_interface m; + struct _gss_mechanism_name *mn; + + SLIST_FOREACH(mn, &name->gn_mn, gmn_link) { + if (gss_oid_equal(mech, mn->gmn_mech_oid)) + break; + } + + if (!mn) { + /* + * If this name is canonical (i.e. there is only an + * MN but it is from a different mech), give up now. + */ + if (!name->gn_value.value) + return (0); + + m = __gss_get_mechanism(mech); + if (!m) + return (0); + + mn = malloc(sizeof(struct _gss_mechanism_name)); + if (!mn) + return (0); + + major_status = m->gm_import_name(&minor_status, + &name->gn_value, + (name->gn_type.elements + ? &name->gn_type : GSS_C_NO_OID), + &mn->gmn_name); + if (major_status) { + free(mn); + return (0); + } + + mn->gmn_mech = m; + mn->gmn_mech_oid = &m->gm_mech_oid; + SLIST_INSERT_HEAD(&name->gn_mn, mn, gmn_link); + } + return (mn); +} + +/* + * Make a name from an MN. + */ +struct _gss_name * +_gss_make_name(gssapi_mech_interface m, gss_name_t new_mn) +{ + struct _gss_name *name; + struct _gss_mechanism_name *mn; + + name = malloc(sizeof(struct _gss_name)); + if (!name) + return (0); + memset(name, 0, sizeof(struct _gss_name)); + + mn = malloc(sizeof(struct _gss_mechanism_name)); + if (!mn) { + free(name); + return (0); + } + + SLIST_INIT(&name->gn_mn); + mn->gmn_mech = m; + mn->gmn_mech_oid = &m->gm_mech_oid; + mn->gmn_name = new_mn; + SLIST_INSERT_HEAD(&name->gn_mn, mn, gmn_link); + + return (name); +} + diff --git a/pool/shard004/C/0099197_a_pan.c b/pool/shard004/C/0099197_a_pan.c new file mode 100644 index 0000000000000000000000000000000000000000..a497913e97dec121c217660951c8f4067570f1ab --- /dev/null +++ b/pool/shard004/C/0099197_a_pan.c @@ -0,0 +1,156 @@ +/* gEDA - GPL Electronic Design Automation + * gschem - gEDA Schematic Capture + * Copyright (C) 1998-2010 Ales Hvezda + * Copyright (C) 1998-2010 gEDA Contributors (see ChangeLog for details) + * + * 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 "gschem.h" + + +/*! \todo Finish function documentation!!! + * \brief + * \par Function Description + * + */ +void +a_pan_general(GschemToplevel *w_current, + PAGE *page, + double world_cx, + double world_cy, + double relativ_zoom_factor, + int flags) +{ + TOPLEVEL *toplevel = gschem_toplevel_get_toplevel (w_current); + /* see libgeda/include/defines.h for flags */ + /*if the borders should be ignored always, remove, outcomment or changes + the flags in the function-calls*/ + /* flags |= A_PAN_IGNORE_BORDERS; + */ + /* think it's better that the zoomfactor is defined as pix/mills + this will be the same as w_current->page_current->to_screen_x/y_constant*/ + int zoom_max = 5; + int diff; + double zx, zy, zoom_old, zoom_new, zoom_min; + +#if DEBUG + printf("a_pan_general(): world_cx=%f, world_cy=%f\n",world_cx, world_cy); +#endif + + /* calc minimum zoomfactors and choose the smaller one. They are equal + if the aspectratio of the world is the same as the screen ratio */ + zx = (double) toplevel->width / (toplevel->init_right - + toplevel->init_left); + zy = (double) toplevel->height / (toplevel->init_bottom - + toplevel->init_top); + zoom_min = zx < zy ? zx : zy; + +#if DEBUG + printf(" zx_min=%f, zy_min=%f , flags=%d\n ",zx, zy, flags); +#endif + + /* to_screen_x_constant and to_screen_y_constant are almost the same. + lets use to_screen_y_constant */ + zoom_old = page->to_screen_y_constant; + + /* calc new zooming factor */ + /* check if there's a zoom_full (relativ_zoom_factor == -1) */ + if (relativ_zoom_factor <0) { + zoom_new = zoom_min; + } + else { + zoom_new = zoom_old * relativ_zoom_factor; + zoom_new = zoom_new > zoom_max ? zoom_max : zoom_new; + if (!(flags & A_PAN_IGNORE_BORDERS)) { + zoom_new = zoom_new < zoom_min ? zoom_min : zoom_new; + } + } + + /* calculate the new visible area; adding 0.5 to round */ + page->left = world_cx - (double) toplevel->width / 2 / zoom_new + 0.5; + page->right = world_cx + (double) toplevel->width / 2 / zoom_new + 0.5; + page->top = world_cy - (double) toplevel->height / 2 / zoom_new + 0.5; + page->bottom = world_cy + (double) toplevel->height / 2 / zoom_new + 0.5; + + /* and put it back to the borders */ + if (!(flags & A_PAN_IGNORE_BORDERS)) { + /* check right border */ + if (page->right > toplevel->init_right) { + page->left += toplevel->init_right - page->right; + page->right = toplevel->init_right; + } + /* check left border */ + if (page->left < toplevel->init_left) { + page->right += toplevel->init_left - page->left; + page->left = toplevel->init_left; + } + + /* If there is any slack, center the view */ + diff = (page->right - page->left) - (toplevel->init_right - toplevel->init_left); + if (diff > 0) { + page->left -= diff / 2; + page->right -= diff / 2; + } + + /* check bottom border */ + if (page->bottom > toplevel->init_bottom) { + page->top += toplevel->init_bottom - page->bottom; + page->bottom = toplevel->init_bottom; + } + /* check top border */ + if (page->top < toplevel->init_top) { + page->bottom += toplevel->init_top - page->top; + page->top = toplevel->init_top; + } + + /* If there is any slack, center the view */ + diff = (page->bottom - page->top) - (toplevel->init_bottom - toplevel->init_top); + if (diff > 0) { + page->top -= diff / 2; + page->bottom -= diff / 2; + } + + } + +#if DEBUG + printf("zoom_old: %f, zoom_new: %f \n ",zoom_old, zoom_new); + printf("left: %d, right: %d, top: %d, bottom: %d\n", + page->left, page->right, page->top, page->bottom); + printf("aspect: %f\n", + (float) fabs(page->right - page->left) / + (float) fabs(page->bottom - page->top )); +#endif + + /* set_window */ + set_window(toplevel, + page, + page->left , + page->right , + page->top , + page->bottom); + + i_update_grid_info (w_current); + + /* redraw */ + if (!(flags & A_PAN_DONT_REDRAW)) { + gschem_page_view_update_scroll_adjustments (GSCHEM_PAGE_VIEW (w_current->drawing_area)); + o_invalidate_all (w_current); + } +} diff --git a/pool/shard004/C/0099202_BI_Unpack.c b/pool/shard004/C/0099202_BI_Unpack.c new file mode 100644 index 0000000000000000000000000000000000000000..4ac8241e1c2242ca21b543c3b0adf54f08f3c604 --- /dev/null +++ b/pool/shard004/C/0099202_BI_Unpack.c @@ -0,0 +1,16 @@ +#include "Bdef.h" + +void BI_Unpack(BLACSCONTEXT *ctxt, BVOID *A, BLACBUFF *bp, MPI_Datatype Dtype) +{ + int i=0, info, one=1; + +/* + * Some versions of mpich and its derivitives cannot handle 0 byte typedefs, + * so we have set MPI_BYTE as a flag for a 0 byte message + */ +#ifdef ZeroByteTypeBug + if (Dtype == MPI_BYTE) return; +#endif + info=MPI_Unpack(bp->Buff, bp->Len, &i, A, one, Dtype, ctxt->scp->comm); + info=MPI_Type_free(&Dtype); +} diff --git a/pool/shard004/C/0099203_threadpool_params.c b/pool/shard004/C/0099203_threadpool_params.c new file mode 100644 index 0000000000000000000000000000000000000000..ee9ce83c1c3053ef1af4ff0ce4820c8f7f1ab178 --- /dev/null +++ b/pool/shard004/C/0099203_threadpool_params.c @@ -0,0 +1,65 @@ +#include +#include +#include + +int main(int argc, char **argv) +{ + int ret = -1; + virAdmConnectPtr conn = NULL; + virAdmServerPtr srv = NULL; /* which server to work with */ + virTypedParameterPtr params = NULL; + int nparams = 0; + size_t i; + + if (argc != 2) { + fprintf(stderr, "One argument specifying the server which to work " + "with is expected\n"); + return -1; + } + + /* first, open a connection to the daemon */ + if (!(conn = virAdmConnectOpen(NULL, 0))) + goto cleanup; + + /* a server handle is necessary before any API regarding threadpool + * parameters can be issued + */ + if (!(srv = virAdmConnectLookupServer(conn, argv[1], 0))) + goto cleanup; + + /* get the current threadpool parameters */ + if (virAdmServerGetThreadPoolParameters(srv, ¶ms, &nparams, 0) < 0) + goto cleanup; + + for (i = 0; i < nparams; i++) + printf("%-15s: %d\n", params[i].field, params[i].value.ui); + + virTypedParamsFree(params, nparams); + params = NULL; + nparams = 0; + + /* let's set minWorkers to 10, maxWorkers to 15 and prioWorkers to 10 */ + int maxparams = 0; + if (virTypedParamsAddUInt(¶ms, &nparams, &maxparams, + VIR_THREADPOOL_WORKERS_MIN, 10) < 0 || + virTypedParamsAddUInt(¶ms, &nparams, &maxparams, + VIR_THREADPOOL_WORKERS_MAX, 15) < 0 || + virTypedParamsAddUInt(¶ms, &nparams, &maxparams, + VIR_THREADPOOL_WORKERS_PRIORITY, 10) < 0) + goto cleanup; + + /* now, change the threadpool settings to some different values */ + if (virAdmServerSetThreadPoolParameters(srv, params, nparams, 0) < 0) + goto cleanup; + + ret = 0; + cleanup: + virTypedParamsFree(params, nparams); + + /* Once finished deallocate the server handle and close the connection + * properly, @conn will be deallocated automatically + */ + virAdmServerFree(srv); + virAdmConnectClose(conn); + return ret; +} diff --git a/pool/shard004/C/0099205_block-enum.c b/pool/shard004/C/0099205_block-enum.c new file mode 100644 index 0000000000000000000000000000000000000000..1570372161762d78099585aa2c44bcf67b593f0f --- /dev/null +++ b/pool/shard004/C/0099205_block-enum.c @@ -0,0 +1,36 @@ +/* APPLE LOCAL file radar 5732232 - blocks */ +/* Test use of enumerators in blocks. */ +/* { dg-do run { target *-*-darwin[1-2][0-9]* } } */ +/* { dg-options "-fblocks" } */ +/* { dg-skip-if "" { powerpc*-*-darwin* } { "-m64" } { "" } } */ + +#include +void * _NSConcreteStackBlock; +extern void exit(int); + +enum numbers +{ + zero, one, two, three +}; + +typedef enum numbers (^myblock)(enum numbers); + + +double test(myblock I) { + return I(three); +} + +int main() { + __block enum numbers x = one; + __block enum numbers y = two; + + enum numbers res = test(^(enum numbers z){y = z; return x; }); + + if (x != one || y != three || res != one) + exit(1); + + res = test(^(enum numbers z){x = z; return x; }); + if (x != three || res != three) + exit(1); + return 0; +} diff --git a/pool/shard004/C/0099206_test-strlen.c b/pool/shard004/C/0099206_test-strlen.c new file mode 100644 index 0000000000000000000000000000000000000000..1838b12d51f771e19e5b101c6599a2c7b84b48c3 --- /dev/null +++ b/pool/shard004/C/0099206_test-strlen.c @@ -0,0 +1,167 @@ +/* Test and measure STRLEN functions. + Copyright (C) 1999-2016 Free Software Foundation, Inc. + This file is part of the GNU C Library. + Written by Jakub Jelinek , 1999. + Added wcslen support by Liubov Dmitrieva , 2011 + + The GNU C Library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + The GNU C Library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with the GNU C Library; if not, see + . */ + +#define TEST_MAIN +#ifndef WIDE +# define TEST_NAME "strlen" +#else +# define TEST_NAME "wcslen" +#endif +#include "test-string.h" + +#ifndef WIDE +# define STRLEN strlen +# define CHAR char +# define MAX_CHAR CHAR_MAX +#else +# include +# define STRLEN wcslen +# define CHAR wchar_t +# define MAX_CHAR WCHAR_MAX +#endif + +typedef size_t (*proto_t) (const CHAR *); + +size_t +simple_STRLEN (const CHAR *s) +{ + const CHAR *p; + + for (p = s; *p; ++p); + return p - s; +} + +#ifndef WIDE +size_t +builtin_strlen (const CHAR *p) +{ + return __builtin_strlen (p); +} +IMPL (builtin_strlen, 0) +#endif + +IMPL (simple_STRLEN, 0) +IMPL (STRLEN, 1) + + +static void +do_one_test (impl_t *impl, const CHAR *s, size_t exp_len) +{ + size_t len = CALL (impl, s); + if (len != exp_len) + { + error (0, 0, "Wrong result in function %s %zd %zd", impl->name, + len, exp_len); + ret = 1; + return; + } +} + +static void +do_test (size_t align, size_t len) +{ + size_t i; + + align &= 63; + if (align + sizeof(CHAR) * len >= page_size) + return; + + CHAR *buf = (CHAR *) (buf1); + + for (i = 0; i < len; ++i) + buf[align + i] = 1 + 11111 * i % MAX_CHAR; + buf[align + len] = 0; + + FOR_EACH_IMPL (impl, 0) + do_one_test (impl, (CHAR *) (buf + align), len); +} + +static void +do_random_tests (void) +{ + size_t i, j, n, align, len; + CHAR *p = (CHAR *) (buf1 + page_size - 512 * sizeof(CHAR)); + + for (n = 0; n < ITERATIONS; n++) + { + align = random () & 15; + len = random () & 511; + if (len + align > 510) + len = 511 - align - (random () & 7); + j = len + align + 64; + if (j > 512) + j = 512; + + for (i = 0; i < j; i++) + { + if (i == len + align) + p[i] = 0; + else + { + p[i] = random () & 255; + if (i >= align && i < len + align && !p[i]) + p[i] = (random () & 127) + 1; + } + } + + FOR_EACH_IMPL (impl, 1) + if (CALL (impl, (CHAR *) (p + align)) != len) + { + error (0, 0, "Iteration %zd - wrong result in function %s (%zd) %zd != %zd, p %p", + n, impl->name, align, CALL (impl, (CHAR *) (p + align)), + len, p); + ret = 1; + } + } +} + +int +test_main (void) +{ + size_t i; + + test_init (); + + printf ("%20s", ""); + FOR_EACH_IMPL (impl, 0) + printf ("\t%s", impl->name); + putchar ('\n'); + + /* Checking with only 4 * N alignments for wcslen, other alignments are wrong for wchar_t type arrays*/ + + for (i = 1; i < 8; ++i) + { + do_test (sizeof(CHAR) * i, i); + do_test (0, i); + } + + for (i = 2; i <= 12; ++i) + { + do_test (0, 1 << i); + do_test (sizeof(CHAR) * 7, 1 << i); + do_test (sizeof(CHAR) * i, 1 << i); + do_test (sizeof(CHAR) * i, (size_t)((1 << i) / 1.5)); + } + + do_random_tests (); + return ret; +} + +#include "../test-skeleton.c" diff --git a/pool/shard004/C/0099208_CWE127_Buffer_Underread__wchar_t_alloca_cpy_68a.c b/pool/shard004/C/0099208_CWE127_Buffer_Underread__wchar_t_alloca_cpy_68a.c new file mode 100644 index 0000000000000000000000000000000000000000..079d9f53bbf44207686515d918302ffd186c399a --- /dev/null +++ b/pool/shard004/C/0099208_CWE127_Buffer_Underread__wchar_t_alloca_cpy_68a.c @@ -0,0 +1,93 @@ +/* TEMPLATE GENERATED TESTCASE FILE +Filename: CWE127_Buffer_Underread__wchar_t_alloca_cpy_68a.c +Label Definition File: CWE127_Buffer_Underread.stack.label.xml +Template File: sources-sink-68a.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: cpy + * BadSink : Copy data to string using wcscpy + * Flow Variant: 68 Data flow: data passed as a global variable from one function to another in different source files + * + * */ + +#include "std_testcase.h" + +#include + +wchar_t * CWE127_Buffer_Underread__wchar_t_alloca_cpy_68_badData; +wchar_t * CWE127_Buffer_Underread__wchar_t_alloca_cpy_68_goodG2BData; + +#ifndef OMITBAD + +/* bad function declaration */ +void CWE127_Buffer_Underread__wchar_t_alloca_cpy_68b_badSink(); + +void CWE127_Buffer_Underread__wchar_t_alloca_cpy_68_bad() +{ + wchar_t * data; + wchar_t * dataBuffer = (wchar_t *)ALLOCA(100*sizeof(wchar_t)); + wmemset(dataBuffer, L'A', 100-1); + dataBuffer[100-1] = L'\0'; + /* FLAW: Set data pointer to before the allocated memory buffer */ + data = dataBuffer - 8; + CWE127_Buffer_Underread__wchar_t_alloca_cpy_68_badData = data; + CWE127_Buffer_Underread__wchar_t_alloca_cpy_68b_badSink(); +} + +#endif /* OMITBAD */ + +#ifndef OMITGOOD + +/* good function declarations */ +void CWE127_Buffer_Underread__wchar_t_alloca_cpy_68b_goodG2BSink(); + +/* goodG2B uses the GoodSource with the BadSink */ +static void goodG2B() +{ + wchar_t * data; + wchar_t * dataBuffer = (wchar_t *)ALLOCA(100*sizeof(wchar_t)); + wmemset(dataBuffer, L'A', 100-1); + dataBuffer[100-1] = L'\0'; + /* FIX: Set data pointer to the allocated memory buffer */ + data = dataBuffer; + CWE127_Buffer_Underread__wchar_t_alloca_cpy_68_goodG2BData = data; + CWE127_Buffer_Underread__wchar_t_alloca_cpy_68b_goodG2BSink(); +} + +void CWE127_Buffer_Underread__wchar_t_alloca_cpy_68_good() +{ + goodG2B(); +} + +#endif /* OMITGOOD */ + +/* Below is the main(). It is only used when building this testcase on + * its own for testing or for building a binary to use in testing binary + * analysis tools. It is not used when compiling all the testcases as one + * application, which is how source code analysis tools are tested. + */ + +#ifdef INCLUDEMAIN + +int main(int argc, char * argv[]) +{ + /* seed randomness */ + srand( (unsigned)time(NULL) ); +#ifndef OMITGOOD + printLine("Calling good()..."); + CWE127_Buffer_Underread__wchar_t_alloca_cpy_68_good(); + printLine("Finished good()"); +#endif /* OMITGOOD */ +#ifndef OMITBAD + printLine("Calling bad()..."); + CWE127_Buffer_Underread__wchar_t_alloca_cpy_68_bad(); + printLine("Finished bad()"); +#endif /* OMITBAD */ + return 0; +} + +#endif diff --git a/pool/shard004/C/0099213_pilot-clip.c b/pool/shard004/C/0099213_pilot-clip.c new file mode 100644 index 0000000000000000000000000000000000000000..e71f8f4c87f85bff055a6e305c5739e294ef8900 --- /dev/null +++ b/pool/shard004/C/0099213_pilot-clip.c @@ -0,0 +1,212 @@ +/* + * $Id: pilot-clip.c,v 1.38 2006/10/12 14:21:21 desrod Exp $ + * + * pilot-clip.c: Transfer data to or from the Palm's clipboard + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the + * Free Software Foundation; either version 2 of the License, or (at your + * option) any later version. + * + * This program is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General + * Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + * + */ + +#include +#include + +#include "pi-source.h" +#include "pi-syspkt.h" +#include "pi-dlp.h" +#include "pi-header.h" +#include "pi-userland.h" + +static void *GetClip(int sock, int type, int *length) +{ + int len, + err; + struct RPC_params p; + unsigned long handle, ptr; + void *buffer; + + /* ClipboardGetItem */ + PackRPC(&p, 0xA10C, RPC_PtrReply, RPC_Byte(type), RPC_ShortPtr(&len), + RPC_End); + err = dlp_RPC(sock, &p, &handle); + if (err) + return 0; + + if (!handle) + return 0; + + /* MemHandleLock */ + PackRPC(&p, 0xA021, RPC_PtrReply, RPC_Long(handle), RPC_End); + err = dlp_RPC(sock, &p, &ptr); + + if (err) + return 0; + + buffer = malloc(len); + + /* MemMove */ + PackRPC(&p, 0xA026, RPC_IntReply, RPC_Ptr(buffer, len), + RPC_Long(ptr), RPC_Long(len), RPC_End); + err = dlp_RPC(sock, &p, 0); + + /* MemHandleUnlock */ + PackRPC(&p, 0xA022, RPC_IntReply, RPC_Long(handle), RPC_End); + err = dlp_RPC(sock, &p, 0); + + if (length) + *length = len; + + return buffer; +} + +static int SetClip(int sock, int type, void *data, int length) +{ + int err; + char *b = data; + struct RPC_params p; + unsigned long handle, ptr; + + /* MemHandleNew */ + PackRPC(&p, 0xA01E, RPC_PtrReply, RPC_Long(length), RPC_End); + err = dlp_RPC(sock, &p, &handle); + if (err) + return 0; + + if (!handle) + return 0; + + /* MemHandleLock */ + PackRPC(&p, 0xA021, RPC_PtrReply, RPC_Long(handle), RPC_End); + err = dlp_RPC(sock, &p, &ptr); + + if (err) + return 0; + + /* MemMove */ + PackRPC(&p, 0xA026, RPC_IntReply, RPC_Long(ptr), + RPC_Ptr(b, length), RPC_Long(length), RPC_End); + err = dlp_RPC(sock, &p, 0); + + length--; + + /* ClipboardAddItem */ + PackRPC(&p, 0xA10A, RPC_IntReply, RPC_Byte(type), RPC_Long(ptr), + RPC_Short(length), RPC_End); + err = dlp_RPC(sock, &p, 0); + + /* MemPtrFree */ + PackRPC(&p, 0xA012, RPC_IntReply, RPC_Long(ptr), RPC_End); + err = dlp_RPC(sock, &p, 0); + return 1; +} + + +int main(int argc, const char *argv[]) +{ + int c, /* switch */ + sd = -1, + ret; + + enum { mode_none, mode_set='s', mode_get='g' } mode = mode_none; + + char buffer[0xffff]; + + poptContext po; + + struct poptOption options[] = { + USERLAND_RESERVED_OPTIONS + {"get", 'g', POPT_ARG_NONE, NULL, 'g', + "Print the contents of the clipboard on STDOUT", NULL}, + {"set", 's', POPT_ARG_NONE, NULL, 's', + "Set the value in the clipboard from STDIN", NULL}, + POPT_AUTOHELP + POPT_TABLEEND + }; + + po = poptGetContext("pilot-clip", argc, argv, options, 0); + poptSetOtherOptionHelp(po,"\n\n" + " Get or Set the Palm Clipboard contents from STDOUT/STDIN.\n" + " Must provide one of -g or -s.\n\n"); + + if (argc < 2) { + poptPrintUsage(po,stderr,0); + return 1; + } + + while ((c = poptGetNextOpt(po)) >= 0) { + switch (c) { + case 's': + case 'g': + if (mode != mode_none) { + fprintf(stderr, + " ERROR: --get or --set, not both.\n"); + return 1; + } + mode = c; + break; + default: + fprintf(stderr," ERROR: Unhandled option %d.\n", c); + return 1; + } + } + if (mode_none == mode) { + fprintf(stderr, " ERROR: You must specify whether to " + "\"Get\" or \"Set\" the clipboard\n"); + return -1; + } + + sd = plu_connect(); + if (sd < 0) + goto error; + + if (dlp_OpenConduit(sd) < 0) + goto error_close; + + + if (mode == mode_set) { + ret = read(fileno(stdin), buffer, 0xffff); + if (ret >= 0) { + buffer[ret++] = 0; + if (SetClip(sd, 0, buffer, ret) <= 0) + goto error_close; + } + } else { + char *b; + + ret = 0; + b = GetClip(sd, 0, &ret); + if (b == NULL) + goto error_close; + if (ret > 0) + write(fileno(stdout), b, ret); + } + + if (pi_close(sd) < 0) + goto error; + + return 0; + +error_close: + pi_close(sd); + +error: + return -1; +} + +/* vi: set ts=8 sw=4 sts=4 noexpandtab: cin */ +/* ex: set tabstop=4 expandtab: */ +/* Local Variables: */ +/* indent-tabs-mode: t */ +/* c-basic-offset: 8 */ +/* End: */ diff --git a/pool/shard004/C/0099216_ldbl2mpn.c b/pool/shard004/C/0099216_ldbl2mpn.c new file mode 100644 index 0000000000000000000000000000000000000000..bf4e4ff43fb7e70b85efd8c8ef126f98996a8c1e --- /dev/null +++ b/pool/shard004/C/0099216_ldbl2mpn.c @@ -0,0 +1,114 @@ +/* Copyright (C) 1995, 1996, 1997, 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; if not, write to the Free + Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA + 02111-1307 USA. */ + +#include "gmp.h" +#include "gmp-impl.h" +#include "longlong.h" +#include "ieee754.h" +#include +#include + +/* Convert a `long double' in IEEE854 standard double-precision format to a + multi-precision integer representing the significand scaled up by its + number of bits (64 for long double) and an integral power of two + (MPN frexpl). */ + +mp_size_t +__mpn_extract_long_double (mp_ptr res_ptr, mp_size_t size, + int *expt, int *is_neg, + long double value) +{ + union ieee854_long_double u; + u.d = value; + + *is_neg = u.ieee.negative; + *expt = (int) u.ieee.exponent - IEEE854_LONG_DOUBLE_BIAS; + +#if BITS_PER_MP_LIMB == 32 + res_ptr[0] = u.ieee.mantissa1; /* Low-order 32 bits of fraction. */ + res_ptr[1] = u.ieee.mantissa0; /* High-order 32 bits. */ + #define N 2 +#elif BITS_PER_MP_LIMB == 64 + /* Hopefully the compiler will combine the two bitfield extracts + and this composition into just the original quadword extract. */ + res_ptr[0] = ((unsigned long int) u.ieee.mantissa0 << 32) | u.ieee.mantissa1; + #define N 1 +#else + #error "mp_limb size " BITS_PER_MP_LIMB "not accounted for" +#endif + + if (u.ieee.exponent == 0) + { + /* A biased exponent of zero is a special case. + Either it is a zero or it is a denormal number. */ + if (res_ptr[0] == 0 && res_ptr[N - 1] == 0) /* Assumes N<=2. */ + /* It's zero. */ + *expt = 0; + else + { + /* It is a denormal number, meaning it has no implicit leading + one bit, and its exponent is in fact the format minimum. */ + int cnt; + + /* One problem with Intel's 80-bit format is that the explicit + leading one in the normalized representation has to be zero + for denormalized number. If it is one, the number is according + to Intel's specification an invalid number. We make the + representation unique by explicitly clearing this bit. */ + res_ptr[N - 1] &= ~(1L << ((LDBL_MANT_DIG - 1) % BITS_PER_MP_LIMB)); + + if (res_ptr[N - 1] != 0) + { + count_leading_zeros (cnt, res_ptr[N - 1]); + if (cnt != 0) + { +#if N == 2 + res_ptr[N - 1] = res_ptr[N - 1] << cnt + | (res_ptr[0] >> (BITS_PER_MP_LIMB - cnt)); + res_ptr[0] <<= cnt; +#else + res_ptr[N - 1] <<= cnt; +#endif + } + *expt = LDBL_MIN_EXP - 1 - cnt; + } + else if (res_ptr[0] != 0) + { + count_leading_zeros (cnt, res_ptr[0]); + res_ptr[N - 1] = res_ptr[0] << cnt; + res_ptr[0] = 0; + *expt = LDBL_MIN_EXP - 1 - BITS_PER_MP_LIMB - cnt; + } + else + { + /* This is the special case of the pseudo denormal number + with only the implicit leading bit set. The value is + in fact a normal number and so we have to treat this + case differently. */ +#if N == 2 + res_ptr[N - 1] = 0x80000000ul; +#else + res_ptr[0] = 0x8000000000000000ul; +#endif + *expt = LDBL_MIN_EXP - 1; + } + } + } + + return N; +} diff --git a/pool/shard004/C/0099221_GUIDEMO_AntialiasedText.c b/pool/shard004/C/0099221_GUIDEMO_AntialiasedText.c new file mode 100644 index 0000000000000000000000000000000000000000..dfb9d8887fe0217ea5ea243478d39ebc142a9760 --- /dev/null +++ b/pool/shard004/C/0099221_GUIDEMO_AntialiasedText.c @@ -0,0 +1,275 @@ +/********************************************************************* +* Portions COPYRIGHT 2016 STMicroelectronics * +* Portions SEGGER Microcontroller GmbH & Co. KG * +* Solutions for real time microcontroller applications * +********************************************************************** +* * +* (c) 1996 - 2015 SEGGER Microcontroller GmbH & Co. KG * +* * +* Internet: www.segger.com Support: support@segger.com * +* * +********************************************************************** + +** emWin V5.28 - Graphical user interface for embedded applications ** +All Intellectual Property rights in the Software belongs to SEGGER. +emWin is protected by international copyright laws. Knowledge of the +source code may not be used to write a similar product. This file may +only be used in accordance with the following terms: + +The software has been licensed to STMicroelectronics International +N.V. a Dutch company with a Swiss branch and its headquarters in Plan- +les-Ouates, Geneva, 39 Chemin du Champ des Filles, Switzerland for the +purposes of creating libraries for ARM Cortex-M-based 32-bit microcon_ +troller products commercialized by Licensee only, sublicensed and dis_ +tributed under the terms and conditions of the End User License Agree_ +ment supplied by STMicroelectronics International N.V. +Full source code is available at: www.segger.com + +We appreciate your understanding and fairness. +---------------------------------------------------------------------- +File : AA_Text.c +Purpose : Shows text with different antialiasing qualities +---------------------------------------------------------------------- +*/ + +/** + ****************************************************************************** + * @file AA_Text.c + * @author MCD Application Team + * @version V1.0.3 + * @date 29-January-2016 + * @brief Shows text with different antialiasing qualities + ****************************************************************************** + * @attention + * + * 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. + * + ****************************************************************************** + */ + +#include "GUIDEMO.h" + +#if (SHOW_GUIDEMO_AATEXT) + +/********************************************************************* +* +* Static const data +* +********************************************************************** +*/ +/********************************************************************* +* +* Static code +* +********************************************************************** +*/ +/********************************************************************* +* +* _DrawAlphaCircles +*/ +static void _DrawAlphaCircles(int mx, int my, int r, int a, int FactorAA) { + int Index; + int x; + int y; + I32 SinHQ; + I32 CosHQ; + U32 a1000; + U32 i; + const GUI_COLOR aColor[] = { + 0xC00FFF38, + 0xC000FF8E, + 0xC000FCEA, + 0xC000B4FF, + 0xC0004EFF, + 0xC01304FF, + 0xC06E00FF, + 0xC0D200FF, + 0xC0FF00D2, + 0xC0FF006E, + 0xC0FF0413, + 0xC0FF4E00, + 0xC0FFB400, + 0xC0EAFC00, + 0xC08EFF00, + 0xC038FF0F + }; + + mx *= FactorAA; + my *= FactorAA; + r *= FactorAA; + a1000 = a * -1000; + for (i = 0, Index = 0; i < 360000; i += 22500, Index++) { + SinHQ = GUI__SinHQ(i + a1000); + CosHQ = GUI__CosHQ(i + a1000); + x = (U32)(r * CosHQ) >> 16; + y = (U32)(r * SinHQ) >> 16; + GUI_SetColor(aColor[Index % (int)GUI_COUNTOF(aColor)]); + GUI_AA_EnableHiRes(); + GUI_AA_SetFactor(FactorAA); + GUI_AA_FillCircle(mx + x, my + y, r); + GUI_AA_DisableHiRes(); + } +} + +/********************************************************************* +* +* _DrawSample +*/ +static void _DrawSample(GUI_RECT * pRect, int yd) { + GUI_RECT Rect; + + Rect = *pRect; + // + // Use application defined clip rectangle + // + GUI_SetClipRect(&Rect); + // + // Move clip rectangle + // + GUI_MoveRect(&Rect, 65, 0); + // + // Draw sample + // + _DrawAlphaCircles((Rect.x0 + Rect.x1) / 2, (Rect.y0 + Rect.y1) / 2, 35, 0, 4); + GUI_SetColor(GUI_WHITE); + GUI_DispStringInRectWrap("ABC\nABC\nABC", &Rect, GUI_TA_HCENTER | GUI_TA_VCENTER, GUI_WRAPMODE_WORD); + // + // Move clip rectangle + // + GUI_MoveRect(&Rect, 65, 0); + + GUI_DrawGradientH(Rect.x0, Rect.y0, Rect.x1, Rect.y1, GUI_BLACK, GUI_WHITE); + Rect.y1 = Rect.y0 + yd; + GUI_SetColor(GUI_RED); + GUI_DispStringInRect("ABC", &Rect, GUI_TA_HCENTER | GUI_TA_VCENTER); + GUI_MoveRect(&Rect, 0, yd); + GUI_SetColor(GUI_GREEN); + GUI_DispStringInRect("ABC", &Rect, GUI_TA_HCENTER | GUI_TA_VCENTER); + GUI_MoveRect(&Rect, 0, yd); + GUI_SetColor(GUI_BLUE); + GUI_DispStringInRect("ABC", &Rect, GUI_TA_HCENTER | GUI_TA_VCENTER); + GUI_MoveRect(&Rect, 0, -yd * 2); + Rect.y1 = Rect.y0 + yd * 3; + // + // Move clip rectangle + // + GUI_MoveRect(&Rect, 65, 0); + // + // Draw sample + // + Rect.y1 = Rect.y0 + yd; + GUI_SetBkColor(GUI_RED); + GUI_Clear(); + GUI_MoveRect(&Rect, 0, yd); + GUI_SetBkColor(GUI_GREEN); + GUI_Clear(); + GUI_MoveRect(&Rect, 0, yd); + GUI_SetBkColor(GUI_BLUE); + GUI_Clear(); + GUI_MoveRect(&Rect, 0, -yd * 2); + Rect.y1 = Rect.y0 + yd * 3; + GUI_SetColor(GUI_WHITE); + GUI_DispStringInRectWrap("ABC\nABC\nABC", &Rect, GUI_TA_HCENTER | GUI_TA_VCENTER, GUI_WRAPMODE_WORD); + // + // Move clip rectangle + // + GUI_MoveRect(&Rect, 65, 0); + // + // Draw sample + // + Rect.y1 = Rect.y0 + yd; + GUI_DrawGradientV(Rect.x0, Rect.y0, Rect.x1, Rect.y1, GUI_RED, GUI_BLACK); + GUI_MoveRect(&Rect, 0, yd); + GUI_DrawGradientV(Rect.x0, Rect.y0, Rect.x1, Rect.y1, GUI_GREEN, GUI_BLACK); + GUI_MoveRect(&Rect, 0, yd); + GUI_DrawGradientV(Rect.x0, Rect.y0, Rect.x1, Rect.y1, GUI_BLUE, GUI_BLACK); + GUI_MoveRect(&Rect, 0, -yd * 2); + Rect.y1 = Rect.y0 + yd * 3; + GUI_SetColor(GUI_WHITE); + GUI_DispStringInRectWrap("ABC\nABC\nABC", &Rect, GUI_TA_HCENTER | GUI_TA_VCENTER, GUI_WRAPMODE_WORD); + // + // Disable application defined clip rectangle + // + GUI_SetClipRect(NULL); +} + +/********************************************************************* +* +* _DrawText +*/ +static void _DrawText(char * s, GUI_RECT * pRect) { + GUI_SetFont(GUI_FONT_13_ASCII); + GUI_SetColor(GUI_WHITE); + GUI_DispStringInRectWrap(s, pRect, GUI_TA_HCENTER | GUI_TA_VCENTER, GUI_WRAPMODE_WORD); +} + +/********************************************************************* +* +* _DrawScreen +*/ +static void _DrawScreen(void) { + GUI_RECT Rect; + int yd; + + GUI_SetFont(&GUI_FontRounded22); + GUI_DispStringHCenterAt("Antialiased text sample", 190, 12); + Rect.x0 = 0; + Rect.y0 = 43; + Rect.x1 = 59; + Rect.y1 = Rect.y0 + 95; + yd = (Rect.y1 - Rect.y0) / 3; + // + // 4 bit antialiasing sample + // + _DrawText("Antialiased text\n (4 bpp)", &Rect); + GUI_SetFont(&GUI_FontAA4_32); + _DrawSample(&Rect, yd); + // + // 2 bit antialiasing sample + // + GUI_MoveRect(&Rect, 0, 101); + _DrawText("Antialiased text\n (2 bpp)", &Rect); + GUI_SetFont(&GUI_FontAA2_32); + _DrawSample(&Rect, yd); +} + +/********************************************************************* +* +* Public code +* +********************************************************************** +*/ +/********************************************************************* +* +* MainTask +*/ +void GUIDEMO_AntialiasedText(void) { + unsigned OldAlphaState; + + GUIDEMO_ShowIntro("Antialiased Text", + "Output antialiased text\n" + "on different backgrounds."); + GUIDEMO_DrawBk(1); + OldAlphaState = GUI_EnableAlpha(1); + _DrawScreen(); + GUIDEMO_Wait(4000); + GUI_EnableAlpha(OldAlphaState); +} + +#else + +void GUIDEMO_AntialiasedText(void) {} + +#endif /* SHOW_GUIDEMO_AATEXT */ + +/*************************** End of file ****************************/ diff --git a/pool/shard004/C/0099234_test.c b/pool/shard004/C/0099234_test.c new file mode 100644 index 0000000000000000000000000000000000000000..49d158ff5b7d7367147436751397d592e37a4c27 --- /dev/null +++ b/pool/shard004/C/0099234_test.c @@ -0,0 +1,201 @@ +/* This file contains what could be called a set of unit tests for the + * accompanying skip list implementation. These functions provide examples + * of how to use the list calls and manage the pointers they return. + * + * (C) 2013 by Troy Deck; see LICENSE.txt for details + */ +#include "test.h" +#include +#include +#include + +// Simply runs all the test functions +int main() { + int err; + if ((err = test_get_set())) return err; + if ((err = test_unset())) return err; + if ((err = test_hundred_inserts())) return err; + + return E_OK; +} + + +// Tests that skip-list initialization, get, and set methods appear +// to be working correctly for a list with three elements. +int test_get_set() { + int err; + + printf("Starting test_get_set:\n"); + + // Try to allocate a list + printf("\tAllocating a list...\n"); + sl_entry * head = sl_init(); + if (!head) { + printf("\tFAIL: Initialization returned null pointer.\n"); + return E_NULL_INIT; + } + + // Insert three elements + printf("\tInserting three elements...\n"); + sl_set(head, "Bravo", "B"); + sl_set(head, "A", "Alpha"); + sl_set(head, "Charlie", "C"); + + // Extract elements and compare with our expectations + // "A" -> "Alpha" + printf("\tLooking up first element...\n"); + if ((err = assert_sl_get(head, "A", "Alpha"))) return err; + + // "Bravo" -> "B" + printf("\tLooking up second element...\n"); + if ((err = assert_sl_get(head, "Bravo", "B"))) return err; + + // "Charlie" -> "C" + printf("\tLooking up third element...\n"); + if ((err = assert_sl_get(head, "Charlie", "C"))) return err; + + // Now test extracting something not in the list + printf("\tLooking up nonexistent element...\n"); + if ((err = assert_sl_get(head, "Delta", NULL))) return err; + + // Deallocate the list + printf("\tFreeing the list...\n"); + sl_destroy(head); + head = NULL; + + printf("\tPASS: test_get_set passed\n"); + return E_OK; +} + +// Tests that unset elements are correctly removed from the skip list, +// while preserving the list's structure. +int test_unset() { + int err; + printf("Starting test_unset:\n"); + + // Try to allocate a list + printf("\tAllocating a list...\n"); + sl_entry * head = sl_init(); + if (!head) { + printf("\tFAIL: Initialization returned null pointer.\n"); + return E_NULL_INIT; + } + + // Put three elements in the list + printf("\tInserting three elements...\n"); + sl_set(head, "333", "Three"); + sl_set(head, "222", "Two"); + sl_set(head, "111", "One"); + + // Unset a nonexistent element + printf("\tUnsetting a nonexistent element...\n"); + sl_unset(head, "999"); + + // Check all three values + printf("\tChecking list values...\n"); + if ((err = assert_sl_get(head, "111", "One"))) return err; + if ((err = assert_sl_get(head, "222", "Two"))) return err; + if ((err = assert_sl_get(head, "333", "Three"))) return err; + + // Unset the second list element + printf("\tUnsetting the second element...\n"); + sl_unset(head, "222"); + + // Check all three values again + printf("\tChecking list values...\n"); + if ((err = assert_sl_get(head, "111", "One"))) return err; + if ((err = assert_sl_get(head, "222", NULL))) return err; + if ((err = assert_sl_get(head, "333", "Three"))) return err; + + // Deallocate the list + sl_destroy(head); + head = NULL; + + printf("\tPASS: test_unset passed\n"); + return E_OK; +} + +// A bulk test of set, unset, and get +int test_hundred_inserts() { + int err; + printf("Starting test_hundred_inserts:\n"); + + // Try to allocate a list + printf("\tAllocating a list...\n"); + sl_entry * head = sl_init(); + if (!head) { + printf("\tFAIL: Initialization returned null pointer.\n"); + return E_NULL_INIT; + } + + // Insert 100 elements but unset every odd element + // after insertion + printf("\tPerforming 100 sets and 50 unsets...\n"); + char num_buffer[3]; + int i; + for (i = 99; i >= 0; -- i) { + sprintf(num_buffer, "%d", i); + sl_set(head, num_buffer, num_buffer); + + if (i % 2) { + sl_unset(head, num_buffer); + } + } + + // Test each element + printf("\tVerifying list...\n"); + for (i = 0; i < 100; ++ i) { + sprintf(num_buffer, "%d", i); + + if (i % 2) { + // Expect a NULL result + if ((err = assert_sl_get(head, num_buffer, NULL))) return err; + } else { + // Expect the correct numeric result + if ((err = assert_sl_get(head, num_buffer, num_buffer))) return err; + } + } + + // Deallocate the list + sl_destroy(head); + + head = NULL; + printf("\tPASS: test_hundred_inserts passed\n"); + return E_OK; +} + +// A utility function used to check that the expected value was +// returned from an sl_get call, since we do this a lot in these tests. +// Handles printing error messages, returning result codes, and special cases +// of returned and/or expected NULLs. +int assert_sl_get(sl_entry * head, char * key, char * expected_str) { + char * result_str; + result_str = sl_get(head, key); + + if (result_str) { // We got a non-NULL result + if (expected_str) { // ... and we expected one + if (strcmp(result_str, expected_str)) { + printf( + "\tFAIL: Expected '%s' but got '%s'.\n", + expected_str, + result_str + ); + free(result_str); + return E_WRONG_RESULT; + } + } else { // ... but we expected null + printf("\tFAIL: Got a non-null pointer for an unexpected key.\n"); + free(result_str); // Potentially dangerous + return E_PHANTOM_RESULT; + } + } else { // We got a NULL pointer + if (expected_str) { // ... but we expected a real result + printf( + "\tFAIL: Expected '%s' but got a null pointer.\n", + expected_str + ); + return E_NULL_GET; + } + } + return E_OK; +} diff --git a/pool/shard004/C/0099239_coninst_c2.c b/pool/shard004/C/0099239_coninst_c2.c new file mode 100644 index 0000000000000000000000000000000000000000..89fbb6c6014da9cc2f6c5b10a914902798c09911 --- /dev/null +++ b/pool/shard004/C/0099239_coninst_c2.c @@ -0,0 +1,108 @@ +#ifndef lint +static char id[] = "$Id: coninst_c2.c,v 1.1 2001/12/21 18:39:07 lombard Exp $"; +#endif + +#include + +typedef struct { + float x, y; +} COMPLEX; + +struct { + int iunit; + float ds; + float gain; + int npoles; + int nzeros; + COMPLEX poles[60]; +} instr_; + + +/* map the common block */ +void InitInstrResponse(iunit, ds, gain, npoles, nzeros, poles) + int iunit; float ds, gain; int npoles, nzeros; COMPLEX *poles; +{ + int i; + + instr_.iunit= iunit; + instr_.ds= ds; + instr_.gain= gain; + instr_.npoles= npoles; + instr_.nzeros= nzeros; + for(i=0;i<60;i++) { + instr_.poles[i].x= poles[i].x; + instr_.poles[i].y= poles[i].y; + } + return; +} + +/* + * instr_type: 0 - deconvolve + * 1 - Benioff 100kg (Mb) + * 2 - 17s-23s 10 pole butterworth filter (Ms) + * 3 - Wood Anderson (ML) + */ +void +ConvertInstr( nsamp, srate, instr_type, data ) + int nsamp; float srate; int instr_type; float *data; +{ + int npts, ind, n2, i; + float dt, dum; + float *cw, *c1; + + npts= nsamp; + ind= instr_type; + n2= ipow_(&npts); + dum= 0.0; + dt= (float)1/srate; + cw= (float *)malloc(sizeof(double)*n2); + c1= (float *)malloc(sizeof(float)*n2); + + for(i=0;i +#include +#include +#include + +#include + +#include +#include + + +static inline void unmask_msp_cic_irq(unsigned int irq) +{ + + /* check for PER interrupt range */ + if (irq < MSP_PER_INTBASE) + *CIC_VPE0_MSK_REG |= (1 << (irq - MSP_CIC_INTBASE)); + else + *PER_INT_MSK_REG |= (1 << (irq - MSP_PER_INTBASE)); +} + +static inline void mask_msp_cic_irq(unsigned int irq) +{ + /* check for PER interrupt range */ + if (irq < MSP_PER_INTBASE) + *CIC_VPE0_MSK_REG &= ~(1 << (irq - MSP_CIC_INTBASE)); + else + *PER_INT_MSK_REG &= ~(1 << (irq - MSP_PER_INTBASE)); +} + +static inline void ack_msp_cic_irq(unsigned int irq) +{ + mask_msp_cic_irq(irq); + + /* + * only really necessary for 18, 16-14 and sometimes 3:0 (since + * these can be edge sensitive) but it doesn't hurt for the others. + */ + + /* check for PER interrupt range */ + if (irq < MSP_PER_INTBASE) + *CIC_STS_REG = (1 << (irq - MSP_CIC_INTBASE)); + else + *PER_INT_STS_REG = (1 << (irq - MSP_PER_INTBASE)); +} + +static struct irq_chip msp_cic_irq_controller = { + .name = "MSP_CIC", + .ack = ack_msp_cic_irq, + .mask = ack_msp_cic_irq, + .mask_ack = ack_msp_cic_irq, + .unmask = unmask_msp_cic_irq, +}; + + +void __init msp_cic_irq_init(void) +{ + int i; + + /* Mask/clear interrupts. */ + *CIC_VPE0_MSK_REG = 0x00000000; + *PER_INT_MSK_REG = 0x00000000; + *CIC_STS_REG = 0xFFFFFFFF; + *PER_INT_STS_REG = 0xFFFFFFFF; + +#if defined(CONFIG_PMC_MSP7120_GW) || \ + defined(CONFIG_PMC_MSP7120_EVAL) + /* + * The MSP7120 RG and EVBD boards use IRQ[6:4] for PCI. + * These inputs map to EXT_INT_POL[6:4] inside the CIC. + * They are to be active low, level sensitive. + */ + *CIC_EXT_CFG_REG &= 0xFFFF8F8F; +#endif + + /* initialize all the IRQ descriptors */ + for (i = MSP_CIC_INTBASE; i < MSP_PER_INTBASE + 32; i++) + set_irq_chip_and_handler(i, &msp_cic_irq_controller, + handle_level_irq); +} + +void msp_cic_irq_dispatch(void) +{ + u32 pending; + int intbase; + + intbase = MSP_CIC_INTBASE; + pending = *CIC_STS_REG & *CIC_VPE0_MSK_REG; + + /* check for PER interrupt */ + if (pending == (1 << (MSP_INT_PER - MSP_CIC_INTBASE))) { + intbase = MSP_PER_INTBASE; + pending = *PER_INT_STS_REG & *PER_INT_MSK_REG; + } + + /* check for spurious interrupt */ + if (pending == 0x00000000) { + printk(KERN_ERR + "Spurious %s interrupt? status %08x, mask %08x\n", + (intbase == MSP_CIC_INTBASE) ? "CIC" : "PER", + (intbase == MSP_CIC_INTBASE) ? + *CIC_STS_REG : *PER_INT_STS_REG, + (intbase == MSP_CIC_INTBASE) ? + *CIC_VPE0_MSK_REG : *PER_INT_MSK_REG); + return; + } + + /* check for the timer and dispatch it first */ + if ((intbase == MSP_CIC_INTBASE) && + (pending & (1 << (MSP_INT_VPE0_TIMER - MSP_CIC_INTBASE)))) + do_IRQ(MSP_INT_VPE0_TIMER); + else + do_IRQ(ffs(pending) + intbase - 1); +} diff --git a/pool/shard004/C/0099244_tdbdump.c b/pool/shard004/C/0099244_tdbdump.c new file mode 100644 index 0000000000000000000000000000000000000000..8cf3146c4b65d7138cac3f24dad3d1ffe2c683c6 --- /dev/null +++ b/pool/shard004/C/0099244_tdbdump.c @@ -0,0 +1,179 @@ +/* + Unix SMB/CIFS implementation. + simple tdb dump util + Copyright (C) Andrew Tridgell 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 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 "replace.h" +#include "system/locale.h" +#include "system/time.h" +#include "system/filesys.h" +#include "system/wait.h" +#include "tdb.h" + +static void print_data(TDB_DATA d) +{ + unsigned char *p = (unsigned char *)d.dptr; + int len = d.dsize; + while (len--) { + if (isprint(*p) && !strchr("\"\\", *p)) { + fputc(*p, stdout); + } else { + printf("\\%02X", *p); + } + p++; + } +} + +static int traverse_fn(TDB_CONTEXT *tdb, TDB_DATA key, TDB_DATA dbuf, void *state) +{ + printf("{\n"); + printf("key(%d) = \"", (int)key.dsize); + print_data(key); + printf("\"\n"); + printf("data(%d) = \"", (int)dbuf.dsize); + print_data(dbuf); + printf("\"\n"); + printf("}\n"); + return 0; +} + +static void log_stderr(struct tdb_context *tdb, enum tdb_debug_level level, + const char *fmt, ...) PRINTF_ATTRIBUTE(3,4); + +static void log_stderr(struct tdb_context *tdb, enum tdb_debug_level level, + const char *fmt, ...) +{ + va_list ap; + const char *name = tdb_name(tdb); + const char *prefix = ""; + + if (!name) + name = "unnamed"; + + switch (level) { + case TDB_DEBUG_ERROR: + prefix = "ERROR: "; + break; + case TDB_DEBUG_WARNING: + prefix = "WARNING: "; + break; + case TDB_DEBUG_TRACE: + return; + + default: + case TDB_DEBUG_FATAL: + prefix = "FATAL: "; + break; + } + + va_start(ap, fmt); + fprintf(stderr, "tdb(%s): %s", name, prefix); + vfprintf(stderr, fmt, ap); + va_end(ap); +} + +static void emergency_walk(TDB_DATA key, TDB_DATA dbuf, void *keyname) +{ + if (keyname) { + if (key.dsize != strlen(keyname)) + return; + if (memcmp(key.dptr, keyname, key.dsize) != 0) + return; + } + traverse_fn(NULL, key, dbuf, NULL); +} + +static int dump_tdb(const char *fname, const char *keyname, bool emergency) +{ + TDB_CONTEXT *tdb; + TDB_DATA key, value; + struct tdb_logging_context logfn = { log_stderr }; + int tdb_flags = TDB_DEFAULT; + + /* + * Note: that O_RDONLY implies TDB_NOLOCK, but we want to make it + * explicit as it's important when working on databases which were + * created with mutex locking. + */ + tdb_flags |= TDB_NOLOCK; + + tdb = tdb_open_ex(fname, 0, tdb_flags, O_RDONLY, 0, &logfn, NULL); + if (!tdb) { + printf("Failed to open %s\n", fname); + return 1; + } + + if (emergency) { + return tdb_rescue(tdb, emergency_walk, discard_const(keyname)) == 0; + } + if (!keyname) { + return tdb_traverse(tdb, traverse_fn, NULL) == -1 ? 1 : 0; + } else { + key.dptr = discard_const_p(uint8_t, keyname); + key.dsize = strlen(keyname); + value = tdb_fetch(tdb, key); + if (!value.dptr) { + return 1; + } else { + print_data(value); + free(value.dptr); + } + } + + return 0; +} + +static void usage( void) +{ + printf( "Usage: tdbdump [options] \n\n"); + printf( " -h this help message\n"); + printf( " -k keyname dumps value of keyname\n"); + printf( " -e emergency dump, for corrupt databases\n"); +} + + int main(int argc, char *argv[]) +{ + char *fname, *keyname=NULL; + bool emergency = false; + int c; + + if (argc < 2) { + printf("Usage: tdbdump \n"); + exit(1); + } + + while ((c = getopt( argc, argv, "hk:e")) != -1) { + switch (c) { + case 'h': + usage(); + exit( 0); + case 'k': + keyname = optarg; + break; + case 'e': + emergency = true; + break; + default: + usage(); + exit( 1); + } + } + + fname = argv[optind]; + + return dump_tdb(fname, keyname, emergency); +} diff --git a/pool/shard004/C/0099250_spiffs_example_main.c b/pool/shard004/C/0099250_spiffs_example_main.c new file mode 100644 index 0000000000000000000000000000000000000000..d2ead7308b3c6105a1ba2c5a9b442264d2b7de3e --- /dev/null +++ b/pool/shard004/C/0099250_spiffs_example_main.c @@ -0,0 +1,99 @@ +/* SPIFFS filesystem example. + This example code is in the Public Domain (or CC0 licensed, at your option.) + + Unless required by applicable law or agreed to in writing, this + software is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR + CONDITIONS OF ANY KIND, either express or implied. +*/ + +#include +#include +#include +#include +#include "esp_err.h" +#include "esp_log.h" +#include "esp_spiffs.h" + +static const char *TAG = "example"; + +void app_main(void) +{ + ESP_LOGI(TAG, "Initializing SPIFFS"); + + esp_vfs_spiffs_conf_t conf = { + .base_path = "/spiffs", + .partition_label = NULL, + .max_files = 5, + .format_if_mount_failed = true + }; + + // Use settings defined above to initialize and mount SPIFFS filesystem. + // Note: esp_vfs_spiffs_register is an all-in-one convenience function. + esp_err_t ret = esp_vfs_spiffs_register(&conf); + + if (ret != ESP_OK) { + if (ret == ESP_FAIL) { + ESP_LOGE(TAG, "Failed to mount or format filesystem"); + } else if (ret == ESP_ERR_NOT_FOUND) { + ESP_LOGE(TAG, "Failed to find SPIFFS partition"); + } else { + ESP_LOGE(TAG, "Failed to initialize SPIFFS (%d)", ret); + } + return; + } + + size_t total = 0, used = 0; + ret = esp_spiffs_info(NULL, &total, &used); + if (ret != ESP_OK) { + ESP_LOGE(TAG, "Failed to get SPIFFS partition information"); + } else { + ESP_LOGI(TAG, "Partition size: total: %d, used: %d", total, used); + } + + // Use POSIX and C standard library functions to work with files. + // First create a file. + ESP_LOGI(TAG, "Opening file"); + FILE* f = fopen("/spiffs/hello.txt", "w"); + if (f == NULL) { + ESP_LOGE(TAG, "Failed to open file for writing"); + return; + } + fprintf(f, "Hello World!\n"); + fclose(f); + ESP_LOGI(TAG, "File written"); + + // Check if destination file exists before renaming + struct stat st; + if (stat("/spiffs/foo.txt", &st) == 0) { + // Delete it if it exists + unlink("/spiffs/foo.txt"); + } + + // Rename original file + ESP_LOGI(TAG, "Renaming file"); + if (rename("/spiffs/hello.txt", "/spiffs/foo.txt") != 0) { + ESP_LOGE(TAG, "Rename failed"); + return; + } + + // Open renamed file for reading + ESP_LOGI(TAG, "Reading file"); + f = fopen("/spiffs/foo.txt", "r"); + if (f == NULL) { + ESP_LOGE(TAG, "Failed to open file for reading"); + return; + } + char line[64]; + fgets(line, sizeof(line), f); + fclose(f); + // strip newline + char* pos = strchr(line, '\n'); + if (pos) { + *pos = '\0'; + } + ESP_LOGI(TAG, "Read from file: '%s'", line); + + // All done, unmount partition and disable SPIFFS + esp_vfs_spiffs_unregister(NULL); + ESP_LOGI(TAG, "SPIFFS unmounted"); +} diff --git a/pool/shard004/C/0099255_messages_dgm_ref.c b/pool/shard004/C/0099255_messages_dgm_ref.c new file mode 100644 index 0000000000000000000000000000000000000000..39d22700740c1492baade795db393077cdffceb4 --- /dev/null +++ b/pool/shard004/C/0099255_messages_dgm_ref.c @@ -0,0 +1,163 @@ +/* + * Unix SMB/CIFS implementation. + * Samba internal messaging functions + * Copyright (C) 2014 by Volker Lendecke + * + * 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 "replace.h" +#include +#include "messages_dgm.h" +#include "messages_dgm_ref.h" +#include "lib/util/debug.h" +#include "lib/util/dlinklist.h" + +struct msg_dgm_ref { + struct msg_dgm_ref *prev, *next; + struct messaging_dgm_fde *fde; + void (*recv_cb)(struct tevent_context *ev, + const uint8_t *msg, size_t msg_len, + int *fds, size_t num_fds, void *private_data); + void *recv_cb_private_data; +}; + +static pid_t dgm_pid = 0; +static struct msg_dgm_ref *refs = NULL; + +static int msg_dgm_ref_destructor(struct msg_dgm_ref *r); +static void msg_dgm_ref_recv(struct tevent_context *ev, + const uint8_t *msg, size_t msg_len, + int *fds, size_t num_fds, void *private_data); + +void *messaging_dgm_ref(TALLOC_CTX *mem_ctx, struct tevent_context *ev, + uint64_t *unique, + const char *socket_dir, + const char *lockfile_dir, + void (*recv_cb)(struct tevent_context *ev, + const uint8_t *msg, size_t msg_len, + int *fds, size_t num_fds, + void *private_data), + void *recv_cb_private_data, + int *err) +{ + struct msg_dgm_ref *result, *tmp_refs; + + result = talloc(mem_ctx, struct msg_dgm_ref); + if (result == NULL) { + *err = ENOMEM; + return NULL; + } + result->fde = NULL; + + tmp_refs = refs; + + if ((refs != NULL) && (dgm_pid != getpid())) { + /* + * Have to reinit after fork + */ + messaging_dgm_destroy(); + refs = NULL; + } + + if (refs == NULL) { + int ret; + + ret = messaging_dgm_init(ev, unique, socket_dir, lockfile_dir, + msg_dgm_ref_recv, NULL); + DBG_DEBUG("messaging_dgm_init returned %s\n", strerror(ret)); + if (ret != 0) { + DEBUG(10, ("messaging_dgm_init failed: %s\n", + strerror(ret))); + TALLOC_FREE(result); + *err = ret; + return NULL; + } + dgm_pid = getpid(); + } else { + int ret; + ret = messaging_dgm_get_unique(getpid(), unique); + DBG_DEBUG("messaging_dgm_get_unique returned %s\n", + strerror(ret)); + if (ret != 0) { + TALLOC_FREE(result); + *err = ret; + return NULL; + } + + } + + result->fde = messaging_dgm_register_tevent_context(result, ev); + if (result->fde == NULL) { + TALLOC_FREE(result); + *err = ENOMEM; + return NULL; + } + + DBG_DEBUG("unique = %"PRIu64"\n", *unique); + + refs = tmp_refs; + + result->recv_cb = recv_cb; + result->recv_cb_private_data = recv_cb_private_data; + DLIST_ADD(refs, result); + talloc_set_destructor(result, msg_dgm_ref_destructor); + + return result; +} + +static void msg_dgm_ref_recv(struct tevent_context *ev, + const uint8_t *msg, size_t msg_len, + int *fds, size_t num_fds, void *private_data) +{ + struct msg_dgm_ref *r, *next; + + /* + * We have to broadcast incoming messages to all refs. The first ref + * that grabs the fd's will get them. + */ + for (r = refs; r != NULL; r = next) { + bool active; + + next = r->next; + + active = messaging_dgm_fde_active(r->fde); + if (!active) { + /* + * r's tevent_context has died. + */ + continue; + } + + r->recv_cb(ev, msg, msg_len, fds, num_fds, + r->recv_cb_private_data); + } +} + +static int msg_dgm_ref_destructor(struct msg_dgm_ref *r) +{ + if (refs == NULL) { + abort(); + } + DLIST_REMOVE(refs, r); + + TALLOC_FREE(r->fde); + + DBG_DEBUG("refs=%p\n", refs); + + if (refs == NULL) { + messaging_dgm_destroy(); + } + return 0; +} diff --git a/pool/shard004/C/0099257_halt.c b/pool/shard004/C/0099257_halt.c new file mode 100644 index 0000000000000000000000000000000000000000..fe3cb9e75357d081491fffaf3b30e2f47c4f509f --- /dev/null +++ b/pool/shard004/C/0099257_halt.c @@ -0,0 +1,249 @@ +/* vi: set sw=4 ts=4: */ +/* + * Poweroff reboot and halt, oh my. + * + * Copyright 2006 by Rob Landley + * + * Licensed under GPLv2, see file LICENSE in this source tree. + */ +//config:config HALT +//config: bool "halt (4 kb)" +//config: default y +//config: help +//config: Stop all processes and halt the system. +//config: +//config:config POWEROFF +//config: bool "poweroff (4 kb)" +//config: default y +//config: help +//config: Stop all processes and power off the system. +//config: +//config:config REBOOT +//config: bool "reboot (4 kb)" +//config: default y +//config: help +//config: Stop all processes and reboot the system. +//config: +//config:config FEATURE_WAIT_FOR_INIT +//config: bool "Before signaling init, make sure it is ready for it" +//config: default y +//config: depends on HALT || POWEROFF || REBOOT +//config: help +//config: In rare cases, poweroff may be commanded by firmware to OS +//config: even before init process exists. On Linux, this spawns +//config: "/sbin/poweroff" very early. This option adds code +//config: which checks that init is ready to receive poweroff +//config: commands. Code size increase of ~80 bytes. +//config: +//config:config FEATURE_CALL_TELINIT +//config: bool "Call telinit on shutdown and reboot" +//config: default y +//config: depends on (HALT || POWEROFF || REBOOT) && !INIT +//config: help +//config: Call an external program (normally telinit) to facilitate +//config: a switch to a proper runlevel. +//config: +//config: This option is only available if you selected halt and friends, +//config: but did not select init. +//config: +//config:config TELINIT_PATH +//config: string "Path to telinit executable" +//config: default "/sbin/telinit" +//config: depends on FEATURE_CALL_TELINIT +//config: help +//config: When busybox halt and friends have to call external telinit +//config: to facilitate proper shutdown, this path is to be used when +//config: locating telinit executable. + +//applet:IF_HALT(APPLET(halt, BB_DIR_SBIN, BB_SUID_DROP)) +// APPLET_ODDNAME:name main location suid_type help +//applet:IF_POWEROFF(APPLET_ODDNAME(poweroff, halt, BB_DIR_SBIN, BB_SUID_DROP, poweroff)) +//applet:IF_REBOOT( APPLET_ODDNAME(reboot, halt, BB_DIR_SBIN, BB_SUID_DROP, reboot)) + +//kbuild:lib-$(CONFIG_HALT) += halt.o +//kbuild:lib-$(CONFIG_POWEROFF) += halt.o +//kbuild:lib-$(CONFIG_REBOOT) += halt.o + +//usage:#define halt_trivial_usage +//usage: "[-d DELAY] [-nf"IF_FEATURE_WTMP("w")"]" +//usage:#define halt_full_usage "\n\n" +//usage: "Halt the system\n" +//usage: "\n -d SEC Delay interval" +//usage: "\n -n Do not sync" +//usage: "\n -f Force (don't go through init)" +//usage: IF_FEATURE_WTMP( +//usage: "\n -w Only write a wtmp record" +//usage: ) +//usage: +//usage:#define poweroff_trivial_usage +//usage: "[-d DELAY] [-nf]" +//usage:#define poweroff_full_usage "\n\n" +//usage: "Halt and shut off power\n" +//usage: "\n -d SEC Delay interval" +//usage: "\n -n Do not sync" +//usage: "\n -f Force (don't go through init)" +//usage: +//usage:#define reboot_trivial_usage +//usage: "[-d DELAY] [-nf]" +//usage:#define reboot_full_usage "\n\n" +//usage: "Reboot the system\n" +//usage: "\n -d SEC Delay interval" +//usage: "\n -n Do not sync" +//usage: "\n -f Force (don't go through init)" + +#include "libbb.h" +#include "reboot.h" + +#if ENABLE_FEATURE_WTMP +#include + +static void write_wtmp(void) +{ + struct utmpx utmp; + struct utsname uts; + /* "man utmp" says wtmp file should *not* be created automagically */ + /*if (access(bb_path_wtmp_file, R_OK|W_OK) == -1) { + close(creat(bb_path_wtmp_file, 0664)); + }*/ + memset(&utmp, 0, sizeof(utmp)); + utmp.ut_tv.tv_sec = time(NULL); + strcpy(utmp.ut_user, "shutdown"); /* it is wide enough */ + utmp.ut_type = RUN_LVL; + utmp.ut_id[0] = '~'; utmp.ut_id[1] = '~'; /* = strcpy(utmp.ut_id, "~~"); */ + utmp.ut_line[0] = '~'; utmp.ut_line[1] = '~'; /* = strcpy(utmp.ut_line, "~~"); */ + uname(&uts); + safe_strncpy(utmp.ut_host, uts.release, sizeof(utmp.ut_host)); + updwtmpx(bb_path_wtmp_file, &utmp); +} +#else +#define write_wtmp() ((void)0) +#endif + +#if ENABLE_FEATURE_WAIT_FOR_INIT +/* In Linux, "poweroff" may be spawned even before init. + * For example, with ACPI: + * linux/drivers/acpi/bus.c: + * static void sb_notify_work(struct work_struct *dummy) + * orderly_poweroff(true); + * linux/kernel/reboot.c: + * static int run_cmd(const char *cmd) + * ret = call_usermodehelper(argv[0], argv, envp, UMH_WAIT_EXEC); + * poweroff_cmd[] = "/sbin/poweroff"; + * static int __orderly_poweroff(bool force) + * ret = run_cmd(poweroff_cmd); + * + * We want to make sure init exists and listens to signals. + */ +static int init_was_not_there(void) +{ + enum { initial = 5 }; /* 5 seconds should be plenty for timeout */ + int cnt = initial - 1; + + /* Just existence of PID 1 does not mean it installed + * the handlers already. + */ +#if 0 + while (kill(1, 0) != 0 && --cnt >= 0) + sleep1(); +#endif + /* ... so let's wait for some evidence a usual startup event, + * mounting of /proc, happened. By that time init should be ready + * for signals. + */ + while (access("/proc/meminfo", F_OK) != 0 && --cnt >= 0) + sleep1(); + + /* Does it look like init wasn't there? */ + return (cnt != initial - 1); +} +#else + /* Assume it's always there */ +# define init_was_not_there() 0 +#endif + +int halt_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE; +int halt_main(int argc UNUSED_PARAM, char **argv) +{ + static const int magic[] = { + RB_HALT_SYSTEM, + RB_POWER_OFF, + RB_AUTOBOOT + }; + static const smallint signals[] = { SIGUSR1, SIGUSR2, SIGTERM }; + + int delay = 0; + int which, flags, rc; + + /* Figure out which applet we're running */ + if (ENABLE_HALT && !ENABLE_POWEROFF && !ENABLE_REBOOT) + which = 0; + else + if (!ENABLE_HALT && ENABLE_POWEROFF && !ENABLE_REBOOT) + which = 1; + else + if (!ENABLE_HALT && !ENABLE_POWEROFF && ENABLE_REBOOT) + which = 2; + else + for (which = 0; "hpr"[which] != applet_name[0]; which++) + continue; + + /* Parse and handle arguments */ + /* We support -w even if !ENABLE_FEATURE_WTMP, + * in order to not break scripts. + * -i (shut down network interfaces) is ignored. + */ + flags = getopt32(argv, "d:+nfwi", &delay); + + sleep(delay); + + write_wtmp(); + + if (flags & 8) /* -w */ + return EXIT_SUCCESS; + + if (!(flags & 2)) /* no -n */ + sync(); + + /* Perform action. */ + rc = 1; + if (!(flags & 4)) { /* no -f */ +//TODO: I tend to think that signalling linuxrc is wrong +// pity original author didn't comment on it... + if (ENABLE_LINUXRC) { + /* talk to linuxrc */ + /* bbox init/linuxrc assumed */ + pid_t *pidlist = find_pid_by_name("linuxrc"); + if (pidlist[0] > 0) + rc = kill(pidlist[0], signals[which]); + if (ENABLE_FEATURE_CLEAN_UP) + free(pidlist); + } + if (rc) { + /* talk to init */ + if (!ENABLE_FEATURE_CALL_TELINIT) { + /* bbox init assumed */ + rc = kill(1, signals[which]); + if (init_was_not_there()) + rc = kill(1, signals[which]); + } else { + /* SysV style init assumed */ + /* runlevels: + * 0 == shutdown + * 6 == reboot */ + execlp(CONFIG_TELINIT_PATH, + CONFIG_TELINIT_PATH, + which == 2 ? "6" : "0", + (char *)NULL + ); + bb_perror_msg_and_die("can't execute '%s'", + CONFIG_TELINIT_PATH); + } + } + } else { + rc = reboot(magic[which]); + } + + if (rc) + bb_perror_nomsg_and_die(); + return rc; +} diff --git a/pool/shard004/C/0099259_stm32f4xx_hal_msp.c b/pool/shard004/C/0099259_stm32f4xx_hal_msp.c new file mode 100644 index 0000000000000000000000000000000000000000..ac3d0bf3f5e93854f06b6b6e405ad179d0da3408 --- /dev/null +++ b/pool/shard004/C/0099259_stm32f4xx_hal_msp.c @@ -0,0 +1,463 @@ +/* USER CODE BEGIN Header */ +/** + ****************************************************************************** + * File Name : stm32f4xx_hal_msp.c + * Description : This file provides code for the MSP Initialization + * and de-Initialization codes. + ****************************************************************************** + ** This notice applies to any and all portions of this file + * that are not between comment pairs USER CODE BEGIN and + * USER CODE END. Other portions of this file, whether + * inserted by the user or by software development tools + * are owned by their respective copyright owners. + * + * COPYRIGHT(c) 2018 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. + * + ****************************************************************************** + */ +/* USER CODE END Header */ + +/* Includes ------------------------------------------------------------------*/ +#include "main.h" +/* USER CODE BEGIN Includes */ + +/* USER CODE END Includes */ + +/* Private typedef -----------------------------------------------------------*/ +/* USER CODE BEGIN TD */ + +/* USER CODE END TD */ + +/* Private define ------------------------------------------------------------*/ +/* USER CODE BEGIN Define */ + +/* USER CODE END Define */ + +/* Private macro -------------------------------------------------------------*/ +/* USER CODE BEGIN Macro */ + +/* USER CODE END Macro */ + +/* Private variables ---------------------------------------------------------*/ +/* USER CODE BEGIN PV */ + +/* USER CODE END PV */ + +/* Private function prototypes -----------------------------------------------*/ +/* USER CODE BEGIN PFP */ + +/* USER CODE END PFP */ + +/* External functions --------------------------------------------------------*/ +/* USER CODE BEGIN ExternalFunctions */ + +/* USER CODE END ExternalFunctions */ + +/* USER CODE BEGIN 0 */ + +/* USER CODE END 0 */ +/** + * Initializes the Global MSP. + */ +void HAL_MspInit(void) +{ + /* USER CODE BEGIN MspInit 0 */ + + /* USER CODE END MspInit 0 */ + + __HAL_RCC_SYSCFG_CLK_ENABLE(); + __HAL_RCC_PWR_CLK_ENABLE(); + + /* System interrupt init*/ + + /* USER CODE BEGIN MspInit 1 */ + + /* USER CODE END MspInit 1 */ +} + +/** +* @brief ADC MSP Initialization +* This function configures the hardware resources used in this example +* @param hadc: ADC handle pointer +* @retval None +*/ +void HAL_ADC_MspInit(ADC_HandleTypeDef* hadc) +{ + + GPIO_InitTypeDef GPIO_InitStruct = {0}; + if(hadc->Instance==ADC1) + { + /* USER CODE BEGIN ADC1_MspInit 0 */ + + /* USER CODE END ADC1_MspInit 0 */ + /* Peripheral clock enable */ + __HAL_RCC_ADC1_CLK_ENABLE(); + + __HAL_RCC_GPIOB_CLK_ENABLE(); + /**ADC1 GPIO Configuration + PB1 ------> ADC1_IN9 + */ + GPIO_InitStruct.Pin = GPIO_PIN_1; + GPIO_InitStruct.Mode = GPIO_MODE_ANALOG; + GPIO_InitStruct.Pull = GPIO_NOPULL; + HAL_GPIO_Init(GPIOB, &GPIO_InitStruct); + + /* USER CODE BEGIN ADC1_MspInit 1 */ + + /* USER CODE END ADC1_MspInit 1 */ + } + +} + +/** +* @brief ADC MSP De-Initialization +* This function freeze the hardware resources used in this example +* @param hadc: ADC handle pointer +* @retval None +*/ + +void HAL_ADC_MspDeInit(ADC_HandleTypeDef* hadc) +{ + + if(hadc->Instance==ADC1) + { + /* USER CODE BEGIN ADC1_MspDeInit 0 */ + + /* USER CODE END ADC1_MspDeInit 0 */ + /* Peripheral clock disable */ + __HAL_RCC_ADC1_CLK_DISABLE(); + + /**ADC1 GPIO Configuration + PB1 ------> ADC1_IN9 + */ + HAL_GPIO_DeInit(GPIOB, GPIO_PIN_1); + + /* USER CODE BEGIN ADC1_MspDeInit 1 */ + + /* USER CODE END ADC1_MspDeInit 1 */ + } + +} + +/** +* @brief I2C MSP Initialization +* This function configures the hardware resources used in this example +* @param hi2c: I2C handle pointer +* @retval None +*/ +void HAL_I2C_MspInit(I2C_HandleTypeDef* hi2c) +{ + + GPIO_InitTypeDef GPIO_InitStruct = {0}; + if(hi2c->Instance==I2C1) + { + /* USER CODE BEGIN I2C1_MspInit 0 */ + + /* USER CODE END I2C1_MspInit 0 */ + + __HAL_RCC_GPIOB_CLK_ENABLE(); + /**I2C1 GPIO Configuration + PB6 ------> I2C1_SCL + PB7 ------> I2C1_SDA + */ + GPIO_InitStruct.Pin = GPIO_PIN_6|GPIO_PIN_7; + GPIO_InitStruct.Mode = GPIO_MODE_AF_OD; + GPIO_InitStruct.Pull = GPIO_PULLUP; + GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_VERY_HIGH; + GPIO_InitStruct.Alternate = GPIO_AF4_I2C1; + HAL_GPIO_Init(GPIOB, &GPIO_InitStruct); + + /* Peripheral clock enable */ + __HAL_RCC_I2C1_CLK_ENABLE(); + /* USER CODE BEGIN I2C1_MspInit 1 */ + + /* USER CODE END I2C1_MspInit 1 */ + } + +} + +/** +* @brief I2C MSP De-Initialization +* This function freeze the hardware resources used in this example +* @param hi2c: I2C handle pointer +* @retval None +*/ + +void HAL_I2C_MspDeInit(I2C_HandleTypeDef* hi2c) +{ + + if(hi2c->Instance==I2C1) + { + /* USER CODE BEGIN I2C1_MspDeInit 0 */ + + /* USER CODE END I2C1_MspDeInit 0 */ + /* Peripheral clock disable */ + __HAL_RCC_I2C1_CLK_DISABLE(); + + /**I2C1 GPIO Configuration + PB6 ------> I2C1_SCL + PB7 ------> I2C1_SDA + */ + HAL_GPIO_DeInit(GPIOB, GPIO_PIN_6|GPIO_PIN_7); + + /* USER CODE BEGIN I2C1_MspDeInit 1 */ + + /* USER CODE END I2C1_MspDeInit 1 */ + } + +} + +/** +* @brief RTC MSP Initialization +* This function configures the hardware resources used in this example +* @param hrtc: RTC handle pointer +* @retval None +*/ +void HAL_RTC_MspInit(RTC_HandleTypeDef* hrtc) +{ + + if(hrtc->Instance==RTC) + { + /* USER CODE BEGIN RTC_MspInit 0 */ + + /* USER CODE END RTC_MspInit 0 */ + /* Peripheral clock enable */ + __HAL_RCC_RTC_ENABLE(); + /* USER CODE BEGIN RTC_MspInit 1 */ + + /* USER CODE END RTC_MspInit 1 */ + } + +} + +/** +* @brief RTC MSP De-Initialization +* This function freeze the hardware resources used in this example +* @param hrtc: RTC handle pointer +* @retval None +*/ + +void HAL_RTC_MspDeInit(RTC_HandleTypeDef* hrtc) +{ + + if(hrtc->Instance==RTC) + { + /* USER CODE BEGIN RTC_MspDeInit 0 */ + + /* USER CODE END RTC_MspDeInit 0 */ + /* Peripheral clock disable */ + __HAL_RCC_RTC_DISABLE(); + /* USER CODE BEGIN RTC_MspDeInit 1 */ + + /* USER CODE END RTC_MspDeInit 1 */ + } + +} + +/** +* @brief SPI MSP Initialization +* This function configures the hardware resources used in this example +* @param hspi: SPI handle pointer +* @retval None +*/ +void HAL_SPI_MspInit(SPI_HandleTypeDef* hspi) +{ + + GPIO_InitTypeDef GPIO_InitStruct = {0}; + if(hspi->Instance==SPI2) + { + /* USER CODE BEGIN SPI2_MspInit 0 */ + + /* USER CODE END SPI2_MspInit 0 */ + /* Peripheral clock enable */ + __HAL_RCC_SPI2_CLK_ENABLE(); + + __HAL_RCC_GPIOB_CLK_ENABLE(); + /**SPI2 GPIO Configuration + PB13 ------> SPI2_SCK + PB14 ------> SPI2_MISO + PB15 ------> SPI2_MOSI + */ + GPIO_InitStruct.Pin = GPIO_PIN_13|GPIO_PIN_14|GPIO_PIN_15; + GPIO_InitStruct.Mode = GPIO_MODE_AF_PP; + GPIO_InitStruct.Pull = GPIO_NOPULL; + GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_VERY_HIGH; + GPIO_InitStruct.Alternate = GPIO_AF5_SPI2; + HAL_GPIO_Init(GPIOB, &GPIO_InitStruct); + + /* USER CODE BEGIN SPI2_MspInit 1 */ + + /* USER CODE END SPI2_MspInit 1 */ + } + +} + +/** +* @brief SPI MSP De-Initialization +* This function freeze the hardware resources used in this example +* @param hspi: SPI handle pointer +* @retval None +*/ + +void HAL_SPI_MspDeInit(SPI_HandleTypeDef* hspi) +{ + + if(hspi->Instance==SPI2) + { + /* USER CODE BEGIN SPI2_MspDeInit 0 */ + + /* USER CODE END SPI2_MspDeInit 0 */ + /* Peripheral clock disable */ + __HAL_RCC_SPI2_CLK_DISABLE(); + + /**SPI2 GPIO Configuration + PB13 ------> SPI2_SCK + PB14 ------> SPI2_MISO + PB15 ------> SPI2_MOSI + */ + HAL_GPIO_DeInit(GPIOB, GPIO_PIN_13|GPIO_PIN_14|GPIO_PIN_15); + + /* USER CODE BEGIN SPI2_MspDeInit 1 */ + + /* USER CODE END SPI2_MspDeInit 1 */ + } + +} + +/** +* @brief UART MSP Initialization +* This function configures the hardware resources used in this example +* @param huart: UART handle pointer +* @retval None +*/ +void HAL_UART_MspInit(UART_HandleTypeDef* huart) +{ + + GPIO_InitTypeDef GPIO_InitStruct = {0}; + if(huart->Instance==USART1) + { + /* USER CODE BEGIN USART1_MspInit 0 */ + + /* USER CODE END USART1_MspInit 0 */ + /* Peripheral clock enable */ + __HAL_RCC_USART1_CLK_ENABLE(); + + __HAL_RCC_GPIOA_CLK_ENABLE(); + /**USART1 GPIO Configuration + PA9 ------> USART1_TX + PA10 ------> USART1_RX + */ + GPIO_InitStruct.Pin = GPIO_PIN_9|GPIO_PIN_10; + GPIO_InitStruct.Mode = GPIO_MODE_AF_PP; + GPIO_InitStruct.Pull = GPIO_PULLUP; + GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_VERY_HIGH; + GPIO_InitStruct.Alternate = GPIO_AF7_USART1; + HAL_GPIO_Init(GPIOA, &GPIO_InitStruct); + + /* USER CODE BEGIN USART1_MspInit 1 */ + + /* USER CODE END USART1_MspInit 1 */ + } + else if(huart->Instance==USART2) + { + /* USER CODE BEGIN USART2_MspInit 0 */ + + /* USER CODE END USART2_MspInit 0 */ + /* Peripheral clock enable */ + __HAL_RCC_USART2_CLK_ENABLE(); + + __HAL_RCC_GPIOA_CLK_ENABLE(); + /**USART2 GPIO Configuration + PA2 ------> USART2_TX + PA3 ------> USART2_RX + */ + GPIO_InitStruct.Pin = GPIO_PIN_2|GPIO_PIN_3; + GPIO_InitStruct.Mode = GPIO_MODE_AF_PP; + GPIO_InitStruct.Pull = GPIO_PULLUP; + GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_VERY_HIGH; + GPIO_InitStruct.Alternate = GPIO_AF7_USART2; + HAL_GPIO_Init(GPIOA, &GPIO_InitStruct); + + /* USER CODE BEGIN USART2_MspInit 1 */ + + /* USER CODE END USART2_MspInit 1 */ + } + +} + +/** +* @brief UART MSP De-Initialization +* This function freeze the hardware resources used in this example +* @param huart: UART handle pointer +* @retval None +*/ + +void HAL_UART_MspDeInit(UART_HandleTypeDef* huart) +{ + + if(huart->Instance==USART1) + { + /* USER CODE BEGIN USART1_MspDeInit 0 */ + + /* USER CODE END USART1_MspDeInit 0 */ + /* Peripheral clock disable */ + __HAL_RCC_USART1_CLK_DISABLE(); + + /**USART1 GPIO Configuration + PA9 ------> USART1_TX + PA10 ------> USART1_RX + */ + HAL_GPIO_DeInit(GPIOA, GPIO_PIN_9|GPIO_PIN_10); + + /* USER CODE BEGIN USART1_MspDeInit 1 */ + + /* USER CODE END USART1_MspDeInit 1 */ + } + else if(huart->Instance==USART2) + { + /* USER CODE BEGIN USART2_MspDeInit 0 */ + + /* USER CODE END USART2_MspDeInit 0 */ + /* Peripheral clock disable */ + __HAL_RCC_USART2_CLK_DISABLE(); + + /**USART2 GPIO Configuration + PA2 ------> USART2_TX + PA3 ------> USART2_RX + */ + HAL_GPIO_DeInit(GPIOA, GPIO_PIN_2|GPIO_PIN_3); + + /* USER CODE BEGIN USART2_MspDeInit 1 */ + + /* USER CODE END USART2_MspDeInit 1 */ + } + +} + +/* USER CODE BEGIN 1 */ + +/* USER CODE END 1 */ + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/pool/shard004/C/0099261_pmac_init.c b/pool/shard004/C/0099261_pmac_init.c new file mode 100644 index 0000000000000000000000000000000000000000..34a23d12ac27b392d43325c495cef72915828d04 --- /dev/null +++ b/pool/shard004/C/0099261_pmac_init.c @@ -0,0 +1,177 @@ +/* + * 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 + */ +#include "tomcrypt.h" + +/** + @file pmac_init.c + PMAC implementation, initialize state, by Tom St Denis +*/ + +#ifdef LTC_PMAC + +static const struct { + int len; + unsigned char poly_div[MAXBLOCKSIZE], + poly_mul[MAXBLOCKSIZE]; +} polys[] = { +{ + 8, + { 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0D }, + { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x1B } +}, { + 16, + { 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x43 }, + { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x87 } +} +}; + +/** + Initialize a PMAC state + @param pmac The PMAC state to initialize + @param cipher The index of the desired cipher + @param key The secret key + @param keylen The length of the secret key (octets) + @return CRYPT_OK if successful +*/ +int pmac_init(pmac_state *pmac, int cipher, const unsigned char *key, unsigned long keylen) +{ + int poly, x, y, m, err; + unsigned char *L; + + LTC_ARGCHK(pmac != NULL); + LTC_ARGCHK(key != NULL); + + /* valid cipher? */ + if ((err = cipher_is_valid(cipher)) != CRYPT_OK) { + return err; + } + + /* determine which polys to use */ + pmac->block_len = cipher_descriptor[cipher].block_length; + for (poly = 0; poly < (int)(sizeof(polys)/sizeof(polys[0])); poly++) { + if (polys[poly].len == pmac->block_len) { + break; + } + } + if (poly >= (int)(sizeof(polys)/sizeof(polys[0]))) { + return CRYPT_INVALID_ARG; + } + if (polys[poly].len != pmac->block_len) { + return CRYPT_INVALID_ARG; + } + +#ifdef LTC_FAST + if (pmac->block_len % sizeof(LTC_FAST_TYPE)) { + return CRYPT_INVALID_ARG; + } +#endif + + + /* schedule the key */ + if ((err = cipher_descriptor[cipher].setup(key, keylen, 0, &pmac->key)) != CRYPT_OK) { + return err; + } + + /* allocate L */ + L = XMALLOC(pmac->block_len); + if (L == NULL) { + return CRYPT_MEM; + } + + /* find L = E[0] */ + zeromem(L, pmac->block_len); + if ((err = cipher_descriptor[cipher].ecb_encrypt(L, L, &pmac->key)) != CRYPT_OK) { + goto error; + } + + /* find Ls[i] = L << i for i == 0..31 */ + XMEMCPY(pmac->Ls[0], L, pmac->block_len); + for (x = 1; x < 32; x++) { + m = pmac->Ls[x-1][0] >> 7; + for (y = 0; y < pmac->block_len-1; y++) { + pmac->Ls[x][y] = ((pmac->Ls[x-1][y] << 1) | (pmac->Ls[x-1][y+1] >> 7)) & 255; + } + pmac->Ls[x][pmac->block_len-1] = (pmac->Ls[x-1][pmac->block_len-1] << 1) & 255; + + if (m == 1) { + for (y = 0; y < pmac->block_len; y++) { + pmac->Ls[x][y] ^= polys[poly].poly_mul[y]; + } + } + } + + /* find Lr = L / x */ + m = L[pmac->block_len-1] & 1; + + /* shift right */ + for (x = pmac->block_len - 1; x > 0; x--) { + pmac->Lr[x] = ((L[x] >> 1) | (L[x-1] << 7)) & 255; + } + pmac->Lr[0] = L[0] >> 1; + + if (m == 1) { + for (x = 0; x < pmac->block_len; x++) { + pmac->Lr[x] ^= polys[poly].poly_div[x]; + } + } + + /* zero buffer, counters, etc... */ + pmac->block_index = 1; + pmac->cipher_idx = cipher; + pmac->buflen = 0; + zeromem(pmac->block, sizeof(pmac->block)); + zeromem(pmac->Li, sizeof(pmac->Li)); + zeromem(pmac->checksum, sizeof(pmac->checksum)); + err = CRYPT_OK; +error: +#ifdef LTC_CLEAN_STACK + zeromem(L, pmac->block_len); +#endif + + XFREE(L); + + return err; +} + +#endif + +/* $Source: /cvs/libtom/libtomcrypt/src/mac/pmac/pmac_init.c,v $ */ +/* $Revision: 1.8 $ */ +/* $Date: 2006/12/28 01:27:23 $ */ diff --git a/pool/shard004/C/0099275_xfs_xattr.c b/pool/shard004/C/0099275_xfs_xattr.c new file mode 100644 index 0000000000000000000000000000000000000000..833c415a4d1a3376e062b13c522c0760b266913b --- /dev/null +++ b/pool/shard004/C/0099275_xfs_xattr.c @@ -0,0 +1,241 @@ +/* + * Copyright (C) 2008 Christoph Hellwig. + * Portions Copyright (C) 2000-2008 Silicon Graphics, 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. + * + * 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 the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + */ + +#include "xfs.h" +#include "xfs_da_btree.h" +#include "xfs_bmap_btree.h" +#include "xfs_inode.h" +#include "xfs_attr.h" +#include "xfs_attr_leaf.h" +#include "xfs_acl.h" +#include "xfs_vnodeops.h" + +#include +#include + + +static int +xfs_xattr_get(struct dentry *dentry, const char *name, + void *value, size_t size, int xflags) +{ + struct xfs_inode *ip = XFS_I(dentry->d_inode); + int error, asize = size; + + if (strcmp(name, "") == 0) + return -EINVAL; + + /* */ + if (!size) { + xflags |= ATTR_KERNOVAL; + value = NULL; + } + + error = -xfs_attr_get(ip, (unsigned char *)name, value, &asize, xflags); + if (error) + return error; + return asize; +} + +static int +xfs_xattr_set(struct dentry *dentry, const char *name, const void *value, + size_t size, int flags, int xflags) +{ + struct xfs_inode *ip = XFS_I(dentry->d_inode); + + if (strcmp(name, "") == 0) + return -EINVAL; + + /* */ + if (flags & XATTR_CREATE) + xflags |= ATTR_CREATE; + if (flags & XATTR_REPLACE) + xflags |= ATTR_REPLACE; + + if (!value) + return -xfs_attr_remove(ip, (unsigned char *)name, xflags); + return -xfs_attr_set(ip, (unsigned char *)name, + (void *)value, size, xflags); +} + +static const struct xattr_handler xfs_xattr_user_handler = { + .prefix = XATTR_USER_PREFIX, + .flags = 0, /* */ + .get = xfs_xattr_get, + .set = xfs_xattr_set, +}; + +static const struct xattr_handler xfs_xattr_trusted_handler = { + .prefix = XATTR_TRUSTED_PREFIX, + .flags = ATTR_ROOT, + .get = xfs_xattr_get, + .set = xfs_xattr_set, +}; + +static const struct xattr_handler xfs_xattr_security_handler = { + .prefix = XATTR_SECURITY_PREFIX, + .flags = ATTR_SECURE, + .get = xfs_xattr_get, + .set = xfs_xattr_set, +}; + +const struct xattr_handler *xfs_xattr_handlers[] = { + &xfs_xattr_user_handler, + &xfs_xattr_trusted_handler, + &xfs_xattr_security_handler, +#ifdef CONFIG_XFS_POSIX_ACL + &xfs_xattr_acl_access_handler, + &xfs_xattr_acl_default_handler, +#endif + NULL +}; + +static unsigned int xfs_xattr_prefix_len(int flags) +{ + if (flags & XFS_ATTR_SECURE) + return sizeof("security"); + else if (flags & XFS_ATTR_ROOT) + return sizeof("trusted"); + else + return sizeof("user"); +} + +static const char *xfs_xattr_prefix(int flags) +{ + if (flags & XFS_ATTR_SECURE) + return xfs_xattr_security_handler.prefix; + else if (flags & XFS_ATTR_ROOT) + return xfs_xattr_trusted_handler.prefix; + else + return xfs_xattr_user_handler.prefix; +} + +static int +xfs_xattr_put_listent( + struct xfs_attr_list_context *context, + int flags, + unsigned char *name, + int namelen, + int valuelen, + unsigned char *value) +{ + unsigned int prefix_len = xfs_xattr_prefix_len(flags); + char *offset; + int arraytop; + + ASSERT(context->count >= 0); + + /* + + + */ + if ((flags & XFS_ATTR_ROOT) && !capable(CAP_SYS_ADMIN)) + return 0; + + arraytop = context->count + prefix_len + namelen + 1; + if (arraytop > context->firstu) { + context->count = -1; /* */ + return 1; + } + offset = (char *)context->alist + context->count; + strncpy(offset, xfs_xattr_prefix(flags), prefix_len); + offset += prefix_len; + strncpy(offset, (char *)name, namelen); /* */ + offset += namelen; + *offset = '\0'; + context->count += prefix_len + namelen + 1; + return 0; +} + +static int +xfs_xattr_put_listent_sizes( + struct xfs_attr_list_context *context, + int flags, + unsigned char *name, + int namelen, + int valuelen, + unsigned char *value) +{ + context->count += xfs_xattr_prefix_len(flags) + namelen + 1; + return 0; +} + +static int +list_one_attr(const char *name, const size_t len, void *data, + size_t size, ssize_t *result) +{ + char *p = data + *result; + + *result += len; + if (!size) + return 0; + if (*result > size) + return -ERANGE; + + strcpy(p, name); + return 0; +} + +ssize_t +xfs_vn_listxattr(struct dentry *dentry, char *data, size_t size) +{ + struct xfs_attr_list_context context; + struct attrlist_cursor_kern cursor = { 0 }; + struct inode *inode = dentry->d_inode; + int error; + + /* + + */ + memset(&context, 0, sizeof(context)); + context.dp = XFS_I(inode); + context.cursor = &cursor; + context.resynch = 1; + context.alist = data; + context.bufsize = size; + context.firstu = context.bufsize; + + if (size) + context.put_listent = xfs_xattr_put_listent; + else + context.put_listent = xfs_xattr_put_listent_sizes; + + xfs_attr_list_int(&context); + if (context.count < 0) + return -ERANGE; + + /* + + */ + if (posix_acl_access_exists(inode)) { + error = list_one_attr(POSIX_ACL_XATTR_ACCESS, + strlen(POSIX_ACL_XATTR_ACCESS) + 1, + data, size, &context.count); + if (error) + return error; + } + + if (posix_acl_default_exists(inode)) { + error = list_one_attr(POSIX_ACL_XATTR_DEFAULT, + strlen(POSIX_ACL_XATTR_DEFAULT) + 1, + data, size, &context.count); + if (error) + return error; + } + + return context.count; +} diff --git a/pool/shard004/C/0099279_python_utils.c b/pool/shard004/C/0099279_python_utils.c new file mode 100644 index 0000000000000000000000000000000000000000..9c83b715b95cbfed8e63387527b561f6d0213277 --- /dev/null +++ b/pool/shard004/C/0099279_python_utils.c @@ -0,0 +1,98 @@ +/* + * Copyright 2019 GoPro Inc. + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +#include + +#include + +#include "python_utils.h" + +struct ngl_node *python_get_scene(const char *modname, const char *func_name, double *duration, int *aspect) +{ + PyObject *pyscene = NULL; + PyObject *com = NULL, *load_script = NULL, *path = NULL; + PyObject *mod = NULL; + PyObject *ret_pydict = NULL; + PyObject *scene_func = NULL, *cptr = NULL, *pyduration = NULL; + struct ngl_node *scene = NULL; + + Py_Initialize(); + + const size_t len = strlen(modname); + if (len > 3 && !strcmp(modname + len - 3, ".py")) { + if (!(com = PyImport_ImportModule("pynodegl_utils.com")) || + !(load_script = PyObject_GetAttrString(com, "load_script")) || + !(path = PyUnicode_FromString(modname)) || + !(mod = PyObject_CallFunctionObjArgs(load_script, path, NULL))) + goto end; + } else { + if (!(mod = PyImport_ImportModule(modname))) + goto end; + } + + if (!(scene_func = PyObject_GetAttrString(mod, func_name)) || + !(ret_pydict = PyObject_CallFunctionObjArgs(scene_func, NULL)) || + !(pyscene = PyDict_GetItemString(ret_pydict, "scene")) || + !(cptr = PyObject_GetAttrString(pyscene, "cptr")) || + !(pyduration = PyDict_GetItemString(ret_pydict, "duration"))) { + goto end; + } + + if (duration) { + *duration = PyFloat_AsDouble(pyduration); + if (PyErr_Occurred()) + goto end; + } + + if (aspect) { + PyObject *pyaspect = PyDict_GetItemString(ret_pydict, "aspect_ratio"); + if (!pyaspect) + goto end; + PyObject *pyaspect0, *pyaspect1; + if (!(pyaspect0 = PyTuple_GetItem(pyaspect, 0)) || + !(pyaspect1 = PyTuple_GetItem(pyaspect, 1))) + goto end; + aspect[0] = PyLong_AsLong(pyaspect0); + if (PyErr_Occurred()) + goto end; + aspect[1] = PyLong_AsLong(pyaspect1); + if (PyErr_Occurred()) + goto end; + } + + scene = PyLong_AsVoidPtr(cptr); + ngl_node_ref(scene); + +end: + if (PyErr_Occurred()) + PyErr_PrintEx(0); + + Py_XDECREF(com); + Py_XDECREF(load_script); + Py_XDECREF(path); + Py_XDECREF(mod); + Py_XDECREF(scene_func); + Py_XDECREF(ret_pydict); + Py_XDECREF(cptr); + + Py_Finalize(); + return scene; +} diff --git a/pool/shard004/C/0099288_soc.c b/pool/shard004/C/0099288_soc.c new file mode 100644 index 0000000000000000000000000000000000000000..1844bf502fcff72eee7068adfceafa64faad30ba --- /dev/null +++ b/pool/shard004/C/0099288_soc.c @@ -0,0 +1,221 @@ +/* + * IBM/AMCC PPC4xx SoC setup code + * + * Copyright 2008 DENX Software Engineering, Stefan Roese + * + * L2 cache routines cloned from arch/ppc/syslib/ibm440gx_common.c which is: + * Eugene Surovegin or + * Copyright (c) 2003 - 2006 Zultys Technologies + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the + * Free Software Foundation; either version 2 of the License, or (at your + * option) any later version. + */ + +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +static u32 dcrbase_l2c; + +/* + * L2-cache + */ + +/* Issue L2C diagnostic command */ +static inline u32 l2c_diag(u32 addr) +{ + mtdcr(dcrbase_l2c + DCRN_L2C0_ADDR, addr); + mtdcr(dcrbase_l2c + DCRN_L2C0_CMD, L2C_CMD_DIAG); + while (!(mfdcr(dcrbase_l2c + DCRN_L2C0_SR) & L2C_SR_CC)) + ; + + return mfdcr(dcrbase_l2c + DCRN_L2C0_DATA); +} + +static irqreturn_t l2c_error_handler(int irq, void *dev) +{ + u32 sr = mfdcr(dcrbase_l2c + DCRN_L2C0_SR); + + if (sr & L2C_SR_CPE) { + /* Read cache trapped address */ + u32 addr = l2c_diag(0x42000000); + printk(KERN_EMERG "L2C: Cache Parity Error, addr[16:26] = 0x%08x\n", + addr); + } + if (sr & L2C_SR_TPE) { + /* Read tag trapped address */ + u32 addr = l2c_diag(0x82000000) >> 16; + printk(KERN_EMERG "L2C: Tag Parity Error, addr[16:26] = 0x%08x\n", + addr); + } + + /* Clear parity errors */ + if (sr & (L2C_SR_CPE | L2C_SR_TPE)){ + mtdcr(dcrbase_l2c + DCRN_L2C0_ADDR, 0); + mtdcr(dcrbase_l2c + DCRN_L2C0_CMD, L2C_CMD_CCP | L2C_CMD_CTE); + } else { + printk(KERN_EMERG "L2C: LRU error\n"); + } + + return IRQ_HANDLED; +} + +static int __init ppc4xx_l2c_probe(void) +{ + struct device_node *np; + u32 r; + unsigned long flags; + int irq; + const u32 *dcrreg; + u32 dcrbase_isram; + int len; + const u32 *prop; + u32 l2_size; + + np = of_find_compatible_node(NULL, NULL, "ibm,l2-cache"); + if (!np) + return 0; + + /* Get l2 cache size */ + prop = of_get_property(np, "cache-size", NULL); + if (prop == NULL) { + printk(KERN_ERR "%pOF: Can't get cache-size!\n", np); + of_node_put(np); + return -ENODEV; + } + l2_size = prop[0]; + + /* Map DCRs */ + dcrreg = of_get_property(np, "dcr-reg", &len); + if (!dcrreg || (len != 4 * sizeof(u32))) { + printk(KERN_ERR "%pOF: Can't get DCR register base !", np); + of_node_put(np); + return -ENODEV; + } + dcrbase_isram = dcrreg[0]; + dcrbase_l2c = dcrreg[2]; + + /* Get and map irq number from device tree */ + irq = irq_of_parse_and_map(np, 0); + if (!irq) { + printk(KERN_ERR "irq_of_parse_and_map failed\n"); + of_node_put(np); + return -ENODEV; + } + + /* Install error handler */ + if (request_irq(irq, l2c_error_handler, 0, "L2C", 0) < 0) { + printk(KERN_ERR "Cannot install L2C error handler" + ", cache is not enabled\n"); + of_node_put(np); + return -ENODEV; + } + + local_irq_save(flags); + asm volatile ("sync" ::: "memory"); + + /* Disable SRAM */ + mtdcr(dcrbase_isram + DCRN_SRAM0_DPC, + mfdcr(dcrbase_isram + DCRN_SRAM0_DPC) & ~SRAM_DPC_ENABLE); + mtdcr(dcrbase_isram + DCRN_SRAM0_SB0CR, + mfdcr(dcrbase_isram + DCRN_SRAM0_SB0CR) & ~SRAM_SBCR_BU_MASK); + mtdcr(dcrbase_isram + DCRN_SRAM0_SB1CR, + mfdcr(dcrbase_isram + DCRN_SRAM0_SB1CR) & ~SRAM_SBCR_BU_MASK); + mtdcr(dcrbase_isram + DCRN_SRAM0_SB2CR, + mfdcr(dcrbase_isram + DCRN_SRAM0_SB2CR) & ~SRAM_SBCR_BU_MASK); + mtdcr(dcrbase_isram + DCRN_SRAM0_SB3CR, + mfdcr(dcrbase_isram + DCRN_SRAM0_SB3CR) & ~SRAM_SBCR_BU_MASK); + + /* Enable L2_MODE without ICU/DCU */ + r = mfdcr(dcrbase_l2c + DCRN_L2C0_CFG) & + ~(L2C_CFG_ICU | L2C_CFG_DCU | L2C_CFG_SS_MASK); + r |= L2C_CFG_L2M | L2C_CFG_SS_256; + mtdcr(dcrbase_l2c + DCRN_L2C0_CFG, r); + + mtdcr(dcrbase_l2c + DCRN_L2C0_ADDR, 0); + + /* Hardware Clear Command */ + mtdcr(dcrbase_l2c + DCRN_L2C0_CMD, L2C_CMD_HCC); + while (!(mfdcr(dcrbase_l2c + DCRN_L2C0_SR) & L2C_SR_CC)) + ; + + /* Clear Cache Parity and Tag Errors */ + mtdcr(dcrbase_l2c + DCRN_L2C0_CMD, L2C_CMD_CCP | L2C_CMD_CTE); + + /* Enable 64G snoop region starting at 0 */ + r = mfdcr(dcrbase_l2c + DCRN_L2C0_SNP0) & + ~(L2C_SNP_BA_MASK | L2C_SNP_SSR_MASK); + r |= L2C_SNP_SSR_32G | L2C_SNP_ESR; + mtdcr(dcrbase_l2c + DCRN_L2C0_SNP0, r); + + r = mfdcr(dcrbase_l2c + DCRN_L2C0_SNP1) & + ~(L2C_SNP_BA_MASK | L2C_SNP_SSR_MASK); + r |= 0x80000000 | L2C_SNP_SSR_32G | L2C_SNP_ESR; + mtdcr(dcrbase_l2c + DCRN_L2C0_SNP1, r); + + asm volatile ("sync" ::: "memory"); + + /* Enable ICU/DCU ports */ + r = mfdcr(dcrbase_l2c + DCRN_L2C0_CFG); + r &= ~(L2C_CFG_DCW_MASK | L2C_CFG_PMUX_MASK | L2C_CFG_PMIM + | L2C_CFG_TPEI | L2C_CFG_CPEI | L2C_CFG_NAM | L2C_CFG_NBRM); + r |= L2C_CFG_ICU | L2C_CFG_DCU | L2C_CFG_TPC | L2C_CFG_CPC | L2C_CFG_FRAN + | L2C_CFG_CPIM | L2C_CFG_TPIM | L2C_CFG_LIM | L2C_CFG_SMCM; + + /* Check for 460EX/GT special handling */ + if (of_device_is_compatible(np, "ibm,l2-cache-460ex") || + of_device_is_compatible(np, "ibm,l2-cache-460gt")) + r |= L2C_CFG_RDBW; + + mtdcr(dcrbase_l2c + DCRN_L2C0_CFG, r); + + asm volatile ("sync; isync" ::: "memory"); + local_irq_restore(flags); + + printk(KERN_INFO "%dk L2-cache enabled\n", l2_size >> 10); + + of_node_put(np); + return 0; +} +arch_initcall(ppc4xx_l2c_probe); + +/* + * Apply a system reset. Alternatively a board specific value may be + * provided via the "reset-type" property in the cpu node. + */ +void ppc4xx_reset_system(char *cmd) +{ + struct device_node *np; + u32 reset_type = DBCR0_RST_SYSTEM; + const u32 *prop; + + np = of_get_cpu_node(0, NULL); + if (np) { + prop = of_get_property(np, "reset-type", NULL); + + /* + * Check if property exists and if it is in range: + * 1 - PPC4xx core reset + * 2 - PPC4xx chip reset + * 3 - PPC4xx system reset (default) + */ + if ((prop) && ((prop[0] >= 1) && (prop[0] <= 3))) + reset_type = prop[0] << 28; + } + + mtspr(SPRN_DBCR0, mfspr(SPRN_DBCR0) | reset_type); + + while (1) + ; /* Just in case the reset doesn't work */ +} diff --git a/pool/shard004/C/0099290_SDL_windows_main.c b/pool/shard004/C/0099290_SDL_windows_main.c new file mode 100644 index 0000000000000000000000000000000000000000..52ea60f5c1a73927d623e26848b53b6c9d626457 --- /dev/null +++ b/pool/shard004/C/0099290_SDL_windows_main.c @@ -0,0 +1,185 @@ +/* + SDL_main.c, placed in the public domain by Sam Lantinga 4/13/98 + + The WinMain function -- calls your program's main() function +*/ +#include "SDL_config.h" + +#ifdef __WIN32__ + +#include +#include + +#define WIN32_LEAN_AND_MEAN +#include + +/* Include the SDL main definition header */ +#include "SDL.h" +#include "SDL_main.h" + +#ifdef main +# undef main +#endif /* main */ + +static void +UnEscapeQuotes(char *arg) +{ + char *last = NULL; + + while (*arg) { + if (*arg == '"' && *last == '\\') { + char *c_curr = arg; + char *c_last = last; + + while (*c_curr) { + *c_last = *c_curr; + c_last = c_curr; + c_curr++; + } + *c_last = '\0'; + } + last = arg; + arg++; + } +} + +/* Parse a command line buffer into arguments */ +static int +ParseCommandLine(char *cmdline, char **argv) +{ + char *bufp; + char *lastp = NULL; + int argc, last_argc; + + argc = last_argc = 0; + for (bufp = cmdline; *bufp;) { + /* Skip leading whitespace */ + while (isspace(*bufp)) { + ++bufp; + } + /* Skip over argument */ + if (*bufp == '"') { + ++bufp; + if (*bufp) { + if (argv) { + argv[argc] = bufp; + } + ++argc; + } + /* Skip over word */ + lastp = bufp; + while (*bufp && (*bufp != '"' || *lastp == '\\')) { + lastp = bufp; + ++bufp; + } + } else { + if (*bufp) { + if (argv) { + argv[argc] = bufp; + } + ++argc; + } + /* Skip over word */ + while (*bufp && !isspace(*bufp)) { + ++bufp; + } + } + if (*bufp) { + if (argv) { + *bufp = '\0'; + } + ++bufp; + } + + /* Strip out \ from \" sequences */ + if (argv && last_argc != argc) { + UnEscapeQuotes(argv[last_argc]); + } + last_argc = argc; + } + if (argv) { + argv[argc] = NULL; + } + return (argc); +} + +/* Show an error message */ +static void +ShowError(const char *title, const char *message) +{ +/* If USE_MESSAGEBOX is defined, you need to link with user32.lib */ +#ifdef USE_MESSAGEBOX + MessageBox(NULL, message, title, MB_ICONEXCLAMATION | MB_OK); +#else + fprintf(stderr, "%s: %s\n", title, message); +#endif +} + +/* Pop up an out of memory message, returns to Windows */ +static BOOL +OutOfMemory(void) +{ + ShowError("Fatal Error", "Out of memory - aborting"); + return FALSE; +} + +#if defined(_MSC_VER) +/* The VC++ compiler needs main defined */ +#define console_main main +#endif + +/* This is where execution begins [console apps] */ +int +console_main(int argc, char *argv[]) +{ + int status; + + /* Run the application main() code */ + status = SDL_main(argc, argv); + + /* Exit cleanly, calling atexit() functions */ + exit(status); + + /* Hush little compiler, don't you cry... */ + return 0; +} + +/* This is where execution begins [windowed apps] */ +int WINAPI +WinMain(HINSTANCE hInst, HINSTANCE hPrev, LPSTR szCmdLine, int sw) +{ + char **argv; + int argc; + char *cmdline; + + /* Grab the command line */ + TCHAR *text = GetCommandLine(); +#if UNICODE + cmdline = SDL_iconv_string("UTF-8", "UCS-2-INTERNAL", (char *)(text), (SDL_wcslen(text)+1)*sizeof(WCHAR)); +#else + cmdline = SDL_strdup(text); +#endif + if (cmdline == NULL) { + return OutOfMemory(); + } + + /* Parse it into argv and argc */ + argc = ParseCommandLine(cmdline, NULL); + argv = SDL_stack_alloc(char *, argc + 1); + if (argv == NULL) { + return OutOfMemory(); + } + ParseCommandLine(cmdline, argv); + + /* Run the main program */ + console_main(argc, argv); + + SDL_free(cmdline); + + /* Hush little compiler, don't you cry... */ + return 0; +} + +#endif /* __WIN32__ */ + +/* vi: set ts=4 sw=4 expandtab: */ diff --git a/pool/shard004/C/0099299_xenon360_input.c b/pool/shard004/C/0099299_xenon360_input.c new file mode 100644 index 0000000000000000000000000000000000000000..2260e55dcdf3b31a771d86ff56c98dd3712e4767 --- /dev/null +++ b/pool/shard004/C/0099299_xenon360_input.c @@ -0,0 +1,148 @@ +/* RetroArch - A frontend for libretro. + * Copyright (C) 2010-2014 - Hans-Kristian Arntzen + * Copyright (C) 2011-2016 - 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 +#include + +#include + +#include "../input_joypad_driver.h" + +#define MAX_PADS 4 + +static uint64_t state[MAX_PADS]; + +static void xenon360_input_poll(void *data) +{ + (void)data; + for (unsigned i = 0; i < MAX_PADS; i++) + { + struct controller_data_s pad; + usb_do_poll(); + get_controller_data(&pad, i); + + uint64_t *cur_state = &state[i]; + + *cur_state |= pad.b ? RETRO_DEVICE_ID_JOYPAD_A : 0; + *cur_state |= pad.a ? RETRO_DEVICE_ID_JOYPAD_B : 0; + *cur_state |= pad.y ? RETRO_DEVICE_ID_JOYPAD_X : 0; + *cur_state |= pad.x ? RETRO_DEVICE_ID_JOYPAD_Y : 0; + *cur_state |= pad.left ? RETRO_DEVICE_ID_JOYPAD_LEFT : 0; + *cur_state |= pad.right ? RETRO_DEVICE_ID_JOYPAD_RIGHT : 0; + *cur_state |= pad.up ? RETRO_DEVICE_ID_JOYPAD_UP : 0; + *cur_state |= pad.down ? RETRO_DEVICE_ID_JOYPAD_DOWN : 0; + *cur_state |= pad.start ? RETRO_DEVICE_ID_JOYPAD_START : 0; + *cur_state |= pad.back ? RETRO_DEVICE_ID_JOYPAD_SELECT : 0; + *cur_state |= pad.lt ? RETRO_DEVICE_ID_JOYPAD_L : 0; + *cur_state |= pad.rt ? RETRO_DEVICE_ID_JOYPAD_R : 0; + } +} + +static int16_t xenon360_input_state(void *data, const struct retro_keybind **binds, + bool port, unsigned device, + unsigned idx, unsigned id) +{ + (void)data; + (void)idx; + unsigned user = port; + uint64_t button = binds[user][id].joykey; + int16_t retval = 0; + + if(user < MAX_PADS) + { + switch (device) + { + case RETRO_DEVICE_JOYPAD: + retval = (state[user] & button) ? 1 : 0; + break; + } + } + + return retval; +} + +static void xenon360_input_free_input(void *data) +{ + (void)data; +} + +static void* xenon360_input_init(void) +{ + return (void*)-1; +} + +static bool xenon360_input_key_pressed(void *data, int key) +{ + if (state & (UINT64_C(1) << key)) + return true; + + return false; +} + +static bool xenon360_input_meta_key_pressed(void *data, int key) +{ + return (state & (UINT64_C(1) << key)); +} + +static uint64_t xenon360_input_get_capabilities(void *data) +{ + uint64_t caps = 0; + + caps |= (1 << RETRO_DEVICE_JOYPAD); + + return caps; +} + +static void xenon360_input_grab_mouse(void *data, bool state) +{ + (void)data; + (void)state; +} + +static bool xenon360_input_set_rumble(void *data, unsigned port, + enum retro_rumble_effect effect, uint16_t strength) +{ + (void)data; + (void)port; + (void)effect; + (void)strength; + + return false; +} + +input_driver_t input_xenon360 = { + xenon360_input_init, + xenon360_input_poll, + xenon360_input_state, + xenon360_input_key_pressed, + xenon360_input_meta_key_pressed, + xenon360_input_free_input, + NULL, + NULL, + NULL, + xenon360_input_get_capabilities, + "xenon360", + xenon360_input_grab_mouse, + NULL, + xenon360_input_set_rumble, + NULL, + NULL, + NULL, +}; diff --git a/pool/shard004/C/0099300_unary_compliment.c b/pool/shard004/C/0099300_unary_compliment.c new file mode 100644 index 0000000000000000000000000000000000000000..268e468d6cba9404146e467615b81599db4d44f6 --- /dev/null +++ b/pool/shard004/C/0099300_unary_compliment.c @@ -0,0 +1,16 @@ +// RUN: %tool "%s" > "%t" +// RUN: %diff %CORRECT "%t" + +int foo() { + + int x; + int y; + x = 501; + y = ~x; + assert (x + y) == -1; + assert (x & y) == 0; + assert (x | y) == -1; + assert (x ^ y) == -1; + return 0; + +} \ No newline at end of file diff --git a/pool/shard004/C/0099308_burn-dbus.c b/pool/shard004/C/0099308_burn-dbus.c new file mode 100644 index 0000000000000000000000000000000000000000..d4cff1b09430ae929f0a46e7d690ad0cafb9f3a8 --- /dev/null +++ b/pool/shard004/C/0099308_burn-dbus.c @@ -0,0 +1,136 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * Librejilla-burn + * Copyright (C) Luis Medinas 2008 + * Copyright (C) Philippe Rouquier 2008 + * + * Librejilla-burn is free software; you can 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. + * + * The Librejilla-burn authors hereby grant permission for non-GPL compatible + * GStreamer plugins to be used and distributed together with GStreamer + * and Librejilla-burn. This permission is above and beyond the permissions granted + * by the GPL license by which Librejilla-burn is covered. 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. + * + * Librejilla-burn is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Library General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to: + * The Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor + * Boston, MA 02110-1301, USA. + */ + +#ifdef HAVE_CONFIG_H +# include +#endif + +#include +#include +#include "burn-dbus.h" + +#define GS_DBUS_SERVICE "org.mate.SessionManager" +#define GS_DBUS_INHIBIT_PATH "/org/mate/SessionManager" +#define GS_DBUS_INHIBIT_INTERFACE "org.mate.SessionManager" + +static GDBusConnection *conn; + +void +rejilla_uninhibit_suspend (guint cookie) +{ + GError *error = NULL; + GVariant *res; + + if (cookie < 0) { + g_warning ("Invalid cookie"); + return; + } + + conn = g_bus_get_sync (G_BUS_TYPE_SESSION, NULL, &error); + + if (conn == NULL) { + g_warning ("Couldn't get a DBUS connection: %s", + error->message); + g_error_free (error); + return; + } + + res = g_dbus_connection_call_sync (conn, + GS_DBUS_SERVICE, + GS_DBUS_INHIBIT_PATH, + GS_DBUS_INHIBIT_INTERFACE, + "Uninhibit", + g_variant_new("(u)", + cookie), + NULL, + G_DBUS_CALL_FLAGS_NONE, + -1, + NULL, + &error); + + if (res == NULL) { + g_warning ("Failed to restore the system power manager: %s", + error->message); + g_error_free (error); + } else { + g_variant_get (res, "(u)", &cookie); + g_variant_unref (res); + } + +} + +gint +rejilla_inhibit_suspend (const char *reason) +{ + guint cookie; + GError *error = NULL; + GVariant *res; + + g_return_val_if_fail (reason != NULL, -1); + + conn = g_bus_get_sync (G_BUS_TYPE_SESSION, NULL, &error); + + if (conn == NULL) { + g_warning ("Couldn't get a DBUS connection: %s", + error->message); + g_error_free (error); + return -1; + } + + res = g_dbus_connection_call_sync (conn, + GS_DBUS_SERVICE, + GS_DBUS_INHIBIT_PATH, + GS_DBUS_INHIBIT_INTERFACE, + "Inhibit", + g_variant_new("(susu)", + g_get_application_name (), + 0, + reason, + 1 | 4), + G_VARIANT_TYPE ("(u)"), + G_DBUS_CALL_FLAGS_NONE, + -1, + NULL, + &error); + + if (res == NULL) { + g_warning ("Failed to inhibit the system from suspending: %s", + error->message); + g_error_free (error); + cookie = -1; + } + else { + g_variant_get (res, "(u)", &cookie); + g_variant_unref (res); + } + + return cookie; +} diff --git a/pool/shard004/C/0099317_qemu.c b/pool/shard004/C/0099317_qemu.c new file mode 100644 index 0000000000000000000000000000000000000000..35a146c66aed2efc238a6ea0ce6257237735d162 --- /dev/null +++ b/pool/shard004/C/0099317_qemu.c @@ -0,0 +1,200 @@ +/* + * Copyright (C) 2015, Bin Meng + * + * SPDX-License-Identifier: GPL-2.0+ + */ + +#include +#include +#include +#include +#include +#include +#include +#include + +static bool i440fx; + +#ifdef CONFIG_QFW + +/* on x86, the qfw registers are all IO ports */ +#define FW_CONTROL_PORT 0x510 +#define FW_DATA_PORT 0x511 +#define FW_DMA_PORT_LOW 0x514 +#define FW_DMA_PORT_HIGH 0x518 + +static void qemu_x86_fwcfg_read_entry_pio(uint16_t entry, + uint32_t size, void *address) +{ + uint32_t i = 0; + uint8_t *data = address; + + /* + * writting FW_CFG_INVALID will cause read operation to resume at + * last offset, otherwise read will start at offset 0 + * + * Note: on platform where the control register is IO port, the + * endianness is little endian. + */ + if (entry != FW_CFG_INVALID) + outw(cpu_to_le16(entry), FW_CONTROL_PORT); + + /* the endianness of data register is string-preserving */ + while (size--) + data[i++] = inb(FW_DATA_PORT); +} + +static void qemu_x86_fwcfg_read_entry_dma(struct fw_cfg_dma_access *dma) +{ + /* the DMA address register is big endian */ + outl(cpu_to_be32((uintptr_t)dma), FW_DMA_PORT_HIGH); + + while (be32_to_cpu(dma->control) & ~FW_CFG_DMA_ERROR) + __asm__ __volatile__ ("pause"); +} + +static struct fw_cfg_arch_ops fwcfg_x86_ops = { + .arch_read_pio = qemu_x86_fwcfg_read_entry_pio, + .arch_read_dma = qemu_x86_fwcfg_read_entry_dma +}; +#endif + +static void enable_pm_piix(void) +{ + u8 en; + u16 cmd; + + /* Set the PM I/O base */ + pci_write_config32(PIIX_PM, PMBA, CONFIG_ACPI_PM1_BASE | 1); + + /* Enable access to the PM I/O space */ + pci_read_config16(PIIX_PM, PCI_COMMAND, &cmd); + cmd |= PCI_COMMAND_IO; + pci_write_config16(PIIX_PM, PCI_COMMAND, cmd); + + /* PM I/O Space Enable (PMIOSE) */ + pci_read_config8(PIIX_PM, PMREGMISC, &en); + en |= PMIOSE; + pci_write_config8(PIIX_PM, PMREGMISC, en); +} + +static void enable_pm_ich9(void) +{ + /* Set the PM I/O base */ + pci_write_config32(ICH9_PM, PMBA, CONFIG_ACPI_PM1_BASE | 1); +} + +static void qemu_chipset_init(void) +{ + u16 device, xbcs; + int pam, i; + + /* + * i440FX and Q35 chipset have different PAM register offset, but with + * the same bitfield layout. Here we determine the offset based on its + * PCI device ID. + */ + pci_read_config16(PCI_BDF(0, 0, 0), PCI_DEVICE_ID, &device); + i440fx = (device == PCI_DEVICE_ID_INTEL_82441); + pam = i440fx ? I440FX_PAM : Q35_PAM; + + /* + * Initialize Programmable Attribute Map (PAM) Registers + * + * Configure legacy segments C/D/E/F to system RAM + */ + for (i = 0; i < PAM_NUM; i++) + pci_write_config8(PCI_BDF(0, 0, 0), pam + i, PAM_RW); + + if (i440fx) { + /* + * Enable legacy IDE I/O ports decode + * + * Note: QEMU always decode legacy IDE I/O port on PIIX chipset. + * However Linux ata_piix driver does sanity check on these two + * registers to see whether legacy ports decode is turned on. + * This is to make Linux ata_piix driver happy. + */ + pci_write_config16(PIIX_IDE, IDE0_TIM, IDE_DECODE_EN); + pci_write_config16(PIIX_IDE, IDE1_TIM, IDE_DECODE_EN); + + /* Enable I/O APIC */ + pci_read_config16(PIIX_ISA, XBCS, &xbcs); + xbcs |= APIC_EN; + pci_write_config16(PIIX_ISA, XBCS, xbcs); + + enable_pm_piix(); + } else { + /* Configure PCIe ECAM base address */ + pci_write_config32(PCI_BDF(0, 0, 0), PCIEX_BAR, + CONFIG_PCIE_ECAM_BASE | BAR_EN); + + enable_pm_ich9(); + } + +#ifdef CONFIG_QFW + qemu_fwcfg_init(&fwcfg_x86_ops); +#endif +} + +#if !CONFIG_IS_ENABLED(SPL_X86_32BIT_INIT) +int arch_cpu_init(void) +{ + post_code(POST_CPU_INIT); + + return x86_cpu_init_f(); +} +#endif + +#if !CONFIG_IS_ENABLED(EFI_STUB) && \ + !CONFIG_IS_ENABLED(SPL_X86_32BIT_INIT) + +int checkcpu(void) +{ + return 0; +} + +int print_cpuinfo(void) +{ + post_code(POST_CPU_INFO); + return default_print_cpuinfo(); +} +#endif + +void reset_cpu(ulong addr) +{ + /* cold reset */ + x86_full_reset(); +} + +int arch_early_init_r(void) +{ + qemu_chipset_init(); + + return 0; +} + +#ifdef CONFIG_GENERATE_MP_TABLE +int mp_determine_pci_dstirq(int bus, int dev, int func, int pirq) +{ + u8 irq; + + if (i440fx) { + /* + * Not like most x86 platforms, the PIRQ[A-D] on PIIX3 are not + * connected to I/O APIC INTPIN#16-19. Instead they are routed + * to an irq number controled by the PIRQ routing register. + */ + pci_read_config8(PCI_BDF(bus, dev, func), + PCI_INTERRUPT_LINE, &irq); + } else { + /* + * ICH9's PIRQ[A-H] are not consecutive numbers from 0 to 7. + * PIRQ[A-D] still maps to [0-3] but PIRQ[E-H] maps to [8-11]. + */ + irq = pirq < 8 ? pirq + 16 : pirq + 12; + } + + return irq; +} +#endif diff --git a/pool/shard004/C/0099318_api.c b/pool/shard004/C/0099318_api.c new file mode 100644 index 0000000000000000000000000000000000000000..32f5de7bcc353b1f017798f6d26caca89dcd0501 --- /dev/null +++ b/pool/shard004/C/0099318_api.c @@ -0,0 +1,169 @@ +/* + * This file is part of the libsigrok project. + * + * Copyright (C) 2012 Uwe Hermann + * + * 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 "libsigrok-internal.h" +#include "protocol.h" + +#define SERIALCOMM "9600/8e1" + +static const uint32_t scanopts[] = { + SR_CONF_CONN, + SR_CONF_SERIALCOMM, +}; + +static const uint32_t devopts[] = { + SR_CONF_SOUNDLEVELMETER, + SR_CONF_CONTINUOUS, + SR_CONF_LIMIT_SAMPLES | SR_CONF_SET, + SR_CONF_LIMIT_MSEC | SR_CONF_SET, +}; + +static GSList *scan(struct sr_dev_driver *di, GSList *options) +{ + struct dev_context *devc; + struct sr_dev_inst *sdi; + struct sr_config *src; + GSList *l; + const char *conn, *serialcomm; + struct sr_serial_dev_inst *serial; + + conn = serialcomm = NULL; + for (l = options; l; l = l->next) { + if (!(src = l->data)) { + sr_err("Invalid option data, skipping."); + continue; + } + switch (src->key) { + case SR_CONF_CONN: + conn = g_variant_get_string(src->data, NULL); + break; + case SR_CONF_SERIALCOMM: + serialcomm = g_variant_get_string(src->data, NULL); + break; + default: + sr_err("Unknown option %d, skipping.", src->key); + break; + } + } + if (!conn) + return NULL; + if (!serialcomm) + serialcomm = SERIALCOMM; + + sdi = g_malloc0(sizeof(struct sr_dev_inst)); + sdi->status = SR_ST_INACTIVE; + sdi->vendor = g_strdup("Tondaj"); + sdi->model = g_strdup("SL-814"); + devc = g_malloc0(sizeof(struct dev_context)); + sr_sw_limits_init(&devc->limits); + + serial = sr_serial_dev_inst_new(conn, serialcomm); + + if (serial_open(serial, SERIAL_RDWR) != SR_OK) + return NULL; + + sdi->inst_type = SR_INST_SERIAL; + sdi->conn = serial; + + sdi->priv = devc; + sr_channel_new(sdi, 0, SR_CHANNEL_ANALOG, TRUE, "P1"); + + return std_scan_complete(di, g_slist_append(NULL, sdi)); +} + +static int config_set(uint32_t key, GVariant *data, const struct sr_dev_inst *sdi, + const struct sr_channel_group *cg) +{ + struct dev_context *devc; + + (void)cg; + + if (sdi->status != SR_ST_ACTIVE) + return SR_ERR_DEV_CLOSED; + + devc = sdi->priv; + + return sr_sw_limits_config_set(&devc->limits, key, data); +} + +static int config_list(uint32_t key, GVariant **data, const struct sr_dev_inst *sdi, + const struct sr_channel_group *cg) +{ + (void)sdi; + (void)cg; + + switch (key) { + case SR_CONF_SCAN_OPTIONS: + *data = g_variant_new_fixed_array(G_VARIANT_TYPE_UINT32, + scanopts, ARRAY_SIZE(scanopts), sizeof(uint32_t)); + break; + case SR_CONF_DEVICE_OPTIONS: + *data = g_variant_new_fixed_array(G_VARIANT_TYPE_UINT32, + devopts, ARRAY_SIZE(devopts), sizeof(uint32_t)); + break; + default: + return SR_ERR_NA; + } + + return SR_OK; +} + +static int dev_acquisition_start(const struct sr_dev_inst *sdi) +{ + struct dev_context *devc = sdi->priv; + struct sr_serial_dev_inst *serial; + + if (sdi->status != SR_ST_ACTIVE) + return SR_ERR_DEV_CLOSED; + + std_session_send_df_header(sdi); + + sr_sw_limits_acquisition_start(&devc->limits); + + /* Poll every 500ms, or whenever some data comes in. */ + serial = sdi->conn; + serial_source_add(sdi->session, serial, G_IO_IN, 500, + tondaj_sl_814_receive_data, (void *)sdi); + + return SR_OK; +} + +static struct sr_dev_driver tondaj_sl_814_driver_info = { + .name = "tondaj-sl-814", + .longname = "Tondaj SL-814", + .api_version = 1, + .init = std_init, + .cleanup = std_cleanup, + .scan = scan, + .dev_list = std_dev_list, + .dev_clear = NULL, + .config_get = NULL, + .config_set = config_set, + .config_list = config_list, + .dev_open = std_serial_dev_open, + .dev_close = std_serial_dev_close, + .dev_acquisition_start = dev_acquisition_start, + .dev_acquisition_stop = std_serial_dev_acquisition_stop, + .context = NULL, +}; +SR_REGISTER_DEV_DRIVER(tondaj_sl_814_driver_info); diff --git a/pool/shard004/C/0099334_main.c b/pool/shard004/C/0099334_main.c new file mode 100644 index 0000000000000000000000000000000000000000..c8a4516a4397f01faa388bf6d99b1c6c78f9bb04 --- /dev/null +++ b/pool/shard004/C/0099334_main.c @@ -0,0 +1,31 @@ +#include "../constants.h" + +char *r_strncpy (char *dest, const char *src, size_t n) +{ + int _i; + + /* r_strncpy RELEVANT */ + if (n > 0) dest[n-1]; + + for (_i = 0; _i < n; _i++) { + dest[_i] = src[_i]; // DO NOT CHANGE THE POSITION OF THIS LINE + if (src[_i] == EOS) + break; + } + return dest; +} + +int main () +{ + struct sockaddr_un serv_adr; + char filename [FILENAME_SZ]; + + /* server filename */ + filename[FILENAME_SZ-1] = EOS; + + /* initialize the server address structure */ + /* OK */ + r_strncpy (serv_adr.sun_path, filename, SUN_PATH_SZ-1); + + return 0; +} diff --git a/pool/shard004/C/0099346_main.c b/pool/shard004/C/0099346_main.c new file mode 100644 index 0000000000000000000000000000000000000000..77c43416174f0e61c4285105d0ecab3f0090e69a --- /dev/null +++ b/pool/shard004/C/0099346_main.c @@ -0,0 +1,172 @@ +/* + * Copyright (C) 2004 Andrew Beekhof + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This software is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ + +#include + +#include +#include +#include +#include +#include + +#include +#include +#include + +#include +#include +#include + +#include +#include +#include + +#define OPTARGS "hV" + +void usage(const char* cmd, int exit_status); +int crmd_init(void); +void crmd_hamsg_callback(const xmlNode * msg, void* private_data); +extern void init_dotfile(void); + +GMainLoop* crmd_mainloop = NULL; + +int +main(int argc, char ** argv) +{ + int flag; + int argerr = 0; + + crm_system_name = CRM_SYSTEM_CRMD; + + while ((flag = getopt(argc, argv, OPTARGS)) != EOF) { + switch(flag) { + case 'V': + cl_log_enable_stderr(1); + alter_debug(DEBUG_INC); + break; + case 'h': /* Help message */ + usage(crm_system_name, LSB_EXIT_OK); + break; + default: + ++argerr; + break; + } + } + + if(argc - optind == 1 && safe_str_eq("metadata", argv[optind])) { + crmd_metadata(); + return 0; + } else if(argc - optind == 1 && safe_str_eq("version", argv[optind])) { + fprintf(stderr, "CRM Version: "); + fprintf(stdout, "%s (%s)\n", VERSION, BUILD_VERSION); + return 0; + } + + crm_log_init(CRM_SYSTEM_CRMD, LOG_INFO, TRUE, FALSE, argc, argv); + + crm_info("CRM Git Version: %s\n", BUILD_VERSION); + + if (optind > argc) { + ++argerr; + } + + if (argerr) { + usage(crm_system_name, LSB_EXIT_GENERIC); + } + + if(crm_is_writable(PE_STATE_DIR, NULL, CRM_DAEMON_USER, CRM_DAEMON_GROUP, FALSE) == FALSE) { + crm_err("Bad permissions on "PE_STATE_DIR". Terminating"); + fprintf(stderr,"ERROR: Bad permissions on "PE_STATE_DIR". See logs for details\n"); + fflush(stderr); + return 100; + + } else if(crm_is_writable(CRM_CONFIG_DIR, NULL, CRM_DAEMON_USER, CRM_DAEMON_GROUP, FALSE) == FALSE) { + crm_err("Bad permissions on "CRM_CONFIG_DIR". Terminating"); + fprintf(stderr,"ERROR: Bad permissions on "CRM_CONFIG_DIR". See logs for details\n"); + fflush(stderr); + return 100; + } + + return crmd_init(); +} + + +int +crmd_init(void) +{ + int exit_code = 0; + enum crmd_fsa_state state; + + fsa_state = S_STARTING; + fsa_input_register = 0; /* zero out the regester */ + + init_dotfile(); + crm_info("Starting %s", crm_system_name); + register_fsa_input(C_STARTUP, I_STARTUP, NULL); + + crm_peer_init(); + state = s_crmd_fsa(C_STARTUP); + + if (state == S_PENDING || state == S_STARTING) { + /* Create the mainloop and run it... */ + crmd_mainloop = g_main_new(FALSE); + crm_info("Starting %s's mainloop", crm_system_name); + +#ifdef REALTIME_SUPPORT + static int crm_realtime = 1; + if (crm_realtime == 1){ + cl_enable_realtime(); + }else if (crm_realtime == 0){ + cl_disable_realtime(); + } + cl_make_realtime(SCHED_RR, 5, 64, 64); +#endif + g_main_run(crmd_mainloop); + if(is_set(fsa_input_register, R_STAYDOWN)) { + crm_info("Inhibiting respawn by Heartbeat"); + exit_code = 100; + } + + } else { + crm_err("Startup of %s failed. Current state: %s", + crm_system_name, fsa_state2string(state)); + exit_code = 1; + } + + crm_info("[%s] stopped (%d)", crm_system_name, exit_code); + return exit_code; +} + + + +void +usage(const char* cmd, int exit_status) +{ + FILE* stream; + + stream = exit_status ? stderr : stdout; + + fprintf(stream, "usage: %s [-V] [-h|version|metadata]\n", cmd); + fprintf(stream, "\t-h\t: this help message\n"); + fprintf(stream, "\t-V\t: increase verbosity\n"); + fprintf(stream, "\tmetadata\t: show configurable crmd options\n"); + fprintf(stream, "\tversion\t\t: show version information and quit\n"); + fflush(stream); + + exit(exit_status); +} diff --git a/pool/shard004/C/0099352_pipes.c b/pool/shard004/C/0099352_pipes.c new file mode 100644 index 0000000000000000000000000000000000000000..11fb37f62924251741d94628a15bb65bc23fe6e4 --- /dev/null +++ b/pool/shard004/C/0099352_pipes.c @@ -0,0 +1,70 @@ +#include +#include +#include +#include +#include +#include + +struct person { + size_t age; + size_t foo; +}; + +int main(void) { + int pfds[2]; + int rpfds[2]; + pid_t pid; + + if (pipe(pfds) == -1) { + perror("pipe"); + return 1; + } + + if (pipe(rpfds) == -1) { + perror("reverse pipe"); + return 1; + } + + if ((pid = fork()) == -1) { + perror("fork"); + return 1; + } else if (pid == 0) { + printf("I am the child\n"); + close(pfds[1]); + char buf[5]; + read(pfds[0], buf, 5); + printf("Child: I finished reading from the pipe: %s\n", buf); + struct person person; + read(pfds[0], &person, sizeof(struct person)); + printf("Child: I finished reading a person from the pipe!\n"); + printf(" Age = %zu, Foo = %zu\n", person.age, person.foo); + close(pfds[0]); + + close(rpfds[0]); + person.age = 12; + person.foo = 50; + printf("Child: Sending back another person over the reverse pipe!\n"); + printf(" Age = %zu, Foo = %zu\n", person.age, person.foo); + write(rpfds[1], &person, sizeof(struct person)); + printf("Child: I sent a person over the pipe.\n"); + close(rpfds[1]); + } else { + printf("I am the parent, child pid = %d\n", pid); + close(pfds[0]); + write(pfds[1], "Test", 5); + printf("Parent: I finished writing to the pipe, going to sleep.\n"); + sleep(3); + struct person person = { 25, 30 }; + write(pfds[1], &person, sizeof(struct person)); + printf("Parent: I sent a person over the pipe.\n"); + close(pfds[1]); + + close(rpfds[1]); + read(rpfds[0], &person, sizeof(struct person)); + printf("Parent: I finished reading a person from the pipe!\n"); + printf(" Age = %zu, Foo = %zu\n", person.age, person.foo); + close(rpfds[0]); + } + + return 0; +} diff --git a/pool/shard004/C/0099354_devicetree.c b/pool/shard004/C/0099354_devicetree.c new file mode 100644 index 0000000000000000000000000000000000000000..340fb4e6c600393f0504e6d6cd5f7adc9cbad29e --- /dev/null +++ b/pool/shard004/C/0099354_devicetree.c @@ -0,0 +1,254 @@ +/* + * Device tree integration for the pin control subsystem + * + * 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 "core.h" +#include "devicetree.h" + +/** + * struct pinctrl_dt_map - mapping table chunk parsed from device tree + * @node: list node for struct pinctrl's @dt_maps field + * @pctldev: the pin controller that allocated this struct, and will free it + * @maps: the mapping table entries + */ +struct pinctrl_dt_map { + struct list_head node; + struct pinctrl_dev *pctldev; + struct pinctrl_map *map; + unsigned num_maps; +}; + +static void dt_free_map(struct pinctrl_dev *pctldev, + struct pinctrl_map *map, unsigned num_maps) +{ + if (pctldev) { + const struct pinctrl_ops *ops = pctldev->desc->pctlops; + ops->dt_free_map(pctldev, map, num_maps); + } else { + /* There is no pctldev for PIN_MAP_TYPE_DUMMY_STATE */ + kfree(map); + } +} + +void pinctrl_dt_free_maps(struct pinctrl *p) +{ + struct pinctrl_dt_map *dt_map, *n1; + + list_for_each_entry_safe(dt_map, n1, &p->dt_maps, node) { + pinctrl_unregister_map(dt_map->map); + list_del(&dt_map->node); + dt_free_map(dt_map->pctldev, dt_map->map, + dt_map->num_maps); + kfree(dt_map); + } + + of_node_put(p->dev->of_node); +} + +static int dt_remember_or_free_map(struct pinctrl *p, const char *statename, + struct pinctrl_dev *pctldev, + struct pinctrl_map *map, unsigned num_maps) +{ + int i; + struct pinctrl_dt_map *dt_map; + + /* Initialize common mapping table entry fields */ + for (i = 0; i < num_maps; i++) { + map[i].dev_name = dev_name(p->dev); + map[i].name = statename; + if (pctldev) + map[i].ctrl_dev_name = dev_name(pctldev->dev); + } + + /* Remember the converted mapping table entries */ + dt_map = kzalloc(sizeof(*dt_map), GFP_KERNEL); + if (!dt_map) { + dev_err(p->dev, "failed to alloc struct pinctrl_dt_map\n"); + dt_free_map(pctldev, map, num_maps); + return -ENOMEM; + } + + dt_map->pctldev = pctldev; + dt_map->map = map; + dt_map->num_maps = num_maps; + list_add_tail(&dt_map->node, &p->dt_maps); + + return pinctrl_register_map(map, num_maps, false, true); +} + +struct pinctrl_dev *of_pinctrl_get(struct device_node *np) +{ + struct pinctrl_dev *pctldev; + + pctldev = get_pinctrl_dev_from_of_node(np); + if (!pctldev) + return NULL; + + return pctldev; +} + +static int dt_to_map_one_config(struct pinctrl *p, const char *statename, + struct device_node *np_config) +{ + struct device_node *np_pctldev; + struct pinctrl_dev *pctldev; + const struct pinctrl_ops *ops; + int ret; + struct pinctrl_map *map; + unsigned num_maps; + + /* Find the pin controller containing np_config */ + np_pctldev = of_node_get(np_config); + for (;;) { + np_pctldev = of_get_next_parent(np_pctldev); + if (!np_pctldev || of_node_is_root(np_pctldev)) { + dev_info(p->dev, "could not find pctldev for node %s, deferring probe\n", + np_config->full_name); + of_node_put(np_pctldev); + /* OK let's just assume this will appear later then */ + return -EPROBE_DEFER; + } + pctldev = get_pinctrl_dev_from_of_node(np_pctldev); + if (pctldev) + break; + /* Do not defer probing of hogs (circular loop) */ + if (np_pctldev == p->dev->of_node) { + of_node_put(np_pctldev); + return -ENODEV; + } + } + of_node_put(np_pctldev); + + /* + * Call pinctrl driver to parse device tree node, and + * generate mapping table entries + */ + ops = pctldev->desc->pctlops; + if (!ops->dt_node_to_map) { + dev_err(p->dev, "pctldev %s doesn't support DT\n", + dev_name(pctldev->dev)); + return -ENODEV; + } + ret = ops->dt_node_to_map(pctldev, np_config, &map, &num_maps); + if (ret < 0) + return ret; + + /* Stash the mapping table chunk away for later use */ + return dt_remember_or_free_map(p, statename, pctldev, map, num_maps); +} + +static int dt_remember_dummy_state(struct pinctrl *p, const char *statename) +{ + struct pinctrl_map *map; + + map = kzalloc(sizeof(*map), GFP_KERNEL); + if (!map) { + dev_err(p->dev, "failed to alloc struct pinctrl_map\n"); + return -ENOMEM; + } + + /* There is no pctldev for PIN_MAP_TYPE_DUMMY_STATE */ + map->type = PIN_MAP_TYPE_DUMMY_STATE; + + return dt_remember_or_free_map(p, statename, NULL, map, 1); +} + +int pinctrl_dt_to_map(struct pinctrl *p) +{ + struct device_node *np = p->dev->of_node; + int state, ret; + char *propname; + struct property *prop; + const char *statename; + const __be32 *list; + int size, config; + phandle phandle; + struct device_node *np_config; + + /* CONFIG_OF enabled, p->dev not instantiated from DT */ + if (!np) { + dev_dbg(p->dev, "no of_node; not parsing pinctrl DT\n"); + return 0; + } + + /* We may store pointers to property names within the node */ + of_node_get(np); + + /* For each defined state ID */ + for (state = 0; ; state++) { + /* Retrieve the pinctrl-* property */ + propname = kasprintf(GFP_KERNEL, "pinctrl-%d", state); + prop = of_find_property(np, propname, &size); + kfree(propname); + if (!prop) + break; + list = prop->value; + size /= sizeof(*list); + + /* Determine whether pinctrl-names property names the state */ + ret = of_property_read_string_index(np, "pinctrl-names", + state, &statename); + /* + * If not, statename is just the integer state ID. But rather + * than dynamically allocate it and have to free it later, + * just point part way into the property name for the string. + */ + if (ret < 0) { + /* strlen("pinctrl-") == 8 */ + statename = prop->name + 8; + } + + /* For every referenced pin configuration node in it */ + for (config = 0; config < size; config++) { + phandle = be32_to_cpup(list++); + + /* Look up the pin configuration node */ + np_config = of_find_node_by_phandle(phandle); + if (!np_config) { + dev_err(p->dev, + "prop %s index %i invalid phandle\n", + prop->name, config); + ret = -EINVAL; + goto err; + } + + /* Parse the node */ + ret = dt_to_map_one_config(p, statename, np_config); + of_node_put(np_config); + if (ret < 0) + goto err; + } + + /* No entries in DT? Generate a dummy state table entry */ + if (!size) { + ret = dt_remember_dummy_state(p, statename); + if (ret < 0) + goto err; + } + } + + return 0; + +err: + pinctrl_dt_free_maps(p); + return ret; +} diff --git a/pool/shard004/C/0099360_test-ptrace01.c b/pool/shard004/C/0099360_test-ptrace01.c new file mode 100644 index 0000000000000000000000000000000000000000..6fe711387adddc556110d210a6741f11e28c0853 --- /dev/null +++ b/pool/shard004/C/0099360_test-ptrace01.c @@ -0,0 +1,45 @@ +#include /* fork(2), */ +#include /* perror(3), fprintf(3), */ +#include /* exit(3), */ +#include /* ptrace(2), */ +#include /* waitpid(2), */ +#include /* waitpid(2), */ + +int main(void) +{ + int child_status, status; + pid_t pid; + + pid = fork(); + switch (pid) { + case -1: + perror("fork()"); + exit(EXIT_FAILURE); + + case 0: /* child */ + status = ptrace(PTRACE_TRACEME, 0, NULL, NULL); + if (status < 0) { + perror("ptrace(TRACEME)"); + exit(EXIT_FAILURE); + } + + exit(EXIT_SUCCESS); + + default: /* parent */ + status = waitpid(pid, &child_status, 0); + if (status < 0) { + perror("waitpid()"); + exit(EXIT_FAILURE); + } + + if (!WIFEXITED(child_status) || WEXITSTATUS(child_status) != 0) { + perror("unexpected child status\n"); + exit(EXIT_FAILURE); + } + + exit(EXIT_SUCCESS); + } + + /* Unreachable. */ + exit(EXIT_FAILURE); +} diff --git a/pool/shard004/C/0099363_sonar.c b/pool/shard004/C/0099363_sonar.c new file mode 100644 index 0000000000000000000000000000000000000000..8921ff2068a5447ac596ea85fbb3a73d7e5d3539 --- /dev/null +++ b/pool/shard004/C/0099363_sonar.c @@ -0,0 +1,145 @@ +/* + * 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 . + */ + +#include +#include + +#include "platform.h" +#include "build_config.h" + +#include "common/maths.h" +#include "common/axis.h" + +#include "drivers/sonar_hcsr04.h" +#include "drivers/gpio.h" +#include "config/runtime_config.h" +#include "config/config.h" + +#include "sensors/sensors.h" +#include "sensors/sonar.h" + +// in cm , -1 indicate sonar is not in range - inclination adjusted by imu + +#ifdef SONAR + +static int32_t calculatedAltitude; + +const sonarHardware_t *sonarGetHardwareConfiguration(batteryConfig_t *batteryConfig) +{ +#if defined(NAZE) || defined(EUSTM32F103RC) || defined(PORT103R) + static const sonarHardware_t sonarPWM56 = { + .trigger_pin = Pin_8, // PWM5 (PB8) - 5v tolerant + .echo_pin = Pin_9, // PWM6 (PB9) - 5v tolerant + .exti_line = EXTI_Line9, + .exti_pin_source = GPIO_PinSource9, + .exti_irqn = EXTI9_5_IRQn + }; + static const sonarHardware_t sonarRC78 = { + .trigger_pin = Pin_0, // RX7 (PB0) - only 3.3v ( add a 1K Ohms resistor ) + .echo_pin = Pin_1, // RX8 (PB1) - only 3.3v ( add a 1K Ohms resistor ) + .exti_line = EXTI_Line1, + .exti_pin_source = GPIO_PinSource1, + .exti_irqn = EXTI1_IRQn + }; + // If we are using parallel PWM for our receiver or ADC current sensor, then use motor pins 5 and 6 for sonar, otherwise use rc pins 7 and 8 + if (feature(FEATURE_RX_PARALLEL_PWM ) || (feature(FEATURE_CURRENT_METER) && batteryConfig->currentMeterType == CURRENT_SENSOR_ADC) ) { + return &sonarPWM56; + } else { + return &sonarRC78; + } +#elif defined(OLIMEXINO) + UNUSED(batteryConfig); + static const sonarHardware_t const sonarHardware = { + .trigger_pin = Pin_0, // RX7 (PB0) - only 3.3v ( add a 1K Ohms resistor ) + .echo_pin = Pin_1, // RX8 (PB1) - only 3.3v ( add a 1K Ohms resistor ) + .exti_line = EXTI_Line1, + .exti_pin_source = GPIO_PinSource1, + .exti_irqn = EXTI1_IRQn + }; + return &sonarHardware; +#elif defined(CC3D) + UNUSED(batteryConfig); + static const sonarHardware_t const sonarHardware = { + .trigger_pin = Pin_5, // (PB5) + .echo_pin = Pin_0, // (PB0) - only 3.3v ( add a 1K Ohms resistor ) + .exti_line = EXTI_Line0, + .exti_pin_source = GPIO_PinSource0, + .exti_irqn = EXTI0_IRQn + }; + return &sonarHardware; +#elif defined(SPRACINGF3) + UNUSED(batteryConfig); + static const sonarHardware_t const sonarHardware = { + .trigger_pin = Pin_0, // RC_CH7 (PB0) - only 3.3v ( add a 1K Ohms resistor ) + .echo_pin = Pin_1, // RC_CH8 (PB1) - only 3.3v ( add a 1K Ohms resistor ) + .exti_line = EXTI_Line1, + .exti_pin_source = EXTI_PinSource1, + .exti_irqn = EXTI1_IRQn + }; + return &sonarHardware; +#else +#error Sonar not defined for target +#endif +} + +void sonarInit(const sonarHardware_t *sonarHardware) +{ + hcsr04_init(sonarHardware); + sensorsSet(SENSOR_SONAR); + calculatedAltitude = -1; +} + +void sonarUpdate(void) +{ + hcsr04_start_reading(); +} + +/** + * Get the last distance measured by the sonar in centimeters. When the ground is too far away, -1 is returned instead. + */ +int32_t sonarRead(void) +{ + return hcsr04_get_distance(); +} + +/** + * Apply tilt correction to the given raw sonar reading in order to compensate for the tilt of the craft when estimating + * the altitude. Returns the computed altitude in centimeters. + * + * When the ground is too far away or the tilt is too strong, -1 is returned instead. + */ +int32_t sonarCalculateAltitude(int32_t sonarAlt, int16_t tiltAngle) +{ + // calculate sonar altitude only if the sonar is facing downwards(<25deg) + if (tiltAngle > 250) + calculatedAltitude = -1; + else + calculatedAltitude = sonarAlt * (900.0f - tiltAngle) / 900.0f; + + return calculatedAltitude; +} + +/** + * Get the latest altitude that was computed by a call to sonarCalculateAltitude(), or -1 if sonarCalculateAltitude + * has never been called. + */ +int32_t sonarGetLatestAltitude(void) +{ + return calculatedAltitude; +} + +#endif diff --git a/pool/shard004/C/0099365_biosprin.c b/pool/shard004/C/0099365_biosprin.c new file mode 100644 index 0000000000000000000000000000000000000000..3e5c84450428b27873e882b7d05022dd6d81e962 --- /dev/null +++ b/pool/shard004/C/0099365_biosprin.c @@ -0,0 +1,16 @@ +/* Copyright (C) 1995 DJ Delorie, see COPYING.DJ for details */ +#define JICAMA +#include +#include +#include + +int +biosprint(int cmd, int byte, int port) +{ + vm86regs_t r; + r.h.ah = cmd; + r.h.al = byte; + r.x.dx = port; + realint(0x17, &r); + return r.h.ah; +} diff --git a/pool/shard004/C/0099366_dns-canon.c b/pool/shard004/C/0099366_dns-canon.c new file mode 100644 index 0000000000000000000000000000000000000000..4276eb65424da5fe1752faa77098bdd20c467f6c --- /dev/null +++ b/pool/shard004/C/0099366_dns-canon.c @@ -0,0 +1,173 @@ +/* Copyright (C) 2004-2017 Free Software Foundation, Inc. + This file is part of the GNU C Library. + Contributed 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 + + +#if PACKETSZ > 65536 +# define MAXPACKET PACKETSZ +#else +# define MAXPACKET 65536 +#endif + + +/* We need this time later. */ +typedef union querybuf +{ + HEADER hdr; + unsigned char buf[MAXPACKET]; +} querybuf; + + +static const short int qtypes[] = { ns_t_a, ns_t_aaaa }; +#define nqtypes (sizeof (qtypes) / sizeof (qtypes[0])) + + +enum nss_status +_nss_dns_getcanonname_r (const char *name, char *buffer, size_t buflen, + char **result,int *errnop, int *h_errnop) +{ + /* Just an alibi buffer, res_nquery will allocate a real buffer for + us. */ + unsigned char buf[20]; + union + { + querybuf *buf; + unsigned char *ptr; + } ansp = { .ptr = buf }; + enum nss_status status = NSS_STATUS_UNAVAIL; + + for (int i = 0; i < nqtypes; ++i) + { + int r = __libc_res_nquery (&_res, name, ns_c_in, qtypes[i], + buf, sizeof (buf), &ansp.ptr, NULL, NULL, + NULL, NULL); + if (r > 0) + { + /* We need to decode the response. Just one question record. + And if we got no answers we bail out, too. */ + if (ansp.buf->hdr.qdcount != htons (1)) + continue; + + /* Number of answers. */ + unsigned int ancount = ntohs (ansp.buf->hdr.ancount); + + /* Beginning and end of the buffer with query, answer, and the + rest. */ + unsigned char *ptr = &ansp.buf->buf[sizeof (HEADER)]; + unsigned char *endptr = ansp.ptr + r; + + /* Skip over the query. This is the name, type, and class. */ + int s = __dn_skipname (ptr, endptr); + if (s < 0) + { + unavail: + status = NSS_STATUS_UNAVAIL; + break; + } + + /* Skip over the name and the two 16-bit values containing type + and class. */ + ptr += s + 2 * sizeof (uint16_t); + + while (ancount-- > 0) + { + /* Now the reply. First again the name from the query, + then type, class, TTL, and the length of the RDATA. + We remember the name start. */ + unsigned char *namestart = ptr; + s = __dn_skipname (ptr, endptr); + if (s < 0) + goto unavail; + + ptr += s; + + /* Check that there are enough bytes for the RR + metadata. */ + if (endptr - ptr < 10) + goto unavail; + + /* Check whether type and class match. */ + uint_fast16_t type; + NS_GET16 (type, ptr); + if (type == qtypes[i]) + { + /* We found the record. */ + s = __dn_expand (ansp.buf->buf, endptr, namestart, + buffer, buflen); + if (s < 0) + { + if (errno != EMSGSIZE) + goto unavail; + + /* The buffer is too small. */ + *errnop = ERANGE; + status = NSS_STATUS_TRYAGAIN; + h_errno = NETDB_INTERNAL; + } + else + { + /* Success. */ + *result = buffer; + status = NSS_STATUS_SUCCESS; + } + + goto out; + } + + if (type != ns_t_cname) + goto unavail; + + if (__ns_get16 (ptr) != ns_c_in) + goto unavail; + + /* Also skip over class and TTL. */ + ptr += sizeof (uint16_t) + sizeof (uint32_t); + + /* Skip over RDATA length and RDATA itself. */ + uint16_t rdatalen = __ns_get16 (ptr); + ptr += sizeof (uint16_t); + /* Not enough room for RDATA. */ + if (endptr - ptr < rdatalen) + goto unavail; + ptr += rdatalen; + } + } + + /* Restore original buffer before retry. */ + if (ansp.ptr != buf) + { + free (ansp.ptr); + ansp.ptr = buf; + } + } + + out: + *h_errnop = h_errno; + + if (ansp.ptr != buf) + free (ansp.ptr); + + return status; +} diff --git a/pool/shard004/C/0099378_cli.c b/pool/shard004/C/0099378_cli.c new file mode 100644 index 0000000000000000000000000000000000000000..488d641cfcfef49751dd94c2481d3617d5eb6cfb --- /dev/null +++ b/pool/shard004/C/0099378_cli.c @@ -0,0 +1,246 @@ +/* + * Command line interface for libnvram + * + * Copyright 2009, Jo-Philipp Wich + * + * 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 libnvram code is based on Broadcom code for Linux 2.4.x . + * + */ + +#include "nvram.h" + + +static nvram_handle_t * nvram_open_rdonly(void) +{ + const char *file = nvram_find_staging(); + + if( file == NULL ) + file = nvram_find_mtd(); + + if( file != NULL ) + return nvram_open(file, NVRAM_RO); + + return NULL; +} + +static nvram_handle_t * nvram_open_staging(void) +{ + if( nvram_find_staging() != NULL || nvram_to_staging() == 0 ) + return nvram_open(NVRAM_STAGING, NVRAM_RW); + + return NULL; +} + +static int do_show(nvram_handle_t *nvram) +{ + nvram_tuple_t *t; + int stat = 1; + + if( (t = nvram_getall(nvram)) != NULL ) + { + while( t ) + { + printf("%s=%s\n", t->name, t->value); + t = t->next; + } + + stat = 0; + } + + return stat; +} + +static int do_get(nvram_handle_t *nvram, const char *var) +{ + const char *val; + int stat = 1; + + if( (val = nvram_get(nvram, var)) != NULL ) + { + printf("%s\n", val); + stat = 0; + } + + return stat; +} + +static int do_unset(nvram_handle_t *nvram, const char *var) +{ + return nvram_unset(nvram, var); +} + +static int do_set(nvram_handle_t *nvram, const char *pair) +{ + char *val = strstr(pair, "="); + char var[strlen(pair)]; + int stat = 1; + + if( val != NULL ) + { + memset(var, 0, sizeof(var)); + strncpy(var, pair, (int)(val-pair)); + stat = nvram_set(nvram, var, (char *)(val + 1)); + } + + return stat; +} + +static int do_info(nvram_handle_t *nvram) +{ + nvram_header_t *hdr = nvram_header(nvram); + + /* CRC8 over the last 11 bytes of the header and data bytes */ + uint8_t crc = hndcrc8((unsigned char *) &hdr[0] + NVRAM_CRC_START_POSITION, + hdr->len - NVRAM_CRC_START_POSITION, 0xff); + + /* Show info */ + printf("Magic: 0x%08X\n", hdr->magic); + printf("Length: 0x%08X\n", hdr->len); + printf("Offset: 0x%08X\n", nvram->offset); + + printf("CRC8: 0x%02X (calculated: 0x%02X)\n", + hdr->crc_ver_init & 0xFF, crc); + + printf("Version: 0x%02X\n", (hdr->crc_ver_init >> 8) & 0xFF); + printf("SDRAM init: 0x%04X\n", (hdr->crc_ver_init >> 16) & 0xFFFF); + printf("SDRAM config: 0x%04X\n", hdr->config_refresh & 0xFFFF); + printf("SDRAM refresh: 0x%04X\n", (hdr->config_refresh >> 16) & 0xFFFF); + printf("NCDL values: 0x%08X\n\n", hdr->config_ncdl); + + printf("%i bytes used / %i bytes available (%.2f%%)\n", + hdr->len, nvram->length - nvram->offset - hdr->len, + (100.00 / (double)(nvram->length - nvram->offset)) * (double)hdr->len); + + return 0; +} + + +int main( int argc, const char *argv[] ) +{ + nvram_handle_t *nvram; + int commit = 0; + int write = 0; + int stat = 1; + int done = 0; + int i; + + /* Ugly... iterate over arguments to see whether we can expect a write */ + for( i = 1; i < argc; i++ ) + if( ( !strcmp(argv[i], "set") && ++i < argc ) || + ( !strcmp(argv[i], "unset") && ++i < argc ) || + !strcmp(argv[i], "commit") ) + { + write = 1; + break; + } + + + nvram = write ? nvram_open_staging() : nvram_open_rdonly(); + + if( nvram != NULL && argc > 1 ) + { + for( i = 1; i < argc; i++ ) + { + if( !strcmp(argv[i], "show") ) + { + stat = do_show(nvram); + done++; + } + else if( !strcmp(argv[i], "info") ) + { + stat = do_info(nvram); + done++; + } + else if( !strcmp(argv[i], "get") || !strcmp(argv[i], "unset") || !strcmp(argv[i], "set") ) + { + if( (i+1) < argc ) + { + switch(argv[i++][0]) + { + case 'g': + stat = do_get(nvram, argv[i]); + break; + + case 'u': + stat = do_unset(nvram, argv[i]); + break; + + case 's': + stat = do_set(nvram, argv[i]); + break; + } + done++; + } + else + { + fprintf(stderr, "Command '%s' requires an argument!\n", argv[i]); + done = 0; + break; + } + } + else if( !strcmp(argv[i], "commit") ) + { + commit = 1; + done++; + } + else + { + fprintf(stderr, "Unknown option '%s' !\n", argv[i]); + done = 0; + break; + } + } + + if( write ) + stat = nvram_commit(nvram); + + nvram_close(nvram); + + if( commit ) + stat = staging_to_nvram(); + } + + if( !nvram ) + { + fprintf(stderr, + "Could not open nvram! Possible reasons are:\n" + " - No device found (/proc not mounted or no nvram present)\n" + " - Insufficient permissions to open mtd device\n" + " - Insufficient memory to complete operation\n" + " - Memory mapping failed or not supported\n" + ); + + stat = 1; + } + else if( !done ) + { + fprintf(stderr, + "Usage:\n" + " nvram show\n" + " nvram info\n" + " nvram get variable\n" + " nvram set variable=value [set ...]\n" + " nvram unset variable [unset ...]\n" + " nvram commit\n" + ); + + stat = 1; + } + + return stat; +} diff --git a/pool/shard004/C/0099379_unshare02.c b/pool/shard004/C/0099379_unshare02.c new file mode 100644 index 0000000000000000000000000000000000000000..47e0d1d5f0982c4ca4eac0667f99d74478915fde --- /dev/null +++ b/pool/shard004/C/0099379_unshare02.c @@ -0,0 +1,225 @@ +/******************************************************************************/ +/* Copyright (c) Crackerjack Project., 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ +/* */ +/******************************************************************************/ +/******************************************************************************/ +/* */ +/* File: unshare02.c */ +/* */ +/* Description: This tests the unshare error() syscall */ +/* */ +/* Usage: */ +/* unshare02 [-c n] [-e][-i n] [-I x] [-p x] [-t] */ +/* where, -c n : Run n copies concurrently. */ +/* -e : Turn on errno logging. */ +/* -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. */ +/* */ +/* Total Tests: 2 */ +/* */ +/* Test Name: unshare02 */ +/* History: Porting from Crackerjack to LTP is done by */ +/* Manas Kumar Nayak maknayak@in.ibm.com> */ +/******************************************************************************/ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "test.h" +#include "usctest.h" +#include "config.h" + +char *TCID = "unshare02"; +int testno; +int TST_TOTAL = 2; + +#ifdef HAVE_UNSHARE + +/* Extern Global Functions */ +/******************************************************************************/ +/* */ +/* Function: cleanup */ +/* */ +/* Description: Performs all one time clean up for this test on successful */ +/* completion, premature exit or failure. Closes all temporary */ +/* files, removes all temporary directories exits the test with */ +/* appropriate TEST_RETURNurn code by calling tst_exit() function. */ +/* */ +/* Input: None. */ +/* */ +/* Output: None. */ +/* */ +/* Return: On failure - Exits calling tst_exit(). Non '0' TEST_RETURNurn code. */ +/* On success - Exits calling tst_exit(). With '0' TEST_RETURNurn code. */ +/* */ +/******************************************************************************/ +void cleanup(void) +{ + + TEST_CLEANUP; + tst_rmdir(); + + /* Exit with appropriate TEST_RETURNurn code. */ + +} + +/* Local Functions */ +/******************************************************************************/ +/* */ +/* Function: setup */ +/* */ +/* Description: Performs all one time setup for this test. This function is */ +/* typically used to capture signals, create temporary dirs */ +/* and temporary files that may be used in the course of this */ +/* test. */ +/* */ +/* Input: None. */ +/* */ +/* Output: None. */ +/* */ +/* Return: On failure - Exits by calling cleanup(). */ +/* On success - TEST_RETURNurns 0. */ +/* */ +/******************************************************************************/ +void setup(void) +{ + /* Capture signals if any */ + /* Create temporary directories */ + TEST_PAUSE; + tst_tmpdir(); +} + +int main(int ac, char **av) +{ + pid_t pid1; + int lc; + int rval; + const char *msg; /* message TEST_RETURNurned from parse_opts */ + + 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 (testno = 0; testno < TST_TOTAL; ++testno) { + + TEST(pid1 = fork()); //call to fork() + if (TEST_RETURN == -1) { + tst_brkm(TFAIL | TTERRNO, cleanup, + "fork() failed."); + } else if (TEST_RETURN == 0) { + TEST_RETURN = unshare(-1); + if (TEST_RETURN == 0) { + printf("Call unexpectedly succeeded\n"); + rval = 1; + } else if (TEST_RETURN == -1) { + if (errno == EINVAL) { + printf("Got EINVAL\n"); + rval = 0; + } else if (errno == ENOSYS) { + rval = 1; + } else { + perror("unshare failed"); + rval = 2; + } + } + exit(rval); + } else { + if (wait(&rval) == -1) { + tst_brkm(TBROK | TERRNO, cleanup, + "wait failed"); + } + if (rval != 0 && WIFEXITED(rval)) { + switch (WEXITSTATUS(rval)) { + case 1: + tst_brkm(TBROK, cleanup, + "unshare call unsupported " + "in kernel"); + break; + case 2: + tst_brkm(TFAIL, cleanup, + "unshare call failed"); + break; + } + } + } + + TEST(pid1 = fork()); //call to fork() + if (pid1 == -1) { + tst_brkm(TFAIL | TTERRNO, cleanup, + "fork() failed."); + } else if (TEST_RETURN == 0) { + TEST_RETURN = unshare(0); + if (TEST_RETURN == 0) { + tst_resm(TPASS, "Call succeeded"); + rval = 0; + } else if (TEST_RETURN == -1) { + if (errno == ENOSYS) + rval = 1; + else { + perror("unshare failed"); + rval = 2; + } + } + exit(rval); + } else { + if (wait(&rval) == -1) { + tst_brkm(TBROK | TERRNO, cleanup, + "wait failed"); + } + if (rval != 0 && WIFEXITED(rval)) { + switch (WEXITSTATUS(rval)) { + case 1: + tst_brkm(TBROK, cleanup, + "unshare call unsupported " + "in kernel"); + break; + case 2: + tst_brkm(TFAIL, cleanup, + "unshare call failed"); + break; + } + } + } + + } + } + cleanup(); + tst_exit(); +} +#else +int main(void) +{ + tst_brkm(TCONF, NULL, "unshare is undefined."); +} +#endif diff --git a/pool/shard004/C/0099386_loopback.c b/pool/shard004/C/0099386_loopback.c new file mode 100644 index 0000000000000000000000000000000000000000..d0893e4c93300d081a27a40b7401e2dcfc1af438 --- /dev/null +++ b/pool/shard004/C/0099386_loopback.c @@ -0,0 +1,221 @@ +/* + * INET An implementation of the TCP/IP protocol suite for the LINUX + * operating system. INET is implemented using the BSD Socket + * interface as the means of communication with the user level. + * + * Pseudo-driver for the loopback interface. + * + * Version: @(#)loopback.c 1.0.4b 08/16/93 + * + * Authors: Ross Biro + * Fred N. van Kempen, + * Donald Becker, + * + * Alan Cox : Fixed oddments for NET3.014 + * Alan Cox : Rejig for NET3.029 snap #3 + * Alan Cox : Fixed NET3.029 bugs and sped up + * Larry McVoy : Tiny tweak to double performance + * Alan Cox : Backed out LMV's tweak - the linux mm + * can't take it... + * Michael Griffith: Don't bother computing the checksums + * on packets received on the loopback + * interface. + * Alexey Kuznetsov: Potential hang under some extreme + * cases removed. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version + * 2 of the License, or (at your option) any later version. + */ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include /* For the statistics structure. */ +#include /* For ARPHRD_ETHER */ +#include +#include +#include +#include +#include + +struct pcpu_lstats { + u64 packets; + u64 bytes; + struct u64_stats_sync syncp; +}; + +/* + * The higher levels take care of making this non-reentrant (it's + * called with bh's disabled). + */ +static netdev_tx_t loopback_xmit(struct sk_buff *skb, + struct net_device *dev) +{ + struct pcpu_lstats *lb_stats; + int len; + + skb_orphan(skb); + + /* Before queueing this packet to netif_rx(), + * make sure dst is refcounted. + */ + skb_dst_force(skb); + + skb->protocol = eth_type_trans(skb, dev); + + /* it's OK to use per_cpu_ptr() because BHs are off */ + lb_stats = this_cpu_ptr(dev->lstats); + + len = skb->len; + if (likely(netif_rx(skb) == NET_RX_SUCCESS)) { + u64_stats_update_begin(&lb_stats->syncp); + lb_stats->bytes += len; + lb_stats->packets++; + u64_stats_update_end(&lb_stats->syncp); + } + + return NETDEV_TX_OK; +} + +static struct rtnl_link_stats64 *loopback_get_stats64(struct net_device *dev, + struct rtnl_link_stats64 *stats) +{ + u64 bytes = 0; + u64 packets = 0; + int i; + + for_each_possible_cpu(i) { + const struct pcpu_lstats *lb_stats; + u64 tbytes, tpackets; + unsigned int start; + + lb_stats = per_cpu_ptr(dev->lstats, i); + do { + start = u64_stats_fetch_begin(&lb_stats->syncp); + tbytes = lb_stats->bytes; + tpackets = lb_stats->packets; + } while (u64_stats_fetch_retry(&lb_stats->syncp, start)); + bytes += tbytes; + packets += tpackets; + } + stats->rx_packets = packets; + stats->tx_packets = packets; + stats->rx_bytes = bytes; + stats->tx_bytes = bytes; + return stats; +} + +static u32 always_on(struct net_device *dev) +{ + return 1; +} + +static const struct ethtool_ops loopback_ethtool_ops = { + .get_link = always_on, +}; + +static int loopback_dev_init(struct net_device *dev) +{ + dev->lstats = alloc_percpu(struct pcpu_lstats); + if (!dev->lstats) + return -ENOMEM; + + return 0; +} + +static void loopback_dev_free(struct net_device *dev) +{ + free_percpu(dev->lstats); + free_netdev(dev); +} + +static const struct net_device_ops loopback_ops = { + .ndo_init = loopback_dev_init, + .ndo_start_xmit= loopback_xmit, + .ndo_get_stats64 = loopback_get_stats64, +}; + +/* + * The loopback device is special. There is only one instance + * per network namespace. + */ +static void loopback_setup(struct net_device *dev) +{ + dev->mtu = (16 * 1024) + 20 + 20 + 12; + dev->hard_header_len = ETH_HLEN; /* 14 */ + dev->addr_len = ETH_ALEN; /* 6 */ + dev->tx_queue_len = 0; + dev->type = ARPHRD_LOOPBACK; /* 0x0001*/ + dev->flags = IFF_LOOPBACK; + dev->priv_flags &= ~IFF_XMIT_DST_RELEASE; + dev->hw_features = NETIF_F_ALL_TSO | NETIF_F_UFO; + dev->features = NETIF_F_SG | NETIF_F_FRAGLIST + | NETIF_F_ALL_TSO + | NETIF_F_UFO + | NETIF_F_NO_CSUM + | NETIF_F_RXCSUM + | NETIF_F_HIGHDMA + | NETIF_F_LLTX + | NETIF_F_NETNS_LOCAL + | NETIF_F_VLAN_CHALLENGED + | NETIF_F_LOOPBACK; + dev->ethtool_ops = &loopback_ethtool_ops; + dev->header_ops = ð_header_ops; + dev->netdev_ops = &loopback_ops; + dev->destructor = loopback_dev_free; +} + +/* Setup and register the loopback device. */ +static __net_init int loopback_net_init(struct net *net) +{ + struct net_device *dev; + int err; + + err = -ENOMEM; + dev = alloc_netdev(0, "lo", loopback_setup); + if (!dev) + goto out; + + dev_net_set(dev, net); + err = register_netdev(dev); + if (err) + goto out_free_netdev; + + net->loopback_dev = dev; + return 0; + + +out_free_netdev: + free_netdev(dev); +out: + if (net_eq(net, &init_net)) + panic("loopback: Failed to register netdevice: %d\n", err); + return err; +} + +/* Registered in net/core/dev.c */ +struct pernet_operations __net_initdata loopback_net_ops = { + .init = loopback_net_init, +}; diff --git a/pool/shard004/C/0099393_PDCP-ROHC-TargetMode.c b/pool/shard004/C/0099393_PDCP-ROHC-TargetMode.c new file mode 100644 index 0000000000000000000000000000000000000000..6ef15a7fafa732e29b527d500404e2175eac70f2 --- /dev/null +++ b/pool/shard004/C/0099393_PDCP-ROHC-TargetMode.c @@ -0,0 +1,146 @@ +/* + * Generated by asn1c-0.9.24 (http://lionet.info/asn1c) + * From ASN.1 module "InformationElements" + * found in "../asn/InformationElements.asn" + * `asn1c -fcompound-names -fnative-types` + */ + +#include "PDCP-ROHC-TargetMode.h" + +int +PDCP_ROHC_TargetMode_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 +PDCP_ROHC_TargetMode_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 +PDCP_ROHC_TargetMode_free(asn_TYPE_descriptor_t *td, + void *struct_ptr, int contents_only) { + PDCP_ROHC_TargetMode_1_inherit_TYPE_descriptor(td); + td->free_struct(td, struct_ptr, contents_only); +} + +int +PDCP_ROHC_TargetMode_print(asn_TYPE_descriptor_t *td, const void *struct_ptr, + int ilevel, asn_app_consume_bytes_f *cb, void *app_key) { + PDCP_ROHC_TargetMode_1_inherit_TYPE_descriptor(td); + return td->print_struct(td, struct_ptr, ilevel, cb, app_key); +} + +asn_dec_rval_t +PDCP_ROHC_TargetMode_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) { + PDCP_ROHC_TargetMode_1_inherit_TYPE_descriptor(td); + return td->ber_decoder(opt_codec_ctx, td, structure, bufptr, size, tag_mode); +} + +asn_enc_rval_t +PDCP_ROHC_TargetMode_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) { + PDCP_ROHC_TargetMode_1_inherit_TYPE_descriptor(td); + return td->der_encoder(td, structure, tag_mode, tag, cb, app_key); +} + +asn_dec_rval_t +PDCP_ROHC_TargetMode_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) { + PDCP_ROHC_TargetMode_1_inherit_TYPE_descriptor(td); + return td->xer_decoder(opt_codec_ctx, td, structure, opt_mname, bufptr, size); +} + +asn_enc_rval_t +PDCP_ROHC_TargetMode_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) { + PDCP_ROHC_TargetMode_1_inherit_TYPE_descriptor(td); + return td->xer_encoder(td, structure, ilevel, flags, cb, app_key); +} + +asn_dec_rval_t +PDCP_ROHC_TargetMode_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) { + PDCP_ROHC_TargetMode_1_inherit_TYPE_descriptor(td); + return td->uper_decoder(opt_codec_ctx, td, constraints, structure, per_data); +} + +asn_enc_rval_t +PDCP_ROHC_TargetMode_encode_uper(asn_TYPE_descriptor_t *td, + asn_per_constraints_t *constraints, + void *structure, asn_per_outp_t *per_out) { + PDCP_ROHC_TargetMode_1_inherit_TYPE_descriptor(td); + return td->uper_encoder(td, constraints, structure, per_out); +} + +static asn_per_constraints_t asn_PER_type_PDCP_ROHC_TargetMode_constr_1 = { + { APC_CONSTRAINED, 1, 1, 0, 1 } /* (0..1) */, + { APC_UNCONSTRAINED, -1, -1, 0, 0 }, + 0, 0 /* No PER value map */ +}; +static asn_INTEGER_enum_map_t asn_MAP_PDCP_ROHC_TargetMode_value2enum_1[] = { + { 0, 6, "o-Mode" }, + { 1, 6, "r-Mode" } +}; +static unsigned int asn_MAP_PDCP_ROHC_TargetMode_enum2value_1[] = { + 0, /* o-Mode(0) */ + 1 /* r-Mode(1) */ +}; +static asn_INTEGER_specifics_t asn_SPC_PDCP_ROHC_TargetMode_specs_1 = { + asn_MAP_PDCP_ROHC_TargetMode_value2enum_1, /* "tag" => N; sorted by tag */ + asn_MAP_PDCP_ROHC_TargetMode_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_PDCP_ROHC_TargetMode_tags_1[] = { + (ASN_TAG_CLASS_UNIVERSAL | (10 << 2)) +}; +asn_TYPE_descriptor_t asn_DEF_PDCP_ROHC_TargetMode = { + "PDCP-ROHC-TargetMode", + "PDCP-ROHC-TargetMode", + PDCP_ROHC_TargetMode_free, + PDCP_ROHC_TargetMode_print, + PDCP_ROHC_TargetMode_constraint, + PDCP_ROHC_TargetMode_decode_ber, + PDCP_ROHC_TargetMode_encode_der, + PDCP_ROHC_TargetMode_decode_xer, + PDCP_ROHC_TargetMode_encode_xer, + PDCP_ROHC_TargetMode_decode_uper, + PDCP_ROHC_TargetMode_encode_uper, + 0, /* Use generic outmost tag fetcher */ + asn_DEF_PDCP_ROHC_TargetMode_tags_1, + sizeof(asn_DEF_PDCP_ROHC_TargetMode_tags_1) + /sizeof(asn_DEF_PDCP_ROHC_TargetMode_tags_1[0]), /* 1 */ + asn_DEF_PDCP_ROHC_TargetMode_tags_1, /* Same as above */ + sizeof(asn_DEF_PDCP_ROHC_TargetMode_tags_1) + /sizeof(asn_DEF_PDCP_ROHC_TargetMode_tags_1[0]), /* 1 */ + &asn_PER_type_PDCP_ROHC_TargetMode_constr_1, + 0, 0, /* Defined elsewhere */ + &asn_SPC_PDCP_ROHC_TargetMode_specs_1 /* Additional specs */ +}; + diff --git a/pool/shard004/C/0099396_ntquotas.c b/pool/shard004/C/0099396_ntquotas.c new file mode 100644 index 0000000000000000000000000000000000000000..1f4fc2d0a215aa73d5aa72ed0da9fb30ac906b41 --- /dev/null +++ b/pool/shard004/C/0099396_ntquotas.c @@ -0,0 +1,252 @@ +/* + Unix SMB/CIFS implementation. + NT QUOTA suppport + Copyright (C) Stefan (metze) Metzmacher 2003 + + 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 "smbd/smbd.h" +#include "../lib/util/util_pw.h" +#include "system/passwd.h" +#include "passdb/lookup_sid.h" +#include "libsmb/libsmb.h" + +#undef DBGC_CLASS +#define DBGC_CLASS DBGC_QUOTA + +static uint64_t limit_nt2unix(uint64_t in, uint64_t bsize) +{ + uint64_t ret = (uint64_t)0; + + ret = (uint64_t)(in/bsize); + if (in>0 && ret==0) { + /* we have to make sure that a overflow didn't set NO_LIMIT */ + ret = (uint64_t)1; + } + + if (in == SMB_NTQUOTAS_NO_LIMIT) + ret = SMB_QUOTAS_NO_LIMIT; + else if (in == SMB_NTQUOTAS_NO_SPACE) + ret = SMB_QUOTAS_NO_SPACE; + else if (in == SMB_NTQUOTAS_NO_ENTRY) + ret = SMB_QUOTAS_NO_LIMIT; + + return ret; +} + +static uint64_t limit_unix2nt(uint64_t in, uint64_t bsize) +{ + uint64_t ret = (uint64_t)0; + + ret = (uint64_t)(in*bsize); + + if (ret < in) { + /* we overflow */ + ret = SMB_NTQUOTAS_NO_LIMIT; + } + + if (in == SMB_QUOTAS_NO_LIMIT) + ret = SMB_NTQUOTAS_NO_LIMIT; + + return ret; +} + +static uint64_t limit_blk2inodes(uint64_t in) +{ + uint64_t ret = (uint64_t)0; + + ret = (uint64_t)(in/2); + + if (ret == 0 && in != 0) + ret = (uint64_t)1; + + return ret; +} + +int vfs_get_ntquota(files_struct *fsp, enum SMB_QUOTA_TYPE qtype, struct dom_sid *psid, SMB_NTQUOTA_STRUCT *qt) +{ + int ret; + SMB_DISK_QUOTA D; + unid_t id; + + ZERO_STRUCT(D); + + if (!fsp||!fsp->conn||!qt) + return (-1); + + ZERO_STRUCT(*qt); + + id.uid = -1; + + if (psid && !sid_to_uid(psid, &id.uid)) { + DEBUG(0,("sid_to_uid: failed, SID[%s]\n", + sid_string_dbg(psid))); + } + + ret = SMB_VFS_GET_QUOTA(fsp->conn, qtype, id, &D); + + if (psid) + qt->sid = *psid; + + if (ret!=0) { + return ret; + } + + qt->usedspace = (uint64_t)D.curblocks*D.bsize; + qt->softlim = limit_unix2nt(D.softlimit, D.bsize); + qt->hardlim = limit_unix2nt(D.hardlimit, D.bsize); + qt->qflags = D.qflags; + + + return 0; +} + +int vfs_set_ntquota(files_struct *fsp, enum SMB_QUOTA_TYPE qtype, struct dom_sid *psid, SMB_NTQUOTA_STRUCT *qt) +{ + int ret; + SMB_DISK_QUOTA D; + unid_t id; + ZERO_STRUCT(D); + + if (!fsp||!fsp->conn||!qt) + return (-1); + + id.uid = -1; + + D.bsize = (uint64_t)QUOTABLOCK_SIZE; + + D.softlimit = limit_nt2unix(qt->softlim,D.bsize); + D.hardlimit = limit_nt2unix(qt->hardlim,D.bsize); + D.qflags = qt->qflags; + + D.isoftlimit = limit_blk2inodes(D.softlimit); + D.ihardlimit = limit_blk2inodes(D.hardlimit); + + if (psid && !sid_to_uid(psid, &id.uid)) { + DEBUG(0,("sid_to_uid: failed, SID[%s]\n", + sid_string_dbg(psid))); + } + + ret = SMB_VFS_SET_QUOTA(fsp->conn, qtype, id, &D); + + return ret; +} + +static bool allready_in_quota_list(SMB_NTQUOTA_LIST *qt_list, uid_t uid) +{ + SMB_NTQUOTA_LIST *tmp_list = NULL; + + if (!qt_list) + return False; + + for (tmp_list=qt_list;tmp_list!=NULL;tmp_list=tmp_list->next) { + if (tmp_list->uid == uid) { + return True; + } + } + + return False; +} + +int vfs_get_user_ntquota_list(files_struct *fsp, SMB_NTQUOTA_LIST **qt_list) +{ + struct passwd *usr; + TALLOC_CTX *mem_ctx = NULL; + + if (!fsp||!fsp->conn||!qt_list) + return (-1); + + *qt_list = NULL; + + if ((mem_ctx=talloc_init("SMB_USER_QUOTA_LIST"))==NULL) { + DEBUG(0,("talloc_init() failed\n")); + return (-1); + } + + sys_setpwent(); + while ((usr = sys_getpwent()) != NULL) { + SMB_NTQUOTA_STRUCT tmp_qt; + SMB_NTQUOTA_LIST *tmp_list_ent; + struct dom_sid sid; + + ZERO_STRUCT(tmp_qt); + + if (allready_in_quota_list((*qt_list),usr->pw_uid)) { + DEBUG(5,("record for uid[%ld] allready in the list\n",(long)usr->pw_uid)); + continue; + } + + uid_to_sid(&sid, usr->pw_uid); + + if (vfs_get_ntquota(fsp, SMB_USER_QUOTA_TYPE, &sid, &tmp_qt)!=0) { + DEBUG(5,("no quota entry for sid[%s] path[%s]\n", + sid_string_dbg(&sid), + fsp->conn->connectpath)); + continue; + } + + DEBUG(15,("quota entry for id[%s] path[%s]\n", + sid_string_dbg(&sid), fsp->conn->connectpath)); + + if ((tmp_list_ent=talloc_zero(mem_ctx,SMB_NTQUOTA_LIST))==NULL) { + DEBUG(0,("TALLOC_ZERO() failed\n")); + *qt_list = NULL; + talloc_destroy(mem_ctx); + return (-1); + } + + if ((tmp_list_ent->quotas=talloc_zero(mem_ctx,SMB_NTQUOTA_STRUCT))==NULL) { + DEBUG(0,("TALLOC_ZERO() failed\n")); + *qt_list = NULL; + talloc_destroy(mem_ctx); + return (-1); + } + + tmp_list_ent->uid = usr->pw_uid; + memcpy(tmp_list_ent->quotas,&tmp_qt,sizeof(tmp_qt)); + tmp_list_ent->mem_ctx = mem_ctx; + + DLIST_ADD((*qt_list),tmp_list_ent); + + } + sys_endpwent(); + + return 0; +} + +static int quota_handle_destructor(SMB_NTQUOTA_HANDLE *handle) +{ + if (handle->quota_list) + free_ntquota_list(&handle->quota_list); + return 0; +} + +void *init_quota_handle(TALLOC_CTX *mem_ctx) +{ + SMB_NTQUOTA_HANDLE *qt_handle; + + if (!mem_ctx) + return False; + + qt_handle = talloc_zero(mem_ctx,SMB_NTQUOTA_HANDLE); + if (qt_handle==NULL) { + DEBUG(0,("TALLOC_ZERO() failed\n")); + return NULL; + } + + talloc_set_destructor(qt_handle, quota_handle_destructor); + return (void *)qt_handle; +} diff --git a/pool/shard004/C/0099404_gg_utf8.c b/pool/shard004/C/0099404_gg_utf8.c new file mode 100644 index 0000000000000000000000000000000000000000..70c2efd472cc65a365c34e5ba61d661c2b1deadf --- /dev/null +++ b/pool/shard004/C/0099404_gg_utf8.c @@ -0,0 +1,184 @@ +/* + + gg_utf8.c -- locale charset handling + + version 4.1, 2013 May 8 + + Author: Sandro Furieri a.furieri@lqt.it + + ------------------------------------------------------------------------------ + + Version: MPL 1.1/GPL 2.0/LGPL 2.1 + + The contents of this file are subject to the Mozilla Public License Version + 1.1 (the "License"); you may not use this file except in compliance with + the License. You may obtain a copy of the License at + http://www.mozilla.org/MPL/ + +Software distributed under the License is distributed on an "AS IS" basis, +WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License +for the specific language governing rights and limitations under the +License. + +The Original Code is the SpatiaLite library + +The Initial Developer of the Original Code is Alessandro Furieri + +Portions created by the Initial Developer are Copyright (C) 2008-2013 +the Initial Developer. All Rights Reserved. + +Contributor(s): + +Alternatively, the contents of this file may be used under the terms of +either the GNU General Public License Version 2 or later (the "GPL"), or +the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), +in which case the provisions of the GPL or the LGPL are applicable instead +of those above. If you wish to allow use of your version of this file only +under the terms of either the GPL or the LGPL, and not to allow others to +use your version of this file under the terms of the MPL, indicate your +decision by deleting the provisions above and replace them with the notice +and other provisions required by the GPL or the LGPL. If you do not delete +the provisions above, a recipient may use your version of this file under +the terms of any one of the MPL, the GPL or the LGPL. + +*/ + +#include +#include +#include +#include +#include + +#if defined(_WIN32) && !defined(__MINGW32__) +#include "config-msvc.h" +#else +#include "config.h" +#endif + +#if OMIT_ICONV == 0 /* ICONV is absolutely required */ + +#if defined(__MINGW32__) || defined(_WIN32) +#define LIBICONV_STATIC +#include +#define LIBCHARSET_STATIC +#ifdef _MSC_VER +/* isn't supported on OSGeo4W */ +/* applying a tricky workaround to fix this issue */ +extern const char *locale_charset (void); +#else /* sane Windows - not OSGeo4W */ +#include +#endif /* end localcharset */ +#else /* not MINGW32 - WIN32 */ +#if defined(__APPLE__) || defined(__ANDROID__) +#include +#include +#else /* neither Mac OsX nor Android */ +#include +#include +#endif +#endif + +#include +#include + +GAIAAUX_DECLARE const char * +gaiaGetLocaleCharset () +{ +/* identifies the locale charset */ +#if defined(__MINGW32__) || defined(_WIN32) + return locale_charset (); +#else /* not MINGW32 - WIN32 */ +#if defined(__APPLE__) || defined(__ANDROID__) + return locale_charset (); +#else /* neither Mac OsX nor Android */ + return nl_langinfo (CODESET); +#endif +#endif +} + +GAIAAUX_DECLARE int +gaiaConvertCharset (char **buf, const char *fromCs, const char *toCs) +{ +/* converting a string from a charset to another "on-the-fly" */ + char utf8buf[65536]; +#if !defined(__MINGW32__) && defined(_WIN32) + const char *pBuf; +#else /* not WIN32 */ + char *pBuf; +#endif + size_t len; + size_t utf8len; + char *pUtf8buf; + iconv_t cvt = iconv_open (toCs, fromCs); + if (cvt == (iconv_t) (-1)) + goto unsupported; + len = strlen (*buf); + utf8len = 65536; + pBuf = *buf; + pUtf8buf = utf8buf; + if (iconv (cvt, &pBuf, &len, &pUtf8buf, &utf8len) == (size_t) (-1)) + goto error; + utf8buf[65536 - utf8len] = '\0'; + memcpy (*buf, utf8buf, (65536 - utf8len) + 1); + iconv_close (cvt); + return 1; + error: + iconv_close (cvt); + unsupported: + return 0; +} + +GAIAAUX_DECLARE void * +gaiaCreateUTF8Converter (const char *fromCS) +{ +/* creating a UTF8 converter and returning an opaque reference to it */ + iconv_t cvt = iconv_open ("UTF-8", fromCS); + if (cvt == (iconv_t) (-1)) + return NULL; + return cvt; +} + +GAIAAUX_DECLARE void +gaiaFreeUTF8Converter (void *cvtCS) +{ +/* destroying a UTF8 converter */ + if (cvtCS) + iconv_close (cvtCS); +} + +GAIAAUX_DECLARE char * +gaiaConvertToUTF8 (void *cvtCS, const char *buf, int buflen, int *err) +{ +/* converting a string to UTF8 */ + char *utf8buf = 0; +#if !defined(__MINGW32__) && defined(_WIN32) + const char *pBuf; +#else + char *pBuf; +#endif + size_t len; + size_t utf8len; + int maxlen = buflen * 4; + char *pUtf8buf; + *err = 0; + if (!cvtCS) + { + *err = 1; + return NULL; + } + utf8buf = malloc (maxlen); + len = buflen; + utf8len = maxlen; + pBuf = (char *) buf; + pUtf8buf = utf8buf; + if (iconv (cvtCS, &pBuf, &len, &pUtf8buf, &utf8len) == (size_t) (-1)) + { + free (utf8buf); + *err = 1; + return NULL; + } + utf8buf[maxlen - utf8len] = '\0'; + return utf8buf; +} + +#endif /* ICONV enabled/disabled */ diff --git a/pool/shard004/C/0099407_99-dizinin_elemanlarini_tersten_yazma_ve_toplama.c b/pool/shard004/C/0099407_99-dizinin_elemanlarini_tersten_yazma_ve_toplama.c new file mode 100644 index 0000000000000000000000000000000000000000..4baf42cae2c810c166025138e3119570d6534ed5 --- /dev/null +++ b/pool/shard004/C/0099407_99-dizinin_elemanlarini_tersten_yazma_ve_toplama.c @@ -0,0 +1,51 @@ +/******************************************** +* * +* Eyüp Can KILINÇDEMİR * +* KARADENİZ TEKNİK UNİVERSİTESİ * +* ceksoft.wordpress.com * +* eyupcankilincdemir@gmail.com * +* * +********************************************/ + +#include +#include + +#define DIZI_BOYUT 15 + +int dizi_eleman_topla(int[],int); +int dizi_eleman_topla(int dizimiz[],int boyut) //recursive olarak elemanlari toplar +{ + if(boyut == 1) + { + return dizimiz[0]; + } + else + { + return dizimiz[boyut - 1] + dizi_eleman_topla(dizimiz,boyut - 1); //Son elemandan itibaren ilk elemana ulasana kadar kendini cagirir + } //ve bunlari toplar +} + +void dizi_eleman_basma(int[],int); +void dizi_eleman_basma(int dizimiz[],int dizi_boyut) +{ + if(dizi_boyut > 0) //Dizinin boyutu 0 dan buyukse kendini tekrar cagirir + { + dizi_eleman_basma(&dizimiz[1],dizi_boyut - 1); //Fonksiyon ikinci elemanin adresini ve dizi boyutunu bir azaltarak kendini cagirir + printf("%d ",dizimiz[0]); + } +} + + +int main() +{ + int dizi[DIZI_BOYUT] = {1,32,549,87,65,1,312,648,641,3,25,153,15,3,74}; + + dizi_eleman_basma(dizi,DIZI_BOYUT); + + int toplam; + toplam = dizi_eleman_topla(dizi,DIZI_BOYUT); + printf("\nDizimizin elemanlarinin toplami = %d",toplam); + + return 0; +} + diff --git a/pool/shard004/C/0099409_pdfcrack_rc4.c b/pool/shard004/C/0099409_pdfcrack_rc4.c new file mode 100644 index 0000000000000000000000000000000000000000..09c3156d53928ed3a5122c81272e1b8225d650ef --- /dev/null +++ b/pool/shard004/C/0099409_pdfcrack_rc4.c @@ -0,0 +1,224 @@ +/** + * Copyright (C) 2006 Henning Norén + * + * 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 "pdfcrack_rc4.h" + +#ifdef _MSC_VER +#define inline _inline +#endif +#ifndef __GNUC__ +#define ATTR_PURE +#define likely(x) (x) +#define unlikely(x) (x) +#else +#define ATTR_PURE __attribute__ ((pure)) +#define likely(x) __builtin_expect((x),1) +#define unlikely(x) __builtin_expect((x),0) +#endif + +/** Seems to faster to do a memcpy of this on my machine than to create + the array with a loop +*/ +static const uint8_t +initial_state[256] = { + 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, + 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, + 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20, 0x21, 0x22, 0x23, + 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, + 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x3b, + 0x3c, 0x3d, 0x3e, 0x3f, 0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, + 0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f, 0x50, 0x51, 0x52, 0x53, + 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5a, 0x5b, 0x5c, 0x5d, 0x5e, 0x5f, + 0x60, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6a, 0x6b, + 0x6c, 0x6d, 0x6e, 0x6f, 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, + 0x78, 0x79, 0x7a, 0x7b, 0x7c, 0x7d, 0x7e, 0x7f, 0x80, 0x81, 0x82, 0x83, + 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x8e, 0x8f, + 0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, 0x9a, 0x9b, + 0x9c, 0x9d, 0x9e, 0x9f, 0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7, + 0xa8, 0xa9, 0xaa, 0xab, 0xac, 0xad, 0xae, 0xaf, 0xb0, 0xb1, 0xb2, 0xb3, + 0xb4, 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xbb, 0xbc, 0xbd, 0xbe, 0xbf, + 0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xcb, + 0xcc, 0xcd, 0xce, 0xcf, 0xd0, 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, + 0xd8, 0xd9, 0xda, 0xdb, 0xdc, 0xdd, 0xde, 0xdf, 0xe0, 0xe1, 0xe2, 0xe3, + 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea, 0xeb, 0xec, 0xed, 0xee, 0xef, + 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa, 0xfb, + 0xfc, 0xfd, 0xfe, 0xff}; + +#define key_pass(n) { \ + tmp = state[++i]; \ + j = (j + tmp + key[n]); \ + state[i] = state[j]; \ + state[j] = tmp; \ + } + +/** Do rc4-decrypt with key on bs of length 32 and compare it to match */ +ATTR_PURE bool +rc4Match40b(const uint8_t *key, const uint8_t *bs,const uint8_t *match) { + uint8_t state[256]; + register unsigned int i; + register uint8_t j, tmp; + + /** initialize the state */ + memcpy(state, initial_state, 256); + + /** do the shuffle */ + j = key[0]; + state[0] = j; + state[j] = 0; + i = 0; + do { + key_pass(1); + key_pass(2); + key_pass(3); + key_pass(4); + key_pass(0); + } while(i < 255); + + j = 0; + for(i=1;i<=32;++i) { + tmp = state[i]; + j += tmp; + state[i] = state[j]; + state[j] = tmp; + + /** + Only continue if we match the match-strings characters. + The match should only happen once every 256 try or so and that is + the motivation behind the likely-hint + */ + tmp += state[i]; + if(likely((bs[i-1]^state[tmp]) != match[i-1])) + return false; + } + return true; +} + +static void +(*rc4d)(const uint8_t *key, const uint8_t *bs, + const unsigned int len, uint8_t *out) = NULL; + +/** Do 40-bit rc4-decrypt with key on bs of length len and + put the result in out +*/ +static void +rc4Decrypt40b(const uint8_t *key, const uint8_t *bs, + const unsigned int len, uint8_t *out) { + uint8_t state[256]; + register unsigned int i; + register uint8_t j, tmp; + + assert(len < 256); + + /** initialize the state */ + memcpy(state, initial_state, 256); + + /** do the shuffle */ + j = key[0]; + state[0] = j; + state[j] = 0; + i = 0; + do { + key_pass(1); + key_pass(2); + key_pass(3); + key_pass(4); + key_pass(0); + } while(i < 255); + + j = 0; + for(i=1;i<=len;++i) { + tmp = state[i]; + j += tmp; + state[i] = state[j]; + state[j] = tmp; + + tmp += state[i]; + out[i-1] = bs[i-1]^state[tmp]; + } +} + +/** Do 128-bit rc4-decrypt with key on bs of length len and + put the result in out +*/ +static void +rc4Decrypt128b(const uint8_t *key, const uint8_t *bs, + const unsigned int len, uint8_t *out) { + uint8_t state[256]; + register int i; + register uint8_t j, tmp; + + assert(len < 256); + + /** initialize the state */ + memcpy(state, initial_state, 256); + + /** do the shuffle */ + j = 0; + i = -1; + do { + key_pass( 0); + key_pass( 1); + key_pass( 2); + key_pass( 3); + key_pass( 4); + key_pass( 5); + key_pass( 6); + key_pass( 7); + key_pass( 8); + key_pass( 9); + key_pass(10); + key_pass(11); + key_pass(12); + key_pass(13); + key_pass(14); + key_pass(15); + } while(i < 255); + + j = 0; + for(i=1;(unsigned int)i<=len;++i) { + tmp = state[i]; + j += tmp; + state[i] = state[j]; + state[j] = tmp; + + tmp += state[i]; + out[i-1] = bs[i-1]^state[tmp]; + } +} + +/** Just a wrapper for the function optimized for a specific length */ +void +rc4Decrypt(const uint8_t *key, const uint8_t *bs, + const unsigned int len, uint8_t *out) { + rc4d(key, bs, len, out); +} + +/** sets which function the wrapper should call */ +ATTR_PURE bool +setrc4DecryptMethod(const unsigned int length) { + if(length == 128) + rc4d = &rc4Decrypt128b; + else if(length == 40) + rc4d = &rc4Decrypt40b; + else + return false; + return true; +} diff --git a/pool/shard004/C/0099417_main.c b/pool/shard004/C/0099417_main.c new file mode 100644 index 0000000000000000000000000000000000000000..fa0fec1f2f8e21ac48dde74ac1863a3fc2110e03 --- /dev/null +++ b/pool/shard004/C/0099417_main.c @@ -0,0 +1,331 @@ +/* + FreeRTOS V8.1.2 - Copyright (C) 2014 Real Time Engineers Ltd. + All rights reserved + + VISIT http://www.FreeRTOS.org TO ENSURE YOU ARE USING THE LATEST VERSION. + + *************************************************************************** + * * + * FreeRTOS provides completely free yet professionally developed, * + * robust, strictly quality controlled, supported, and cross * + * platform software that has become a de facto standard. * + * * + * Help yourself get started quickly and support the FreeRTOS * + * project by purchasing a FreeRTOS tutorial book, reference * + * manual, or both from: http://www.FreeRTOS.org/Documentation * + * * + * Thank you! * + * * + *************************************************************************** + + 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. Full license text is available from the following + link: http://www.freertos.org/a00114.html + + 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, a DOS + compatible FAT file system, and our tiny thread aware UDP/IP stack. + + http://www.OpenRTOS.com - Real Time Engineers ltd license FreeRTOS to High + Integrity Systems to sell under the OpenRTOS brand. Low cost OpenRTOS + licenses offer ticketed support, indemnification and middleware. + + 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. + + 1 tab == 4 spaces! +*/ + +/* + NOTE : Tasks run in system mode and the scheduler runs in Supervisor mode. + The processor MUST be in supervisor mode when vTaskStartScheduler is + called. The demo applications included in the FreeRTOS.org download switch + to supervisor mode prior to main being called. If you are not using one of + these demo application projects then ensure Supervisor mode is used. +*/ + + +/* + * Creates all the application tasks, then starts the scheduler. + * + * A task defined by the function vBasicWEBServer is created. This executes + * the lwIP stack and basic WEB server sample. A task defined by the function + * vUSBCDCTask. This executes the USB to serial CDC example. All the other + * tasks are from the set of standard demo tasks. The WEB documentation + * provides more details of the standard demo application tasks. + * + * Main.c also creates a task called "Check". This only executes every three + * seconds but has the highest priority so is guaranteed to get processor time. + * Its main function is to check the status of all the other demo application + * tasks. LED mainCHECK_LED is toggled every three seconds by the check task + * should no error conditions be detected in any of the standard demo tasks. + * The toggle rate increasing to 500ms indicates that at least one error has + * been detected. + * + * Main.c includes an idle hook function that simply periodically sends data + * to the USB task for transmission. + */ + +/* + Changes from V3.2.2 + + + Modified the stack sizes used by some tasks to permit use of the + command line GCC tools. +*/ + +/* Library includes. */ +#include +#include + +/* Scheduler includes. */ +#include "FreeRTOS.h" +#include "task.h" + +/* Demo application includes. */ +#include "partest.h" +#include "PollQ.h" +#include "semtest.h" +#include "flash.h" +#include "integer.h" +#include "BlockQ.h" +#include "BasicWEB.h" +#include "USB-CDC.h" + +/* lwIP includes. */ +#include "lwip/api.h" + +/* Hardware specific headers. */ +#include "Board.h" +#include "AT91SAM7X256.h" + +/* Priorities/stacks for the various tasks within the demo application. */ +#define mainQUEUE_POLL_PRIORITY ( tskIDLE_PRIORITY + 1 ) +#define mainCHECK_TASK_PRIORITY ( tskIDLE_PRIORITY + 3 ) +#define mainSEM_TEST_PRIORITY ( tskIDLE_PRIORITY + 1 ) +#define mainFLASH_PRIORITY ( tskIDLE_PRIORITY + 2 ) +#define mainBLOCK_Q_PRIORITY ( tskIDLE_PRIORITY + 1 ) +#define mainWEBSERVER_PRIORITY ( tskIDLE_PRIORITY + 2 ) +#define mainUSB_PRIORITY ( tskIDLE_PRIORITY + 1 ) +#define mainUSB_TASK_STACK ( 200 ) + +/* The rate at which the on board LED will toggle when there is/is not an +error. */ +#define mainNO_ERROR_FLASH_PERIOD ( ( TickType_t ) 3000 / portTICK_PERIOD_MS ) +#define mainERROR_FLASH_PERIOD ( ( TickType_t ) 500 / portTICK_PERIOD_MS ) + +/* The rate at which the idle hook sends data to the USB port. */ +#define mainUSB_TX_FREQUENCY ( 100 / portTICK_PERIOD_MS ) + +/* The string that is transmitted down the USB port. */ +#define mainFIRST_TX_CHAR 'a' +#define mainLAST_TX_CHAR 'z' + +/* The LED used by the check task to indicate the system status. */ +#define mainCHECK_LED ( 3 ) +/*-----------------------------------------------------------*/ + +/* + * Checks that all the demo application tasks are still executing without error + * - as described at the top of the file. + */ +static long prvCheckOtherTasksAreStillRunning( void ); + +/* + * The task that executes at the highest priority and calls + * prvCheckOtherTasksAreStillRunning(). See the description at the top + * of the file. + */ +static void vErrorChecks( void *pvParameters ); + +/* + * Configure the processor for use with the Atmel demo board. This is very + * minimal as most of the setup is performed in the startup code. + */ +static void prvSetupHardware( void ); + +/* + * The idle hook is just used to stream data to the USB port. + */ +void vApplicationIdleHook( void ); +/*-----------------------------------------------------------*/ + +/* + * Setup hardware then start all the demo application tasks. + */ +int main( void ) +{ + /* Setup the ports. */ + prvSetupHardware(); + + /* Setup the IO required for the LED's. */ + vParTestInitialise(); + + /* Setup lwIP. */ + vlwIPInit(); + + /* Create the lwIP task. This uses the lwIP RTOS abstraction layer.*/ + sys_thread_new( vBasicWEBServer, ( void * ) NULL, mainWEBSERVER_PRIORITY ); + + /* Create the demo USB CDC task. */ + xTaskCreate( vUSBCDCTask, "USB", mainUSB_TASK_STACK, NULL, mainUSB_PRIORITY, NULL ); + + /* Create the standard demo application tasks. */ + vStartPolledQueueTasks( mainQUEUE_POLL_PRIORITY ); + vStartSemaphoreTasks( mainSEM_TEST_PRIORITY ); + vStartLEDFlashTasks( mainFLASH_PRIORITY ); + vStartIntegerMathTasks( tskIDLE_PRIORITY ); + vStartBlockingQueueTasks( mainBLOCK_Q_PRIORITY ); + + /* Start the check task - which is defined in this file. */ + xTaskCreate( vErrorChecks, "Check", configMINIMAL_STACK_SIZE, NULL, mainCHECK_TASK_PRIORITY, NULL ); + + /* Finally, start the scheduler. + + NOTE : Tasks run in system mode and the scheduler runs in Supervisor mode. + The processor MUST be in supervisor mode when vTaskStartScheduler is + called. The demo applications included in the FreeRTOS.org download switch + to supervisor mode prior to main being called. If you are not using one of + these demo application projects then ensure Supervisor mode is used here. */ + vTaskStartScheduler(); + + /* Should never get here! */ + return 0; +} +/*-----------------------------------------------------------*/ + + +static void prvSetupHardware( void ) +{ + /* When using the JTAG debugger the hardware is not always initialised to + the correct default state. This line just ensures that this does not + cause all interrupts to be masked at the start. */ + AT91C_BASE_AIC->AIC_EOICR = 0; + + /* Most setup is performed by the low level init function called from the + startup asm file. + + Configure the PIO Lines corresponding to LED1 to LED4 to be outputs as + well as the UART Tx line. */ + AT91C_BASE_PIOB->PIO_PER = LED_MASK; // Set in PIO mode + AT91C_BASE_PIOB->PIO_OER = LED_MASK; // Configure in Output + + + /* Enable the peripheral clock. */ + AT91C_BASE_PMC->PMC_PCER = 1 << AT91C_ID_PIOA; + AT91C_BASE_PMC->PMC_PCER = 1 << AT91C_ID_PIOB; + AT91C_BASE_PMC->PMC_PCER = 1 << AT91C_ID_EMAC; +} +/*-----------------------------------------------------------*/ + +static void vErrorChecks( void *pvParameters ) +{ +TickType_t xDelayPeriod = mainNO_ERROR_FLASH_PERIOD; +TickType_t xLastWakeTime; + + /* The parameters are not used. */ + ( void ) pvParameters; + + /* Initialise xLastWakeTime to ensure the first call to vTaskDelayUntil() + functions correctly. */ + xLastWakeTime = xTaskGetTickCount(); + + /* Cycle for ever, delaying then checking all the other tasks are still + operating without error. If an error is detected then the delay period + is decreased from mainNO_ERROR_FLASH_PERIOD to mainERROR_FLASH_PERIOD so + the Check LED flash rate will increase. */ + for( ;; ) + { + /* Delay until it is time to execute again. The delay period is + shorter following an error. */ + vTaskDelayUntil( &xLastWakeTime, xDelayPeriod ); + + /* Check all the standard demo application tasks are executing without + error. */ + if( prvCheckOtherTasksAreStillRunning() != pdPASS ) + { + /* An error has been detected in one of the tasks - flash faster. */ + xDelayPeriod = mainERROR_FLASH_PERIOD; + } + + vParTestToggleLED( mainCHECK_LED ); + } +} +/*-----------------------------------------------------------*/ + +static long prvCheckOtherTasksAreStillRunning( void ) +{ +long lReturn = ( long ) pdPASS; + + /* Check all the demo tasks (other than the flash tasks) to ensure + that they are all still running, and that none of them have detected + an error. */ + + if( xArePollingQueuesStillRunning() != pdTRUE ) + { + lReturn = ( long ) pdFAIL; + } + + if( xAreSemaphoreTasksStillRunning() != pdTRUE ) + { + lReturn = ( long ) pdFAIL; + } + + if( xAreIntegerMathsTaskStillRunning() != pdTRUE ) + { + lReturn = ( long ) pdFAIL; + } + + if( xAreBlockingQueuesStillRunning() != pdTRUE ) + { + lReturn = ( long ) pdFAIL; + } + + return lReturn; +} +/*-----------------------------------------------------------*/ + +void vApplicationIdleHook( void ) +{ +static TickType_t xLastTx = 0; +char cTxByte; + + /* The idle hook simply sends a string of characters to the USB port. + The characters will be buffered and sent once the port is connected. */ + if( ( xTaskGetTickCount() - xLastTx ) > mainUSB_TX_FREQUENCY ) + { + xLastTx = xTaskGetTickCount(); + for( cTxByte = mainFIRST_TX_CHAR; cTxByte <= mainLAST_TX_CHAR; cTxByte++ ) + { + vUSBSendByte( cTxByte ); + } + } +} + + diff --git a/pool/shard004/C/0099418_spi-slave-time.c b/pool/shard004/C/0099418_spi-slave-time.c new file mode 100644 index 0000000000000000000000000000000000000000..f2e07a392d6863ea22a098ee8cdef5c841cdd6b8 --- /dev/null +++ b/pool/shard004/C/0099418_spi-slave-time.c @@ -0,0 +1,129 @@ +/* + * SPI slave handler reporting uptime at reception of previous SPI message + * + * This SPI slave handler sends the time of reception of the last SPI message + * as two 32-bit unsigned integers in binary format and in network byte order, + * representing the number of seconds and fractional seconds (in microseconds) + * since boot up. + * + * Copyright (C) 2016-2017 Glider bvba + * + * 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. + * + * Usage (assuming /dev/spidev2.0 corresponds to the SPI master on the remote + * system): + * + * # spidev_test -D /dev/spidev2.0 -p dummy-8B + * spi mode: 0x0 + * bits per word: 8 + * max speed: 500000 Hz (500 KHz) + * RX | 00 00 04 6D 00 09 5B BB ... + * ^^^^^ ^^^^^^^^ + * seconds microseconds + */ + +#include +#include +#include +#include + + +struct spi_slave_time_priv { + struct spi_device *spi; + struct completion finished; + struct spi_transfer xfer; + struct spi_message msg; + __be32 buf[2]; +}; + +static int spi_slave_time_submit(struct spi_slave_time_priv *priv); + +static void spi_slave_time_complete(void *arg) +{ + struct spi_slave_time_priv *priv = arg; + int ret; + + ret = priv->msg.status; + if (ret) + goto terminate; + + ret = spi_slave_time_submit(priv); + if (ret) + goto terminate; + + return; + +terminate: + dev_info(&priv->spi->dev, "Terminating\n"); + complete(&priv->finished); +} + +static int spi_slave_time_submit(struct spi_slave_time_priv *priv) +{ + u32 rem_us; + int ret; + u64 ts; + + ts = local_clock(); + rem_us = do_div(ts, 1000000000) / 1000; + + priv->buf[0] = cpu_to_be32(ts); + priv->buf[1] = cpu_to_be32(rem_us); + + spi_message_init_with_transfers(&priv->msg, &priv->xfer, 1); + + priv->msg.complete = spi_slave_time_complete; + priv->msg.context = priv; + + ret = spi_async(priv->spi, &priv->msg); + if (ret) + dev_err(&priv->spi->dev, "spi_async() failed %d\n", ret); + + return ret; +} + +static int spi_slave_time_probe(struct spi_device *spi) +{ + struct spi_slave_time_priv *priv; + int ret; + + priv = devm_kzalloc(&spi->dev, sizeof(*priv), GFP_KERNEL); + if (!priv) + return -ENOMEM; + + priv->spi = spi; + init_completion(&priv->finished); + priv->xfer.tx_buf = priv->buf; + priv->xfer.len = sizeof(priv->buf); + + ret = spi_slave_time_submit(priv); + if (ret) + return ret; + + spi_set_drvdata(spi, priv); + return 0; +} + +static int spi_slave_time_remove(struct spi_device *spi) +{ + struct spi_slave_time_priv *priv = spi_get_drvdata(spi); + + spi_slave_abort(spi); + wait_for_completion(&priv->finished); + return 0; +} + +static struct spi_driver spi_slave_time_driver = { + .driver = { + .name = "spi-slave-time", + }, + .probe = spi_slave_time_probe, + .remove = spi_slave_time_remove, +}; +module_spi_driver(spi_slave_time_driver); + +MODULE_AUTHOR("Geert Uytterhoeven "); +MODULE_DESCRIPTION("SPI slave reporting uptime at previous SPI message"); +MODULE_LICENSE("GPL v2"); diff --git a/pool/shard004/C/0099421_tst-tls9.c b/pool/shard004/C/0099421_tst-tls9.c new file mode 100644 index 0000000000000000000000000000000000000000..6306fb5658657c07d01dfec544d399164792e34e --- /dev/null +++ b/pool/shard004/C/0099421_tst-tls9.c @@ -0,0 +1,37 @@ +#include +#include +#include + +#include + +#define TEST_FUNCTION do_test () +static int +do_test (void) +{ + static const char modname1[] = "tst-tlsmod5.so"; + static const char modname2[] = "tst-tlsmod6.so"; + int result = 0; + + void *h1 = dlopen (modname1, RTLD_LAZY); + if (h1 == NULL) + { + printf ("cannot open '%s': %s\n", modname1, dlerror ()); + result = 1; + } + void *h2 = dlopen (modname2, RTLD_LAZY); + if (h2 == NULL) + { + printf ("cannot open '%s': %s\n", modname2, dlerror ()); + result = 1; + } + + if (h1 != NULL) + dlclose (h1); + if (h2 != NULL) + dlclose (h2); + + return result; +} + + +#include "../test-skeleton.c" diff --git a/pool/shard004/C/0099422_timer.c b/pool/shard004/C/0099422_timer.c new file mode 100644 index 0000000000000000000000000000000000000000..3dbaed28867bb957b27b88ab9af0ac626cb9f3ff --- /dev/null +++ b/pool/shard004/C/0099422_timer.c @@ -0,0 +1,137 @@ +#include +#include +#include +#include +#include + +#define OS_TIMER_MAX 32 + +struct timer_t +{ + void (*pfun)(void* para); + unsigned int delay; + unsigned int period; + bool run; + void* para; +}; +struct timer_t timer_list[OS_TIMER_MAX]; + +typedef uint8_t timer_id; + +void timer_init(void) +{ + uint8_t index; + + for (index = 0; index < OS_TIMER_MAX; index++) + { + timer_list[index].pfun = NULL; + } +} + +timer_id timer_creat(void(*pFunction)(void* para), + const unsigned int delay, + const unsigned int period, + bool run, + void* para) +{ + uint8_t index = 0; + + while ((timer_list[index].pfun != NULL) && (index < OS_TIMER_MAX)) + { + index++; + } + + printf("time index %d\r\n",index); + timer_list[index].pfun = pFunction; + timer_list[index].delay = delay; + timer_list[index].period = period; + timer_list[index].run = run; + timer_list[index].para = para; + return index; +} + +bool timer_delete(const timer_id index) +{ + if(index >= OS_TIMER_MAX) return false; + + if (timer_list[index].pfun == NULL) + { + return false; + } + timer_list[index].pfun = NULL; + timer_list[index].delay = 0; + timer_list[index].period = 0; + timer_list[index].run = false; + timer_list[index].para = NULL; + return true; +} + +void timer_start(const timer_id index) +{ + if(index >= OS_TIMER_MAX) return; + + timer_list[index].run = true; +} + +void timer_stop(const timer_id index) +{ + if(index >= OS_TIMER_MAX) return; + + timer_list[index].run = false; +} + +void timer_sched(void) +{ + uint8_t index; + for (index = 0; index < OS_TIMER_MAX; index++) + { + if(timer_list[index].delay == 0) + { + if (timer_list[index].run) + { + (*timer_list[index].pfun)(timer_list[index].para); + if (timer_list[index].period == 0) + { + timer_delete(index); + } + else timer_list[index].delay = timer_list[index].period; + } + } + else + { + timer_list[index].delay -= 1; + } + } +} + +void f1(void* para) +{} + +void f2(void* para) +{} + +void f3(void* para) +{} + + +int main() +{ + printf("Hello world!\n"); + + timer_init(); + + timer_id t1 = timer_creat(f1, 0, 100, false, NULL); + timer_id t2 = timer_creat(f2, 10, 200, false, NULL); + timer_id t3 = timer_creat(f3, 20, 400, false, NULL); + + timer_sched(); + + timer_start(t1); + timer_stop(t1); + + timer_delete(t1); + timer_delete(t2); + timer_delete(t3); + + return 0; +} diff --git a/pool/shard004/C/0099426_json-validate.c b/pool/shard004/C/0099426_json-validate.c new file mode 100644 index 0000000000000000000000000000000000000000..d6e3cc8bb31924d00a675319dbbbff0a5a1a47ba --- /dev/null +++ b/pool/shard004/C/0099426_json-validate.c @@ -0,0 +1,266 @@ +/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */ +/* + * Walbottle + * Copyright (C) Philip Withnall 2015 + * + * Walbottle 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. + * + * Walbottle is distributed in the hope that 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 Walbottle. If not, see . + */ + +#include "config.h" + +#include +#include +#include + +#include "wbl-schema.h" +#include "utilities/wbl-utilities.h" + +/* Exit statuses. */ +typedef enum { + /* Success. */ + EXIT_OK = 0, + /* Error parsing command line options. */ + EXIT_INVALID_OPTIONS = 1, + /* JSON file could not be parsed. */ + EXIT_INVALID_JSON = 2, + /* JSON schema could not be parsed. */ + EXIT_INVALID_SCHEMA = 3, + /* JSON file does not validate against a schema. */ + EXIT_SCHEMA_VALIDATION_FAILED = 4, +} ExitStatus; + +/* Command line parameters. */ +static gboolean option_quiet = FALSE; +static gboolean option_ignore_errors = FALSE; +static gchar **option_schema_filenames = NULL; +static gchar **option_json_filenames = NULL; + +static const GOptionEntry entries[] = { + { "quiet", 'q', 0, G_OPTION_ARG_NONE, &option_quiet, + N_("Quieten command line output"), NULL }, + { "schema", 's', 0, G_OPTION_ARG_FILENAME_ARRAY, + &option_schema_filenames, + N_("JSON Schema to validate against; may be specified multiple " + "times"), N_("JSON-SCHEMA") }, + { "ignore-errors", 'i', 0, G_OPTION_ARG_NONE, &option_ignore_errors, + N_("Continue validating after errors are encountered, rather than " + "stopping at the first error"), NULL }, + { G_OPTION_REMAINING, 0, 0, G_OPTION_ARG_FILENAME_ARRAY, + &option_json_filenames, + N_("JSON files to validate"), N_("JSON-FILE [JSON-FILE …]") }, + { NULL, }, +}; + +int +main (int argc, char *argv[]) +{ + GOptionContext *context = NULL; /* owned */ + ExitStatus retval = EXIT_OK; + guint i, j; + GPtrArray/**/ *json_files = NULL; /* owned */ + GPtrArray/**/ *schemas = NULL; /* owned */ + GError *error = NULL; + +#if !GLIB_CHECK_VERSION (2, 35, 0) + g_type_init (); +#endif + + setlocale (LC_ALL, ""); + + /* Redirect debug output to stderr so that stdout is purely useful. */ + g_log_set_default_handler (wbl_log, NULL); + + /* Command line parsing. */ + context = g_option_context_new (_("— validate JSON documents")); + g_option_context_set_summary (context, + _("Validate one or more JSON documents, " + "checking for well-formedness. If JSON " + "Schemas are provided by using " + "--schema one or more times, all JSON " + "documents will be validated against " + "all schemas.\n\nRead about JSON " + "Schema here: " + "http://json-schema.org/.")); + g_option_context_add_main_entries (context, entries, PACKAGE_NAME); + + if (!g_option_context_parse (context, &argc, &argv, &error)) { + gchar *message; + + message = g_strdup_printf (_("Option parsing failed: %s"), + error->message); + g_printerr ("%s: %s\n", argv[0], message); + g_free (message); + + g_clear_error (&error); + + retval = EXIT_INVALID_OPTIONS; + goto done; + } + + /* Load the JSON files. */ + json_files = g_ptr_array_new_with_free_func ((GDestroyNotify) g_object_unref); + + for (i = 0; + option_json_filenames != NULL && option_json_filenames[i] != NULL; + i++) { + JsonParser *parser = NULL; /* owned */ + + parser = json_parser_new (); + json_parser_load_from_file (parser, option_json_filenames[i], + &error); + + if (error != NULL) { + if (!option_quiet) { + gchar *message; + + /* The filename is specified in @error. */ + message = g_strdup_printf (_("Invalid JSON document: %s"), + error->message); + g_printerr ("%s: %s\n", argv[0], message); + g_free (message); + } + + if (retval == EXIT_OK) { + retval = EXIT_INVALID_JSON; + } + g_clear_error (&error); + + if (!option_ignore_errors) { + goto done; + } else { + g_object_unref (parser); + continue; + } + } + + g_object_set_data (G_OBJECT (parser), + "filename", option_json_filenames[i]); + g_ptr_array_add (json_files, parser); /* transfer */ + } + + /* Load the schemas. */ + schemas = g_ptr_array_new_with_free_func ((GDestroyNotify) g_object_unref); + + for (i = 0; + option_schema_filenames != NULL && option_schema_filenames[i] != NULL; + i++) { + WblSchema *schema = NULL; /* owned */ + + schema = wbl_schema_new (); + wbl_schema_load_from_file (schema, option_schema_filenames[i], + &error); + + if (error != NULL) { + if (!option_quiet) { + gchar *message; + + message = g_strdup_printf (_("Invalid JSON schema ‘%s’: %s"), + option_schema_filenames[i], + error->message); + g_printerr ("%s: %s\n", argv[0], message); + g_free (message); + } + + if (retval == EXIT_OK) { + retval = EXIT_INVALID_SCHEMA; + } + g_clear_error (&error); + + if (!option_ignore_errors) { + goto done; + } else { + g_object_unref (schema); + continue; + } + } + + g_object_set_data (G_OBJECT (schema), + "filename", option_schema_filenames[i]); + g_ptr_array_add (schemas, schema); /* transfer */ + } + + /* Validate each of the JSON files against each of the schemas. */ + for (i = 0; i < json_files->len; i++) { + for (j = 0; j < schemas->len; j++) { + JsonParser *parser; /* unowned */ + JsonNode *instance; /* unowned */ + WblSchema *schema; /* unowned */ + const gchar *json_filename, *schema_filename; + + parser = json_files->pdata[i]; + instance = json_parser_get_root (parser); + schema = schemas->pdata[j]; + + json_filename = g_object_get_data (G_OBJECT (parser), + "filename"); + schema_filename = g_object_get_data (G_OBJECT (schema), + "filename"); + + if (!option_quiet) { + gchar *message; + + message = g_strdup_printf (_("Validating ‘%s’ against ‘%s’…"), + json_filename, + schema_filename); + g_print ("%s ", message); + g_free (message); + } + + /* Try applying the schema to the JSON. */ + wbl_schema_apply (schema, instance, &error); + + if (!option_quiet) { + g_print ("%s", + (error == NULL) ? _("OK") : _("FAIL")); + g_print ("\n"); + } + + if (error != NULL) { + if (!option_quiet) { + gchar *message; + + message = g_strdup_printf (_("Validation error for ‘%s’ against ‘%s’: %s"), + json_filename, + schema_filename, + error->message); + g_printerr ("%s: %s\n", + argv[0], message); + g_free (message); + } + + if (retval == EXIT_OK) { + retval = EXIT_SCHEMA_VALIDATION_FAILED; + } + g_clear_error (&error); + + if (!option_ignore_errors) { + goto done; + } + } + } + } + +done: + if (context != NULL) { + g_option_context_free (context); + } + if (json_files != NULL) { + g_ptr_array_unref (json_files); + } + if (schemas != NULL) { + g_ptr_array_unref (schemas); + } + + return retval; +} diff --git a/pool/shard004/C/0099435_s5p_mfc_cmd_v6.c b/pool/shard004/C/0099435_s5p_mfc_cmd_v6.c new file mode 100644 index 0000000000000000000000000000000000000000..7b3de1cfc847e21487c06ab3b99fc8032d8a3339 --- /dev/null +++ b/pool/shard004/C/0099435_s5p_mfc_cmd_v6.c @@ -0,0 +1,147 @@ +/* + * linux/drivers/media/video/exynos/mfc/s5p_mfc_cmd_v6.c + * + * Copyright (c) 2010 Samsung Electronics Co., Ltd. + * http://www.samsung.com/ + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + */ + +#include "s5p_mfc_common.h" + +#include "s5p_mfc_debug.h" +#include "s5p_mfc_reg.h" +#include "s5p_mfc_cmd.h" +#include "s5p_mfc_mem.h" + +int s5p_mfc_cmd_host2risc(int cmd, struct s5p_mfc_cmd_args *args) +{ + mfc_debug(2, "Issue the command: %d\n", cmd); + + /* Reset RISC2HOST command */ + s5p_mfc_write_reg(0x0, S5P_FIMV_RISC2HOST_CMD); + + /* Issue the command */ + s5p_mfc_write_reg(cmd, S5P_FIMV_HOST2RISC_CMD); + s5p_mfc_write_reg(0x1, S5P_FIMV_HOST2RISC_INT); + + return 0; +} + +int s5p_mfc_sys_init_cmd(struct s5p_mfc_dev *dev) +{ + struct s5p_mfc_cmd_args h2r_args; + struct s5p_mfc_buf_size_v6 *buf_size; + int ret; + + mfc_debug_enter(); + + if (!dev) { + mfc_err("no mfc device to run\n"); + return -EINVAL; + } + + buf_size = dev->variant->buf_size->buf; + + s5p_mfc_write_reg(dev->ctx_buf.ofs, S5P_FIMV_CONTEXT_MEM_ADDR); + s5p_mfc_write_reg(buf_size->dev_ctx, S5P_FIMV_CONTEXT_MEM_SIZE); + if (IS_MFCv7X(dev)) { + s5p_mfc_write_reg(dev->dis_shm_buf.ofs, + S5P_FIMV_DIS_SHARED_MEM_ADDR); + mfc_debug(2, "Setting shared memory = 0x%x\n", + (unsigned int)dev->dis_shm_buf.ofs); + } + + ret = s5p_mfc_cmd_host2risc(S5P_FIMV_H2R_CMD_SYS_INIT, &h2r_args); + + mfc_debug_leave(); + + return ret; +} + +int s5p_mfc_sleep_cmd(struct s5p_mfc_dev *dev) +{ + struct s5p_mfc_cmd_args h2r_args; + int ret; + + mfc_debug_enter(); + + memset(&h2r_args, 0, sizeof(struct s5p_mfc_cmd_args)); + + ret = s5p_mfc_cmd_host2risc(S5P_FIMV_H2R_CMD_SLEEP, &h2r_args); + + mfc_debug_leave(); + + return ret; +} + +int s5p_mfc_wakeup_cmd(struct s5p_mfc_dev *dev) +{ + struct s5p_mfc_cmd_args h2r_args; + int ret; + + mfc_debug_enter(); + + memset(&h2r_args, 0, sizeof(struct s5p_mfc_cmd_args)); + + ret = s5p_mfc_cmd_host2risc(S5P_FIMV_H2R_CMD_WAKEUP, &h2r_args); + + mfc_debug_leave(); + + return ret; +} + +/* Open a new instance and get its number */ +int s5p_mfc_open_inst_cmd(struct s5p_mfc_ctx *ctx) +{ + struct s5p_mfc_cmd_args h2r_args; + struct s5p_mfc_dec *dec; + int ret; + + mfc_debug_enter(); + + if (!ctx) { + mfc_err("no mfc context to run\n"); + return -EINVAL; + } + + dec = ctx->dec_priv; + mfc_debug(2, "Requested codec mode: %d\n", ctx->codec_mode); + + s5p_mfc_write_reg(ctx->codec_mode, S5P_FIMV_CODEC_TYPE); + s5p_mfc_write_reg(ctx->ctx.ofs, S5P_FIMV_CONTEXT_MEM_ADDR); + s5p_mfc_write_reg(ctx->ctx_buf_size, S5P_FIMV_CONTEXT_MEM_SIZE); + if (ctx->type == MFCINST_DECODER) + s5p_mfc_write_reg(dec->crc_enable, S5P_FIMV_D_CRC_CTRL); + + ret = s5p_mfc_cmd_host2risc(S5P_FIMV_H2R_CMD_OPEN_INSTANCE, &h2r_args); + + mfc_debug_leave(); + + return ret; +} + +/* Close instance */ +int s5p_mfc_close_inst_cmd(struct s5p_mfc_ctx *ctx) +{ + struct s5p_mfc_cmd_args h2r_args; + int ret = 0; + + mfc_debug_enter(); + + if (ctx->state != MFCINST_FREE) { + s5p_mfc_write_reg(ctx->inst_no, S5P_FIMV_INSTANCE_ID); + + ret = s5p_mfc_cmd_host2risc(S5P_FIMV_H2R_CMD_CLOSE_INSTANCE, + &h2r_args); + } else { + ret = -EINVAL; + } + + mfc_debug_leave(); + + return ret; +} diff --git a/pool/shard004/C/0099437_ffi.c b/pool/shard004/C/0099437_ffi.c new file mode 100644 index 0000000000000000000000000000000000000000..dde6daa1d3fb11667853385c17e1d084c0110731 --- /dev/null +++ b/pool/shard004/C/0099437_ffi.c @@ -0,0 +1,98 @@ +/* + * Copyright 2014-2016 Samsung Research America, 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 + + +//extern object_map* console_table; + +#ifdef FALSE +extern object_map* document_table; + +extern object_map* htmlelement_table; + +object_t* alloc_wrapper(int slots) { + return (object_t*)MEM_ALLOC(sizeof(object_map*)+slots*sizeof(value_t*)); +} + +extern void* __document_getElementById(char*); + +// TODO: Note we may create n wrappers for n lookups of the same node. +// Each will give consistent views, though, since they each just bounce through the FFI +object_t* document_getElementById(object_t* this, char* id) { + void* handle = __document_getElementById(id); + // Allocate wrapper with extra unindexed slot for the + // hidden handle rep + object_t* wrapper = alloc_wrapper(3); // TODO: shouldn't hardcode # of members... + wrapper->vtbl = htmlelement_table; + // TODO: refactor this so we're not hardcoding object layouts in random places + wrapper->fields[0] = handle; // TODO: storing an lval where most code expects rval... + wrapper->fields[1] = innerHTML___get; + wrapper->fields[2] = innerHTML___set; + return wrapper; +} + +object_t __ffi_document = { + .vtbl = document_table, + .fields = { document_getHTMLElementById } +}; + +object_t __ffi_htmlelement = { + .vtbl = htmlelement_table, + .fields = { htmlelement_innerHTML___set, + htmlelement_innerHTML___get } +}; + +#endif + +extern void __console_log(char*); +extern void __console_error(char*); +extern void __console_assert(bool b); + +void console_log(env_t env, object_t* this, char* str) { + __console_log(str); +} +void console_error(env_t env, object_t* this, char* str) { + __console_error(str); +} +void console_assert(env_t env, object_t* this, bool b) { + __console_assert(b); +} +// TODO: everything from here down could be shared between native and web +// TODO: The native backend declares these boxes as value_t's, but if you cast a function pointer to +// a value_t, emcc complains that it's not a compile-time constant, while clang happily accepts +// it... +// TODO: asm.js is 32-bit, value_t's are 64-bit. Bad things will happen if these are overwritten +// --- allocate some extra space +struct { env_t env; void (*func)(env_t, object_t*, char*); } console_log_clos = { NULL, console_log }; +struct { env_t env; void (*func)(env_t, object_t*, bool); } console_assert_clos = { NULL, console_assert }; +struct { env_t env; void (*func)(env_t, object_t*, char*); } console_error_clos = { NULL, console_error }; +struct { env_t env; void (*func)(env_t, object_t*, char*); } console_warn_clos = { NULL, console_error }; + +struct { env_t env; void (*func)(env_t, object_t*, char*); } *console_log_box = &console_log_clos; +struct { env_t env; void (*func)(env_t, object_t*, bool); } *console_assert_box = &console_assert_clos; +struct { env_t env; void (*func)(env_t, object_t*, char*); } *console_error_box = &console_error_clos; +struct { env_t env; void (*func)(env_t, object_t*, char*); } *console_warn_box = &console_error_clos; + +extern object_map console_table; +object_t __ffi_console = { + .vtbl = &console_table, + .fields = { &console_log_box, + &console_assert_box, + &console_error_box, + &console_warn_box } +}; diff --git a/pool/shard004/C/0099450_fuzz_memory.c b/pool/shard004/C/0099450_fuzz_memory.c new file mode 100644 index 0000000000000000000000000000000000000000..8778869893181a4dbf4c10942430dbf7ae347c5f --- /dev/null +++ b/pool/shard004/C/0099450_fuzz_memory.c @@ -0,0 +1,44 @@ +#include "ifuzz.h" + +static char *ptr_list[MAX_HEAP_STRINGS]; + +void +rfree () +{ + int ix = 0; + while (ptr_list[ix] && (ix < MAX_HEAP_STRINGS)) + { + free (ptr_list[ix]); + ptr_list[ix++] = NULL; + } + return; +} + + +/* malloc and register some heap space */ +void * +rmalloc (size_t size) +{ + int ix = 0; + void *ptr; + if (!size) + return NULL; + + if (!(ptr = malloc (size))) + { + fprintf (stderr, "FATAL ERROR: OUT OF MEMORY IN RMALLOC\n"); + exit (-1); + } + while (ptr_list[ix] && (ix < MAX_HEAP_STRINGS)) + ix++; + if (ix < MAX_HEAP_STRINGS) + ptr_list[ix] = ptr; + else + { + fprintf (stderr, "FATAL ERROR: TOO MANY HEAP BASED FUZZ STRINGS.\n"); + fprintf (stderr, + "TRY ADJUSTING 'MAX_HEAP_STRINGS' OR JUST DON'T BE SUCH A MANIAC ALL THE TIME\n"); + exit (-1); + } + return ptr; +} diff --git a/pool/shard004/C/0099452_devbell.c b/pool/shard004/C/0099452_devbell.c new file mode 100644 index 0000000000000000000000000000000000000000..264f648002c17d8acec8c534d0cf20450e5635b6 --- /dev/null +++ b/pool/shard004/C/0099452_devbell.c @@ -0,0 +1,150 @@ +/************************************************************ + +Copyright 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. + +Copyright 1989 by Hewlett-Packard Company, Palo Alto, California. + + 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 Hewlett-Packard not be +used in advertising or publicity pertaining to distribution of the +software without specific, written prior permission. + +HEWLETT-PACKARD DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING +ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL +HEWLETT-PACKARD 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. + +********************************************************/ + +/*********************************************************************** + * + * Extension function to change the keyboard device. + * + */ + +#define NEED_EVENTS +#define NEED_REPLIES +#ifdef HAVE_DIX_CONFIG_H +#include +#endif + +#include "inputstr.h" /* DeviceIntPtr */ +#include +#include +#include "exglobals.h" + +#include "devbell.h" + +/*********************************************************************** + * + * This procedure is invoked to swap the request bytes if the server and + * client have a different byte order. + * + */ + +int +SProcXDeviceBell(ClientPtr client) +{ + char n; + + REQUEST(xDeviceBellReq); + swaps(&stuff->length, n); + return (ProcXDeviceBell(client)); +} + +/*********************************************************************** + * + * This procedure rings a bell on an extension device. + * + */ + +int +ProcXDeviceBell(ClientPtr client) +{ + DeviceIntPtr dev; + KbdFeedbackPtr k; + BellFeedbackPtr b; + int rc, base; + int newpercent; + CARD8 class; + pointer ctrl; + BellProcPtr proc; + + REQUEST(xDeviceBellReq); + REQUEST_SIZE_MATCH(xDeviceBellReq); + + rc = dixLookupDevice(&dev, stuff->deviceid, client, DixBellAccess); + if (rc != Success) { + client->errorValue = stuff->deviceid; + return rc; + } + + if (stuff->percent < -100 || stuff->percent > 100) { + client->errorValue = stuff->percent; + return BadValue; + } + if (stuff->feedbackclass == KbdFeedbackClass) { + for (k = dev->kbdfeed; k; k = k->next) + if (k->ctrl.id == stuff->feedbackid) + break; + if (!k) { + client->errorValue = stuff->feedbackid; + return BadValue; + } + base = k->ctrl.bell; + proc = k->BellProc; + ctrl = (pointer) & (k->ctrl); + class = KbdFeedbackClass; + } else if (stuff->feedbackclass == BellFeedbackClass) { + for (b = dev->bell; b; b = b->next) + if (b->ctrl.id == stuff->feedbackid) + break; + if (!b) { + client->errorValue = stuff->feedbackid; + return BadValue; + } + base = b->ctrl.percent; + proc = b->BellProc; + ctrl = (pointer) & (b->ctrl); + class = BellFeedbackClass; + } else { + client->errorValue = stuff->feedbackclass; + return BadValue; + } + newpercent = (base * stuff->percent) / 100; + if (stuff->percent < 0) + newpercent = base + newpercent; + else + newpercent = base - newpercent + stuff->percent; + (*proc) (newpercent, dev, ctrl, class); + + return Success; +} diff --git a/pool/shard004/C/0099455_bug-regex8.c b/pool/shard004/C/0099455_bug-regex8.c new file mode 100644 index 0000000000000000000000000000000000000000..e39ad59759eed3df4db6bb39d82fa1e9d4ec42bd --- /dev/null +++ b/pool/shard004/C/0099455_bug-regex8.c @@ -0,0 +1,88 @@ +/* Test for the STOP parameter of re_match_2 and re_search_2. + Copyright (C) 2002 Free Software Foundation, Inc. + This file is part of the GNU C Library. + Contributed by Stepan Kasal , 2002. + + 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., 51 Franklin Street, Fifth Floor, Boston, MA + 02110-1301 USA. */ + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +#include +#include +#include +#include +#include +#include + + +int +main (void) +{ + struct re_pattern_buffer regex; + const char *s; + int match[4]; + + memset (®ex, '\0', sizeof (regex)); + + s = re_compile_pattern ("xy$", 3, ®ex); + if (s != NULL) + { + puts ("failed to compile pattern \"xy$\""); + return 1; + } + else + match[0] = re_match_2(®ex,"xyz",3,NULL,0,0,NULL,2); + + free (regex.buffer); + memset (®ex, '\0', sizeof (regex)); + + s = re_compile_pattern ("xy\\>", 4, ®ex); + if (s != NULL) + { + puts ("failed to compile pattern \"xy\\>\""); + return 1; + } + else + match[1] = re_search_2(®ex,"xyz",3,NULL,0,0,2,NULL,2); + + free (regex.buffer); + memset (®ex, '\0', sizeof (regex)); + + s = re_compile_pattern ("xy \\<", 5, ®ex); + if (s != NULL) + { + puts ("failed to compile pattern \"xy \\<\""); + return 1; + } + else + { + match[2] = re_match_2(®ex,"xy ",4,NULL,0,0,NULL,3); + match[3] = re_match_2(®ex,"xy z",4,NULL,0,0,NULL,3); + } + + if (match[0] != -1 || match[1] != -1 || match[2] != -1 || match[3] != 3) + { + printf ("re_{match,search}_2 returned %d,%d,%d,%d, expected -1,-1,-1,3\n", + match[0], match[1], match[2], match[3]); + return 1; + } + + puts (" -> OK"); + + return 0; +} diff --git a/pool/shard004/C/0099462_cmplxdivide.c b/pool/shard004/C/0099462_cmplxdivide.c new file mode 100644 index 0000000000000000000000000000000000000000..b340f04d8873c5082711a811975cd155b73e1d26 --- /dev/null +++ b/pool/shard004/C/0099462_cmplxdivide.c @@ -0,0 +1,82 @@ +// 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. + +// gcc '-std=c99' cmplxdivide.c && a.out >cmplxdivide1.go + +#include +#include +#include +#include + +#define nelem(x) (sizeof(x)/sizeof((x)[0])) + +double f[] = { + 0, + 1, + -1, + 2, + NAN, + INFINITY, + -INFINITY, +}; + +char* +fmt(double g) +{ + static char buf[10][30]; + static int n; + char *p; + + p = buf[n++]; + if(n == 10) + n = 0; + sprintf(p, "%g", g); + if(strcmp(p, "-0") == 0) + strcpy(p, "negzero"); + return p; +} + +int +iscnan(double complex d) +{ + return !isinf(creal(d)) && !isinf(cimag(d)) && (isnan(creal(d)) || isnan(cimag(d))); +} + +double complex zero; // attempt to hide zero division from gcc + +int +main(void) +{ + int i, j, k, l; + double complex n, d, q; + + printf("// # generated by cmplxdivide.c\n"); + printf("\n"); + printf("package main\n"); + printf("var tests = []Test{\n"); + for(i=0; i +#include +#include "bfd.h" +#include "elf/tilepro.h" +#include "elf-bfd.h" +#include "dis-asm.h" +#include "opcode/tilepro.h" + + +#define TREG_ZERO 63 + +static int +contains_insn (tilepro_mnemonic expected_mnemonic, + int expected_first_operand, + int expected_second_operand, + bfd_vma memaddr, + int *last_operand_ret, + disassemble_info *info) +{ + struct tilepro_decoded_instruction + decoded[TILEPRO_MAX_INSTRUCTIONS_PER_BUNDLE]; + bfd_byte opbuf[TILEPRO_BUNDLE_SIZE_IN_BYTES]; + int i, num_instructions; + + if ((*info->read_memory_func) (memaddr, opbuf, + TILEPRO_BUNDLE_SIZE_IN_BYTES, info) != 0) + /* If we cannot even read the memory, it obviously does not have the + instruction for which we are looking. */ + return 0; + + /* Parse the instructions in the bundle. */ + num_instructions = parse_insn_tilepro (bfd_getl64 (opbuf), memaddr, decoded); + + for (i = 0; i < num_instructions; i++) + { + const struct tilepro_opcode *opcode = decoded[i].opcode; + + if (opcode->mnemonic != expected_mnemonic) + continue; + + if (expected_first_operand != -1 + && decoded[i].operand_values[0] != expected_first_operand) + continue; + + if (expected_second_operand != -1 + && decoded[i].operand_values[1] != expected_second_operand) + continue; + + *last_operand_ret = decoded[i].operand_values[opcode->num_operands - 1]; + return 1; + } + + /* No match. */ + return 0; +} + + +int +print_insn_tilepro (bfd_vma memaddr, disassemble_info *info) +{ + struct tilepro_decoded_instruction + decoded[TILEPRO_MAX_INSTRUCTIONS_PER_BUNDLE]; + bfd_byte opbuf[TILEPRO_BUNDLE_SIZE_IN_BYTES]; + int status, i, num_instructions, num_printed; + tilepro_mnemonic padding_mnemonic; + + status = (*info->read_memory_func) (memaddr, opbuf, + TILEPRO_BUNDLE_SIZE_IN_BYTES, info); + if (status != 0) + { + (*info->memory_error_func) (status, memaddr, info); + return -1; + } + + info->bytes_per_line = TILEPRO_BUNDLE_SIZE_IN_BYTES; + info->bytes_per_chunk = TILEPRO_BUNDLE_SIZE_IN_BYTES; + info->octets_per_byte = 1; + info->display_endian = BFD_ENDIAN_LITTLE; + + /* Parse the instructions in the bundle. */ + num_instructions = parse_insn_tilepro (bfd_getl64 (opbuf), memaddr, decoded); + + /* Print the instructions in the bundle. */ + info->fprintf_func (info->stream, "{ "); + num_printed = 0; + + /* Determine which nop opcode is used for padding and should be skipped. */ + padding_mnemonic = TILEPRO_OPC_FNOP; + for (i = 0; i < num_instructions; i++) + { + if (!decoded[i].opcode->can_bundle) + { + /* Instructions that cannot be bundled are padded out with nops, + rather than fnops. Displaying them is always clutter. */ + padding_mnemonic = TILEPRO_OPC_NOP; + break; + } + } + + for (i = 0; i < num_instructions; i++) + { + const struct tilepro_opcode *opcode = decoded[i].opcode; + const char *name; + int j; + + /* Do not print out fnops, unless everything is an fnop, in + which case we will print out just the last one. */ + if (opcode->mnemonic == padding_mnemonic + && (num_printed > 0 || i + 1 < num_instructions)) + continue; + + if (num_printed > 0) + info->fprintf_func (info->stream, " ; "); + ++num_printed; + + name = opcode->name; + if (name == NULL) + name = ""; + info->fprintf_func (info->stream, "%s", name); + + for (j = 0; j < opcode->num_operands; j++) + { + int num; + const struct tilepro_operand *op; + const char *spr_name; + + if (j > 0) + info->fprintf_func (info->stream, ","); + info->fprintf_func (info->stream, " "); + + num = decoded[i].operand_values[j]; + + op = decoded[i].operands[j]; + switch (op->type) + { + case TILEPRO_OP_TYPE_REGISTER: + info->fprintf_func (info->stream, "%s", + tilepro_register_names[num]); + break; + + case TILEPRO_OP_TYPE_SPR: + spr_name = get_tilepro_spr_name(num); + if (spr_name != NULL) + info->fprintf_func (info->stream, "%s", spr_name); + else + info->fprintf_func (info->stream, "%d", num); + break; + + case TILEPRO_OP_TYPE_IMMEDIATE: + { + bfd_vma addr = 0; + int found_addr = 0; + int addr_piece; + + switch (opcode->mnemonic) + { + case TILEPRO_OPC_ADDLI: + if (contains_insn (TILEPRO_OPC_AULI, + decoded[i].operand_values[1], + TREG_ZERO, + memaddr - TILEPRO_BUNDLE_SIZE_IN_BYTES, + &addr_piece, + info)) + { + addr = num + (addr_piece << 16); + found_addr = 1; + } + break; + + case TILEPRO_OPC_AULI: + if (contains_insn (TILEPRO_OPC_MOVELI, + decoded[i].operand_values[1], + -1, + memaddr - TILEPRO_BUNDLE_SIZE_IN_BYTES, + &addr_piece, + info)) + { + addr = (num << 16) + addr_piece; + found_addr = 1; + } + break; + + default: + /* Operand does not look like a constructed address. */ + break; + } + + info->fprintf_func (info->stream, "%d", num); + + if (found_addr) + { + info->fprintf_func (info->stream, " /* "); + info->print_address_func (addr, info); + info->fprintf_func (info->stream, " */"); + } + } + break; + + case TILEPRO_OP_TYPE_ADDRESS: + info->print_address_func ((bfd_vma)(unsigned int) num, info); + break; + + default: + abort (); + } + } + } + info->fprintf_func (info->stream, " }"); + + return TILEPRO_BUNDLE_SIZE_IN_BYTES; +} diff --git a/pool/shard004/C/0099489_strsep.c b/pool/shard004/C/0099489_strsep.c new file mode 100644 index 0000000000000000000000000000000000000000..a2abb49e42ec20772f5ba127c4f013fb9c4c54ae --- /dev/null +++ b/pool/shard004/C/0099489_strsep.c @@ -0,0 +1,57 @@ +/* Copyright (C) 2004, 2007, 2009-2015 Free Software Foundation, Inc. + + Written by Yoann Vandoorselaere . + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3, or (at your option) + any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, see . */ + +#ifdef HAVE_CONFIG_H +# include +#endif + +/* Specification. */ +#include + +char * +strsep (char **stringp, const char *delim) +{ + char *start = *stringp; + char *ptr; + + if (start == NULL) + return NULL; + + /* Optimize the case of no delimiters. */ + if (delim[0] == '\0') + { + *stringp = NULL; + return start; + } + + /* Optimize the case of one delimiter. */ + if (delim[1] == '\0') + ptr = strchr (start, delim[0]); + else + /* The general case. */ + ptr = strpbrk (start, delim); + if (ptr == NULL) + { + *stringp = NULL; + return start; + } + + *ptr = '\0'; + *stringp = ptr + 1; + + return start; +} diff --git a/pool/shard004/C/0099491_pm_rc6_residency.c b/pool/shard004/C/0099491_pm_rc6_residency.c new file mode 100644 index 0000000000000000000000000000000000000000..9203d2faf543f50648621d08c2a7f9821a61aa6a --- /dev/null +++ b/pool/shard004/C/0099491_pm_rc6_residency.c @@ -0,0 +1,218 @@ +/* + * Copyright © 2012 Intel Corporation + * + * 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. + * + * Authors: + * Ben Widawsky + * + */ + +#define _GNU_SOURCE +#include +#include +#include +#include +#include + +#include "drmtest.h" +#include "intel_chipset.h" + +#define SLEEP_DURATION 3000 // in milliseconds +#define CODE_TIME 50 // in microseconfs + +#define RC6_ENABLED 1 +#define RC6P_ENABLED 2 +#define RC6PP_ENABLED 4 + +struct residencies { + int rc6; + int media_rc6; + int rc6p; + int rc6pp; +}; + +static unsigned int readit(const char *path) +{ + unsigned int ret; + int scanned; + + FILE *file; + file = fopen(path, "r"); + igt_assert(file); + scanned = fscanf(file, "%u", &ret); + igt_assert_eq(scanned, 1); + + fclose(file); + + return ret; +} + +static unsigned long get_rc6_enabled_mask(void) +{ + unsigned long rc6_mask; + char *path; + int ret; + + ret = asprintf(&path, "/sys/class/drm/card%d/power/rc6_enable", + drm_get_card()); + igt_assert_neq(ret, -1); + rc6_mask = readit(path); + free(path); + + return rc6_mask; +} + +static int read_rc6_residency(const char *name_of_rc6_residency) +{ + unsigned int residency; + const int device = drm_get_card(); + char *path ; + int ret; + + ret = asprintf(&path, "/sys/class/drm/card%d/power/%s_residency_ms", + device, name_of_rc6_residency); + igt_assert_neq(ret, -1); + residency = readit(path); + free(path); + + return residency; +} + +static void residency_accuracy(unsigned int diff, + const char *name_of_rc6_residency) +{ + double ratio; + + ratio = (double)diff / (SLEEP_DURATION + CODE_TIME); + + igt_info("Residency in %s or deeper state: %u ms (ratio to expected duration: %.02f)\n", + name_of_rc6_residency, diff, ratio); + igt_assert_f(ratio > 0.9 && ratio <= 1, + "Sysfs RC6 residency counter is inaccurate.\n"); +} + +static void read_residencies(int devid, unsigned int rc6_mask, + struct residencies *res) +{ + if (rc6_mask & RC6_ENABLED) + res->rc6 = read_rc6_residency("rc6"); + + if ((rc6_mask & RC6_ENABLED) && + (IS_VALLEYVIEW(devid) || IS_CHERRYVIEW(devid))) + res->media_rc6 = read_rc6_residency("media_rc6"); + + if (rc6_mask & RC6P_ENABLED) + res->rc6p = read_rc6_residency("rc6p"); + + if (rc6_mask & RC6PP_ENABLED) + res->rc6pp = read_rc6_residency("rc6pp"); +} + +static void measure_residencies(int devid, unsigned int rc6_mask, + struct residencies *res) +{ + struct residencies start = { }; + struct residencies end = { }; + int retry; + + if (!rc6_mask) + return; + + /* + * For some reason my ivb isn't idle even after syncing up with the gpu. + * Let's add a sleep just to make it happy. + */ + sleep(8); + + /* + * Retry in case of counter wrap-around. We simply re-run the + * measurement, since the valid counter range is different on + * different platforms and so fixing it up would be non-trivial. + */ + for (retry = 0; retry < 2; retry++) { + read_residencies(devid, rc6_mask, &start); + sleep(SLEEP_DURATION / 1000); + read_residencies(devid, rc6_mask, &end); + + if (end.rc6 >= start.rc6 && end.media_rc6 >= start.media_rc6 && + end.rc6p >= start.rc6p && end.rc6pp >= start.rc6pp) + break; + } + igt_assert_f(retry < 2, "residency values are not consistent\n"); + + res->rc6 = end.rc6 - start.rc6; + res->rc6p = end.rc6p - start.rc6p; + res->rc6pp = end.rc6pp - start.rc6pp; + res->media_rc6 = end.media_rc6 - start.media_rc6; + + /* + * For the purposes of this test case we want a given residency value + * to include the time spent in the corresponding RC state _and_ also + * the time spent in any enabled deeper states. So for example if any + * of RC6P or RC6PP is enabled we want the time spent in these states + * to be also included in the RC6 residency value. The kernel reported + * residency values are exclusive, so add up things here. + */ + res->rc6p += res->rc6pp; + res->rc6 += res->rc6p; +} + +igt_main +{ + unsigned int rc6_mask; + int fd; + int devid = 0; + struct residencies res; + + igt_skip_on_simulation(); + + /* Use drm_open_any to verify device existence */ + igt_fixture { + fd = drm_open_any(); + devid = intel_get_drm_devid(fd); + close(fd); + + rc6_mask = get_rc6_enabled_mask(); + measure_residencies(devid, rc6_mask, &res); + } + + igt_subtest("rc6-accuracy") { + igt_skip_on(!(rc6_mask & RC6_ENABLED)); + + residency_accuracy(res.rc6, "rc6"); + } + igt_subtest("media-rc6-accuracy") { + igt_skip_on(!((rc6_mask & RC6_ENABLED) && + (IS_VALLEYVIEW(devid) || IS_CHERRYVIEW(devid)))); + + residency_accuracy(res.media_rc6, "media_rc6"); + } + igt_subtest("rc6p-accuracy") { + igt_skip_on(!(rc6_mask & RC6P_ENABLED)); + + residency_accuracy(res.rc6p, "rc6p"); + } + igt_subtest("rc6pp-accuracy") { + igt_skip_on(!(rc6_mask & RC6PP_ENABLED)); + + residency_accuracy(res.rc6pp, "rc6pp"); + } +} diff --git a/pool/shard004/C/0099495_mmap.c b/pool/shard004/C/0099495_mmap.c new file mode 100644 index 0000000000000000000000000000000000000000..c70b3d8dea066a1cd68f398fc6ebf8cf657e03b8 --- /dev/null +++ b/pool/shard004/C/0099495_mmap.c @@ -0,0 +1,188 @@ +/* + * linux/arch/s390/mm/mmap.c + * + * flexible mmap layout support + * + * Copyright 2003-2004 Red Hat Inc., Durham, North Carolina. + * All Rights Reserved. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. 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 + * + * + * Started by Ingo Molnar + */ + +#include +#include +#include +#include +#include +#include +#include + +static unsigned long stack_maxrandom_size(void) +{ + if (!(current->flags & PF_RANDOMIZE)) + return 0; + if (current->personality & ADDR_NO_RANDOMIZE) + return 0; + return STACK_RND_MASK << PAGE_SHIFT; +} + +/* + * Top of mmap area (just below the process stack). + * + * Leave at least a ~32 MB hole. + */ +#define MIN_GAP (32*1024*1024) +#define MAX_GAP (STACK_TOP/6*5) + +static inline int mmap_is_legacy(void) +{ + if (current->personality & ADDR_COMPAT_LAYOUT) + return 1; + if (rlimit(RLIMIT_STACK) == RLIM_INFINITY) + return 1; + return sysctl_legacy_va_layout; +} + +static unsigned long mmap_rnd(void) +{ + if (!(current->flags & PF_RANDOMIZE)) + return 0; + /* 8MB randomization for mmap_base */ + return (get_random_int() & 0x7ffUL) << PAGE_SHIFT; +} + +static inline unsigned long mmap_base(void) +{ + unsigned long gap = rlimit(RLIMIT_STACK); + + if (gap < MIN_GAP) + gap = MIN_GAP; + else if (gap > MAX_GAP) + gap = MAX_GAP; + gap &= PAGE_MASK; + return STACK_TOP - stack_maxrandom_size() - mmap_rnd() - gap; +} + +#ifndef CONFIG_64BIT + +/* + * This function, called very early during the creation of a new + * process VM image, sets up which VM layout function to use: + */ +void arch_pick_mmap_layout(struct mm_struct *mm) +{ + /* + * Fall back to the standard layout if the personality + * bit is set, or if the expected stack growth is unlimited: + */ + if (mmap_is_legacy()) { + mm->mmap_base = TASK_UNMAPPED_BASE; + mm->get_unmapped_area = arch_get_unmapped_area; + mm->unmap_area = arch_unmap_area; + } else { + mm->mmap_base = mmap_base(); + mm->get_unmapped_area = arch_get_unmapped_area_topdown; + mm->unmap_area = arch_unmap_area_topdown; + } +} +EXPORT_SYMBOL_GPL(arch_pick_mmap_layout); + +#else + +int s390_mmap_check(unsigned long addr, unsigned long len) +{ + int rc; + + if (!is_compat_task() && + len >= TASK_SIZE && TASK_SIZE < (1UL << 53)) { + rc = crst_table_upgrade(current->mm, 1UL << 53); + if (rc) + return rc; + update_mm(current->mm, current); + } + return 0; +} + +static unsigned long +s390_get_unmapped_area(struct file *filp, unsigned long addr, + unsigned long len, unsigned long pgoff, unsigned long flags) +{ + struct mm_struct *mm = current->mm; + unsigned long area; + int rc; + + area = arch_get_unmapped_area(filp, addr, len, pgoff, flags); + if (!(area & ~PAGE_MASK)) + return area; + if (area == -ENOMEM && !is_compat_task() && TASK_SIZE < (1UL << 53)) { + /* Upgrade the page table to 4 levels and retry. */ + rc = crst_table_upgrade(mm, 1UL << 53); + if (rc) + return (unsigned long) rc; + update_mm(mm, current); + area = arch_get_unmapped_area(filp, addr, len, pgoff, flags); + } + return area; +} + +static unsigned long +s390_get_unmapped_area_topdown(struct file *filp, const unsigned long addr, + const unsigned long len, const unsigned long pgoff, + const unsigned long flags) +{ + struct mm_struct *mm = current->mm; + unsigned long area; + int rc; + + area = arch_get_unmapped_area_topdown(filp, addr, len, pgoff, flags); + if (!(area & ~PAGE_MASK)) + return area; + if (area == -ENOMEM && !is_compat_task() && TASK_SIZE < (1UL << 53)) { + /* Upgrade the page table to 4 levels and retry. */ + rc = crst_table_upgrade(mm, 1UL << 53); + if (rc) + return (unsigned long) rc; + update_mm(mm, current); + area = arch_get_unmapped_area_topdown(filp, addr, len, + pgoff, flags); + } + return area; +} +/* + * This function, called very early during the creation of a new + * process VM image, sets up which VM layout function to use: + */ +void arch_pick_mmap_layout(struct mm_struct *mm) +{ + /* + * Fall back to the standard layout if the personality + * bit is set, or if the expected stack growth is unlimited: + */ + if (mmap_is_legacy()) { + mm->mmap_base = TASK_UNMAPPED_BASE; + mm->get_unmapped_area = s390_get_unmapped_area; + mm->unmap_area = arch_unmap_area; + } else { + mm->mmap_base = mmap_base(); + mm->get_unmapped_area = s390_get_unmapped_area_topdown; + mm->unmap_area = arch_unmap_area_topdown; + } +} +EXPORT_SYMBOL_GPL(arch_pick_mmap_layout); + +#endif diff --git a/pool/shard004/C/0099496_position_noncontig.c b/pool/shard004/C/0099496_position_noncontig.c new file mode 100644 index 0000000000000000000000000000000000000000..f579905e6c04d082c973d467a3ec8c7bc8643158 --- /dev/null +++ b/pool/shard004/C/0099496_position_noncontig.c @@ -0,0 +1,253 @@ +/* -*- Mode: C; c-basic-offset:4 ; -*- */ +/* + * Copyright (c) 2004-2007 The University of Tennessee and The University + * of Tennessee Research Foundation. All rights + * reserved. + * Copyright (c) 2011-2013 Cisco Systems, Inc. All rights reserved. + * Copyright (c) 2014 Intel, Inc. All rights reserved. + * $COPYRIGHT$ + * + * Additional copyrights may follow + * + * $HEADER$ + */ + +#include "ompi_config.h" +#include +#include +#if OPAL_USE_STDBOOL_H +#include +#endif + +#include "opal/datatype/opal_convertor.h" +#include "ompi/datatype/ompi_datatype.h" +#include "opal/util/output.h" + +/** + * The purpose of this test is to simulate the multi-network packing and + * unpacking process. The pack operation will happens in-order while the + * will be done randomly. Therefore, before each unpack the correct + * position in the user buffer has to be set. + */ + +static int fragment_size = 113; + +typedef struct { + size_t position; + size_t size; + void* buffer; +} ddt_segment_t; + +static int +create_segments( ompi_datatype_t* datatype, int count, + size_t segment_length, + ddt_segment_t** segments, int* seg_count ) +{ + size_t data_size, total_length, position; + opal_convertor_t* convertor; + int i; + ddt_segment_t* segment; + + ompi_datatype_type_size( datatype, &data_size ); + data_size *= count; + *seg_count = data_size / segment_length; + if( ((*seg_count) * segment_length) != data_size ) + *seg_count += 1; + allocate_segments: + *segments = (ddt_segment_t*)malloc( (*seg_count) * sizeof(ddt_segment_t) ); + + convertor = opal_convertor_create( opal_local_arch, 0 ); + opal_convertor_prepare_for_send( convertor, &(datatype->super), count, NULL ); + + position = 0; + total_length = 0; + for( i = 0; i < (*seg_count); i++ ) { + segment = &((*segments)[i]); + segment->buffer = malloc(segment_length); + segment->position = position; + + /* Find the end of the segment */ + position += segment_length; + opal_convertor_set_position( convertor, &position ); + segment->size = position - segment->position; + total_length += segment->size; + } + OBJ_RELEASE(convertor); + if( total_length != data_size ) { + for( i = 0; i < (*seg_count); i++ ) { + segment = &((*segments)[i]); + free(segment->buffer); + } + free( *segments ); + (*seg_count) += 1; + goto allocate_segments; + } + return 0; +} + +static int +shuffle_segments( ddt_segment_t* segments, int seg_count ) +{ + ddt_segment_t temporary; + int i; + + for( i = 0; i < (seg_count/2); i += 2 ) { + temporary = segments[i]; + segments[i] = segments[seg_count - i - 1]; + segments[seg_count - i - 1] = temporary; + } + return 0; +} + +static int +pack_segments( ompi_datatype_t* datatype, int count, + size_t segment_size, + ddt_segment_t* segments, int seg_count, + void* buffer ) +{ + size_t max_size, position; + opal_convertor_t* convertor; + struct iovec iov; + int i; + uint32_t iov_count; + + convertor = opal_convertor_create( opal_local_arch, 0 ); + opal_convertor_prepare_for_send( convertor, &(datatype->super), count, buffer ); + + for( i = 0; i < seg_count; i++ ) { + iov.iov_len = segments[i].size; + iov.iov_base = segments[i].buffer; + max_size = iov.iov_len; + position = segments[i].position; + opal_convertor_set_position( convertor, &position ); + if( position != segments[i].position ) { + opal_output( 0, "Setting position failed (%lu != %lu)\n", + (unsigned long)segments[i].position, (unsigned long)position ); + break; + } + + iov_count = 1; + opal_convertor_pack( convertor, &iov, &iov_count, &max_size ); + if( max_size != segments[i].size ) { + opal_output( 0, "Amount of packed data do not match (%lu != %lu)\n", + (unsigned long)max_size, (unsigned long)segments[i].size ); + opal_output( 0, "Segment %d position %lu size %lu\n", i, + (unsigned long)segments[i].position, segments[i].size ); + } + } + OBJ_RELEASE(convertor); + return i; +} + +static int +unpack_segments( ompi_datatype_t* datatype, int count, + size_t segment_size, + ddt_segment_t* segments, int seg_count, + void* buffer ) +{ + opal_convertor_t* convertor; + size_t max_size, position; + int i; + uint32_t iov_count; + struct iovec iov; + + convertor = opal_convertor_create( opal_local_arch, 0 ); + opal_convertor_prepare_for_recv( convertor, &(datatype->super), count, buffer ); + + for( i = 0; i < seg_count; i++ ) { + iov.iov_len = segments[i].size; + iov.iov_base = segments[i].buffer; + max_size = iov.iov_len; + + position = segments[i].position; + opal_convertor_set_position( convertor, &position ); + if( position != segments[i].position ) { + opal_output( 0, "Setting position failed (%lu != %lu)\n", + (unsigned long)segments[i].position, (unsigned long)position ); + break; + } + + iov_count = 1; + opal_convertor_unpack( convertor, &iov, &iov_count, &max_size ); + if( max_size != segments[i].size ) { + opal_output( 0, "Amount of unpacked data do not match (%lu != %lu)\n", + (unsigned long)max_size, (unsigned long)segments[i].size ); + opal_output( 0, "Segment %d position %lu size %lu\n", i, + (unsigned long)segments[i].position, segments[i].size ); + } + } + OBJ_RELEASE(convertor); + return 0; +} + +#if (OPAL_ENABLE_DEBUG == 1) && (OPAL_C_HAVE_VISIBILITY == 0) +extern bool opal_unpack_debug; +extern bool opal_pack_debug; +extern bool opal_position_debug ; +#endif /* OPAL_ENABLE_DEBUG */ + +int main( int argc, char* argv[] ) +{ + ddt_segment_t* segments; + int *send_buffer, *recv_buffer; + int i, seg_count, errors; + int show_only_first_error = 1; + ompi_datatype_t* datatype = MPI_DATATYPE_NULL; + +#define NELT (300) + send_buffer = malloc(NELT*sizeof(int)); + recv_buffer = malloc(NELT*sizeof(int)); + for (i = 0; i < NELT; ++i) { + send_buffer[i] = i; + recv_buffer[i] = 0xdeadbeef; + } + + opal_datatype_init(); + ompi_datatype_init(); + + ompi_datatype_create_vector(NELT/2, 1, 2, MPI_INT, &datatype); + ompi_datatype_commit(&datatype); + +#if (OPAL_ENABLE_DEBUG == 1) && (OPAL_C_HAVE_VISIBILITY == 0) + opal_unpack_debug = false; + opal_pack_debug = false; + opal_position_debug = false; +#endif /* OPAL_ENABLE_DEBUG */ + + create_segments( datatype, 1, fragment_size, + &segments, &seg_count ); + + /* shuffle the segments */ + shuffle_segments( segments, seg_count ); + + /* pack the data */ + pack_segments( datatype, 1, fragment_size, segments, seg_count, + send_buffer ); + + /* unpack the data back in the user space (recv buffer) */ + unpack_segments( datatype, 1, fragment_size, segments, seg_count, + recv_buffer ); + + /* And now check the data */ + for( errors = i = 0; i < NELT; i++ ) { + int expected = ((i % 2) ? (int)0xdeadbeef : i); + if (recv_buffer[i] != expected) { + if( (show_only_first_error && (0 == errors)) || + !show_only_first_error ) { + printf("error at index %4d: 0x%08x != 0x%08x\n", i, recv_buffer[i], expected); + } + errors++; + } + } + printf( "Found %d errors\n", errors ); + free(send_buffer); free(recv_buffer); + + for( i = 0; i < seg_count; i++ ) { + free( segments[i].buffer ); + } + free(segments); + + ompi_datatype_finalize(); + + return (0 == errors ? 0 : -1); +} diff --git a/pool/shard004/C/0099504_minicache.c b/pool/shard004/C/0099504_minicache.c new file mode 100644 index 0000000000000000000000000000000000000000..dedf2ab01b2a7984309009130ab50f4e7901d13b --- /dev/null +++ b/pool/shard004/C/0099504_minicache.c @@ -0,0 +1,73 @@ +/* + * linux/arch/arm/mm/minicache.c + * + * Copyright (C) 2001 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. + * + * This handles the mini data cache, as found on SA11x0 and XScale + * processors. When we copy a user page page, we map it in such a way + * that accesses to this page will not touch the main data cache, but + * will be cached in the mini data cache. This prevents us thrashing + * the main data cache on page faults. + */ +#include +#include + +#include +#include +#include + +/* + * 0xffff8000 to 0xffffffff is reserved for any ARM architecture + * specific hacks for copying pages efficiently. + */ +#define minicache_address (0xffff8000) +#define minicache_pgprot __pgprot(L_PTE_PRESENT | L_PTE_YOUNG | \ + L_PTE_CACHEABLE) + +static pte_t *minicache_pte; + +/* + * Note that this is intended to be called only from the copy_user_page + * asm code; anything else will require special locking to prevent the + * mini-cache space being re-used. (Note: probably preempt unsafe). + * + * We rely on the fact that the minicache is 2K, and we'll be pushing + * 4K of data through it, so we don't actually have to specifically + * flush the minicache when we change the mapping. + * + * Note also: assert(PAGE_OFFSET <= virt < high_memory). + * Unsafe: preempt, kmap. + */ +unsigned long map_page_minicache(unsigned long virt) +{ + set_pte(minicache_pte, pfn_pte(__pa(virt) >> PAGE_SHIFT, minicache_pgprot)); + flush_tlb_kernel_page(minicache_address); + + return minicache_address; +} + +static int __init minicache_init(void) +{ + pgd_t *pgd; + pmd_t *pmd; + + spin_lock(&init_mm.page_table_lock); + + pgd = pgd_offset_k(minicache_address); + pmd = pmd_alloc(&init_mm, pgd, minicache_address); + if (!pmd) + BUG(); + minicache_pte = pte_alloc_kernel(&init_mm, pmd, minicache_address); + if (!minicache_pte) + BUG(); + + spin_unlock(&init_mm.page_table_lock); + + return 0; +} + +core_initcall(minicache_init); diff --git a/pool/shard004/C/0099518_h264_mp4toannexb_bsf.c b/pool/shard004/C/0099518_h264_mp4toannexb_bsf.c new file mode 100644 index 0000000000000000000000000000000000000000..a003a1df1d3eb8b9835439b2cf9b975551869fd9 --- /dev/null +++ b/pool/shard004/C/0099518_h264_mp4toannexb_bsf.c @@ -0,0 +1,221 @@ +/* + * H.264 MP4 to Annex B byte stream format filter + * Copyright (c) 2007 Benoit Fouet + * + * This file is part of FFmpeg. + * + * FFmpeg is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * FFmpeg is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with FFmpeg; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + */ + +#include + +#include "libavutil/intreadwrite.h" +#include "libavutil/mem.h" +#include "avcodec.h" + +typedef struct H264BSFContext { + uint8_t length_size; + uint8_t first_idr; + uint8_t idr_sps_pps_seen; + int extradata_parsed; +} H264BSFContext; + +static int alloc_and_copy(uint8_t **poutbuf, int *poutbuf_size, + const uint8_t *sps_pps, uint32_t sps_pps_size, + const uint8_t *in, uint32_t in_size) +{ + uint32_t offset = *poutbuf_size; + uint8_t nal_header_size = offset ? 3 : 4; + int err; + + *poutbuf_size += sps_pps_size + in_size + nal_header_size; + if ((err = av_reallocp(poutbuf, + *poutbuf_size + FF_INPUT_BUFFER_PADDING_SIZE)) < 0) { + *poutbuf_size = 0; + return err; + } + if (sps_pps) + memcpy(*poutbuf + offset, sps_pps, sps_pps_size); + memcpy(*poutbuf + sps_pps_size + nal_header_size + offset, in, in_size); + if (!offset) { + AV_WB32(*poutbuf + sps_pps_size, 1); + } else { + (*poutbuf + offset + sps_pps_size)[0] = + (*poutbuf + offset + sps_pps_size)[1] = 0; + (*poutbuf + offset + sps_pps_size)[2] = 1; + } + + return 0; +} + +static int h264_extradata_to_annexb(AVCodecContext *avctx, const int padding) +{ + uint16_t unit_size; + uint64_t total_size = 0; + uint8_t *out = NULL, unit_nb, sps_done = 0, + sps_seen = 0, pps_seen = 0; + const uint8_t *extradata = avctx->extradata + 4; + static const uint8_t nalu_header[4] = { 0, 0, 0, 1 }; + int length_size = (*extradata++ & 0x3) + 1; // retrieve length coded size + + /* retrieve sps and pps unit(s) */ + unit_nb = *extradata++ & 0x1f; /* number of sps unit(s) */ + if (!unit_nb) { + goto pps; + } else { + sps_seen = 1; + } + + while (unit_nb--) { + int err; + + unit_size = AV_RB16(extradata); + total_size += unit_size + 4; + if (total_size > INT_MAX - padding) { + av_log(avctx, AV_LOG_ERROR, + "Too big extradata size, corrupted stream or invalid MP4/AVCC bitstream\n"); + av_free(out); + return AVERROR(EINVAL); + } + if (extradata + 2 + unit_size > avctx->extradata + avctx->extradata_size) { + av_log(avctx, AV_LOG_ERROR, "Packet header is not contained in global extradata, " + "corrupted stream or invalid MP4/AVCC bitstream\n"); + av_free(out); + return AVERROR(EINVAL); + } + if ((err = av_reallocp(&out, total_size + padding)) < 0) + return err; + memcpy(out + total_size - unit_size - 4, nalu_header, 4); + memcpy(out + total_size - unit_size, extradata + 2, unit_size); + extradata += 2 + unit_size; +pps: + if (!unit_nb && !sps_done++) { + unit_nb = *extradata++; /* number of pps unit(s) */ + if (unit_nb) + pps_seen = 1; + } + } + + if (out) + memset(out + total_size, 0, FF_INPUT_BUFFER_PADDING_SIZE); + + if (!sps_seen) + av_log(avctx, AV_LOG_WARNING, + "Warning: SPS NALU missing or invalid. " + "The resulting stream may not play.\n"); + + if (!pps_seen) + av_log(avctx, AV_LOG_WARNING, + "Warning: PPS NALU missing or invalid. " + "The resulting stream may not play.\n"); + + av_free(avctx->extradata); + avctx->extradata = out; + avctx->extradata_size = total_size; + + return length_size; +} + +static int h264_mp4toannexb_filter(AVBitStreamFilterContext *bsfc, + AVCodecContext *avctx, const char *args, + uint8_t **poutbuf, int *poutbuf_size, + const uint8_t *buf, int buf_size, + int keyframe) +{ + H264BSFContext *ctx = bsfc->priv_data; + int i; + uint8_t unit_type; + int32_t nal_size; + uint32_t cumul_size = 0; + const uint8_t *buf_end = buf + buf_size; + int ret = 0; + + /* nothing to filter */ + if (!avctx->extradata || avctx->extradata_size < 6) { + *poutbuf = (uint8_t *)buf; + *poutbuf_size = buf_size; + return 0; + } + + /* retrieve sps and pps NAL units from extradata */ + if (!ctx->extradata_parsed) { + ret = h264_extradata_to_annexb(avctx, FF_INPUT_BUFFER_PADDING_SIZE); + if (ret < 0) + return ret; + ctx->length_size = ret; + ctx->first_idr = 1; + ctx->idr_sps_pps_seen = 0; + ctx->extradata_parsed = 1; + } + + *poutbuf_size = 0; + *poutbuf = NULL; + do { + ret= AVERROR(EINVAL); + if (buf + ctx->length_size > buf_end) + goto fail; + + for (nal_size = 0, i = 0; ilength_size; i++) + nal_size = (nal_size << 8) | buf[i]; + + buf += ctx->length_size; + unit_type = *buf & 0x1f; + + if (buf + nal_size > buf_end || nal_size < 0) + goto fail; + + if (ctx->first_idr && (unit_type == 7 || unit_type == 8)) + ctx->idr_sps_pps_seen = 1; + + /* if this is a new IDR picture following an IDR picture, reset the idr flag. + * Just check first_mb_in_slice to be 0 as this is the simplest solution. + * This could be checking idr_pic_id instead, but would complexify the parsing. */ + if (!ctx->first_idr && unit_type == 5 && (buf[1] & 0x80)) + ctx->first_idr = 1; + + /* prepend only to the first type 5 NAL unit of an IDR picture, if no sps/pps are already present */ + if (ctx->first_idr && unit_type == 5 && !ctx->idr_sps_pps_seen) { + if ((ret=alloc_and_copy(poutbuf, poutbuf_size, + avctx->extradata, avctx->extradata_size, + buf, nal_size)) < 0) + goto fail; + ctx->first_idr = 0; + } else { + if ((ret=alloc_and_copy(poutbuf, poutbuf_size, + NULL, 0, buf, nal_size)) < 0) + goto fail; + if (!ctx->first_idr && unit_type == 1) { + ctx->first_idr = 1; + ctx->idr_sps_pps_seen = 0; + } + } + + buf += nal_size; + cumul_size += nal_size + ctx->length_size; + } while (cumul_size < buf_size); + + return 1; + +fail: + av_freep(poutbuf); + *poutbuf_size = 0; + return ret; +} + +AVBitStreamFilter ff_h264_mp4toannexb_bsf = { + .name = "h264_mp4toannexb", + .priv_data_size = sizeof(H264BSFContext), + .filter = h264_mp4toannexb_filter, +}; diff --git a/pool/shard004/C/0099526_user_main.c b/pool/shard004/C/0099526_user_main.c new file mode 100644 index 0000000000000000000000000000000000000000..8accae3011e4dc11d63c223c1d08777b2a86c4d1 --- /dev/null +++ b/pool/shard004/C/0099526_user_main.c @@ -0,0 +1,121 @@ +/* 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 "driver/uart.h" +#include "osapi.h" +#include "mqtt.h" +#include "wifi.h" +#include "config.h" +#include "debug.h" +#include "gpio.h" +#include "user_interface.h" +#include "mem.h" + +MQTT_Client mqttClient; + +void wifiConnectCb(uint8_t status) +{ + if(status == STATION_GOT_IP){ + MQTT_Connect(&mqttClient); + } else { + MQTT_Disconnect(&mqttClient); + } +} +void mqttConnectedCb(uint32_t *args) +{ + MQTT_Client* client = (MQTT_Client*)args; + INFO("MQTT: Connected\r\n"); + MQTT_Subscribe(client, "/mqtt/topic/0", 0); + MQTT_Subscribe(client, "/mqtt/topic/1", 1); + MQTT_Subscribe(client, "/mqtt/topic/2", 2); + + MQTT_Publish(client, "/mqtt/topic/0", "hello0", 6, 0, 0); + MQTT_Publish(client, "/mqtt/topic/1", "hello1", 6, 1, 0); + MQTT_Publish(client, "/mqtt/topic/2", "hello2", 6, 2, 0); + +} + +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; + 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 = (char*)os_zalloc(topic_len+1), + *dataBuf = (char*)os_zalloc(data_len+1); + + 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; + + INFO("Receive topic: %s, data: %s \r\n", topicBuf, dataBuf); + os_free(topicBuf); + os_free(dataBuf); +} + +void user_rf_pre_init(void) +{ +} + +void user_init(void) +{ + uart_init(BIT_RATE_115200, BIT_RATE_115200); + os_delay_us(1000000); + + CFG_Load(); + + MQTT_InitConnection(&mqttClient, sysCfg.mqtt_host, sysCfg.mqtt_port, sysCfg.security); + //MQTT_InitConnection(&mqttClient, "192.168.11.122", 1880, 0); + + MQTT_InitClient(&mqttClient, sysCfg.device_id, sysCfg.mqtt_user, sysCfg.mqtt_pass, sysCfg.mqtt_keepalive, 1); + //MQTT_InitClient(&mqttClient, "client_id", "user", "pass", 120, 1); + + MQTT_InitLWT(&mqttClient, "/lwt", "offline", 0, 0); + 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"); +} diff --git a/pool/shard004/C/0099529_devfifo.c b/pool/shard004/C/0099529_devfifo.c new file mode 100644 index 0000000000000000000000000000000000000000..5d3c641ec6b2421a9721364f871dfbddebb670a1 --- /dev/null +++ b/pool/shard004/C/0099529_devfifo.c @@ -0,0 +1,188 @@ +/* Copyright 2011-2018 Tyler Gilbert; + * This file is part of Stratify OS. + * + * Stratify OS is free software: you can 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. + * + * Stratify OS is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Stratify OS. If not, see . + * + * + */ + +#include +#include +#include +#include "sos/dev/devfifo.h" +#include "device/devfifo.h" +#include "mcu/debug.h" + + +static int set_read_action(const devfs_handle_t * handle, mcu_callback_t callback){ + mcu_action_t action; + const devfifo_config_t * cfgp = handle->config; + const devfs_device_t * device = cfgp->dev; + + action.handler.callback = callback; + action.handler.context = (void*)handle; + action.o_events = cfgp->event; + action.prio = 0; + if ( device->driver.ioctl(&(device->handle), cfgp->req_setaction, &action) < 0 ){ + return -1; + } + + return 0; +} + +static void inc_head(devfifo_state_t * state, int size){ + state->head++; + if ( state->head == size ){ + state->head = 0; + } + + if ( state->head == state->tail ){ + state->tail++; + if ( state->tail == size ){ + state->tail = 0; + } + state->overflow = true; + } +} + +static int read_buffer(const devfifo_config_t * cfgp, devfifo_state_t * state, devfs_async_t * rop){ + int i; + for(i=0; i < state->len; i++){ + if ( state->head == state->tail ){ //check for data in the fifo buffer + break; + } else { + ((char*)(rop->buf))[i] = cfgp->buffer[state->tail]; + state->tail++; + if ( state->tail == cfgp->size ){ + state->tail = 0; + } + } + } + return i; //number of bytes read +} + +static int data_received(void * context, const mcu_event_t * data){ + char c; + const devfs_handle_t * handle; + handle = context; + const devfifo_config_t * cfgp = handle->config; + devfifo_state_t * state = handle->state; + const devfs_device_t * device = cfgp->dev; + + while ( device->driver.ioctl(&(device->handle), cfgp->req_getbyte, &c) == 0 ){ + cfgp->buffer[ state->head ] = c; + inc_head(state, cfgp->size); + } + + if( state->rop != NULL ){ + int bytes_read; + if( (bytes_read = read_buffer(cfgp, state, state->rop)) > 0 ){ + state->rop->nbyte = bytes_read; + if ( state->rop->handler.callback(state->rop->handler.context, NULL) == 0 ){ + state->rop = NULL; + } + } + } + + + return 1; //leave the callback in place +} + +int devfifo_open(const devfs_handle_t * handle){ + const devfifo_config_t * cfgp = handle->config; + devfifo_state_t * state = handle->state; + const devfs_device_t * device = cfgp->dev; + state->head = 0; + state->tail = 0; + state->rop = NULL; + state->overflow = false; + //setup the device to write to the fifo when data arrives + if ( device->driver.open(&(device->handle)) < 0 ){ + return -1; + } + + if ( set_read_action(handle, data_received) < 0 ){ + return -1; + } + + return 0; +} + +int devfifo_ioctl(const devfs_handle_t * handle, int request, void * ctl){ + devfifo_attr_t * attr = ctl; + const devfifo_config_t * cfgp = handle->config; + devfifo_state_t * state = handle->state; + const devfs_device_t * device = cfgp->dev; + + if ( request == I_DEVFIFO_GETINFO ){ + attr->size = cfgp->size; + if( state->head > state->tail ){ + attr->used = state->head - state->tail; + } else { + attr->used = cfgp->size - state->tail + state->head; + } + attr->overflow = state->overflow; + state->overflow = false; //clear the overflow flag now that it has been read + return 0; + } else { + return device->driver.ioctl(&(device->handle), request, ctl); + } +} + + +int devfifo_read(const devfs_handle_t * handle, devfs_async_t * rop){ + const devfifo_config_t * cfgp = handle->config; + devfifo_state_t * state = handle->state; + + int bytes_read; + + if ( state->rop != NULL ){ + rop->nbyte = 0; + return 0; //caller will block until data is read + } + + state->len = rop->nbyte; + bytes_read = read_buffer(cfgp, state, rop); //see if there are bytes in the buffer + if ( bytes_read == 0 ){ + if( (rop->flags & O_NONBLOCK) ){ + bytes_read = SYSFS_SET_RETURN(EAGAIN); + } else { + state->rop = rop; + state->len = rop->nbyte; + rop->nbyte = 0; + } + } + + return bytes_read; +} + +int devfifo_write(const devfs_handle_t * handle, devfs_async_t * wop){ + const devfifo_config_t * cfgp = handle->config; + const devfs_device_t * device = cfgp->dev; + + return device->driver.write(&(device->handle), wop); +} + +int devfifo_close(const devfs_handle_t * handle){ + const devfifo_config_t * cfgp = handle->config; + const devfs_device_t * device = cfgp->dev; + + //clear the callback for the device + if( set_read_action(handle, NULL) < 0 ){ + return -1; + } + + return device->driver.close(&(device->handle)); +} + diff --git a/pool/shard004/C/0099543_grib_accessor_class_data_2order_packing_count.c b/pool/shard004/C/0099543_grib_accessor_class_data_2order_packing_count.c new file mode 100644 index 0000000000000000000000000000000000000000..6ff955a132eea67f31f23caf50aad1b329dc24c7 --- /dev/null +++ b/pool/shard004/C/0099543_grib_accessor_class_data_2order_packing_count.c @@ -0,0 +1,196 @@ +/* + * 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_unsigned + IMPLEMENTS = init + IMPLEMENTS = unpack_long + MEMBERS = const char* offsetsection + MEMBERS = const char* p1 + MEMBERS = const char* two_ordr_spd + MEMBERS = const char* plus1_spd + MEMBERS = const char* width_lengths + MEMBERS = const char* octet_start_group + + 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 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_data_2order_packing_count { + grib_accessor att; +/* Members defined in gen */ +/* Members defined in long */ +/* Members defined in unsigned */ + long nbytes; + grib_arguments* arg; +/* Members defined in data_2order_packing_count */ + const char* offsetsection; + const char* p1; + const char* two_ordr_spd; + const char* plus1_spd; + const char* width_lengths; + const char* octet_start_group; +} grib_accessor_data_2order_packing_count; + +extern grib_accessor_class* grib_accessor_class_unsigned; + +static grib_accessor_class _grib_accessor_class_data_2order_packing_count = { + &grib_accessor_class_unsigned, /* super */ + "data_2order_packing_count", /* name */ + sizeof(grib_accessor_data_2order_packing_count), /* 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 */ + 0, /* 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 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 */ +}; + + +grib_accessor_class* grib_accessor_class_data_2order_packing_count = &_grib_accessor_class_data_2order_packing_count; + + +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_long = (*(c->super))->pack_long; + 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_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; +} + +/* END_CLASS_IMP */ + +static void init(grib_accessor* a,const long v, grib_arguments* args) +{ + grib_accessor_data_2order_packing_count *self =(grib_accessor_data_2order_packing_count*)a; + int n=0; + + self->offsetsection = grib_arguments_get_name(a->parent->h,args,n++); + self->p1 = grib_arguments_get_name(a->parent->h,args,n++); + self->two_ordr_spd = grib_arguments_get_name(a->parent->h,args,n++); + self->plus1_spd = grib_arguments_get_name(a->parent->h,args,n++); + self->width_lengths = grib_arguments_get_name(a->parent->h,args,n++); + self->octet_start_group = grib_arguments_get_name(a->parent->h,args,n++); + + a->flags |= GRIB_ACCESSOR_FLAG_READ_ONLY; + +} + + +static int unpack_long (grib_accessor* a, long* val, size_t *len) +{ + int ret=0; + grib_accessor_data_2order_packing_count* self = (grib_accessor_data_2order_packing_count*)a; + long count = 0; + long two_ordr_spd = 0; + long plus1_spd = 0; + unsigned char* buf_size_of_groups = (unsigned char*)a->parent->h->buffer->data; + long octet_start_group = 0; + long offsetsection = 0; + long nbits_per_lengths = 0; + long pointer_of_group_size = 0; + long p1 = 0; + + size_t i = 0; + + if ((ret=grib_get_long_internal(a->parent->h,self->two_ordr_spd, &two_ordr_spd)) + !=GRIB_SUCCESS) return ret; + if ((ret=grib_get_long_internal(a->parent->h,self->plus1_spd, &plus1_spd)) + !=GRIB_SUCCESS) return ret; + if ((ret=grib_get_long_internal(a->parent->h,self->width_lengths, &nbits_per_lengths)) + !=GRIB_SUCCESS) return ret; + if ((ret=grib_get_long_internal(a->parent->h,self->offsetsection, &offsetsection)) + !=GRIB_SUCCESS) return ret; + if ((ret=grib_get_long_internal(a->parent->h,self->octet_start_group, &octet_start_group)) + !=GRIB_SUCCESS) return ret; + if ((ret=grib_get_long_internal(a->parent->h,self->p1, &p1)) + !=GRIB_SUCCESS) return ret; + + buf_size_of_groups += offsetsection+(octet_start_group-1); + count = two_ordr_spd*2+plus1_spd; + + for(i=0;i < p1;i++) + count += grib_decode_unsigned_long(buf_size_of_groups, &pointer_of_group_size, nbits_per_lengths); + + *val=count; + *len=1; + return GRIB_SUCCESS; +} diff --git a/pool/shard004/C/0099546_platform.c b/pool/shard004/C/0099546_platform.c new file mode 100644 index 0000000000000000000000000000000000000000..3a44db4da6f360c12c56f0f7059e0e13479dd926 --- /dev/null +++ b/pool/shard004/C/0099546_platform.c @@ -0,0 +1,128 @@ +/* Copyright (c) 2012-2013, The Linux Foundation. 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 Linux 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 COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NON-INFRINGEMENT ARE 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 + +#define MB (1024*1024) + +#define MSM_IOMAP_SIZE ((MSM_IOMAP_END - MSM_IOMAP_BASE)/MB) + +/* LK memory - cacheable, write through */ +#define LK_MEMORY (MMU_MEMORY_TYPE_NORMAL_WRITE_THROUGH | \ + MMU_MEMORY_AP_READ_WRITE) + +/* Peripherals - non-shared device */ +#define IOMAP_MEMORY (MMU_MEMORY_TYPE_DEVICE_SHARED | \ + MMU_MEMORY_AP_READ_WRITE | MMU_MEMORY_XN) + +static mmu_section_t mmu_section_table[] = { +/* Physical addr, Virtual addr, Size (in MB), Flags */ + { MEMBASE, MEMBASE, (MEMSIZE / MB), LK_MEMORY}, + { MSM_IOMAP_BASE, MSM_IOMAP_BASE, MSM_IOMAP_SIZE, IOMAP_MEMORY}, +}; + +static struct smem_ram_ptable ram_ptable; + +void platform_early_init(void) +{ + board_init(); + platform_clock_init(); + qgic_init(); + qtimer_init(); +} + +void platform_init(void) +{ + dprintf(INFO, "platform_init()\n"); +} + +void platform_uninit(void) +{ + qtimer_uninit(); +} + +/* Setup memory for this platform */ +void platform_init_mmu_mappings(void) +{ + uint32_t i; + uint32_t sections; + uint32_t table_size = ARRAY_SIZE(mmu_section_table); + + ASSERT(smem_ram_ptable_init(&ram_ptable)); + + /* Configure the MMU page entries for SDRAM and IMEM memory read + from the smem ram table*/ + for(i = 0; i < ram_ptable.len; i++) + { + if(ram_ptable.parts[i].type == SYS_MEMORY) + { + if((ram_ptable.parts[i].category == SDRAM) || + (ram_ptable.parts[i].category == IMEM)) + { + /* Check to ensure that start address is 1MB aligned */ + ASSERT((ram_ptable.parts[i].start & 0xFFFFF) == 0); + + sections = (ram_ptable.parts[i].size) / MB; + while(sections--) + { + arm_mmu_map_section(ram_ptable.parts[i].start + + sections * MB, + ram_ptable.parts[i].start + + sections * MB, + (MMU_MEMORY_TYPE_NORMAL_WRITE_THROUGH | \ + MMU_MEMORY_AP_READ_WRITE | MMU_MEMORY_XN)); + } + } + } + } + + /* Configure the MMU page entries for memory read from the + mmu_section_table */ + for (i = 0; i < table_size; i++) + { + sections = mmu_section_table[i].num_of_sections; + + while (sections--) + { + arm_mmu_map_section(mmu_section_table[i].paddress + + sections * MB, + mmu_section_table[i].vaddress + + sections * MB, + mmu_section_table[i].flags); + } + } +} diff --git a/pool/shard004/C/0099547_platedetector.c b/pool/shard004/C/0099547_platedetector.c new file mode 100644 index 0000000000000000000000000000000000000000..fa7292571383d47d57c18c33639b81dd38e965de --- /dev/null +++ b/pool/shard004/C/0099547_platedetector.c @@ -0,0 +1,182 @@ +/* + * (C) Copyright 2014 Kurento (http://kurento.org/) + * + * 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 + +#include + +#define VIDEO_PATH BINARY_LOCATION "/video/filter/plates.webm" +#define KMS_VIDEO_PREFIX "video_src_" +#define KMS_AUDIO_PREFIX "audio_src_" +#define KMS_ELEMENT_PAD_TYPE_AUDIO 1 +#define KMS_ELEMENT_PAD_TYPE_VIDEO 2 + +GMainLoop *loop; +GstElement *player, *pipeline, *filter, *fakesink_video; + +static void +bus_msg (GstBus * bus, GstMessage * msg, gpointer pipe) +{ + switch (GST_MESSAGE_TYPE (msg)) { + case GST_MESSAGE_ERROR:{ + GST_ERROR ("Error: %" GST_PTR_FORMAT, msg); + GST_DEBUG_BIN_TO_DOT_FILE_WITH_TS (GST_BIN (pipe), + GST_DEBUG_GRAPH_SHOW_ALL, "error"); + fail ("Error received on bus"); + break; + } + case GST_MESSAGE_EOS:{ + g_main_loop_quit (loop); + break; + } + case GST_MESSAGE_WARNING:{ + GST_ERROR ("Warning: %" GST_PTR_FORMAT, msg); + GST_DEBUG_BIN_TO_DOT_FILE_WITH_TS (GST_BIN (pipe), + GST_DEBUG_GRAPH_SHOW_ALL, "error"); + fail ("Warning received on bus"); + break; + } + default: + break; + } +} + +static void +connect_sink_on_srcpad_added (GstElement * playerep, GstPad * new_pad, + gpointer user_data) +{ + gchar *padname; + gboolean ret; + + GST_INFO_OBJECT (playerep, "Pad added %" GST_PTR_FORMAT, new_pad); + padname = gst_pad_get_name (new_pad); + fail_if (padname == NULL); + + if (g_str_has_prefix (padname, KMS_VIDEO_PREFIX)) { + ret = gst_element_link_pads (playerep, padname, filter, "sink"); + fail_if (ret == FALSE); + ret = gst_element_link (filter, fakesink_video); + fail_if (ret == FALSE); + } + + g_free (padname); +} + +static gboolean +quit_main_loop_idle (gpointer data) +{ + GMainLoop *loop = data; + + GST_DEBUG ("Test finished exiting main loop"); + g_main_loop_quit (loop); + return FALSE; +} + +static void +player_eos (GstElement * player, GMainLoop * loop) +{ + GST_DEBUG ("Eos received"); + g_idle_add (quit_main_loop_idle, loop); +} + +GST_START_TEST (player_with_filter) +{ + guint bus_watch_id; + GstBus *bus; + gchar *padname; + + loop = g_main_loop_new (NULL, FALSE); + pipeline = gst_pipeline_new ("pipeline_live_stream"); + g_object_set (G_OBJECT (pipeline), "async-handling", TRUE, NULL); + player = gst_element_factory_make ("playerendpoint", NULL); + filter = gst_element_factory_make ("platedetector", NULL); + fakesink_video = gst_element_factory_make ("fakesink", NULL); + bus = gst_pipeline_get_bus (GST_PIPELINE (pipeline)); + + bus_watch_id = gst_bus_add_watch (bus, gst_bus_async_signal_func, NULL); + g_signal_connect (bus, "message", G_CALLBACK (bus_msg), pipeline); + g_object_unref (bus); + + g_object_set (G_OBJECT (player), "uri", VIDEO_PATH, NULL); + + gst_element_set_state (pipeline, GST_STATE_PLAYING); + + gst_bin_add (GST_BIN (pipeline), filter); + gst_element_set_state (filter, GST_STATE_PLAYING); + + gst_bin_add (GST_BIN (pipeline), fakesink_video); + gst_element_set_state (fakesink_video, GST_STATE_PLAYING); + + gst_bin_add (GST_BIN (pipeline), player); + + g_signal_connect (G_OBJECT (player), "eos", G_CALLBACK (player_eos), loop); + g_signal_connect (player, "pad-added", + G_CALLBACK (connect_sink_on_srcpad_added), loop); + + /* request audio src pad using action */ + g_signal_emit_by_name (player, "request-new-pad", + KMS_ELEMENT_PAD_TYPE_AUDIO, NULL, GST_PAD_SRC, &padname); + fail_if (padname == NULL); + + GST_DEBUG ("Requested pad %s", padname); + g_free (padname); + + /* request video src pad using action */ + g_signal_emit_by_name (player, "request-new-pad", + KMS_ELEMENT_PAD_TYPE_VIDEO, NULL, GST_PAD_SRC, &padname); + fail_if (padname == NULL); + + GST_DEBUG ("Requested pad %s", padname); + g_free (padname); + + gst_element_set_state (player, GST_STATE_PLAYING); + + /* Set player to start state */ + g_object_set (G_OBJECT (player), "state", KMS_URI_ENDPOINT_STATE_START, NULL); + + g_main_loop_run (loop); + + // TODO: Wait for a "plate-detected" bus message, to verify that the + // license plate has actually been detected and read correctly + + gst_element_set_state (pipeline, GST_STATE_NULL); + gst_object_unref (GST_OBJECT (pipeline)); + g_source_remove (bus_watch_id); + g_main_loop_unref (loop); +} + +GST_END_TEST +/* Define test suite */ +static Suite * +platedetector_suite (void) +{ + Suite *s = suite_create ("platedetector"); + TCase *tc_chain = tcase_create ("element"); + + suite_add_tcase (s, tc_chain); + tcase_add_test (tc_chain, player_with_filter); + + return s; +} + +GST_CHECK_MAIN (platedetector); diff --git a/pool/shard004/C/0099554_identify.c b/pool/shard004/C/0099554_identify.c new file mode 100644 index 0000000000000000000000000000000000000000..5f428bdf44c0ae422c017ae24f6ac2fa77a27924 --- /dev/null +++ b/pool/shard004/C/0099554_identify.c @@ -0,0 +1,117 @@ +/* identify -- Probe system and report characteristica. + Copyright (C) 2013, 2014 Free Software Foundation, Inc. + + This file is part of GNU Inetutils. + + GNU Inetutils is free software: you can 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. + + GNU Inetutils is distributed in the hope that it will be useful, but + WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR 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 `http://www.gnu.org/licenses/'. */ + +/* Written by Mats Erik Andersson. */ + +/* Collect information about this system and report it. + * Some identified characteristica of relevance to GNU Inetutils + * are displayed for use in bug reporting and resolution. + */ + +#ifdef HAVE_CONFIG_H +# include +#endif + +#include +#include +#include + +#include +#include +#include +#include +#include + +#define tell_macro(a,b) \ + printf ("%s: %s\n", (b) ? "Available macro" : "Not defined", (a)); + +int +main (void) +{ + int a, ux; + struct utsname uts; + struct sockaddr_un su; + + if (uname (&uts) < 0) + { + fprintf (stderr, "Not able to identify running system.\n"); + exit (EXIT_FAILURE); + } + + /* Identify the hardware. */ + printf ("Running system: %s, %s\n", + uts.sysname, uts.machine); + printf (" Variant: %s\n", uts.release); + printf (" Variant: %s\n", uts.version); + puts (""); + + /* + * Report on macros that determine alternate code. + * These depend on toolchains and hardware. + */ + ux = 0; +#ifdef unix + ux = 1; +#endif + tell_macro ("unix", ux); + + ux = 0; +#ifdef __unix + ux = 1; +#endif + tell_macro ("__unix", ux); + + ux = 0; +#ifdef __unix__ + ux = 1; +#endif + tell_macro ("__unix__", ux); + + ux = 0; +#ifdef __sun + ux = 1; +#endif + tell_macro ("__sun", ux); + + ux = 0; +#ifdef __sun__ + ux = 1; +#endif + tell_macro ("__sun__", ux); + + a = 0; +#ifdef TN3270 + a = 1; +#endif + tell_macro ("TN3270", a); + + /* + * Implementation specific charateristica. + */ + puts (""); + + a = 0; +#ifdef BSD + a = 1; +#endif + tell_macro ("BSD", a); + + printf ("Size of 'struct sockaddr_un.sun_path': %zu\n", + sizeof (su.sun_path)); + return 0; +} diff --git a/pool/shard004/C/0099556_pr62021.c b/pool/shard004/C/0099556_pr62021.c new file mode 100644 index 0000000000000000000000000000000000000000..40c64429d6382821af4a31b3569c696ea0e5fa2a --- /dev/null +++ b/pool/shard004/C/0099556_pr62021.c @@ -0,0 +1,32 @@ +/* { dg-require-effective-target vect_simd_clones } */ +/* { dg-additional-options "-fopenmp-simd" } */ +/* { dg-additional-options "-mavx" { target avx_runtime } } */ + +#include "tree-vect.h" + +#pragma omp declare simd linear(y) +__attribute__((noinline)) int * +foo (int *x, int y) +{ + return x + y; +} + +int a[1024]; +int *b[1024] = { &a[0] }; + +int +main () +{ + int i; + check_vect (); + for (i = 0; i < 1024; i++) + b[i] = &a[1023 - i]; + #pragma omp simd + for (i = 0; i < 1024; i++) + b[i] = foo (b[i], i); + for (i = 0; i < 1024; i++) + if (b[i] != &a[1023]) + __builtin_abort (); + return 0; +} + diff --git a/pool/shard004/C/0099561_asg.c b/pool/shard004/C/0099561_asg.c new file mode 100644 index 0000000000000000000000000000000000000000..8f9c49f8ff67d501e06c074ab0ab68afa14c924a --- /dev/null +++ b/pool/shard004/C/0099561_asg.c @@ -0,0 +1,139 @@ +/*----------------------------------------------------------------------*/ +/* asg.c --- Glue code between xcircuit and SPAR */ +/*----------------------------------------------------------------------*/ + +#ifdef ASG + +#include +#include "externs.h" /* Local ASG definitions */ + +extern void spar_destructor(); +extern void spar_constructor(); + +/*--------------------------------------------------------------------- */ + +int xc_print_sym(XCWindowData *areastruct, char *sym, char*name, + int x, int y, int x_dis, int y_dis, int rot) +{ + asg_make_instance(areastruct, sym, x, y, x_dis, y_dis); + asg_make_label(areastruct, NORMAL, x, y, name); + + return(1); +} + + +/*----------------------------------------------------------------------*/ +/* This function is used to draw an ASG module as an xcircuit object */ +/* instance. */ +/*----------------------------------------------------------------------*/ + +int asg_make_instance(XCWindowData *clientData, char *keyword, int x, + int y, int x_size, int y_size) +{ + objectptr pobj; + objinstptr pinst, *newinst; + XPoint newpos; + + // Set Position for newly created object + newpos.x = (short)(x * 15.0); + newpos.y = (short)(y * 15.0); + + // Create Space for Object Instances... + NEW_OBJINST(newinst, clientData->topinstance->thisobject); + + // Find Object instance in the library... + pobj = NameToObject(keyword, &pinst, FALSE); + + // If object specified by keyword, it must exist in a loaded library. + // (need to develop this code) + + if (pobj == NULL) { + /* sprintf(_STR, "Cannot Find %s in any existing library.", keyword); */ + /* Wprintf(_STR); */ + return -1; + } + + // Copy values from the library instance into the new instance + instcopy(*newinst, pinst); + (*newinst)->scale = 1.0; + + // Rotated objects should be using the rotated instances. + // Instances at rotation = 0 in the asg_spice.lps library should + // match the orientations of devices in the original SPAR + // definitions, or vice versa. + + if (!strcmp(keyword, "arrow")) (*newinst)->rotation += 90; + else if (!strcmp(keyword, "RESTR")) (*newinst)->rotation += 270; + else if (!strcmp(keyword, "INDR")) (*newinst)->rotation += 270; + else if (!strcmp(keyword, "CAPC")) (*newinst)->rotation += 270; + else if (!strcmp(keyword, "IAMP")) (*newinst)->rotation += 270; + + // Eventually all drawing parameters need to be overridden. + // Assign just position for now + + (*newinst)->position = newpos; + return 0; +} + +/*----------------------------------------------------------------------*/ +/* This function draws the path connecting the object on the screen */ +/*----------------------------------------------------------------------*/ + +void asg_make_polygon(XCWindowData *clientData, int npoints, int x[], int y[]) +{ + polyptr *newpoly; + int j; + + NEW_POLY(newpoly, clientData->topinstance->thisobject); + polydefaults(*newpoly, npoints, 0, 0); + (*newpoly)->style = UNCLOSED; + for (j = 0; j < npoints; j++) { + (*newpoly)->points[j].x = x[j]; + (*newpoly)->points[j].y = y[j]; + } + /* singlebbox((genericptr *)newpoly); */ + incr_changes(clientData->topinstance->thisobject); +} + +/*----------------------------------------------------------------------*/ +/* This function helps print the label of the object on the screen */ +/*----------------------------------------------------------------------*/ + +void asg_make_label(XCWindowData *clientData, u_char dopin, int x, int y, char *data) +{ + labelptr *newlab; + stringpart *strptr; + + NEW_LABEL(newlab, clientData->topinstance->thisobject); + labeldefaults(*newlab, dopin, x - 20, y - 30); + + // (*newlab)->justify = PINVISIBLE; + strptr = makesegment(&((*newlab)->string), NULL); + strptr->type = TEXT_STRING; + strptr->data.string = data; + singlebbox((genericptr *)newlab); + incr_changes(clientData->topinstance->thisobject); +} + +/*----------------------------------------------------------------------*/ +/* Free memory for SPAR structures */ +/*----------------------------------------------------------------------*/ + +void spar_destructor() +{ + free_list(modules); + free_list(nets); +} + +/*----------------------------------------------------------------------*/ +/* Generate SPAR structures */ +/*----------------------------------------------------------------------*/ + +void spar_constructor() +{ + newnode("$0"); + newnode("$1"); + newnode("_DUMMY_SIGNAL_"); +} + +#endif /* ASG */ diff --git a/pool/shard004/C/0099573_ptrace_user.c b/pool/shard004/C/0099573_ptrace_user.c new file mode 100644 index 0000000000000000000000000000000000000000..b1021e82bce4a652465b5e755323d1771dd3dead --- /dev/null +++ b/pool/shard004/C/0099573_ptrace_user.c @@ -0,0 +1,118 @@ +/* + * Copyright (C) 2002 Jeff Dike (jdike@karaya.com) + * Licensed under the GPL + */ + +#include +#include +#include +#include +#include +#include +#include +#include "kern_util.h" +#include "sysdep/thread.h" +#include "user.h" +#include "os.h" + +int ptrace_getregs(long pid, unsigned long *regs_out) +{ + return(ptrace(PTRACE_GETREGS, pid, 0, regs_out)); +} + +int ptrace_setregs(long pid, unsigned long *regs) +{ + return(ptrace(PTRACE_SETREGS, pid, 0, regs)); +} + +int ptrace_getfpregs(long pid, unsigned long *regs) +{ + return(ptrace(PTRACE_GETFPREGS, pid, 0, regs)); +} + +static void write_debugregs(int pid, unsigned long *regs) +{ + struct user *dummy; + int nregs, i; + + dummy = NULL; + nregs = sizeof(dummy->u_debugreg)/sizeof(dummy->u_debugreg[0]); + for(i = 0; i < nregs; i++){ + if((i == 4) || (i == 5)) continue; + if(ptrace(PTRACE_POKEUSER, pid, &dummy->u_debugreg[i], + regs[i]) < 0) + printk("write_debugregs - ptrace failed on " + "register %d, value = 0x%x, errno = %d\n", i, + regs[i], errno); + } +} + +static void read_debugregs(int pid, unsigned long *regs) +{ + struct user *dummy; + int nregs, i; + + dummy = NULL; + nregs = sizeof(dummy->u_debugreg)/sizeof(dummy->u_debugreg[0]); + for(i = 0; i < nregs; i++){ + regs[i] = ptrace(PTRACE_PEEKUSER, pid, + &dummy->u_debugreg[i], 0); + } +} + +/* Accessed only by the tracing thread */ +static unsigned long kernel_debugregs[8] = { [ 0 ... 7 ] = 0 }; +static int debugregs_seq = 0; + +void arch_enter_kernel(void *task, int pid) +{ + read_debugregs(pid, TASK_DEBUGREGS(task)); + write_debugregs(pid, kernel_debugregs); +} + +void arch_leave_kernel(void *task, int pid) +{ + read_debugregs(pid, kernel_debugregs); + write_debugregs(pid, TASK_DEBUGREGS(task)); +} + +void ptrace_pokeuser(unsigned long addr, unsigned long data) +{ + if((addr < offsetof(struct user, u_debugreg[0])) || + (addr > offsetof(struct user, u_debugreg[7]))) + return; + addr -= offsetof(struct user, u_debugreg[0]); + addr = addr >> 2; + if(kernel_debugregs[addr] == data) return; + + kernel_debugregs[addr] = data; + debugregs_seq++; +} + +static void update_debugregs_cb(void *arg) +{ + int pid = *((int *) arg); + + write_debugregs(pid, kernel_debugregs); +} + +void update_debugregs(int seq) +{ + int me; + + if(seq == debugregs_seq) return; + + me = os_getpid(); + initial_thread_cb(update_debugregs_cb, &me); +} + +/* + * Overrides for Emacs so that we follow Linus's tabbing style. + * Emacs will notice this stuff at the end of the file and automatically + * adjust the settings for this buffer only. This must remain at the end + * of the file. + * --------------------------------------------------------------------------- + * Local variables: + * c-file-style: "linux" + * End: + */ diff --git a/pool/shard004/C/0099574_test26.c b/pool/shard004/C/0099574_test26.c new file mode 100644 index 0000000000000000000000000000000000000000..c693e5ee7a58d44eeb96c350f8b0c421146d878b --- /dev/null +++ b/pool/shard004/C/0099574_test26.c @@ -0,0 +1,52 @@ +#include +#include +#include +#include "utlist.h" + +#define BUFLEN 20 + +typedef struct el { + char bname[BUFLEN]; + struct el *next, *prev; +} el; + +int namecmp(void *_a, void *_b) { + el *a = (el*)_a; + el *b = (el*)_b; + return strcmp(a->bname,b->bname); +} + +el *head = NULL; /* important- initialize to NULL! */ + +int main(int argc, char *argv[]) { + el *name, *elt, *tmp, etmp; + + char linebuf[BUFLEN]; + FILE *file; + + if ( (file = fopen( "test11.dat", "r" )) == NULL ) { + perror("can't open: "); + exit(-1); + } + + while (fgets(linebuf,BUFLEN,file) != NULL) { + if ( (name = (el*)malloc(sizeof(el))) == NULL) exit(-1); + strncpy(name->bname,linebuf,BUFLEN); + DL_APPEND(head, name); + } + DL_SORT(head, namecmp); + DL_FOREACH(head,elt) printf("%s", elt->bname); + + memcpy(&etmp.bname, "WES\n", 5); + DL_SEARCH(head,elt,&etmp,namecmp); + if (elt) printf("found %s\n", elt->bname); + + /* now delete each element, use the safe iterator */ + DL_FOREACH_SAFE(head,elt,tmp) { + DL_DELETE(head,elt); + } + + fclose(file); + + return 0; +} diff --git a/pool/shard004/C/0099577_main.c b/pool/shard004/C/0099577_main.c new file mode 100644 index 0000000000000000000000000000000000000000..487c1e0e69412e5f2ec50daf2bd6f5a58adc4f3c --- /dev/null +++ b/pool/shard004/C/0099577_main.c @@ -0,0 +1,193 @@ +/* --COPYRIGHT--,BSD + * Copyright (c) 2014, 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--*/ +/* + * main.c + * RO_PINOSC_TA0_TA1 implementation using 6 buttons/LEDS or a 1 button/LED. + * + * Schematic Description: + * + * MSP430F2553 + * +---------------+ + * | | + * LED0--------|P1.0 P2.6|--------LED5 + * LED1--------|P1.4 P2.7|--------LED4 + * LED2--------|P1.5 P1.6|--------LED3 + * | | + * key0--------|P2.0 P2.5|--------key5 + * key1--------|P2.1 P2.4|--------key4 + * eProx/key2--------|P2.2 P2.3|--------key3 + * + * The TIMERA_1 interval represents the gate time. The number of counts within + * the TA0R that have accumulated during the gate time represents the + * capacitance of the element. The code is divided into two different + * applications; keypad and proximity sensor. The structure./.h files support + * both. + * The gate time for the element defined in sensor proximity is about 11ms. + * The scan rate for the sensor proximity is approximately 20ms plus the 11ms + * it takes to measure the sensor. + * 1/(20ms + 11ms) ~ 32Hz + * The gate time for each element defined in sensor keypad is about 1ms. The + * the time it takes to measure all six elements is 6ms. + * The scan rate for the sensor keypad is approximately 25ms plus the 6ms it + * takes to measure all six elements wihtin the sensor. + * 1/(25ms + 6ms) ~ 32Hz + * + * The element and sensor definitions found in the configuration file + * structure.c use designated initializer lists. This allows members to be + * initialized in any order and also enhances the readability of the element + * being initialized. + * This feature requires the GCC language extension found in Code Composer + * Studio (CCS). C99 is the default dialect found in IAR and therefore the + * default settings can be used. + */ + +#include "CTS_Layer.h" + +//#define PROXIMITY_APP +#define KEYPAD_APP + +#ifdef KEYPAD_APP +struct Element * activeKey; +const struct Element* keyAddress[6] = +{ + &key0, + &key1, + &key2, + &key3, + &key4, + &key5 +}; +const uint8_t * portOut[6] = +{ + (uint8_t *)&P1OUT, + (uint8_t *)&P1OUT, + (uint8_t *)&P1OUT, + (uint8_t *)&P1OUT, + (uint8_t *)&P2OUT, + (uint8_t *)&P2OUT +}; +const uint8_t bitOut[6] = +{ + BIT0, + BIT4, + BIT5, + BIT6, + BIT7, + BIT6 +}; +#endif +void sleep(uint16_t); +/* + * ======== main() ======== + */ +uint16_t main(void) { + + volatile uint8_t i; + + WDTCTL = WDTPW + WDTHOLD; /* Stop WDT */ + BCSCTL1 = CALBC1_1MHZ; /* Set DCO to 1, 8, 12 or 16MHz */ + DCOCTL = CALDCO_1MHZ; + BCSCTL3 |= LFXT1S_2; /* LFXT1 = VLO */ + + P1DIR |= 0xFF; + P2DIR |= 0xFF; + P1OUT = 0; + P2OUT = 0; + P2SEL = 0; + P1SEL = 0; + +#ifdef PROXIMITY_APP + TI_CAPT_Init_Baseline(&proximity); + TI_CAPT_Update_Baseline(&proximity,5); +#endif + +#ifdef KEYPAD_APP + TI_CAPT_Init_Baseline(&keypad); + TI_CAPT_Update_Baseline(&keypad,5); +#endif + + while(1) + { +#ifdef PROXIMITY_APP + if(TI_CAPT_Button(&proximity)) + { + P1OUT |= BIT0; + } + /* Delay 20ms, 20ms*12Khz = 240 */ + sleep(240); + P1OUT &= ~BIT0; +#endif +#ifdef KEYPAD_APP + activeKey = (struct Element *)TI_CAPT_Buttons(&keypad); + for(i=0;i<6;i++) + { + if(activeKey == keyAddress[i]) + { + *(uint8_t *)portOut[i] |= bitOut[i]; + } + } + /* Delay 25ms, 25ms*12Khz = 300 */ + sleep(300); + P1OUT &= ~(BIT0+BIT4+BIT5+BIT6); + P2OUT &= ~(BIT6+BIT7); +#endif + } /* End While */ +} /* End Main */ + +/* + * ======== sleep(uint16_t) ======== + * Place device into LPM3. Source of TimerA1 is ACLK which is sourced from the + * VLO (~12Khz). The ISR is found in the library, in CTS_HAL.c + */ +void sleep(uint16_t time) +{ + TA1CCR0 = time; + TA1CTL = MC_1+TACLR+TASSEL_1; + TA1CCTL0 &= ~(CAP+CCIFG); + TA1CCTL0 |= CCIE; + __bis_SR_register(LPM3_bits+GIE); + __no_operation(); + __disable_interrupt(); + TA1CTL &= ~(MC_1); + TA1CCTL0 &= ~(CCIE); +} + +#pragma vector= PORT2_VECTOR,PORT1_VECTOR,WDT_VECTOR,ADC10_VECTOR,NMI_VECTOR, \ + USCIAB0TX_VECTOR,USCIAB0RX_VECTOR, TIMER0_A1_VECTOR, \ + COMPARATORA_VECTOR, TIMER1_A1_VECTOR, TIMER0_A0_VECTOR +__interrupt void ISR_trap(void) +{ + /* the following will cause an access violation and result in a PUC reset */ + WDTCTL = 0; +} + + diff --git a/pool/shard004/C/0099583_pata_ns87410.c b/pool/shard004/C/0099583_pata_ns87410.c new file mode 100644 index 0000000000000000000000000000000000000000..9944a28daa9c681874413ea23f8d95a938dc678a --- /dev/null +++ b/pool/shard004/C/0099583_pata_ns87410.c @@ -0,0 +1,240 @@ +/* + * pata_ns87410.c - National Semiconductor 87410 PATA for new ATA layer + * (C) 2006 Red Hat Inc + * Alan Cox + * + * 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; see the file COPYING. If not, write to + * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA. + */ + +#include +#include +#include +#include +#include +#include +#include +#include + +#define DRV_NAME "pata_ns87410" +#define DRV_VERSION "0.4.3" + +/** + * ns87410_pre_reset - probe begin + * @ap: ATA port + * + * Set up cable type and use generic probe init + */ + +static int ns87410_pre_reset(struct ata_port *ap) +{ + struct pci_dev *pdev = to_pci_dev(ap->host->dev); + static const struct pci_bits ns87410_enable_bits[] = { + { 0x43, 1, 0x08, 0x08 }, + { 0x47, 1, 0x08, 0x08 } + }; + + if (!pci_test_config_bits(pdev, &ns87410_enable_bits[ap->port_no])) + return -ENOENT; + ap->cbl = ATA_CBL_PATA40; + return ata_std_prereset(ap); +} + +/** + * ns87410_error_handler - probe reset + * @ap: ATA port + * + * Perform the ATA probe and bus reset sequence plus specific handling + * for this hardware. The MPIIX has the enable bits in a different place + * to PIIX4 and friends. As a pure PIO device it has no cable detect + */ + +static void ns87410_error_handler(struct ata_port *ap) +{ + ata_bmdma_drive_eh(ap, ns87410_pre_reset, ata_std_softreset, NULL, ata_std_postreset); +} + +/** + * ns87410_set_piomode - set initial PIO mode data + * @ap: ATA interface + * @adev: ATA device + * + * Program timing data. This is kept per channel not per device, + * and only affects the data port. + */ + +static void ns87410_set_piomode(struct ata_port *ap, struct ata_device *adev) +{ + struct pci_dev *pdev = to_pci_dev(ap->host->dev); + int port = 0x40 + 4 * ap->port_no; + u8 idetcr, idefr; + struct ata_timing at; + + static const u8 activebits[15] = { + 0, 1, 2, 3, 4, + 5, 5, 6, 6, 6, + 6, 7, 7, 7, 7 + }; + + static const u8 recoverbits[12] = { + 0, 1, 2, 3, 4, 5, 6, 6, 7, 7, 7, 7 + }; + + pci_read_config_byte(pdev, port + 3, &idefr); + + if (ata_pio_need_iordy(adev)) + idefr |= 0x04; /* IORDY enable */ + else + idefr &= ~0x04; + + if (ata_timing_compute(adev, adev->pio_mode, &at, 30303, 1) < 0) { + dev_printk(KERN_ERR, &pdev->dev, "unknown mode %d.\n", adev->pio_mode); + return; + } + + at.active = FIT(at.active, 2, 16) - 2; + at.setup = FIT(at.setup, 1, 4) - 1; + at.recover = FIT(at.recover, 1, 12) - 1; + + idetcr = (at.setup << 6) | (recoverbits[at.recover] << 3) | activebits[at.active]; + + pci_write_config_byte(pdev, port, idetcr); + pci_write_config_byte(pdev, port + 3, idefr); + /* We use ap->private_data as a pointer to the device currently + loaded for timing */ + ap->private_data = adev; +} + +/** + * ns87410_qc_issue_prot - command issue + * @qc: command pending + * + * Called when the libata layer is about to issue a command. We wrap + * this interface so that we can load the correct ATA timings if + * neccessary. + */ + +static unsigned int ns87410_qc_issue_prot(struct ata_queued_cmd *qc) +{ + struct ata_port *ap = qc->ap; + struct ata_device *adev = qc->dev; + + /* If modes have been configured and the channel data is not loaded + then load it. We have to check if pio_mode is set as the core code + does not set adev->pio_mode to XFER_PIO_0 while probing as would be + logical */ + + if (adev->pio_mode && adev != ap->private_data) + ns87410_set_piomode(ap, adev); + + return ata_qc_issue_prot(qc); +} + +static struct scsi_host_template ns87410_sht = { + .module = THIS_MODULE, + .name = DRV_NAME, + .ioctl = ata_scsi_ioctl, + .queuecommand = ata_scsi_queuecmd, + .can_queue = ATA_DEF_QUEUE, + .this_id = ATA_SHT_THIS_ID, + .sg_tablesize = LIBATA_MAX_PRD, + .cmd_per_lun = ATA_SHT_CMD_PER_LUN, + .emulated = ATA_SHT_EMULATED, + .use_clustering = ATA_SHT_USE_CLUSTERING, + .proc_name = DRV_NAME, + .dma_boundary = ATA_DMA_BOUNDARY, + .slave_configure = ata_scsi_slave_config, + .slave_destroy = ata_scsi_slave_destroy, + .bios_param = ata_std_bios_param, +#ifdef CONFIG_PM + .resume = ata_scsi_device_resume, + .suspend = ata_scsi_device_suspend, +#endif +}; + +static struct ata_port_operations ns87410_port_ops = { + .port_disable = ata_port_disable, + .set_piomode = ns87410_set_piomode, + + .tf_load = ata_tf_load, + .tf_read = ata_tf_read, + .check_status = ata_check_status, + .exec_command = ata_exec_command, + .dev_select = ata_std_dev_select, + + .freeze = ata_bmdma_freeze, + .thaw = ata_bmdma_thaw, + .error_handler = ns87410_error_handler, + .post_internal_cmd = ata_bmdma_post_internal_cmd, + + .qc_prep = ata_qc_prep, + .qc_issue = ns87410_qc_issue_prot, + + .data_xfer = ata_data_xfer, + + .irq_handler = ata_interrupt, + .irq_clear = ata_bmdma_irq_clear, + .irq_on = ata_irq_on, + .irq_ack = ata_irq_ack, + + .port_start = ata_port_start, +}; + +static int ns87410_init_one(struct pci_dev *dev, const struct pci_device_id *id) +{ + static struct ata_port_info info = { + .sht = &ns87410_sht, + .flags = ATA_FLAG_SLAVE_POSS | ATA_FLAG_SRST, + .pio_mask = 0x0F, + .port_ops = &ns87410_port_ops + }; + static struct ata_port_info *port_info[2] = {&info, &info}; + return ata_pci_init_one(dev, port_info, 2); +} + +static const struct pci_device_id ns87410[] = { + { PCI_VDEVICE(NS, PCI_DEVICE_ID_NS_87410), }, + + { }, +}; + +static struct pci_driver ns87410_pci_driver = { + .name = DRV_NAME, + .id_table = ns87410, + .probe = ns87410_init_one, + .remove = ata_pci_remove_one, +#ifdef CONFIG_PM + .suspend = ata_pci_device_suspend, + .resume = ata_pci_device_resume, +#endif +}; + +static int __init ns87410_init(void) +{ + return pci_register_driver(&ns87410_pci_driver); +} + +static void __exit ns87410_exit(void) +{ + pci_unregister_driver(&ns87410_pci_driver); +} + +MODULE_AUTHOR("Alan Cox"); +MODULE_DESCRIPTION("low-level driver for Nat Semi 87410"); +MODULE_LICENSE("GPL"); +MODULE_DEVICE_TABLE(pci, ns87410); +MODULE_VERSION(DRV_VERSION); + +module_init(ns87410_init); +module_exit(ns87410_exit); diff --git a/pool/shard004/C/0099587_pat_rbtree.c b/pool/shard004/C/0099587_pat_rbtree.c new file mode 100644 index 0000000000000000000000000000000000000000..fcc5d0bec53400e60df041e8978a236f5fb3c61e --- /dev/null +++ b/pool/shard004/C/0099587_pat_rbtree.c @@ -0,0 +1,249 @@ +/* + * Handle caching attributes in page tables (PAT) + * + * Authors: Venkatesh Pallipadi + * Suresh B Siddha + * + * Interval tree (augmented rbtree) used to store the PAT memory type + * reservations. + */ + +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +#include "pat_internal.h" + +/* + * The memtype tree keeps track of memory type for specific + * physical memory areas. Without proper tracking, conflicting memory + * types in different mappings can cause CPU cache corruption. + * + * The tree is an interval tree (augmented rbtree) with tree ordered + * on starting address. Tree can contain multiple entries for + * different regions which overlap. All the aliases have the same + * cache attributes of course. + * + * memtype_lock protects the rbtree. + */ + +static struct rb_root memtype_rbroot = RB_ROOT; + +static int is_node_overlap(struct memtype *node, u64 start, u64 end) +{ + if (node->start >= end || node->end <= start) + return 0; + + return 1; +} + +static u64 get_subtree_max_end(struct rb_node *node) +{ + u64 ret = 0; + if (node) { + struct memtype *data = container_of(node, struct memtype, rb); + ret = data->subtree_max_end; + } + return ret; +} + +static u64 compute_subtree_max_end(struct memtype *data) +{ + u64 max_end = data->end, child_max_end; + + child_max_end = get_subtree_max_end(data->rb.rb_right); + if (child_max_end > max_end) + max_end = child_max_end; + + child_max_end = get_subtree_max_end(data->rb.rb_left); + if (child_max_end > max_end) + max_end = child_max_end; + + return max_end; +} + +RB_DECLARE_CALLBACKS(static, memtype_rb_augment_cb, struct memtype, rb, + u64, subtree_max_end, compute_subtree_max_end) + +/* Find the first (lowest start addr) overlapping range from rb tree */ +static struct memtype *memtype_rb_lowest_match(struct rb_root *root, + u64 start, u64 end) +{ + struct rb_node *node = root->rb_node; + struct memtype *last_lower = NULL; + + while (node) { + struct memtype *data = container_of(node, struct memtype, rb); + + if (get_subtree_max_end(node->rb_left) > start) { + /* Lowest overlap if any must be on left side */ + node = node->rb_left; + } else if (is_node_overlap(data, start, end)) { + last_lower = data; + break; + } else if (start >= data->start) { + /* Lowest overlap if any must be on right side */ + node = node->rb_right; + } else { + break; + } + } + return last_lower; /* Returns NULL if there is no overlap */ +} + +static struct memtype *memtype_rb_exact_match(struct rb_root *root, + u64 start, u64 end) +{ + struct memtype *match; + + match = memtype_rb_lowest_match(root, start, end); + while (match != NULL && match->start < end) { + struct rb_node *node; + + if (match->start == start && match->end == end) + return match; + + node = rb_next(&match->rb); + if (node) + match = container_of(node, struct memtype, rb); + else + match = NULL; + } + + return NULL; /* Returns NULL if there is no exact match */ +} + +static int memtype_rb_check_conflict(struct rb_root *root, + u64 start, u64 end, + enum page_cache_mode reqtype, + enum page_cache_mode *newtype) +{ + struct rb_node *node; + struct memtype *match; + enum page_cache_mode found_type = reqtype; + + match = memtype_rb_lowest_match(&memtype_rbroot, start, end); + if (match == NULL) + goto success; + + if (match->type != found_type && newtype == NULL) + goto failure; + + dprintk("Overlap at 0x%Lx-0x%Lx\n", match->start, match->end); + found_type = match->type; + + node = rb_next(&match->rb); + while (node) { + match = container_of(node, struct memtype, rb); + + if (match->start >= end) /* Checked all possible matches */ + goto success; + + if (is_node_overlap(match, start, end) && + match->type != found_type) { + goto failure; + } + + node = rb_next(&match->rb); + } +success: + if (newtype) + *newtype = found_type; + + return 0; + +failure: + printk(KERN_INFO "%s:%d conflicting memory types " + "%Lx-%Lx %s<->%s\n", current->comm, task_pid_nr(current), start, + end, cattr_name(found_type), cattr_name(match->type)); + return -EBUSY; +} + +static void memtype_rb_insert(struct rb_root *root, struct memtype *newdata) +{ + struct rb_node **node = &(root->rb_node); + struct rb_node *parent = NULL; + + while (*node) { + struct memtype *data = container_of(*node, struct memtype, rb); + + parent = *node; + if (data->subtree_max_end < newdata->end) + data->subtree_max_end = newdata->end; + if (newdata->start <= data->start) + node = &((*node)->rb_left); + else if (newdata->start > data->start) + node = &((*node)->rb_right); + } + + newdata->subtree_max_end = newdata->end; + rb_link_node(&newdata->rb, parent, node); + rb_insert_augmented(&newdata->rb, root, &memtype_rb_augment_cb); +} + +int rbt_memtype_check_insert(struct memtype *new, + enum page_cache_mode *ret_type) +{ + int err = 0; + + err = memtype_rb_check_conflict(&memtype_rbroot, new->start, new->end, + new->type, ret_type); + + if (!err) { + if (ret_type) + new->type = *ret_type; + + new->subtree_max_end = new->end; + memtype_rb_insert(&memtype_rbroot, new); + } + return err; +} + +struct memtype *rbt_memtype_erase(u64 start, u64 end) +{ + struct memtype *data; + + data = memtype_rb_exact_match(&memtype_rbroot, start, end); + if (!data) + goto out; + + rb_erase_augmented(&data->rb, &memtype_rbroot, &memtype_rb_augment_cb); +out: + return data; +} + +struct memtype *rbt_memtype_lookup(u64 addr) +{ + struct memtype *data; + data = memtype_rb_lowest_match(&memtype_rbroot, addr, addr + PAGE_SIZE); + return data; +} + +#if defined(CONFIG_DEBUG_FS) +int rbt_memtype_copy_nth_element(struct memtype *out, loff_t pos) +{ + struct rb_node *node; + int i = 1; + + node = rb_first(&memtype_rbroot); + while (node && pos != i) { + node = rb_next(node); + i++; + } + + if (node) { /* pos == i */ + struct memtype *this = container_of(node, struct memtype, rb); + *out = *this; + return 0; + } else { + return 1; + } +} +#endif diff --git a/pool/shard004/C/0099597_linux-bgp-memory.c b/pool/shard004/C/0099597_linux-bgp-memory.c new file mode 100644 index 0000000000000000000000000000000000000000..f05468284e9b32010fa65ad79c82966f5b7dc61e --- /dev/null +++ b/pool/shard004/C/0099597_linux-bgp-memory.c @@ -0,0 +1,71 @@ +/* + * File: linux-bgp-memory.c + * Author: Dave Hermsmeier + * dlherms@us.ibm.com + */ + +#include "papi.h" +#include "papi_internal.h" +#ifdef __LINUX__ +#include +#endif +#include + +/* + * Prototypes... + */ +int init_bgp( PAPI_mh_info_t * pMem_Info ); + +/* + * Get Memory Information + * + * Fills in memory information - effectively set to all 0x00's + */ +extern int +_bgp_get_memory_info( PAPI_hw_info_t * pHwInfo, int pCPU_Type ) +{ + int retval = 0; + + switch ( pCPU_Type ) { + default: + //fprintf(stderr,"Default CPU type in %s (%d)\n",__FUNCTION__,__LINE__); + retval = init_bgp( &pHwInfo->mem_hierarchy ); + break; + } + + return retval; +} + +/* + * Get DMem Information for BG/P + * + * NOTE: Currently, all values set to -1 + */ +extern int +_bgp_get_dmem_info( PAPI_dmem_info_t * pDmemInfo ) +{ + + pDmemInfo->size = PAPI_EINVAL; + pDmemInfo->resident = PAPI_EINVAL; + pDmemInfo->high_water_mark = PAPI_EINVAL; + pDmemInfo->shared = PAPI_EINVAL; + pDmemInfo->text = PAPI_EINVAL; + pDmemInfo->library = PAPI_EINVAL; + pDmemInfo->heap = PAPI_EINVAL; + pDmemInfo->locked = PAPI_EINVAL; + pDmemInfo->stack = PAPI_EINVAL; + pDmemInfo->pagesize = PAPI_EINVAL; + + return PAPI_OK; +} + +/* + * Cache configuration for BG/P + */ +int +init_bgp( PAPI_mh_info_t * pMem_Info ) +{ + memset( pMem_Info, 0x0, sizeof ( *pMem_Info ) ); + + return PAPI_OK; +} diff --git a/pool/shard004/C/0099602_collate.c b/pool/shard004/C/0099602_collate.c new file mode 100644 index 0000000000000000000000000000000000000000..eaae04950d76f6c570b6e0006070dc26eb2fea09 --- /dev/null +++ b/pool/shard004/C/0099602_collate.c @@ -0,0 +1,217 @@ +#include +#include +#include +#include + +typedef struct { + const gchar **input; + const gchar **sorted; + const gchar **file_sorted; +} CollateTest; + +typedef struct { + const gchar *key; + const gchar *str; +} Line; + +int +compare_collate (const void *a, const void *b) +{ + const Line *line_a = a; + const Line *line_b = b; + + return g_utf8_collate (line_a->str, line_b->str); +} + +int +compare_key (const void *a, const void *b) +{ + const Line *line_a = a; + const Line *line_b = b; + + return strcmp (line_a->key, line_b->key); +} + +static void +do_collate (gboolean for_file, gboolean use_key, const CollateTest *test) +{ + GArray *line_array = g_array_new (FALSE, FALSE, sizeof(Line)); + Line line; + gint i; + + for (i = 0; test->input[i]; i++) + { + line.str = test->input[i]; + if (for_file) + line.key = g_utf8_collate_key_for_filename (line.str, -1); + else + line.key = g_utf8_collate_key (line.str, -1); + + g_array_append_val (line_array, line); + } + + qsort (line_array->data, line_array->len, sizeof (Line), use_key ? compare_key : compare_collate); + + for (i = 0; test->input[i]; i++) + { + const gchar *str; + str = g_array_index (line_array, Line, i).str; + if (for_file) + g_assert_cmpstr (str, ==, test->file_sorted[i]); + else + g_assert_cmpstr (str, ==, test->sorted[i]); + } +} + +static void +test_collate (gconstpointer d) +{ + const CollateTest *test = d; + do_collate (FALSE, FALSE, test); +} + +static void +test_collate_key (gconstpointer d) +{ + const CollateTest *test = d; + do_collate (FALSE, TRUE, test); +} + +static void +test_collate_file (gconstpointer d) +{ + const CollateTest *test = d; + do_collate (TRUE, TRUE, test); +} + +const gchar *input0[] = { + "z", + "c", + "eer34", + "223", + "er1", + "foo", + "bar", + "baz", + "GTK+", + NULL +}; + +const gchar *sorted0[] = { + "223", + "bar", + "baz", + "c", + "eer34", + "er1", + "foo", + "GTK+", + "z", + NULL +}; + +const gchar *file_sorted0[] = { + "223", + "bar", + "baz", + "c", + "eer34", + "er1", + "foo", + "GTK+", + "z", + NULL +}; + +const gchar *input1[] = { + "file.txt", + "file2.bla", + "file.c", + "file3.xx", + "bla001", + "bla02", + "bla03", + "bla4", + "bla10", + "bla100", + "event.c", + "eventgenerator.c", + "event.h", + NULL +}; + +const gchar *sorted1[] = { + "bla001", + "bla02", + "bla03", + "bla10", + "bla100", + "bla4", + "event.c", + "eventgenerator.c", + "event.h", + "file2.bla", + "file3.xx", + "file.c", + "file.txt", + NULL +}; + +const gchar *file_sorted1[] = { + "bla001", + "bla02", + "bla03", + "bla4", + "bla10", + "bla100", + "event.c", + "event.h", + "eventgenerator.c", + "file.c", + "file.txt", + "file2.bla", + "file3.xx", + NULL +}; + +int +main (int argc, char *argv[]) +{ + gchar *path; + gint i; + const gchar *locale; + CollateTest test[2]; + + g_test_init (&argc, &argv, NULL); + + g_setenv ("LC_ALL", "en_US", TRUE); + locale = setlocale (LC_ALL, ""); + if (locale == NULL || strcmp (locale, "en_US") != 0) + { + g_test_message ("No suitable locale, skipping test"); + return 0; + } + + test[0].input = input0; + test[0].sorted = sorted0; + test[0].file_sorted = file_sorted0; + test[1].input = input1; + test[1].sorted = sorted1; + test[1].file_sorted = file_sorted1; + + for (i = 0; i < G_N_ELEMENTS (test); i++) + { + path = g_strdup_printf ("/unicode/collate/%d", i); + g_test_add_data_func (path, &test[i], test_collate); + g_free (path); + path = g_strdup_printf ("/unicode/collate-key/%d", i); + g_test_add_data_func (path, test, test_collate_key); + g_free (path); + path = g_strdup_printf ("/unicode/collate-filename/%d", i); + g_test_add_data_func (path, test, test_collate_file); + g_free (path); + } + + return g_test_run (); +} + diff --git a/pool/shard004/C/0099603_abort.c b/pool/shard004/C/0099603_abort.c new file mode 100644 index 0000000000000000000000000000000000000000..e0e39d4a923eca33fca0bf2c1d9f1495b4408653 --- /dev/null +++ b/pool/shard004/C/0099603_abort.c @@ -0,0 +1,39 @@ +#include +#include +#include +#include + +void +abort(void) /* POSIX-style abort() function */ +{ + sigset_t mask; + struct sigaction action; + + /* caller can't ignore SIGABRT, if so reset to default */ + sigaction(SIGABRT, NULL, &action); + if (action.sa_handler == SIG_IGN) { + action.sa_handler = SIG_DFL; + sigaction(SIGABRT, &action, NULL); + } + + if (action.sa_handler == SIG_DFL) + fflush(NULL); /* flush all open stdio streams */ + + /* caller can't block SIGABRT; make sure it's unblocked */ + sigfillset(&mask); + sigdelset(&mask, SIGABRT); /* mask has only SIGABRT turned off */ + sigprocmask(SIG_SETMASK, &mask, NULL); + + kill(getpid(), SIGABRT); /* send the signal */ + + /* if we're here, process caught SIGABRT and returned */ + fflush(NULL); /* flush all open stdio streams */ + + action.sa_handler = SIG_DFL; + sigaction(SIGABRT, &action, NULL); /* reset disposition to default */ + sigprocmask(SIG_SETMASK, &mask, NULL); /* just in case ... */ + + kill(getpid(), SIGABRT); /* and one more time */ + + exit(1); /* this should never be executed ... */ +} diff --git a/pool/shard004/C/0099606_fuzixlib.c b/pool/shard004/C/0099606_fuzixlib.c new file mode 100644 index 0000000000000000000000000000000000000000..b07bfd1e24551f89fd7f5b2f8199883bc78a631e --- /dev/null +++ b/pool/shard004/C/0099606_fuzixlib.c @@ -0,0 +1,42 @@ +#include +#include +#include +#include +#include + +int main(int argc, char *argv[]) +{ + int fd; + char buf[16]; + + if (argc != 2) { + fprintf(stderr, "%s [binary].\n", argv[0]); + exit(1); + } + + fd = open(argv[1], O_RDWR); + if (fd == -1) { + perror(argv[1]); + exit(1); + } + if (read(fd, buf, 16) != 16) { + fprintf(stderr, "%s: could not read the header.\n", argv[1]); + exit(1); + } + if (memcmp(buf + 3, "FZX", 3)) { + fprintf(stderr, "%s: not a fuzix binary.\n", argv[1]); + exit(1); + } + buf[5] = 'L'; + + if (lseek(fd, 0L, SEEK_SET) < 0) { + perror(argv[1]); + exit(1); + } + + if (write(fd, buf, 16) != 16 || close(fd)) { + fprintf(stderr, "%s: header rewrite failed.\n", argv[1]); + exit(1); + } + return 0; +} diff --git a/pool/shard004/C/0099615_reduction-5.c b/pool/shard004/C/0099615_reduction-5.c new file mode 100644 index 0000000000000000000000000000000000000000..efe87027bbfe14e352ee350503fc44c930cc919d --- /dev/null +++ b/pool/shard004/C/0099615_reduction-5.c @@ -0,0 +1,32 @@ +#include +#include + +int +main (void) +{ + int s1 = 2, s2 = 5, v1 = 2, v2 = 5; + int n = 100; + int i; + +#pragma acc parallel vector_length (32) copy(s1,s2) +#pragma acc loop reduction (+:s1, s2) + for (i = 0; i < n; i++) + { + s1 = s1 + 3; + s2 = s2 + 2; + } + + for (i = 0; i < n; i++) + { + v1 = v1 + 3; + v2 = v2 + 2; + } + + if (s1 != v1) + abort (); + + if (s2 != v2) + abort (); + + return 0; +} diff --git a/pool/shard004/C/0099617_memory.c b/pool/shard004/C/0099617_memory.c new file mode 100644 index 0000000000000000000000000000000000000000..5054c2ddd1a03471b4423e7c9eb1719dca667901 --- /dev/null +++ b/pool/shard004/C/0099617_memory.c @@ -0,0 +1,140 @@ +/* -*- linux-c -*- ------------------------------------------------------- * + * + * Copyright (C) 1991, 1992 Linus Torvalds + * Copyright 2007 rPath, Inc. - All Rights Reserved + * Copyright 2009 Intel Corporation; author H. Peter Anvin + * + * This file is part of the Linux kernel, and is made available under + * the terms of the GNU General Public License version 2. + * + * ----------------------------------------------------------------------- */ + +/* + * Memory detection code + */ + +#include "boot.h" + +#define SMAP 0x534d4150 /* ASCII "SMAP" */ + +struct e820_ext_entry { + struct e820entry std; + u32 ext_flags; +} __attribute__((packed)); + +static int detect_memory_e820(void) +{ + int count = 0; + u32 next = 0; + u32 size, id, edi; + u8 err; + struct e820entry *desc = boot_params.e820_map; + static struct e820_ext_entry buf; /* static so it is zeroed */ + + /* + * Set this here so that if the BIOS doesn't change this field + * but still doesn't change %ecx, we're still okay... + */ + buf.ext_flags = 1; + + do { + size = sizeof buf; + + /* Important: %edx and %esi are clobbered by some BIOSes, + so they must be either used for the error output + or explicitly marked clobbered. Given that, assume there + is something out there clobbering %ebp and %edi, too. */ + asm("pushl %%ebp; int $0x15; popl %%ebp; setc %0" + : "=d" (err), "+b" (next), "=a" (id), "+c" (size), + "=D" (edi), "+m" (buf) + : "D" (&buf), "d" (SMAP), "a" (0xe820) + : "esi"); + + /* BIOSes which terminate the chain with CF = 1 as opposed + to %ebx = 0 don't always report the SMAP signature on + the final, failing, probe. */ + if (err) + break; + + /* Some BIOSes stop returning SMAP in the middle of + the search loop. We don't know exactly how the BIOS + screwed up the map at that point, we might have a + partial map, the full map, or complete garbage, so + just return failure. */ + if (id != SMAP) { + count = 0; + break; + } + + /* ACPI 3.0 added the extended flags support. If bit 0 + in the extended flags is zero, we're supposed to simply + ignore the entry -- a backwards incompatible change! */ + if (size > 20 && !(buf.ext_flags & 1)) + continue; + + *desc++ = buf.std; + count++; + } while (next && count < ARRAY_SIZE(boot_params.e820_map)); + + return boot_params.e820_entries = count; +} + +static int detect_memory_e801(void) +{ + u16 ax, bx, cx, dx; + u8 err; + + bx = cx = dx = 0; + ax = 0xe801; + asm("stc; int $0x15; setc %0" + : "=m" (err), "+a" (ax), "+b" (bx), "+c" (cx), "+d" (dx)); + + if (err) + return -1; + + /* Do we really need to do this? */ + if (cx || dx) { + ax = cx; + bx = dx; + } + + if (ax > 15*1024) + return -1; /* Bogus! */ + + /* This ignores memory above 16MB if we have a memory hole + there. If someone actually finds a machine with a memory + hole at 16MB and no support for 0E820h they should probably + generate a fake e820 map. */ + boot_params.alt_mem_k = (ax == 15*1024) ? (dx << 6)+ax : ax; + + return 0; +} + +static int detect_memory_88(void) +{ + u16 ax; + u8 err; + + ax = 0x8800; + asm("stc; int $0x15; setc %0" : "=bcdm" (err), "+a" (ax)); + + boot_params.screen_info.ext_mem_k = ax; + + return -err; +} + +int detect_memory(void) +{ + int err = -1; + + if (detect_memory_e820() > 0) + err = 0; + + if (!detect_memory_e801()) + err = 0; + + if (!detect_memory_88()) + err = 0; + + return err; +} diff --git a/pool/shard004/C/0099618_main.c b/pool/shard004/C/0099618_main.c new file mode 100644 index 0000000000000000000000000000000000000000..3b0d1871ec804b4666a56fb5f96aaaadf6ed30e6 --- /dev/null +++ b/pool/shard004/C/0099618_main.c @@ -0,0 +1,176 @@ +/** + * \file ferret/examples/list_demo/main.c + * \brief Example demonstrating the usage of lists. + * + * \date 25/11/2005 + * \author Martin Pohlack + * \author Bjoern Doebel + */ +/* + * (c) 2005-2009 Technische Universität Dresden + * This file is part of TUD:OS and distributed under the terms of the + * GNU General Public License 2. + * Please see the COPYING-GPL-2 file for details. + */ +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +#include + +int main(void) +{ + l4_cap_idx_t srv = lookup_sensordir(); + int i, j, loops; + + + // -=# monitoring code start #=- + ferret_list_local_t * l1 = NULL, * l2 = NULL, * l3 = NULL, * l4 = NULL; + int ret; + int index; + ferret_utime_t t; + + ferret_list_entry_common_t * elc; + ferret_list_entry_t * el; + + l4_sleep(1000); + // create sensor and configure it to an element size of 8 bytes with + // 100 list entries + ret = ferret_create(srv, 12, 1, 0, FERRET_LIST, + 0, "8:100", l1, &malloc); + if (ret) + { + printf("Error creating sensor: ret = %d\n", ret); + exit(1); + } + + // create sensor and configure it to an element size of 64 bytes with + // 1000 list entries + ret = ferret_create(srv, 12, 2, 0, FERRET_LIST, + FERRET_SUPERPAGES, "64:1000", l2, &malloc); + if (ret) + { + printf("Error creating sensor: ret = %d\n", ret); + exit(1); + } + + + // testing reopen here + ret = ferret_create(srv, 12, 2, 0, FERRET_LIST, + FERRET_SUPERPAGES, "64:1000", l3, &malloc); + if (ret) + { + printf("Error creating sensor: ret = %d\n", ret); + exit(1); + } + else + { + printf("Reopen worked.\n"); + } + + ret = ferret_create(srv, 12, 2, 0, FERRET_LIST, + FERRET_SUPERPAGES, "64:999", l4, &malloc); + if (ret) + { + printf("Error creating sensor: ret = %d (as expected)\n", ret); + } + else + { + printf("Reopen worked (should not).\n"); + exit(1); + } + + // -=# monitoring code end #=- + + j = 0; + while (1) + { + // -=# monitoring code start #=- + // this sensor has empty events, just timestamps are inserted + // on commiting, so we don't have to insert other data + //printf("X1: %p, %p, %p, %p\n", l1, l1->glob, l1->ind_buf, l1->out_buf); + index = ferret_list_dequeue(l1); + ferret_list_commit(l1, index); + index = ferret_list_dequeue(l1); + ferret_list_commit(l1, index); + index = ferret_list_dequeue(l1); + ferret_list_commit(l1, index); + index = ferret_list_dequeue(l1); + ferret_list_commit(l1, index); + // -=# monitoring code end #=- + + // -=# monitoring code start #=- + // this demonstrates to cast the received pointer to a certain + // struct and fill it + index = ferret_list_dequeue(l2); + elc = (ferret_list_entry_common_t *)ferret_list_e4i(l2->glob, index); + FERRET_GET_TIME(FERRET_TIME_REL_US, elc->data64[0]); + elc->major = 12; + elc->minor = 2; + elc->instance = 0; + elc->cpu = 0; + elc->data32[2] = 1; // start + elc->data32[3] = j; + ferret_list_commit(l2, index); + // -=# monitoring code end #=- + + // do some work + loops = 10000 + l4util_rand(); + for (i = 0; i < loops; i++) + asm volatile ("": : : "memory"); + + // -=# monitoring code start #=- + // here, dynamic marshaling is demonstrated + index = ferret_list_dequeue(l2); + el = ferret_list_e4i(l2->glob, index); + FERRET_GET_TIME(FERRET_TIME_REL_US, t); + //printf("%lld, %p, %p\n", t, el, l2->glob); + ret = ferret_util_pack("hhhbxqll", el->data, 12, 2, 0, 0, t, 2, j); + ferret_list_commit(l2, index); + // -=# monitoring code end #=- + + // -=# monitoring code start #=- + // demonstrate use of convenience wrappers here + ferret_list_post_c (1, l3, 12, 2, 0); + ferret_list_post_1wc(1, l3, 12, 2, 0, 1); + ferret_list_post_2wc(1, l3, 12, 2, 0, 1, 2); + ferret_list_post_3wc(1, l3, 12, 2, 0, 1, 2, 3); + ferret_list_post_4wc(1, l3, 12, 2, 0, 1, 2, 3, 4); + // -=# monitoring code end #=- + + l4_sleep(100); + j++; + } + + // -=# monitoring code start #=- + /* will never be reached due to the infinite loop above, but + * demonstrates cleanup. + * + * The sensor will be freed after all parties released it, that + * is, the creator and all monitors. + */ + ret = ferret_free_sensor(10, 1, 0, l1, &free); + if (ret) + { + printf("Error freeing sensor: ret = %d\n", ret); + exit(1); + } + + ret = ferret_free_sensor(10, 2, 0, l2, &free); + if (ret) + { + printf("Error freeing sensor: ret = %d\n", ret); + exit(1); + } + // -=# monitoring code end #=- + return 0; +} diff --git a/pool/shard004/C/0099626_test_event_ring.c b/pool/shard004/C/0099626_test_event_ring.c new file mode 100644 index 0000000000000000000000000000000000000000..70eb9845e1c29fdb38d332acf024330d100b1752 --- /dev/null +++ b/pool/shard004/C/0099626_test_event_ring.c @@ -0,0 +1,247 @@ +/* SPDX-License-Identifier: BSD-3-Clause + * Copyright(c) 2010-2017 Intel Corporation + */ + +#include + +#include + +#include "test.h" + +/* + * Event Ring + * =========== + * + * Test some basic ops for the event rings. + * Does not fully test everything, since most code is reused from rte_ring + * library and tested as part of the normal ring autotests. + */ + +#define RING_SIZE 4096 +#define MAX_BULK 32 + +static struct rte_event_ring *r; + +/* + * ensure failure to create ring with a bad ring size + */ +static int +test_event_ring_creation_with_wrong_size(void) +{ + struct rte_event_ring *rp = NULL; + + /* Test if ring size is not power of 2 */ + rp = rte_event_ring_create("test_bad_ring_size", RING_SIZE + 1, + SOCKET_ID_ANY, 0); + if (rp != NULL) + return -1; + + /* Test if ring size is exceeding the limit */ + rp = rte_event_ring_create("test_bad_ring_size", (RTE_RING_SZ_MASK + 1), + SOCKET_ID_ANY, 0); + if (rp != NULL) + return -1; + return 0; +} + +/* + * Test to check if a non-power-of-2 count causes the create + * function to fail correctly + */ +static int +test_create_count_odd(void) +{ + struct rte_event_ring *r = rte_event_ring_create("test_event_ring_count", + 4097, SOCKET_ID_ANY, 0); + if (r != NULL) + return -1; + return 0; +} + +static int +test_lookup_null(void) +{ + struct rte_event_ring *rlp = rte_event_ring_lookup("ring_not_found"); + if (rlp == NULL && rte_errno != ENOENT) { + printf("test failed to return error on null pointer\n"); + return -1; + } + return 0; +} + +static int +test_basic_event_enqueue_dequeue(void) +{ + struct rte_event_ring *sr = NULL; + struct rte_event evs[16]; + uint16_t ret, free_count, used_count; + + memset(evs, 0, sizeof(evs)); + sr = rte_event_ring_create("spsc_ring", 32, rte_socket_id(), + RING_F_SP_ENQ | RING_F_SC_DEQ); + if (sr == NULL) { + printf("Failed to create sp/sc ring\n"); + return -1; + } + if (rte_event_ring_get_capacity(sr) != 31) { + printf("Error, invalid capacity\n"); + goto error; + } + + /* test sp/sc ring */ + if (rte_event_ring_count(sr) != 0) { + printf("Error, ring not empty as expected\n"); + goto error; + } + if (rte_event_ring_free_count(sr) != rte_event_ring_get_capacity(sr)) { + printf("Error, ring free count not as expected\n"); + goto error; + } + + ret = rte_event_ring_enqueue_burst(sr, evs, RTE_DIM(evs), &free_count); + if (ret != RTE_DIM(evs) || + free_count != rte_event_ring_get_capacity(sr) - ret) { + printf("Error, status after enqueue is unexpected\n"); + goto error; + } + + ret = rte_event_ring_enqueue_burst(sr, evs, RTE_DIM(evs), &free_count); + if (ret != RTE_DIM(evs) - 1 || + free_count != 0) { + printf("Error, status after enqueue is unexpected\n"); + goto error; + } + + ret = rte_event_ring_dequeue_burst(sr, evs, RTE_DIM(evs), &used_count); + if (ret != RTE_DIM(evs) || + used_count != rte_event_ring_get_capacity(sr) - ret) { + printf("Error, status after enqueue is unexpected\n"); + goto error; + } + ret = rte_event_ring_dequeue_burst(sr, evs, RTE_DIM(evs), &used_count); + if (ret != RTE_DIM(evs) - 1 || + used_count != 0) { + printf("Error, status after enqueue is unexpected\n"); + goto error; + } + + rte_event_ring_free(sr); + return 0; +error: + rte_event_ring_free(sr); + return -1; +} + +static int +test_event_ring_with_exact_size(void) +{ + struct rte_event_ring *std_ring, *exact_sz_ring; + struct rte_event ev = { .mbuf = NULL }; + struct rte_event ev_array[16]; + static const unsigned int ring_sz = RTE_DIM(ev_array); + unsigned int i; + + std_ring = rte_event_ring_create("std", ring_sz, rte_socket_id(), + RING_F_SP_ENQ | RING_F_SC_DEQ); + if (std_ring == NULL) { + printf("%s: error, can't create std ring\n", __func__); + return -1; + } + exact_sz_ring = rte_event_ring_create("exact sz", + ring_sz, rte_socket_id(), + RING_F_SP_ENQ | RING_F_SC_DEQ | RING_F_EXACT_SZ); + if (exact_sz_ring == NULL) { + printf("%s: error, can't create exact size ring\n", __func__); + return -1; + } + + /* + * Check that the exact size ring is bigger than the standard ring + */ + if (rte_event_ring_get_size(std_ring) >= + rte_event_ring_get_size(exact_sz_ring)) { + printf("%s: error, std ring (size: %u) is not smaller than exact size one (size %u)\n", + __func__, + rte_event_ring_get_size(std_ring), + rte_event_ring_get_size(exact_sz_ring)); + return -1; + } + /* + * check that the exact_sz_ring can hold one more element than the + * standard ring. (16 vs 15 elements) + */ + for (i = 0; i < ring_sz - 1; i++) { + rte_event_ring_enqueue_burst(std_ring, &ev, 1, NULL); + rte_event_ring_enqueue_burst(exact_sz_ring, &ev, 1, NULL); + } + if (rte_event_ring_enqueue_burst(std_ring, &ev, 1, NULL) != 0) { + printf("%s: error, unexpected successful enqueue\n", __func__); + return -1; + } + if (rte_event_ring_enqueue_burst(exact_sz_ring, &ev, 1, NULL) != 1) { + printf("%s: error, enqueue failed\n", __func__); + return -1; + } + + /* check that dequeue returns the expected number of elements */ + if (rte_event_ring_dequeue_burst(exact_sz_ring, ev_array, + RTE_DIM(ev_array), NULL) != ring_sz) { + printf("%s: error, failed to dequeue expected nb of elements\n", + __func__); + return -1; + } + + /* check that the capacity function returns expected value */ + if (rte_event_ring_get_capacity(exact_sz_ring) != ring_sz) { + printf("%s: error, incorrect ring capacity reported\n", + __func__); + return -1; + } + + rte_event_ring_free(std_ring); + rte_event_ring_free(exact_sz_ring); + return 0; +} + +static int +test_event_ring(void) +{ + if (r == NULL) + r = rte_event_ring_create("ev_test", RING_SIZE, + SOCKET_ID_ANY, 0); + if (r == NULL) + return -1; + + /* retrieve the ring from its name */ + if (rte_event_ring_lookup("ev_test") != r) { + printf("Cannot lookup ring from its name\n"); + return -1; + } + + /* basic operations */ + if (test_create_count_odd() < 0) { + printf("Test failed to detect odd count\n"); + return -1; + } + printf("Test detected odd count\n"); + + if (test_lookup_null() < 0) { + printf("Test failed to detect NULL ring lookup\n"); + return -1; + } + printf("Test detected NULL ring lookup\n"); + + /* test of creating ring with wrong size */ + if (test_event_ring_creation_with_wrong_size() < 0) + return -1; + + if (test_basic_event_enqueue_dequeue() < 0) + return -1; + + if (test_event_ring_with_exact_size() < 0) + return -1; + + return 0; +} + +REGISTER_TEST_COMMAND(event_ring_autotest, test_event_ring); diff --git a/pool/shard004/C/0099629_nr_mem_test.c b/pool/shard004/C/0099629_nr_mem_test.c new file mode 100644 index 0000000000000000000000000000000000000000..34a8814d08d39ec5f64e53c96d5cac70d0f9ba70 --- /dev/null +++ b/pool/shard004/C/0099629_nr_mem_test.c @@ -0,0 +1,108 @@ +/* +Non-readable memory test case + +Copyright(c) 2015 Chris Eagle + +This program is free software; you can redistribute it and/or +modify it under the terms of the GNU General Public License +version 2 as published by the Free Software Foundation. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program; if not, write to the Free Software +Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + +*/ + +#include + +#include + +const uint8_t PROGRAM[] = + "\x8b\x1d\x00\x00\x30\x00\xa1\x00\x00\x40\x00"; +// total size: 11 bytes + +/* +bits 32 + + mov ebx, [0x300000] + mov eax, [0x400000] +*/ + +// callback for tracing memory access (READ or WRITE) +static bool hook_mem_invalid(uc_engine *uc, uc_mem_type type, + uint64_t address, int size, int64_t value, void *user_data) +{ + + switch(type) { + default: + // return false to indicate we want to stop emulation + return false; + case UC_MEM_READ_PROT: + printf(">>> non-readable memory is being read at 0x%"PRIx64 ", data size = %u\n", + address, size); + return false; + } +} + + +int main(int argc, char **argv, char **envp) +{ + uc_engine *uc; + uc_hook trace1; + uc_err err; + uint32_t eax, ebx; + + printf("Memory protections test\n"); + + // Initialize emulator in X86-32bit mode + err = uc_open(UC_ARCH_X86, UC_MODE_32, &uc); + if (err) { + printf("Failed on uc_open() with error returned: %u\n", err); + return 1; + } + + uc_mem_map(uc, 0x100000, 0x1000, UC_PROT_READ); + uc_mem_map(uc, 0x300000, 0x1000, UC_PROT_READ | UC_PROT_WRITE); + uc_mem_map(uc, 0x400000, 0x1000, UC_PROT_WRITE); + + // write machine code to be emulated to memory + if (uc_mem_write(uc, 0x100000, PROGRAM, sizeof(PROGRAM))) { + printf("Failed to write emulation code to memory, quit!\n"); + return 2; + } else { + printf("Allowed to write to read only memory via uc_mem_write\n"); + } + + uc_mem_write(uc, 0x300000, (const uint8_t*)"\x41\x41\x41\x41", 4); + uc_mem_write(uc, 0x400000, (const uint8_t*)"\x42\x42\x42\x42", 4); + + //uc_hook_add(uc, &trace2, UC_HOOK_CODE, hook_code, NULL, 0x400000, 0x400fff); + + // intercept invalid memory events + uc_hook_add(uc, &trace1, UC_MEM_READ_PROT, hook_mem_invalid, NULL, 1, 0); + + // emulate machine code in infinite time + printf("BEGIN execution\n"); + err = uc_emu_start(uc, 0x100000, 0x100000 + sizeof(PROGRAM), 0, 2); + if (err) { + printf("Expected failure on uc_emu_start() with error returned %u: %s\n", + err, uc_strerror(err)); + } else { + printf("UNEXPECTED uc_emu_start returned UC_ERR_OK\n"); + } + printf("END execution\n"); + + uc_reg_read(uc, UC_X86_REG_EAX, &eax); + printf("Final eax = 0x%x\n", eax); + uc_reg_read(uc, UC_X86_REG_EBX, &ebx); + printf("Final ebx = 0x%x\n", ebx); + + uc_close(uc); + + return 0; +} diff --git a/pool/shard004/C/0099633_compute_hierarchy.c b/pool/shard004/C/0099633_compute_hierarchy.c new file mode 100644 index 0000000000000000000000000000000000000000..05833fc952eb87e97a214d98645ae5e27c8f9268 --- /dev/null +++ b/pool/shard004/C/0099633_compute_hierarchy.c @@ -0,0 +1,135 @@ +/* $Id: compute_hierarchy.c,v 1.6 2011/01/25 16:30:49 ellson Exp $ $Revision: 1.6 $ */ +/* 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/ + *************************************************************************/ + +#include +#ifdef DIGCOLA +#include "kkutils.h" + +static int* given_levels = NULL; +/* + * This function partitions the graph nodes into levels + * according to the minimizer of the hierarchy energy. + * + * To allow more flexibility we define a new level only + * when the hierarchy energy shows a significant jump + * (to compensate for noise). + * This is controlled by two parameters: 'abs_tol' and + * 'relative_tol'. The smaller these two are, the more + * levels we'll get. + * More speciffically: + * We never consider gaps smaller than 'abs_tol' + * Additionally, we never consider gaps smaller than 'abs_tol'* + * + * The output is an ordering of the nodes according to + * their levels, as follows: + * First level: + * ordering[0],ordering[1],...ordering[levels[0]-1] + * Second level: + * ordering[levels[0]],ordering[levels[0]+1],...ordering[levels[1]-1] + * ... + * Last level: + * ordering[levels[num_levels-1]],ordering[levels[num_levels-1]+1],...ordering[n-1] + * + * Hence, the nodes were partitioned into 'num_levels'+1 + * levels. + * + * Please note that 'ordering[levels[i]]' contains the first node at level i+1, + * and not the last node of level i. + */ +double +compute_hierarchy(vtx_data* graph, int n, double abs_tol, double relative_tol, + double* given_coords, int** orderingp, int** levelsp, int* num_levelsp) +{ + double* y; + int i; + double spread; + int use_given_levels=FALSE; + int* ordering; + int* levels; + double tol; /* node 'i' precedes 'j' in hierachy iff y[i]-y[j]>tol */ + double hierarchy_span; + int num_levels; + + /* compute optimizer of hierarchy energy: 'y' */ + if (given_coords) { + y = given_coords; + } + else { + y = N_GNEW(n,double); + compute_y_coords(graph, n, y, n); + } + + /* sort nodes accoridng to their y-ordering */ + *orderingp = ordering = N_NEW(n, int); + for (i=0; i=0; + } + } + if (use_given_levels) { + for (i=0; i tol) { + num_levels++; + } + } + *num_levelsp = num_levels; + if (num_levels==0) { + *levelsp = levels = N_GNEW(1, int); + levels[0] = n; + } + else { + int count=0; + *levelsp = levels = N_GNEW(num_levels, int); + for (i=1; i tol) { + levels[count++] = i; + } + } + } + if (!given_coords) { + free(y); + } + + return spread; +} + +#endif /* DIGCOLA */ + diff --git a/pool/shard004/C/0099647_stm32f7xx_ll_sdmmc.c b/pool/shard004/C/0099647_stm32f7xx_ll_sdmmc.c new file mode 100644 index 0000000000000000000000000000000000000000..e4f44aa3ddd416598945546335be8975897ba588 --- /dev/null +++ b/pool/shard004/C/0099647_stm32f7xx_ll_sdmmc.c @@ -0,0 +1,510 @@ +/** + ****************************************************************************** + * @file stm32f7xx_ll_sdmmc.c + * @author MCD Application Team + * @version V1.0.0 + * @date 12-May-2015 + * @brief SDMMC Low Layer HAL module driver. + * + * This file provides firmware functions to manage the following + * functionalities of the SDMMC peripheral: + * + Initialization/de-initialization functions + * + I/O operation functions + * + Peripheral Control functions + * + Peripheral State functions + * + @verbatim + ============================================================================== + ##### SDMMC peripheral features ##### + ============================================================================== + [..] The SD/SDMMC MMC card host interface (SDMMC) provides an interface between the APB2 + peripheral bus and MultiMedia cards (MMCs), SD memory cards, SDMMC cards and CE-ATA + devices. + + [..] The SDMMC features include the following: + (+) Full compliance with MultiMedia Card System Specification Version 4.2. Card support + for three different databus modes: 1-bit (default), 4-bit and 8-bit + (+) Full compatibility with previous versions of MultiMedia Cards (forward compatibility) + (+) Full compliance with SD Memory Card Specifications Version 2.0 + (+) Full compliance with SD I/O Card Specification Version 2.0: card support for two + different data bus modes: 1-bit (default) and 4-bit + (+) Full support of the CE-ATA features (full compliance with CE-ATA digital protocol + Rev1.1) + (+) Data transfer up to 48 MHz for the 8 bit mode + (+) Data and command output enable signals to control external bidirectional drivers. + + + ##### How to use this driver ##### + ============================================================================== + [..] + This driver is a considered as a driver of service for external devices drivers + that interfaces with the SDMMC peripheral. + According to the device used (SD card/ MMC card / SDMMC card ...), a set of APIs + is used in the device's driver to perform SDMMC operations and functionalities. + + This driver is almost transparent for the final user, it is only used to implement other + functionalities of the external device. + + [..] + (+) The SDMMC clock (SDMMCCLK = 48 MHz) is coming from a specific output of PLL + (PLL48CLK). Before start working with SDMMC peripheral make sure that the + PLL is well configured. + The SDMMC peripheral uses two clock signals: + (++) SDMMC adapter clock (SDMMCCLK = 48 MHz) + (++) APB2 bus clock (PCLK2) + + -@@- PCLK2 and SDMMC_CK clock frequencies must respect the following condition: + Frequency(PCLK2) >= (3 / 8 x Frequency(SDMMC_CK)) + + (+) Enable/Disable peripheral clock using RCC peripheral macros related to SDMMC + peripheral. + + (+) Enable the Power ON State using the SDMMC_PowerState_ON(SDMMCx) + function and disable it using the function SDMMC_PowerState_OFF(SDMMCx). + + (+) Enable/Disable the clock using the __SDMMC_ENABLE()/__SDMMC_DISABLE() macros. + + (+) Enable/Disable the peripheral interrupts using the macros __SDMMC_ENABLE_IT(hSDMMC, IT) + and __SDMMC_DISABLE_IT(hSDMMC, IT) if you need to use interrupt mode. + + (+) When using the DMA mode + (++) Configure the DMA in the MSP layer of the external device + (++) Active the needed channel Request + (++) Enable the DMA using __SDMMC_DMA_ENABLE() macro or Disable it using the macro + __SDMMC_DMA_DISABLE(). + + (+) To control the CPSM (Command Path State Machine) and send + commands to the card use the SDMMC_SendCommand(SDMMCx), + SDMMC_GetCommandResponse() and SDMMC_GetResponse() functions. First, user has + to fill the command structure (pointer to SDMMC_CmdInitTypeDef) according + to the selected command to be sent. + The parameters that should be filled are: + (++) Command Argument + (++) Command Index + (++) Command Response type + (++) Command Wait + (++) CPSM Status (Enable or Disable). + + -@@- To check if the command is well received, read the SDMMC_CMDRESP + register using the SDMMC_GetCommandResponse(). + The SDMMC responses registers (SDMMC_RESP1 to SDMMC_RESP2), use the + SDMMC_GetResponse() function. + + (+) To control the DPSM (Data Path State Machine) and send/receive + data to/from the card use the SDMMC_DataConfig(), SDMMC_GetDataCounter(), + SDMMC_ReadFIFO(), DIO_WriteFIFO() and SDMMC_GetFIFOCount() functions. + + *** Read Operations *** + ======================= + [..] + (#) First, user has to fill the data structure (pointer to + SDMMC_DataInitTypeDef) according to the selected data type to be received. + The parameters that should be filled are: + (++) Data TimeOut + (++) Data Length + (++) Data Block size + (++) Data Transfer direction: should be from card (To SDMMC) + (++) Data Transfer mode + (++) DPSM Status (Enable or Disable) + + (#) Configure the SDMMC resources to receive the data from the card + according to selected transfer mode (Refer to Step 8, 9 and 10). + + (#) Send the selected Read command (refer to step 11). + + (#) Use the SDMMC flags/interrupts to check the transfer status. + + *** Write Operations *** + ======================== + [..] + (#) First, user has to fill the data structure (pointer to + SDMMC_DataInitTypeDef) according to the selected data type to be received. + The parameters that should be filled are: + (++) Data TimeOut + (++) Data Length + (++) Data Block size + (++) Data Transfer direction: should be to card (To CARD) + (++) Data Transfer mode + (++) DPSM Status (Enable or Disable) + + (#) Configure the SDMMC resources to send the data to the card according to + selected transfer mode. + + (#) Send the selected Write command. + + (#) Use the SDMMC flags/interrupts to check the transfer 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 "stm32f7xx_hal.h" + +/** @addtogroup STM32F7xx_HAL_Driver + * @{ + */ + +/** @defgroup SDMMC_LL SDMMC Low Layer + * @brief Low layer module for SD + * @{ + */ + +#if defined (HAL_SD_MODULE_ENABLED) || defined(HAL_MMC_MODULE_ENABLED) + +/* Private typedef -----------------------------------------------------------*/ +/* Private define ------------------------------------------------------------*/ +/* Private macro -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private function prototypes -----------------------------------------------*/ +/* Exported functions --------------------------------------------------------*/ + +/** @defgroup SDMMC_LL_Exported_Functions SDMMC Low Layer Exported Functions + * @{ + */ + +/** @defgroup HAL_SDMMC_LL_Group1 Initialization de-initialization functions + * @brief Initialization and Configuration functions + * +@verbatim + =============================================================================== + ##### Initialization/de-initialization functions ##### + =============================================================================== + [..] This section provides functions allowing to: + +@endverbatim + * @{ + */ + +/** + * @brief Initializes the SDMMC according to the specified + * parameters in the SDMMC_InitTypeDef and create the associated handle. + * @param SDMMCx: Pointer to SDMMC register base + * @param Init: SDMMC initialization structure + * @retval HAL status + */ +HAL_StatusTypeDef SDMMC_Init(SDMMC_TypeDef *SDMMCx, SDMMC_InitTypeDef Init) +{ + uint32_t tmpreg = 0; + + /* Check the parameters */ + assert_param(IS_SDMMC_ALL_INSTANCE(SDMMCx)); + assert_param(IS_SDMMC_CLOCK_EDGE(Init.ClockEdge)); + assert_param(IS_SDMMC_CLOCK_BYPASS(Init.ClockBypass)); + assert_param(IS_SDMMC_CLOCK_POWER_SAVE(Init.ClockPowerSave)); + assert_param(IS_SDMMC_BUS_WIDE(Init.BusWide)); + assert_param(IS_SDMMC_HARDWARE_FLOW_CONTROL(Init.HardwareFlowControl)); + assert_param(IS_SDMMC_CLKDIV(Init.ClockDiv)); + + /* Set SDMMC configuration parameters */ + tmpreg |= (Init.ClockEdge |\ + Init.ClockBypass |\ + Init.ClockPowerSave |\ + Init.BusWide |\ + Init.HardwareFlowControl |\ + Init.ClockDiv + ); + + /* Write to SDMMC CLKCR */ + MODIFY_REG(SDMMCx->CLKCR, CLKCR_CLEAR_MASK, tmpreg); + + return HAL_OK; +} + + + +/** + * @} + */ + +/** @defgroup HAL_SDMMC_LL_Group2 IO operation functions + * @brief Data transfers functions + * +@verbatim + =============================================================================== + ##### I/O operation functions ##### + =============================================================================== + [..] + This subsection provides a set of functions allowing to manage the SDMMC data + transfers. + +@endverbatim + * @{ + */ + +/** + * @brief Read data (word) from Rx FIFO in blocking mode (polling) + * @param SDMMCx: Pointer to SDMMC register base + * @retval HAL status + */ +uint32_t SDMMC_ReadFIFO(SDMMC_TypeDef *SDMMCx) +{ + /* Read data from Rx FIFO */ + return (SDMMCx->FIFO); +} + +/** + * @brief Write data (word) to Tx FIFO in blocking mode (polling) + * @param SDMMCx: Pointer to SDMMC register base + * @param pWriteData: pointer to data to write + * @retval HAL status + */ +HAL_StatusTypeDef SDMMC_WriteFIFO(SDMMC_TypeDef *SDMMCx, uint32_t *pWriteData) +{ + /* Write data to FIFO */ + SDMMCx->FIFO = *pWriteData; + + return HAL_OK; +} + +/** + * @} + */ + +/** @defgroup HAL_SDMMC_LL_Group3 Peripheral Control functions + * @brief management functions + * +@verbatim + =============================================================================== + ##### Peripheral Control functions ##### + =============================================================================== + [..] + This subsection provides a set of functions allowing to control the SDMMC data + transfers. + +@endverbatim + * @{ + */ + +/** + * @brief Set SDMMC Power state to ON. + * @param SDMMCx: Pointer to SDMMC register base + * @retval HAL status + */ +HAL_StatusTypeDef SDMMC_PowerState_ON(SDMMC_TypeDef *SDMMCx) +{ + /* Set power state to ON */ + SDMMCx->POWER = SDMMC_POWER_PWRCTRL; + + return HAL_OK; +} + +/** + * @brief Set SDMMC Power state to OFF. + * @param SDMMCx: Pointer to SDMMC register base + * @retval HAL status + */ +HAL_StatusTypeDef SDMMC_PowerState_OFF(SDMMC_TypeDef *SDMMCx) +{ + /* Set power state to OFF */ + SDMMCx->POWER = (uint32_t)0x00000000; + + return HAL_OK; +} + +/** + * @brief Get SDMMC Power state. + * @param SDMMCx: Pointer to SDMMC register base + * @retval Power status of the controller. The returned value can be one of the + * following values: + * - 0x00: Power OFF + * - 0x02: Power UP + * - 0x03: Power ON + */ +uint32_t SDMMC_GetPowerState(SDMMC_TypeDef *SDMMCx) +{ + return (SDMMCx->POWER & SDMMC_POWER_PWRCTRL); +} + +/** + * @brief Configure the SDMMC command path according to the specified parameters in + * SDMMC_CmdInitTypeDef structure and send the command + * @param SDMMCx: Pointer to SDMMC register base + * @param Command: pointer to a SDMMC_CmdInitTypeDef structure that contains + * the configuration information for the SDMMC command + * @retval HAL status + */ +HAL_StatusTypeDef SDMMC_SendCommand(SDMMC_TypeDef *SDMMCx, SDMMC_CmdInitTypeDef *Command) +{ + uint32_t tmpreg = 0; + + /* Check the parameters */ + assert_param(IS_SDMMC_CMD_INDEX(Command->CmdIndex)); + assert_param(IS_SDMMC_RESPONSE(Command->Response)); + assert_param(IS_SDMMC_WAIT(Command->WaitForInterrupt)); + assert_param(IS_SDMMC_CPSM(Command->CPSM)); + + /* Set the SDMMC Argument value */ + SDMMCx->ARG = Command->Argument; + + /* Set SDMMC command parameters */ + tmpreg |= (uint32_t)(Command->CmdIndex |\ + Command->Response |\ + Command->WaitForInterrupt |\ + Command->CPSM); + + /* Write to SDMMC CMD register */ + MODIFY_REG(SDMMCx->CMD, CMD_CLEAR_MASK, tmpreg); + + return HAL_OK; +} + +/** + * @brief Return the command index of last command for which response received + * @param SDMMCx: Pointer to SDMMC register base + * @retval Command index of the last command response received + */ +uint8_t SDMMC_GetCommandResponse(SDMMC_TypeDef *SDMMCx) +{ + return (uint8_t)(SDMMCx->RESPCMD); +} + + +/** + * @brief Return the response received from the card for the last command + * @param SDMMCx: Pointer to SDMMC register base + * @param Response: Specifies the SDMMC response register. + * This parameter can be one of the following values: + * @arg SDMMC_RESP1: Response Register 1 + * @arg SDMMC_RESP2: Response Register 2 + * @arg SDMMC_RESP3: Response Register 3 + * @arg SDMMC_RESP4: Response Register 4 + * @retval The Corresponding response register value + */ +uint32_t SDMMC_GetResponse(SDMMC_TypeDef *SDMMCx, uint32_t Response) +{ + __IO uint32_t tmp = 0; + + /* Check the parameters */ + assert_param(IS_SDMMC_RESP(Response)); + + /* Get the response */ + tmp = (uint32_t)&(SDMMCx->RESP1) + Response; + + return (*(__IO uint32_t *) tmp); +} + +/** + * @brief Configure the SDMMC data path according to the specified + * parameters in the SDMMC_DataInitTypeDef. + * @param SDMMCx: Pointer to SDMMC register base + * @param Data : pointer to a SDMMC_DataInitTypeDef structure + * that contains the configuration information for the SDMMC data. + * @retval HAL status + */ +HAL_StatusTypeDef SDMMC_DataConfig(SDMMC_TypeDef *SDMMCx, SDMMC_DataInitTypeDef* Data) +{ + uint32_t tmpreg = 0; + + /* Check the parameters */ + assert_param(IS_SDMMC_DATA_LENGTH(Data->DataLength)); + assert_param(IS_SDMMC_BLOCK_SIZE(Data->DataBlockSize)); + assert_param(IS_SDMMC_TRANSFER_DIR(Data->TransferDir)); + assert_param(IS_SDMMC_TRANSFER_MODE(Data->TransferMode)); + assert_param(IS_SDMMC_DPSM(Data->DPSM)); + + /* Set the SDMMC Data TimeOut value */ + SDMMCx->DTIMER = Data->DataTimeOut; + + /* Set the SDMMC DataLength value */ + SDMMCx->DLEN = Data->DataLength; + + /* Set the SDMMC data configuration parameters */ + tmpreg |= (uint32_t)(Data->DataBlockSize |\ + Data->TransferDir |\ + Data->TransferMode |\ + Data->DPSM); + + /* Write to SDMMC DCTRL */ + MODIFY_REG(SDMMCx->DCTRL, DCTRL_CLEAR_MASK, tmpreg); + + return HAL_OK; + +} + +/** + * @brief Returns number of remaining data bytes to be transferred. + * @param SDMMCx: Pointer to SDMMC register base + * @retval Number of remaining data bytes to be transferred + */ +uint32_t SDMMC_GetDataCounter(SDMMC_TypeDef *SDMMCx) +{ + return (SDMMCx->DCOUNT); +} + +/** + * @brief Get the FIFO data + * @param SDMMCx: Pointer to SDMMC register base + * @retval Data received + */ +uint32_t SDMMC_GetFIFOCount(SDMMC_TypeDef *SDMMCx) +{ + return (SDMMCx->FIFO); +} + + +/** + * @brief Sets one of the two options of inserting read wait interval. + * @param SDMMCx: Pointer to SDMMC register base + * @param SDMMC_ReadWaitMode: SDMMC Read Wait operation mode. + * This parameter can be: + * @arg SDMMC_READ_WAIT_MODE_CLK: Read Wait control by stopping SDMMCCLK + * @arg SDMMC_READ_WAIT_MODE_DATA2: Read Wait control using SDMMC_DATA2 + * @retval None + */ +HAL_StatusTypeDef SDMMC_SetSDMMCReadWaitMode(SDMMC_TypeDef *SDMMCx, uint32_t SDMMC_ReadWaitMode) +{ + /* Check the parameters */ + assert_param(IS_SDMMC_READWAIT_MODE(SDMMC_ReadWaitMode)); + + /* Set SDMMC read wait mode */ + SDMMCx->DCTRL |= SDMMC_ReadWaitMode; + + return HAL_OK; +} + +/** + * @} + */ + +/** + * @} + */ + +#endif /* (HAL_SD_MODULE_ENABLED) || (HAL_MMC_MODULE_ENABLED) */ +/** + * @} + */ + +/** + * @} + */ + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/pool/shard004/C/0099656_example.c b/pool/shard004/C/0099656_example.c new file mode 100644 index 0000000000000000000000000000000000000000..7a730f82c08686cc9c91d7b6a9b6b5c3896d69ba --- /dev/null +++ b/pool/shard004/C/0099656_example.c @@ -0,0 +1,39 @@ +/** +* @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/blas/ext/base/ssorthp.h" +#include + +int main() { + // Create a strided array: + float x[] = { 1.0, -2.0, 3.0, -4.0, 5.0, -6.0, 7.0, -8.0 }; + + // Specify the number of elements: + int N = 8; + + // Specify a stride: + int strideX = 1; + + // Sort the array: + c_ssorthp( N, 1.0f, x, strideX ); + + // Print the result: + for ( int i = 0; i < 8; i++ ) { + printf( "x[ %i ] = %f\n", i, x[ i ] ); + } +} diff --git a/pool/shard004/C/0099662_ip22-eisa.c b/pool/shard004/C/0099662_ip22-eisa.c new file mode 100644 index 0000000000000000000000000000000000000000..a2b5baf5657efe2fa0362b76be614963b18da8a2 --- /dev/null +++ b/pool/shard004/C/0099662_ip22-eisa.c @@ -0,0 +1,155 @@ +/* + * Basic EISA bus support for the SGI Indigo-2. + * + * (C) 2002 Pascal Dameme + * and Marc Zyngier + * + * This code is released under both the GPL version 2 and BSD + * licenses. Either license may be used. + * + * This code offers a very basic support for this EISA bus present in + * the SGI Indigo-2. It currently only supports PIO (forget about DMA + * for the time being). This is enough for a low-end ethernet card, + * but forget about your favorite SCSI card... + * + * TODO : + * - Fix bugs... + * - Add ISA support + * - Add DMA (yeah, right...). + * - Fix more bugs. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +/* I2 has four EISA slots. */ +#define IP22_EISA_MAX_SLOTS 4 +#define EISA_MAX_IRQ 16 + +#define EIU_MODE_REG 0x0001ffc0 +#define EIU_STAT_REG 0x0001ffc4 +#define EIU_PREMPT_REG 0x0001ffc8 +#define EIU_QUIET_REG 0x0001ffcc +#define EIU_INTRPT_ACK 0x00010004 + +static char __init *decode_eisa_sig(unsigned long addr) +{ + static char sig_str[EISA_SIG_LEN] __initdata; + u8 sig[4]; + u16 rev; + int i; + + for (i = 0; i < 4; i++) + { + sig[i] = inb(addr + i); + + if (!i && (sig[0] & 0x80)) + { + return NULL; + } + } + + sig_str[0] = ((sig[0] >> 2) & 0x1f) + ('A' - 1); + sig_str[1] = (((sig[0] & 3) << 3) | (sig[1] >> 5)) + ('A' - 1); + sig_str[2] = (sig[1] & 0x1f) + ('A' - 1); + rev = (sig[2] << 8) | sig[3]; + sprintf(sig_str + 3, "%04X", rev); + + return sig_str; +} + +static irqreturn_t ip22_eisa_intr(int irq, void *dev_id) +{ + u8 eisa_irq = inb(EIU_INTRPT_ACK); + + inb(EISA_DMA1_STATUS); + inb(EISA_DMA2_STATUS); + + if (eisa_irq < EISA_MAX_IRQ) + { + do_IRQ(eisa_irq); + return IRQ_HANDLED; + } + + /* Oops, Bad Stuff Happened... */ + printk(KERN_ERR "eisa_irq %d out of bound\n", eisa_irq); + + outb(0x20, EISA_INT2_CTRL); + outb(0x20, EISA_INT1_CTRL); + + return IRQ_NONE; +} + +static struct irqaction eisa_action = +{ + .handler = ip22_eisa_intr, + .name = "EISA", +}; + +int __init ip22_eisa_init(void) +{ + int i, c; + char *str; + + if (!(sgimc->systemid & SGIMC_SYSID_EPRESENT)) + { + printk(KERN_INFO "EISA: bus not present.\n"); + return 1; + } + + printk(KERN_INFO "EISA: Probing bus...\n"); + + for (c = 0, i = 1; i <= IP22_EISA_MAX_SLOTS; i++) + { + if ((str = decode_eisa_sig(0x1000 * i + EISA_VENDOR_ID_OFFSET))) + { + printk(KERN_INFO "EISA: slot %d : %s detected.\n", + i, str); + c++; + } + } + + printk(KERN_INFO "EISA: Detected %d card%s.\n", c, c < 2 ? "" : "s"); +#ifdef CONFIG_ISA + printk(KERN_INFO "ISA support compiled in.\n"); +#endif + + /* Warning : BlackMagicAhead(tm). + Please wave your favorite dead chicken over the busses */ + + /* First say hello to the EIU */ + outl(0x0000FFFF, EIU_PREMPT_REG); + outl(1, EIU_QUIET_REG); + outl(0x40f3c07F, EIU_MODE_REG); + + /* Now be nice to the EISA chipset */ + outb(1, EISA_EXT_NMI_RESET_CTRL); + udelay(50); /* Wait long enough for the dust to settle */ + outb(0, EISA_EXT_NMI_RESET_CTRL); + outb(0, EISA_DMA2_WRITE_SINGLE); + + init_i8259_irqs(); + + /* Cannot use request_irq because of kmalloc not being ready at such + * an early stage. Yes, I've been bitten... */ + setup_irq(SGI_EISA_IRQ, &eisa_action); + + EISA_bus = 1; + return 0; +} diff --git a/pool/shard004/C/0099667_console.c b/pool/shard004/C/0099667_console.c new file mode 100644 index 0000000000000000000000000000000000000000..47336ac4f05054ba980daf239c13351c170644e8 --- /dev/null +++ b/pool/shard004/C/0099667_console.c @@ -0,0 +1,74 @@ +#include +#include +#include + +struct console_struct system_console = { .writec = NULL, .readc = NULL}; + +/* + * These routines get the console set up as quickly and cheaply as possible over serial. + * They are meant to be used early in the boot process before any real serial driver + * is loaded. + */ + +#define COM1 0x3F8 + +static void init_serial(uint16_t address) { + outb(address + 1, 0x00); // Disable interrupts + outb(address + 3, 0x80); // 0x80 == 10000000 (enable DLAB) + outb(address + 0, 0x03); // Set baud rate divisor to three (low byte) + outb(address + 1, 0x00); // " (high byte) + outb(address + 3, 0x03); // Character length = 8 bits + outb(address + 2, 0xC7); + outb(address + 4, 0x0B); +} + +static void write_serial(uint16_t address, char ascii) { + outb(address, ascii); +} + +static void early_serial_write(char ascii) { + write_serial(COM1, ascii); +} + +void init_early_console(void) { + init_serial(COM1); + system_console.writec = early_serial_write; + kprint("Initialized early console\n"); +} + + +void kprint(char *string) { + while(*string != '\0') { + system_console.writec(*string); + string++; + } +} + +void kprint_hex(unsigned int value, int width) { + char buf[width + 3]; + int index = width + 1; + buf[width + 2] = '\0'; + while(value > 0) { + buf[index] = "0123456789ABCDEF"[value % 0x10]; + value = value / 0x10; + index--; + } + while(index >= 0) { + buf[index--] = '0'; + } + buf[0] = '0'; + buf[1] = 'x'; + kprint(buf); +} + +void kprint_dec(unsigned int value, int width) { + char buf[width + 1]; + int index = width - 1; + buf[width] = '\0'; + while(value > 0) { + buf[index] = "0123456789"[value % 10]; + value = value / 10; + index--; + } + kprint(buf + index + 1); +} diff --git a/pool/shard004/C/0099674_vcom.c b/pool/shard004/C/0099674_vcom.c new file mode 100644 index 0000000000000000000000000000000000000000..67b5e10be94066ac6505e83e2e1cb1fe9ecdae4c --- /dev/null +++ b/pool/shard004/C/0099674_vcom.c @@ -0,0 +1,262 @@ + /****************************************************************************** + * @file vcom.c + * @author MCD Application Team + * @version V1.1.0 + * @date 27-February-2017 + * @brief manages virtual com port + ****************************************************************************** + * @attention + * + *

© Copyright (c) 2017 STMicroelectronics International N.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: + * + * 1. Redistribution 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 other + * contributors to this software may be used to endorse or promote products + * derived from this software without specific written permission. + * 4. This software, including modifications and/or derivative works of this + * software, must execute solely and exclusively on microcontroller or + * microprocessor devices manufactured by or for STMicroelectronics. + * 5. Redistribution and use of this software other than as permitted under + * this license is void and will automatically terminate your rights under + * this license. + * + * THIS SOFTWARE IS PROVIDED BY STMICROELECTRONICS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS, IMPLIED OR STATUTORY WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A + * PARTICULAR PURPOSE AND NON-INFRINGEMENT OF THIRD PARTY INTELLECTUAL PROPERTY + * RIGHTS ARE DISCLAIMED TO THE FULLEST EXTENT PERMITTED BY LAW. IN NO EVENT + * SHALL STMICROELECTRONICS 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 "hw.h" +#include "vcom.h" +#include + + +/* Private typedef -----------------------------------------------------------*/ +/* Private define ------------------------------------------------------------*/ +#define BUFSIZE 256 +#define USARTX_IRQn USART2_IRQn +/* Private macro -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ + +/* buffer */ +static char buff[BUFSIZE]; +/* buffer write index*/ +__IO uint16_t iw=0; +/* buffer read index*/ +static uint16_t ir=0; +/* Uart Handle */ +static UART_HandleTypeDef UartHandle; + +/* Private function prototypes -----------------------------------------------*/ +/* Functions Definition ------------------------------------------------------*/ + +void vcom_Init(void) +{ + /*## Configure the UART peripheral ######################################*/ + /* Put the USART peripheral in the Asynchronous mode (UART Mode) */ + /* UART1 configured as follow: + - Word Length = 8 Bits + - Stop Bit = One Stop bit + - Parity = ODD parity + - BaudRate = 921600 baud + - Hardware flow control disabled (RTS and CTS signals) */ + UartHandle.Instance = USARTX; + + UartHandle.Init.BaudRate = 115200; + UartHandle.Init.WordLength = UART_WORDLENGTH_8B; + UartHandle.Init.StopBits = UART_STOPBITS_1; + UartHandle.Init.Parity = UART_PARITY_NONE; + UartHandle.Init.HwFlowCtl = UART_HWCONTROL_NONE; + UartHandle.Init.Mode = UART_MODE_TX_RX; + + if(HAL_UART_Init(&UartHandle) != HAL_OK) + { + /* Initialization Error */ + Error_Handler(); + } + + HAL_NVIC_SetPriority(USARTX_IRQn, 0x1, 0); + HAL_NVIC_EnableIRQ(USARTX_IRQn); +} + + +void vcom_DeInit(void) +{ +#if 1 + HAL_UART_DeInit(&UartHandle); +#endif +} + +void vcom_Send( char *format, ... ) +{ + va_list args; + va_start(args, format); + uint8_t len; + uint8_t lenTop; + char tempBuff[128]; + + BACKUP_PRIMASK(); + DISABLE_IRQ(); + + /*convert into string at buff[0] of length iw*/ + len = vsprintf(&tempBuff[0], format, args); + + if (iw+len0 ) + { + BACKUP_PRIMASK(); + DISABLE_IRQ(); + + CurChar = &buff[ir]; + ir= (ir+1) %BUFSIZE; + + RESTORE_PRIMASK(); + + HAL_UART_Transmit(&UartHandle,(uint8_t *) CurChar, 1, 300); + } + HAL_NVIC_ClearPendingIRQ(USARTX_IRQn); +} + +void vcom_Send_Lp( char *format, ... ) +{ + va_list args; + va_start(args, format); + uint8_t len; + uint8_t lenTop; + char tempBuff[128]; + + BACKUP_PRIMASK(); + DISABLE_IRQ(); + + /*convert into string at buff[0] of length iw*/ + len = vsprintf(&tempBuff[0], format, args); + + if (iw+lenm->track_count - 1; + t = data->m->track[index]; + + /* Report only once */ + if (t->reported == TRUE) + return; + + /* Set up url */ + len = strlen("http://8tracks.com/sets/") + strlen(data->playtoken) + + strlen("/report?track_id=") + intlen(t->id) + + strlen("&mix_id=") + intlen(data->m->id) + 1; + url = malloc(len * sizeof(char)); + if (url == NULL) + err(1, NULL); + (void)snprintf(url, len, + "http://8tracks.com/sets/%s/report?track_id=%d&mix_id=%d", + data->playtoken, t->id, data->m->id); + + /* Report track */ + js = malloc(1); + if (js == NULL) + err(1, NULL); + (void)fetch(&js, url); /* Just reporting, result doesn't matter. */ + t->reported = TRUE; + + /* Cleanup */ + free(js); + free(url); +} diff --git a/pool/shard004/C/0099678_nlmon.c b/pool/shard004/C/0099678_nlmon.c new file mode 100644 index 0000000000000000000000000000000000000000..b91603835d2680aa08911da7870ea176c5dd0792 --- /dev/null +++ b/pool/shard004/C/0099678_nlmon.c @@ -0,0 +1,161 @@ +#include +#include +#include +#include +#include +#include +#include + +struct pcpu_lstats { + u64 packets; + u64 bytes; + struct u64_stats_sync syncp; +}; + +static netdev_tx_t nlmon_xmit(struct sk_buff *skb, struct net_device *dev) +{ + int len = skb->len; + struct pcpu_lstats *stats = this_cpu_ptr(dev->lstats); + + u64_stats_update_begin(&stats->syncp); + stats->bytes += len; + stats->packets++; + u64_stats_update_end(&stats->syncp); + + dev_kfree_skb(skb); + + return NETDEV_TX_OK; +} + +static int nlmon_dev_init(struct net_device *dev) +{ + dev->lstats = netdev_alloc_pcpu_stats(struct pcpu_lstats); + return dev->lstats == NULL ? -ENOMEM : 0; +} + +static void nlmon_dev_uninit(struct net_device *dev) +{ + free_percpu(dev->lstats); +} + +struct nlmon { + struct netlink_tap nt; +}; + +static int nlmon_open(struct net_device *dev) +{ + struct nlmon *nlmon = netdev_priv(dev); + + nlmon->nt.dev = dev; + nlmon->nt.module = THIS_MODULE; + return netlink_add_tap(&nlmon->nt); +} + +static int nlmon_close(struct net_device *dev) +{ + struct nlmon *nlmon = netdev_priv(dev); + + return netlink_remove_tap(&nlmon->nt); +} + +static void +nlmon_get_stats64(struct net_device *dev, struct rtnl_link_stats64 *stats) +{ + int i; + u64 bytes = 0, packets = 0; + + for_each_possible_cpu(i) { + const struct pcpu_lstats *nl_stats; + u64 tbytes, tpackets; + unsigned int start; + + nl_stats = per_cpu_ptr(dev->lstats, i); + + do { + start = u64_stats_fetch_begin_irq(&nl_stats->syncp); + tbytes = nl_stats->bytes; + tpackets = nl_stats->packets; + } while (u64_stats_fetch_retry_irq(&nl_stats->syncp, start)); + + packets += tpackets; + bytes += tbytes; + } + + stats->rx_packets = packets; + stats->tx_packets = 0; + + stats->rx_bytes = bytes; + stats->tx_bytes = 0; +} + +static u32 always_on(struct net_device *dev) +{ + return 1; +} + +static const struct ethtool_ops nlmon_ethtool_ops = { + .get_link = always_on, +}; + +static const struct net_device_ops nlmon_ops = { + .ndo_init = nlmon_dev_init, + .ndo_uninit = nlmon_dev_uninit, + .ndo_open = nlmon_open, + .ndo_stop = nlmon_close, + .ndo_start_xmit = nlmon_xmit, + .ndo_get_stats64 = nlmon_get_stats64, +}; + +static void nlmon_setup(struct net_device *dev) +{ + dev->type = ARPHRD_NETLINK; + dev->priv_flags |= IFF_NO_QUEUE; + + dev->netdev_ops = &nlmon_ops; + dev->ethtool_ops = &nlmon_ethtool_ops; + dev->destructor = free_netdev; + + dev->features = NETIF_F_SG | NETIF_F_FRAGLIST | + NETIF_F_HIGHDMA | NETIF_F_LLTX; + dev->flags = IFF_NOARP; + + /* That's rather a softlimit here, which, of course, + * can be altered. Not a real MTU, but what is to be + * expected in most cases. + */ + dev->mtu = NLMSG_GOODSIZE; + dev->min_mtu = sizeof(struct nlmsghdr); +} + +static int nlmon_validate(struct nlattr *tb[], struct nlattr *data[]) +{ + if (tb[IFLA_ADDRESS]) + return -EINVAL; + return 0; +} + +static struct rtnl_link_ops nlmon_link_ops __read_mostly = { + .kind = "nlmon", + .priv_size = sizeof(struct nlmon), + .setup = nlmon_setup, + .validate = nlmon_validate, +}; + +static __init int nlmon_register(void) +{ + return rtnl_link_register(&nlmon_link_ops); +} + +static __exit void nlmon_unregister(void) +{ + rtnl_link_unregister(&nlmon_link_ops); +} + +module_init(nlmon_register); +module_exit(nlmon_unregister); + +MODULE_LICENSE("GPL v2"); +MODULE_AUTHOR("Daniel Borkmann "); +MODULE_AUTHOR("Mathieu Geli "); +MODULE_DESCRIPTION("Netlink monitoring device"); +MODULE_ALIAS_RTNL_LINK("nlmon"); diff --git a/pool/shard004/C/0099684_util.c b/pool/shard004/C/0099684_util.c new file mode 100644 index 0000000000000000000000000000000000000000..ca60ccf2806873a39bccf49bad7e263b35029a30 --- /dev/null +++ b/pool/shard004/C/0099684_util.c @@ -0,0 +1,96 @@ +/* + * util.c + * + * Copyright (C) AB Strakt + * Copyright (C) Jean-Paul Calderone + * See LICENSE for details. + * + * Utility functions. + * See the file RATIONALE for a short explanation of why this module was written. + * + * Reviewed 2001-07-23 + */ +#include +#include "util.h" + +/* + * Flush OpenSSL's error queue and return a list of errors (a (library, + * function, reason) string tuple) + * + * Arguments: None + * Returns: A list of errors (new reference) + */ +PyObject * +error_queue_to_list(void) { + PyObject *errlist, *tuple; + long err; + + errlist = PyList_New(0); + + while ((err = ERR_get_error()) != 0) { + tuple = Py_BuildValue("(sss)", ERR_lib_error_string(err), + ERR_func_error_string(err), + ERR_reason_error_string(err)); + PyList_Append(errlist, tuple); + Py_DECREF(tuple); + } + + return errlist; +} + +void exception_from_error_queue(PyObject *the_Error) { + PyObject *errlist = error_queue_to_list(); + PyErr_SetObject(the_Error, errlist); + Py_DECREF(errlist); +} + +/* + * Flush OpenSSL's error queue and ignore the result + * + * Arguments: None + * Returns: None + */ +void +flush_error_queue(void) { + /* + * Make sure to save the errors to a local. Py_DECREF might expand such + * that it evaluates its argument more than once, which would lead to + * very nasty things if we just invoked it with error_queue_to_list(). + */ + PyObject *list = error_queue_to_list(); + Py_DECREF(list); +} + +#if (PY_VERSION_HEX < 0x02600000) +PyObject* PyOpenSSL_LongToHex(PyObject *o) { + PyObject *hex = NULL; + PyObject *format = NULL; + PyObject *format_args = NULL; + + if ((format_args = Py_BuildValue("(O)", o)) == NULL) { + goto err; + } + + if ((format = PyString_FromString("%x")) == NULL) { + goto err; + } + + if ((hex = PyString_Format(format, format_args)) == NULL) { + goto err; + } + + return hex; + + err: + if (format_args) { + Py_DECREF(format_args); + } + if (format) { + Py_DECREF(format); + } + if (hex) { + Py_DECREF(hex); + } + return NULL; +} +#endif diff --git a/pool/shard004/C/0099690_ft_utoa.c b/pool/shard004/C/0099690_ft_utoa.c new file mode 100644 index 0000000000000000000000000000000000000000..7407087e2299371f930aceb20852a7643d71c9e5 --- /dev/null +++ b/pool/shard004/C/0099690_ft_utoa.c @@ -0,0 +1,72 @@ +/* ************************************************************************** */ +/* */ +/* ::: :::::::: */ +/* ft_utoa.c :+: :+: :+: */ +/* +:+ +:+ +:+ */ +/* By: mfaye +#+ +:+ +#+ */ +/* +#+#+#+#+#+ +#+ */ +/* Created: 2013/11/25 15:08:32 by mfaye #+# #+# */ +/* Updated: 2013/11/26 16:18:04 by mfaye ### ########.fr */ +/* */ +/* ************************************************************************** */ + +#include "libft.h" + +static t_ul count_nbr(t_ul n) +{ + t_ul count; + + count = 1; + while (n / 10 > 0) + { + n /= 10; + count++; + } + return (count); +} + +static void set_mod_and_div(t_ul *mod, t_ul *div, t_ul base, t_ul n) +{ + *mod = n % base; + *div = n / base; +} + +static char *make_string(char *toa, t_ul n, t_ul base) +{ + char c_val; + t_ul mod; + t_ul div; + + if (n >= base) + { + set_mod_and_div(&mod, &div, base, n); + if (div != 0) + toa = make_string(toa, div, base); + make_string(toa, mod, base); + } + else + { + if (base <= 10) + c_val = (char) n + '0'; + else + { + if (n <= 9) + c_val = (char) n + '0'; + else + c_val = (char) (n - 10) + 'a'; + } + *toa = c_val; + } + return (toa + 1); +} + +char *ft_utoa(t_ul n, t_ul base) +{ + t_ul nb_nbr; + char *toa; + + nb_nbr = count_nbr(n); + toa = ft_strnew(nb_nbr + 1); + make_string(toa, n, base); + return (toa); +} diff --git a/pool/shard004/C/0099694_rsi_91x_debugfs.c b/pool/shard004/C/0099694_rsi_91x_debugfs.c new file mode 100644 index 0000000000000000000000000000000000000000..828a042f903f19fef82eb09425f3e865e534f551 --- /dev/null +++ b/pool/shard004/C/0099694_rsi_91x_debugfs.c @@ -0,0 +1,336 @@ +/** + * Copyright (c) 2014 Redpine Signals Inc. + * + * Permission to use, copy, modify, and/or distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR + * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN + * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF + * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + */ + +#include "rsi_debugfs.h" +#include "rsi_sdio.h" + +/** + * rsi_sdio_stats_read() - This function returns the sdio status of the driver. + * @seq: Pointer to the sequence file structure. + * @data: Pointer to the data. + * + * Return: 0 on success, -1 on failure. + */ +static int rsi_sdio_stats_read(struct seq_file *seq, void *data) +{ + struct rsi_common *common = seq->private; + struct rsi_hw *adapter = common->priv; + struct rsi_91x_sdiodev *dev = + (struct rsi_91x_sdiodev *)adapter->rsi_dev; + + seq_printf(seq, "total_sdio_interrupts: %d\n", + dev->rx_info.sdio_int_counter); + seq_printf(seq, "sdio_msdu_pending_intr_count: %d\n", + dev->rx_info.total_sdio_msdu_pending_intr); + seq_printf(seq, "sdio_buff_full_count : %d\n", + dev->rx_info.buf_full_counter); + seq_printf(seq, "sdio_buf_semi_full_count %d\n", + dev->rx_info.buf_semi_full_counter); + seq_printf(seq, "sdio_unknown_intr_count: %d\n", + dev->rx_info.total_sdio_unknown_intr); + /* RX Path Stats */ + seq_printf(seq, "BUFFER FULL STATUS : %d\n", + dev->rx_info.buffer_full); + seq_printf(seq, "SEMI BUFFER FULL STATUS : %d\n", + dev->rx_info.semi_buffer_full); + seq_printf(seq, "MGMT BUFFER FULL STATUS : %d\n", + dev->rx_info.mgmt_buffer_full); + seq_printf(seq, "BUFFER FULL COUNTER : %d\n", + dev->rx_info.buf_full_counter); + seq_printf(seq, "BUFFER SEMI FULL COUNTER : %d\n", + dev->rx_info.buf_semi_full_counter); + seq_printf(seq, "MGMT BUFFER FULL COUNTER : %d\n", + dev->rx_info.mgmt_buf_full_counter); + + return 0; +} + +/** + * rsi_sdio_stats_open() - This funtion calls single open function of seq_file + * to open file and read contents from it. + * @inode: Pointer to the inode structure. + * @file: Pointer to the file structure. + * + * Return: Pointer to the opened file status: 0 on success, ENOMEM on failure. + */ +static int rsi_sdio_stats_open(struct inode *inode, + struct file *file) +{ + return single_open(file, rsi_sdio_stats_read, inode->i_private); +} + +/** + * rsi_version_read() - This function gives driver and firmware version number. + * @seq: Pointer to the sequence file structure. + * @data: Pointer to the data. + * + * Return: 0 on success, -1 on failure. + */ +static int rsi_version_read(struct seq_file *seq, void *data) +{ + struct rsi_common *common = seq->private; + + common->driver_ver.major = 0; + common->driver_ver.minor = 1; + common->driver_ver.release_num = 0; + common->driver_ver.patch_num = 0; + seq_printf(seq, "Driver : %x.%d.%d.%d\nLMAC : %d.%d.%d.%d\n", + common->driver_ver.major, + common->driver_ver.minor, + common->driver_ver.release_num, + common->driver_ver.patch_num, + common->fw_ver.major, + common->fw_ver.minor, + common->fw_ver.release_num, + common->fw_ver.patch_num); + return 0; +} + +/** + * rsi_version_open() - This funtion calls single open function of seq_file to + * open file and read contents from it. + * @inode: Pointer to the inode structure. + * @file: Pointer to the file structure. + * + * Return: Pointer to the opened file status: 0 on success, ENOMEM on failure. + */ +static int rsi_version_open(struct inode *inode, + struct file *file) +{ + return single_open(file, rsi_version_read, inode->i_private); +} + +/** + * rsi_stats_read() - This function return the status of the driver. + * @seq: Pointer to the sequence file structure. + * @data: Pointer to the data. + * + * Return: 0 on success, -1 on failure. + */ +static int rsi_stats_read(struct seq_file *seq, void *data) +{ + struct rsi_common *common = seq->private; + + unsigned char fsm_state[][32] = { + "FSM_CARD_NOT_READY", + "FSM_BOOT_PARAMS_SENT", + "FSM_EEPROM_READ_MAC_ADDR", + "FSM_RESET_MAC_SENT", + "FSM_RADIO_CAPS_SENT", + "FSM_BB_RF_PROG_SENT", + "FSM_MAC_INIT_DONE" + }; + seq_puts(seq, "==> RSI STA DRIVER STATUS <==\n"); + seq_puts(seq, "DRIVER_FSM_STATE: "); + + if (common->fsm_state <= FSM_MAC_INIT_DONE) + seq_printf(seq, "%s", fsm_state[common->fsm_state]); + + seq_printf(seq, "(%d)\n\n", common->fsm_state); + + /* Mgmt TX Path Stats */ + seq_printf(seq, "total_mgmt_pkt_send : %d\n", + common->tx_stats.total_tx_pkt_send[MGMT_SOFT_Q]); + seq_printf(seq, "total_mgmt_pkt_queued : %d\n", + skb_queue_len(&common->tx_queue[MGMT_SOFT_Q])); + seq_printf(seq, "total_mgmt_pkt_freed : %d\n", + common->tx_stats.total_tx_pkt_freed[MGMT_SOFT_Q]); + + /* Data TX Path Stats */ + seq_printf(seq, "total_data_vo_pkt_send: %8d\t", + common->tx_stats.total_tx_pkt_send[VO_Q]); + seq_printf(seq, "total_data_vo_pkt_queued: %8d\t", + skb_queue_len(&common->tx_queue[VO_Q])); + seq_printf(seq, "total_vo_pkt_freed: %8d\n", + common->tx_stats.total_tx_pkt_freed[VO_Q]); + seq_printf(seq, "total_data_vi_pkt_send: %8d\t", + common->tx_stats.total_tx_pkt_send[VI_Q]); + seq_printf(seq, "total_data_vi_pkt_queued: %8d\t", + skb_queue_len(&common->tx_queue[VI_Q])); + seq_printf(seq, "total_vi_pkt_freed: %8d\n", + common->tx_stats.total_tx_pkt_freed[VI_Q]); + seq_printf(seq, "total_data_be_pkt_send: %8d\t", + common->tx_stats.total_tx_pkt_send[BE_Q]); + seq_printf(seq, "total_data_be_pkt_queued: %8d\t", + skb_queue_len(&common->tx_queue[BE_Q])); + seq_printf(seq, "total_be_pkt_freed: %8d\n", + common->tx_stats.total_tx_pkt_freed[BE_Q]); + seq_printf(seq, "total_data_bk_pkt_send: %8d\t", + common->tx_stats.total_tx_pkt_send[BK_Q]); + seq_printf(seq, "total_data_bk_pkt_queued: %8d\t", + skb_queue_len(&common->tx_queue[BK_Q])); + seq_printf(seq, "total_bk_pkt_freed: %8d\n", + common->tx_stats.total_tx_pkt_freed[BK_Q]); + + seq_puts(seq, "\n"); + return 0; +} + +/** + * rsi_stats_open() - This funtion calls single open function of seq_file to + * open file and read contents from it. + * @inode: Pointer to the inode structure. + * @file: Pointer to the file structure. + * + * Return: Pointer to the opened file status: 0 on success, ENOMEM on failure. + */ +static int rsi_stats_open(struct inode *inode, + struct file *file) +{ + return single_open(file, rsi_stats_read, inode->i_private); +} + +/** + * rsi_debug_zone_read() - This function display the currently enabled debug zones. + * @seq: Pointer to the sequence file structure. + * @data: Pointer to the data. + * + * Return: 0 on success, -1 on failure. + */ +static int rsi_debug_zone_read(struct seq_file *seq, void *data) +{ + rsi_dbg(FSM_ZONE, "%x: rsi_enabled zone", rsi_zone_enabled); + seq_printf(seq, "The zones available are %#x\n", + rsi_zone_enabled); + return 0; +} + +/** + * rsi_debug_read() - This funtion calls single open function of seq_file to + * open file and read contents from it. + * @inode: Pointer to the inode structure. + * @file: Pointer to the file structure. + * + * Return: Pointer to the opened file status: 0 on success, ENOMEM on failure. + */ +static int rsi_debug_read(struct inode *inode, + struct file *file) +{ + return single_open(file, rsi_debug_zone_read, inode->i_private); +} + +/** + * rsi_debug_zone_write() - This function writes into hal queues as per user + * requirement. + * @filp: Pointer to the file structure. + * @buff: Pointer to the character buffer. + * @len: Length of the data to be written into buffer. + * @data: Pointer to the data. + * + * Return: len: Number of bytes read. + */ +static ssize_t rsi_debug_zone_write(struct file *filp, + const char __user *buff, + size_t len, + loff_t *data) +{ + unsigned long dbg_zone; + int ret; + + if (!len) + return 0; + + ret = kstrtoul_from_user(buff, len, 16, &dbg_zone); + + if (ret) + return ret; + + rsi_zone_enabled = dbg_zone; + return len; +} + +#define FOPS(fopen) { \ + .owner = THIS_MODULE, \ + .open = (fopen), \ + .read = seq_read, \ + .llseek = seq_lseek, \ +} + +#define FOPS_RW(fopen, fwrite) { \ + .owner = THIS_MODULE, \ + .open = (fopen), \ + .read = seq_read, \ + .llseek = seq_lseek, \ + .write = (fwrite), \ +} + +static const struct rsi_dbg_files dev_debugfs_files[] = { + {"version", 0644, FOPS(rsi_version_open),}, + {"stats", 0644, FOPS(rsi_stats_open),}, + {"debug_zone", 0666, FOPS_RW(rsi_debug_read, rsi_debug_zone_write),}, + {"sdio_stats", 0644, FOPS(rsi_sdio_stats_open),}, +}; + +/** + * rsi_init_dbgfs() - This function initializes the dbgfs entry. + * @adapter: Pointer to the adapter structure. + * + * Return: 0 on success, -1 on failure. + */ +int rsi_init_dbgfs(struct rsi_hw *adapter) +{ + struct rsi_common *common = adapter->priv; + struct rsi_debugfs *dev_dbgfs; + char devdir[6]; + int ii; + const struct rsi_dbg_files *files; + + dev_dbgfs = kzalloc(sizeof(*dev_dbgfs), GFP_KERNEL); + if (!dev_dbgfs) + return -ENOMEM; + + adapter->dfsentry = dev_dbgfs; + + snprintf(devdir, sizeof(devdir), "%s", + wiphy_name(adapter->hw->wiphy)); + + dev_dbgfs->subdir = debugfs_create_dir(devdir, NULL); + + if (!dev_dbgfs->subdir) { + kfree(dev_dbgfs); + return -ENOMEM; + } + + for (ii = 0; ii < adapter->num_debugfs_entries; ii++) { + files = &dev_debugfs_files[ii]; + dev_dbgfs->rsi_files[ii] = + debugfs_create_file(files->name, + files->perms, + dev_dbgfs->subdir, + common, + &files->fops); + } + return 0; +} +EXPORT_SYMBOL_GPL(rsi_init_dbgfs); + +/** + * rsi_remove_dbgfs() - Removes the previously created dbgfs file entries + * in the reverse order of creation. + * @adapter: Pointer to the adapter structure. + * + * Return: None. + */ +void rsi_remove_dbgfs(struct rsi_hw *adapter) +{ + struct rsi_debugfs *dev_dbgfs = adapter->dfsentry; + + if (!dev_dbgfs) + return; + + debugfs_remove_recursive(dev_dbgfs->subdir); +} +EXPORT_SYMBOL_GPL(rsi_remove_dbgfs); diff --git a/pool/shard004/C/0099696_ubmark-mvmult-cp2.c b/pool/shard004/C/0099696_ubmark-mvmult-cp2.c new file mode 100644 index 0000000000000000000000000000000000000000..783fd605266edc1bcec083a6b5cb4cfdbeb0f472 --- /dev/null +++ b/pool/shard004/C/0099696_ubmark-mvmult-cp2.c @@ -0,0 +1,84 @@ +//======================================================================== +// ubmark-mvmult-cp2 +//======================================================================== + +#include "ubmark.h" +#include "ubmark-mvmult.dat" + +//------------------------------------------------------------------------ +// mvmult-cp2 +//------------------------------------------------------------------------ + +__attribute__ ((noinline)) +void mvmult_cp2( int* resultvector, int* matrix, int* vector, + int R, int C, int nlanes ) +{ + int i = 0; + int go = 1; + int size = C; + int result = -1; + + for( i = 0; i < R; i+=nlanes ) { + int* r_baddr = &(matrix[i*C]); + int* v_baddr = &(vector[0]); + int* d_baddr = &(resultvector[i]); + // TODO: add native code + #ifdef _MIPS_ARCH_MAVEN + // TODO: left shift by two in order to avoid unaligned branch warning, + // but processor still sees the unshifted version... + __asm__ __volatile__ ( "mtc2 %0, $1;" : : "r"(size) : "memory" ); + __asm__ __volatile__ ( "mtc2 %0, $2;" : : "r"(r_baddr) : "memory" ); + __asm__ __volatile__ ( "mtc2 %0, $3;" : : "r"(v_baddr) : "memory" ); + __asm__ __volatile__ ( "mtc2 %0, $0;" : : "r"(go) : "memory" ); + __asm__ __volatile__ ( "mfc2 %0, %0;" : : "r"(result) : "memory" ); + __asm__ __volatile__ ( "sw %0, 0(%1);" : : "r"(result),"r"(d_baddr) : "memory" ); + #endif + } +} + + +//------------------------------------------------------------------------ +// verify_results +//------------------------------------------------------------------------ + +void verify_results( int dest[], int ref[], int size ) +{ + int temp = 0; + int i; + for ( i = 0; i < size; i++ ) { + if ( !( dest[i] == ref[i] ) ) { + test_fail( temp ); + } + } + test_pass( temp ); +} + +//------------------------------------------------------------------------ +// Test Harness +//------------------------------------------------------------------------ + +int main( int argc, char* argv[] ) +{ + + int size = C; + int dest[size]; + + int i; + for ( i = 0; i < size; i++ ) + dest[i] = 0; + + int temp = 0; + + // warmup + mvmult_cp2( dest, (int*) matrix, vector, R, C, 1 ); + + test_stats_on( temp ); + for ( i = 0; i < 1; i++ ) + mvmult_cp2( dest, (int*) matrix, vector, R, C, 1 ); + test_stats_off( temp ); + + verify_results( dest, ref, size ); + + return 0; +} + diff --git a/pool/shard004/C/0099697_a_strnid.c b/pool/shard004/C/0099697_a_strnid.c new file mode 100644 index 0000000000000000000000000000000000000000..2d2303d8599e7abfa41204f323a20d443fb1604d --- /dev/null +++ b/pool/shard004/C/0099697_a_strnid.c @@ -0,0 +1,314 @@ +/* a_strnid.c */ +/* + * Written by Dr Stephen N Henson (steve@openssl.org) for the OpenSSL project + * 1999. + */ +/* ==================================================================== + * Copyright (c) 1999 The OpenSSL 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. + * + * 3. All advertising materials mentioning features or use of this + * software must display the following acknowledgment: + * "This product includes software developed by the OpenSSL Project + * for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)" + * + * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to + * endorse or promote products derived from this software without + * prior written permission. For written permission, please contact + * licensing@OpenSSL.org. + * + * 5. Products derived from this software may not be called "OpenSSL" + * nor may "OpenSSL" appear in their names without prior written + * permission of the OpenSSL Project. + * + * 6. Redistributions of any form whatsoever must retain the following + * acknowledgment: + * "This product includes software developed by the OpenSSL Project + * for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)" + * + * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY + * EXPRESSED 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 OpenSSL PROJECT 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. + * ==================================================================== + * + * This product includes cryptographic software written by Eric Young + * (eay@cryptsoft.com). This product includes software written by Tim + * Hudson (tjh@cryptsoft.com). + * + */ + +#include +#include +#include "cryptlib.h" +#include +#include + +static STACK_OF(ASN1_STRING_TABLE) *stable = NULL; +static void st_free(ASN1_STRING_TABLE *tbl); +static int sk_table_cmp(const ASN1_STRING_TABLE *const *a, + const ASN1_STRING_TABLE *const *b); + +/* + * This is the global mask for the mbstring functions: this is use to mask + * out certain types (such as BMPString and UTF8String) because certain + * software (e.g. Netscape) has problems with them. + */ + +static unsigned long global_mask = B_ASN1_UTF8STRING; + +void ASN1_STRING_set_default_mask(unsigned long mask) +{ + global_mask = mask; +} + +unsigned long ASN1_STRING_get_default_mask(void) +{ + return global_mask; +} + +/*- + * This function sets the default to various "flavours" of configuration. + * based on an ASCII string. Currently this is: + * MASK:XXXX : a numerical mask value. + * nobmp : Don't use BMPStrings (just Printable, T61). + * pkix : PKIX recommendation in RFC2459. + * utf8only : only use UTF8Strings (RFC2459 recommendation for 2004). + * default: the default value, Printable, T61, BMP. + */ + +int ASN1_STRING_set_default_mask_asc(const char *p) +{ + unsigned long mask; + char *end; + if (!strncmp(p, "MASK:", 5)) { + if (!p[5]) + return 0; + mask = strtoul(p + 5, &end, 0); + if (*end) + return 0; + } else if (!strcmp(p, "nombstr")) + mask = ~((unsigned long)(B_ASN1_BMPSTRING | B_ASN1_UTF8STRING)); + else if (!strcmp(p, "pkix")) + mask = ~((unsigned long)B_ASN1_T61STRING); + else if (!strcmp(p, "utf8only")) + mask = B_ASN1_UTF8STRING; + else if (!strcmp(p, "default")) + mask = 0xFFFFFFFFL; + else + return 0; + ASN1_STRING_set_default_mask(mask); + return 1; +} + +/* + * The following function generates an ASN1_STRING based on limits in a + * table. Frequently the types and length of an ASN1_STRING are restricted by + * a corresponding OID. For example certificates and certificate requests. + */ + +ASN1_STRING *ASN1_STRING_set_by_NID(ASN1_STRING **out, + const unsigned char *in, int inlen, + int inform, int nid) +{ + ASN1_STRING_TABLE *tbl; + ASN1_STRING *str = NULL; + unsigned long mask; + int ret; + if (!out) + out = &str; + tbl = ASN1_STRING_TABLE_get(nid); + if (tbl) { + mask = tbl->mask; + if (!(tbl->flags & STABLE_NO_MASK)) + mask &= global_mask; + ret = ASN1_mbstring_ncopy(out, in, inlen, inform, mask, + tbl->minsize, tbl->maxsize); + } else + ret = + ASN1_mbstring_copy(out, in, inlen, inform, + DIRSTRING_TYPE & global_mask); + if (ret <= 0) + return NULL; + return *out; +} + +/* + * Now the tables and helper functions for the string table: + */ + +/* size limits: this stuff is taken straight from RFC3280 */ + +#define ub_name 32768 +#define ub_common_name 64 +#define ub_locality_name 128 +#define ub_state_name 128 +#define ub_organization_name 64 +#define ub_organization_unit_name 64 +#define ub_title 64 +#define ub_email_address 128 +#define ub_serial_number 64 + +/* This table must be kept in NID order */ + +static const ASN1_STRING_TABLE tbl_standard[] = { + {NID_commonName, 1, ub_common_name, DIRSTRING_TYPE, 0}, + {NID_countryName, 2, 2, B_ASN1_PRINTABLESTRING, STABLE_NO_MASK}, + {NID_localityName, 1, ub_locality_name, DIRSTRING_TYPE, 0}, + {NID_stateOrProvinceName, 1, ub_state_name, DIRSTRING_TYPE, 0}, + {NID_organizationName, 1, ub_organization_name, DIRSTRING_TYPE, 0}, + {NID_organizationalUnitName, 1, ub_organization_unit_name, DIRSTRING_TYPE, + 0}, + {NID_pkcs9_emailAddress, 1, ub_email_address, B_ASN1_IA5STRING, + STABLE_NO_MASK}, + {NID_pkcs9_unstructuredName, 1, -1, PKCS9STRING_TYPE, 0}, + {NID_pkcs9_challengePassword, 1, -1, PKCS9STRING_TYPE, 0}, + {NID_pkcs9_unstructuredAddress, 1, -1, DIRSTRING_TYPE, 0}, + {NID_givenName, 1, ub_name, DIRSTRING_TYPE, 0}, + {NID_surname, 1, ub_name, DIRSTRING_TYPE, 0}, + {NID_initials, 1, ub_name, DIRSTRING_TYPE, 0}, + {NID_serialNumber, 1, ub_serial_number, B_ASN1_PRINTABLESTRING, + STABLE_NO_MASK}, + {NID_friendlyName, -1, -1, B_ASN1_BMPSTRING, STABLE_NO_MASK}, + {NID_name, 1, ub_name, DIRSTRING_TYPE, 0}, + {NID_dnQualifier, -1, -1, B_ASN1_PRINTABLESTRING, STABLE_NO_MASK}, + {NID_domainComponent, 1, -1, B_ASN1_IA5STRING, STABLE_NO_MASK}, + {NID_ms_csp_name, -1, -1, B_ASN1_BMPSTRING, STABLE_NO_MASK} +}; + +static int sk_table_cmp(const ASN1_STRING_TABLE *const *a, + const ASN1_STRING_TABLE *const *b) +{ + return (*a)->nid - (*b)->nid; +} + +DECLARE_OBJ_BSEARCH_CMP_FN(ASN1_STRING_TABLE, ASN1_STRING_TABLE, table); + +static int table_cmp(const ASN1_STRING_TABLE *a, const ASN1_STRING_TABLE *b) +{ + return a->nid - b->nid; +} + +IMPLEMENT_OBJ_BSEARCH_CMP_FN(ASN1_STRING_TABLE, ASN1_STRING_TABLE, table); + +ASN1_STRING_TABLE *ASN1_STRING_TABLE_get(int nid) +{ + int idx; + ASN1_STRING_TABLE *ttmp; + ASN1_STRING_TABLE fnd; + fnd.nid = nid; + ttmp = OBJ_bsearch_table(&fnd, tbl_standard, + sizeof(tbl_standard) / + sizeof(ASN1_STRING_TABLE)); + if (ttmp) + return ttmp; + if (!stable) + return NULL; + idx = sk_ASN1_STRING_TABLE_find(stable, &fnd); + if (idx < 0) + return NULL; + return sk_ASN1_STRING_TABLE_value(stable, idx); +} + +int ASN1_STRING_TABLE_add(int nid, + long minsize, long maxsize, unsigned long mask, + unsigned long flags) +{ + ASN1_STRING_TABLE *tmp; + char new_nid = 0; + flags &= ~STABLE_FLAGS_MALLOC; + if (!stable) + stable = sk_ASN1_STRING_TABLE_new(sk_table_cmp); + if (!stable) { + ASN1err(ASN1_F_ASN1_STRING_TABLE_ADD, ERR_R_MALLOC_FAILURE); + return 0; + } + if (!(tmp = ASN1_STRING_TABLE_get(nid))) { + tmp = OPENSSL_malloc(sizeof(ASN1_STRING_TABLE)); + if (!tmp) { + ASN1err(ASN1_F_ASN1_STRING_TABLE_ADD, ERR_R_MALLOC_FAILURE); + return 0; + } + tmp->flags = flags | STABLE_FLAGS_MALLOC; + tmp->nid = nid; + tmp->minsize = tmp->maxsize = -1; + new_nid = 1; + } else + tmp->flags = (tmp->flags & STABLE_FLAGS_MALLOC) | flags; + if (minsize != -1) + tmp->minsize = minsize; + if (maxsize != -1) + tmp->maxsize = maxsize; + tmp->mask = mask; + if (new_nid) + sk_ASN1_STRING_TABLE_push(stable, tmp); + return 1; +} + +void ASN1_STRING_TABLE_cleanup(void) +{ + STACK_OF(ASN1_STRING_TABLE) *tmp; + tmp = stable; + if (!tmp) + return; + stable = NULL; + sk_ASN1_STRING_TABLE_pop_free(tmp, st_free); +} + +static void st_free(ASN1_STRING_TABLE *tbl) +{ + if (tbl->flags & STABLE_FLAGS_MALLOC) + OPENSSL_free(tbl); +} + + +IMPLEMENT_STACK_OF(ASN1_STRING_TABLE) + +#ifdef STRING_TABLE_TEST + +main() +{ + ASN1_STRING_TABLE *tmp; + int i, last_nid = -1; + + for (tmp = tbl_standard, i = 0; + i < sizeof(tbl_standard) / sizeof(ASN1_STRING_TABLE); i++, tmp++) { + if (tmp->nid < last_nid) { + last_nid = 0; + break; + } + last_nid = tmp->nid; + } + + if (last_nid != 0) { + printf("Table order OK\n"); + exit(0); + } + + for (tmp = tbl_standard, i = 0; + i < sizeof(tbl_standard) / sizeof(ASN1_STRING_TABLE); i++, tmp++) + printf("Index %d, NID %d, Name=%s\n", i, tmp->nid, + OBJ_nid2ln(tmp->nid)); + +} + +#endif diff --git a/pool/shard004/C/0099703_fsal_init.c b/pool/shard004/C/0099703_fsal_init.c new file mode 100644 index 0000000000000000000000000000000000000000..b3fa68c1a0cecd1f0073e6751be777ff411257ff --- /dev/null +++ b/pool/shard004/C/0099703_fsal_init.c @@ -0,0 +1,177 @@ +/* + * vim:expandtab:shiftwidth=8:tabstop=8: + */ + +/** + * + * \file fsal_init.c + * \author $Author: leibovic $ + * \date $Date: 2006/01/24 13:45:37 $ + * \version $Revision: 1.20 $ + * \brief Initialization functions. + * + */ +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +#ifdef _SOLARIS +#include "solaris_port.h" +#endif /* _SOLARIS */ + +#include +#include + +#include "fsal.h" +#include "fsal_internal.h" +#include "fsal_common.h" + +#ifdef _USE_GSSRPC +#include +#else +#include +#endif + +#ifdef _HANDLE_MAPPING +#include "handle_mapping/handle_mapping.h" +#endif + +void *FSAL_proxy_clientid_renewer_thread(void *); + +pthread_t thrid_clientid_renewer; + +/* A variable to be seen (for read) in other files */ +proxyfs_specific_initinfo_t global_fsal_proxy_specific_info; + +/** Initializes filesystem, security management... */ +static int FS_Specific_Init(proxyfs_specific_initinfo_t * fs_init_info) +{ + sigset_t sigset_in; + sigset_t sigset_out; + pthread_attr_t attr_thr; + int rc; + + memcpy(&global_fsal_proxy_specific_info, fs_init_info, + sizeof(proxyfs_specific_initinfo_t)); + + /* No SIG_PIPE. This is mandatory for reconnection logic. If sigpipe is not blocked, + * then when a server crashes the next clnt_call will cause un unhandled sigpipe that + * will crash the server */ + sigemptyset(&sigset_in); + sigaddset(&sigset_in, SIGPIPE); + + if(sigprocmask(SIG_BLOCK, &sigset_in, &sigset_out) == -1) + return -1; + +#ifdef _HANDLE_MAPPING + + /* Initialize NFSv2/3 handle mapping management */ + + if(fs_init_info->enable_handle_mapping) + { + int rc; + handle_map_param_t param; + + strcpy(param.databases_directory, fs_init_info->hdlmap_dbdir); + strcpy(param.temp_directory, fs_init_info->hdlmap_tmpdir); + param.database_count = fs_init_info->hdlmap_dbcount; + param.hashtable_size = fs_init_info->hdlmap_hashsize; + param.nb_handles_prealloc = fs_init_info->hdlmap_nb_entry_prealloc; + param.nb_db_op_prealloc = fs_init_info->hdlmap_nb_db_op_prealloc; + param.synchronous_insert = FALSE; + + rc = HandleMap_Init(¶m); + + if(rc) + return rc; + } +#endif + /* Init the thread in charge of renewing the client id */ + /* Init for thread parameter (mostly for scheduling) */ + pthread_attr_init(&attr_thr); + + pthread_attr_setscope(&attr_thr, PTHREAD_SCOPE_SYSTEM); + pthread_attr_setdetachstate(&attr_thr, PTHREAD_CREATE_JOINABLE); + + if((rc = pthread_create(&thrid_clientid_renewer, + &attr_thr, + FSAL_proxy_clientid_renewer_thread, (void *)NULL) != 0)) + { + LogError(COMPONENT_FSAL, ERR_SYS, ERR_PTHREAD_CREATE, rc); + exit(1); + } + + return 0; +} + +/** + * FSAL_Init : Initializes the FileSystem Abstraction Layer. + * + * \param init_info (input, fsal_parameter_t *) : + * Pointer to a structure that contains + * all initialization parameters for the FSAL. + * Specifically, it contains settings about + * the filesystem on which the FSAL is based, + * security settings, logging policy and outputs, + * and other general FSAL options. + * + * \return Major error codes : + * ERR_FSAL_NO_ERROR (initialisation OK) + * ERR_FSAL_FAULT (init_info pointer is null) + * ERR_FSAL_SERVERFAULT (misc FSAL error) + * ERR_FSAL_ALREADY_INIT (The FS is already initialized) + * ERR_FSAL_BAD_INIT (FS specific init error, + * minor error code gives the reason + * for this error.) + * ERR_FSAL_SEC_INIT (Security context init error). + */ +fsal_status_t PROXYFSAL_Init(fsal_parameter_t * init_info /* IN */ + ) +{ + + fsal_status_t status; + int rc; + + /* sanity check. */ + + if(!init_info) + Return(ERR_FSAL_FAULT, 0, INDEX_FSAL_Init); + + /* >> You can check args bellow << */ + + /* proceeds FSAL internal status initialization */ + + status = fsal_internal_init_global(&(init_info->fsal_info), + &(init_info->fs_common_info)); + + if(FSAL_IS_ERROR(status)) + Return(status.major, status.minor, INDEX_FSAL_Init); + + /* >> You can also initialize some filesystem stuff << */ + + if((rc = FS_Specific_Init((proxyfs_specific_initinfo_t *) &init_info->fs_specific_info))) + Return(ERR_FSAL_BAD_INIT, -rc, INDEX_FSAL_Init); + + /* Everything went OK. */ + + Return(ERR_FSAL_NO_ERROR, 0, INDEX_FSAL_Init); + +} + +/* To be called before exiting */ +fsal_status_t PROXYFSAL_terminate() +{ +#ifdef _HANDLE_MAPPING + int rc; + + if(global_fsal_proxy_specific_info.enable_handle_mapping) + { + rc = HandleMap_Flush(); + + if(rc) + ReturnCode(ERR_FSAL_SERVERFAULT, rc); + } +#endif + + ReturnCode(ERR_FSAL_NO_ERROR, 0); +} diff --git a/pool/shard004/C/0099714_scratch_buffer_dupfree.c b/pool/shard004/C/0099714_scratch_buffer_dupfree.c new file mode 100644 index 0000000000000000000000000000000000000000..e34336f0e53624e498f851d219be8c70aeb1a8fb --- /dev/null +++ b/pool/shard004/C/0099714_scratch_buffer_dupfree.c @@ -0,0 +1,41 @@ +/* Variable-sized buffer with on-stack default allocation. + Copyright (C) 2020 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 General Public + License as published by the Free Software Foundation; either + version 3 of the License, or (at your option) any later version. + + The GNU 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 + General Public License for more details. + + You should have received a copy of the GNU General Public + License along with the GNU C Library; if not, see + . */ + +#ifndef _LIBC +# include +#endif + +#include +#include + +void * +__libc_scratch_buffer_dupfree (struct scratch_buffer *buffer, size_t size) +{ + void *data = buffer->data; + if (data == buffer->__space.__c) + { + void *copy = malloc (size); + return copy != NULL ? memcpy (copy, data, size) : NULL; + } + else + { + void *copy = realloc (data, size); + return copy != NULL ? copy : data; + } +} +libc_hidden_def (__libc_scratch_buffer_dupfree) diff --git a/pool/shard004/C/0099727_malloc.c b/pool/shard004/C/0099727_malloc.c new file mode 100644 index 0000000000000000000000000000000000000000..b2febebca901e1a6a56e66427175319127e689b0 --- /dev/null +++ b/pool/shard004/C/0099727_malloc.c @@ -0,0 +1,144 @@ +/* + * Copyright(C) 2011-2014 Pedro H. Penna + * + * stdlib/malloc.c - malloc() and free() implementations. + */ + +#include +#include +#include +#include + +/* expand() in at least NALLOC blocks. */ +#define NALLOC 511 + +/* Size of block structure. */ +#define SIZEOF_BLOCK (sizeof(struct block)) + +/* + * Memory block. + */ +struct block +{ + struct block *nextp; /* Next free block. */ + unsigned nblocks; /* Size (in blocks). */ +}; + +/* Free list of blocks. */ +static struct block head; +static struct block *freep = NULL; + +/* + * Frees memory. + */ +void free(void *ptr) +{ + struct block *p; /* Working block. */ + struct block *bp; /* Block being freed. */ + + bp = (struct block *)ptr - 1; + + /* Look for insertion point. */ + for (p = freep; p > bp || p->nextp < bp; p = p->nextp) { + /* Freed block at start or end. */ + if (p >= p->nextp && (bp > p || bp < p->nextp)) + break; + } + + /* Merge with upper block. */ + if (bp + bp->nblocks == p->nextp) + { + bp->nblocks += p->nextp->nblocks + 1; + bp->nextp = p->nextp->nextp; + } else + bp->nextp = p->nextp; + + /* Merge with lower block. */ + if (p + p->nblocks == bp) + { + p->nblocks += bp->nblocks + 1; + p->nextp = bp->nextp; + } + + else + p->nextp = bp; + + freep = p; +} + +/* + * Expands the heap. + */ +static void *expand(unsigned nblocks) +{ + struct block *p; + + /* Expand in at least NALLOC blocks. */ + if (nblocks < NALLOC) + nblocks = NALLOC; + + /* Request more memory to the kernel. */ + if ((p = sbrk((nblocks + 1)*SIZEOF_BLOCK)) == (void *)-1) + return (NULL); + + p->nblocks = nblocks; + free(p + 1); + + return (freep); +} + +/* + * Allocates memory. + */ +void *malloc(size_t size) +{ + struct block *p; /* Working block. */ + struct block *prevp; /* Previous working block. */ + unsigned nblocks; /* Request size (in blocks). */ + + /* Too big request. */ + if (size > size + (SIZEOF_BLOCK - 1)) { + errno = -ENOMEM; + return (NULL); + } + + nblocks = (size + (SIZEOF_BLOCK - 1))/SIZEOF_BLOCK + 1; + + /* Create free list. */ + if ((prevp = freep) == NULL) { + head.nextp = freep = prevp = &head; + head.nblocks = 0; + } + + /* Look for a free block that is big enough. */ + for (p = prevp->nextp; /* void */ ; prevp = p, p = p->nextp) { + /* Found. */ + if (p->nblocks >= nblocks) + { + /* Exact. */ + if (p->nblocks == nblocks) + prevp->nextp = p->nextp; + + /* Split block. */ + else + { + p->nblocks -= nblocks; + p += p->nblocks; + p->nblocks = nblocks; + } + + freep = prevp; + + return (p + 1); + } + + /* Wrapped around free list. */ + if (p == freep) { + /* Expand heap. */ + if ((p = expand(nblocks)) == NULL) + break; + } + } + + return (NULL); +} diff --git a/pool/shard004/C/0099732_mdss_asus_debug.c b/pool/shard004/C/0099732_mdss_asus_debug.c new file mode 100644 index 0000000000000000000000000000000000000000..10e6755dd7dec158e0a7c0a3d2fe97072b222b63 --- /dev/null +++ b/pool/shard004/C/0099732_mdss_asus_debug.c @@ -0,0 +1,107 @@ +#include "mdss_asus_debug.h" +#include +#include +#include +#include +#include +#include +#include +#include + +extern u32 mdss_dsi_panel_cmd_read(struct mdss_dsi_ctrl_pdata *ctrl, char cmd0, + char cmd1, void (*fxn)(int), char *rbuf, int len); + +static struct mdss_dsi_ctrl_pdata *ctrl_asus_global; + +#define LCM_TYPE_ID 28 + +int notify_panel_on_cmds_start(struct mdss_dsi_ctrl_pdata *ctrl) + +{ + ctrl_asus_global = ctrl; + printk("[mDSS][Hyde]keeep dsi control\n"); + return 0; +} + +ssize_t lcd_unique_id_read_proc(char *page, char **start, off_t off, int count, + int *eof, void *data) +{ + int panel_value=0; + volatile int panel_type = -1; + + panel_type = gpio_get_value(LCM_TYPE_ID); + + if (panel_type) + { + char *hsd_rbuffer_01 = kmalloc(sizeof(ctrl_asus_global->rx_buf.len), GFP_KERNEL); + char *hsd_rbuffer_02 = kmalloc(sizeof(ctrl_asus_global->rx_buf.len), GFP_KERNEL); + char *hsd_rbuffer_03 = kmalloc(sizeof(ctrl_asus_global->rx_buf.len), GFP_KERNEL); + if (IS_ERR_OR_NULL(ctrl_asus_global)) { + printk("[MDSSS][Hyde] keep ctrl_asus_global: fail !!\n"); + return -EINVAL; + } + mdss_dsi_panel_cmd_read(ctrl_asus_global,0xDA,0x00,NULL,hsd_rbuffer_01,0); + mdss_dsi_panel_cmd_read(ctrl_asus_global,0xDB,0x00,NULL,hsd_rbuffer_02,0); + mdss_dsi_panel_cmd_read(ctrl_asus_global,0xDC,0x0,NULL,hsd_rbuffer_03,0); + + panel_value = sprintf(page, "%02x%02x%02x\n", *(hsd_rbuffer_01),*(hsd_rbuffer_02),*(hsd_rbuffer_03)); + kfree(hsd_rbuffer_01); + kfree(hsd_rbuffer_02); + kfree(hsd_rbuffer_03); + + } + + else + { + + u32 Tianma_da=0x01; + u32 Tianma_db=0x94; + u32 Tianma_dc=0x1A; + panel_value = sprintf(page, "%02x%02x%02x\n", Tianma_da,Tianma_db,Tianma_dc); + } +return panel_value; + +} + +void create_lcd_unique_id_proc_file(void) +{ + struct proc_dir_entry *lcd_unique_id_proc_file = create_proc_entry("lcd_unique_id", 0644, NULL); + + if (lcd_unique_id_proc_file) + { + lcd_unique_id_proc_file->read_proc = lcd_unique_id_read_proc; + } + else + { + printk("[MDSS][Hyde]proc lcd_unique_id_proc_file create failed!\n"); + } + + return; +} + +ssize_t lcd_type_read_proc(char *page, char **start, off_t off, int count, + int *eof, void *data) +{ + volatile int panel_type = -1; + panel_type = gpio_get_value(LCM_TYPE_ID); + + return sprintf(page, "%d\n", panel_type); +} + +void create_lcd_type_proc_file(void) +{ + struct proc_dir_entry *lcd_type_proc_file = create_proc_entry("lcd_type", 0644, NULL); + + if (lcd_type_proc_file) + { + lcd_type_proc_file->read_proc = lcd_type_read_proc; + } + else + { + printk("[MDSS][Hyde]proc lcd_type_proc_file create failed!\n"); + } + + return; +} + + diff --git a/pool/shard004/C/0099734_lock_failchk.c b/pool/shard004/C/0099734_lock_failchk.c new file mode 100644 index 0000000000000000000000000000000000000000..75f85afc33694cf81660cbccf15b51d95a06086c --- /dev/null +++ b/pool/shard004/C/0099734_lock_failchk.c @@ -0,0 +1,111 @@ +/*- + * See the file LICENSE for redistribution information. + * + * Copyright (c) 2005-2009 Oracle. All rights reserved. + * + * $Id$ + */ + +#include "db_config.h" + +#include "db_int.h" +#include "dbinc/lock.h" +#include "dbinc/txn.h" + +/* + * __lock_failchk -- + * Check for locks held by dead threads of control and release + * read locks. If any write locks were held by dead non-trasnactional + * lockers then we must abort and run recovery. Otherwise we release + * read locks for lockers owned by dead threads. Write locks for + * dead transactional lockers will be freed when we abort the transaction. + * + * PUBLIC: int __lock_failchk __P((ENV *)); + */ +int +__lock_failchk(env) + ENV *env; +{ + DB_ENV *dbenv; + DB_LOCKER *lip; + DB_LOCKREGION *lrp; + DB_LOCKREQ request; + DB_LOCKTAB *lt; + u_int32_t i; + int ret; + char buf[DB_THREADID_STRLEN]; + + dbenv = env->dbenv; + lt = env->lk_handle; + lrp = lt->reginfo.primary; + +retry: LOCK_LOCKERS(env, lrp); + + ret = 0; + for (i = 0; i < lrp->locker_t_size; i++) + SH_TAILQ_FOREACH(lip, <->locker_tab[i], links, __db_locker) { + /* + * If the locker is transactional, we can ignore it if + * it has no read locks or has no locks at all. Check + * the heldby list rather then nlocks since a lock may + * be PENDING. __txn_failchk aborts any transactional + * lockers. Non-transactional lockers progress to + * is_alive test. + */ + if ((lip->id >= TXN_MINIMUM) && + (SH_LIST_EMPTY(&lip->heldby) || + lip->nlocks == lip->nwrites)) + continue; + + /* If the locker is still alive, it's not a problem. */ + if (dbenv->is_alive(dbenv, lip->pid, lip->tid, 0)) + continue; + + /* + * We can only deal with read locks. If a + * non-transactional locker holds write locks we + * have to assume a Berkeley DB operation was + * interrupted with only 1-of-N pages modified. + */ + if (lip->id < TXN_MINIMUM && lip->nwrites != 0) { + ret = __db_failed(env, + "locker has write locks", + lip->pid, lip->tid); + break; + } + + /* + * Discard the locker and its read locks. + */ + if (!SH_LIST_EMPTY(&lip->heldby)) { + __db_msg(env, + "Freeing read locks for locker %#lx: %s", + (u_long)lip->id, dbenv->thread_id_string( + dbenv, lip->pid, lip->tid, buf)); + UNLOCK_LOCKERS(env, lrp); + memset(&request, 0, sizeof(request)); + request.op = DB_LOCK_PUT_READ; + if ((ret = __lock_vec(env, + lip, 0, &request, 1, NULL)) != 0) + return (ret); + } + else + UNLOCK_LOCKERS(env, lrp); + + /* + * This locker is most likely referenced by a cursor + * which is owned by a dead thread. Normally the + * cursor would be available for other threads + * but we assume the dead thread will never release + * it. + */ + if (lip->id < TXN_MINIMUM && + (ret = __lock_freefamilylocker(lt, lip)) != 0) + return (ret); + goto retry; + } + + UNLOCK_LOCKERS(env, lrp); + + return (ret); +} diff --git a/pool/shard004/C/0099741_func_global.c b/pool/shard004/C/0099741_func_global.c new file mode 100644 index 0000000000000000000000000000000000000000..af238e9e0571343a4667c468c55b8ebe2335e9e6 --- /dev/null +++ b/pool/shard004/C/0099741_func_global.c @@ -0,0 +1,333 @@ +/* + * Asterisk -- An open source telephony toolkit. + * + * Copyright (C) 2006, Tilghman Lesher + * + * Tilghman Lesher + * + * See http://www.asterisk.org for more information about + * the Asterisk project. Please do not directly contact + * any of the maintainers of this project for assistance; + * the project provides a web site, mailing lists and IRC + * channels for your use. + * + * This program is free software, distributed under the terms of + * the GNU General Public License Version 2. See the LICENSE file + * at the top of the source tree. + */ + +/*! \file + * + * \brief Global variable dialplan functions + * + * \author Tilghman Lesher + * + * \ingroup functions + */ + +/*** MODULEINFO + core + ***/ + +#include "asterisk.h" + +ASTERISK_FILE_VERSION(__FILE__, "$Revision: 411328 $") + +#include + +#include "asterisk/module.h" +#include "asterisk/pbx.h" +#include "asterisk/channel.h" +#include "asterisk/app.h" +#include "asterisk/stasis_channels.h" + +/*** DOCUMENTATION + + + Gets or sets the global variable specified. + + + + Global variable name + + + + Set or get the value of a global variable specified in varname + + + + + Gets or sets the shared variable specified. + + + + Variable name + + + If not specified will default to current channel. It is the complete + channel name: SIP/12-abcd1234 or the prefix only SIP/12. + + + + Implements a shared variable area, in which you may share variables between + channels. + The variables used in this space are separate from the general namespace of + the channel and thus SHARED(foo) and foo + represent two completely different variables, despite sharing the same name. + Finally, realize that there is an inherent race between channels operating + at the same time, fiddling with each others' internal variables, which is why + this special variable namespace exists; it is to remind you that variables in + the SHARED namespace may change at any time, without warning. You should + therefore take special care to ensure that when using the SHARED namespace, + you retrieve the variable and store it in a regular channel variable before + using it in a set of calculations (or you might be surprised by the result). + + + + + Raised when a variable is shared between channels. + + + + The SHARED variable being set. + The variable name will always be enclosed with + SHARED() + + + The new value of the variable. + + + + SHARED + + + + ***/ + +static void shared_variable_free(void *data); + +static const struct ast_datastore_info shared_variable_info = { + .type = "SHARED_VARIABLES", + .destroy = shared_variable_free, +}; + +static void shared_variable_free(void *data) +{ + struct varshead *varshead = data; + struct ast_var_t *var; + + while ((var = AST_LIST_REMOVE_HEAD(varshead, entries))) { + ast_var_delete(var); + } + ast_free(varshead); +} + +static int global_read(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len) +{ + const char *var = pbx_builtin_getvar_helper(NULL, data); + + *buf = '\0'; + + if (var) + ast_copy_string(buf, var, len); + + return 0; +} + +static int global_write(struct ast_channel *chan, const char *cmd, char *data, const char *value) +{ + pbx_builtin_setvar_helper(NULL, data, value); + + return 0; +} + +static struct ast_custom_function global_function = { + .name = "GLOBAL", + .read = global_read, + .write = global_write, +}; + +static int shared_read(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len) +{ + struct ast_datastore *varstore; + struct varshead *varshead; + struct ast_var_t *var; + AST_DECLARE_APP_ARGS(args, + AST_APP_ARG(var); + AST_APP_ARG(chan); + ); + struct ast_channel *c_ref = NULL; + + if (ast_strlen_zero(data)) { + ast_log(LOG_WARNING, "SHARED() requires an argument: SHARED([,])\n"); + return -1; + } + + AST_STANDARD_APP_ARGS(args, data); + + if (!ast_strlen_zero(args.chan)) { + char *prefix = ast_alloca(strlen(args.chan) + 2); + sprintf(prefix, "%s-", args.chan); + if (!(c_ref = ast_channel_get_by_name(args.chan)) && !(c_ref = ast_channel_get_by_name_prefix(prefix, strlen(prefix)))) { + ast_log(LOG_ERROR, "Channel '%s' not found! Variable '%s' will be blank.\n", args.chan, args.var); + return -1; + } + chan = c_ref; + } else if (!chan) { + ast_log(LOG_WARNING, "No channel was provided to %s function.\n", cmd); + return -1; + } + + ast_channel_lock(chan); + + if (!(varstore = ast_channel_datastore_find(chan, &shared_variable_info, NULL))) { + ast_channel_unlock(chan); + if (c_ref) { + c_ref = ast_channel_unref(c_ref); + } + return -1; + } + + varshead = varstore->data; + *buf = '\0'; + + /* Protected by the channel lock */ + AST_LIST_TRAVERSE(varshead, var, entries) { + if (!strcmp(args.var, ast_var_name(var))) { + ast_copy_string(buf, ast_var_value(var), len); + break; + } + } + + ast_channel_unlock(chan); + + if (c_ref) { + c_ref = ast_channel_unref(c_ref); + } + + return 0; +} + +static int shared_write(struct ast_channel *chan, const char *cmd, char *data, const char *value) +{ + struct ast_datastore *varstore; + struct varshead *varshead; + struct ast_var_t *var; + AST_DECLARE_APP_ARGS(args, + AST_APP_ARG(var); + AST_APP_ARG(chan); + ); + struct ast_channel *c_ref = NULL; + int len; + RAII_VAR(char *, shared_buffer, NULL, ast_free); + + if (ast_strlen_zero(data)) { + ast_log(LOG_WARNING, "SHARED() requires an argument: SHARED([,])\n"); + return -1; + } + + AST_STANDARD_APP_ARGS(args, data); + + if (!ast_strlen_zero(args.chan)) { + char *prefix = ast_alloca(strlen(args.chan) + 2); + sprintf(prefix, "%s-", args.chan); + if (!(c_ref = ast_channel_get_by_name(args.chan)) && !(c_ref = ast_channel_get_by_name_prefix(prefix, strlen(prefix)))) { + ast_log(LOG_ERROR, "Channel '%s' not found! Variable '%s' not set to '%s'.\n", args.chan, args.var, value); + return -1; + } + chan = c_ref; + } else if (!chan) { + ast_log(LOG_WARNING, "No channel was provided to %s function.\n", cmd); + return -1; + } + + len = 9 + strlen(args.var); /* SHARED() + var */ + shared_buffer = ast_malloc(len); + if (!shared_buffer) { + if (c_ref) { + ast_channel_unref(c_ref); + } + return -1; + } + + ast_channel_lock(chan); + + if (!(varstore = ast_channel_datastore_find(chan, &shared_variable_info, NULL))) { + if (!(varstore = ast_datastore_alloc(&shared_variable_info, NULL))) { + ast_log(LOG_ERROR, "Unable to allocate new datastore. Shared variable not set.\n"); + ast_channel_unlock(chan); + if (c_ref) { + c_ref = ast_channel_unref(c_ref); + } + return -1; + } + + if (!(varshead = ast_calloc(1, sizeof(*varshead)))) { + ast_log(LOG_ERROR, "Unable to allocate variable structure. Shared variable not set.\n"); + ast_datastore_free(varstore); + ast_channel_unlock(chan); + if (c_ref) { + c_ref = ast_channel_unref(c_ref); + } + return -1; + } + + varstore->data = varshead; + ast_channel_datastore_add(chan, varstore); + } + varshead = varstore->data; + + /* Protected by the channel lock */ + AST_LIST_TRAVERSE_SAFE_BEGIN(varshead, var, entries) { + /* If there's a previous value, remove it */ + if (!strcmp(args.var, ast_var_name(var))) { + AST_LIST_REMOVE_CURRENT(entries); + ast_var_delete(var); + break; + } + } + AST_LIST_TRAVERSE_SAFE_END; + + if ((var = ast_var_assign(args.var, S_OR(value, "")))) { + AST_LIST_INSERT_HEAD(varshead, var, entries); + + sprintf(shared_buffer, "SHARED(%s)", args.var); + ast_channel_publish_varset(chan, shared_buffer, value); + } + + ast_channel_unlock(chan); + + if (c_ref) { + c_ref = ast_channel_unref(c_ref); + } + + return 0; +} + +static struct ast_custom_function shared_function = { + .name = "SHARED", + .read = shared_read, + .write = shared_write, +}; + +static int unload_module(void) +{ + int res = 0; + + res |= ast_custom_function_unregister(&global_function); + res |= ast_custom_function_unregister(&shared_function); + + return res; +} + +static int load_module(void) +{ + int res = 0; + + res |= ast_custom_function_register(&global_function); + res |= ast_custom_function_register(&shared_function); + + return res; +} + +AST_MODULE_INFO_STANDARD(ASTERISK_GPL_KEY, "Variable dialplan functions"); diff --git a/pool/shard004/C/0099746_bcast_from_p_on_t2.c b/pool/shard004/C/0099746_bcast_from_p_on_t2.c new file mode 100644 index 0000000000000000000000000000000000000000..d8d0da54ce6425908f2d9c195d51984c88434593 --- /dev/null +++ b/pool/shard004/C/0099746_bcast_from_p_on_t2.c @@ -0,0 +1,53 @@ +#include +#include +#include +static const int N=1000; +#pragma xmp nodes p(*) +#pragma xmp template t(1000,1000) +#pragma xmp distribute t(*,cyclic) onto p +int i,j,aa[1000],a; +double bb[1000],b; +float cc[1000],c; +int procs,result=0; + +int main(void) +{ + procs = xmp_num_nodes(); + for(j=1;j + * + * sys/pipe.c - pipe() system call implementation. + */ + +#include +#include +#include +#include +#include + +/* + * Creates an interprocess channel. + */ +PUBLIC int sys_pipe(int fildes[2]) +{ + struct file *f[2]; /* Files. */ + int fd[2]; /* File descriptors. */ + struct inode *inode; /* Pipe inode. */ + + if (!chkmem(fildes, 2*sizeof(int), MAY_WRITE)) + return (-EINVAL); + + /* Get empty file descriptors. */ + if ((fd[0] = getfildes()) < 0) + return (-EMFILE); + if ((fd[1] = getfildes()) < 0) + return (-EMFILE); + + /* Get empty files. */ + if ((f[0] = getfile()) == NULL) + return (-ENFILE); + if ((f[1] = getfile()) == NULL) + return (-ENFILE); + + inode = inode_pipe(); + + /* Failed to get pipe inode. */ + if (inode == NULL) + return (-EAGAIN); + + /* Initialize files. */ + f[0]->oflag = O_RDONLY; + f[1]->oflag = O_WRONLY; + f[0]->count = f[1]->count = 1; + f[0]->inode = f[1]->inode = inode; + curr_proc->ofiles[fd[0]] = f[0]; + curr_proc->ofiles[fd[1]] = f[1]; + + fildes[0] = fd[0]; + fildes[1] = fd[1]; + + return (0); +} diff --git a/pool/shard004/C/0099756_hugetlbpage.c b/pool/shard004/C/0099756_hugetlbpage.c new file mode 100644 index 0000000000000000000000000000000000000000..5bfd5aef53787a349519fea0ee73086d0dcfc7e7 --- /dev/null +++ b/pool/shard004/C/0099756_hugetlbpage.c @@ -0,0 +1,211 @@ +// SPDX-License-Identifier: GPL-2.0 +/* + * IA-32 Huge TLB Page Support for Kernel. + * + * Copyright (C) 2002, Rohit Seth + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#if 0 /* This is just for testing */ +struct page * +follow_huge_addr(struct mm_struct *mm, unsigned long address, int write) +{ + unsigned long start = address; + int length = 1; + int nr; + struct page *page; + struct vm_area_struct *vma; + + vma = find_vma(mm, addr); + if (!vma || !is_vm_hugetlb_page(vma)) + return ERR_PTR(-EINVAL); + + pte = huge_pte_offset(mm, address, vma_mmu_pagesize(vma)); + + /* hugetlb should be locked, and hence, prefaulted */ + WARN_ON(!pte || pte_none(*pte)); + + page = &pte_page(*pte)[vpfn % (HPAGE_SIZE/PAGE_SIZE)]; + + WARN_ON(!PageHead(page)); + + return page; +} + +int pmd_huge(pmd_t pmd) +{ + return 0; +} + +int pud_huge(pud_t pud) +{ + return 0; +} + +#else + +/* + * pmd_huge() returns 1 if @pmd is hugetlb related entry, that is normal + * hugetlb entry or non-present (migration or hwpoisoned) hugetlb entry. + * Otherwise, returns 0. + */ +int pmd_huge(pmd_t pmd) +{ + return !pmd_none(pmd) && + (pmd_val(pmd) & (_PAGE_PRESENT|_PAGE_PSE)) != _PAGE_PRESENT; +} + +int pud_huge(pud_t pud) +{ + return !!(pud_val(pud) & _PAGE_PSE); +} +#endif + +#ifdef CONFIG_HUGETLB_PAGE +static unsigned long hugetlb_get_unmapped_area_bottomup(struct file *file, + unsigned long addr, unsigned long len, + unsigned long pgoff, unsigned long flags) +{ + struct hstate *h = hstate_file(file); + struct vm_unmapped_area_info info; + + info.flags = 0; + info.length = len; + info.low_limit = get_mmap_base(1); + + /* + * If hint address is above DEFAULT_MAP_WINDOW, look for unmapped area + * in the full address space. + */ + info.high_limit = in_32bit_syscall() ? + task_size_32bit() : task_size_64bit(addr > DEFAULT_MAP_WINDOW); + + info.align_mask = PAGE_MASK & ~huge_page_mask(h); + info.align_offset = 0; + return vm_unmapped_area(&info); +} + +static unsigned long hugetlb_get_unmapped_area_topdown(struct file *file, + unsigned long addr, unsigned long len, + unsigned long pgoff, unsigned long flags) +{ + struct hstate *h = hstate_file(file); + struct vm_unmapped_area_info info; + + info.flags = VM_UNMAPPED_AREA_TOPDOWN; + info.length = len; + info.low_limit = PAGE_SIZE; + info.high_limit = get_mmap_base(0); + + /* + * If hint address is above DEFAULT_MAP_WINDOW, look for unmapped area + * in the full address space. + */ + if (addr > DEFAULT_MAP_WINDOW && !in_32bit_syscall()) + info.high_limit += TASK_SIZE_MAX - DEFAULT_MAP_WINDOW; + + info.align_mask = PAGE_MASK & ~huge_page_mask(h); + info.align_offset = 0; + addr = vm_unmapped_area(&info); + + /* + * A failed mmap() very likely causes application failure, + * so fall back to the bottom-up function here. This scenario + * can happen with large stack limits and large mmap() + * allocations. + */ + if (addr & ~PAGE_MASK) { + VM_BUG_ON(addr != -ENOMEM); + info.flags = 0; + info.low_limit = TASK_UNMAPPED_BASE; + info.high_limit = TASK_SIZE_LOW; + addr = vm_unmapped_area(&info); + } + + return addr; +} + +unsigned long +hugetlb_get_unmapped_area(struct file *file, unsigned long addr, + unsigned long len, unsigned long pgoff, unsigned long flags) +{ + struct hstate *h = hstate_file(file); + struct mm_struct *mm = current->mm; + struct vm_area_struct *vma; + + if (len & ~huge_page_mask(h)) + return -EINVAL; + + if (len > TASK_SIZE) + return -ENOMEM; + + /* No address checking. See comment at mmap_address_hint_valid() */ + if (flags & MAP_FIXED) { + if (prepare_hugepage_range(file, addr, len)) + return -EINVAL; + return addr; + } + + if (addr) { + addr &= huge_page_mask(h); + if (!mmap_address_hint_valid(addr, len)) + goto get_unmapped_area; + + vma = find_vma(mm, addr); + if (!vma || addr + len <= vm_start_gap(vma)) + return addr; + } + +get_unmapped_area: + if (mm->get_unmapped_area == arch_get_unmapped_area) + return hugetlb_get_unmapped_area_bottomup(file, addr, len, + pgoff, flags); + else + return hugetlb_get_unmapped_area_topdown(file, addr, len, + pgoff, flags); +} +#endif /* CONFIG_HUGETLB_PAGE */ + +#ifdef CONFIG_X86_64 +static __init int setup_hugepagesz(char *opt) +{ + unsigned long ps = memparse(opt, &opt); + if (ps == PMD_SIZE) { + hugetlb_add_hstate(PMD_SHIFT - PAGE_SHIFT); + } else if (ps == PUD_SIZE && boot_cpu_has(X86_FEATURE_GBPAGES)) { + hugetlb_add_hstate(PUD_SHIFT - PAGE_SHIFT); + } else { + hugetlb_bad_size(); + printk(KERN_ERR "hugepagesz: Unsupported page size %lu M\n", + ps >> 20); + return 0; + } + return 1; +} +__setup("hugepagesz=", setup_hugepagesz); + +#ifdef CONFIG_CONTIG_ALLOC +static __init int gigantic_pages_init(void) +{ + /* With compaction or CMA we can allocate gigantic pages at runtime */ + if (boot_cpu_has(X86_FEATURE_GBPAGES) && !size_to_hstate(1UL << PUD_SHIFT)) + hugetlb_add_hstate(PUD_SHIFT - PAGE_SHIFT); + return 0; +} +arch_initcall(gigantic_pages_init); +#endif +#endif diff --git a/pool/shard004/C/0099758_mali_osk_mali.c b/pool/shard004/C/0099758_mali_osk_mali.c new file mode 100644 index 0000000000000000000000000000000000000000..20881e4cdb37ec894da9368ed58f8ea900035ef8 --- /dev/null +++ b/pool/shard004/C/0099758_mali_osk_mali.c @@ -0,0 +1,139 @@ +/* + * Copyright (C) 2010-2013 ARM Limited. All rights reserved. + * + * This program is free software and is provided to you under the terms of the GNU General Public License version 2 + * as published by the Free Software Foundation, and any use by you of this program is subject to the terms of such GNU licence. + * + * A copy of the licence is included with the program, and can also be obtained from Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + */ + +/** + * @file mali_osk_mali.c + * Implementation of the OS abstraction layer which is specific for the Mali kernel device driver + */ +#include +#include +#include +#include + +#include "mali_osk_mali.h" +#include "mali_kernel_common.h" /* MALI_xxx macros */ +#include "mali_osk.h" /* kernel side OS functions */ +#include "mali_uk_types.h" +#include "mali_kernel_linux.h" + +_mali_osk_errcode_t _mali_osk_resource_find(u32 addr, _mali_osk_resource_t *res) +{ + int i; + + if (NULL == mali_platform_device) + { + /* Not connected to a device */ + return _MALI_OSK_ERR_ITEM_NOT_FOUND; + } + + for (i = 0; i < mali_platform_device->num_resources; i++) + { + if (IORESOURCE_MEM == resource_type(&(mali_platform_device->resource[i])) && + mali_platform_device->resource[i].start == addr) + { + if (NULL != res) + { + res->base = addr; + res->description = mali_platform_device->resource[i].name; + + /* Any (optional) IRQ resource belonging to this resource will follow */ + if ((i + 1) < mali_platform_device->num_resources && + IORESOURCE_IRQ == resource_type(&(mali_platform_device->resource[i+1]))) + { + res->irq = mali_platform_device->resource[i+1].start; + } + else + { + res->irq = -1; + } + } + return _MALI_OSK_ERR_OK; + } + } + + return _MALI_OSK_ERR_ITEM_NOT_FOUND; +} + +u32 _mali_osk_resource_base_address(void) +{ + u32 lowest_addr = 0xFFFFFFFF; + u32 ret = 0; + + if (NULL != mali_platform_device) + { + int i; + for (i = 0; i < mali_platform_device->num_resources; i++) + { + if (mali_platform_device->resource[i].flags & IORESOURCE_MEM && + mali_platform_device->resource[i].start < lowest_addr) + { + lowest_addr = mali_platform_device->resource[i].start; + ret = lowest_addr; + } + } + } + + return ret; +} + +_mali_osk_errcode_t _mali_osk_device_data_get(struct _mali_osk_device_data *data) +{ + MALI_DEBUG_ASSERT_POINTER(data); + + if (NULL != mali_platform_device) + { + struct mali_gpu_device_data* os_data = NULL; + + os_data = (struct mali_gpu_device_data*)mali_platform_device->dev.platform_data; + if (NULL != os_data) + { + /* Copy data from OS dependant struct to Mali neutral struct (identical!) */ + data->dedicated_mem_start = os_data->dedicated_mem_start; + data->dedicated_mem_size = os_data->dedicated_mem_size; + data->shared_mem_size = os_data->shared_mem_size; + data->fb_start = os_data->fb_start; + data->fb_size = os_data->fb_size; + data->utilization_interval = os_data->utilization_interval; + data->utilization_handler = os_data->utilization_handler; + return _MALI_OSK_ERR_OK; + } + } + + return _MALI_OSK_ERR_ITEM_NOT_FOUND; +} + +mali_bool _mali_osk_shared_interrupts(void) +{ + u32 irqs[128]; + u32 i, j, irq, num_irqs_found = 0; + + MALI_DEBUG_ASSERT_POINTER(mali_platform_device); + MALI_DEBUG_ASSERT(128 >= mali_platform_device->num_resources); + + for (i = 0; i < mali_platform_device->num_resources; i++) + { + if (IORESOURCE_IRQ & mali_platform_device->resource[i].flags) + { + irq = mali_platform_device->resource[i].start; + + for (j = 0; j < num_irqs_found; ++j) + { + if (irq == irqs[j]) + { + return MALI_TRUE; + } + } + + irqs[num_irqs_found++] = irq; + } + } + + return MALI_FALSE; +} diff --git a/pool/shard004/C/0099761_t_vfsops.c b/pool/shard004/C/0099761_t_vfsops.c new file mode 100644 index 0000000000000000000000000000000000000000..1bcee89e573d384fd6cdc41b21887b8692090c09 --- /dev/null +++ b/pool/shard004/C/0099761_t_vfsops.c @@ -0,0 +1,211 @@ +/* $NetBSD: t_vfsops.c,v 1.11 2011/04/04 19:16:58 hannken Exp $ */ + +/*- + * Copyright (c) 2010 The NetBSD Foundation, 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 NETBSD FOUNDATION, INC. AND CONTRIBUTORS + * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED + * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS + * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + */ + +#include +#include + +#include +#include +#include +#include +#include + +#include +#include + +#include "../common/h_fsmacros.h" +#include "../../h_macros.h" + +static void +tmount(const atf_tc_t *tc, const char *path) +{ + + return; +} + +static void +tstatvfs(const atf_tc_t *tc, const char *path) +{ + const char *fstype = atf_tc_get_md_var(tc, "X-fs.mntname"); + struct statvfs svb; + + if (rump_sys_statvfs1(path, &svb, ST_WAIT) == -1) + atf_tc_fail_errno("statvfs"); + + ATF_REQUIRE(svb.f_namemax > 0 && svb.f_namemax <= MAXNAMLEN); + if (!(FSTYPE_PUFFS(tc) || FSTYPE_P2K_FFS(tc))) + ATF_REQUIRE_STREQ(svb.f_fstypename, fstype); + ATF_REQUIRE_STREQ(svb.f_mntonname, path); +} + +static void +tsync(const atf_tc_t *tc, const char *path) +{ + + rump_sys_sync(); +} + +#define MAGICSTR "just a string, I like A" +static void +tfilehandle(const atf_tc_t *tc, const char *path) +{ + char fpath[MAXPATHLEN]; + char buf[sizeof(MAGICSTR)]; + size_t fhsize; + void *fhp; + int fd; + + sprintf(fpath, "%s/file", path); + fd = rump_sys_open(fpath, O_RDWR | O_CREAT, 0777); + if (fd == -1) + atf_tc_fail_errno("open"); + + if (rump_sys_write(fd, MAGICSTR, sizeof(MAGICSTR)) != sizeof(MAGICSTR)) + atf_tc_fail("write to file"); + rump_sys_close(fd); + + /* + * Get file handle size. + * This also weeds out unsupported file systems. + */ + fhsize = 0; + if (rump_sys_getfh(fpath, NULL, &fhsize) == -1) { + if (errno == EOPNOTSUPP) { + atf_tc_skip("file handles not supported"); + } else if (errno != E2BIG) { + atf_tc_fail_errno("getfh size"); + } + } + + fhp = malloc(fhsize); + if (rump_sys_getfh(fpath, fhp, &fhsize) == -1) + atf_tc_fail_errno("getfh"); + + /* open file based on file handle */ + fd = rump_sys_fhopen(fhp, fhsize, O_RDONLY); + if (fd == -1) { + atf_tc_fail_errno("fhopen"); + } + + /* check that we got the same file */ + if (rump_sys_read(fd, buf, sizeof(buf)) != sizeof(MAGICSTR)) + atf_tc_fail("read fhopened file"); + + ATF_REQUIRE_STREQ(buf, MAGICSTR); + + rump_sys_close(fd); +} + +#define FNAME "a_file" +static void +tfhremove(const atf_tc_t *tc, const char *path) +{ + size_t fhsize; + void *fhp; + int fd; + + RL(rump_sys_chdir(path)); + RL(fd = rump_sys_open(FNAME, O_RDWR | O_CREAT, 0777)); + RL(rump_sys_close(fd)); + + fhsize = 0; + if (rump_sys_getfh(FNAME, NULL, &fhsize) == -1) { + if (errno == EOPNOTSUPP) { + atf_tc_skip("file handles not supported"); + } else if (errno != E2BIG) { + atf_tc_fail_errno("getfh size"); + } + } + + fhp = malloc(fhsize); + RL(rump_sys_getfh(FNAME, fhp, &fhsize)); + RL(rump_sys_unlink(FNAME)); + + if (FSTYPE_LFS(tc)) + atf_tc_expect_fail("fhopen() for removed file succeeds " + "(PR kern/43745)"); + ATF_REQUIRE_ERRNO(ESTALE, rump_sys_fhopen(fhp, fhsize, O_RDONLY) == -1); + atf_tc_expect_pass(); + + RL(rump_sys_chdir("/")); +} +#undef FNAME + +/* + * This test only checks the file system doesn't crash. We *might* + * try a valid file handle. + */ +static void +tfhinval(const atf_tc_t *tc, const char *path) +{ + size_t fhsize; + void *fhp; + unsigned long seed; + int fd; + + srandom(seed = time(NULL)); + printf("RNG seed %lu\n", seed); + + RL(rump_sys_chdir(path)); + fhsize = 0; + if (rump_sys_getfh(".", NULL, &fhsize) == -1) { + if (errno == EOPNOTSUPP) { + atf_tc_skip("file handles not supported"); + } else if (errno != E2BIG) { + atf_tc_fail_errno("getfh size"); + } + } + + fhp = malloc(fhsize); + tests_makegarbage(fhp, fhsize); + fd = rump_sys_fhopen(fhp, fhsize, O_RDWR); + if (fd != -1) + rump_sys_close(fd); + + RL(rump_sys_chdir("/")); +} + +ATF_TC_FSAPPLY(tmount, "mount/unmount"); +ATF_TC_FSAPPLY(tstatvfs, "statvfs"); +ATF_TC_FSAPPLY(tsync, "sync"); +ATF_TC_FSAPPLY(tfilehandle, "file handles"); +ATF_TC_FSAPPLY(tfhremove, "fhtovp for removed file"); +ATF_TC_FSAPPLY(tfhinval, "fhopen invalid filehandle"); + +ATF_TP_ADD_TCS(tp) +{ + + ATF_TP_FSAPPLY(tmount); + ATF_TP_FSAPPLY(tstatvfs); + ATF_TP_FSAPPLY(tsync); + ATF_TP_FSAPPLY(tfilehandle); + ATF_TP_FSAPPLY(tfhremove); + ATF_TP_FSAPPLY(tfhinval); + + return atf_no_error(); +} diff --git a/pool/shard004/C/0099767_mipi_orise.c b/pool/shard004/C/0099767_mipi_orise.c new file mode 100644 index 0000000000000000000000000000000000000000..2afbb9b6821fe3b1e156b0dd9db24d632b8b1b6b --- /dev/null +++ b/pool/shard004/C/0099767_mipi_orise.c @@ -0,0 +1,194 @@ +/* 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. + * + */ + +#include "msm_fb.h" +#include "mipi_dsi.h" +#include "mipi_orise.h" +#include "mdp4.h" + + +static struct mipi_dsi_panel_platform_data *mipi_orise_pdata; + +static struct dsi_buf orise_tx_buf; +static struct dsi_buf orise_rx_buf; + +static char enter_sleep[2] = {0x10, 0x00}; /* DTYPE_DCS_WRITE */ +static char exit_sleep[2] = {0x11, 0x00}; /* DTYPE_DCS_WRITE */ +static char display_off[2] = {0x28, 0x00}; /* DTYPE_DCS_WRITE */ +static char display_on[2] = {0x29, 0x00}; /* DTYPE_DCS_WRITE */ + +static struct dsi_cmd_desc orise_video_on_cmds[] = { + {DTYPE_DCS_WRITE, 1, 0, 0, 10, + sizeof(exit_sleep), exit_sleep}, + {DTYPE_DCS_WRITE, 1, 0, 0, 10, + sizeof(display_on), display_on}, +}; + +static struct dsi_cmd_desc orise_cmd_on_cmds[] = { + {DTYPE_DCS_WRITE, 1, 0, 0, 10, + sizeof(exit_sleep), exit_sleep}, + {DTYPE_DCS_WRITE, 1, 0, 0, 10, + sizeof(display_on), display_on}, +}; + +static struct dsi_cmd_desc orise_display_off_cmds[] = { + {DTYPE_DCS_WRITE, 1, 0, 0, 10, + sizeof(display_off), display_off}, + {DTYPE_DCS_WRITE, 1, 0, 0, 120, + sizeof(enter_sleep), enter_sleep} +}; + +static int mipi_orise_lcd_on(struct platform_device *pdev) +{ + struct msm_fb_data_type *mfd; + struct mipi_panel_info *mipi; + struct msm_panel_info *pinfo; + + mfd = platform_get_drvdata(pdev); + if (!mfd) + return -ENODEV; + if (mfd->key != MFD_KEY) + return -EINVAL; + + pinfo = &mfd->panel_info; + mipi = &mfd->panel_info.mipi; + + if (mipi->mode == DSI_VIDEO_MODE) { + mipi_dsi_cmds_tx(mfd, &orise_tx_buf, orise_video_on_cmds, + ARRAY_SIZE(orise_video_on_cmds)); + } else { + mipi_dsi_cmds_tx(mfd, &orise_tx_buf, orise_cmd_on_cmds, + ARRAY_SIZE(orise_cmd_on_cmds)); + + mipi_dsi_cmd_bta_sw_trigger(); /* clean up ack_err_status */ + } + + return 0; +} + +static int mipi_orise_lcd_off(struct platform_device *pdev) +{ + struct msm_fb_data_type *mfd; + + mfd = platform_get_drvdata(pdev); + + if (!mfd) + return -ENODEV; + if (mfd->key != MFD_KEY) + return -EINVAL; + + mipi_dsi_cmds_tx(mfd, &orise_tx_buf, orise_display_off_cmds, + ARRAY_SIZE(orise_display_off_cmds)); + + return 0; +} + + + +static int __devinit mipi_orise_lcd_probe(struct platform_device *pdev) +{ + struct msm_fb_data_type *mfd; + struct mipi_panel_info *mipi; + struct platform_device *current_pdev; + static struct mipi_dsi_phy_ctrl *phy_settings; + + if (pdev->id == 0) { + mipi_orise_pdata = pdev->dev.platform_data; + + if (mipi_orise_pdata + && mipi_orise_pdata->phy_ctrl_settings) { + phy_settings = (mipi_orise_pdata->phy_ctrl_settings); + } + + return 0; + } + + current_pdev = msm_fb_add_device(pdev); + + if (current_pdev) { + mfd = platform_get_drvdata(current_pdev); + if (!mfd) + return -ENODEV; + if (mfd->key != MFD_KEY) + return -EINVAL; + + mipi = &mfd->panel_info.mipi; + + if (phy_settings != NULL) + mipi->dsi_phy_db = phy_settings; + } + return 0; +} + +static struct platform_driver this_driver = { + .probe = mipi_orise_lcd_probe, + .driver = { + .name = "mipi_orise", + }, +}; + +static struct msm_fb_panel_data orise_panel_data = { + .on = mipi_orise_lcd_on, + .off = mipi_orise_lcd_off, +}; + +static int ch_used[3]; + +int mipi_orise_device_register(struct msm_panel_info *pinfo, + u32 channel, u32 panel) +{ + struct platform_device *pdev = NULL; + int ret; + + if ((channel >= 3) || ch_used[channel]) + return -ENODEV; + + ch_used[channel] = TRUE; + + pdev = platform_device_alloc("mipi_orise", (panel << 8)|channel); + if (!pdev) + return -ENOMEM; + + orise_panel_data.panel_info = *pinfo; + + ret = platform_device_add_data(pdev, &orise_panel_data, + sizeof(orise_panel_data)); + if (ret) { + printk(KERN_ERR + "%s: platform_device_add_data failed!\n", __func__); + goto err_device_put; + } + + ret = platform_device_add(pdev); + if (ret) { + printk(KERN_ERR + "%s: platform_device_register failed!\n", __func__); + goto err_device_put; + } + + return 0; + +err_device_put: + platform_device_put(pdev); + return ret; +} + +static int __init mipi_orise_lcd_init(void) +{ + mipi_dsi_buf_alloc(&orise_tx_buf, DSI_BUF_SIZE); + mipi_dsi_buf_alloc(&orise_rx_buf, DSI_BUF_SIZE); + + return platform_driver_register(&this_driver); +} + +module_init(mipi_orise_lcd_init); diff --git a/pool/shard004/C/0099768_loader_gif.c b/pool/shard004/C/0099768_loader_gif.c new file mode 100644 index 0000000000000000000000000000000000000000..638df591f5b0e8649b1c243858116665c06382ef --- /dev/null +++ b/pool/shard004/C/0099768_loader_gif.c @@ -0,0 +1,226 @@ +#include "loader_common.h" +#include +#include +#include +#include + +char +load(ImlibImage * im, ImlibProgressFunction progress, char progress_granularity, + char immediate_load) +{ + static const int intoffset[] = { 0, 4, 2, 1 }; + static const int intjump[] = { 8, 8, 4, 2 }; + int rc; + DATA32 *ptr; + GifFileType *gif; + GifRowType *rows; + GifRecordType rec; + ColorMapObject *cmap; + int i, j, done, bg, r, g, b, w = 0, h = 0; + float per = 0.0, per_inc; + int last_per = 0, last_y = 0; + int transp; + int fd; + + done = 0; + rows = NULL; + transp = -1; + + /* if immediate_load is 1, then dont delay image laoding as below, or */ + /* already data in this image - dont load it again */ + if (im->data) + return 0; + + fd = open(im->real_file, O_RDONLY); + if (fd < 0) + return 0; + +#if GIFLIB_MAJOR >= 5 + gif = DGifOpenFileHandle(fd, NULL); +#else + gif = DGifOpenFileHandle(fd); +#endif + if (!gif) + { + close(fd); + return 0; + } + + rc = 0; /* Failure */ + + do + { + if (DGifGetRecordType(gif, &rec) == GIF_ERROR) + { + /* PrintGifError(); */ + rec = TERMINATE_RECORD_TYPE; + } + if ((rec == IMAGE_DESC_RECORD_TYPE) && (!done)) + { + if (DGifGetImageDesc(gif) == GIF_ERROR) + { + /* PrintGifError(); */ + rec = TERMINATE_RECORD_TYPE; + break; + } + w = gif->Image.Width; + h = gif->Image.Height; + if (!IMAGE_DIMENSIONS_OK(w, h)) + goto quit2; + + rows = calloc(h, sizeof(GifRowType *)); + if (!rows) + goto quit2; + + for (i = 0; i < h; i++) + { + rows[i] = calloc(w, sizeof(GifPixelType)); + if (!rows[i]) + goto quit; + } + + if (gif->Image.Interlace) + { + for (i = 0; i < 4; i++) + { + for (j = intoffset[i]; j < h; j += intjump[i]) + { + DGifGetLine(gif, rows[j], w); + } + } + } + else + { + for (i = 0; i < h; i++) + { + DGifGetLine(gif, rows[i], w); + } + } + done = 1; + } + else if (rec == EXTENSION_RECORD_TYPE) + { + int ext_code; + GifByteType *ext; + + ext = NULL; + DGifGetExtension(gif, &ext_code, &ext); + while (ext) + { + if ((ext_code == 0xf9) && (ext[1] & 1) && (transp < 0)) + { + transp = (int)ext[4]; + } + ext = NULL; + DGifGetExtensionNext(gif, &ext); + } + } + } + while (rec != TERMINATE_RECORD_TYPE); + + if (transp >= 0) + { + SET_FLAG(im->flags, F_HAS_ALPHA); + } + else + { + UNSET_FLAG(im->flags, F_HAS_ALPHA); + } + if (!rows) + { + goto quit2; + } + + /* set the format string member to the lower-case full extension */ + /* name for the format - so example names would be: */ + /* "png", "jpeg", "tiff", "ppm", "pgm", "pbm", "gif", "xpm" ... */ + im->w = w; + im->h = h; + if (!im->format) + im->format = strdup("gif"); + + if (im->loader || immediate_load || progress) + { + bg = gif->SBackGroundColor; + cmap = (gif->Image.ColorMap ? gif->Image.ColorMap : gif->SColorMap); + im->data = (DATA32 *) malloc(sizeof(DATA32) * w * h); + if (!im->data) + goto quit; + + if (!cmap) + { + /* No colormap? Now what?? Let's clear the image (and not segv) */ + memset(im->data, 0, sizeof(DATA32) * w * h); + rc = 1; + goto finish; + } + + ptr = im->data; + per_inc = 100.0 / (((float)w) * h); + for (i = 0; i < h; i++) + { + for (j = 0; j < w; j++) + { + if (rows[i][j] == transp) + { + r = cmap->Colors[bg].Red; + g = cmap->Colors[bg].Green; + b = cmap->Colors[bg].Blue; + *ptr++ = 0x00ffffff & ((r << 16) | (g << 8) | b); + } + else + { + r = cmap->Colors[rows[i][j]].Red; + g = cmap->Colors[rows[i][j]].Green; + b = cmap->Colors[rows[i][j]].Blue; + *ptr++ = (0xff << 24) | (r << 16) | (g << 8) | b; + } + per += per_inc; + if (progress && (((int)per) != last_per) + && (((int)per) % progress_granularity == 0)) + { + last_per = (int)per; + if (!(progress(im, (int)per, 0, last_y, w, i))) + { + rc = 2; + goto quit; + } + last_y = i; + } + } + } + + finish: + if (progress) + progress(im, 100, 0, last_y, w, h); + } + + rc = 1; /* Success */ + + quit: + for (i = 0; i < h; i++) + free(rows[i]); + free(rows); + + quit2: +#if GIFLIB_MAJOR > 5 || (GIFLIB_MAJOR == 5 && GIFLIB_MINOR >= 1) + DGifCloseFile(gif, NULL); +#else + DGifCloseFile(gif); +#endif + + return rc; +} + +void +formats(ImlibLoader * l) +{ + static const char *const list_formats[] = { "gif" }; + int i; + + l->num_formats = sizeof(list_formats) / sizeof(char *); + l->formats = malloc(sizeof(char *) * l->num_formats); + + for (i = 0; i < l->num_formats; i++) + l->formats[i] = strdup(list_formats[i]); +} diff --git a/pool/shard004/C/0099783_cdt_atf.c b/pool/shard004/C/0099783_cdt_atf.c new file mode 100644 index 0000000000000000000000000000000000000000..162606a4dde36a6e353ceba703a994353f56f37d --- /dev/null +++ b/pool/shard004/C/0099783_cdt_atf.c @@ -0,0 +1,145 @@ +#include +#include +#include +#include +#include "charsets.h" +#include "gdl.h" +#include "atffile.h" +#include "cdf.h" +#include "cdt.h" +#include "cdt_foreign.h" + +extern void xtf_init(void); +extern void xtf_term(void); + +extern const char *file; +extern int lnum; + +extern FILE *f_xml; +extern int no_destfile, no_pi; + +struct node; + +struct cdt_atf +{ + const char *type; + struct node *atf_tree; +}; + +static char tempname[16]; + +static void * +cdt_atf_init(const char *type) +{ + static struct cdt_atf *atfp = NULL; + if (!atfp) + { + atfp = malloc(sizeof(struct cdt_atf)); + atfp->type = type; + /*xtf_init();*/ + /*current_state = set_state(s_global,s_text);*/ + curr_lang = text_lang = global_lang; + if (!cdt_project) + cdt_project = "cdli"; +#if 0 + load_lang_in_project(current_state.lang); + charset_init_lang(curr_data->this); + curr_data->cset = curr_data->this->cset[current_state.mode]; +#endif + /* strcpy(tempname,"cdt_atf_XXXXXX"); */ + f_xml = tmpfile(); +#if 0 + if (tmpfd >= 0) + f_xml = fdopen(tmpfd,"r+"); +#endif + no_destfile = no_pi = 1; + } + else if (!type) + { + free(atfp); + atfp = NULL; + } + return atfp; +} + +static void +cdt_atf_term(struct cdt_atf *atfp) +{ + int fno = -1; + /*atf free routine atfp->atf_tree*/ + /*xtf_term();*/ + (void)cdt_atf_init(NULL); + fno = fileno(f_xml); + fclose(f_xml); + close(fno); + unlink(tempname); +} + +static void +finish_atf(struct cdt_node *np) +{ + long flen, actual; + unsigned char *res; + extern int verbose; + + fflush(f_xml); + fseek(f_xml,0L,SEEK_END); + flen = ftell(f_xml); + if (verbose) + fprintf(stderr, "cdt_atf: ATF flen = %ld\n", flen); + fseek(f_xml,0L,SEEK_SET); + res = malloc(flen+1); + + if (flen != (actual = fread(res,1,flen,f_xml))) + { + fprintf(stderr, "cdt_atf: ATF call returned %ld bytes but I only read %ld\n", + flen, actual); + } + res[flen] = '\0'; + np->children = list_create(LIST_SINGLE); + list_add(np->children,res); + + ftruncate(fileno(f_xml),0); + fseek(f_xml,0L,SEEK_SET); +} + +static void +atf_reader(struct cdt_node *np) +{ + process_string(cdt_run, np->text,strlen((const char *)np->text)); + finish_atf(np); +} + +static void +atf_writer(FILE *fp, struct cdt_node *np) +{ + if (np->children) + { + fputs("",fp); + fputs(list_first(np->children),fp); + fputs("",fp); + } +} + +void +gdl_reader(struct cdt_node *np, unsigned char *gdlinput) +{ + (void)cdt_atf_init("gdl"); + file = np->file; + lnum = np->lnum; + gdl_string(gdlinput, GDL_FRAG_OK); + finish_atf(np); +} + +void +gdl_writer(FILE *fp, struct cdt_node *np) +{ + if (np->children) + { + fputs("",fp); + fputs(list_first(np->children),fp); + fputs("",fp); + } +} + +struct cdt_foreign cdt_atf = { cdt_atf_init , (cdt_foreign_term)cdt_atf_term , atf_reader , atf_writer }; diff --git a/pool/shard004/C/0099785_stm32l4xx_hal_rng.c b/pool/shard004/C/0099785_stm32l4xx_hal_rng.c new file mode 100644 index 0000000000000000000000000000000000000000..225b4042cc4aeb59601bdc3663a05b0e489ad9bd --- /dev/null +++ b/pool/shard004/C/0099785_stm32l4xx_hal_rng.c @@ -0,0 +1,519 @@ +/** + ****************************************************************************** + * @file stm32l4xx_hal_rng.c + * @author MCD Application Team + * @version V1.5.2 + * @date 12-September-2016 + * @brief RNG HAL module driver. + * This file provides firmware functions to manage the following + * functionalities of the Random Number Generator (RNG) peripheral: + * + Initialization/de-initialization functions + * + Peripheral Control functions + * + Peripheral State functions + * + @verbatim + ============================================================================== + ##### How to use this driver ##### + ============================================================================== + [..] + The RNG HAL driver can be used as follows: + + (#) Enable the RNG controller clock using __HAL_RCC_RNG_CLK_ENABLE() macro + in HAL_RNG_MspInit(). + (#) Activate the RNG peripheral using HAL_RNG_Init() function. + (#) Wait until the 32-bit Random Number Generator contains a valid + random data using (polling/interrupt) mode. + (#) Get the 32 bit random number using HAL_RNG_GenerateRandomNumber() function. + + @endverbatim + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2016 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 "stm32l4xx_hal.h" + +/** @addtogroup STM32L4xx_HAL_Driver + * @{ + */ + +/** @defgroup RNG RNG + * @brief RNG HAL module driver. + * @{ + */ + +#ifdef HAL_RNG_MODULE_ENABLED + + + +/* Private types -------------------------------------------------------------*/ +/* Private defines -----------------------------------------------------------*/ +/** @defgroup RNG_Private_Constants RNG_Private_Constants + * @{ + */ +#define RNG_TIMEOUT_VALUE 2 +/** + * @} + */ + +/* Private macros ------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private function prototypes -----------------------------------------------*/ +/* Private functions ---------------------------------------------------------*/ +/* Exported functions --------------------------------------------------------*/ + +/** @addtogroup RNG_Exported_Functions + * @{ + */ + +/** @addtogroup RNG_Exported_Functions_Group1 + * @brief Initialization and de-initialization functions + * +@verbatim + =============================================================================== + ##### Initialization and de-initialization functions ##### + =============================================================================== + [..] This section provides functions allowing to: + (+) Initialize the RNG according to the specified parameters + in the RNG_InitTypeDef and create the associated handle + (+) DeInitialize the RNG peripheral + (+) Initialize the RNG MSP (MCU Specific Package) + (+) DeInitialize the RNG MSP + +@endverbatim + * @{ + */ + +/** + * @brief Initialize the RNG peripheral and initialize the associated handle. + * @param hrng: pointer to a RNG_HandleTypeDef structure. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_RNG_Init(RNG_HandleTypeDef *hrng) +{ + /* Check the RNG handle allocation */ + if(hrng == NULL) + { + return HAL_ERROR; + } + + assert_param(IS_RNG_ALL_INSTANCE(hrng->Instance)); + + __HAL_LOCK(hrng); + + if(hrng->State == HAL_RNG_STATE_RESET) + { + /* Allocate lock resource and initialize it */ + hrng->Lock = HAL_UNLOCKED; + + /* Init the low level hardware */ + HAL_RNG_MspInit(hrng); + } + + /* Change RNG peripheral state */ + hrng->State = HAL_RNG_STATE_BUSY; + + /* Enable the RNG Peripheral */ + __HAL_RNG_ENABLE(hrng); + + /* Initialize the RNG state */ + hrng->State = HAL_RNG_STATE_READY; + + __HAL_UNLOCK(hrng); + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief DeInitialize the RNG peripheral. + * @param hrng: pointer to a RNG_HandleTypeDef structure. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_RNG_DeInit(RNG_HandleTypeDef *hrng) +{ + /* Check the RNG handle allocation */ + if(hrng == NULL) + { + return HAL_ERROR; + } + /* Disable the RNG Peripheral */ + CLEAR_BIT(hrng->Instance->CR, RNG_CR_IE | RNG_CR_RNGEN); + + /* Clear RNG interrupt status flags */ + CLEAR_BIT(hrng->Instance->SR, RNG_SR_CEIS | RNG_SR_SEIS); + + /* DeInit the low level hardware */ + HAL_RNG_MspDeInit(hrng); + + /* Update the RNG state */ + hrng->State = HAL_RNG_STATE_RESET; + + /* Release Lock */ + __HAL_UNLOCK(hrng); + + /* Return the function status */ + return HAL_OK; +} + +/** + * @brief Initialize the RNG MSP. + * @param hrng: pointer to a RNG_HandleTypeDef structure. + * @retval None + */ +__weak void HAL_RNG_MspInit(RNG_HandleTypeDef *hrng) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hrng); + + /* NOTE : This function should not be modified. When the callback is needed, + function HAL_RNG_MspInit must be implemented in the user file. + */ +} + +/** + * @brief DeInitialize the RNG MSP. + * @param hrng: pointer to a RNG_HandleTypeDef structure. + * @retval None + */ +__weak void HAL_RNG_MspDeInit(RNG_HandleTypeDef *hrng) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hrng); + + /* NOTE : This function should not be modified. When the callback is needed, + function HAL_RNG_MspDeInit must be implemented in the user file. + */ +} + +/** + * @} + */ + +/** @addtogroup RNG_Exported_Functions_Group2 + * @brief Management functions. + * +@verbatim + =============================================================================== + ##### Peripheral Control functions ##### + =============================================================================== + [..] This section provides functions allowing to: + (+) Get the 32 bit Random number + (+) Get the 32 bit Random number with interrupt enabled + (+) Handle RNG interrupt request + +@endverbatim + * @{ + */ + +/** + * @brief Generate a 32-bit random number. + * @note Each time the random number data is read the RNG_FLAG_DRDY flag + * is automatically cleared. + * @param hrng: pointer to a RNG_HandleTypeDef structure. + * @param random32bit: pointer to generated random number variable if successful. + * @retval HAL status + */ + +HAL_StatusTypeDef HAL_RNG_GenerateRandomNumber(RNG_HandleTypeDef *hrng, uint32_t *random32bit) +{ + uint32_t tickstart = 0; + HAL_StatusTypeDef status = HAL_OK; + + /* Process Locked */ + __HAL_LOCK(hrng); + + /* Check RNS peripheral state */ + if(hrng->State == HAL_RNG_STATE_READY) + { + /* Change RNG peripheral state */ + hrng->State = HAL_RNG_STATE_BUSY; + + /* Get tick */ + tickstart = HAL_GetTick(); + + /* Check if data register contains valid random data */ + while(__HAL_RNG_GET_FLAG(hrng, RNG_FLAG_DRDY) == RESET) + { + if((HAL_GetTick() - tickstart ) > RNG_TIMEOUT_VALUE) + { + hrng->State = HAL_RNG_STATE_ERROR; + + /* Process Unlocked */ + __HAL_UNLOCK(hrng); + + return HAL_TIMEOUT; + } + } + + /* Get a 32bit Random number */ + hrng->RandomNumber = hrng->Instance->DR; + *random32bit = hrng->RandomNumber; + + hrng->State = HAL_RNG_STATE_READY; + } + else + { + status = HAL_ERROR; + } + + /* Process Unlocked */ + __HAL_UNLOCK(hrng); + + return status; +} + +/** + * @brief Generate a 32-bit random number in interrupt mode. + * @param hrng: pointer to a RNG_HandleTypeDef structure. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_RNG_GenerateRandomNumber_IT(RNG_HandleTypeDef *hrng) +{ + HAL_StatusTypeDef status = HAL_OK; + + /* Process Locked */ + __HAL_LOCK(hrng); + + /* Check RNG peripheral state */ + if(hrng->State == HAL_RNG_STATE_READY) + { + /* Change RNG peripheral state */ + hrng->State = HAL_RNG_STATE_BUSY; + + /* Process Unlocked */ + __HAL_UNLOCK(hrng); + + /* Enable the RNG Interrupts: Data Ready, Clock error, Seed error */ + __HAL_RNG_ENABLE_IT(hrng); + } + else + { + /* Process Unlocked */ + __HAL_UNLOCK(hrng); + + status = HAL_ERROR; + } + + return status; +} + +/** + * @brief Handle RNG interrupt request. + * @note In the case of a clock error, the RNG is no more able to generate + * random numbers because the PLL48CLK clock is not correct. User has + * to check that the clock controller is correctly configured to provide + * the RNG clock and clear the CEIS bit using __HAL_RNG_CLEAR_IT(). + * The clock error has no impact on the previously generated + * random numbers, and the RNG_DR register contents can be used. + * @note In the case of a seed error, the generation of random numbers is + * interrupted as long as the SECS bit is '1'. If a number is + * available in the RNG_DR register, it must not be used because it may + * not have enough entropy. In this case, it is recommended to clear the + * SEIS bit using __HAL_RNG_CLEAR_IT(), then disable and enable + * the RNG peripheral to reinitialize and restart the RNG. + * @note User-written HAL_RNG_ErrorCallback() API is called once whether SEIS + * or CEIS are set. + * @param hrng: pointer to a RNG_HandleTypeDef structure. + * @retval None + + */ +void HAL_RNG_IRQHandler(RNG_HandleTypeDef *hrng) +{ + /* RNG clock error interrupt occurred */ + if((__HAL_RNG_GET_IT(hrng, RNG_IT_CEI) != RESET) || (__HAL_RNG_GET_IT(hrng, RNG_IT_SEI) != RESET)) + { + /* Change RNG peripheral state */ + hrng->State = HAL_RNG_STATE_ERROR; + + HAL_RNG_ErrorCallback(hrng); + + /* Clear the clock error flag */ + __HAL_RNG_CLEAR_IT(hrng, RNG_IT_CEI|RNG_IT_SEI); + + } + + /* Check RNG data ready interrupt occurred */ + if(__HAL_RNG_GET_IT(hrng, RNG_IT_DRDY) != RESET) + { + /* Generate random number once, so disable the IT */ + __HAL_RNG_DISABLE_IT(hrng); + + /* Get the 32bit Random number (DRDY flag automatically cleared) */ + hrng->RandomNumber = hrng->Instance->DR; + + if(hrng->State != HAL_RNG_STATE_ERROR) + { + /* Change RNG peripheral state */ + hrng->State = HAL_RNG_STATE_READY; + + /* Data Ready callback */ + HAL_RNG_ReadyDataCallback(hrng, hrng->RandomNumber); + } + } +} + +/** + * @brief Return generated random number in polling mode (Obsolete). + * @note Use HAL_RNG_GenerateRandomNumber() API instead. + * @param hrng: pointer to a RNG_HandleTypeDef structure that contains + * the configuration information for RNG. + * @retval random value + */ +uint32_t HAL_RNG_GetRandomNumber(RNG_HandleTypeDef *hrng) +{ + if(HAL_RNG_GenerateRandomNumber(hrng, &(hrng->RandomNumber)) == HAL_OK) + { + return hrng->RandomNumber; + } + else + { + return 0; + } +} + + +/** + * @brief Return a 32-bit random number with interrupt enabled (Obsolete). + * @note Use HAL_RNG_GenerateRandomNumber_IT() API instead. + * @param hrng: RNG handle + * @retval 32-bit random number + */ +uint32_t HAL_RNG_GetRandomNumber_IT(RNG_HandleTypeDef *hrng) +{ + uint32_t random32bit = 0; + + /* Process locked */ + __HAL_LOCK(hrng); + + /* Change RNG peripheral state */ + hrng->State = HAL_RNG_STATE_BUSY; + + /* Get a 32bit Random number */ + random32bit = hrng->Instance->DR; + + /* Enable the RNG Interrupts: Data Ready, Clock error, Seed error */ + __HAL_RNG_ENABLE_IT(hrng); + + /* Return the 32 bit random number */ + return random32bit; +} + + + +/** + * @brief Read latest generated random number. + * @param hrng: pointer to a RNG_HandleTypeDef structure. + * @retval random value + */ +uint32_t HAL_RNG_ReadLastRandomNumber(RNG_HandleTypeDef *hrng) +{ + return(hrng->RandomNumber); +} + +/** + * @brief Data Ready callback in non-blocking mode. + * @param hrng: pointer to a RNG_HandleTypeDef structure. + * @param random32bit: generated random value + * @retval None + */ +__weak void HAL_RNG_ReadyDataCallback(RNG_HandleTypeDef *hrng, uint32_t random32bit) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hrng); + UNUSED(random32bit); + + /* NOTE : This function should not be modified. When the callback is needed, + function HAL_RNG_ReadyDataCallback must be implemented in the user file. + */ +} + +/** + * @brief RNG error callback. + * @param hrng: pointer to a RNG_HandleTypeDef structure. + * @retval None + */ +__weak void HAL_RNG_ErrorCallback(RNG_HandleTypeDef *hrng) +{ + /* Prevent unused argument(s) compilation warning */ + UNUSED(hrng); + + /* NOTE : This function should not be modified. When the callback is needed, + function HAL_RNG_ErrorCallback must be implemented in the user file. + */ +} + +/** + * @} + */ + +/** @addtogroup RNG_Exported_Functions_Group3 + * @brief Peripheral State functions. + * +@verbatim + =============================================================================== + ##### Peripheral State functions ##### + =============================================================================== + [..] + This subsection permits to get in run-time the status of the peripheral. + +@endverbatim + * @{ + */ + +/** + * @brief Return the RNG handle state. + * @param hrng: pointer to a RNG_HandleTypeDef structure. + * @retval HAL state + */ +HAL_RNG_StateTypeDef HAL_RNG_GetState(RNG_HandleTypeDef *hrng) +{ + /* Return RNG handle state */ + return hrng->State; +} + +/** + * @} + */ + +/** + * @} + */ + + +#endif /* HAL_RNG_MODULE_ENABLED */ +/** + * @} + */ + +/** + * @} + */ + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/pool/shard004/C/0099787_usbd_midi_if.c b/pool/shard004/C/0099787_usbd_midi_if.c new file mode 100644 index 0000000000000000000000000000000000000000..beabc15d3656bfc5cd1b4374e7a154de1f0afc15 --- /dev/null +++ b/pool/shard004/C/0099787_usbd_midi_if.c @@ -0,0 +1,50 @@ +#include "usbd_midi_if.h" +#include "stm32746g_discovery.h" +#include "stm32746g_discovery_lcd.h" + +static int8_t Midi_Receive(uint8_t *msg, uint32_t len); + +extern USBD_HandleTypeDef USBD_Device; +USBD_Midi_ItfTypeDef USBD_Midi_fops = { + Midi_Receive, +}; + +static int8_t Midi_Receive(uint8_t *msg, uint32_t len) { + + uint8_t chan = msg[1] & 0xf; + uint8_t msgtype = msg[1] & 0xf0; + uint8_t b1 = msg[2]; + uint8_t b2 = msg[3]; + uint16_t b = ((b2 & 0x7f) << 7) | (b1 & 0x7f); + + BSP_LED_Toggle(LED_GREEN); + + char a[] = ""; + sprintf(a, "%d", b1); + BSP_LCD_DisplayStringAt(10, 50, (uint8_t *)a, LEFT_MODE); + + // switch (msgtype) { +// case 0x80: +// fluid_synth_noteoff(synth, chan, b1); +// break; +// case 0x90: +// fluid_synth_noteon(synth, chan, b1, b2); +// break; +// case 0xB0: +// fluid_synth_cc(synth, chan, b1, b2); +// break; +// case 0xC0: +// fluid_synth_program_change(synth, chan, b1); +// break; +// case 0xD0: +// fluid_synth_channel_pressure(synth, chan, b1); +// break; +// case 0xE0: +// fluid_synth_pitch_bend(synth, chan, b); +// break; +// default: +// break; +// } + + return 0; +} \ No newline at end of file diff --git a/pool/shard004/C/0099792_SDP_Error.c b/pool/shard004/C/0099792_SDP_Error.c new file mode 100644 index 0000000000000000000000000000000000000000..344089637daf14380c03a8347593689f68560968 --- /dev/null +++ b/pool/shard004/C/0099792_SDP_Error.c @@ -0,0 +1,226 @@ +/******************************************************************************* + * + * Copyright 2004 by William G. Davis. + * + * This library is free software released under the terms of the GNU Lesser + * General Public License (LGPL), the full terms of which can be found in the + * "COPYING" file that comes with the distribution. + * + * This library is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. + * + ******************************************************************************/ + +#include +#include +#include +#include "SDP_Error.h" +#include "SDP_Utility.h" + +/* + * The size of the global string used to store a description of the last error + * to occur: + */ +#define ERROR_STRING_SIZE 512 + + + + + + + +/* The error code of the last error to occur: */ +static SDP_Error _last_error = SDP_NO_ERROR; + +/* The string containing the error message of the last error to occur: */ +static char _last_error_string[ERROR_STRING_SIZE]; + + + +/* + * If this symbol is defined, then these two default error handlers will be + * registered: + */ +#ifdef SINISTERSDP_REGISTER_DEFAULT_ERROR_HANDLERS + +/* Default error handlers: */ +static void _DefaultFatalErrorHandler( + SDP_Error error_code, + const char * error_string +); +static int _DefaultNonFatalErrorHandler( + SDP_Error error_code, + const char * error_string +); + +/* The callback for fatal, non-recoverable errors: */ +static SDP_FatalErrorHandler _fatal_error_handler = + _DefaultFatalErrorHandler; + +/* The callback for non-fatal, recoverable errors: */ +static SDP_NonFatalErrorHandler _non_fatal_error_handler = + _DefaultNonFatalErrorHandler; + +#else + +static SDP_FatalErrorHandler _fatal_error_handler = NULL; +static SDP_NonFatalErrorHandler _non_fatal_error_handler = NULL; + +#endif + + + +/* + * If some function raises an error, should either of the appropriate error + * handlers above be invoked? + */ +static int _use_error_handlers = 1; + + + + + +int SDP_ErrorRaised(void) +{ + return _last_error ? 1 : 0; +} + + + + + +SDP_Error SDP_GetLastError(void) +{ + return _last_error; +} + + + + + +const char *SDP_GetLastErrorString(void) +{ + return _last_error_string; +} + + + + + +void SDP_SetFatalErrorHandler(SDP_FatalErrorHandler handler) +{ + _fatal_error_handler = handler; +} + + + + + +void SDP_SetNonFatalErrorHandler(SDP_NonFatalErrorHandler handler) +{ + _non_fatal_error_handler = handler; +} + + + + + +void SDP_UseHandlersForErrors(int use_handlers) +{ + _use_error_handlers = use_handlers ? 1 : 0; +} + + + + + +void SDP_RaiseFatalError( + SDP_Error code, + const char * format, + ...) +{ + va_list args; + + SDP_AssertTrue(code); + SDP_AssertNotNull(format); + + _last_error = code; + + va_start(args, format); + vsnprintf( + _last_error_string, sizeof(_last_error_string), format, args + ); + va_end(args); + + if (_use_error_handlers && _fatal_error_handler) + (*_fatal_error_handler)(_last_error, _last_error_string); +} + + + + + +int SDP_RaiseNonFatalError( + SDP_Error code, + const char * format, + ...) +{ + va_list args; + + SDP_AssertTrue(code); + SDP_AssertNotNull(format); + + _last_error = code; + + va_start(args, format); + vsnprintf( + _last_error_string, sizeof(_last_error_string), format, args + ); + va_end(args); + + /* + * We use the handler's return value as a flag to tell us whether or + * not we should keep going even after encountering an error. + * + * If there's no registered handler, then just stop: + */ + if (_use_error_handlers && _non_fatal_error_handler) + return (*_non_fatal_error_handler)( + _last_error, _last_error_string + ); + else + return SDP_STOP_AFTER_ERROR; +} + + + + + +#ifdef SINISTERSDP_REGISTER_DEFAULT_ERROR_HANDLERS + +static void _DefaultFatalErrorHandler( + SDP_Error error_code, + const char * error_string) +{ + fprintf(stderr, "Fatal error: %s\n", error_string); + + /* Exit the entire process: */ + exit(EXIT_FAILURE); +} + + + + + +static int _DefaultNonFatalErrorHandler( + SDP_Error error_code, + const char * error_string) +{ + fprintf(stderr, "Error: %s\n", error_string); + + /* Force the caller to exit prematurely: */ + return SDP_STOP_AFTER_ERROR; +} + +#endif diff --git a/pool/shard004/C/0099795_StringDictionary.c b/pool/shard004/C/0099795_StringDictionary.c new file mode 100644 index 0000000000000000000000000000000000000000..bf5760f3fb3d9d5484a908b6bf808f69aba55d87 --- /dev/null +++ b/pool/shard004/C/0099795_StringDictionary.c @@ -0,0 +1,159 @@ +/* + Copyright (c) 1996 Blake McBride + 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. +*/ + + + +/* This file automatically generated by dpp - do not edit */ + +#define DPP_STRATEGY 2 +#define DPP_FASTWIDE 0 + + + + +#define CLASS StringDictionary_c +#define ivType StringDictionary_iv_t + +#include "generics.h" + +object StringDictionary_c; + + +#line 37 "StringDictionary.d" +#include "set1.h" + +#define LTYPE 2 + +static gLookup_t Lookup; + +imeth objrtn StringDictionary_im_gAddStr(object self, char *key, object value) +{ + ChkArgNul(value, 3); + return Lookup(self, (object) key, HT_ADD, 0, LTYPE, value); +} + +imeth objrtn StringDictionary_im_gFindValueStr(object self, char *key) +{ + object x = Lookup(self, (object) key, HT_FIND, 0, LTYPE, NULL); + return x ? gValue(x) : x; +} + +imeth objrtn StringDictionary_im_gFindStr(object self, char *key) +{ + return Lookup(self, (object) key, HT_FIND, 0, LTYPE, NULL); +} + +imeth objrtn StringDictionary_im_gChangeValueWithStr(object self, char *key, object val) +{ + object x; + ChkArgNul(val, 3); + x = Lookup(self, (object) key, HT_FIND, 0, LTYPE, NULL); + return x ? gChangeValue(x, val) : x; +} + +imeth objrtn StringDictionary_im_gFindAddStr(object self, char *key, object value) +{ + ChkArgNul(value, 3); + return Lookup(self, (object) key, HT_FINDADD, 0, LTYPE, value); +} + +imeth objrtn StringDictionary_im_gDispose(object self) +{ + return gDispose1(self); +} + +imeth objrtn StringDictionary_im_gDisposeAllNodes(object self) +{ + return gDisposeAllNodes1(self); +} + +imeth objrtn StringDictionary_im_gRemoveStr(object self, char *key) +{ + return Lookup(self, (object) key, HT_DELETE, 1, LTYPE, NULL); +} + +imeth objrtn StringDictionary_im_gDeepDisposeStr(object self, char *key) +{ + return Lookup(self, (object) key, HT_DELETE, 2, LTYPE, NULL); +} + +static void init_class(void) +{ + Lookup = imcPointer(Set, gLookup); +} + +#line 111 "StringDictionary.c" + +objrtn StringDictionary_initialize(void) +{ + static CRITICALSECTION cs; + static int volatile once = 0; + + ENTERCRITICALSECTION(_CI_CS_); + if (!once) { + INITIALIZECRITICALSECTION(cs); + once = 1; + } + LEAVECRITICALSECTION(_CI_CS_); + + ENTERCRITICALSECTION(cs); + + if (StringDictionary_c) { + LEAVECRITICALSECTION(cs); + return StringDictionary_c; + } + INHIBIT_THREADER; + Set_initialize(); + if (StringDictionary_c) { + ENABLE_THREADER; + LEAVECRITICALSECTION(cs); + return StringDictionary_c; + } + StringDictionary_c = gNewClass(Class, "StringDictionary", 0, 0, Set, END); + iMethodFor(StringDictionary, gRemoveStr, StringDictionary_im_gRemoveStr); + iMethodFor(StringDictionary, gDisposeStr, StringDictionary_im_gDeepDisposeStr); + iMethodFor(StringDictionary, gFindStr, StringDictionary_im_gFindStr); + iMethodFor(StringDictionary, gAddStr, StringDictionary_im_gAddStr); + iMethodFor(StringDictionary, gDisposeAllNodes, StringDictionary_im_gDisposeAllNodes); + iMethodFor(StringDictionary, gDispose, StringDictionary_im_gDispose); + iMethodFor(StringDictionary, gFindAddStr, StringDictionary_im_gFindAddStr); + iMethodFor(StringDictionary, gChangeValueWithStr, StringDictionary_im_gChangeValueWithStr); + iMethodFor(StringDictionary, gFindValueStr, StringDictionary_im_gFindValueStr); + iMethodFor(StringDictionary, gDeepDisposeStr, StringDictionary_im_gDeepDisposeStr); + + init_class(); + + ENABLE_THREADER; + + LEAVECRITICALSECTION(cs); + + return StringDictionary_c; +} + + + diff --git a/pool/shard004/C/0099797_m_challenge.c b/pool/shard004/C/0099797_m_challenge.c new file mode 100644 index 0000000000000000000000000000000000000000..c030594654cfb24c29b6467958e5d2226029d7f2 --- /dev/null +++ b/pool/shard004/C/0099797_m_challenge.c @@ -0,0 +1,242 @@ +/* + * ircd-hybrid: an advanced, lightweight Internet Relay Chat Daemon (ircd) + * + * Copyright (c) 2000-2015 ircd-hybrid development 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 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 m_challenge.c + * \brief Includes required functions for processing the CHALLENGE command. + * \version $Id: m_challenge.c 5346 2015-01-11 12:41:14Z michael $ + */ + +#include "stdinc.h" +#include "client.h" +#include "ircd.h" +#include "modules.h" +#include "numeric.h" +#include "send.h" +#include "conf.h" +#include "rsa.h" +#include "parse.h" +#include "irc_string.h" +#include "log.h" +#include "user.h" +#include "memory.h" + + +#ifdef HAVE_LIBCRYPTO +/*! \brief Notices all opers of the failed challenge attempt if enabled + * + * \param source_p Client doing /challenge ... + * \param name The nick they tried to oper as + * \param reason The reason why they have failed + */ +static void +failed_challenge_notice(struct Client *source_p, const char *name, + const char *reason) +{ + if (ConfigGeneral.failed_oper_notice) + sendto_realops_flags(UMODE_ALL, L_ALL, SEND_NOTICE, + "Failed CHALLENGE attempt as %s " + "by %s (%s@%s) - %s", name, source_p->name, + source_p->username, source_p->host, reason); + + ilog(LOG_TYPE_OPER, "Failed CHALLENGE attempt as %s " + "by %s (%s@%s) - %s", name, source_p->name, + source_p->username, source_p->host, reason); +} + +/*! \brief CHALLENGE command handler + * + * \param source_p Pointer to allocated Client struct from which the message + * originally comes from. This can be a local or remote client. + * \param parc Integer holding the number of supplied arguments. + * \param parv Argument vector where parv[0] .. parv[parc-1] are non-NULL + * pointers. + * \note Valid arguments for this command are: + * - parv[0] = command + * - parv[1] = operator to challenge for, or +response + */ +static int +m_challenge(struct Client *source_p, int parc, char *parv[]) +{ + char *challenge = NULL; + struct MaskItem *conf = NULL; + + if (EmptyString(parv[1])) + { + sendto_one_numeric(source_p, &me, ERR_NEEDMOREPARAMS, "CHALLENGE"); + return 0; + } + + if (*parv[1] == '+') + { + /* Ignore it if we aren't expecting this... -A1kmm */ + if (source_p->connection->challenge_response == NULL) + return 0; + + if (irccmp(source_p->connection->challenge_response, ++parv[1])) + { + sendto_one_numeric(source_p, &me, ERR_PASSWDMISMATCH); + failed_challenge_notice(source_p, source_p->connection->challenge_operator, + "challenge failed"); + return 0; + } + + conf = find_exact_name_conf(CONF_OPER, source_p, + source_p->connection->challenge_operator, NULL, NULL); + if (conf == NULL) + { + sendto_one_numeric(source_p, &me, ERR_NOOPERHOST); + conf = find_exact_name_conf(CONF_OPER, NULL, source_p->connection->challenge_operator, NULL, NULL); + failed_challenge_notice(source_p, source_p->connection->challenge_operator, (conf != NULL) ? + "host mismatch" : "no operator {} block"); + return 0; + } + + if (attach_conf(source_p, conf)) + { + sendto_one_notice(source_p, &me, ":Can't attach conf!"); + failed_challenge_notice(source_p, conf->name, "can't attach conf!"); + return 0; + } + + oper_up(source_p); + + ilog(LOG_TYPE_OPER, "CHALLENGE %s by %s!%s@%s", + source_p->connection->challenge_operator, + source_p->name, source_p->username, + source_p->host); + + MyFree(source_p->connection->challenge_response); + MyFree(source_p->connection->challenge_operator); + source_p->connection->challenge_response = NULL; + source_p->connection->challenge_operator = NULL; + return 0; + } + + MyFree(source_p->connection->challenge_response); + MyFree(source_p->connection->challenge_operator); + source_p->connection->challenge_response = NULL; + source_p->connection->challenge_operator = NULL; + + conf = find_exact_name_conf(CONF_OPER, source_p, parv[1], NULL, NULL); + + if (!conf) + { + sendto_one_numeric(source_p, &me, ERR_NOOPERHOST); + conf = find_exact_name_conf(CONF_OPER, NULL, parv[1], NULL, NULL); + failed_challenge_notice(source_p, parv[1], (conf != NULL) + ? "host mismatch" : "no operator {} block"); + return 0; + } + + if (conf->rsa_public_key == NULL) + { + sendto_one_notice(source_p, &me, ":I'm sorry, PK authentication " + "is not enabled for your operator {} block."); + return 0; + } + + if (IsConfSSL(conf) && !HasUMode(source_p, UMODE_SSL)) + { + sendto_one_numeric(source_p, &me, ERR_NOOPERHOST); + failed_challenge_notice(source_p, conf->name, "requires SSL/TLS"); + return 0; + } + + if (!EmptyString(conf->certfp)) + { + if (EmptyString(source_p->certfp) || strcasecmp(source_p->certfp, conf->certfp)) + { + sendto_one_numeric(source_p, &me, ERR_NOOPERHOST); + failed_challenge_notice(source_p, conf->name, "client certificate fingerprint mismatch"); + return 0; + } + } + + if (!generate_challenge(&challenge, &source_p->connection->challenge_response, + conf->rsa_public_key)) + { + sendto_one_numeric(source_p, &me, RPL_RSACHALLENGE, challenge); + source_p->connection->challenge_operator = xstrdup(conf->name); + } + + MyFree(challenge); + return 0; +} + +/*! \brief CHALLENGE command handler + * + * \param source_p Pointer to allocated Client struct from which the message + * originally comes from. This can be a local or remote client. + * \param parc Integer holding the number of supplied arguments. + * \param parv Argument vector where parv[0] .. parv[parc-1] are non-NULL + * pointers. + * \note Valid arguments for this command are: + * - parv[0] = command + * - parv[1] = operator to challenge for, or +response + */ +static int +mo_challenge(struct Client *source_p, int parc, char *parv[]) +{ + sendto_one_numeric(source_p, &me, RPL_YOUREOPER); + return 0; +} + +static struct Message challenge_msgtab = +{ + "CHALLENGE", NULL, 0, 0, 2, MAXPARA, MFLG_SLOW, 0, + { m_unregistered, m_challenge, m_ignore, m_ignore, mo_challenge, m_ignore } +}; + +static void +module_init(void) +{ + mod_add_cmd(&challenge_msgtab); +} + +static void +module_exit(void) +{ + mod_del_cmd(&challenge_msgtab); +} + +#else + +static void +module_init(void) +{ +} + +static void +module_exit(void) +{ +} +#endif + +struct module module_entry = +{ + .node = { NULL, NULL, NULL }, + .name = NULL, + .version = "$Revision: 5346 $", + .handle = NULL, + .modinit = module_init, + .modexit = module_exit, + .flags = 0 +}; diff --git a/pool/shard004/C/0099806_experimental.c b/pool/shard004/C/0099806_experimental.c new file mode 100644 index 0000000000000000000000000000000000000000..052eb0b6df68296d2c5a66d8d6dbff5781fc619c --- /dev/null +++ b/pool/shard004/C/0099806_experimental.c @@ -0,0 +1,37 @@ +/* +** 2005 January 20 +** +** 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 C code routines that are not a part of the official +** SQLite API. These routines are unsupported. +** +** $Id: experimental.c,v 1.4 2006/01/31 20:49:13 drh Exp $ +*/ +#include "sqliteInt.h" +#include "os.h" + +/* +** Set all the parameters in the compiled SQL statement to NULL. +*/ +int sqlite3_clear_bindings(sqlite3_stmt *pStmt){ + int i; + int rc = SQLITE_OK; + for(i=1; rc==SQLITE_OK && i<=sqlite3_bind_parameter_count(pStmt); i++){ + rc = sqlite3_bind_null(pStmt, i); + } + return rc; +} + +/* +** Sleep for a little while. Return the amount of time slept. +*/ +int sqlite3_sleep(int ms){ + return sqlite3OsSleep(ms); +} diff --git a/pool/shard004/C/0099808_main.c b/pool/shard004/C/0099808_main.c new file mode 100644 index 0000000000000000000000000000000000000000..0e1cc44d4433056a81cfa5dedd1212910483a141 --- /dev/null +++ b/pool/shard004/C/0099808_main.c @@ -0,0 +1,212 @@ +/* + * Copyright (C) Sistina Software, Inc. 1997-2003 All rights reserved. + * Copyright (C) 2004-2006 Red Hat, Inc. All rights reserved. + * + * This copyrighted material is made available to anyone wishing to use, + * modify, copy, or redistribute it subject to the terms and conditions + * of the GNU General Public License version 2. + */ + +#include +#include +#include +#include +#include +#include +#include +#include + +#include "gfs2.h" +#include "incore.h" +#include "super.h" +#include "sys.h" +#include "util.h" +#include "glock.h" +#include "quota.h" +#include "recovery.h" + +static struct shrinker qd_shrinker = { + .shrink = gfs2_shrink_qd_memory, + .seeks = DEFAULT_SEEKS, +}; + +static void gfs2_init_inode_once(void *foo) +{ + struct gfs2_inode *ip = foo; + + inode_init_once(&ip->i_inode); + init_rwsem(&ip->i_rw_mutex); + INIT_LIST_HEAD(&ip->i_trunc_list); + ip->i_alloc = NULL; +} + +static void gfs2_init_glock_once(void *foo) +{ + struct gfs2_glock *gl = foo; + + INIT_HLIST_NODE(&gl->gl_list); + spin_lock_init(&gl->gl_spin); + INIT_LIST_HEAD(&gl->gl_holders); + INIT_LIST_HEAD(&gl->gl_lru); + INIT_LIST_HEAD(&gl->gl_ail_list); + atomic_set(&gl->gl_ail_count, 0); +} + +static void gfs2_init_gl_aspace_once(void *foo) +{ + struct gfs2_glock *gl = foo; + struct address_space *mapping = (struct address_space *)(gl + 1); + + gfs2_init_glock_once(gl); + memset(mapping, 0, sizeof(*mapping)); + INIT_RADIX_TREE(&mapping->page_tree, GFP_ATOMIC); + spin_lock_init(&mapping->tree_lock); + spin_lock_init(&mapping->i_mmap_lock); + INIT_LIST_HEAD(&mapping->private_list); + spin_lock_init(&mapping->private_lock); + INIT_RAW_PRIO_TREE_ROOT(&mapping->i_mmap); + INIT_LIST_HEAD(&mapping->i_mmap_nonlinear); +} + +/** + * init_gfs2_fs - Register GFS2 as a filesystem + * + * Returns: 0 on success, error code on failure + */ + +static int __init init_gfs2_fs(void) +{ + int error; + + error = gfs2_sys_init(); + if (error) + return error; + + error = gfs2_glock_init(); + if (error) + goto fail; + + error = -ENOMEM; + gfs2_glock_cachep = kmem_cache_create("gfs2_glock", + sizeof(struct gfs2_glock), + 0, 0, + gfs2_init_glock_once); + if (!gfs2_glock_cachep) + goto fail; + + gfs2_glock_aspace_cachep = kmem_cache_create("gfs2_glock(aspace)", + sizeof(struct gfs2_glock) + + sizeof(struct address_space), + 0, 0, gfs2_init_gl_aspace_once); + + if (!gfs2_glock_aspace_cachep) + goto fail; + + gfs2_inode_cachep = kmem_cache_create("gfs2_inode", + sizeof(struct gfs2_inode), + 0, SLAB_RECLAIM_ACCOUNT| + SLAB_MEM_SPREAD, + gfs2_init_inode_once); + if (!gfs2_inode_cachep) + goto fail; + + gfs2_bufdata_cachep = kmem_cache_create("gfs2_bufdata", + sizeof(struct gfs2_bufdata), + 0, 0, NULL); + if (!gfs2_bufdata_cachep) + goto fail; + + gfs2_rgrpd_cachep = kmem_cache_create("gfs2_rgrpd", + sizeof(struct gfs2_rgrpd), + 0, 0, NULL); + if (!gfs2_rgrpd_cachep) + goto fail; + + gfs2_quotad_cachep = kmem_cache_create("gfs2_quotad", + sizeof(struct gfs2_quota_data), + 0, 0, NULL); + if (!gfs2_quotad_cachep) + goto fail; + + register_shrinker(&qd_shrinker); + + error = register_filesystem(&gfs2_fs_type); + if (error) + goto fail; + + error = register_filesystem(&gfs2meta_fs_type); + if (error) + goto fail_unregister; + + error = -ENOMEM; + gfs_recovery_wq = alloc_workqueue("gfs_recovery", + WQ_NON_REENTRANT | WQ_RESCUER, 0); + if (!gfs_recovery_wq) + goto fail_wq; + + gfs2_register_debugfs(); + + printk("GFS2 (built %s %s) installed\n", __DATE__, __TIME__); + + return 0; + +fail_wq: + unregister_filesystem(&gfs2meta_fs_type); +fail_unregister: + unregister_filesystem(&gfs2_fs_type); +fail: + unregister_shrinker(&qd_shrinker); + gfs2_glock_exit(); + + if (gfs2_quotad_cachep) + kmem_cache_destroy(gfs2_quotad_cachep); + + if (gfs2_rgrpd_cachep) + kmem_cache_destroy(gfs2_rgrpd_cachep); + + if (gfs2_bufdata_cachep) + kmem_cache_destroy(gfs2_bufdata_cachep); + + if (gfs2_inode_cachep) + kmem_cache_destroy(gfs2_inode_cachep); + + if (gfs2_glock_aspace_cachep) + kmem_cache_destroy(gfs2_glock_aspace_cachep); + + if (gfs2_glock_cachep) + kmem_cache_destroy(gfs2_glock_cachep); + + gfs2_sys_uninit(); + return error; +} + +/** + * exit_gfs2_fs - Unregister the file system + * + */ + +static void __exit exit_gfs2_fs(void) +{ + unregister_shrinker(&qd_shrinker); + gfs2_glock_exit(); + gfs2_unregister_debugfs(); + unregister_filesystem(&gfs2_fs_type); + unregister_filesystem(&gfs2meta_fs_type); + destroy_workqueue(gfs_recovery_wq); + + kmem_cache_destroy(gfs2_quotad_cachep); + kmem_cache_destroy(gfs2_rgrpd_cachep); + kmem_cache_destroy(gfs2_bufdata_cachep); + kmem_cache_destroy(gfs2_inode_cachep); + kmem_cache_destroy(gfs2_glock_aspace_cachep); + kmem_cache_destroy(gfs2_glock_cachep); + + gfs2_sys_uninit(); +} + +MODULE_DESCRIPTION("Global File System"); +MODULE_AUTHOR("Red Hat, Inc."); +MODULE_LICENSE("GPL"); + +module_init(init_gfs2_fs); +module_exit(exit_gfs2_fs); diff --git a/pool/shard004/C/0099821_cpu.c b/pool/shard004/C/0099821_cpu.c new file mode 100644 index 0000000000000000000000000000000000000000..364963a0a34486ec92975888442650da491a7d9b --- /dev/null +++ b/pool/shard004/C/0099821_cpu.c @@ -0,0 +1,50 @@ +/* linux/arch/arm/plat-samsung/cpu.c + * + * Copyright (c) 2009-2011 Samsung Electronics Co., Ltd. + * http://www.samsung.com + * + * Samsung CPU Support + * + * 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 + +unsigned long samsung_cpu_id; +static unsigned int samsung_cpu_rev; + +unsigned int samsung_rev(void) +{ + return samsung_cpu_rev; +} +EXPORT_SYMBOL(samsung_rev); + +void __init s3c64xx_init_cpu(void) +{ + samsung_cpu_id = __raw_readl(S3C_VA_SYS + 0x118); + if (!samsung_cpu_id) { + /* + * S3C6400 has the ID register in a different place, + * and needs a write before it can be read. + */ + __raw_writel(0x0, S3C_VA_SYS + 0xA1C); + samsung_cpu_id = __raw_readl(S3C_VA_SYS + 0xA1C); + } + + samsung_cpu_rev = 0; +} + +void __init s5p_init_cpu(void __iomem *cpuid_addr) +{ + samsung_cpu_id = __raw_readl(cpuid_addr); + samsung_cpu_rev = samsung_cpu_id & 0xFF; +} diff --git a/pool/shard004/C/0099830_dnsmq.c b/pool/shard004/C/0099830_dnsmq.c new file mode 100644 index 0000000000000000000000000000000000000000..de750f1089a9e53e837c09d5ef453eb476cf8768 --- /dev/null +++ b/pool/shard004/C/0099830_dnsmq.c @@ -0,0 +1,264 @@ +/* + * Packet matching code. + * + * Copyright (C) 1999 Paul `Rusty' Russell & Michael J. Neuling + * Copyright (C) 2009-2002 Netfilter core team + * + * 19 Jan 2002 Harald Welte + * - increase module usage count as soon as we have rules inside + * a table + */ +//#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#define DEBUGP(format, args...) + +unsigned int dnsmq_ip=0; +char dnsmq_name[32]; +unsigned char dnsmq_mac[ETH_ALEN] = { 0x00, 0xe0, 0x11, 0x22, 0x33, 0x44 }; +typedef int (*dnsmqHitHook)(struct sk_buff *skb); +dnsmqHitHook dnsmq_hit_hook = NULL; + +static inline void dnsmq_hit_hook_func(dnsmqHitHook hook_func) +{ + dnsmq_hit_hook = hook_func; +} + +void dump_packet(struct sk_buff *skb, char *title) +{ + int i; + + if(nvram_match("dnsmq_debug", "1")) { + printk("dump packet[%s] %x %x %x", title, skb->len, skb->mac_len, skb->data_len); + if(skb->dev) printk("%s\n", skb->dev->name); + else printk("\n"); + + if(skb && skb->data) { + for(i=0;ilen&&i<120;i++) { + if(i%16==0) printk("\n"); + printk("%x ", skb->data[i]); + } + } + printk("\n\n\n"); + } +} + +EXPORT_SYMBOL(dump_packet); + +#define MAXDNSNAME 256 +#pragma pack(1) // let struct be neat by byte + +typedef struct Flags_Pack { + uint16_t reply_1:4, + non_auth_ok:1, + answer_auth:1, + reserved:1, + recur_avail:1, + recur_desired:1, + truncated:1, + authori:1, + opcode:4, + response:1; +} flag_pack; + +typedef struct DNS_HEADER { + uint16_t tid; + union { + uint16_t flag_num; + flag_pack flags; + } flag_set; + uint16_t questions; + uint16_t answer_rrs; + uint16_t auth_rrs; + uint16_t additional_rss; +} dns_header; + +typedef struct DNS_QUERIES { + char name[MAXDNSNAME]; + uint16_t type; + uint16_t ip_class; +} dns_queries; + +typedef struct DNS_REQUEST { + dns_header header; + dns_queries queries; +} dns_query_packet; + +static inline int dnschar_cmp(char a, char b) +{ + char a1; + + if(a==b) return 0; + + if(a>='a'&&a<='z') a1 = 'A' + a - 'a'; + else if(a>='A'&&a<='Z') a1 = 'a' + a - 'A'; + else return 1; + + if(a1==b) return 0; + + return 1; +} + +static inline int dnsmq_hit(struct udphdr *udph) +{ + dns_query_packet *dns_query; + int i, j; + + dns_query = (dns_query_packet *)((unsigned char *)udph + sizeof(struct udphdr)); + + j = 0; + //printk("dns hit\n"); + for(i=0;dns_query->queries.name[i]!=0;i++) { + //printk("%x %x %x\n", i, dns_query->queries.name[i], dnsmq_name[i]); + if(dnschar_cmp(dns_query->queries.name[i],dnsmq_name[j])) return 0; + j++; + } + return 1; +} + +static inline int dnsmq_func(struct sk_buff *skb) +{ + struct ethhdr *ethh; + struct vlan_ethhdr *vethh; + struct iphdr *iph; + struct udphdr *udph; + struct tcphdr *tcph; + u32 hlen; + u16 proto; + + if(dnsmq_ip==0) return 0; + + if(!skb || !skb->data) return 0; + + ethh = (struct ethhdr *)skb->data; + + proto = ntohs(ethh->h_proto); + + if(proto == ETH_P_IP) hlen = ETH_HLEN; + else if (proto == ETH_P_8021Q) { + vethh = (struct vlan_ethhdr *)skb->data; + if(vethh->h_vlan_encapsulated_proto == htons(ETH_P_IP)) + hlen = VLAN_ETH_HLEN; + else return 0; + } + else return 0; + + iph = (struct iphdr *)(skb->data+hlen); + + // IP & DNS & Looking for my host name + if(iph->protocol==IPPROTO_UDP) { + udph = (struct udphdr *)(skb->data+hlen+(iph->ihl<<2)); + if(ntohs(udph->dest)==53) { + if(dnsmq_hit(udph)) { + memcpy(ethh->h_dest, dnsmq_mac, ETH_ALEN); + //dump_packet(skb, "dnshit"); + return 1; + } + } + } + // IP & HTTP & Original Locol IP & Looking for my host name + else if(iph->protocol==IPPROTO_TCP) { + tcph = (struct tcphdr *)(skb->data+hlen+(iph->ihl<<2)); + if(iph->daddr==dnsmq_ip && ntohs(tcph->dest)==80) { + memcpy(ethh->h_dest, dnsmq_mac, ETH_ALEN); + //dump_packet(skb, "httphit"); + return 1; + } + } + return 0; +} + +static int dnsmq_ctrl(struct file *file, const char *buffer, unsigned long length, void *data) +{ + char s[32]; + char str[32]; + char *ptr; + int i, j; + + // "[dnsmq ip] [dnsmq name] + if ((length > 0) && (length < 32)) { + memcpy(s, buffer, length); + s[length] = 0; + for(i=0;iowner = THIS_MODULE; + p->write_proc = dnsmq_ctrl; + } +#endif + // it will be enabled later + dnsmq_hit_hook_func (NULL); + return 0; +} + +static void __exit fini(void) +{ + dnsmq_hit_hook_func (NULL); +} + +EXPORT_SYMBOL(dnsmq_hit_hook); + +module_init(init); +module_exit(fini); +MODULE_LICENSE("Proprietary"); + diff --git a/pool/shard004/C/0099837_ksm03.c b/pool/shard004/C/0099837_ksm03.c new file mode 100644 index 0000000000000000000000000000000000000000..d94d3489f4935d2159eae07ad2ad7093cab20355 --- /dev/null +++ b/pool/shard004/C/0099837_ksm03.c @@ -0,0 +1,133 @@ +/* + * Kernel Samepage Merging (KSM) for Memory Resource Controller + * + * Basic tests were to start several programs with same and different + * memory contents and ensure only to merge the ones with the same + * contents. When changed the content of one of merged pages in a + * process and to the mode "unmerging", it should discard all merged + * pages there. Also tested it is possible to disable KSM. There are + * also command-line options to specify the memory allocation size, and + * number of processes have same memory contents so it is possible to + * test more advanced things like KSM + OOM etc. + * + * Prerequisites: + * + * 1) ksm and ksmtuned daemons need to be disabled. Otherwise, it could + * distrub the testing as they also change some ksm tunables depends + * on current workloads. + * + * The test steps are: + * - Check ksm feature and backup current run setting. + * - Change run setting to 1 - merging. + * - 3 memory allocation programs have the memory contents that 2 of + * them are all 'a' and one is all 'b'. + * - Check ksm statistics and verify the content. + * - 1 program changes the memory content from all 'a' to all 'b'. + * - Check ksm statistics and verify the content. + * - All programs change the memory content to all 'd'. + * - Check ksm statistics and verify the content. + * - Change one page of a process. + * - Check ksm statistics and verify the content. + * - Change run setting to 2 - unmerging. + * - Check ksm statistics and verify the content. + * - Change run setting to 0 - stop. + * + * Copyright (C) 2010 Red Hat, 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. + * + * 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 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. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "test.h" +#include "usctest.h" +#include "mem.h" + +char *TCID = "ksm03"; +int TST_TOTAL = 1; + +static int merge_across_nodes; + +option_t ksm_options[] = { + {"n:", &opt_num, &opt_numstr}, + {"s:", &opt_size, &opt_sizestr}, + {"u:", &opt_unit, &opt_unitstr}, + {NULL, NULL, NULL} +}; + +int main(int argc, char *argv[]) +{ + int lc; + const char *msg; + int size = 128, num = 3, unit = 1; + + msg = parse_opts(argc, argv, ksm_options, ksm_usage); + if (msg != NULL) + tst_brkm(TBROK, tst_exit, "OPTION PARSING ERROR - %s", msg); + setup(); + for (lc = 0; TEST_LOOPING(lc); lc++) { + tst_count = 0; + check_ksm_options(&size, &num, &unit); + write_memcg(); + create_same_memory(size, num, unit); + } + cleanup(); + tst_exit(); +} + +void setup(void) +{ + tst_require_root(NULL); + + if (tst_kvercmp(2, 6, 32) < 0) + tst_brkm(TCONF, NULL, "2.6.32 or greater kernel required"); + if (access(PATH_KSM, F_OK) == -1) + tst_brkm(TCONF, NULL, "KSM configuration is not enabled"); + + if (access(PATH_KSM "merge_across_nodes", F_OK) == 0) { + SAFE_FILE_SCANF(NULL, PATH_KSM "merge_across_nodes", + "%d", &merge_across_nodes); + SAFE_FILE_PRINTF(NULL, PATH_KSM "merge_across_nodes", "1"); + } + + mount_mem("memcg", "cgroup", "memory", MEMCG_PATH, MEMCG_PATH_NEW); + tst_sig(FORK, DEF_HANDLER, NULL); + TEST_PAUSE; +} + +void cleanup(void) +{ + if (access(PATH_KSM "merge_across_nodes", F_OK) == 0) + FILE_PRINTF(PATH_KSM "merge_across_nodes", + "%d", merge_across_nodes); + + umount_mem(MEMCG_PATH, MEMCG_PATH_NEW); + TEST_CLEANUP; +} diff --git a/pool/shard004/C/0099845_clock_test.c b/pool/shard004/C/0099845_clock_test.c new file mode 100644 index 0000000000000000000000000000000000000000..cf9d8bb0e71444c5b2fe1d72c2f3c5dba8a1708f --- /dev/null +++ b/pool/shard004/C/0099845_clock_test.c @@ -0,0 +1,51 @@ +#include +#include + +#define TIME_END 0xFFFFFFF +#define TIME_STEP 333 +#define RATE 200 + +int main(void) { + uint32_t now = 0; + uint32_t runTime = now; + + printf("Beginn\n"); + while (now < TIME_END) { + uint8_t canRun = (int32_t) (now - runTime) >= 0; + if (canRun) { + static uint32_t cum; + static uint32_t last; + static uint32_t s; + + if (now - last >= 1000) { + s++; + last = now; + } + /*cum += now - last; + if (cum >= 1000) { + cum -= 1000; + s++; +// printf("now = %u ", now); +// printf("s = %u ", s); +// printf("\n"); + } + last = now;*/ +// printf("now-runTime = %d ", (int16_t) (now - runTime)); +// printf("now = %u ", now); +// printf("runTime = %u ", runTime); +// printf("s = %u ", s); +// printf("cum = %u ", cum); +// printf("\n"); + if (s != now/1000) { + printf("Fehler "); + printf("now = %u ", now); + printf("s = %u ", s); + printf("\n"); + break; + } + runTime = runTime + RATE; + } + now += TIME_STEP; + } + printf("Ende\n"); +} diff --git a/pool/shard004/C/0099849_si70xx.c b/pool/shard004/C/0099849_si70xx.c new file mode 100644 index 0000000000000000000000000000000000000000..f99e85dc3153f0cf01ef0be2a095225a98e44dd0 --- /dev/null +++ b/pool/shard004/C/0099849_si70xx.c @@ -0,0 +1,221 @@ +/* + * Copyright (C) 2016 Bas Stottelaar + * + * 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 drivers_si70xx + * @{ + * + * @file + * @brief Implementation of Si7006/13/20/21 sensor driver. + * + * @author Bas Stottelaar + * + * @} + */ + +#include +#include "xtimer.h" + +#include "si70xx_internals.h" +#include "si70xx.h" + +#define ENABLE_DEBUG (0) +#include "debug.h" + +#define SI70XX_I2C (dev->params.i2c_dev) +#define SI70XX_ADDR (dev->params.address) + +/** + * @brief Internal helper function to perform and reconstruct a measurement. + */ +static uint16_t _do_measure(const si70xx_t *dev, uint8_t command) +{ + uint8_t result[2]; + + i2c_acquire(SI70XX_I2C); + + if (i2c_write_byte(SI70XX_I2C, SI70XX_ADDR, command, 0) != 0) { + DEBUG("[ERROR] Cannot write command '%d' to I2C.\n", command); + } + + if (i2c_read_bytes(SI70XX_I2C, SI70XX_ADDR, result, 2, 0) != 0) { + DEBUG("[ERROR] Cannot read command '%d' result from I2C.\n", command); + } + + i2c_release(SI70XX_I2C); + + /* reconstruct raw result */ + return ((uint16_t)result[0] << 8) + (result[1] & 0xfc); +} + +/** + * @brief Internal helper function that reads the device serial number. + */ +static uint64_t _get_serial(const si70xx_t *dev) +{ + uint8_t out[2]; + uint8_t in_first[8] = { 0 }; + uint8_t in_second[8] = { 0 }; + + /* read the lower bytes */ + out[0] = SI70XX_READ_ID_FIRST_A; + out[1] = SI70XX_READ_ID_FIRST_B; + + if (i2c_write_bytes(SI70XX_I2C, SI70XX_ADDR, out, 2, 0) != 0) { + DEBUG("[ERROR] Cannot write command 'READ_ID_FIRST' to I2C.\n"); + } + + if (i2c_read_bytes(SI70XX_I2C, SI70XX_ADDR, in_first, 8, 0) != 0) { + DEBUG("[ERROR] Cannot read device first ID from I2C.\n"); + } + + /* read the higher bytes */ + out[0] = SI70XX_READ_ID_SECOND_A; + out[1] = SI70XX_READ_ID_SECOND_B; + + if (i2c_write_bytes(SI70XX_I2C, SI70XX_ADDR, out, 2, 0) != 0) { + DEBUG("[ERROR] Cannot write command 'READ_ID_SECOND' to I2C.\n"); + } + + if (i2c_read_bytes(SI70XX_I2C, SI70XX_ADDR, in_second, 8, 0) != 0) { + DEBUG("[ERROR] Cannot read device second ID from I2C.\n"); + } + + /* calculate the ID */ + uint32_t id_first = ((uint32_t)in_first[0] << 24) + ((uint32_t)in_first[2] << 16) + + (in_first[4] << 8) + (in_first[6] << 0); + uint32_t id_second = ((uint32_t)in_second[0] << 24) + ((uint32_t)in_second[2] << 16) + + (in_second[4] << 8) + (in_second[6] << 0); + + return (((uint64_t) id_first) << 32) + id_second; +} + +/** + * @brief Internal helper function that reads the device identifier. + */ +static uint8_t _get_id(const si70xx_t *dev) +{ + return (_get_serial(dev) >> 24) & 0xff; +} + +/** + * @brief Internal helper function that reads the device serial revision. + */ +static uint8_t _get_revision(const si70xx_t *dev) +{ + uint8_t out[2]; + uint8_t in = 0; + + /* read the revision number */ + out[0] = SI70XX_READ_REVISION_A; + out[1] = SI70XX_READ_REVISION_B; + + if (i2c_write_bytes(SI70XX_I2C, SI70XX_ADDR, out, 2, 0) != 0) { + DEBUG("[ERROR] Cannot write command 'READ_REVISION' to I2C.\n"); + } + + if (i2c_read_byte(SI70XX_I2C, SI70XX_ADDR, &in, 0) != 0) { + DEBUG("[ERROR] Cannot read device revision from I2C.\n"); + } + + return in; +} + +static int _test_device(const si70xx_t *dev) +{ + uint8_t revision = _get_revision(dev); + + if (revision != SI70XX_REVISION_1 && revision != SI70XX_REVISION_2) { + DEBUG("[ERROR] Bad device revision (%d).\n", revision); + return -SI70XX_ERR_NODEV; + } + + uint8_t id = _get_id(dev); + + if (id != SI70XX_ID) { + DEBUG("[ERROR] Not a valid Si7006/13/20/21 device\n"); + return -SI70XX_ERR_NODEV;; + } + + return SI70XX_OK; +} + +int si70xx_init(si70xx_t *dev, const si70xx_params_t *params) +{ + /* initialize the device descriptor */ + dev->params = *params; + + /* setup the i2c bus */ + i2c_acquire(SI70XX_I2C); + + if (_test_device(dev) != SI70XX_OK) { + DEBUG("[ERROR] No valid device found.\n"); + i2c_release(SI70XX_I2C); + return SI70XX_ERR_NODEV; + } + + /* initialize the peripheral */ + if (i2c_write_byte(SI70XX_I2C, SI70XX_ADDR, SI70XX_RESET, 0) != 0) { + DEBUG("[ERROR] Cannot reset device.\n"); + i2c_release(SI70XX_I2C); + return SI70XX_ERR_I2C; + } + + i2c_release(SI70XX_I2C); + + /* sensor is ready after at most 25 ms */ + xtimer_usleep(25 * US_PER_MS); + + DEBUG("[DEBUG] Device initialized with success.\n"); + return SI70XX_OK; +} + +uint16_t si70xx_get_relative_humidity(const si70xx_t *dev) +{ + uint16_t raw; + int32_t humidity; + + /* perform measurement */ + raw = _do_measure(dev, SI70XX_MEASURE_RH_HOLD); + + humidity = ((12500 * raw) / 65536) - 600; + + /* according to datasheet, values may exceed bounds, but can be clipped */ + if (humidity < 0) { + return 0; + } + else if (humidity > 10000) { + return 10000; + } + else { + return (uint16_t) humidity; + } +} + +int16_t si70xx_get_temperature(const si70xx_t *dev) +{ + uint16_t raw; + + /* perform measurement */ + raw = _do_measure(dev, SI70XX_MEASURE_TEMP_HOLD); + + return ((17572 * raw) / 65536) - 4685; +} + +void si70xx_get_both(const si70xx_t *dev, uint16_t *humidity, int16_t *temperature) +{ + uint16_t raw; + + /* read the humidity the normal way */ + *humidity = si70xx_get_relative_humidity(dev); + + /* read the temperature using the data from the previous measurement */ + raw = _do_measure(dev, SI70XX_MEASURE_TEMP_PREV); + + *temperature = ((17572 * raw) / 65536) - 4685; +} diff --git a/pool/shard004/C/0099860_srecorder_reason_time.c b/pool/shard004/C/0099860_srecorder_reason_time.c new file mode 100644 index 0000000000000000000000000000000000000000..d670e0b877f1132727bb2d2c066cecb3d056f2e0 --- /dev/null +++ b/pool/shard004/C/0099860_srecorder_reason_time.c @@ -0,0 +1,92 @@ +/** + @copyright: Huawei Technologies Co., Ltd. 2012-2012. All rights reserved. + + @file: srecorder_crash_time.c + + @brief: + + @version: 2.1.1 + + @author: Qi Dechun 00216641, Yan Tongguang 00297150 + + @date: 2015-03-13 + + @history: +*/ + +#include +#include +#include +#include + +#include +#include +#include +#include +#include + +#include "srecorder_reason_time.h" +#include "srecorder_symbols.h" + +#define LOG_BUF_MASK(log_buf_len) ((log_buf_len) - 1) + +static int reason_time_flag = 0; + +/** + @function: void srecorder_enable_reason_time() + @brief: + @return: + @note: +**/ +void srecorder_enable_reason_time(void) +{ + reason_time_flag = 1; +} + +/** + @function: void srecorder_disable_reason_time() + @brief: + @return: + @note: +**/ +void srecorder_disable_reason_time(void) +{ + reason_time_flag = 0; +} + +/** + @function: int srecorder_dump_reason_time() + @brief: + @return: + @note: +**/ +int srecorder_dump_reason_time(void) +{ + struct timeval tv; + struct rtc_time tm; + + if (reason_time_flag == 0) + { + SRECORDER_PRINTK("The dump flag of crash reason and time isn't enabled\n"); + return -1; + } + + memset(&tv, 0, sizeof(struct timeval)); + memset(&tm, 0, sizeof(struct rtc_time)); + + srecorder_log_header_l_start(TYPE_REASON_TIME); + + srecorder_dump_log_title(TYPE_REASON_TIME); + + do_gettimeofday(&tv); + tv.tv_sec -= sys_tz.tz_minuteswest * 60; + rtc_time_to_tm(tv.tv_sec, &tm); + + SRECORDER_SNPRINTF("Crash reason: apanic Crash Time: %04d%02d%02d-%02d:%02d:%02d\n", + tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday, + tm.tm_hour, tm.tm_min, tm.tm_sec); + + srecorder_log_header_l_end(); + + return 0; +} diff --git a/pool/shard004/C/0099863_machine_kexec.c b/pool/shard004/C/0099863_machine_kexec.c new file mode 100644 index 0000000000000000000000000000000000000000..463db2c3876e35a66b1a941fac408a3557048335 --- /dev/null +++ b/pool/shard004/C/0099863_machine_kexec.c @@ -0,0 +1,171 @@ +/****************************************************************************** + * machine_kexec.c + * + * Based on arch/ia64/kernel/machine_kexec.c from Linux 2.6.20-rc1 + * + * Xen port written by: + * - Simon 'Horms' Horman + * - Magnus Damm + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#define kexec_flush_icache_page(page) \ +do { \ + unsigned long page_addr = (unsigned long)page_address(page); \ + flush_icache_range(page_addr, page_addr + PAGE_SIZE); \ +} while(0) + +int machine_kexec_load(int type, int slot, xen_kexec_image_t *image) +{ + return 0; +} + +void machine_kexec_unload(int type, int slot, xen_kexec_image_t *image) +{ +} + +static void ia64_machine_kexec(struct unw_frame_info *info, void *arg) +{ + xen_kexec_image_t *image = arg; + int ii; + + /* Interrupts aren't acceptable while we reboot */ + local_irq_disable(); + + /* Mask CMC and Performance Monitor interrupts */ + ia64_setreg(_IA64_REG_CR_PMV, 1 << 16); + ia64_setreg(_IA64_REG_CR_CMCV, 1 << 16); + + /* Mask ITV and Local Redirect Registers */ + ia64_set_itv(1 << 16); + ia64_set_lrr0(1 << 16); + ia64_set_lrr1(1 << 16); + + /* terminate possible nested in-service interrupts */ + for (ii = 0; ii < 16; ii++) + ia64_eoi(); + + /* unmask TPR and clear any pending interrupts */ + ia64_setreg(_IA64_REG_CR_TPR, 0); + ia64_srlz_d(); + while (ia64_get_ivr() != IA64_SPURIOUS_INT_VECTOR) + ia64_eoi(); + platform_kernel_launch_event(); + relocate_new_kernel(image->indirection_page, image->start_address, + __pa(ia64_boot_param), image->reboot_code_buffer); + BUG(); +} + +/* This should probably be an arch-hook called from kexec_exec() + * Its also likely that it should be in the xen equivalent of + * arch/ia64/kernel/process.c */ +static void machine_shutdown(void) +{ +#ifdef CONFIG_SMP + unsigned int cpu; + + for_each_online_cpu(cpu) { + if (cpu != smp_processor_id()) + cpu_down(cpu); + } +#endif + kexec_disable_iosapic(); + acpi_restore_tables(); +} + +void machine_kexec(xen_kexec_image_t *image) +{ + machine_shutdown(); + unw_init_running(ia64_machine_kexec, image); + for(;;); +} + +void machine_reboot_kexec(xen_kexec_image_t *image) +{ + machine_kexec(image); +} + +int machine_kexec_get_xen(xen_kexec_range_t *range) +{ + range->start = ia64_tpa(_text); + range->size = (unsigned long)_end - (unsigned long)_text; + return 0; +} + +#define ELF_PAGE_SHIFT 16 +#define ELF_PAGE_SIZE (__IA64_UL_CONST(1) << ELF_PAGE_SHIFT) +#define ELF_PAGE_MASK (~(ELF_PAGE_SIZE - 1)) + +static int machine_kexec_get_xenheap(xen_kexec_range_t *range) +{ + range->start = (ia64_tpa(_end) + (ELF_PAGE_SIZE - 1)) & ELF_PAGE_MASK; + range->size = + (((unsigned long)range->start + KERNEL_TR_PAGE_SIZE) & + ~(KERNEL_TR_PAGE_SIZE - 1)) + - (unsigned long)range->start; + return 0; +} + +static int machine_kexec_get_boot_param(xen_kexec_range_t *range) +{ + range->start = __pa(ia64_boot_param); + range->size = sizeof(*ia64_boot_param); + return 0; +} + +static int machine_kexec_get_efi_memmap(xen_kexec_range_t *range) +{ + range->start = ia64_boot_param->efi_memmap; + range->size = ia64_boot_param->efi_memmap_size; + return 0; +} + +int machine_kexec_get(xen_kexec_range_t *range) +{ + switch (range->range) { + case KEXEC_RANGE_MA_XEN: + return machine_kexec_get_xen(range); + case KEXEC_RANGE_MA_XENHEAP: + return machine_kexec_get_xenheap(range); + case KEXEC_RANGE_MA_BOOT_PARAM: + return machine_kexec_get_boot_param(range); + case KEXEC_RANGE_MA_EFI_MEMMAP: + return machine_kexec_get_efi_memmap(range); + } + return -EINVAL; +} + +void arch_crash_save_vmcoreinfo(void) +{ + VMCOREINFO_SYMBOL(dom_xen); + VMCOREINFO_SYMBOL(dom_io); + VMCOREINFO_SYMBOL(xen_pstart); + VMCOREINFO_SYMBOL(frametable_pg_dir); +} + +/* + * Local variables: + * mode: C + * c-set-style: "BSD" + * c-basic-offset: 4 + * tab-width: 4 + * indent-tabs-mode: nil + * End: + */ diff --git a/pool/shard004/C/0099865_nid_genid.c b/pool/shard004/C/0099865_nid_genid.c new file mode 100644 index 0000000000000000000000000000000000000000..08d38bc8f24f69672d91d568e1cc30c0a4a539ad --- /dev/null +++ b/pool/shard004/C/0099865_nid_genid.c @@ -0,0 +1,74 @@ +#include "nid_core.h" +#include "nid_genid.h" + +static void nid_genid_timer(int signo); + +static uint32_t subid = 0x00FFFFFF; +static nid_bool_t resettime = NID_FALSE; +static time_t timestamp; +static uint64_t tempid; +static uint64_t machine_id; + +extern uint64_t nid_genid_new() { + if (resettime || 0x00FFFFFF == subid++) { //如果id尾部(24 bits)溢出,读秒并轮转 + /** + * 如果跑的过快(一秒钟跑了超过一千六百万条),则等到下一秒 + * 该部位代码应该没什么可能被触发到。 + */ + while (!resettime) { + usleep(1000); //sleep 1ms + } + + subid = 0; + resettime = NID_FALSE; + + if (timestamp > 0xFFFFFFFF) { + /** + * 超过32位的情况。该部位代码应该没什么可能被触发到。 + * 魔法数字由来:2015-07-07 00:00:00 的时间戳 加 0xFFFFFFFF,用来判断轮转溢出。 + * 如果超过32位时间,会重新轮转到1。 + * 但如果轮转的时间超过2151-08-13 06:28:15 则系统无法使用。 + * 但我想最起码一百多年过去了,更宽的位和更好的架构肯定出现了。 + */ + if (timestamp > 0x1559AA5FF) { + return 0; + } + timestamp -= 0xFFFFFFFF; + tempid = (uint64_t)timestamp << 31 | machine_id; + } + } + + return tempid | subid; +} + +static void nid_genid_timer(int signo) { + if (SIGALRM == signo) { + timestamp = time(NULL); + tempid = (uint64_t)timestamp << 31 | machine_id; + resettime = NID_TRUE; + } +} + +extern int32_t nid_genid_init(uint8_t mid) { + struct sigaction sa; + struct itimerval itv; + + machine_id = (uint64_t)mid << 24; + + sa.sa_flags = 0; + sa.sa_handler = nid_genid_timer; + sigemptyset(&sa.sa_mask); + if (NID_ERROR == sigaction(SIGALRM, &sa, NULL)) { + return NID_ERROR; + } + + itv.it_interval.tv_sec = 1; + itv.it_interval.tv_usec = 0; + itv.it_value.tv_sec = 1; + itv.it_value.tv_usec = 0; + if (NID_ERROR == setitimer(ITIMER_REAL, &itv, NULL)) { + return NID_ERROR; + } + + return NID_OK; +} diff --git a/pool/shard004/C/0099867_i2hex.c b/pool/shard004/C/0099867_i2hex.c new file mode 100644 index 0000000000000000000000000000000000000000..0f9f7e66ae68e1920ecb34782b821245f20c285a --- /dev/null +++ b/pool/shard004/C/0099867_i2hex.c @@ -0,0 +1,61 @@ +/**************************************************************** + * * + * Copyright 2001, 2007 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" + +void i2hex(UINTPTR_T val, uchar_ptr_t dest, int len) +{ + register uchar_ptr_t cp; + register UINTPTR_T n; + char x; + n = val; + cp = &dest[len]; + while (cp > dest) + { + x = n & 0xF; + n >>= 4; + *--cp = x + ((x > 9) ? 'A' - 10 : '0'); + } + return; +} + +#ifdef INT8_SUPPORTED +void i2hexl(qw_num val, uchar_ptr_t dest, int len) +{ + uchar_ptr_t cp; + qw_num n; + char x; + + n = val; + cp = &dest[len]; + + while (cp > dest) + { + x = n & 0xF; + n >>= 4; + *--cp = x + ((x > 9) ? 'A' - 10 : '0'); + } +} +#else +void i2hexl(qw_num val, uchar_ptr_t dest, int len) +{ + if (4 > len) + { /* We only process some bytes of the low order word */ + i2hex(val.value[msb_index], dest, len); + return; + } + i2hex(val.value[msb_index], dest, 8); /* Process low order word */ + dest += 8; + len -= 8; + if (len) + i2hex(val.value[lsb_index], dest, len); +} +#endif diff --git a/pool/shard004/C/0099868_file2sock.c b/pool/shard004/C/0099868_file2sock.c new file mode 100644 index 0000000000000000000000000000000000000000..b1e600c57ad3be1aaf2e5f7aaafcec0f612de1f3 --- /dev/null +++ b/pool/shard004/C/0099868_file2sock.c @@ -0,0 +1,201 @@ +/*************************************************************** + * FILE2SOCK.c - File to Socket Dump Utility + * + * Copyright (c) 20052-2007 Ethan Galstad + * Copyright (c) 2009-2012 Icinga Development Team (http://www.icinga.org) + * + * License: GPL v2 + * + **************************************************************/ + +#include "../../../include/config.h" +#include "../include/common.h" +#include "../include/io.h" + +int process_arguments(int, char **); + + +char *source_name = NULL; +char *dest_name = NULL; +int socket_type = IDO_SINK_UNIXSOCKET; +int tcp_port = 0; +int show_version = IDO_FALSE; +int show_license = IDO_FALSE; +int show_help = IDO_FALSE; + +int main(int argc, char **argv) { + int sd = 0; + int fd = 0; + char ch[1]; + int result = 0; + + + result = process_arguments(argc, argv); + + if (result != IDO_OK || show_help == IDO_TRUE || show_license == IDO_TRUE || show_version == IDO_TRUE) { + + if (result != IDO_OK) + printf("Incorrect command line arguments supplied\n"); + + printf("\n"); + printf("%s %s\n", FILE2SOCK_NAME, IDO_VERSION); + printf("%s\n", IDO_COPYRIGHT); + printf("Last Modified: %s\n", IDO_DATE); + printf("%s\n", IDO_LICENSE); + printf("\n"); + printf("Sends the contents of a file to a TCP or UNIX domain socket. The contents of\n"); + printf("the file are sent in their original format - no conversion, encapsulation, or\n"); + printf("other processing is done before sending the contents to the destination socket.\n"); + printf("\n"); + printf("Usage: %s -s -d [-t ] [-p ]\n", argv[0]); + printf("\n"); + printf(" = Name of the file to read from. Use '-' to read from stdin.\n"); + printf(" = If destination is a TCP socket, the address/hostname to connect to.\n"); + printf(" If destination is a Unix domain socket, the path to the socket.\n"); + printf(" = Specifies the type of destination socket. Valid values include:\n"); + printf(" tcp\n"); + printf(" unix (default)\n"); + printf(" = Port number to connect to if destination is TCP socket.\n"); + printf("\n"); + + exit(1); + } + + /* open the source file for reading */ + if (!strcmp(source_name, "-")) + fd = STDIN_FILENO; + else if ((fd = open(source_name, O_RDONLY)) == -1) { + perror("Unable to open source file for reading"); + exit(1); + } + + /* open data sink */ + if (ido_sink_open(dest_name, sd, socket_type, tcp_port, 0, &sd) == IDO_ERROR) { + perror("Cannot open destination socket"); + close(fd); + exit(1); + } + + /* we're reading from stdin... */ +#ifdef USE_SENDFILE + if (fd == STDIN_FILENO) { +#endif + while ((read(fd, &ch, 1))) { + if (write(sd, &ch, 1) == -1) { + perror("Error while writing to destination socket"); + result = 1; + break; + } + } +#ifdef USE_SENDFILE + } + + /* we're reading from a standard file... */ + else { + + /* get file size info */ + if (fstat(fd, &stat_buf) == -1) { + perror("fstat() error"); + result = 1; + } + + /* send the file contents to the socket */ + else if (sendfile(sd, fd, &offset, stat_buf.st_size) == -1) { + perror("sendfile() error"); + result = 1; + } + } +#endif + + /* close the data sink */ + ido_sink_flush(sd); + ido_sink_close(sd); + + /* close the source file */ + close(fd); + + return result; +} + + +/* process command line arguments */ +int process_arguments(int argc, char **argv) { + char optchars[32]; + int c = 1; + +#ifdef HAVE_GETOPT_H + int option_index = 0; + static struct option long_options[] = { + {"source", required_argument, 0, 's'}, + {"dest", required_argument, 0, 'd'}, + {"type", required_argument, 0, 't'}, + {"port", required_argument, 0, 'p'}, + {"help", no_argument, 0, 'h'}, + {"license", no_argument, 0, 'l'}, + {"version", no_argument, 0, 'V'}, + {0, 0, 0, 0} + }; +#endif + + /* no options were supplied */ + if (argc < 2) { + show_help = IDO_TRUE; + return IDO_OK; + } + + snprintf(optchars, sizeof(optchars), "s:d:t:p:hlV"); + + while (1) { +#ifdef HAVE_GETOPT_H + c = getopt_long(argc, argv, optchars, long_options, &option_index); +#else + c = getopt(argc, argv, optchars); +#endif + if (c == -1 || c == EOF) + break; + + /* process all arguments */ + switch (c) { + + case '?': + case 'h': + show_help = IDO_TRUE; + break; + case 'V': + show_version = IDO_TRUE; + break; + case 'l': + show_license = IDO_TRUE; + break; + case 't': + if (!strcmp(optarg, "tcp")) + socket_type = IDO_SINK_TCPSOCKET; + else if (!strcmp(optarg, "unix")) + socket_type = IDO_SINK_UNIXSOCKET; + else + return IDO_ERROR; + break; + case 'p': + tcp_port = atoi(optarg); + if (tcp_port <= 0) + return IDO_ERROR; + break; + case 's': + source_name = strdup(optarg); + break; + case 'd': + dest_name = strdup(optarg); + break; + default: + return IDO_ERROR; + break; + } + } + + /* make sure required args were supplied */ + if ((source_name == NULL || dest_name == NULL) && show_help == IDO_FALSE && show_version == IDO_FALSE && show_license == IDO_FALSE) + return IDO_ERROR; + + return IDO_OK; +} + diff --git a/pool/shard004/C/0099869_lapacke_chptrf_work.c b/pool/shard004/C/0099869_lapacke_chptrf_work.c new file mode 100644 index 0000000000000000000000000000000000000000..ebc93bda2f78eb55688d4dd19b7306065a84c42d --- /dev/null +++ b/pool/shard004/C/0099869_lapacke_chptrf_work.c @@ -0,0 +1,77 @@ +/***************************************************************************** + 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 chptrf +* Author: Intel Corporation +* Generated November, 2011 +*****************************************************************************/ + +#include "lapacke.h" +#include "lapacke_utils.h" + +lapack_int LAPACKE_chptrf_work( int matrix_order, char uplo, lapack_int n, + lapack_complex_float* ap, lapack_int* ipiv ) +{ + lapack_int info = 0; + if( matrix_order == LAPACK_COL_MAJOR ) { + /* Call LAPACK function and adjust info */ + LAPACK_chptrf( &uplo, &n, ap, ipiv, &info ); + if( info < 0 ) { + info = info - 1; + } + } else if( matrix_order == LAPACK_ROW_MAJOR ) { + lapack_complex_float* ap_t = NULL; + /* Allocate memory for temporary array(s) */ + ap_t = (lapack_complex_float*) + LAPACKE_malloc( sizeof(lapack_complex_float) * + ( MAX(1,n) * MAX(2,n+1) ) / 2 ); + if( ap_t == NULL ) { + info = LAPACK_TRANSPOSE_MEMORY_ERROR; + goto exit_level_0; + } + /* Transpose input matrices */ + LAPACKE_chp_trans( matrix_order, uplo, n, ap, ap_t ); + /* Call LAPACK function and adjust info */ + LAPACK_chptrf( &uplo, &n, ap_t, ipiv, &info ); + if( info < 0 ) { + info = info - 1; + } + /* Transpose output matrices */ + LAPACKE_chp_trans( LAPACK_COL_MAJOR, uplo, n, ap_t, ap ); + /* Release memory and exit */ + LAPACKE_free( ap_t ); +exit_level_0: + if( info == LAPACK_TRANSPOSE_MEMORY_ERROR ) { + LAPACKE_xerbla( "LAPACKE_chptrf_work", info ); + } + } else { + info = -1; + LAPACKE_xerbla( "LAPACKE_chptrf_work", info ); + } + return info; +} diff --git a/pool/shard004/C/0099870_queue.c b/pool/shard004/C/0099870_queue.c new file mode 100644 index 0000000000000000000000000000000000000000..090937cbe1a52c194ce4fb3388478c11307334e8 --- /dev/null +++ b/pool/shard004/C/0099870_queue.c @@ -0,0 +1,86 @@ +/* + * queue.c - implementation of queue manipulation functions + */ +#include "queue.h" + +queue_element_t *empty_element_ptr; + +void sthread_user_free(struct _sthread *thread); + +queue_t* create_queue() { + queue_t *queue; + queue = (queue_t*) malloc(sizeof(queue_t)); + queue->first = NULL; + queue->last = NULL; + empty_element_ptr = NULL; + return queue; +} + +void delete_queue(queue_t *queue) { + queue_element_t *pointer, *next; + pointer = queue->first; + while(pointer){ + next = pointer->next; + sthread_user_free(pointer->thread); + free(pointer); + pointer = next; + } + free(queue); +} + +void queue_insert(queue_t *queue, struct _sthread *thread) { + + queue_element_t *new_element; + + if(empty_element_ptr == NULL) + new_element = (queue_element_t*) malloc(sizeof(queue_element_t)); + else { + new_element = empty_element_ptr; + empty_element_ptr = NULL; + } + + new_element->thread = thread; + new_element->next = NULL; + + if(queue->first == NULL) { + queue->first = new_element; + queue->last = new_element; + return; + } + queue->last->next = new_element; + queue->last = new_element; +} + + +int queue_is_empty(queue_t *queue){ + if (queue->first == NULL)return 1; + else return 0; +} + + +struct _sthread *queue_first(queue_t *queue) { + queue_element_t *pointer; + pointer = queue->first; + return pointer->thread; +} + + +struct _sthread * queue_remove(queue_t *queue) { + queue_element_t *temp; + struct _sthread *thread; + + if(queue->first == NULL) { + return NULL; + } + + temp = queue->first; + queue->first = temp->next; + thread = temp->thread; + temp->thread = NULL; + temp->next = NULL; + + if(empty_element_ptr)free(temp); + else empty_element_ptr = temp; + + return thread; +} diff --git a/pool/shard004/C/0099872_bdbuf_test4_1.c b/pool/shard004/C/0099872_bdbuf_test4_1.c new file mode 100644 index 0000000000000000000000000000000000000000..41c12fc1ca3e87a42e7014daa36db0775d58cbf9 --- /dev/null +++ b/pool/shard004/C/0099872_bdbuf_test4_1.c @@ -0,0 +1,176 @@ +/*! @file + * @brief Check how rtems_bdbuf_sync() works. + * + * Test sequence: + * -# Call rtems_bdbuf_read(#N) in thread #1. + * -# Call rtems_bdbuf_read(#N) from thread #2. + * -# Thread #2 blocks on this call. + * -# Call rtems_bdbuf_sync(#N) in thread #1. + * -# After a while disk driver gets write request for block #N. + * Notify bdbuf library about write complete event. + * -# Check that thread #1 unlocked after this. + * -# Check that thread #2 unblocks and get buffer #N. + * -# Release buffer in thread #2. + * . + * + * Copyright (C) 2010 OKTET Labs, St.-Petersburg, Russia + * Author: Oleg Kravtsov + * + * 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: bdbuf_test4_1.c,v 1.1 2010/01/19 08:55:18 thomas Exp $ + */ + +#include + +static rtems_task bdbuf_test4_1_thread1(rtems_task_argument arg); +static rtems_task bdbuf_test4_1_thread2(rtems_task_argument arg); + +/* Block number used in the test */ +#define TEST_BLK_NUM_N 112 + +void +bdbuf_test4_1_main() +{ + bdbuf_test_msg msg; + + TEST_START("Test 4.1"); + + START_THREAD(1, bdbuf_test4_1_thread1); + START_THREAD(2, bdbuf_test4_1_thread2); + + /* + * Step 1: + * Call rtems_bdbuf_read(#N) in thread #1. + * Wait for read request in disk driver. + */ + WAIT_DRV_MSG(&msg); + SEND_DRV_MSG(0, 0, RTEMS_SUCCESSFUL, 0); + + /* Wait for return from rtems_bdbuf_read(#N) function. */ + WAIT_THREAD_SYNC(1); + + /* + * Step 2: + * Call rtems_bdbuf_read(#N) in thread #2. + */ + CONTINUE_THREAD(2); + + /* Make sure that thread #2 blocks */ + CHECK_THREAD_BLOCKED(2); + TEST_CHECK_RESULT("2"); + + /* + * Step 3: + * Call rtems_bdbuf_sync (#N) in thread #1. + */ + CONTINUE_THREAD(1); + + /* + * Setp 4: + * Wait for Write request to device driver. + */ + WAIT_DRV_MSG_WR(&msg); + + /* Check that both threads are blocked right now */ + CHECK_THREAD_BLOCKED(1); + CHECK_THREAD_BLOCKED(2); + + /* Send Write complete notification */ + SEND_DRV_MSG(0, 0, RTEMS_SUCCESSFUL, 0); + + /* + * Step 5: + * Check that rtems_bdbuf_sync(#N) call is unlocked. + */ + WAIT_THREAD_SYNC(1); + TEST_CHECK_RESULT("5"); + + /* + * Step 6: + * Check that rtems_bdbuf_read(#N) call in thread #2 is unlocked. + */ + WAIT_THREAD_SYNC(2); + + /* + * Step 7: + * Release buffer in thread #2 + */ + CONTINUE_THREAD(2); + + /* + * Exit from thread #1. + */ + CONTINUE_THREAD(1); + + TEST_END(); +} + +static rtems_task +bdbuf_test4_1_thread1(rtems_task_argument arg) +{ + rtems_status_code rc; + rtems_bdbuf_buffer *bd = NULL; + + /* + * Step 1: + * Call rtems_bdbuf_read(#N) in thread #1; + */ + rc = rtems_bdbuf_read(test_dev, TEST_BLK_NUM_N, &bd); + if (rc != RTEMS_SUCCESSFUL) + { + TEST_FAILED(); + } + + CONTINUE_MAIN(1); + + /* + * Step 3: + * Call rtems_bdbuf_sync(#N) + */ + rc = rtems_bdbuf_sync(bd); + if (rc != RTEMS_SUCCESSFUL) + { + TEST_FAILED(); + } + + CONTINUE_MAIN(1); + + THREAD_END(); +} + +static rtems_task +bdbuf_test4_1_thread2(rtems_task_argument arg) +{ + rtems_status_code rc; + rtems_bdbuf_buffer *bd = NULL; + + WAIT_MAIN_SYNC(2); + + /* + * Step 2: + * In thread #2 call rtems_bdbuf_read(#N). + * We will block on this call. + */ + rc = rtems_bdbuf_read(test_dev, TEST_BLK_NUM_N, &bd); + if (rc != RTEMS_SUCCESSFUL) + { + TEST_FAILED(); + } + + CONTINUE_MAIN(2); + + /* + * Release buffer. + */ + rc = rtems_bdbuf_release(bd); + if (rc != RTEMS_SUCCESSFUL) + { + TEST_FAILED(); + } + THREAD_END(); +} + + diff --git a/pool/shard004/C/0099878_ip6t_physdev.c b/pool/shard004/C/0099878_ip6t_physdev.c new file mode 100644 index 0000000000000000000000000000000000000000..f4eebb43d219f8f6f89a5f74d6a2f7af8b82c7f8 --- /dev/null +++ b/pool/shard004/C/0099878_ip6t_physdev.c @@ -0,0 +1,136 @@ +/* Kernel module to match the bridge port in and + * out device for IP packets coming into contact with a bridge. */ + +/* (C) 2001-2003 Bart De Schuymer + * + * 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 +#define MATCH 1 +#define NOMATCH 0 + +MODULE_LICENSE("GPL"); +MODULE_AUTHOR("Bart De Schuymer "); +MODULE_DESCRIPTION("iptables bridge physical device match module"); + +static int +match(const struct sk_buff *skb, + const struct net_device *in, + const struct net_device *out, + const void *matchinfo, + int offset, + const void *hdr, + u_int16_t datalen, + int *hotdrop) +{ + int i; + static const char nulldevname[IFNAMSIZ]; + const struct ip6t_physdev_info *info = matchinfo; + unsigned int ret; + const char *indev, *outdev; + struct nf_bridge_info *nf_bridge; + + /* Not a bridged IP packet or no info available yet: + * LOCAL_OUT/mangle and LOCAL_OUT/nat don't know if + * the destination device will be a bridge. */ + if (!(nf_bridge = skb->nf_bridge)) { + /* Return MATCH if the invert flags of the used options are on */ + if ((info->bitmask & IP6T_PHYSDEV_OP_BRIDGED) && + !(info->invert & IP6T_PHYSDEV_OP_BRIDGED)) + return NOMATCH; + if ((info->bitmask & IP6T_PHYSDEV_OP_ISIN) && + !(info->invert & IP6T_PHYSDEV_OP_ISIN)) + return NOMATCH; + if ((info->bitmask & IP6T_PHYSDEV_OP_ISOUT) && + !(info->invert & IP6T_PHYSDEV_OP_ISOUT)) + return NOMATCH; + if ((info->bitmask & IP6T_PHYSDEV_OP_IN) && + !(info->invert & IP6T_PHYSDEV_OP_IN)) + return NOMATCH; + if ((info->bitmask & IP6T_PHYSDEV_OP_OUT) && + !(info->invert & IP6T_PHYSDEV_OP_OUT)) + return NOMATCH; + return MATCH; + } + + /* This only makes sense in the FORWARD and POSTROUTING chains */ + if ((info->bitmask & IP6T_PHYSDEV_OP_BRIDGED) && + (!!(nf_bridge->mask & BRNF_BRIDGED) ^ + !(info->invert & IP6T_PHYSDEV_OP_BRIDGED))) + return NOMATCH; + + if ((info->bitmask & IP6T_PHYSDEV_OP_ISIN && + (!nf_bridge->physindev ^ !!(info->invert & IP6T_PHYSDEV_OP_ISIN))) || + (info->bitmask & IP6T_PHYSDEV_OP_ISOUT && + (!nf_bridge->physoutdev ^ !!(info->invert & IP6T_PHYSDEV_OP_ISOUT)))) + return NOMATCH; + + if (!(info->bitmask & IP6T_PHYSDEV_OP_IN)) + goto match_outdev; + indev = nf_bridge->physindev ? nf_bridge->physindev->name : nulldevname; + for (i = 0, ret = 0; i < IFNAMSIZ/sizeof(unsigned int); i++) { + ret |= (((const unsigned int *)indev)[i] + ^ ((const unsigned int *)info->physindev)[i]) + & ((const unsigned int *)info->in_mask)[i]; + } + + if ((ret == 0) ^ !(info->invert & IP6T_PHYSDEV_OP_IN)) + return NOMATCH; + +match_outdev: + if (!(info->bitmask & IP6T_PHYSDEV_OP_OUT)) + return MATCH; + outdev = nf_bridge->physoutdev ? + nf_bridge->physoutdev->name : nulldevname; + for (i = 0, ret = 0; i < IFNAMSIZ/sizeof(unsigned int); i++) { + ret |= (((const unsigned int *)outdev)[i] + ^ ((const unsigned int *)info->physoutdev)[i]) + & ((const unsigned int *)info->out_mask)[i]; + } + + return (ret != 0) ^ !(info->invert & IP6T_PHYSDEV_OP_OUT); +} + +static int +checkentry(const char *tablename, + const struct ip6t_ip6 *ip, + void *matchinfo, + unsigned int matchsize, + unsigned int hook_mask) +{ + const struct ip6t_physdev_info *info = matchinfo; + + if (matchsize != IP6T_ALIGN(sizeof(struct ip6t_physdev_info))) + return 0; + if (!(info->bitmask & IP6T_PHYSDEV_OP_MASK) || + info->bitmask & ~IP6T_PHYSDEV_OP_MASK) + return 0; + return 1; +} + +static struct ip6t_match physdev_match = { + .name = "physdev", + .match = &match, + .checkentry = &checkentry, + .me = THIS_MODULE, +}; + +static int __init init(void) +{ + return ip6t_register_match(&physdev_match); +} + +static void __exit fini(void) +{ + ip6t_unregister_match(&physdev_match); +} + +module_init(init); +module_exit(fini); diff --git a/pool/shard004/C/0099883_main.c b/pool/shard004/C/0099883_main.c new file mode 100644 index 0000000000000000000000000000000000000000..1d1c5a9eea49ead1fb90705ddf96a64b526780bb --- /dev/null +++ b/pool/shard004/C/0099883_main.c @@ -0,0 +1,81 @@ +#include +#include "lcd1602.h" + +/* ++--------+------+------+-----------+ +| P0 | P1 | P2 | P3 | ++--------+------+------+-----------+ +| 0x80 | 0x90 | 0xA0 | 0xB0 | ++--------+------+------+-----------+ +*/ +__sfr __at 0x80 LED; +__sfr __at 0x90 NUM; +__sbit __at 0x80 LED1; + +enum count_num{ + TIMER_1S = 200, + +}; + +#define GDO(count, val, func) do\ + {\ + if(++count > val){\ + count = 0;\ + func();\ + }\ + }while(0) + + +#define TIMES (5000) + +#define TH0_0 ((8192 - TIMES) >> 8 ) +#define TL0_0 (8192 - TIMES) + +int count = 0; +int wait = 0; +void interrupt1(void) __interrupt(1); + +void blink_led(void); +void null_func(void); + + +void main(void) +{ + + InitLcd1602(); + + TMOD = 0x00; + ET0 = 1; + TR0 = 1; + TL0 = TL0_0; + TH0 = TH0_0; + EA = 1; + + P0 = 0x81; + + ShowStr("hello World!"); + LcdShowNum(1, 1, 123); + for (;;) { + } + +} + +void interrupt1(void) __interrupt(1) +{ + + TL0 = TL0_0; + TH0 = TH0_0; + + GDO(count, TIMER_1S, null_func); + GDO(wait, 100, blink_led); +} +void blink_led(void) +{ + P1 = ~P1; +} + + +void null_func(void) +{ + +} diff --git a/pool/shard004/C/0099886_main.c b/pool/shard004/C/0099886_main.c new file mode 100644 index 0000000000000000000000000000000000000000..e89ae272021077d7b036209b35d78304e5eb55ca --- /dev/null +++ b/pool/shard004/C/0099886_main.c @@ -0,0 +1,158 @@ +/* + * Copyright (C) Paul Mackerras 1997. + * + * 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 "../coffboot/nonstdio.h" +#include "../coffboot/zlib.h" + +extern void *finddevice(const char *); +extern int getprop(void *, const char *, void *, int); +void gunzip(void *, int, unsigned char *, int *); + +#define get_16be(x) (*(unsigned short *)(x)) +#define get_32be(x) (*(unsigned *)(x)) + +#define RAM_START 0x00000000 +#define RAM_END 0x00800000 /* only 8M mapped with BATs */ + +#define RAM_FREE 0x00540000 /* after image of chrpboot */ +#define PROG_START 0x00010000 + +char *avail_ram; +char *end_avail; + +extern char image_data[]; +extern int image_len; +extern char initrd_data[]; +extern int initrd_len; + + +chrpboot(int a1, int a2, void *prom) +{ + int ns, oh, i; + unsigned sa, len; + void *dst; + unsigned char *im; + unsigned initrd_start, initrd_size; + + printf("chrpboot starting\n\r"); + /* setup_bats(); */ + + if (initrd_len) { + initrd_size = initrd_len; + initrd_start = (RAM_END - initrd_size) & ~0xFFF; + a1 = initrd_start; + a2 = initrd_size; + printf("initial ramdisk at %x (%u bytes)\n\r", initrd_start, + initrd_size); + memcpy((char *)initrd_start, initrd_data, initrd_size); + end_avail = (char *)initrd_start; + } else + end_avail = (char *) RAM_END; + im = image_data; + len = image_len; + dst = (void *) PROG_START; + + if (im[0] == 0x1f && im[1] == 0x8b) { + void *cp = (void *) RAM_FREE; + avail_ram = (void *) (RAM_FREE + ((len + 7) & -8)); + memcpy(cp, im, len); + printf("gunzipping... "); + gunzip(dst, 0x400000, cp, &len); + printf("done\n\r"); + + } else { + memmove(dst, im, len); + } + + flush_cache(dst, len); + + sa = PROG_START+12; + printf("start address = 0x%x\n\r", sa); + +#if 0 + pause(); +#endif + (*(void (*)())sa)(a1, a2, prom, 0, 0); + + printf("returned?\n\r"); + + pause(); +} + +void *zalloc(void *x, unsigned items, unsigned size) +{ + void *p = avail_ram; + + size *= items; + size = (size + 7) & -8; + avail_ram += size; + if (avail_ram > end_avail) { + printf("oops... out of memory\n\r"); + pause(); + } + return p; +} + +void zfree(void *x, void *addr, unsigned nb) +{ +} + +#define HEAD_CRC 2 +#define EXTRA_FIELD 4 +#define ORIG_NAME 8 +#define COMMENT 0x10 +#define RESERVED 0xe0 + +#define DEFLATED 8 + +void gunzip(void *dst, int dstlen, unsigned char *src, int *lenp) +{ + z_stream s; + int r, i, flags; + + /* skip header */ + i = 10; + flags = src[3]; + if (src[2] != DEFLATED || (flags & RESERVED) != 0) { + printf("bad gzipped data\n\r"); + exit(); + } + if ((flags & EXTRA_FIELD) != 0) + i = 12 + src[10] + (src[11] << 8); + if ((flags & ORIG_NAME) != 0) + while (src[i++] != 0) + ; + if ((flags & COMMENT) != 0) + while (src[i++] != 0) + ; + if ((flags & HEAD_CRC) != 0) + i += 2; + if (i >= *lenp) { + printf("gunzip: ran out of data in header\n\r"); + exit(); + } + + s.zalloc = zalloc; + s.zfree = zfree; + r = inflateInit2(&s, -MAX_WBITS); + if (r != Z_OK) { + printf("inflateInit2 returned %d\n\r", r); + exit(); + } + s.next_in = src + i; + s.avail_in = *lenp - i; + s.next_out = dst; + s.avail_out = dstlen; + r = inflate(&s, Z_FINISH); + if (r != Z_OK && r != Z_STREAM_END) { + printf("inflate returned %d\n\r", r); + exit(); + } + *lenp = s.next_out - (unsigned char *) dst; + inflateEnd(&s); +} diff --git a/pool/shard004/C/0099887_gyro.c b/pool/shard004/C/0099887_gyro.c new file mode 100644 index 0000000000000000000000000000000000000000..c37e199d724da364a743f6771024df77a71f1504 --- /dev/null +++ b/pool/shard004/C/0099887_gyro.c @@ -0,0 +1,117 @@ +/* + * This file is part of Ninjaflight. + * + * Ninjaflight is free software: you can 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. + * + * Ninjaflight is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Ninjaflight. If not, see . + */ + +#include +#include +#include +#include + +#include + +#include "common/axis.h" +#include "common/maths.h" +#include "common/filter.h" + +#include "config/config.h" + +#include "drivers/sensor.h" +#include "drivers/accgyro.h" + +#include "boardalignment.h" +#include "gyro.h" + +#define CALIBRATING_GYRO_CYCLES 1000 + +void ins_gyro_init(struct ins_gyro *self, const struct gyro_config *config){ + memset(self, 0, sizeof(struct ins_gyro)); + self->config = config; + self->calibratingG = CALIBRATING_GYRO_CYCLES; + + if (config->soft_gyro_lpf_hz) { + ins_gyro_set_filter_hz(self, config->soft_gyro_lpf_hz); + } +} + +static void _add_calibration_samples(struct ins_gyro *self, int32_t raw[3]){ + for (int axis = 0; axis < 3; axis++) { + // Reset g[axis] at start of calibration + if (self->calibratingG == CALIBRATING_GYRO_CYCLES) { + self->g[axis] = 0; + devClear(&self->var[axis]); + } + + // Sum up CALIBRATING_GYRO_CYCLES readings + self->g[axis] += raw[axis]; + devPush(&self->var[axis], raw[axis]); + + if (self->calibratingG == 1) { + float dev = devStandardDeviation(&self->var[axis]); + // if any of the axes has moved then we need to restart calibration for all of them + if (self->config->move_threshold && dev > self->config->move_threshold) { + ins_gyro_calibrate(self); + return; + } + self->gyroZero[axis] = self->g[axis] / CALIBRATING_GYRO_CYCLES; + } + } + + self->calibratingG--; +} + +void ins_gyro_process_sample(struct ins_gyro *self, int32_t x, int32_t y, int32_t z){ + int32_t raw[3] = { x, y, z }; + + if (self->use_filter) { + for (int axis = 0; axis < XYZ_AXIS_COUNT; axis++) { + raw[axis] = lrintf(applyBiQuadFilter((float)raw[axis], &self->gyroFilterState[axis])); + } + } + + if (self->calibratingG > 0) { + _add_calibration_samples(self, raw); + } else { + // only update values if we have been calibrated + for (int axis = 0; axis < 3; axis++) { + self->gyroADC[axis] = raw[axis] - self->gyroZero[axis]; + } + } +} + +void ins_gyro_set_filter_hz(struct ins_gyro *self, uint16_t hz){ + if(!hz){ + self->use_filter = false; + return; + } + for (int axis = 0; axis < 3; axis++) { + BiQuadNewLpf(hz, &self->gyroFilterState[axis], 1000); + } + self->use_filter = true; +} + +void ins_gyro_calibrate(struct ins_gyro *self){ + for(int c = 0; c < 3; c++) { + self->gyroADC[c] = 0; + self->gyroZero[c] = 0; + devClear(&self->var[c]); + } + self->calibratingG = CALIBRATING_GYRO_CYCLES; +} + +bool ins_gyro_is_calibrated(struct ins_gyro *self){ + return self->calibratingG == 0; +} + diff --git a/pool/shard004/C/0099892_2-1.c b/pool/shard004/C/0099892_2-1.c new file mode 100644 index 0000000000000000000000000000000000000000..ef31372c8b1d9636151c372887739070682e019a --- /dev/null +++ b/pool/shard004/C/0099892_2-1.c @@ -0,0 +1,135 @@ +/* + * Copyright (c) 2002, Intel Corporation. All rights reserved. + * Created by: bing.wei.liu 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 that pthread_cond_broadcast() + * When each thread unblocked as a result of pthread_cond_signal() + * returns from its call to pthread_cond_wait(), the thread shall + * own the mutex with which it called pthread_cond_wait(). + */ + +#define _XOPEN_SOURCE 600 + +#include +#include +#include +#include +#include "posixtest.h" + +#define THREAD_NUM 3 + +struct testdata { + pthread_mutex_t mutex; + pthread_cond_t cond; +} td; + +static int start_num; +static int waken_num; + +static void *thr_func(void *arg) +{ + int rc; + pthread_t self = pthread_self(); + + if (pthread_mutex_lock(&td.mutex) != 0) { + fprintf(stderr, "[Thread 0x%p] failed to acquire the mutex\n", + (void *)self); + exit(PTS_UNRESOLVED); + } + fprintf(stderr, "[Thread 0x%p] started and locked the mutex\n", + (void *)self); + start_num++; + + fprintf(stderr, "[Thread 0x%p] is waiting for the cond\n", + (void *)self); + rc = pthread_cond_wait(&td.cond, &td.mutex); + if (rc != 0) { + fprintf(stderr, "pthread_cond_wait return %d\n", rc); + exit(PTS_UNRESOLVED); + } + + if (pthread_mutex_trylock(&td.mutex) == 0) { + fprintf(stderr, "[Thread 0x%p] should not be able to lock the " + "mutex again\n", (void *)self); + printf("Test FAILED\n"); + exit(PTS_FAIL); + } + fprintf(stderr, "[Thread 0x%p] was wakened and acquired the " + "mutex again\n", (void *)self); + waken_num++; + + if (pthread_mutex_unlock(&td.mutex) != 0) { + fprintf(stderr, "[Thread 0x%p] failed to release the " + "mutex\n", (void *)self); + printf("Test FAILED\n"); + exit(PTS_FAIL); + } + fprintf(stderr, "[Thread 0x%p] released the mutex\n", (void *)self); + return NULL; +} + +int main(void) +{ + int i, rc; + pthread_t thread[THREAD_NUM]; + + if (pthread_mutex_init(&td.mutex, NULL) != 0) { + fprintf(stderr, "Fail to initialize mutex\n"); + return PTS_UNRESOLVED; + } + if (pthread_cond_init(&td.cond, NULL) != 0) { + fprintf(stderr, "Fail to initialize cond\n"); + return PTS_UNRESOLVED; + } + + for (i = 0; i < THREAD_NUM; i++) { + if (pthread_create(&thread[i], NULL, thr_func, NULL) != 0) { + fprintf(stderr, "Fail to create thread[%d]\n", i); + return PTS_UNRESOLVED; + } + } + while (start_num < THREAD_NUM) + usleep(100); + + /* Acquire the mutex to make sure that all waiters are currently + blocked on pthread_cond_wait */ + if (pthread_mutex_lock(&td.mutex) != 0) { + fprintf(stderr, "Main: Fail to acquire mutex\n"); + return PTS_UNRESOLVED; + } + if (pthread_mutex_unlock(&td.mutex) != 0) { + fprintf(stderr, "Main: Fail to release mutex\n"); + return PTS_UNRESOLVED; + } + + /* broadcast the condition to wake up all waiters */ + fprintf(stderr, "[Main thread] broadcast the condition\n"); + rc = pthread_cond_broadcast(&td.cond); + if (rc != 0) { + fprintf(stderr, "[Main thread] failed to broadcast the " + "condition\n"); + return PTS_UNRESOLVED; + } + sleep(1); + if (waken_num < THREAD_NUM) { + fprintf(stderr, "[Main thread] Not all waiters were wakened\n"); + for (i = 0; i < THREAD_NUM; i++) + pthread_cancel(thread[i]); + + return PTS_UNRESOLVED; + } + fprintf(stderr, "[Main thread] all waiters were wakened\n"); + + /* join all secondary threads */ + for (i = 0; i < THREAD_NUM; i++) { + if (pthread_join(thread[i], NULL) != 0) { + fprintf(stderr, "Fail to join thread[%d]\n", i); + return PTS_UNRESOLVED; + } + } + printf("Test PASSED\n"); + return PTS_PASS; +} diff --git a/pool/shard004/C/0099896_gptsync.c b/pool/shard004/C/0099896_gptsync.c new file mode 100644 index 0000000000000000000000000000000000000000..1a203dc59d2fa70c23c62ba3b61d77eca83412e5 --- /dev/null +++ b/pool/shard004/C/0099896_gptsync.c @@ -0,0 +1,264 @@ +/* gptsync.c - fill the mbr based on gpt entries */ +/* XXX: I don't know what to do if sector size isn't 512 bytes */ +/* + * GRUB -- GRand Unified Bootloader + * Copyright (C) 2009 Free Software Foundation, Inc. + * + * GRUB is free software: you can 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. + * + * GRUB is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with GRUB. If not, see . + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +GRUB_MOD_LICENSE ("GPLv3+"); + +/* Convert a LBA address to a CHS address in the INT 13 format. */ +/* Taken from grub1. */ +/* XXX: use hardcoded geometry of C = 1024, H = 255, S = 63. + Is it a problem? +*/ +static void +lba_to_chs (int lba, grub_uint8_t *cl, grub_uint8_t *ch, + grub_uint8_t *dh) +{ + int cylinder, head, sector; + int sectors = 63, heads = 255, cylinders = 1024; + + sector = lba % sectors + 1; + head = (lba / sectors) % heads; + cylinder = lba / (sectors * heads); + + if (cylinder >= cylinders) + { + *cl = *ch = *dh = 0xff; + return; + } + + *cl = sector | ((cylinder & 0x300) >> 2); + *ch = cylinder & 0xFF; + *dh = head; +} + +static grub_err_t +grub_cmd_gptsync (grub_command_t cmd __attribute__ ((unused)), + int argc, char **args) +{ + grub_device_t dev; + struct grub_msdos_partition_mbr mbr; + struct grub_partition *partition; + grub_disk_addr_t first_sector; + int numactive = 0; + int i; + + if (argc < 1) + return grub_error (GRUB_ERR_BAD_ARGUMENT, "device name required"); + if (argc > 4) + return grub_error (GRUB_ERR_BAD_ARGUMENT, "only 3 partitions can be " + "in hybrid MBR"); + + if (args[0][0] == '(' && args[0][grub_strlen (args[0]) - 1] == ')') + { + args[0][grub_strlen (args[0]) - 1] = 0; + dev = grub_device_open (args[0] + 1); + args[0][grub_strlen (args[0])] = ')'; + } + else + dev = grub_device_open (args[0]); + + if (! dev) + return grub_errno; + + if (! dev->disk) + { + grub_device_close (dev); + return grub_error (GRUB_ERR_BAD_ARGUMENT, "not a disk"); + } + + /* Read the protective MBR. */ + if (grub_disk_read (dev->disk, 0, 0, sizeof (mbr), &mbr)) + { + grub_device_close (dev); + return grub_errno; + } + + /* Check if it is valid. */ + if (mbr.signature != grub_cpu_to_le16 (GRUB_PC_PARTITION_SIGNATURE)) + { + grub_device_close (dev); + return grub_error (GRUB_ERR_BAD_PART_TABLE, "no signature"); + } + + /* Make sure the MBR is a protective MBR and not a normal MBR. */ + for (i = 0; i < 4; i++) + if (mbr.entries[i].type == GRUB_PC_PARTITION_TYPE_GPT_DISK) + break; + if (i == 4) + { + grub_device_close (dev); + return grub_error (GRUB_ERR_BAD_PART_TABLE, "no GPT partition map found"); + } + + first_sector = dev->disk->total_sectors; + for (i = 1; i < argc; i++) + { + char *separator, csep = 0; + grub_uint8_t type; + separator = grub_strchr (args[i], '+'); + if (! separator) + separator = grub_strchr (args[i], '-'); + if (separator) + { + csep = *separator; + *separator = 0; + } + partition = grub_partition_probe (dev->disk, args[i]); + if (separator) + *separator = csep; + if (! partition) + { + grub_device_close (dev); + return grub_error (GRUB_ERR_UNKNOWN_DEVICE, + N_("no such partition")); + } + + if (partition->start + partition->len > 0xffffffff) + { + grub_device_close (dev); + return grub_error (GRUB_ERR_OUT_OF_RANGE, + "only partitions residing in the first 2TB " + "can be present in hybrid MBR"); + } + + + if (first_sector > partition->start) + first_sector = partition->start; + + if (separator && *(separator + 1)) + type = grub_strtoul (separator + 1, 0, 0); + else + { + grub_fs_t fs = 0; + dev->disk->partition = partition; + fs = grub_fs_probe (dev); + + /* Unknown filesystem isn't fatal. */ + if (grub_errno == GRUB_ERR_UNKNOWN_FS) + { + fs = 0; + grub_errno = GRUB_ERR_NONE; + } + + if (fs && grub_strcmp (fs->name, "ntfs") == 0) + type = GRUB_PC_PARTITION_TYPE_NTFS; + else if (fs && grub_strcmp (fs->name, "fat") == 0) + /* FIXME: detect FAT16. */ + type = GRUB_PC_PARTITION_TYPE_FAT32_LBA; + else if (fs && (grub_strcmp (fs->name, "hfsplus") == 0 + || grub_strcmp (fs->name, "hfs") == 0)) + type = GRUB_PC_PARTITION_TYPE_HFS; + else + /* FIXME: detect more types. */ + type = GRUB_PC_PARTITION_TYPE_EXT2FS; + + dev->disk->partition = 0; + } + + mbr.entries[i].flag = (csep == '+') ? 0x80 : 0; + if (csep == '+') + { + numactive++; + if (numactive == 2) + { + grub_device_close (dev); + return grub_error (GRUB_ERR_BAD_ARGUMENT, + "only one partition can be active"); + } + } + mbr.entries[i].type = type; + mbr.entries[i].start = grub_cpu_to_le32 (partition->start); + lba_to_chs (partition->start, + &(mbr.entries[i].start_sector), + &(mbr.entries[i].start_cylinder), + &(mbr.entries[i].start_head)); + lba_to_chs (partition->start + partition->len - 1, + &(mbr.entries[i].end_sector), + &(mbr.entries[i].end_cylinder), + &(mbr.entries[i].end_head)); + mbr.entries[i].length = grub_cpu_to_le32 (partition->len); + grub_free (partition); + } + for (; i < 4; i++) + grub_memset (&(mbr.entries[i]), 0, sizeof (mbr.entries[i])); + + /* The protective partition. */ + if (first_sector > 0xffffffff) + first_sector = 0xffffffff; + else + first_sector--; + mbr.entries[0].flag = 0; + mbr.entries[0].type = GRUB_PC_PARTITION_TYPE_GPT_DISK; + mbr.entries[0].start = grub_cpu_to_le32 (1); + lba_to_chs (1, + &(mbr.entries[0].start_sector), + &(mbr.entries[0].start_cylinder), + &(mbr.entries[0].start_head)); + lba_to_chs (first_sector, + &(mbr.entries[0].end_sector), + &(mbr.entries[0].end_cylinder), + &(mbr.entries[0].end_head)); + mbr.entries[0].length = grub_cpu_to_le32 (first_sector); + + mbr.signature = grub_cpu_to_le16 (GRUB_PC_PARTITION_SIGNATURE); + + if (grub_disk_write (dev->disk, 0, 0, sizeof (mbr), &mbr)) + { + grub_device_close (dev); + return grub_errno; + } + + grub_printf_ (N_("New MBR is written to `%s'\n"), args[0]); + + return GRUB_ERR_NONE; +} + + +static grub_command_t cmd; + +GRUB_MOD_INIT(gptsync) +{ + (void) mod; /* To stop warning. */ + cmd = grub_register_command ("gptsync", grub_cmd_gptsync, + N_("DEVICE [PARTITION[+/-[TYPE]]] ..."), + /* TRANSLATORS: MBR type is one-byte partition + type id. */ + N_("Fill hybrid MBR of GPT drive DEVICE. " + "Specified partitions will be a part " + "of hybrid MBR. Up to 3 partitions are " + "allowed. TYPE is an MBR type. " + "+ means that partition is active. " + "Only one partition can be active.")); +} + +GRUB_MOD_FINI(gptsync) +{ + grub_unregister_command (cmd); +} diff --git a/pool/shard004/C/0099903_fsl_tegra_udc.c b/pool/shard004/C/0099903_fsl_tegra_udc.c new file mode 100644 index 0000000000000000000000000000000000000000..37d9fe8af4d790e68f1dca371a6d7de2c9e2bbe7 --- /dev/null +++ b/pool/shard004/C/0099903_fsl_tegra_udc.c @@ -0,0 +1,156 @@ +/* + * Description: + * Helper functions to support the tegra USB controller + * + * 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 + +static struct tegra_usb_phy *phy; +static struct clk *udc_clk; +static struct clk *emc_clk; +static struct clk *sclk; +static void *udc_base; + +int fsl_udc_clk_init(struct platform_device *pdev) +{ + struct resource *res; + int err; + int instance; + struct fsl_usb2_platform_data *pdata = pdev->dev.platform_data; + + + udc_clk = clk_get(&pdev->dev, NULL); + if (IS_ERR(udc_clk)) { + dev_err(&pdev->dev, "Can't get udc clock\n"); + return PTR_ERR(udc_clk); + } + + clk_enable(udc_clk); + + emc_clk = clk_get(&pdev->dev, "emc"); + if (IS_ERR(emc_clk)) { + dev_err(&pdev->dev, "Can't get emc clock\n"); + err = PTR_ERR(emc_clk); + goto err_emc; + } + + clk_enable(emc_clk); + + clk_set_rate(emc_clk, 400000000); + + sclk = clk_get(&pdev->dev, "sclk"); + if (IS_ERR(sclk)) { + dev_err(&pdev->dev, "Can't get sclk clock\n"); + err = PTR_ERR(sclk); + goto err_sclk; + } + + /* we have to remap the registers ourselves as fsl_udc does not + * export them for us. + */ + res = platform_get_resource(pdev, IORESOURCE_MEM, 0); + if (!res) { + err = -ENXIO; + goto err0; + } + udc_base = ioremap(res->start, resource_size(res)); + if (!udc_base) { + err = -ENOMEM; + goto err0; + } + + instance = pdev->id; + if (instance == -1) + instance = 0; + + phy = tegra_usb_phy_open(instance, udc_base, pdata->phy_config, + TEGRA_USB_PHY_MODE_DEVICE); + if (IS_ERR(phy)) { + dev_err(&pdev->dev, "Can't open phy\n"); + err = PTR_ERR(phy); + goto err1; + } + + tegra_usb_phy_power_on(phy); + + return 0; +err1: + iounmap(udc_base); +err0: + clk_put(sclk); +err_sclk: + clk_disable(emc_clk); + clk_put(emc_clk); +err_emc: + clk_disable(udc_clk); + clk_put(udc_clk); + return err; +} + +void fsl_udc_lock_sclk(uint rate) +{ + printk(KERN_ERR "sclk rate lock %d\n", rate); + clk_set_rate(sclk, rate); + clk_enable(sclk); +} + +void fsl_udc_unlock_sclk() +{ + printk(KERN_ERR "sclk rate unlock 80Mhz\n"); + clk_disable(sclk); +} + +void fsl_udc_clk_finalize(struct platform_device *pdev) +{ +} + +void fsl_udc_clk_release(void) +{ + tegra_usb_phy_close(phy); + + iounmap(udc_base); + + clk_disable(udc_clk); + clk_put(udc_clk); + + clk_disable(emc_clk); + clk_put(emc_clk); +} + +void fsl_udc_clk_suspend(void) +{ + tegra_usb_phy_power_off(phy); + clk_disable(udc_clk); + clk_disable(emc_clk); +} + +void fsl_udc_clk_resume(void) +{ + clk_enable(emc_clk); + clk_enable(udc_clk); + tegra_usb_phy_power_on(phy); +} + +void fsl_udc_dtd_prepare(void) +{ + /* When we are programming two DTDs very close to each other, + * the second DTD is being prefetched before it is actually written + * to DDR. To prevent this, we disable prefetcher before programming + * any new DTD and re-enable it before priming endpoint. + */ + tegra_usb_phy_memory_prefetch_off(phy); +} + +void fsl_udc_ep_barrier(void) +{ + tegra_usb_phy_memory_prefetch_on(phy); +} + diff --git a/pool/shard004/C/0099904_msi_ia64.c b/pool/shard004/C/0099904_msi_ia64.c new file mode 100644 index 0000000000000000000000000000000000000000..2b15e233f7fef6b016f50367c90f9c91ba096b63 --- /dev/null +++ b/pool/shard004/C/0099904_msi_ia64.c @@ -0,0 +1,207 @@ +/* + * MSI hooks for standard x86 apic + */ + +#include +#include +#include +#include +#include +#include + +static struct irq_chip ia64_msi_chip; + +#ifdef CONFIG_SMP +static void ia64_set_msi_irq_affinity(unsigned int irq, + const cpumask_t *cpu_mask) +{ + struct msi_msg msg; + u32 addr, data; + int cpu = first_cpu(*cpu_mask); + + if (!cpu_online(cpu)) + return; + + if (irq_prepare_move(irq, cpu)) + return; + + read_msi_msg(irq, &msg); + + addr = msg.address_lo; + addr &= MSI_ADDR_DEST_ID_MASK; + addr |= MSI_ADDR_DEST_ID_CPU(cpu_physical_id(cpu)); + msg.address_lo = addr; + + data = msg.data; + data &= MSI_DATA_VECTOR_MASK; + data |= MSI_DATA_VECTOR(irq_to_vector(irq)); + msg.data = data; + + write_msi_msg(irq, &msg); + cpumask_copy(irq_desc[irq].affinity, cpumask_of(cpu)); +} +#endif /* CONFIG_SMP */ + +int ia64_setup_msi_irq(struct pci_dev *pdev, struct msi_desc *desc) +{ + struct msi_msg msg; + unsigned long dest_phys_id; + int irq, vector; + cpumask_t mask; + + irq = create_irq(); + if (irq < 0) + return irq; + + set_irq_msi(irq, desc); + cpus_and(mask, irq_to_domain(irq), cpu_online_map); + dest_phys_id = cpu_physical_id(first_cpu(mask)); + vector = irq_to_vector(irq); + + msg.address_hi = 0; + msg.address_lo = + MSI_ADDR_HEADER | + MSI_ADDR_DEST_MODE_PHYS | + MSI_ADDR_REDIRECTION_CPU | + MSI_ADDR_DEST_ID_CPU(dest_phys_id); + + msg.data = + MSI_DATA_TRIGGER_EDGE | + MSI_DATA_LEVEL_ASSERT | + MSI_DATA_DELIVERY_FIXED | + MSI_DATA_VECTOR(vector); + + write_msi_msg(irq, &msg); + set_irq_chip_and_handler(irq, &ia64_msi_chip, handle_edge_irq); + + return 0; +} + +void ia64_teardown_msi_irq(unsigned int irq) +{ + destroy_irq(irq); +} + +static void ia64_ack_msi_irq(unsigned int irq) +{ + irq_complete_move(irq); + move_native_irq(irq); + ia64_eoi(); +} + +static int ia64_msi_retrigger_irq(unsigned int irq) +{ + unsigned int vector = irq_to_vector(irq); + ia64_resend_irq(vector); + + return 1; +} + +/* + * Generic ops used on most IA64 platforms. + */ +static struct irq_chip ia64_msi_chip = { + .name = "PCI-MSI", + .mask = mask_msi_irq, + .unmask = unmask_msi_irq, + .ack = ia64_ack_msi_irq, +#ifdef CONFIG_SMP + .set_affinity = ia64_set_msi_irq_affinity, +#endif + .retrigger = ia64_msi_retrigger_irq, +}; + + +int arch_setup_msi_irq(struct pci_dev *pdev, struct msi_desc *desc) +{ + if (platform_setup_msi_irq) + return platform_setup_msi_irq(pdev, desc); + + return ia64_setup_msi_irq(pdev, desc); +} + +void arch_teardown_msi_irq(unsigned int irq) +{ + if (platform_teardown_msi_irq) + return platform_teardown_msi_irq(irq); + + return ia64_teardown_msi_irq(irq); +} + +#ifdef CONFIG_DMAR +#ifdef CONFIG_SMP +static void dmar_msi_set_affinity(unsigned int irq, const struct cpumask *mask) +{ + struct irq_cfg *cfg = irq_cfg + irq; + struct msi_msg msg; + int cpu = cpumask_first(mask); + + if (!cpu_online(cpu)) + return; + + if (irq_prepare_move(irq, cpu)) + return; + + dmar_msi_read(irq, &msg); + + msg.data &= ~MSI_DATA_VECTOR_MASK; + msg.data |= MSI_DATA_VECTOR(cfg->vector); + msg.address_lo &= ~MSI_ADDR_DEST_ID_MASK; + msg.address_lo |= MSI_ADDR_DEST_ID_CPU(cpu_physical_id(cpu)); + + dmar_msi_write(irq, &msg); + cpumask_copy(irq_desc[irq].affinity, mask); +} +#endif /* CONFIG_SMP */ + +struct irq_chip dmar_msi_type = { + .name = "DMAR_MSI", + .unmask = dmar_msi_unmask, + .mask = dmar_msi_mask, + .ack = ia64_ack_msi_irq, +#ifdef CONFIG_SMP + .set_affinity = dmar_msi_set_affinity, +#endif + .retrigger = ia64_msi_retrigger_irq, +}; + +static int +msi_compose_msg(struct pci_dev *pdev, unsigned int irq, struct msi_msg *msg) +{ + struct irq_cfg *cfg = irq_cfg + irq; + unsigned dest; + cpumask_t mask; + + cpus_and(mask, irq_to_domain(irq), cpu_online_map); + dest = cpu_physical_id(first_cpu(mask)); + + msg->address_hi = 0; + msg->address_lo = + MSI_ADDR_HEADER | + MSI_ADDR_DEST_MODE_PHYS | + MSI_ADDR_REDIRECTION_CPU | + MSI_ADDR_DEST_ID_CPU(dest); + + msg->data = + MSI_DATA_TRIGGER_EDGE | + MSI_DATA_LEVEL_ASSERT | + MSI_DATA_DELIVERY_FIXED | + MSI_DATA_VECTOR(cfg->vector); + return 0; +} + +int arch_setup_dmar_msi(unsigned int irq) +{ + int ret; + struct msi_msg msg; + + ret = msi_compose_msg(NULL, irq, &msg); + if (ret < 0) + return ret; + dmar_msi_write(irq, &msg); + set_irq_chip_and_handler_name(irq, &dmar_msi_type, handle_edge_irq, + "edge"); + return 0; +} +#endif /* CONFIG_DMAR */ + diff --git a/pool/shard004/C/0099908_test_manual.c b/pool/shard004/C/0099908_test_manual.c new file mode 100644 index 0000000000000000000000000000000000000000..e244b6c82deae314f3c5733963826cc363f3d684 --- /dev/null +++ b/pool/shard004/C/0099908_test_manual.c @@ -0,0 +1,193 @@ +/* + * Copyright (C) 2014 Felix Ruess + * + * 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 test_manual.c + * + * Test the manual control via RC including command_laws. + */ + + +#define DATALINK_C + +#include "generated/airframe.h" +#include "generated/settings.h" + +#include "subsystems/datalink/datalink.h" +#include "subsystems/datalink/downlink.h" +#include "modules/datalink/pprz_dl.h" + +#include "mcu.h" +#include "mcu_periph/sys_time.h" +#include "led.h" + +#include "subsystems/commands.h" +#include "subsystems/actuators.h" +#if USE_MOTOR_MIXING +#include "subsystems/actuators/motor_mixing.h" +#endif + +#include "subsystems/radio_control.h" + +static inline void main_init(void); +static inline void main_periodic(void); +static inline void main_event(void); + +static void on_rc_frame(void); + +tid_t main_periodic_tid; ///< id for main_periodic() timer +tid_t radio_control_tid; ///< id for radio_control_periodic_task() timer + +bool autopilot_motors_on; + +int main(void) +{ + + main_init(); + while (1) { + if (sys_time_check_and_ack_timer(main_periodic_tid)) { + main_periodic(); + } + if (sys_time_check_and_ack_timer(radio_control_tid)) { + radio_control_periodic_task(); + } + main_event(); + }; + return 0; +} + +static inline void main_init(void) +{ + mcu_init(); + downlink_init(); + pprz_dl_init(); + + actuators_init(); +#if USE_MOTOR_MIXING + motor_mixing_init(); +#endif + + radio_control_init(); + + mcu_int_enable(); + main_periodic_tid = sys_time_register_timer((1. / PERIODIC_FREQUENCY), NULL); + radio_control_tid = sys_time_register_timer((1. / 60.), NULL); + + // just to make it usable in a standard rotorcraft airframe file + // with + // in the command_laws section + autopilot_motors_on = true; +} + +static inline void main_periodic(void) +{ + + SetActuatorsFromCommands(commands, 0); + + LED_PERIODIC(); + RunOnceEvery(512, {DOWNLINK_SEND_ALIVE(DefaultChannel, DefaultDevice, 16, MD5SUM);}); + RunOnceEvery(100, {DOWNLINK_SEND_RC(DefaultChannel, DefaultDevice, RADIO_CONTROL_NB_CHANNEL, radio_control.values);}); + RunOnceEvery(101, {DOWNLINK_SEND_COMMANDS(DefaultChannel, DefaultDevice, COMMANDS_NB, commands);}); + RunOnceEvery(102, {DOWNLINK_SEND_ACTUATORS(DefaultChannel, DefaultDevice, ACTUATORS_NB, actuators);}); + +} + +static inline void main_event(void) +{ + mcu_event(); + pprz_dl_event(); + RadioControlEvent(on_rc_frame); +} + +#define IdOfMsg(x) (x[1]) + +void dl_parse_msg(struct link_device *dev __attribute__((unused)), struct transport_tx *trans __attribute__((unused)), uint8_t *buf) +{ + uint8_t msg_id = IdOfMsg(buf); + switch (msg_id) { + case DL_PING: { + DOWNLINK_SEND_PONG(DefaultChannel, DefaultDevice); + } + break; + + case DL_SETTING: { + if (DL_SETTING_ac_id(buf) != AC_ID) { break; } + uint8_t i = DL_SETTING_index(buf); + float var = DL_SETTING_value(buf); + DlSetting(i, var); + DOWNLINK_SEND_DL_VALUE(DefaultChannel, DefaultDevice, &i, &var); + } + break; + + case DL_GET_SETTING : { + if (DL_GET_SETTING_ac_id(buf) != AC_ID) { break; } + uint8_t i = DL_GET_SETTING_index(buf); + float val = settings_get_value(i); + DOWNLINK_SEND_DL_VALUE(DefaultChannel, DefaultDevice, &i, &val); + } + break; +#ifdef RADIO_CONTROL_TYPE_DATALINK + case DL_RC_3CH : +#ifdef RADIO_CONTROL_DATALINK_LED + LED_TOGGLE(RADIO_CONTROL_DATALINK_LED); +#endif + parse_rc_3ch_datalink( + DL_RC_3CH_throttle_mode(buf), + DL_RC_3CH_roll(buf), + DL_RC_3CH_pitch(buf)); + break; + case DL_RC_4CH : +#ifdef RADIO_CONTROL_DATALINK_LED + LED_TOGGLE(RADIO_CONTROL_DATALINK_LED); +#endif + parse_rc_4ch_datalink( + DL_RC_4CH_mode(buf), + DL_RC_4CH_throttle(buf), + DL_RC_4CH_roll(buf), + DL_RC_4CH_pitch(buf), + DL_RC_4CH_yaw(buf)); + break; +#endif // RADIO_CONTROL_TYPE_DATALINK + + default: + break; + } +} + + +static void on_rc_frame(void) +{ + + /* if there are some commands that should always be set from RC, do it */ +#ifdef SetAutoCommandsFromRC + SetAutoCommandsFromRC(commands, radio_control.values); +#endif + +#ifdef SetCommandsFromRC + SetCommandsFromRC(commands, radio_control.values); +#else + // no rc_commands, assume we have rotorcraft with ROLL, PITCH, YAW, THRUST + commands[COMMAND_ROLL] = radio_control.values[RADIO_ROLL]; + commands[COMMAND_PITCH] = radio_control.values[RADIO_PITCH]; + commands[COMMAND_YAW] = radio_control.values[RADIO_YAW]; + commands[COMMAND_THRUST] = radio_control.values[RADIO_THROTTLE]; +#endif + +} diff --git a/pool/shard004/C/0099916_plugin_checks.c b/pool/shard004/C/0099916_plugin_checks.c new file mode 100644 index 0000000000000000000000000000000000000000..312515115f692aa607954a288b336b4fa1740ffc --- /dev/null +++ b/pool/shard004/C/0099916_plugin_checks.c @@ -0,0 +1,125 @@ +// SPDX-License-Identifier: GPL-3.0-or-later + +#include "daemon/common.h" + +static void checks_main_cleanup(void *ptr) { + struct netdata_static_thread *static_thread = (struct netdata_static_thread *)ptr; + static_thread->enabled = NETDATA_MAIN_THREAD_EXITING; + + info("cleaning up..."); + + static_thread->enabled = NETDATA_MAIN_THREAD_EXITED; +} + +void *checks_main(void *ptr) { + netdata_thread_cleanup_push(checks_main_cleanup, ptr); + + usec_t usec = 0, susec = localhost->rrd_update_every * USEC_PER_SEC, loop_usec = 0, total_susec = 0; + struct timeval now, last, loop; + + RRDSET *check1, *check2, *check3, *apps_cpu = NULL; + + check1 = rrdset_create_localhost( + "netdata" + , "check1" + , NULL + , "netdata" + , NULL + , "Caller gives microseconds" + , "a million !" + , "checks.plugin" + , "" + , NETDATA_CHART_PRIO_CHECKS + , localhost->rrd_update_every + , RRDSET_TYPE_LINE + ); + + rrddim_add(check1, "absolute", NULL, -1, 1, RRD_ALGORITHM_ABSOLUTE); + rrddim_add(check1, "incremental", NULL, 1, 1, RRD_ALGORITHM_INCREMENTAL); + + check2 = rrdset_create_localhost( + "netdata" + , "check2" + , NULL + , "netdata" + , NULL + , "Netdata calcs microseconds" + , "a million !" + , "checks.plugin" + , "" + , NETDATA_CHART_PRIO_CHECKS + , localhost->rrd_update_every + , RRDSET_TYPE_LINE + ); + rrddim_add(check2, "absolute", NULL, -1, 1, RRD_ALGORITHM_ABSOLUTE); + rrddim_add(check2, "incremental", NULL, 1, 1, RRD_ALGORITHM_INCREMENTAL); + + check3 = rrdset_create_localhost( + "netdata" + , "checkdt" + , NULL + , "netdata" + , NULL + , "Clock difference" + , "microseconds diff" + , "checks.plugin" + , "" + , NETDATA_CHART_PRIO_CHECKS + , localhost->rrd_update_every + , RRDSET_TYPE_LINE + ); + rrddim_add(check3, "caller", NULL, 1, 1, RRD_ALGORITHM_ABSOLUTE); + rrddim_add(check3, "netdata", NULL, 1, 1, RRD_ALGORITHM_ABSOLUTE); + rrddim_add(check3, "apps.plugin", NULL, 1, 1, RRD_ALGORITHM_ABSOLUTE); + + now_realtime_timeval(&last); + while(!netdata_exit) { + usleep(susec); + + // find the time to sleep in order to wait exactly update_every seconds + now_realtime_timeval(&now); + loop_usec = dt_usec(&now, &last); + usec = loop_usec - susec; + debug(D_PROCNETDEV_LOOP, "CHECK: last loop took %llu usec (worked for %llu, slept for %llu).", loop_usec, usec, susec); + + if(usec < (localhost->rrd_update_every * USEC_PER_SEC / 2ULL)) susec = (localhost->rrd_update_every * USEC_PER_SEC) - usec; + else susec = localhost->rrd_update_every * USEC_PER_SEC / 2ULL; + + // -------------------------------------------------------------------- + // Calculate loop time + + last.tv_sec = now.tv_sec; + last.tv_usec = now.tv_usec; + total_susec += loop_usec; + + // -------------------------------------------------------------------- + // check chart 1 + + if(check1->counter_done) rrdset_next_usec(check1, loop_usec); + rrddim_set(check1, "absolute", 1000000); + rrddim_set(check1, "incremental", total_susec); + rrdset_done(check1); + + // -------------------------------------------------------------------- + // check chart 2 + + if(check2->counter_done) rrdset_next(check2); + rrddim_set(check2, "absolute", 1000000); + rrddim_set(check2, "incremental", total_susec); + rrdset_done(check2); + + // -------------------------------------------------------------------- + // check chart 3 + + if(!apps_cpu) apps_cpu = rrdset_find_localhost("apps.cpu"); + if(check3->counter_done) rrdset_next_usec(check3, loop_usec); + now_realtime_timeval(&loop); + rrddim_set(check3, "caller", (long long) dt_usec(&loop, &check1->last_collected_time)); + rrddim_set(check3, "netdata", (long long) dt_usec(&loop, &check2->last_collected_time)); + if(apps_cpu) rrddim_set(check3, "apps.plugin", (long long) dt_usec(&loop, &apps_cpu->last_collected_time)); + rrdset_done(check3); + } + + netdata_thread_cleanup_pop(1); + return NULL; +} diff --git a/pool/shard004/C/0099928_smp.c b/pool/shard004/C/0099928_smp.c new file mode 100644 index 0000000000000000000000000000000000000000..55727fe7ce2acdbbef5c6905502ea990486d9cfd --- /dev/null +++ b/pool/shard004/C/0099928_smp.c @@ -0,0 +1,85 @@ +/* + * Copyright (C) 2008-2011 Gil Mendes + * + * 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. + */ + +/** + * @file + * @brief PC SMP detection code. + */ + +#include +#include + +#include +#include + +#include + +#include + +#include +#include +#include + +/** Detect all secondary CPUs in the system. */ +void platform_smp_detect(void) { + acpi_madt_lapic_t *lapic; + acpi_madt_t *madt; + size_t i, length; + + /* If the LAPIC is disabled, we cannot use SMP. */ + if(!lapic_enabled()) { + return; + } else if(!acpi_supported) { + return; + } + + madt = (acpi_madt_t *)acpi_table_find(ACPI_MADT_SIGNATURE); + if(!madt) + return; + + length = madt->header.length - sizeof(acpi_madt_t); + for(i = 0; i < length; i += lapic->length) { + lapic = (acpi_madt_lapic_t *)(madt->apic_structures + i); + if(lapic->type != ACPI_MADT_LAPIC) { + continue; + } else if(!(lapic->flags & (1<<0))) { + /* Ignore disabled processors. */ + continue; + } else if(lapic->lapic_id == curr_cpu->id) { + continue; + } + + cpu_register(lapic->lapic_id, CPU_OFFLINE); + } + + return; +} + +/** Prepare the SMP boot process. */ +__init_text void platform_smp_boot_prepare(void) { + x86_smp_boot_prepare(); +} + +/** Boot a secondary CPU. + * @param cpu CPU to boot. */ +__init_text void platform_smp_boot(cpu_t *cpu) { + x86_smp_boot(cpu); +} + +/** Clean up after secondary CPUs have been booted. */ +__init_text void platform_smp_boot_cleanup(void) { + x86_smp_boot_cleanup(); +} diff --git a/pool/shard004/C/0099933_program_07_15.c b/pool/shard004/C/0099933_program_07_15.c new file mode 100644 index 0000000000000000000000000000000000000000..00df143483164e4245acd385ff8f58dbe942d0aa --- /dev/null +++ b/pool/shard004/C/0099933_program_07_15.c @@ -0,0 +1,65 @@ +/* + * program_07_15.c - Converting a Positive Integer to Another Base + */ + +#include + +int convertedNumber[64]; +long int numberToConvert; +int base; +int digit = 0; + +void getNumberAndBase (void) +{ + printf ("Number to be converted? "); + scanf ("%li", &numberToConvert); + + printf ("Base? "); + scanf ("%i", &base); + + if (base < 2 || base > 16) + { + printf ("Bad base - must be between 2 and 16\n"); + base = 10; + } +} + +void convertNumber (void) +{ + do + { + convertedNumber[digit] = numberToConvert % base; + ++digit; + numberToConvert /= base; + } while (numberToConvert != 0); +} + +void displayConvertedNumber (void) +{ + const char baseDigits[16] = + { '0', '1', '2', '3', '4', '5', '6', '7', + '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', }; + int nextDigit; + + printf ("Converted number = "); + + for ( --digit; digit >= 0; --digit ) + { + nextDigit = convertedNumber[digit]; + printf ("%c", baseDigits[nextDigit]); + } + + printf ("\n"); +} + +int main (void) +{ + void getNumberAndBase (void), convertNumber (void), + displayConvertedNumber (void); + + getNumberAndBase(); + convertNumber (); + displayConvertedNumber (); + + return 0; +} diff --git a/pool/shard004/C/0099939_liblinear_helper.c b/pool/shard004/C/0099939_liblinear_helper.c new file mode 100644 index 0000000000000000000000000000000000000000..7433a0086f682b51920f101b645eb4e7bc42a248 --- /dev/null +++ b/pool/shard004/C/0099939_liblinear_helper.c @@ -0,0 +1,234 @@ +#include +#include +#include "linear.h" + +/* + * Convert matrix to sparse representation suitable for liblinear. x is + * expected to be an array of length n_samples*n_features. + * + * Whether the matrix is densely or sparsely populated, the fastest way to + * convert it to liblinear's sparse format is to calculate the amount of memory + * needed and allocate a single big block. + * + * Special care must be taken with indices, since liblinear indices start at 1 + * and not at 0. + * + * If bias is > 0, we append an item at the end. + */ +static struct feature_node **dense_to_sparse(char *x, int double_precision, + int n_samples, int n_features, int n_nonzero, double bias) +{ + float *x32 = (float *)x; + double *x64 = (double *)x; + struct feature_node **sparse; + int i, j; /* number of nonzero elements in row i */ + struct feature_node *T; /* pointer to the top of the stack */ + int have_bias = (bias > 0); + + sparse = malloc (n_samples * sizeof(struct feature_node *)); + if (sparse == NULL) + return NULL; + + n_nonzero += (have_bias+1) * n_samples; + T = malloc (n_nonzero * sizeof(struct feature_node)); + if (T == NULL) { + free(sparse); + return NULL; + } + + for (i=0; ivalue = *x64; + T->index = j; + ++ T; + } + ++ x64; /* go to next element */ + } else { + if (*x32 != 0) { + T->value = *x32; + T->index = j; + ++ T; + } + ++ x32; /* go to next element */ + } + } + + /* set bias element */ + if (have_bias) { + T->value = bias; + T->index = j; + ++ T; + } + + /* set sentinel */ + T->index = -1; + ++ T; + } + + return sparse; +} + + +/* + * Convert scipy.sparse.csr to liblinear's sparse data structure + */ +static struct feature_node **csr_to_sparse(char *x, int double_precision, + int *indices, int *indptr, int n_samples, int n_features, int n_nonzero, + double bias) +{ + float *x32 = (float *)x; + double *x64 = (double *)x; + struct feature_node **sparse; + int i, j=0, k=0, n; + struct feature_node *T; + int have_bias = (bias > 0); + + sparse = malloc (n_samples * sizeof(struct feature_node *)); + if (sparse == NULL) + return NULL; + + n_nonzero += (have_bias+1) * n_samples; + T = malloc (n_nonzero * sizeof(struct feature_node)); + if (T == NULL) { + free(sparse); + return NULL; + } + + for (i=0; ivalue = double_precision ? x64[k] : x32[k]; + T->index = indices[k] + 1; /* liblinear uses 1-based indexing */ + ++T; + ++k; + } + + if (have_bias) { + T->value = bias; + T->index = n_features + 1; + ++T; + ++j; + } + + /* set sentinel */ + T->index = -1; + ++T; + } + + return sparse; +} + +struct problem * set_problem(char *X, int double_precision_X, int n_samples, + int n_features, int n_nonzero, double bias, char* sample_weight, + char *Y) +{ + struct problem *problem; + /* not performant but simple */ + problem = malloc(sizeof(struct problem)); + if (problem == NULL) return NULL; + problem->l = n_samples; + problem->n = n_features + (bias > 0); + problem->y = (double *) Y; + problem->W = (double *) sample_weight; + problem->x = dense_to_sparse(X, double_precision_X, n_samples, n_features, + n_nonzero, bias); + problem->bias = bias; + + if (problem->x == NULL) { + free(problem); + return NULL; + } + + return problem; +} + +struct problem * csr_set_problem (char *X, int double_precision_X, + char *indices, char *indptr, int n_samples, int n_features, + int n_nonzero, double bias, char *sample_weight, char *Y) +{ + struct problem *problem; + problem = malloc (sizeof (struct problem)); + if (problem == NULL) return NULL; + problem->l = n_samples; + problem->n = n_features + (bias > 0); + problem->y = (double *) Y; + problem->W = (double *) sample_weight; + problem->x = csr_to_sparse(X, double_precision_X, (int *) indices, + (int *) indptr, n_samples, n_features, n_nonzero, bias); + problem->bias = bias; + + if (problem->x == NULL) { + free(problem); + return NULL; + } + + return problem; +} + + +/* Create a parameter struct with and return it */ +struct parameter *set_parameter(int solver_type, double eps, double C, + npy_intp nr_weight, char *weight_label, + char *weight, int max_iter, unsigned seed, + double epsilon) +{ + struct parameter *param = malloc(sizeof(struct parameter)); + if (param == NULL) + return NULL; + + set_seed(seed); + param->solver_type = solver_type; + param->eps = eps; + param->C = C; + param->p = epsilon; // epsilon for epsilon-SVR + param->nr_weight = (int) nr_weight; + param->weight_label = (int *) weight_label; + param->weight = (double *) weight; + param->max_iter = max_iter; + return param; +} + +void copy_w(void *data, struct model *model, int len) +{ + memcpy(data, model->w, len * sizeof(double)); +} + +double get_bias(struct model *model) +{ + return model->bias; +} + +void free_problem(struct problem *problem) +{ + free(problem->x[0]); + free(problem->x); + free(problem); +} + +void free_parameter(struct parameter *param) +{ + free(param); +} + +/* rely on built-in facility to control verbose output */ +static void print_null(const char *s) {} + +static void print_string_stdout(const char *s) +{ + fputs(s ,stdout); + fflush(stdout); +} + +/* provide convenience wrapper */ +void set_verbosity(int verbosity_flag){ + if (verbosity_flag) + set_print_string_function(&print_string_stdout); + else + set_print_string_function(&print_null); +} diff --git a/pool/shard004/C/0099940_xtft_l.c b/pool/shard004/C/0099940_xtft_l.c new file mode 100644 index 0000000000000000000000000000000000000000..c744a2fbe90339c07a01e4dc0e0d6815b8002a8c --- /dev/null +++ b/pool/shard004/C/0099940_xtft_l.c @@ -0,0 +1,78 @@ +/****************************************************************************** +* $Date: 2005/02/17 20:26:25 $ +* $RCSfile: xtft_l.c,v $ +******************************************************************************* + +******************************************************************************* +* +* XILINX IS PROVIDING THIS DESIGN, CODE, OR INFORMATION "AS IS" +* SOLELY FOR USE IN DEVELOPING PROGRAMS AND SOLUTIONS FOR +* XILINX DEVICES. BY PROVIDING THIS DESIGN, CODE, OR INFORMATION +* AS ONE POSSIBLE IMPLEMENTATION OF THIS FEATURE, APPLICATION +* OR STANDARD, XILINX IS MAKING NO REPRESENTATION THAT THIS +* IMPLEMENTATION IS FREE FROM ANY CLAIMS OF INFRINGEMENT, +* AND YOU ARE RESPONSIBLE FOR OBTAINING ANY RIGHTS YOU MAY REQUIRE +* FOR YOUR IMPLEMENTATION. XILINX EXPRESSLY DISCLAIMS ANY +* WARRANTY WHATSOEVER WITH RESPECT TO THE ADEQUACY OF THE +* IMPLEMENTATION, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OR +* REPRESENTATIONS THAT THIS IMPLEMENTATION IS FREE FROM CLAIMS OF +* INFRINGEMENT, IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS +* FOR A PARTICULAR PURPOSE. +* +* (c) Copyright 2004 Xilinx, Inc. +* All rights reserved. +* +******************************************************************************/ +/***************************** Include Files ********************************/ + +#include "xtft_l.h" +#include "xtft_charcode.h" + +/************************** Constant Definitions ****************************/ + + + +void XTft_FillScreen(Xuint32 BaseAddress, Xuint32 xu, Xuint32 yu, Xuint32 xl, + Xuint32 yl, Xuint32 col) +{ + Xuint32 x; + Xuint32 y; + + for(x = xu; x <= xl; x++) + { + for(y = yu; y <= yl; y++) + { + XTft_mSetPixel(BaseAddress, x, y, col); + } + } +} + +void XTft_WriteChar( + Xuint32 BaseAddress, + Xint8 ch, + Xuint32 xu, + Xuint32 yu, + Xuint32 fgColor, + Xuint32 bgColor) +{ + Xuint32 col, x, y; + Xuint8 val; + + for (y = 0; y < XTFT_CHAR_HEIGHT; y++) + { + val = XTft_vidChars[(Xuint32) ch][y]; + for (x = 0; x < XTFT_CHAR_WIDTH; x++) + { + if (val & (1 << (XTFT_CHAR_WIDTH - x - 1))) + col = fgColor; + else + col = bgColor; + + XTft_mSetPixel(BaseAddress, xu+x, yu+y, col); + } + } +} + + + + diff --git a/pool/shard004/C/0099943_system_manager.c b/pool/shard004/C/0099943_system_manager.c new file mode 100644 index 0000000000000000000000000000000000000000..e0be67af8bc7018ad77355dd6da55f0fba216d29 --- /dev/null +++ b/pool/shard004/C/0099943_system_manager.c @@ -0,0 +1,98 @@ +/* + * Copyright (C) 2012 Altera 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. + * + * 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 + +/* + * Populate the value for SYSMGR.FPGAINTF.MODULE based on pinmux setting. + * The value is not wrote to SYSMGR.FPGAINTF.MODULE but + * CONFIG_SYSMGR_ISWGRP_HANDOFF. + */ +static unsigned long populate_sysmgr_fpgaintf_module(void) +{ + writel(0, ISWGRP_HANDOFF_FPGAINTF); + + /* enable the signal for those hps peripheral use fpga */ + if (readl(SYSMGR_PINMUXGRP_NANDUSEFPGA) == SYSMGR_FPGAINTF_USEFPGA) + setbits_le32(ISWGRP_HANDOFF_FPGAINTF, + SYSMGR_FPGAINTF_NAND); + + if (readl(SYSMGR_PINMUXGRP_EMAC1USEFPGA) == SYSMGR_FPGAINTF_USEFPGA) + setbits_le32(ISWGRP_HANDOFF_FPGAINTF, + SYSMGR_FPGAINTF_EMAC1); + + if (readl(SYSMGR_PINMUXGRP_SDMMCUSEFPGA) == SYSMGR_FPGAINTF_USEFPGA) + setbits_le32(ISWGRP_HANDOFF_FPGAINTF, + SYSMGR_FPGAINTF_SDMMC); + + if (readl(SYSMGR_PINMUXGRP_EMAC0USEFPGA) == SYSMGR_FPGAINTF_USEFPGA) + setbits_le32(ISWGRP_HANDOFF_FPGAINTF, + SYSMGR_FPGAINTF_EMAC0); + + if (readl(SYSMGR_PINMUXGRP_SPIM1USEFPGA) == SYSMGR_FPGAINTF_USEFPGA) + setbits_le32(ISWGRP_HANDOFF_FPGAINTF, + SYSMGR_FPGAINTF_SPIM1); + + if (readl(SYSMGR_PINMUXGRP_SPIM0USEFPGA) == SYSMGR_FPGAINTF_USEFPGA) + setbits_le32(ISWGRP_HANDOFF_FPGAINTF, + SYSMGR_FPGAINTF_SPIM0); + + return readl(ISWGRP_HANDOFF_FPGAINTF); +} + +/****************************************************************************** + * Configure all the pin mux + *****************************************************************************/ +void sysmgr_pinmux_init(void) +{ + unsigned long offset = CONFIG_SYSMGR_PINMUXGRP_OFFSET; + + const unsigned long *pval = sys_mgr_init_table; + unsigned long i, reg_value; + + for (i = 0; + i < ((sizeof(sys_mgr_init_table)) / + sizeof(sys_mgr_pinmux_entry_t)); + i++, offset += sizeof(sys_mgr_pinmux_entry_t)) { + writel(*pval++, (SOCFPGA_SYSMGR_ADDRESS + offset)); + } + + /* populate (not writing) the value for SYSMGR.FPGAINTF.MODULE + based on pinmux setting */ + reg_value = populate_sysmgr_fpgaintf_module(); + + if (is_fpgamgr_fpga_ready()) { + /* enable the required signals only */ + writel(reg_value, SYSMGR_FPGAINTF_MODULE); + } +} + +/* + * If SDMMC PWREN is used, we need to ensure BootROM always reconfigure + * IOCSR and pinmux after warm reset. This is to cater the use case + * of board design which is using SDMMC PWREN pins. + */ +void sysmgr_sdmmc_pweren_mux_check(void) +{ + if (readl(SYSMGR_PINMUXGRP_FLASHIO1) == 3) + writel(SYSMGR_ROMCODEGRP_CTRL_WARMRSTCFGPINMUX | + SYSMGR_ROMCODEGRP_CTRL_WARMRSTCFGIO, + CONFIG_SYSMGR_ROMCODEGRP_CTRL); +} diff --git a/pool/shard004/C/0099944_cpufreq.c b/pool/shard004/C/0099944_cpufreq.c new file mode 100644 index 0000000000000000000000000000000000000000..9c50ffe7c9c44b824632697f360f9aa9eeb67571 --- /dev/null +++ b/pool/shard004/C/0099944_cpufreq.c @@ -0,0 +1,212 @@ +/* + * Blackfin core clock scaling + * + * Copyright 2008-2011 Analog Devices Inc. + * + * Licensed under the GPL-2 or later. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +static struct cpufreq_frequency_table bfin_freq_table[] = { + { + .frequency = CPUFREQ_TABLE_END, + .index = 0, + }, + { + .frequency = CPUFREQ_TABLE_END, + .index = 1, + }, + { + .frequency = CPUFREQ_TABLE_END, + .index = 2, + }, + { + .frequency = CPUFREQ_TABLE_END, + .index = 0, + }, +}; + +static struct bfin_dpm_state { + unsigned int csel; + unsigned int tscale; +} dpm_state_table[3]; + +#if defined(CONFIG_CYCLES_CLOCKSOURCE) +unsigned long long __bfin_cycles_off; +unsigned int __bfin_cycles_mod; +#endif + +static void __init bfin_init_tables(unsigned long cclk, unsigned long sclk) +{ + + unsigned long csel, min_cclk; + int index; + + +#if ANOMALY_05000273 || ANOMALY_05000274 || \ + (!defined(CONFIG_BF54x) && defined(CONFIG_BFIN_EXTMEM_DCACHEABLE)) + min_cclk = sclk * 2; +#else + min_cclk = sclk; +#endif + csel = ((bfin_read_PLL_DIV() & CSEL) >> 4); + + for (index = 0; (cclk >> index) >= min_cclk && csel <= 3; index++, csel++) { + bfin_freq_table[index].frequency = cclk >> index; + dpm_state_table[index].csel = csel << 4; + dpm_state_table[index].tscale = (TIME_SCALE / (1 << csel)) - 1; + + pr_debug("cpufreq: freq:%d csel:0x%x tscale:%d\n", + bfin_freq_table[index].frequency, + dpm_state_table[index].csel, + dpm_state_table[index].tscale); + } + return; +} + +static void bfin_adjust_core_timer(void *info) +{ + unsigned int tscale; + unsigned int index = *(unsigned int *)info; + + + tscale = dpm_state_table[index].tscale; + bfin_write_TSCALE(tscale); + return; +} + +static unsigned int bfin_getfreq_khz(unsigned int cpu) +{ + + return get_cclk() / 1000; +} + +static int bfin_target(struct cpufreq_policy *poli, + unsigned int target_freq, unsigned int relation) +{ + unsigned int index, plldiv, cpu; + unsigned long flags, cclk_hz; + struct cpufreq_freqs freqs; + static unsigned long lpj_ref; + static unsigned int lpj_ref_freq; + +#if defined(CONFIG_CYCLES_CLOCKSOURCE) + cycles_t cycles; +#endif + + for_each_online_cpu(cpu) { + struct cpufreq_policy *policy = cpufreq_cpu_get(cpu); + + if (!policy) + continue; + + if (cpufreq_frequency_table_target(policy, bfin_freq_table, + target_freq, relation, &index)) + return -EINVAL; + + cclk_hz = bfin_freq_table[index].frequency; + + freqs.old = bfin_getfreq_khz(0); + freqs.new = cclk_hz; + freqs.cpu = cpu; + + pr_debug("cpufreq: changing cclk to %lu; target = %u, oldfreq = %u\n", + cclk_hz, target_freq, freqs.old); + + cpufreq_notify_transition(&freqs, CPUFREQ_PRECHANGE); + if (cpu == CPUFREQ_CPU) { + flags = hard_local_irq_save(); + plldiv = (bfin_read_PLL_DIV() & SSEL) | + dpm_state_table[index].csel; + bfin_write_PLL_DIV(plldiv); + on_each_cpu(bfin_adjust_core_timer, &index, 1); +#if defined(CONFIG_CYCLES_CLOCKSOURCE) + cycles = get_cycles(); + SSYNC(); + cycles += 10; + __bfin_cycles_off += + (cycles << __bfin_cycles_mod) - (cycles << index); + __bfin_cycles_mod = index; +#endif + if (!lpj_ref_freq) { + lpj_ref = loops_per_jiffy; + lpj_ref_freq = freqs.old; + } + if (freqs.new != freqs.old) { + loops_per_jiffy = cpufreq_scale(lpj_ref, + lpj_ref_freq, freqs.new); + } + hard_local_irq_restore(flags); + } + + cpufreq_notify_transition(&freqs, CPUFREQ_POSTCHANGE); + } + + pr_debug("cpufreq: done\n"); + return 0; +} + +static int bfin_verify_speed(struct cpufreq_policy *policy) +{ + return cpufreq_frequency_table_verify(policy, bfin_freq_table); +} + +static int __init __bfin_cpu_init(struct cpufreq_policy *policy) +{ + + unsigned long cclk, sclk; + + cclk = get_cclk() / 1000; + sclk = get_sclk() / 1000; + + if (policy->cpu == CPUFREQ_CPU) + bfin_init_tables(cclk, sclk); + + policy->cpuinfo.transition_latency = 50000; + + policy->cur = cclk; + cpufreq_frequency_table_get_attr(bfin_freq_table, policy->cpu); + return cpufreq_frequency_table_cpuinfo(policy, bfin_freq_table); +} + +static struct freq_attr *bfin_freq_attr[] = { + &cpufreq_freq_attr_scaling_available_freqs, + NULL, +}; + +static struct cpufreq_driver bfin_driver = { + .verify = bfin_verify_speed, + .target = bfin_target, + .get = bfin_getfreq_khz, + .init = __bfin_cpu_init, + .name = "bfin cpufreq", + .owner = THIS_MODULE, + .attr = bfin_freq_attr, +}; + +static int __init bfin_cpu_init(void) +{ + return cpufreq_register_driver(&bfin_driver); +} + +static void __exit bfin_cpu_exit(void) +{ + cpufreq_unregister_driver(&bfin_driver); +} + +MODULE_AUTHOR("Michael Hennerich "); +MODULE_DESCRIPTION("cpufreq driver for Blackfin"); +MODULE_LICENSE("GPL"); + +module_init(bfin_cpu_init); +module_exit(bfin_cpu_exit); diff --git a/pool/shard004/C/0099948_kevent.c b/pool/shard004/C/0099948_kevent.c new file mode 100644 index 0000000000000000000000000000000000000000..722ec0ca39a9b1f01626eda5df66f9033081f06c --- /dev/null +++ b/pool/shard004/C/0099948_kevent.c @@ -0,0 +1,79 @@ +/* + * Copyright (c) 2009 Mark Heily + * + * 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. + */ + +#include + +#include "sys/event.h" +#include "private.h" + +const struct filter evfilt_proc = EVFILT_NOTIMPL; + +int +posix_kevent_wait( + struct kqueue *kq, + const struct timespec *timeout) +{ + int n, nfds; + fd_set rfds; + + nfds = kq->kq_nfds; + rfds = kq->kq_fds; + + dbg_puts("waiting for events"); + n = pselect(nfds, &rfds, NULL , NULL, timeout, NULL); + if (n < 0) { + if (errno == EINTR) { + dbg_puts("signal caught"); + return (-1); + } + dbg_perror("pselect(2)"); + return (-1); + } + + kq->kq_rfds = rfds; + + return (n); +} + +int +posix_kevent_copyout(struct kqueue *kq, int nready, + struct kevent *eventlist, int nevents) +{ + struct filter *filt; + int i, rv, nret; + + nret = 0; + for (i = 0; (i < EVFILT_SYSCOUNT && nready > 0 && nevents > 0); i++) { +// dbg_printf("eventlist: n = %d nevents = %d", nready, nevents); + filt = &kq->kq_filt[i]; +// dbg_printf("pfd[%d] = %d", i, filt->kf_pfd); + if (FD_ISSET(filt->kf_pfd, &kq->kq_rfds)) { + dbg_printf("pending events for filter %d (%s)", filt->kf_id, filter_name(filt->kf_id)); + rv = filt->kf_copyout(filt, eventlist, nevents); + if (rv < 0) { + dbg_puts("kevent_copyout failed"); + nret = -1; + break; + } + nret += rv; + eventlist += rv; + nevents -= rv; + nready--; + } + } + + return (nret); +} diff --git a/pool/shard004/C/0099949_AudDrv_Ana.c b/pool/shard004/C/0099949_AudDrv_Ana.c new file mode 100644 index 0000000000000000000000000000000000000000..e576e205fbbd1b1a217fee1c1499e50abe2c7cb5 --- /dev/null +++ b/pool/shard004/C/0099949_AudDrv_Ana.c @@ -0,0 +1,109 @@ +/* + * Copyright (C) 2007 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. + */ +/******************************************************************************* + * + * Filename: + * --------- + * AudDrv_Ana.c + * + * Project: + * -------- + * MT6583 Audio Driver ana Register setting + * + * Description: + * ------------ + * Audio register + * + * Author: + * ------- + * Chipeng Chang + * + *------------------------------------------------------------------------------ + * $Revision: #1 $ + * $Modtime:$ + * $Log:$ + * + * + *******************************************************************************/ + + +/***************************************************************************** + * C O M P I L E R F L A G S + *****************************************************************************/ + + +/***************************************************************************** + * E X T E R N A L R E F E R E N C E S + *****************************************************************************/ + +#include "AudDrv_Common.h" +#include "AudDrv_Ana.h" +#include "AudDrv_Clk.h" + +// define this to use wrapper to control +#define AUDIO_USING_WRAP_DRIVER +#ifdef AUDIO_USING_WRAP_DRIVER +#include +#endif + +/***************************************************************************** + * D A T A T Y P E S + *****************************************************************************/ + +void Ana_Set_Reg(uint32 offset, uint32 value, uint32 mask) +{ + // set pmic register or analog CONTROL_IFACE_PATH + int ret = 0; + PRINTK_ANA_REG("Ana_Set_Reg offset= 0x%x , value = 0x%x mask = 0x%x\n", offset, value, mask); +#ifdef AUDIO_USING_WRAP_DRIVER + uint32 Reg_Value = Ana_Get_Reg(offset); + Reg_Value &= (~mask); + Reg_Value |= (value & mask); + ret = pwrap_write(offset, Reg_Value); + Reg_Value = Ana_Get_Reg(offset); + if ((Reg_Value & mask) != (value & mask)) + { + //printk("Ana_Set_Reg offset= 0x%x , value = 0x%x mask = 0x%x ret = %d Reg_Value = 0x%x\n", offset, value, mask, ret, Reg_Value); + } +#endif +} + +uint32 Ana_Get_Reg(uint32 offset) +{ + // get pmic register + int ret = 0; + uint32 Rdata = 0; +#ifdef AUDIO_USING_WRAP_DRIVER + ret = pwrap_read(offset, &Rdata); +#endif + PRINTK_ANA_REG ("Ana_Get_Reg offset= 0x%x Rdata = 0x%x ret = %d\n",offset,Rdata,ret); + return Rdata; +} + +void Ana_Log_Print(void) +{ + AudDrv_ANA_Clk_On(); + AudDrv_ANA_Clk_Off(); + printk("-Ana_Log_Print \n"); +} + + +// export symbols for other module using +EXPORT_SYMBOL(Ana_Log_Print); +EXPORT_SYMBOL(Ana_Set_Reg); +EXPORT_SYMBOL(Ana_Get_Reg); + + diff --git a/pool/shard004/C/0099957_utils_subst.c b/pool/shard004/C/0099957_utils_subst.c new file mode 100644 index 0000000000000000000000000000000000000000..a49f6db56e8b75307e7790ae1601edb08c2f6b10 --- /dev/null +++ b/pool/shard004/C/0099957_utils_subst.c @@ -0,0 +1,144 @@ +/** + * collectd - src/utils_subst.c + * Copyright (C) 2008 Sebastian Harl + * + * 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 is applicable. + * + * 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 + * + * Authors: + * Sebastian "tokkee" Harl + **/ + +/* + * This module provides functions for string substitution. + */ + +#include "collectd.h" +#include "common.h" + +char *subst (char *buf, size_t buflen, const char *string, int off1, int off2, + const char *replacement) +{ + char *buf_ptr = buf; + size_t len = buflen; + + if ((NULL == buf) || (0 >= buflen) || (NULL == string) + || (0 > off1) || (0 > off2) || (off1 > off2) + || (NULL == replacement)) + return NULL; + + sstrncpy (buf_ptr, string, + ((size_t)off1 + 1 > buflen) ? buflen : (size_t)off1 + 1); + buf_ptr += off1; + len -= off1; + + if (0 >= len) + return buf; + + sstrncpy (buf_ptr, replacement, len); + buf_ptr += strlen (replacement); + len -= strlen (replacement); + + if (0 >= len) + return buf; + + sstrncpy (buf_ptr, string + off2, len); + return buf; +} /* subst */ + +char *asubst (const char *string, int off1, int off2, const char *replacement) +{ + char *buf; + int len; + + char *ret; + + if ((NULL == string) || (0 > off1) || (0 > off2) || (off1 > off2) + || (NULL ==replacement)) + return NULL; + + len = off1 + strlen (replacement) + strlen (string) - off2 + 1; + + buf = (char *)malloc (len); + if (NULL == buf) + return NULL; + + ret = subst (buf, len, string, off1, off2, replacement); + if (NULL == ret) + free (buf); + return ret; +} /* asubst */ + +char *subst_string (char *buf, size_t buflen, const char *string, + const char *needle, const char *replacement) +{ + char *temp; + size_t needle_len; + size_t i; + + if ((buf == NULL) || (string == NULL) + || (needle == NULL) || (replacement == NULL)) + return (NULL); + + temp = (char *) malloc (buflen); + if (temp == NULL) + { + ERROR ("subst_string: malloc failed."); + return (NULL); + } + + needle_len = strlen (needle); + strncpy (buf, string, buflen); + + /* Limit the loop to prevent endless loops. */ + for (i = 0; i < buflen; i++) + { + char *begin_ptr; + size_t begin; + + /* Find `needle' in `buf'. */ + begin_ptr = strstr (buf, needle); + if (begin_ptr == NULL) + break; + + /* Calculate the start offset. */ + begin = begin_ptr - buf; + + /* Substitute the region using `subst'. The result is stored in + * `temp'. */ + begin_ptr = subst (temp, buflen, buf, + begin, begin + needle_len, + replacement); + if (begin_ptr == NULL) + { + WARNING ("subst_string: subst failed."); + break; + } + + /* Copy the new string in `temp' to `buf' for the next round. */ + strncpy (buf, temp, buflen); + } + + if (i >= buflen) + { + WARNING ("subst_string: Loop exited after %zu iterations: " + "string = %s; needle = %s; replacement = %s;", + i, string, needle, replacement); + } + + sfree (temp); + return (buf); +} /* char *subst_string */ + +/* vim: set sw=4 ts=4 tw=78 noexpandtab : */ + diff --git a/pool/shard004/C/0099962_iostore.c b/pool/shard004/C/0099962_iostore.c new file mode 100644 index 0000000000000000000000000000000000000000..8645b253cfecd39bf45ffcde96611933946881ee --- /dev/null +++ b/pool/shard004/C/0099962_iostore.c @@ -0,0 +1,285 @@ +// +// iostore.h +// Firedrake +// +// Created by Sidney Just +// Copyright (c) 2012 by Sidney Just +// 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 "iostore.h" +#include "iostubs.h" +#include "iomodule.h" + +//static spinlock_t __io_storeLock = SPINLOCK_INIT; +static atree_t *__io_storeLibraries = NULL; +static spinlock_t __io_storeLock = SPINLOCK_INIT; + +static io_library_t *__io_libio = NULL; +static io_library_t *__io_libkernel = NULL; + +elf_sym_t *io_storeLookupSymbol(io_library_t *library, uint32_t symNum, io_library_t **outLib) +{ + elf_sym_t *lookup = library->symtab + symNum; + const char *name = library->strtab + lookup->st_name; + + if(ELF32_ST_BIND(lookup->st_info) == STB_LOCAL) + { + *outLib = library; + return lookup; + } + else + { + uint32_t hash = elf_hash(name); + elf_sym_t *symbol; + + // Try to find the symbol in the kernel + symbol = io_findKernelSymbol(name); + if(symbol) + { + *outLib = io_kernelLibraryStub(); + return symbol; + } + + // Search through the dependencies + // Breadth first + array_t *dependencyTree = array_create(); + array_addObject(dependencyTree, library->dependencies); + + for(size_t i=0; ilibrary, name, hash); + if(symbol && symbol->st_value != 0x0) + { + *outLib = dependency->library; + array_destroy(dependencyTree); + return symbol; + } + + if(list_count(dependency->library->dependencies) > 0) + array_addObject(dependencyTree, dependency->library->dependencies); + + dependency = dependency->next; + } + } + + array_destroy(dependencyTree); + + // Look it up in the library + symbol = io_librarySymbolWithName(library, name, hash); + if(symbol && symbol->st_value != 0x0) + { + *outLib = library; + return symbol; + } + } + + return NULL; +} + + + +int io_storeAtreeLookup(void *key1, void *key2) +{ + const char *name1 = (const char *)key1; + const char *name2 = (const char *)key2; + + uint32_t index = 0; + while(1) + { + char char1 = name1[index]; + char char2 = name2[index]; + + if(char1 == char2) + { + if(char1 == '\0') + return kCompareEqualTo; + + index ++; + continue; + } + + if(char1 > char2) + return kCompareGreaterThan; + + if(char1 < char2) + return kCompareLesserThan; + } +} + + + +io_library_t *io_storeLibraryWithName(const char *name) +{ + spinlock_lock(&__io_storeLock); + io_library_t *library = (io_library_t *)atree_find(__io_storeLibraries, (void *)name); + spinlock_unlock(&__io_storeLock); + + return library; +} + +io_library_t *io_storeLibraryWithAddress(vm_address_t address) +{ + spinlock_lock(&__io_storeLock); + iterator_t *iterator = atree_iterator(__io_storeLibraries); + io_library_t *library; + + while((library = iterator_nextObject(iterator))) + { + vm_address_t vlimit = library->vmemory + (library->pages * VM_PAGE_SIZE); + if(address >= library->vmemory && address <= vlimit) + { + iterator_destroy(iterator); + spinlock_unlock(&__io_storeLock); + + return library; + } + } + + iterator_destroy(iterator); + spinlock_unlock(&__io_storeLock); + return NULL; +} + +io_library_t *__io_storeLibraryWithAddress(vm_address_t address) +{ + if(spinlock_tryLock(&__io_storeLock)) + { + iterator_t *iterator = atree_iterator(__io_storeLibraries); + io_library_t *library; + + while((library = iterator_nextObject(iterator))) + { + vm_address_t vlimit = library->vmemory + (library->pages * VM_PAGE_SIZE); + if(address >= library->vmemory && address <= vlimit) + { + iterator_destroy(iterator); + spinlock_unlock(&__io_storeLock); + + return library; + } + } + + iterator_destroy(iterator); + spinlock_unlock(&__io_storeLock); + } + + return NULL; +} + + +bool io_storeAddLibrary(io_library_t *library) +{ + spinlock_lock(&__io_storeLock); + if(!atree_find(__io_storeLibraries, (void *)library->name)) + { + atree_insert(__io_storeLibraries, library, (void *)library->name); + spinlock_unlock(&__io_storeLock); + + io_libraryResolveDependencies(library); + + bool rel1 = io_libraryRelocateNonPLT(library); + bool rel2 = io_libraryRelocatePLT(library); + + if(!rel1 || !rel2) + { + io_storeRemoveLibrary(library); + return false; + } + + return true; + } + + spinlock_unlock(&__io_storeLock); + return true; +} + +void io_storeRemoveLibrary(io_library_t *library) +{ + spinlock_lock(&__io_storeLock); + atree_remove(__io_storeLibraries, (void *)library->name); + spinlock_unlock(&__io_storeLock); +} + + +typedef bool (*libio_init_t)(); + +void io_storeCallInitFunctions(io_library_t *library) +{ + for(size_t i=0; iinitArrayCount; i++) + { + uintptr_t ptr = library->initArray[i]; + if(ptr == 0x0 || ptr == UINT32_MAX) + continue; + + io_module_init_t init = (io_module_init_t)ptr; + init(); + } +} + +bool io_initStubs(); +bool io_moduleInit(); + +bool io_init(void *UNUSED(unused)) +{ + if(!io_initStubs() || !io_moduleInit()) + return false; + + __io_storeLibraries = atree_create(io_storeAtreeLookup); + if(!__io_storeLibraries) + return false; + + // Load the two essential kernel libraries + __io_libkernel = io_libraryCreateWithFile("libkernel.so"); + __io_libio = io_libraryCreateWithFile("libio.so"); + + if(__io_libkernel && __io_libio) + { + // Relocate and link into the kernel + bool result1 = io_storeAddLibrary(__io_libkernel); + bool result2 = io_storeAddLibrary(__io_libio); + + if(!result1 || !result2) + { + if(!result1) + dbg("Couldn't add libkernel.so to the iostore!"); + + if(!result2) + dbg("Couldn't add libio.so to the iostore!"); + + return false; + } + + io_storeCallInitFunctions(__io_libkernel); + io_storeCallInitFunctions(__io_libio); + + libio_init_t libio_init = (libio_init_t)io_libraryFindSymbol(__io_libio, "libio_init"); + if(!libio_init) + { + dbg("libio_init() not found in libio!"); + return false; + } + + dbg("libkernel.so at \16\27%p\16\31, libio.so at \16\27%p\16\31", __io_libkernel->relocBase, __io_libio->relocBase); + return libio_init(); + } + + return false; +} diff --git a/pool/shard004/C/0099963_isl-ast-gen-blocks-2.c b/pool/shard004/C/0099963_isl-ast-gen-blocks-2.c new file mode 100644 index 0000000000000000000000000000000000000000..d97a8ab20d54637b7d3dd6ab3bbf9a315b5e428d --- /dev/null +++ b/pool/shard004/C/0099963_isl-ast-gen-blocks-2.c @@ -0,0 +1,24 @@ +int k = 50; +static int __attribute__((noinline)) +foo () +{ + int i, res; + for (i = 0, res = 0; i < k; i++) + res += i; + + return res; +} + +extern void abort (); + +int +main (void) +{ + int res = foo (); + + + if (res != 1225) + abort (); + + return 0; +} diff --git a/pool/shard004/C/0099964_legacy-1-nov.c b/pool/shard004/C/0099964_legacy-1-nov.c new file mode 100644 index 0000000000000000000000000000000000000000..b51ac7f0271e7253c332f9aeee9e9091d6f0f5e6 --- /dev/null +++ b/pool/shard004/C/0099964_legacy-1-nov.c @@ -0,0 +1,25 @@ +/* { dg-do run } */ +/* { dg-options "-fcheck-pointer-bounds -mmpx" } */ + + +#include "mpx-check.h" + +int buf[100]; + +__attribute__((bnd_legacy)) +int rd (int *p, int i) +{ + int res = p[i]; + printf ("%d\n", res); + return res; +} + +int mpx_test (int argc, const char **argv) +{ + int *p = __bnd_set_ptr_bounds (buf + 1, 10); + + rd (p, -1); + rd (p, 10); + + return 0; +} diff --git a/pool/shard004/C/0099975_omxVCM4P2_DecodeVLCZigzag_IntraDCVLC.c b/pool/shard004/C/0099975_omxVCM4P2_DecodeVLCZigzag_IntraDCVLC.c new file mode 100644 index 0000000000000000000000000000000000000000..95e00d79e119179099920b6ec554e7482c07f579 --- /dev/null +++ b/pool/shard004/C/0099975_omxVCM4P2_DecodeVLCZigzag_IntraDCVLC.c @@ -0,0 +1,170 @@ +/** + * + * File Name: omxVCM4P2_DecodeVLCZigzag_IntraDCVLC.c + * OpenMAX DL: v1.0.2 + * Revision: 9641 + * Date: Thursday, February 7, 2008 + * + * (c) Copyright 2007-2008 ARM Limited. All Rights Reserved. + * + * + * + * Description: + * Contains modules for zigzag scanning and VLC decoding + * for intra block. + * + */ + +#include "omxtypes.h" +#include "armOMX.h" +#include "omxVC.h" + +#include "armVC.h" +#include "armCOMM_Bitstream.h" +#include "armCOMM.h" +#include "armVCM4P2_Huff_Tables_VLC.h" +#include "armVCM4P2_ZigZag_Tables.h" + + + + +/** + * Function: omxVCM4P2_DecodeVLCZigzag_IntraDCVLC (6.2.5.2.2) + * + * Description: + * Performs VLC decoding and inverse zigzag scan of AC and DC coefficients + * for one intra block. Two versions of the function (DCVLC and ACVLC) are + * provided in order to support the two different methods of processing DC + * coefficients, as described in [ISO14496-2], subclause 7.4.1.4, Intra DC + * Coefficient Decoding for the Case of Switched VLC Encoding. + * + * Input Arguments: + * + * ppBitStream - pointer to the pointer to the current byte in the + * bitstream buffer + * pBitOffset - pointer to the bit position in the current byte referenced + * by *ppBitStream. The parameter *pBitOffset is valid in the + * range [0-7]. + * Bit Position in one byte: |Most Least| + * *pBitOffset |0 1 2 3 4 5 6 7| + * predDir - AC prediction direction; used to select the zigzag scan + * pattern; takes one of the following values: + * - OMX_VC_NONE - AC prediction not used; + * performs classical zigzag scan. + * - OMX_VC_HORIZONTAL - Horizontal prediction; + * performs alternate-vertical zigzag scan; + * - OMX_VC_VERTICAL - Vertical prediction; + * performs alternate-horizontal zigzag scan. + * shortVideoHeader - binary flag indicating presence of + * short_video_header; escape modes 0-3 are used if + * shortVideoHeader==0, and escape mode 4 is used when + * shortVideoHeader==1. + * videoComp - video component type (luminance or chrominance) of the + * current block + * + * Output Arguments: + * + * ppBitStream - *ppBitStream is updated after the block is decoded such + * that it points to the current byte in the bit stream buffer + * pBitOffset - *pBitOffset is updated such that it points to the current + * bit position in the byte pointed by *ppBitStream + * pDst - pointer to the coefficient buffer of current block; must be + * 4-byte aligned. + * + * Return Value: + * + * OMX_Sts_NoErr - no error + * OMX_Sts_BadArgErr - bad arguments, if: + * - At least one of the following pointers is NULL: + * ppBitStream, *ppBitStream, pBitOffset, pDst + * - *pBitOffset exceeds [0,7] + * - preDir exceeds [0,2] + * - pDst is not 4-byte aligned + * OMX_Sts_Err - if: + * - In DecodeVLCZigzag_IntraDCVLC, dc_size > 12 + * - At least one of mark bits equals zero + * - Illegal stream encountered; code cannot be located in VLC table + * - Forbidden code encountered in the VLC FLC table. + * - The number of coefficients is greater than 64 + * + */ + +OMXResult omxVCM4P2_DecodeVLCZigzag_IntraDCVLC( + const OMX_U8 ** ppBitStream, + OMX_INT * pBitOffset, + OMX_S16 * pDst, + OMX_U8 predDir, + OMX_INT shortVideoHeader, + OMXVCM4P2VideoComponent videoComp +) +{ + /* Dummy initilaization to remove compilation error */ + OMX_S8 DCValueSize = 0; + OMX_U16 powOfSize, fetchDCbits; + OMX_U8 start = 1; + + /* Argument error checks */ + armRetArgErrIf(ppBitStream == NULL, OMX_Sts_BadArgErr); + armRetArgErrIf(*ppBitStream == NULL, OMX_Sts_BadArgErr); + armRetArgErrIf(pBitOffset == NULL, OMX_Sts_BadArgErr); + armRetArgErrIf(pDst == NULL, OMX_Sts_BadArgErr); + armRetArgErrIf(!armIs4ByteAligned(pDst), OMX_Sts_BadArgErr); + armRetArgErrIf((*pBitOffset < 0) || (*pBitOffset > 7), OMX_Sts_BadArgErr); + armRetArgErrIf((predDir > 2), OMX_Sts_BadArgErr); + + /* Insert the code into the bitstream */ + if (videoComp == OMX_VC_LUMINANCE) + { + DCValueSize = armUnPackVLC32(ppBitStream, + pBitOffset, armVCM4P2_aIntraDCLumaIndex); + } + else if (videoComp == OMX_VC_CHROMINANCE) + { + DCValueSize = armUnPackVLC32(ppBitStream, + pBitOffset, armVCM4P2_aIntraDCChromaIndex); + } + armRetDataErrIf(DCValueSize == -1, OMX_Sts_Err); + armRetDataErrIf(DCValueSize > 12, OMX_Sts_Err); + + + if (DCValueSize == 0) + { + pDst[0] = 0; + } + else + { + fetchDCbits = (OMX_U16) armGetBits(ppBitStream, pBitOffset, \ + DCValueSize); + + if ( (fetchDCbits >> (DCValueSize - 1)) == 0) + { + /* calulate pow */ + powOfSize = (1 << DCValueSize); + + pDst[0] = (OMX_S16) (fetchDCbits ^ (powOfSize - 1)); + pDst[0] = -pDst[0]; + } + else + { + pDst[0] = fetchDCbits; + } + + if (DCValueSize > 8) + { + /* reading and checking the marker bit*/ + armRetDataErrIf (armGetBits(ppBitStream, pBitOffset, 1) == 0, \ + OMX_Sts_Err); + } + } + + return armVCM4P2_DecodeVLCZigzag_Intra( + ppBitStream, + pBitOffset, + pDst, + predDir, + shortVideoHeader, + start); +} + +/* End of file */ + diff --git a/pool/shard004/C/0099976_progressfunc.c b/pool/shard004/C/0099976_progressfunc.c new file mode 100644 index 0000000000000000000000000000000000000000..fa75c273385b319ea44c5e2098ce3ed23c4d4804 --- /dev/null +++ b/pool/shard004/C/0099976_progressfunc.c @@ -0,0 +1,119 @@ +/*************************************************************************** + * _ _ ____ _ + * Project ___| | | | _ \| | + * / __| | | | |_) | | + * | (__| |_| | _ <| |___ + * \___|\___/|_| \_\_____| + * + * Copyright (C) 1998 - 2013, 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 http://curl.haxx.se/docs/copyright.html. + * + * You may opt to use, copy, modify, merge, publish, distribute and/or sell + * copies of the Software, and permit persons to whom the Software is + * furnished to do so, under the terms of the COPYING file. + * + * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY + * KIND, either express or implied. + * + ***************************************************************************/ +#include +#include + +#define STOP_DOWNLOAD_AFTER_THIS_MANY_BYTES 6000 +#define MINIMAL_PROGRESS_FUNCTIONALITY_INTERVAL 3 + +struct myprogress { + double lastruntime; + CURL *curl; +}; + +/* this is how the CURLOPT_XFERINFOFUNCTION callback works */ +static int xferinfo(void *p, + curl_off_t dltotal, curl_off_t dlnow, + curl_off_t ultotal, curl_off_t ulnow) +{ + struct myprogress *myp = (struct myprogress *)p; + CURL *curl = myp->curl; + double curtime = 0; + + curl_easy_getinfo(curl, CURLINFO_TOTAL_TIME, &curtime); + + /* under certain circumstances it may be desirable for certain functionality + to only run every N seconds, in order to do this the transaction time can + be used */ + if ((curtime - myp->lastruntime) >= + MINIMAL_PROGRESS_FUNCTIONALITY_INTERVAL) { + myp->lastruntime = curtime; + fprintf(stderr, "TOTAL TIME: %f \r\n", curtime); + } + + fprintf(stderr, + "UP: %" CURL_FORMAT_CURL_OFF_T " of %" CURL_FORMAT_CURL_OFF_T + " DOWN: %" CURL_FORMAT_CURL_OFF_T " of %" + CURL_FORMAT_CURL_OFF_T "\r\n", ulnow, ultotal, dlnow, dltotal); + + if (dlnow > STOP_DOWNLOAD_AFTER_THIS_MANY_BYTES) + return 1; + return 0; +} + +/* for libcurl older than 7.32.0 (CURLOPT_PROGRESSFUNCTION) */ +static int older_progress(void *p, + double dltotal, double dlnow, + double ultotal, double ulnow) +{ + return xferinfo(p, + (curl_off_t) dltotal, + (curl_off_t) dlnow, + (curl_off_t) ultotal, (curl_off_t) ulnow); +} + +int main(void) +{ + CURL *curl; + CURLcode res = CURLE_OK; + struct myprogress prog; + + curl = curl_easy_init(); + if (curl) { + prog.lastruntime = 0; + prog.curl = curl; + + curl_easy_setopt(curl, CURLOPT_URL, "http://example.com/"); + + curl_easy_setopt(curl, CURLOPT_PROGRESSFUNCTION, + older_progress); + /* pass the struct pointer into the progress function */ + curl_easy_setopt(curl, CURLOPT_PROGRESSDATA, &prog); + +#if LIBCURL_VERSION_NUM >= 0x072000 + /* xferinfo was introduced in 7.32.0, no earlier libcurl versions will + compile as they won't have the symbols around. + + If built with a newer libcurl, but running with an older libcurl: + curl_easy_setopt() will fail in run-time trying to set the new + callback, making the older callback get used. + + New libcurls will prefer the new callback and instead use that one even + if both callbacks are set. */ + + curl_easy_setopt(curl, CURLOPT_XFERINFOFUNCTION, xferinfo); + /* pass the struct pointer into the xferinfo function, note that this is + an alias to CURLOPT_PROGRESSDATA */ + curl_easy_setopt(curl, CURLOPT_XFERINFODATA, &prog); +#endif + + curl_easy_setopt(curl, CURLOPT_NOPROGRESS, 0L); + res = curl_easy_perform(curl); + + if (res != CURLE_OK) + fprintf(stderr, "%s\n", curl_easy_strerror(res)); + + /* always cleanup */ + curl_easy_cleanup(curl); + } + return (int)res; +} diff --git a/pool/shard004/C/0099984_xlog_printk.c b/pool/shard004/C/0099984_xlog_printk.c new file mode 100644 index 0000000000000000000000000000000000000000..757b2f804fd5b9d591de671272c615efa31684c5 --- /dev/null +++ b/pool/shard004/C/0099984_xlog_printk.c @@ -0,0 +1,87 @@ +#include +#include +#include +#include +#include +#include +#include "xlog_internal.h" + + +int __xlog_output(int level, const char *tag, const char *fmt, va_list args) +{ + int r; + const char *level_str; + + if (!tag) + return -1; + + if (!xLog_isOn(tag, level)) + return -1; + + switch (level) { + case ANDROID_LOG_VERBOSE: + level_str = KERN_DEBUG; + break; + + case ANDROID_LOG_DEBUG: + level_str = KERN_INFO; + break; + + case ANDROID_LOG_INFO: + level_str = KERN_NOTICE; + break; + + case ANDROID_LOG_WARN: + level_str = KERN_WARNING; + break; + + case ANDROID_LOG_ERROR: + level_str = KERN_ERR; + break; + + case ANDROID_LOG_FATAL: + level_str = KERN_EMERG; + break; + + default: + level_str = KERN_INFO; + break; + } + + printk("%s[%s] ", level_str, tag); + + r = vprintk(fmt, args); + + if (level == ANDROID_LOG_FATAL) { + BUG(); + } + return r; +} + +asmlinkage int __xlog_printk(const struct xlog_record *rec, ...) +{ + va_list args; + int r; + va_start(args, rec); + r = __xlog_output(rec->prio, rec->tag_str, rec->fmt_str, args); + va_end(args); + + return r; +} + +int __xlog_ale_printk(int prio, const struct ale_convert *convert, ...) +{ + if (convert->fmt_ptr != NULL) { + va_list args; + int r; + va_start(args, convert); + r = __xlog_output(prio, convert->tag_str, convert->fmt_ptr, args); + va_end(args); + return r; + } + return 0; +} + + +EXPORT_SYMBOL(__xlog_printk); +EXPORT_SYMBOL(__xlog_ale_printk); diff --git a/pool/shard004/C/0099999_mpidi_win_control.c b/pool/shard004/C/0099999_mpidi_win_control.c new file mode 100644 index 0000000000000000000000000000000000000000..56016be90b7a8cf7fbcbe4a61fba9e802e1d65b8 --- /dev/null +++ b/pool/shard004/C/0099999_mpidi_win_control.c @@ -0,0 +1,149 @@ +/* begin_generated_IBM_copyright_prolog */ +/* */ +/* This is an automatically generated copyright prolog. */ +/* After initializing, DO NOT MODIFY OR MOVE */ +/* --------------------------------------------------------------- */ +/* Licensed Materials - Property of IBM */ +/* Blue Gene/Q 5765-PER 5765-PRP */ +/* */ +/* (C) Copyright IBM Corp. 2011, 2012 All Rights Reserved */ +/* US Government Users Restricted Rights - */ +/* Use, duplication, or disclosure restricted */ +/* by GSA ADP Schedule Contract with IBM Corp. */ +/* */ +/* --------------------------------------------------------------- */ +/* */ +/* end_generated_IBM_copyright_prolog */ +/* (C)Copyright IBM Corp. 2007, 2011 */ +/** + * \file src/onesided/mpidi_win_control.c + * \brief ??? + */ +#include "mpidi_onesided.h" + + +void +MPIDI_WinCtrlSend(pami_context_t context, + MPIDI_Win_control_t *control, + int rank, + MPID_Win *win) +{ + pami_task_t taskid; + MPIDI_WinLock_info *winLock; + control->win = win->mpid.info[rank].win; + control->rank = win->comm_ptr->rank; + taskid=MPID_VCR_GET_LPID(win->comm_ptr->vcr,rank); + + pami_endpoint_t dest; + pami_result_t rc; + taskid=MPID_VCR_GET_LPID(win->comm_ptr->vcr,rank); + rc = PAMI_Endpoint_create(MPIDI_Client,taskid, 0, &dest); + MPID_assert(rc == PAMI_SUCCESS); + + if ((control->type == MPIDI_WIN_MSGTYPE_UNLOCK) || + (control->type == MPIDI_WIN_MSGTYPE_UNLOCKALL)) { + pami_send_t params = { + .send = { + .dispatch = MPIDI_Protocols_WinCtrl, + .dest = dest, + .header = { + .iov_base = control, + .iov_len = sizeof(MPIDI_Win_control_t), + }, + }, + .events = { + .cookie = win, + .local_fn = NULL, + .remote_fn= MPIDI_WinUnlockDoneCB, + }, + }; + rc = PAMI_Send(context, ¶ms); + } else { + pami_send_immediate_t params = { + .dispatch = MPIDI_Protocols_WinCtrl, + .dest = dest, + .header = { + .iov_base = control, + .iov_len = sizeof(MPIDI_Win_control_t), + }, + .data = { + .iov_base = NULL, + .iov_len = 0, + }, + }; + rc = PAMI_Send_immediate(context, ¶ms); + } + if ((control->type == MPIDI_WIN_MSGTYPE_LOCKALLREQ) || (control->type == MPIDI_WIN_MSGTYPE_UNLOCKALL)) { + winLock = (MPIDI_WinLock_info *) control->flagAddr; + winLock->done = 1; + } + MPID_assert(rc == PAMI_SUCCESS); + +} + +void +MPIDI_WinUnlockDoneCB(pami_context_t context, + void * cookie, + pami_result_t result) +{ + MPID_Win *win = (MPID_Win *)cookie; + if (win->mpid.sync.origin_epoch_type == MPID_EPOTYPE_LOCK) { + win->mpid.sync.lock.remote.locked = 0; + } + else if (win->mpid.sync.origin_epoch_type == MPID_EPOTYPE_LOCK_ALL) + { + MPID_assert((int)win->mpid.sync.lock.remote.allLocked > 0); + win->mpid.sync.lock.remote.allLocked -= 1; + } + else + MPID_assert_always(0); +} + + +void +MPIDI_WinControlCB(pami_context_t context, + void * cookie, + const void * _control, + size_t size, + const void * sndbuf, + size_t sndlen, + pami_endpoint_t sender, + pami_recv_t * recv) +{ + MPID_assert(recv == NULL); + MPID_assert(sndlen == 0); + MPID_assert(_control != NULL); + MPID_assert(size == sizeof(MPIDI_Win_control_t)); + const MPIDI_Win_control_t *control = (const MPIDI_Win_control_t *)_control; + pami_task_t senderrank = PAMIX_Endpoint_query(sender); + + switch (control->type) + { + case MPIDI_WIN_MSGTYPE_LOCKREQ: + case MPIDI_WIN_MSGTYPE_LOCKALLREQ: + MPIDI_WinLockReq_proc(context, control, senderrank); + break; + case MPIDI_WIN_MSGTYPE_LOCKACK: + case MPIDI_WIN_MSGTYPE_LOCKALLACK: + MPIDI_WinLockAck_proc(context, control, senderrank); + break; + case MPIDI_WIN_MSGTYPE_UNLOCK: + case MPIDI_WIN_MSGTYPE_UNLOCKALL: + MPIDI_WinUnlock_proc(context, control, senderrank); + break; + case MPIDI_WIN_MSGTYPE_COMPLETE: + MPIDI_WinComplete_proc(context, control, senderrank); + break; + case MPIDI_WIN_MSGTYPE_POST: + MPIDI_WinPost_proc(context, control, senderrank); + break; + + default: + fprintf(stderr, "Bad win-control type: 0x%08x %d\n", + control->type, + control->type); + MPID_abort(); + } + + MPIDI_Progress_signal(); +} diff --git a/pool/shard004/C/0100001_mt76x8-usb-phy.c b/pool/shard004/C/0100001_mt76x8-usb-phy.c new file mode 100644 index 0000000000000000000000000000000000000000..4c0818f6e8da3588985e1ed4f39bbf33fdaf5b31 --- /dev/null +++ b/pool/shard004/C/0100001_mt76x8-usb-phy.c @@ -0,0 +1,252 @@ +// SPDX-License-Identifier: GPL-2.0+ +/* + * Copyright (C) 2019 Stefan Roese + * + * Derived from linux/drivers/phy/ralink/phy-ralink-usb.c + * Copyright (C) 2017 John Crispin + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#define OFS_U2_PHY_AC0 0x800 +#define USBPLL_FBDIV_S 16 +#define USBPLL_FBDIV_M GENMASK(22, 16) +#define BG_TRIM_S 8 +#define BG_TRIM_M GENMASK(11, 8) +#define BG_RBSEL_S 6 +#define BG_RBSEL_M GENMASK(7, 6) +#define BG_RASEL_S 4 +#define BG_RASEL_M GENMASK(5, 4) +#define BGR_DIV_S 2 +#define BGR_DIV_M GENMASK(3, 2) +#define CHP_EN BIT(1) + +#define OFS_U2_PHY_AC1 0x804 +#define VRT_VREF_SEL_S 28 +#define VRT_VREF_SEL_M GENMASK(30, 28) +#define TERM_VREF_SEL_S 24 +#define TERM_VREF_SEL_M GENMASK(26, 24) +#define USBPLL_RSVD BIT(4) +#define USBPLL_ACCEN BIT(3) +#define USBPLL_LF BIT(2) + +#define OFS_U2_PHY_AC2 0x808 + +#define OFS_U2_PHY_ACR0 0x810 +#define HSTX_SRCAL_EN BIT(23) +#define HSTX_SRCTRL_S 16 +#define HSTX_SRCTRL_M GENMASK(18, 16) + +#define OFS_U2_PHY_ACR3 0x81C +#define HSTX_DBIST_S 28 +#define HSTX_DBIST_M GENMASK(31, 28) +#define HSRX_BIAS_EN_SEL_S 20 +#define HSRX_BIAS_EN_SEL_M GENMASK(21, 20) + +#define OFS_U2_PHY_DCR0 0x860 +#define PHYD_RESERVE_S 8 +#define PHYD_RESERVE_M GENMASK(23, 8) +#define CDR_FILT_S 0 +#define CDR_FILT_M GENMASK(3, 0) + +#define OFS_U2_PHY_DTM0 0x868 +#define FORCE_USB_CLKEN BIT(25) + +#define OFS_FM_CR0 0xf00 +#define FREQDET_EN BIT(24) +#define CYCLECNT_S 0 +#define CYCLECNT_M GENMASK(23, 0) + +#define OFS_FM_MONR0 0xf0c + +#define OFS_FM_MONR1 0xf10 +#define FRCK_EN BIT(8) + +#define U2_SR_COEF_7628 32 + +struct mt76x8_usb_phy { + void __iomem *base; + struct clk cg; /* for clock gating */ + struct reset_ctl rst_phy; +}; + +static void phy_w32(struct mt76x8_usb_phy *phy, u32 reg, u32 val) +{ + writel(val, phy->base + reg); +} + +static u32 phy_r32(struct mt76x8_usb_phy *phy, u32 reg) +{ + return readl(phy->base + reg); +} + +static void phy_rmw32(struct mt76x8_usb_phy *phy, u32 reg, u32 clr, u32 set) +{ + clrsetbits_32(phy->base + reg, clr, set); +} + +static void mt76x8_usb_phy_init(struct mt76x8_usb_phy *phy) +{ + phy_r32(phy, OFS_U2_PHY_AC2); + phy_r32(phy, OFS_U2_PHY_ACR0); + phy_r32(phy, OFS_U2_PHY_DCR0); + + phy_w32(phy, OFS_U2_PHY_DCR0, + (0xffff << PHYD_RESERVE_S) | (2 << CDR_FILT_S)); + phy_r32(phy, OFS_U2_PHY_DCR0); + + phy_w32(phy, OFS_U2_PHY_DCR0, + (0x5555 << PHYD_RESERVE_S) | (2 << CDR_FILT_S)); + phy_r32(phy, OFS_U2_PHY_DCR0); + + phy_w32(phy, OFS_U2_PHY_DCR0, + (0xaaaa << PHYD_RESERVE_S) | (2 << CDR_FILT_S)); + phy_r32(phy, OFS_U2_PHY_DCR0); + + phy_w32(phy, OFS_U2_PHY_DCR0, + (4 << PHYD_RESERVE_S) | (2 << CDR_FILT_S)); + phy_r32(phy, OFS_U2_PHY_DCR0); + + phy_w32(phy, OFS_U2_PHY_AC0, + (0x48 << USBPLL_FBDIV_S) | (8 << BG_TRIM_S) | + (1 << BG_RBSEL_S) | (2 << BG_RASEL_S) | (2 << BGR_DIV_S) | + CHP_EN); + + phy_w32(phy, OFS_U2_PHY_AC1, + (4 << VRT_VREF_SEL_S) | (4 << TERM_VREF_SEL_S) | USBPLL_RSVD | + USBPLL_ACCEN | USBPLL_LF); + + phy_w32(phy, OFS_U2_PHY_ACR3, + (12 << HSTX_DBIST_S) | (2 << HSRX_BIAS_EN_SEL_S)); + + phy_w32(phy, OFS_U2_PHY_DTM0, FORCE_USB_CLKEN); +} + +static void mt76x8_usb_phy_sr_calibrate(struct mt76x8_usb_phy *phy) +{ + u32 fmout, tmp = 4; + int i; + + /* Enable HS TX SR calibration */ + phy_rmw32(phy, OFS_U2_PHY_ACR0, 0, HSTX_SRCAL_EN); + mdelay(1); + + /* Enable free run clock */ + phy_rmw32(phy, OFS_FM_MONR1, 0, FRCK_EN); + + /* Set cycle count = 0x400 */ + phy_rmw32(phy, OFS_FM_CR0, CYCLECNT_M, 0x400 << CYCLECNT_S); + + /* Enable frequency meter */ + phy_rmw32(phy, OFS_FM_CR0, 0, FREQDET_EN); + + /* Wait for FM detection done, set timeout to 10ms */ + for (i = 0; i < 10; i++) { + fmout = phy_r32(phy, OFS_FM_MONR0); + + if (fmout) + break; + + mdelay(1); + } + + /* Disable frequency meter */ + phy_rmw32(phy, OFS_FM_CR0, FREQDET_EN, 0); + + /* Disable free run clock */ + phy_rmw32(phy, OFS_FM_MONR1, FRCK_EN, 0); + + /* Disable HS TX SR calibration */ + phy_rmw32(phy, OFS_U2_PHY_ACR0, HSTX_SRCAL_EN, 0); + mdelay(1); + + if (fmout) { + /* + * set reg = (1024 / FM_OUT) * 25 * 0.028 + * (round to the nearest digits) + */ + tmp = (((1024 * 25 * U2_SR_COEF_7628) / fmout) + 500) / 1000; + } + + phy_rmw32(phy, OFS_U2_PHY_ACR0, HSTX_SRCTRL_M, + (tmp << HSTX_SRCTRL_S) & HSTX_SRCTRL_M); +} + +static int mt76x8_usb_phy_power_on(struct phy *_phy) +{ + struct mt76x8_usb_phy *phy = dev_get_priv(_phy->dev); + + clk_enable(&phy->cg); + + reset_deassert(&phy->rst_phy); + + /* + * The SDK kernel had a delay of 100ms. however on device + * testing showed that 10ms is enough + */ + mdelay(10); + + mt76x8_usb_phy_init(phy); + mt76x8_usb_phy_sr_calibrate(phy); + + return 0; +} + +static int mt76x8_usb_phy_power_off(struct phy *_phy) +{ + struct mt76x8_usb_phy *phy = dev_get_priv(_phy->dev); + + clk_disable(&phy->cg); + + reset_assert(&phy->rst_phy); + + return 0; +} + +static int mt76x8_usb_phy_probe(struct udevice *dev) +{ + struct mt76x8_usb_phy *phy = dev_get_priv(dev); + int ret; + + phy->base = dev_read_addr_ptr(dev); + if (!phy->base) + return -EINVAL; + + /* clock gate */ + ret = clk_get_by_name(dev, "cg", &phy->cg); + if (ret) + return ret; + + ret = reset_get_by_name(dev, "phy", &phy->rst_phy); + if (ret) + return ret; + + return 0; +} + +static struct phy_ops mt76x8_usb_phy_ops = { + .power_on = mt76x8_usb_phy_power_on, + .power_off = mt76x8_usb_phy_power_off, +}; + +static const struct udevice_id mt76x8_usb_phy_ids[] = { + { .compatible = "mediatek,mt7628-usbphy" }, + { } +}; + +U_BOOT_DRIVER(mt76x8_usb_phy) = { + .name = "mt76x8_usb_phy", + .id = UCLASS_PHY, + .of_match = mt76x8_usb_phy_ids, + .ops = &mt76x8_usb_phy_ops, + .probe = mt76x8_usb_phy_probe, + .priv_auto_alloc_size = sizeof(struct mt76x8_usb_phy), +}; diff --git a/pool/shard004/C/0100002_screen.c b/pool/shard004/C/0100002_screen.c new file mode 100644 index 0000000000000000000000000000000000000000..b9214ff6a49fcf0d6ce635f9f9b5679e2932edb1 --- /dev/null +++ b/pool/shard004/C/0100002_screen.c @@ -0,0 +1,140 @@ +/* + * Copyright (c) 2012, 2014, 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. + */ + +#if (defined(ANDROID_NDK) && defined(DALVIK_VM)) + +#include "LensCommon.h" +#include "../../wm/LensWindowManager.h" +#include "dalvikInput.h" + +static NativeScreen localScreen; +static int windowIndex = 1; + +NativeScreen lens_screen_initialize(JNIEnv *env) { + + GLASS_LOG_FINEST("Android/Lens screen initialize"); + if (localScreen) { + free(localScreen); + } + ANativeWindow *androidWindow = android_getNativeWindow(env); + if (!androidWindow) { + return 0; + } + localScreen = (NativeScreen)malloc(sizeof(struct _NativeScreen)); + int32_t width = ANativeWindow_getWidth(androidWindow); + int32_t height = ANativeWindow_getHeight(androidWindow); + localScreen->width = width; + localScreen->height = height; + localScreen->visibleWidth = width; + localScreen->visibleHeight = height; + localScreen->visibleX = 0; + localScreen->visibleY = 0; + localScreen->x = 0; + localScreen->y = 0; + localScreen->depth = 24; //????? Samsung has 16 + + // convert pixels/mm to pixels/inch + localScreen->resolutionX = 100; + localScreen->resolutionY = 100; + + GLASS_LOG_FINEST("Screen [%d, %d]", width, height); + return localScreen; +} + +jboolean glass_application_initialize(JNIEnv *env) { + //nothing to do + return JNI_TRUE; +} + +jboolean glass_window_setAlpha(JNIEnv *env, NativeWindow window, float alpha) { + window->alpha = alpha; + lens_wm_repaint(env, window); + return JNI_TRUE; +} + +LensResult glass_view_PlatformViewData_create(NativeView view) { + view->data = NULL; + return LENS_OK; +} + +LensResult glass_view_PlatformViewRelease(JNIEnv *env, NativeView view) { + // No data to free + return LENS_OK; +} + +LensResult glass_window_PlatformWindowData_create(JNIEnv *env, + NativeWindow window) { + + window->id = windowIndex++; + window->data = NULL; //no platfrom specific data + + return LENS_OK; +} + +LensResult glass_window_PlatformWindowRelease(JNIEnv *env, NativeWindow window) { + // No data to free + return LENS_OK; +} + +void *glass_window_getPlatformWindow(JNIEnv *env, NativeWindow window) { + return android_getNativeWindow(env); +} + +void lens_platform_shutdown(JNIEnv *env) { + lens_input_shutdown(env); +} + +void glass_screen_clear() { + // NOOP +} + +void glass_pixel_attachIntBuffer(JNIEnv *env, jint *src, + NativeWindow window, + jint width, jint height, int offset) { + GLASS_LOG_FINE("androidScreen: glass_pixel_attachIntBuffer not implemented!"); +} + +jboolean glass_screen_capture(jint x, + jint y, + jint width, + jint height, + jint *pixels) { + GLASS_LOG_FINE("androidScreen: glass_screen_capture not implemented!"); +} + +LensResult lens_platform_windowMinimize(JNIEnv *env, + NativeWindow window, + jboolean toMinimize) { + //noop for fb + return LENS_OK; +} + +LensResult lens_platform_windowSetVisible(JNIEnv *env, + NativeWindow window, + jboolean visible) { + return LENS_OK; +} + +#endif /* ANDROID_NDK */ diff --git a/pool/shard004/C/0100004_probe.c b/pool/shard004/C/0100004_probe.c new file mode 100644 index 0000000000000000000000000000000000000000..4568861bc95507fab39629e223860d574bd6271e --- /dev/null +++ b/pool/shard004/C/0100004_probe.c @@ -0,0 +1,48 @@ + +// just testing send and receive + +#include "tests.h" + +int main( int argc, char **argv ) +{ + int i, n; + int var; + + MPI_Init( &argc, &argv ); + + n = GET_N(); + if( n < 2 ) { + TESTS_ERROR( 1, "Use this with at least 2 processes!" ); + } + + if( GET_ID() == 0 ) { + var = 666; + TESTS_MPI_SEND( &var, 1, MPI_INT, GET_ID()+1 ); + } + else if( GET_ID() < GET_N()-1 ) { + int size; + MPI_Status status; + MPI_Probe( GET_ID()-1, MPI_ANY_TAG, MPI_COMM_WORLD, &status ); + MPI_Get_count( &status, MPI_BYTE, &size ); + SPD_DEBUG( "Gonna receive %d bytes", size ); + + TESTS_MPI_RECEIVE( &var, 1, MPI_INT, GET_ID()-1 ); + TESTS_MPI_SEND( &var, 1, MPI_INT, GET_ID()+1 ); + } + else /* GET_ID() == GET_N()-1 */ { + int size; + MPI_Status status; + MPI_Probe( GET_ID()-1, MPI_ANY_TAG, MPI_COMM_WORLD, &status ); + MPI_Get_count( &status, MPI_BYTE, &size ); + SPD_DEBUG( "Gonna receive %d bytes", size ); + + TESTS_MPI_RECEIVE( &var, 1, MPI_INT, GET_ID()-1 ); + } + + SPD_DEBUG( "Got %d", var ); + + MPI_Finalize( ); + return 0; +} + + diff --git a/pool/shard004/C/0100009_instr_size.c b/pool/shard004/C/0100009_instr_size.c new file mode 100644 index 0000000000000000000000000000000000000000..2982b8d661e775dea369c0aa9457a904ac19d4f8 --- /dev/null +++ b/pool/shard004/C/0100009_instr_size.c @@ -0,0 +1,138 @@ +/* + * CDDL HEADER START + * + * The contents of this file are subject to the terms of the + * Common Development and Distribution License, Version 1.0 only + * (the "License"). You may not use this file except in compliance + * with the License. + * + * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE + * or http://www.opensolaris.org/os/licensing. + * See the License for the specific language governing permissions + * and limitations under the License. + * + * When distributing Covered Code, include this CDDL HEADER in each + * file and include the License file at usr/src/OPENSOLARIS.LICENSE. + * If applicable, add the following below this CDDL HEADER, with the + * fields enclosed by brackets "[]" replaced with your own identifying + * information: Portions Copyright [yyyy] [name of copyright owner] + * + * CDDL HEADER END + */ +/* + * Copyright 2005 Sun Microsystems, Inc. All rights reserved. + * Use is subject to license terms. + */ + +/* Copyright (c) 1988 AT&T */ +/* All Rights Reserved */ + + +/* + * #pragma ident "@(#)instr_size.c 1.14 05/07/08 SMI" + */ + +#include +#include + +#include + +/* + * This subsystem (with the minor exception of the instr_size() function) is + * is called from DTrace probe context. This imposes several requirements on + * the implementation: + * + * 1. External subsystems and functions may not be referenced. The one current + * exception is for cmn_err, but only to signal the detection of table + * errors. Assuming the tables are correct, no combination of input is to + * trigger a cmn_err call. + * + * 2. These functions can't be allowed to be traced. To prevent this, + * all functions in the probe path (everything except instr_size()) must + * have names that begin with "dtrace_". + */ + +typedef enum dis_isize { + DIS_ISIZE_INSTR, + DIS_ISIZE_OPERAND +} dis_isize_t; + + +/* + * get a byte from instruction stream + */ +static int +dtrace_dis_get_byte(void *p) +{ + int ret; + uchar_t **instr = p; + + ret = **instr; + *instr += 1; + + return (ret); +} + +/* + * Returns either the size of a given instruction, in bytes, or the size of that + * instruction's memory access (if any), depending on the value of `which'. + * If a programming error in the tables is detected, the system will panic to + * ease diagnosis. Invalid instructions will not be flagged. They will appear + * to have an instruction size between 1 and the actual size, and will be + * reported as having no memory impact. + */ +/* ARGSUSED2 */ +static int +dtrace_dis_isize(uchar_t *instr, dis_isize_t which, model_t model, int *rmindex) +{ + int sz; + dis86_t x; + uint_t mode = SIZE32; + + mode = (model == DATAMODEL_LP64) ? SIZE64 : SIZE32; + + x.d86_data = (void **)&instr; + x.d86_get_byte = dtrace_dis_get_byte; + x.d86_check_func = NULL; + + if (dtrace_disx86(&x, mode) != 0) + return (-1); + + if (which == DIS_ISIZE_INSTR) + sz = x.d86_len; /* length of the instruction */ + else + sz = x.d86_memsize; /* length of memory operand */ + + if (rmindex != NULL) + *rmindex = x.d86_rmindex; + return (sz); +} + +int +dtrace_instr_size_isa(uchar_t *instr, model_t model, int *rmindex) +{ + return (dtrace_dis_isize(instr, DIS_ISIZE_INSTR, model, rmindex)); +} + +int +dtrace_instr_size(uchar_t *instr) +{ + return (dtrace_dis_isize(instr, DIS_ISIZE_INSTR, DATAMODEL_NATIVE, + NULL)); +} + +#if !defined(__APPLE__) +/*ARGSUSED*/ +int +instr_size(struct regs *rp, caddr_t *addrp, enum seg_rw rw) +{ + uchar_t instr[16]; /* maximum size instruction */ + caddr_t pc = (caddr_t)rp->r_pc; + + (void) copyin_nowatch(pc, (caddr_t)instr, sizeof (instr)); + + return (dtrace_dis_isize(instr, + rw == S_EXEC ? DIS_ISIZE_INSTR : DIS_ISIZE_OPERAND, + curproc->p_model, NULL)); +} +#endif /* __APPLE__ */ diff --git a/pool/shard004/C/0100021_ipcp-cstagg-1.c b/pool/shard004/C/0100021_ipcp-cstagg-1.c new file mode 100644 index 0000000000000000000000000000000000000000..4d64ea7d4cec5311dcb61454c322c367a277edde --- /dev/null +++ b/pool/shard004/C/0100021_ipcp-cstagg-1.c @@ -0,0 +1,42 @@ +/* { dg-do compile } */ +/* { dg-options "-O3 -fdump-ipa-cp-details" } */ + +typedef struct S +{ + int add_offset; + int (*call)(int); +} S; + +extern const S *gs; + +static int __attribute__((noinline)) +bar (const S *f, int x) +{ + x = f->call(x); + x = f->call(x); + x = f->call(x); + gs = f; + return x; +} + +static int +sq (int x) +{ + return x * x; +} + +static const S s = {16, sq}; + +int +g (int x) +{ + return bar (&s, x); +} + +int +obfuscate (int x) +{ + return bar ((S *) 0, x); +} + +/* { dg-final { scan-ipa-dump-times "Discovered an indirect call to a known target" 3 "cp" } } */ diff --git a/pool/shard004/C/0100022_rb-uri-dialog.c b/pool/shard004/C/0100022_rb-uri-dialog.c new file mode 100644 index 0000000000000000000000000000000000000000..00f02e3dd795ed7bc96098cae32a54ae3c069763 --- /dev/null +++ b/pool/shard004/C/0100022_rb-uri-dialog.c @@ -0,0 +1,275 @@ +/* -*- Mode: C; tab-width: 8; indent-tabs-mode: t; c-basic-offset: 8 -*- + * + * Copyright (C) 2005 Renato Araujo Oliveira Filho - INdT + * + * 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. + * + * The Rhythmbox authors hereby grant permission for non-GPL compatible + * GStreamer plugins to be used and distributed together with GStreamer + * and Rhythmbox. This permission is above and beyond the permissions granted + * by the GPL license by which Rhythmbox is covered. 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. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + */ + +#include "config.h" + +#include +#include + +#include +#include + +#include "rb-uri-dialog.h" +#include "rb-builder-helpers.h" +#include "rb-dialog.h" +#include "rb-debug.h" + +/** + * SECTION:rb-uri-dialog + * @short_description: simple URI entry dialog + * @include: rb-uri-dialog.h + * + * A simple dialog used to request a single URI from the user. + */ + +static void rb_uri_dialog_class_init (RBURIDialogClass *klass); +static void rb_uri_dialog_init (RBURIDialog *dialog); +static void rb_uri_dialog_response_cb (GtkDialog *gtkdialog, + int response_id, + RBURIDialog *dialog); +static void rb_uri_dialog_text_changed (GtkEditable *buffer, + RBURIDialog *dialog); +static void rb_uri_dialog_set_property (GObject *object, + guint prop_id, + const GValue *value, + GParamSpec *pspec); +static void rb_uri_dialog_get_property (GObject *object, + guint prop_id, + GValue *value, + GParamSpec *pspec); + +struct RBURIDialogPrivate +{ + GtkWidget *label; + GtkWidget *url; + GtkWidget *okbutton; + GtkWidget *cancelbutton; +}; + +#define RB_URI_DIALOG_GET_PRIVATE(o) (G_TYPE_INSTANCE_GET_PRIVATE ((o), RB_TYPE_URI_DIALOG, RBURIDialogPrivate)) + +enum +{ + LOCATION_ADDED, + LAST_SIGNAL +}; + +enum +{ + PROP_0, + PROP_LABEL +}; + +static guint rb_uri_dialog_signals [LAST_SIGNAL] = { 0 }; + +G_DEFINE_TYPE (RBURIDialog, rb_uri_dialog, GTK_TYPE_DIALOG) + +static void +rb_uri_dialog_class_init (RBURIDialogClass *klass) +{ + GObjectClass *object_class = G_OBJECT_CLASS (klass); + + object_class->set_property = rb_uri_dialog_set_property; + object_class->get_property = rb_uri_dialog_get_property; + + /** + * RBURIDialog:label: + * + * The label displayed in the dialog. + */ + g_object_class_install_property (object_class, + PROP_LABEL, + g_param_spec_string ("label", + "label", + "label", + "", + G_PARAM_READWRITE | G_PARAM_CONSTRUCT_ONLY)); + + /** + * RBURIDialog::location-added: + * @dialog: the #RBURIDialog + * @uri: URI entered + * + * Emitted when the user has entered a URI into the dialog. + */ + rb_uri_dialog_signals [LOCATION_ADDED] = + g_signal_new ("location-added", + G_OBJECT_CLASS_TYPE (object_class), + G_SIGNAL_RUN_LAST, + G_STRUCT_OFFSET (RBURIDialogClass, location_added), + NULL, NULL, + g_cclosure_marshal_VOID__STRING, + G_TYPE_NONE, + 1, + G_TYPE_STRING); + + g_type_class_add_private (klass, sizeof (RBURIDialogPrivate)); +} + +static void +rb_uri_dialog_init (RBURIDialog *dialog) +{ + GtkWidget *content_area; + GtkBuilder *builder; + + /* create the dialog and some buttons forward - close */ + dialog->priv = RB_URI_DIALOG_GET_PRIVATE (dialog); + + g_signal_connect_object (G_OBJECT (dialog), + "response", + G_CALLBACK (rb_uri_dialog_response_cb), + dialog, 0); + + content_area = gtk_dialog_get_content_area (GTK_DIALOG (dialog)); + + gtk_dialog_set_has_separator (GTK_DIALOG (dialog), FALSE); + gtk_container_set_border_width (GTK_CONTAINER (dialog), 5); + gtk_box_set_spacing (GTK_BOX (content_area), 2); + + dialog->priv->cancelbutton = gtk_dialog_add_button (GTK_DIALOG (dialog), + GTK_STOCK_CANCEL, + GTK_RESPONSE_CANCEL); + dialog->priv->okbutton = gtk_dialog_add_button (GTK_DIALOG (dialog), + GTK_STOCK_ADD, + GTK_RESPONSE_OK); + gtk_dialog_set_default_response (GTK_DIALOG (dialog), GTK_RESPONSE_OK); + + builder = rb_builder_load ("uri-new.ui", dialog); + + gtk_container_add (GTK_CONTAINER (content_area), + GTK_WIDGET (gtk_builder_get_object (builder, "newuri"))); + + /* get the widgets from the GtkBuilder */ + dialog->priv->label = GTK_WIDGET (gtk_builder_get_object (builder, "label")); + dialog->priv->url = GTK_WIDGET (gtk_builder_get_object (builder, "txt_url")); + gtk_entry_set_activates_default (GTK_ENTRY (dialog->priv->url), TRUE); + + g_signal_connect_object (G_OBJECT (dialog->priv->url), + "changed", + G_CALLBACK (rb_uri_dialog_text_changed), + dialog, 0); + + /* default focus */ + gtk_widget_grab_focus (dialog->priv->url); + + /* FIXME */ + gtk_widget_set_sensitive (dialog->priv->okbutton, FALSE); + + g_object_unref (builder); +} + +static void +rb_uri_dialog_set_property (GObject *object, + guint prop_id, + const GValue *value, + GParamSpec *pspec) +{ + RBURIDialog *dialog = RB_URI_DIALOG (object); + + switch (prop_id) { + case PROP_LABEL: + gtk_label_set_text (GTK_LABEL (dialog->priv->label), g_value_get_string (value)); + break; + default: + G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec); + break; + } +} + +static void +rb_uri_dialog_get_property (GObject *object, + guint prop_id, + GValue *value, + GParamSpec *pspec) +{ + RBURIDialog *dialog = RB_URI_DIALOG (object); + + switch (prop_id) { + case PROP_LABEL: + g_value_set_string (value, gtk_label_get_text (GTK_LABEL (dialog->priv->label))); + break; + default: + G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec); + break; + } +} + +/** + * rb_uri_dialog_new: + * @title: Window title for the dialog + * @label: Label to display in the dialog + * + * Creates a URI entry dialog. + * + * Returns: URI dialog instance. + */ +GtkWidget * +rb_uri_dialog_new (const char *title, const char *label) +{ + RBURIDialog *dialog; + + dialog = g_object_new (RB_TYPE_URI_DIALOG, + "title", title, + "label", label, + NULL); + return GTK_WIDGET (dialog); +} + +static void +rb_uri_dialog_response_cb (GtkDialog *gtkdialog, + int response_id, + RBURIDialog *dialog) +{ + char *valid_url; + char *str; + + if (response_id != GTK_RESPONSE_OK) + return; + + str = gtk_editable_get_chars (GTK_EDITABLE (dialog->priv->url), 0, -1); + valid_url = g_strstrip (str); + + g_signal_emit (dialog, rb_uri_dialog_signals [LOCATION_ADDED], 0, valid_url); + + g_free (str); + + gtk_widget_hide (GTK_WIDGET (gtkdialog)); +} + +static void +rb_uri_dialog_text_changed (GtkEditable *buffer, + RBURIDialog *dialog) +{ + char *text = gtk_editable_get_chars (buffer, 0, -1); + gboolean has_text = ((text != NULL) && (*text != 0)); + + g_free (text); + + gtk_widget_set_sensitive (dialog->priv->okbutton, has_text); +} + diff --git a/pool/shard004/C/0100023_g_fastboot.c b/pool/shard004/C/0100023_g_fastboot.c new file mode 100644 index 0000000000000000000000000000000000000000..850464d30be005bea308474d07432961ede96dcc --- /dev/null +++ b/pool/shard004/C/0100023_g_fastboot.c @@ -0,0 +1,236 @@ +/* Ingenic Fastboot Command Explain Gadget Driver + * + * Copyright (C) 2013 Ingenic Semiconductor Co., LTD. + * Sun Jiwei + * + * 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 "gadget_chips.h" +#include "composite.c" +#if 0 +//#include +//#include +//#include "f_dfu.h" + +/* + * One needs to define the following: + * CONFIG_G_FASTBOOT_VENDOR_NUM + * CONFIG_G_FASTBOOT_PRODUCT_NUM + * CONFIG_G_FASTBOOT_MANUFACTURER + * at e.g. ./include/configs/.h + */ +#endif + +#define STRING_MANUFACTURER 25 +#define STRING_PRODUCT 2 +#define STRING_USBDOWN 0 +#define CONFIG_USBDOWNLOADER 1 + +#define DRIVER_VERSION "usb_fastboot 1.0" + +static const char shortname[] = "usb_"; +static const char product[] = "Android 1.0"; +static const char manufacturer[] = "Google, Ingenic";//CONFIG_G_FASTBOOT_MANUFACTURER; +static const char serialnum[] = "0123456789"; + +static struct usb_device_descriptor device_desc = { + .bLength = sizeof device_desc, + .bDescriptorType = USB_DT_DEVICE, + + .bcdUSB = __constant_cpu_to_le16(0x0200), + .bDeviceClass = USB_CLASS_VENDOR_SPEC, + .bDeviceSubClass = 0x42, /*0x02:CDC-modem , 0x00:CDC-serial*/ + .bDeviceProtocol = 0x03, + .bMaxPacketSize0 = 0x40, + + .idVendor = __constant_cpu_to_le16(CONFIG_G_FASTBOOT_VENDOR_NUM), + .idProduct = __constant_cpu_to_le16(CONFIG_G_FASTBOOT_PRODUCT_NUM), + .bcdDevice = __constant_cpu_to_le16(0x0100), + .iManufacturer = 1, + .iProduct = STRING_PRODUCT, + .bNumConfigurations = 1, +}; + +/* static strings, in UTF-8 */ +static struct usb_string g_fastboot_string_defs[] = { + { 0, manufacturer, }, + { 1, product, }, + { 2, serialnum, }, + { } /* end of list */ +}; + +static struct usb_gadget_strings g_fastboot_string_tab = { + .language = 0x0409, /* en-us */ + .strings = g_fastboot_string_defs, +}; + +static struct usb_gadget_strings *g_fastboot_composite_strings[] = { + &g_fastboot_string_tab, + NULL, +}; + +static int g_fastboot_unbind(struct usb_composite_dev *cdev) +{ + struct usb_gadget *gadget = cdev->gadget; + + debug("%s: calling usb_gadget_disconnect for " + "controller '%s'\n", shortname, gadget->name); + usb_gadget_disconnect(gadget); + + return 0; +} + +static int g_fastboot_do_config(struct usb_configuration *c) +{ + const char *s = c->cdev->driver->name; + int ret = -1; + + debug("%s: configuration: 0x%p composite dev: 0x%p\n", + __func__, c, c->cdev); + + printf("GADGET DRIVER: %s\n", s); + if (!strcmp(s, "usb_fastboot")) + ret = fastboot_add(c); + + return ret; +} + +static int g_fastboot_config_register(struct usb_composite_dev *cdev) +{ + static struct usb_configuration config = { + .label = "usb_fastbootoad", + + .bmAttributes = USB_CONFIG_ATT_ONE | USB_CONFIG_ATT_BATTERY, +// .bmAttributes = USB_CONFIG_ATT_ONE, + .bMaxPower = 0x80, + .bConfigurationValue = CONFIG_USBDOWNLOADER, + .iConfiguration = STRING_USBDOWN, + + .bind = g_fastboot_do_config, + }; + + return usb_add_config(cdev, &config); +} + +__weak +int g_fastboot_bind_fixup(struct usb_device_descriptor *dev) +{ + return 0; +} + +static int g_fastboot_bind(struct usb_composite_dev *cdev) +{ + struct usb_gadget *gadget = cdev->gadget; + int id, ret; + int gcnum; + + debug("%s: gadget: 0x%p cdev: 0x%p\n", __func__, gadget, cdev); + + id = usb_string_id(cdev); + + if (id < 0) + return id; + g_fastboot_string_defs[0].id = id; + device_desc.iManufacturer = id; + + id = usb_string_id(cdev); + if (id < 0) + return id; + + g_fastboot_string_defs[1].id = id; + device_desc.iProduct = id; + + id = usb_string_id(cdev); + if (id < 0) + return id; + g_fastboot_string_defs[2].id = id; + device_desc.iSerialNumber = id; + + g_fastboot_bind_fixup(&device_desc); + ret = g_fastboot_config_register(cdev); + if (ret) + goto error; + + gcnum = usb_gadget_controller_number(gadget); + + debug("gcnum: %d\n", gcnum); + if (gcnum >= 0) + device_desc.bcdDevice = cpu_to_le16(0x0200 + gcnum); + else { + debug("%s: controller '%s' not recognized\n", + shortname, gadget->name); + device_desc.bcdDevice = __constant_cpu_to_le16(0x9999); + } + + debug("%s: calling usb_gadget_connect for " + "controller '%s'\n", shortname, gadget->name); + usb_gadget_connect(gadget); + + return 0; + + error: + g_fastboot_unbind(cdev); + return -ENOMEM; +} + +static struct usb_composite_driver g_fastboot_driver = { + .name = NULL, + .dev = &device_desc, + .strings = g_fastboot_composite_strings, + + .bind = g_fastboot_bind, + .unbind = g_fastboot_unbind, +}; + +int g_fastboot_register(const char *type) +{ + /* We only allow "dfu" atm, so 3 should be enough */ + static char name[sizeof(shortname) + 8]; + int ret; + + if (!strcmp(type, "fastboot")) { + strcpy(name, shortname); + strcat(name, type); + } else { + printf("%s: unknown command: %s\n", __func__, type); + return -EINVAL; + } + + g_fastboot_driver.name = name; + + debug("%s: g_fastboot_driver.name: %s\n", __func__, g_fastboot_driver.name); + ret = usb_composite_register(&g_fastboot_driver); + + if (ret) { + printf("%s: failed!, error: %d\n", __func__, ret); + return ret; + } + + return 0; +} + +void g_fastboot_unregister(void) +{ + usb_composite_unregister(&g_fastboot_driver); +} diff --git a/pool/shard004/C/0100025_vec-strir_p-3.c b/pool/shard004/C/0100025_vec-strir_p-3.c new file mode 100644 index 0000000000000000000000000000000000000000..70ab0f61f1840be319220c4cb1eec37902caeccc --- /dev/null +++ b/pool/shard004/C/0100025_vec-strir_p-3.c @@ -0,0 +1,41 @@ +/* { dg-do run { target { power10_hw } } } */ +/* { dg-do link { target { ! power10_hw } } } */ +/* { dg-require-effective-target power10_ok } */ +/* { dg-options "-mdejagnu-cpu=power10" } */ + +#include + +extern void abort (void); + +/* Vector string isolate right-justified on array of signed char. */ +int +sirj_p (vector signed char arg) +{ + return vec_strir_p (arg); +} + +int main (int argc, char *argv []) +{ + vector signed char input1 = + { 0x1, 0x2, 0xf3, 0x4, 0x5, 0x6, 0x7, 0x8, + 0x9, 0xa, 0xb, 0xc, 0xd, 0xe2, 0xf, 0x11 }; + vector signed char input2 = + { 0x1, 0x2, 0xf3, 0x4, 0x5, 0x6, 0x7, 0x8, + 0x9, 0xa, 0xb, 0xc, 0xd, 0x0, 0xf, 0x11 }; + vector signed char input3 = + { 0x1, 0x2, 0xf3, 0x0, 0x5, 0x6, 0x7, 0x8, + 0x9, 0xa, 0xb, 0xc, 0xd, 0xe2, 0x0, 0x11 }; + vector signed char input4 = + { 0x1, 0x2, 0xf3, 0x4, 0x5, 0x6, 0x7, 0x8, + 0x9, 0xa, 0xb, 0xc, 0xd, 0xe2, 0x0, 0x11 }; + + if (sirj_p (input1)) + abort (); + if (!sirj_p (input2)) + abort (); + if (!sirj_p (input3)) + abort (); + if (!sirj_p (input4)) + abort (); + +} diff --git a/pool/shard004/C/0100029_nlua_bkg.c b/pool/shard004/C/0100029_nlua_bkg.c new file mode 100644 index 0000000000000000000000000000000000000000..c426b84a283cae4ae42d2eeee4e6efdb1e59f9c9 --- /dev/null +++ b/pool/shard004/C/0100029_nlua_bkg.c @@ -0,0 +1,130 @@ +/* + * See Licensing and Copyright notice in naev.h + */ + +/** + * @file nlua_bkg.c + * + * @brief Bindings for modifying the space background. + */ + +#include "nlua_bkg.h" + +#include "naev.h" + +#include + +#include "nlua.h" +#include "nluadef.h" +#include "nlua_tex.h" +#include "nlua_col.h" +#include "log.h" +#include "background.h" + + +/* Background methods. */ +static int bkgL_clear( lua_State *L ); +static int bkgL_image( lua_State *L ); +static const luaL_reg bkgL_methods[] = { + { "clear", bkgL_clear }, + { "image", bkgL_image }, + {0,0} +}; /**< Background methods. */ + + + + +/** + * @brief Loads the graphics library. + * + * @param L State to load graphics library into. + * @return 0 on success. + */ +int nlua_loadBackground( lua_State *L, int readonly ) +{ + if (readonly) /* Nothing is read only */ + return 0; + + /* Register the values */ + luaL_register(L, "bkg", bkgL_methods); + + return 0; +} + + +/** + * @brief Lua bindings to interact with the background. + * + * An example would be: + * @code + * @endcode + * + * @luamod bkg + */ + + + +/** + * @brief Clears any backgrounds that may currently be displaying. + * + * @luafunc clear() + */ +static int bkgL_clear( lua_State *L ) +{ + (void) L; + background_clear(); + return 0; +} + + +/** + * @brief Adds a background image. + * + * If the colour parameter is a boolean it's treated as the foreground parameter instead. + * + * @usage bkg.image( img, 0, 0, 0.1, 1. ) -- Adds the image without scaling that moves at 0.1 the player speed + * @usage bkg.image( img, 0, 0, 0.1, 1., true ) -- Now on the foreground + * @usage bkg.image( img, 0, 0, 0.1, 1., col.new(1,0,0) ) -- Now with colour + * @usage bkg.image( img, 0, 0, 0.1, 1., col.new(1,0,0), true ) -- Now with colour and on the foreground + * + * @luaparam image Image to use. + * @luaparam x X position. + * @luaparam y Y position. + * @luaparam move Fraction of a pixel to move when the player moves one pixel. + * @luaparam scale How much to scale the image. + * @luaparam col Colour to tint image (optional parameter). + * @luaparam foreground Whether or not it should be rendered above the stars (optional parameter ). Defaults to false. + * @luareturn ID of the background. + * @luafunc image( image, x, y, move, scale, col, foreground ) + */ +static int bkgL_image( lua_State *L ) +{ + glTexture *tex; + double x,y, move, scale; + const glColour *col; + unsigned int id; + int foreground; + + /* Parse parameters. */ + tex = luaL_checktex(L,1); + x = luaL_checknumber(L,2); + y = luaL_checknumber(L,3); + move = luaL_checknumber(L,4); + scale = luaL_checknumber(L,5); + if (lua_iscolour(L,6)) { + col = lua_tocolour(L,6); + foreground = lua_toboolean(L,7); + } + else { + col = &cWhite; + foreground = lua_toboolean(L,6); + } + + /* Create image. */ + id = background_addImage( tex, x, y, move, scale, col, foreground ); + lua_pushnumber(L,id); + return 1; +} + + + diff --git a/pool/shard004/C/0100036_sctp_client.c b/pool/shard004/C/0100036_sctp_client.c new file mode 100644 index 0000000000000000000000000000000000000000..454bec91828c195a64c499a56b791c36fea907b3 --- /dev/null +++ b/pool/shard004/C/0100036_sctp_client.c @@ -0,0 +1,206 @@ +/* + SCTP echo client + + Build : gcc -o sctp_client sctp_client.c + + Copyright (C) 2014 Red Hat Inc. + Author Vivek Dasgupta | + + 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 +#include +#include +#include + +#define BUFFSIZE 32000 + + +int debug_on = 0; + +#define debug_print(...) \ + do { if (debug_on) fprintf(stdout, ##__VA_ARGS__); } while (0) + +int main(int argc, char **argv) +{ + + int i,j, pflag, aflag, bflag, errflag=0, sockfd, port; + int len, pid, num_conn, bufsize, rflag, retval; + struct sockaddr_in client; + struct hostent *hp,*gethostbyname(); + char *remote_host; + + while ((i = getopt(argc,argv,"p:n:r:b:d:?")) != -1) + { + switch(i) + { + case 'p': + pflag = 1; + port = atoi(optarg); + break; + case 'n': + aflag = 1; + num_conn = atoi(optarg); + break; + case 'b': + bflag = 1; + bufsize = atoi(optarg); + break; + case 'r': + rflag = 1; + remote_host = optarg; + break; + case 'd': + debug_on = atoi(optarg); + break; + case '?': + errflag = 1; + break; + + } + } + + debug_print(" Params : port %d num_conn %d remote_host %s errflag %d\n", port, num_conn, remote_host, errflag); + + fprintf(stdout,"Initiating %d SCTP associations to %s and sending chunks of %d byte each\n", num_conn, remote_host, bufsize); + + if (errflag || (argc == 1)) + { + usage(argv[0]); + exit(1); + } + + + if (bflag != 1) + bufsize = BUFFSIZE; + + + client.sin_port = htons(port); + client.sin_family = AF_INET; + hp = gethostbyname(remote_host); + if (hp == 0) { + fprintf(stderr,"unknown host %s\n",remote_host); + exit(1); + } + + memcpy((char *)&client.sin_addr,(const char *)hp->h_addr, hp->h_length); + + + for (i=0; i < num_conn; i++) + { + + + pid = fork(); + if (pid < 0) + { + fprintf(stderr,"fork failed, errno = %d\n",errno); + continue; + } + + + if (pid > 0) // parent + { + usleep(10000); + continue; + } // parent + + + if (pid == 0) // child + { + retval = data_tx(&client, bufsize); + } // child + + + } // for loop + + fprintf(stdout, "Done\n"); + return 0; +} //main + +int data_tx(struct sockaddr_in *client, int bufsize) +{ + int rbytes, wbytes, sockfd, retval, i=0, j=0; + char *buf; + + struct linger linger; + int linger_time; + + sockfd = socket(AF_INET,SOCK_STREAM,IPPROTO_SCTP); + if (sockfd < 0) + { + fprintf(stderr,"socket failed\n"); + exit(1); + } + debug_print("socket created - sockfd %d\n", sockfd); + + retval = connect(sockfd,(struct sockaddr *)client,sizeof(struct sockaddr_in)); + if (retval < 0) + { + fprintf(stderr,"connect failed errno %d\n",errno); + } + + + buf = (char *) malloc(bufsize); + + for (i=j; i<(j+30000); i++) + buf[i]=i; + j = i; + + + usleep(10000); + debug_print("connect retval %d\n", retval); + debug_print("Connected to server\n"); + for(;;) + { + + debug_print("writing - buf %s\n\n", buf); + wbytes = write(sockfd, buf, BUFFSIZE); + debug_print("PID %d wrote %d bytes\n", getpid(), wbytes); + + usleep(10000); + + debug_print("reading - buffer\n"); + rbytes = read(sockfd, buf, BUFFSIZE); + debug_print("PID %d read %d bytes\n", getpid(),rbytes); + + sleep(2000); + } + + free(buf); + return 0; +} + + +usage(char *c) +{ + + fprintf(stderr,"usage: %s -p port -n num_conn -r remote_host \n",c); + + fprintf(stderr," -p : portnumber\n"); + fprintf(stderr," -n : num_conn\n"); + fprintf(stderr," -b : bufsize in bytes\n"); + fprintf(stderr," -r : remote_host\n"); + fprintf(stderr," -d : debug 1 or nodebug 0\n"); + +} + diff --git a/pool/shard004/C/0100038_splat-atomic.c b/pool/shard004/C/0100038_splat-atomic.c new file mode 100644 index 0000000000000000000000000000000000000000..f6ed80fb8228e59ab7818e4b2fc0f67386d246cd --- /dev/null +++ b/pool/shard004/C/0100038_splat-atomic.c @@ -0,0 +1,232 @@ +/*****************************************************************************\ + * Copyright (C) 2007-2010 Lawrence Livermore National Security, LLC. + * Copyright (C) 2007 The Regents of the University of California. + * Produced at Lawrence Livermore National Laboratory (cf, DISCLAIMER). + * Written by Brian Behlendorf . + * UCRL-CODE-235197 + * + * This file is part of the SPL, Solaris Porting Layer. + * For details, see . + * + * The SPL is free software; you can 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. + * + * The SPL is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * for more details. + * + * You should have received a copy of the GNU General Public License along + * with the SPL. If not, see . + ***************************************************************************** + * Solaris Porting LAyer Tests (SPLAT) Atomic Tests. +\*****************************************************************************/ + +#include +#include +#include +#include +#include +#include "splat-internal.h" + +#define SPLAT_ATOMIC_NAME "atomic" +#define SPLAT_ATOMIC_DESC "Kernel Atomic Tests" + +#define SPLAT_ATOMIC_TEST1_ID 0x0b01 +#define SPLAT_ATOMIC_TEST1_NAME "64-bit" +#define SPLAT_ATOMIC_TEST1_DESC "Validate 64-bit atomic ops" + +#define SPLAT_ATOMIC_TEST_MAGIC 0x43435454UL +#define SPLAT_ATOMIC_INIT_VALUE 10000000UL + +typedef enum { + SPLAT_ATOMIC_INC_64 = 0, + SPLAT_ATOMIC_DEC_64 = 1, + SPLAT_ATOMIC_ADD_64 = 2, + SPLAT_ATOMIC_SUB_64 = 3, + SPLAT_ATOMIC_ADD_64_NV = 4, + SPLAT_ATOMIC_SUB_64_NV = 5, + SPLAT_ATOMIC_COUNT_64 = 6 +} atomic_op_t; + +typedef struct atomic_priv { + unsigned long ap_magic; + struct file *ap_file; + kmutex_t ap_lock; + wait_queue_head_t ap_waitq; + volatile uint64_t ap_atomic; + volatile uint64_t ap_atomic_exited; + atomic_op_t ap_op; + +} atomic_priv_t; + +static void +splat_atomic_work(void *priv) +{ + atomic_priv_t *ap; + atomic_op_t op; + int i; + + ap = (atomic_priv_t *)priv; + ASSERT(ap->ap_magic == SPLAT_ATOMIC_TEST_MAGIC); + + mutex_enter(&ap->ap_lock); + op = ap->ap_op; + wake_up(&ap->ap_waitq); + mutex_exit(&ap->ap_lock); + + splat_vprint(ap->ap_file, SPLAT_ATOMIC_TEST1_NAME, + "Thread %d successfully started: %lu/%lu\n", op, + (long unsigned)ap->ap_atomic, + (long unsigned)ap->ap_atomic_exited); + + for (i = 0; i < SPLAT_ATOMIC_INIT_VALUE / 10; i++) { + + /* Periodically sleep to mix up the ordering */ + if ((i % (SPLAT_ATOMIC_INIT_VALUE / 100)) == 0) { + splat_vprint(ap->ap_file, SPLAT_ATOMIC_TEST1_NAME, + "Thread %d sleeping: %lu/%lu\n", op, + (long unsigned)ap->ap_atomic, + (long unsigned)ap->ap_atomic_exited); + set_current_state(TASK_INTERRUPTIBLE); + schedule_timeout(HZ / 100); + } + + switch (op) { + case SPLAT_ATOMIC_INC_64: + atomic_inc_64(&ap->ap_atomic); + break; + case SPLAT_ATOMIC_DEC_64: + atomic_dec_64(&ap->ap_atomic); + break; + case SPLAT_ATOMIC_ADD_64: + atomic_add_64(&ap->ap_atomic, 3); + break; + case SPLAT_ATOMIC_SUB_64: + atomic_sub_64(&ap->ap_atomic, 3); + break; + case SPLAT_ATOMIC_ADD_64_NV: + atomic_add_64_nv(&ap->ap_atomic, 5); + break; + case SPLAT_ATOMIC_SUB_64_NV: + atomic_sub_64_nv(&ap->ap_atomic, 5); + break; + default: + PANIC("Undefined op %d\n", op); + } + } + + atomic_inc_64(&ap->ap_atomic_exited); + + splat_vprint(ap->ap_file, SPLAT_ATOMIC_TEST1_NAME, + "Thread %d successfully exited: %lu/%lu\n", op, + (long unsigned)ap->ap_atomic, + (long unsigned)ap->ap_atomic_exited); + + wake_up(&ap->ap_waitq); + thread_exit(); +} + +static int +splat_atomic_test1_cond(atomic_priv_t *ap, int started) +{ + return (ap->ap_atomic_exited == started); +} + +static int +splat_atomic_test1(struct file *file, void *arg) +{ + atomic_priv_t ap; + DEFINE_WAIT(wait); + kthread_t *thr; + int i, rc = 0; + + ap.ap_magic = SPLAT_ATOMIC_TEST_MAGIC; + ap.ap_file = file; + mutex_init(&ap.ap_lock, SPLAT_ATOMIC_TEST1_NAME, MUTEX_DEFAULT, NULL); + init_waitqueue_head(&ap.ap_waitq); + ap.ap_atomic = SPLAT_ATOMIC_INIT_VALUE; + ap.ap_atomic_exited = 0; + + for (i = 0; i < SPLAT_ATOMIC_COUNT_64; i++) { + mutex_enter(&ap.ap_lock); + ap.ap_op = i; + + thr = (kthread_t *)thread_create(NULL, 0, splat_atomic_work, + &ap, 0, &p0, TS_RUN, + defclsyspri); + if (thr == NULL) { + rc = -ESRCH; + mutex_exit(&ap.ap_lock); + break; + } + + /* Prepare to wait, the new thread will wake us once it + * has made a copy of the unique private passed data */ + prepare_to_wait(&ap.ap_waitq, &wait, TASK_UNINTERRUPTIBLE); + mutex_exit(&ap.ap_lock); + schedule(); + } + + wait_event(ap.ap_waitq, splat_atomic_test1_cond(&ap, i)); + + if (rc) { + splat_vprint(file, SPLAT_ATOMIC_TEST1_NAME, "Only started " + "%d/%d test threads\n", i, SPLAT_ATOMIC_COUNT_64); + return rc; + } + + if (ap.ap_atomic != SPLAT_ATOMIC_INIT_VALUE) { + splat_vprint(file, SPLAT_ATOMIC_TEST1_NAME, + "Final value %lu does not match initial value %lu\n", + (long unsigned)ap.ap_atomic, SPLAT_ATOMIC_INIT_VALUE); + return -EINVAL; + } + + splat_vprint(file, SPLAT_ATOMIC_TEST1_NAME, + "Success initial and final values match, %lu == %lu\n", + (long unsigned)ap.ap_atomic, SPLAT_ATOMIC_INIT_VALUE); + + mutex_destroy(&ap.ap_lock); + + return 0; +} + +splat_subsystem_t * +splat_atomic_init(void) +{ + splat_subsystem_t *sub; + + sub = kmalloc(sizeof(*sub), GFP_KERNEL); + if (sub == NULL) + return NULL; + + memset(sub, 0, sizeof(*sub)); + strncpy(sub->desc.name, SPLAT_ATOMIC_NAME, SPLAT_NAME_SIZE); + strncpy(sub->desc.desc, SPLAT_ATOMIC_DESC, SPLAT_DESC_SIZE); + INIT_LIST_HEAD(&sub->subsystem_list); + INIT_LIST_HEAD(&sub->test_list); + spin_lock_init(&sub->test_lock); + sub->desc.id = SPLAT_SUBSYSTEM_ATOMIC; + + splat_test_init(sub, SPLAT_ATOMIC_TEST1_NAME, SPLAT_ATOMIC_TEST1_DESC, + SPLAT_ATOMIC_TEST1_ID, splat_atomic_test1); + + return sub; +} + +void +splat_atomic_fini(splat_subsystem_t *sub) +{ + ASSERT(sub); + splat_test_fini(sub, SPLAT_ATOMIC_TEST1_ID); + + kfree(sub); +} + +int +splat_atomic_id(void) { + return SPLAT_SUBSYSTEM_ATOMIC; +} diff --git a/pool/shard004/C/0100039_min_sce.c b/pool/shard004/C/0100039_min_sce.c new file mode 100644 index 0000000000000000000000000000000000000000..30f20fcb39f1623a95930d59823980b46af13423 --- /dev/null +++ b/pool/shard004/C/0100039_min_sce.c @@ -0,0 +1,23 @@ +// min_sec.c --°ÑÃëÊýת»»³É·ÖºÍÃë +#include +#define SEC_PER_MIN 60 //1·ÖÖÓ60Ãë +int main(void) +{ + int sec, min, left; + + printf("Convert seconds to minutes and seconds!\n"); + printf("Enter the number of seconds ( <=0 to quit):\n"); + scanf("%d", &sec); //¶ÁÈ¡ÃëÊý + while (sec > 0) + { + min = sec / SEC_PER_MIN; //½Ø¶Ï·ÖÖÓÊý + left = sec % SEC_PER_MIN; //ʣϵÄÃëÊý + printf("%d seconds is %d minutes, %d seconds.\n", sec, + min, left); + printf("Enter the next value (<=0 to quit):\n"); + scanf("%d", &sec); + } + printf("Done!\n"); + + return 0; +} \ No newline at end of file diff --git a/pool/shard004/C/0100045_cpuamu.c b/pool/shard004/C/0100045_cpuamu.c new file mode 100644 index 0000000000000000000000000000000000000000..3a2fa819f8788d9fbfea8bbdc8e807e72e73697d --- /dev/null +++ b/pool/shard004/C/0100045_cpuamu.c @@ -0,0 +1,70 @@ +/* + * Copyright (c) 2018, ARM Limited and Contributors. All rights reserved. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +#include +#include +#include + +#define CPUAMU_NR_COUNTERS 5U + +struct cpuamu_ctx { + uint64_t cnts[CPUAMU_NR_COUNTERS]; + unsigned int mask; +}; + +static struct cpuamu_ctx cpuamu_ctxs[PLATFORM_CORE_COUNT]; + +int midr_match(unsigned int cpu_midr) +{ + unsigned int midr, midr_mask; + + midr = (unsigned int)read_midr(); + midr_mask = (MIDR_IMPL_MASK << MIDR_IMPL_SHIFT) | + (MIDR_PN_MASK << MIDR_PN_SHIFT); + return ((midr & midr_mask) == (cpu_midr & midr_mask)); +} + +void cpuamu_context_save(unsigned int nr_counters) +{ + struct cpuamu_ctx *ctx = &cpuamu_ctxs[plat_my_core_pos()]; + unsigned int i; + + assert(nr_counters <= CPUAMU_NR_COUNTERS); + + /* Save counter configuration */ + ctx->mask = cpuamu_read_cpuamcntenset_el0(); + + /* Disable counters */ + cpuamu_write_cpuamcntenclr_el0(ctx->mask); + isb(); + + /* Save counters */ + for (i = 0; i < nr_counters; i++) + ctx->cnts[i] = cpuamu_cnt_read(i); +} + +void cpuamu_context_restore(unsigned int nr_counters) +{ + struct cpuamu_ctx *ctx = &cpuamu_ctxs[plat_my_core_pos()]; + unsigned int i; + + assert(nr_counters <= CPUAMU_NR_COUNTERS); + + /* + * Disable counters. They were enabled early in the + * CPU reset function. + */ + cpuamu_write_cpuamcntenclr_el0(ctx->mask); + isb(); + + /* Restore counters */ + for (i = 0; i < nr_counters; i++) + cpuamu_cnt_write(i, ctx->cnts[i]); + isb(); + + /* Restore counter configuration */ + cpuamu_write_cpuamcntenset_el0(ctx->mask); +} diff --git a/pool/shard004/C/0100054_lmc_proto.c b/pool/shard004/C/0100054_lmc_proto.c new file mode 100644 index 0000000000000000000000000000000000000000..963e2925c854891d5c12e02ede136657bcd8a92c --- /dev/null +++ b/pool/shard004/C/0100054_lmc_proto.c @@ -0,0 +1,131 @@ + /* + * Copyright (c) 1997-2000 LAN Media Corporation (LMC) + * All rights reserved. www.lanmedia.com + * + * This code is written by: + * Andrew Stanley-Jones (asj@cban.com) + * Rob Braun (bbraun@vix.com), + * Michael Graff (explorer@vix.com) and + * Matt Thomas (matt@3am-software.com). + * + * With Help By: + * David Boggs + * Ron Crane + * Allan Cox + * + * This software may be used and distributed according to the terms + * of the GNU General Public License version 2, incorporated herein by reference. + * + * Driver for the LanMedia LMC5200, LMC5245, LMC1000, LMC1200 cards. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "lmc.h" +#include "lmc_var.h" +#include "lmc_debug.h" +#include "lmc_ioctl.h" +#include "lmc_proto.h" + +void lmc_proto_attach(lmc_softc_t *sc) +{ + lmc_trace(sc->lmc_device, "lmc_proto_attach in"); + if (sc->if_type == LMC_NET) { + struct net_device *dev = sc->lmc_device; + dev->flags |= IFF_POINTOPOINT; + dev->hard_header_len = 0; + dev->addr_len = 0; + } + lmc_trace(sc->lmc_device, "lmc_proto_attach out"); +} + +int lmc_proto_ioctl(lmc_softc_t *sc, struct ifreq *ifr, int cmd) +{ + lmc_trace(sc->lmc_device, "lmc_proto_ioctl"); + if (sc->if_type == LMC_PPP) + return hdlc_ioctl(sc->lmc_device, ifr, cmd); + return -EOPNOTSUPP; +} + +int lmc_proto_open(lmc_softc_t *sc) +{ + int ret = 0; + + lmc_trace(sc->lmc_device, "lmc_proto_open in"); + + if (sc->if_type == LMC_PPP) { + ret = hdlc_open(sc->lmc_device); + if (ret < 0) + printk(KERN_WARNING "%s: HDLC open failed: %d\n", + sc->name, ret); + } + + lmc_trace(sc->lmc_device, "lmc_proto_open out"); + return ret; +} + +void lmc_proto_close(lmc_softc_t *sc) +{ + lmc_trace(sc->lmc_device, "lmc_proto_close in"); + + if (sc->if_type == LMC_PPP) + hdlc_close(sc->lmc_device); + + lmc_trace(sc->lmc_device, "lmc_proto_close out"); +} + +__be16 lmc_proto_type(lmc_softc_t *sc, struct sk_buff *skb) +{ + lmc_trace(sc->lmc_device, "lmc_proto_type in"); + switch(sc->if_type){ + case LMC_PPP: + return hdlc_type_trans(skb, sc->lmc_device); + break; + case LMC_NET: + return htons(ETH_P_802_2); + break; + case LMC_RAW: + return htons(ETH_P_802_2); + break; + default: + printk(KERN_WARNING "%s: No protocol set for this interface, assuming 802.2 (which is wrong!!)\n", sc->name); + return htons(ETH_P_802_2); + break; + } + lmc_trace(sc->lmc_device, "lmc_proto_tye out"); + +} + +void lmc_proto_netif(lmc_softc_t *sc, struct sk_buff *skb) +{ + lmc_trace(sc->lmc_device, "lmc_proto_netif in"); + switch(sc->if_type){ + case LMC_PPP: + case LMC_NET: + default: + netif_rx(skb); + break; + case LMC_RAW: + break; + } + lmc_trace(sc->lmc_device, "lmc_proto_netif out"); +} diff --git a/pool/shard004/C/0100065_benchmark.c b/pool/shard004/C/0100065_benchmark.c new file mode 100644 index 0000000000000000000000000000000000000000..d58e34c96c8866d2baa1aa9f357dbc73f31babed --- /dev/null +++ b/pool/shard004/C/0100065_benchmark.c @@ -0,0 +1,141 @@ +/** +* @license Apache-2.0 +* +* Copyright (c) 2021 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. +*/ + +/** +* Benchmark `cabs2`. +*/ +#include "stdlib/math/base/special/cabs2.h" +#include +#include +#include +#include +#include +#include + +#define NAME "cabs2" +#define ITERATIONS 1000000 +#define REPEATS 3 + +/** +* Prints the TAP version. +*/ +void print_version() { + printf( "TAP version 13\n" ); +} + +/** +* Prints the TAP summary. +* +* @param total total number of tests +* @param passing total number of passing tests +*/ +void print_summary( int total, int passing ) { + printf( "#\n" ); + printf( "1..%d\n", total ); // TAP plan + printf( "# total %d\n", total ); + printf( "# pass %d\n", passing ); + printf( "#\n" ); + printf( "# ok\n" ); +} + +/** +* Prints benchmarks results. +* +* @param elapsed elapsed time in seconds +*/ +void print_results( double elapsed ) { + double rate = (double)ITERATIONS / elapsed; + printf( " ---\n" ); + printf( " iterations: %d\n", ITERATIONS ); + printf( " elapsed: %0.9f\n", elapsed ); + printf( " rate: %0.9f\n", rate ); + printf( " ...\n" ); +} + +/** +* Returns a clock time. +* +* @return clock time +*/ +double tic() { + struct timeval now; + gettimeofday( &now, NULL ); + return (double)now.tv_sec + (double)now.tv_usec/1.0e6; +} + +/** +* Generates a random number on the interval [0,1]. +* +* @return random number +*/ +double rand_double() { + int r = rand(); + return (double)r / ( (double)RAND_MAX + 1.0 ); +} + +/** +* Runs a benchmark. +* +* @return elapsed time in seconds +*/ +double benchmark() { + double complex z; + double elapsed; + double re; + double im; + double y; + double t; + int i; + + t = tic(); + for ( i = 0; i < ITERATIONS; i++ ) { + re = ( 1000.0*rand_double() ) - 500.0; + im = ( 1000.0*rand_double() ) - 500.0; + z = re + im*I; + y = stdlib_base_cabs2( z ); + if ( y != y ) { + printf( "should not return NaN\n" ); + break; + } + } + elapsed = tic() - t; + if ( y != y ) { + printf( "should not return NaN\n" ); + } + return elapsed; +} + +/** +* Main execution sequence. +*/ +int main( void ) { + double elapsed; + int i; + + // Use the current time to seed the random number generator: + srand( time( NULL ) ); + + print_version(); + for ( i = 0; i < REPEATS; i++ ) { + printf( "# c::native::%s\n", NAME ); + elapsed = benchmark(); + print_results( elapsed ); + printf( "ok %d benchmark finished\n", i+1 ); + } + print_summary( REPEATS, REPEATS ); +} diff --git a/pool/shard004/C/0100067_tier.c b/pool/shard004/C/0100067_tier.c new file mode 100644 index 0000000000000000000000000000000000000000..8627ac3ea60436e9e4b6e16f87d2d3f6179ff85e --- /dev/null +++ b/pool/shard004/C/0100067_tier.c @@ -0,0 +1,282 @@ + +#include "bcache.h" +#include "alloc.h" +#include "btree_iter.h" +#include "buckets.h" +#include "clock.h" +#include "extents.h" +#include "io.h" +#include "keylist.h" +#include "move.h" +#include "super-io.h" +#include "tier.h" + +#include +#include +#include + +struct tiering_state { + struct bch_tier *tier; + unsigned sectors; + unsigned stripe_size; + unsigned dev_idx; + struct bch_dev *ca; +}; + +static bool tiering_pred(struct bch_fs *c, + struct tiering_state *s, + struct bkey_s_c k) +{ + if (bkey_extent_is_data(k.k)) { + struct bkey_s_c_extent e = bkey_s_c_to_extent(k); + const struct bch_extent_ptr *ptr; + unsigned replicas = 0; + + /* Make sure we have room to add a new pointer: */ + if (bkey_val_u64s(e.k) + BKEY_EXTENT_PTR_U64s_MAX > + BKEY_EXTENT_VAL_U64s_MAX) + return false; + + extent_for_each_ptr(e, ptr) + if (c->devs[ptr->dev]->mi.tier >= s->tier->idx) + replicas++; + + return replicas < c->opts.data_replicas; + } + + return false; +} + +static void tier_put_device(struct tiering_state *s) +{ + if (s->ca) + percpu_ref_put(&s->ca->io_ref); + s->ca = NULL; +} + +/** + * refill_next - move on to refilling the next cache's tiering keylist + */ +static void tier_next_device(struct bch_fs *c, struct tiering_state *s) +{ + if (!s->ca || s->sectors > s->stripe_size) { + tier_put_device(s); + s->sectors = 0; + s->dev_idx++; + + spin_lock(&s->tier->devs.lock); + if (s->dev_idx >= s->tier->devs.nr) + s->dev_idx = 0; + + if (s->tier->devs.nr) { + s->ca = s->tier->devs.d[s->dev_idx].dev; + percpu_ref_get(&s->ca->io_ref); + } + spin_unlock(&s->tier->devs.lock); + } +} + +static int issue_tiering_move(struct bch_fs *c, + struct tiering_state *s, + struct moving_context *ctxt, + struct bkey_s_c k) +{ + int ret; + + ret = bch_data_move(c, ctxt, &s->ca->tiering_write_point, k, NULL); + if (!ret) { + trace_bcache_tiering_copy(k.k); + s->sectors += k.k->size; + } else { + trace_bcache_tiering_alloc_fail(c, k.k->size); + } + + return ret; +} + +/** + * tiering_next_cache - issue a move to write an extent to the next cache + * device in round robin order + */ +static s64 read_tiering(struct bch_fs *c, struct bch_tier *tier) +{ + struct moving_context ctxt; + struct tiering_state s; + struct btree_iter iter; + struct bkey_s_c k; + unsigned nr_devices = READ_ONCE(tier->devs.nr); + int ret; + + if (!nr_devices) + return 0; + + trace_bcache_tiering_start(c); + + memset(&s, 0, sizeof(s)); + s.tier = tier; + s.stripe_size = 2048; /* 1 mb for now */ + + bch_move_ctxt_init(&ctxt, &tier->pd.rate, + nr_devices * SECTORS_IN_FLIGHT_PER_DEVICE); + bch_btree_iter_init(&iter, c, BTREE_ID_EXTENTS, POS_MIN); + + while (!kthread_should_stop() && + !bch_move_ctxt_wait(&ctxt) && + (k = bch_btree_iter_peek(&iter)).k && + !btree_iter_err(k)) { + if (!tiering_pred(c, &s, k)) + goto next; + + tier_next_device(c, &s); + if (!s.ca) + break; + + ret = issue_tiering_move(c, &s, &ctxt, k); + if (ret) { + bch_btree_iter_unlock(&iter); + + /* memory allocation failure, wait for some IO to finish */ + bch_move_ctxt_wait_for_io(&ctxt); + continue; + } +next: + bch_btree_iter_advance_pos(&iter); + //bch_btree_iter_cond_resched(&iter); + + /* unlock before calling moving_context_wait() */ + bch_btree_iter_unlock(&iter); + cond_resched(); + } + + bch_btree_iter_unlock(&iter); + tier_put_device(&s); + bch_move_ctxt_exit(&ctxt); + trace_bcache_tiering_end(c, ctxt.sectors_moved, ctxt.keys_moved); + + return ctxt.sectors_moved; +} + +static int bch_tiering_thread(void *arg) +{ + struct bch_tier *tier = arg; + struct bch_fs *c = container_of(tier, struct bch_fs, tiers[tier->idx]); + struct io_clock *clock = &c->io_clock[WRITE]; + struct bch_dev *ca; + u64 tier_capacity, available_sectors; + unsigned long last; + unsigned i; + + set_freezable(); + + while (!kthread_should_stop()) { + if (kthread_wait_freezable(c->tiering_enabled && + tier->devs.nr)) + break; + + while (1) { + struct bch_tier *faster_tier; + + last = atomic_long_read(&clock->now); + + tier_capacity = available_sectors = 0; + for (faster_tier = c->tiers; + faster_tier != tier; + faster_tier++) { + spin_lock(&faster_tier->devs.lock); + group_for_each_dev(ca, &faster_tier->devs, i) { + tier_capacity += + (ca->mi.nbuckets - + ca->mi.first_bucket) << ca->bucket_bits; + available_sectors += + dev_buckets_available(ca) << ca->bucket_bits; + } + spin_unlock(&faster_tier->devs.lock); + } + + if (available_sectors < (tier_capacity >> 1)) + break; + + bch_kthread_io_clock_wait(clock, + last + + available_sectors - + (tier_capacity >> 1)); + if (kthread_should_stop()) + return 0; + } + + read_tiering(c, tier); + } + + return 0; +} + +static void __bch_tiering_stop(struct bch_tier *tier) +{ + tier->pd.rate.rate = UINT_MAX; + bch_ratelimit_reset(&tier->pd.rate); + + if (tier->migrate) + kthread_stop(tier->migrate); + + tier->migrate = NULL; +} + +void bch_tiering_stop(struct bch_fs *c) +{ + struct bch_tier *tier; + + for (tier = c->tiers; tier < c->tiers + ARRAY_SIZE(c->tiers); tier++) + __bch_tiering_stop(tier); +} + +static int __bch_tiering_start(struct bch_tier *tier) +{ + if (!tier->migrate) { + struct task_struct *p = + kthread_create(bch_tiering_thread, tier, + "bch_tier[%u]", tier->idx); + if (IS_ERR(p)) + return PTR_ERR(p); + + tier->migrate = p; + } + + wake_up_process(tier->migrate); + return 0; +} + +int bch_tiering_start(struct bch_fs *c) +{ + struct bch_tier *tier; + bool have_faster_tier = false; + + if (c->opts.nochanges) + return 0; + + for (tier = c->tiers; tier < c->tiers + ARRAY_SIZE(c->tiers); tier++) { + if (!tier->devs.nr) + continue; + + if (have_faster_tier) { + int ret = __bch_tiering_start(tier); + if (ret) + return ret; + } else { + __bch_tiering_stop(tier); + } + + have_faster_tier = true; + } + + return 0; +} + +void bch_fs_tiering_init(struct bch_fs *c) +{ + unsigned i; + + for (i = 0; i < ARRAY_SIZE(c->tiers); i++) { + c->tiers[i].idx = i; + bch_pd_controller_init(&c->tiers[i].pd); + } +} diff --git a/pool/shard004/C/0100068_dom-test.c b/pool/shard004/C/0100068_dom-test.c new file mode 100644 index 0000000000000000000000000000000000000000..33b56e17f9dfe7dc941d2f67145334d692f67091 --- /dev/null +++ b/pool/shard004/C/0100068_dom-test.c @@ -0,0 +1,180 @@ +/* -*- Mode: C; tab-width: 8; indent-tabs-mode: t; c-basic-offset: 8 -*- */ + +/* + * GThumb + * + * Copyright (C) 2008 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 "dom.h" + + +static void +compare_loaded_and_dumped_xml (DomDocument *doc) +{ + char *xml; + gsize len; + DomDocument *loaded_doc; + char *loaded_xml; + + xml = dom_document_dump (doc, &len); + /*g_print ("%s", xml);*/ + + loaded_doc = dom_document_new (); + dom_document_load (loaded_doc, xml, len, NULL); + loaded_xml = dom_document_dump (loaded_doc, NULL); + /*g_print ("%s", loaded_xml);*/ + + g_assert_cmpstr (xml, ==, loaded_xml); + + g_free (loaded_xml); + g_object_unref (loaded_doc); + g_free (xml); +} + + +static void +check_dumped_xml (DomDocument *doc, + const char *expected_xml) +{ + char *xml; + + xml = dom_document_dump (doc, NULL); + /*g_print ("%s", xml);*/ + g_assert_cmpstr (xml, ==, expected_xml); + g_free (xml); +} + + +static void +test_dom_1 (void) +{ + DomDocument *doc; + + doc = dom_document_new (); + + compare_loaded_and_dumped_xml (doc); + check_dumped_xml (doc, "\n"); + + g_object_unref (doc); +} + + +static void +test_dom_2 (void) +{ + DomDocument *doc; + DomElement *filters; + + doc = dom_document_new (); + filters = dom_document_create_element (doc, "filters", "version", "1.0", NULL); + dom_element_append_child (DOM_ELEMENT (doc), filters); + + compare_loaded_and_dumped_xml (doc); + check_dumped_xml (doc, "\n" + "\n"); + + g_object_unref (doc); +} + + +static void +test_dom_3 (void) +{ + DomDocument *doc; + DomElement *filters; + DomElement *filter; + DomElement *match; + DomElement *test; + DomElement *limit; + + doc = dom_document_new (); + filters = dom_document_create_element (doc, "filters", NULL); + dom_element_set_attribute (filters, "version", "1.0"); + dom_element_append_child (DOM_ELEMENT (doc), filters); + + filter = dom_document_create_element (doc, "filter", NULL); + dom_element_set_attribute (filter, "name", "test1"); + dom_element_append_child (filters, filter); + + match = dom_document_create_element (doc, "match", NULL); + dom_element_set_attribute (match, "type", "all"); + dom_element_append_child (filter, match); + + test = dom_document_create_element (doc, "test", NULL); + dom_element_set_attribute (test, "id", "::filesize"); + dom_element_set_attribute (test, "op", "lt"); + dom_element_set_attribute (test, "value", "10"); + dom_element_set_attribute (test, "unit", "kB"); + dom_element_append_child (match, test); + + test = dom_document_create_element (doc, "test", NULL); + dom_element_set_attribute (test, "id", "::filename"); + dom_element_set_attribute (test, "op", "contains"); + dom_element_set_attribute (test, "value", "logo"); + dom_element_append_child (match, test); + + limit = dom_document_create_element (doc, "limit", NULL); + dom_element_set_attribute (limit, "value", "25"); + dom_element_set_attribute (limit, "type", "files"); + dom_element_set_attribute (limit, "selected_by", "more_recent"); + dom_element_append_child (filter, limit); + + filter = dom_document_create_element (doc, "filter", NULL); + dom_element_set_attribute (filter, "name", "test2"); + dom_element_append_child (filters, filter); + + limit = dom_document_create_element (doc, "limit", NULL); + dom_element_set_attribute (limit, "value", "25"); + dom_element_set_attribute (limit, "type", "files"); + dom_element_set_attribute (limit, "selected_by", "more_recent"); + dom_element_append_child (filter, limit); + + compare_loaded_and_dumped_xml (doc); + + check_dumped_xml (doc, "\n" + "\n" + " \n" + " \n" + " \n" + " \n" + " \n" + " \n" + " \n" + " \n" + " \n" + " \n" + "\n"); + + g_object_unref (doc); +} + + +int +main (int argc, + char *argv[]) +{ + g_type_init (); + g_test_init (&argc, &argv, NULL); + + g_test_add_func ("/dom/1", test_dom_1); + g_test_add_func ("/dom/2", test_dom_2); + g_test_add_func ("/dom/3", test_dom_3); + + return g_test_run (); +} diff --git a/pool/shard004/C/0100071_definitions.c b/pool/shard004/C/0100071_definitions.c new file mode 100644 index 0000000000000000000000000000000000000000..479246a14eb54b2dd336e8dcaff4d843129bd13c --- /dev/null +++ b/pool/shard004/C/0100071_definitions.c @@ -0,0 +1,50 @@ +// TEST_CONFIG + +// DO NOT include anything else here +#include +// DO NOT include anything else here +Class c = Nil; +SEL s; +IMP i; +id o = nil; +BOOL b = YES; +BOOL b2 = NO; +#if !__has_feature(objc_arr) +__strong void *p; +#endif +id __unsafe_unretained u; +id __weak w; + +void fn(void) __unused; +void fn(void) { + id __autoreleasing a __unused; +} + +#if __llvm__ && !__clang__ +// llvm-gcc defines _NSConcreteGlobalBlock wrong +#else +// rdar://10118972 wrong type inference for blocks returning YES and NO +BOOL (^block1)(void) = ^{ return YES; }; +BOOL (^block2)(void) = ^{ return NO; }; +#endif + +#include "test.h" + +int main() +{ + testassert(YES); + testassert(!NO); + testassert(!nil); + testassert(!Nil); + +#if __has_feature(objc_bool) + // YES[array] is disallowed for objc just as true[array] is for C++ +#else + // this will fail if YES and NO do not have enough parentheses + int array[2] = { 888, 999 }; + testassert(NO[array] == 888); + testassert(YES[array] == 999); +#endif + + succeed(__FILE__); +} diff --git a/pool/shard004/C/0100072_eeprom-conf.c b/pool/shard004/C/0100072_eeprom-conf.c new file mode 100644 index 0000000000000000000000000000000000000000..1567ba8be94ddcbe48b8b33b4fa22eb674e85c02 --- /dev/null +++ b/pool/shard004/C/0100072_eeprom-conf.c @@ -0,0 +1,188 @@ +/* sd2iec - SD/MMC to Commodore serial bus interface/controller + Copyright (C) 2007-2014 Ingo Korb + + Inspired by MMC2IEC by Lars Pontoppidan et al. + + FAT filesystem access based on code from ChaN and Jim Brain, see ff.c|h. + + 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 only. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + + + eeprom-conf.c: Persistent configuration storage + +*/ + +#include +#include "config.h" +#include "arch-eeprom.h" +#include "diskio.h" +#include "fatops.h" +#include "flags.h" +#include "iec.h" +#include "timer.h" +#include "ustring.h" +#include "eeprom-conf.h" + +uint8_t rom_filename[ROM_NAME_LENGTH+1]; + +/** + * struct storedconfig - in-eeprom data structure + * @dummy : EEPROM position 0 is unused + * @checksum : Checksum over the EEPROM contents + * @structsize : size of the eeprom structure + * @unused : unused byte kept for structure compatibility + * @globalflags: subset of the globalflags variable + * @address : device address set by software + * @hardaddress: device address set by jumpers + * @fileexts : file extension mapping mode + * @drvflags0 : 16 bits of drv mappings, organized as 4 nybbles. + * @drvflags1 : 16 bits of drv mappings, organized as 4 nybbles. + * @imagedirs : Disk images-as-directory mode + * @romname : M-R rom emulation file name (zero-padded, but not terminated) + * + * This is the data structure for the contents of the EEPROM. + * + * Do not remove any fields! + * Only add fields at the end! + */ +static EEMEM struct { + uint8_t dummy; + uint8_t checksum; + uint16_t structsize; + uint8_t unused; + uint8_t global_flags; + uint8_t address; + uint8_t hardaddress; + uint8_t fileexts; + uint16_t drvconfig0; + uint16_t drvconfig1; + uint8_t imagedirs; + uint8_t romname[ROM_NAME_LENGTH]; +} __attribute__((packed)) storedconfig; + +/** + * read_configuration - reads configuration from EEPROM + * + * This function reads the stored configuration values from the EEPROM. + * If the stored checksum doesn't match the calculated one nothing will + * be changed. + */ +void read_configuration(void) { + uint_fast16_t i,size; + uint8_t checksum, tmp; + + /* Set default values */ + globalflags |= POSTMATCH; /* Post-* matching enabled */ + file_extension_mode = 1; /* Store x00 extensions except for PRG */ + set_drive_config(get_default_driveconfig()); /* Set the default drive configuration */ + memset(rom_filename, 0, sizeof(rom_filename)); + + /* Use the NEXT button to skip reading the EEPROM configuration */ + if (!(buttons_read() & BUTTON_NEXT)) { + ignore_keys(); + return; + } + + size = eeprom_read_word(&storedconfig.structsize); + + /* abort if the size bytes are not set */ + if (size == 0xffff) { + eeprom_safety(); + return; + } + + /* Calculate checksum of EEPROM contents */ + checksum = 0; + for (i=2; i 9) { + uint32_t tmpconfig; + tmpconfig = eeprom_read_word(&storedconfig.drvconfig0); + tmpconfig |= (uint32_t)eeprom_read_word(&storedconfig.drvconfig1) << 16; + set_drive_config(tmpconfig); + } + + /* sanity check. If the user has truly turned off all drives, turn the + * defaults back on + */ + if(drive_config == 0xffffffff) + set_drive_config(get_default_driveconfig()); +#endif + + if (size > 13) + image_as_dir = eeprom_read_byte(&storedconfig.imagedirs); + + if (size > 29) + eeprom_read_block(rom_filename, &storedconfig.romname, ROM_NAME_LENGTH); + + /* Prevent problems due to accidental writes */ + eeprom_safety(); +} + +/** + * write_configuration - stores configuration data to EEPROM + * + * This function stores the current configuration values to the EEPROM. + */ +void write_configuration(void) { + uint_fast16_t i; + uint8_t checksum; + + /* Write configuration to EEPROM */ + eeprom_write_word(&storedconfig.structsize, sizeof(storedconfig)); + eeprom_write_byte(&storedconfig.global_flags, + globalflags & (POSTMATCH | + EXTENSION_HIDING)); + eeprom_write_byte(&storedconfig.address, device_address); + eeprom_write_byte(&storedconfig.hardaddress, device_hw_address()); + eeprom_write_byte(&storedconfig.fileexts, file_extension_mode); +#ifdef NEED_DISKMUX + eeprom_write_word(&storedconfig.drvconfig0, drive_config); + eeprom_write_word(&storedconfig.drvconfig1, drive_config >> 16); +#endif + eeprom_write_byte(&storedconfig.imagedirs, image_as_dir); + memset(rom_filename+ustrlen(rom_filename), 0, sizeof(rom_filename)-ustrlen(rom_filename)); + eeprom_write_block(rom_filename, &storedconfig.romname, ROM_NAME_LENGTH); + + /* Calculate checksum over EEPROM contents */ + checksum = 0; + for (i=2;istatus_type = S2N_STATUS_REQUEST_OCSP; + return S2N_SUCCESS; +} + +/* Old-style extension functions -- remove after extensions refactor is complete */ + +int s2n_server_extensions_status_request_send_size(struct s2n_connection *conn) +{ + if (s2n_server_can_send_ocsp(conn)) { + return 2 * sizeof(uint16_t); + } + + return 0; +} + +int s2n_server_extensions_status_request_send(struct s2n_connection *conn, struct s2n_stuffer *out) +{ + return s2n_extension_send(&s2n_server_status_request_extension, conn, out); +} + +int s2n_recv_server_status_request(struct s2n_connection *conn, struct s2n_stuffer *extension) +{ + return s2n_extension_recv(&s2n_server_status_request_extension, conn, extension); +} diff --git a/pool/shard004/C/0100091_pipe.c b/pool/shard004/C/0100091_pipe.c new file mode 100644 index 0000000000000000000000000000000000000000..a7d0dcef4f56da4cc1a296c3ceeeefb21d873b54 --- /dev/null +++ b/pool/shard004/C/0100091_pipe.c @@ -0,0 +1,71 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include + +void +lock_pipe(struct pipe_fs *pipe) { + down(&(pipe->pipe_sem)); +} + +void +unlock_pipe(struct pipe_fs *pipe) { + up(&(pipe->pipe_sem)); +} + +static int +pipe_sync(struct fs *fs) { + return 0; +} + +static struct inode * +pipe_get_root(struct fs *fs) { + struct pipe_fs *pipe = fsop_info(fs, pipe); + vop_ref_inc(pipe->root); + return pipe->root; +} + +static int +pipe_unmount(struct fs *fs) { + return -E_INVAL; +} + +static void +pipe_cleanup(struct fs *fs) { + /* do nothing */ +} + +static void +pipe_fs_init(struct fs *fs) { + struct pipe_fs *pipe = fsop_info(fs, pipe); + if ((pipe->root = pipe_create_root(fs)) == NULL) { + panic("pipe: create root inode failed.\n"); + } + sem_init(&(pipe->pipe_sem), 1); + list_init(&(pipe->pipe_list)); + + fs->fs_sync = pipe_sync; + fs->fs_get_root = pipe_get_root; + fs->fs_unmount = pipe_unmount; + fs->fs_cleanup = pipe_cleanup; +} + +void +pipe_init(void) { + struct fs *fs; + if ((fs = alloc_fs(pipe)) == NULL) { + panic("pipe: create pipe_fs failed.\n"); + } + pipe_fs_init(fs); + + int ret; + if ((ret = vfs_add_fs("pipe", fs)) != 0) { + panic("pipe: vfs_add_fs: %e.\n", ret); + } +} + diff --git a/pool/shard004/C/0100094_TestNormalizer.c b/pool/shard004/C/0100094_TestNormalizer.c new file mode 100644 index 0000000000000000000000000000000000000000..d6028dce0c30f89f98427d4f7eaab05d38a66c63 --- /dev/null +++ b/pool/shard004/C/0100094_TestNormalizer.c @@ -0,0 +1,188 @@ +/* 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 + +#define C_TESTLUCY_TESTNORMALIZER +#define C_LUCY_NORMALIZER +#define TESTLUCY_USE_SHORT_NAMES +#include "Lucy/Util/ToolSet.h" + +#include "Clownfish/Boolean.h" +#include "Clownfish/TestHarness/TestBatchRunner.h" +#include "Clownfish/TestHarness/TestUtils.h" +#include "Lucy/Test.h" +#include "Lucy/Test/Analysis/TestNormalizer.h" +#include "Lucy/Analysis/Normalizer.h" +#include "Lucy/Store/FSFolder.h" +#include "Lucy/Test/TestUtils.h" +#include "Lucy/Util/Json.h" +#include "utf8proc.h" + +TestNormalizer* +TestNormalizer_new() { + return (TestNormalizer*)Class_Make_Obj(TESTNORMALIZER); +} + +static void +test_Dump_Load_and_Equals(TestBatchRunner *runner) { + Normalizer *normalizer[4]; + + String *NFC = SSTR_WRAP_C("NFC"); + String *NFKC = SSTR_WRAP_C("NFKC"); + + normalizer[0] = Normalizer_new(NFKC, true, false); + normalizer[1] = Normalizer_new(NFC, true, false); + normalizer[2] = Normalizer_new(NFKC, false, false); + normalizer[3] = Normalizer_new(NFKC, true, true); + + TEST_FALSE(runner, + Normalizer_Equals(normalizer[0], (Obj*)normalizer[1]), + "Equals() false with different normalization form"); + TEST_FALSE(runner, + Normalizer_Equals(normalizer[0], (Obj*)normalizer[2]), + "Equals() false with different case_fold flag"); + TEST_FALSE(runner, + Normalizer_Equals(normalizer[0], (Obj*)normalizer[3]), + "Equals() false with different strip_accents flag"); + + for (int i = 0; i < 4; ++i) { + Obj *dump = (Obj*)Normalizer_Dump(normalizer[i]); + Normalizer *clone = (Normalizer*)Normalizer_Load(normalizer[i], dump); + + TEST_TRUE(runner, + Normalizer_Equals(normalizer[i], (Obj*)clone), + "Dump => Load round trip"); + + DECREF(normalizer[i]); + DECREF(dump); + DECREF(clone); + } +} + +static void +test_normalization(TestBatchRunner *runner) { + FSFolder *modules_folder = TestUtils_modules_folder(); + if (modules_folder == NULL) { + SKIP(runner, 13, "Can't locate test data"); + return; + } + + String *path = Str_newf("unicode/utf8proc/tests.json"); + Vector *tests = (Vector*)Json_slurp_json((Folder*)modules_folder, path); + if (!tests) { RETHROW(Err_get_error()); } + + for (size_t i = 0, max = Vec_Get_Size(tests); i < max; i++) { + Hash *test = (Hash*)Vec_Fetch(tests, i); + String *form = (String*)Hash_Fetch_Utf8( + test, "normalization_form", 18); + bool case_fold = Bool_Get_Value((Boolean*)Hash_Fetch_Utf8( + test, "case_fold", 9)); + bool strip_accents = Bool_Get_Value((Boolean*)Hash_Fetch_Utf8( + test, "strip_accents", 13)); + Normalizer *normalizer = Normalizer_new(form, case_fold, strip_accents); + Vector *words = (Vector*)Hash_Fetch_Utf8(test, "words", 5); + Vector *norms = (Vector*)Hash_Fetch_Utf8(test, "norms", 5); + for (size_t j = 0, max = Vec_Get_Size(words); j < max; j++) { + String *word = (String*)Vec_Fetch(words, j); + Vector *got = Normalizer_Split(normalizer, word); + String *norm = (String*)Vec_Fetch(got, 0); + char *fstr = Str_To_Utf8(form); + char *wstr = Str_To_Utf8(word); + TEST_TRUE(runner, + norm + && Str_is_a(norm, STRING) + && Str_Equals(norm, Vec_Fetch(norms, j)), + "Normalize %s %d %d: %s", fstr, + case_fold, strip_accents, wstr + ); + free(fstr); + free(wstr); + DECREF(got); + } + DECREF(normalizer); + } + + DECREF(tests); + DECREF(modules_folder); + DECREF(path); +} + +static void +test_utf8proc_normalization(TestBatchRunner *runner) { + SKIP(runner, 1, + "utf8proc can't handle control chars or Unicode non-chars"); + return; + + for (int32_t i = 0; i < 100; i++) { + String *source = TestUtils_random_string(rand() % 40); + + // Normalize once. + uint8_t *normalized; + int32_t check = utf8proc_map((const uint8_t*)Str_Get_Ptr8(source), + Str_Get_Size(source), + &normalized, + UTF8PROC_STABLE | + UTF8PROC_COMPOSE | + UTF8PROC_COMPAT | + UTF8PROC_CASEFOLD); + if (check < 0) { + lucy_Json_set_tolerant(1); + String *json = lucy_Json_to_json((Obj*)source); + if (!json) { + json = Str_newf("[failed to encode]"); + } + char *str = Str_To_Utf8(json); + FAIL(runner, "Failed to normalize: %s", str); + free(str); + DECREF(json); + DECREF(source); + return; + } + + // Normalize again. + size_t normalized_len = strlen((char*)normalized); + uint8_t *dupe; + int32_t dupe_check = utf8proc_map(normalized, normalized_len, &dupe, + UTF8PROC_STABLE | + UTF8PROC_COMPOSE | + UTF8PROC_COMPAT | + UTF8PROC_CASEFOLD); + if (dupe_check < 0) { + THROW(ERR, "Unexpected normalization error: %i32", dupe_check); + } + int comparison = strcmp((char*)normalized, (char*)dupe); + free(dupe); + free(normalized); + DECREF(source); + if (comparison != 0) { + FAIL(runner, "Not fully normalized"); + return; + } + } + PASS(runner, "Normalization successful."); +} + +void +TestNormalizer_Run_IMP(TestNormalizer *self, TestBatchRunner *runner) { + TestBatchRunner_Plan(runner, (TestBatch*)self, 21); + test_Dump_Load_and_Equals(runner); + test_normalization(runner); + test_utf8proc_normalization(runner); +} + + + diff --git a/pool/shard004/C/0100096_ncd_value_parser_test.c b/pool/shard004/C/0100096_ncd_value_parser_test.c new file mode 100644 index 0000000000000000000000000000000000000000..5eca59c44eabb438d2fa0a92dfecd3a5700dc7c8 --- /dev/null +++ b/pool/shard004/C/0100096_ncd_value_parser_test.c @@ -0,0 +1,86 @@ +/** + * @file ncd_value_parser_test.c + * @author Ambroz Bizjak + * + * @section 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 the author 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 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 +#include +#include + +#include +#include +#include +#include + +int main (int argc, char *argv[]) +{ + int res = 1; + + if (argc != 2) { + printf("Usage: %s \n", (argc > 0 ? argv[0] : "")); + goto fail0; + } + + BLog_InitStdout(); + + NCDStringIndex string_index; + if (!NCDStringIndex_Init(&string_index)) { + DEBUG("NCDStringIndex_Init failed"); + goto fail01; + } + + NCDValMem mem; + NCDValMem_Init(&mem, &string_index); + + // parse + NCDValRef val; + if (!NCDValParser_Parse(MemRef_MakeCstr(argv[1]), &mem, &val)) { + DEBUG("NCDValParser_Parse failed"); + goto fail1; + } + + // generate value string + char *str = NCDValGenerator_Generate(val); + if (!str) { + DEBUG("NCDValGenerator_Generate failed"); + goto fail1; + } + + // print value string + printf("%s\n", str); + + res = 0; + + free(str); +fail1: + NCDValMem_Free(&mem); + NCDStringIndex_Free(&string_index); +fail01: + BLog_Free(); +fail0: + return res; +} diff --git a/pool/shard004/C/0100098_Uart_Lib.c b/pool/shard004/C/0100098_Uart_Lib.c new file mode 100644 index 0000000000000000000000000000000000000000..1bc055d7066fdb34411df533ef71ae2fe0a5d28f --- /dev/null +++ b/pool/shard004/C/0100098_Uart_Lib.c @@ -0,0 +1,313 @@ +//---------------------------------------------------------------------------------------------- +// TITLE : Serial 통신 처리 함수 모음 +// WORK : +// DATE : 2003. 3. 7 +// FILE : Uart_Lib.c +// Modified By : Hanchol Cho - IRSL - +//---------------------------------------------------------------------------------------------- + + +#include + + + +// MACRO Uart_Open(PortNum,BaudData) 로 정의 되어있다. + +//---------------------------------------------------------------------------------------------- +// TITLE : Ser_OpenPortCanonical_Mode +// +// WORK : 시리얼 포트 초기화 +// +// DATE : 2003. 3. 7 +//---------------------------------------------------------------------------------------------- +void Uart_OpenPortCanonical_Mode( int Uart_PortNum, int Uart_BaudData ) +{ + + Uart_Handle = open( Uart_PortStr[ Uart_PortNum ], O_RDWR | O_NOCTTY ); + if( Uart_Handle < 0 ) + { + perror( Uart_PortStr[ Uart_PortNum ] ); + exit( -1 ); + } + + + // 저장한다 현제 시리얼포트 정보를 + tcgetattr( Uart_Handle, &Term_OldIo ); + // Write zeros to a byte string + bzero( &Term_NewIo, sizeof( Term_NewIo ) ); + + // CS8 : 8N1 (8bit, No Parity, 1 Stopbit + // CREAD : 수신 가능 + Term_NewIo.c_cflag = Uart_Baud[ Uart_BaudData ] | CS8 | CLOCAL | CREAD; + + // IGNPAR : Parity 에러가 있는 문자 바이트를 무시한다 + // ICRNL : CR 문자를 NL 문자로 변환 처리한다. ( 이설정을 안하면 다른 컴퓨터는 + // CR 문자를 한 줄의 종료문자로 인식하지 않을 수 있다 + Term_NewIo.c_iflag = IGNPAR ; + + Term_NewIo.c_oflag = 0; + + // ICANON : Canonical 입력을 가능하게 한다 + Term_NewIo.c_lflag = ICANON; + + Term_NewIo.c_cc[ VINTR ] = 0; + Term_NewIo.c_cc[ VQUIT ] = 0; + Term_NewIo.c_cc[ VERASE ] = 0; + Term_NewIo.c_cc[ VKILL ] = 0; + Term_NewIo.c_cc[ VEOF ] = 4; + Term_NewIo.c_cc[ VTIME ] = 0; + Term_NewIo.c_cc[ VMIN ] = 1; + Term_NewIo.c_cc[ VSWTC ] = 0; + Term_NewIo.c_cc[ VSTART ] = 0; + Term_NewIo.c_cc[ VSTOP ] = 0; + Term_NewIo.c_cc[ VSUSP ] = 0; + Term_NewIo.c_cc[ VEOL ] = 0; + Term_NewIo.c_cc[ VREPRINT ] = 0; + Term_NewIo.c_cc[ VDISCARD ] = 0; + Term_NewIo.c_cc[ VWERASE ] = 0; + Term_NewIo.c_cc[ VLNEXT ] = 0; + Term_NewIo.c_cc[ VEOL2 ] = 0; + + // tcflush ( Uart_Handle, TCIFLUSH ); + + // TCSANOW : change occurs immediately. + tcsetattr( Uart_Handle, TCSANOW, &Term_NewIo ); + + Uart_ModeFlag = CANON_MODE; +} + + + + + +//---------------------------------------------------------------------------------------------- +// TITLE : Uart_OpenPortNonCanonical_Mode +// +// WORK : 시리얼 포트 초기화 +// +// DATE : 2003. 7. 4 +//---------------------------------------------------------------------------------------------------- +int Uart_OpenPortNonCanonical_Mode( int Uart_PortNum, int Uart_BaudData ) +{ + + + Uart_Handle = open( Uart_PortStr[ Uart_PortNum ], O_RDWR | O_NOCTTY | O_NONBLOCK ); + if( Uart_Handle < 0 ) + { + perror( Uart_PortStr[ Uart_PortNum ] ); + exit( -1 ); + } + + // 저장한다 현제 시리얼포트 정보를 + tcgetattr( Uart_Handle, &Term_OldIo ); + // Write zeros to a byte string + bzero( &Term_NewIo, sizeof( Term_NewIo ) ); + // CS8 : 8N1 (8bit, No Parity, 1 Stopbit + // CREAD : 수신 가능 + Term_NewIo.c_cflag = Uart_Baud[ Uart_BaudData ] | CS8 | CLOCAL | CREAD; + // IGNPAR : Parity 에러가 있는 문자 바이트를 무시한다 + // ICRNL : CR 문자를 NL 문자로 변환 처리한다. ( 이설정을 안하면 다른 컴퓨터는 + // CR 문자를 한 줄의 종료문자로 인식하지 않을 수 있다 + Term_NewIo.c_iflag = IGNPAR ; + + Term_NewIo.c_oflag = 0; + + Term_NewIo.c_cc[ VTIME ] = 0; + Term_NewIo.c_cc[ VMIN ] = 0; + + tcflush ( Uart_Handle, TCIFLUSH ); + tcsetattr( Uart_Handle, TCSANOW, &Term_NewIo ); + + // Flush + // + //ioctl( Uart_Handle, TCFLSH, 0 ); + + Uart_ModeFlag = NONE_CANON_MODE; + + return Uart_Handle; +} + + + + + +//---------------------------------------------------------------------------------------------- +// TITLE : Uart_Close +// +// WORK : 시리얼 포트 닫는다 +// +// DATE : 2003. 7. 4 +//---------------------------------------------------------------------------------------------- +void Uart_Close( void ) +{ + tcsetattr( Uart_Handle, TCSANOW, &Term_OldIo ); +} + + + + + + +//---------------------------------------------------------------------------------------------- +// TITLE : Uart_Getch +// +// WORK : 문자 1개를 받는다 +// +// DATE : 2003. 7. 4 +//---------------------------------------------------------------------------------------------------- +int Uart_Getch( void ) +{ + char Uart_GetData; + + switch( Uart_ModeFlag ) + { + case CANON_MODE: + + /* 데이터 1바이트 가져온다 */ + read( Uart_Handle, Uart_Buf, 1 ); + + Uart_GetData = Uart_Buf[0]; + + break; + + case NONE_CANON_MODE: + + Uart_GetData = read( Uart_Handle, Uart_Buf, 1 ); + + if( Uart_GetData < 1) return 1000; + + Uart_GetData = Uart_Buf[0]; + break; + } + + return Uart_GetData; +} + + + + + +//---------------------------------------------------------------------------------------------- +// TITLE : Uart_Putch +// +// WORK : 문자 1개를 보낸다 +// +// DATE : 2003. 3. 7 +//---------------------------------------------------------------------------------------------- +void Uart_Putch( char Uart_PutData ) +{ + + + switch( Uart_ModeFlag ) + { + case CANON_MODE: + case NONE_CANON_MODE: + + /* 데이터 1바이트 보낸다 */ + write( Uart_Handle, &Uart_PutData, 1 ); + break; + } + +} + + + +//---------------------------------------------------------------------------- +// +// TITLE : Uart_Print +// +// WORK : 시리얼로 문자열을 보낸다. +// +//---------------------------------------------------------------------------- +void Uart_Print(char *UartPrintData) +{ + while( *UartPrintData != '\0') + { + Uart_Putch(*UartPrintData); + + if( *UartPrintData == 0x0A ) // LF 에 CR을 보탠다 + Uart_Putch(0x0D); + + UartPrintData++; + } +} + + + + + + +/*--------------------------------------------------------------------------- + TITLE : Uart_Printf + WORK + ARG + RET +---------------------------------------------------------------------------*/ +void Uart_Printf( char *format, ... ) +{ + char Str[200]; + + va_list ap; + + va_start( ap, format ); + + vsprintf( Str, format, ap ); + + Uart_Print(Str); + + va_end(ap); +} + + + + + + +//---------------------------------------------------------------------------------------------- +// TITLE : Uart_Gets +// +// WORK : 문자 1개를 받는다 +// +// DATE : 2003. 3. 7 +//---------------------------------------------------------------------------------------------- +char *Uart_Gets( void ) +{ + + switch( Uart_ModeFlag ) + { + // 표준 모드 + case CANON_MODE: + + /* 데이터열을 가져온다 */ + Buf_ReadSize = read( Uart_Handle, Uart_Buf, 255 ); + Uart_Buf[ Buf_ReadSize ] = 0; + + return Uart_Buf; + + break; + // 비표준 모드 + case NONE_CANON_MODE: + + Buf_ReadSize = read( Uart_Handle, Uart_Buf, 255); + + //if( Buf_ReadSize < 1 ) return Ser_Buf; + + Term_NewIo.c_cc[ VMIN ] = Buf_ReadSize-1; + tcsetattr( Uart_Handle, TCSANOW, &Term_NewIo ); + + /* 데이터 1바이트 가져온다 */ + Buf_ReadSize = read( Uart_Handle, Uart_Buf, 255 ); + + Uart_Buf[ Buf_ReadSize ] = 0; + + Term_NewIo.c_cc[ VMIN ] = 0; + tcsetattr( Uart_Handle, TCSANOW, &Term_NewIo ); + + return Uart_Buf; + + break; + } + + return 0; +} + diff --git a/pool/shard004/C/0100116_imsettings-restart.c b/pool/shard004/C/0100116_imsettings-restart.c new file mode 100644 index 0000000000000000000000000000000000000000..9e52e840208e137be94b39c2c96179e2ff29e3c6 --- /dev/null +++ b/pool/shard004/C/0100116_imsettings-restart.c @@ -0,0 +1,132 @@ +/* -*- Mode: C; tab-width: 8; indent-tabs-mode: t; c-basic-offset: 8 -*- */ +/* + * imsettings-restart.c + * Copyright (C) 2008-2009 Red Hat, Inc. All rights reserved. + * + * Authors: + * Akira TAGOH + * + * 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. + */ +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +#include +#include +#include +#include "imsettings/imsettings.h" +#include "imsettings/imsettings-request.h" + +int +main(int argc, + char **argv) +{ + IMSettingsRequest *req; + DBusConnection *connection; + gchar *locale, *module = NULL; + gboolean arg_force = FALSE, arg_no_update = FALSE; + GOptionContext *ctx = g_option_context_new(_("[Input Method name|xinput.conf]")); + GOptionEntry entries[] = { + {"force", 'f', G_OPTION_FLAG_NO_ARG, G_OPTION_ARG_NONE, &arg_force, N_("Force restarting the IM process regardless of any errors."), NULL}, + {"no-update", 'n', G_OPTION_FLAG_NO_ARG, G_OPTION_ARG_NONE, &arg_no_update, N_("Do not update .xinputrc."), NULL}, + {NULL, 0, 0, 0, NULL, NULL, NULL} + }; + GError *error = NULL; + gboolean flag; + int retval = 0; + +#ifdef ENABLE_NLS + bindtextdomain (GETTEXT_PACKAGE, IMSETTINGS_LOCALEDIR); +#ifdef HAVE_BIND_TEXTDOMAIN_CODESET + bind_textdomain_codeset (GETTEXT_PACKAGE, "UTF-8"); +#endif /* HAVE_BIND_TEXTDOMAIN_CODESET */ + textdomain (GETTEXT_PACKAGE); +#endif /* ENABLE_NLS */ + + setlocale(LC_ALL, ""); + locale = setlocale(LC_CTYPE, NULL); + + g_type_init(); + + g_option_context_add_main_entries(ctx, entries, GETTEXT_PACKAGE); + if (!g_option_context_parse(ctx, &argc, &argv, &error)) { + if (error != NULL) { + g_printerr("%s\n", error->message); + } else { + g_warning(_("Unknown error in parsing the command lines.")); + } + return 1; + } + + connection = dbus_bus_get(DBUS_BUS_SESSION, NULL); + if (connection == NULL) { + g_printerr(_("Failed to get a session bus.\n")); + return 1; + } + req = imsettings_request_new(connection, IMSETTINGS_INTERFACE_DBUS); + imsettings_request_set_locale(req, locale); + + if (imsettings_request_get_version(req, NULL) != IMSETTINGS_SETTINGS_API_VERSION) { + g_printerr(_("Currently a different version of imsettings is running.\nRunning \"imsettings-reload -f\" may help but it will restart the Input Method\n")); + retval = 1; + goto end; + } + + if (argc < 2) { + module = imsettings_request_whats_input_method_running(req, &error); + if (error) { + g_printerr("%s\n", error->message); + g_error_free(error); + retval = 1; + goto end; + } + if (module == NULL || module[0] == 0) { + g_print(_("No Input Method running. please specify Input Method name explicitly if necessary.\n")); + retval = 1; + goto end; + } + } else { + module = g_strdup(argv[1]); + } + g_option_context_free(ctx); + + if (!(flag = imsettings_request_stop_im(req, module, FALSE, arg_force, &error))) { + if (!arg_force) { + g_printerr(_("Failed to stop IM process `%s'\n"), module); + retval = 1; + goto end; + } + } + sleep(3); + if (imsettings_request_start_im(req, module, !arg_no_update, &error)) { + if (arg_force && flag) { + g_print(_("Forcibly restarted %s, but maybe not completely\n"), module); + } else { + g_print(_("Restarted %s\n"), module); + } + } else { + g_printerr(_("Failed to restart IM process `%s'\n"), module); + retval = 1; + g_error_free(error); + } + end: + g_free(module); + g_object_unref(req); + dbus_connection_unref(connection); + + return retval; +} diff --git a/pool/shard004/C/0100126_p_tick.c b/pool/shard004/C/0100126_p_tick.c new file mode 100644 index 0000000000000000000000000000000000000000..323cc1e6af384e897e013fec3531c54f68e8bce0 --- /dev/null +++ b/pool/shard004/C/0100126_p_tick.c @@ -0,0 +1,167 @@ +// +// Copyright(C) 1993-1996 Id Software, Inc. +// Copyright(C) 1993-2008 Raven Software +// Copyright(C) 2005-2014 Simon Howard +// +// 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. +// + +// P_tick.c + +#include "doomdef.h" +#include "i_system.h" +#include "p_local.h" +#include "v_video.h" + +int leveltime; +int TimerGame; + +/* +=============================================================================== + + THINKERS + +All thinkers should be allocated by Z_Malloc so they can be operated on uniformly. The actual +structures will vary in size, but the first element must be thinker_t. + +=============================================================================== +*/ + +thinker_t thinkercap; // both the head and tail of the thinker list + +/* +=============== += += P_InitThinkers += +=============== +*/ + +void P_InitThinkers(void) +{ + thinkercap.prev = thinkercap.next = &thinkercap; +} + + +/* +=============== += += P_AddThinker += += Adds a new thinker at the end of the list += +=============== +*/ + +void P_AddThinker(thinker_t * thinker) +{ + thinkercap.prev->next = thinker; + thinker->next = &thinkercap; + thinker->prev = thinkercap.prev; + thinkercap.prev = thinker; +} + +/* +=============== += += P_RemoveThinker += += Deallocation is lazy -- it will not actually be freed until its += thinking turn comes up += +=============== +*/ + +void P_RemoveThinker(thinker_t * thinker) +{ + thinker->function = (think_t) - 1; +} + +/* +=============== += += P_AllocateThinker += += Allocates memory and adds a new thinker at the end of the list += +=============== +*/ + +void P_AllocateThinker(thinker_t * thinker) +{ +} + + +/* +=============== += += P_RunThinkers += +=============== +*/ + +void P_RunThinkers(void) +{ + thinker_t *currentthinker, *nextthinker; + + currentthinker = thinkercap.next; + while (currentthinker != &thinkercap) + { + nextthinker = currentthinker->next; + + if (currentthinker->function == (think_t) - 1) + { // time to remove it + currentthinker->next->prev = currentthinker->prev; + currentthinker->prev->next = currentthinker->next; + Z_Free(currentthinker); + } + else + { + if (currentthinker->function) + currentthinker->function(currentthinker); + } + currentthinker = nextthinker; + } +} + +//---------------------------------------------------------------------------- +// +// PROC P_Ticker +// +//---------------------------------------------------------------------------- + +void P_Ticker(void) +{ + int i; + + if (paused) + { + return; + } + for (i = 0; i < MAXPLAYERS; i++) + { + if (playeringame[i]) + { + P_PlayerThink(&players[i]); + } + } + if (TimerGame) + { + if (!--TimerGame) + { + G_ExitLevel(); + } + } + P_RunThinkers(); + P_UpdateSpecials(); + P_AmbientSound(); + leveltime++; +} diff --git a/pool/shard004/C/0100128_The_3n+1_Problem.c b/pool/shard004/C/0100128_The_3n+1_Problem.c new file mode 100644 index 0000000000000000000000000000000000000000..bc282d38afa3cd72df187541f6b2a3f42968edb7 --- /dev/null +++ b/pool/shard004/C/0100128_The_3n+1_Problem.c @@ -0,0 +1,18 @@ +#include +#include + +int main() +{ + unsigned long val; + unsigned long cou; + while(EOF!=scanf("%ld",&val)){ + cou=0; + while(val!=1){ + if(val%2==0) val=val/2; + else val=3*val+1; + cou++; + } + printf("%ld\n",cou); + } + return 0; +} diff --git a/pool/shard004/C/0100143_message.c b/pool/shard004/C/0100143_message.c new file mode 100644 index 0000000000000000000000000000000000000000..a5704d18dcd5a2710b942f20027032392ea05b66 --- /dev/null +++ b/pool/shard004/C/0100143_message.c @@ -0,0 +1,221 @@ +/* function definitions for message handling */ +#include +#include +#include "message.h" +#include "types.h" +#include "meta.h" + +//initialize the global variables (no messages and null pointers) +int message_count = 0; +Message* in_queue = 0; +Message* out_queue = 0; +Message* in_queue_end = 0; +Message* out_queue_end = 0; + +//define cache sizes and associations +#define MSG_CACHE_SIZE 32 +#define MSG_CACHE_MASK 3 +#define DATA_CACHE_SIZE 32 +#define DATA_CACHE_NUM 8 +#define DATA_CACHE_1B 0 +#define DATA_CACHE_2B 1 +#define DATA_CACHE_4B 2 +#define DATA_CACHE_6B 3 +#define DATA_CACHE_12B 6 + +/* create the data caches */ +uint8_t data_cache_1B[DATA_CACHE_SIZE]; +uint8_t data_cache_2B[DATA_CACHE_SIZE]; +uint8_t data_cache_4B[DATA_CACHE_SIZE]; +uint8_t data_cache_6B[DATA_CACHE_SIZE]; +uint8_t data_cache_12B[DATA_CACHE_SIZE]; //IMU uses this + +//setup the pointers to the data caches +uint8_t* data_cache_toplvl[DATA_CACHE_NUM] = {data_cache_1B, data_cache_2B, data_cache_4B, data_cache_6B, 0, 0, data_cache_12B, 0}; + +//32-bit map for used/unused words (1st bit is 1 if word is free) +uint32_t data_cache_map[DATA_CACHE_NUM]; //data cache avaliability tracker + +/* create the message cache */ +Message msg_cache[MSG_CACHE_SIZE] = {{0}}; //initialize all cache members to 0 +uint32_t msg_cache_map; //msg cache bit tracker +Message* get_node(); //get a message node +void free_node(Message* m); //clear the message node + +//message to initialize queues and caches +void init_msg_queue(){ + //wipe the message queues (mostly for resets) + wipe_queue(OUT_QUEUE); + wipe_queue(IN_QUEUE); + + message_count = 0; //reset the count + + //initalize the caches + data_cache_map[DATA_CACHE_1B] = 0x7FFFFFFF; //first bit is null + data_cache_map[DATA_CACHE_2B] = 0xAAAAAAAA; + data_cache_map[DATA_CACHE_4B] = 0x88888888; + data_cache_map[DATA_CACHE_6B] = 0x82082080; + data_cache_map[DATA_CACHE_12B] = 0x80080000; + msg_cache_map = 0xFFFFFFFF; +} + +/* Function will remove message from proper queue (1 for out/priority) + * Function gets the next message, places it in m, and deletes its reference + * Returns 0 (OK) if successful */ +int queue_pop(Message* m, int direction){ + //determine the proper queue + if(IN_QUEUE == direction){ //in queue + if(!in_queue) return MESSAGE_ERROR_TYPE; //queue is empty + *m = *in_queue; //copy the node + Message *next = in_queue->next; //store next node + free_node(in_queue); //free the memory + in_queue = next; //advance queue + } else{ //out queue + if(!out_queue) return MESSAGE_ERROR_TYPE; + *m = *out_queue; //add the node + Message *next = out_queue->next; //store next node + free_node(out_queue); //free the memory + out_queue = next; //advance queue + } + m->next = 0; //don't let return function see pointer + message_count--; + return OK; +} + +/* Function will add message to selected queue + * Returns 0 if successfull */ +int queue_push(Message m, int direction){ + if(MAX_MESSAGE <= message_count) return MESSAGE_ERROR_TYPE; //no more space + + //dont let messages enter queue before starting + if(!start_ok && direction) return; + + Message *new_msg = get_node(); //get the pointer + new_msg->type = m.type; //copy the data fields + new_msg->size = m.size; + new_msg->data = m.data; + new_msg->cache_tag = m.cache_tag; + + //deternew_msgine the proper queue + if(IN_QUEUE == direction){ //incming message + if(!in_queue){ //special case if queue is enew_msgpty + in_queue = new_msg; + in_queue_end = new_msg; + } else { //nornew_msgal execution + in_queue_end->next = new_msg; //add the node + in_queue_end = new_msg; //redefine the tail + } + } else { //out + if(!out_queue){ //check if queue is empty + out_queue = new_msg; + out_queue_end = new_msg; + } else { //nornew_msgal execution + out_queue_end->next = new_msg; //add the node + out_queue_end = new_msg; //redefoute the tail + } + } + message_count++; + return OK; +} + +//wrapper for message creation, size doesnt matter unless you're NB typed +// will try to get data storage from cache if avaliable +Message get_msg(uint8_t type, uint8_t size){ + Message m; + m.type = type; //get the type + + switch (type & DATA_MASK){ + case NO_DATA_TYPE: m.size = 0; break; + case DATA_1B_TYPE: m.size = 1; break; + case DATA_2B_TYPE: m.size = 2; break; + case DATA_NB_TYPE: m.size = size; break; + } + + if(!m.size){ //no_data types don't need caching + m.data = 0; + m.cache_tag = 0; + return m; + } + + int cache_num = -1; + switch(m.size){ + case 1: cache_num = DATA_CACHE_1B; break; + case 2: cache_num = DATA_CACHE_2B; break; + case 4: cache_num = DATA_CACHE_4B; break; + case 6: cache_num = DATA_CACHE_6B; break; + case 12: cache_num = DATA_CACHE_12B; break; + } + + //make sure cache exists and isn't full (map is empty) + if(-1 != cache_num && data_cache_map[cache_num]){ + for(int i=0; i> 5) & 7] |= 1 << (m.cache_tag & 0x1F); + m.cache_tag = 0; //no more cache + } + m.data = 0; //reset the data pointer + return m; +} + +//free the data associated with a linked-list node +void free_node(Message* m){ + if(m->msg_tag){ //message is valid, free cache + uint32_t bit = 1 << (m->msg_tag & 0x1F); //convert index to a bit + msg_cache_map |= bit; //set the bit to indicate avaliability + } else free(m); //otherwise free the data, was not cached +} + +//get a linked-list node +Message* get_node(){ + Message* m; + + if(msg_cache_map) //if location is avaliable + for(int i=0; imsg_tag = (0xC0 | (0x1F & i)); //tag (110)[7-5](index)[4-0] + msg_cache_map &= ~(1 << (MSG_CACHE_SIZE - i - 1)); //clear cache bit + return m; //we're done, return message + } + m = (Message*) calloc(1,sizeof(Message)); //cache unavaliable, allocate msg + + return m; +} + +//remove all messages from a queue (start and kill call this) +void wipe_queue(int direction){ + Message *p = (IN_QUEUE == direction)? in_queue : out_queue; + + while(p){ + free_msg(*p); //free the data + Message *next = p->next; //get the next pointer + free_node(p); //free the memory + p = next; //advance list + } + + //wipe the end pointer + if(IN_QUEUE == direction) in_queue_end = 0; + else out_queue_end = 0; +} + diff --git a/pool/shard004/C/0100147_wdt285.c b/pool/shard004/C/0100147_wdt285.c new file mode 100644 index 0000000000000000000000000000000000000000..176cdd252da05e6c731bc4c1bdcd8235639391dc --- /dev/null +++ b/pool/shard004/C/0100147_wdt285.c @@ -0,0 +1,209 @@ +/* + * Intel 21285 watchdog driver + * Copyright (c) Phil Blundell , 1998 + * + * based on + * + * SoftDog 0.05: A Software Watchdog Device + * + * (c) Copyright 1996 Alan Cox , + * All Rights Reserved. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version + * 2 of the License, or (at your option) any later version. + * + */ + +#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +#undef ONLY_TESTING + +static unsigned int soft_margin = 60; +static unsigned int reload; +static unsigned long timer_alive; + +#ifdef ONLY_TESTING +static void watchdog_fire(int irq, void *dev_id) +{ + pr_crit("Would Reboot\n"); + *CSR_TIMER4_CNTL = 0; + *CSR_TIMER4_CLR = 0; +} +#endif + +static void watchdog_ping(void) +{ + *CSR_TIMER4_LOAD = reload; +} + +static int watchdog_open(struct inode *inode, struct file *file) +{ + int ret; + + if (*CSR_SA110_CNTL & (1 << 13)) + return -EBUSY; + + if (test_and_set_bit(1, &timer_alive)) + return -EBUSY; + + reload = soft_margin * (mem_fclk_21285 / 256); + + *CSR_TIMER4_CLR = 0; + watchdog_ping(); + *CSR_TIMER4_CNTL = TIMER_CNTL_ENABLE | TIMER_CNTL_AUTORELOAD + | TIMER_CNTL_DIV256; + +#ifdef ONLY_TESTING + ret = request_irq(IRQ_TIMER4, watchdog_fire, 0, "watchdog", NULL); + if (ret) { + *CSR_TIMER4_CNTL = 0; + clear_bit(1, &timer_alive); + } +#else + *CSR_SA110_CNTL |= 1 << 13; + + ret = 0; +#endif + nonseekable_open(inode, file); + return ret; +} + +static int watchdog_release(struct inode *inode, struct file *file) +{ +#ifdef ONLY_TESTING + free_irq(IRQ_TIMER4, NULL); + clear_bit(1, &timer_alive); +#endif + return 0; +} + +static ssize_t watchdog_write(struct file *file, const char __user *data, + size_t len, loff_t *ppos) +{ + if (len) + watchdog_ping(); + + return len; +} + +static const struct watchdog_info ident = { + .options = WDIOF_SETTIMEOUT, + .identity = "Footbridge Watchdog", +}; + +static long watchdog_ioctl(struct file *file, unsigned int cmd, + unsigned long arg) +{ + unsigned int new_margin; + int __user *int_arg = (int __user *)arg; + int ret = -ENOTTY; + + switch (cmd) { + case WDIOC_GETSUPPORT: + ret = 0; + if (copy_to_user((void __user *)arg, &ident, sizeof(ident))) + ret = -EFAULT; + break; + + case WDIOC_GETSTATUS: + case WDIOC_GETBOOTSTATUS: + ret = put_user(0, int_arg); + break; + + case WDIOC_KEEPALIVE: + watchdog_ping(); + ret = 0; + break; + + case WDIOC_SETTIMEOUT: + ret = get_user(new_margin, int_arg); + if (ret) + break; + + + if (new_margin < 0 || new_margin > 60) { + ret = -EINVAL; + break; + } + + soft_margin = new_margin; + reload = soft_margin * (mem_fclk_21285 / 256); + watchdog_ping(); + + case WDIOC_GETTIMEOUT: + ret = put_user(soft_margin, int_arg); + break; + } + return ret; +} + +static const struct file_operations watchdog_fops = { + .owner = THIS_MODULE, + .llseek = no_llseek, + .write = watchdog_write, + .unlocked_ioctl = watchdog_ioctl, + .open = watchdog_open, + .release = watchdog_release, +}; + +static struct miscdevice watchdog_miscdev = { + .minor = WATCHDOG_MINOR, + .name = "watchdog", + .fops = &watchdog_fops, +}; + +static int __init footbridge_watchdog_init(void) +{ + int retval; + + if (machine_is_netwinder()) + return -ENODEV; + + retval = misc_register(&watchdog_miscdev); + if (retval < 0) + return retval; + + pr_info("Footbridge Watchdog Timer: 0.01, timer margin: %d sec\n", + soft_margin); + + if (machine_is_cats()) + pr_warn("Warning: Watchdog reset may not work on this machine\n"); + return 0; +} + +static void __exit footbridge_watchdog_exit(void) +{ + misc_deregister(&watchdog_miscdev); +} + +MODULE_AUTHOR("Phil Blundell "); +MODULE_DESCRIPTION("Footbridge watchdog driver"); +MODULE_LICENSE("GPL"); +MODULE_ALIAS_MISCDEV(WATCHDOG_MINOR); + +module_param(soft_margin, int, 0); +MODULE_PARM_DESC(soft_margin, "Watchdog timeout in seconds"); + +module_init(footbridge_watchdog_init); +module_exit(footbridge_watchdog_exit); diff --git a/pool/shard004/C/0100153_ipc_calculator.c b/pool/shard004/C/0100153_ipc_calculator.c new file mode 100644 index 0000000000000000000000000000000000000000..aff0f96dfe2eddbd404cb78ef72ec08d7be1f764 --- /dev/null +++ b/pool/shard004/C/0100153_ipc_calculator.c @@ -0,0 +1,238 @@ + +/** + * @file ipc_calculator.c + * @author Simone Girardi + * @date 27 jun 2016. + * @version 1.0 + */ + +#include "../headers/mylib.h" +#include "../headers/utils.h" +#include "../headers/parent.h" +#include "../headers/child.h" + +#ifndef DOXYGEN_SHOULD_SKIP_THIS + +#define GREEN "\033[32m" +#define RESET "\e[0m" +#define ORANGE "\033[38;5;208m" +#define PARENT "["ORANGE"Parent"RESET"]" +#define CALLER "ipc_calculator.c" + +#endif /* DOXYGEN_SHOULD_SKIP_THIS */ + +/** + * @brief the Main of the program + * + * @param argc the number of arguments + * @param argv the vector of parameter + * @return 0 + */ +int main(int argc, char *argv[]){ + + struct operation *operations; + struct operation *current_operation; + struct result* current_result; + + bool *child_isFree; + int id_number = -1; + int n_operations = -1; + int NPROC = 0; + int *childs_ready; + + const int SHM_COP = 101; + const int SHM_RES = 102; + const int SHM_STATUS = 103; + const int SHM_STARTED = 104; + + /* argv[1] must be the name of the file configuration */ + if (argc != 2) { + print("Usage: ./ipc_calculator.x \n", CALLER, __LINE__); + exit(1); + } + + // ========================================================================================================== + // SETUP - FROM FILE + // ========================================================================================================== + print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n" + "\e[7;36m IPC CALCULATOR \e[0m\n" + "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n", CALLER, __LINE__); + + int fd; + int i = 0; + char line[50]; + int line_count; + struct list* first_element = NULL; + struct list* last_element = NULL; + + /* open the file confoiguration */ + if((fd = open(argv[1], O_RDONLY|O_SYNC, S_IRUSR)) == -1){ + syserr (argv[0], "open() failure"); + } + + /* read the content of configuration file */ + line_count = read_from_file(fd, line, &first_element, &last_element); + + close(fd); + + if(line_count == 0 || first_element == NULL){ + syserr (argv[0], "file is empty or wrong formatted!"); + } + + // check for the number of processes to create + NPROC = atoi(first_element->value); + if(NPROC > 500 || NPROC < 0){ + syserr (argv[0], "NPROC is wrong!"); + } + + print("The the content of file is the follow:\n", CALLER, __LINE__); + /* print the content of file */ + list_print(first_element); + + // the first line isn't an operation + n_operations = line_count - 1; + + // allocate memory for operations + operations = (struct operation*)malloc(sizeof(struct operation)*n_operations); + + // take first element of this list as the first operation + struct list* list = first_element->next; + + // fill the list with operations (atoi() for numbers) + fill_list_operations(list, operations); + + // free the lines memory + list_free(first_element); + first_element = NULL; + + // ========================================================================================================== + // SETUP - SEMAPHORE + // ========================================================================================================== + + unsigned short *sem_init = (unsigned short*) malloc(sizeof(unsigned short) * NPROC); + for (i = 0; i < NPROC; i++) { + sem_init[i] = 0; + } + + /* CREATE semaphores for childs */ + sem_computing = do_semget(ftok(argv[0], 'a'), NPROC); + sem_wait_data = do_semget(ftok(argv[0], 'b'), NPROC); + sem_request_result = do_semget(ftok(argv[0], 'c'), NPROC); + + /* SETALL semphores to zero */ + initialize_sem(sem_computing, sem_init); + initialize_sem(sem_wait_data, sem_init); + initialize_sem(sem_request_result, sem_init); + + /* CREATE semaphore for parent */ + sem_parent = do_semget(ftok(argv[0], 'd') , 3); + + /* SETALL semaphore to follow values: + * 0: mutex + * 1: result_ready + * 2: data_read */ + sem_init = (unsigned short*) realloc(sem_init, sizeof(unsigned short) * 3); + *(sem_init) = 1; + *(sem_init + 1) = 0; + *(sem_init + 2) = 0; + + initialize_sem(sem_parent, sem_init); + + free(sem_init); + + int my_semaphores[] = { sem_computing, sem_wait_data, sem_request_result, sem_parent }; + + /* check the correct values of each semaphore */ + + //check_semval(sem_computing, NPROC); + //check_semval(sem_wait_data, NPROC); + //check_semval(sem_request_result, NPROC); + //check_semval(sem_parent, 3); + + // ========================================================================================================== + // SETUP - SHARED MEMORY + // ========================================================================================================== + current_operation = (struct operation*) xmalloc(SHM_COP, sizeof(struct operation)); + current_result = (struct result*) xmalloc(SHM_RES, sizeof(struct result)); + child_isFree = (bool*) xmalloc(SHM_STATUS, sizeof (bool*) * NPROC); + childs_ready = (int*) xmalloc(SHM_STARTED, sizeof(int)); + + /* initialize all the children as free */ + for(i = 0; i < NPROC; i++) + child_isFree[i] = true; + + /* initialize the number of childs_ready */ + *childs_ready = 0; + + + // ========================================================================================================== + // START - FORK() + // ========================================================================================================== + print("---------------------------------------\n" + " START CALCULATIONS \n" + "---------------------------------------\n", CALLER, __LINE__); + pid_t pid; + char str_info[100]; + + for (i = 0; i < NPROC; i++) + { + pid = fork(); + if (pid < 0) { + syserr("fork()", "cannot create a new process"); + } else if (pid == 0) { // code execute from child + id_number = i; // assign id number to child process + child(id_number, NPROC, my_semaphores, childs_ready, current_operation, current_result, child_isFree); + free(operations); + exit(0); + } else { + if(snprintf(str_info, 100, ""PARENT" create child %d with pid = %d\n" , i+1, pid) == -1){ + syserr(argv[0], "snprintf() error oversized string"); + } + print(str_info, CALLER, __LINE__); + } + } + + /* execute from parent */ + if(pid != 0) + { + float *results = my_parent(my_semaphores, n_operations, NPROC, operations, current_operation, current_result, child_isFree); + + /* free shared memory */ + xfree(childs_ready); + xfree(current_operation); + xfree(current_result); + xfree(child_isFree); + + /* delete all semaphores */ + delete_sem(sem_computing); + delete_sem(sem_wait_data); + delete_sem(sem_request_result); + delete_sem(sem_parent); + + // open/create the file for results + fd = open("results.txt", O_CREAT|O_RDWR|O_TRUNC, S_IRUSR|S_IWUSR ); + if (fd < 0) { + syserr ("results.txt", "open() failure"); + } + + + // write the results of operations on a file + char res[20]; + int ret_val; + for(i = 0; i < n_operations; i++) + { + sprintf(res, "%.2f\n", results[i]); + + if ((ret_val = (int) write(fd, res, strlen(res))) == -1) + syserr ("results", "write() on file failure"); + } + + close(fd); + free(operations); + free(results); + + print("The file \"results.txt\" is written in the sources directory\n", CALLER, __LINE__); + } + print("Program "GREEN"complete"RESET".\n", CALLER, __LINE__); + return 0; +} diff --git a/pool/shard004/C/0100155_database.c b/pool/shard004/C/0100155_database.c new file mode 100644 index 0000000000000000000000000000000000000000..40278e61a2ba9a5831e64f0f397516497d8865ad --- /dev/null +++ b/pool/shard004/C/0100155_database.c @@ -0,0 +1,245 @@ +/** + * @file database.c + * @author hbuyse + * @date 03/11/2015 + */ + +#include // dao, pdb_t, sort, pdb_t, str2time, time2str, by_date +#include // fprintf, printf, fscanf, FILE +#include // memset +#include // exit, qsort +#include // localtime, strftime, mktime, struct tm, strptime + + +/* Data Access Object (DAO) */ +pdb_t dao(int cmd, + FILE *f, + pdb_t in_db, + sort sortby + ) +{ + pdb_t *pdb = NULL; + pdb_t rec = NULL; + pdb_t hd = NULL; + int i = 0; + int ret = 0; + char buf[100]; + + + switch ( cmd ) + { + case CREATE: + { + fprintf(f, "\"%s\",", in_db->title); + fprintf(f, "\"%s\",", in_db->first_name); + fprintf(f, "\"%s\",", in_db->last_name); + fprintf(f, "\"%s\",", time2str(&in_db->date) ); + fprintf(f, "\"%s\" \n", in_db->publ); + break; + } + + + // Print all the elements contained in 'in_db' + case PRINT: + { + while ( in_db != NULL ) + { + printf("Title : %s\n", in_db->title); + printf("Author : %s %s\n", in_db->first_name, in_db->last_name); + printf("Date : %s\n", time2str(&in_db->date) ); + printf("Publication : %s\n\n", in_db->publ); + + if ( ! ( (i + 1) % 3) ) + { + printf("Press Enter to continue.\n"); + ret = scanf("%*[^\n]"); + + if ( ret < 0 ) + { + return (rec); /* handle EOF */ + } + else + { + getchar(); + } + } + + in_db = in_db->next; + } + + break; + } + + + // Store the element in 'in_db' + case READLINE: + { + if ( (fscanf(f, " \"%[^\"]\",", in_db->title) ) < 0 ) + { + break; + } + + if ( (fscanf(f, " \"%[^\"]\",", in_db->first_name) ) < 0 ) + { + break; + } + + if ( (fscanf(f, " \"%[^\"]\",", in_db->last_name) ) < 0 ) + { + break; + } + + if ( (fscanf(f, " \"%[^\"]\",", buf) ) < 0 ) + { + break; + } + + if ( (fscanf(f, " \"%[^\"]\" ", in_db->publ) ) < 0 ) + { + break; + } + + in_db->date = str2time(buf); + break; + } + + + // Read the whole database file and store the contents in 'rec' + case READ: + { + while ( ! feof(f) ) + { + dao(READLINE, f, in_db, NULL); + + if ( ! (rec = malloc(sizeof(db_t) ) ) ) + { + perror("Could not allocate 'rec'"); + exit(1); + } + + *rec = *in_db; /* copy contents */ + rec->next = hd; /* to linked list */ + hd = rec; + i++; + } + + if ( i < 1 ) + { + puts("Empty database. Please create some entries."); + fclose(f); + exit(0); + } + + break; + } + + + // Print all the element sorted + case SORT: + { + rec = in_db; + + while ( in_db != NULL ) + { + in_db = in_db->next; + } + + if ( ! (pdb = malloc(i * sizeof(pdb_t) ) ) ) + { + perror("Could not allocate 'pdb'"); + exit(1); + } + + in_db = rec; + + for ( i = 0; in_db; i++ ) + { + pdb[i] = in_db; + in_db = in_db->next; + } + + qsort(pdb, i, sizeof(in_db), sortby); + pdb[i - 1]->next = NULL; + + for ( i = i - 1; i; i-- ) + { + pdb[i - 1]->next = pdb[i]; + } + + rec = pdb[0]; + + if ( pdb ) + { + free(pdb); + pdb = NULL; + } + + pdb = NULL; + break; + } + + + // Delete all the element that are in the database + case DESTROY: + { + while ( (rec = in_db) ) + { + in_db = in_db->next; + + if ( rec ) + { + free(rec); + rec = NULL; + } + } + } + } + + return (rec); +} + + + +/* convert numeric time to date string */ +char* time2str(time_t *time) +{ + static char buf[255]; + struct tm *ptm; + + + ptm = localtime(time); + strftime(buf, 255, "%m-%d-%Y", ptm); + + return (buf); +} + + + +/* convert date string to numeric time */ +time_t str2time(char *date) +{ + struct tm tm; + + + memset(&tm, 0, sizeof(struct tm) ); + strptime(date, "%m-%d-%Y", &tm); + + return (mktime(&tm) ); +} + + + +/* sort by date callback for qsort */ +int by_date(pdb_t *p1, + pdb_t *p2 + ) +{ + if ( (*p1)->date < (*p2)->date ) + { + return (-1); + } + else + { + return ( (*p1)->date > (*p2)->date); + } +} \ No newline at end of file diff --git a/pool/shard004/C/0100158_ipv4-addr.c b/pool/shard004/C/0100158_ipv4-addr.c new file mode 100644 index 0000000000000000000000000000000000000000..db87a667f38a0beea7c2dae18078692ec69469b0 --- /dev/null +++ b/pool/shard004/C/0100158_ipv4-addr.c @@ -0,0 +1,45 @@ +/* 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 "haka/ipv4.h" + +#include +#include + +#include +#include + +uint32 ipv4_addr_from_string(const char *string) +{ + struct in_addr addr; + + if (inet_pton(AF_INET, string, &addr) <= 0) { + error("invalid IPv4 address format"); + return 0; + } + + return SWAP_FROM_BE(ipv4addr, addr.s_addr); +} + +void ipv4_addr_to_string(ipv4addr addr, char *string, size_t size) +{ + UNUSED const char *ret; + addr = SWAP_TO_BE(ipv4addr, addr); + ret = inet_ntop(AF_INET, &addr, string, size); + assert(ret); +} + +ipv4addr ipv4_addr_from_bytes(uint8 a, uint8 b, uint8 c, uint8 d) +{ + ipv4addr addr; + uint8* bytes = (uint8*)&addr; + +#if HAKA_LITTLEENDIAN + bytes[3] = a; bytes[2] = b; bytes[1] = c; bytes[0] = d; +#else + bytes[0] = a; bytes[1] = b; bytes[2] = c; bytes[3] = d; +#endif + + return addr; +} diff --git a/pool/shard004/C/0100159_timer_90k.c b/pool/shard004/C/0100159_timer_90k.c new file mode 100644 index 0000000000000000000000000000000000000000..1ac2ddca397ad35f4240be8ae1f973143a9a9a3e --- /dev/null +++ b/pool/shard004/C/0100159_timer_90k.c @@ -0,0 +1,305 @@ +/* + * (C) Copyright 2010 + * jung hyun kim, Nexell Co, + * + * 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 + +/* nexell soc headers */ +#include +#include + +#if (0) +#define DBGOUT(msg...) { printk(KERN_INFO "timer_90k: " msg); } +#else +#define DBGOUT(msg...) do {} while (0) +#endif + +/*------------------------------------------------------------------------------ + * data + */ +struct timer_90k_tick { + unsigned long sec; + unsigned long tick; /* 0 ~ 90khz */ +}; + +struct timer_sys_tick { + unsigned long sec; + unsigned long tick; /* 0 ~ 90khz */ + unsigned long irq_tick; /* 0 ~ 90khz */ + spinlock_t lock; +}; + +/*------------------------------------------------------------------------------ + * ioctl + */ +#include + +enum { + IOCTL_TIMER_90K_GET_TICK = _IO(IOC_NX_MAGIC, 0), +}; + +#define TICK_HZ 90000 + +static struct timer_sys_tick tick_cnt = { 0, }; +/*------------------------------------------------------------------------------ + */ +static irqreturn_t do_irq_handler(int irq, void *desc) +{ + tick_cnt.sec++; + tick_cnt.irq_tick = NX_TIMER_GetTimerCounter(CFG_TIMER_90K_TICK_CH); + NX_TIMER_ClearInterruptPendingAll(CFG_TIMER_90K_TICK_CH); + + return IRQ_HANDLED; +} + +static void get_tick(struct timer_90k_tick *tick) +{ + unsigned int count, value; + int irq; + unsigned long flags; + + DBGOUT("%s\n", __func__); + + irq = NX_TIMER_GetInterruptNumber(CFG_TIMER_90K_TICK_CH); + + /* lock */ + spin_lock_irqsave(&tick_cnt.lock, flags); + + value = NX_TIMER_GetTimerCounter(CFG_TIMER_90K_TICK_CH); + count = value; + + /* count = count * 0.09; */ + count = count * ((TICK_HZ*1000)/CFG_TIMER_90K_TICK_CLKFREQ); + count = count/1000; + + tick->sec = tick_cnt.sec; + tick->tick = count; + + if ( tick_cnt.irq_tick != value && + (CFG_TIMER_90K_TICK_CLKFREQ == value || 0 == value) ) { + tick->sec += 1; + tick->tick = 0; + } + + /* unlock */ + spin_unlock_irqrestore(&tick_cnt.lock, flags); +} + +static int timer_90k_ops_open(struct inode *inode, struct file *flip) +{ + DBGOUT("%s\n", __func__); + return 0; +} + +static int timer_90k_ops_release(struct inode *inode, struct file *flip) +{ + DBGOUT("%s\n", __func__); + return 0; +} + +static int timer_90k_ops_ioctl(struct inode *inode, struct file *filp, unsigned int cmd, unsigned long arg) +{ + DBGOUT("%s(cmd:0x%x)\n", __func__, cmd); + + switch (cmd) { + case IOCTL_TIMER_90K_GET_TICK: + { + struct timer_90k_tick tick; + if (copy_from_user(&tick, (const void __user *)arg, sizeof(struct timer_90k_tick))) + return -EFAULT; + + get_tick(&tick); + + if (copy_to_user((void __user *)arg, (const void *)&tick, sizeof(struct timer_90k_tick))) + return -EFAULT; + } + break; + + default: + printk(KERN_ERR "%s: fail, unknown command 0x%x, \n", + TIMER_90K_DEV_NAME, cmd); + return -EINVAL; + } + + DBGOUT("IoCtl (cmd:0x%x) \n\n", cmd); + return 0; +} + +struct file_operations timer_90k_ops = { + .owner = THIS_MODULE, + .open = timer_90k_ops_open, + .release= timer_90k_ops_release, + .ioctl = timer_90k_ops_ioctl, +}; + +/*-------------------------------------------------------------------------------- + * platform_driver functions + ---------------------------------------------------------------------------------*/ +static int __init timer_90k_drv_probe(struct platform_device *pdev) +{ + int irq = -1, ret; + + /* timer hw */ + NX_TIMER_Initialize(); + NX_TIMER_SetBaseAddress(CFG_TIMER_90K_TICK_CH, + (U32)IO_ADDRESS(NX_TIMER_GetPhysicalAddress(CFG_TIMER_90K_TICK_CH))); + NX_TIMER_OpenModule(CFG_TIMER_90K_TICK_CH); + + NX_TIMER_SetClockDivisorEnable(CFG_TIMER_90K_TICK_CH, CFALSE); + NX_TIMER_SetClockSource (CFG_TIMER_90K_TICK_CH, 0, CFG_TIMER_90K_TICK_CLKSRC); + NX_TIMER_SetClockDivisor(CFG_TIMER_90K_TICK_CH, 0, CFG_TIMER_90K_TICK_CLKDIV); + NX_TIMER_SetClockPClkMode(CFG_TIMER_90K_TICK_CH, NX_PCLKMODE_ALWAYS); + + NX_TIMER_SetClockDivisorEnable(CFG_TIMER_90K_TICK_CH, CTRUE); + NX_TIMER_Stop(CFG_TIMER_90K_TICK_CH); + + NX_TIMER_SetWatchDogEnable(CFG_TIMER_90K_TICK_CH, CFALSE); + NX_TIMER_SetInterruptEnableAll(CFG_TIMER_90K_TICK_CH, CFALSE); + NX_TIMER_SetTClkDivider(CFG_TIMER_90K_TICK_CH, NX_TIMER_CLOCK_TCLK); + NX_TIMER_ClearInterruptPendingAll(CFG_TIMER_90K_TICK_CH); + + NX_TIMER_SetTimerCounter(CFG_TIMER_90K_TICK_CH, 0); + NX_TIMER_SetMatchCounter(CFG_TIMER_90K_TICK_CH, CFG_TIMER_90K_TICK_CLKFREQ); + + irq = NX_TIMER_GetInterruptNumber(CFG_TIMER_90K_TICK_CH); + + /* register driver */ + ret = register_chrdev(TIMER_90K_DEV_MAJOR, "timer(90khz)", &timer_90k_ops); + if (0 > ret) { + printk(KERN_ERR "fail, register device (%s, major:%d)\n", + TIMER_90K_DEV_NAME, TIMER_90K_DEV_MAJOR); + return ret; + } + + /* register interrupt */ + ret = request_irq(irq, &do_irq_handler, IRQF_DISABLED, TIMER_90K_DEV_NAME, NULL); + if (ret) { + printk(KERN_ERR "Error, request_irq(irq:%d)\n", irq); + unregister_chrdev(TIMER_90K_DEV_MAJOR, TIMER_90K_DEV_NAME); + return ret; + } + NX_TIMER_SetInterruptEnableAll(CFG_TIMER_90K_TICK_CH, CTRUE); + NX_TIMER_Run(CFG_TIMER_90K_TICK_CH); + + spin_lock_init(&tick_cnt.lock); + + printk(KERN_INFO "%s: register major:%d, irq:%d\n", + pdev->name, TIMER_90K_DEV_MAJOR, irq); + return 0; +} + +static int timer_90k_drv_remove(struct platform_device *pdev) +{ + int irq; + DBGOUT("%s\n", __func__); + + irq = NX_TIMER_GetInterruptNumber(CFG_TIMER_90K_TICK_CH); + + NX_TIMER_SetInterruptEnableAll(CFG_TIMER_90K_TICK_CH, CFALSE); + NX_TIMER_Stop(CFG_TIMER_90K_TICK_CH); + NX_TIMER_SetClockDivisorEnable(CFG_TIMER_90K_TICK_CH, CFALSE); // Disable Timer Clock + + free_irq(irq, NULL); + unregister_chrdev(TIMER_90K_DEV_MAJOR, "timer(90khz)"); + return 0; +} + +static unsigned int saved_count; +static int timer_90k_drv_suspend(struct platform_device *dev, pm_message_t state) +{ + PM_DBGOUT("+%s\n", __func__); + + saved_count = NX_TIMER_GetTimerCounter(CFG_TIMER_90K_TICK_CH); + + PM_DBGOUT("-%s\n", __func__); + return 0; +} + +static int timer_90k_drv_resume(struct platform_device *dev) +{ + u_long flags; + + PM_DBGOUT("+%s\n", __func__); + + if (NX_TIMER_GetClockDivisorEnable(CFG_TIMER_90K_TICK_CH)) + return 0; + + local_irq_save(flags); + + NX_TIMER_SetClockDivisorEnable(CFG_TIMER_90K_TICK_CH, CFALSE); + NX_TIMER_SetClockSource (CFG_TIMER_90K_TICK_CH, 0, CFG_TIMER_90K_TICK_CLKSRC); + NX_TIMER_SetClockDivisor(CFG_TIMER_90K_TICK_CH, 0, CFG_TIMER_90K_TICK_CLKDIV); + NX_TIMER_SetClockPClkMode(CFG_TIMER_90K_TICK_CH, NX_PCLKMODE_ALWAYS); + + NX_TIMER_SetClockDivisorEnable(CFG_TIMER_90K_TICK_CH, CTRUE); + NX_TIMER_Stop(CFG_TIMER_90K_TICK_CH); + + NX_TIMER_SetWatchDogEnable(CFG_TIMER_90K_TICK_CH, CFALSE); + NX_TIMER_SetInterruptEnableAll(CFG_TIMER_90K_TICK_CH, CFALSE); + NX_TIMER_SetTClkDivider(CFG_TIMER_90K_TICK_CH, NX_TIMER_CLOCK_TCLK); + NX_TIMER_ClearInterruptPendingAll(CFG_TIMER_90K_TICK_CH); + + NX_TIMER_SetTimerCounter(CFG_TIMER_90K_TICK_CH, saved_count); + NX_TIMER_SetMatchCounter(CFG_TIMER_90K_TICK_CH, CFG_TIMER_90K_TICK_CLKFREQ); + + + NX_TIMER_SetInterruptEnableAll(CFG_TIMER_90K_TICK_CH, CTRUE); + NX_TIMER_Run(CFG_TIMER_90K_TICK_CH); + + local_irq_restore(flags); + + PM_DBGOUT("-%s\n", __func__); + return 0; +} + +static struct platform_driver pwm_plat_driver = { + .probe = timer_90k_drv_probe, + .remove = timer_90k_drv_remove, + .suspend = timer_90k_drv_suspend, + .resume = timer_90k_drv_resume, + .driver = { + .owner = THIS_MODULE, + .name = TIMER_90K_DEV_NAME, + }, +}; + +static int __init timer_90k_drv_init(void) +{ + DBGOUT("%s\n", __func__); + return platform_driver_register(&pwm_plat_driver); +} + +static void __exit timer_90k_drv_exit(void) +{ + DBGOUT("%s\n", __func__); + platform_driver_unregister(&pwm_plat_driver); +} + +module_init(timer_90k_drv_init); +module_exit(timer_90k_drv_exit); + +MODULE_AUTHOR("jhkim "); +MODULE_DESCRIPTION("90Khz timer driver for the Nexell"); +MODULE_LICENSE("GPL"); + diff --git a/pool/shard004/C/0100170_bitmap.c b/pool/shard004/C/0100170_bitmap.c new file mode 100644 index 0000000000000000000000000000000000000000..79ff34752a88134684043f4f61daf332082fc7f3 --- /dev/null +++ b/pool/shard004/C/0100170_bitmap.c @@ -0,0 +1,122 @@ +/* + * Copyright © 2014-2015 - Vitaliy Perevertun + */ + + +#include +#include + +#include "bitmap.h" + + +#define szHead 54 + + +static void bmp_decode(unsigned char *header, bmp_head_t *pHead, bmp_info_t *pInfo); + +int bmp_load(const char *filename, bmp_t *bmp) +{ + FILE *file = fopen(filename, "rb"); + if (!file) + return -1; + + unsigned char header[szHead]; + + size_t sz = fread(header, 1, szHead, file); + if (sz != szHead || *(short*)header != 0x4D42) + { + fclose(file); + return -2; + } + + int i = 0; + bmp_head_t *pHead = &bmp->head; + bmp_info_t *pInfo = &bmp->info; + + bmp_decode(header, pHead, pInfo); + + + char *pData = malloc(pInfo->szImage); + if (!pData) + { + fclose(file); + return -3; + } + + i = 0; + while (i < pInfo->height) + { + fread(pData + (pInfo->height-i-1)*4* pInfo->width, 1, pInfo->width*4, file); + i++; + } + + fclose(file); + + bmp->data = pData; + + return 0; +} + +void bmp_bgr2rgb(bmp_t *bmp) +{ + bmp_info_t *pInfo = &bmp->info; + + int i = 0; + char *p = bmp->data; + + if (pInfo->bpp == 32) + { + char c; + for (i = 0; i < pInfo->szImage; i+=4) + { + c = p[i]; + p[i] = p[i+2]; + p[i+2] = c; + } + } +} + +static void bmp_decode(unsigned char *header, bmp_head_t *pHead, bmp_info_t *pInfo) +{ + /* decode bmp header */ + pHead->type = *(short*)header; + header += 2; + pHead->size = *(int*)header; + header += 4; + pHead->res1 = *(short*)header; + header += 2; + pHead->res2 = *(short*)header; + header += 2; + pHead->off = *(int*)header; + header += 4; + + if (pHead->off == 0) + pHead->off = 54; + + /* decode bmp info */ + pInfo->size = *(int*)header; + header += 4; + pInfo->width = *(int*)header; + header += 4; + pInfo->height = *(int*)header; + header += 4; + pInfo->planes = *(short*)header; + header += 2; + pInfo->bpp = *(short*)header; + header += 2; + pInfo->comp = *(int*)header; + header += 4; + pInfo->szImage = *(int*)header; + header += 4; + + if (pInfo->szImage == 0) + pInfo->szImage = pInfo->bpp/8 * pInfo->width * pInfo->height; + + pInfo->xPelsPerMeter = *(int*)header; + header += 4; + pInfo->yPelsPerMeter = *(int*)header; + header += 4; + pInfo->clrUsed = *(int*)header; + header += 4; + pInfo->clrImportant = *(int*)header; +} diff --git a/pool/shard004/C/0100185_strided_get_indexed.c b/pool/shard004/C/0100185_strided_get_indexed.c new file mode 100644 index 0000000000000000000000000000000000000000..3a98d298797fc982747b9912c123aef18541e423 --- /dev/null +++ b/pool/shard004/C/0100185_strided_get_indexed.c @@ -0,0 +1,133 @@ +/* -*- Mode: C; c-basic-offset:4 ; indent-tabs-mode:nil ; -*- */ +/* + * (C) 2001 by Argonne National Laboratory. + * See COPYRIGHT in top-level directory. + */ + +/* One-Sided MPI 2-D Strided Get Test + * + * Author: James Dinan + * Date : December, 2010 + * + * This code performs N strided get operations from a 2d patch of a shared + * array. The array has dimensions [X, Y] and the subarray has dimensions + * [SUB_X, SUB_Y] and begins at index [0, 0]. The input and output buffers are + * specified using an MPI indexed type. + */ + +#include +#include +#include +#include +#include "mpitest.h" +#include "squelch.h" + +#define XDIM 8 +#define YDIM 1024 +#define SUB_XDIM 8 +#define SUB_YDIM 256 + +int main(int argc, char **argv) { + int i, j, rank, nranks, peer, bufsize, errors; + double *win_buf, *loc_buf; + MPI_Win buf_win; + + int idx_rem[SUB_YDIM]; + int blk_len[SUB_YDIM]; + MPI_Datatype loc_type, rem_type; + + MTest_Init(&argc, &argv); + + MPI_Comm_rank(MPI_COMM_WORLD, &rank); + MPI_Comm_size(MPI_COMM_WORLD, &nranks); + + bufsize = XDIM * YDIM * sizeof(double); + MPI_Alloc_mem(bufsize, MPI_INFO_NULL, &win_buf); + MPI_Alloc_mem(bufsize, MPI_INFO_NULL, &loc_buf); + + for (i = 0; i < XDIM*YDIM; i++) { + *(win_buf + i) = 1.0 + rank; + *(loc_buf + i) = -1.0; + } + + MPI_Win_create(win_buf, bufsize, 1, MPI_INFO_NULL, MPI_COMM_WORLD, &buf_win); + + peer = (rank+1) % nranks; + + /* Build the datatype */ + + for (i = 0; i < SUB_YDIM; i++) { + idx_rem[i] = i*XDIM; + blk_len[i] = SUB_XDIM; + } + + MPI_Type_indexed(SUB_YDIM, blk_len, idx_rem, MPI_DOUBLE, &loc_type); + MPI_Type_indexed(SUB_YDIM, blk_len, idx_rem, MPI_DOUBLE, &rem_type); + + MPI_Type_commit(&loc_type); + MPI_Type_commit(&rem_type); + + /* Perform get operation */ + + MPI_Win_lock(MPI_LOCK_EXCLUSIVE, peer, 0, buf_win); + + MPI_Get(loc_buf, 1, loc_type, peer, 0, 1, rem_type, buf_win); + + /* Use the datatype only on the remote side (must have SUB_XDIM == XDIM) */ + /* MPI_Get(loc_buf, SUB_XDIM*SUB_YDIM, MPI_DOUBLE, peer, 0, 1, rem_type, buf_win); */ + + MPI_Win_unlock(peer, buf_win); + + MPI_Type_free(&loc_type); + MPI_Type_free(&rem_type); + + MPI_Barrier(MPI_COMM_WORLD); + + /* Verify that the results are correct */ + + errors = 0; + for (i = 0; i < SUB_XDIM; i++) { + for (j = 0; j < SUB_YDIM; j++) { + const double actual = *(loc_buf + i + j*XDIM); + const double expected = (1.0 + peer); + if (fabs(actual - expected) > 1.0e-10) { + SQUELCH( printf("%d: Data validation failed at [%d, %d] expected=%f actual=%f\n", + rank, j, i, expected, actual); ); + errors++; + fflush(stdout); + } + } + } + for (i = SUB_XDIM; i < XDIM; i++) { + for (j = 0; j < SUB_YDIM; j++) { + const double actual = *(loc_buf + i + j*XDIM); + const double expected = -1.0; + if (fabs(actual - expected) > 1.0e-10) { + SQUELCH( printf("%d: Data validation failed at [%d, %d] expected=%f actual=%f\n", + rank, j, i, expected, actual); ); + errors++; + fflush(stdout); + } + } + } + for (i = 0; i < XDIM; i++) { + for (j = SUB_YDIM; j < YDIM; j++) { + const double actual = *(loc_buf + i + j*XDIM); + const double expected = -1.0; + if (fabs(actual - expected) > 1.0e-10) { + SQUELCH( printf("%d: Data validation failed at [%d, %d] expected=%f actual=%f\n", + rank, j, i, expected, actual); ); + errors++; + fflush(stdout); + } + } + } + + MPI_Win_free(&buf_win); + MPI_Free_mem(win_buf); + MPI_Free_mem(loc_buf); + + MTest_Finalize( errors ); + MPI_Finalize(); + return MTestReturnValue( errors ); +} diff --git a/pool/shard004/C/0100186_checkdigit.c b/pool/shard004/C/0100186_checkdigit.c new file mode 100644 index 0000000000000000000000000000000000000000..0c820c3b83fa643e5be2e468eabab19ce3524136 --- /dev/null +++ b/pool/shard004/C/0100186_checkdigit.c @@ -0,0 +1,49 @@ +#include +#include +#include +#include "checkdigit.h" + +int main(int argc, char const *argv[]) { + if (argc != 2) { + printf("You must provide one card number to check.\n"); + return 2; + } + if (strlen(argv[1]) != 16) { + printf("Invalid credit card number.\n"); + return 2; + } + if (checkdigit(strtol(argv[1], NULL, 10))) { + printf("The provided credit card number is valid.\n"); + return 0; + } else { + printf("The provided credit card number is invalid.\n"); + return 1; + } +} + +int checkdigit(long int num) { + int sum = 0; + int check = num % 10; // Get last digit, i.e. the checkdigit + num /= 10; // Integer math truncates, so this just strips off the last digit + + for (int i = 1; i < 16; ++i) { + int current = num % 10; + + // If the number is five or bigger, it times two will be 10 + some single digit number + if (i % 2) { + if (current >= 5) { + sum += 1; + } + sum += ((2*current) % 10); + } else { + sum += current; + } + + num /= 10; + } + + // Find the number we need to add to the checksum to make it mod 10 = 0 + sum = (10 - (sum % 10)) % 10; + + return (sum == check ? 1 : 0); +} diff --git a/pool/shard004/C/0100191_ccm_process.c b/pool/shard004/C/0100191_ccm_process.c new file mode 100644 index 0000000000000000000000000000000000000000..90ce706e4bfcd2968468edf4ebd533a9e1c6a408 --- /dev/null +++ b/pool/shard004/C/0100191_ccm_process.c @@ -0,0 +1,88 @@ +/* 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. + */ +#include "tomcrypt.h" + +#ifdef LTC_CCM_MODE + +/** + Process plaintext/ciphertext through CCM + @param ccm The CCM state + @param pt The plaintext + @param ptlen The plaintext length (ciphertext length is the same) + @param ct The ciphertext + @param direction Encrypt or Decrypt mode (CCM_ENCRYPT or CCM_DECRYPT) + @return CRYPT_OK on success + */ +int ccm_process(ccm_state *ccm, + unsigned char *pt, unsigned long ptlen, + unsigned char *ct, + int direction) +{ + unsigned char z, b; + unsigned long y; + int err; + + LTC_ARGCHK(ccm != NULL); + + /* Check aad has been correctly added */ + if (ccm->aadlen != ccm->current_aadlen) { + return CRYPT_ERROR; + } + + /* Check we do not process too much data */ + if (ccm->ptlen < ccm->current_ptlen + ptlen) { + return CRYPT_ERROR; + } + ccm->current_ptlen += ptlen; + + /* now handle the PT */ + if (ptlen > 0) { + LTC_ARGCHK(pt != NULL); + LTC_ARGCHK(ct != NULL); + + for (y = 0; y < ptlen; y++) { + /* increment the ctr? */ + if (ccm->CTRlen == 16) { + for (z = 15; z > 15-ccm->L; z--) { + ccm->ctr[z] = (ccm->ctr[z] + 1) & 255; + if (ccm->ctr[z]) break; + } + if ((err = cipher_descriptor[ccm->cipher].ecb_encrypt(ccm->ctr, ccm->CTRPAD, &ccm->K)) != CRYPT_OK) { + return err; + } + ccm->CTRlen = 0; + } + + /* if we encrypt we add the bytes to the MAC first */ + if (direction == CCM_ENCRYPT) { + b = pt[y]; + ct[y] = b ^ ccm->CTRPAD[ccm->CTRlen++]; + } else { + b = ct[y] ^ ccm->CTRPAD[ccm->CTRlen++]; + pt[y] = b; + } + + if (ccm->x == 16) { + if ((err = cipher_descriptor[ccm->cipher].ecb_encrypt(ccm->PAD, ccm->PAD, &ccm->K)) != CRYPT_OK) { + return err; + } + ccm->x = 0; + } + ccm->PAD[ccm->x++] ^= b; + } + } + + return CRYPT_OK; +} + +#endif + +/* ref: HEAD -> master, tag: v1.18.2 */ +/* git commit: 7e7eb695d581782f04b24dc444cbfde86af59853 */ +/* commit time: 2018-07-01 22:49:01 +0200 */ diff --git a/pool/shard004/C/0100195_view.c b/pool/shard004/C/0100195_view.c new file mode 100644 index 0000000000000000000000000000000000000000..b2d86513d4f49a5fe16fa77a56dda6570efc6cbc --- /dev/null +++ b/pool/shard004/C/0100195_view.c @@ -0,0 +1,207 @@ +/* + * services/view.c - named views containing local zones authority service. + * + * Copyright (c) 2016, NLnet Labs. All rights reserved. + * + * This software is open source. + * + * 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 NLNET LABS 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 + * + * This file contains functions to enable named views that can hold local zone + * authority service. + */ +#include "config.h" +#include "services/view.h" +#include "services/localzone.h" +#include "util/config_file.h" + +int +view_cmp(const void* v1, const void* v2) +{ + struct view* a = (struct view*)v1; + struct view* b = (struct view*)v2; + + return strcmp(a->name, b->name); +} + +struct views* +views_create(void) +{ + struct views* v = (struct views*)calloc(1, + sizeof(*v)); + if(!v) + return NULL; + rbtree_init(&v->vtree, &view_cmp); + lock_rw_init(&v->lock); + lock_protect(&v->lock, &v->vtree, sizeof(v->vtree)); + return v; +} + +void +view_delete(struct view* v) +{ + if(!v) + return; + lock_rw_destroy(&v->lock); + local_zones_delete(v->local_zones); + free(v->name); + free(v); +} + +static void +delviewnode(rbnode_t* n, void* ATTR_UNUSED(arg)) +{ + struct view* v = (struct view*)n; + view_delete(v); +} + +void +views_delete(struct views* v) +{ + if(!v) + return; + lock_rw_destroy(&v->lock); + traverse_postorder(&v->vtree, delviewnode, NULL); + free(v); +} + +/** create a new view */ +static struct view* +view_create(char* name) +{ + struct view* v = (struct view*)calloc(1, sizeof(*v)); + if(!v) + return NULL; + v->node.key = v; + if(!(v->name = strdup(name))) { + free(v); + return NULL; + } + lock_rw_init(&v->lock); + lock_protect(&v->lock, &v->name, sizeof(*v)-sizeof(rbnode_t)); + return v; +} + +/** enter a new view returns with WRlock */ +static struct view* +views_enter_view_name(struct views* vs, char* name) +{ + struct view* v = view_create(name); + if(!v) { + log_err("out of memory"); + return NULL; + } + + /* add to rbtree */ + lock_rw_wrlock(&vs->lock); + lock_rw_wrlock(&v->lock); + if(!rbtree_insert(&vs->vtree, &v->node)) { + log_warn("duplicate view: %s", name); + lock_rw_unlock(&v->lock); + view_delete(v); + lock_rw_unlock(&vs->lock); + return NULL; + } + lock_rw_unlock(&vs->lock); + return v; +} + +int +views_apply_cfg(struct views* vs, struct config_file* cfg) +{ + struct config_view* cv; + struct view* v; + struct config_file lz_cfg; + /* Check existence of name in first view (last in config). Rest of + * views are already checked when parsing config. */ + if(cfg->views && !cfg->views->name) { + log_err("view without a name"); + return 0; + } + for(cv = cfg->views; cv; cv = cv->next) { + /* create and enter view */ + if(!(v = views_enter_view_name(vs, cv->name))) + return 0; + v->isfirst = cv->isfirst; + if(cv->local_zones || cv->local_data) { + if(!(v->local_zones = local_zones_create())){ + lock_rw_unlock(&v->lock); + return 0; + } + memset(&lz_cfg, 0, sizeof(lz_cfg)); + lz_cfg.local_zones = cv->local_zones; + lz_cfg.local_data = cv->local_data; + lz_cfg.local_zones_nodefault = + cv->local_zones_nodefault; + if(!local_zones_apply_cfg(v->local_zones, &lz_cfg)){ + lock_rw_unlock(&v->lock); + return 0; + } + /* local_zones, local_zones_nodefault and local_data + * are free'd from config_view by local_zones_apply_cfg. + * Set pointers to NULL. */ + cv->local_zones = NULL; + cv->local_data = NULL; + cv->local_zones_nodefault = NULL; + } + lock_rw_unlock(&v->lock); + } + return 1; +} + +/** find a view by name */ +struct view* +views_find_view(struct views* vs, const char* name, int write) +{ + struct view* v; + struct view key; + key.node.key = &v; + key.name = (char *)name; + lock_rw_rdlock(&vs->lock); + if(!(v = (struct view*)rbtree_search(&vs->vtree, &key.node))) { + lock_rw_unlock(&vs->lock); + return 0; + } + if(write) { + lock_rw_wrlock(&v->lock); + } else { + lock_rw_rdlock(&v->lock); + } + lock_rw_unlock(&vs->lock); + return v; +} + +void views_print(struct views* v) +{ + /* TODO implement print */ + (void)v; +} diff --git a/pool/shard004/C/0100197_cache_vrt_re.c b/pool/shard004/C/0100197_cache_vrt_re.c new file mode 100644 index 0000000000000000000000000000000000000000..867ec86ce2bcf37ff9d3371e0ea8d7288da8f197 --- /dev/null +++ b/pool/shard004/C/0100197_cache_vrt_re.c @@ -0,0 +1,164 @@ +/*- + * Copyright (c) 2006 Verdens Gang AS + * Copyright (c) 2006-2011 Varnish Software AS + * All rights reserved. + * + * Author: Poul-Henning Kamp + * + * 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 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. + * + * Runtime support for compiled VCL programs, regexps + */ + +#include "config.h" + +#include + +#include "cache.h" + +#include "vre.h" +#include "vrt.h" + +void +VRT_re_init(void **rep, const char *re) +{ + vre_t *t; + const char *error; + int erroroffset; + + /* This was already check-compiled by the VCL compiler */ + t = VRE_compile(re, 0, &error, &erroroffset); + AN(t); + *rep = t; +} + +void +VRT_re_fini(void *rep) +{ + vre_t *vv; + + vv = rep; + if (rep != NULL) + VRE_free(&vv); +} + +int +VRT_re_match(const struct sess *sp, const char *s, void *re) +{ + vre_t *t; + int i; + + if (s == NULL) + s = ""; + AN(re); + t = re; + i = VRE_exec(t, s, strlen(s), 0, 0, NULL, 0, &cache_param->vre_limits); + if (i >= 0) + return (1); + if (i < VRE_ERROR_NOMATCH ) + WSP(sp, SLT_VCL_Error, "Regexp matching returned %d", i); + return (0); +} + +const char * +VRT_regsub(const struct sess *sp, int all, const char *str, void *re, + const char *sub) +{ + int ovector[30]; + vre_t *t; + int i, l; + txt res; + char *b0; + const char *s; + unsigned u, x; + int options = 0; + size_t len; + + AN(re); + if (str == NULL) + str = ""; + if (sub == NULL) + sub = ""; + t = re; + memset(ovector, 0, sizeof(ovector)); + len = strlen(str); + i = VRE_exec(t, str, len, 0, options, ovector, 30, + &cache_param->vre_limits); + + /* If it didn't match, we can return the original string */ + if (i == VRE_ERROR_NOMATCH) + return(str); + if (i < VRE_ERROR_NOMATCH ) { + WSP(sp, SLT_VCL_Error, "Regexp matching returned %d", i); + return(str); + } + + u = WS_Reserve(sp->req->http->ws, 0); + res.e = res.b = b0 = sp->req->http->ws->f; + res.e += u; + + do { + /* Copy prefix to match */ + Tadd(&res, str, ovector[0]); + for (s = sub ; *s != '\0'; s++ ) { + if (*s != '\\' || s[1] == '\0') { + if (res.b < res.e) + *res.b++ = *s; + continue; + } + s++; + if (isdigit(*s)) { + x = *s - '0'; + l = ovector[2*x+1] - ovector[2*x]; + Tadd(&res, str + ovector[2*x], l); + continue; + } else { + if (res.b < res.e) + *res.b++ = *s; + } + } + str += ovector[1]; + len -= ovector[1]; + if (!all) + break; + memset(&ovector, 0, sizeof(ovector)); + options |= VRE_NOTEMPTY; + i = VRE_exec(t, str, len, 0, options, ovector, 30, + &cache_param->vre_limits); + if (i < VRE_ERROR_NOMATCH ) { + WS_Release(sp->req->http->ws, 0); + WSP(sp, SLT_VCL_Error, + "Regexp matching returned %d", i); + return(str); + } + } while (i != VRE_ERROR_NOMATCH); + + /* Copy suffix to match */ + Tadd(&res, str, len+1); + if (res.b >= res.e) { + WS_Release(sp->req->http->ws, 0); + return (str); + } + Tcheck(res); + WS_ReleaseP(sp->req->http->ws, res.b); + return (b0); +} diff --git a/pool/shard004/C/0100199_gstkatetag.c b/pool/shard004/C/0100199_gstkatetag.c new file mode 100644 index 0000000000000000000000000000000000000000..e1c1c3cf49dcb8d81f60c2136a016a0f65120d59 --- /dev/null +++ b/pool/shard004/C/0100199_gstkatetag.c @@ -0,0 +1,342 @@ +/* + * GStreamer + * Copyright (C) 2006 James Livingston + * Copyright (C) 2008 Vincent Penquerc'h + * + * 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:element-katetag + * @see_also: #oggdemux, #oggmux, #kateparse, #GstTagSetter + * @short_description: retags kate streams + * + * + * + * The katetag element can change the tag contained within a raw + * kate stream. Specifically, it modifies the comments header packet + * of the kate stream, as well as the language and category of the + * kate stream. + * + * + * The element will also process the stream as the #kateparse element does + * so it can be used when remuxing an Ogg Kate stream, without additional + * elements. + * + * + * Applications can set the tags to write using the #GstTagSetter interface. + * Tags contained within the kate stream will be picked up + * automatically (and merged according to the merge mode set via the tag + * setter interface). + * + * Example pipelines + * + * This element is only useful with gst-launch for modifying the language + * and/or category (which are properties of the stream located in the kate + * beginning of stream header), because it does not support setting the tags + * on a #GstTagSetter interface. Conceptually, the element will usually be + * used like: + * + * gst-launch -v filesrc location=foo.ogg ! oggdemux ! katetag ! oggmux ! filesink location=bar.ogg + * + * + * + * This pipeline will set the language and category of the stream to the + * given values: + * + * gst-launch -v filesrc location=foo.ogg ! oggdemux ! katetag language=pt_BR category=subtitles ! oggmux ! filesink location=bar.ogg + * + * + * + */ + +#ifdef HAVE_CONFIG_H +# include "config.h" +#endif + +#include +#include +#include +#include + +#include + +#include "gstkatetag.h" + + +GST_DEBUG_CATEGORY_EXTERN (gst_katetag_debug); +#define GST_CAT_DEFAULT gst_katetag_debug + +enum +{ + ARG_0, + ARG_LANGUAGE, + ARG_CATEGORY, + ARG_ORIGINAL_CANVAS_WIDTH, + ARG_ORIGINAL_CANVAS_HEIGHT, +}; + +static GstFlowReturn gst_kate_tag_parse_packet (GstKateParse * parse, + GstBuffer * buffer); +static void gst_kate_tag_set_property (GObject * object, guint prop_id, + const GValue * value, GParamSpec * pspec); +static void gst_kate_tag_get_property (GObject * object, guint prop_id, + GValue * value, GParamSpec * pspec); +static void gst_kate_tag_dispose (GObject * object); + + +#define _do_init(type) \ + G_STMT_START{ \ + static const GInterfaceInfo tag_setter_info = { \ + NULL, \ + NULL, \ + NULL \ + }; \ + g_type_add_interface_static (type, GST_TYPE_TAG_SETTER, \ + &tag_setter_info); \ + }G_STMT_END + +GST_BOILERPLATE_FULL (GstKateTag, gst_kate_tag, GstKateParse, + GST_TYPE_KATE_PARSE, _do_init); + +static void +gst_kate_tag_base_init (gpointer g_class) +{ + GstElementClass *element_class = GST_ELEMENT_CLASS (g_class); + + gst_element_class_set_details_simple (element_class, "Kate stream tagger", + "Formatter/Metadata", + "Retags kate streams", "Vincent Penquerc'h "); +} + +static void +gst_kate_tag_class_init (GstKateTagClass * klass) +{ + GObjectClass *gobject_class; + GstKateParseClass *gstkateparse_class; + + gobject_class = (GObjectClass *) klass; + gstkateparse_class = GST_KATE_PARSE_CLASS (klass); + + gobject_class->set_property = GST_DEBUG_FUNCPTR (gst_kate_tag_set_property); + gobject_class->get_property = GST_DEBUG_FUNCPTR (gst_kate_tag_get_property); + gobject_class->dispose = GST_DEBUG_FUNCPTR (gst_kate_tag_dispose); + + g_object_class_install_property (gobject_class, ARG_LANGUAGE, + g_param_spec_string ("language", "Language", + "Set the language of the stream", "", G_PARAM_READWRITE)); + + g_object_class_install_property (gobject_class, ARG_CATEGORY, + g_param_spec_string ("category", "Category", + "Set the category of the stream", "", G_PARAM_READWRITE)); + + g_object_class_install_property (gobject_class, ARG_ORIGINAL_CANVAS_WIDTH, + g_param_spec_int ("original-canvas-width", "Original canvas width", + "Set the width of the canvas this stream was authored for (0 is unspecified)", + 0, G_MAXINT, 0, G_PARAM_READWRITE)); + + g_object_class_install_property (gobject_class, ARG_ORIGINAL_CANVAS_HEIGHT, + g_param_spec_int ("original-canvas-height", "Original canvas height", + "Set the height of the canvas this stream was authored for (0 is unspecified)", + 0, G_MAXINT, 0, G_PARAM_READWRITE)); + + gstkateparse_class->parse_packet = + GST_DEBUG_FUNCPTR (gst_kate_tag_parse_packet); +} + +static void +gst_kate_tag_init (GstKateTag * kt, GstKateTagClass * g_class) +{ + kt->language = NULL; + kt->category = NULL; + kt->original_canvas_width = -1; + kt->original_canvas_height = -1; +} + +static void +gst_kate_tag_dispose (GObject * object) +{ + GstKateTag *kt = GST_KATE_TAG (object); + + GST_LOG_OBJECT (kt, "disposing"); + + if (kt->language) { + g_free (kt->language); + kt->language = NULL; + } + if (kt->category) { + g_free (kt->category); + kt->category = NULL; + } + + GST_CALL_PARENT (G_OBJECT_CLASS, dispose, (object)); +} + +static void +gst_kate_tag_set_property (GObject * object, guint prop_id, + const GValue * value, GParamSpec * pspec) +{ + GstKateTag *kt = GST_KATE_TAG (object); + const char *str; + + switch (prop_id) { + case ARG_LANGUAGE: + if (kt->language) { + g_free (kt->language); + kt->language = NULL; + } + str = g_value_get_string (value); + if (str) + kt->language = g_strdup (str); + break; + case ARG_CATEGORY: + if (kt->category) { + g_free (kt->category); + kt->category = NULL; + } + str = g_value_get_string (value); + if (str) + kt->category = g_strdup (str); + break; + case ARG_ORIGINAL_CANVAS_WIDTH: + kt->original_canvas_width = g_value_get_int (value); + break; + case ARG_ORIGINAL_CANVAS_HEIGHT: + kt->original_canvas_height = g_value_get_int (value); + break; + default: + G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec); + break; + } +} + +static void +gst_kate_tag_get_property (GObject * object, guint prop_id, + GValue * value, GParamSpec * pspec) +{ + GstKateTag *kt = GST_KATE_TAG (object); + + switch (prop_id) { + case ARG_LANGUAGE: + g_value_set_string (value, kt->language ? kt->language : ""); + break; + case ARG_CATEGORY: + g_value_set_string (value, kt->category ? kt->category : ""); + break; + case ARG_ORIGINAL_CANVAS_WIDTH: + g_value_set_int (value, kt->original_canvas_width); + break; + case ARG_ORIGINAL_CANVAS_HEIGHT: + g_value_set_int (value, kt->original_canvas_height); + break; + default: + G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec); + break; + } +} + +static guint16 +encode_canvas_size (size_t size) +{ + size_t base = size; + size_t shift = 0; + int value; + + while (base & ~((1 << 12) - 1)) { + /* we have a high bit we can't fit, increase shift if we wouldn't lose low bits */ + if ((size >> shift) & 1) + return 0; + ++shift; + base >>= 1; + } + if (G_UNLIKELY (shift >= 16)) + return 0; + + /* the size can be represented in our encoding */ + value = (base << 4) | shift; + + return (guint16) value; +} + +static GstFlowReturn +gst_kate_tag_parse_packet (GstKateParse * parse, GstBuffer * buffer) +{ + GstTagList *old_tags, *new_tags; + const GstTagList *user_tags; + GstKateTag *kt; + gchar *encoder = NULL; + GstBuffer *new_buf; + + kt = GST_KATE_TAG (parse); + + /* rewrite the language and category */ + if (GST_BUFFER_SIZE (buffer) >= 64 && GST_BUFFER_DATA (buffer)[0] == 0x80) { + GstBuffer *new_buffer = gst_buffer_copy (buffer); + + gst_buffer_unref (buffer); + buffer = new_buffer; + + /* language is at offset 32, 16 bytes, zero terminated */ + if (kt->language) { + strncpy ((char *) GST_BUFFER_DATA (buffer) + 32, kt->language, 15); + GST_BUFFER_DATA (buffer)[47] = 0; + } + /* category is at offset 48, 16 bytes, zero terminated */ + if (kt->category) { + strncpy ((char *) GST_BUFFER_DATA (buffer) + 48, kt->category, 15); + GST_BUFFER_DATA (buffer)[63] = 0; + } + if (kt->original_canvas_width >= 0) { + guint16 v = encode_canvas_size (kt->original_canvas_width); + GST_BUFFER_DATA (buffer)[16] = v & 0xff; + GST_BUFFER_DATA (buffer)[17] = (v >> 8) & 0xff; + } + if (kt->original_canvas_height >= 0) { + guint16 v = encode_canvas_size (kt->original_canvas_height); + GST_BUFFER_DATA (buffer)[18] = v & 0xff; + GST_BUFFER_DATA (buffer)[19] = (v >> 8) & 0xff; + } + } + + /* rewrite the comments packet */ + if (GST_BUFFER_SIZE (buffer) >= 9 && GST_BUFFER_DATA (buffer)[0] == 0x81) { + old_tags = + gst_tag_list_from_vorbiscomment_buffer (buffer, + (const guint8 *) "\201kate\0\0\0\0", 9, &encoder); + user_tags = gst_tag_setter_get_tag_list (GST_TAG_SETTER (kt)); + + /* build new tag list */ + new_tags = gst_tag_list_merge (user_tags, old_tags, + gst_tag_setter_get_tag_merge_mode (GST_TAG_SETTER (kt))); + gst_tag_list_free (old_tags); + + new_buf = + gst_tag_list_to_vorbiscomment_buffer (new_tags, + (const guint8 *) "\201kate\0\0\0\0", 9, encoder); + gst_buffer_copy_metadata (new_buf, buffer, GST_BUFFER_COPY_TIMESTAMPS); + + gst_tag_list_free (new_tags); + g_free (encoder); + gst_buffer_unref (buffer); + + /* the buffer will have the framing bit used by Vorbis, but we don't use it */ + --GST_BUFFER_SIZE (new_buf); + + buffer = new_buf; + } + + return GST_KATE_PARSE_CLASS (parent_class)->parse_packet (parse, buffer); +} diff --git a/pool/shard004/C/0100206_CWE127_Buffer_Underread__wchar_t_declare_ncpy_52a.c b/pool/shard004/C/0100206_CWE127_Buffer_Underread__wchar_t_declare_ncpy_52a.c new file mode 100644 index 0000000000000000000000000000000000000000..00e68b59165311de678b590939af2003854acd9a --- /dev/null +++ b/pool/shard004/C/0100206_CWE127_Buffer_Underread__wchar_t_declare_ncpy_52a.c @@ -0,0 +1,88 @@ +/* TEMPLATE GENERATED TESTCASE FILE +Filename: CWE127_Buffer_Underread__wchar_t_declare_ncpy_52a.c +Label Definition File: CWE127_Buffer_Underread.stack.label.xml +Template File: sources-sink-52a.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 wcsncpy + * 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 + +#ifndef OMITBAD + +/* bad function declaration */ +void CWE127_Buffer_Underread__wchar_t_declare_ncpy_52b_badSink(wchar_t * data); + +void CWE127_Buffer_Underread__wchar_t_declare_ncpy_52_bad() +{ + wchar_t * data; + wchar_t dataBuffer[100]; + wmemset(dataBuffer, L'A', 100-1); + dataBuffer[100-1] = L'\0'; + /* FLAW: Set data pointer to before the allocated memory buffer */ + data = dataBuffer - 8; + CWE127_Buffer_Underread__wchar_t_declare_ncpy_52b_badSink(data); +} + +#endif /* OMITBAD */ + +#ifndef OMITGOOD + +/* good function declaration */ +void CWE127_Buffer_Underread__wchar_t_declare_ncpy_52b_goodG2BSink(wchar_t * data); + +/* goodG2B uses the GoodSource with the BadSink */ +static void goodG2B() +{ + wchar_t * data; + wchar_t dataBuffer[100]; + wmemset(dataBuffer, L'A', 100-1); + dataBuffer[100-1] = L'\0'; + /* FIX: Set data pointer to the allocated memory buffer */ + data = dataBuffer; + CWE127_Buffer_Underread__wchar_t_declare_ncpy_52b_goodG2BSink(data); +} + +void CWE127_Buffer_Underread__wchar_t_declare_ncpy_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()..."); + CWE127_Buffer_Underread__wchar_t_declare_ncpy_52_good(); + printLine("Finished good()"); +#endif /* OMITGOOD */ +#ifndef OMITBAD + printLine("Calling bad()..."); + CWE127_Buffer_Underread__wchar_t_declare_ncpy_52_bad(); + printLine("Finished bad()"); +#endif /* OMITBAD */ + return 0; +} + +#endif diff --git a/pool/shard004/C/0100214_adapt.c b/pool/shard004/C/0100214_adapt.c new file mode 100644 index 0000000000000000000000000000000000000000..ddc125fd412917cb09c231f79888e4934efbf323 --- /dev/null +++ b/pool/shard004/C/0100214_adapt.c @@ -0,0 +1,163 @@ +/*Daala video codec +Copyright (c) 2013 Daala project contributors. 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.*/ + +#ifdef HAVE_CONFIG_H +# include "config.h" +#endif + +#include + +#include "internal.h" +#include "adapt.h" + +/*This implements a 2D moving average filter. + Every point is a combination of a forward horizontal moving average, a + vertical moving average, and a backwards moving average on the prior row. + This gives a computationally efficient casual 2d filter with a + symmetrical response. + The filter supports adapting multiple distinct values at once for better + memory locality during the backwards pass.*/ + +/*Initializes a 2D moving average filter.*/ +void od_adapt2d_init(od_adapt2d_ctx *ctx, int nhv, + int nctx, const int32_t *params) { + OD_ASSERT(nctx <= OD_NADAPT_CTXS_MAX); + ctx->data = (od_adapt2d_data *)malloc(sizeof(*ctx->data)*nhv*nctx); + ctx->nhv = nhv; + ctx->nctx = nctx; + ctx->params = params; +} + +/*Frees a 2D moving average filter.*/ +void od_adapt2d_clear(od_adapt2d_ctx *ctx) { + free(ctx->data); + ctx->data = NULL; +} + +/*Reinitializes a row context. + This must be called once per-frame per filter.*/ +void od_adapt2d_row_init(od_adapt2d_ctx *ctx) { + const int32_t *params; + od_adapt2d_data *data; + int nhv; + int nctx; + int r; + nhv = ctx->nhv; + nctx = ctx->nctx; + data = ctx->data; + params = ctx->params; + for (r = 0; r < nhv; r++) { + int i; + for (i = 0; i < nctx; i++) { + data[r*nctx + i].mean = 2*params[nctx + i] + - (params[nctx + i] >> params[i]); + } + } +} + +/*Initializes a set of running average means for the 2D moving average.*/ +void od_adapt2d_hmean_init(const od_adapt2d_ctx *ctx, int32_t *hmean) { + const int32_t *inits; + int nctx; + int i; + nctx = ctx->nctx; + inits = &ctx->params[nctx]; + for (i = 0; i < nctx; i++) { + hmean[i] = inits[i]; + } +} + +/*Compute expected values for the current position. + xpos: current x offset. + hmeans: horizontal running averages. + means: current values.*/ +void od_adapt2d_get_stats(const od_adapt2d_ctx *ctx, int xpos, + const int32_t *hmean, int32_t *means) { + const int32_t *adapts; + od_adapt2d_data *data; + int i; + int nctx; + nctx = ctx->nctx; + data = &ctx->data[xpos*nctx]; + adapts = ctx->params; + for (i = 0; i < nctx; i++) { + means[i] = data[i].mean + (hmean[i] >> adapts[i]); + } +} + +/*Update the filter for the current position. + xpos: current x offset. + hmeans: horizontal running averages. + curr: current values.*/ +void od_adapt2d_forward(od_adapt2d_ctx *ctx, int xpos, + int32_t *hmean, const int32_t *curr) { + od_adapt2d_data *data; + const int32_t *adapts; + int i; + int nctx; + nctx = ctx->nctx; + data = &ctx->data[xpos*nctx]; + adapts = ctx->params; + for (i = 0; i < nctx; i++) { + if (curr[i] != OD_ADAPT_NO_VALUE) { + int32_t adapt; + adapt = adapts[i]; + data[i].curr = curr[i] >> 1; + hmean[i] += (data[i].curr - hmean[i]) >> adapt; + data[i].mean += (hmean[i] - data[i].mean) >> adapt; + } + else { + data[i].curr = OD_ADAPT_NO_VALUE; + } + } +} + +/*Update the 2D filter for a finished row. + This must be run at the end of every horizontal scan.*/ +void od_adapt2d_row_backward(od_adapt2d_ctx *ctx) { + const int32_t *adapts; + od_adapt2d_data *data; + int32_t hmean[OD_NADAPT_CTXS_MAX]; + int r; + int nctx; + int nhv; + od_adapt2d_hmean_init(ctx, hmean); + nctx = ctx->nctx; + nhv = ctx->nhv; + data = ctx->data; + adapts = ctx->params; + for (r = nhv; r-- > 0;) { + int i; + int roff; + roff = r*nctx; + for (i = 0; i < nctx; i++) { + if (data[roff + i].curr != OD_ADAPT_NO_VALUE) { + int32_t adapt; + adapt = adapts[i]; + data[roff + i].mean += (hmean[i] >> adapt) - (hmean[i] >> 2*adapt); + hmean[i] += (data[roff + i].curr - hmean[i]) >> adapt; + } + } + } +} diff --git a/pool/shard004/C/0100217_inherit1.c b/pool/shard004/C/0100217_inherit1.c new file mode 100644 index 0000000000000000000000000000000000000000..482a5a88484621caf6a7274c8487ce4bfe97cab0 --- /dev/null +++ b/pool/shard004/C/0100217_inherit1.c @@ -0,0 +1,177 @@ +/* + * File: inherit1.c + * + * + * -------------------------------------------------------------------------- + * + * 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 + * + * -------------------------------------------------------------------------- + * + * Test Synopsis: + * - Test thread priority inheritance. + * + * 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: + * - + * + * Pass Criteria: + * - Process returns zero exit status. + * + * Fail Criteria: + * - Process returns non-zero exit status. + */ + +#include "test.h" + +enum { + PTW32TEST_THREAD_INIT_PRIO = 0, + PTW32TEST_MAXPRIORITIES = 512 +}; + +int minPrio; +int maxPrio; +int validPriorities[PTW32TEST_MAXPRIORITIES]; + + +void * func(void * arg) +{ + int policy; + struct sched_param param; + + assert(pthread_getschedparam(pthread_self(), &policy, ¶m) == 0); + return (void *) param.sched_priority; +} + + +void * +getValidPriorities(void * arg) +{ + int prioSet; + pthread_t thread = pthread_self(); + HANDLE threadH = pthread_getw32threadhandle_np(thread); + struct sched_param param; + + for (prioSet = minPrio; + prioSet <= maxPrio; + prioSet++) + { + /* + * If prioSet is invalid then the threads priority is unchanged + * from the previous value. Make the previous value a known + * one so that we can check later. + */ + param.sched_priority = prioSet; + assert(pthread_setschedparam(thread, SCHED_OTHER, ¶m) == 0); + validPriorities[prioSet+(PTW32TEST_MAXPRIORITIES/2)] = GetThreadPriority(threadH); + } + + return (void *) 0; +} + + +int +main() +{ + pthread_t t; + pthread_t mainThread = pthread_self(); + pthread_attr_t attr; + void * result = NULL; + struct sched_param param; + struct sched_param mainParam; + int prio; + int policy; + int inheritsched = -1; + pthread_t threadID = pthread_self(); + HANDLE threadH = pthread_getw32threadhandle_np(threadID); + + assert((maxPrio = sched_get_priority_max(SCHED_OTHER)) != -1); + assert((minPrio = sched_get_priority_min(SCHED_OTHER)) != -1); + + assert(pthread_create(&t, NULL, getValidPriorities, NULL) == 0); + assert(pthread_join(t, &result) == 0); + + assert(pthread_attr_init(&attr) == 0); + assert(pthread_attr_setinheritsched(&attr, PTHREAD_INHERIT_SCHED) == 0); + assert(pthread_attr_getinheritsched(&attr, &inheritsched) == 0); + assert(inheritsched == PTHREAD_INHERIT_SCHED); + + for (prio = minPrio; prio <= maxPrio; prio++) + { + mainParam.sched_priority = prio; + + /* Set the thread's priority to a known initial value. */ + SetThreadPriority(threadH, PTW32TEST_THREAD_INIT_PRIO); + + /* Change the main thread priority */ + assert(pthread_setschedparam(mainThread, SCHED_OTHER, &mainParam) == 0); + assert(pthread_getschedparam(mainThread, &policy, &mainParam) == 0); + assert(policy == SCHED_OTHER); + /* Priority returned below should be the level set by pthread_setschedparam(). */ + assert(mainParam.sched_priority == prio); + assert(GetThreadPriority(threadH) == + validPriorities[prio+(PTW32TEST_MAXPRIORITIES/2)]); + + for (param.sched_priority = prio; + param.sched_priority <= maxPrio; + param.sched_priority++) + { + /* The new thread create should ignore this new priority */ + assert(pthread_attr_setschedparam(&attr, ¶m) == 0); + assert(pthread_create(&t, &attr, func, NULL) == 0); + pthread_join(t, &result); + assert((int) result == mainParam.sched_priority); + } + } + + return 0; +} diff --git a/pool/shard004/C/0100220_bitshift.c b/pool/shard004/C/0100220_bitshift.c new file mode 100644 index 0000000000000000000000000000000000000000..c39bb0cb0b5b176ea13a1d1b60ac12c5e1d03f80 --- /dev/null +++ b/pool/shard004/C/0100220_bitshift.c @@ -0,0 +1,19 @@ +#include +#include +#include +int main(int argc, char **argv) +{ + uint64_t a = strtoull(argv[1], NULL, 0); + int b = atoi(argv[2]); + + if (b < 0) + { + b = -b; + printf("0x%.16lx\n", a<>b); + } + return 0; +} diff --git a/pool/shard004/C/0100221_blake2b-compress-ref.c b/pool/shard004/C/0100221_blake2b-compress-ref.c new file mode 100644 index 0000000000000000000000000000000000000000..c177ed1792a4eb6f9c22a5ef68166fd740be3e65 --- /dev/null +++ b/pool/shard004/C/0100221_blake2b-compress-ref.c @@ -0,0 +1,93 @@ + +#include +#include + +#include "blake2.h" +#include "blake2-impl.h" + +static const uint64_t blake2b_IV[8] = +{ + 0x6a09e667f3bcc908ULL, 0xbb67ae8584caa73bULL, + 0x3c6ef372fe94f82bULL, 0xa54ff53a5f1d36f1ULL, + 0x510e527fade682d1ULL, 0x9b05688c2b3e6c1fULL, + 0x1f83d9abfb41bd6bULL, 0x5be0cd19137e2179ULL +}; + +static const uint8_t blake2b_sigma[12][16] = +{ + { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 } , + { 14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3 } , + { 11, 8, 12, 0, 5, 2, 15, 13, 10, 14, 3, 6, 7, 1, 9, 4 } , + { 7, 9, 3, 1, 13, 12, 11, 14, 2, 6, 5, 10, 4, 0, 15, 8 } , + { 9, 0, 5, 7, 2, 4, 10, 15, 14, 1, 11, 12, 6, 8, 3, 13 } , + { 2, 12, 6, 10, 0, 11, 8, 3, 4, 13, 7, 5, 15, 14, 1, 9 } , + { 12, 5, 1, 15, 14, 13, 4, 10, 0, 7, 6, 3, 9, 2, 8, 11 } , + { 13, 11, 7, 14, 12, 1, 3, 9, 5, 0, 15, 4, 8, 6, 2, 10 } , + { 6, 15, 14, 9, 11, 3, 0, 8, 12, 2, 13, 7, 1, 4, 10, 5 } , + { 10, 2, 8, 4, 7, 6, 1, 5, 15, 11, 9, 14, 3, 12, 13 , 0 } , + { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 } , + { 14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3 } +}; + +int blake2b_compress_ref( blake2b_state *S, const uint8_t block[BLAKE2B_BLOCKBYTES] ) +{ + uint64_t m[16]; + uint64_t v[16]; + int i; + + for( i = 0; i < 16; ++i ) + m[i] = load64( block + i * sizeof( m[i] ) ); + + for( i = 0; i < 8; ++i ) + v[i] = S->h[i]; + + v[ 8] = blake2b_IV[0]; + v[ 9] = blake2b_IV[1]; + v[10] = blake2b_IV[2]; + v[11] = blake2b_IV[3]; + v[12] = S->t[0] ^ blake2b_IV[4]; + v[13] = S->t[1] ^ blake2b_IV[5]; + v[14] = S->f[0] ^ blake2b_IV[6]; + v[15] = S->f[1] ^ blake2b_IV[7]; +#define G(r,i,a,b,c,d) \ + do { \ + a = a + b + m[blake2b_sigma[r][2*i+0]]; \ + d = rotr64(d ^ a, 32); \ + c = c + d; \ + b = rotr64(b ^ c, 24); \ + a = a + b + m[blake2b_sigma[r][2*i+1]]; \ + d = rotr64(d ^ a, 16); \ + c = c + d; \ + b = rotr64(b ^ c, 63); \ + } while(0) +#define ROUND(r) \ + do { \ + G(r,0,v[ 0],v[ 4],v[ 8],v[12]); \ + G(r,1,v[ 1],v[ 5],v[ 9],v[13]); \ + G(r,2,v[ 2],v[ 6],v[10],v[14]); \ + G(r,3,v[ 3],v[ 7],v[11],v[15]); \ + G(r,4,v[ 0],v[ 5],v[10],v[15]); \ + G(r,5,v[ 1],v[ 6],v[11],v[12]); \ + G(r,6,v[ 2],v[ 7],v[ 8],v[13]); \ + G(r,7,v[ 3],v[ 4],v[ 9],v[14]); \ + } while(0) + ROUND( 0 ); + ROUND( 1 ); + ROUND( 2 ); + ROUND( 3 ); + ROUND( 4 ); + ROUND( 5 ); + ROUND( 6 ); + ROUND( 7 ); + ROUND( 8 ); + ROUND( 9 ); + ROUND( 10 ); + ROUND( 11 ); + + for( i = 0; i < 8; ++i ) + S->h[i] = S->h[i] ^ v[i] ^ v[i + 8]; + +#undef G +#undef ROUND + return 0; +} diff --git a/pool/shard004/C/0100222_entry.c b/pool/shard004/C/0100222_entry.c new file mode 100644 index 0000000000000000000000000000000000000000..b53a9f9a32ff73f8bf81439eb4d984829820b3e2 --- /dev/null +++ b/pool/shard004/C/0100222_entry.c @@ -0,0 +1,93 @@ +/* example-start entry entry.c */ + +#include + +void enter_callback( GtkWidget *widget, + GtkWidget *entry ) +{ + gchar *entry_text; + entry_text = gtk_entry_get_text(GTK_ENTRY(entry)); + printf("Entry contents: %s\n", entry_text); +} + +void entry_toggle_editable( GtkWidget *checkbutton, + GtkWidget *entry ) +{ + gtk_entry_set_editable(GTK_ENTRY(entry), + GTK_TOGGLE_BUTTON(checkbutton)->active); +} + +void entry_toggle_visibility( GtkWidget *checkbutton, + GtkWidget *entry ) +{ + gtk_entry_set_visibility(GTK_ENTRY(entry), + GTK_TOGGLE_BUTTON(checkbutton)->active); +} + +int main( int argc, + char *argv[] ) +{ + + GtkWidget *window; + GtkWidget *vbox, *hbox; + GtkWidget *entry; + GtkWidget *button; + GtkWidget *check; + + gtk_init (&argc, &argv); + + /* create a new window */ + window = gtk_window_new(GTK_WINDOW_TOPLEVEL); + gtk_widget_set_usize( GTK_WIDGET (window), 200, 100); + gtk_window_set_title(GTK_WINDOW (window), "GTK Entry"); + gtk_signal_connect(GTK_OBJECT (window), "delete_event", + (GtkSignalFunc) gtk_exit, NULL); + + vbox = gtk_vbox_new (FALSE, 0); + gtk_container_add (GTK_CONTAINER (window), vbox); + gtk_widget_show (vbox); + + entry = gtk_entry_new_with_max_length (50); + gtk_signal_connect(GTK_OBJECT(entry), "activate", + GTK_SIGNAL_FUNC(enter_callback), + entry); + gtk_entry_set_text (GTK_ENTRY (entry), "hello"); + gtk_entry_append_text (GTK_ENTRY (entry), " world"); + gtk_entry_select_region (GTK_ENTRY (entry), + 0, GTK_ENTRY(entry)->text_length); + gtk_box_pack_start (GTK_BOX (vbox), entry, TRUE, TRUE, 0); + gtk_widget_show (entry); + + hbox = gtk_hbox_new (FALSE, 0); + gtk_container_add (GTK_CONTAINER (vbox), hbox); + gtk_widget_show (hbox); + + check = gtk_check_button_new_with_label("Editable"); + gtk_box_pack_start (GTK_BOX (hbox), check, TRUE, TRUE, 0); + gtk_signal_connect (GTK_OBJECT(check), "toggled", + GTK_SIGNAL_FUNC(entry_toggle_editable), entry); + gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(check), TRUE); + gtk_widget_show (check); + + check = gtk_check_button_new_with_label("Visible"); + gtk_box_pack_start (GTK_BOX (hbox), check, TRUE, TRUE, 0); + gtk_signal_connect (GTK_OBJECT(check), "toggled", + GTK_SIGNAL_FUNC(entry_toggle_visibility), entry); + gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(check), TRUE); + gtk_widget_show (check); + + button = gtk_button_new_with_label ("Close"); + gtk_signal_connect_object (GTK_OBJECT (button), "clicked", + GTK_SIGNAL_FUNC(gtk_exit), + GTK_OBJECT (window)); + gtk_box_pack_start (GTK_BOX (vbox), button, TRUE, TRUE, 0); + GTK_WIDGET_SET_FLAGS (button, GTK_CAN_DEFAULT); + gtk_widget_grab_default (button); + gtk_widget_show (button); + + gtk_widget_show(window); + + gtk_main(); + return(0); +} +/* example-end */ diff --git a/pool/shard004/C/0100227_pthread_getaffinity.c b/pool/shard004/C/0100227_pthread_getaffinity.c new file mode 100644 index 0000000000000000000000000000000000000000..35b0c442b419efe7e9ee97a0b84c2c4fb14b243b --- /dev/null +++ b/pool/shard004/C/0100227_pthread_getaffinity.c @@ -0,0 +1,67 @@ +/* Copyright (C) 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 +#include +#include +#include +#include +#include +#include +#include + +#include "../cpuset-kern.h" + +int +__pthread_getaffinity_new (pthread_t th, size_t cpusetsize, cpu_set_t *cpuset) +{ + const struct pthread *pd = (const struct pthread *) th; + int64_t id = pd->tid; + int res; + + if (cpusetsize > sizeof(cpu_set_t)) + { + /* Clean the rest of the memory the kernel won't do. */ + memset ((char *) cpuset + sizeof(cpu_set_t), '\0', cpusetsize - sizeof(cpu_set_t)); + + cpusetsize = sizeof(cpu_set_t); + } + + res = INLINE_SYSCALL (cpuset_getaffinity, 5, CPU_LEVEL_WHICH, + CPU_WHICH_TID, id, cpusetsize, cpuset); + + if (res == 0) + return 0; + + if (errno == ERANGE) + { + return EINVAL; + } + + return errno; +} +strong_alias (__pthread_getaffinity_new, __pthread_getaffinity_np) +versioned_symbol (libpthread, __pthread_getaffinity_new, + pthread_getaffinity_np, GLIBC_2_3_4); + + +#if SHLIB_COMPAT (libpthread, GLIBC_2_3_3, GLIBC_2_3_4) +/* The old interface have not been really exposed */ +strong_alias (__pthread_getaffinity_new, __pthread_getaffinity_old) +compat_symbol (libpthread, __pthread_getaffinity_old, pthread_getaffinity_np, + GLIBC_2_3_3); +#endif diff --git a/pool/shard004/C/0100232_f_mmap.c b/pool/shard004/C/0100232_f_mmap.c new file mode 100644 index 0000000000000000000000000000000000000000..6f02a8654d966bc72527cd6310156054d789cd63 --- /dev/null +++ b/pool/shard004/C/0100232_f_mmap.c @@ -0,0 +1,78 @@ +//START_INCLUDES +/* +#include +#include +#include +#include +#include +#include +#include +#include +#include +*/ +#include "q_incs.h" +#include "mmap_types.h" +//STOP_INCLUDES +#include "_f_mmap.h" +//START_FUNC_DECL + +MMAP_REC_TYPE * +f_mmap( + char * const file_name, + bool is_write +) +//STOP_FUNC_DECL +{ + int status = 0; + MMAP_REC_TYPE *ptr_mmap = NULL; + ptr_mmap = (MMAP_REC_TYPE *)malloc(sizeof(MMAP_REC_TYPE)); + memset(ptr_mmap, '\0', sizeof(MMAP_REC_TYPE)); + + errno = 0; + if ( ( file_name == NULL) || ( *file_name == '\0' ) ) { go_BYE(-1); } + if ( strlen(file_name) >= Q_MAX_LEN_FILE_NAME ) { go_BYE(-1); } + for ( char *cptr = file_name; *cptr != '\0'; cptr++ ) { + if ( !isascii(*cptr) ) { go_BYE(-1); } + } + if ( ptr_mmap == NULL ) { go_BYE(-1); } + ptr_mmap->status = -1; + ptr_mmap->map_addr = NULL; + ptr_mmap->map_len = 0; + // TODO: Change 255 to q #define CONSTANT + if ( strlen(file_name) > 255 ) { go_BYE(-1); } + + int fd, flags; + struct stat filestat; + size_t len; + + //--------------------- + if ( is_write ) { + fd = open(file_name, O_RDWR); + } + else { + fd = open(file_name, O_RDONLY); + } + if ( fd < 0 ) { go_BYE(-1); } + status = fstat(fd, &filestat); cBYE(status); + len = filestat.st_size; + if ( len == 0 ) { go_BYE(-1); } + if ( is_write ) { + flags = PROT_READ | PROT_WRITE; + } + else { + flags = PROT_READ; + } + ptr_mmap->map_addr = (void*)mmap(NULL, (size_t)len, flags, + MAP_SHARED, fd, 0); + close(fd); + ptr_mmap->map_len = filestat.st_size; + ptr_mmap->status = 0; + strcpy(ptr_mmap->file_name, file_name); +BYE: + if ( status < 0 ) { + return NULL; + } + else { + return ptr_mmap; + } +} diff --git a/pool/shard004/C/0100233_ap_sh4a_4a.c b/pool/shard004/C/0100233_ap_sh4a_4a.c new file mode 100644 index 0000000000000000000000000000000000000000..ff37df1f5c92ae30e5688f7f292ad898742a4bc7 --- /dev/null +++ b/pool/shard004/C/0100233_ap_sh4a_4a.c @@ -0,0 +1,195 @@ +/* + * Copyright (C) 2012 Nobuhiro Iwamatsu + * Copyright (C) 2012 Renesas Solutions Corp. + * + * 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. + * + */ + +#include +#include +#include +#include +#include + +DECLARE_GLOBAL_DATA_PTR; + +#define MODEMR (0xFFCC0020) +#define MODEMR_MASK (0x6) +#define MODEMR_533MHZ (0x2) + +int checkboard(void) +{ + u32 r = readl(MODEMR); + if ((r & MODEMR_MASK) & MODEMR_533MHZ) + puts("CPU Clock: 533MHz\n"); + else + puts("CPU Clock: 400MHz\n"); + + puts("BOARD: Alpha Project. AP-SH4A-4A\n"); + return 0; +} + +#define MSTPSR1 (0xFFC80044) +#define MSTPCR1 (0xFFC80034) +#define MSTPSR1_GETHER (1 << 14) + +/* IPSR3 */ +#define ET0_ETXD0 (0x4 << 3) +#define ET0_GTX_CLK_A (0x4 << 6) +#define ET0_ETXD1_A (0x4 << 9) +#define ET0_ETXD2_A (0x4 << 12) +#define ET0_ETXD3_A (0x4 << 15) +#define ET0_ETXD4 (0x3 << 18) +#define ET0_ETXD5_A (0x5 << 21) +#define ET0_ETXD6_A (0x5 << 24) +#define ET0_ETXD7 (0x4 << 27) +#define IPSR3_ETH_ENABLE \ + (ET0_ETXD0 | ET0_GTX_CLK_A | ET0_ETXD1_A | ET0_ETXD2_A | \ + ET0_ETXD3_A | ET0_ETXD4 | ET0_ETXD5_A | ET0_ETXD6_A | ET0_ETXD7) + +/* IPSR4 */ +#define ET0_ERXD7 (0x4) +#define ET0_RX_DV (0x4 << 3) +#define ET0_RX_ER (0x4 << 6) +#define ET0_CRS (0x4 << 9) +#define ET0_COL (0x4 << 12) +#define ET0_MDC (0x4 << 15) +#define ET0_MDIO_A (0x3 << 18) +#define ET0_LINK_A (0x3 << 20) +#define ET0_PHY_INT_A (0x3 << 24) + +#define IPSR4_ETH_ENABLE \ + (ET0_ERXD7 | ET0_RX_DV | ET0_RX_ER | ET0_CRS | ET0_COL | \ + ET0_MDC | ET0_MDIO_A | ET0_LINK_A | ET0_PHY_INT_A) + +/* IPSR8 */ +#define ET0_ERXD0 (0x4 << 20) +#define ET0_ERXD1 (0x4 << 23) +#define ET0_ERXD2_A (0x3 << 26) +#define ET0_ERXD3_A (0x3 << 28) +#define IPSR8_ETH_ENABLE \ + (ET0_ERXD0 | ET0_ERXD1 | ET0_ERXD2_A | ET0_ERXD3_A) + +/* IPSR10 */ +#define RX4_D (0x1 << 22) +#define TX4_D (0x1 << 23) +#define IPSR10_SCIF_ENABLE (RX4_D | TX4_D) + +/* IPSR11 */ +#define ET0_ERXD4 (0x4 << 4) +#define ET0_ERXD5 (0x4 << 7) +#define ET0_ERXD6 (0x3 << 10) +#define ET0_TX_EN (0x2 << 19) +#define ET0_TX_ER (0x2 << 21) +#define ET0_TX_CLK_A (0x4 << 23) +#define ET0_RX_CLK_A (0x3 << 26) +#define IPSR11_ETH_ENABLE \ + (ET0_ERXD4 | ET0_ERXD5 | ET0_ERXD6 | ET0_TX_EN | ET0_TX_ER | \ + ET0_TX_CLK_A | ET0_RX_CLK_A) + +#define GPSR1_INIT (0xFFFF7FFF) +#define GPSR2_INIT (0x4005FEFF) +#define GPSR3_INIT (0x2EFFFFFF) +#define GPSR4_INIT (0xC7000000) + +int board_init(void) +{ + u32 data; + + /* Set IPSR register */ + data = readl(IPSR3); + data |= IPSR3_ETH_ENABLE; + writel(~data, PMMR); + writel(data, IPSR3); + + data = readl(IPSR4); + data |= IPSR4_ETH_ENABLE; + writel(~data, PMMR); + writel(data, IPSR4); + + data = readl(IPSR8); + data |= IPSR8_ETH_ENABLE; + writel(~data, PMMR); + writel(data, IPSR8); + + data = readl(IPSR10); + data |= IPSR10_SCIF_ENABLE; + writel(~data, PMMR); + writel(data, IPSR10); + + data = readl(IPSR11); + data |= IPSR11_ETH_ENABLE; + writel(~data, PMMR); + writel(data, IPSR11); + + /* GPIO select */ + data = GPSR1_INIT; + writel(~data, PMMR); + writel(data, GPSR1); + + data = GPSR2_INIT; + writel(~data, PMMR); + writel(data, GPSR2); + + data = GPSR3_INIT; + writel(~data, PMMR); + writel(data, GPSR3); + + data = GPSR4_INIT; + writel(~data, PMMR); + writel(data, GPSR4); + + data = 0x0; + writel(~data, PMMR); + writel(data, GPSR5); + + /* mode select */ + data = MODESEL2_INIT; + writel(~data, PMMR); + writel(data, MODESEL2); + +#if defined(CONFIG_SH_ETHER) + u32 r = readl(MSTPSR1); + if (r & MSTPSR1_GETHER) + writel((r & ~MSTPSR1_GETHER), MSTPCR1); +#endif + return 0; +} + +int board_late_init(void) +{ + u8 mac[6]; + + /* Read Mac Address and set*/ + i2c_init(CONFIG_SYS_I2C_SPEED, CONFIG_SYS_I2C_SLAVE); + i2c_set_bus_num(CONFIG_SYS_I2C_MODULE); + + /* Read MAC address */ + i2c_read(0x50, 0x0, 0, mac, 6); + + if (is_valid_ether_addr(mac)) + eth_setenv_enetaddr("ethaddr", mac); + + return 0; +} + +int dram_init(void) +{ + gd->bd->bi_memstart = CONFIG_SYS_SDRAM_BASE; + gd->bd->bi_memsize = CONFIG_SYS_SDRAM_SIZE; + printf("DRAM: %dMB\n", CONFIG_SYS_SDRAM_SIZE / (1024 * 1024)); + + return 0; +} diff --git a/pool/shard004/C/0100238_ptr_queues.c b/pool/shard004/C/0100238_ptr_queues.c new file mode 100644 index 0000000000000000000000000000000000000000..93a51e6459c60bd7cdd5c527430275629eb534bf --- /dev/null +++ b/pool/shard004/C/0100238_ptr_queues.c @@ -0,0 +1,173 @@ +/* + * This file is part of the Yices SMT Solver. + * Copyright (C) 2017 SRI International. + * + * Yices is free software: you can 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. + * + * Yices is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with Yices. If not, see . + */ + +/* + * QUEUES OF POINTERS + * + * data = content of the queue + * size = full size of the data array + * head = start of the queue = index in data array + * tail = end of the queue = index in data array + * + * There are two modes: + * 1) if 0 <= head <= tail < size, then + * the queue consists of data[head ... tail-1] + * the queue is empty if head = tail + * 2) if 0 <= tail < head < size then + * the queue is the concatenation of + * data[head ... size -1] and data[0 ... tail-1] + * + * So size cannot be zero and head and tail are always between + * 0 and size-1. + */ + +#include + +#include "utils/memalloc.h" +#include "utils/ptr_queues.h" + + +/* + * Initialize a queue of size n + */ +void init_ptr_queue(ptr_queue_t *q, uint32_t n) { + if (n == 0) n = DEF_PTR_QUEUE_SIZE; + if (n > MAX_PTR_QUEUE_SIZE) { + out_of_memory(); + } + + q->data = (void **) safe_malloc(n * sizeof(void *)); + q->size = n; + q->head = 0; + q->tail = 0; +} + + +/* + * Delete: free data array + */ +void delete_ptr_queue(ptr_queue_t *q) { + safe_free(q->data); + q->data = NULL; +} + + +/* + * Resize the queue. Make the data array 50% larger. + * The array's content is unchanged. + */ +static void resize_queue(ptr_queue_t *q) { + uint32_t n; + + n = q->size + 1; + n += n >> 1; + + if (n > MAX_PTR_QUEUE_SIZE) { + out_of_memory(); + } + + q->data = (void **) safe_realloc(q->data, n * sizeof(void *)); + q->size = n; +} + + + +/* + * Push element p at the end of the queue + */ +void ptr_queue_push(ptr_queue_t *q, void *p) { + uint32_t i, n, j; + + i = q->tail; + q->data[i] = p; + i ++; + q->tail = i; + + if (i == q->size) { + if (q->head == 0) { + /* + * full queue, stored in data[0...size-1], + * just increase the size + */ + resize_queue(q); + } else { + q->tail = 0; + } + } else if (i == q->head) { + /* + * full queue, stored in data[0..i-1][head .. size-1] + * increase the size and shift data[head .. size - 1] to the end + * of the new data array. + */ + n = q->size; + resize_queue(q); + j = q->size; + assert(n < j); + do { + n --; + j --; + q->data[j] = q->data[n]; + } while (n > i); + q->head = j; + } +} + + +/* + * Return first element and remove it + */ +void *ptr_queue_pop(ptr_queue_t *q) { + uint32_t h; + void *x; + + assert(q->head != q->tail); + + h = q->head; + x = q->data[h]; + h ++; + if (h >= q->size) h = 0; + q->head = h; + + return x; +} + + + +/* + * First element of q + */ +void *ptr_queue_first(ptr_queue_t *q) { + assert(q->head != q->tail); + return q->data[q->head]; +} + + +/* + * Last element of q + */ +void *ptr_queue_last(ptr_queue_t *q) { + uint32_t i; + + assert(q->head != q->tail); + i = q->tail; + if (i == 0) { + i = q->size; + } + assert(i > 0); + return q->data[i-1]; +} diff --git a/pool/shard004/C/0100241_test_header_parser.c b/pool/shard004/C/0100241_test_header_parser.c new file mode 100644 index 0000000000000000000000000000000000000000..d434ce0892c0e12232258bbedfe1f6c07ebb7d0e --- /dev/null +++ b/pool/shard004/C/0100241_test_header_parser.c @@ -0,0 +1,69 @@ +#undef NDEBUG +#include +#include +#include +#include + +int +main(void) +{ + // === + struct parsed_headers_s *ph = hp_parse_headers( + "HTTP/1.1 200 OK\r\n" + "Date: Sat, 19 Apr 2014 15:53:34 GMT\r\n" + "Server: Apache/2.4.9 (Debian)\r\n" + "Last-Modified: Tue, 12 Feb 2013 12:57:02 GMT\r\n" + "Etag: \"1efbf-4d5868fd0c380\"\r\n" + "Accept-Ranges: bytes\r\n" + "Content-Length: 126911\r\n" + "Keep-Alive: timeout=5, max=95\r\n" + "Connection: Keep-Alive\r\n" + "Content-Type: application/x-shockwave-flash\r\n" + ); + + assert(ph); + assert(ph->http_code == 200); + assert(hp_header_exists(ph, "Date") == 1); + assert(hp_header_exists(ph, "date") == 1); + assert(hp_header_exists(ph, "Date2") == 0); + assert(hp_header_exists(ph, "Content-Type") == 1); + assert(hp_header_exists(ph, "bytes") == 0); + + assert(0 == strcmp(hp_get_header_value(ph, "Date"), "Sat, 19 Apr 2014 15:53:34 GMT")); + assert(0 == strcmp(ph->status_line, "HTTP/1.1 200 OK")); + hp_free_parsed_headers(ph); + + // === + ph = hp_parse_headers( + "HTTP/1.0 301 Moved Permanently\r\n" + "Location: http://example.org\r\n" + "Connection: Keep-Alive\r\n" + ); + + assert(ph->http_code == 301); + assert(0 == strcmp(hp_get_header_value(ph, "Location"), "http://example.org")); + assert(0 == strcmp(ph->status_line, "HTTP/1.0 301 Moved Permanently")); + hp_free_parsed_headers(ph); + + // === + ph = hp_parse_headers(NULL); + assert(0 == ph->cnt); + hp_free_parsed_headers(ph); + + // === + // no \r\n at the end of last header line + ph = hp_parse_headers( + "HTTP/1.0 301 Moved Permanently\r\n" + "Location: http://example.org\r\n" + "Connection: Keep-Alive" + ); + + assert(hp_header_exists(ph, "Location") == 1); + assert(hp_header_exists(ph, "Connection") == 1); + assert(0 == strcmp(hp_get_header_value(ph, "Connection"), "Keep-Alive")); + hp_free_parsed_headers(ph); + + // === + printf("pass\n"); + return 0; +} diff --git a/pool/shard004/C/0100246_1-1.c b/pool/shard004/C/0100246_1-1.c new file mode 100644 index 0000000000000000000000000000000000000000..eae549ee66e36fdff8f3ee649fc86734d1625cec --- /dev/null +++ b/pool/shard004/C/0100246_1-1.c @@ -0,0 +1,54 @@ +/* + * Copyright (c) 2002, Intel Corporation. All rights reserved. + * Created by: julie.n.fleischer 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 that the raise() function shall send the signal + * to the executing process. + * 1) Set up a signal handler for the signal that says we have caught the + * signal. + * 2) Raise the signal. + * 3) If signal handler was called, test passed. + * This test is only performed on one signal. All other signals are + * considered to be in the same equivalence class. + */ + +#include +#include +#include +#include "posixtest.h" + +#define SIGTOTEST SIGABRT + +static void handler(int signo PTS_ATTRIBUTE_UNUSED) +{ + printf("Caught signal being tested!\n"); + printf("Test PASSED\n"); + exit(0); +} + +int main(void) +{ + struct sigaction act; + + act.sa_handler = handler; + act.sa_flags = 0; + if (sigemptyset(&act.sa_mask) == -1) { + perror("Error calling sigemptyset\n"); + return PTS_UNRESOLVED; + } + if (sigaction(SIGTOTEST, &act, 0) == -1) { + perror("Error calling sigaction\n"); + return PTS_UNRESOLVED; + } + if (raise(SIGTOTEST) != 0) { + printf("Could not raise signal being tested\n"); + return PTS_FAIL; + } + + printf("Should have exited from signal handler\n"); + printf("Test FAILED\n"); + return PTS_FAIL; +} diff --git a/pool/shard004/C/0100247_vect-26.c b/pool/shard004/C/0100247_vect-26.c new file mode 100644 index 0000000000000000000000000000000000000000..3cb9fb674becf2ea7990e3235ac8ec7579cec0a6 --- /dev/null +++ b/pool/shard004/C/0100247_vect-26.c @@ -0,0 +1,41 @@ +/* { dg-require-effective-target vect_int } */ + +#include +#include "tree-vect.h" + +#define N 128 + +/* unaligned store. */ + +__attribute__ ((noinline)) +int main1 () +{ + int i; + int ia[N+1]; + + for (i = 1; i <= N; i++) + { + ia[i] = 5; + } + + /* check results: */ + for (i = 1; i <= N; i++) + { + if (ia[i] != 5) + abort (); + } + + return 0; +} + +int main (void) +{ + check_vect (); + + return main1 (); +} + +/* { dg-final { scan-tree-dump-times "vectorized 1 loops" 1 "vect" } } */ +/* { dg-final { scan-tree-dump-times "Vectorizing an unaligned access" 0 "vect" } } */ +/* { dg-final { scan-tree-dump-times "Alignment of access forced using peeling" 1 "vect" } } */ +/* { dg-final { cleanup-tree-dump "vect" } } */ diff --git a/pool/shard004/C/0100248_zapfiles.c b/pool/shard004/C/0100248_zapfiles.c new file mode 100644 index 0000000000000000000000000000000000000000..a0e683624fc1d3a51758d7600cdf943ca0045ffa --- /dev/null +++ b/pool/shard004/C/0100248_zapfiles.c @@ -0,0 +1,123 @@ + +/* zapfiles.c + * + * Copyright 2015 Bob Parker + * + * 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 "fileops.h" + + +static char *helpmsg = "\n\tUsage: zapfiles [option] listfile\n" + "\tzapfiles deletes the files listed in listfile." + "\tFiles must be in the format sent by oldfiles to stdout or\n" + "\tin the format sent to stderr by oldfiles, brokensym or\n " + "\tduplicates\n" + "\n\tOptions:\n" + "\t-h outputs this help message.\n" + ; +static char* pathend = "!*END*!"; + +static void dohelp(int forced); + +int main(int argc, char **argv) +{ + int opt; + struct stat sb; + FILE *fpi; + char buf[PATH_MAX]; + char *cp; + + while((opt = getopt(argc, argv, ":h")) != -1) { + switch(opt){ + case 'h': + dohelp(0); + break; + case ':': + fprintf(stderr, "Option %c requires an argument\n",optopt); + dohelp(1); + break; + case '?': + fprintf(stderr, "Illegal option: %c\n",optopt); + dohelp(1); + break; + } //switch() + } //while() + // now process the non-option arguments + + // 1.Check that argv[???] exists. + if (!(argv[optind])) { + fprintf(stderr, "No file provided\n"); + dohelp(1); + } + + // 2. Check that it's meaningful, ie file/dir exists. + if (stat(argv[optind], &sb) == -1){ + perror(argv[optind]); + exit(EXIT_FAILURE); + } + + // 3. Check that the thing is a file + if (!S_ISREG(sb.st_mode)) { + fprintf(stderr, "%s is not a regular file\n", argv[optind]); + exit(EXIT_FAILURE); + } + + // open the file and zap them + fpi = dofopen(argv[optind], "r"); + while((cp = fgets(buf, PATH_MAX, fpi))) { + char *eod; + + // have to deal with more than one convention here + + // Will not abort on error, there may be non-standard lines that + // occur from the output to stderr and stdout. Just list them. + + // 1. broken symlinks + eod = memmem(buf, PATH_MAX, ": No such file", + strlen(": No such file")); + if(eod) *eod = '\0'; + // 2. list from oldfiles + if (!(eod)) { + eod = memmem(buf, PATH_MAX, pathend, strlen(pathend)); + if (eod) *eod = '\0'; + } + if (eod) { + if (unlink(buf) == -1) { + perror(buf); + } + } else { + fprintf(stderr, "Unknown line in file: %s", buf); + } + } + + return 0; +} + +void dohelp(int forced) +{ + fputs(helpmsg, stderr); + exit(forced); +} + diff --git a/pool/shard004/C/0100252_open-osdp-PD-status.c b/pool/shard004/C/0100252_open-osdp-PD-status.c new file mode 100644 index 0000000000000000000000000000000000000000..dda4a5d7f4f1380d5d1f6d6447ff217e03b2b0ea --- /dev/null +++ b/pool/shard004/C/0100252_open-osdp-PD-status.c @@ -0,0 +1,159 @@ +/* + open-osdp-PD-status - display PD status as refreshing HTML page + + (C)Copyright 2015-2016 Smithee,Spelvin,Agnew & Plinge, Inc. + + Support provided by the Security Industry Association + http://www.securityindustry.org + + 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 + +OSDP_CONTEXT +osdp_context; + +void display_sim_reader(OSDP_CONTEXT* ctx, + char* buffer) +{ + char + field[1024]; + int + found_field; + char + json_string[4096]; + json_t* root; + int + status; + json_error_t + status_json; + json_t* value; + + unsigned int + led_color; + int + pd_address; + + status = ST_OK; + found_field = 0; + pd_address = 0; + led_color = 0; + if (status EQUALS ST_OK) { + root = json_loads(buffer, 0, &status_json); + if (!root) { + printf("JSON parser failed. String was ->\n%s<-\n", + json_string); + status = ST_CMD_ERROR; + }; + }; + if (status EQUALS ST_OK) { + found_field = 1; + strcpy(field, "led_color_00"); + value = json_object_get(root, field); + if (!json_is_string(value)) + found_field = 0; + }; + if (found_field) { + char vstr[1024]; + unsigned int i; + strcpy(vstr, json_string_value(value)); + sscanf(vstr + 1, "%x", &i); + fprintf(stdout, "led color %06x\n", i); + led_color = i; + }; + if (status EQUALS ST_OK) { + found_field = 1; + strcpy(field, "pd_address"); + value = json_object_get(root, field); + if (!json_is_string(value)) + found_field = 0; + }; + if (found_field) { + char vstr[1024]; + int i; + strcpy(vstr, json_string_value(value)); + sscanf(vstr, "%d", &i); + pd_address = i; + }; + if (status EQUALS ST_OK) { + found_field = 1; + strcpy(field, "text"); + value = json_object_get(root, field); + if (!json_is_string(value)) + found_field = 0; + }; + if (found_field) { + strcpy(ctx->text, json_string_value(value)); + }; + printf("libosdp PD Reader
\n"); + printf("A: %02x
\n", + pd_address); + printf("
LED ZERO\n", + led_color); + printf("Message Text: %s
\n", + ctx->text); +} + +int main(int + argc, + char* argv[]) +{ /* main for open-osdp-PD-status */ + + char + buffer[16384]; + time_t + current_time; + struct timespec + current_time_fine; + FILE* sf; + int + status; + + status = ST_OK; + printf("Content-type: text/html\n\n"); + printf("open-osdp PD Status"); + printf(""); + printf(""); + + buffer[0] = 0; + sf = fopen("/opt/osdp-conformance/run/PD/open-osdp-status.json", "r"); + if (sf != NULL) { + (void)fread(buffer, sizeof(buffer[0]), sizeof(buffer), sf); + fclose(sf); + }; + clock_gettime(CLOCK_REALTIME, ¤t_time_fine); + current_time = time(NULL); + display_sim_reader(&osdp_context, buffer); + + printf("
\n");
+    printf("Timestamp: %08ld.%08ld %s",
+        (unsigned long int)current_time_fine.tv_sec, current_time_fine.tv_nsec,
+        asctime(localtime(¤t_time)));
+
+    sf = fopen("/opt/osdp-conformance/run/PD/open-osdp-status.json", "r");
+    if (strlen(buffer) > 0) {
+        printf("%s", buffer);
+    };
+    printf("
\n"); + + printf("\n"); + return (status); + +} /* main for open-osdp-PD-status */ diff --git a/pool/shard004/C/0100254_htk.c b/pool/shard004/C/0100254_htk.c new file mode 100644 index 0000000000000000000000000000000000000000..4bcfac33d78b9557185fa8de18045db6c6454108 --- /dev/null +++ b/pool/shard004/C/0100254_htk.c @@ -0,0 +1,74 @@ +/* libSoX file format: HTK (c) 2008 robs@users.sourceforge.net + * + * See http://labrosa.ee.columbia.edu/doc/HTKBook21/HTKBook.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.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 "sox_i.h" + +typedef enum { + Waveform, Lpc, Lprefc, Lpcepstra, Lpdelcep, Irefc, + Mfcc, Fbank, Melspec, User, Discrete, Unknown} kind_t; +static char const * const str[] = { + "Sampled waveform", "Linear prediction filter", "Linear prediction", + "LPC cepstral", "LPC cepstra plus delta", "LPC reflection coef in", + "Mel-frequency cepstral", "Log mel-filter bank", "Linear mel-filter bank", + "User defined sample", "Vector quantised data", "Unknown"}; + +static int start_read(sox_format_t * ft) +{ + uint32_t period_100ns, num_samples; + uint16_t bytes_per_sample, parmKind; + + if (lsx_readdw(ft, &num_samples ) || + lsx_readdw(ft, &period_100ns ) || + lsx_readw (ft, &bytes_per_sample) || + lsx_readw (ft, &parmKind )) return SOX_EOF; + if (parmKind != Waveform) { + int n = min(parmKind & 077, Unknown); + lsx_fail_errno(ft, SOX_EFMT, "unsupported HTK type `%s' (0%o)", str[n], parmKind); + return SOX_EOF; + } + return lsx_check_read_params(ft, 1, 1e7 / period_100ns, + SOX_ENCODING_SIGN2, (unsigned)bytes_per_sample << 3, (off_t)num_samples); +} + +static int write_header(sox_format_t * ft) +{ + double period_100ns = 1e7 / ft->signal.rate; + + if (!ft->olength && floor(period_100ns) != period_100ns) + lsx_warn("rounding sample period %f (x 100ns) to nearest integer", period_100ns); + return lsx_writedw(ft, (unsigned)(ft->olength? ft->olength:ft->signal.length)) + || lsx_writedw(ft, (unsigned)(period_100ns + .5)) + || lsx_writew(ft, ft->encoding.bits_per_sample >> 3) + || lsx_writew(ft, Waveform) ? SOX_EOF : SOX_SUCCESS; +} + +SOX_FORMAT_HANDLER(htk) +{ + static char const * const names[] = {"htk", NULL}; + static unsigned const write_encodings[] = {SOX_ENCODING_SIGN2, 16, 0, 0}; + static sox_format_handler_t handler = { + SOX_LIB_VERSION_CODE, + "PCM format used for Hidden Markov Model speech processing", + names, SOX_FILE_BIG_END | SOX_FILE_MONO | SOX_FILE_REWIND, + start_read, lsx_rawread, NULL, + write_header, lsx_rawwrite, NULL, + lsx_rawseek, write_encodings, NULL, 0 + }; + return &handler; +} diff --git a/pool/shard004/C/0100261_attach-f-p-cmd.c b/pool/shard004/C/0100261_attach-f-p-cmd.c new file mode 100644 index 0000000000000000000000000000000000000000..1e9ed9932163af97c109613a535a86cff5b24fbf --- /dev/null +++ b/pool/shard004/C/0100261_attach-f-p-cmd.c @@ -0,0 +1,49 @@ +/* + * This file is part of attach-f-p strace test. + * + * Copyright (c) 2016 Dmitry V. Levin + * Copyright (c) 2016-2017 The strace developers. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. The name of the author may not be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include "tests.h" +#include +#include + +int +main(void) +{ + skip_if_unavailable("/proc/self/task/"); + + static const char dir[] = "attach-f-p.test cmd"; + pid_t pid = getpid(); + int rc = chdir(dir); + + printf("%-5d chdir(\"%s\") = %s\n" + "%-5d +++ exited with 0 +++\n", + pid, dir, sprintrc(rc), pid); + + return 0; +} diff --git a/pool/shard004/C/0100264_omapimage.c b/pool/shard004/C/0100264_omapimage.c new file mode 100644 index 0000000000000000000000000000000000000000..fa8fe863907426f8c6b220774f8e11b8602f5482 --- /dev/null +++ b/pool/shard004/C/0100264_omapimage.c @@ -0,0 +1,270 @@ +/* + * (C) Copyright 2010 + * Linaro LTD, www.linaro.org + * Author: John Rigby + * Based on TI's signGP.c + * + * (C) Copyright 2009 + * Stefano Babic, DENX Software Engineering, sbabic@denx.de. + * + * (C) Copyright 2008 + * Marvell Semiconductor + * Written-by: Prafulla Wadaskar + * + * 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 + */ + +/* Required to obtain the getline prototype from stdio.h */ +#define _GNU_SOURCE + +#include "mkimage.h" +#include +#include "omapimage.h" + +/* Header size is CH header rounded up to 512 bytes plus GP header */ +#define OMAP_CH_HDR_SIZE 512 +#define OMAP_GP_HDR_SIZE (sizeof(struct gp_header)) +#define OMAP_FILE_HDR_SIZE (OMAP_CH_HDR_SIZE+OMAP_GP_HDR_SIZE) + +static int do_swap32 = 0; + +static uint32_t omapimage_swap32(uint32_t data) +{ + uint32_t result = 0; + result = (data & 0xFF000000) >> 24; + result |= (data & 0x00FF0000) >> 8; + result |= (data & 0x0000FF00) << 8; + result |= (data & 0x000000FF) << 24; + return result; +} + +static uint8_t omapimage_header[OMAP_FILE_HDR_SIZE]; + +static int omapimage_check_image_types(uint8_t type) +{ + if (type == IH_TYPE_OMAPIMAGE) + return EXIT_SUCCESS; + else { + return EXIT_FAILURE; + } +} + +/* + * Only the simplest image type is currently supported: + * TOC pointing to CHSETTINGS + * TOC terminator + * CHSETTINGS + * + * padding to OMAP_CH_HDR_SIZE bytes + * + * gp header + * size + * load_addr + */ +static int valid_gph_size(uint32_t size) +{ + return size; +} + +static int valid_gph_load_addr(uint32_t load_addr) +{ + return load_addr; +} + +static int omapimage_verify_header(unsigned char *ptr, int image_size, + struct mkimage_params *params) +{ + struct ch_toc *toc = (struct ch_toc *)ptr; + struct gp_header *gph = (struct gp_header *)(ptr+OMAP_CH_HDR_SIZE); + uint32_t offset, size, gph_size, gph_load_addr; + + while (toc->section_offset != 0xffffffff + && toc->section_size != 0xffffffff) { + if (do_swap32) { + offset = omapimage_swap32(toc->section_offset); + size = omapimage_swap32(toc->section_size); + } else { + offset = toc->section_offset; + size = toc->section_size; + } + if (!offset || !size) + return -1; + if (offset >= OMAP_CH_HDR_SIZE || + offset+size >= OMAP_CH_HDR_SIZE) + return -1; + toc++; + } + + if (do_swap32) { + gph_size = omapimage_swap32(gph->size); + gph_load_addr = omapimage_swap32(gph->load_addr); + } else { + gph_size = gph->size; + gph_load_addr = gph->load_addr; + } + + if (!valid_gph_size(gph_size)) + return -1; + if (!valid_gph_load_addr(gph_load_addr)) + return -1; + + return 0; +} + +static void omapimage_print_section(struct ch_settings *chs) +{ + const char *section_name; + + if (chs->section_key) + section_name = "CHSETTINGS"; + else + section_name = "UNKNOWNKEY"; + + printf("%s (%x) " + "valid:%x " + "version:%x " + "reserved:%x " + "flags:%x\n", + section_name, + chs->section_key, + chs->valid, + chs->version, + chs->reserved, + chs->flags); +} + +static void omapimage_print_header(const void *ptr) +{ + const struct ch_toc *toc = (struct ch_toc *)ptr; + const struct gp_header *gph = + (struct gp_header *)(ptr+OMAP_CH_HDR_SIZE); + uint32_t offset, size, gph_size, gph_load_addr; + + while (toc->section_offset != 0xffffffff + && toc->section_size != 0xffffffff) { + if (do_swap32) { + offset = omapimage_swap32(toc->section_offset); + size = omapimage_swap32(toc->section_size); + } else { + offset = toc->section_offset; + size = toc->section_size; + } + + if (offset >= OMAP_CH_HDR_SIZE || + offset+size >= OMAP_CH_HDR_SIZE) + exit(EXIT_FAILURE); + + printf("Section %s offset %x length %x\n", + toc->section_name, + toc->section_offset, + toc->section_size); + + omapimage_print_section((struct ch_settings *)(ptr+offset)); + toc++; + } + + if (do_swap32) { + gph_size = omapimage_swap32(gph->size); + gph_load_addr = omapimage_swap32(gph->load_addr); + } else { + gph_size = gph->size; + gph_load_addr = gph->load_addr; + } + + if (!valid_gph_size(gph_size)) { + fprintf(stderr, "Error: invalid image size %x\n", gph_size); + exit(EXIT_FAILURE); + } + + if (!valid_gph_load_addr(gph_load_addr)) { + fprintf(stderr, "Error: invalid image load address %x\n", + gph_load_addr); + exit(EXIT_FAILURE); + } + + printf("GP Header: Size %x LoadAddr %x\n", gph_size, gph_load_addr); +} + +static int toc_offset(void *hdr, void *member) +{ + return member - hdr; +} + +static void omapimage_set_header(void *ptr, struct stat *sbuf, int ifd, + struct mkimage_params *params) +{ + struct ch_toc *toc = (struct ch_toc *)ptr; + struct ch_settings *chs = (struct ch_settings *) + (ptr + 2 * sizeof(*toc)); + struct gp_header *gph = (struct gp_header *)(ptr + OMAP_CH_HDR_SIZE); + + toc->section_offset = toc_offset(ptr, chs); + toc->section_size = sizeof(struct ch_settings); + strcpy((char *)toc->section_name, "CHSETTINGS"); + + chs->section_key = KEY_CHSETTINGS; + chs->valid = 0; + chs->version = 1; + chs->reserved = 0; + chs->flags = 0; + + toc++; + memset(toc, 0xff, sizeof(*toc)); + + gph->size = sbuf->st_size - OMAP_FILE_HDR_SIZE; + gph->load_addr = params->addr; + + if (strncmp(params->imagename, "byteswap-spi", 12) == 0) { + do_swap32 = 1; + int swapped = 0; + uint32_t *data = (uint32_t *)ptr; + + while (swapped <= (sbuf->st_size / sizeof(uint32_t))) { + *data = omapimage_swap32(*data); + swapped++; + data++; + } + } +} + +int omapimage_check_params(struct mkimage_params *params) +{ + return (params->dflag && (params->fflag || params->lflag)) || + (params->fflag && (params->dflag || params->lflag)) || + (params->lflag && (params->dflag || params->fflag)); +} + +/* + * omapimage parameters + */ +static struct image_type_params omapimage_params = { + .name = "TI OMAP CH/GP Boot Image support", + .header_size = OMAP_FILE_HDR_SIZE, + .hdr = (void *)&omapimage_header, + .check_image_type = omapimage_check_image_types, + .verify_header = omapimage_verify_header, + .print_header = omapimage_print_header, + .set_header = omapimage_set_header, + .check_params = omapimage_check_params, +}; + +void init_omap_image_type(void) +{ + mkimage_register(&omapimage_params); +} diff --git a/pool/shard004/C/0100279_mk_memory.c b/pool/shard004/C/0100279_mk_memory.c new file mode 100644 index 0000000000000000000000000000000000000000..828e8a6ec50527a9b8f15b7fb2f7fefa782c2359 --- /dev/null +++ b/pool/shard004/C/0100279_mk_memory.c @@ -0,0 +1,92 @@ +/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ + +/* Monkey HTTP Server + * ================== + * Copyright 2001-2014 Monkey Software LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#define _GNU_SOURCE +#include +#include +#include +#include + +#include "monkey.h" +#include "mk_config.h" +#include "mk_memory.h" +#include "mk_request.h" +#include "mk_header.h" +#include "mk_http.h" +#include "mk_iov.h" +#include "mk_user.h" +#include "mk_macros.h" + +mk_ptr_t mk_ptr_t_create(char *buf, long init, long end) +{ + mk_ptr_t p; + + p.data = buf + init; + + if (init != end) { + p.len = (end - init); + } + else { + p.len = 1; + } + + return p; +} + +void mk_ptr_t_free(mk_ptr_t * p) +{ + mk_mem_free(p->data); + p->len = 0; +} + +char *mk_ptr_t_to_buf(mk_ptr_t p) +{ + char *buf; + + buf = mk_mem_malloc(p.len + 1); + if (!buf) return NULL; + + memcpy(buf, p.data, p.len); + buf[p.len] = '\0'; + + return (char *) buf; +} + +void mk_ptr_t_print(mk_ptr_t p) +{ + unsigned int i; + + printf("\nDEBUG MK_POINTER: '"); + for (i = 0; i < p.len && p.data != NULL; i++) { + printf("%c", p.data[i]); + } + printf("'"); + fflush(stdout); +} + +void mk_ptr_t_set(mk_ptr_t *p, char *data) +{ + p->data = data; + p->len = strlen(data); +} + +void mk_mem_pointers_init() +{ + mk_iov_separators_init(); +} diff --git a/pool/shard004/C/0100283_next-kbd.c b/pool/shard004/C/0100283_next-kbd.c new file mode 100644 index 0000000000000000000000000000000000000000..c7ca3fbbc9629544cf323901cfade9aff519a9e9 --- /dev/null +++ b/pool/shard004/C/0100283_next-kbd.c @@ -0,0 +1,294 @@ +/* + * QEMU NeXT Keyboard/Mouse emulation + * + * Copyright (c) 2011 Bryce Lanham + * + * 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 is admittedly hackish, but works well enough for basic input. Mouse + * support will be added once we can boot something that needs the mouse. + */ + +#include "qemu/osdep.h" +#include "qemu/log.h" +#include "exec/address-spaces.h" +#include "hw/hw.h" +#include "hw/sysbus.h" +#include "hw/m68k/next-cube.h" +#include "ui/console.h" +#include "sysemu/sysemu.h" +#include "migration/vmstate.h" +#include "qom/object.h" + +typedef struct NextKBDState NextKBDState; +DECLARE_INSTANCE_CHECKER(NextKBDState, NEXTKBD, + TYPE_NEXTKBD) + +/* following defintions from next68k netbsd */ +#define CSR_INT 0x00800000 +#define CSR_DATA 0x00400000 + +#define KD_KEYMASK 0x007f +#define KD_DIRECTION 0x0080 /* pressed or released */ +#define KD_CNTL 0x0100 +#define KD_LSHIFT 0x0200 +#define KD_RSHIFT 0x0400 +#define KD_LCOMM 0x0800 +#define KD_RCOMM 0x1000 +#define KD_LALT 0x2000 +#define KD_RALT 0x4000 +#define KD_VALID 0x8000 /* only set for scancode keys ? */ +#define KD_MODS 0x4f00 + +#define KBD_QUEUE_SIZE 256 + +typedef struct { + uint8_t data[KBD_QUEUE_SIZE]; + int rptr, wptr, count; +} KBDQueue; + + +struct NextKBDState { + SysBusDevice sbd; + MemoryRegion mr; + KBDQueue queue; + uint16_t shift; +}; + +static void queue_code(void *opaque, int code); + +/* lots of magic numbers here */ +static uint32_t kbd_read_byte(void *opaque, hwaddr addr) +{ + switch (addr & 0x3) { + case 0x0: /* 0xe000 */ + return 0x80 | 0x20; + + case 0x1: /* 0xe001 */ + return 0x80 | 0x40 | 0x20 | 0x10; + + case 0x2: /* 0xe002 */ + /* returning 0x40 caused mach to hang */ + return 0x10 | 0x2 | 0x1; + + default: + qemu_log_mask(LOG_UNIMP, "NeXT kbd read byte %"HWADDR_PRIx"\n", addr); + } + + return 0; +} + +static uint32_t kbd_read_word(void *opaque, hwaddr addr) +{ + qemu_log_mask(LOG_UNIMP, "NeXT kbd read word %"HWADDR_PRIx"\n", addr); + return 0; +} + +/* even more magic numbers */ +static uint32_t kbd_read_long(void *opaque, hwaddr addr) +{ + int key = 0; + NextKBDState *s = NEXTKBD(opaque); + KBDQueue *q = &s->queue; + + switch (addr & 0xf) { + case 0x0: /* 0xe000 */ + return 0xA0F09300; + + case 0x8: /* 0xe008 */ + /* get keycode from buffer */ + if (q->count > 0) { + key = q->data[q->rptr]; + if (++q->rptr == KBD_QUEUE_SIZE) { + q->rptr = 0; + } + + q->count--; + + if (s->shift) { + key |= s->shift; + } + + if (key & 0x80) { + return 0; + } else { + return 0x10000000 | KD_VALID | key; + } + } else { + return 0; + } + + default: + qemu_log_mask(LOG_UNIMP, "NeXT kbd read long %"HWADDR_PRIx"\n", addr); + return 0; + } +} + +static uint64_t kbd_readfn(void *opaque, hwaddr addr, unsigned size) +{ + switch (size) { + case 1: + return kbd_read_byte(opaque, addr); + case 2: + return kbd_read_word(opaque, addr); + case 4: + return kbd_read_long(opaque, addr); + default: + g_assert_not_reached(); + } +} + +static void kbd_writefn(void *opaque, hwaddr addr, uint64_t value, + unsigned size) +{ + qemu_log_mask(LOG_UNIMP, "NeXT kbd write: size=%u addr=0x%"HWADDR_PRIx + "val=0x%"PRIx64"\n", size, addr, value); +} + +static const MemoryRegionOps kbd_ops = { + .read = kbd_readfn, + .write = kbd_writefn, + .valid.min_access_size = 1, + .valid.max_access_size = 4, + .endianness = DEVICE_NATIVE_ENDIAN, +}; + +static void nextkbd_event(void *opaque, int ch) +{ + /* + * Will want to set vars for caps/num lock + * if (ch & 0x80) -> key release + * there's also e0 escaped scancodes that might need to be handled + */ + queue_code(opaque, ch); +} + +static const unsigned char next_keycodes[128] = { + 0x00, 0x49, 0x4A, 0x4B, 0x4C, 0x4D, 0x50, 0x4F, + 0x4E, 0x1E, 0x1F, 0x20, 0x1D, 0x1C, 0x1B, 0x00, + 0x42, 0x43, 0x44, 0x45, 0x48, 0x47, 0x46, 0x06, + 0x07, 0x08, 0x00, 0x00, 0x2A, 0x00, 0x39, 0x3A, + 0x3B, 0x3C, 0x3D, 0x40, 0x3F, 0x3E, 0x2D, 0x2C, + 0x2B, 0x26, 0x00, 0x00, 0x31, 0x32, 0x33, 0x34, + 0x35, 0x37, 0x36, 0x2e, 0x2f, 0x30, 0x00, 0x00, + 0x00, 0x38, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 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, 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 +}; + +static void queue_code(void *opaque, int code) +{ + NextKBDState *s = NEXTKBD(opaque); + KBDQueue *q = &s->queue; + int key = code & KD_KEYMASK; + int release = code & 0x80; + static int ext; + + if (code == 0xE0) { + ext = 1; + } + + if (code == 0x2A || code == 0x1D || code == 0x36) { + if (code == 0x2A) { + s->shift = KD_LSHIFT; + } else if (code == 0x36) { + s->shift = KD_RSHIFT; + ext = 0; + } else if (code == 0x1D && !ext) { + s->shift = KD_LCOMM; + } else if (code == 0x1D && ext) { + ext = 0; + s->shift = KD_RCOMM; + } + return; + } else if (code == (0x2A | 0x80) || code == (0x1D | 0x80) || + code == (0x36 | 0x80)) { + s->shift = 0; + return; + } + + if (q->count >= KBD_QUEUE_SIZE) { + return; + } + + q->data[q->wptr] = next_keycodes[key] | release; + + if (++q->wptr == KBD_QUEUE_SIZE) { + q->wptr = 0; + } + + q->count++; + + /* + * might need to actually trigger the NeXT irq, but as the keyboard works + * at the moment, I'll worry about it later + */ + /* s->update_irq(s->update_arg, 1); */ +} + +static void nextkbd_reset(DeviceState *dev) +{ + NextKBDState *nks = NEXTKBD(dev); + + memset(&nks->queue, 0, sizeof(KBDQueue)); + nks->shift = 0; +} + +static void nextkbd_realize(DeviceState *dev, Error **errp) +{ + NextKBDState *s = NEXTKBD(dev); + + memory_region_init_io(&s->mr, OBJECT(dev), &kbd_ops, s, "next.kbd", 0x1000); + sysbus_init_mmio(SYS_BUS_DEVICE(dev), &s->mr); + + qemu_add_kbd_event_handler(nextkbd_event, s); +} + +static const VMStateDescription nextkbd_vmstate = { + .name = TYPE_NEXTKBD, + .unmigratable = 1, /* TODO: Implement this when m68k CPU is migratable */ +}; + +static void nextkbd_class_init(ObjectClass *oc, void *data) +{ + DeviceClass *dc = DEVICE_CLASS(oc); + + set_bit(DEVICE_CATEGORY_INPUT, dc->categories); + dc->vmsd = &nextkbd_vmstate; + dc->realize = nextkbd_realize; + dc->reset = nextkbd_reset; +} + +static const TypeInfo nextkbd_info = { + .name = TYPE_NEXTKBD, + .parent = TYPE_SYS_BUS_DEVICE, + .instance_size = sizeof(NextKBDState), + .class_init = nextkbd_class_init, +}; + +static void nextkbd_register_types(void) +{ + type_register_static(&nextkbd_info); +} + +type_init(nextkbd_register_types) diff --git a/pool/shard004/C/0100284_compiler.c b/pool/shard004/C/0100284_compiler.c new file mode 100644 index 0000000000000000000000000000000000000000..c3de6c0d5c54e78a430bcb78e757d84445533747 --- /dev/null +++ b/pool/shard004/C/0100284_compiler.c @@ -0,0 +1,78 @@ +#include +#include +#include + +#include + +#include +#include +#include +#include + + +/** + * Allocate a word of space in memory, and advance DP by + * the size of word (4 bytes). + */ +word_t *comma(context_t *ctx, word_t num) +{ + assert(ctx->dp - ctx->mem < MEMSIZ); + ctx->dp = align(ctx->dp); + *ctx->dp = num; + return ctx->dp++; +} + + +void literal(context_t *ctx, int n) +{ + entry_t *entry; + if (find_entry(ctx->exe_tok, "(LIT)", &entry) == 0) + { + compile(ctx, 2, entry, n); + } + else + { + assert(false); // Failed to find (LIT) + } +} + +void compile(context_t *ctx, int n, ...) +{ + va_list params; + va_start(params, n); + + for (int i = 0; i < n; i++) + { + word_t arg = va_arg(params, word_t); + comma(ctx, arg); + } + + va_end(params); +} + +context_t *load(context_t *ctx, char *filename, char *data) +{ + char *buf = strdup(data); + char *saveptr; + char *line = strtok_r(buf, "\n", &saveptr); + int lineno = 1; + + while (line != NULL) + { + interpret(ctx, line); + if (ctx->state == ERROR) + { + printf(" in '%s' at line %d:\n", filename, lineno); + terminal_setcolor(0x0F); + printf("%s\n", line); + terminal_setcolor(0x07); + break; + } + + line = strsep(&saveptr, "\n"); + lineno++; + } + + free(buf); + return ctx; +} diff --git a/pool/shard004/C/0100286_caps.c b/pool/shard004/C/0100286_caps.c new file mode 100644 index 0000000000000000000000000000000000000000..9a2e0a5f1291cf67cf8a1ac136311bae2ccb7d11 --- /dev/null +++ b/pool/shard004/C/0100286_caps.c @@ -0,0 +1,114 @@ +/* + * The PCI Library -- Capabilities + * + * Copyright (c) 2008 Martin Mares + * + * Can be freely distributed and used under the terms of the GNU GPL. + */ + +#include + +#include "internal.h" + +static void +pci_add_cap(struct pci_dev *d, unsigned int addr, unsigned int id, unsigned int type) +{ + struct pci_cap *cap = pci_malloc(d->access, sizeof(*cap)); + + cap->next = d->first_cap; + d->first_cap = cap; + cap->addr = addr; + cap->id = id; + cap->type = type; + d->access->debug("%04x:%02x:%02x.%d: Found capability %04x of type %d at %04x\n", + d->domain, d->bus, d->dev, d->func, id, type, addr); +} + +static void +pci_scan_trad_caps(struct pci_dev *d) +{ + word status = pci_read_word(d, PCI_STATUS); + byte been_there[256]; + int where; + + if (!(status & PCI_STATUS_CAP_LIST)) + return; + + memset(been_there, 0, 256); + where = pci_read_byte(d, PCI_CAPABILITY_LIST) & ~3; + while (where) + { + byte id = pci_read_byte(d, where + PCI_CAP_LIST_ID); + byte next = pci_read_byte(d, where + PCI_CAP_LIST_NEXT) & ~3; + if (been_there[where]++) + break; + if (id == 0xff) + break; + pci_add_cap(d, where, id, PCI_CAP_NORMAL); + where = next; + } +} + +static void +pci_scan_ext_caps(struct pci_dev *d) +{ + byte been_there[0x1000]; + int where = 0x100; + + if (!pci_find_cap(d, PCI_CAP_ID_EXP, PCI_CAP_NORMAL)) + return; + + memset(been_there, 0, 0x1000); + do + { + u32 header; + int id; + + header = pci_read_long(d, where); + if (!header || header == 0xffffffff) + break; + id = header & 0xffff; + if (been_there[where]++) + break; + pci_add_cap(d, where, id, PCI_CAP_EXTENDED); + where = (header >> 20) & ~3; + } + while (where); +} + +unsigned int +pci_scan_caps(struct pci_dev *d, unsigned int want_fields) +{ + if ((want_fields & PCI_FILL_EXT_CAPS) && !(d->known_fields & PCI_FILL_CAPS)) + want_fields |= PCI_FILL_CAPS; + + if (want_fields & PCI_FILL_CAPS) + pci_scan_trad_caps(d); + if (want_fields & PCI_FILL_EXT_CAPS) + pci_scan_ext_caps(d); + return want_fields; +} + +void +pci_free_caps(struct pci_dev *d) +{ + struct pci_cap *cap; + + while (cap = d->first_cap) + { + d->first_cap = cap->next; + pci_mfree(cap); + } +} + +struct pci_cap * +pci_find_cap(struct pci_dev *d, unsigned int id, unsigned int type) +{ + struct pci_cap *c; + + pci_fill_info_v35(d, ((type == PCI_CAP_NORMAL) ? PCI_FILL_CAPS : PCI_FILL_EXT_CAPS)); + for (c=d->first_cap; c; c=c->next) + if (c->type == type && c->id == id) + return c; + return NULL; +} diff --git a/pool/shard004/C/0100287_alternative.c b/pool/shard004/C/0100287_alternative.c new file mode 100644 index 0000000000000000000000000000000000000000..574e77622c049c68e557d1a7413e6c161b457fb8 --- /dev/null +++ b/pool/shard004/C/0100287_alternative.c @@ -0,0 +1,111 @@ +// SPDX-License-Identifier: GPL-2.0 +#include +#include +#include + +#define MAX_PATCH_LEN (255 - 1) + +static int __initdata_or_module alt_instr_disabled; + +static int __init disable_alternative_instructions(char *str) +{ + alt_instr_disabled = 1; + return 0; +} + +early_param("noaltinstr", disable_alternative_instructions); + +struct brcl_insn { + u16 opc; + s32 disp; +} __packed; + +static u16 __initdata_or_module nop16 = 0x0700; +static u32 __initdata_or_module nop32 = 0x47000000; +static struct brcl_insn __initdata_or_module nop48 = { + 0xc004, 0 +}; + +static const void *nops[] __initdata_or_module = { + &nop16, + &nop32, + &nop48 +}; + +static void __init_or_module add_jump_padding(void *insns, unsigned int len) +{ + struct brcl_insn brcl = { + 0xc0f4, + len / 2 + }; + + memcpy(insns, &brcl, sizeof(brcl)); + insns += sizeof(brcl); + len -= sizeof(brcl); + + while (len > 0) { + memcpy(insns, &nop16, 2); + insns += 2; + len -= 2; + } +} + +static void __init_or_module add_padding(void *insns, unsigned int len) +{ + if (len > 6) + add_jump_padding(insns, len); + else if (len >= 2) + memcpy(insns, nops[len / 2 - 1], len); +} + +static void __init_or_module __apply_alternatives(struct alt_instr *start, + struct alt_instr *end) +{ + struct alt_instr *a; + u8 *instr, *replacement; + u8 insnbuf[MAX_PATCH_LEN]; + + /* + * The scan order should be from start to end. A later scanned + * alternative code can overwrite previously scanned alternative code. + */ + for (a = start; a < end; a++) { + int insnbuf_sz = 0; + + instr = (u8 *)&a->instr_offset + a->instr_offset; + replacement = (u8 *)&a->repl_offset + a->repl_offset; + + if (!test_facility(a->facility)) + continue; + + if (unlikely(a->instrlen % 2 || a->replacementlen % 2)) { + WARN_ONCE(1, "cpu alternatives instructions length is " + "odd, skipping patching\n"); + continue; + } + + memcpy(insnbuf, replacement, a->replacementlen); + insnbuf_sz = a->replacementlen; + + if (a->instrlen > a->replacementlen) { + add_padding(insnbuf + a->replacementlen, + a->instrlen - a->replacementlen); + insnbuf_sz += a->instrlen - a->replacementlen; + } + + s390_kernel_write(instr, insnbuf, insnbuf_sz); + } +} + +void __init_or_module apply_alternatives(struct alt_instr *start, + struct alt_instr *end) +{ + if (!alt_instr_disabled) + __apply_alternatives(start, end); +} + +extern struct alt_instr __alt_instructions[], __alt_instructions_end[]; +void __init apply_alternative_instructions(void) +{ + apply_alternatives(__alt_instructions, __alt_instructions_end); +} diff --git a/pool/shard004/C/0100290_SB0013.c b/pool/shard004/C/0100290_SB0013.c new file mode 100644 index 0000000000000000000000000000000000000000..d78a52e3abb502e11aac32fe12896429001cedaa --- /dev/null +++ b/pool/shard004/C/0100290_SB0013.c @@ -0,0 +1,61 @@ +/* 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_r3_0; +atomic_int atom_1_r5_0; + +void *t0(void *arg){ +label_1:; + atomic_store_explicit(&vars[0], 1, memory_order_seq_cst); + + int v2_r3 = atomic_load_explicit(&vars[1], memory_order_seq_cst); + int v14 = (v2_r3 == 0); + atomic_store_explicit(&atom_0_r3_0, v14, memory_order_seq_cst); + return NULL; +} + +void *t1(void *arg){ +label_2:; + atomic_store_explicit(&vars[1], 1, memory_order_seq_cst); + atomic_store_explicit(&vars[1], 2, memory_order_seq_cst); + int v4_r4 = atomic_load_explicit(&vars[1], memory_order_seq_cst); + int v5_cmpeq = (v4_r4 == v4_r4); + if (v5_cmpeq) goto lbl_LC00; else goto lbl_LC00; +lbl_LC00:; + + int v7_r5 = atomic_load_explicit(&vars[0], memory_order_seq_cst); + int v15 = (v7_r5 == 0); + atomic_store_explicit(&atom_1_r5_0, v15, memory_order_seq_cst); + return NULL; +} + +int main(int argc, char *argv[]){ + pthread_t thr0; + pthread_t thr1; + + atomic_init(&vars[0], 0); + atomic_init(&vars[1], 0); + atomic_init(&atom_0_r3_0, 0); + atomic_init(&atom_1_r5_0, 0); + + pthread_create(&thr0, NULL, t0, NULL); + pthread_create(&thr1, NULL, t1, NULL); + + pthread_join(thr0, NULL); + pthread_join(thr1, NULL); + + int v8 = atomic_load_explicit(&vars[1], memory_order_seq_cst); + int v9 = (v8 == 2); + int v10 = atomic_load_explicit(&atom_0_r3_0, memory_order_seq_cst); + int v11 = atomic_load_explicit(&atom_1_r5_0, memory_order_seq_cst); + int v12_conj = v10 & v11; + int v13_conj = v9 & v12_conj; + if (v13_conj == 1) assert(0); + return 0; +} diff --git a/pool/shard004/C/0100291_title_console.c b/pool/shard004/C/0100291_title_console.c new file mode 100644 index 0000000000000000000000000000000000000000..d0cd1fe54ae23ca4b9aad9c8a50c5143571fca5e --- /dev/null +++ b/pool/shard004/C/0100291_title_console.c @@ -0,0 +1,25 @@ +#include + +#include "title_console.h" +#include "fontAffine.h" + +void TitleConsole_Init(PrintConsole *console, int bg_layer, bool main_engine, int map_base, int tile_base) +{ + consoleInit(console, bg_layer, BgType_ExRotation, BgSize_ER_256x256, map_base, tile_base, main_engine, false); + + ConsoleFont font_future; + + font_future.gfx = (u16 *)fontAffineTiles; + font_future.pal = (u16 *)fontAffinePal; + font_future.numChars = 59; + font_future.numColors = 2; + font_future.bpp = 8; + font_future.asciiOffset = 32; + font_future.convertSingleColor = false; + + consoleSetFont(console, &font_future); + consoleSelect(console); + + bgSetScale(console->bgId, (1 << 6), (1 << 6)); +} + diff --git a/pool/shard004/C/0100294_dtzrzf.c b/pool/shard004/C/0100294_dtzrzf.c new file mode 100644 index 0000000000000000000000000000000000000000..ee5e09edd8869221d4e27fd4d87a312c64293e6e --- /dev/null +++ b/pool/shard004/C/0100294_dtzrzf.c @@ -0,0 +1,308 @@ +/* dtzrzf.f -- translated by f2c (version 20061008). + You must link the resulting object file with libf2c: + on Microsoft Windows system, link with libf2c.lib; + on Linux or Unix systems, link with .../path/to/libf2c.a -lm + or, if you install libf2c.a in a standard place, with -lf2c -lm + -- in that order, at the end of the command line, as in + cc *.o -lf2c -lm + Source for libf2c is in /netlib/f2c/libf2c.zip, e.g., + + http://www.netlib.org/f2c/libf2c.zip +*/ + +#include "f2c.h" +#include "blaswrap.h" + +/* Table of constant values */ + +static integer c__1 = 1; +static integer c_n1 = -1; +static integer c__3 = 3; +static integer c__2 = 2; + +/* Subroutine */ int dtzrzf_(integer *m, integer *n, doublereal *a, integer * + lda, doublereal *tau, doublereal *work, integer *lwork, integer *info) +{ + /* System generated locals */ + integer a_dim1, a_offset, i__1, i__2, i__3, i__4, i__5; + + /* Local variables */ + integer i__, m1, ib, nb, ki, kk, mu, nx, iws, nbmin; + extern /* Subroutine */ int xerbla_(char *, integer *), dlarzb_( + char *, char *, char *, char *, integer *, integer *, integer *, + integer *, doublereal *, integer *, doublereal *, integer *, + doublereal *, integer *, doublereal *, integer *); + extern integer ilaenv_(integer *, char *, char *, integer *, integer *, + integer *, integer *); + extern /* Subroutine */ int dlarzt_(char *, char *, integer *, integer *, + doublereal *, integer *, doublereal *, doublereal *, integer *), dlatrz_(integer *, integer *, integer *, + doublereal *, integer *, doublereal *, doublereal *); + integer ldwork, lwkopt; + logical lquery; + + +/* -- LAPACK routine (version 3.2) -- */ +/* Univ. of Tennessee, Univ. of California Berkeley and NAG Ltd.. */ +/* November 2006 */ + +/* .. Scalar Arguments .. */ +/* .. */ +/* .. Array Arguments .. */ +/* .. */ + +/* Purpose */ +/* ======= */ + +/* DTZRZF reduces the M-by-N ( M<=N ) real upper trapezoidal matrix A */ +/* to upper triangular form by means of orthogonal transformations. */ + +/* The upper trapezoidal matrix A is factored as */ + +/* A = ( R 0 ) * Z, */ + +/* where Z is an N-by-N orthogonal matrix and R is an M-by-M upper */ +/* triangular matrix. */ + +/* Arguments */ +/* ========= */ + +/* M (input) INTEGER */ +/* The number of rows of the matrix A. M >= 0. */ + +/* N (input) INTEGER */ +/* The number of columns of the matrix A. N >= M. */ + +/* A (input/output) DOUBLE PRECISION array, dimension (LDA,N) */ +/* On entry, the leading M-by-N upper trapezoidal part of the */ +/* array A must contain the matrix to be factorized. */ +/* On exit, the leading M-by-M upper triangular part of A */ +/* contains the upper triangular matrix R, and elements M+1 to */ +/* N of the first M rows of A, with the array TAU, represent the */ +/* orthogonal matrix Z as a product of M elementary reflectors. */ + +/* LDA (input) INTEGER */ +/* The leading dimension of the array A. LDA >= max(1,M). */ + +/* TAU (output) DOUBLE PRECISION array, dimension (M) */ +/* The scalar factors of the elementary reflectors. */ + +/* WORK (workspace/output) DOUBLE PRECISION array, dimension (MAX(1,LWORK)) */ +/* On exit, if INFO = 0, WORK(1) returns the optimal LWORK. */ + +/* LWORK (input) INTEGER */ +/* The dimension of the array WORK. LWORK >= max(1,M). */ +/* For optimum performance LWORK >= M*NB, where NB is */ +/* the optimal blocksize. */ + +/* If LWORK = -1, then a workspace query is assumed; the routine */ +/* only calculates the optimal size of the WORK array, returns */ +/* this value as the first entry of the WORK array, and no error */ +/* message related to LWORK is issued by XERBLA. */ + +/* INFO (output) INTEGER */ +/* = 0: successful exit */ +/* < 0: if INFO = -i, the i-th argument had an illegal value */ + +/* Further Details */ +/* =============== */ + +/* Based on contributions by */ +/* A. Petitet, Computer Science Dept., Univ. of Tenn., Knoxville, USA */ + +/* The factorization is obtained by Householder's method. The kth */ +/* transformation matrix, Z( k ), which is used to introduce zeros into */ +/* the ( m - k + 1 )th row of A, is given in the form */ + +/* Z( k ) = ( I 0 ), */ +/* ( 0 T( k ) ) */ + +/* where */ + +/* T( k ) = I - tau*u( k )*u( k )', u( k ) = ( 1 ), */ +/* ( 0 ) */ +/* ( z( k ) ) */ + +/* tau is a scalar and z( k ) is an ( n - m ) element vector. */ +/* tau and z( k ) are chosen to annihilate the elements of the kth row */ +/* of X. */ + +/* The scalar tau is returned in the kth element of TAU and the vector */ +/* u( k ) in the kth row of A, such that the elements of z( k ) are */ +/* in a( k, m + 1 ), ..., a( k, n ). The elements of R are returned in */ +/* the upper triangular part of A. */ + +/* Z is given by */ + +/* Z = Z( 1 ) * Z( 2 ) * ... * Z( m ). */ + +/* ===================================================================== */ + +/* .. Parameters .. */ +/* .. */ +/* .. Local Scalars .. */ +/* .. */ +/* .. External Subroutines .. */ +/* .. */ +/* .. Intrinsic Functions .. */ +/* .. */ +/* .. External Functions .. */ +/* .. */ +/* .. Executable Statements .. */ + +/* Test the input arguments */ + + /* Parameter adjustments */ + a_dim1 = *lda; + a_offset = 1 + a_dim1; + a -= a_offset; + --tau; + --work; + + /* Function Body */ + *info = 0; + lquery = *lwork == -1; + if (*m < 0) { + *info = -1; + } else if (*n < *m) { + *info = -2; + } else if (*lda < max(1,*m)) { + *info = -4; + } + + if (*info == 0) { + if (*m == 0 || *m == *n) { + lwkopt = 1; + } else { + +/* Determine the block size. */ + + nb = ilaenv_(&c__1, "DGERQF", " ", m, n, &c_n1, &c_n1); + lwkopt = *m * nb; + } + work[1] = (doublereal) lwkopt; + + if (*lwork < max(1,*m) && ! lquery) { + *info = -7; + } + } + + if (*info != 0) { + i__1 = -(*info); + xerbla_("DTZRZF", &i__1); + return 0; + } else if (lquery) { + return 0; + } + +/* Quick return if possible */ + + if (*m == 0) { + return 0; + } else if (*m == *n) { + i__1 = *n; + for (i__ = 1; i__ <= i__1; ++i__) { + tau[i__] = 0.; +/* L10: */ + } + return 0; + } + + nbmin = 2; + nx = 1; + iws = *m; + if (nb > 1 && nb < *m) { + +/* Determine when to cross over from blocked to unblocked code. */ + +/* Computing MAX */ + i__1 = 0, i__2 = ilaenv_(&c__3, "DGERQF", " ", m, n, &c_n1, &c_n1); + nx = max(i__1,i__2); + if (nx < *m) { + +/* Determine if workspace is large enough for blocked code. */ + + ldwork = *m; + iws = ldwork * nb; + if (*lwork < iws) { + +/* Not enough workspace to use optimal NB: reduce NB and */ +/* determine the minimum value of NB. */ + + nb = *lwork / ldwork; +/* Computing MAX */ + i__1 = 2, i__2 = ilaenv_(&c__2, "DGERQF", " ", m, n, &c_n1, & + c_n1); + nbmin = max(i__1,i__2); + } + } + } + + if (nb >= nbmin && nb < *m && nx < *m) { + +/* Use blocked code initially. */ +/* The last kk rows are handled by the block method. */ + +/* Computing MIN */ + i__1 = *m + 1; + m1 = min(i__1,*n); + ki = (*m - nx - 1) / nb * nb; +/* Computing MIN */ + i__1 = *m, i__2 = ki + nb; + kk = min(i__1,i__2); + + i__1 = *m - kk + 1; + i__2 = -nb; + for (i__ = *m - kk + ki + 1; i__2 < 0 ? i__ >= i__1 : i__ <= i__1; + i__ += i__2) { +/* Computing MIN */ + i__3 = *m - i__ + 1; + ib = min(i__3,nb); + +/* Compute the TZ factorization of the current block */ +/* A(i:i+ib-1,i:n) */ + + i__3 = *n - i__ + 1; + i__4 = *n - *m; + dlatrz_(&ib, &i__3, &i__4, &a[i__ + i__ * a_dim1], lda, &tau[i__], + &work[1]); + if (i__ > 1) { + +/* Form the triangular factor of the block reflector */ +/* H = H(i+ib-1) . . . H(i+1) H(i) */ + + i__3 = *n - *m; + dlarzt_("Backward", "Rowwise", &i__3, &ib, &a[i__ + m1 * + a_dim1], lda, &tau[i__], &work[1], &ldwork); + +/* Apply H to A(1:i-1,i:n) from the right */ + + i__3 = i__ - 1; + i__4 = *n - i__ + 1; + i__5 = *n - *m; + dlarzb_("Right", "No transpose", "Backward", "Rowwise", &i__3, + &i__4, &ib, &i__5, &a[i__ + m1 * a_dim1], lda, &work[ + 1], &ldwork, &a[i__ * a_dim1 + 1], lda, &work[ib + 1], + &ldwork) + ; + } +/* L20: */ + } + mu = i__ + nb - 1; + } else { + mu = *m; + } + +/* Use unblocked code to factor the last or only block */ + + if (mu > 0) { + i__2 = *n - *m; + dlatrz_(&mu, n, &i__2, &a[a_offset], lda, &tau[1], &work[1]); + } + + work[1] = (doublereal) lwkopt; + + return 0; + +/* End of DTZRZF */ + +} /* dtzrzf_ */ diff --git a/pool/shard004/C/0100295_java_stacktrace.c b/pool/shard004/C/0100295_java_stacktrace.c new file mode 100644 index 0000000000000000000000000000000000000000..c1c874c8e219034f9fc14518afacf9c51e663b4a --- /dev/null +++ b/pool/shard004/C/0100295_java_stacktrace.c @@ -0,0 +1,148 @@ +#include "java_testcases.c" + +#include +#include +#include +#include +#include + +void +test_java_stacktrace_cmp(void) +{ + struct sr_java_stacktrace *stacktraces[2]; + + for (size_t i = 0; i < G_N_ELEMENTS(stacktraces); i++) + { + stacktraces[i] = sr_java_stacktrace_new(); + stacktraces[i]->threads = create_real_main_thread_objects(); + } + + g_assert_cmpint(sr_java_stacktrace_cmp(stacktraces[0], stacktraces[1]), ==, 0); + + sr_java_thread_free(stacktraces[1]->threads); + + stacktraces[1]->threads = NULL; + + g_assert_cmpint(sr_java_stacktrace_cmp(stacktraces[0], stacktraces[1]), !=, 0); + + for (size_t i = 0; i < G_N_ELEMENTS(stacktraces); i++) + { + sr_java_stacktrace_free(stacktraces[i]); + } +} + +void +test_java_stacktrace_dup(void) +{ + struct sr_java_stacktrace *stacktrace; + struct sr_java_stacktrace *dupe_stacktrace; + + stacktrace = sr_java_stacktrace_new(); + + stacktrace->threads = create_real_main_thread_objects(); + + dupe_stacktrace = sr_java_stacktrace_dup(stacktrace); + + g_assert_cmpint(sr_java_stacktrace_cmp(stacktrace, dupe_stacktrace), ==, 0); + + sr_java_stacktrace_free(dupe_stacktrace); + sr_java_stacktrace_free(stacktrace); +} + +static void +test_java_stacktrace_parse(void) +{ + struct sr_java_stacktrace *stacktrace; + const char *input; + const char *cursor; + struct sr_location location; + struct sr_java_stacktrace *parsed_java_stacktrace; + + stacktrace = sr_java_stacktrace_new(); + input = get_real_thread_stacktrace(); + cursor = input; + + stacktrace->threads = create_real_main_thread_objects(); + + sr_location_init(&location); + + parsed_java_stacktrace = sr_java_stacktrace_parse(&cursor, &location); + + g_assert_true(NULL == stacktrace || NULL != parsed_java_stacktrace); + + if (NULL != parsed_java_stacktrace) + { + char *error; + g_autofree char *json1 = NULL; + struct sr_stacktrace *parsed_stacktrace; + g_autofree char *json2 = NULL; + + g_assert_cmpint(*cursor, ==, '\0'); + g_assert_cmpint(sr_java_stacktrace_cmp(parsed_java_stacktrace, stacktrace), ==, 0); + + json1 = sr_stacktrace_to_json((struct sr_stacktrace *) parsed_java_stacktrace); + g_assert_nonnull(json1); + + sr_java_stacktrace_free(parsed_java_stacktrace); + + parsed_stacktrace = sr_stacktrace_parse(SR_REPORT_JAVA, input, &error); + g_assert_nonnull(parsed_stacktrace); + + json2 = sr_stacktrace_to_json(parsed_stacktrace); + g_assert_nonnull(json2); + + g_assert_cmpstr(json1, ==, json2); + + sr_stacktrace_free(parsed_stacktrace); + + } + else + { + /* Check that the pointer is not moved. */ + g_assert_true(cursor == input); + g_assert_nonnull(stacktrace); + } + + sr_java_stacktrace_free(stacktrace); +} + +static void +test_java_stacktrace_reason(void) +{ + char *error = NULL; + g_autofree char *input = NULL; + const char *cursor; + struct sr_location location; + struct sr_java_stacktrace *stacktrace; + g_autofree char *reason = NULL; + + input = sr_file_to_string("java_stacktraces/java-01", &error); + cursor = input; + + g_assert_nonnull(input); + g_assert_null(error); + + stacktrace = sr_java_stacktrace_parse(&cursor, &location); + + g_assert_nonnull(stacktrace); + + reason = sr_java_stacktrace_get_reason(stacktrace); + + g_assert_nonnull(reason); + + sr_java_stacktrace_free(stacktrace); +} + +int +main(int argc, + char **argv) +{ + g_test_init(&argc, &argv, NULL); + + g_test_add_func("/stacktrace/java/cmp", test_java_stacktrace_cmp); + g_test_add_func("/stacktrace/java/dup", test_java_stacktrace_dup); + g_test_add_func("/stacktrace/java/parse", test_java_stacktrace_parse); + g_test_add_func("/stacktrace/java/reason", test_java_stacktrace_reason); + + return g_test_run(); +} diff --git a/pool/shard004/C/0100297_gmx_cyclecounter.c b/pool/shard004/C/0100297_gmx_cyclecounter.c new file mode 100644 index 0000000000000000000000000000000000000000..a1f9b4755e6b91bd249fcacbaaab56ff2fdb1dba --- /dev/null +++ b/pool/shard004/C/0100297_gmx_cyclecounter.c @@ -0,0 +1,132 @@ + /* -*- mode: c; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4; c-file-style: "stroustrup"; -*- + * + * + * This file is part of Gromacs Copyright (c) 1991-2006 + * David van der Spoel, Erik Lindahl, Berk Hess, University of Groningen. + * + * 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. + * + * To help us fund GROMACS development, we humbly ask that you cite + * the research papers on the package. Check out http://www.gromacs.org + * + * And Hey: + * Gnomes, ROck Monsters And Chili Sauce + */ +#ifdef HAVE_CONFIG_H +#include +#endif + +#include +#ifdef HAVE_SYS_TIME_H +#include +#endif + +#ifdef _MSC_VER +#include +#endif + +#include "gmx_cyclecounter.h" + + + + + +/*! \brief Calculate number of seconds per cycle tick on host +* +* This routine runs a timer loop to calibrate the number of +* seconds per the units returned fro gmx_cycles_read(). +* +* \param sampletime Minimum real sample time. It takes some trial-and-error +* to find the correct delay loop size, so the total runtime of +* this routine is about twice this time. +* \return Number of seconds per cycle unit. If it is not possible to +* calculate on this system (for whatever reason) the return value +* will be -1, so check that it is positive before using it. +*/ +double +gmx_cycles_calibrate(double sampletime) +{ +#ifdef _MSC_VER + + /* Windows does not have gettimeofday, but it provides a special + * routine that returns the cycle counter frequency. + */ + LARGE_INTEGER i; + + QueryPerformanceFrequency(&i); + + return 1.0/((double) i.QuadPart); + /* end of MS Windows implementation */ + +#elif (defined HAVE_GETTIMEOFDAY) + + /* generic implementation with gettimeofday() */ + struct timeval t1,t2; + gmx_cycles_t c1,c2; + double timediff,cyclediff; + double d=0.1; /* Dummy variable so we don't optimize away delay loop */ + int i; + + if(!gmx_cycles_have_counter()) + { + return -1; + } + +#if (defined(__alpha__) || defined(__alpha)) + /* Alpha cannot count to more than 4e9, but I don't expect + * that the architecture will go over 2GHz before it dies, so + * up to 2.0 seconds of sampling should be safe. + */ + if(sampletime>2.0) + { + sampletime=2.0; + } +#endif + + /* Start a timing loop. We want this to be largely independent + * of machine speed, so we need to start with a very small number + * of iterations and repeat it until we reach the requested time. + * + * We call gettimeofday an extra time at the start to avoid cache misses. + */ + gettimeofday(&t1,NULL); + gettimeofday(&t1,NULL); + c1=gmx_cycles_read(); + + do + { + /* just a delay loop. To avoid optimizing it away, we calculate a number + * that will underflow to zero in most cases. By conditionally adding it + * to a result at the end it cannot be removed. n=10000 is arbitrary... + */ + for(i=0;i<10000;i++) + d=d/(1.0+(double)i); + /* Read the time again */ + gettimeofday(&t2,NULL); + c2=gmx_cycles_read(); + timediff=(double)(t2.tv_sec-t1.tv_sec)+ + (double)(t2.tv_usec-t1.tv_usec)*1e-6; + } + while( timediff < sampletime ); + + cyclediff=c2-c1; + + /* Add a very small result so the delay loop cannot be optimized away */ + if(d<1e-30) + { + timediff+=d; + } + + /* Return seconds per cycle */ + return timediff/cyclediff; + +#else + /* No timing function available */ + return -1; +#endif +} + + diff --git a/pool/shard004/C/0100301_movie.c b/pool/shard004/C/0100301_movie.c new file mode 100644 index 0000000000000000000000000000000000000000..db67ce5e72d4a8160f67d50541a58041f3df2d44 --- /dev/null +++ b/pool/shard004/C/0100301_movie.c @@ -0,0 +1,255 @@ +/* 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 "movie.h" +#include +#include +#include +#include +#include "general.h" +#include "dynamic.h" + +struct bsv_movie +{ + FILE *file; + + /* A ring buffer keeping track of positions + * in the file for each frame. */ + size_t *frame_pos; + size_t frame_mask; + size_t frame_ptr; + + size_t min_file_pos; + + size_t state_size; + uint8_t *state; + + bool playback; + bool first_rewind; + bool did_rewind; +}; + +static bool init_playback(bsv_movie_t *handle, const char *path) +{ + uint32_t state_size; + uint32_t header[4] = {0}; + global_t *global = global_get_ptr(); + + handle->playback = true; + handle->file = fopen(path, "rb"); + + if (!handle->file) + { + RARCH_ERR("Couldn't open BSV file \"%s\" for playback.\n", path); + return false; + } + + if (fread(header, sizeof(uint32_t), 4, handle->file) != 4) + { + RARCH_ERR("Couldn't read movie header.\n"); + return false; + } + + /* Compatibility with old implementation that + * used incorrect documentation. */ + if (swap_if_little32(header[MAGIC_INDEX]) != BSV_MAGIC + && swap_if_big32(header[MAGIC_INDEX]) != BSV_MAGIC) + { + RARCH_ERR("Movie file is not a valid BSV1 file.\n"); + return false; + } + + if (swap_if_big32(header[CRC_INDEX]) != global->content_crc) + RARCH_WARN("CRC32 checksum mismatch between content file and saved content checksum in replay file header; replay highly likely to desync on playback.\n"); + + state_size = swap_if_big32(header[STATE_SIZE_INDEX]); + + if (state_size) + { + handle->state = (uint8_t*)malloc(state_size); + handle->state_size = state_size; + if (!handle->state) + return false; + + if (fread(handle->state, 1, state_size, handle->file) != state_size) + { + RARCH_ERR("Couldn't read state from movie.\n"); + return false; + } + + if (pretro_serialize_size() == state_size) + pretro_unserialize(handle->state, state_size); + else + RARCH_WARN("Movie format seems to have a different serializer version. Will most likely fail.\n"); + } + + handle->min_file_pos = sizeof(header) + state_size; + + return true; +} + +static bool init_record(bsv_movie_t *handle, const char *path) +{ + uint32_t state_size; + uint32_t header[4] = {0}; + global_t *global = global_get_ptr(); + + handle->file = fopen(path, "wb"); + if (!handle->file) + { + RARCH_ERR("Couldn't open BSV \"%s\" for recording.\n", path); + return false; + } + + /* This value is supposed to show up as + * BSV1 in a HEX editor, big-endian. */ + header[MAGIC_INDEX] = swap_if_little32(BSV_MAGIC); + header[CRC_INDEX] = swap_if_big32(global->content_crc); + state_size = pretro_serialize_size(); + header[STATE_SIZE_INDEX] = swap_if_big32(state_size); + + fwrite(header, 4, sizeof(uint32_t), handle->file); + + handle->min_file_pos = sizeof(header) + state_size; + handle->state_size = state_size; + + if (state_size) + { + handle->state = (uint8_t*)malloc(state_size); + if (!handle->state) + return false; + + pretro_serialize(handle->state, state_size); + fwrite(handle->state, 1, state_size, handle->file); + } + + return true; +} + +void bsv_movie_free(bsv_movie_t *handle) +{ + if (!handle) + return; + + if (handle->file) + fclose(handle->file); + free(handle->state); + free(handle->frame_pos); + free(handle); +} + +bool bsv_movie_get_input(bsv_movie_t *handle, int16_t *input) +{ + if (fread(input, sizeof(int16_t), 1, handle->file) != 1) + return false; + + *input = swap_if_big16(*input); + return true; +} + +void bsv_movie_set_input(bsv_movie_t *handle, int16_t input) +{ + input = swap_if_big16(input); + fwrite(&input, sizeof(int16_t), 1, handle->file); +} + +bsv_movie_t *bsv_movie_init(const char *path, enum rarch_movie_type type) +{ + bsv_movie_t *handle = (bsv_movie_t*)calloc(1, sizeof(*handle)); + if (!handle) + return NULL; + + if (type == RARCH_MOVIE_PLAYBACK) + { + if (!init_playback(handle, path)) + goto error; + } + else if (!init_record(handle, path)) + goto error; + + /* Just pick something really large + * ~1 million frames rewind should do the trick. */ + if (!(handle->frame_pos = (size_t*)calloc((1 << 20), sizeof(size_t)))) + goto error; + + handle->frame_pos[0] = handle->min_file_pos; + handle->frame_mask = (1 << 20) - 1; + + return handle; + +error: + bsv_movie_free(handle); + return NULL; +} + +void bsv_movie_set_frame_start(bsv_movie_t *handle) +{ + if (!handle) + return; + handle->frame_pos[handle->frame_ptr] = ftell(handle->file); +} + +void bsv_movie_set_frame_end(bsv_movie_t *handle) +{ + if (!handle) + return; + + handle->frame_ptr = (handle->frame_ptr + 1) & handle->frame_mask; + + handle->first_rewind = !handle->did_rewind; + handle->did_rewind = false; +} + +void bsv_movie_frame_rewind(bsv_movie_t *handle) +{ + handle->did_rewind = true; + + if ((handle->frame_ptr <= 1) && (handle->frame_pos[0] == handle->min_file_pos)) + { + /* If we're at the beginning... */ + handle->frame_ptr = 0; + fseek(handle->file, handle->min_file_pos, SEEK_SET); + } + else + { + /* First time rewind is performed, the old frame is simply replayed. + * However, playing back that frame caused us to read data, and push + * data to the ring buffer. + * + * Sucessively rewinding frames, we need to rewind past the read data, + * plus another. */ + handle->frame_ptr = (handle->frame_ptr - + (handle->first_rewind ? 1 : 2)) & handle->frame_mask; + fseek(handle->file, handle->frame_pos[handle->frame_ptr], SEEK_SET); + } + + if (ftell(handle->file) <= (long)handle->min_file_pos) + { + /* We rewound past the beginning. */ + + if (!handle->playback) + { + /* If recording, we simply reset + * the starting point. Nice and easy. */ + fseek(handle->file, 4 * sizeof(uint32_t), SEEK_SET); + pretro_serialize(handle->state, handle->state_size); + fwrite(handle->state, 1, handle->state_size, handle->file); + } + else + fseek(handle->file, handle->min_file_pos, SEEK_SET); + } +} + diff --git a/pool/shard004/C/0100307_testMemory3DComplex.c b/pool/shard004/C/0100307_testMemory3DComplex.c new file mode 100644 index 0000000000000000000000000000000000000000..836447b127f0b3537e337c45175a6922f604f20f --- /dev/null +++ b/pool/shard004/C/0100307_testMemory3DComplex.c @@ -0,0 +1,133 @@ +/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +** +** Copyright (C), 2003, Victorian Partnership for Advanced Computing (VPAC) Ltd, 110 Victoria Street, Melbourne, 3053, Australia. +** +** Authors: +** Stevan M. Quenette, Senior Software Engineer, VPAC. (steve@vpac.org) +** Patrick D. Sunter, Software Engineer, VPAC. (pds@vpac.org) +** Luke J. Hodkinson, Computational Engineer, VPAC. (lhodkins@vpac.org) +** Siew-Ching Tan, Software Engineer, VPAC. (siew@vpac.org) +** Alan H. Lo, Computational Engineer, VPAC. (alan@vpac.org) +** Raquibul Hassan, Computational Engineer, VPAC. (raq@vpac.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., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA +** +** Role: +** Tests the allocation, reading and writing of 3D complex arrays. +** +** $Id: testMemory3DComplex.c 3462 2006-02-19 06:53:24Z WalterLandry $ +** +**~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/ + +#include "Base/Foundation/Foundation.h" + +#include "JournalWrappers.h" + +#include +#include +#include + +int main( int argc, char* argv[] ) +{ + MPI_Comm CommWorld; + int rank; + int numProcessors; + int procToWatch; + + Stream* stream; + + Index** setup; + double*** complex3d; + + Index x2 = 3; + Index y2[] = { 4, 2, 3 }; + + Index i, j, k; + + /* Initialise MPI, get world info */ + MPI_Init( &argc, &argv ); + MPI_Comm_dup( MPI_COMM_WORLD, &CommWorld ); + MPI_Comm_size( CommWorld, &numProcessors ); + MPI_Comm_rank( CommWorld, &rank ); + + BaseFoundation_Init( &argc, &argv ); + + stream = Journal_Register ( "info", "MyInfo" ); + + if( argc >= 2 ) + { + procToWatch = atoi( argv[1] ); + } + else + { + procToWatch = 0; + } + if( rank == procToWatch ) + { + Journal_Printf( stream, "Watching rank: %i\n", rank ); + } + + + Journal_Printf( stream, "3D Complex\n" ); + setup = Memory_Alloc_3DSetup( x2, y2 ); + setup[0][0] = 2; + setup[0][1] = 3; + setup[0][2] = 2; + setup[0][3] = 3; + setup[1][0] = 1; + setup[1][1] = 5; + setup[2][0] = 2; + setup[2][1] = 4; + setup[2][2] = 2; + + complex3d = Memory_Alloc_3DComplex_Unnamed( double, x2, y2, setup ); + + /* write */ + for (i = 0; i < x2; ++i) + { + for (j = 0; j < y2[i]; ++j) + { + for (k = 0; k < setup[i][j]; ++k) + { + complex3d[i][j][k] = i + (j / 10.0) + (k / 100.0); + } + } + } + + /* read */ + for (i = 0; i < x2; ++i) + { + for (j = 0; j < y2[i]; ++j) + { + for (k = 0; k < setup[i][j]; ++k) + { + Journal_Printf( stream, "%lf ", complex3d[i][j][k] ); + } + Journal_Printf( stream, "\n" ); + } + } + + + + Memory_Free( setup ); + Memory_Free( complex3d ); + + BaseFoundation_Finalise(); + + /* Close off MPI */ + MPI_Finalize(); + + return 0; /* success */ +} diff --git a/pool/shard004/C/0100310_persistent.c b/pool/shard004/C/0100310_persistent.c new file mode 100644 index 0000000000000000000000000000000000000000..84bc8089c14522b697bb9a916051c9e3495e4410 --- /dev/null +++ b/pool/shard004/C/0100310_persistent.c @@ -0,0 +1,257 @@ +/* + * Freescale STMP378X Persistent bits manipulation driver + * + * Author: Pantelis Antoniou + * + * Copyright 2008-2009 Freescale Semiconductor, Inc. All Rights Reserved. + * Copyright 2008 Embedded Alley Solutions, 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 +#include +#include +#include +#include + +#include + +struct stmp3xxx_persistent_data { + struct device *dev; + struct stmp3xxx_platform_persistent_data *pdata; + int count; + struct attribute_group attr_group; + /* attribute ** follow */ + /* device_attribute follow */ +}; + +#define pd_attribute_ptr(x) \ + ((struct attribute **)((x) + 1)) +#define pd_device_attribute_ptr(x) \ + ((struct device_attribute *)(pd_attribute_ptr(x) + (x)->count + 1)) + +static inline u32 persistent_reg_read(int reg) +{ + u32 msk; + + /* wait for stable value */ + msk = BF(0x01 << reg, RTC_STAT_STALE_REGS); + while (__raw_readl(REGS_RTC_BASE + HW_RTC_STAT) & msk) + cpu_relax(); + + return __raw_readl(REGS_RTC_BASE + 0x60 + (reg * 0x10)); +} + +static inline void persistent_reg_wait_settle(int reg) +{ + u32 msk; + + /* wait until the change is propagated */ + msk = BF(0x01 << reg, RTC_STAT_NEW_REGS); + while (__raw_readl(REGS_RTC_BASE + HW_RTC_STAT) & msk) + cpu_relax(); +} + +static inline void persistent_reg_write(u32 val, int reg) +{ + __raw_writel(val, REGS_RTC_BASE + 0x60 + (reg * 0x10)); + persistent_reg_wait_settle(reg); +} + +static inline void persistent_reg_set(u32 val, int reg) +{ + __raw_writel(val, REGS_RTC_BASE + 0x60 + (reg * 0x10) + 0x4); + persistent_reg_wait_settle(reg); +} + +static inline void persistent_reg_clr(u32 val, int reg) +{ + __raw_writel(val, REGS_RTC_BASE + 0x60 + (reg * 0x10) + 0x8); + persistent_reg_wait_settle(reg); +} + +static inline void persistent_reg_tog(u32 val, int reg) +{ + __raw_writel(val, REGS_RTC_BASE + 0x60 + (reg * 0x10) + 0xc); + persistent_reg_wait_settle(reg); +} + +static ssize_t +persistent_show(struct device *dev, struct device_attribute *attr, char *buf) +{ + struct platform_device *pdev = to_platform_device(dev); + struct stmp3xxx_persistent_data *pd = platform_get_drvdata(pdev); + struct device_attribute *devattr = pd_device_attribute_ptr(pd); + const struct stmp3xxx_persistent_bit_config *pb; + int idx; + u32 val; + + idx = attr - devattr; + if ((unsigned int)idx >= pd->count) + return -EINVAL; + + pb = &pd->pdata->bit_config_tab[idx]; + + /* read value and shift */ + val = persistent_reg_read(pb->reg); + val >>= pb->start; + val &= (1 << pb->width) - 1; + + return sprintf(buf, "%u\n", val); +} + +static ssize_t +persistent_store(struct device *dev, struct device_attribute *attr, + const char *buf, size_t count) +{ + struct platform_device *pdev = to_platform_device(dev); + struct stmp3xxx_persistent_data *pd = platform_get_drvdata(pdev); + struct device_attribute *devattr = pd_device_attribute_ptr(pd); + const struct stmp3xxx_persistent_bit_config *pb; + int idx, r; + unsigned long val, msk; + + idx = attr - devattr; + if ((unsigned int)idx >= pd->count) + return -EINVAL; + + pb = &pd->pdata->bit_config_tab[idx]; + + /* get value to write */ + r = strict_strtoul(buf, 10, &val); + if (r != 0) + return r; + + /* verify it fits */ + if ((unsigned int)val > (1 << pb->width) - 1) + return -EINVAL; + + /* lockless update, first clear the area */ + msk = ((1 << pb->width) - 1) << pb->start; + persistent_reg_clr(msk, pb->reg); + + /* shift into position */ + val <<= pb->start; + persistent_reg_set(val, pb->reg); + + return count; +} + + +static int __devinit stmp3xxx_persistent_probe(struct platform_device *pdev) +{ + struct stmp3xxx_persistent_data *pd; + struct stmp3xxx_platform_persistent_data *pdata; + const struct stmp3xxx_persistent_bit_config *pb; + struct attribute **attr; + struct device_attribute *devattr; + int i, cnt, size; + int err; + + pdata = pdev->dev.platform_data; + if (pdata == NULL) + return -ENODEV; + + cnt = pdata->bit_config_cnt; + size = sizeof(*pd) + + (cnt + 1) * sizeof(struct atrribute *) + + cnt * sizeof(struct device_attribute); + pd = kzalloc(size, GFP_KERNEL); + if (pd == NULL) + return -ENOMEM; + pd->dev = &pdev->dev; + pd->pdata = pdata; + platform_set_drvdata(pdev, pd); + pd->count = cnt; + attr = pd_attribute_ptr(pd); + devattr = pd_device_attribute_ptr(pd); + + /* build the attributes structures */ + pd->attr_group.attrs = attr; + pb = pdata->bit_config_tab; + for (i = 0; i < cnt; i++) { + devattr[i].attr.name = pb[i].name; + devattr[i].attr.mode = S_IWUSR | S_IRUGO; + devattr[i].show = persistent_show; + devattr[i].store = persistent_store; + attr[i] = &devattr[i].attr; + } + + err = sysfs_create_group(&pdev->dev.kobj, &pd->attr_group); + if (err != 0) { + platform_set_drvdata(pdev, NULL); + kfree(pd); + return err; + } + + return 0; +} + +static int stmp3xxx_persistent_remove(struct platform_device *pdev) +{ + struct stmp3xxx_persistent_data *pd; + + pd = platform_get_drvdata(pdev); + sysfs_remove_group(&pdev->dev.kobj, &pd->attr_group); + platform_set_drvdata(pdev, NULL); + kfree(pd); + + return 0; +} + +#ifdef CONFIG_PM +static int +stmp3xxx_persistent_suspend(struct platform_device *pdev, pm_message_t state) +{ + return 0; +} + +static int stmp3xxx_persistent_resume(struct platform_device *pdev) +{ + return 0; +} +#else +#define stmp3xxx_persistent_suspend NULL +#define stmp3xxx_persistent_resume NULL +#endif + +static struct platform_driver stmp3xxx_persistent_driver = { + .probe = stmp3xxx_persistent_probe, + .remove = stmp3xxx_persistent_remove, + .suspend = stmp3xxx_persistent_suspend, + .resume = stmp3xxx_persistent_resume, + .driver = { + .name = "stmp3xxx-persistent", + .owner = THIS_MODULE, + }, +}; + +static int __init stmp3xxx_persistent_init(void) +{ + return platform_driver_register(&stmp3xxx_persistent_driver); +} + +static void __exit stmp3xxx_persistent_exit(void) +{ + platform_driver_unregister(&stmp3xxx_persistent_driver); +} + +MODULE_AUTHOR("Pantelis Antoniou "); +MODULE_DESCRIPTION("Persistent bits user-access driver"); +MODULE_LICENSE("GPL"); + +module_init(stmp3xxx_persistent_init); +module_exit(stmp3xxx_persistent_exit); diff --git a/pool/shard004/C/0100312_example-libev.c b/pool/shard004/C/0100312_example-libev.c new file mode 100644 index 0000000000000000000000000000000000000000..c91aa714951c8f558bb0f99b85245bd07cabe070 --- /dev/null +++ b/pool/shard004/C/0100312_example-libev.c @@ -0,0 +1,129 @@ +#include +#include +#include +#include + +#include +#include +#include + +void delCallback(redisAsyncContext *c, void *r, void *privdata) { + redisReply *reply = r; + int status; + + printf("%s() \n", __FUNCTION__); + + if (reply == NULL) return; + printf("argv[%s]: %s\n", (char*)privdata, reply->str); + + /* Disconnect after receiving the reply to DEL */ + redisAsyncDisconnect(c); + + return; +} + +void getCallback(redisAsyncContext *c, void *r, void *privdata) { + redisReply *reply = r; + int status; + + printf("%s() \n", __FUNCTION__); + + if (reply == NULL) return; + printf("argv[%s]: %s\n", (char*)privdata, reply->str); + + /* DEL Key after receiving the reply to GET */ + status = redisAsyncCommand((redisAsyncContext *)c, delCallback, NULL, "DEL mcc-key-0"); + if (status != REDIS_OK) { + printf("Error: %s\n", c->errstr); + return; + } + + return; +} + +void setCallback(redisAsyncContext *c, void *r, void *privdata) { + redisReply *reply = r; + int status; + + printf("%s() \n", __FUNCTION__); + + if (reply == NULL) return; + printf("argv[%s]: %s\n", (char*)privdata, reply->str); + + /* GET key after receiving the reply to SET */ + status = redisAsyncCommand((redisAsyncContext *)c, getCallback, (char *)"end-1", "GET mcc-key-0"); + if (status != REDIS_OK) { + printf("Error: %s\n", c->errstr); + return; + } + + return; +} + +void connectCallback(const redisAsyncContext *c, int status) { + + if (status != REDIS_OK) { + printf("Error: %s\n", c->errstr); + return; + } + printf("Connected...\n"); + + status = redisAsyncCommand((redisAsyncContext *)c, setCallback, NULL, "SET mcc-key-0 %b nx", "FooBarMCC", strlen("FooBarMCC")); + if (status != REDIS_OK) { + printf("Error: %s\n", c->errstr); + return; + } + + return; +} + +void disconnectCallback(const redisAsyncContext *c, int status) { + if (status != REDIS_OK) { + printf("Error: %s\n", c->errstr); + return; + } + printf("Disconnected...\n"); +} + +// another callback, this time for a time-out +static void timeout_cb (EV_P_ ev_timer *w, int revents) +{ + printf("Timeout Callback...\n"); + // this causes the innermost ev_run to stop iterating + ev_break (EV_A_ EVBREAK_ONE); + + return; +} + +int main (int argc, char **argv) { + signal(SIGPIPE, SIG_IGN); + + ev_timer timeout_watcher; + struct ev_loop *loop = EV_DEFAULT; + redisAsyncContext *c; + + //c = redisAsyncConnect("127.0.0.1", 6379); +#define SERVER_NAME "xmpp.mccdomain.com" + printf("Using DNS name %s, not 127.0.0.1\n", SERVER_NAME); + c = redisAsyncConnect(SERVER_NAME, 6379); + if (c->err) { + /* Let *c leak for now... */ + printf("Error: %s\n", c->errstr); + return 1; + } + + redisLibevAttach(EV_DEFAULT_ c); + redisAsyncSetConnectCallback(c,connectCallback); + redisAsyncSetDisconnectCallback(c,disconnectCallback); + + // initialise a timer watcher, then start it + // simple non-repeating 5.5 second timeout + ev_timer_init (&timeout_watcher, timeout_cb, 5.5, 0.); + ev_timer_start (loop, &timeout_watcher); + + // now wait for events to arrive + ev_run (loop, 0); + + // break was called, so exit + return 0; +} diff --git a/pool/shard004/C/0100313_memcmp.c b/pool/shard004/C/0100313_memcmp.c new file mode 100644 index 0000000000000000000000000000000000000000..8250db25b379818e326a50518a87faed0d1879aa --- /dev/null +++ b/pool/shard004/C/0100313_memcmp.c @@ -0,0 +1,104 @@ +// SPDX-License-Identifier: GPL-2.0 +#include +#include +#include +#include "utils.h" + +#define SIZE 256 +#define ITERATIONS 10000 + +int test_memcmp(const void *s1, const void *s2, size_t n); + +/* test all offsets and lengths */ +static void test_one(char *s1, char *s2) +{ + unsigned long offset, size; + + for (offset = 0; offset < SIZE; offset++) { + for (size = 0; size < (SIZE-offset); size++) { + int x, y; + unsigned long i; + + y = memcmp(s1+offset, s2+offset, size); + x = test_memcmp(s1+offset, s2+offset, size); + + if (((x ^ y) < 0) && /* Trick to compare sign */ + ((x | y) != 0)) { /* check for zero */ + printf("memcmp returned %d, should have returned %d (offset %ld size %ld)\n", x, y, offset, size); + + for (i = offset; i < offset+size; i++) + printf("%02x ", s1[i]); + printf("\n"); + + for (i = offset; i < offset+size; i++) + printf("%02x ", s2[i]); + printf("\n"); + abort(); + } + } + } +} + +static int testcase(void) +{ + char *s1; + char *s2; + unsigned long i; + + s1 = memalign(128, SIZE); + if (!s1) { + perror("memalign"); + exit(1); + } + + s2 = memalign(128, SIZE); + if (!s2) { + perror("memalign"); + exit(1); + } + + srandom(1); + + for (i = 0; i < ITERATIONS; i++) { + unsigned long j; + unsigned long change; + + for (j = 0; j < SIZE; j++) + s1[j] = random(); + + memcpy(s2, s1, SIZE); + + /* change one byte */ + change = random() % SIZE; + s2[change] = random() & 0xff; + + test_one(s1, s2); + } + + srandom(1); + + for (i = 0; i < ITERATIONS; i++) { + unsigned long j; + unsigned long change; + + for (j = 0; j < SIZE; j++) + s1[j] = random(); + + memcpy(s2, s1, SIZE); + + /* change multiple bytes, 1/8 of total */ + for (j = 0; j < SIZE / 8; j++) { + change = random() % SIZE; + s2[change] = random() & 0xff; + } + + test_one(s1, s2); + } + + return 0; +} + +int main(void) +{ + return test_harness(testcase, "memcmp"); +} diff --git a/pool/shard004/C/0100315_ycbcr.c b/pool/shard004/C/0100315_ycbcr.c new file mode 100644 index 0000000000000000000000000000000000000000..2fdfb0ce9913e48d607170094789443b9c1c356d --- /dev/null +++ b/pool/shard004/C/0100315_ycbcr.c @@ -0,0 +1,161 @@ +float ycbcrCoeffs[3] = { .299, .587, .114 }; +/* default coding range is CCIR Rec 601-1 with no headroom/footroom */ +unsigned long refBlackWhite[6] = { 0, 255, 128, 255, 128, 255 }; + +#define LumaRed ycbcrCoeffs[0] +#define LumaGreen ycbcrCoeffs[1] +#define LumaBlue ycbcrCoeffs[2] + +long eRtotal = 0; +long eGtotal = 0; +long eBtotal = 0; +long preveRtotal = 0; +long preveGtotal = 0; +long preveBtotal = 0; +unsigned long AbseRtotal = 0; +unsigned long AbseGtotal = 0; +unsigned long AbseBtotal = 0; +unsigned long eCodes = 0; +unsigned long preveCodes = 0; +unsigned long eBits = 0; +unsigned long preveBits = 0; + +static void setupLumaTables(); +static int abs(int v) { return (v < 0 ? -v : v); } +static double pct(int v,double range) { return (v*100. / range); } +static void check(int R, int G, int B); + +float D1, D2; +float D3, D4; +float D5, D6; + +int +main(int argc, char* argv) +{ + int R, G, B; + + if (argc > 1) { + refBlackWhite[0] = 16; + refBlackWhite[1] = 235; + refBlackWhite[2] = 128; + refBlackWhite[3] = 240; + refBlackWhite[4] = 128; + refBlackWhite[5] = 240; + } + D3 = 2 - 2*LumaRed; + D4 = 2 - 2*LumaBlue; + D1 = 1. / D3; + D2 = 1. / D4; + D5 = D3*LumaRed / LumaGreen; + D6 = D4*LumaBlue / LumaGreen; + setupLumaTables(); + for (R = 0; R < 256; R++) { + for (G = 0; G < 256; G++) + for (B = 0; B < 256; B++) + check(R, G, B); + printf("[%3u] c %u/%u b %u/%u (R %u/%d/%u G %u/%d/%u B %u/%d/%u)\n" + , R + , eCodes - preveCodes, eCodes + , eBits - preveBits, eBits + , abs(AbseRtotal - preveRtotal), eRtotal , AbseRtotal + , abs(AbseGtotal - preveGtotal), eGtotal , AbseGtotal + , abs(AbseBtotal - preveBtotal), eBtotal , AbseBtotal + ); + preveRtotal = AbseRtotal; + preveGtotal = AbseGtotal; + preveBtotal = AbseBtotal; + preveCodes = eCodes; + preveBits = eBits; + } + printf("%u total codes\n", 256*256*256); + printf("total error: %u codes %u bits (R %d/%u G %d/%u B %d/%u)\n" + , eCodes + , eBits + , eRtotal , AbseRtotal + , eGtotal , AbseGtotal + , eBtotal , AbseBtotal + ); + return (0); +} + +float *lumaRed; +float *lumaGreen; +float *lumaBlue; + +static float* +setupLuma(float c) +{ + float *v = (float *)_TIFFmalloc(256 * sizeof (float)); + int i; + for (i = 0; i < 256; i++) + v[i] = c * i; + return (v); +} + +static void +setupLumaTables(void) +{ + lumaRed = setupLuma(LumaRed); + lumaGreen = setupLuma(LumaGreen); + lumaBlue = setupLuma(LumaBlue); +} + +static unsigned +V2Code(float f, unsigned long RB, unsigned long RW, int CR) +{ + unsigned int c = (unsigned int)((((f)*(RW-RB)/CR)+RB)+.5); + return (c > 255 ? 255 : c); +} + +#define Code2V(c, RB, RW, CR) ((((c)-(int)RB)*(float)CR)/(float)(RW-RB)) + +#define CLAMP(f,min,max) \ + (int)((f)+.5 < (min) ? (min) : (f)+.5 > (max) ? (max) : (f)+.5) + +static +void +check(int R, int G, int B) +{ + float Y, Cb, Cr; + int iY, iCb, iCr; + float rY, rCb, rCr; + float rR, rG, rB; + int eR, eG, eB; + + Y = lumaRed[R] + lumaGreen[G] + lumaBlue[B]; + Cb = (B - Y)*D2; + Cr = (R - Y)*D1; + iY = V2Code(Y, refBlackWhite[0], refBlackWhite[1], 255); + iCb = V2Code(Cb, refBlackWhite[2], refBlackWhite[3], 127); + iCr = V2Code(Cr, refBlackWhite[4], refBlackWhite[5], 127); + rCb = Code2V(iCb, refBlackWhite[2], refBlackWhite[3], 127); + rCr = Code2V(iCr, refBlackWhite[4], refBlackWhite[5], 127); + rY = Code2V(iY, refBlackWhite[0], refBlackWhite[1], 255); + rR = rY + rCr*D3; + rB = rY + rCb*D4; + rG = rY - rCb*D6 - rCr*D5; + eR = R - CLAMP(rR,0,255); + eG = G - CLAMP(rG,0,255); + eB = B - CLAMP(rB,0,255); + if (abs(eR) > 1 || abs(eG) > 1 || abs(eB) > 1) { + printf("R %u G %u B %u", R, G, B); + printf(" Y %g Cb %g Cr %g", Y, Cb, Cr); + printf(" iY %u iCb %u iCr %u", iY, iCb, iCr); + printf("\n -> Y %g Cb %g Cr %g", rY, rCb, rCr); + printf(" R %g (%u) G %g (%u) B %g (%u) E=[%d %d %d])\n" + , rR, CLAMP(rR,0,255) + , rG, CLAMP(rG,0,255) + , rB, CLAMP(rB,0,255) + , eR, eG, eB + ); + } + eRtotal += eR; + eGtotal += eG; + eBtotal += eB; + AbseRtotal += abs(eR); + AbseGtotal += abs(eG); + AbseBtotal += abs(eB); + if (eR | eG | eB) + eCodes++; + eBits += abs(eR) + abs(eG) + abs(eB); +} diff --git a/pool/shard004/C/0100317_hashfunc.c b/pool/shard004/C/0100317_hashfunc.c new file mode 100644 index 0000000000000000000000000000000000000000..23fef4d0b10c4bf29521aee7670d87cea1cac8e9 --- /dev/null +++ b/pool/shard004/C/0100317_hashfunc.c @@ -0,0 +1,38 @@ +#define __STDC_FORMAT_MACROS +#include + +#include "hashfunc.h" +#include "dbg.h" + +uint64_t +Hashfunc_djb2(const unsigned char * str) +{ + uint64_t hash = 5381; + int c; +#ifdef DEBUG + const unsigned char * str_start = str; +#endif + + while ((c = *str++)) { + hash = ((hash << 5) + hash) + c; /* hash * 33 + c */ + } + debug("Hashfunc_djb2(%s) -> %" PRIu64, str_start, hash); + return hash; +} + + +uint64_t +Hashfunc_sdbm(const unsigned char *str) +{ + uint64_t hash = 0; + int c; +#ifdef DEBUG + const unsigned char * str_start = str; +#endif + + while ((c = *str++)) { + hash = c + (hash << 6) + (hash << 16) - hash; + } + debug("Hashfunc_sdbm(%s) -> %" PRIu64, str_start, hash); + return hash; +} diff --git a/pool/shard004/C/0100319_watchdogstatus.c b/pool/shard004/C/0100319_watchdogstatus.c new file mode 100644 index 0000000000000000000000000000000000000000..9d54d710f3777f83d56c97a4048d67b3d70ddaf9 --- /dev/null +++ b/pool/shard004/C/0100319_watchdogstatus.c @@ -0,0 +1,133 @@ +/** + ****************************************************************************** + * @addtogroup UAVObjects OpenPilot UAVObjects + * @{ + * @addtogroup WatchdogStatus WatchdogStatus + * @brief For monitoring the flags in the watchdog and especially the bootup flags + * + * Autogenerated files and functions for WatchdogStatus Object + * @{ + * + * @file watchdogstatus.c + * @author The OpenPilot Team, http://www.openpilot.org Copyright (C) 2010. + * @brief Implementation of the WatchdogStatus object. This file has been + * automatically generated by the UAVObjectGenerator. + * + * @note Object definition file: watchdogstatus.xml. + * This is an automatically generated file. + * DO NOT modify manually. + * + * @see The GNU Public License (GPL) Version 3 + * + *****************************************************************************/ +/* + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY + * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ + +#include "openpilot.h" +#include "watchdogstatus.h" + +// Private variables +static UAVObjHandle handle = NULL; + +/** + * Initialize object. + * \return 0 Success + * \return -1 Failure to initialize or -2 for already initialized + */ +int32_t WatchdogStatusInitialize(void) +{ + // Don't set the handle to null if already registered + if(UAVObjGetByID(WATCHDOGSTATUS_OBJID) != NULL) + return -2; + + // Register object with the object manager + handle = UAVObjRegister(WATCHDOGSTATUS_OBJID, + WATCHDOGSTATUS_ISSINGLEINST, WATCHDOGSTATUS_ISSETTINGS, WATCHDOGSTATUS_NUMBYTES, &WatchdogStatusSetDefaults); + + // Done + if (handle != 0) + { + return 0; + } + else + { + return -1; + } +} + +/** + * Initialize object fields and metadata with the default values. + * If a default value is not specified the object fields + * will be initialized to zero. + */ +void WatchdogStatusSetDefaults(UAVObjHandle obj, uint16_t instId) +{ + WatchdogStatusData data; + UAVObjMetadata metadata; + + // Initialize object fields to their default values + UAVObjGetInstanceData(obj, instId, &data); + memset(&data, 0, sizeof(WatchdogStatusData)); + + UAVObjSetInstanceData(obj, instId, &data); + + // Initialize object metadata to their default values + metadata.flags = + ACCESS_READWRITE << UAVOBJ_ACCESS_SHIFT | + ACCESS_READWRITE << UAVOBJ_GCS_ACCESS_SHIFT | + 0 << UAVOBJ_TELEMETRY_ACKED_SHIFT | + 0 << UAVOBJ_GCS_TELEMETRY_ACKED_SHIFT | + UPDATEMODE_PERIODIC << UAVOBJ_TELEMETRY_UPDATE_MODE_SHIFT | + UPDATEMODE_MANUAL << UAVOBJ_GCS_TELEMETRY_UPDATE_MODE_SHIFT; + metadata.telemetryUpdatePeriod = 5000; + metadata.gcsTelemetryUpdatePeriod = 0; + metadata.loggingUpdatePeriod = 5000; + UAVObjSetMetadata(obj, &metadata); +} + +/** + * Get object handle + */ +UAVObjHandle WatchdogStatusHandle() +{ + return handle; +} + +/** + * Get/Set object Functions + */ +void WatchdogStatusBootupFlagsSet( uint16_t *NewBootupFlags ) +{ + UAVObjSetDataField(WatchdogStatusHandle(), (void*)NewBootupFlags, offsetof( WatchdogStatusData, BootupFlags), sizeof(uint16_t)); +} +void WatchdogStatusBootupFlagsGet( uint16_t *NewBootupFlags ) +{ + UAVObjGetDataField(WatchdogStatusHandle(), (void*)NewBootupFlags, offsetof( WatchdogStatusData, BootupFlags), sizeof(uint16_t)); +} +void WatchdogStatusActiveFlagsSet( uint16_t *NewActiveFlags ) +{ + UAVObjSetDataField(WatchdogStatusHandle(), (void*)NewActiveFlags, offsetof( WatchdogStatusData, ActiveFlags), sizeof(uint16_t)); +} +void WatchdogStatusActiveFlagsGet( uint16_t *NewActiveFlags ) +{ + UAVObjGetDataField(WatchdogStatusHandle(), (void*)NewActiveFlags, offsetof( WatchdogStatusData, ActiveFlags), sizeof(uint16_t)); +} + + +/** + * @} + */ + diff --git a/pool/shard004/C/0100321_gus_dma.c b/pool/shard004/C/0100321_gus_dma.c new file mode 100644 index 0000000000000000000000000000000000000000..f45f6116c77ab03d7f171717617f5569a0f4127c --- /dev/null +++ b/pool/shard004/C/0100321_gus_dma.c @@ -0,0 +1,243 @@ +/* + * Routines for GF1 DMA control + * Copyright (c) by Jaroslav Kysela + * + * + * 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 + +static void snd_gf1_dma_ack(struct snd_gus_card * gus) +{ + unsigned long flags; + + spin_lock_irqsave(&gus->reg_lock, flags); + snd_gf1_write8(gus, SNDRV_GF1_GB_DRAM_DMA_CONTROL, 0x00); + snd_gf1_look8(gus, SNDRV_GF1_GB_DRAM_DMA_CONTROL); + spin_unlock_irqrestore(&gus->reg_lock, flags); +} + +static void snd_gf1_dma_program(struct snd_gus_card * gus, + unsigned int addr, + unsigned long buf_addr, + unsigned int count, + unsigned int cmd) +{ + unsigned long flags; + unsigned int address; + unsigned char dma_cmd; + unsigned int address_high; + + // snd_printk("dma_transfer: addr=0x%x, buf=0x%lx, count=0x%x\n", addr, (long) buf, count); + + if (gus->gf1.dma1 > 3) { + if (gus->gf1.enh_mode) { + address = addr >> 1; + } else { + if (addr & 0x1f) { + snd_printd("snd_gf1_dma_transfer: unaligned address (0x%x)?\n", addr); + return; + } + address = (addr & 0x000c0000) | ((addr & 0x0003ffff) >> 1); + } + } else { + address = addr; + } + + dma_cmd = SNDRV_GF1_DMA_ENABLE | (unsigned short) cmd; +#if 0 + dma_cmd |= 0x08; +#endif + if (dma_cmd & SNDRV_GF1_DMA_16BIT) { + count++; + count &= ~1; /* align */ + } + if (gus->gf1.dma1 > 3) { + dma_cmd |= SNDRV_GF1_DMA_WIDTH16; + count++; + count &= ~1; /* align */ + } + snd_gf1_dma_ack(gus); + snd_dma_program(gus->gf1.dma1, buf_addr, count, dma_cmd & SNDRV_GF1_DMA_READ ? DMA_MODE_READ : DMA_MODE_WRITE); +#if 0 + snd_printk("address = 0x%x, count = 0x%x, dma_cmd = 0x%x\n", address << 1, count, dma_cmd); +#endif + spin_lock_irqsave(&gus->reg_lock, flags); + if (gus->gf1.enh_mode) { + address_high = ((address >> 16) & 0x000000f0) | (address & 0x0000000f); + snd_gf1_write16(gus, SNDRV_GF1_GW_DRAM_DMA_LOW, (unsigned short) (address >> 4)); + snd_gf1_write8(gus, SNDRV_GF1_GB_DRAM_DMA_HIGH, (unsigned char) address_high); + } else + snd_gf1_write16(gus, SNDRV_GF1_GW_DRAM_DMA_LOW, (unsigned short) (address >> 4)); + snd_gf1_write8(gus, SNDRV_GF1_GB_DRAM_DMA_CONTROL, dma_cmd); + spin_unlock_irqrestore(&gus->reg_lock, flags); +} + +static struct snd_gf1_dma_block *snd_gf1_dma_next_block(struct snd_gus_card * gus) +{ + struct snd_gf1_dma_block *block; + + /* PCM block have bigger priority than synthesizer one */ + if (gus->gf1.dma_data_pcm) { + block = gus->gf1.dma_data_pcm; + if (gus->gf1.dma_data_pcm_last == block) { + gus->gf1.dma_data_pcm = + gus->gf1.dma_data_pcm_last = NULL; + } else { + gus->gf1.dma_data_pcm = block->next; + } + } else if (gus->gf1.dma_data_synth) { + block = gus->gf1.dma_data_synth; + if (gus->gf1.dma_data_synth_last == block) { + gus->gf1.dma_data_synth = + gus->gf1.dma_data_synth_last = NULL; + } else { + gus->gf1.dma_data_synth = block->next; + } + } else { + block = NULL; + } + if (block) { + gus->gf1.dma_ack = block->ack; + gus->gf1.dma_private_data = block->private_data; + } + return block; +} + + +static void snd_gf1_dma_interrupt(struct snd_gus_card * gus) +{ + struct snd_gf1_dma_block *block; + + snd_gf1_dma_ack(gus); + if (gus->gf1.dma_ack) + gus->gf1.dma_ack(gus, gus->gf1.dma_private_data); + spin_lock(&gus->dma_lock); + if (gus->gf1.dma_data_pcm == NULL && + gus->gf1.dma_data_synth == NULL) { + gus->gf1.dma_ack = NULL; + gus->gf1.dma_flags &= ~SNDRV_GF1_DMA_TRIGGER; + spin_unlock(&gus->dma_lock); + return; + } + block = snd_gf1_dma_next_block(gus); + spin_unlock(&gus->dma_lock); + snd_gf1_dma_program(gus, block->addr, block->buf_addr, block->count, (unsigned short) block->cmd); + kfree(block); +#if 0 + printk("program dma (IRQ) - addr = 0x%x, buffer = 0x%lx, count = 0x%x, cmd = 0x%x\n", addr, (long) buffer, count, cmd); +#endif +} + +int snd_gf1_dma_init(struct snd_gus_card * gus) +{ + mutex_lock(&gus->dma_mutex); + gus->gf1.dma_shared++; + if (gus->gf1.dma_shared > 1) { + mutex_unlock(&gus->dma_mutex); + return 0; + } + gus->gf1.interrupt_handler_dma_write = snd_gf1_dma_interrupt; + gus->gf1.dma_data_pcm = + gus->gf1.dma_data_pcm_last = + gus->gf1.dma_data_synth = + gus->gf1.dma_data_synth_last = NULL; + mutex_unlock(&gus->dma_mutex); + return 0; +} + +int snd_gf1_dma_done(struct snd_gus_card * gus) +{ + struct snd_gf1_dma_block *block; + + mutex_lock(&gus->dma_mutex); + gus->gf1.dma_shared--; + if (!gus->gf1.dma_shared) { + snd_dma_disable(gus->gf1.dma1); + snd_gf1_set_default_handlers(gus, SNDRV_GF1_HANDLER_DMA_WRITE); + snd_gf1_dma_ack(gus); + while ((block = gus->gf1.dma_data_pcm)) { + gus->gf1.dma_data_pcm = block->next; + kfree(block); + } + while ((block = gus->gf1.dma_data_synth)) { + gus->gf1.dma_data_synth = block->next; + kfree(block); + } + gus->gf1.dma_data_pcm_last = + gus->gf1.dma_data_synth_last = NULL; + } + mutex_unlock(&gus->dma_mutex); + return 0; +} + +int snd_gf1_dma_transfer_block(struct snd_gus_card * gus, + struct snd_gf1_dma_block * __block, + int atomic, + int synth) +{ + unsigned long flags; + struct snd_gf1_dma_block *block; + + block = kmalloc(sizeof(*block), atomic ? GFP_ATOMIC : GFP_KERNEL); + if (block == NULL) { + snd_printk(KERN_ERR "gf1: DMA transfer failure; not enough memory\n"); + return -ENOMEM; + } + *block = *__block; + block->next = NULL; +#if 0 + printk("addr = 0x%x, buffer = 0x%lx, count = 0x%x, cmd = 0x%x\n", block->addr, (long) block->buffer, block->count, block->cmd); +#endif +#if 0 + printk("gus->gf1.dma_data_pcm_last = 0x%lx\n", (long)gus->gf1.dma_data_pcm_last); + printk("gus->gf1.dma_data_pcm = 0x%lx\n", (long)gus->gf1.dma_data_pcm); +#endif + spin_lock_irqsave(&gus->dma_lock, flags); + if (synth) { + if (gus->gf1.dma_data_synth_last) { + gus->gf1.dma_data_synth_last->next = block; + gus->gf1.dma_data_synth_last = block; + } else { + gus->gf1.dma_data_synth = + gus->gf1.dma_data_synth_last = block; + } + } else { + if (gus->gf1.dma_data_pcm_last) { + gus->gf1.dma_data_pcm_last->next = block; + gus->gf1.dma_data_pcm_last = block; + } else { + gus->gf1.dma_data_pcm = + gus->gf1.dma_data_pcm_last = block; + } + } + if (!(gus->gf1.dma_flags & SNDRV_GF1_DMA_TRIGGER)) { + gus->gf1.dma_flags |= SNDRV_GF1_DMA_TRIGGER; + block = snd_gf1_dma_next_block(gus); + spin_unlock_irqrestore(&gus->dma_lock, flags); + if (block == NULL) + return 0; + snd_gf1_dma_program(gus, block->addr, block->buf_addr, block->count, (unsigned short) block->cmd); + kfree(block); + return 0; + } + spin_unlock_irqrestore(&gus->dma_lock, flags); + return 0; +} diff --git a/pool/shard004/C/0100322_AfSTMV.c b/pool/shard004/C/0100322_AfSTMV.c new file mode 100644 index 0000000000000000000000000000000000000000..cd108f3f6120063a00f1edc198c8bb4a82769f4e --- /dev/null +++ b/pool/shard004/C/0100322_AfSTMV.c @@ -0,0 +1,187 @@ +//******************************************************************************** +// +// << LC89821x Step Move module >> +// Program Name : AfSTMV.c +// Design : Y.Yamada +// History : First edition 2009.07.31 Y.Tashita +// History : LC898211 changes 2012.06.11 YS.Kim +// History : LC898212 changes 2013.07.19 Rex.Tang +//******************************************************************************** +//************************** +// Include Header File +//************************** +#include "AfSTMV.h" +#include "AfDef.h" + + +//************************** +// Definations +//************************** +#define abs(x) ((x) < 0 ? -(x) : (x)) +#define LC898211_fs 234375 + +/*-------------------------- + Local defination +---------------------------*/ +static stSmvPar StSmvPar; + +/* Step Move to Finish Check Function */ +/* static unsigned char StmvEnd( unsigned char ) ; */ + +/*==================================================================== + Interface functions (import) +=====================================================================*/ +extern void RamWriteA(unsigned short addr, unsigned short data); + +extern void RamReadA(unsigned short addr, unsigned short *data); + +extern void RegWriteA(unsigned short addr, unsigned char data); + +extern void RegReadA(unsigned short addr, unsigned char *data); + +extern void WaitTime(unsigned short msec); + +/*----------------------------------------------------------- + Function Name : StmvSet, StmvTo, StmvEnd + Description : StepMove Setting, Execute, Finish, Current Limit + Arguments : Stepmove Mode Parameter + Return : Stepmove Mode Parameter +-----------------------------------------------------------*/ +//StmvSet -> StmvTo -> StmvEnd -> StmvTo -> StmvEnd ->EEE + +//******************************************************************************** +// Function Name : StmvSet +// Retun Value : NON +// Argment Value : NON +// Explanation : Stpmove parameter Setting Function +// History : First edition 2012.06.12 YS.Kim +// History : Changes 2013.07.19 Rex.Tang +//******************************************************************************** +void StmvSet( stSmvPar StSetSmv ) +{ + unsigned char UcSetEnb; + unsigned char UcSetSwt; + unsigned short UsParSiz; + unsigned char UcParItv; + short SsParStt; // StepMove Start Position + + StSmvPar.UsSmvSiz = StSetSmv.UsSmvSiz; + StSmvPar.UcSmvItv = StSetSmv.UcSmvItv; + StSmvPar.UcSmvEnb = StSetSmv.UcSmvEnb; + + RegWriteA( AFSEND_211 , 0x00 ); // StepMove Enable Bit Clear + + RegReadA( ENBL_211 , &UcSetEnb ); + UcSetEnb &= (unsigned char)0xFD ; + RegWriteA( ENBL_211 , UcSetEnb ); // Measuremenet Circuit1 Off + + RegReadA( SWTCH_211 , &UcSetSwt ); + UcSetSwt &= (unsigned char)0x7F ; + RegWriteA( SWTCH_211 , UcSetSwt ); // RZ1 Switch Cut Off + + RamReadA( RZ_211H , (unsigned short *)&SsParStt ); // Get Start Position + UsParSiz = StSetSmv.UsSmvSiz ; // Get StepSize + UcParItv = StSetSmv.UcSmvItv ; // Get StepInterval + + RamWriteA( ms11a_211H , (unsigned short)0x0800 ); // Set Coefficient Value For StepMove + RamWriteA( MS1Z22_211H , (unsigned short)SsParStt ); // Set Start Positon + RamWriteA( MS1Z12_211H , UsParSiz ); // Set StepSize + RegWriteA( STMINT_211 , UcParItv ); // Set StepInterval + + UcSetSwt |= (unsigned char)0x80; + RegWriteA( SWTCH_211, UcSetSwt ); // RZ1 Switch ON +} + + + +//******************************************************************************** +// Function Name : StmvTo +// Retun Value : Stepmove Parameter +// Argment Value : Stepmove Parameter, Target Position +// Explanation : Stpmove Function +// History : First edition 2012.06.12 YS.Kim +// History : Changes 2013.07.19 Rex.Tang +//******************************************************************************** +unsigned char StmvTo( short SsSmvEnd ) +{ + /* unsigned short UsSmvTim; */ + unsigned short UsSmvDpl; + short SsParStt; // StepMove Start Position + + //PIOA_SetOutput(_PIO_PA29); // Monitor I/O Port + + RamReadA( RZ_211H , (unsigned short *)&SsParStt ); // Get Start Position + UsSmvDpl = abs( SsParStt - SsSmvEnd ); + + if( ( UsSmvDpl <= StSmvPar.UsSmvSiz ) && (( StSmvPar.UcSmvEnb & STMSV_ON ) == STMSV_ON ) ){ + if( StSmvPar.UcSmvEnb & STMCHTG_ON ){ + RegWriteA( MSSET_211 , INI_MSSET_211 | (unsigned char)0x01 ); + } + RamWriteA( MS1Z22_211H, SsSmvEnd ); // Handling Single Step For ES1 + StSmvPar.UcSmvEnb |= STMVEN_ON; // Combine StepMove Enable Bit & StepMove Mode Bit + } else { + if( SsParStt < SsSmvEnd ){ // Check StepMove Direction + RamWriteA( MS1Z12_211H , StSmvPar.UsSmvSiz ); + } else if( SsParStt > SsSmvEnd ){ + RamWriteA( MS1Z12_211H , -StSmvPar.UsSmvSiz ); + } + + RamWriteA( STMVENDH_211, SsSmvEnd ); // Set StepMove Target Positon + StSmvPar.UcSmvEnb |= STMVEN_ON; // Combine StepMove Enable Bit & StepMove Mode Bit + RegWriteA( STMVEN_211 , StSmvPar.UcSmvEnb ); // Start StepMove + } + +#if 1 + /* + * AF step_moveto is set per 33ms, so don't need this waiting. + */ + return 0; +#else + UsSmvTim=(UsSmvDpl/STMV_SIZE)*((STMV_INTERVAL+1)*10000 / LC898211_fs); // Stepmove Operation time + WaitTime( UsSmvTim ); + //TRACE("STMV Operation Time = %d \n", UsSmvTim ) ; + + return StmvEnd( StSmvPar.UcSmvEnb ); +#endif +} + + + +//******************************************************************************** +// Function Name : StmvEnd +// Retun Value : Stepmove Parameter +// Argment Value : Stepmove Parameter +// Explanation : Stpmove Finish Check Function +// History : First edition 2012.06.12 YS.Kim +// History : Changes 2013.07.19 Rex.Tang +//******************************************************************************** +/* unsigned char StmvEnd( unsigned char UcParMod ) +{ + unsigned char UcChtGst; + unsigned short i = 0; + + while( (UcParMod & (unsigned char)STMVEN_ON ) && (i++ < 100)) // Wait StepMove operation end + { + RegReadA( STMVEN_211 , &UcParMod ); + } + + if( ( UcParMod & (unsigned char)0x08 ) == (unsigned char)STMCHTG_ON ){ // If Convergence Judgement is Enabled + for(i=0; icontent_height; + uint32_t h = height, m, dy; + int scroll_width = 0; + if (s->small) { + scroll_width = SCROLL_WIDTH / 2; + } else { + scroll_width = SCROLL_WIDTH; + } + + if(h >= c) { + // If h(eight) > c(ontent height), don't draw anything. + return; + } else { + m = (h * h) / c; + double d = (h - m); + dy = (s->d * d) + 0.5; + } + + y += dy; + x += s->x; + + + if(!s->left) { + x += width - scroll_width; + } + + drawalpha(s->small ? BM_SCROLLHALFTOP_SMALL : BM_SCROLLHALFTOP, x, y, scroll_width, scroll_width /2, s->color); + + y += scroll_width / 2; + int y2 = y + m - scroll_width; + if(scroll_width > m) { + y2 = y; + } + drawrect(x, y, x + scroll_width, y2, s->color); + + drawalpha(s->small ? BM_SCROLLHALFBOT_SMALL : BM_SCROLLHALFBOT, x, y2, scroll_width, scroll_width /2, s->color); +} + +int scroll_gety(SCROLLABLE *s, int height) { + int c = s->content_height; + + if (c > height) { + return (s->d * (double)(c - height)) + 0.5; + } + + return 0; +} + +_Bool scroll_mmove(SCROLLABLE *s, int UNUSED(px), int UNUSED(py), int width, int height, int x, int y, int UNUSED(dx), int dy) +{ + _Bool draw = 0; + + _Bool hit = inrect(x, y, s->left ? 0 : (width - SCROLL_WIDTH), 0, SCROLL_WIDTH, height); + if(s->mouseover != hit) + { + s->mouseover = hit; + draw = 1; + } + + s->mouseover2 = inrect(x, y, 0, 0, width, height); + + if(s->mousedown) + { + uint32_t c = s->content_height; + uint32_t h = height; + + if(c > h) + { + uint32_t m = (h * h) / c; + double d = (h - m); + + s->d = ((s->d * d) + (double)dy) / d; + + if(s->d < 0.0) + { + s->d = 0.0; + } + else if(s->d >= 1.0) + { + s->d = 1.0; + } + + draw = 1; + } + } + + return draw; +} + +_Bool scroll_mdown(SCROLLABLE *s) +{ + if(s->mouseover) + { + s->mousedown = 1; + return 1; + } + + return 0; +} + +_Bool scroll_mright(SCROLLABLE *UNUSED(s)) +{ + return 0; +} + +_Bool scroll_mwheel(SCROLLABLE *s, int height, double delta, _Bool smooth) +{ + if(s->mouseover2) + { + uint32_t content_height = s->content_height; + uint32_t port_height = height; + + if (content_height > port_height) { + if (smooth) { + // this seems to be the magic equation that makes it scroll at the same speed + // regardless of how big the port is compared to the content. + s->d -= (delta * (32.0 * port_height / content_height) / content_height); + } else { + uint32_t magic = (port_height * port_height) / content_height; + double fred = (port_height - magic); + s->d -= 16.0 * delta / fred; + } + + if (s->d < 0.0) { + s->d = 0.0; + } else if (s->d >= 1.0) { + s->d = 1.0; + } + + return 1; + } + } + + return 0; +} + +_Bool scroll_mup(SCROLLABLE *s) +{ + if(s->mousedown) + { + s->mousedown = 0; + return 1; + } + + return 0; +} + +_Bool scroll_mleave(SCROLLABLE *s) +{ + if(s->mouseover) + { + s->mouseover = 0; + return 1; + } + + s->mouseover2 = 0; + + return 0; +} diff --git a/pool/shard004/C/0100332_parser.c b/pool/shard004/C/0100332_parser.c new file mode 100644 index 0000000000000000000000000000000000000000..6c3c45236591981eae38d75d340d6970dd2cd4d9 --- /dev/null +++ b/pool/shard004/C/0100332_parser.c @@ -0,0 +1,237 @@ +/* + * lib/parser.c - simple parser for mount, etc. options. + * + * This source code is licensed under the GNU General Public License, + * Version 2. See the file COPYING for more details. + */ + +#include +#include +#include +#include +#include + +/** + * match_one: - Determines if a string matches a simple pattern + * @s: the string to examine for presense of the pattern + * @p: the string containing the pattern + * @args: array of %MAX_OPT_ARGS &substring_t elements. Used to return match + * locations. + * + * Description: Determines if the pattern @p is present in string @s. Can only + * match extremely simple token=arg style patterns. If the pattern is found, + * the location(s) of the arguments will be returned in the @args array. + */ + /* + *Õâ¸öº¯Êý±È½ÏsÊÇ·ñÆ¥ÅäpÖеÄ×Ö·û´®¡£Èç¹û + *1.s, p¾ùÊÇ×Ö·û´®£¬¾ÍʹÓÃstrcmp±È½Ï + *2.sÖк¬ÓÐÊý×Ö£¬ÀýÈç s = "xxx 5", p = "xxx %d" + * ÕâÒ²ÊÇ¿ÉÒÔÆ¥ÅäµÄ¡£µ«ÊÇ%×î¶àÓÐ3¸ö ¡£Êý×ֵįðʼ¼Ç¼ÔÚargs[]ÖС£ + */ +static int match_one(char *s, char *p, substring_t args[]) +{ + char *meta; + int argc = 0; + + if (!p) + return 1; + + while(1) { + int len = -1; + meta = strchr(p, '%'); + if (!meta) + //ÆÕͨ×Ö·û´®±È½Ï¾ÍʹÓÃstrcmp + return strcmp(p, s) == 0; + + //Èç¹ûmeta-p == 0£¬strncmp×ÜÊÇ·µ»Ø0 + if (strncmp(p, s, meta-p)) + //%֮ǰµÄ×Ö·û´®²»ÏàµÈ¡£ + return 0; + + s += meta - p; + p = meta + 1; + + if (isdigit(*p)) + //´¦ÀíÀýÈç%5sÕâÖÖ¸ñʽ + len = simple_strtoul(p, &p, 10); + else if (*p == '%') { + //´¦Àíµ¥´¿µÄ×Ö·û"%" + if (*s++ != '%') + return 0; + p++; + continue; + } + + if (argc >= MAX_OPT_ARGS) + return 0; + + args[argc].from = s; + switch (*p++) { + case 's': + if (strlen(s) == 0) + return 0; + else if (len == -1 || len > strlen(s)) + len = strlen(s); + //´¦ÀíÀýÈçÌø¹ý%4sÕâÖÖ¸ñʽµÄǰµÄ4¸ö¿Õ¸ñ + args[argc].to = s + len; + break; + case 'd': + simple_strtol(s, &args[argc].to, 0); + goto num; + case 'u': + simple_strtoul(s, &args[argc].to, 0); + goto num; + case 'o': + simple_strtoul(s, &args[argc].to, 8); + goto num; + case 'x': + simple_strtoul(s, &args[argc].to, 16); + num: + if (args[argc].to == args[argc].from) + return 0; + break; + default: + return 0; + } + s = args[argc].to; + argc++; + } +} + +/** + * match_token: - Find a token (and optional args) in a string + * @s: the string to examine for token/argument pairs + * @table: match_table_t describing the set of allowed option tokens and the + * arguments that may be associated with them. Must be terminated with a + * &struct match_token whose pattern is set to the NULL pointer. + * @args: array of %MAX_OPT_ARGS &substring_t elements. Used to return match + * locations. + * + * Description: Detects which if any of a set of token strings has been passed + * to it. Tokens can include up to MAX_OPT_ARGS instances of basic c-style + * format identifiers which will be taken into account when matching the + * tokens, and whose locations will be returned in the @args array. + */ +/* + *Õâ¸öº¯ÊýÓÃÓÚÔÚstruct match_tokenÖÐËÑË÷ºÍÓësÆ¥ÅäµÄtoken(ÕûÐÎ) +*/ +int match_token(char *s, match_table_t table, substring_t args[]) +{ + struct match_token *p; + + for (p = table; !match_one(s, p->pattern, args) ; p++) + ; + + return p->token; +} + +/** + * match_number: scan a number in the given base from a substring_t + * @s: substring to be scanned + * @result: resulting integer on success + * @base: base to use when converting string + * + * Description: Given a &substring_t and a base, attempts to parse the substring + * as a number in that base. On success, sets @result to the integer represented + * by the string and returns 0. Returns either -ENOMEM or -EINVAL on failure. + */ +//½«substring_tÖб£´æµÄÊý×Ö×Ö·û´®£¬×ª»»³ÉintÐÍ +static int match_number(substring_t *s, int *result, int base) +{ + char *endp; + char *buf; + int ret; + + buf = kmalloc(s->to - s->from + 1, GFP_KERNEL); + if (!buf) + return -ENOMEM; + memcpy(buf, s->from, s->to - s->from); + buf[s->to - s->from] = '\0'; + *result = simple_strtol(buf, &endp, base); + ret = 0; + if (endp == buf) + //substring_tÖÐ×Ö·û´®³¤¶ÈΪ0 + ret = -EINVAL; + kfree(buf); + return ret; +} + +/** + * match_int: - scan a decimal representation of an integer from a substring_t + * @s: substring_t to be scanned + * @result: resulting integer on success + * + * Description: Attempts to parse the &substring_t @s as a decimal integer. On + * success, sets @result to the integer represented by the string and returns 0. + * Returns either -ENOMEM or -EINVAL on failure. + */ +int match_int(substring_t *s, int *result) +{ + return match_number(s, result, 0); +} + +/** + * match_octal: - scan an octal representation of an integer from a substring_t + * @s: substring_t to be scanned + * @result: resulting integer on success + * + * Description: Attempts to parse the &substring_t @s as an octal integer. On + * success, sets @result to the integer represented by the string and returns + * 0. Returns either -ENOMEM or -EINVAL on failure. + */ +int match_octal(substring_t *s, int *result) +{ + return match_number(s, result, 8); +} + +/** + * match_hex: - scan a hex representation of an integer from a substring_t + * @s: substring_t to be scanned + * @result: resulting integer on success + * + * Description: Attempts to parse the &substring_t @s as a hexadecimal integer. + * On success, sets @result to the integer represented by the string and + * returns 0. Returns either -ENOMEM or -EINVAL on failure. + */ +int match_hex(substring_t *s, int *result) +{ + return match_number(s, result, 16); +} + +/** + * match_strcpy: - copies the characters from a substring_t to a string + * @to: string to copy characters to. + * @s: &substring_t to copy + * + * Description: Copies the set of characters represented by the given + * &substring_t @s to the c-style string @to. Caller guarantees that @to is + * large enough to hold the characters of @s. + */ +void match_strcpy(char *to, substring_t *s) +{ + memcpy(to, s->from, s->to - s->from); + to[s->to - s->from] = '\0'; +} + +/** + * match_strdup: - allocate a new string with the contents of a substring_t + * @s: &substring_t to copy + * + * Description: Allocates and returns a string filled with the contents of + * the &substring_t @s. The caller is responsible for freeing the returned + * string with kfree(). + */ +char *match_strdup(substring_t *s) +{ + char *p = kmalloc(s->to - s->from + 1, GFP_KERNEL); + if (p) + match_strcpy(p, s); + return p; +} + +EXPORT_SYMBOL(match_token); +EXPORT_SYMBOL(match_int); +EXPORT_SYMBOL(match_octal); +EXPORT_SYMBOL(match_hex); +EXPORT_SYMBOL(match_strcpy); +EXPORT_SYMBOL(match_strdup); diff --git a/pool/shard004/C/0100339_win32mouse.c b/pool/shard004/C/0100339_win32mouse.c new file mode 100644 index 0000000000000000000000000000000000000000..1a4616e7a2ae695973832d45e39977e43068589d --- /dev/null +++ b/pool/shard004/C/0100339_win32mouse.c @@ -0,0 +1,95 @@ +/* win32mouse.c: Win32 routines for emulating Spectrum mice + Copyright (c) 2008 Marek Januszewski + + 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. + + Author contact information: + + E-mail: philip-fuse@shadowmagic.org.uk + +*/ + +#include + +#include +#include /* for GET_X_LPARAM and GET_Y_LPARAM */ + +#include "ui/ui.h" +#include "win32internals.h" + +static void +win32mouse_reset_pointer( void ) +{ + RECT rect; + POINT point; + + GetClientRect( fuse_hWnd, &rect ); + + point.x = rect.left + 128; + point.y = rect.top + 128; + + ClientToScreen( fuse_hWnd, &point ); + SetCursorPos( point.x, point.y ); +} + +void +win32mouse_position( LPARAM lParam ) +{ + int x,y; + + if( !ui_mouse_grabbed ) return; + + x = GET_X_LPARAM( lParam ); + y = GET_Y_LPARAM( lParam ); + + if( x != 128 || y != 128 ) + win32mouse_reset_pointer(); + ui_mouse_motion( x - 128, y - 128 ); + return; +} + +void +win32mouse_button( int button, int down ) +/* button is: 1 - left, 2 - middle, 3 - right, down is: 1 - down, 0 - up */ +{ + ui_mouse_button( button, down ); + return; +} + +int +ui_mouse_grab( int startup ) +{ + if( startup ) return 0; + + SetCursor( NULL ); + SetCapture( fuse_hWnd ); + ui_statusbar_update( UI_STATUSBAR_ITEM_MOUSE, UI_STATUSBAR_STATE_ACTIVE ); + return 1; + +/* doesn't seem like SetCapture can return an error */ +/* + ui_error( UI_ERROR_WARNING, "Mouse grab failed" ); + return 0; +*/ +} + +int +ui_mouse_release( int suspend ) +{ + ReleaseCapture(); + SetCursor( LoadCursor( NULL, IDC_ARROW ) ); + ui_statusbar_update( UI_STATUSBAR_ITEM_MOUSE, UI_STATUSBAR_STATE_INACTIVE ); + return 0; +} diff --git a/pool/shard004/C/0100342_otf_example.c b/pool/shard004/C/0100342_otf_example.c new file mode 100644 index 0000000000000000000000000000000000000000..dbb4f39216515ee3ddb63bfe23348e6a2adc006d --- /dev/null +++ b/pool/shard004/C/0100342_otf_example.c @@ -0,0 +1,117 @@ +/* drivers/misc/otf/otf_example.c + * + * Original source by Benee (c) 2012 + * + * Modified for the OTF by vadonka 2012 + * + * 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. + * + +/* Some example */ +#if 0 +void example_block(void) +{ +...code... +} +EXPORT_SYMBOL(example_block); +--- +extern void example_block(void); +example_block(); +#endif + +#include +#include +#include + +int MIN_EXAMPLEVALUE = 1000; +int MAX_EXAMPLEVALUE = 2000; +int DEF_EXAMPLEVALUE = 1500; + +static int example_value = 1500; +int examplecontrol_value(void) { + return example_value; +} +EXPORT_SYMBOL(examplecontrol_value); +/* + * Calling with this: + ******************** + * extern int examplecontrol_value(void); + * + * Using: + ******** + * examplecontrol_value() + * + */ + +static ssize_t examplecontrol_value_read(struct device * dev, struct device_attribute * attr, char * buf) { + return sprintf(buf, "%d\n", example_value); +} + +static ssize_t examplecontrol_value_write(struct device * dev, struct device_attribute * attr, const char * buf, size_t size) { + int data; + + if (sscanf(buf, "%d\n", &data) == 1) { + if (data != example_value) { + example_value = min(max(data, MIN_EXAMPLEVALUE), MAX_EXAMPLEVALUE); + pr_info("EXAMPLECONTROL threshold changed to %d\n", example_value); + } + } else { + pr_info("EXAMPLECONTROL invalid input\n"); + } + return size; +} + +static ssize_t examplecontrol_min(struct device * dev, struct device_attribute * attr, char * buf) { + return sprintf(buf, "%u\n", MIN_EXAMPLEVALUE); +} + +static ssize_t examplecontrol_max(struct device * dev, struct device_attribute * attr, char * buf) { + return sprintf(buf, "%u\n", MAX_EXAMPLEVALUE); +} + +static ssize_t examplecontrol_def(struct device * dev, struct device_attribute * attr, char * buf) { + return sprintf(buf, "%u\n", DEF_EXAMPLEVALUE); +} + +static DEVICE_ATTR(examplevalue, S_IRUGO | S_IWUGO, examplecontrol_value_read, examplecontrol_value_write); +static DEVICE_ATTR(min, S_IRUGO , examplecontrol_min, NULL); +static DEVICE_ATTR(max, S_IRUGO , examplecontrol_max, NULL); +static DEVICE_ATTR(def, S_IRUGO , examplecontrol_def, NULL); + +static struct attribute *examplecontrol_attributes[] = { + &dev_attr_examplevalue.attr, + &dev_attr_min.attr, + &dev_attr_max.attr, + &dev_attr_def.attr, + NULL +}; + +static struct attribute_group examplecontrol_group = { + .attrs = examplecontrol_attributes, +}; + +static struct miscdevice examplecontrol_device = { + .minor = MISC_DYNAMIC_MINOR, + .name = "examplecontrol", +}; + +static int __init examplecontrol_init(void) { + int ret; + pr_info("%s misc_register(%s)\n", __FUNCTION__, examplecontrol_device.name); + ret = misc_register(&examplecontrol_device); + + if (ret) { + pr_err("%s misc_register(%s) fail\n", __FUNCTION__, examplecontrol_device.name); + return 1; + } + + if (sysfs_create_group(&examplecontrol_device.this_device->kobj, &examplecontrol_group) < 0) { + pr_err("%s sysfs_create_group fail\n", __FUNCTION__); + pr_err("Failed to create sysfs group for device (%s)!\n", examplecontrol_device.name); + } + return 0; +} + +device_initcall(examplecontrol_init); diff --git a/pool/shard004/C/0100344_wdc-samba4.c b/pool/shard004/C/0100344_wdc-samba4.c new file mode 100644 index 0000000000000000000000000000000000000000..2f4945c312ce98dd6c22162748ceff080afd2d04 --- /dev/null +++ b/pool/shard004/C/0100344_wdc-samba4.c @@ -0,0 +1,279 @@ +/* + Unix SMB/CIFS implementation. + + PAC Glue between Samba and the KDC + + Copyright (C) Andrew Bartlett 2005-2009 + Copyright (C) Simo Sorce 2010 + + 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 "kdc/kdc-glue.h" +#include "kdc/pac-glue.h" + +/* Given the right private pointer from hdb_samba4, get a PAC from the attached ldb messages */ +static krb5_error_code samba_wdc_get_pac(void *priv, krb5_context context, + struct hdb_entry_ex *client, + krb5_pac *pac) +{ + TALLOC_CTX *mem_ctx; + DATA_BLOB *pac_blob; + krb5_error_code ret; + NTSTATUS nt_status; + + mem_ctx = talloc_named(client->ctx, 0, "samba_get_pac context"); + if (!mem_ctx) { + return ENOMEM; + } + + nt_status = samba_kdc_get_pac_blob(mem_ctx, client, &pac_blob); + if (!NT_STATUS_IS_OK(nt_status)) { + talloc_free(mem_ctx); + return EINVAL; + } + + ret = samba_make_krb5_pac(context, pac_blob, NULL, pac); + + talloc_free(mem_ctx); + return ret; +} + +/* Resign (and reform, including possibly new groups) a PAC */ + +static krb5_error_code samba_wdc_reget_pac(void *priv, krb5_context context, + const krb5_principal client_principal, + const krb5_principal delegated_proxy_principal, + struct hdb_entry_ex *client, + struct hdb_entry_ex *server, + struct hdb_entry_ex *krbtgt, + krb5_pac *pac) +{ + struct samba_kdc_entry *p = talloc_get_type(server->ctx, struct samba_kdc_entry); + TALLOC_CTX *mem_ctx = talloc_named(p, 0, "samba_kdc_reget_pac context"); + DATA_BLOB *pac_blob; + DATA_BLOB *deleg_blob = NULL; + krb5_error_code ret; + NTSTATUS nt_status; + struct PAC_SIGNATURE_DATA *pac_srv_sig; + struct PAC_SIGNATURE_DATA *pac_kdc_sig; + bool is_in_db, is_untrusted; + + if (!mem_ctx) { + return ENOMEM; + } + + /* The user account may be set not to want the PAC */ + if (!samba_princ_needs_pac(server)) { + talloc_free(mem_ctx); + return EINVAL; + } + + /* If the krbtgt was generated by an RODC, and we are not that + * RODC, then we need to regenerate the PAC - we can't trust + * it */ + ret = samba_krbtgt_is_in_db(krbtgt, &is_in_db, &is_untrusted); + if (ret != 0) { + talloc_free(mem_ctx); + return ret; + } + + if (is_untrusted) { + if (client == NULL) { + return KRB5KDC_ERR_C_PRINCIPAL_UNKNOWN; + } + nt_status = samba_kdc_get_pac_blob(mem_ctx, client, &pac_blob); + if (!NT_STATUS_IS_OK(nt_status)) { + talloc_free(mem_ctx); + return EINVAL; + } + } else { + pac_blob = talloc_zero(mem_ctx, DATA_BLOB); + if (!pac_blob) { + talloc_free(mem_ctx); + return ENOMEM; + } + + pac_srv_sig = talloc_zero(mem_ctx, struct PAC_SIGNATURE_DATA); + if (!pac_srv_sig) { + talloc_free(mem_ctx); + return ENOMEM; + } + + pac_kdc_sig = talloc_zero(mem_ctx, struct PAC_SIGNATURE_DATA); + if (!pac_kdc_sig) { + talloc_free(mem_ctx); + return ENOMEM; + } + + nt_status = samba_kdc_update_pac_blob(mem_ctx, context, + *pac, pac_blob, + pac_srv_sig, pac_kdc_sig); + if (!NT_STATUS_IS_OK(nt_status)) { + DEBUG(0, ("Building PAC failed: %s\n", + nt_errstr(nt_status))); + talloc_free(mem_ctx); + return EINVAL; + } + + if (is_in_db) { + /* Now check the KDC signature, fetching the correct key based on the enc type */ + ret = kdc_check_pac(context, pac_srv_sig->signature, pac_kdc_sig, krbtgt); + if (ret != 0) { + DEBUG(1, ("PAC KDC signature failed to verify\n")); + talloc_free(mem_ctx); + return ret; + } + } + } + + if (delegated_proxy_principal) { + deleg_blob = talloc_zero(mem_ctx, DATA_BLOB); + if (!deleg_blob) { + talloc_free(mem_ctx); + return ENOMEM; + } + + nt_status = samba_kdc_update_delegation_info_blob(mem_ctx, + context, *pac, + server->entry.principal, + delegated_proxy_principal, + deleg_blob); + if (!NT_STATUS_IS_OK(nt_status)) { + DEBUG(0, ("Building PAC failed: %s\n", + nt_errstr(nt_status))); + talloc_free(mem_ctx); + return EINVAL; + } + } + + /* We now completely regenerate this pac */ + krb5_pac_free(context, *pac); + + ret = samba_make_krb5_pac(context, pac_blob, deleg_blob, pac); + + talloc_free(mem_ctx); + return ret; +} + +static char *get_netbios_name(TALLOC_CTX *mem_ctx, HostAddresses *addrs) +{ + char *nb_name = NULL; + size_t len; + unsigned int i; + + for (i = 0; addrs && i < addrs->len; i++) { + if (addrs->val[i].addr_type != KRB5_ADDRESS_NETBIOS) { + continue; + } + len = MIN(addrs->val[i].address.length, 15); + nb_name = talloc_strndup(mem_ctx, + addrs->val[i].address.data, len); + if (nb_name) { + break; + } + } + + if ((nb_name == NULL) || (nb_name[0] == '\0')) { + return NULL; + } + + /* Strip space padding */ + for (len = strlen(nb_name) - 1; + (len > 0) && (nb_name[len] == ' '); + --len) { + nb_name[len] = '\0'; + } + + return nb_name; +} + +static krb5_data fill_krb5_data(void *data, size_t length) +{ + krb5_data kdata; + + kdata.data = data; + kdata.length = length; + + return kdata; +} + +static krb5_error_code samba_wdc_check_client_access(void *priv, + krb5_context context, + krb5_kdc_configuration *config, + hdb_entry_ex *client_ex, const char *client_name, + hdb_entry_ex *server_ex, const char *server_name, + KDC_REQ *req, + krb5_data *e_data) +{ + struct samba_kdc_entry *kdc_entry; + bool password_change; + char *workstation; + NTSTATUS nt_status; + + kdc_entry = talloc_get_type(client_ex->ctx, struct samba_kdc_entry); + password_change = (server_ex && server_ex->entry.flags.change_pw); + workstation = get_netbios_name((TALLOC_CTX *)client_ex->ctx, + req->req_body.addresses); + + nt_status = samba_kdc_check_client_access(kdc_entry, + client_name, + workstation, + password_change); + + if (!NT_STATUS_IS_OK(nt_status)) { + if (NT_STATUS_EQUAL(nt_status, NT_STATUS_NO_MEMORY)) { + return ENOMEM; + } + + if (e_data) { + DATA_BLOB data; + + samba_kdc_build_edata_reply(nt_status, &data); + *e_data = fill_krb5_data(data.data, data.length); + } + + return samba_kdc_map_policy_err(nt_status); + } + + /* Now do the standard Heimdal check */ + return kdc_check_flags(context, config, + client_ex, client_name, + server_ex, server_name, + req->msg_type == krb_as_req); +} + +static krb5_error_code samba_wdc_plugin_init(krb5_context context, void **ptr) +{ + *ptr = NULL; + return 0; +} + +static void samba_wdc_plugin_fini(void *ptr) +{ + return; +} + +struct krb5plugin_windc_ftable windc_plugin_table = { + .minor_version = KRB5_WINDC_PLUGIN_MINOR, + .init = samba_wdc_plugin_init, + .fini = samba_wdc_plugin_fini, + .pac_generate = samba_wdc_get_pac, + .pac_verify = samba_wdc_reget_pac, + .client_access = samba_wdc_check_client_access, +}; + + diff --git a/pool/shard004/C/0100350_starmade.c b/pool/shard004/C/0100350_starmade.c new file mode 100644 index 0000000000000000000000000000000000000000..d90f0591b1f584e9c013e0e53bd2d6544eb441f6 --- /dev/null +++ b/pool/shard004/C/0100350_starmade.c @@ -0,0 +1,253 @@ +/* + * qstat + * by Steve Jankowski + * + * StarMade query protocol + * Copyright 2013 Steven Hartland + * + * Licensed under the Artistic License, see LICENSE.txt for license terms + * + */ + +#include +#ifndef _WIN32 + #include + #include + #include +#else + #include +#endif +#include +#include +#include + +#include "debug.h" +#include "qstat.h" +#include "utils.h" +#include "packet_manip.h" + +typedef enum { + SM_INT = 0x01, + SM_LONG, + SM_FLOAT, + SM_STRING, + SM_BOOLEAN, + SM_BYTE, + SM_SHORT, + SM_BYTE_ARRAY +} starmade_param_type; + +query_status_t +send_starmade_request_packet(struct qserver *server) +{ + char buf[13] = { 0x00, 0x00, 0x00, 0x09, 0x2a, 0xff, 0xff, 0x01, 0x6f, 0x00, 0x00, 0x00, 0x00 }; + + /* + * Header + * int(4) - packet length + * byte - packet type : 0x2a = packet, 0x20 = ping, test = 0x64, logout = 0x41 + * short(2) - packet id + * byte - command id : 0x01 = status, 0x02 = exec + * byte - command type : 0x6f = parameterised command, 0x84 = stream command + * + * Paramters + * int(4) - paramter count + * byte - paramter type : 1 = int, 2 = long, 3 = float, 4 = UTF8 string, 5 = boolean, 6 = byte, 7 = short, 8 = byte array + * ... + */ + + debug(3, "send_starmade_request_packet: state = %ld", server->challenge); + + return (send_packet(server, buf, 13)); +} + + +static query_status_t +starmade_read_parameter(char **datap, int *datalen, void *val, int vlen, starmade_param_type type) +{ + int size; + + if (**datap != type) { + /* unexpected type */ + debug(2, "Invalid type detected, expected 0x%02x got 0x%02x", type, **datap); + return (REQ_ERROR); + } + + (*datap)++; + (*datalen)--; + + switch (type) { + case SM_INT: + size = 4; + if ((size > vlen) || (size > *datalen)) { + return (MEM_ERROR); + } + *(uint32_t *)val = ((uint32_t)(*datap)[3]) | + ((uint32_t)(*datap)[2] << 8) | + ((uint32_t)(*datap)[1] << 16) | + ((uint32_t)(*datap)[0] << 24); + break; + + case SM_LONG: + size = 8; + if ((size > vlen) || (size > *datalen)) { + return (MEM_ERROR); + } + *(uint64_t *)val = ((uint64_t)(*datap)[7]) | + ((uint64_t)(*datap)[6] << 8) | + ((uint64_t)(*datap)[5] << 16) | + ((uint64_t)(*datap)[4] << 24) | + ((uint64_t)(*datap)[3] << 32) | + ((uint64_t)(*datap)[2] << 40) | + ((uint64_t)(*datap)[1] << 48) | + ((uint64_t)(*datap)[0] << 56); + break; + + case SM_FLOAT: + size = 4; + if ((size > vlen) || (size > *datalen)) { + return (MEM_ERROR); + } + *(uint32_t *)val = (uint32_t)(*datap)[3] | + ((uint32_t)(*datap)[2] << 8) | + ((uint32_t)(*datap)[1] << 16) | + ((uint32_t)(*datap)[0] << 24); + break; + + case SM_STRING: + size = ((short)(*datap)[1]) | ((short)(*datap)[0] << 8); + if ((size > vlen) || (size > *datalen)) { + return (MEM_ERROR); + } + (*datap) += 2; + memcpy(val, *datap, size); + ((char *)val)[size] = 0x00; + break; + + case SM_BOOLEAN: + size = 1; + if ((size > vlen) || (size > *datalen)) { + return (MEM_ERROR); + } + *(unsigned char *)val = **datap; + break; + + case SM_BYTE: + size = 1; + if ((size > vlen) || (size > *datalen)) { + return (MEM_ERROR); + } + *(unsigned char *)val = **datap; + break; + + case SM_SHORT: + size = 2; + if ((size > vlen) || (size > *datalen)) { + return (MEM_ERROR); + } + *(short *)val = (short)(*datap)[1] | ((short)(*datap)[0] << 8); + break; + + case SM_BYTE_ARRAY: + debug(2, "Unsupport type 0x%02x requested / received", type); + return (REQ_ERROR); + + default: + debug(2, "Unknown type 0x%02x requested / received", type); + return (REQ_ERROR); + } + + (*datap) += size; + (*datalen) -= size; + + return (INPROGRESS); +} + + +query_status_t +deal_with_starmade_packet(struct qserver *server, char *rawpkt, int pktlen) +{ + char *s, buf[256]; + int ret; + + debug(2, "processing..."); + + if (pktlen < 54) { + // Invalid password + return (REQ_ERROR); + } + + s = rawpkt; + + // TODO: continue reading / combining packets until we've read enough. + debug(3, "packet: combined = %d, challenge = %ld", server->combined, server->challenge); + // Packet Header + // int - response size excluding header (12 bytes) + s += 4; + // long - ts?? + s += 8; + + // Response Header + // TODO: validate header details + // byte - packet type + s += 1; + // short - packet id + s += 2; + // byte - command id + s += 1; + // byte - command type + s += 1; + + // Parameters + // int - paramater count + s += 4; + + // byte - info version + ret = starmade_read_parameter(&s, &pktlen, buf, sizeof(buf), SM_BYTE); + if (ret != INPROGRESS) { + return (ret); + } + + // float - version + ret = starmade_read_parameter(&s, &pktlen, buf, sizeof(buf), SM_FLOAT); + if (ret != INPROGRESS) { + return (ret); + } + + // string - server name + ret = starmade_read_parameter(&s, &pktlen, buf, sizeof(buf), SM_STRING); + if (ret != INPROGRESS) { + return (ret); + } + server->server_name = strdup(buf); + + // string - description + ret = starmade_read_parameter(&s, &pktlen, buf, sizeof(buf), SM_STRING); + if (ret != INPROGRESS) { + return (ret); + } + + // long - start time + ret = starmade_read_parameter(&s, &pktlen, buf, sizeof(buf), SM_LONG); + if (ret != INPROGRESS) { + return (ret); + } + + // int - player count + ret = starmade_read_parameter(&s, &pktlen, &server->num_players, sizeof(server->num_players), SM_INT); + if (ret != INPROGRESS) { + return (ret); + } + + // int - max players + ret = starmade_read_parameter(&s, &pktlen, &server->max_players, sizeof(server->max_players), SM_INT); + if (ret != INPROGRESS) { + return (ret); + } + + gettimeofday(&server->packet_time1, NULL); + + server->map_name = strdup("default"); + + return (DONE_FORCE); +} diff --git a/pool/shard004/C/0100357_test-freopen-safer.c b/pool/shard004/C/0100357_test-freopen-safer.c new file mode 100644 index 0000000000000000000000000000000000000000..5d658f7811b9e8d39c2871ef582d9f006b71645f --- /dev/null +++ b/pool/shard004/C/0100357_test-freopen-safer.c @@ -0,0 +1,97 @@ +/* Test of reopening a stream. + Copyright (C) 2009-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 Eric Blake , 2009. */ + +#include + +/* Specification. */ +#include "stdio--.h" + +/* Helpers. */ +#include + +/* This test intentionally closes stderr. So, we arrange to have fd 10 + (outside the range of interesting fd's during the test) set up to + duplicate the original stderr. */ + +#define BACKUP_STDERR_FILENO 10 +#define ASSERT_STREAM myerr +#include "macros.h" + +static FILE *myerr; + +int +main (void) +{ + FILE *fp; + + /* We close fd 2 later, so save it in fd 10. */ + if (dup2 (STDERR_FILENO, BACKUP_STDERR_FILENO) != BACKUP_STDERR_FILENO + || (myerr = fdopen (BACKUP_STDERR_FILENO, "w")) == NULL) + return 2; + + { + FILE *tmp; + ASSERT (tmp = fopen ("/dev/null", "r")); + ASSERT (STDERR_FILENO < fileno (tmp)); + ASSERT (fp = fopen ("/dev/null", "w")); + ASSERT (fileno (tmp) < fileno (fp)); + ASSERT (fclose (tmp) == 0); + } + + /* Gap in fds. */ + ASSERT (freopen ("/dev/null", "r+", fp) == fp); + ASSERT (STDERR_FILENO < fileno (fp)); + + ASSERT (freopen ("/dev/null", "r", stdin) == stdin); + ASSERT (STDIN_FILENO == fileno (stdin)); + + ASSERT (freopen ("/dev/null", "w", stdout) == stdout); + ASSERT (STDOUT_FILENO == fileno (stdout)); + + ASSERT (freopen ("/dev/null", "w", stderr) == stderr); + ASSERT (STDERR_FILENO == fileno (stderr)); + + /* fd 0 closed. */ + ASSERT (close (STDIN_FILENO) == 0); + + ASSERT (freopen ("/dev/null", "w", stdout) == stdout); + ASSERT (STDOUT_FILENO == fileno (stdout)); + + ASSERT (freopen ("/dev/null", "w", stderr) == stderr); + ASSERT (STDERR_FILENO == fileno (stderr)); + + ASSERT (freopen ("/dev/null", "a", fp) == fp); + ASSERT (STDERR_FILENO < fileno (fp)); + + /* fd 1 closed. */ + ASSERT (close (STDOUT_FILENO) == 0); + + ASSERT (freopen ("/dev/null", "w", stderr) == stderr); + ASSERT (STDERR_FILENO == fileno (stderr)); + + ASSERT (freopen ("/dev/null", "a+", fp) == fp); + ASSERT (STDERR_FILENO < fileno (fp)); + + /* fd 2 closed. */ + ASSERT (close (STDERR_FILENO) == 0); + + ASSERT (freopen ("/dev/null", "w+", fp) == fp); + ASSERT (STDERR_FILENO < fileno (fp)); + + return 0; +} diff --git a/pool/shard004/C/0100370_pf.c b/pool/shard004/C/0100370_pf.c new file mode 100644 index 0000000000000000000000000000000000000000..f116ac3c1fb1795e1a6803cf7bd5dd205625dac9 --- /dev/null +++ b/pool/shard004/C/0100370_pf.c @@ -0,0 +1,81 @@ +/* + * pf.c - Print file attributes on an ext2 file system + * + * Copyright (C) 1993, 1994 Remy Card + * Laboratoire MASI, Institut Blaise Pascal + * Universite Pierre et Marie Curie (Paris VI) + * + * %Begin-Header% + * This file may be redistributed under the terms of the GNU Library + * General Public License, version 2. + * %End-Header% + */ + +/* + * History: + * 93/10/30 - Creation + */ + +#include "config.h" +#include + +#include "e2p.h" + +struct flags_name { + unsigned long flag; + const char *short_name; + const char *long_name; +}; + +static struct flags_name flags_array[] = { + { EXT2_SECRM_FL, "s", "Secure_Deletion" }, + { EXT2_UNRM_FL, "u" , "Undelete" }, + { EXT2_SYNC_FL, "S", "Synchronous_Updates" }, + { EXT2_DIRSYNC_FL, "D", "Synchronous_Directory_Updates" }, + { EXT2_IMMUTABLE_FL, "i", "Immutable" }, + { EXT2_APPEND_FL, "a", "Append_Only" }, + { EXT2_NODUMP_FL, "d", "No_Dump" }, + { EXT2_NOATIME_FL, "A", "No_Atime" }, + { EXT2_COMPR_FL, "c", "Compression_Requested" }, +#ifdef ENABLE_COMPRESSION + { EXT2_COMPRBLK_FL, "B", "Compressed_File" }, + { EXT2_DIRTY_FL, "Z", "Compressed_Dirty_File" }, + { EXT2_NOCOMPR_FL, "X", "Compression_Raw_Access" }, + { EXT2_ECOMPR_FL, "E", "Compression_Error" }, +#endif + { EXT3_JOURNAL_DATA_FL, "j", "Journaled_Data" }, + { EXT2_INDEX_FL, "I", "Indexed_directory" }, + { EXT2_NOTAIL_FL, "t", "No_Tailmerging" }, + { EXT2_TOPDIR_FL, "T", "Top_of_Directory_Hierarchies" }, + { EXT4_EXTENTS_FL, "e", "Extents" }, + { EXT4_HUGE_FILE_FL, "h", "Huge_file" }, + { FS_NOCOW_FL, "C", "No_COW" }, + { EXT4_INLINE_DATA_FL, "N", "Inline_Data" }, + { 0, NULL, NULL } +}; + +void print_flags (FILE * f, unsigned long flags, unsigned options) +{ + int long_opt = (options & PFOPT_LONG); + struct flags_name *fp; + int first = 1; + + for (fp = flags_array; fp->flag != 0; fp++) { + if (flags & fp->flag) { + if (long_opt) { + if (first) + first = 0; + else + fputs(", ", f); + fputs(fp->long_name, f); + } else + fputs(fp->short_name, f); + } else { + if (!long_opt) + fputs("-", f); + } + } + if (long_opt && first) + fputs("---", f); +} + diff --git a/pool/shard004/C/0100371_query.c b/pool/shard004/C/0100371_query.c new file mode 100644 index 0000000000000000000000000000000000000000..5a41b540d1784f3dcd761a7cea28609927e651d2 --- /dev/null +++ b/pool/shard004/C/0100371_query.c @@ -0,0 +1,41 @@ +/* This is a managed file. Do not delete this comment. */ + +#include +uint32_t corto_query_cardinality( + corto_query* this) +{ + if (!strchr(this->select, '*') || strstr(this->select, "//")) { + return -1; + } else { + return 1; + } + +} + +bool corto_query_match( + corto_query* this, + corto_record *record) +{ + ut_assert(record->id != NULL, "no id specified in result"); + ut_assert(record->parent != NULL, "no parent specified in result"); + ut_assert(record->type != NULL, "no type specified in result"); + + const char *result_type = record->type; + const char *query_type = record->type; + if (result_type[0] == '/') result_type ++; + if (query_type[0] == '/') query_type ++; + + if (this->type && this->type[0] && strcmp(result_type, query_type)) { + return false; + } + + if (this->from && this->from[0] && strcmp(this->from, record->parent)) { + return false; + } + + if (this->select && !ut_expr(this->select, record->id)) { + return false; + } + + return true; +} diff --git a/pool/shard004/C/0100387_thread_tryjoin.c b/pool/shard004/C/0100387_thread_tryjoin.c new file mode 100644 index 0000000000000000000000000000000000000000..675e1595528a7504186744f638c94a650cfcf74e --- /dev/null +++ b/pool/shard004/C/0100387_thread_tryjoin.c @@ -0,0 +1,41 @@ +// RUN: %clang_tsan -O1 %s -o %t && %run %t 2>&1 | FileCheck %s +#define _GNU_SOURCE +#include "../test.h" +#include + +int var; + +void *Thread(void *x) { + barrier_wait(&barrier); + var = 1; + return 0; +} + +static void check(int res) { + if (res != EBUSY) { + fprintf(stderr, "Unexpected result of pthread_tryjoin_np: %d\n", res); + exit(1); + } +} + +int main() { + barrier_init(&barrier, 2); + pthread_t t; + pthread_create(&t, 0, Thread, 0); + check(pthread_tryjoin_np(t, 0)); + barrier_wait(&barrier); + for (;;) { + int res = pthread_tryjoin_np(t, 0); + if (!res) + break; + check(res); + pthread_yield(); + } + var = 2; + fprintf(stderr, "PASS\n"); + return 0; +} + +// CHECK-NOT: WARNING: ThreadSanitizer: data race +// CHECK-NOT: WARNING: ThreadSanitizer: thread leak +// CHECK: PASS diff --git a/pool/shard004/C/0100389_vector_tests.c b/pool/shard004/C/0100389_vector_tests.c new file mode 100644 index 0000000000000000000000000000000000000000..afbc77da1e967916f17df43117997e0d486152a5 --- /dev/null +++ b/pool/shard004/C/0100389_vector_tests.c @@ -0,0 +1,109 @@ +/********************************************************************** + * Copyright (c) 2015 Jonas Schnelli * + * Distributed under the MIT software license, see the accompanying * + * file COPYING or http://www.opensource.org/licenses/mit-license.php.* + **********************************************************************/ + +#include +#include +#include +#include + +#include +#include + +struct teststruct { + void* dummy1; + void* dummy2; +}; + +void free_dummy(void* data) +{ + btc_free(((struct teststruct*)data)->dummy1); + btc_free(((struct teststruct*)data)->dummy2); + btc_free((struct teststruct*)data); +} + +void test_vector() +{ + btc_bool res; + char str0[] = "string"; + char str1[] = "rumba"; + + vector* vec = vector_new(10, NULL); + assert(vec != NULL); + assert(vec->len == 0); + assert(vec->alloc > 0); + + res = vector_add(vec, str0); + assert(res == true); + assert(vec->len == 1); + + res = vector_add(vec, str1); + assert(res == true); + assert(vec->len == 2); + + assert(vector_find(vec, str0) == 0); + assert(vector_find(vec, "test") == -1); + assert(vector_find(vec, str1) == 1); + + assert(strcmp(vector_idx(vec, 0), "string") == 0); + assert(strcmp(vector_idx(vec, 1), "rumba") == 0); + + vector_remove_idx(vec, 0); + assert(res == true); + assert(strcmp(vector_idx(vec, 0), "rumba") == 0); + + vector_free(vec, true); + + vec = vector_new(10, free); + res = vector_add(vec, strdup("TEST0")); + assert(res == true); + res = vector_add(vec, strdup("TEST1")); + assert(res == true); + + char* a_str = strdup("TEST2"); + res = vector_add(vec, a_str); + assert(res == true); + assert(vec->len == 3); + res = vector_remove(vec, a_str); + assert(res == true); + assert(vec->len == 2); + vector_free(vec, true); + + + /* test resize */ + vec = vector_new(1, free); + res = vector_resize(vec, 30); + assert(res == true); + res = vector_resize(vec, 30); + assert(res == true); + char str[80]; + int i; + for (i = 0; i < 20; i++) { + sprintf(str, "TEST%d", i); + res = vector_add(vec, strdup(str)); + assert(res == true); + assert(vec->len == (size_t)i + 1); + } + + res = vector_resize(vec, 5); + assert(res == true); + assert(strcmp(vector_idx(vec, 0), "TEST0") == 0); + assert(strcmp(vector_idx(vec, 4), "TEST4") == 0); + assert(vector_idx(vec, 5) == NULL); + + vector_remove_range(vec, 0, 4); + assert(strcmp(vector_idx(vec, 0), "TEST4") == 0); + vector_free(vec, true); + + + /* test custom free callback handler */ + struct teststruct* some_data = btc_calloc(1, sizeof(struct teststruct)); + some_data->dummy1 = btc_calloc(1, 10); + some_data->dummy2 = btc_calloc(1, 10); + + vec = vector_new(1, free_dummy); + vector_add(vec, some_data); + vector_free(vec, true); +} diff --git a/pool/shard004/C/0100390_test_rotate.c b/pool/shard004/C/0100390_test_rotate.c new file mode 100644 index 0000000000000000000000000000000000000000..a09a0ee54d6c86dec901a7e0a60a579cba6dc5fb --- /dev/null +++ b/pool/shard004/C/0100390_test_rotate.c @@ -0,0 +1,99 @@ +#ifdef HAVE_CONFIG_H +# include +#endif + +#include "ephysics_test.h" + +static void +_world_populate(Test_Data *test_data) +{ + EPhysics_Body *box_body1, *box_body2; + Evas_Object *box1, *box2, *sh1, *sh2; + + sh1 = elm_layout_add(test_data->win); + elm_layout_file_set( + sh1, PACKAGE_DATA_DIR "/" EPHYSICS_TEST_THEME ".edj", "shadow-cube"); + evas_object_move(sh1, WIDTH / 6, FLOOR_Y); + evas_object_resize(sh1, 70, 3); + evas_object_show(sh1); + test_data->evas_objs = eina_list_append(test_data->evas_objs, sh1); + + box1 = elm_image_add(test_data->win); + elm_image_file_set( + box1, PACKAGE_DATA_DIR "/" EPHYSICS_TEST_THEME ".edj", "blue-cube"); + evas_object_move(box1, WIDTH / 6, FLOOR_Y - 70); + evas_object_resize(box1, 70, 70); + evas_object_show(box1); + test_data->evas_objs = eina_list_append(test_data->evas_objs, box1); + + box_body1 = ephysics_body_box_add(test_data->world); + ephysics_body_mass_set(box_body1, 0); + ephysics_body_evas_object_set(box_body1, box1, EINA_TRUE); + ephysics_body_event_callback_add(box_body1, EPHYSICS_CALLBACK_BODY_UPDATE, + update_object_cb, sh1); + ephysics_body_restitution_set(box_body1, 0.3); + ephysics_body_friction_set(box_body1, 0.1); + test_data->bodies = eina_list_append(test_data->bodies, box_body1); + + sh2 = elm_layout_add(test_data->win); + elm_layout_file_set( + sh2, PACKAGE_DATA_DIR "/" EPHYSICS_TEST_THEME ".edj", "shadow-cube"); + evas_object_move(sh2, WIDTH / 6 + 60, FLOOR_Y); + evas_object_resize(sh2, 70, 3); + evas_object_show(sh2); + test_data->evas_objs = eina_list_append(test_data->evas_objs, sh2); + + box2 = elm_image_add(test_data->win); + elm_image_file_set( + box2, PACKAGE_DATA_DIR "/" EPHYSICS_TEST_THEME ".edj", "purple-cube"); + evas_object_move(box2, WIDTH / 6 + 60, HEIGHT / 8); + evas_object_resize(box2, 70, 70); + evas_object_show(box2); + test_data->evas_objs = eina_list_append(test_data->evas_objs, box2); + + box_body2 = ephysics_body_box_add(test_data->world); + ephysics_body_evas_object_set(box_body2, box2, EINA_TRUE); + ephysics_body_event_callback_add(box_body2, EPHYSICS_CALLBACK_BODY_UPDATE, + update_object_cb, sh2); + ephysics_body_restitution_set(box_body2, 0.5); + ephysics_body_friction_set(box_body2, 0.1); + test_data->bodies = eina_list_append(test_data->bodies, box_body2); +} + +static void +_restart(void *data, Evas_Object *obj __UNUSED__, const char *emission __UNUSED__, const char *source __UNUSED__) +{ + Test_Data *test_data = data; + + DBG("Restart pressed"); + test_clean(test_data); + _world_populate(test_data); +} + +void +test_rotate(void *data __UNUSED__, Evas_Object *obj __UNUSED__, void *event_info __UNUSED__) +{ + EPhysics_Body *boundary; + EPhysics_World *world; + Test_Data *test_data; + + if (!ephysics_init()) + return; + + test_data = test_data_new(); + test_win_add(test_data, "Rotate", EINA_TRUE); + elm_object_signal_emit(test_data->layout, "borders,show", "ephysics_test"); + elm_layout_signal_callback_add(test_data->layout, "restart", "test-theme", + _restart, test_data); + + world = ephysics_world_new(); + ephysics_world_render_geometry_set(world, 50, 40, -50, + WIDTH - 100, FLOOR_Y - 40, DEPTH); + test_data->world = world; + + boundary = ephysics_body_bottom_boundary_add(test_data->world); + ephysics_body_restitution_set(boundary, 0.65); + ephysics_body_friction_set(boundary, 3); + + _world_populate(test_data); +} diff --git a/pool/shard004/C/0100392_dm-stripe.c b/pool/shard004/C/0100392_dm-stripe.c new file mode 100644 index 0000000000000000000000000000000000000000..51f5e0760012dd76c35d939bb18862a20e2ee435 --- /dev/null +++ b/pool/shard004/C/0100392_dm-stripe.c @@ -0,0 +1,242 @@ +/* + * Copyright (C) 2001-2003 Sistina Software (UK) Limited. + * + * This file is released under the GPL. + */ + +#include "dm.h" + +#include +#include +#include +#include +#include + +#define DM_MSG_PREFIX "striped" + +struct stripe { + struct dm_dev *dev; + sector_t physical_start; +}; + +struct stripe_c { + uint32_t stripes; + + /* The size of this target / num. stripes */ + sector_t stripe_width; + + /* stripe chunk size */ + uint32_t chunk_shift; + sector_t chunk_mask; + + struct stripe stripe[0]; +}; + +static inline struct stripe_c *alloc_context(unsigned int stripes) +{ + size_t len; + + if (array_too_big(sizeof(struct stripe_c), sizeof(struct stripe), + stripes)) + return NULL; + + len = sizeof(struct stripe_c) + (sizeof(struct stripe) * stripes); + + return kmalloc(len, GFP_KERNEL); +} + +/* + * Parse a single pair + */ +static int get_stripe(struct dm_target *ti, struct stripe_c *sc, + unsigned int stripe, char **argv) +{ + unsigned long long start; + + if (sscanf(argv[1], "%llu", &start) != 1) + return -EINVAL; + + if (dm_get_device(ti, argv[0], start, sc->stripe_width, + dm_table_get_mode(ti->table), + &sc->stripe[stripe].dev)) + return -ENXIO; + + sc->stripe[stripe].physical_start = start; + return 0; +} + +/* + * Construct a striped mapping. + * [ ]+ + */ +static int stripe_ctr(struct dm_target *ti, unsigned int argc, char **argv) +{ + struct stripe_c *sc; + sector_t width; + uint32_t stripes; + uint32_t chunk_size; + char *end; + int r; + unsigned int i; + + if (argc < 2) { + ti->error = "Not enough arguments"; + return -EINVAL; + } + + stripes = simple_strtoul(argv[0], &end, 10); + if (*end) { + ti->error = "Invalid stripe count"; + return -EINVAL; + } + + chunk_size = simple_strtoul(argv[1], &end, 10); + if (*end) { + ti->error = "Invalid chunk_size"; + return -EINVAL; + } + + /* + * chunk_size is a power of two + */ + if (!chunk_size || (chunk_size & (chunk_size - 1)) || + (chunk_size < (PAGE_SIZE >> SECTOR_SHIFT))) { + ti->error = "Invalid chunk size"; + return -EINVAL; + } + + if (ti->len & (chunk_size - 1)) { + ti->error = "Target length not divisible by " + "chunk size"; + return -EINVAL; + } + + width = ti->len; + if (sector_div(width, stripes)) { + ti->error = "Target length not divisible by " + "number of stripes"; + return -EINVAL; + } + + /* + * Do we have enough arguments for that many stripes ? + */ + if (argc != (2 + 2 * stripes)) { + ti->error = "Not enough destinations " + "specified"; + return -EINVAL; + } + + sc = alloc_context(stripes); + if (!sc) { + ti->error = "Memory allocation for striped context " + "failed"; + return -ENOMEM; + } + + sc->stripes = stripes; + sc->stripe_width = width; + ti->split_io = chunk_size; + + sc->chunk_mask = ((sector_t) chunk_size) - 1; + for (sc->chunk_shift = 0; chunk_size; sc->chunk_shift++) + chunk_size >>= 1; + sc->chunk_shift--; + + /* + * Get the stripe destinations. + */ + for (i = 0; i < stripes; i++) { + argv += 2; + + r = get_stripe(ti, sc, i, argv); + if (r < 0) { + ti->error = "Couldn't parse stripe destination"; + while (i--) + dm_put_device(ti, sc->stripe[i].dev); + kfree(sc); + return r; + } + } + + ti->private = sc; + return 0; +} + +static void stripe_dtr(struct dm_target *ti) +{ + unsigned int i; + struct stripe_c *sc = (struct stripe_c *) ti->private; + + for (i = 0; i < sc->stripes; i++) + dm_put_device(ti, sc->stripe[i].dev); + + kfree(sc); +} + +static int stripe_map(struct dm_target *ti, struct bio *bio, + union map_info *map_context) +{ + struct stripe_c *sc = (struct stripe_c *) ti->private; + + sector_t offset = bio->bi_sector - ti->begin; + sector_t chunk = offset >> sc->chunk_shift; + uint32_t stripe = sector_div(chunk, sc->stripes); + + bio->bi_bdev = sc->stripe[stripe].dev->bdev; + bio->bi_sector = sc->stripe[stripe].physical_start + + (chunk << sc->chunk_shift) + (offset & sc->chunk_mask); + return DM_MAPIO_REMAPPED; +} + +static int stripe_status(struct dm_target *ti, + status_type_t type, char *result, unsigned int maxlen) +{ + struct stripe_c *sc = (struct stripe_c *) ti->private; + unsigned int sz = 0; + unsigned int i; + + switch (type) { + case STATUSTYPE_INFO: + result[0] = '\0'; + break; + + case STATUSTYPE_TABLE: + DMEMIT("%d %llu", sc->stripes, + (unsigned long long)sc->chunk_mask + 1); + for (i = 0; i < sc->stripes; i++) + DMEMIT(" %s %llu", sc->stripe[i].dev->name, + (unsigned long long)sc->stripe[i].physical_start); + break; + } + return 0; +} + +static struct target_type stripe_target = { + .name = "striped", + .version= {1, 0, 2}, + .module = THIS_MODULE, + .ctr = stripe_ctr, + .dtr = stripe_dtr, + .map = stripe_map, + .status = stripe_status, +}; + +int __init dm_stripe_init(void) +{ + int r; + + r = dm_register_target(&stripe_target); + if (r < 0) + DMWARN("target registration failed"); + + return r; +} + +void dm_stripe_exit(void) +{ + if (dm_unregister_target(&stripe_target)) + DMWARN("target unregistration failed"); + + return; +} diff --git a/pool/shard004/C/0100394_udevadm.c b/pool/shard004/C/0100394_udevadm.c new file mode 100644 index 0000000000000000000000000000000000000000..4ecd3e82f9ebb9bff4ce9a2d6ddad1059b1be730 --- /dev/null +++ b/pool/shard004/C/0100394_udevadm.c @@ -0,0 +1,169 @@ +/* + * Copyright (C) 2007 Kay Sievers + * + * 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 +#include +#include +#include +#include +#include +#include + +#include "udev.h" + +static int verbose; + +#ifdef USE_LOG +void log_message(int priority, const char *format, ...) +{ + va_list args; + + if (priority > udev_log_priority) + return; + + va_start(args, format); + if (verbose) { + vprintf(format, args); + printf("\n"); + } else + vsyslog(priority, format, args); + va_end(args); +} +#endif + +struct command { + const char *name; + int (*cmd)(int argc, char *argv[], char *envp[]); + const char *help; + int verbose; +}; + +static const struct command cmds[]; + +static int version(int argc, char *argv[], char *envp[]) +{ + printf("%s\n", UDEV_VERSION); + return 0; +} + +static int help(int argc, char *argv[], char *envp[]) +{ + const struct command *cmd; + + printf("Usage: udevadm COMMAND [OPTIONS]\n"); + for (cmd = cmds; cmd->name != NULL; cmd++) + printf(" %-12s %s\n", cmd->name, cmd->help); + printf("\n"); + return 0; +} + +static const struct command cmds[] = { + { + .name = "info", + .cmd = udevinfo, + .help = "query sysfs or the udev database", + }, + { + .name = "trigger", + .cmd = udevtrigger, + .help = "request events from the kernel", + }, + { + .name = "settle", + .cmd = udevsettle, "", + .help = "wait for the event queue to finish", + }, + { + .name = "control", + .cmd = udevcontrol, + .help = "control the udev daemon", + }, + { + .name = "monitor", + .cmd = udevmonitor, + .help = "listen to kernel and udev events", + }, + { + .name = "test", + .cmd = udevtest, + .help = "simulation run", + .verbose = 1, + }, + { + .name = "version", + .cmd = version, + .help = "print the version number", + }, + { + .name = "help", + .cmd = help, + .help = "print this help text", + }, + {} +}; + +int main(int argc, char *argv[], char *envp[]) +{ + const char *command; + const char *pos; + const struct command *cmd; + int rc; + + /* get binary or symlink name */ + pos = strrchr(argv[0], '/'); + if (pos != NULL) + command = &pos[1]; + else + command = argv[0]; + + /* the trailing part of the binary or symlink name is the command */ + if (strncmp(command, "udev", 4) == 0) + command = &command[4]; + + if (command == NULL || command[0] == '\0') + goto err_unknown; + + /* udevadm itself needs to strip its name from the passed options */ + if (strcmp(command, "adm") == 0) { + command = argv[1]; + argv++; + argc--; + } + + if (command == NULL) + goto err_unknown; + + /* allow command to be specified as an option */ + if (strncmp(command, "--", 2) == 0) + command += 2; + + /* find and execute command */ + for (cmd = cmds; cmd->name != NULL; cmd++) { + if (strcmp(cmd->name, command) == 0) { + verbose = cmd->verbose; + rc = cmd->cmd(argc, argv, envp); + goto out; + } + } + +err_unknown: + fprintf(stderr, "unknown command, try help\n\n"); + rc = 2; +out: + return rc; +} diff --git a/pool/shard004/C/0100400_sock_example.c b/pool/shard004/C/0100400_sock_example.c new file mode 100644 index 0000000000000000000000000000000000000000..a0ce251c53900e08617740633cc726b045c8fcc1 --- /dev/null +++ b/pool/shard004/C/0100400_sock_example.c @@ -0,0 +1,101 @@ +/* eBPF example program: + * - creates arraymap in kernel with key 4 bytes and value 8 bytes + * + * - loads eBPF program: + * r0 = skb->data[ETH_HLEN + offsetof(struct iphdr, protocol)]; + * *(u32*)(fp - 4) = r0; + * // assuming packet is IPv4, lookup ip->proto in a map + * value = bpf_map_lookup_elem(map_fd, fp - 4); + * if (value) + * (*(u64*)value) += 1; + * + * - attaches this program to eth0 raw socket + * + * - every second user space reads map[tcp], map[udp], map[icmp] to see + * how many packets of given protocol were seen on eth0 + */ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "libbpf.h" + +static int test_sock(void) +{ + int sock = -1, map_fd, prog_fd, i, key; + long long value = 0, tcp_cnt, udp_cnt, icmp_cnt; + + map_fd = bpf_create_map(BPF_MAP_TYPE_ARRAY, sizeof(key), sizeof(value), + 256); + if (map_fd < 0) { + printf("failed to create map '%s'\n", strerror(errno)); + goto cleanup; + } + + struct bpf_insn prog[] = { + BPF_MOV64_REG(BPF_REG_6, BPF_REG_1), + BPF_LD_ABS(BPF_B, ETH_HLEN + offsetof(struct iphdr, protocol) /* R0 = ip->proto */), + BPF_STX_MEM(BPF_W, BPF_REG_10, BPF_REG_0, -4), /* *(u32 *)(fp - 4) = r0 */ + BPF_MOV64_REG(BPF_REG_2, BPF_REG_10), + BPF_ALU64_IMM(BPF_ADD, BPF_REG_2, -4), /* r2 = fp - 4 */ + BPF_LD_MAP_FD(BPF_REG_1, map_fd), + BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_map_lookup_elem), + BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, 0, 2), + BPF_MOV64_IMM(BPF_REG_1, 1), /* r1 = 1 */ + BPF_RAW_INSN(BPF_STX | BPF_XADD | BPF_DW, BPF_REG_0, BPF_REG_1, 0, 0), /* xadd r0 += r1 */ + BPF_MOV64_IMM(BPF_REG_0, 0), /* r0 = 0 */ + BPF_EXIT_INSN(), + }; + + prog_fd = bpf_prog_load(BPF_PROG_TYPE_SOCKET_FILTER, prog, sizeof(prog), + "GPL", 0); + if (prog_fd < 0) { + printf("failed to load prog '%s'\n", strerror(errno)); + goto cleanup; + } + + sock = open_raw_sock("lo"); + + if (setsockopt(sock, SOL_SOCKET, SO_ATTACH_BPF, &prog_fd, + sizeof(prog_fd)) < 0) { + printf("setsockopt %s\n", strerror(errno)); + goto cleanup; + } + + for (i = 0; i < 10; i++) { + key = IPPROTO_TCP; + assert(bpf_lookup_elem(map_fd, &key, &tcp_cnt) == 0); + + key = IPPROTO_UDP; + assert(bpf_lookup_elem(map_fd, &key, &udp_cnt) == 0); + + key = IPPROTO_ICMP; + assert(bpf_lookup_elem(map_fd, &key, &icmp_cnt) == 0); + + printf("TCP %lld UDP %lld ICMP %lld packets\n", + tcp_cnt, udp_cnt, icmp_cnt); + sleep(1); + } + +cleanup: + /* maps, programs, raw sockets will auto cleanup on process exit */ + return 0; +} + +int main(void) +{ + FILE *f; + + f = popen("ping -c5 localhost", "r"); + (void)f; + + return test_sock(); +} diff --git a/pool/shard004/C/0100403_HPYNOS.c b/pool/shard004/C/0100403_HPYNOS.c new file mode 100644 index 0000000000000000000000000000000000000000..4174300ea14cb13cf4adc9af463b43fdecfa198d --- /dev/null +++ b/pool/shard004/C/0100403_HPYNOS.c @@ -0,0 +1,56 @@ +#include +#include +#include +#include +#include + +#define max(x,y) ((x) > (y) ? (x) : (y)) +#define min(x,y) ((x) < (y) ? (x) : (y)) +#define abs(x) ((x) >= 0 ? (x) : -(x)) +#define sgn(x) ((x) > 0 ? 1 : ((x) < 0 ? -1 : 0)) +int digitSum(int num){ + int sum=0; + int rem; + while(num){ + rem=num%10; + sum+=rem*rem; + num/=10; + } + return sum; + +} +bool arr[1000000]={false}; +int main() +{ + int i,j,c,len,num,temp,t,res,count; + + scanf("%d",&num); + if(num==1) + printf("0\n"); + else{ + count=0; + while(1){ + count++; + temp=digitSum(num); + if(temp==1){ + res=1; + break; + } + + if(arr[temp]){ + res=0; + break; + } + else{ + arr[temp]=true; + num=temp; + } + } + } + + if(res) + printf("%d\n",count ); + else + printf("-1\n"); + return 0; +} diff --git a/pool/shard004/C/0100408_bootmem.c b/pool/shard004/C/0100408_bootmem.c new file mode 100644 index 0000000000000000000000000000000000000000..cdc019ace3fefb54ffaeb22cef8530e6e6291c3b --- /dev/null +++ b/pool/shard004/C/0100408_bootmem.c @@ -0,0 +1,129 @@ +/* linux/arch/arm/plat-s5p/bootmem.c + * + * Copyright (c) 2009 Samsung Electronics Co., Ltd. + * http://www.samsung.com/ + * + * Bootmem helper functions + * + * 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 + +static struct s5p_media_device *media_devs; +static int nr_media_devs; + +static struct s5p_media_device *s5p_get_media_device(int dev_id, int bank) +{ + struct s5p_media_device *mdev = NULL; + int i = 0, found = 0; + + if (dev_id < 0) + return NULL; + + while (!found && (i < nr_media_devs)) { + mdev = &media_devs[i]; + if (mdev->id == dev_id && mdev->bank == bank) + found = 1; + else + i++; + } + + if (!found) + mdev = NULL; + + return mdev; +} + +dma_addr_t s5p_get_media_memory_bank(int dev_id, int bank) +{ + struct s5p_media_device *mdev; + + mdev = s5p_get_media_device(dev_id, bank); + if (!mdev) { + printk(KERN_ERR "invalid media device\n"); + return 0; + } + + if (!mdev->paddr) { + printk(KERN_ERR "no memory for %s\n", mdev->name); + return 0; + } + + return mdev->paddr; +} +EXPORT_SYMBOL(s5p_get_media_memory_bank); + +size_t s5p_get_media_memsize_bank(int dev_id, int bank) +{ + struct s5p_media_device *mdev; + + mdev = s5p_get_media_device(dev_id, bank); + if (!mdev) { + printk(KERN_ERR "invalid media device\n"); + return 0; + } + + return mdev->memsize; +} +EXPORT_SYMBOL(s5p_get_media_memsize_bank); + +void s5p_reserve_bootmem(struct s5p_media_device *mdevs, int nr_mdevs) +{ + struct s5p_media_device *mdev; + int i; + +#ifdef CONFIG_S5PV210_BIGMEM + dma_addr_t mfc_paddr; +#endif + + media_devs = mdevs; + nr_media_devs = nr_mdevs; + + for (i = 0; i < nr_media_devs; i++) { + mdev = &media_devs[i]; + if (mdev->memsize <= 0) + continue; + + if (mdev->paddr) + mdev->paddr = virt_to_phys(__alloc_bootmem( + mdev->memsize, + PAGE_SIZE, + mdev->paddr)); +#ifdef CONFIG_S5PV210_BIGMEM + else if (!strcmp(mdev->name, "jpeg")) + mdev->paddr = mfc_paddr; +#endif + else + mdev->paddr = virt_to_phys(__alloc_bootmem( + mdev->memsize, + PAGE_SIZE, + meminfo.bank[mdev->bank].start)); + +#ifdef CONFIG_S5PV210_BIGMEM + if (!strcmp(mdev->name, "mfc") && mdev->bank == 0) + mfc_paddr = mdev->paddr; +#endif + + printk(KERN_INFO "s5pv210: %lu bytes system memory reserved " + "for %s at 0x%08x\n", (unsigned long) mdev->memsize, + mdev->name, mdev->paddr); + } +} + +/* FIXME: temporary implementation to avoid compile error */ +int dma_needs_bounce(struct device *dev, dma_addr_t addr, size_t size) +{ + return 0; +} + + diff --git a/pool/shard004/C/0100413_test_kasiski.c b/pool/shard004/C/0100413_test_kasiski.c new file mode 100644 index 0000000000000000000000000000000000000000..ab4b69bce0f0942f20d18a2809074cc22ddc6daa --- /dev/null +++ b/pool/shard004/C/0100413_test_kasiski.c @@ -0,0 +1,103 @@ +#include +#include +#include +#include + +#define TAILLE_MAX 10000 +#define NB_POSSIBILITE_MAX 10000 + +char message[TAILLE_MAX]; +int tailleMessage; + +int nbPossibilite[NB_POSSIBILITE_MAX]; +int possibiliteMax; + +int chercherOccurrence(char chaine[], int taille, int debut) +{ + int iDebut; + + for(iDebut = debut; iDebut < tailleMessage - taille + 1; ++iDebut) { + int iTab, iChaine; + + iTab = iDebut; + iChaine = 0; + while(iTab < tailleMessage - taille + 1 && + chaine[iChaine] == message[iTab]) { + ++iTab; + ++iChaine; + } + + if(iChaine == taille) + return iDebut; + } + + return -1; +} + +void ajouterTaillePossible(int ecart) +{ + int iDiv; + + for(iDiv = 2; iDiv <= ecart; ++iDiv) { + if(ecart % iDiv == 0) { + ++nbPossibilite[iDiv]; + if(nbPossibilite[iDiv] > nbPossibilite[possibiliteMax]) + possibiliteMax = iDiv; + } + } +} + +void testKasiski(void) +{ + int iTaille, iDebut; + bool trouve; + + iTaille = 3; + trouve = true; + + while(trouve) { + trouve = false; + + for(iDebut = 0; iDebut < tailleMessage - iTaille + 1; ++iDebut) { + char chaine[iTaille + 1]; + int iTab; + int occurrence; + + for(iTab = 0; iTab < iTaille; ++iTab) + chaine[iTab] = message[iDebut + iTab]; + chaine[iTab] = '\0'; + + occurrence = chercherOccurrence(chaine, iTaille, iDebut + iTaille); + if(occurrence != -1) { + int ecart; + + ecart = occurrence - iDebut; + trouve = true; + + //printf("%s %d\n", chaine, ecart); + + ajouterTaillePossible(ecart); + } + } + + ++iTaille; + } +} + +int main(void) +{ + scanf("%s\n", message); + tailleMessage = strlen(message); + + possibiliteMax = 0; + testKasiski(); + + /*int iDiv; + for(iDiv = 0; iDiv < NB_POSSIBILITE_MAX; ++iDiv) + if(nbPossibilite[iDiv] != 0) + printf("%d : %d\n", iDiv, nbPossibilite[iDiv]);*/ + + printf("%d\n", possibiliteMax); + + return 0; +} diff --git a/pool/shard004/C/0100414_nearest_neighbor_graph.c b/pool/shard004/C/0100414_nearest_neighbor_graph.c new file mode 100644 index 0000000000000000000000000000000000000000..02707c3d0a1044fa8b612eacc052c73ea60988ae --- /dev/null +++ b/pool/shard004/C/0100414_nearest_neighbor_graph.c @@ -0,0 +1,56 @@ +/************************************************************************* + * 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 "general.h" +#include "SparseMatrix.h" +#include "nearest_neighbor_graph_ann.h" +#include "nearest_neighbor_graph.h" + +SparseMatrix nearest_neighbor_graph(int nPts, int num_neigbors, int dim, double *x, double eps){ + /* Gives a nearest neighbor graph of a list of dim-dimendional points. The result is a sparse matrix + of nPts x nPts, with num_neigbors entries per row. + + nPts: number of points + num_neigbors: number of neighbors needed + dim: dimension + eps: error tolerance + x: nPts*dim vector. The i-th point is x[i*dim : i*dim + dim - 1] + + */ + int *irn = NULL, *jcn = NULL, nz; + real *val = NULL; + SparseMatrix A; + int k = num_neigbors; + + /* need to *2 as we do two sweeps of neighbors, so could have repeats */ + irn = MALLOC(sizeof(int)*nPts*k*2); + jcn = MALLOC(sizeof(int)*nPts*k*2); + val = MALLOC(sizeof(double)*nPts*k*2); + +#ifdef HAVE_ANN + nearest_neighbor_graph_ann(nPts, dim, num_neigbors, eps, x, &nz, &irn, &jcn, &val); + + A = SparseMatrix_from_coordinate_arrays(nz, nPts, nPts, irn, jcn, (void *) val, MATRIX_TYPE_REAL, sizeof(real)); +#else + A = NULL; +#endif + + FREE(irn); + FREE(jcn); + FREE(val); + + return A; + + +} diff --git a/pool/shard004/C/0100421_BlockDX_i.c b/pool/shard004/C/0100421_BlockDX_i.c new file mode 100644 index 0000000000000000000000000000000000000000..3827b801800da2a87c78b6c0352388d4438b6346 --- /dev/null +++ b/pool/shard004/C/0100421_BlockDX_i.c @@ -0,0 +1,59 @@ +/** +Atomix project, BlockDX_i.c, TODO: insert summary here +Copyright (c) 2015 Stanford University +Released under the Apache License v2.0. See the LICENSE file for details. +Author(s): Manu Bansal +*/ +#include +#include "BlockDX_t.h" + +void BlockDX_i ( + IN EXILIB_tData_1 *bInpData, + OUT Decision_t *bOutDecision, + CF BlockDX_tConf *bInpConf + ) { + + Uint32 nextState; + Uint32 iterCount; + + Uint32 *transitionMap; + transitionMap = bInpConf->transitionMap; + + //int r = _loll(CSL_tscRead()) & 0x00FF; + Uint32 r = bInpData->val[0]; + DEBUG ( + printf("****** r = %d\n", r); + ) + if (r < 85) { + nextState = transitionMap[0]; + iterCount = 1; + } + else if (r < 170) { + nextState = transitionMap[1]; + iterCount = 4; + } + else { + nextState = transitionMap[2]; + iterCount = 4; + } + bOutDecision->nextState = nextState; + bOutDecision->iterCount = iterCount; + + DEBUG( + printf("DX: r=%d, nextState=%d, iterCount=%d\n", r, nextState, iterCount); + ) +} + +void BlockDX_i_conf( + CF BlockDX_tConf *bInpConf, + Uint32 st0, + Uint32 st1, + Uint32 st2 + ) { + Uint32 *transitionMap; + transitionMap = bInpConf->transitionMap; + + transitionMap[0] = st0; + transitionMap[1] = st1; + transitionMap[2] = st2; +} diff --git a/pool/shard004/C/0100423_events.c b/pool/shard004/C/0100423_events.c new file mode 100644 index 0000000000000000000000000000000000000000..2394ef3153f308f8662fe7d013969b5108a64c65 --- /dev/null +++ b/pool/shard004/C/0100423_events.c @@ -0,0 +1,118 @@ +// +// events.c +// YAML Serialization support by Mirek Rusin based on C library LibYAML by Kirill Simonov +// +// Copyright 2010 Mirek Rusin, Released under MIT License +// + +//#import +//#import "YAMLSerialization.h" + +#include +#include +#include "yaml.h" + +#ifdef NDEBUG +#undef NDEBUG +#endif +#include + +#define PRINT_INDENT() for (int i = 0; i < indent; i++) printf(" ") + + +int +main(int argc, char *argv[]) +{ + int number; + + if (argc < 2) { + printf("Usage: %s file1.yaml ...\n", argv[0]); + return 0; + } + + for (number = 1; number < argc; number ++) + { + FILE *file; + yaml_parser_t parser; + yaml_event_t event; + int done = 0; + int count = 0; + int error = 0; + + printf("[%d] Parsing '%s': \n", number, argv[number]); + fflush(stdout); + + file = fopen(argv[number], "rb"); + assert(file); + + assert(yaml_parser_initialize(&parser)); + + yaml_parser_set_input_file(&parser, file); + + int indent = 0; + + while (!done) + { + if (!yaml_parser_parse(&parser, &event)) { + error = 1; + break; + } + + switch (event.type) { + case YAML_NO_EVENT: + break; + case YAML_STREAM_START_EVENT: + break; + case YAML_STREAM_END_EVENT: + break; + case YAML_DOCUMENT_START_EVENT: + printf("%%YAML 1.2\n---\n"); + break; + case YAML_DOCUMENT_END_EVENT: + break; + case YAML_ALIAS_EVENT: + PRINT_INDENT(); + printf("*%s\n", event.data.alias.anchor); + break; + case YAML_SCALAR_EVENT: + PRINT_INDENT(); + if (event.data.scalar.anchor) + printf("&%s ", event.data.scalar.anchor); + printf("!!str \"%s\"\n", event.data.scalar.value); + break; + case YAML_SEQUENCE_START_EVENT: + printf("seq,s\t\n"); + indent++; + break; + case YAML_SEQUENCE_END_EVENT: + indent--; + printf("seq,e\t\n"); + break; + case YAML_MAPPING_START_EVENT: + printf("!!map {\n"); + indent++; + break; + case YAML_MAPPING_END_EVENT: + indent--; + printf("}\n"); + break; + default: + printf("unkn\t\n"); + break; + } + done = (event.type == YAML_STREAM_END_EVENT); + + yaml_event_delete(&event); + + count ++; + } + + yaml_parser_delete(&parser); + + assert(!fclose(file)); + + printf("%s (%d events)\n", (error ? "FAILURE" : "SUCCESS"), count); + } + + return 0; +} diff --git a/pool/shard004/C/0100437_clock-debug.c b/pool/shard004/C/0100437_clock-debug.c new file mode 100644 index 0000000000000000000000000000000000000000..0571a8b7bd92369b1b3b9713d20de39711292937 --- /dev/null +++ b/pool/shard004/C/0100437_clock-debug.c @@ -0,0 +1,307 @@ +/* + * Copyright (C) 2007 Google, Inc. + * Copyright (c) 2007-2012, Code Aurora Forum. All rights reserved. + * + * 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 "clock.h" + +#ifdef CONFIG_MSM_SM_EVENT +#include +#include +#endif +static int clock_debug_rate_set(void *data, u64 val) +{ + struct clk *clock = data; + int ret; + + /* Only increases to max rate will succeed, but that's actually good + * for debugging purposes so we don't check for error. */ + if (clock->flags & CLKFLAG_MAX) + clk_set_max_rate(clock, val); + ret = clk_set_rate(clock, val); + if (ret) + pr_err("clk_set_rate failed (%d)\n", ret); + + return ret; +} + +int clock_debug_rate_get(void *data, u64 *val) +{ + struct clk *clock = data; + *val = clk_get_rate(clock); + return 0; +} + +DEFINE_SIMPLE_ATTRIBUTE(clock_rate_fops, clock_debug_rate_get, + clock_debug_rate_set, "%llu\n"); + +static struct clk *measure; + +static int clock_debug_measure_get(void *data, u64 *val) +{ + struct clk *clock = data; + int ret, is_hw_gated; + + /* Check to see if the clock is in hardware gating mode */ + if (clock->flags & CLKFLAG_HWCG) + is_hw_gated = clock->ops->in_hwcg_mode(clock); + else + is_hw_gated = 0; + + ret = clk_set_parent(measure, clock); + if (!ret) { + /* + * Disable hw gating to get accurate rate measurements. Only do + * this if the clock is explictly enabled by software. This + * allows us to detect errors where clocks are on even though + * software is not requesting them to be on due to broken + * hardware gating signals. + */ + if (is_hw_gated && clock->count) + clock->ops->disable_hwcg(clock); + *val = clk_get_rate(measure); + /* Reenable hwgating if it was disabled */ + if (is_hw_gated && clock->count) + clock->ops->enable_hwcg(clock); + } + + return ret; +} + +DEFINE_SIMPLE_ATTRIBUTE(clock_measure_fops, clock_debug_measure_get, + NULL, "%lld\n"); + +static int clock_debug_enable_set(void *data, u64 val) +{ + struct clk *clock = data; + int rc = 0; + + if (val) + rc = clk_prepare_enable(clock); + else + clk_disable_unprepare(clock); + + return rc; +} + +static int clock_debug_enable_get(void *data, u64 *val) +{ + struct clk *clock = data; + int enabled; + + if (clock->ops->is_enabled) + enabled = clock->ops->is_enabled(clock); + else + enabled = !!(clock->count); + + *val = enabled; + return 0; +} + +DEFINE_SIMPLE_ATTRIBUTE(clock_enable_fops, clock_debug_enable_get, + clock_debug_enable_set, "%lld\n"); + +static int clock_debug_local_get(void *data, u64 *val) +{ + struct clk *clock = data; + + if (!clock->ops->is_local) + *val = true; + else + *val = clock->ops->is_local(clock); + + return 0; +} + +DEFINE_SIMPLE_ATTRIBUTE(clock_local_fops, clock_debug_local_get, + NULL, "%llu\n"); + +static int clock_debug_hwcg_get(void *data, u64 *val) +{ + struct clk *clock = data; + *val = !!(clock->flags & CLKFLAG_HWCG); + return 0; +} + +DEFINE_SIMPLE_ATTRIBUTE(clock_hwcg_fops, clock_debug_hwcg_get, + NULL, "%llu\n"); + +static struct dentry *debugfs_base; +static u32 debug_suspend; +static struct clk_lookup *msm_clocks; +static size_t num_msm_clocks; + +int __init clock_debug_init(struct clock_init_data *data) +{ + debugfs_base = debugfs_create_dir("clk", NULL); + if (!debugfs_base) + return -ENOMEM; + if (!debugfs_create_u32("debug_suspend", S_IRUGO | S_IWUSR, + debugfs_base, &debug_suspend)) { + debugfs_remove_recursive(debugfs_base); + return -ENOMEM; + } + msm_clocks = data->table; + num_msm_clocks = data->size; + + measure = clk_get_sys("debug", "measure"); + if (IS_ERR(measure)) + measure = NULL; + + return 0; +} + + +static int clock_debug_print_clock(struct clk *c) +{ + size_t ln = 0; + char s[128]; + + if (!c || !c->count) + return 0; + + ln += snprintf(s, sizeof(s), "\t%s", c->dbg_name); + while (ln < sizeof(s) && (c = clk_get_parent(c))) + ln += snprintf(s + ln, sizeof(s) - ln, " -> %s", c->dbg_name); + pr_info("%s\n", s); + return 1; +} + +void clock_debug_print_enabled(void) +{ + unsigned i; + int cnt = 0; + +#ifdef CONFIG_MSM_SM_EVENT + struct clk *clk; + for (i = 0; i < num_msm_clocks; i++) { + clk = msm_clocks[i].clk; + + if (clk && clk->ops->is_enabled(clk)) { + // pr_info("\t%s\n", clk->dbg_name); + sm_add_event(SM_CLOCK_EVENT | SM_CLK_EVENT_SET_ENABLE, 0, 0, (void *)clk->dbg_name, strlen(clk->dbg_name)+1); + cnt++; + } + } + +#endif + + if (likely(!debug_suspend)) + return; + + pr_info("Enabled clocks:\n"); + for (i = 0; i < num_msm_clocks; i++) + cnt += clock_debug_print_clock(msm_clocks[i].clk); + + if (cnt) + pr_info("Enabled clock count: %d\n", cnt); + else + pr_info("No clocks enabled.\n"); + +} + +static int list_rates_show(struct seq_file *m, void *unused) +{ + struct clk *clock = m->private; + int rate, level, fmax = 0, i = 0; + + /* Find max frequency supported within voltage constraints. */ + if (!clock->vdd_class) { + fmax = INT_MAX; + } else { + for (level = 0; level < ARRAY_SIZE(clock->fmax); level++) + if (clock->fmax[level]) + fmax = clock->fmax[level]; + } + + /* + * List supported frequencies <= fmax. Higher frequencies may appear in + * the frequency table, but are not valid and should not be listed. + */ + while ((rate = clock->ops->list_rate(clock, i++)) >= 0) { + if (rate <= fmax) + seq_printf(m, "%u\n", rate); + } + + return 0; +} + +static int list_rates_open(struct inode *inode, struct file *file) +{ + return single_open(file, list_rates_show, inode->i_private); +} + +static const struct file_operations list_rates_fops = { + .open = list_rates_open, + .read = seq_read, + .llseek = seq_lseek, + .release = seq_release, +}; + +int __init clock_debug_add(struct clk *clock) +{ + char temp[50], *ptr; + struct dentry *clk_dir; + + if (!debugfs_base) + return -ENOMEM; + + strlcpy(temp, clock->dbg_name, ARRAY_SIZE(temp)); + for (ptr = temp; *ptr; ptr++) + *ptr = tolower(*ptr); + + clk_dir = debugfs_create_dir(temp, debugfs_base); + if (!clk_dir) + return -ENOMEM; + + if (!debugfs_create_file("rate", S_IRUGO | S_IWUSR, clk_dir, + clock, &clock_rate_fops)) + goto error; + + if (!debugfs_create_file("enable", S_IRUGO | S_IWUSR, clk_dir, + clock, &clock_enable_fops)) + goto error; + + if (!debugfs_create_file("is_local", S_IRUGO, clk_dir, clock, + &clock_local_fops)) + goto error; + + if (!debugfs_create_file("has_hw_gating", S_IRUGO, clk_dir, clock, + &clock_hwcg_fops)) + goto error; + + if (measure && + !clk_set_parent(measure, clock) && + !debugfs_create_file("measure", S_IRUGO, clk_dir, clock, + &clock_measure_fops)) + goto error; + + if (clock->ops->list_rate) + if (!debugfs_create_file("list_rates", + S_IRUGO, clk_dir, clock, &list_rates_fops)) + goto error; + + return 0; +error: + debugfs_remove_recursive(clk_dir); + return -ENOMEM; +} diff --git a/pool/shard004/C/0100440_OLED_DC.c b/pool/shard004/C/0100440_OLED_DC.c new file mode 100644 index 0000000000000000000000000000000000000000..b01bbbb6dfb55edb56226ee1f2fd38537df58308 --- /dev/null +++ b/pool/shard004/C/0100440_OLED_DC.c @@ -0,0 +1,268 @@ +/* ################################################################### +** This component module is generated by Processor Expert. Do not modify it. +** Filename : OLED_DC.c +** Project : Flask +** Processor : MK22FN256VLH12 +** Component : BitIO_LDD +** Version : Component 01.033, Driver 01.03, CPU db: 3.00.000 +** Repository : Kinetis +** Compiler : GNU C Compiler +** Date/Time : 2017-11-17, 01:01, # CodeGen: 2 +** Abstract : +** The HAL BitIO component provides a low level API for unified +** access to general purpose digital input/output pins across +** various device designs. +** +** RTOS drivers using HAL BitIO API are simpler and more +** portable to various microprocessors. +** Settings : +** Component name : OLED_DC +** Pin for I/O : CMP0_IN1/PTC7/SPI0_SIN/USB_SOF_OUT/I2S0_RX_FS +** Direction : Output +** Initialization : +** Init. direction : Output +** Init. value : 0 +** Auto initialization : yes +** Safe mode : no +** Contents : +** Init - LDD_TDeviceData* OLED_DC_Init(LDD_TUserData *UserDataPtr); +** GetVal - bool OLED_DC_GetVal(LDD_TDeviceData *DeviceDataPtr); +** PutVal - void OLED_DC_PutVal(LDD_TDeviceData *DeviceDataPtr, bool Val); +** ClrVal - void OLED_DC_ClrVal(LDD_TDeviceData *DeviceDataPtr); +** SetVal - void OLED_DC_SetVal(LDD_TDeviceData *DeviceDataPtr); +** +** Copyright : 1997 - 2015 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. +** +** http: www.freescale.com +** mail: support@freescale.com +** ###################################################################*/ +/*! +** @file OLED_DC.c +** @version 01.03 +** @brief +** The HAL BitIO component provides a low level API for unified +** access to general purpose digital input/output pins across +** various device designs. +** +** RTOS drivers using HAL BitIO API are simpler and more +** portable to various microprocessors. +*/ +/*! +** @addtogroup OLED_DC_module OLED_DC module documentation +** @{ +*/ + +/* MODULE OLED_DC. */ + +/* {Default RTOS Adapter} No RTOS includes */ +#include "OLED_DC.h" + +#ifdef __cplusplus +extern "C" { +#endif + +typedef struct { + LDD_TUserData *UserDataPtr; /* Pointer to user data */ +} OLED_DC_TDeviceData; /* Device data structure type */ + +typedef OLED_DC_TDeviceData *OLED_DC_TDeviceDataPtr ; /* Pointer to the device data structure. */ + +/* {Default RTOS Adapter} Static object used for simulation of dynamic driver memory allocation */ +static OLED_DC_TDeviceData DeviceDataPrv__DEFAULT_RTOS_ALLOC; +/* +** =================================================================== +** Method : OLED_DC_Init (component BitIO_LDD) +*/ +/*! +** @brief +** Initializes the device. Allocates memory for the device data +** structure, allocates interrupt vectors and sets interrupt +** priority, sets pin routing, sets timing, etc. If the "Enable +** in init. code" is set to "yes" value then the device is also +** enabled(see the description of the Enable() method). In this +** case the Enable() method is not necessary and needn't to be +** generated. +** @param +** UserDataPtr - Pointer to the user or +** RTOS specific data. This pointer will be +** passed as an event or callback parameter. +** @return +** - Pointer to the dynamically allocated private +** structure or NULL if there was an error. +*/ +/* ===================================================================*/ +LDD_TDeviceData* OLED_DC_Init(LDD_TUserData *UserDataPtr) +{ + /* Allocate device structure */ + OLED_DC_TDeviceDataPtr DeviceDataPrv; + + /* {Default RTOS Adapter} Driver memory allocation: Dynamic allocation is simulated by a pointer to the static object */ + DeviceDataPrv = &DeviceDataPrv__DEFAULT_RTOS_ALLOC; + DeviceDataPrv->UserDataPtr = UserDataPtr; /* Store the RTOS device structure */ + /* Enable device clock gate */ + /* SIM_SCGC5: PORTC=1 */ + SIM_SCGC5 |= SIM_SCGC5_PORTC_MASK; + /* Configure pin as output */ + /* GPIOC_PDDR: PDD|=0x80 */ + GPIOC_PDDR |= GPIO_PDDR_PDD(0x80); + /* Set initialization value */ + /* GPIOC_PDOR: PDO&=~0x80 */ + GPIOC_PDOR &= (uint32_t)~(uint32_t)(GPIO_PDOR_PDO(0x80)); + /* Initialization of pin routing */ + /* PORTC_PCR7: ISF=0,MUX=1 */ + PORTC_PCR7 = (uint32_t)((PORTC_PCR7 & (uint32_t)~(uint32_t)( + PORT_PCR_ISF_MASK | + PORT_PCR_MUX(0x06) + )) | (uint32_t)( + PORT_PCR_MUX(0x01) + )); + /* Registration of the device structure */ + PE_LDD_RegisterDeviceStructure(PE_LDD_COMPONENT_OLED_DC_ID,DeviceDataPrv); + return ((LDD_TDeviceData *)DeviceDataPrv); +} +/* +** =================================================================== +** Method : OLED_DC_GetVal (component BitIO_LDD) +*/ +/*! +** @brief +** Returns the input/output value. If the direction is [input] +** then the input value of the pin is read and returned. If the +** direction is [output] then the last written value is read +** and returned (see property for limitations). +** This method cannot be disabled if direction is [input]. +** @param +** DeviceDataPtr - Device data structure +** pointer returned by method. +** @return +** - Input or output value. Possible values: +** - logical "0" (Low level) +** - logical "1" (High level) +*/ +/* ===================================================================*/ +bool OLED_DC_GetVal(LDD_TDeviceData *DeviceDataPtr) +{ + uint32_t PortData; /* Port data masked according to the bit used */ + + (void)DeviceDataPtr; /* Parameter is not used, suppress unused argument warning */ + PortData = GPIO_PDD_GetPortDataOutput(OLED_DC_MODULE_BASE_ADDRESS) & OLED_DC_PORT_MASK; + return (PortData != 0U) ? (bool)TRUE : (bool)FALSE; +} + +/* +** =================================================================== +** Method : OLED_DC_PutVal (component BitIO_LDD) +*/ +/*! +** @brief +** The specified output value is set. If the direction is +** input, the component saves the value to a memory or a +** register and this value will be written to the pin after +** switching to the output mode (using SetDir(TRUE); +** see Safe mode +** property for limitations). If the direction is output, +** it writes the value to the pin. (Method is available only if +** the direction = output or +** input/output). +** @param +** DeviceDataPtr - Device data structure +** pointer returned by method. +** @param +** Val - Output value. Possible values: +** - logical "0" (Low level) +** - logical "1" (High level) +*/ +/* ===================================================================*/ +void OLED_DC_PutVal(LDD_TDeviceData *DeviceDataPtr, bool Val) +{ + (void)DeviceDataPtr; /* Parameter is not used, suppress unused argument warning */ + if (Val) { + GPIO_PDD_SetPortDataOutputMask(OLED_DC_MODULE_BASE_ADDRESS, OLED_DC_PORT_MASK); + } else { /* !Val */ + GPIO_PDD_ClearPortDataOutputMask(OLED_DC_MODULE_BASE_ADDRESS, OLED_DC_PORT_MASK); + } /* !Val */ +} + +/* +** =================================================================== +** Method : OLED_DC_ClrVal (component BitIO_LDD) +*/ +/*! +** @brief +** Clears (set to zero) the output value. It is equivalent to +** the [PutVal(FALSE)]. This method is available only if the +** direction = _[output]_ or _[input/output]_. +** @param +** DeviceDataPtr - Pointer to device data +** structure returned by method. +*/ +/* ===================================================================*/ +void OLED_DC_ClrVal(LDD_TDeviceData *DeviceDataPtr) +{ + (void)DeviceDataPtr; /* Parameter is not used, suppress unused argument warning */ + GPIO_PDD_ClearPortDataOutputMask(OLED_DC_MODULE_BASE_ADDRESS, OLED_DC_PORT_MASK); +} + +/* +** =================================================================== +** Method : OLED_DC_SetVal (component BitIO_LDD) +*/ +/*! +** @brief +** Sets (to one) the output value. It is equivalent to the +** [PutVal(TRUE)]. This method is available only if the +** direction = _[output]_ or _[input/output]_. +** @param +** DeviceDataPtr - Pointer to device data +** structure returned by method. +*/ +/* ===================================================================*/ +void OLED_DC_SetVal(LDD_TDeviceData *DeviceDataPtr) +{ + (void)DeviceDataPtr; /* Parameter is not used, suppress unused argument warning */ + GPIO_PDD_SetPortDataOutputMask(OLED_DC_MODULE_BASE_ADDRESS, OLED_DC_PORT_MASK); +} + +/* END OLED_DC. */ + +#ifdef __cplusplus +} /* extern "C" */ +#endif + +/*! +** @} +*/ +/* +** ################################################################### +** +** This file was created by Processor Expert 10.5 [05.21] +** for the Freescale Kinetis series of microcontrollers. +** +** ################################################################### +*/ diff --git a/pool/shard004/C/0100451_dlclose.c b/pool/shard004/C/0100451_dlclose.c new file mode 100644 index 0000000000000000000000000000000000000000..c672d9eb5d6d4cc9b7f62bf597bd4bda9c88cebb --- /dev/null +++ b/pool/shard004/C/0100451_dlclose.c @@ -0,0 +1,44 @@ +#include + +#include "_dl_int.h" + +static void dec_referenced_libs(struct _dl_handle*dh) { + Elf_Dyn* dyn_tab=dh->dynamic; + int i; + for(i=0;dyn_tab[i].d_tag;i++) { + if (dyn_tab[i].d_tag==DT_NEEDED) { + char *lib_name=dh->dyn_str_tab+dyn_tab[i].d_un.d_val; +#ifdef DEBUG + pf(__FUNCTION__); pf(": lib: "); pf(lib_name); pf("\n"); +#endif + dlclose(_dl_find_lib(lib_name)); + } + } +} + +int dlclose(void*handle) { + _dl_error_location="dlclose"; + if (handle) { + struct _dl_handle*dh=handle; + if (--(dh->lnk_count)) return 0; /* not yet unreferenced */ + +#ifdef DEBUG + pf(__FUNCTION__); pf(": "); pf(dh->name); pf("\n"); +#endif + if (dh->fini) dh->fini(); + dec_referenced_libs(dh); +#ifdef __DIET_LD_SO__ + if (_dl_sys_munmap(dh->mem_base,dh->mem_size)<0) return -1; +#else + if (munmap(dh->mem_base,dh->mem_size)==-1) return -1; +#endif + _dl_free_handle(handle); +#ifdef WANT_LD_SO_GDB_SUPPORT + _r_debug.r_state=RT_DELETE; + _dl_debug_state(); + _r_debug.r_state=RT_CONSISTENT; + _dl_debug_state(); +#endif + } + return 0; +} diff --git a/pool/shard004/C/0100453_t-genkey.c b/pool/shard004/C/0100453_t-genkey.c new file mode 100644 index 0000000000000000000000000000000000000000..e5bbf9cb3d8f276076694d8ab752f11164f4ecc5 --- /dev/null +++ b/pool/shard004/C/0100453_t-genkey.c @@ -0,0 +1,158 @@ +/* t-genkey.c - Regression test. + * Copyright (C) 2000 Werner Koch (dd9jn) + * Copyright (C) 2001, 2003, 2004 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 + */ + +/* We need to include config.h so that we know whether we are building + with large file system (LFS) support. */ +#ifdef HAVE_CONFIG_H +#include +#endif + +#include +#include +#include +#include + +#include +#include "t-support.h" + + +/* True if progress function printed something on the screen. */ +static int progress_called; + +static void +progress (void *self, const char *what, int type, int current, int total) +{ + (void)self; + + if (!strcmp (what, "primegen") && !current && !total + && (type == '.' || type == '+' || type == '!' + || type == '^' || type == '<' || type == '>')) + { + printf ("%c", type); + fflush (stdout); + progress_called = 1; + } + else + { + fprintf (stderr, "unknown progress `%s' %d %d %d\n", what, type, + current, total); + exit (1); + } +} + + +static void +check_result (gpgme_genkey_result_t result) +{ + if (!result) + { + fprintf (stderr, "%s:%d: gpgme_op_genkey_result returns NULL\n", + __FILE__, __LINE__); + exit (1); + } + if (progress_called) + printf ("\n"); + + printf ("Generated key: %s (%s)\n", result->fpr ? result->fpr : "none", + result->primary ? (result->sub ? "primary, sub" : "primary") + : (result->sub ? "sub" : "none")); + + if (result->fpr) + { + fprintf (stderr, "%s:%d: generated key has (unexpectedly) a fingerprint\n", + __FILE__, __LINE__); + exit (1); + } + if (!result->primary) + { + fprintf (stderr, "%s:%d: primary key was not generated\n", + __FILE__, __LINE__); + exit (1); + } + if (result->sub) + { + fprintf (stderr, "%s:%d: sub key was (unexpectedly) generated\n", + __FILE__, __LINE__); + exit (1); + } +} + +static const char *parms[] = { + "\n" + "Key-Type: RSA\n" + "Key-Length: 1024\n" + "Name-DN: C=de,O=g10 code,OU=Testlab,CN=Joe 2 Tester\n" + "Name-Email: joe@foo.bar\n" + "\n", + "\n" + "Key-Type: ECC\n" + "Key-Curve: NIST P-256\n" + "Name-DN: C=de,O=g10 code,OU=Testlab,CN=Joe 2 Tester\n" + "Name-Email: joe@foo.bar\n" + "\n", + "\n" + "Key-Type: ECC\n" + "Key-Curve: Ed25519\n" + "Name-DN: C=de,O=g10 code,OU=Testlab,CN=Joe 2 Tester\n" + "Name-Email: joe@foo.bar\n" + "\n", +}; + +int +main (void) +{ + gpgme_ctx_t ctx; + gpgme_error_t err; + gpgme_genkey_result_t result; + int i; + + init_gpgme (GPGME_PROTOCOL_CMS); + + err = gpgme_new (&ctx); + fail_if_err (err); + + gpgme_set_protocol (ctx, GPGME_PROTOCOL_CMS); + gpgme_set_armor (ctx, 1); + + gpgme_set_progress_cb (ctx, progress, NULL); + + for (i = 0; i < DIM(parms); i++) + { + gpgme_data_t certreq; + + progress_called = 0; + err = gpgme_data_new (&certreq); + fail_if_err (err); + + err = gpgme_op_genkey (ctx, parms[i], certreq, NULL); + fail_if_err (err); + + result = gpgme_op_genkey_result (ctx); + check_result (result); + + print_data (certreq); + gpgme_data_release (certreq); + } + + gpgme_release (ctx); + + return 0; +} diff --git a/pool/shard004/C/0100456_tpipe.c b/pool/shard004/C/0100456_tpipe.c new file mode 100644 index 0000000000000000000000000000000000000000..5e88dd14b8eea734bb0f3fcf74c618e0f0f70741 --- /dev/null +++ b/pool/shard004/C/0100456_tpipe.c @@ -0,0 +1,56 @@ +#include +#include +#include +#include + +int main(int argc, char **argv) +{ + int pipefd[2]; + pid_t pid; + int ret; + char buf[1]; + + if (argc != 2 || argv[1] == NULL) { + errno = EINVAL; + perror("one arg string is needed"); + return -1; + } + + ret = pipe(pipefd); + if (ret == -1) { + perror("pipe"); + return -1; + } + + pid = fork(); + if (pid == -1) { + perror("fork"); + return -1; + } + + if (pid == 0) { /* child */ + close(pipefd[1]); + printf("child start\n"); + while (read(pipefd[0], buf, 1) > 0) { + ret = write(STDOUT_FILENO, buf, 1); + if (ret == -1) { + perror("write error in child"); + return -1; + } + } + close(pipefd[0]); + printf("\nchild end\n"); + return 0; // without this return, parent write get badfd error + } + + close(pipefd[0]); + ret = write(pipefd[1], argv[1], strlen(argv[1])); + if (ret == -1) { + perror("write error in parent"); + return -1; + } + close(pipefd[1]); + wait(); + + return 0; +} diff --git a/pool/shard004/C/0100467_T4221_c.c b/pool/shard004/C/0100467_T4221_c.c new file mode 100644 index 0000000000000000000000000000000000000000..0c5ca228c14fd370818a385637f0f5cf2c5777e6 --- /dev/null +++ b/pool/shard004/C/0100467_T4221_c.c @@ -0,0 +1,26 @@ +#include +#include + +typedef double (*hs_function_ptr)(double); + +typedef struct { + hs_function_ptr fn; + void (*free_fn)(hs_function_ptr); +} fn_blob; + +fn_blob* create_fn_blob(hs_function_ptr fn, void (*free_fn)(hs_function_ptr)) { + fn_blob* new_blob = malloc(sizeof(fn_blob)); + new_blob->fn = fn; + new_blob->free_fn = free_fn; + return new_blob; +} + +double call_fn_blob(fn_blob* fn_blob, double arg) { + return(fn_blob->fn(arg)); +} + +void free_fn_blob(fn_blob* dead_blob) { + dead_blob->free_fn(dead_blob->fn); + free(dead_blob); +} + diff --git a/pool/shard004/C/0100468_parse.c b/pool/shard004/C/0100468_parse.c new file mode 100644 index 0000000000000000000000000000000000000000..10510c9d951ae958853b2efc6ac0f42e7a46be08 --- /dev/null +++ b/pool/shard004/C/0100468_parse.c @@ -0,0 +1,131 @@ +/* + * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ +#define _GNU_SOURCE +#include +#undef _GNU_SOURCE +#include +#include +#include +#include + +#include "parse.h" +#include + +lxc_log_define(lxc_parse, lxc); + +static int dir_filter(const struct dirent *dirent) +{ + if (!strcmp(dirent->d_name, ".") || + !strcmp(dirent->d_name, "..")) + return 0; + return 1; +} + +int lxc_dir_for_each(const char *name, const char *directory, + lxc_dir_cb callback, void *data) +{ + struct dirent **namelist; + int n, ret = 0; + + n = scandir(directory, &namelist, dir_filter, alphasort); + if (n < 0) { + SYSERROR("failed to scan %s directory", directory); + return -1; + } + + while (n--) { + if (!ret && + callback(name, directory, namelist[n]->d_name, data)) { + ERROR("callback failed"); + ret = -1; + } + free(namelist[n]); + } + free(namelist); + + return ret; +} + +int lxc_file_for_each_line(const char *file, lxc_file_cb callback, void *data) +{ + FILE *f; + int err = 0; + char *line = NULL; + size_t len = 0; + + f = fopen(file, "r"); + if (!f) { + SYSERROR("failed to open %s", file); + return -1; + } + + while (getline(&line, &len, f) != -1) { + err = callback(line, data); + if (err) + break; + } + + if (line) + free(line); + fclose(f); + return err; +} + +int lxc_char_left_gc(char *buffer, size_t len) +{ + int i; + for (i = 0; i < len; i++) { + if (buffer[i] == ' ' || + buffer[i] == '\t') + continue; + return i; + } + return 0; +} + +int lxc_char_right_gc(char *buffer, size_t len) +{ + int i; + for (i = len - 1; i >= 0; i--) { + if (buffer[i] == ' ' || + buffer[i] == '\t' || + buffer[i] == '\n' || + buffer[i] == '\0') + continue; + return i + 1; + } + return 0; +} + +int lxc_is_line_empty(char *line) +{ + int i; + size_t len = strlen(line); + + for (i = 0; i < len; i++) + if (line[i] != ' ' && line[i] != '\t' && + line[i] != '\n' && line[i] != '\r' && + line[i] != '\f' && line[i] != '\0') + return 0; + return 1; +} diff --git a/pool/shard004/C/0100473_dma-example.c b/pool/shard004/C/0100473_dma-example.c new file mode 100644 index 0000000000000000000000000000000000000000..be0d4a5fdf53629d1ceeb38dc5953f619277f8e4 --- /dev/null +++ b/pool/shard004/C/0100473_dma-example.c @@ -0,0 +1,143 @@ +/* + * Sample fifo dma implementation + * + * Copyright (C) 2010 Stefani Seibold + * + * Released under the GPL version 2 only. + * + */ + +#include +#include +#include + +/* + * This module shows how to handle fifo dma operations. + */ + +/* fifo size in elements (bytes) */ +#define FIFO_SIZE 32 + +static struct kfifo fifo; + +static int __init example_init(void) +{ + int i; + unsigned int ret; + unsigned int nents; + struct scatterlist sg[10]; + + printk(KERN_INFO "DMA fifo test start\n"); + + if (kfifo_alloc(&fifo, FIFO_SIZE, GFP_KERNEL)) { + printk(KERN_WARNING "error kfifo_alloc\n"); + return -ENOMEM; + } + + printk(KERN_INFO "queue size: %u\n", kfifo_size(&fifo)); + + kfifo_in(&fifo, "test", 4); + + for (i = 0; i != 9; i++) + kfifo_put(&fifo, i); + + /* kick away first byte */ + kfifo_skip(&fifo); + + printk(KERN_INFO "queue len: %u\n", kfifo_len(&fifo)); + + /* + * Configure the kfifo buffer to receive data from DMA input. + * + * .--------------------------------------. + * | 0 | 1 | 2 | ... | 12 | 13 | ... | 31 | + * |---|------------------|---------------| + * \_/ \________________/ \_____________/ + * \ \ \ + * \ \_allocated data \ + * \_*free space* \_*free space* + * + * We need two different SG entries: one for the free space area at the + * end of the kfifo buffer (19 bytes) and another for the first free + * byte at the beginning, after the kfifo_skip(). + */ + sg_init_table(sg, ARRAY_SIZE(sg)); + nents = kfifo_dma_in_prepare(&fifo, sg, ARRAY_SIZE(sg), FIFO_SIZE); + printk(KERN_INFO "DMA sgl entries: %d\n", nents); + if (!nents) { + /* fifo is full and no sgl was created */ + printk(KERN_WARNING "error kfifo_dma_in_prepare\n"); + return -EIO; + } + + /* receive data */ + printk(KERN_INFO "scatterlist for receive:\n"); + for (i = 0; i < nents; i++) { + printk(KERN_INFO + "sg[%d] -> " + "page %p offset 0x%.8x length 0x%.8x\n", + i, sg_page(&sg[i]), sg[i].offset, sg[i].length); + + if (sg_is_last(&sg[i])) + break; + } + + /* put here your code to setup and exectute the dma operation */ + /* ... */ + + /* example: zero bytes received */ + ret = 0; + + /* finish the dma operation and update the received data */ + kfifo_dma_in_finish(&fifo, ret); + + /* Prepare to transmit data, example: 8 bytes */ + nents = kfifo_dma_out_prepare(&fifo, sg, ARRAY_SIZE(sg), 8); + printk(KERN_INFO "DMA sgl entries: %d\n", nents); + if (!nents) { + /* no data was available and no sgl was created */ + printk(KERN_WARNING "error kfifo_dma_out_prepare\n"); + return -EIO; + } + + printk(KERN_INFO "scatterlist for transmit:\n"); + for (i = 0; i < nents; i++) { + printk(KERN_INFO + "sg[%d] -> " + "page %p offset 0x%.8x length 0x%.8x\n", + i, sg_page(&sg[i]), sg[i].offset, sg[i].length); + + if (sg_is_last(&sg[i])) + break; + } + + /* put here your code to setup and exectute the dma operation */ + /* ... */ + + /* example: 5 bytes transmitted */ + ret = 5; + + /* finish the dma operation and update the transmitted data */ + kfifo_dma_out_finish(&fifo, ret); + + ret = kfifo_len(&fifo); + printk(KERN_INFO "queue len: %u\n", kfifo_len(&fifo)); + + if (ret != 7) { + printk(KERN_WARNING "size mismatch: test failed"); + return -EIO; + } + printk(KERN_INFO "test passed\n"); + + return 0; +} + +static void __exit example_exit(void) +{ + kfifo_free(&fifo); +} + +module_init(example_init); +module_exit(example_exit); +MODULE_LICENSE("GPL"); +MODULE_AUTHOR("Stefani Seibold "); diff --git a/pool/shard004/C/0100481_ide-application-color.c b/pool/shard004/C/0100481_ide-application-color.c new file mode 100644 index 0000000000000000000000000000000000000000..2cb6fb5acdf274010ae8866911bc2a1b1a12e542 --- /dev/null +++ b/pool/shard004/C/0100481_ide-application-color.c @@ -0,0 +1,75 @@ +/* ide-application-color.c + * + * Copyright © 2017 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 "ide-application-color" + +#include "application/ide-application.h" +#include "application/ide-application-private.h" + +static void +ide_application_color_properties_changed (IdeApplication *self, + GVariant *properties, + const gchar * const *invalidated, + GDBusProxy *proxy) +{ + g_assert (IDE_IS_APPLICATION (self)); + g_assert (G_IS_DBUS_PROXY (proxy)); + + if (g_settings_get_boolean (self->settings, "follow-night-light")) + { + g_autoptr(GVariant) activev = NULL; + gboolean active; + + activev = g_dbus_proxy_get_cached_property (proxy, "NightLightActive"); + active = g_variant_get_boolean (activev); + + if (active != g_settings_get_boolean (self->settings, "night-mode")) + g_settings_set_boolean (self->settings, "night-mode", active); + } +} + +void +_ide_application_init_color (IdeApplication *self) +{ + g_autoptr(GDBusConnection) conn = NULL; + g_autoptr(GDBusProxy) proxy = NULL; + + g_return_if_fail (IDE_IS_APPLICATION (self)); + + if (NULL == (conn = g_bus_get_sync (G_BUS_TYPE_SESSION, NULL, NULL))) + return; + + if (NULL == (proxy = g_dbus_proxy_new_sync (conn, + G_DBUS_PROXY_FLAGS_GET_INVALIDATED_PROPERTIES, + NULL, + "org.gnome.SettingsDaemon.Color", + "/org/gnome/SettingsDaemon/Color", + "org.gnome.SettingsDaemon.Color", + NULL, NULL))) + return; + + g_signal_connect_object (proxy, + "g-properties-changed", + G_CALLBACK (ide_application_color_properties_changed), + self, + G_CONNECT_SWAPPED); + + self->color_proxy = g_steal_pointer (&proxy); + + ide_application_color_properties_changed (self, NULL, NULL, self->color_proxy); +} diff --git a/pool/shard004/C/0100495_gp_fault_strategy.c b/pool/shard004/C/0100495_gp_fault_strategy.c new file mode 100644 index 0000000000000000000000000000000000000000..42eab757d06efd57d26c730952137aa73c7de7dd --- /dev/null +++ b/pool/shard004/C/0100495_gp_fault_strategy.c @@ -0,0 +1,86 @@ +/* + * gp_fault_strategy.c + * + * Copyright (c) 2017-Present Pivotal Software, Inc. + * + */ + +#include "postgres.h" + +#include "catalog/gp_fault_strategy.h" +#include "access/genam.h" +#include "access/heapam.h" + +/* + * Get the gp_fault_strategy entry + */ +char +get_gp_fault_strategy(void) +{ + Relation rel; + HeapTuple tuple; + SysScanDesc sscan; + Datum strategy_datum; + char strategy; + + rel = heap_open(GpFaultStrategyRelationId, AccessShareLock); + + /* SELECT * FROM gp_fault_strategy */ + sscan = systable_beginscan(rel, InvalidOid, false, SnapshotNow, 0, NULL); + + /* there should only be one row in table */ + tuple = systable_getnext(sscan); + + if (!HeapTupleIsValid(tuple)) + ereport(ERROR, (errmsg("could not read gp_fault_strategy"))); + + strategy_datum = heap_getattr(tuple, Anum_gp_fault_strategy_fault_strategy, RelationGetDescr(rel), NULL); + strategy = DatumGetChar(strategy_datum); + + systable_endscan(sscan); + heap_close(rel, AccessShareLock); + +#ifdef USE_SEGWALREP + Assert(strategy == GpFaultStrategyMirrorLess || strategy == GpFaultStrategyWalRepMirrored); +#else + Assert(strategy == GpFaultStrategyMirrorLess || strategy == GpFaultStrategyFileRepMirrored); +#endif + + return strategy; +} + +#ifdef USE_SEGWALREP +/* + * Update the gp_fault_strategy if needed + */ +void +update_gp_fault_strategy(char fault_strategy) +{ + Relation rel; + HeapTuple tuple; + SysScanDesc sscan; + Form_gp_fault_strategy form; + + rel = heap_open(GpFaultStrategyRelationId, AccessExclusiveLock); + + sscan = systable_beginscan(rel, InvalidOid, false, SnapshotNow, 0, NULL); + + /* there should only be one row in table */ + tuple = systable_getnext(sscan); + + if (!HeapTupleIsValid(tuple)) + ereport(ERROR, (errmsg("could not update gp_fault_strategy"))); + + tuple = heap_copytuple(tuple); + systable_endscan(sscan); + + form = ((Form_gp_fault_strategy)GETSTRUCT(tuple)); + if (form->fault_strategy != fault_strategy) + { + form->fault_strategy = fault_strategy; + simple_heap_update(rel, &tuple->t_self, tuple); + } + + heap_close(rel, AccessExclusiveLock); +} +#endif diff --git a/pool/shard004/C/0100501_test_collision_detection.c b/pool/shard004/C/0100501_test_collision_detection.c new file mode 100644 index 0000000000000000000000000000000000000000..5e89163de0327ee4abc101196b6b37a887883ac2 --- /dev/null +++ b/pool/shard004/C/0100501_test_collision_detection.c @@ -0,0 +1,187 @@ +#ifdef HAVE_CONFIG_H +# include +#endif + +#include "ephysics_test.h" + +typedef struct _Collision_Data Collision_Data; + +struct _Collision_Data { + Test_Data base; + Evas_Object *impact; + EPhysics_Body *sphere; + EPhysics_Body *sphere2; +}; + +static void +_collision_cb(void *data, EPhysics_Body *body __UNUSED__, void *event_info) +{ + EPhysics_Body *contact_body; + Collision_Data *collision_data = data; + EPhysics_Body_Collision *collision = event_info; + int x, y, z; + + contact_body = ephysics_body_collision_contact_body_get(collision); + if (contact_body != collision_data->sphere2) return; + + ephysics_body_collision_position_get(collision, &x, &y, &z); + + evas_object_move(collision_data->impact, x - 10, y - 40); + elm_object_signal_emit(collision_data->impact, "impact,show", + "ephysics_test"); + + INF("Collision Detected at (%i, %i, %i)", x, y, z); +} + +static void +_world_populate(Collision_Data *collision_data) +{ + Evas_Object *sphere1, *sphere2, *sh1, *sh2, *impact; + EPhysics_Body *sphere_body1, *sphere_body2; + + sh1 = elm_layout_add(collision_data->base.win); + elm_layout_file_set( + sh1, PACKAGE_DATA_DIR "/" EPHYSICS_TEST_THEME ".edj", "shadow-ball"); + evas_object_move(sh1, WIDTH / 2, FLOOR_Y); + evas_object_resize(sh1, 70, 3); + evas_object_show(sh1); + collision_data->base.evas_objs = eina_list_append( + collision_data->base.evas_objs, sh1); + + sphere1 = elm_image_add(collision_data->base.win); + elm_image_file_set( + sphere1, PACKAGE_DATA_DIR "/" EPHYSICS_TEST_THEME ".edj", + "big-blue-ball"); + evas_object_move(sphere1, WIDTH / 2, FLOOR_Y - 70 + 1); + evas_object_resize(sphere1, 70, 70); + evas_object_show(sphere1); + collision_data->base.evas_objs = eina_list_append( + collision_data->base.evas_objs, sphere1); + + sphere_body1 = ephysics_body_sphere_add(collision_data->base.world); + ephysics_body_evas_object_set(sphere_body1, sphere1, EINA_TRUE); + ephysics_body_event_callback_add(sphere_body1, + EPHYSICS_CALLBACK_BODY_UPDATE, + update_object_cb, sh1); + ephysics_body_restitution_set(sphere_body1, 0.8); + ephysics_body_friction_set(sphere_body1, 0.4); + collision_data->base.bodies = eina_list_append( + collision_data->base.bodies, sphere_body1); + collision_data->sphere = sphere_body1; + + sh2 = elm_layout_add(collision_data->base.win); + elm_layout_file_set( + sh2, PACKAGE_DATA_DIR "/" EPHYSICS_TEST_THEME ".edj", "shadow-ball"); + evas_object_move(sh2, WIDTH / 8, FLOOR_Y); + evas_object_resize(sh2, 70, 3); + evas_object_show(sh2); + collision_data->base.evas_objs = eina_list_append( + collision_data->base.evas_objs, sh2); + + sphere2 = elm_image_add(collision_data->base.win); + elm_image_file_set( + sphere2, PACKAGE_DATA_DIR "/" EPHYSICS_TEST_THEME ".edj", + "big-red-ball"); + evas_object_move(sphere2, WIDTH / 8, FLOOR_Y - 70 + 1); + evas_object_resize(sphere2, 70, 70); + evas_object_show(sphere2); + collision_data->base.evas_objs = eina_list_append( + collision_data->base.evas_objs, sphere2); + + sphere_body2 = ephysics_body_sphere_add(collision_data->base.world); + ephysics_body_evas_object_set(sphere_body2, sphere2, EINA_TRUE); + ephysics_body_event_callback_add(sphere_body2, + EPHYSICS_CALLBACK_BODY_UPDATE, + update_object_cb, sh2); + ephysics_body_restitution_set(sphere_body2, 1); + ephysics_body_friction_set(sphere_body2, 0.4); + ephysics_body_central_impulse_apply(sphere_body2, 360, 0, 0); + collision_data->sphere2 = sphere_body2; + collision_data->base.bodies = eina_list_append( + collision_data->base.bodies, sphere_body2); + + impact = elm_layout_add(collision_data->base.win); + elm_layout_file_set( + impact, PACKAGE_DATA_DIR "/" EPHYSICS_TEST_THEME ".edj", "impact"); + evas_object_resize(impact, 20, 20); + evas_object_show(impact); + collision_data->base.evas_objs = eina_list_append( + collision_data->base.evas_objs, impact); + collision_data->impact = impact; +} + +static void +_restart(void *data, Evas_Object *obj __UNUSED__, const char *emission __UNUSED__, const char *source __UNUSED__) +{ + Collision_Data *collision_data = data; + + DBG("Restart pressed"); + ephysics_body_event_callback_del(collision_data->sphere, + EPHYSICS_CALLBACK_BODY_COLLISION, + _collision_cb); + test_clean((Test_Data *)collision_data); + _world_populate(collision_data); + ephysics_body_event_callback_add(collision_data->sphere, + EPHYSICS_CALLBACK_BODY_COLLISION, + _collision_cb, collision_data); +} + +static void +_win_del(void *data, Evas *e __UNUSED__, Evas_Object *obj __UNUSED__, void *event_info __UNUSED__) +{ + Collision_Data *collision_data = data; + + test_clean((Test_Data *)collision_data); + evas_object_del(collision_data->base.layout); + ephysics_world_del(collision_data->base.world); + free(collision_data); + ephysics_shutdown(); +} + +void +test_collision(void *data __UNUSED__, Evas_Object *obj __UNUSED__, void *event_info __UNUSED__) +{ + Collision_Data *collision_data; + EPhysics_Body *boundary; + EPhysics_World *world; + + if (!ephysics_init()) + return; + + collision_data = calloc(1, sizeof(Collision_Data)); + if (!collision_data) + { + ERR("Failed to create test data"); + ephysics_shutdown(); + return; + } + + test_win_add((Test_Data *)collision_data, "Collision Detection", EINA_FALSE); + elm_object_signal_emit(collision_data->base.layout, "borders,show", + "ephysics_test"); + evas_object_event_callback_add(collision_data->base.win, EVAS_CALLBACK_DEL, + _win_del, collision_data); + elm_layout_signal_callback_add(collision_data->base.layout, "restart", + "test-theme", _restart, collision_data); + + world = ephysics_world_new(); + ephysics_world_render_geometry_set(world, 50, 40, -50, + WIDTH - 100, FLOOR_Y - 40, DEPTH); + collision_data->base.world = world; + + boundary = ephysics_body_bottom_boundary_add(collision_data->base.world); + ephysics_body_restitution_set(boundary, 0); + ephysics_body_friction_set(boundary, 20); + + boundary = ephysics_body_right_boundary_add(collision_data->base.world); + ephysics_body_restitution_set(boundary, 0.8); + + ephysics_body_left_boundary_add(collision_data->base.world); + ephysics_body_top_boundary_add(collision_data->base.world); + + _world_populate(collision_data); + + ephysics_body_event_callback_add(collision_data->sphere, + EPHYSICS_CALLBACK_BODY_COLLISION, + _collision_cb, collision_data); +} diff --git a/pool/shard004/C/0100502_filter.c b/pool/shard004/C/0100502_filter.c new file mode 100644 index 0000000000000000000000000000000000000000..a75c3648ebaf858745b989c6d221302a31bcd154 --- /dev/null +++ b/pool/shard004/C/0100502_filter.c @@ -0,0 +1,157 @@ +#include "smman.h" +#include + +static void +_filter_rules_free(void *data EINA_UNUSED) +{ +} + +Eina_Bool +filter_reload(void *data, + int type EINA_UNUSED, + void *ev EINA_UNUSED) +{ + Smman *smman = data; + Filter *filter; + + DBG("smman[%p]", smman); + + EINA_INLIST_FOREACH(smman->filters, filter) + { + spy_file_pause(filter->sf); + eina_hash_free(filter->rules); + filter->rules = eina_hash_string_superfast_new(_filter_rules_free); + } + + rules_purge(smman->rules); + + rules_load(smman->rules, filter_load, filter_load_done, + filter_load_error, smman); + return EINA_TRUE; +} + +Filter * +_filter_find(Smman *smman, + const char *filename) +{ + Filter *filter; + + EINA_INLIST_FOREACH(smman->filters, filter) + { + if (!strcmp(filter->filename, filename)) + return filter; + } + return NULL; +} + +void +filter_load(void *data, + Rules *rules, + Rule *rule) +{ + Smman *smman; + Filter *filter; + int r; + glob_t files; + char **s; + size_t i; + + smman = data; + if (smman->rules != rules) + return; + + DBG("smman[%p] rules[%p] rule[%p][%s]", smman, rules, rule, rule->name); + + DBG("rule : %s\n\tfilename[%s]\n\tsource_host[%s]\n\t" + "source_path[%s]\ntodel[%s]", + rule->name, rule->spec.filename, rule->spec.source_host, + rule->spec.source_path, (rule->spec.todel) ? "EINA_TRUE" : "EINA_FALSE"); + + /* Loop with globbing to write here! */ + r = glob(rule->spec.filename, GLOB_MARK, 0, &files); + if (r) + { + ERR("Unable to find files matching \"%s\"", rule->spec.filename); + return; + } + + for (s = files.gl_pathv, i = files.gl_pathc; i; s++, i--) + { + DBG("Corresponding file %s", *s); + + /* We have to check the files affected by this rule */ + filter = _filter_find(smman,*s); + if (filter) + goto add_rule; + + DBG("No filter found for %s, creating new one", *s); + filter = calloc(1, sizeof(Filter)); + filter->sf = spy_file_new(smman->spy, *s); + if (!filter->sf) + { + ERR("Failed to put spy on %s", *s); + free(filter); + continue; + } + + spy_file_data_set(filter->sf, filter); + filter->filename = strdup(*s); + filter->rules = eina_hash_string_superfast_new(_filter_rules_free); + smman->filters = eina_inlist_append(smman->filters, + EINA_INLIST_GET(filter)); + + add_rule: + DBG("Adding rule[%p][%s] to filter[%p][%s]", + rule, rule->name, filter, filter->filename); + eina_hash_add(filter->rules, rule->name, rule); + } + globfree(&files); +} + +void +filter_load_done(void *data, + Rules *rules) +{ + Smman *smman; + Filter *filter; + Eina_Inlist *l; + + smman = data; + if (smman->rules != rules) + return; + + DBG("smman[%p] rules[%p]", smman, rules); + + EINA_INLIST_FOREACH_SAFE(smman->filters, l, filter) + { + if (eina_hash_population(filter->rules)) + { + DBG("Resuming sf[%p]", filter->sf); + spy_file_resume(filter->sf); + continue; + } + + DBG("Freeing filter %s", filter->filename); + smman->filters = eina_inlist_remove(smman->filters, smman->filters); + spy_file_free(filter->sf); + free((char *)filter->filename); + eina_hash_free(filter->rules); + free(filter); + } +} + +void +filter_load_error(void *data, + Rules *rules, + const char *errstr) +{ + Smman *smman; + + smman = data; + + if (smman->rules != rules) + return; + + ERR("Failed to load rules : %s", errstr); + ecore_main_loop_quit(); +} diff --git a/pool/shard004/C/0100503_Editor.c b/pool/shard004/C/0100503_Editor.c new file mode 100644 index 0000000000000000000000000000000000000000..4ec49be3729055fc30b6e8997ce73c80820ce0e6 --- /dev/null +++ b/pool/shard004/C/0100503_Editor.c @@ -0,0 +1,162 @@ +#include "Editor.h" +#include +#include +#include +#include "Command.h" + +#ifdef __GNUC__ +#include +static struct termios old, new; + +/* Initialize new terminal i/o settings */ +void initTermios(int echo) +{ + tcgetattr(0, &old); /* grab old terminal i/o settings */ + new = old; /* make new settings same as old settings */ + new.c_lflag &= ~ICANON; /* disable buffered i/o */ + new.c_lflag &= echo ? ECHO : ~ECHO; /* set echo mode */ + tcsetattr(0, TCSANOW, &new); /* use these new terminal i/o settings now */ +} + +/* Restore old terminal i/o settings */ +void resetTermios(void) +{ + tcsetattr(0, TCSANOW, &old); +} + +/* Read 1 character - echo defines echo mode */ +char getch_(int echo) +{ + char ch; + ch = getchar(); + return ch; +} + +/* Read 1 character without echo */ +char getch(void) +{ + return getch_(0); +} + +#define GETKEY getch() +#endif +#ifdef _MSC_VER +#include +char mygetch() +{ + char c = getch(); + if (c == '\r') + { + c = '\n'; + } + return c; +} +#define GETKEY mygetch() +#endif + + + +void Exec(CommandContext* context) +{ + if (EDContentLen > 0 && Content != NULL) + { + printf(Content); + } + while (EditorStatus == ED_OPEN) + { + if (EditorMode == ED_C) + { + Commander(context, '>'); + } + else + { + char tmp; +#ifdef __GNUC__ + initTermios(0); // with echo +#endif + while ((tmp = GETKEY) != EOF) + { + if (tmp == 27) // ESC + { + break; + } + if (32 <= tmp && tmp <= 126 || tmp == '\n') + { + // 缓冲区不够就扩充一倍 + if (EDContentLen + 1 >= EDContentSize) + { + EDContentSize *= 2; + char* ptmp = malloc(EDContentSize); + strcpy(ptmp, Content); + free(Content); + Content = ptmp; + } + Content[EDContentLen] = tmp; + Content[EDContentLen + 1] = 0; + EDContentLen++; + printf("%c", tmp); + } + if (tmp == 8) + { + EDContentLen--; + Content[EDContentLen] = 0; + putc(8, stdout); //退格 + putc(' ', stdout); //空格 + putc(8, stdout); //空格 + } + } +#ifdef __GNUC__ + resetTermios(); +#endif + printf("\n---------Now, You Are In Command Mode---------\n"); + printf("i\tSwitch to EDITING mode.\nq\tQuit without save.\nw\tSave file.\n"); + EditorMode = ED_C; + } + } +} + +int EditorQuit() +{ + EditorStatus = ED_CLOSE; + printf("Editor closing...\n"); + return 1; +} +int Editing() +{ + printf("\n---------Now, You Are In Editing Mode---------\n"); + EditorMode = ED_E; + return 1; +} + +int EditorWriteSig() +{ + EditorStatus = ED_WRITE; + return 1; +} + +/** + * \brief 函数退出后,可以从 Content 中读取用户的输入。 + * 如果需要编辑空白文件,Content 需要设置为 NULL。 + * 如果需要追加编辑,Content,EDContentSize,EDContentLen 需要手动设置 + */ +void InitEditor() +{ + EditorStatus = ED_OPEN; + EditorMode = ED_E; + if (Content == NULL) + { + EDContentSize = 512; + Content = malloc(sizeof(char)*EDContentSize); + EDContentLen = 0; + } + CommandContext context; + context.Entries = malloc(sizeof(CommandEntry) * 5); + context.CommandCnt = 0; + Register(&context, "q", &EditorQuit); + Register(&context, "i", &Editing); + Register(&context, "w", &EditorWriteSig); + printf("\nPress 'ESC' to switch to COMMAND Mode.\n"); + Exec(&context); + CommandEntry* entries = context.Entries; + free(entries); +} \ No newline at end of file diff --git a/pool/shard004/C/0100504_cacoshl.c b/pool/shard004/C/0100504_cacoshl.c new file mode 100644 index 0000000000000000000000000000000000000000..7f482c409b40bf7f4de586b80e1175b89131df39 --- /dev/null +++ b/pool/shard004/C/0100504_cacoshl.c @@ -0,0 +1,39 @@ +/* + cacoshl.c + Contributed by Danny Smith + 2005-01-04 +*/ + +#include +#include + +#if 0 +/* cacosh (z) = I * cacos (z) */ +long double complex cacoshl (long double complex Z) +{ + long double complex Tmp; + long double complex Res; + + Tmp = cacosl (Z); + __real__ Res = -__imag__ Tmp; + __imag__ Res = __real__ Tmp; + return Res; +} + +#else + +/* cacosh (z) = I * cacos (z) = I * (pi/2 - casin (z)) */ +#ifndef _M_PI_2L +#define _M_PI_2L 1.5707963267948966192313L +#endif +long double complex cacoshl (long double complex Z) +{ + long double complex Tmp; + long double complex Res; + + Tmp = casinl (Z); + __real__ Res = __imag__ Tmp; + __imag__ Res = _M_PI_2L - __real__ Tmp; + return Res; +} +#endif diff --git a/pool/shard004/C/0100516_QGreen.c b/pool/shard004/C/0100516_QGreen.c new file mode 100644 index 0000000000000000000000000000000000000000..59bbbd5f9ef583f7c478f435f337832b2b567508 --- /dev/null +++ b/pool/shard004/C/0100516_QGreen.c @@ -0,0 +1,85 @@ +/* $Xorg: QGreen.c,v 1.3 2000/08/17 19:44:49 cpqbld Exp $ */ + +/* + * Code and supporting documentation (c) Copyright 1990 1991 Tektronix, Inc. + * All Rights Reserved + * + * This file is a component of an X Window System-specific implementation + * of Xcms based on the TekColor Color Management System. Permission is + * hereby granted to use, copy, modify, sell, and otherwise distribute this + * software and its documentation for any purpose and without fee, provided + * that this copyright, permission, and disclaimer notice is reproduced in + * all copies of this software and in supporting documentation. TekColor + * is a trademark of Tektronix, Inc. + * + * Tektronix makes no representation about the suitability of this software + * for any purpose. It is provided "as is" and with all faults. + * + * TEKTRONIX DISCLAIMS ALL WARRANTIES APPLICABLE TO THIS SOFTWARE, + * INCLUDING THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A + * PARTICULAR PURPOSE. IN NO EVENT SHALL TEKTRONIX 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 THE PERFORMANCE OF THIS SOFTWARE. + * + * + * NAME + * XcmsQGreen.c - Query Green + * + * DESCRIPTION + * Routine to obtain a color specification for full + * green intensity and zero red and blue intensities. + * + * + */ + +#ifdef HAVE_CONFIG_H +#include +#endif +#include "Xlibint.h" +#include "Xcms.h" + + + +/************************************************************************ + * * + * PUBLIC INTERFACES * + * * + ************************************************************************/ + +/* + * NAME + * XcmsQueryGreen + * + * SYNOPSIS + */ + +Status +XcmsQueryGreen(ccc, target_format, pColor_ret) + XcmsCCC ccc; + XcmsColorFormat target_format; + XcmsColor *pColor_ret; +/* + * DESCRIPTION + * Returns the color specification in the target format for + * full intensity green and zero intensity red and blue. + * + * RETURNS + * Returns XcmsSuccess, if failed; otherwise XcmsFailure + * + */ +{ + XcmsColor tmp; + + tmp.format = XcmsRGBiFormat; + tmp.pixel = 0; + tmp.spec.RGBi.red = 0.0; + tmp.spec.RGBi.green = 1.0; + tmp.spec.RGBi.blue = 0.0; + if (XcmsConvertColors(ccc, &tmp, 1, target_format, NULL) != XcmsSuccess) { + return(XcmsFailure); + } + memcpy((char *)pColor_ret, (char *)&tmp, sizeof(XcmsColor)); + return(XcmsSuccess); +} diff --git a/pool/shard004/C/0100520_inf-text-delete-operation.c b/pool/shard004/C/0100520_inf-text-delete-operation.c new file mode 100644 index 0000000000000000000000000000000000000000..f3c3563bf34911eb523bffe4ecc6d8eb400bcc1f --- /dev/null +++ b/pool/shard004/C/0100520_inf-text-delete-operation.c @@ -0,0 +1,260 @@ +/* libinfinity - a GObject-based infinote implementation + * Copyright (C) 2007-2015 Armin Burgmeier + * + * 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 St, Fifth Floor, Boston, + * MA 02110-1301, USA. + */ + +/** + * SECTION:inf-text-delete-operation + * @title: InfTextDeleteOperation + * @short_description: Interface for an operation erasing text + * @include: libinftext/inf-text-delete-operation.h + * @see_also: #InfTextInsertOperation + * @stability: Unstable + * + * #InfTextDeleteOperation is an interface for an operation removing text + * from the document. It implements the transformation logic for + * transformation against other delete operations or insert operations. + * + * This interface does not make any assumption on what kind of text is + * removed, it works only with character offsets and lengths. This information + * is enough to perform transformation of this operation or other operations + * against this operation. Whether the actual operation only knows about the + * offsets, too, or actually knows the text that is being erased (and if so, + * in what representation), is up to the implementation. + */ + +#include +#include + +G_DEFINE_INTERFACE(InfTextDeleteOperation, inf_text_delete_operation, INF_ADOPTED_TYPE_OPERATION) + +static void +inf_text_delete_operation_default_init(InfTextDeleteOperationInterface* iface) +{ +} + +/** + * inf_text_delete_operation_get_position: + * @operation: A #InfTextDeleteOperation. + * + * Returns the position at which @operation starts to delete dext. + * + * Returns: The position of @operation. + **/ +guint +inf_text_delete_operation_get_position(InfTextDeleteOperation* operation) +{ + InfTextDeleteOperationInterface* iface; + + g_return_val_if_fail(INF_TEXT_IS_DELETE_OPERATION(operation), 0); + + iface = INF_TEXT_DELETE_OPERATION_GET_IFACE(operation); + g_return_val_if_fail(iface->get_position != NULL, 0); + + return iface->get_position(operation); +} + +/** + * inf_text_delete_operation_get_length: + * @operation: A #InfTextDeleteOperation. + * + * Returns the number of characters deleted by @operation. + * + * Returns: The length of @operation. + **/ +guint +inf_text_delete_operation_get_length(InfTextDeleteOperation* operation) +{ + InfTextDeleteOperationInterface* iface; + + g_return_val_if_fail(INF_TEXT_IS_DELETE_OPERATION(operation), 0); + + iface = INF_TEXT_DELETE_OPERATION_GET_IFACE(operation); + g_return_val_if_fail(iface->get_length != NULL, 0); + + return iface->get_length(operation); +} + +/** + * inf_text_delete_operation_need_concurrency_id: + * @op: A #InfTextDeleteOperation. + * @against: Another #InfAdoptedOperation. + * + * Returns whether transforming @op against @against requires a concurrency ID + * (see inf_adopted_operation_need_concurrency_id() for further information). + * + * Returns: Whether transforming @op against @against requires a concurrency + * ID. + */ +gboolean +inf_text_delete_operation_need_concurrency_id(InfTextDeleteOperation* op, + InfAdoptedOperation* against) +{ + g_return_val_if_fail(INF_TEXT_IS_DELETE_OPERATION(op), FALSE); + g_return_val_if_fail(INF_ADOPTED_IS_OPERATION(against), FALSE); + + return FALSE; +} + +/** + * inf_text_delete_operation_transform_insert: + * @operation: A #InfTextDeleteOperation. + * @against: A #InfTextInsertOperation. + * + * Returns a new operation that includes the effect of @against into + * @operation. + * + * Returns: (transfer full): A new #InfAdoptedOperation. + **/ +InfAdoptedOperation* +inf_text_delete_operation_transform_insert(InfTextDeleteOperation* operation, + InfTextInsertOperation* against) +{ + InfTextDeleteOperationInterface* iface; + guint own_pos; + guint own_len; + guint other_pos; + guint other_len; + + g_return_val_if_fail(INF_TEXT_IS_DELETE_OPERATION(operation), NULL); + g_return_val_if_fail(INF_TEXT_IS_INSERT_OPERATION(against), NULL); + + iface = INF_TEXT_DELETE_OPERATION_GET_IFACE(operation); + g_return_val_if_fail(iface->transform_position != NULL, NULL); + g_return_val_if_fail(iface->transform_split != NULL, NULL); + + own_pos = inf_text_delete_operation_get_position(operation); + own_len = inf_text_delete_operation_get_length(operation); + other_pos = inf_text_insert_operation_get_position(against); + other_len = inf_text_insert_operation_get_length(against); + + if(other_pos >= own_pos + own_len) + { + return inf_adopted_operation_copy(INF_ADOPTED_OPERATION(operation)); + } + else if(other_pos <= own_pos) + { + return INF_ADOPTED_OPERATION( + iface->transform_position(operation, own_pos + other_len) + ); + } + else + { + return INF_ADOPTED_OPERATION( + iface->transform_split(operation, other_pos - own_pos, other_len) + ); + } +} + +/** + * inf_text_delete_operation_transform_delete: + * @operation: A #InfTextDeleteOperation. + * @against: Another #InfTextDeleteOperation. + * + * Returns a new operation that includes the effect of @against into + * @operation. + * + * Returns: (transfer full): A new #InfAdoptedOperation. + **/ +InfAdoptedOperation* +inf_text_delete_operation_transform_delete(InfTextDeleteOperation* operation, + InfTextDeleteOperation* against) +{ + InfTextDeleteOperationInterface* iface; + guint own_pos; + guint own_len; + guint other_pos; + guint other_len; + + g_return_val_if_fail(INF_TEXT_IS_DELETE_OPERATION(operation), NULL); + g_return_val_if_fail(INF_TEXT_IS_DELETE_OPERATION(against), NULL); + + iface = INF_TEXT_DELETE_OPERATION_GET_IFACE(operation); + g_return_val_if_fail(iface->transform_position != NULL, NULL); + g_return_val_if_fail(iface->transform_overlap != NULL, NULL); + + own_pos = inf_text_delete_operation_get_position(operation); + own_len = inf_text_delete_operation_get_length(operation); + other_pos = inf_text_delete_operation_get_position(against); + other_len = inf_text_delete_operation_get_length(against); + + if(own_pos + own_len <= other_pos) + { + return inf_adopted_operation_copy(INF_ADOPTED_OPERATION(operation)); + } + else if(own_pos >= other_pos + other_len) + { + return INF_ADOPTED_OPERATION( + iface->transform_position(operation, own_pos - other_len) + ); + } + /* Somehow overlapping now */ + else if(other_pos <= own_pos && other_pos + other_len >= own_pos + own_len) + { + return INF_ADOPTED_OPERATION( + iface->transform_overlap( + operation, + against, + other_pos, + 0, + own_pos - other_pos, + own_len + ) + ); + } + else if(other_pos <= own_pos && other_pos + other_len < own_pos + own_len) + { + return INF_ADOPTED_OPERATION( + iface->transform_overlap( + operation, + against, + other_pos, + 0, + own_pos - other_pos, + other_pos + other_len - own_pos + ) + ); + } + else if(other_pos > own_pos && other_pos + other_len >= own_pos + own_len) + { + return INF_ADOPTED_OPERATION( + iface->transform_overlap( + operation, + against, + own_pos, + other_pos - own_pos, + 0, + own_pos + own_len - other_pos + ) + ); + } + else + { + return INF_ADOPTED_OPERATION( + iface->transform_overlap( + operation, + against, + own_pos, + other_pos - own_pos, + 0, + other_len + ) + ); + } +} + +/* vim:set et sw=2 ts=2: */ diff --git a/pool/shard004/C/0100523_list.c b/pool/shard004/C/0100523_list.c new file mode 100644 index 0000000000000000000000000000000000000000..01942dd17bf35d5fca68c89c7b46e23deb8b6cac --- /dev/null +++ b/pool/shard004/C/0100523_list.c @@ -0,0 +1,112 @@ +/** + * Linked List implementation + */ + +#include +#include + +#include "list.h" + +/** + * Initializes the list pointed to by "l". destory is a pointer to a function that is called + * when an element from the list is freed. This can be null if no memory management needs to take place, + * or it could simply be free() if the data is simple + */ +void list_init(list* l, void (*destroy)(void* data)) { + l->size = 0; + l->destroy = destroy; + + l->head = 0; + l->tail = 0; +} + +/** + * Destroys the entire list pointed to be "l" + */ +void list_destroy(list* l) { + void* data; + + while (list_size(l) > 0) { + if (list_remove_next(l, NULL, (void**)&data) == 0 && l->destroy) { + l->destroy(data); + } + } + + // Zero out the structure so no junk data + memset(l, 0, sizeof(list)); +} + +/** + * Inserts data into list "l" in the node after "after". If "after" is NULL, the data is inserted + * as the head. + * + * Returns 0 if successful, -1 otherwise + */ +int list_insert_next(list* l, list_element* after, const void* data) { + list_element* new; + + new = (list_element*)malloc(sizeof(list_element)); + new->data = (void*)data; + + if (after == 0) { + if (list_size(l) == 0) { + l->tail = new; + } + + new->next = l->head; + l->head = new; + } else { + if (after->next == 0) { + l->tail = new; + } + + new->next = after->next; + after->next = new; + } + + l->size++; + return 0; +} + +/** + * Removes the element after the given element "after" from list "l". "data" will contain a pointer + * to the data managed by the removed element. list->destroy will NOT be called on this data, so it + * is up to the caller to clean up the data item + * + * Returns 0 if successful, -1 otherwise + */ +int list_remove_next(list *l, list_element* after, void **data) { + list_element *old; + + if (list_size(l) == 0) { + return -1; + } + + if (after == 0) { + *data = l->head->data; + old = l->head; + l->head = l->head->next; + + if (list_size(l) == 1) { + l->tail = NULL; + } + } else { + + if (after->next == 0) { + return -1; + } + + *data = after->next->data; + old = after->next; + after->next = after->next->next; + + if (after->next == NULL) { + l->tail = after; + } + } + + free(old); + + l->size--; + return 0; +} \ No newline at end of file diff --git a/pool/shard004/C/0100526_opal-hmi.c b/pool/shard004/C/0100526_opal-hmi.c new file mode 100644 index 0000000000000000000000000000000000000000..b322bfb51343f65fdfe76d265cdcb76928011d21 --- /dev/null +++ b/pool/shard004/C/0100526_opal-hmi.c @@ -0,0 +1,189 @@ +/* + * OPAL hypervisor Maintenance interrupt handling support in PowreNV. + * + * 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 . + * + * Copyright 2014 IBM Corporation + * Author: Mahesh Salgaonkar + */ + +#undef DEBUG + +#include +#include +#include +#include +#include + +#include +#include +#include + +static int opal_hmi_handler_nb_init; +struct OpalHmiEvtNode { + struct list_head list; + struct OpalHMIEvent hmi_evt; +}; +static LIST_HEAD(opal_hmi_evt_list); +static DEFINE_SPINLOCK(opal_hmi_evt_lock); + +static void print_hmi_event_info(struct OpalHMIEvent *hmi_evt) +{ + const char *level, *sevstr, *error_info; + static const char *hmi_error_types[] = { + "Malfunction Alert", + "Processor Recovery done", + "Processor recovery occurred again", + "Processor recovery occurred for masked error", + "Timer facility experienced an error", + "TFMR SPR is corrupted", + "UPS (Uniterrupted Power System) Overflow indication", + "An XSCOM operation failure", + "An XSCOM operation completed", + "SCOM has set a reserved FIR bit to cause recovery", + "Debug trigger has set a reserved FIR bit to cause recovery", + "A hypervisor resource error occurred" + }; + + /* Print things out */ + if (hmi_evt->version < OpalHMIEvt_V1) { + pr_err("HMI Interrupt, Unknown event version %d !\n", + hmi_evt->version); + return; + } + switch (hmi_evt->severity) { + case OpalHMI_SEV_NO_ERROR: + level = KERN_INFO; + sevstr = "Harmless"; + break; + case OpalHMI_SEV_WARNING: + level = KERN_WARNING; + sevstr = ""; + break; + case OpalHMI_SEV_ERROR_SYNC: + level = KERN_ERR; + sevstr = "Severe"; + break; + case OpalHMI_SEV_FATAL: + default: + level = KERN_ERR; + sevstr = "Fatal"; + break; + } + + printk("%s%s Hypervisor Maintenance interrupt [%s]\n", + level, sevstr, + hmi_evt->disposition == OpalHMI_DISPOSITION_RECOVERED ? + "Recovered" : "Not recovered"); + error_info = hmi_evt->type < ARRAY_SIZE(hmi_error_types) ? + hmi_error_types[hmi_evt->type] + : "Unknown"; + printk("%s Error detail: %s\n", level, error_info); + printk("%s HMER: %016llx\n", level, be64_to_cpu(hmi_evt->hmer)); + if ((hmi_evt->type == OpalHMI_ERROR_TFAC) || + (hmi_evt->type == OpalHMI_ERROR_TFMR_PARITY)) + printk("%s TFMR: %016llx\n", level, + be64_to_cpu(hmi_evt->tfmr)); +} + +static void hmi_event_handler(struct work_struct *work) +{ + unsigned long flags; + struct OpalHMIEvent *hmi_evt; + struct OpalHmiEvtNode *msg_node; + uint8_t disposition; + + spin_lock_irqsave(&opal_hmi_evt_lock, flags); + while (!list_empty(&opal_hmi_evt_list)) { + msg_node = list_entry(opal_hmi_evt_list.next, + struct OpalHmiEvtNode, list); + list_del(&msg_node->list); + spin_unlock_irqrestore(&opal_hmi_evt_lock, flags); + + hmi_evt = (struct OpalHMIEvent *) &msg_node->hmi_evt; + print_hmi_event_info(hmi_evt); + disposition = hmi_evt->disposition; + kfree(msg_node); + + /* + * Check if HMI event has been recovered or not. If not + * then we can't continue, invoke panic. + */ + if (disposition != OpalHMI_DISPOSITION_RECOVERED) + panic("Unrecoverable HMI exception"); + + spin_lock_irqsave(&opal_hmi_evt_lock, flags); + } + spin_unlock_irqrestore(&opal_hmi_evt_lock, flags); +} + +static DECLARE_WORK(hmi_event_work, hmi_event_handler); +/* + * opal_handle_hmi_event - notifier handler that queues up HMI events + * to be preocessed later. + */ +static int opal_handle_hmi_event(struct notifier_block *nb, + unsigned long msg_type, void *msg) +{ + unsigned long flags; + struct OpalHMIEvent *hmi_evt; + struct opal_msg *hmi_msg = msg; + struct OpalHmiEvtNode *msg_node; + + /* Sanity Checks */ + if (msg_type != OPAL_MSG_HMI_EVT) + return 0; + + /* HMI event info starts from param[0] */ + hmi_evt = (struct OpalHMIEvent *)&hmi_msg->params[0]; + + /* Delay the logging of HMI events to workqueue. */ + msg_node = kzalloc(sizeof(*msg_node), GFP_ATOMIC); + if (!msg_node) { + pr_err("HMI: out of memory, Opal message event not handled\n"); + return -ENOMEM; + } + memcpy(&msg_node->hmi_evt, hmi_evt, sizeof(struct OpalHMIEvent)); + + spin_lock_irqsave(&opal_hmi_evt_lock, flags); + list_add(&msg_node->list, &opal_hmi_evt_list); + spin_unlock_irqrestore(&opal_hmi_evt_lock, flags); + + schedule_work(&hmi_event_work); + return 0; +} + +static struct notifier_block opal_hmi_handler_nb = { + .notifier_call = opal_handle_hmi_event, + .next = NULL, + .priority = 0, +}; + +static int __init opal_hmi_handler_init(void) +{ + int ret; + + if (!opal_hmi_handler_nb_init) { + ret = opal_message_notifier_register( + OPAL_MSG_HMI_EVT, &opal_hmi_handler_nb); + if (ret) { + pr_err("%s: Can't register OPAL event notifier (%d)\n", + __func__, ret); + return ret; + } + opal_hmi_handler_nb_init = 1; + } + return 0; +} +machine_subsys_initcall(powernv, opal_hmi_handler_init); diff --git a/pool/shard004/C/0100534_setdval.c b/pool/shard004/C/0100534_setdval.c new file mode 100644 index 0000000000000000000000000000000000000000..463e4f38c5097119602ba0575b58786536f64c0a --- /dev/null +++ b/pool/shard004/C/0100534_setdval.c @@ -0,0 +1,147 @@ +/************************************************************ + +Copyright 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. + +Copyright 1989 by Hewlett-Packard Company, Palo Alto, California. + + 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 Hewlett-Packard not be +used in advertising or publicity pertaining to distribution of the +software without specific, written prior permission. + +HEWLETT-PACKARD DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING +ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL +HEWLETT-PACKARD 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. + +********************************************************/ + +/*********************************************************************** + * + * Request to change the mode of an extension input device. + * + */ + +#ifdef HAVE_DIX_CONFIG_H +#include +#endif + +#include "inputstr.h" /* DeviceIntPtr */ +#include +#include +#include "XIstubs.h" +#include "exglobals.h" + +#include "setdval.h" + +/*********************************************************************** + * + * Handle a request from a client with a different byte order. + * + */ + +int +SProcXSetDeviceValuators(ClientPtr client) +{ + REQUEST(xSetDeviceValuatorsReq); + swaps(&stuff->length); + return (ProcXSetDeviceValuators(client)); +} + +/*********************************************************************** + * + * This procedure sets the value of valuators on an extension input device. + * + */ + +int +ProcXSetDeviceValuators(ClientPtr client) +{ + DeviceIntPtr dev; + xSetDeviceValuatorsReply rep; + int rc; + + REQUEST(xSetDeviceValuatorsReq); + REQUEST_AT_LEAST_SIZE(xSetDeviceValuatorsReq); + + rep = (xSetDeviceValuatorsReply) { + .repType = X_Reply, + .RepType = X_SetDeviceValuators, + .sequenceNumber = client->sequence, + .length = 0, + .status = Success + }; + + if (stuff->length != bytes_to_int32(sizeof(xSetDeviceValuatorsReq)) + + stuff->num_valuators) + return BadLength; + + rc = dixLookupDevice(&dev, stuff->deviceid, client, DixSetAttrAccess); + if (rc != Success) + return rc; + if (dev->valuator == NULL) + return BadMatch; + + if (IsXTestDevice(dev, NULL)) + return BadMatch; + + if (stuff->first_valuator + stuff->num_valuators > dev->valuator->numAxes) + return BadValue; + + if ((dev->deviceGrab.grab) && !SameClient(dev->deviceGrab.grab, client)) + rep.status = AlreadyGrabbed; + else + rep.status = SetDeviceValuators(client, dev, (int *) &stuff[1], + stuff->first_valuator, + stuff->num_valuators); + + if (rep.status != Success && rep.status != AlreadyGrabbed) + return rep.status; + + WriteReplyToClient(client, sizeof(xSetDeviceValuatorsReply), &rep); + return Success; +} + +/*********************************************************************** + * + * This procedure writes the reply for the XSetDeviceValuators function, + * if the client and server have a different byte ordering. + * + */ + +void +SRepXSetDeviceValuators(ClientPtr client, int size, + xSetDeviceValuatorsReply * rep) +{ + swaps(&rep->sequenceNumber); + swapl(&rep->length); + WriteToClient(client, size, rep); +} diff --git a/pool/shard004/C/0100547_dht.c b/pool/shard004/C/0100547_dht.c new file mode 100644 index 0000000000000000000000000000000000000000..cf62893b25019c43dbde68fa8582fffb7e60c2e3 --- /dev/null +++ b/pool/shard004/C/0100547_dht.c @@ -0,0 +1,294 @@ +/* + * FILE: dht.cpp + * AUTHOR: Rob Tillaart + * VERSION: 0.1.14 + * PURPOSE: DHT Temperature & Humidity Sensor library for Arduino + * URL: http://arduino.cc/playground/Main/DHTLib + * + * Port to ESP8266 by Huang Rui + * + * HISTORY: + * 0.1.14 replace digital read with faster (~3x) code => more robust low MHz machines. + * 0.1.13 fix negative dht_temperature + * 0.1.12 support DHT33 and DHT44 initial version + * 0.1.11 renamed DHTLIB_TIMEOUT + * 0.1.10 optimized faster WAKEUP + TIMEOUT + * 0.1.09 optimize size: timeout check + use of mask + * 0.1.08 added formula for timeout based upon clockspeed + * 0.1.07 added support for DHT21 + * 0.1.06 minimize footprint (2012-12-27) + * 0.1.05 fixed negative dht_temperature bug (thanks to Roseman) + * 0.1.04 improved readability of code using DHTLIB_OK in code + * 0.1.03 added error values for temp and dht_humidity when read failed + * 0.1.02 added error codes + * 0.1.01 added support for Arduino 1.0, fixed typos (31/12/2011) + * 0.1.00 by Rob Tillaart (01/04/2011) + * + * Inspired by DHT11 library + * + * Released to the public domain + * + */ + +#include "dht.h" + +static double dht_humidity; +static double dht_temperature; + +static uint8_t dht_bytes[5]; // buffer to receive data +static int dht_readSensor(uint8_t pin, uint8_t wakeupDelay); + +///////////////////////////////////////////////////// +// +// PUBLIC +// + +double dht_getHumidity(void) +{ + return dht_humidity; +} + +double dht_getTemperature(void) +{ + return dht_temperature; +} + +// return values: +// DHTLIB_OK +// DHTLIB_ERROR_CHECKSUM +// DHTLIB_ERROR_TIMEOUT +int dht_read_universal(uint8_t pin) +{ + // READ VALUES + int rv = dht_readSensor(pin, DHTLIB_DHT_UNI_WAKEUP); + if (rv != DHTLIB_OK) { + dht_humidity = DHTLIB_INVALID_VALUE; // invalid value, or is NaN prefered? + dht_temperature = DHTLIB_INVALID_VALUE; // invalid value + return rv; // propagate error value + } +#if defined(DHT_DEBUG_BYTES) + int i; + for (i = 0; i < 5; i++) { + DHT_DEBUG("%02X\n", dht_bytes[i]); + } +#endif // defined(DHT_DEBUG_BYTES) + + // Assume it is DHT11 + // If it is DHT11, both bit[1] and bit[3] is 0 + if ((dht_bytes[1] == 0) && (dht_bytes[3] == 0)) { + // It may DHT11 + // CONVERT AND STORE + DHT_DEBUG("DHT11 method\n"); + dht_humidity = dht_bytes[0]; // dht_bytes[1] == 0; + dht_temperature = dht_bytes[2]; // dht_bytes[3] == 0; + + // TEST CHECKSUM + // dht_bytes[1] && dht_bytes[3] both 0 + uint8_t sum = dht_bytes[0] + dht_bytes[2]; + if (dht_bytes[4] != sum) { + // It may not DHT11 + dht_humidity = DHTLIB_INVALID_VALUE; // invalid value, or is NaN prefered? + dht_temperature = DHTLIB_INVALID_VALUE; // invalid value + // Do nothing + } else { + return DHTLIB_OK; + } + } + // Assume it is not DHT11 + // CONVERT AND STORE + DHT_DEBUG("DHTxx method\n"); + dht_humidity = + (double)COMBINE_HIGH_AND_LOW_BYTE(dht_bytes[0], dht_bytes[1]) * 0.1; + dht_temperature = + (double)COMBINE_HIGH_AND_LOW_BYTE(dht_bytes[2] & 0x7F, + dht_bytes[3]) * 0.1; + if (dht_bytes[2] & 0x80) // negative dht_temperature + { + dht_temperature = -dht_temperature; + } + // TEST CHECKSUM + uint8_t sum = dht_bytes[0] + dht_bytes[1] + dht_bytes[2] + dht_bytes[3]; + if (dht_bytes[4] != sum) { + return DHTLIB_ERROR_CHECKSUM; + } + return DHTLIB_OK; +} + +// return values: +// DHTLIB_OK +// DHTLIB_ERROR_CHECKSUM +// DHTLIB_ERROR_TIMEOUT +int dht_read11(uint8_t pin) +{ + // READ VALUES + int rv = dht_readSensor(pin, DHTLIB_DHT11_WAKEUP); + if (rv != DHTLIB_OK) { + dht_humidity = DHTLIB_INVALID_VALUE; // invalid value, or is NaN prefered? + dht_temperature = DHTLIB_INVALID_VALUE; // invalid value + return rv; + } + // CONVERT AND STORE + dht_humidity = dht_bytes[0]; // dht_bytes[1] == 0; + dht_temperature = dht_bytes[2]; // dht_bytes[3] == 0; + + // TEST CHECKSUM + // dht_bytes[1] && dht_bytes[3] both 0 + uint8_t sum = dht_bytes[0] + dht_bytes[2]; + if (dht_bytes[4] != sum) + return DHTLIB_ERROR_CHECKSUM; + + return DHTLIB_OK; +} + +// return values: +// DHTLIB_OK +// DHTLIB_ERROR_CHECKSUM +// DHTLIB_ERROR_TIMEOUT +int dht_read(uint8_t pin) +{ + // READ VALUES + int rv = dht_readSensor(pin, DHTLIB_DHT_WAKEUP); + if (rv != DHTLIB_OK) { + dht_humidity = DHTLIB_INVALID_VALUE; // invalid value, or is NaN prefered? + dht_temperature = DHTLIB_INVALID_VALUE; // invalid value + return rv; // propagate error value + } + // CONVERT AND STORE + dht_humidity = + (double)COMBINE_HIGH_AND_LOW_BYTE(dht_bytes[0], dht_bytes[1]) * 0.1; + dht_temperature = + (double)COMBINE_HIGH_AND_LOW_BYTE(dht_bytes[2] & 0x7F, + dht_bytes[3]) * 0.1; + if (dht_bytes[2] & 0x80) // negative dht_temperature + { + dht_temperature = -dht_temperature; + } + // TEST CHECKSUM + uint8_t sum = dht_bytes[0] + dht_bytes[1] + dht_bytes[2] + dht_bytes[3]; + if (dht_bytes[4] != sum) { + return DHTLIB_ERROR_CHECKSUM; + } + return DHTLIB_OK; +} + +// return values: +// DHTLIB_OK +// DHTLIB_ERROR_CHECKSUM +// DHTLIB_ERROR_TIMEOUT +int dht_read21(uint8_t pin) __attribute__ ((alias("dht_read"))); + +// return values: +// DHTLIB_OK +// DHTLIB_ERROR_CHECKSUM +// DHTLIB_ERROR_TIMEOUT +int dht_read22(uint8_t pin) __attribute__ ((alias("dht_read"))); + +// return values: +// DHTLIB_OK +// DHTLIB_ERROR_CHECKSUM +// DHTLIB_ERROR_TIMEOUT +int dht_read33(uint8_t pin) __attribute__ ((alias("dht_read"))); + +// return values: +// DHTLIB_OK +// DHTLIB_ERROR_CHECKSUM +// DHTLIB_ERROR_TIMEOUT +int dht_read44(uint8_t pin) __attribute__ ((alias("dht_read"))); + +///////////////////////////////////////////////////// +// +// PRIVATE +// + +// return values: +// DHTLIB_OK +// DHTLIB_ERROR_TIMEOUT +int dht_readSensor(uint8_t pin, uint8_t wakeupDelay) +{ + // INIT BUFFERVAR TO RECEIVE DATA + uint8_t mask = 128; + uint8_t idx = 0; + uint8_t i = 0; + + // replace digitalRead() with Direct Port Reads. + // reduces footprint ~100 bytes => portability issue? + // direct port read is about 3x faster + // uint8_t bit = digitalPinToBitMask(pin); + // uint8_t port = digitalPinToPort(pin); + // volatile uint8_t *PIR = portInputRegister(port); + + // EMPTY BUFFER + for (i = 0; i < 5; i++) + dht_bytes[i] = 0; + + // REQUEST SAMPLE + // pinMode(pin, OUTPUT); + //platform_gpio_mode(pin, PLATFORM_GPIO_OUTPUT, PLATFORM_GPIO_PULLUP); + DIRECT_MODE_OUTPUT(pin); + // digitalWrite(pin, LOW); // T-be + DIRECT_WRITE_LOW(pin); + // delay(wakeupDelay); + for (i = 0; i < wakeupDelay; i++) + os_delay_us(1000); + // Disable interrupts + ets_intr_lock(); + // digitalWrite(pin, HIGH); // T-go + DIRECT_WRITE_HIGH(pin); + os_delay_us(40); + // pinMode(pin, INPUT); + DIRECT_MODE_INPUT(pin); + + // GET ACKNOWLEDGE or TIMEOUT + uint16_t loopCntLOW = DHTLIB_TIMEOUT; + while (DIRECT_READ(pin) == LOW) // T-rel + { + os_delay_us(1); + if (--loopCntLOW == 0) + return DHTLIB_ERROR_TIMEOUT; + } + + uint16_t loopCntHIGH = DHTLIB_TIMEOUT; + while (DIRECT_READ(pin) != LOW) // T-reh + { + os_delay_us(1); + if (--loopCntHIGH == 0) + return DHTLIB_ERROR_TIMEOUT; + } + + // READ THE OUTPUT - 40 BITS => 5 BYTES + for (i = 40; i != 0; i--) { + loopCntLOW = DHTLIB_TIMEOUT; + while (DIRECT_READ(pin) == LOW) { + os_delay_us(1); + if (--loopCntLOW == 0) + return DHTLIB_ERROR_TIMEOUT; + } + + uint32_t t = system_get_time(); + + loopCntHIGH = DHTLIB_TIMEOUT; + while (DIRECT_READ(pin) != LOW) { + os_delay_us(1); + if (--loopCntHIGH == 0) + return DHTLIB_ERROR_TIMEOUT; + } + + if ((system_get_time() - t) > 40) { + dht_bytes[idx] |= mask; + } + mask >>= 1; + if (mask == 0) // next byte? + { + mask = 128; + idx++; + } + } + // Enable interrupts + ets_intr_unlock(); + // pinMode(pin, OUTPUT); + DIRECT_MODE_OUTPUT(pin); + // digitalWrite(pin, HIGH); + DIRECT_WRITE_HIGH(pin); + + return DHTLIB_OK; +} diff --git a/pool/shard004/C/0100548_net.c b/pool/shard004/C/0100548_net.c new file mode 100644 index 0000000000000000000000000000000000000000..4c9df60b7064a5f5d07a14bfab990206aec0d97c --- /dev/null +++ b/pool/shard004/C/0100548_net.c @@ -0,0 +1,168 @@ +/* $Header: /home/cvsroot/RT288x_SDK/source/user/watchdog-5.6/src/net.c,v 1.1 2009-10-14 06:32:06 steven Exp $ */ + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +#include +#include +#include +#include + +#include "extern.h" +#include "watch_err.h" + +#if USE_SYSLOG +#include +#endif + +/* + * in_cksum -- + * Checksum routine for Internet Protocol family headers (C Version) + */ +static int in_cksum(unsigned short *addr, int len) +{ + int nleft = len, sum = 0; + unsigned short *w = addr, answer = 0; + + /* + * Our algorithm is simple, using a 32 bit accumulator (sum), we add + * sequential 16 bit words to it, and at the end, fold back all the + * carry bits from the top 16 bits into the lower 16 bits. + */ + while (nleft > 1) { + sum += *w++; + nleft -= 2; + } /* mop up an odd byte, if necessary */ + if (nleft == 1) { + *(unsigned char *) (&answer) = *(unsigned char *) w; + sum += answer; + } + /* add back carry outs from top 16 bits to low 16 bits */ + sum = (sum >> 16) + (sum & 0xffff); /* add hi 16 to low 16 */ + sum += (sum >> 16); /* add carry */ + answer = ~sum; /* truncate to 16 bits */ + return (answer); +} + +int check_net(char *target, int sock_fp, struct sockaddr to, unsigned char *packet, int time, int count) +{ + int i; + unsigned char outpack[MAXPACKET]; + + if (target == NULL) + return (ENOERR); + + /* try "ping-count" times */ + for (i = 0; i < count; i++) { + + struct sockaddr_in from; + int fdmask, j; + socklen_t fromlen; + struct timeval timeout, dtimeout; + struct icmphdr *icp = (struct icmphdr *) outpack; + + /* setup a ping message */ + icp->type = ICMP_ECHO; + icp->code = icp->checksum = icp->un.echo.sequence = 0; + icp->un.echo.id = pid; /* ID */ + + /* compute ICMP checksum here */ + icp->checksum = in_cksum((unsigned short *) icp, DATALEN + 8); + + /* and send it out */ + j = sendto(sock_fp, (char *) outpack, DATALEN + 8, 0, &to, + sizeof(struct sockaddr)); + + if (j < 0) { + int err = errno; + + /* if our kernel tells us the network is unreachable we are done */ + if (err == ENETUNREACH) { +#if USE_SYSLOG + syslog(LOG_ERR, "network is unreachable (target: %s)", target); +#endif /* USE_SYSLOG */ + + return (ENETUNREACH); + + } else { +#if USE_SYSLOG + syslog(LOG_ERR, "sendto gave errno = %d = '%m'\n", err); +#else /* USE_SYSLOG */ + perror(progname); +#endif /* USE_SYSLOG */ + + if (softboot) + return (err); + } + + } else { + gettimeofday(&timeout, NULL); + /* set the timeout value */ + timeout.tv_sec += time / count; + + /* wait for reply */ + fdmask = 1 << sock_fp; + while(1) { + gettimeofday(&dtimeout, NULL); + dtimeout.tv_sec = timeout.tv_sec - dtimeout.tv_sec; + dtimeout.tv_usec = timeout.tv_usec - dtimeout.tv_usec; + if (dtimeout.tv_usec < 0) { + dtimeout.tv_usec += 1000000; + dtimeout.tv_sec--; + } + while (dtimeout.tv_usec >= 1000000) + { + dtimeout.tv_usec -= 1000000; + dtimeout.tv_sec++; + } + if (dtimeout.tv_sec <= 0) + break; +#if USE_SYSLOG + if (verbose && logtick && ticker == 1) + syslog(LOG_ERR, "ping select timeout = %ld seconds and %ld useconds\n", dtimeout.tv_sec, dtimeout.tv_usec); +#endif /* USE_SYSLOG */ + + if (select(sock_fp + 1, (fd_set *) & fdmask, (fd_set *) NULL, + (fd_set *) NULL, &dtimeout) >= 1) { + + /* read reply */ + fromlen = sizeof(from); + if (recvfrom(sock_fp, (char *) packet, DATALEN + MAXIPLEN + MAXICMPLEN, 0, + (struct sockaddr *) &from, &fromlen) < 0) { + int err = errno; + + if (err != EINTR) +#if USE_SYSLOG + syslog(LOG_ERR, "recvfrom gave errno = %d = '%m'\n", err); +#else /* USE_SYSLOG */ + perror(progname); +#endif /* USE_SYSLOG */ + if (softboot) + return (err); + + continue; + } + + /* check if packet is our ECHO */ + icp = (struct icmphdr *) (packet + (((struct ip *) packet)->ip_hl << 2)); + + if (icp->type == ICMP_ECHOREPLY && icp->un.echo.id == pid) { + if (from.sin_addr.s_addr == ((struct sockaddr_in *) &to)->sin_addr.s_addr) { +#if USE_SYSLOG + if (verbose && logtick && ticker == 1) + syslog(LOG_INFO, "got answer from target %s", target); +#endif + return (ENOERR); + } + } + } + } + } + } +#if USE_SYSLOG + syslog(LOG_ERR, "no response from ping (target: %s)", target); +#endif /* USE_SYSLOG */ + return (ENETUNREACH); +} + diff --git a/pool/shard004/C/0100549_time.c b/pool/shard004/C/0100549_time.c new file mode 100644 index 0000000000000000000000000000000000000000..829a96d4a179337019f1790ab2e50577f8cc3524 --- /dev/null +++ b/pool/shard004/C/0100549_time.c @@ -0,0 +1,128 @@ +/* + * linux/arch/arm/kernel/time.c + * + * Copyright (C) 1991, 1992, 1995 Linus Torvalds + * Modifications for ARM (C) 1994-2001 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. + * + * This file contains the ARM-specific time handling details: + * reading the RTC at bootup, etc... + */ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +#if defined(CONFIG_RTC_DRV_CMOS) || defined(CONFIG_RTC_DRV_CMOS_MODULE) || \ + defined(CONFIG_NVRAM) || defined(CONFIG_NVRAM_MODULE) +/* this needs a better home */ +DEFINE_SPINLOCK(rtc_lock); +EXPORT_SYMBOL(rtc_lock); +#endif /* pc-style 'CMOS' RTC support */ + +/* change this if you have some constant time drift */ +#define USECS_PER_JIFFY (1000000/HZ) + +#ifdef CONFIG_SMP +unsigned long profile_pc(struct pt_regs *regs) +{ + struct stackframe frame; + + if (!in_lock_functions(regs->ARM_pc)) + return regs->ARM_pc; + + frame.fp = regs->ARM_fp; + frame.sp = regs->ARM_sp; + frame.lr = regs->ARM_lr; + frame.pc = regs->ARM_pc; + do { + int ret = unwind_frame(&frame); + if (ret < 0) + return 0; + } while (in_lock_functions(frame.pc)); + + return frame.pc; +} +EXPORT_SYMBOL(profile_pc); +#endif + +#ifndef CONFIG_GENERIC_CLOCKEVENTS +/* + * Kernel system timer support. + */ +void timer_tick(void) +{ + profile_tick(CPU_PROFILING); + xtime_update(1); +#ifndef CONFIG_SMP + update_process_times(user_mode(get_irq_regs())); +#endif +} +#endif + +static void dummy_clock_access(struct timespec *ts) +{ + ts->tv_sec = 0; + ts->tv_nsec = 0; +} + +static clock_access_fn __read_persistent_clock = dummy_clock_access; +static clock_access_fn __read_boot_clock = dummy_clock_access;; + +void read_persistent_clock(struct timespec *ts) +{ + __read_persistent_clock(ts); +} + +void read_boot_clock(struct timespec *ts) +{ + __read_boot_clock(ts); +} + +int __init register_persistent_clock(clock_access_fn read_boot, + clock_access_fn read_persistent) +{ + /* Only allow the clockaccess functions to be registered once */ + if (__read_persistent_clock == dummy_clock_access && + __read_boot_clock == dummy_clock_access) { + if (read_boot) + __read_boot_clock = read_boot; + if (read_persistent) + __read_persistent_clock = read_persistent; + + return 0; + } + + return -EINVAL; +} + +void __init time_init(void) +{ + if (machine_desc->init_time) { + machine_desc->init_time(); + } else { +#ifdef CONFIG_COMMON_CLK + of_clk_init(NULL); +#endif + clocksource_of_init(); + } +} diff --git a/pool/shard004/C/0100560_nand.c b/pool/shard004/C/0100560_nand.c new file mode 100644 index 0000000000000000000000000000000000000000..873b3304a32d993e6f1d49b7a2fae124b7387fb0 --- /dev/null +++ b/pool/shard004/C/0100560_nand.c @@ -0,0 +1,152 @@ + + +#define MEM_SYS_CFG (*((volatile unsigned long *)0x7E00F120)) +#define NFCONF (*((volatile unsigned long *)0x70200000)) +#define NFCONT (*((volatile unsigned long *)0x70200004)) +#define NFCMMD (*((volatile unsigned long *)0x70200008)) +#define NFADDR (*((volatile unsigned long *)0x7020000C)) +#define NFDATA (*((volatile unsigned char *)0x70200010)) +#define NFSTAT (*((volatile unsigned long *)0x70200028)) + + +void nand_select(void) +{ + NFCONT &= ~(1<<1); +} + +void nand_deselect(void) +{ + NFCONT |= (1<<1); +} + + +void nand_cmd(unsigned char cmd) +{ + NFCMMD = cmd; +} + +void nand_addr(unsigned char addr) +{ + NFADDR = addr; +} + +unsigned char nand_get_data(void) +{ + return NFDATA; +} + +void wait_ready(void) +{ + while ((NFSTAT & 0x1) == 0); +} + +void nand_reset(void) +{ + /* Ñ¡ÖÐ */ + nand_select(); + + /* ·¢³ö0xffÃüÁî */ + nand_cmd(0xff); + + /* µÈ´ý¾ÍÐ÷ */ + wait_ready(); + + /* È¡ÏûÑ¡ÖÐ */ + nand_deselect(); +} + + +void nand_init(void) +{ + /* ÈÃxm0csn2ÓÃ×÷nand flash cs0 ƬѡÒý½Å */ + MEM_SYS_CFG &= ~(1<<1); + + /* ÉèÖÃʱ¼ä²ÎÊý */ +#define TACLS 0 +#define TWRPH0 1 +#define TWRPH1 0 + NFCONF &= ~((1<<30) | (7<<12) | (7<<8) | (7<<4)); + NFCONF |= ((TACLS<<12) | (TWRPH0<<8) | (TWRPH1<<4)); + + /* ʹÄÜnand flash controller */ + NFCONT |= 1; + + nand_reset(); +} + + +void nand_send_addr(unsigned int addr) +{ +#if 0 + unsigned int page = addr / 2048; + + /* ÕâÁ½¸öµØÖ·±íʾ´ÓÒ³ÄÚÄÄÀ↑ʼ */ + nand_addr(addr & 0xff); + nand_addr((addr >> 8) & 0xff); + + /* ÏÂÃæÈý¸öµØÖ·±íʾÄÄÒ»Ò³ */ + nand_addr(page & 0xff); + nand_addr((page >> 8) & 0xff); + nand_addr((page >> 16) & 0xff); +#else + nand_addr(addr & 0xff); /* a0~a7 */ + nand_addr((addr >> 8) & 0x7); /* ³ÌÐòµÄ½Ç¶È: a8~a10 */ + + nand_addr((addr >> 11) & 0xff); /* ³ÌÐòµÄ½Ç¶È: a11~a18 */ + nand_addr((addr >> 19) & 0xff); /* ³ÌÐòµÄ½Ç¶È: a19~a26 */ + nand_addr((addr >> 27) & 0xff); /* ³ÌÐòµÄ½Ç¶È: a27~ */ + +#endif +} + + +int nand_read(unsigned int nand_start, unsigned int ddr_start, unsigned int len) +{ + unsigned int addr = nand_start; + int i, count = 0; + unsigned char *dest = (unsigned char *)ddr_start; + + /* Ñ¡ÖÐоƬ */ + nand_select(); + + while (count < len) + { + /* ·¢³öÃüÁî0x00 */ + nand_cmd(0x00); + + /* ·¢³öµØÖ· */ + nand_send_addr(addr); + + /* ·¢³öÃüÁî0x30 */ + nand_cmd(0x30); + + /* µÈ´ý¾ÍÐ÷ */ + wait_ready(); + + /* ¶ÁÊý¾Ý */ + for (i = 0; i < 2048 && count < len; i++) + { + dest[count++] = nand_get_data(); + } + + addr += 2048; + } + + /* È¡ÏûƬѡ */ + nand_deselect(); + return 0; +} + +int copy2ddr(unsigned int nand_start, unsigned int ddr_start, unsigned int len) +{ + int ret; + + /* ³õʼ»¯nand flash controller */ + nand_init(); + + /* ¶Ánand flash */ + ret = nand_read(nand_start, ddr_start, len); + + return ret; +} + diff --git a/pool/shard004/C/0100565_saccept.c b/pool/shard004/C/0100565_saccept.c new file mode 100644 index 0000000000000000000000000000000000000000..0d173aa039a700cef5882704cc5373ca49b775e6 --- /dev/null +++ b/pool/shard004/C/0100565_saccept.c @@ -0,0 +1,106 @@ +/* NOCW */ +/* demos/bio/saccept.c */ + +/*- + * A minimal program to serve an SSL connection. + * It uses blocking. + * saccept host:port + * host is the interface IP to use. If any interface, use *:port + * The default it *:4433 + * + * cc -I../../include saccept.c -L../.. -lssl -lcrypto -ldl + */ + +#include +#include +#include +#include + +#define CERT_FILE "server.pem" + +BIO *in = NULL; + +void close_up() +{ + BIO_free(in); +} + +int main(int argc, char *argv[]) +{ + char *port = NULL; + BIO *ssl_bio, *tmp; + SSL_CTX *ctx; + char buf[512]; + int ret = 1, i; + + if (argc <= 1) + port = "*:4433"; + else + port = argv[1]; + + signal(SIGINT, close_up); + + SSL_load_error_strings(); + + /* Add ciphers and message digests */ + OpenSSL_add_ssl_algorithms(); + + ctx = SSL_CTX_new(TLS_server_method()); + if (!SSL_CTX_use_certificate_file(ctx, CERT_FILE, SSL_FILETYPE_PEM)) + goto err; + if (!SSL_CTX_use_PrivateKey_file(ctx, CERT_FILE, SSL_FILETYPE_PEM)) + goto err; + if (!SSL_CTX_check_private_key(ctx)) + goto err; + + /* Setup server side SSL bio */ + ssl_bio = BIO_new_ssl(ctx, 0); + + if ((in = BIO_new_accept(port)) == NULL) + goto err; + + /* + * This means that when a new connection is accepted on 'in', The ssl_bio + * will be 'duplicated' and have the new socket BIO push into it. + * Basically it means the SSL BIO will be automatically setup + */ + BIO_set_accept_bios(in, ssl_bio); + + again: + /* + * The first call will setup the accept socket, and the second will get a + * socket. In this loop, the first actual accept will occur in the + * BIO_read() function. + */ + + if (BIO_do_accept(in) <= 0) + goto err; + + for (;;) { + i = BIO_read(in, buf, 512); + if (i == 0) { + /* + * If we have finished, remove the underlying BIO stack so the + * next time we call any function for this BIO, it will attempt + * to do an accept + */ + printf("Done\n"); + tmp = BIO_pop(in); + BIO_free_all(tmp); + goto again; + } + if (i < 0) + goto err; + fwrite(buf, 1, i, stdout); + fflush(stdout); + } + + ret = 0; + err: + if (ret) { + ERR_print_errors_fp(stderr); + } + BIO_free(in); + exit(ret); + return (!ret); +} diff --git a/pool/shard004/C/0100568_encode3Valid.c b/pool/shard004/C/0100568_encode3Valid.c new file mode 100644 index 0000000000000000000000000000000000000000..c45c88e05a4bdb9d4d9cc4d662f50fbd200810cd --- /dev/null +++ b/pool/shard004/C/0100568_encode3Valid.c @@ -0,0 +1,162 @@ +/* Things to do with ENCODE 3 validation. */ + +/* Copyright (C) 2013 The Regents of the University of California + * See README in this or parent directory for licensing information. */ + +#include "common.h" +#include "hex.h" +#include "linefile.h" +#include "encode3/encode3Valid.h" + + +char *encode3CalcValidationKey(char *md5Hex, long long fileSize) +/* calculate validation key to discourage faking of validation. Do freeMem on + *result when done. */ +{ +if (strlen(md5Hex) != 32) + errAbort("Invalid md5Hex string: %s\n", md5Hex); +long long sum = 0; +sum += fileSize; +while (*md5Hex) + { + unsigned char n = hexToByte(md5Hex); + sum += n; + md5Hex += 2; + } +int vNum = sum % 10000; +char buf[256]; +safef(buf, sizeof buf, "V%d", vNum); +return cloneString(buf); +} + +static char *fileNameOnly(char *fullName) +/* Return just the fileName part of the path */ +{ +char *fileName = strrchr(fullName, '/'); +if (!fileName) + fileName = fullName; +return fileName; +} + +static void requireStartEndLines(char *fileName, char *startLine, char *endLine) +/* Make sure first real line in file is startLine, and last is endLine. Tolerate + * empty lines and white space. */ +{ +char *reportFileName = fileNameOnly(fileName); +struct lineFile *lf = lineFileOpen(fileName, TRUE); +char *line; + +/* Get first real line and make sure it is not empty and matches start line. */ +if (!lineFileNextReal(lf, &line)) + errAbort("%s is empty", reportFileName); +line = trimSpaces(line); +if (!sameString(line, startLine)) + errAbort("%s doesn't start with %s as expected", reportFileName, startLine); + +boolean lastSame = FALSE; + +for (;;) + { + if (!lineFileNextReal(lf, &line)) + break; + line = trimSpaces(line); + lastSame = sameString(line, endLine); + } +if (!lastSame) + errAbort("%s doesn't end with %s as expected", reportFileName, endLine); + +lineFileClose(&lf); +} + +void encode3ValidateRcc(char *path) +/* Validate a nanostring rcc file. */ +{ +requireStartEndLines(path, "
", ""); +} + +boolean fileStartsWithOneOfPair(char *fileName, char *one, char *two) +/* Return TRUE if file starts with either one of two strings. */ +{ +/* Figure out size of one and two strings. */ +int oneLen = strlen(one); +int twoLen = strlen(two); +int maxLen = max(oneLen, twoLen); +assert(maxLen > 0); +int bufLen = maxLen+1; +char buf[bufLen]; + +/* Open up file and try to read enough data */ +FILE *f = fopen(fileName, "r"); +if (f == NULL) + return FALSE; +int sizeRead = fread(buf, 1, maxLen, f); +carefulClose(&f); + +/* Return TRUE if we match one or two, otherwise FALSE. */ +if (oneLen >= sizeRead && memcmp(buf, one, oneLen) == 0) + return TRUE; +else if (twoLen >= sizeRead && memcmp(buf, two, twoLen) == 0) + return TRUE; +return FALSE; +} + +void encode3ValidateIdat(char *path) +/* Validate illumina idat file. */ +{ +if (!fileStartsWithOneOfPair(path, "IDAT", "DITA")) + errAbort("%s is not a valid .idat file, it does not start with IDAT or DITA", fileNameOnly(path)); +} + +boolean encode3IsGzipped(char *path) +/* Return TRUE if file at path starts with GZIP signature */ +{ +FILE *f = mustOpen(path, "r"); +int first = fgetc(f); +int second = fgetc(f); +carefulClose(&f); +return first == 0x1F && second == 0x8B; +} + +static char *edwSupportedEnrichedIn[] = {"unknown", "exon", "intron", "promoter", "coding", + "utr", "utr3", "utr5", "open"}; +static int edwSupportedEnrichedInCount = ArraySize(edwSupportedEnrichedIn); + +boolean encode3CheckEnrichedIn(char *enriched) +/* return TRUE if value is allowed */ +{ +return (stringArrayIx(enriched, edwSupportedEnrichedIn, edwSupportedEnrichedInCount) >= 0); +} + +struct encode3BedType encode3BedTypeTable[] = { + {"bedLogR", 9, 1}, + {"bedRnaElements", 6, 3}, + {"bedRrbs", 9, 2}, + {"bedMethyl", 9, 2}, + {"narrowPeak", 6, 4}, + {"broadPeak", 6, 3}, +}; + +int encode3BedTypeCount = ArraySize(encode3BedTypeTable); + +struct encode3BedType *encode3BedTypeMayFind(char *name) +/* Return encode3BedType of given name, just return NULL if not found. */ +{ +int i; +for (i=0; i +#include + +#ifndef HEAP_PROTECTION + #define _Heap_Protection_determine_block_free( heap, block ) true +#else + static void _Heap_Protection_delay_block_free( + Heap_Control *heap, + Heap_Block *block + ) + { + uintptr_t *const pattern_begin = (uintptr_t *) + _Heap_Alloc_area_of_block( block ); + uintptr_t *const pattern_end = (uintptr_t *) + ((uintptr_t) block + _Heap_Block_size( block ) + HEAP_ALLOC_BONUS); + uintptr_t const delayed_free_block_count = + heap->Protection.delayed_free_block_count; + uintptr_t *current = NULL; + + block->Protection_begin.next_delayed_free_block = block; + block->Protection_begin.task = _Thread_Executing; + + if ( delayed_free_block_count > 0 ) { + Heap_Block *const last = heap->Protection.last_delayed_free_block; + + last->Protection_begin.next_delayed_free_block = block; + } else { + heap->Protection.first_delayed_free_block = block; + } + heap->Protection.last_delayed_free_block = block; + heap->Protection.delayed_free_block_count = delayed_free_block_count + 1; + + for ( current = pattern_begin; current != pattern_end; ++current ) { + *current = HEAP_FREE_PATTERN; + } + } + + static void _Heap_Protection_check_free_block( + Heap_Control *heap, + Heap_Block *block + ) + { + uintptr_t *const pattern_begin = (uintptr_t *) + _Heap_Alloc_area_of_block( block ); + uintptr_t *const pattern_end = (uintptr_t *) + ((uintptr_t) block + _Heap_Block_size( block ) + HEAP_ALLOC_BONUS); + uintptr_t *current = NULL; + + for ( current = pattern_begin; current != pattern_end; ++current ) { + if ( *current != HEAP_FREE_PATTERN ) { + _Heap_Protection_block_error( heap, block ); + break; + } + } + } + + static bool _Heap_Protection_determine_block_free( + Heap_Control *heap, + Heap_Block *block + ) + { + bool do_free = true; + + /* + * Sometimes after a free the allocated area is still in use. An example + * is the task stack of a thread that deletes itself. The thread dispatch + * disable level is a way to detect this use case. + */ + if ( !_Thread_Dispatch_in_critical_section() ) { + Heap_Block *const next = block->Protection_begin.next_delayed_free_block; + if ( next == NULL ) { + _Heap_Protection_delay_block_free( heap, block ); + do_free = false; + } else if ( next == HEAP_PROTECTION_OBOLUS ) { + _Heap_Protection_check_free_block( heap, block ); + } else { + _Heap_Protection_block_error( heap, block ); + } + } + + return do_free; + } +#endif + +bool _Heap_Free( Heap_Control *heap, void *alloc_begin_ptr ) +{ + Heap_Statistics *const stats = &heap->stats; + uintptr_t alloc_begin; + Heap_Block *block; + Heap_Block *next_block = NULL; + uintptr_t block_size = 0; + uintptr_t next_block_size = 0; + bool next_is_free = false; + + /* + * If NULL return true so a free on NULL is considered a valid release. This + * is a special case that could be handled by the in heap check how-ever that + * would result in false being returned which is wrong. + */ + if ( alloc_begin_ptr == NULL ) { + return true; + } + + alloc_begin = (uintptr_t) alloc_begin_ptr; + block = _Heap_Block_of_alloc_area( alloc_begin, heap->page_size ); + + if ( !_Heap_Is_block_in_heap( heap, block ) ) { + return false; + } + + _Heap_Protection_block_check( heap, block ); + + block_size = _Heap_Block_size( block ); + next_block = _Heap_Block_at( block, block_size ); + + if ( !_Heap_Is_block_in_heap( heap, next_block ) ) { + return false; + } + + _Heap_Protection_block_check( heap, next_block ); + + if ( !_Heap_Is_prev_used( next_block ) ) { + _Heap_Protection_block_error( heap, block ); + return false; + } + + if ( !_Heap_Protection_determine_block_free( heap, block ) ) { + return true; + } + + next_block_size = _Heap_Block_size( next_block ); + next_is_free = next_block != heap->last_block + && !_Heap_Is_prev_used( _Heap_Block_at( next_block, next_block_size )); + + if ( !_Heap_Is_prev_used( block ) ) { + uintptr_t const prev_size = block->prev_size; + Heap_Block * const prev_block = _Heap_Block_at( block, -prev_size ); + + if ( !_Heap_Is_block_in_heap( heap, prev_block ) ) { + _HAssert( false ); + return( false ); + } + + /* As we always coalesce free blocks, the block that preceedes prev_block + must have been used. */ + if ( !_Heap_Is_prev_used ( prev_block) ) { + _HAssert( false ); + return( false ); + } + + if ( next_is_free ) { /* coalesce both */ + uintptr_t const size = block_size + prev_size + next_block_size; + _Heap_Free_list_remove( next_block ); + stats->free_blocks -= 1; + prev_block->size_and_flag = size | HEAP_PREV_BLOCK_USED; + next_block = _Heap_Block_at( prev_block, size ); + _HAssert(!_Heap_Is_prev_used( next_block)); + next_block->prev_size = size; + } else { /* coalesce prev */ + uintptr_t const size = block_size + prev_size; + prev_block->size_and_flag = size | HEAP_PREV_BLOCK_USED; + next_block->size_and_flag &= ~HEAP_PREV_BLOCK_USED; + next_block->prev_size = size; + } + } else if ( next_is_free ) { /* coalesce next */ + uintptr_t const size = block_size + next_block_size; + _Heap_Free_list_replace( next_block, block ); + block->size_and_flag = size | HEAP_PREV_BLOCK_USED; + next_block = _Heap_Block_at( block, size ); + next_block->prev_size = size; + } else { /* no coalesce */ + /* Add 'block' to the head of the free blocks list as it tends to + produce less fragmentation than adding to the tail. */ + _Heap_Free_list_insert_after( _Heap_Free_list_head( heap), block ); + block->size_and_flag = block_size | HEAP_PREV_BLOCK_USED; + next_block->size_and_flag &= ~HEAP_PREV_BLOCK_USED; + next_block->prev_size = block_size; + + /* Statistics */ + ++stats->free_blocks; + if ( stats->max_free_blocks < stats->free_blocks ) { + stats->max_free_blocks = stats->free_blocks; + } + } + + /* Statistics */ + --stats->used_blocks; + ++stats->frees; + stats->free_size += block_size; + + return( true ); +} diff --git a/pool/shard004/C/0100579_intc.c b/pool/shard004/C/0100579_intc.c new file mode 100644 index 0000000000000000000000000000000000000000..3590137081bfe1a0292536b11d10ab9711d11f48 --- /dev/null +++ b/pool/shard004/C/0100579_intc.c @@ -0,0 +1,162 @@ +/* + * Copyright (C) 2007-2009 Michal Simek + * Copyright (C) 2007-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 + +#ifdef CONFIG_SELFMOD_INTC +#include +#define INTC_BASE BARRIER_BASE_ADDR +#else +static unsigned int intc_baseaddr; +#define INTC_BASE intc_baseaddr +#endif + +#define ISR 0x00 +#define IPR 0x04 +#define IER 0x08 +#define IAR 0x0c +#define SIE 0x10 +#define CIE 0x14 +#define IVR 0x18 +#define MER 0x1c + +#define MER_ME (1<<0) +#define MER_HIE (1<<1) + +static void intc_enable_or_unmask(struct irq_data *d) +{ + unsigned long mask = 1 << d->hwirq; + + pr_debug("enable_or_unmask: %ld\n", d->hwirq); + out_be32(INTC_BASE + SIE, mask); + + if (irqd_is_level_type(d)) + out_be32(INTC_BASE + IAR, mask); +} + +static void intc_disable_or_mask(struct irq_data *d) +{ + pr_debug("disable: %ld\n", d->hwirq); + out_be32(INTC_BASE + CIE, 1 << d->hwirq); +} + +static void intc_ack(struct irq_data *d) +{ + pr_debug("ack: %ld\n", d->hwirq); + out_be32(INTC_BASE + IAR, 1 << d->hwirq); +} + +static void intc_mask_ack(struct irq_data *d) +{ + unsigned long mask = 1 << d->hwirq; + + pr_debug("disable_and_ack: %ld\n", d->hwirq); + out_be32(INTC_BASE + CIE, mask); + out_be32(INTC_BASE + IAR, mask); +} + +static struct irq_chip intc_dev = { + .name = "Xilinx INTC", + .irq_unmask = intc_enable_or_unmask, + .irq_mask = intc_disable_or_mask, + .irq_ack = intc_ack, + .irq_mask_ack = intc_mask_ack, +}; + +static struct irq_domain *root_domain; + +unsigned int get_irq(void) +{ + unsigned int hwirq, irq = -1; + + hwirq = in_be32(INTC_BASE + IVR); + if (hwirq != -1U) + irq = irq_find_mapping(root_domain, hwirq); + + pr_debug("get_irq: hwirq=%d, irq=%d\n", hwirq, irq); + + return irq; +} + +int xintc_map(struct irq_domain *d, unsigned int irq, irq_hw_number_t hw) +{ + u32 intr_mask = (u32)d->host_data; + + if (intr_mask & (1 << hw)) { + irq_set_chip_and_handler_name(irq, &intc_dev, + handle_edge_irq, "edge"); + irq_clear_status_flags(irq, IRQ_LEVEL); + } else { + irq_set_chip_and_handler_name(irq, &intc_dev, + handle_level_irq, "level"); + irq_set_status_flags(irq, IRQ_LEVEL); + } + return 0; +} + +static const struct irq_domain_ops xintc_irq_domain_ops = { + .xlate = irq_domain_xlate_onetwocell, + .map = xintc_map, +}; + +void __init init_IRQ(void) +{ + u32 nr_irq, intr_mask; + struct device_node *intc = NULL; +#ifdef CONFIG_SELFMOD_INTC + unsigned int intc_baseaddr = 0; + static int arr_func[] = { + (int)&get_irq, + (int)&intc_enable_or_unmask, + (int)&intc_disable_or_mask, + (int)&intc_mask_ack, + (int)&intc_ack, + (int)&intc_end, + 0 + }; +#endif + intc = of_find_compatible_node(NULL, NULL, "xlnx,xps-intc-1.00.a"); + BUG_ON(!intc); + + intc_baseaddr = be32_to_cpup(of_get_property(intc, "reg", NULL)); + intc_baseaddr = (unsigned long) ioremap(intc_baseaddr, PAGE_SIZE); + nr_irq = be32_to_cpup(of_get_property(intc, + "xlnx,num-intr-inputs", NULL)); + + intr_mask = + be32_to_cpup(of_get_property(intc, "xlnx,kind-of-intr", NULL)); + if (intr_mask > (u32)((1ULL << nr_irq) - 1)) + printk(KERN_INFO " ERROR: Mismatch in kind-of-intr param\n"); + +#ifdef CONFIG_SELFMOD_INTC + selfmod_function((int *) arr_func, intc_baseaddr); +#endif + printk(KERN_INFO "%s #0 at 0x%08x, num_irq=%d, edge=0x%x\n", + intc->name, intc_baseaddr, nr_irq, intr_mask); + + out_be32(intc_baseaddr + IER, 0); + + + out_be32(intc_baseaddr + IAR, 0xffffffff); + + + out_be32(intc_baseaddr + MER, MER_HIE | MER_ME); + + root_domain = irq_domain_add_linear(intc, nr_irq, &xintc_irq_domain_ops, + (void *)intr_mask); +} diff --git a/pool/shard004/C/0100581_cmd_line_opts.c b/pool/shard004/C/0100581_cmd_line_opts.c new file mode 100644 index 0000000000000000000000000000000000000000..4d1ba4c1705df5bb7570cff278338475cdb4360c --- /dev/null +++ b/pool/shard004/C/0100581_cmd_line_opts.c @@ -0,0 +1,92 @@ +#include "cmd_line_opts.h" + +#include +#include + +int co_get_int(int argc, char** argv, const char* text, int* res) { + int opt_len = strlen(text); + int found = 0; + + int ii; + for(ii = 0; ii < argc; ++ii) { + if( argv[ii][0] == '-' ) { + if(!strncmp(text, argv[ii], opt_len)) { + *res = atoi(argv[ii+1]); + found = 1; + break; + } + + else { + ++ii; + } + } + } + + return found; +} + +int co_get_bool(int argc, char** argv, const char* text, int* res) { + int opt_len = strlen(text); + int found = 0; + + int ii; + for(ii = 0; ii < argc; ++ii) { + if( argv[ii][0] == '-' ) { + if(!strncmp(text, argv[ii], opt_len)) { + *res = 1; + found = 1; + break; + } + + else { + ++ii; + } + } + } + + return found; +} + +int co_get_float(int argc, char** argv, const char* text, float* res) { + int opt_len = strlen(text); + int found = 0; + + int ii; + for(ii = 0; ii < argc; ++ii) { + if( argv[ii][0] == '-' ) { + if(!strncmp(text, argv[ii], opt_len)) { + *res = atof(argv[ii+1]); + found = 1; + break; + } + + else { + ++ii; + } + } + } + + return found; +} + +int co_get_string(int argc, char** argv, const char* text, char* * res) { + int opt_len = strlen(text); + int found = 0; + + int ii; + for(ii = 0; ii < argc; ++ii) { + if( argv[ii][0] == '-' ) { + if(!strncmp(text, argv[ii], opt_len)) { + *res = argv[ii+1]; + found = 1; + break; + } + + else { + ++ii; + } + } + } + + return found; +} diff --git a/pool/shard004/C/0100587_lj_udata.c b/pool/shard004/C/0100587_lj_udata.c new file mode 100644 index 0000000000000000000000000000000000000000..b2ea8031cd4ff5a46b5c5f8e657f7df0a68dad16 --- /dev/null +++ b/pool/shard004/C/0100587_lj_udata.c @@ -0,0 +1,61 @@ +/* +** Userdata handling. +** Copyright (C) 2005-2021 Mike Pall. See Copyright Notice in luajit.h +*/ + +#define lj_udata_c +#define LUA_CORE + +#include "lj_obj.h" +#include "lj_gc.h" +#include "lj_err.h" +#include "lj_udata.h" + +GCudata *lj_udata_new(lua_State *L, MSize sz, GCtab *env) +{ + GCudata *ud = lj_mem_newt(L, sizeof(GCudata) + sz, GCudata); + global_State *g = G(L); + newwhite(g, ud); /* Not finalized. */ + ud->gct = ~LJ_TUDATA; + ud->udtype = UDTYPE_USERDATA; + ud->len = sz; + /* NOBARRIER: The GCudata is new (marked white). */ + setgcrefnull(ud->metatable); + setgcref(ud->env, obj2gco(env)); + /* Chain to userdata list (after main thread). */ + setgcrefr(ud->nextgc, mainthread(g)->nextgc); + setgcref(mainthread(g)->nextgc, obj2gco(ud)); + return ud; +} + +void LJ_FASTCALL lj_udata_free(global_State *g, GCudata *ud) +{ + lj_mem_free(g, ud, sizeudata(ud)); +} + +#if LJ_64 +void *lj_lightud_intern(lua_State *L, void *p) +{ + global_State *g = G(L); + uint64_t u = (uint64_t)p; + uint32_t up = lightudup(u); + uint32_t *segmap = mref(g->gc.lightudseg, uint32_t); + MSize segnum = g->gc.lightudnum; + if (segmap) { + MSize seg; + for (seg = 0; seg <= segnum; seg++) + if (segmap[seg] == up) /* Fast path. */ + return (void *)(((uint64_t)seg << LJ_LIGHTUD_BITS_LO) | lightudlo(u)); + segnum++; + } + if (!((segnum-1) & segnum) && segnum != 1) { + if (segnum >= (1 << LJ_LIGHTUD_BITS_SEG)) lj_err_msg(L, LJ_ERR_BADLU); + lj_mem_reallocvec(L, segmap, segnum, segnum ? 2*segnum : 2u, uint32_t); + setmref(g->gc.lightudseg, segmap); + } + g->gc.lightudnum = segnum; + segmap[segnum] = up; + return (void *)(((uint64_t)segnum << LJ_LIGHTUD_BITS_LO) | lightudlo(u)); +} +#endif + diff --git a/pool/shard004/C/0100591_window.c b/pool/shard004/C/0100591_window.c new file mode 100644 index 0000000000000000000000000000000000000000..cee410d8b9f88f56b7f76a0cfaa722ab202bc941 --- /dev/null +++ b/pool/shard004/C/0100591_window.c @@ -0,0 +1,81 @@ +#include +#include +#include + + +int start_child(char *cmd, FILE **readpipe, FILE **writepipe); + + +void main(int argc, char **argv) +{ + char *source_path = "/home/tkr/SYMPHONY/DrawGraph/IGD_1.0/"; + char *graph_name = NULL; + FILE *read_from, *write_to; + int childpid; + + if (argc > 1) + graph_name = argv[1]; + + /* fork the wish shell */ + childpid = start_child((char *)"wish", &read_from, &write_to); + + /* source the tcl script into wish and invoke Igd_StartUp */ + fprintf(write_to, "source %s/Init.tcl\n", source_path); + fprintf(write_to, "source %s/Tools.tcl\n", source_path); + fprintf(write_to, "source %s/NodeEdgeBasics.tcl\n", source_path); + fprintf(write_to, "source %s/FileMenu.tcl\n", source_path); + fprintf(write_to, "source %s/WindowMenu.tcl\n", source_path); + fprintf(write_to, "source %s/NodeMenu.tcl\n", source_path); + fprintf(write_to, "source %s/EdgeMenu.tcl\n", source_path); + fprintf(write_to, "Igd_StartUp\n"); + fprintf(write_to, "Igd_CopyApplDefaultToWindow 1\n"); + fprintf(write_to, "Igd_InitWindow 1 first\n"); + fprintf(write_to, "Igd_DisplayWindow 1\n"); + if (graph_name) + fprintf(write_to, "Igd_LoadGraph 1 %s\n", graph_name); +} + + +/***************************************************************************** + * Exec the named cmd as a child process, returning two pipes to + * communicate with the process, and the child's process ID. + *****************************************************************************/ + +int start_child(char *cmd, FILE **readpipe, FILE **writepipe) +{ + int childpid, pipe1[2], pipe2[2]; + + if ((pipe(pipe1) < 0) || (pipe(pipe2) < 0)){ + perror("pipe"); + exit(-1); + } + + if ((childpid = vfork()) < 0){ + perror("fork"); + exit(-1); + }else if (childpid > 0){ /* parent */ + close(pipe1[0]); + close(pipe2[1]); + /* write to child is pipe1[1], read from child is pipe2[0] */ + *readpipe = fdopen(pipe2[0], "r"); + /* this sets the pipe to be a Non-Blocking IO one, so fgets won't wait + * until it receives a line. */ + fcntl(pipe2[0], F_SETFL, O_NONBLOCK); + *writepipe = fdopen(pipe1[1], "w"); + setlinebuf(*writepipe); + return(childpid); + }else{ /* child */ + close(pipe1[1]); + close(pipe2[0]); + /* read from parent is pipe1[0], write to parent is pipe2[1] */ + dup2(pipe1[0], 0); + dup2(pipe2[1], 1); + close(pipe1[0]); + close(pipe2[1]); + if (execlp(cmd, cmd, NULL) < 0) + perror("execlp"); + + /* never returns */ + } + return(0); +} diff --git a/pool/shard004/C/0100596_keycombo.c b/pool/shard004/C/0100596_keycombo.c new file mode 100644 index 0000000000000000000000000000000000000000..2fba451b91d594a40c0a7223d457d1e6b346bfbf --- /dev/null +++ b/pool/shard004/C/0100596_keycombo.c @@ -0,0 +1,261 @@ +/* drivers/input/keycombo.c + * + * Copyright (C) 2014 Google, Inc. + * + * This software is licensed under the terms of the GNU General Public + * License version 2, as published by the Free Software Foundation, and + * may be copied, distributed, and modified under those terms. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + */ + +#include +#include +#include +#include +#include +#include +#include + +struct keycombo_state { + struct input_handler input_handler; + unsigned long keybit[BITS_TO_LONGS(KEY_CNT)]; + unsigned long upbit[BITS_TO_LONGS(KEY_CNT)]; + unsigned long key[BITS_TO_LONGS(KEY_CNT)]; + spinlock_t lock; + struct workqueue_struct *wq; + int key_down_target; + int key_down; + int key_up; + struct delayed_work key_down_work; + int delay; + struct work_struct key_up_work; + void (*key_up_fn)(void *); + void (*key_down_fn)(void *); + void *priv; + int key_is_down; + struct wakeup_source combo_held_wake_source; + struct wakeup_source combo_up_wake_source; +}; + +static void do_key_down(struct work_struct *work) +{ + struct delayed_work *dwork = container_of(work, struct delayed_work, + work); + struct keycombo_state *state = container_of(dwork, + struct keycombo_state, key_down_work); + if (state->key_down_fn) + state->key_down_fn(state->priv); +} + +static void do_key_up(struct work_struct *work) +{ + struct keycombo_state *state = container_of(work, struct keycombo_state, + key_up_work); + if (state->key_up_fn) + state->key_up_fn(state->priv); + __pm_relax(&state->combo_up_wake_source); +} + +static void keycombo_event(struct input_handle *handle, unsigned int type, + unsigned int code, int value) +{ + unsigned long flags; + struct keycombo_state *state = handle->private; + + if (type != EV_KEY) + return; + + if (code >= KEY_MAX) + return; + + if (!test_bit(code, state->keybit)) + return; + + spin_lock_irqsave(&state->lock, flags); + if (!test_bit(code, state->key) == !value) + goto done; + __change_bit(code, state->key); + if (test_bit(code, state->upbit)) { + if (value) + state->key_up++; + else + state->key_up--; + } else { + if (value) + state->key_down++; + else + state->key_down--; + } + if (state->key_down == state->key_down_target && state->key_up == 0) { + __pm_stay_awake(&state->combo_held_wake_source); + state->key_is_down = 1; + if (queue_delayed_work(state->wq, &state->key_down_work, + state->delay)) + pr_debug("Key down work already queued!"); + } else if (state->key_is_down) { + if (!cancel_delayed_work(&state->key_down_work)) { + __pm_stay_awake(&state->combo_up_wake_source); + queue_work(state->wq, &state->key_up_work); + } + __pm_relax(&state->combo_held_wake_source); + state->key_is_down = 0; + } +done: + spin_unlock_irqrestore(&state->lock, flags); +} + +static int keycombo_connect(struct input_handler *handler, + struct input_dev *dev, + const struct input_device_id *id) +{ + int i; + int ret; + struct input_handle *handle; + struct keycombo_state *state = + container_of(handler, struct keycombo_state, input_handler); + for (i = 0; i < KEY_MAX; i++) { + if (test_bit(i, state->keybit) && test_bit(i, dev->keybit)) + break; + } + if (i == KEY_MAX) + return -ENODEV; + + handle = kzalloc(sizeof(*handle), GFP_KERNEL); + if (!handle) + return -ENOMEM; + + handle->dev = dev; + handle->handler = handler; + handle->name = KEYCOMBO_NAME; + handle->private = state; + + ret = input_register_handle(handle); + if (ret) + goto err_input_register_handle; + + ret = input_open_device(handle); + if (ret) + goto err_input_open_device; + + return 0; + +err_input_open_device: + input_unregister_handle(handle); +err_input_register_handle: + kfree(handle); + return ret; +} + +static void keycombo_disconnect(struct input_handle *handle) +{ + input_close_device(handle); + input_unregister_handle(handle); + kfree(handle); +} + +static const struct input_device_id keycombo_ids[] = { + { + .flags = INPUT_DEVICE_ID_MATCH_EVBIT, + .evbit = { BIT_MASK(EV_KEY) }, + }, + { }, +}; +MODULE_DEVICE_TABLE(input, keycombo_ids); + +static int keycombo_probe(struct platform_device *pdev) +{ + int ret; + int key, *keyp; + struct keycombo_state *state; + struct keycombo_platform_data *pdata = pdev->dev.platform_data; + + if (!pdata) + return -EINVAL; + + state = kzalloc(sizeof(*state), GFP_KERNEL); + if (!state) + return -ENOMEM; + + spin_lock_init(&state->lock); + keyp = pdata->keys_down; + while ((key = *keyp++)) { + if (key >= KEY_MAX) + continue; + state->key_down_target++; + __set_bit(key, state->keybit); + } + if (pdata->keys_up) { + keyp = pdata->keys_up; + while ((key = *keyp++)) { + if (key >= KEY_MAX) + continue; + __set_bit(key, state->keybit); + __set_bit(key, state->upbit); + } + } + + state->wq = alloc_ordered_workqueue("keycombo", 0); + if (!state->wq) + return -ENOMEM; + + state->priv = pdata->priv; + + if (pdata->key_down_fn) + state->key_down_fn = pdata->key_down_fn; + INIT_DELAYED_WORK(&state->key_down_work, do_key_down); + + if (pdata->key_up_fn) + state->key_up_fn = pdata->key_up_fn; + INIT_WORK(&state->key_up_work, do_key_up); + + wakeup_source_init(&state->combo_held_wake_source, "key combo"); + wakeup_source_init(&state->combo_up_wake_source, "key combo up"); + state->delay = msecs_to_jiffies(pdata->key_down_delay); + + state->input_handler.event = keycombo_event; + state->input_handler.connect = keycombo_connect; + state->input_handler.disconnect = keycombo_disconnect; + state->input_handler.name = KEYCOMBO_NAME; + state->input_handler.id_table = keycombo_ids; + ret = input_register_handler(&state->input_handler); + if (ret) { + kfree(state); + return ret; + } + platform_set_drvdata(pdev, state); + return 0; +} + +int keycombo_remove(struct platform_device *pdev) +{ + struct keycombo_state *state = platform_get_drvdata(pdev); + input_unregister_handler(&state->input_handler); + destroy_workqueue(state->wq); + kfree(state); + return 0; +} + + +struct platform_driver keycombo_driver = { + .driver.name = KEYCOMBO_NAME, + .probe = keycombo_probe, + .remove = keycombo_remove, +}; + +static int __init keycombo_init(void) +{ + return platform_driver_register(&keycombo_driver); +} + +static void __exit keycombo_exit(void) +{ + return platform_driver_unregister(&keycombo_driver); +} + +module_init(keycombo_init); +module_exit(keycombo_exit); diff --git a/pool/shard004/C/0100602_evsci.c b/pool/shard004/C/0100602_evsci.c new file mode 100644 index 0000000000000000000000000000000000000000..9e9e3454d8932c9c44f853bbe3d05edffeb38130 --- /dev/null +++ b/pool/shard004/C/0100602_evsci.c @@ -0,0 +1,250 @@ +/******************************************************************************* + * + * Module Name: evsci - System Control Interrupt configuration and + * legacy to ACPI mode state transition functions + * + ******************************************************************************/ + +/* + * Copyright (C) 2000 - 2013, Intel Corp. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions, and the following disclaimer, + * without modification. + * 2. Redistributions in binary form must reproduce at minimum a disclaimer + * substantially similar to the "NO WARRANTY" disclaimer below + * ("Disclaimer") and any redistribution must be conditioned upon + * including a substantially similar Disclaimer requirement for further + * binary redistribution. + * 3. Neither the names of the above-listed copyright holders nor the names + * of any contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * Alternatively, this software may be distributed under the terms of the + * GNU General Public License ("GPL") version 2 as published by the Free + * Software Foundation. + * + * NO WARRANTY + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * HOLDERS OR CONTRIBUTORS BE LIABLE FOR SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, + * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGES. + */ + +#include +#include "accommon.h" +#include "acevents.h" + +#define _COMPONENT ACPI_EVENTS +ACPI_MODULE_NAME("evsci") +#if (!ACPI_REDUCED_HARDWARE) /* Entire module */ +/* Local prototypes */ +static u32 ACPI_SYSTEM_XFACE acpi_ev_sci_xrupt_handler(void *context); + +/******************************************************************************* + * + * FUNCTION: acpi_ev_sci_dispatch + * + * PARAMETERS: None + * + * RETURN: Status code indicates whether interrupt was handled. + * + * DESCRIPTION: Dispatch the SCI to all host-installed SCI handlers. + * + ******************************************************************************/ + +u32 acpi_ev_sci_dispatch(void) +{ + struct acpi_sci_handler_info *sci_handler; + acpi_cpu_flags flags; + u32 int_status = ACPI_INTERRUPT_NOT_HANDLED; + + ACPI_FUNCTION_NAME(ev_sci_dispatch); + + /* Are there any host-installed SCI handlers? */ + + if (!acpi_gbl_sci_handler_list) { + return (int_status); + } + + flags = acpi_os_acquire_lock(acpi_gbl_gpe_lock); + + /* Invoke all host-installed SCI handlers */ + + sci_handler = acpi_gbl_sci_handler_list; + while (sci_handler) { + + /* Invoke the installed handler (at interrupt level) */ + + int_status |= sci_handler->address(sci_handler->context); + + sci_handler = sci_handler->next; + } + + acpi_os_release_lock(acpi_gbl_gpe_lock, flags); + return (int_status); +} + +/******************************************************************************* + * + * FUNCTION: acpi_ev_sci_xrupt_handler + * + * PARAMETERS: context - Calling Context + * + * RETURN: Status code indicates whether interrupt was handled. + * + * DESCRIPTION: Interrupt handler that will figure out what function or + * control method to call to deal with a SCI. + * + ******************************************************************************/ + +static u32 ACPI_SYSTEM_XFACE acpi_ev_sci_xrupt_handler(void *context) +{ + struct acpi_gpe_xrupt_info *gpe_xrupt_list = context; + u32 interrupt_handled = ACPI_INTERRUPT_NOT_HANDLED; + + ACPI_FUNCTION_TRACE(ev_sci_xrupt_handler); + + /* + * We are guaranteed by the ACPI CA initialization/shutdown code that + * if this interrupt handler is installed, ACPI is enabled. + */ + + /* + * Fixed Events: + * Check for and dispatch any Fixed Events that have occurred + */ + interrupt_handled |= acpi_ev_fixed_event_detect(); + + /* + * General Purpose Events: + * Check for and dispatch any GPEs that have occurred + */ + interrupt_handled |= acpi_ev_gpe_detect(gpe_xrupt_list); + + /* Invoke all host-installed SCI handlers */ + + interrupt_handled |= acpi_ev_sci_dispatch(); + + acpi_sci_count++; + return_UINT32(interrupt_handled); +} + +/******************************************************************************* + * + * FUNCTION: acpi_ev_gpe_xrupt_handler + * + * PARAMETERS: context - Calling Context + * + * RETURN: Status code indicates whether interrupt was handled. + * + * DESCRIPTION: Handler for GPE Block Device interrupts + * + ******************************************************************************/ + +u32 ACPI_SYSTEM_XFACE acpi_ev_gpe_xrupt_handler(void *context) +{ + struct acpi_gpe_xrupt_info *gpe_xrupt_list = context; + u32 interrupt_handled = ACPI_INTERRUPT_NOT_HANDLED; + + ACPI_FUNCTION_TRACE(ev_gpe_xrupt_handler); + + /* + * We are guaranteed by the ACPICA initialization/shutdown code that + * if this interrupt handler is installed, ACPI is enabled. + */ + + /* GPEs: Check for and dispatch any GPEs that have occurred */ + + interrupt_handled |= acpi_ev_gpe_detect(gpe_xrupt_list); + return_UINT32(interrupt_handled); +} + +/****************************************************************************** + * + * FUNCTION: acpi_ev_install_sci_handler + * + * PARAMETERS: none + * + * RETURN: Status + * + * DESCRIPTION: Installs SCI handler. + * + ******************************************************************************/ + +u32 acpi_ev_install_sci_handler(void) +{ + u32 status = AE_OK; + + ACPI_FUNCTION_TRACE(ev_install_sci_handler); + + status = + acpi_os_install_interrupt_handler((u32) acpi_gbl_FADT.sci_interrupt, + acpi_ev_sci_xrupt_handler, + acpi_gbl_gpe_xrupt_list_head); + return_ACPI_STATUS(status); +} + +/****************************************************************************** + * + * FUNCTION: acpi_ev_remove_all_sci_handlers + * + * PARAMETERS: none + * + * RETURN: AE_OK if handler uninstalled, AE_ERROR if handler was not + * installed to begin with + * + * DESCRIPTION: Remove the SCI interrupt handler. No further SCIs will be + * taken. Remove all host-installed SCI handlers. + * + * Note: It doesn't seem important to disable all events or set the event + * enable registers to their original values. The OS should disable + * the SCI interrupt level when the handler is removed, so no more + * events will come in. + * + ******************************************************************************/ + +acpi_status acpi_ev_remove_all_sci_handlers(void) +{ + struct acpi_sci_handler_info *sci_handler; + acpi_cpu_flags flags; + acpi_status status; + + ACPI_FUNCTION_TRACE(ev_remove_all_sci_handlers); + + /* Just let the OS remove the handler and disable the level */ + + status = + acpi_os_remove_interrupt_handler((u32) acpi_gbl_FADT.sci_interrupt, + acpi_ev_sci_xrupt_handler); + + if (!acpi_gbl_sci_handler_list) { + return (status); + } + + flags = acpi_os_acquire_lock(acpi_gbl_gpe_lock); + + /* Free all host-installed SCI handlers */ + + while (acpi_gbl_sci_handler_list) { + sci_handler = acpi_gbl_sci_handler_list; + acpi_gbl_sci_handler_list = sci_handler->next; + ACPI_FREE(sci_handler); + } + + acpi_os_release_lock(acpi_gbl_gpe_lock, flags); + return_ACPI_STATUS(status); +} + +#endif /* !ACPI_REDUCED_HARDWARE */ diff --git a/pool/shard004/C/0100608_vGfx.c b/pool/shard004/C/0100608_vGfx.c new file mode 100644 index 0000000000000000000000000000000000000000..b13f99e5094c199b5e76ab4802f747d8e20c0102 --- /dev/null +++ b/pool/shard004/C/0100608_vGfx.c @@ -0,0 +1,51 @@ +/* vGfx - interface to polymorphic graphic object + * that currently can either be a memory buffer or + * a postScript file. */ + +/* Copyright (C) 2011 The Regents of the University of California + * See README in this or parent directory for licensing information. */ + +#include "common.h" +#include "vGfx.h" + +/* Most of the implementation of this is in macros in vGfx.h. */ + +void vgClose(struct vGfx **pVg) +/* Close down virtual graphics object, and finish writing it to file. */ +{ +struct vGfx *vg = *pVg; +if (vg != NULL) + { + vg->close(&vg->data); + freez(pVg); + } +} + +struct vGfx *vgHalfInit(int width, int height) +/* Close down virtual graphics object, and finish writing it to file. */ +{ +struct vGfx *vg; +AllocVar(vg); +vg->width = width; +vg->height = height; +return vg; +} + +int vgFindRgb(struct vGfx *vg, struct rgbColor *rgb) +/* Find color index corresponding to rgb color. */ +{ +return vgFindColorIx(vg, rgb->r, rgb->g, rgb->b); +} + +Color vgContrastingColor(struct vGfx *vg, int backgroundIx) +/* Return black or white whichever would be more visible over + * background. */ +{ +struct rgbColor c = vgColorIxToRgb(vg, backgroundIx); +int val = (int)c.r + c.g + c.g + c.b; +if (val > 512) + return MG_BLACK; +else + return MG_WHITE; +} + diff --git a/pool/shard004/C/0100623_pl031.c b/pool/shard004/C/0100623_pl031.c new file mode 100644 index 0000000000000000000000000000000000000000..11ecf73284e9a03b2de60291f7f669fba5158ab4 --- /dev/null +++ b/pool/shard004/C/0100623_pl031.c @@ -0,0 +1,212 @@ +/* + * ARM AMBA PrimeCell PL031 RTC + * + * Copyright (c) 2007 CodeSourcery + * + * This file 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 "sysbus.h" +#include "qemu-timer.h" + +//#define DEBUG_PL031 + +#ifdef DEBUG_PL031 +#define DPRINTF(fmt, ...) \ +do { printf("pl031: " fmt , ## __VA_ARGS__); } while (0) +#else +#define DPRINTF(fmt, ...) do {} while(0) +#endif + +#define RTC_DR 0x00 /* Data read register */ +#define RTC_MR 0x04 /* Match register */ +#define RTC_LR 0x08 /* Data load register */ +#define RTC_CR 0x0c /* Control register */ +#define RTC_IMSC 0x10 /* Interrupt mask and set register */ +#define RTC_RIS 0x14 /* Raw interrupt status register */ +#define RTC_MIS 0x18 /* Masked interrupt status register */ +#define RTC_ICR 0x1c /* Interrupt clear register */ + +typedef struct { + SysBusDevice busdev; + QEMUTimer *timer; + qemu_irq irq; + + uint32_t tick_offset; + + uint32_t mr; + uint32_t lr; + uint32_t cr; + uint32_t im; + uint32_t is; +} pl031_state; + +static const unsigned char pl031_id[] = { + 0x31, 0x10, 0x14, 0x00, /* Device ID */ + 0x0d, 0xf0, 0x05, 0xb1 /* Cell ID */ +}; + +static void pl031_update(pl031_state *s) +{ + qemu_set_irq(s->irq, s->is & s->im); +} + +static void pl031_interrupt(void * opaque) +{ + pl031_state *s = (pl031_state *)opaque; + + s->im = 1; + DPRINTF("Alarm raised\n"); + pl031_update(s); +} + +static uint32_t pl031_get_count(pl031_state *s) +{ + /* This assumes qemu_get_clock returns the time since the machine was + created. */ + return s->tick_offset + qemu_get_clock(vm_clock) / ticks_per_sec; +} + +static void pl031_set_alarm(pl031_state *s) +{ + int64_t now; + uint32_t ticks; + + now = qemu_get_clock(vm_clock); + ticks = s->tick_offset + now / ticks_per_sec; + + /* The timer wraps around. This subtraction also wraps in the same way, + and gives correct results when alarm < now_ticks. */ + ticks = s->mr - ticks; + DPRINTF("Alarm set in %ud ticks\n", ticks); + if (ticks == 0) { + qemu_del_timer(s->timer); + pl031_interrupt(s); + } else { + qemu_mod_timer(s->timer, now + (int64_t)ticks * ticks_per_sec); + } +} + +static uint32_t pl031_read(void *opaque, target_phys_addr_t offset) +{ + pl031_state *s = (pl031_state *)opaque; + + if (offset >= 0xfe0 && offset < 0x1000) + return pl031_id[(offset - 0xfe0) >> 2]; + + switch (offset) { + case RTC_DR: + return pl031_get_count(s); + case RTC_MR: + return s->mr; + case RTC_IMSC: + return s->im; + case RTC_RIS: + return s->is; + case RTC_LR: + return s->lr; + case RTC_CR: + /* RTC is permanently enabled. */ + return 1; + case RTC_MIS: + return s->is & s->im; + case RTC_ICR: + fprintf(stderr, "qemu: pl031_read: Unexpected offset 0x%x\n", + (int)offset); + break; + default: + hw_error("pl031_read: Bad offset 0x%x\n", (int)offset); + break; + } + + return 0; +} + +static void pl031_write(void * opaque, target_phys_addr_t offset, + uint32_t value) +{ + pl031_state *s = (pl031_state *)opaque; + + + switch (offset) { + case RTC_LR: + s->tick_offset += value - pl031_get_count(s); + pl031_set_alarm(s); + break; + case RTC_MR: + s->mr = value; + pl031_set_alarm(s); + break; + case RTC_IMSC: + s->im = value & 1; + DPRINTF("Interrupt mask %d\n", s->im); + pl031_update(s); + break; + case RTC_ICR: + /* The PL031 documentation (DDI0224B) states that the interupt is + cleared when bit 0 of the written value is set. However the + arm926e documentation (DDI0287B) states that the interrupt is + cleared when any value is written. */ + DPRINTF("Interrupt cleared"); + s->is = 0; + pl031_update(s); + break; + case RTC_CR: + /* Written value is ignored. */ + break; + + case RTC_DR: + case RTC_MIS: + case RTC_RIS: + fprintf(stderr, "qemu: pl031_write: Unexpected offset 0x%x\n", + (int)offset); + break; + + default: + hw_error("pl031_write: Bad offset 0x%x\n", (int)offset); + break; + } +} + +static CPUWriteMemoryFunc * pl031_writefn[] = { + pl031_write, + pl031_write, + pl031_write +}; + +static CPUReadMemoryFunc * pl031_readfn[] = { + pl031_read, + pl031_read, + pl031_read +}; + +static void pl031_init(SysBusDevice *dev) +{ + int iomemtype; + pl031_state *s = FROM_SYSBUS(pl031_state, dev); + struct tm tm; + + iomemtype = cpu_register_io_memory(0, pl031_readfn, pl031_writefn, s); + if (iomemtype == -1) { + hw_error("pl031_init: Can't register I/O memory\n"); + } + + sysbus_init_mmio(dev, 0x1000, iomemtype); + + sysbus_init_irq(dev, &s->irq); + /* ??? We assume vm_clock is zero at this point. */ + qemu_get_timedate(&tm, 0); + s->tick_offset = mktimegm(&tm); + + s->timer = qemu_new_timer(vm_clock, pl031_interrupt, s); +} + +static void pl031_register_devices(void) +{ + sysbus_register_dev("pl031", sizeof(pl031_state), pl031_init); +} + +device_init(pl031_register_devices) diff --git a/pool/shard004/C/0100624_linearsearch.c b/pool/shard004/C/0100624_linearsearch.c new file mode 100644 index 0000000000000000000000000000000000000000..3b582ef1030d4b86a495bbf6ad5c72dd44347465 --- /dev/null +++ b/pool/shard004/C/0100624_linearsearch.c @@ -0,0 +1,24 @@ +#include +int main() +{ + int n,i,x,flag=0; + int a[100100]; + scanf("%d",&n); //how many numbers in which you want to search + for(i=0;if_in = f_in; + saved->file_name = file_name; + saved->preprocess = preprocess; + if (preprocess) + saved->app_save = app_push (); + + /* Initialize for new file. */ + input_file_begin (); + + return (char *) saved; +} + +void +input_file_pop (char *arg) +{ + struct saved_file *saved = (struct saved_file *) arg; + + input_file_end (); /* Close out old file. */ + + f_in = saved->f_in; + file_name = saved->file_name; + preprocess = saved->preprocess; + if (preprocess) + app_pop (saved->app_save); + + free (arg); +} + +/* Open the specified file, "" means stdin. Filename must not be null. */ + +void +input_file_open (const char *filename, + int pre) +{ + int c; + char buf[80]; + + preprocess = pre; + + gas_assert (filename != 0); /* Filename may not be NULL. */ + if (filename[0]) + { + f_in = fopen (filename, FOPEN_RT); + file_name = filename; + } + else + { + /* Use stdin for the input file. */ + f_in = stdin; + /* For error messages. */ + file_name = _("{standard input}"); + } + + if (f_in == NULL) + { + as_bad (_("can't open %s for reading: %s"), + file_name, xstrerror (errno)); + return; + } + + c = getc (f_in); + + if (ferror (f_in)) + { + as_bad (_("can't read from %s: %s"), + file_name, xstrerror (errno)); + + fclose (f_in); + f_in = NULL; + return; + } + + /* Check for an empty input file. */ + if (feof (f_in)) + { + fclose (f_in); + f_in = NULL; + return; + } + gas_assert (c != EOF); + + if (c == '#') + { + /* Begins with comment, may not want to preprocess. */ + c = getc (f_in); + if (c == 'N') + { + if (fgets (buf, sizeof (buf), f_in) + && !strncmp (buf, "O_APP", 5) && ISSPACE (buf[5])) + preprocess = 0; + if (!strchr (buf, '\n')) + ungetc ('#', f_in); /* It was longer. */ + else + ungetc ('\n', f_in); + } + else if (c == 'A') + { + if (fgets (buf, sizeof (buf), f_in) + && !strncmp (buf, "PP", 2) && ISSPACE (buf[2])) + preprocess = 1; + if (!strchr (buf, '\n')) + ungetc ('#', f_in); + else + ungetc ('\n', f_in); + } + else if (c == '\n') + ungetc ('\n', f_in); + else + ungetc ('#', f_in); + } + else + ungetc (c, f_in); +} + +/* Close input file. */ + +void +input_file_close (void) +{ + /* Don't close a null file pointer. */ + if (f_in != NULL) + fclose (f_in); + + f_in = 0; +} + +/* This function is passed to do_scrub_chars. */ + +static size_t +input_file_get (char *buf, size_t buflen) +{ + size_t size; + + if (feof (f_in)) + return 0; + + size = fread (buf, sizeof (char), buflen, f_in); + if (ferror (f_in)) + as_bad (_("can't read from %s: %s"), file_name, xstrerror (errno)); + return size; +} + +/* Read a buffer from the input file. */ + +char * +input_file_give_next_buffer (char *where /* Where to place 1st character of new buffer. */) +{ + char *return_value; /* -> Last char of what we read, + 1. */ + size_t size; + + if (f_in == (FILE *) 0) + return 0; + /* fflush (stdin); could be done here if you want to synchronise + stdin and stdout, for the case where our input file is stdin. + Since the assembler shouldn't do any output to stdout, we + don't bother to synch output and input. */ + if (preprocess) + size = do_scrub_chars (input_file_get, where, BUFFER_SIZE); + else + size = input_file_get (where, BUFFER_SIZE); + + if (size) + return_value = where + size; + else + { + if (fclose (f_in)) + as_warn (_("can't close %s: %s"), file_name, xstrerror (errno)); + + f_in = (FILE *) 0; + return_value = 0; + } + + return return_value; +} diff --git a/pool/shard004/C/0100639_env_settings.c b/pool/shard004/C/0100639_env_settings.c new file mode 100644 index 0000000000000000000000000000000000000000..0b578c969c670c79d834ff9c98364bbad0486471 --- /dev/null +++ b/pool/shard004/C/0100639_env_settings.c @@ -0,0 +1,137 @@ +/* +Copyright 2018 Google Inc. All rights reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +#include "env_settings.h" + +#include // for errno, ERANGE +#include // for fprintf, NULL, stderr +#include // for getenv, strtol, strtoull +#include // for strchr +#include // for access, X_OK + +#include "logging.h" + +unsigned long long GetUnsignedLongLongSetting(const char* name, + unsigned long long def) { + const char* value = getenv(name); + if (value == NULL || value[0] == 0) { + return def; + } + char* endptr = NULL; + errno = 0; + unsigned long long number = strtoull(value, &endptr, 0); + if (errno == ERANGE) { + Log("Ignoring out-of-range value of %s: %s", name, value); + return def; + } + if ((endptr != NULL && *endptr != 0)) { + Log("Ignoring non-numeric value of %s: %s", name, value); + return def; + } + return number; +} + +long GetLongSetting(const char* name, long def) { + const char* value = getenv(name); + if (value == NULL || value[0] == 0) { + return def; + } + char* endptr = NULL; + errno = 0; + long number = strtol(value, &endptr, 0); + if (errno == ERANGE) { + Log("Ignoring out-of-range value of %s: %s", name, value); + return def; + } + if ((endptr != NULL && *endptr != 0)) { + Log("Ignoring non-numeric value of %s: %s", name, value); + return def; + } + return number; +} + +int GetIntSetting(const char* name, int def) { + long lnumber = GetLongSetting(name, def); + int number = (int)lnumber; + if (lnumber != (long)number) { + Log("Ignoring out-of-range value of %s: %d", name, number); + return def; + } + return number; +} + +double GetDoubleSetting(const char* name, double def) { + const char* value = getenv(name); + if (value == NULL || value[0] == 0) { + return def; + } + char* endptr = NULL; + errno = 0; + double number = strtod(value, &endptr); + if (errno == ERANGE) { + Log("Ignoring out-of-range value of %s: %s", name, value); + return def; + } + if ((endptr != NULL && *endptr != 0)) { + Log("Ignoring non-numeric value of %s: %s", name, value); + return def; + } + return number; +} + +const char* GetStringSetting(const char* name, const char* def) { + const char* value = getenv(name); + if (value == NULL || value[0] == 0) { + return def; + } + return value; +} + +const char* GetExecutablePathSetting(const char* name, const char* def, + int is_auth) { + const char* value = getenv(name); + if (value == NULL || value[0] == 0) { + return def; + } + if (strchr(value, '/') && value[0] != '/') { + Log("Executable name '%s' must be either an absolute path or a file within " + "%s", + value, HELPER_PATH); + return def; + } + const char* basename = strrchr(value, '/'); + if (basename == NULL) { + basename = value; // No slash, use as is. + } else { + ++basename; // Skip the slash. + } + if (is_auth) { + if (strncmp(basename, "auth_", 5) != 0) { + Log("Auth executable name '%s' must start with auth_", value); + return def; + } + } else { + if (!strncmp(basename, "auth_", 5)) { + Log("Non-auth executable name '%s' must not start with auth_", value); + return def; + } + } + if (access(value, X_OK)) { + Log("Executable '%s' must be executable", value); + return def; + } + return value; +} diff --git a/pool/shard004/C/0100643_mpc5121_ads_cpld.c b/pool/shard004/C/0100643_mpc5121_ads_cpld.c new file mode 100644 index 0000000000000000000000000000000000000000..11090ab4bf59a38f2b78074fd8b7a9e10467656d --- /dev/null +++ b/pool/shard004/C/0100643_mpc5121_ads_cpld.c @@ -0,0 +1,203 @@ +/* + * Copyright (C) 2008 Freescale Semiconductor, Inc. All rights reserved. + * + * Author: John Rigby, + * + * Description: + * MPC5121ADS CPLD irq handling + * + * 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. + */ + +#undef DEBUG + +#include +#include +#include +#include +#include + +static struct device_node *cpld_pic_node; +static struct irq_domain *cpld_pic_host; + +/* + * Bits to ignore in the misc_status register + * 0x10 touch screen pendown is hard routed to irq1 + * 0x02 pci status is read from pci status register + */ +#define MISC_IGNORE 0x12 + +/* + * Nothing to ignore in pci status register + */ +#define PCI_IGNORE 0x00 + +struct cpld_pic { + u8 pci_mask; + u8 pci_status; + u8 route; + u8 misc_mask; + u8 misc_status; + u8 misc_control; +}; + +static struct cpld_pic __iomem *cpld_regs; + +static void __iomem * +irq_to_pic_mask(unsigned int irq) +{ + return irq <= 7 ? &cpld_regs->pci_mask : &cpld_regs->misc_mask; +} + +static unsigned int +irq_to_pic_bit(unsigned int irq) +{ + return 1 << (irq & 0x7); +} + +static void +cpld_mask_irq(struct irq_data *d) +{ + unsigned int cpld_irq = (unsigned int)irqd_to_hwirq(d); + void __iomem *pic_mask = irq_to_pic_mask(cpld_irq); + + out_8(pic_mask, + in_8(pic_mask) | irq_to_pic_bit(cpld_irq)); +} + +static void +cpld_unmask_irq(struct irq_data *d) +{ + unsigned int cpld_irq = (unsigned int)irqd_to_hwirq(d); + void __iomem *pic_mask = irq_to_pic_mask(cpld_irq); + + out_8(pic_mask, + in_8(pic_mask) & ~irq_to_pic_bit(cpld_irq)); +} + +static struct irq_chip cpld_pic = { + .name = "CPLD PIC", + .irq_mask = cpld_mask_irq, + .irq_ack = cpld_mask_irq, + .irq_unmask = cpld_unmask_irq, +}; + +static int +cpld_pic_get_irq(int offset, u8 ignore, u8 __iomem *statusp, + u8 __iomem *maskp) +{ + int cpld_irq; + u8 status = in_8(statusp); + u8 mask = in_8(maskp); + + /* ignore don't cares and masked irqs */ + status |= (ignore | mask); + + if (status == 0xff) + return NO_IRQ; + + cpld_irq = ffz(status) + offset; + + return irq_linear_revmap(cpld_pic_host, cpld_irq); +} + +static void +cpld_pic_cascade(unsigned int irq, struct irq_desc *desc) +{ + irq = cpld_pic_get_irq(0, PCI_IGNORE, &cpld_regs->pci_status, + &cpld_regs->pci_mask); + if (irq != NO_IRQ) { + generic_handle_irq(irq); + return; + } + + irq = cpld_pic_get_irq(8, MISC_IGNORE, &cpld_regs->misc_status, + &cpld_regs->misc_mask); + if (irq != NO_IRQ) { + generic_handle_irq(irq); + return; + } +} + +static int +cpld_pic_host_match(struct irq_domain *h, struct device_node *node, + enum irq_domain_bus_token bus_token) +{ + return cpld_pic_node == node; +} + +static int +cpld_pic_host_map(struct irq_domain *h, unsigned int virq, + irq_hw_number_t hw) +{ + irq_set_status_flags(virq, IRQ_LEVEL); + irq_set_chip_and_handler(virq, &cpld_pic, handle_level_irq); + return 0; +} + +static const struct irq_domain_ops cpld_pic_host_ops = { + .match = cpld_pic_host_match, + .map = cpld_pic_host_map, +}; + +void __init +mpc5121_ads_cpld_map(void) +{ + struct device_node *np = NULL; + + np = of_find_compatible_node(NULL, NULL, "fsl,mpc5121ads-cpld-pic"); + if (!np) { + printk(KERN_ERR "CPLD PIC init: can not find cpld-pic node\n"); + return; + } + + cpld_regs = of_iomap(np, 0); + of_node_put(np); +} + +void __init +mpc5121_ads_cpld_pic_init(void) +{ + unsigned int cascade_irq; + struct device_node *np = NULL; + + pr_debug("cpld_ic_init\n"); + + np = of_find_compatible_node(NULL, NULL, "fsl,mpc5121ads-cpld-pic"); + if (!np) { + printk(KERN_ERR "CPLD PIC init: can not find cpld-pic node\n"); + return; + } + + if (!cpld_regs) + goto end; + + cascade_irq = irq_of_parse_and_map(np, 0); + if (cascade_irq == NO_IRQ) + goto end; + + /* + * statically route touch screen pendown through 1 + * and ignore it here + * route all others through our cascade irq + */ + out_8(&cpld_regs->route, 0xfd); + out_8(&cpld_regs->pci_mask, 0xff); + /* unmask pci ints in misc mask */ + out_8(&cpld_regs->misc_mask, ~(MISC_IGNORE)); + + cpld_pic_node = of_node_get(np); + + cpld_pic_host = irq_domain_add_linear(np, 16, &cpld_pic_host_ops, NULL); + if (!cpld_pic_host) { + printk(KERN_ERR "CPLD PIC: failed to allocate irq host!\n"); + goto end; + } + + irq_set_chained_handler(cascade_irq, cpld_pic_cascade); +end: + of_node_put(np); +} diff --git a/pool/shard004/C/0100666_zio_compress.c b/pool/shard004/C/0100666_zio_compress.c new file mode 100644 index 0000000000000000000000000000000000000000..6b8d6c39bd912b98e5e19f4e58bc43a15afb6447 --- /dev/null +++ b/pool/shard004/C/0100666_zio_compress.c @@ -0,0 +1,134 @@ +/* + * CDDL HEADER START + * + * The contents of this file are subject to the terms of the + * Common Development and Distribution License (the "License"). + * You may not use this file except in compliance with the License. + * + * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE + * or http://www.opensolaris.org/os/licensing. + * See the License for the specific language governing permissions + * and limitations under the License. + * + * When distributing Covered Code, include this CDDL HEADER in each + * file and include the License file at usr/src/OPENSOLARIS.LICENSE. + * If applicable, add the following below this CDDL HEADER, with the + * fields enclosed by brackets "[]" replaced with your own identifying + * information: Portions Copyright [yyyy] [name of copyright owner] + * + * CDDL HEADER END + */ + +/* + * Copyright 2009 Sun Microsystems, Inc. All rights reserved. + * Use is subject to license terms. + */ +/* + * Copyright (c) 2013 by Saso Kiselkov. All rights reserved. + */ + +/* + * Copyright (c) 2013 by Delphix. All rights reserved. + */ + +#include +#include +#include +#include +#include +#include + +/* + * Compression vectors. + */ + +zio_compress_info_t zio_compress_table[ZIO_COMPRESS_FUNCTIONS] = { + {NULL, NULL, 0, "inherit"}, + {NULL, NULL, 0, "on"}, + {NULL, NULL, 0, "uncompressed"}, + {lzjb_compress, lzjb_decompress, 0, "lzjb"}, + {NULL, NULL, 0, "empty"}, + {gzip_compress, gzip_decompress, 1, "gzip-1"}, + {gzip_compress, gzip_decompress, 2, "gzip-2"}, + {gzip_compress, gzip_decompress, 3, "gzip-3"}, + {gzip_compress, gzip_decompress, 4, "gzip-4"}, + {gzip_compress, gzip_decompress, 5, "gzip-5"}, + {gzip_compress, gzip_decompress, 6, "gzip-6"}, + {gzip_compress, gzip_decompress, 7, "gzip-7"}, + {gzip_compress, gzip_decompress, 8, "gzip-8"}, + {gzip_compress, gzip_decompress, 9, "gzip-9"}, + {zle_compress, zle_decompress, 64, "zle"}, + {lz4_compress_zfs, lz4_decompress_zfs, 0, "lz4"}, +}; + +enum zio_compress +zio_compress_select(spa_t *spa, enum zio_compress child, + enum zio_compress parent) +{ + enum zio_compress result; + + ASSERT(child < ZIO_COMPRESS_FUNCTIONS); + ASSERT(parent < ZIO_COMPRESS_FUNCTIONS); + ASSERT(parent != ZIO_COMPRESS_INHERIT); + + result = child; + if (result == ZIO_COMPRESS_INHERIT) + result = parent; + + if (result == ZIO_COMPRESS_ON) { + if (spa_feature_is_active(spa, SPA_FEATURE_LZ4_COMPRESS)) + result = ZIO_COMPRESS_LZ4_ON_VALUE; + else + result = ZIO_COMPRESS_LEGACY_ON_VALUE; + } + + return (result); +} + +size_t +zio_compress_data(enum zio_compress c, void *src, void *dst, size_t s_len) +{ + uint64_t *word, *word_end; + size_t c_len, d_len; + zio_compress_info_t *ci = &zio_compress_table[c]; + + ASSERT((uint_t)c < ZIO_COMPRESS_FUNCTIONS); + ASSERT((uint_t)c == ZIO_COMPRESS_EMPTY || ci->ci_compress != NULL); + + /* + * If the data is all zeroes, we don't even need to allocate + * a block for it. We indicate this by returning zero size. + */ + word_end = (uint64_t *)((char *)src + s_len); + for (word = src; word < word_end; word++) + if (*word != 0) + break; + + if (word == word_end) + return (0); + + if (c == ZIO_COMPRESS_EMPTY) + return (s_len); + + /* Compress at least 12.5% */ + d_len = s_len - (s_len >> 3); + c_len = ci->ci_compress(src, dst, s_len, d_len, ci->ci_level); + + if (c_len > d_len) + return (s_len); + + ASSERT3U(c_len, <=, d_len); + return (c_len); +} + +int +zio_decompress_data(enum zio_compress c, void *src, void *dst, + size_t s_len, size_t d_len) +{ + zio_compress_info_t *ci = &zio_compress_table[c]; + + if ((uint_t)c >= ZIO_COMPRESS_FUNCTIONS || ci->ci_decompress == NULL) + return (SET_ERROR(EINVAL)); + + return (ci->ci_decompress(src, dst, s_len, d_len, ci->ci_level)); +} diff --git a/pool/shard004/C/0100668_decoder_internal.c b/pool/shard004/C/0100668_decoder_internal.c new file mode 100644 index 0000000000000000000000000000000000000000..bc349f2ff6ef0dfb3b99f312926f9a6e25d2e372 --- /dev/null +++ b/pool/shard004/C/0100668_decoder_internal.c @@ -0,0 +1,96 @@ +/* + * Copyright (C) 2003-2011 The Music Player Daemon Project + * http://www.musicpd.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 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 "decoder_internal.h" +#include "decoder_control.h" +#include "pipe.h" +#include "input_stream.h" +#include "buffer.h" +#include "chunk.h" + +#include + +/** + * All chunks are full of decoded data; wait for the player to free + * one. + */ +static enum decoder_command +need_chunks(struct decoder_control *dc, bool do_wait) +{ + if (dc->command == DECODE_COMMAND_STOP || + dc->command == DECODE_COMMAND_SEEK) + return dc->command; + + if (do_wait) { + decoder_wait(dc); + g_cond_signal(dc->client_cond); + + return dc->command; + } + + return DECODE_COMMAND_NONE; +} + +struct music_chunk * +decoder_get_chunk(struct decoder *decoder) +{ + struct decoder_control *dc = decoder->dc; + enum decoder_command cmd; + + assert(decoder != NULL); + + if (decoder->chunk != NULL) + return decoder->chunk; + + do { + decoder->chunk = music_buffer_allocate(dc->buffer); + if (decoder->chunk != NULL) { + decoder->chunk->replay_gain_serial = + decoder->replay_gain_serial; + if (decoder->replay_gain_serial != 0) + decoder->chunk->replay_gain_info = + decoder->replay_gain_info; + + return decoder->chunk; + } + + decoder_lock(dc); + cmd = need_chunks(dc, true); + decoder_unlock(dc); + } while (cmd == DECODE_COMMAND_NONE); + + return NULL; +} + +void +decoder_flush_chunk(struct decoder *decoder) +{ + struct decoder_control *dc = decoder->dc; + + assert(decoder != NULL); + assert(decoder->chunk != NULL); + + if (music_chunk_is_empty(decoder->chunk)) + music_buffer_return(dc->buffer, decoder->chunk); + else + music_pipe_push(dc->pipe, decoder->chunk); + + decoder->chunk = NULL; +} diff --git a/pool/shard004/C/0100670_vmod_dclass.c b/pool/shard004/C/0100670_vmod_dclass.c new file mode 100644 index 0000000000000000000000000000000000000000..8097e1d599c8c1d592b7aa590ca13c1ae35212b1 --- /dev/null +++ b/pool/shard004/C/0100670_vmod_dclass.c @@ -0,0 +1,254 @@ +/* + * Copyright 2012 The Weather Channel + * Copyright 2013 Reza Naghibi + * + * 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 "dclass_client.h" + +#include "vrt.h" +#include "bin/varnishd/cache.h" +#include "vcc_if.h" + + +#define VMOD_DTREE_SIZE 4 + + +typedef struct +{ + unsigned xid; + dclass_keyvalue *kvd[VMOD_DTREE_SIZE]; +} +vmod_dclass_container; + +typedef struct +{ + dclass_index heads[VMOD_DTREE_SIZE]; + + vmod_dclass_container *vmod_dc_list; + int vmod_dc_list_size; + pthread_mutex_t vmod_dc_list_mutex; +} +vmod_dtree_container; + + +void vmod_free_dtc(void*); +static vmod_dclass_container *dcc_get(struct sess*,vmod_dtree_container*); + + +//inits a dtc, stores it in PRIV_VCL, inits dc_list +int init_function(struct vmod_priv *priv, const struct VCL_conf *conf) +{ + int i,j; + vmod_dtree_container *dtc; + + dtc=malloc(sizeof(vmod_dtree_container)); + + AN(dtc); + + pthread_mutex_init(&dtc->vmod_dc_list_mutex,NULL); + + for(i=0;iheads[i]); + + dtc->vmod_dc_list_size=256; + + dtc->vmod_dc_list=malloc(dtc->vmod_dc_list_size*sizeof(vmod_dclass_container)); + + AN(dtc->vmod_dc_list); + + for (i=0;ivmod_dc_list_size;i++) + { + for(j=0;jvmod_dc_list[i].kvd[j]=NULL; + + dtc->vmod_dc_list[i].xid=0; + } + + priv->priv=dtc; + priv->free=vmod_free_dtc; + + return 0; +} + +void vmod_init_dclass(struct sess *sp,struct vmod_priv *priv,const char *dtree_loc) +{ + vmod_init_dclass_p(sp,priv,dtree_loc,0); +} + +//inits a dclass dtree +void vmod_init_dclass_p(struct sess *sp,struct vmod_priv *priv,const char *dtree_loc,int p) +{ + int ret; + vmod_dtree_container *dtc; + + if(p<0 || p>=VMOD_DTREE_SIZE) + return; + + dtc=(vmod_dtree_container*)priv->priv; + + printf("vmod_init_dtree: loading new dtree: %d:'%s'\n",p,dtree_loc); + + ret=dclass_load_file(&dtc->heads[p],(char*)dtree_loc); + + if(ret<=0) + openddr_load_resources(&dtc->heads[p],(char*)dtree_loc); +} + +const char *vmod_classify(struct sess *sp, struct vmod_priv *priv, const char *str) +{ + return vmod_classify_p(sp,priv,str,0); +} + +//classifies a string +const char *vmod_classify_p(struct sess *sp,struct vmod_priv *priv,const char *str,int p) +{ + dclass_keyvalue *kvd; + vmod_dtree_container *dtc; + vmod_dclass_container *dcc; + + if(p<0 || p>=VMOD_DTREE_SIZE) + return NULL; + + dtc=(vmod_dtree_container*)priv->priv; + + dcc=dcc_get(sp,dtc); + + kvd=(dclass_keyvalue*)dclass_classify(&dtc->heads[p],str); + + dcc->kvd[p]=kvd; + + if(!kvd) + return NULL; + else + return kvd->id; +} + +const char *vmod_get_field(struct sess *sp, struct vmod_priv *priv, const char *key) +{ + return vmod_get_field_p(sp,priv,key,0); +} + +const char *vmod_get_field_p(struct sess *sp,struct vmod_priv *priv,const char *key,int p) +{ + const char *ret=NULL; + vmod_dtree_container *dtc; + vmod_dclass_container *dcc; + + if(p<0 || p>=VMOD_DTREE_SIZE) + return ""; + + dtc=(vmod_dtree_container*)priv->priv; + + dcc=dcc_get(sp,dtc); + + if(dcc->kvd[p]) + ret=dclass_get_kvalue(dcc->kvd[p],key); + + if(ret) + return ret; + else + return ""; +} + +int vmod_get_ifield(struct sess *sp, struct vmod_priv *priv, const char *key) +{ + return vmod_get_ifield_p(sp,priv,key,0); +} + +int vmod_get_ifield_p(struct sess *sp,struct vmod_priv *priv,const char *key,int p) +{ + const char *s; + vmod_dtree_container *dtc; + vmod_dclass_container *dcc; + + if(p<0 || p>=VMOD_DTREE_SIZE) + return 0; + + dtc=(vmod_dtree_container*)priv->priv; + + dcc=dcc_get(sp,dtc); + + if(dcc->kvd[p]) + { + s=dclass_get_kvalue(dcc->kvd[p],key); + + if(s) + return atoi(s); + else + return 0; + } + + return 0; +} + +//gets a dc from the dc_list +static vmod_dclass_container *dcc_get(struct sess *sp,vmod_dtree_container *dtc) +{ + int ns,j; + vmod_dclass_container *dcc; + + AZ(pthread_mutex_lock(&dtc->vmod_dc_list_mutex)); + + while (dtc->vmod_dc_list_size<=sp->id) + { + ns=dtc->vmod_dc_list_size*2; + + dtc->vmod_dc_list=realloc(dtc->vmod_dc_list,ns*sizeof(vmod_dclass_container)); + + AN(dtc->vmod_dc_list); + + for (;dtc->vmod_dc_list_sizevmod_dc_list_size++) + { + for(j=0;jvmod_dc_list[dtc->vmod_dc_list_size].kvd[j]=NULL; + + dtc->vmod_dc_list[dtc->vmod_dc_list_size].xid=0; + } + } + + dcc=&dtc->vmod_dc_list[sp->id]; + + if (dcc->xid!=sp->xid) + { + dcc->kvd[0]=NULL; + dcc->xid=sp->xid; + } + + AZ(pthread_mutex_unlock(&dtc->vmod_dc_list_mutex)); + + return dcc; +} + +void vmod_free_dtc(void *data) +{ + int i; + vmod_dtree_container *dtc; + + dtc=(vmod_dtree_container*)data; + + for(i=0;iheads[i]); + + free(dtc->vmod_dc_list); + + free(data); +} + +const char *vmod_get_version(struct sess *sp) +{ + return dclass_get_version(); +} diff --git a/pool/shard004/C/0100678_svc_rdma_marshal.c b/pool/shard004/C/0100678_svc_rdma_marshal.c new file mode 100644 index 0000000000000000000000000000000000000000..0ba9887f3e22bab9a1e3e809df5c4e2c23a510fe --- /dev/null +++ b/pool/shard004/C/0100678_svc_rdma_marshal.c @@ -0,0 +1,344 @@ +/* + * Copyright (c) 2005-2006 Network Appliance, Inc. 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 BSD-type + * 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. + * + * Neither the name of the Network Appliance, 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. + * + * Author: Tom Tucker + */ + +#include +#include +#include +#include +#include + +#define RPCDBG_FACILITY RPCDBG_SVCXPRT + +/* + * Decodes a read chunk list. The expected format is as follows: + * descrim : xdr_one + * position : __be32 offset into XDR stream + * handle : __be32 RKEY + * . . . + * end-of-list: xdr_zero + */ +static __be32 *decode_read_list(__be32 *va, __be32 *vaend) +{ + struct rpcrdma_read_chunk *ch = (struct rpcrdma_read_chunk *)va; + + while (ch->rc_discrim != xdr_zero) { + if (((unsigned long)ch + sizeof(struct rpcrdma_read_chunk)) > + (unsigned long)vaend) { + dprintk("svcrdma: vaend=%p, ch=%p\n", vaend, ch); + return NULL; + } + ch++; + } + return &ch->rc_position; +} + +/* + * Decodes a write chunk list. The expected format is as follows: + * descrim : xdr_one + * nchunks : + * handle : __be32 RKEY ---+ + * length : __be32 | + * offset : remove va + + * . . . | + * ---+ + */ +static __be32 *decode_write_list(__be32 *va, __be32 *vaend) +{ + unsigned long start, end; + int nchunks; + + struct rpcrdma_write_array *ary = + (struct rpcrdma_write_array *)va; + + /* Check for not write-array */ + if (ary->wc_discrim == xdr_zero) + return &ary->wc_nchunks; + + if ((unsigned long)ary + sizeof(struct rpcrdma_write_array) > + (unsigned long)vaend) { + dprintk("svcrdma: ary=%p, vaend=%p\n", ary, vaend); + return NULL; + } + nchunks = be32_to_cpu(ary->wc_nchunks); + + start = (unsigned long)&ary->wc_array[0]; + end = (unsigned long)vaend; + if (nchunks < 0 || + nchunks > (SIZE_MAX - start) / sizeof(struct rpcrdma_write_chunk) || + (start + (sizeof(struct rpcrdma_write_chunk) * nchunks)) > end) { + dprintk("svcrdma: ary=%p, wc_nchunks=%d, vaend=%p\n", + ary, nchunks, vaend); + return NULL; + } + /* + * rs_length is the 2nd 4B field in wc_target and taking its + * address skips the list terminator + */ + return &ary->wc_array[nchunks].wc_target.rs_length; +} + +static __be32 *decode_reply_array(__be32 *va, __be32 *vaend) +{ + unsigned long start, end; + int nchunks; + struct rpcrdma_write_array *ary = + (struct rpcrdma_write_array *)va; + + /* Check for no reply-array */ + if (ary->wc_discrim == xdr_zero) + return &ary->wc_nchunks; + + if ((unsigned long)ary + sizeof(struct rpcrdma_write_array) > + (unsigned long)vaend) { + dprintk("svcrdma: ary=%p, vaend=%p\n", ary, vaend); + return NULL; + } + nchunks = be32_to_cpu(ary->wc_nchunks); + + start = (unsigned long)&ary->wc_array[0]; + end = (unsigned long)vaend; + if (nchunks < 0 || + nchunks > (SIZE_MAX - start) / sizeof(struct rpcrdma_write_chunk) || + (start + (sizeof(struct rpcrdma_write_chunk) * nchunks)) > end) { + dprintk("svcrdma: ary=%p, wc_nchunks=%d, vaend=%p\n", + ary, nchunks, vaend); + return NULL; + } + return (__be32 *)&ary->wc_array[nchunks]; +} + +/** + * svc_rdma_xdr_decode_req - Parse incoming RPC-over-RDMA header + * @rq_arg: Receive buffer + * + * On entry, xdr->head[0].iov_base points to first byte in the + * RPC-over-RDMA header. + * + * On successful exit, head[0] points to first byte past the + * RPC-over-RDMA header. For RDMA_MSG, this is the RPC message. + * The length of the RPC-over-RDMA header is returned. + */ +int svc_rdma_xdr_decode_req(struct xdr_buf *rq_arg) +{ + struct rpcrdma_msg *rmsgp; + __be32 *va, *vaend; + unsigned int len; + u32 hdr_len; + + /* Verify that there's enough bytes for header + something */ + if (rq_arg->len <= RPCRDMA_HDRLEN_ERR) { + dprintk("svcrdma: header too short = %d\n", + rq_arg->len); + return -EINVAL; + } + + rmsgp = (struct rpcrdma_msg *)rq_arg->head[0].iov_base; + if (rmsgp->rm_vers != rpcrdma_version) { + dprintk("%s: bad version %u\n", __func__, + be32_to_cpu(rmsgp->rm_vers)); + return -EPROTONOSUPPORT; + } + + switch (be32_to_cpu(rmsgp->rm_type)) { + case RDMA_MSG: + case RDMA_NOMSG: + break; + + case RDMA_DONE: + /* Just drop it */ + dprintk("svcrdma: dropping RDMA_DONE message\n"); + return 0; + + case RDMA_ERROR: + /* Possible if this is a backchannel reply. + * XXX: We should cancel this XID, though. + */ + dprintk("svcrdma: dropping RDMA_ERROR message\n"); + return 0; + + case RDMA_MSGP: + /* Pull in the extra for the padded case, bump our pointer */ + rmsgp->rm_body.rm_padded.rm_align = + be32_to_cpu(rmsgp->rm_body.rm_padded.rm_align); + rmsgp->rm_body.rm_padded.rm_thresh = + be32_to_cpu(rmsgp->rm_body.rm_padded.rm_thresh); + + va = &rmsgp->rm_body.rm_padded.rm_pempty[4]; + rq_arg->head[0].iov_base = va; + len = (u32)((unsigned long)va - (unsigned long)rmsgp); + rq_arg->head[0].iov_len -= len; + if (len > rq_arg->len) + return -EINVAL; + return len; + default: + dprintk("svcrdma: bad rdma procedure (%u)\n", + be32_to_cpu(rmsgp->rm_type)); + return -EINVAL; + } + + /* The chunk list may contain either a read chunk list or a write + * chunk list and a reply chunk list. + */ + va = &rmsgp->rm_body.rm_chunks[0]; + vaend = (__be32 *)((unsigned long)rmsgp + rq_arg->len); + va = decode_read_list(va, vaend); + if (!va) { + dprintk("svcrdma: failed to decode read list\n"); + return -EINVAL; + } + va = decode_write_list(va, vaend); + if (!va) { + dprintk("svcrdma: failed to decode write list\n"); + return -EINVAL; + } + va = decode_reply_array(va, vaend); + if (!va) { + dprintk("svcrdma: failed to decode reply chunk\n"); + return -EINVAL; + } + + rq_arg->head[0].iov_base = va; + hdr_len = (unsigned long)va - (unsigned long)rmsgp; + rq_arg->head[0].iov_len -= hdr_len; + return hdr_len; +} + +int svc_rdma_xdr_encode_error(struct svcxprt_rdma *xprt, + struct rpcrdma_msg *rmsgp, + enum rpcrdma_errcode err, __be32 *va) +{ + __be32 *startp = va; + + *va++ = rmsgp->rm_xid; + *va++ = rmsgp->rm_vers; + *va++ = cpu_to_be32(xprt->sc_max_requests); + *va++ = rdma_error; + *va++ = cpu_to_be32(err); + if (err == ERR_VERS) { + *va++ = rpcrdma_version; + *va++ = rpcrdma_version; + } + + return (int)((unsigned long)va - (unsigned long)startp); +} + +int svc_rdma_xdr_get_reply_hdr_len(struct rpcrdma_msg *rmsgp) +{ + struct rpcrdma_write_array *wr_ary; + + /* There is no read-list in a reply */ + + /* skip write list */ + wr_ary = (struct rpcrdma_write_array *) + &rmsgp->rm_body.rm_chunks[1]; + if (wr_ary->wc_discrim) + wr_ary = (struct rpcrdma_write_array *) + &wr_ary->wc_array[be32_to_cpu(wr_ary->wc_nchunks)]. + wc_target.rs_length; + else + wr_ary = (struct rpcrdma_write_array *) + &wr_ary->wc_nchunks; + + /* skip reply array */ + if (wr_ary->wc_discrim) + wr_ary = (struct rpcrdma_write_array *) + &wr_ary->wc_array[be32_to_cpu(wr_ary->wc_nchunks)]; + else + wr_ary = (struct rpcrdma_write_array *) + &wr_ary->wc_nchunks; + + return (unsigned long) wr_ary - (unsigned long) rmsgp; +} + +void svc_rdma_xdr_encode_write_list(struct rpcrdma_msg *rmsgp, int chunks) +{ + struct rpcrdma_write_array *ary; + + /* no read-list */ + rmsgp->rm_body.rm_chunks[0] = xdr_zero; + + /* write-array discrim */ + ary = (struct rpcrdma_write_array *) + &rmsgp->rm_body.rm_chunks[1]; + ary->wc_discrim = xdr_one; + ary->wc_nchunks = cpu_to_be32(chunks); + + /* write-list terminator */ + ary->wc_array[chunks].wc_target.rs_handle = xdr_zero; + + /* reply-array discriminator */ + ary->wc_array[chunks].wc_target.rs_length = xdr_zero; +} + +void svc_rdma_xdr_encode_reply_array(struct rpcrdma_write_array *ary, + int chunks) +{ + ary->wc_discrim = xdr_one; + ary->wc_nchunks = cpu_to_be32(chunks); +} + +void svc_rdma_xdr_encode_array_chunk(struct rpcrdma_write_array *ary, + int chunk_no, + __be32 rs_handle, + __be64 rs_offset, + u32 write_len) +{ + struct rpcrdma_segment *seg = &ary->wc_array[chunk_no].wc_target; + seg->rs_handle = rs_handle; + seg->rs_offset = rs_offset; + seg->rs_length = cpu_to_be32(write_len); +} + +void svc_rdma_xdr_encode_reply_header(struct svcxprt_rdma *xprt, + struct rpcrdma_msg *rdma_argp, + struct rpcrdma_msg *rdma_resp, + enum rpcrdma_proc rdma_type) +{ + rdma_resp->rm_xid = rdma_argp->rm_xid; + rdma_resp->rm_vers = rdma_argp->rm_vers; + rdma_resp->rm_credit = cpu_to_be32(xprt->sc_max_requests); + rdma_resp->rm_type = cpu_to_be32(rdma_type); + + /* Encode chunks lists */ + rdma_resp->rm_body.rm_chunks[0] = xdr_zero; + rdma_resp->rm_body.rm_chunks[1] = xdr_zero; + rdma_resp->rm_body.rm_chunks[2] = xdr_zero; +} diff --git a/pool/shard004/C/0100690_siena_mcdi.c b/pool/shard004/C/0100690_siena_mcdi.c new file mode 100644 index 0000000000000000000000000000000000000000..ff975798f22c9d45d55e0631ff49aa177f28da3a --- /dev/null +++ b/pool/shard004/C/0100690_siena_mcdi.c @@ -0,0 +1,243 @@ +/* SPDX-License-Identifier: BSD-3-Clause + * + * Copyright(c) 2019-2021 Xilinx, Inc. + * Copyright(c) 2012-2019 Solarflare Communications Inc. + */ + +#include "efx.h" +#include "efx_impl.h" + +#if EFSYS_OPT_SIENA && EFSYS_OPT_MCDI + +#define SIENA_MCDI_PDU(_emip) \ + (((emip)->emi_port == 1) \ + ? MC_SMEM_P0_PDU_OFST >> 2 \ + : MC_SMEM_P1_PDU_OFST >> 2) + +#define SIENA_MCDI_DOORBELL(_emip) \ + (((emip)->emi_port == 1) \ + ? MC_SMEM_P0_DOORBELL_OFST >> 2 \ + : MC_SMEM_P1_DOORBELL_OFST >> 2) + +#define SIENA_MCDI_STATUS(_emip) \ + (((emip)->emi_port == 1) \ + ? MC_SMEM_P0_STATUS_OFST >> 2 \ + : MC_SMEM_P1_STATUS_OFST >> 2) + + + void +siena_mcdi_send_request( + __in efx_nic_t *enp, + __in_bcount(hdr_len) void *hdrp, + __in size_t hdr_len, + __in_bcount(sdu_len) void *sdup, + __in size_t sdu_len) +{ + efx_mcdi_iface_t *emip = &(enp->en_mcdi.em_emip); + efx_dword_t dword; + unsigned int pdur; + unsigned int dbr; + unsigned int pos; + + EFSYS_ASSERT(enp->en_family == EFX_FAMILY_SIENA); + + EFSYS_ASSERT(emip->emi_port == 1 || emip->emi_port == 2); + pdur = SIENA_MCDI_PDU(emip); + dbr = SIENA_MCDI_DOORBELL(emip); + + /* Write the header */ + EFSYS_ASSERT3U(hdr_len, ==, sizeof (efx_dword_t)); + dword = *(efx_dword_t *)hdrp; + EFX_BAR_TBL_WRITED(enp, FR_CZ_MC_TREG_SMEM, pdur, &dword, B_TRUE); + + /* Write the payload */ + for (pos = 0; pos < sdu_len; pos += sizeof (efx_dword_t)) { + dword = *(efx_dword_t *)((uint8_t *)sdup + pos); + EFX_BAR_TBL_WRITED(enp, FR_CZ_MC_TREG_SMEM, + pdur + 1 + (pos >> 2), &dword, B_FALSE); + } + + /* Ring the doorbell */ + EFX_POPULATE_DWORD_1(dword, EFX_DWORD_0, 0xd004be11); + EFX_BAR_TBL_WRITED(enp, FR_CZ_MC_TREG_SMEM, dbr, &dword, B_FALSE); +} + + efx_rc_t +siena_mcdi_poll_reboot( + __in efx_nic_t *enp) +{ +#if 1 + /* + * XXX Bug 25922, bug 26099: This function is not being used + * properly. Until its callers are fixed, it should always + * return 0. + */ + _NOTE(ARGUNUSED(enp)) + return (0); +#else + efx_mcdi_iface_t *emip = &(enp->en_mcdi.em_emip); + unsigned int rebootr; + efx_dword_t dword; + uint32_t value; + + EFSYS_ASSERT(enp->en_family == EFX_FAMILY_SIENA); + EFSYS_ASSERT(emip->emi_port == 1 || emip->emi_port == 2); + rebootr = SIENA_MCDI_STATUS(emip); + + EFX_BAR_TBL_READD(enp, FR_CZ_MC_TREG_SMEM, rebootr, &dword, B_FALSE); + value = EFX_DWORD_FIELD(dword, EFX_DWORD_0); + + if (value == 0) + return (0); + + EFX_ZERO_DWORD(dword); + EFX_BAR_TBL_WRITED(enp, FR_CZ_MC_TREG_SMEM, rebootr, &dword, B_FALSE); + + if (value == MC_STATUS_DWORD_ASSERT) + return (EINTR); + else + return (EIO); +#endif +} + +extern __checkReturn boolean_t +siena_mcdi_poll_response( + __in efx_nic_t *enp) +{ + efx_mcdi_iface_t *emip = &(enp->en_mcdi.em_emip); + efx_dword_t hdr; + unsigned int pdur; + + EFSYS_ASSERT(emip->emi_port == 1 || emip->emi_port == 2); + pdur = SIENA_MCDI_PDU(emip); + + EFX_BAR_TBL_READD(enp, FR_CZ_MC_TREG_SMEM, pdur, &hdr, B_FALSE); + return (EFX_DWORD_FIELD(hdr, MCDI_HEADER_RESPONSE) ? B_TRUE : B_FALSE); +} + + void +siena_mcdi_read_response( + __in efx_nic_t *enp, + __out_bcount(length) void *bufferp, + __in size_t offset, + __in size_t length) +{ + efx_mcdi_iface_t *emip = &(enp->en_mcdi.em_emip); + unsigned int pdur; + unsigned int pos = 0; + efx_dword_t data; + size_t remaining = length; + + EFSYS_ASSERT(emip->emi_port == 1 || emip->emi_port == 2); + pdur = SIENA_MCDI_PDU(emip); + + while (remaining > 0) { + size_t chunk = MIN(remaining, sizeof (data)); + + EFX_BAR_TBL_READD(enp, FR_CZ_MC_TREG_SMEM, + pdur + ((offset + pos) >> 2), &data, B_FALSE); + memcpy((uint8_t *)bufferp + pos, &data, chunk); + pos += chunk; + remaining -= chunk; + } +} + + __checkReturn efx_rc_t +siena_mcdi_init( + __in efx_nic_t *enp, + __in const efx_mcdi_transport_t *mtp) +{ + efx_mcdi_iface_t *emip = &(enp->en_mcdi.em_emip); + efx_oword_t oword; + unsigned int portnum; + efx_rc_t rc; + + _NOTE(ARGUNUSED(mtp)) + + EFSYS_ASSERT(enp->en_family == EFX_FAMILY_SIENA); + + /* Determine the port number to use for MCDI */ + EFX_BAR_READO(enp, FR_AZ_CS_DEBUG_REG, &oword); + portnum = EFX_OWORD_FIELD(oword, FRF_CZ_CS_PORT_NUM); + + if (portnum == 0) { + /* Presumably booted from ROM; only MCDI port 1 will work */ + emip->emi_port = 1; + } else if (portnum <= 2) { + emip->emi_port = portnum; + } else { + rc = EINVAL; + goto fail1; + } + + /* Siena BootROM and firmware only support MCDIv1 */ + emip->emi_max_version = 1; + + /* + * Wipe the atomic reboot status so subsequent MCDI requests succeed. + * BOOT_STATUS is preserved so eno_nic_probe() can boot out of the + * assertion handler. + */ + (void) siena_mcdi_poll_reboot(enp); + + return (0); + +fail1: + EFSYS_PROBE1(fail1, efx_rc_t, rc); + + return (rc); +} + + void +siena_mcdi_fini( + __in efx_nic_t *enp) +{ + _NOTE(ARGUNUSED(enp)) +} + + __checkReturn efx_rc_t +siena_mcdi_feature_supported( + __in efx_nic_t *enp, + __in efx_mcdi_feature_id_t id, + __out boolean_t *supportedp) +{ + efx_rc_t rc; + + EFSYS_ASSERT3U(enp->en_family, ==, EFX_FAMILY_SIENA); + + switch (id) { + case EFX_MCDI_FEATURE_FW_UPDATE: + case EFX_MCDI_FEATURE_LINK_CONTROL: + case EFX_MCDI_FEATURE_MACADDR_CHANGE: + case EFX_MCDI_FEATURE_MAC_SPOOFING: + *supportedp = B_TRUE; + break; + default: + rc = ENOTSUP; + goto fail1; + } + + return (0); + +fail1: + EFSYS_PROBE1(fail1, efx_rc_t, rc); + + return (rc); +} + +/* Default timeout for MCDI command processing. */ +#define SIENA_MCDI_CMD_TIMEOUT_US (10 * 1000 * 1000) + + void +siena_mcdi_get_timeout( + __in efx_nic_t *enp, + __in efx_mcdi_req_t *emrp, + __out uint32_t *timeoutp) +{ + _NOTE(ARGUNUSED(enp, emrp)) + + *timeoutp = SIENA_MCDI_CMD_TIMEOUT_US; +} + + +#endif /* EFSYS_OPT_SIENA && EFSYS_OPT_MCDI */ diff --git a/pool/shard004/C/0100698_cpu.c b/pool/shard004/C/0100698_cpu.c new file mode 100644 index 0000000000000000000000000000000000000000..31a41b0e1b6a00022bd36a57ff8f3d60f1f72fd8 --- /dev/null +++ b/pool/shard004/C/0100698_cpu.c @@ -0,0 +1,45 @@ + +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include + +static int cnmips_cu2_call(struct notifier_block *nfb, unsigned long action, + void *data) +{ + unsigned long flags; + unsigned int status; + + switch (action) { + case CU2_EXCEPTION: + prefetch(¤t->thread.cp2); + local_irq_save(flags); + KSTK_STATUS(current) |= ST0_CU2; + status = read_c0_status(); + write_c0_status(status | ST0_CU2); + octeon_cop2_restore(&(current->thread.cp2)); + write_c0_status(status & ~ST0_CU2); + local_irq_restore(flags); + + return NOTIFY_BAD; /* Don't call default notifier */ + } + + return NOTIFY_OK; /* Let default notifier send signals */ +} + +static struct notifier_block cnmips_cu2_notifier = { + .notifier_call = cnmips_cu2_call, +}; + +static int cnmips_cu2_setup(void) +{ + return register_cu2_notifier(&cnmips_cu2_notifier); +} +early_initcall(cnmips_cu2_setup); diff --git a/pool/shard004/C/0100700_server.c b/pool/shard004/C/0100700_server.c new file mode 100644 index 0000000000000000000000000000000000000000..6fc39ebf2cd9576bfedb60c85fd12ce3b8f03f0f --- /dev/null +++ b/pool/shard004/C/0100700_server.c @@ -0,0 +1,164 @@ +#include +#include +#include "../../include/lib.h" +#include "../../include/database.h" +#include "../../include/mysqlwrapper.h" +#include "../../include/stringwrapper.h" +#include "../../include/addrwrapper.h" +#include "../../include/socketwrapper.h" +#include "../../include/readline.h" +#include "../../include/protocol.h" + +/* initial cleaning macro for parent server process */ +#define PRE_START_CLEANING() \ + do \ + { \ + close (listenfd); \ + return EXIT_FAILURE; \ + } \ + while (0) + +/* full clean up macro for child server process */ +//TODO: shutdown zamyka zamknięte połączenie zupełnie niepotrzebnie!!! +//select??? na sockfd ? -- rozwiązanie uniwersalne (do biblioteki?) +#define CHILD_CLEAN_EXIT(STATUS) \ + do \ + { \ + close_mysql_connection (Mysqlconn); \ + close (clientfd); \ + free (Protocol); \ + exit (STATUS); \ + } while (0) + + +//TODO: remove this to the header!!! +extern int login_handler_server (int, Mysql_conn_t*, char* ,const Template*); + +/* ------------------server error messages ------------------------------- */ +/* server start template */ +static const char* ser_start_templ = "Server started at port %s."; +/* server fork error */ +static const char* ser_fork_templ = "Main server loop fork error."; +/* ----------------------------------------------------------------------- */ + + +/* main server function for chat server application */ +int +main(int argc, char **argv) +{ + int listenfd; /* server's listen socket file descriptor */ + int clientfd; /* clients's connect file descriptor */ + pid_t childpid; + struct sockaddr_in cliaddr; + socklen_t clilen = sizeof (cliaddr); + struct sockaddr_in servaddr; + Mysql_conn_t* Mysqlconn = 0; /* mysql aggregate struct for server */ + int ret = 0; /* buffer for output statuses */ + char output_login[MAXUSER]; /* user's login */ + + if (argc != 2) + { + printf ("`chat_server' usage: server "); + return EXIT_FAILURE; + } + + /********** initial chat_server database administration ******************/ + /*************************************************************************/ + ret = Mysql_library_init (0, NULL, NULL); + if (ret != 0) return EXIT_FAILURE; + + Mysqlconn = open_mysql_connection (Mysqlconn); + if (Mysqlconn == NULL) + { + Mysql_library_end (); + return EXIT_FAILURE; + } + + ret = build_database (Mysqlconn); + if (ret == RETURN_ERROR) + { + close_mysql_connection (Mysqlconn); + return EXIT_FAILURE; + } + close_mysql_connection (Mysqlconn); /* parent does not need this */ + + /********** initial chat_server network socket administration ************/ + /*************************************************************************/ + listenfd = Socket (AF_INET, SOCK_STREAM, 0); /* server listenning socket */ + if (listenfd == RETURN_CONNECT_ERROR) return EXIT_FAILURE; + /* fill server listenning socker addr struct */ + memset (&servaddr, 0, sizeof(servaddr)); + servaddr.sin_family = AF_INET; + servaddr.sin_addr.s_addr = htonl (INADDR_ANY); /* 0.0.0.0 for ipv4 */ + servaddr.sin_port = htons (atoi (argv[1])); + + //TODO : tutaj wstawić ustawienie flagi SO_REUSEADDR !!!(str 266) + // żeby można było swobodnie restartować serwer!!! + + ret = Bind (listenfd, (SA *)&servaddr, sizeof(servaddr)); + if (ret == RETURN_CONNECT_ERROR) PRE_START_CLEANING(); + + ret = Listen (listenfd, LISTENQ); + if (ret == RETURN_CONNECT_ERROR) PRE_START_CLEANING(); + + /* now apply SIGCHLD signal handler (BEFORE server loop, BEFORE accept) + * no zombies needed --> clear memory after child exit */ + //struct sigaction act; + /* act.sa_handler = some_handler; */ + //act.sa_flags = SA_NOCLDWAIT; + //sigaction (SIGCHLD, &act, NULL); + + /* put this info into systemd journal, almost all errors and warnings are + * handled by respective wrapper functions, the rest is only server admin's + * specific */ + sd_journal_print (LOG_ERR, ser_start_templ, argv[1]); + /*********************main server work starts here************************/ + /*************************************************************************/ + /* every shutdown must be performed here (not in subfunctions!!!) */ + while (true) + { + clientfd = Accept (listenfd, (SA *)&cliaddr, &clilen); + if (clientfd < 0) break; /* should never reach this */ + + childpid = fork (); + if (childpid == 0) + { + /*************************CHILD SERVER*******************************/ + close (listenfd); /* close listening socket for child */ + Template* Protocol = NULL; /* initialize protocol struct */ + Protocol = templates_init(); /* GLOBAL for functions below */ + if (Protocol == NULL) + { + close (clientfd); + exit (EXIT_FAILURE); + } + + Mysqlconn = open_mysql_connection (Mysqlconn); + if (Mysqlconn == NULL) + { + close (clientfd); + free (Protocol); + exit (EXIT_FAILURE); + } + + /* -------------------user logins--------------------------------*/ + ret = login_handler_server(clientfd, Mysqlconn, output_login, Protocol); + if (ret != RETURN_OK && ret != RETURN_LOGOUT) + CHILD_CLEAN_EXIT(EXIT_FAILURE); + /* -------------------user chats---------------------------------*/ + CHILD_CLEAN_EXIT(EXIT_SUCCESS); + } + /*****************************PARENT SERVER***************************/ + else if (childpid > 0) + { + close (clientfd); /* close socket fd for parent */ + } + /*****************************ERROR***********************************/ + else /*resources depleted */ + { + sd_journal_perror (ser_fork_templ); + continue; + } + } /*-----> end of the server listenning loop */ + exit (EXIT_FAILURE); /* clientfd < 0 */ +} diff --git a/pool/shard004/C/0100701_p_lge_ums.c b/pool/shard004/C/0100701_p_lge_ums.c new file mode 100644 index 0000000000000000000000000000000000000000..54aef78d3830bba860c99c29fda1d756c3eee5bc --- /dev/null +++ b/pool/shard004/C/0100701_p_lge_ums.c @@ -0,0 +1,85 @@ +/* Copyright (C) 2010 emsys Embedded Systems GmbH + * + * 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 "disable_init_defines.h" + +#include "p_adb.h" +#include "p_msc.h" +#include "personality.h" + + +static int lge_ums_bind(struct usb_configuration *c) +{ + int ret = 0; + struct usb_device_descriptor* device_descriptor = personality_cdev_to_device_desc(c->cdev); + + printk(KERN_INFO "%s(%p)\n", __func__, c); + + if (!device_descriptor) { + return -EINVAL; + } + + ret = mass_storage_function_add(c->cdev, c); + if (ret) + return ret; + device_descriptor->bDeviceClass = 2; + device_descriptor->idProduct = 0x6181; + return 0; +} + +static int lge_ums_adb_bind(struct usb_configuration *c) +{ + int ret = lge_ums_bind(c); + if (ret) { + return ret; + } + return adb_function_add(c->cdev, c); +} + +static void lge_ums_unbind(struct usb_configuration *c) +{ + printk(KERN_INFO "%s\n", __func__); + personality_cdev_to_device_desc(c->cdev)->bDeviceClass = 0; +} + +void add_lge_ums_adb_configurations(struct usb_composite_dev* cdev, const char* name) +{ + static struct usb_configuration config = { + .bind = lge_ums_adb_bind, + .unbind = lge_ums_unbind, + .bConfigurationValue = 1, + .bmAttributes = USB_CONFIG_ATT_ONE | USB_CONFIG_ATT_SELFPOWER, + }; + printk(KERN_INFO "%s\n", __func__); + config.label = name; + usb_add_config(cdev, &config); +} + +void add_lge_ums_configurations(struct usb_composite_dev* cdev, const char* name) +{ + static struct usb_configuration config = { + .bind = lge_ums_bind, + .unbind = lge_ums_unbind, + .bConfigurationValue = 1, + .bmAttributes = USB_CONFIG_ATT_ONE | USB_CONFIG_ATT_SELFPOWER, + }; + printk(KERN_INFO "%s\n", __func__); + config.label = name; + usb_add_config(cdev, &config); +} diff --git a/pool/shard004/C/0100705_sndi2s.c b/pool/shard004/C/0100705_sndi2s.c new file mode 100644 index 0000000000000000000000000000000000000000..1db611415a3ac133bfd8c8411c20f90e73434397 --- /dev/null +++ b/pool/shard004/C/0100705_sndi2s.c @@ -0,0 +1,213 @@ +/* + * sound\soc\sun5i\i2s\sndi2s.c + * (C) Copyright 2007-2011 + * Reuuimlla Technology Co., Ltd. + * chenpailin + * + * some simple description for this code + * + * 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 "sndi2s.h" + +struct sndi2s_priv { + int sysclk; + int dai_fmt; + + struct snd_pcm_substream *master_substream; + struct snd_pcm_substream *slave_substream; +}; + +static int i2s_used = 0; +#define sndi2s_RATES (SNDRV_PCM_RATE_8000_192000|SNDRV_PCM_RATE_KNOT) +#define sndi2s_FORMATS (SNDRV_PCM_FMTBIT_S8 | SNDRV_PCM_FMTBIT_S16_LE | \ + SNDRV_PCM_FMTBIT_S18_3LE | SNDRV_PCM_FMTBIT_S20_3LE) + +//hdmi_audio_t hdmi_parameter; + +static int sndi2s_mute(struct snd_soc_dai *dai, int mute) +{ + return 0; +} + +static int sndi2s_startup(struct snd_pcm_substream *substream, + struct snd_soc_dai *dai) +{ + return 0; +} + +static void sndi2s_shutdown(struct snd_pcm_substream *substream, + struct snd_soc_dai *dai) +{ + +} + +static int sndi2s_hw_params(struct snd_pcm_substream *substream, + struct snd_pcm_hw_params *params, + struct snd_soc_dai *dai) +{ + //hdmi_parameter.sample_rate = params_rate(params); + + return 0; +} + +static int sndi2s_set_dai_sysclk(struct snd_soc_dai *codec_dai, + int clk_id, unsigned int freq, int dir) +{ + return 0; +} + +static int sndi2s_set_dai_clkdiv(struct snd_soc_dai *codec_dai, int div_id, int div) +{ + +// hdmi_parameter.fs_between = div; + + return 0; +} + +static int sndi2s_set_dai_fmt(struct snd_soc_dai *codec_dai, + unsigned int fmt) +{ + return 0; +} + +struct snd_soc_dai_ops sndi2s_dai_ops = { + .startup = sndi2s_startup, + .shutdown = sndi2s_shutdown, + .hw_params = sndi2s_hw_params, + .digital_mute = sndi2s_mute, + .set_sysclk = sndi2s_set_dai_sysclk, + .set_clkdiv = sndi2s_set_dai_clkdiv, + .set_fmt = sndi2s_set_dai_fmt, +}; + +struct snd_soc_dai_driver sndi2s_dai = { + .name = "sndi2s", + /* playback capabilities */ + .playback = { + .stream_name = "Playback", + .channels_min = 1, + .channels_max = 2, + .rates = sndi2s_RATES, + .formats = sndi2s_FORMATS, + }, + .capture = { + .stream_name = "Capture", + .channels_min = 1, + .channels_max = 2, + .rates = sndi2s_RATES, + .formats = sndi2s_FORMATS, + }, + /* pcm operations */ + .ops = &sndi2s_dai_ops, + .symmetric_rates = 1, +}; +EXPORT_SYMBOL(sndi2s_dai); + +static int sndi2s_soc_probe(struct snd_soc_codec *codec) +{ + struct sndi2s_priv *sndi2s; + + sndi2s = kzalloc(sizeof(struct sndi2s_priv), GFP_KERNEL); + if(sndi2s == NULL){ + return -ENOMEM; + } + snd_soc_codec_set_drvdata(codec, sndi2s); + + return 0; +} + +/* power down chip */ +static int sndi2s_soc_remove(struct snd_soc_codec *codec) +{ + struct sndhdmi_priv *sndi2s = snd_soc_codec_get_drvdata(codec); + + kfree(sndi2s); + + return 0; +} + +static struct snd_soc_codec_driver soc_codec_dev_sndi2s = { + .probe = sndi2s_soc_probe, + .remove = sndi2s_soc_remove, +}; + +static int __devinit sndi2s_codec_probe(struct platform_device *pdev) +{ + return snd_soc_register_codec(&pdev->dev, &soc_codec_dev_sndi2s, &sndi2s_dai, 1); +} + +static int __devexit sndi2s_codec_remove(struct platform_device *pdev) +{ + snd_soc_unregister_codec(&pdev->dev); + return 0; +} +/*data relating*/ +static struct platform_device sndi2s_codec_device = { + .name = "sun5i-i2s-codec", +}; + +/*method relating*/ +static struct platform_driver sndi2s_codec_driver = { + .driver = { + .name = "sun5i-i2s-codec", + .owner = THIS_MODULE, + }, + .probe = sndi2s_codec_probe, + .remove = __devexit_p(sndi2s_codec_remove), +}; + +static int __init sndi2s_codec_init(void) +{ + int err = 0; + int ret = 0; + + ret = script_parser_fetch("i2s_para","i2s_used", &i2s_used, sizeof(int)); + if (ret) { + printk("[I2S]sndi2s_init fetch i2s using configuration failed\n"); + } + + if (i2s_used) { + if((err = platform_device_register(&sndi2s_codec_device)) < 0) + return err; + + if ((err = platform_driver_register(&sndi2s_codec_driver)) < 0) + return err; + } else { + printk("[I2S]sndi2s cannot find any using configuration for controllers, return directly!\n"); + return 0; + } + + return 0; +} +module_init(sndi2s_codec_init); + +static void __exit sndi2s_codec_exit(void) +{ + if (i2s_used) { + i2s_used = 0; + platform_driver_unregister(&sndi2s_codec_driver); + } +} +module_exit(sndi2s_codec_exit); + +MODULE_DESCRIPTION("SNDI2S ALSA soc codec driver"); +MODULE_AUTHOR("Zoltan Devai, Christian Pellegrin "); +MODULE_LICENSE("GPL"); +MODULE_ALIAS("platform:sun5i-i2s-codec"); diff --git a/pool/shard004/C/0100706_relic_cp_ecdh.c b/pool/shard004/C/0100706_relic_cp_ecdh.c new file mode 100644 index 0000000000000000000000000000000000000000..153f423c4d8af43fe891474047226aee3e4bc45a --- /dev/null +++ b/pool/shard004/C/0100706_relic_cp_ecdh.c @@ -0,0 +1,107 @@ +/* + * RELIC is an Efficient LIbrary for Cryptography + * Copyright (C) 2007-2014 RELIC Authors + * + * This file is part of RELIC. RELIC is legal property of its developers, + * whose names are not listed here. Please refer to the COPYRIGHT file + * for contact information. + * + * RELIC 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. + * + * RELIC is distributed in the hope that 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 RELIC. If not, see . + */ + +/** + * @file + * + * Implementation of the ECDH protocol. + * + * @version $Id: relic_cp_ecdh.c 1764 2014-02-05 17:29:46Z dfaranha $ + * @ingroup cp + */ + +#include "relic.h" +#include "relic_test.h" +#include "relic_bench.h" + +/*============================================================================*/ +/* Public definitions */ +/*============================================================================*/ + +int cp_ecdh_gen(bn_t d, ec_t q) { + bn_t n; + int result = STS_OK; + + bn_null(n); + + TRY { + bn_new(n); + + ec_curve_get_ord(n); + + do { + bn_rand(d, BN_POS, bn_bits(n)); + bn_mod(d, d, n); + } while (bn_is_zero(d)); + + ec_mul_gen(q, d); + } + CATCH_ANY { + result = STS_ERR; + } + FINALLY { + bn_free(n); + } + + return result; +} + +int cp_ecdh_key(uint8_t *key, int key_len, bn_t d, ec_t q) { + ec_t p; + bn_t x, h; + int l, result = STS_OK; + uint8_t _x[FC_BYTES]; + + ec_null(p); + bn_null(x); + bn_null(h); + + TRY { + ec_new(p); + bn_new(x); + bn_new(h); + + ec_curve_get_cof(h); + if (bn_bits(h) < BN_DIGIT) { + ec_mul_dig(p, q, h->dp[0]); + } else { + ec_mul(p, q, h); + } + ec_mul(p, p, d); + if (ec_is_infty(p)) { + result = STS_ERR; + } + ec_get_x(x, p); + bn_size_bin(&l, x); + bn_write_bin(_x, l, x); + md_kdf2(key, key_len, _x, l); + } + CATCH_ANY { + THROW(ERR_CAUGHT); + } + FINALLY { + ec_free(p); + bn_free(x); + bn_free(h); + } + return result; +} diff --git a/pool/shard004/C/0100716_pr66691.c b/pool/shard004/C/0100716_pr66691.c new file mode 100644 index 0000000000000000000000000000000000000000..da78808acd235a608fefac60a1a254ce39b26c69 --- /dev/null +++ b/pool/shard004/C/0100716_pr66691.c @@ -0,0 +1,64 @@ +/* PR debug/66691 */ +/* { dg-do compile } */ +/* { dg-require-effective-target ia32 } */ +/* { dg-options "-O3 -g -mtune=generic -march=i686" } */ + +unsigned int a; +int b[2], c, d, e, f, g, h, i, k[8], l, m, s, t, w; +static int j; + +void +fn1 (long long p) +{ + int t = p; + c = c ^ b[c ^ (t & 1)]; +} + +static void +fn2 (long long p) +{ + c = c ^ b[1 ^ (d & 1)]; + fn1 (p >> 1 & 1); + fn1 (p >> 2); +} + +static void +fn3 () +{ + unsigned char p; + f = g = 0; + for (h = 0; h < 6; h++) + { + for (s = 0; s < 7; s++) + if (k[s+1]) + g = 0; + else + for (j = 0; j < 2; j++) + ; + t = j > 2 ? 0 : 1 >> j; + } + if (l) + { + short q[2]; + q[0] = q[1] = 0; + if (m) + for (i = 0; i < 2; i++) + { + unsigned char r = q[i]; + p = f ? r % f : r; + e = ((p > 0) <= (q[i] ^ 1)) + a; + if (k[1]) + for (e = 0; e != 18; ++e) + k[0] = 0; + } + } +} + +int +main () +{ + fn3 (); + fn2 (w); + fn2 (j); + return 0; +} diff --git a/pool/shard004/C/0100722_CWE78_OS_Command_Injection__wchar_t_file_w32_spawnvp_66a.c b/pool/shard004/C/0100722_CWE78_OS_Command_Injection__wchar_t_file_w32_spawnvp_66a.c new file mode 100644 index 0000000000000000000000000000000000000000..8c7ca693c69fb2f461360818b65e90c7709552ef --- /dev/null +++ b/pool/shard004/C/0100722_CWE78_OS_Command_Injection__wchar_t_file_w32_spawnvp_66a.c @@ -0,0 +1,132 @@ +/* TEMPLATE GENERATED TESTCASE FILE +Filename: CWE78_OS_Command_Injection__wchar_t_file_w32_spawnvp_66a.c +Label Definition File: CWE78_OS_Command_Injection.strings.label.xml +Template File: sources-sink-66a.tmpl.c +*/ +/* + * @description + * CWE: 78 OS Command Injection + * BadSource: file Read input from a file + * GoodSource: Fixed string + * Sinks: w32_spawnvp + * BadSink : execute command with wspawnvp + * Flow Variant: 66 Data flow: data passed in an array 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"-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 + +#include + +#ifndef OMITBAD + +/* bad function declaration */ +void CWE78_OS_Command_Injection__wchar_t_file_w32_spawnvp_66b_badSink(wchar_t * dataArray[]); + +void CWE78_OS_Command_Injection__wchar_t_file_w32_spawnvp_66_bad() +{ + wchar_t * data; + wchar_t * dataArray[5]; + wchar_t dataBuffer[100] = COMMAND_ARG2; + data = dataBuffer; + { + /* 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); + } + } + } + /* put data in array */ + dataArray[2] = data; + CWE78_OS_Command_Injection__wchar_t_file_w32_spawnvp_66b_badSink(dataArray); +} + +#endif /* OMITBAD */ + +#ifndef OMITGOOD + +/* goodG2B uses the GoodSource with the BadSink */ +void CWE78_OS_Command_Injection__wchar_t_file_w32_spawnvp_66b_goodG2BSink(wchar_t * dataArray[]); + +static void goodG2B() +{ + wchar_t * data; + wchar_t * dataArray[5]; + wchar_t dataBuffer[100] = COMMAND_ARG2; + data = dataBuffer; + /* FIX: Append a fixed string to data (not user / external input) */ + wcscat(data, L"*.*"); + dataArray[2] = data; + CWE78_OS_Command_Injection__wchar_t_file_w32_spawnvp_66b_goodG2BSink(dataArray); +} + +void CWE78_OS_Command_Injection__wchar_t_file_w32_spawnvp_66_good() +{ + goodG2B(); +} + +#endif /* OMITGOOD */ + +/* Below is the main(). It is only used when building this testcase on + * its own for testing or for building a binary to use in testing binary + * analysis tools. It is not used when compiling all the testcases as one + * application, which is how source code analysis tools are tested. + */ + +#ifdef INCLUDEMAIN + +int main(int argc, char * argv[]) +{ + /* seed randomness */ + srand( (unsigned)time(NULL) ); +#ifndef OMITGOOD + printLine("Calling good()..."); + CWE78_OS_Command_Injection__wchar_t_file_w32_spawnvp_66_good(); + printLine("Finished good()"); +#endif /* OMITGOOD */ +#ifndef OMITBAD + printLine("Calling bad()..."); + CWE78_OS_Command_Injection__wchar_t_file_w32_spawnvp_66_bad(); + printLine("Finished bad()"); +#endif /* OMITBAD */ + return 0; +} + +#endif diff --git a/pool/shard004/C/0100726_mcd-debug.c b/pool/shard004/C/0100726_mcd-debug.c new file mode 100644 index 0000000000000000000000000000000000000000..41246fce4593761f5f73f03e7529bc7e1f8adb05 --- /dev/null +++ b/pool/shard004/C/0100726_mcd-debug.c @@ -0,0 +1,201 @@ +/* vi: set et sw=4 ts=8 cino=t0,(0: */ +/* -*- Mode: C; indent-tabs-mode: nil; c-basic-offset: 4; tab-width: 8 -*- */ +/* + * This file is part of mission-control + * + * Copyright (C) 2007-2009 Nokia Corporation. + * Copyright (C) 2008 Collabora Ltd. + * + * Contact: Naba Kumar + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public License + * version 2.1 as published by the Free Software Foundation. + * + * This library is distributed in the hope that it will be useful, but + * WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA + * 02110-1301 USA + * + */ + +/** + * SECTION:mcd-debug + * @title: Debugging + * @short_description: Debugging utilities + * @see_also: + * @stability: Unstable + * @include: mcd-debug.h + * + * FIXME + */ + +#include + +#include + +#include +#include + +#include + +#include "mcd-debug.h" +#include "mcd-operation.h" + +gint mcd_debug_level = 0; + +static void +mcd_debug_print_tree_real (gpointer object, gint level) +{ + GString *indent_str; + gchar *indent = " "; + gint i; + + indent_str = g_string_new (""); + + for (i = 0; i < level; i++) + { + g_string_append (indent_str, indent); + } + + g_debug ("%s%s (%p): %d", indent_str->str, + G_OBJECT_TYPE_NAME(object), object, G_OBJECT (object)->ref_count); + + if (MCD_IS_OPERATION (object)) + { + const GList *missions = mcd_operation_get_missions (MCD_OPERATION (object)); + const GList *node = missions; + while (node) + { + mcd_debug_print_tree_real (node->data, level + 1); + node = g_list_next (node); + } + } + g_string_free (indent_str, TRUE); +} + +/* We don't really have debug categories yet */ + +typedef enum { + MCD_DEBUG_MISC = 1 << 0, + MCD_DEBUG_TREES = 1 << 1 +} McdDebugCategory; + +static GDebugKey const keys[] = { + { "misc", MCD_DEBUG_MISC }, + { "trees", MCD_DEBUG_TREES }, + { NULL, 0 } +}; + +static McdDebugCategory categories = 0; + +void +mcd_debug_print_tree (gpointer object) +{ + g_return_if_fail (MCD_IS_MISSION (object)); + + if (categories & MCD_DEBUG_TREES) + { + g_debug ("Object Hierarchy of object %p", object); + g_debug ("["); + mcd_debug_print_tree_real (object, 1); + g_debug ("]"); + } +} + +void mcd_debug_init () +{ + gchar *mc_debug_str; + guint level; + + mc_debug_str = getenv ("MC_DEBUG"); + + if (mc_debug_str) + { + /* historically, MC_DEBUG was an integer; try that first */ + level = atoi (mc_debug_str); + + /* if it wasn't an integer; try interpreting it as a + * telepathy-glib-style flags-word */ + if (level == 0) + { + categories = g_parse_debug_string (mc_debug_str, keys, + G_N_ELEMENTS (keys) - 1); + tp_debug_set_flags (mc_debug_str); + + /* mcd-debug.h uses the value of mcd_debug_level directly, so + * we need to set it nonzero to get uncategorized messages */ + if ((categories & MCD_DEBUG_MISC) != 0 && mcd_debug_level == 0) + { + mcd_debug_level = 1; + } + } + else + { + /* this is API, and will also try to set up categories from the + * level */ + mcd_debug_set_level (level); + } + } + + mcp_set_debug ((mcd_debug_level >= 1)); + mcp_debug_init (); + + tp_debug_divert_messages (g_getenv ("MC_LOGFILE")); + + if (mcd_debug_level >= 1) + g_debug ("%s version %s", PACKAGE, VERSION); +} + +void +mcd_debug_set_level (gint level) +{ + mcd_debug_level = level; + + mcp_set_debug ((mcd_debug_level >= 1)); + + if (level >= 1) + { + categories |= MCD_DEBUG_MISC; + } + else + { + categories = 0; + } + + if (level >= 2) + { + categories |= MCD_DEBUG_TREES; + } +} + +void +mcd_debug (const gchar *format, ...) +{ + gchar *message = NULL; + gchar **formatted = NULL; + TpDebugSender *dbg = tp_debug_sender_dup (); + va_list args; + + if (_mcd_debug_get_level () > 0) + formatted = &message; + + va_start (args, format); + tp_debug_sender_add_message_vprintf (dbg, NULL, formatted, + G_LOG_DOMAIN, G_LOG_LEVEL_DEBUG, format, args); + va_end (args); + + if (!tp_str_empty (message)) + { + g_debug ("%s", message); + g_free (message); + } + + /* NOTE: the sender must be cached elsewhere, or this gets EXPENSIVE: */ + g_object_unref (dbg); +} diff --git a/pool/shard004/C/0100731_oldsemaphore.c b/pool/shard004/C/0100731_oldsemaphore.c new file mode 100644 index 0000000000000000000000000000000000000000..80a82dfcf6896aa9b32370da44a89b873ced01a4 --- /dev/null +++ b/pool/shard004/C/0100731_oldsemaphore.c @@ -0,0 +1,245 @@ +/* + * This file contains the old semaphore code that we need to + * preserve for glibc-2.0 backwards compatibility. Port to glibc 2.1 + * done by Cristian Gafton. + */ + +/* Linuxthreads - a simple clone()-based implementation of Posix */ +/* threads for Linux. */ +/* Copyright (C) 1996 Xavier Leroy (Xavier.Leroy@inria.fr) */ +/* */ +/* This program 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 program is distributed in the hope that it will be useful, */ +/* but WITHOUT ANY WARRANTY; without even the implied warranty of */ +/* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the */ +/* GNU Library General Public License for more details. */ + +/* Semaphores a la POSIX 1003.1b */ +#include +#if SHLIB_COMPAT(libpthread, GLIBC_2_0, GLIBC_2_1) + +#include +#include "pthread.h" +#include "internals.h" +#include "spinlock.h" +#include "restart.h" +#include "queue.h" + +typedef struct { + long int sem_status; + int sem_spinlock; +} old_sem_t; + +extern int __old_sem_init (old_sem_t *__sem, int __pshared, unsigned int __value); +extern int __old_sem_wait (old_sem_t *__sem); +extern int __old_sem_trywait (old_sem_t *__sem); +extern int __old_sem_post (old_sem_t *__sem); +extern int __old_sem_getvalue (old_sem_t *__sem, int *__sval); +extern int __old_sem_destroy (old_sem_t *__sem); + + +/* Maximum value the semaphore can have. */ +#define SEM_VALUE_MAX ((int) ((~0u) >> 1)) + +static inline int sem_compare_and_swap(old_sem_t *sem, long oldval, long newval) +{ + return compare_and_swap(&sem->sem_status, oldval, newval, &sem->sem_spinlock); +} + +/* The state of a semaphore is represented by a long int encoding + either the semaphore count if >= 0 and no thread is waiting on it, + or the head of the list of threads waiting for the semaphore. + To distinguish the two cases, we encode the semaphore count N + as 2N+1, so that it has the lowest bit set. + + A sequence of sem_wait operations on a semaphore initialized to N + result in the following successive states: + 2N+1, 2N-1, ..., 3, 1, &first_waiting_thread, &second_waiting_thread, ... +*/ + +static void sem_restart_list(pthread_descr waiting); + +int __old_sem_init(old_sem_t *sem, int pshared, unsigned int value) +{ + if (value > SEM_VALUE_MAX) { + errno = EINVAL; + return -1; + } + if (pshared) { + errno = ENOSYS; + return -1; + } + sem->sem_spinlock = __LT_SPINLOCK_INIT; + sem->sem_status = ((long)value << 1) + 1; + return 0; +} + +/* Function called by pthread_cancel to remove the thread from + waiting inside __old_sem_wait. Here we simply unconditionally + indicate that the thread is to be woken, by returning 1. */ + +static int old_sem_extricate_func(void *obj, pthread_descr th) +{ + return 1; +} + +int __old_sem_wait(old_sem_t * sem) +{ + long oldstatus, newstatus; + volatile pthread_descr self = thread_self(); + pthread_descr * th; + pthread_extricate_if extr; + + /* Set up extrication interface */ + extr.pu_object = 0; + extr.pu_extricate_func = old_sem_extricate_func; + + while (1) { + /* Register extrication interface */ + __pthread_set_own_extricate_if(self, &extr); + do { + oldstatus = sem->sem_status; + if ((oldstatus & 1) && (oldstatus != 1)) + newstatus = oldstatus - 2; + else { + newstatus = (long) self; + self->p_nextwaiting = (pthread_descr) oldstatus; + } + } + while (! sem_compare_and_swap(sem, oldstatus, newstatus)); + if (newstatus & 1) { + /* We got the semaphore. */ + __pthread_set_own_extricate_if(self, 0); + self->p_nextwaiting = NULL; + return 0; + } + /* Wait for sem_post or cancellation */ + suspend(self); + __pthread_set_own_extricate_if(self, 0); + + /* This is a cancellation point */ + if (self->p_canceled && self->p_cancelstate == PTHREAD_CANCEL_ENABLE) { + /* Remove ourselves from the waiting list if we're still on it */ + /* First check if we're at the head of the list. */ + do { + oldstatus = sem->sem_status; + if (oldstatus != (long) self) break; + newstatus = (long) self->p_nextwaiting; + } + while (! sem_compare_and_swap(sem, oldstatus, newstatus)); + /* Now, check if we're somewhere in the list. + There's a race condition with sem_post here, but it does not matter: + the net result is that at the time pthread_exit is called, + self is no longer reachable from sem->sem_status. */ + if (oldstatus != (long) self && (oldstatus & 1) == 0) { + for (th = &(((pthread_descr) oldstatus)->p_nextwaiting); + *th != NULL && *th != (pthread_descr) 1; + th = &((*th)->p_nextwaiting)) { + if (*th == self) { + *th = self->p_nextwaiting; + break; + } + } + } + __pthread_do_exit(PTHREAD_CANCELED, CURRENT_STACK_FRAME); + } + } +} + +int __old_sem_trywait(old_sem_t * sem) +{ + long oldstatus, newstatus; + + do { + oldstatus = sem->sem_status; + if ((oldstatus & 1) == 0 || (oldstatus == 1)) { + errno = EAGAIN; + return -1; + } + newstatus = oldstatus - 2; + } + while (! sem_compare_and_swap(sem, oldstatus, newstatus)); + return 0; +} + +int __old_sem_post(old_sem_t * sem) +{ + long oldstatus, newstatus; + + do { + oldstatus = sem->sem_status; + if ((oldstatus & 1) == 0) + newstatus = 3; + else { + if (oldstatus >= SEM_VALUE_MAX) { + /* Overflow */ + errno = ERANGE; + return -1; + } + newstatus = oldstatus + 2; + } + } + while (! sem_compare_and_swap(sem, oldstatus, newstatus)); + if ((oldstatus & 1) == 0) + sem_restart_list((pthread_descr) oldstatus); + return 0; +} + +int __old_sem_getvalue(old_sem_t * sem, int * sval) +{ + long status = sem->sem_status; + if (status & 1) + *sval = (int)((unsigned long) status >> 1); + else + *sval = 0; + return 0; +} + +int __old_sem_destroy(old_sem_t * sem) +{ + if ((sem->sem_status & 1) == 0) { + errno = EBUSY; + return -1; + } + return 0; +} + +/* Auxiliary function for restarting all threads on a waiting list, + in priority order. */ + +static void sem_restart_list(pthread_descr waiting) +{ + pthread_descr th, towake, *p; + + /* Sort list of waiting threads by decreasing priority (insertion sort) */ + towake = NULL; + while (waiting != (pthread_descr) 1) { + th = waiting; + waiting = waiting->p_nextwaiting; + p = &towake; + while (*p != NULL && th->p_priority < (*p)->p_priority) + p = &((*p)->p_nextwaiting); + th->p_nextwaiting = *p; + *p = th; + } + /* Wake up threads in priority order */ + while (towake != NULL) { + th = towake; + towake = towake->p_nextwaiting; + th->p_nextwaiting = NULL; + restart(th); + } +} + +compat_symbol (libpthread, __old_sem_init, sem_init, GLIBC_2_0); +compat_symbol (libpthread, __old_sem_wait, sem_wait, GLIBC_2_0); +compat_symbol (libpthread, __old_sem_trywait, sem_trywait, GLIBC_2_0); +compat_symbol (libpthread, __old_sem_post, sem_post, GLIBC_2_0); +compat_symbol (libpthread, __old_sem_getvalue, sem_getvalue, GLIBC_2_0); +compat_symbol (libpthread, __old_sem_destroy, sem_destroy, GLIBC_2_0); + +#endif diff --git a/pool/shard004/C/0100732_mach_time.c b/pool/shard004/C/0100732_mach_time.c new file mode 100644 index 0000000000000000000000000000000000000000..18fa9b9a4d1d0622919227ff9e642c2b350a3081 --- /dev/null +++ b/pool/shard004/C/0100732_mach_time.c @@ -0,0 +1,55 @@ +#include +#include +#include +#include + +#ifndef NSEC_PER_SEC +# define NSEC_PER_SEC 1000000000ull +#endif + +kern_return_t mach_timebase_info_trap_impl( + mach_timebase_info_t info) +{ + info->numer = NSEC_PER_SEC; + info->denom = NSEC_PER_SEC; + return KERN_SUCCESS; +} + +kern_return_t mach_wait_until_impl( + uint64_t deadline) +{ + struct timespec ts = { deadline / NSEC_PER_SEC, deadline % NSEC_PER_SEC }; + +do_sleep: + if (clock_sleep(CLOCK_MONOTONIC, TIMER_ABSTIME, &ts, 0) == -1) + { + if (errno == EINTR) + goto do_sleep; + return KERN_FAILURE; + } + + return KERN_SUCCESS; +} + + +uint64_t mach_absolute_time(void) +{ + struct timespec ts; + uint64_t out; + + clock_gettime(CLOCK_MONOTONIC, &ts); + + out = ts.tv_nsec; + out += ts.tv_sec * NSEC_PER_SEC; + + return out; +} + +int __gettimeofday_with_mach(struct timeval *tv, struct timezone *tz, uint64_t *absolute) +{ + sys_gettimeofday(tv, tz); + if (absolute) + *absolute = mach_absolute_time(); + + return 0; +} diff --git a/pool/shard004/C/0100736_atarimouse.c b/pool/shard004/C/0100736_atarimouse.c new file mode 100644 index 0000000000000000000000000000000000000000..b1cce517b2f85bcd16b1dbf870967ddda039f119 --- /dev/null +++ b/pool/shard004/C/0100736_atarimouse.c @@ -0,0 +1,158 @@ +/* + * 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/shard004/C/0100737_brmon.c b/pool/shard004/C/0100737_brmon.c new file mode 100644 index 0000000000000000000000000000000000000000..39e69dbb96a9ee3549deff5f463ab48c4e7c06d2 --- /dev/null +++ b/pool/shard004/C/0100737_brmon.c @@ -0,0 +1,215 @@ +/* + * brmon.c RTnetlink listener. + * + * 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: Stephen Hemminger + * Modified by Srinivas Aji + * for use in RSTP daemon. - 2006-09-01 + * Modified by Vitalii Demianets + * for use in MSTP daemon. - 2011-07-18 + */ + +#include +#include +#include +#include +#include + +#include "log.h" +#include "libnetlink.h" +#include "bridge_ctl.h" +#include "netif_utils.h" +#include "epoll_loop.h" + +/* RFC 2863 operational status */ +enum +{ + IF_OPER_UNKNOWN, + IF_OPER_NOTPRESENT, + IF_OPER_DOWN, + IF_OPER_LOWERLAYERDOWN, + IF_OPER_TESTING, + IF_OPER_DORMANT, + IF_OPER_UP, +}; + +/* link modes */ +enum +{ + IF_LINK_MODE_DEFAULT, + IF_LINK_MODE_DORMANT, /* limit upward transition to dormant */ +}; + +static const char *port_states[] = +{ + [BR_STATE_DISABLED] = "disabled", + [BR_STATE_LISTENING] = "listening", + [BR_STATE_LEARNING] = "learning", + [BR_STATE_FORWARDING] = "forwarding", + [BR_STATE_BLOCKING] = "blocking", +}; + +static struct rtnl_handle rth; +static struct epoll_event_handler br_handler; + +struct rtnl_handle rth_state; + +static int dump_msg(const struct sockaddr_nl *who, struct nlmsghdr *n, + void *arg) +{ + struct ifinfomsg *ifi = NLMSG_DATA(n); + struct rtattr * tb[IFLA_MAX + 1]; + int len = n->nlmsg_len; + char b1[IFNAMSIZ]; + int af_family = ifi->ifi_family; + bool newlink; + int br_index; + + if(n->nlmsg_type == NLMSG_DONE) + return 0; + + len -= NLMSG_LENGTH(sizeof(*ifi)); + if(len < 0) + { + return -1; + } + + if(af_family != AF_BRIDGE && af_family != AF_UNSPEC) + return 0; + + if(n->nlmsg_type != RTM_NEWLINK && n->nlmsg_type != RTM_DELLINK) + return 0; + + parse_rtattr(tb, IFLA_MAX, IFLA_RTA(ifi), len); + + /* Check if we got this from bonding */ + if(tb[IFLA_MASTER] && af_family != AF_BRIDGE) + return 0; + + if(tb[IFLA_IFNAME] == NULL) + { + ERROR("BUG: nil ifname\n"); + return -1; + } + + if(n->nlmsg_type == RTM_DELLINK) + LOG("Deleted "); + + LOG("%d: %s ", ifi->ifi_index, (char*)RTA_DATA(tb[IFLA_IFNAME])); + + if(tb[IFLA_OPERSTATE]) + { + int state = *(int*)RTA_DATA(tb[IFLA_OPERSTATE]); + switch (state) + { + case IF_OPER_UNKNOWN: + LOG("Unknown "); + break; + case IF_OPER_NOTPRESENT: + LOG("Not Present "); + break; + case IF_OPER_DOWN: + LOG("Down "); + break; + case IF_OPER_LOWERLAYERDOWN: + LOG("Lowerlayerdown "); + break; + case IF_OPER_TESTING: + LOG("Testing "); + break; + case IF_OPER_DORMANT: + LOG("Dormant "); + break; + case IF_OPER_UP: + LOG("Up "); + break; + default: + LOG("State(%d) ", state); + } + } + + if(tb[IFLA_MTU]) + LOG("mtu %u ", *(int*)RTA_DATA(tb[IFLA_MTU])); + + if(tb[IFLA_MASTER]) + { + LOG("master %s ", + if_indextoname(*(int*)RTA_DATA(tb[IFLA_MASTER]), b1)); + } + + if(tb[IFLA_PROTINFO]) + { + uint8_t state = *(uint8_t *)RTA_DATA(tb[IFLA_PROTINFO]); + if(state <= BR_STATE_BLOCKING) + LOG("state %s", port_states[state]); + else + LOG("state (%d)", state); + } + + newlink = (n->nlmsg_type == RTM_NEWLINK); + + if(tb[IFLA_MASTER]) + br_index = *(int*)RTA_DATA(tb[IFLA_MASTER]); + else if(is_bridge((char*)RTA_DATA(tb[IFLA_IFNAME]))) + br_index = ifi->ifi_index; + else + br_index = -1; + + bridge_notify(br_index, ifi->ifi_index, newlink, ifi->ifi_flags); + + return 0; +} + +static inline void br_ev_handler(uint32_t events, struct epoll_event_handler *h) +{ + if(rtnl_listen(&rth, dump_msg, stdout) < 0) + { + ERROR("Error on bridge monitoring socket\n"); + } +} + +int init_bridge_ops(void) +{ + if(rtnl_open(&rth, RTMGRP_LINK) < 0) + { + ERROR("Couldn't open rtnl socket for monitoring\n"); + return -1; + } + + if(rtnl_open(&rth_state, 0) < 0) + { + ERROR("Couldn't open rtnl socket for setting state\n"); + return -1; + } + + if(rtnl_wilddump_request(&rth, PF_BRIDGE, RTM_GETLINK) < 0) + { + ERROR("Cannot send dump request: %m\n"); + return -1; + } + + if(rtnl_dump_filter(&rth, dump_msg, stdout, NULL, NULL) < 0) + { + ERROR("Dump terminated\n"); + return -1; + } + + if(fcntl(rth.fd, F_SETFL, O_NONBLOCK) < 0) + { + ERROR("Error setting O_NONBLOCK: %m\n"); + return -1; + } + + br_handler.fd = rth.fd; + br_handler.arg = NULL; + br_handler.handler = br_ev_handler; + + if(add_epoll(&br_handler) < 0) + return -1; + + return 0; +} diff --git a/pool/shard004/C/0100742_history.c b/pool/shard004/C/0100742_history.c new file mode 100644 index 0000000000000000000000000000000000000000..5aa4ef2880c9037a800e5e9856633ede289638be --- /dev/null +++ b/pool/shard004/C/0100742_history.c @@ -0,0 +1,124 @@ +/* + * Copyright (C) 2004, 2005, 2006, 2008, 2009, 2010, 2011 Savoir-Faire Linux Inc. + * Author: Julien Bonjean + * + * 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., 675 Mass Ave, Cambridge, MA 02139, USA. + * + * Additional permission under GNU GPL version 3 section 7: + * + * If you modify this program, or any covered work, by linking or + * combining it with the OpenSSL project's OpenSSL library (or a + * modified version of that library), containing parts covered by the + * terms of the OpenSSL or SSLeay licenses, Savoir-Faire Linux Inc. + * grants you additional permission to convey the resulting work. + * Corresponding Source for a non-source form of such a combination + * shall include the source code for the parts of OpenSSL used as well + * as that of the covered work. + */ + +#include +#include +#include +#include + +GtkTreeModel* history_filter; +GtkWidget * history_searchbar_widget; + +static GtkTreeModel* history_create_filter (GtkTreeModel*); +static gboolean history_is_visible (GtkTreeModel*, GtkTreeIter*, gpointer); + +void history_search (SearchType search_type UNUSED) +{ + if (history_filter != NULL) { + gtk_tree_model_filter_refilter (GTK_TREE_MODEL_FILTER (history_filter)); + } +} + +void history_init (void) +{ + history_filter = history_create_filter (GTK_TREE_MODEL (history->store)); + gtk_tree_view_set_model (GTK_TREE_VIEW (history->view), GTK_TREE_MODEL (history_filter)); +} + +void history_reinit (calltab_t* history) +{ + history_filter = history_create_filter (GTK_TREE_MODEL (history->store)); + gtk_tree_view_set_model (GTK_TREE_VIEW (history->view), GTK_TREE_MODEL (history_filter)); +} + + +void history_set_searchbar_widget (GtkWidget *searchbar) +{ + history_searchbar_widget = searchbar; +} + +static GtkTreeModel* history_create_filter (GtkTreeModel* child) +{ + GtkTreeModel* ret; + + DEBUG ("Create Filter"); + ret = gtk_tree_model_filter_new (child, NULL); + gtk_tree_model_filter_set_visible_func (GTK_TREE_MODEL_FILTER (ret), history_is_visible, NULL, NULL); + return GTK_TREE_MODEL (ret); +} + +static gboolean history_is_visible (GtkTreeModel* model, GtkTreeIter* iter, gpointer data UNUSED) +{ + GValue val, obj; + + callable_obj_t *history_entry = NULL; + gchar* text = NULL; + + gchar* search = (gchar*) gtk_entry_get_text (GTK_ENTRY (history_searchbar_widget)); + + memset (&val, 0, sizeof (val)); + memset (&obj, 0, sizeof (obj)); + + // Fetch the call description + gtk_tree_model_get_value (GTK_TREE_MODEL (model), iter, 1, &val); + + if (G_VALUE_HOLDS_STRING (&val)) { + text = (gchar *) g_value_get_string (&val); + } + + // Fetch the call type + gtk_tree_model_get_value (GTK_TREE_MODEL (model), iter, 3, &obj); + + if (G_VALUE_HOLDS_POINTER (&obj)) { + history_entry = (gpointer) g_value_get_pointer (&obj); + } + + gboolean result = TRUE; + + if (text != NULL) { + if (history_entry) { + // Filter according to the type of call + // MISSED, INCOMING, OUTGOING, ALL + if ( (int) get_current_history_search_type () == SEARCH_ALL) + result = g_regex_match_simple (search, text, G_REGEX_CASELESS, 0); + else { + // We need a match on the history_state_t and the current search type + result = (history_entry->_history_state + 1) == (guint) get_current_history_search_type () && + g_regex_match_simple (search, text, G_REGEX_CASELESS, 0); + } + } + } + + // Clean up + g_value_unset (&val); + g_value_unset (&obj); + + return result; +} diff --git a/pool/shard004/C/0100747_target_set.c b/pool/shard004/C/0100747_target_set.c new file mode 100644 index 0000000000000000000000000000000000000000..73ca49fb8f071f898f328907c4aedb3a20f89ec0 --- /dev/null +++ b/pool/shard004/C/0100747_target_set.c @@ -0,0 +1,269 @@ +/** + * collectd - src/target_set.c + * Copyright (C) 2008 Florian Forster + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the "Software"), + * to deal in the Software without restriction, including without limitation + * the rights to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + * DEALINGS IN THE SOFTWARE. + * + * Authors: + * Florian Forster + **/ + +#include "collectd.h" +#include "common.h" +#include "filter_chain.h" + +struct ts_data_s +{ + char *host; + char *plugin; + char *plugin_instance; + /* char *type; */ + char *type_instance; + meta_data_t *meta; +}; +typedef struct ts_data_s ts_data_t; + +int ts_util_get_key_and_string_wo_strdup (const oconfig_item_t *ci, char **ret_key, char **ret_string) /* {{{ */ +{ + if ((ci->values_num != 2) + || (ci->values[0].type != OCONFIG_TYPE_STRING) + || (ci->values[1].type != OCONFIG_TYPE_STRING)) + { + ERROR ("ts_util_get_key_and_string_wo_strdup: The %s option requires " + "exactly two string argument.", ci->key); + return (-1); + } + + *ret_key = ci->values[0].value.string; + *ret_string = ci->values[1].value.string; + + return (0); +} /* }}} int ts_util_get_key_and_string_wo_strdup */ + +static int ts_config_add_string (char **dest, /* {{{ */ + const oconfig_item_t *ci, int may_be_empty) +{ + char *tmp = NULL; + int status; + + status = cf_util_get_string (ci, &tmp); + if (status != 0) + return (status); + + if (!may_be_empty && (strlen (tmp) == 0)) + { + ERROR ("Target `set': The `%s' option does not accept empty strings.", + ci->key); + sfree (tmp); + return (-1); + } + + *dest = tmp; + return (0); +} /* }}} int ts_config_add_string */ + +static int ts_config_add_meta (meta_data_t **dest, /* {{{ */ + const oconfig_item_t *ci, int may_be_empty) +{ + char *key = NULL; + char *string = NULL; + int status; + + status = ts_util_get_key_and_string_wo_strdup (ci, &key, &string); + if (status != 0) + return (status); + + if (strlen (key) == 0) + { + ERROR ("Target `set': The `%s' option does not accept empty string as first argument.", + ci->key); + return (-1); + } + + if (!may_be_empty && (strlen (string) == 0)) + { + ERROR ("Target `set': The `%s' option does not accept empty string as second argument.", + ci->key); + return (-1); + } + + if ((*dest) == NULL) + { + // Create a new meta_data_t + if ((*dest = meta_data_create()) == NULL) + { + ERROR ("Target `set': failed to create a meta data for `%s'.", ci->key); + return (-1); + } + } + + return (meta_data_add_string (*dest, key, string)); +} /* }}} int ts_config_add_meta */ + +static int ts_destroy (void **user_data) /* {{{ */ +{ + ts_data_t *data; + + if (user_data == NULL) + return (-EINVAL); + + data = *user_data; + if (data == NULL) + return (0); + + free (data->host); + free (data->plugin); + free (data->plugin_instance); + /* free (data->type); */ + free (data->type_instance); + meta_data_destroy(data->meta); + free (data); + + return (0); +} /* }}} int ts_destroy */ + +static int ts_create (const oconfig_item_t *ci, void **user_data) /* {{{ */ +{ + ts_data_t *data; + int status; + int i; + + data = calloc (1, sizeof (*data)); + if (data == NULL) + { + ERROR ("ts_create: calloc failed."); + return (-ENOMEM); + } + + data->host = NULL; + data->plugin = NULL; + data->plugin_instance = NULL; + /* data->type = NULL; */ + data->type_instance = NULL; + data->meta = NULL; + + status = 0; + for (i = 0; i < ci->children_num; i++) + { + oconfig_item_t *child = ci->children + i; + + if ((strcasecmp ("Host", child->key) == 0) + || (strcasecmp ("Hostname", child->key) == 0)) + status = ts_config_add_string (&data->host, child, + /* may be empty = */ 0); + else if (strcasecmp ("Plugin", child->key) == 0) + status = ts_config_add_string (&data->plugin, child, + /* may be empty = */ 0); + else if (strcasecmp ("PluginInstance", child->key) == 0) + status = ts_config_add_string (&data->plugin_instance, child, + /* may be empty = */ 1); +#if 0 + else if (strcasecmp ("Type", child->key) == 0) + status = ts_config_add_string (&data->type, child, + /* may be empty = */ 0); +#endif + else if (strcasecmp ("TypeInstance", child->key) == 0) + status = ts_config_add_string (&data->type_instance, child, + /* may be empty = */ 1); + else if (strcasecmp ("MetaDataSet", child->key) == 0) + status = ts_config_add_meta (&data->meta, child, + /* may be empty = */ 1); + else + { + ERROR ("Target `set': The `%s' configuration option is not understood " + "and will be ignored.", child->key); + status = 0; + } + + if (status != 0) + break; + } + + /* Additional sanity-checking */ + while (status == 0) + { + if ((data->host == NULL) + && (data->plugin == NULL) + && (data->plugin_instance == NULL) + /* && (data->type == NULL) */ + && (data->type_instance == NULL) + && (data->meta == NULL)) + { + ERROR ("Target `set': You need to set at least one of `Host', " + "`Plugin', `PluginInstance', `TypeInstance', " + "`MetaDataSet' or `MetaDataEval'."); + status = -1; + } + + break; + } + + if (status != 0) + { + ts_destroy ((void *) &data); + return (status); + } + + *user_data = data; + return (0); +} /* }}} int ts_create */ + +static int ts_invoke (const data_set_t *ds, value_list_t *vl, /* {{{ */ + notification_meta_t __attribute__((unused)) **meta, void **user_data) +{ + ts_data_t *data; + + if ((ds == NULL) || (vl == NULL) || (user_data == NULL)) + return (-EINVAL); + + data = *user_data; + if (data == NULL) + { + ERROR ("Target `set': Invoke: `data' is NULL."); + return (-EINVAL); + } + + if (data->meta != NULL) + { + meta_data_clone_merge(&(vl->meta), data->meta); + } + +#define SET_FIELD(f) if (data->f != NULL) { sstrncpy (vl->f, data->f, sizeof (vl->f)); } + SET_FIELD (host); + SET_FIELD (plugin); + SET_FIELD (plugin_instance); + /* SET_FIELD (type); */ + SET_FIELD (type_instance); + + return (FC_TARGET_CONTINUE); +} /* }}} int ts_invoke */ + +void module_register (void) +{ + target_proc_t tproc; + + memset (&tproc, 0, sizeof (tproc)); + tproc.create = ts_create; + tproc.destroy = ts_destroy; + tproc.invoke = ts_invoke; + fc_register_target ("set", tproc); +} /* module_register */ + +/* vim: set sw=2 sts=2 tw=78 et fdm=marker : */ + diff --git a/pool/shard004/C/0100756_aes_ctr.c b/pool/shard004/C/0100756_aes_ctr.c new file mode 100644 index 0000000000000000000000000000000000000000..fc60d00a2e844405934152cc23ba6dac9ec9ecd6 --- /dev/null +++ b/pool/shard004/C/0100756_aes_ctr.c @@ -0,0 +1,186 @@ +/** + * AES CTR routines supporting VMX instructions on the Power 8 + * + * Copyright (C) 2015 International Business Machines Inc. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; version 2 only. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. + * + * Author: Marcelo Henrique Cerri + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "aesp8-ppc.h" + +struct p8_aes_ctr_ctx { + struct crypto_skcipher *fallback; + struct aes_key enc_key; +}; + +static int p8_aes_ctr_init(struct crypto_tfm *tfm) +{ + const char *alg = crypto_tfm_alg_name(tfm); + struct crypto_skcipher *fallback; + struct p8_aes_ctr_ctx *ctx = crypto_tfm_ctx(tfm); + + fallback = crypto_alloc_skcipher(alg, 0, + CRYPTO_ALG_ASYNC | CRYPTO_ALG_NEED_FALLBACK); + if (IS_ERR(fallback)) { + printk(KERN_ERR + "Failed to allocate transformation for '%s': %ld\n", + alg, PTR_ERR(fallback)); + return PTR_ERR(fallback); + } + printk(KERN_INFO "Using '%s' as fallback implementation.\n", + crypto_skcipher_driver_name(fallback)); + + crypto_skcipher_set_flags( + fallback, + crypto_skcipher_get_flags((struct crypto_skcipher *)tfm)); + ctx->fallback = fallback; + + return 0; +} + +static void p8_aes_ctr_exit(struct crypto_tfm *tfm) +{ + struct p8_aes_ctr_ctx *ctx = crypto_tfm_ctx(tfm); + + if (ctx->fallback) { + crypto_free_skcipher(ctx->fallback); + ctx->fallback = NULL; + } +} + +static int p8_aes_ctr_setkey(struct crypto_tfm *tfm, const u8 *key, + unsigned int keylen) +{ + int ret; + struct p8_aes_ctr_ctx *ctx = crypto_tfm_ctx(tfm); + + preempt_disable(); + pagefault_disable(); + enable_kernel_vsx(); + ret = aes_p8_set_encrypt_key(key, keylen * 8, &ctx->enc_key); + disable_kernel_vsx(); + pagefault_enable(); + preempt_enable(); + + ret += crypto_skcipher_setkey(ctx->fallback, key, keylen); + return ret; +} + +static void p8_aes_ctr_final(struct p8_aes_ctr_ctx *ctx, + struct blkcipher_walk *walk) +{ + u8 *ctrblk = walk->iv; + u8 keystream[AES_BLOCK_SIZE]; + u8 *src = walk->src.virt.addr; + u8 *dst = walk->dst.virt.addr; + unsigned int nbytes = walk->nbytes; + + preempt_disable(); + pagefault_disable(); + enable_kernel_vsx(); + aes_p8_encrypt(ctrblk, keystream, &ctx->enc_key); + disable_kernel_vsx(); + pagefault_enable(); + preempt_enable(); + + crypto_xor_cpy(dst, keystream, src, nbytes); + crypto_inc(ctrblk, AES_BLOCK_SIZE); +} + +static int p8_aes_ctr_crypt(struct blkcipher_desc *desc, + struct scatterlist *dst, + struct scatterlist *src, unsigned int nbytes) +{ + int ret; + u64 inc; + struct blkcipher_walk walk; + struct p8_aes_ctr_ctx *ctx = + crypto_tfm_ctx(crypto_blkcipher_tfm(desc->tfm)); + + if (in_interrupt()) { + SKCIPHER_REQUEST_ON_STACK(req, ctx->fallback); + skcipher_request_set_tfm(req, ctx->fallback); + skcipher_request_set_callback(req, desc->flags, NULL, NULL); + skcipher_request_set_crypt(req, src, dst, nbytes, desc->info); + ret = crypto_skcipher_encrypt(req); + skcipher_request_zero(req); + } else { + blkcipher_walk_init(&walk, dst, src, nbytes); + ret = blkcipher_walk_virt_block(desc, &walk, AES_BLOCK_SIZE); + while ((nbytes = walk.nbytes) >= AES_BLOCK_SIZE) { + preempt_disable(); + pagefault_disable(); + enable_kernel_vsx(); + aes_p8_ctr32_encrypt_blocks(walk.src.virt.addr, + walk.dst.virt.addr, + (nbytes & + AES_BLOCK_MASK) / + AES_BLOCK_SIZE, + &ctx->enc_key, + walk.iv); + disable_kernel_vsx(); + pagefault_enable(); + preempt_enable(); + + /* We need to update IV mostly for last bytes/round */ + inc = (nbytes & AES_BLOCK_MASK) / AES_BLOCK_SIZE; + if (inc > 0) + while (inc--) + crypto_inc(walk.iv, AES_BLOCK_SIZE); + + nbytes &= AES_BLOCK_SIZE - 1; + ret = blkcipher_walk_done(desc, &walk, nbytes); + } + if (walk.nbytes) { + p8_aes_ctr_final(ctx, &walk); + ret = blkcipher_walk_done(desc, &walk, 0); + } + } + + return ret; +} + +struct crypto_alg p8_aes_ctr_alg = { + .cra_name = "ctr(aes)", + .cra_driver_name = "p8_aes_ctr", + .cra_module = THIS_MODULE, + .cra_priority = 2000, + .cra_type = &crypto_blkcipher_type, + .cra_flags = CRYPTO_ALG_TYPE_BLKCIPHER | CRYPTO_ALG_NEED_FALLBACK, + .cra_alignmask = 0, + .cra_blocksize = 1, + .cra_ctxsize = sizeof(struct p8_aes_ctr_ctx), + .cra_init = p8_aes_ctr_init, + .cra_exit = p8_aes_ctr_exit, + .cra_blkcipher = { + .ivsize = AES_BLOCK_SIZE, + .min_keysize = AES_MIN_KEY_SIZE, + .max_keysize = AES_MAX_KEY_SIZE, + .setkey = p8_aes_ctr_setkey, + .encrypt = p8_aes_ctr_crypt, + .decrypt = p8_aes_ctr_crypt, + }, +}; diff --git a/pool/shard004/C/0100757_testosumpi_bcast_lat.c b/pool/shard004/C/0100757_testosumpi_bcast_lat.c new file mode 100644 index 0000000000000000000000000000000000000000..02251e162d5abd0f1d63bd35236bf766a9cfd7b6 --- /dev/null +++ b/pool/shard004/C/0100757_testosumpi_bcast_lat.c @@ -0,0 +1,147 @@ +/* + * Copyright (C) 2002-2004 the Network-Based Computing Laboratory + * (NBCL), The Ohio State University. + */ + +#include "mpi.h" +#include +#include +#include + +#define MAX_MSG_SIZE 200000 +#define SKIP 100 +#define ITERATIONS 1000 +#define ROOT 0 +#define LEAF (numprocs - 1) +#define DELAY 100 + +static /*inline*/ double usecs_delay(int usecs); +double ret_us(void); +void get_ack_time(int); + +char x[MAX_MSG_SIZE]; +char y[4] = {0,0,0,0}; +double ack_time = 0.0; +int numprocs; + +int main(int argc, char *argv[]) +{ + int i = 0, rank = 0; + double tmp1 = 0.0, tmp2 = 0.0; + int size; + int mpi_errno = 0; + double latency = 0.0, total = 0.0; + MPI_Status status; + + MPI_Init( &argc, &argv ); + MPI_Comm_rank( MPI_COMM_WORLD, &rank ); + MPI_Comm_size( MPI_COMM_WORLD, &numprocs ); + + if (rank == 0) { + fprintf(stdout, "# OSU MPI_Bcast Latency Test (Version 1.0)\n"); + fprintf(stdout, "# Size\t\tLatency (us) \n"); + } + + MPI_Barrier( MPI_COMM_WORLD ); + get_ack_time(rank); + + for( i=0; i < MAX_MSG_SIZE; i++ ) { + x[i]='a'; + } + + + MPI_Barrier( MPI_COMM_WORLD ); + + for (size=1; size <= 16384; size *= 2){ + for ( i=0; i < ITERATIONS + SKIP ; i++ ) { + + if (i == SKIP){ + if (rank == ROOT) tmp1 = ret_us(); + } + + MPI_Bcast(&x, size, MPI_CHAR, 0, MPI_COMM_WORLD); + + if ( rank == ROOT ) { + mpi_errno = MPI_Recv(&y, 0, MPI_CHAR, LEAF, 1, MPI_COMM_WORLD, &status); + if (mpi_errno != MPI_SUCCESS) printf("Receive failed\n"); + + } + + if (rank == LEAF) { + usecs_delay(DELAY); + mpi_errno = MPI_Send(&y, 0, MPI_CHAR, ROOT, 1, MPI_COMM_WORLD); + if (mpi_errno != MPI_SUCCESS) printf("Send failed\n"); + } + } + + if (rank == ROOT){ + tmp2 = ret_us(); + total = tmp2 - tmp1; + } + + if ( rank == ROOT ) { + latency = ( total/ (double)ITERATIONS ); + printf ("%5d %8.3f\n", + size,latency - DELAY - ack_time ); + } + + MPI_Barrier(MPI_COMM_WORLD); + } + + MPI_Finalize(); + return 0; +} + +void get_ack_time(int myid){ + + int i; + double t_start = 0.0, t_end = 0.0; + MPI_Status reqstat; + + if (myid == 0) { + for (i = 0; i < ITERATIONS + SKIP ; i++) { + if (i == SKIP) + t_start = ret_us(); + MPI_Send(x, 0, MPI_CHAR, numprocs-1, 1, MPI_COMM_WORLD); + MPI_Recv(y, 0, MPI_CHAR, numprocs-1, 1, MPI_COMM_WORLD, + &reqstat); + } + t_end = ret_us(); + + } else if (myid == numprocs-1) { + for (i = 0; i < ITERATIONS + SKIP; i++) { + MPI_Recv(y, 0, MPI_CHAR, 0, 1, MPI_COMM_WORLD, + &reqstat); + MPI_Send(x, 0, MPI_CHAR, 0, 1, MPI_COMM_WORLD); + } + } + + if (myid == 0) { + ack_time = (t_end - t_start) / (2.0 * ITERATIONS); + } + +} + +double usecs_delay(int usecs) +{ + double elapsed, tmp1, tmp2; + + tmp1 = ret_us(); + + do{ + tmp2 = ret_us(); + elapsed = tmp2 - tmp1; + } while (elapsed < (double)usecs); + + return (elapsed); +} + + +double ret_us(void) +{ + struct timeval t; + gettimeofday(&t, NULL); + return (double) t.tv_sec * (double) 1e6 + (double) t.tv_usec; +} + + diff --git a/pool/shard004/C/0100763_iniconf.c b/pool/shard004/C/0100763_iniconf.c new file mode 100644 index 0000000000000000000000000000000000000000..0f266df7c89957da1f4fa8264e7788a6e00f0e0f --- /dev/null +++ b/pool/shard004/C/0100763_iniconf.c @@ -0,0 +1,128 @@ +/* +* +* Copyright (c) 2000-2001, Darren Hiebert +* +* This source code is released for free distribution under the terms of the +* GNU General Public License. +* +* This module contains functions for generating tags for config files. +*/ + +/* +* INCLUDE FILES +*/ +#include "general.h" /* must always come first */ + +#include + +#include "parse.h" +#include "read.h" +#include "vstring.h" +#include "routines.h" +#include "entry.h" + +/* +* DATA DEFINITIONS +*/ +typedef enum { + K_SECTION, + K_KEY +} confKind; + +static kindDefinition ConfKinds [] = { + { true, 'n', "namespace", "sections"}, + { true, 'm', "macro", "keys"} +}; + +/* +* FUNCTION DEFINITIONS +*/ + +static bool isIdentifier (int c) +{ + /* allow whitespace within keys and sections */ + return (bool)(isalnum (c) || isspace (c) || c == '_'); +} + +static void findConfTags (void) +{ + vString *name = vStringNew (); + vString *scope = vStringNew (); + const unsigned char *line; + + while ((line = readLineFromInputFile ()) != NULL) + { + const unsigned char* cp = line; + bool possible = true; + + if (isspace ((int) *cp) || *cp == '#' || (*cp != '\0' && *cp == '/' && *(cp+1) == '/')) + continue; + + /* look for a section */ + if (*cp != '\0' && *cp == '[') + { + ++cp; + while (*cp != '\0' && *cp != ']') + { + vStringPut (name, (int) *cp); + ++cp; + } + makeSimpleTag (name, K_SECTION); + /* remember section name */ + vStringCopy (scope, name); + vStringClear (name); + continue; + } + + while (*cp != '\0') + { + /* We look for any sequence of identifier characters following a white space */ + if (possible && isIdentifier ((int) *cp)) + { + while (isIdentifier ((int) *cp)) + { + vStringPut (name, (int) *cp); + ++cp; + } + vStringStripTrailing (name); + while (isspace ((int) *cp)) + ++cp; + if (*cp == '=') + { + tagEntryInfo e; + initTagEntry (&e, vStringValue (name), K_KEY); + + if (vStringLength (scope) > 0) + { + e.extensionFields.scopeKindIndex = K_SECTION; + e.extensionFields.scopeName = vStringValue(scope); + } + makeTagEntry (&e); + } + vStringClear (name); + } + else if (isspace ((int) *cp)) + possible = true; + else + possible = false; + + if (*cp != '\0') + ++cp; + } + } + vStringDelete (name); + vStringDelete (scope); +} + +extern parserDefinition* ConfParser (void) +{ + static const char *const patterns [] = { "*.ini", "*.conf", NULL }; + static const char *const extensions [] = { "conf", NULL }; + parserDefinition* const def = parserNew ("Conf"); + def->kindTable = ConfKinds; + def->kindCount = ARRAY_SIZE (ConfKinds); + def->patterns = patterns; + def->extensions = extensions; + def->parser = findConfTags; + return def; +} diff --git a/pool/shard004/C/0100764_t-revert_series_lagrange_fast.c b/pool/shard004/C/0100764_t-revert_series_lagrange_fast.c new file mode 100644 index 0000000000000000000000000000000000000000..86cbf95422a6729e6b0d2318a8204543999c8099 --- /dev/null +++ b/pool/shard004/C/0100764_t-revert_series_lagrange_fast.c @@ -0,0 +1,87 @@ +/* + 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 "acb_poly.h" + + +int main() +{ + slong iter; + flint_rand_t state; + + flint_printf("revert_series_lagrange_fast...."); + fflush(stdout); + + flint_randinit(state); + + for (iter = 0; iter < 1000 * arb_test_multiplier(); iter++) + { + slong qbits1, rbits1, rbits2, n; + fmpq_poly_t A, B; + acb_poly_t a, b, c; + + qbits1 = 2 + n_randint(state, 200); + rbits1 = 2 + n_randint(state, 200); + rbits2 = 2 + n_randint(state, 200); + n = 2 + n_randint(state, 25); + + fmpq_poly_init(A); + fmpq_poly_init(B); + + acb_poly_init(a); + acb_poly_init(b); + acb_poly_init(c); + + do { + fmpq_poly_randtest(A, state, 1 + n_randint(state, 25), qbits1); + fmpq_poly_set_coeff_ui(A, 0, 0); + } while (A->length < 2 || fmpz_is_zero(A->coeffs + 1)); + + fmpq_poly_revert_series(B, A, n); + + acb_poly_set_fmpq_poly(a, A, rbits1); + acb_poly_revert_series_lagrange_fast(b, a, n, rbits2); + + if (!acb_poly_contains_fmpq_poly(b, B)) + { + flint_printf("FAIL\n\n"); + flint_printf("n = %wd, bits2 = %wd\n", n, rbits2); + + flint_printf("A = "); fmpq_poly_print(A); flint_printf("\n\n"); + flint_printf("B = "); fmpq_poly_print(B); flint_printf("\n\n"); + + flint_printf("a = "); acb_poly_printd(a, 15); flint_printf("\n\n"); + flint_printf("b = "); acb_poly_printd(b, 15); flint_printf("\n\n"); + + flint_abort(); + } + + acb_poly_set(c, a); + acb_poly_revert_series_lagrange_fast(c, c, n, rbits2); + if (!acb_poly_equal(c, b)) + { + flint_printf("FAIL (aliasing)\n\n"); + flint_abort(); + } + + fmpq_poly_clear(A); + fmpq_poly_clear(B); + + acb_poly_clear(a); + acb_poly_clear(b); + acb_poly_clear(c); + } + + flint_randclear(state); + flint_cleanup(); + flint_printf("PASS\n"); + return EXIT_SUCCESS; +} diff --git a/pool/shard004/C/0100778_analogout_api.c b/pool/shard004/C/0100778_analogout_api.c new file mode 100644 index 0000000000000000000000000000000000000000..c17b06e8b554916e8c75e7f467d4770e26672ef8 --- /dev/null +++ b/pool/shard004/C/0100778_analogout_api.c @@ -0,0 +1,212 @@ +/******************************************************************************* + * Copyright (C) 2015 Maxim Integrated Products, 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 MAXIM INTEGRATED 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 Maxim Integrated + * Products, Inc. shall not be used except as stated in the Maxim Integrated + * Products, Inc. Branding Policy. + * + * The mere transfer of this software does not imply any licenses + * of trade secrets, proprietary technology, copyrights, patents, + * trademarks, maskwork rights, or any other form of intellectual + * property whatsoever. Maxim Integrated Products, Inc. retains all + * ownership rights. + ******************************************************************************* + */ + +#include "mbed_assert.h" +#include "analogout_api.h" +#include "clkman_regs.h" +#include "pwrman_regs.h" +#include "afe_regs.h" +#include "PeripheralPins.h" + +//****************************************************************************** +void analogout_init(dac_t *obj, PinName pin) +{ + // Make sure pin is an analog pin we can use for ADC + DACName dac = (DACName)pinmap_peripheral(pin, PinMap_DAC); + MBED_ASSERT((DACName)dac != (DACName)NC); + + // Set the object pointer + obj->dac = ((mxc_dac_regs_t*)MXC_DAC_GET_DAC((pin & 0x3))); + obj->dac_fifo = ((mxc_dac_fifo_t*)MXC_DAC_GET_FIFO((pin & 0x3))); + obj->index = (pin & 0x3); + + // Set the ADC clock to the system clock frequency + MXC_SET_FIELD(&MXC_CLKMAN->clk_ctrl, MXC_F_CLKMAN_CLK_CTRL_ADC_SOURCE_SELECT, + (MXC_F_CLKMAN_CLK_CTRL_ADC_GATE_N | (MXC_E_CLKMAN_ADC_SOURCE_SELECT_SYSTEM << + MXC_F_CLKMAN_CLK_CTRL_ADC_SOURCE_SELECT_POS))); + + + // Setup the OPAMP in follower mode + switch(obj->index) { + case 0: + // Enable DAC clock + MXC_CLKMAN->clk_ctrl_14_dac0 = MXC_E_CLKMAN_CLK_SCALE_ENABLED; + + // Enable OPAMP + MXC_AFE->ctrl5 &= ~MXC_F_AFE_CTRL5_OP_CMP0; + + // Set the positive and negative inputs + MXC_SET_FIELD(&MXC_AFE->ctrl4, (MXC_F_AFE_CTRL4_DAC_SEL_A | + MXC_F_AFE_CTRL4_P_IN_SEL_OPAMP0 | MXC_F_AFE_CTRL4_N_IN_SEL_OPAMP0), + ((0x1 << MXC_F_AFE_CTRL4_P_IN_SEL_OPAMP0_POS) | + (0x1 << MXC_F_AFE_CTRL4_N_IN_SEL_OPAMP0_POS) | + (0x0 << MXC_F_AFE_CTRL4_DAC_SEL_A_POS))); + + // Enable N and P channel inputs + MXC_AFE->ctrl3 |= (MXC_F_AFE_CTRL3_EN_PCH_OPAMP0 | + MXC_F_AFE_CTRL3_EN_NCH_OPAMP0); + break; + case 1: + // Enable DAC clock + MXC_CLKMAN->clk_ctrl_15_dac1 = MXC_E_CLKMAN_CLK_SCALE_ENABLED; + + // Enable OPAMP + MXC_AFE->ctrl5 &= ~MXC_F_AFE_CTRL5_OP_CMP1; + + // Set the positive and negative inputs + MXC_SET_FIELD(&MXC_AFE->ctrl4, (MXC_F_AFE_CTRL4_DAC_SEL_B | + MXC_F_AFE_CTRL4_P_IN_SEL_OPAMP1 | MXC_F_AFE_CTRL4_N_IN_SEL_OPAMP1), + ((0x1 << MXC_F_AFE_CTRL4_P_IN_SEL_OPAMP1_POS) | + (0x1 << MXC_F_AFE_CTRL4_N_IN_SEL_OPAMP1_POS) | + (0x1 << MXC_F_AFE_CTRL4_DAC_SEL_B_POS))); + + // Enable N and P channel inputs + MXC_AFE->ctrl3 |= (MXC_F_AFE_CTRL3_EN_PCH_OPAMP1 | + MXC_F_AFE_CTRL3_EN_NCH_OPAMP1); + + break; + case 2: + // Enable DAC clock + MXC_CLKMAN->clk_ctrl_16_dac2 = MXC_E_CLKMAN_CLK_SCALE_ENABLED; + + // Enable OPAMP + MXC_AFE->ctrl5 &= ~MXC_F_AFE_CTRL5_OP_CMP2; + + // Set the positive and negative inputs + MXC_SET_FIELD(&MXC_AFE->ctrl4, (MXC_F_AFE_CTRL4_DAC_SEL_C | + MXC_F_AFE_CTRL4_P_IN_SEL_OPAMP2 | MXC_F_AFE_CTRL4_N_IN_SEL_OPAMP2), + ((0x1 << MXC_F_AFE_CTRL4_P_IN_SEL_OPAMP2_POS) | + (0x1 << MXC_F_AFE_CTRL4_N_IN_SEL_OPAMP2_POS) | + (0x2 << MXC_F_AFE_CTRL4_DAC_SEL_C_POS))); + + // Enable N and P channel inputs + MXC_AFE->ctrl3 |= (MXC_F_AFE_CTRL3_EN_PCH_OPAMP2 | + MXC_F_AFE_CTRL3_EN_NCH_OPAMP2); + break; + case 3: + // Enable DAC clock + MXC_CLKMAN->clk_ctrl_17_dac3 = MXC_E_CLKMAN_CLK_SCALE_ENABLED; + + // Enable OPAMP + MXC_AFE->ctrl5 &= ~MXC_F_AFE_CTRL5_OP_CMP3; + + // Set the positive and negative inputs + MXC_SET_FIELD(&MXC_AFE->ctrl4, (MXC_F_AFE_CTRL4_DAC_SEL_D | + MXC_F_AFE_CTRL4_P_IN_SEL_OPAMP3 | MXC_F_AFE_CTRL4_N_IN_SEL_OPAMP3), + ((0x1 << MXC_F_AFE_CTRL4_P_IN_SEL_OPAMP3_POS) | + (0x1 << MXC_F_AFE_CTRL4_N_IN_SEL_OPAMP3_POS) | + (0x3 << MXC_F_AFE_CTRL4_DAC_SEL_D_POS))); + + // Enable N and P channel inputs + MXC_AFE->ctrl3 |= (MXC_F_AFE_CTRL3_EN_PCH_OPAMP3 | + MXC_F_AFE_CTRL3_EN_NCH_OPAMP3); + break; + } + + // Enable AFE power + MXC_PWRMAN->pwr_rst_ctrl |= MXC_F_PWRMAN_PWR_RST_CTRL_AFE_POWERED; + + // Setup internal voltage references + MXC_SET_FIELD(&MXC_AFE->ctrl1, (MXC_F_AFE_CTRL1_REF_DAC_VOLT_SEL | MXC_F_AFE_CTRL1_REF_ADC_VOLT_SEL), + (MXC_F_AFE_CTRL1_REF_ADC_POWERUP | MXC_F_AFE_CTRL1_REF_BLK_POWERUP | + (MXC_E_AFE_REF_VOLT_SEL_1500 << MXC_F_AFE_CTRL1_REF_ADC_VOLT_SEL_POS))); + + // Disable interpolation + obj->dac->ctrl0 &= MXC_F_DAC_CTRL0_INTERP_MODE; +} + +//****************************************************************************** +void analogout_write(dac_t *obj, float value) +{ + analogout_write_u16(obj, (uint16_t)((value/1.0) * 0xFFFF)); +} + +//****************************************************************************** +void analogout_write_u16(dac_t *obj, uint16_t value) +{ + // Enable the OPAMP + // Setup the OPAMP in follower mode + switch(obj->index) { + case 0: + MXC_AFE->ctrl3 |= MXC_F_AFE_CTRL3_POWERUP_OPAMP0; + break; + case 1: + MXC_AFE->ctrl3 |= MXC_F_AFE_CTRL3_POWERUP_OPAMP1; + break; + case 2: + MXC_AFE->ctrl3 |= MXC_F_AFE_CTRL3_POWERUP_OPAMP2; + break; + case 3: + MXC_AFE->ctrl3 |= MXC_F_AFE_CTRL3_POWERUP_OPAMP3; + break; + } + + // Output 1 sample with minimal delay + obj->dac->rate |= 0x1; + + // Set the start mode to output once data is in the FIFO + obj->dac->ctrl0 &= ~(MXC_F_DAC_CTRL0_START_MODE | MXC_F_DAC_CTRL0_OP_MODE); + + // Enable the DAC + obj->dac->ctrl0 |= (MXC_F_DAC_CTRL0_POWER_MODE_2 | + MXC_F_DAC_CTRL0_POWER_MODE_1_0 | MXC_F_DAC_CTRL0_POWER_ON | + MXC_F_DAC_CTRL0_CLOCK_GATE_EN | MXC_F_DAC_CTRL0_CPU_START); + + if(obj->index < 2) { + obj->out = (value); + obj->dac_fifo->output_16 = (obj->out); + + } else { + // Convert 16 bits to 8 bits + obj->out = (value >> 8); + obj->dac_fifo->output_8 = (obj->out); + } +} + +//****************************************************************************** +float analogout_read(dac_t *obj) +{ + return (((float)analogout_read_u16(obj) / (float)0xFFFF) * 1.5); +} + +//****************************************************************************** +uint16_t analogout_read_u16(dac_t *obj) +{ + if(obj->index < 2) { + // Convert 12 bits to 16 bits + return (obj->out << 4); + } else { + // Convert 8 bits to 16 bits + return (obj->out << 8); + } +} diff --git a/pool/shard004/C/0100779_2-5.c b/pool/shard004/C/0100779_2-5.c new file mode 100644 index 0000000000000000000000000000000000000000..93ad4077897fd7ca32e23616275d1c124136c630 --- /dev/null +++ b/pool/shard004/C/0100779_2-5.c @@ -0,0 +1,61 @@ +/* + + * Copyright (c) 2002-2003, Intel Corporation. All rights reserved. + * Created by: rusty.lynch 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 #2 of the sigaction system call that shows + sigaction (when used with a non-null oact pointer) changes the action + for a signal. + + Steps: + 1. Call sigaction to set handler for SIGCONT to use handler1 + 2. Call sigaction again to set handler for SIGCONT to use handler2, + but this time use a non-null oarg and verify the sa_handler for + oarg is set for handler1. +*/ + +#include +#include +#include "posixtest.h" + +void handler1(int signo LTP_ATTRIBUTE_UNUSED) +{ +} + +void handler2(int signo LTP_ATTRIBUTE_UNUSED) +{ +} + +int main(void) +{ + struct sigaction act; + struct sigaction oact; + + act.sa_handler = handler1; + act.sa_flags = 0; + sigemptyset(&act.sa_mask); + if (sigaction(SIGCONT, &act, 0) == -1) { + perror("Unexpected error while attempting to setup test " + "pre-conditions"); + return PTS_UNRESOLVED; + } + + act.sa_handler = handler2; + sigemptyset(&act.sa_mask); + if (sigaction(SIGCONT, &act, &oact) == -1) { + perror("Unexpected error while attempting to setup test " + "pre-conditions"); + return PTS_UNRESOLVED; + } + + if (oact.sa_handler == handler1) { + printf("Test PASSED\n"); + return PTS_PASS; + } + + printf("Test Failed\n"); + return PTS_FAIL; +} diff --git a/pool/shard004/C/0100785_rslist.c b/pool/shard004/C/0100785_rslist.c new file mode 100644 index 0000000000000000000000000000000000000000..ee2e206fc6c8e8dbad901ad67653cd7d697e2273 --- /dev/null +++ b/pool/shard004/C/0100785_rslist.c @@ -0,0 +1,251 @@ +/******************************************************************************* + * + * Module Name: rslist - Linked list utilities + * + ******************************************************************************/ + +/* + * Copyright (C) 2000 - 2013, Intel Corp. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions, and the following disclaimer, + * without modification. + * 2. Redistributions in binary form must reproduce at minimum a disclaimer + * substantially similar to the "NO WARRANTY" disclaimer below + * ("Disclaimer") and any redistribution must be conditioned upon + * including a substantially similar Disclaimer requirement for further + * binary redistribution. + * 3. Neither the names of the above-listed copyright holders nor the names + * of any contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * Alternatively, this software may be distributed under the terms of the + * GNU General Public License ("GPL") version 2 as published by the Free + * Software Foundation. + * + * NO WARRANTY + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * HOLDERS OR CONTRIBUTORS BE LIABLE FOR SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, + * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING + * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGES. + */ + +#include +#include "accommon.h" +#include "acresrc.h" + +#define _COMPONENT ACPI_RESOURCES +ACPI_MODULE_NAME("rslist") + +/******************************************************************************* + * + * FUNCTION: acpi_rs_convert_aml_to_resources + * + * PARAMETERS: acpi_walk_aml_callback + * resource_ptr - Pointer to the buffer that will + * contain the output structures + * + * RETURN: Status + * + * DESCRIPTION: Convert an AML resource to an internal representation of the + * resource that is aligned and easier to access. + * + ******************************************************************************/ +acpi_status +acpi_rs_convert_aml_to_resources(u8 * aml, + u32 length, + u32 offset, u8 resource_index, void **context) +{ + struct acpi_resource **resource_ptr = + ACPI_CAST_INDIRECT_PTR(struct acpi_resource, context); + struct acpi_resource *resource; + union aml_resource *aml_resource; + struct acpi_rsconvert_info *conversion_table; + acpi_status status; + + ACPI_FUNCTION_TRACE(rs_convert_aml_to_resources); + + /* + * Check that the input buffer and all subsequent pointers into it + * are aligned on a native word boundary. Most important on IA64 + */ + resource = *resource_ptr; + if (ACPI_IS_MISALIGNED(resource)) { + ACPI_WARNING((AE_INFO, + "Misaligned resource pointer %p", resource)); + } + + /* Get the appropriate conversion info table */ + + aml_resource = ACPI_CAST_PTR(union aml_resource, aml); + if (acpi_ut_get_resource_type(aml) == ACPI_RESOURCE_NAME_SERIAL_BUS) { + if (aml_resource->common_serial_bus.type > + AML_RESOURCE_MAX_SERIALBUSTYPE) { + conversion_table = NULL; + } else { + /* This is an I2C, SPI, or UART serial_bus descriptor */ + + conversion_table = + acpi_gbl_convert_resource_serial_bus_dispatch + [aml_resource->common_serial_bus.type]; + } + } else { + conversion_table = + acpi_gbl_get_resource_dispatch[resource_index]; + } + + if (!conversion_table) { + ACPI_ERROR((AE_INFO, + "Invalid/unsupported resource descriptor: Type 0x%2.2X", + resource_index)); + return_ACPI_STATUS(AE_AML_INVALID_RESOURCE_TYPE); + } + + /* Convert the AML byte stream resource to a local resource struct */ + + status = + acpi_rs_convert_aml_to_resource(resource, aml_resource, + conversion_table); + if (ACPI_FAILURE(status)) { + ACPI_EXCEPTION((AE_INFO, status, + "Could not convert AML resource (Type 0x%X)", + *aml)); + return_ACPI_STATUS(status); + } + + ACPI_DEBUG_PRINT((ACPI_DB_RESOURCES, + "Type %.2X, AmlLength %.2X InternalLength %.2X\n", + acpi_ut_get_resource_type(aml), length, + resource->length)); + + /* Point to the next structure in the output buffer */ + + *resource_ptr = ACPI_NEXT_RESOURCE(resource); + return_ACPI_STATUS(AE_OK); +} + +/******************************************************************************* + * + * FUNCTION: acpi_rs_convert_resources_to_aml + * + * PARAMETERS: resource - Pointer to the resource linked list + * aml_size_needed - Calculated size of the byte stream + * needed from calling acpi_rs_get_aml_length() + * The size of the output_buffer is + * guaranteed to be >= aml_size_needed + * output_buffer - Pointer to the buffer that will + * contain the byte stream + * + * RETURN: Status + * + * DESCRIPTION: Takes the resource linked list and parses it, creating a + * byte stream of resources in the caller's output buffer + * + ******************************************************************************/ + +acpi_status +acpi_rs_convert_resources_to_aml(struct acpi_resource *resource, + acpi_size aml_size_needed, u8 * output_buffer) +{ + u8 *aml = output_buffer; + u8 *end_aml = output_buffer + aml_size_needed; + struct acpi_rsconvert_info *conversion_table; + acpi_status status; + + ACPI_FUNCTION_TRACE(rs_convert_resources_to_aml); + + /* Walk the resource descriptor list, convert each descriptor */ + + while (aml < end_aml) { + + /* Validate the (internal) Resource Type */ + + if (resource->type > ACPI_RESOURCE_TYPE_MAX) { + ACPI_ERROR((AE_INFO, + "Invalid descriptor type (0x%X) in resource list", + resource->type)); + return_ACPI_STATUS(AE_BAD_DATA); + } + + /* Perform the conversion */ + + if (resource->type == ACPI_RESOURCE_TYPE_SERIAL_BUS) { + if (resource->data.common_serial_bus.type > + AML_RESOURCE_MAX_SERIALBUSTYPE) { + conversion_table = NULL; + } else { + /* This is an I2C, SPI, or UART serial_bus descriptor */ + + conversion_table = + acpi_gbl_convert_resource_serial_bus_dispatch + [resource->data.common_serial_bus.type]; + } + } else { + conversion_table = + acpi_gbl_set_resource_dispatch[resource->type]; + } + + if (!conversion_table) { + ACPI_ERROR((AE_INFO, + "Invalid/unsupported resource descriptor: Type 0x%2.2X", + resource->type)); + return_ACPI_STATUS(AE_AML_INVALID_RESOURCE_TYPE); + } + + status = acpi_rs_convert_resource_to_aml(resource, + ACPI_CAST_PTR(union + aml_resource, + aml), + conversion_table); + if (ACPI_FAILURE(status)) { + ACPI_EXCEPTION((AE_INFO, status, + "Could not convert resource (type 0x%X) to AML", + resource->type)); + return_ACPI_STATUS(status); + } + + /* Perform final sanity check on the new AML resource descriptor */ + + status = acpi_ut_validate_resource(NULL, + ACPI_CAST_PTR(union + aml_resource, + aml), NULL); + if (ACPI_FAILURE(status)) { + return_ACPI_STATUS(status); + } + + /* Check for end-of-list, normal exit */ + + if (resource->type == ACPI_RESOURCE_TYPE_END_TAG) { + + /* An End Tag indicates the end of the input Resource Template */ + + return_ACPI_STATUS(AE_OK); + } + + /* + * Extract the total length of the new descriptor and set the + * Aml to point to the next (output) resource descriptor + */ + aml += acpi_ut_get_descriptor_length(aml); + + /* Point to the next input resource descriptor */ + + resource = ACPI_NEXT_RESOURCE(resource); + } + + /* Completed buffer, but did not find an end_tag resource descriptor */ + + return_ACPI_STATUS(AE_AML_NO_RESOURCE_END_TAG); +} diff --git a/pool/shard004/C/0100787_lsb.hosts.c b/pool/shard004/C/0100787_lsb.hosts.c new file mode 100644 index 0000000000000000000000000000000000000000..c9251cc3d4a3b525f0c16e522cd8c5ad8fc2f375 --- /dev/null +++ b/pool/shard004/C/0100787_lsb.hosts.c @@ -0,0 +1,181 @@ +/* + * Copyright (C) 2007 Platform Computing Inc + * Copyright (C) 2014 David Bigagli + * + * 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-1301, USA + * + */ + +#include "lsb.h" + +struct hostInfoEnt * +lsb_hostinfo(char **hosts, int *numHosts) +{ + return (lsb_hostinfo_ex (hosts, numHosts, NULL, 0)); +} + + +struct hostInfoEnt * +lsb_hostinfo_ex(char **hosts, int *numHosts, char *resReq, int options) +{ + mbdReqType mbdReqtype; + XDR xdrs; + struct LSFHeader hdr; + char *request_buf; + char *reply_buf; + int cc, i, numReq = -1; + char *clusterName =NULL; + static struct infoReq hostInfoReq; + struct hostDataReply reply; + + if (numHosts) { + numReq = *numHosts; + *numHosts = 0; + } + if (numReq < 0) { + lsberrno = LSBE_BAD_ARG; + return NULL; + } + + FREEUP (hostInfoReq.names); + if (numHosts == NULL || numReq == 0) { + hostInfoReq.numNames = 0; + if ((hostInfoReq.names = (char **) malloc (sizeof(char *))) == NULL) { + lsberrno = LSBE_NO_MEM; + return NULL; + } + + hostInfoReq.numNames = 0; + + + if (resReq != NULL) { + TIMEIT(0, (hostInfoReq.names[0] = ls_getmyhostname()), "ls_getmyhostname"); + options |= CHECK_HOST; + } + else { + hostInfoReq.names[0] = ""; + } + + cc = 1; + } + else if (numReq == 1 && hosts == NULL) { + hostInfoReq.numNames = 1; + if ((hostInfoReq.names = (char **) malloc (sizeof(char *))) == NULL) { + lsberrno = LSBE_NO_MEM; + return NULL; + } + TIMEIT(0, (hostInfoReq.names[0] = ls_getmyhostname()), "ls_getmyhostname"); + hostInfoReq.numNames = 1; + cc = 1; + } + else { + if ((hostInfoReq.names = (char **) calloc + (numReq, sizeof(char*))) == NULL) { + lsberrno = LSBE_NO_MEM; + return NULL; + } + for (i = 0; i < numReq; i++) { + if (ls_isclustername(hosts[i]) <= 0) + continue; + hostInfoReq.names[0] = ""; + hostInfoReq.numNames = 0; + clusterName = hosts[i]; + cc = 1; + break; + } + if (clusterName == NULL) { + for (i = 0; i < numReq; i++) { + if (hosts[i] && strlen (hosts[i]) + 1 < MAXHOSTNAMELEN) + hostInfoReq.names[i] = hosts[i]; + else { + free (hostInfoReq.names); + lsberrno = LSBE_BAD_HOST; + *numHosts = i; + return NULL; + } + } + cc = numReq; + hostInfoReq.numNames = numReq; + } + } + + hostInfoReq.options = options; + if (resReq != NULL) { + if (strlen(resReq) > MAXLINELEN -1) { + lsberrno = LSBE_BAD_RESREQ; + return NULL; + } else { + hostInfoReq.resReq = resReq; + hostInfoReq.options |= SORT_HOST; + } + } else + hostInfoReq.resReq = ""; + + + mbdReqtype = BATCH_HOST_INFO; + cc = sizeof(struct infoReq) + cc * MAXHOSTNAMELEN + cc + 100; + if ((request_buf = malloc (cc)) == NULL) { + lsberrno = LSBE_NO_MEM; + return NULL; + } + xdrmem_create(&xdrs, request_buf, cc, XDR_ENCODE); + + hdr.opCode = mbdReqtype; + if (!xdr_encodeMsg(&xdrs, (char *)&hostInfoReq, &hdr, xdr_infoReq, + 0, NULL)) { + xdr_destroy(&xdrs); + free (request_buf); + lsberrno = LSBE_XDR; + return NULL; + } + + + TIMEIT(0, (cc = callmbd(clusterName, request_buf, XDR_GETPOS(&xdrs), &reply_buf, &hdr, NULL, NULL, NULL)), "callmbd"); + if (cc == -1) { + xdr_destroy(&xdrs); + free (request_buf); + return NULL; + } + xdr_destroy(&xdrs); + free (request_buf); + + + + lsberrno = hdr.opCode; + if (lsberrno == LSBE_NO_ERROR || lsberrno == LSBE_BAD_HOST) { + xdrmem_create(&xdrs, reply_buf, XDR_DECODE_SIZE_(cc), XDR_DECODE); + + if(!xdr_hostDataReply(&xdrs, &reply, &hdr)) { + lsberrno = LSBE_XDR; + xdr_destroy(&xdrs); + if (cc) + free(reply_buf); + return NULL; + } + xdr_destroy(&xdrs); + if (cc) + free(reply_buf); + if (lsberrno == LSBE_BAD_HOST) { + *numHosts = reply.badHost; + return NULL; + } + *numHosts = reply.numHosts; + return(reply.hosts); + } + + if (cc) + free(reply_buf); + return NULL; + +} diff --git a/pool/shard004/C/0100789_StreamIOWriteHandler.c b/pool/shard004/C/0100789_StreamIOWriteHandler.c new file mode 100644 index 0000000000000000000000000000000000000000..0908c33e5ac2835539c18e453fa8fff3e0e00394 --- /dev/null +++ b/pool/shard004/C/0100789_StreamIOWriteHandler.c @@ -0,0 +1,157 @@ +/* ========================================================================= + * 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, see . + * + */ + +#include "nitf/StreamIOWriteHandler.h" + + +typedef struct _WriteHandlerImpl +{ + nitf_IOInterface* ioHandle; + uint64_t offset; + uint64_t bytes; +} WriteHandlerImpl; + + +#define _STREAM_CHUNK_SIZE 8192 + +/* + * Private read implementation for file source. + */ +NITFPRIV(NITF_BOOL) WriteHandler_write + (NITF_DATA * data, nitf_IOInterface* output, nitf_Error * error) +{ + WriteHandlerImpl *impl = NULL; + uint64_t toWrite; + uint32_t bytesThisPass; + char *buf = NULL; + + /* cast it to the structure we know about */ + impl = (WriteHandlerImpl *) data; + + buf = (char*)NITF_MALLOC(_STREAM_CHUNK_SIZE); + if (!buf) + { + nitf_Error_init(error, NITF_STRERROR( NITF_ERRNO ), + NITF_CTXT, NITF_ERR_MEMORY); + return NITF_FAILURE; + } + + /* stream the input to the output in chunks */ + + /* first, seek to the right spot of the input handle */ + if (!NITF_IO_SUCCESS( + nitf_IOInterface_seek( + impl->ioHandle, impl->offset, NITF_SEEK_SET, error + ) + ) + ) + goto CATCH_ERROR; + + toWrite = impl->bytes; + while (toWrite > 0) + { + bytesThisPass = toWrite >= _STREAM_CHUNK_SIZE ? _STREAM_CHUNK_SIZE : + (uint32_t) toWrite; + + /* read */ + if (!nitf_IOInterface_read(impl->ioHandle, buf, bytesThisPass, error)) + goto CATCH_ERROR; + + /* write */ + if (!nitf_IOInterface_write(output, buf, bytesThisPass, error)) + goto CATCH_ERROR; + + /* update count */ + toWrite -= bytesThisPass; + } + + NITF_FREE(buf); + + return NITF_SUCCESS; + + CATCH_ERROR: + if (buf) + NITF_FREE(buf); + return NITF_FAILURE; +} + + +NITFPRIV(void) WriteHandler_destruct(NITF_DATA * data) +{ + if (data) + { + WriteHandlerImpl *impl = (WriteHandlerImpl*)data; + NITF_FREE(impl); + } +} + + +NITFAPI(nitf_WriteHandler*) +nitf_StreamIOWriteHandler_construct(nitf_IOInterface *ioHandle, + uint64_t offset, + uint64_t bytes, + nitf_Error *error) +{ + nitf_WriteHandler *writeHandler = NULL; + WriteHandlerImpl *impl = NULL; + + /* make the interface */ + static nitf_IWriteHandler iWriteHandler = { + &WriteHandler_write, + &WriteHandler_destruct + }; + + /* construct the persisent one */ + impl = (WriteHandlerImpl *) NITF_MALLOC(sizeof(WriteHandlerImpl)); + if (!impl) + { + nitf_Error_init(error, NITF_STRERROR( NITF_ERRNO ), + NITF_CTXT, NITF_ERR_MEMORY); + goto CATCH_ERROR; + } + + impl->ioHandle = ioHandle; + impl->offset = offset; + impl->bytes = bytes; + + writeHandler = + (nitf_WriteHandler *) NITF_MALLOC(sizeof(nitf_WriteHandler)); + + if (!writeHandler) + { + nitf_Error_init(error, NITF_STRERROR( NITF_ERRNO ), + NITF_CTXT, NITF_ERR_MEMORY); + goto CATCH_ERROR; + } + writeHandler->data = impl; + writeHandler->iface = &iWriteHandler; + + /* return successfully */ + return writeHandler; + + CATCH_ERROR: + if (writeHandler) + nitf_WriteHandler_destruct(&writeHandler); + if (impl) + NITF_FREE(impl); + return NULL; +} diff --git a/pool/shard004/C/0100795_CWE134_Uncontrolled_Format_String__wchar_t_console_w32_vsnprintf_02.c b/pool/shard004/C/0100795_CWE134_Uncontrolled_Format_String__wchar_t_console_w32_vsnprintf_02.c new file mode 100644 index 0000000000000000000000000000000000000000..7c106106353dcbe8e415d3dbba38226f10065fe7 --- /dev/null +++ b/pool/shard004/C/0100795_CWE134_Uncontrolled_Format_String__wchar_t_console_w32_vsnprintf_02.c @@ -0,0 +1,293 @@ +/* TEMPLATE GENERATED TESTCASE FILE +Filename: CWE134_Uncontrolled_Format_String__wchar_t_console_w32_vsnprintf_02.c +Label Definition File: CWE134_Uncontrolled_Format_String.vasinks.label.xml +Template File: sources-vasinks-02.tmpl.c +*/ +/* + * @description + * CWE: 134 Uncontrolled Format String + * BadSource: console Read input from the console + * GoodSource: Copy a fixed string into data + * Sinks: w32_vsnprintf + * GoodSink: _vsnwprintf with a format string + * BadSink : _vsnwprintf without a format string + * Flow Variant: 02 Control flow: if(1) and if(0) + * + * */ + +#include +#include "std_testcase.h" + +#ifndef _WIN32 +#include +#endif + +#ifndef OMITBAD + +static void badVaSinkB(wchar_t * data, ...) +{ + { + wchar_t dest[100] = L""; + va_list args; + va_start(args, data); + /* POTENTIAL FLAW: Do not specify the format allowing a possible format string vulnerability */ + _vsnwprintf(dest, 100-1, data, args); + va_end(args); + printWLine(dest); + } +} + +void CWE134_Uncontrolled_Format_String__wchar_t_console_w32_vsnprintf_02_bad() +{ + wchar_t * data; + wchar_t dataBuffer[100] = L""; + data = dataBuffer; + if(1) + { + { + /* Read input from the console */ + size_t dataLen = wcslen(data); + /* if there is room in data, read into it from the console */ + if (100-dataLen > 1) + { + /* POTENTIAL FLAW: Read data from the console */ + if (fgetws(data+dataLen, (int)(100-dataLen), stdin) != NULL) + { + /* The next few lines remove the carriage return from the string that is + * inserted by fgetws() */ + dataLen = wcslen(data); + if (dataLen > 0 && data[dataLen-1] == L'\n') + { + data[dataLen-1] = L'\0'; + } + } + else + { + printLine("fgetws() failed"); + /* Restore NUL terminator if fgetws fails */ + data[dataLen] = L'\0'; + } + } + } + } + if(1) + { + badVaSinkB(data, data); + } +} + +#endif /* OMITBAD */ + +#ifndef OMITGOOD + +static void goodB2G1VaSinkG(wchar_t * data, ...) +{ + { + wchar_t dest[100] = L""; + va_list args; + va_start(args, data); + /* FIX: Specify the format disallowing a format string vulnerability */ + _vsnwprintf(dest, 100-1, L"%s", args); + va_end(args); + printWLine(dest); + } +} + +/* goodB2G1() - use badsource and goodsink by changing the second 1 to 0 */ +static void goodB2G1() +{ + wchar_t * data; + wchar_t dataBuffer[100] = L""; + data = dataBuffer; + if(1) + { + { + /* Read input from the console */ + size_t dataLen = wcslen(data); + /* if there is room in data, read into it from the console */ + if (100-dataLen > 1) + { + /* POTENTIAL FLAW: Read data from the console */ + if (fgetws(data+dataLen, (int)(100-dataLen), stdin) != NULL) + { + /* The next few lines remove the carriage return from the string that is + * inserted by fgetws() */ + dataLen = wcslen(data); + if (dataLen > 0 && data[dataLen-1] == L'\n') + { + data[dataLen-1] = L'\0'; + } + } + else + { + printLine("fgetws() failed"); + /* Restore NUL terminator if fgetws fails */ + data[dataLen] = L'\0'; + } + } + } + } + if(0) + { + /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */ + printLine("Benign, fixed string"); + } + else + { + goodB2G1VaSinkG(data, data); + } +} + +static void goodB2G2VaSinkG(wchar_t * data, ...) +{ + { + wchar_t dest[100] = L""; + va_list args; + va_start(args, data); + /* FIX: Specify the format disallowing a format string vulnerability */ + _vsnwprintf(dest, 100-1, L"%s", args); + va_end(args); + printWLine(dest); + } +} + +/* goodB2G2() - use badsource and goodsink by reversing the blocks in the second if */ +static void goodB2G2() +{ + wchar_t * data; + wchar_t dataBuffer[100] = L""; + data = dataBuffer; + if(1) + { + { + /* Read input from the console */ + size_t dataLen = wcslen(data); + /* if there is room in data, read into it from the console */ + if (100-dataLen > 1) + { + /* POTENTIAL FLAW: Read data from the console */ + if (fgetws(data+dataLen, (int)(100-dataLen), stdin) != NULL) + { + /* The next few lines remove the carriage return from the string that is + * inserted by fgetws() */ + dataLen = wcslen(data); + if (dataLen > 0 && data[dataLen-1] == L'\n') + { + data[dataLen-1] = L'\0'; + } + } + else + { + printLine("fgetws() failed"); + /* Restore NUL terminator if fgetws fails */ + data[dataLen] = L'\0'; + } + } + } + } + if(1) + { + goodB2G2VaSinkG(data, data); + } +} + +static void goodG2B1VaSinkB(wchar_t * data, ...) +{ + { + wchar_t dest[100] = L""; + va_list args; + va_start(args, data); + /* POTENTIAL FLAW: Do not specify the format allowing a possible format string vulnerability */ + _vsnwprintf(dest, 100-1, data, args); + va_end(args); + printWLine(dest); + } +} + +/* goodG2B1() - use goodsource and badsink by changing the first 1 to 0 */ +static void goodG2B1() +{ + wchar_t * data; + wchar_t dataBuffer[100] = L""; + data = dataBuffer; + if(0) + { + /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */ + printLine("Benign, fixed string"); + } + else + { + /* FIX: Use a fixed string that does not contain a format specifier */ + wcscpy(data, L"fixedstringtest"); + } + if(1) + { + goodG2B1VaSinkB(data, data); + } +} + +static void goodG2B2VaSinkB(wchar_t * data, ...) +{ + { + wchar_t dest[100] = L""; + va_list args; + va_start(args, data); + /* POTENTIAL FLAW: Do not specify the format allowing a possible format string vulnerability */ + _vsnwprintf(dest, 100-1, data, args); + va_end(args); + printWLine(dest); + } +} + +/* goodG2B2() - use goodsource and badsink by reversing the blocks in the first if */ +static void goodG2B2() +{ + wchar_t * data; + wchar_t dataBuffer[100] = L""; + data = dataBuffer; + if(1) + { + /* FIX: Use a fixed string that does not contain a format specifier */ + wcscpy(data, L"fixedstringtest"); + } + if(1) + { + goodG2B2VaSinkB(data, data); + } +} + +void CWE134_Uncontrolled_Format_String__wchar_t_console_w32_vsnprintf_02_good() +{ + goodG2B1(); + goodG2B2(); + goodB2G1(); + goodB2G2(); +} + +#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()..."); + CWE134_Uncontrolled_Format_String__wchar_t_console_w32_vsnprintf_02_good(); + printLine("Finished good()"); +#endif /* OMITGOOD */ +#ifndef OMITBAD + printLine("Calling bad()..."); + CWE134_Uncontrolled_Format_String__wchar_t_console_w32_vsnprintf_02_bad(); + printLine("Finished bad()"); +#endif /* OMITBAD */ + return 0; +} + +#endif diff --git a/pool/shard004/C/0100806_cap.c b/pool/shard004/C/0100806_cap.c new file mode 100644 index 0000000000000000000000000000000000000000..c3ba841bbf3772bffabde9e5d4f0060a8daa9dfa --- /dev/null +++ b/pool/shard004/C/0100806_cap.c @@ -0,0 +1,29 @@ +// SPDX-License-Identifier: GPL-2.0 +/* + * Capability utilities + */ + +#ifdef HAVE_LIBCAP_SUPPORT + +#include "cap.h" +#include +#include + +bool perf_cap__capable(cap_value_t cap) +{ + cap_flag_value_t val; + cap_t caps = cap_get_proc(); + + if (!caps) + return false; + + if (cap_get_flag(caps, cap, CAP_EFFECTIVE, &val) != 0) + val = CAP_CLEAR; + + if (cap_free(caps) != 0) + return false; + + return val == CAP_SET; +} + +#endif /* HAVE_LIBCAP_SUPPORT */ diff --git a/pool/shard004/C/0100811_main.c b/pool/shard004/C/0100811_main.c new file mode 100644 index 0000000000000000000000000000000000000000..cc46e3e4e14f2b5209a6d2a5edd36b84b0eb0222 --- /dev/null +++ b/pool/shard004/C/0100811_main.c @@ -0,0 +1,336 @@ +/** + ****************************************************************************** + * @file FMC/FMC_SRAM/Src/main.c + * @author MCD Application Team + * @version V1.0.1 + * @date 09-October-2015 + * @brief This sample code shows how to use STM32F4xx FMC HAL API to access + * by read and write operation the SRAM external memory device. + ****************************************************************************** + * @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 FMC_SRAM + * @{ + */ + +/* Private typedef -----------------------------------------------------------*/ +/* Private define ------------------------------------------------------------*/ +#define BUFFER_SIZE ((uint32_t)0x0100) +#define WRITE_READ_ADDR ((uint32_t)0x0800) + +/* Private macro -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +SRAM_HandleTypeDef hsram; +FMC_NORSRAM_TimingTypeDef SRAM_Timing; + +/* Read/Write Buffers */ +uint32_t aTxBuffer[BUFFER_SIZE]; +uint32_t aRxBuffer[BUFFER_SIZE]; + +/* Status variables */ +__IO uint32_t uwWriteReadStatus = 0; + +/* Counter index */ +uint32_t uwIndex = 0; + +/* Private function prototypes -----------------------------------------------*/ +static void SystemClock_Config(void); +static void Error_Handler(void); +static void Fill_Buffer(uint32_t *pBuffer, uint32_t uwBufferLenght, uint32_t uwOffset); +static TestStatus Buffercmp(uint32_t *pBuffer1, uint32_t *pBuffer2, uint16_t BufferLength); + +/* Private functions ---------------------------------------------------------*/ + +/** + * @brief Main program + * @param None + * @retval None + */ +int main(void) +{ + /* STM32F4xx HAL library initialization: + - Configure the Flash prefetch, instruction and Data caches + - Systick timer is configured by default as source of time base, but user + can eventually implement his proper time base source (a general purpose + timer for example or other time source), keeping in mind that Time base + duration should be kept 1ms since PPP_TIMEOUT_VALUEs are defined and + handled in milliseconds basis. + - Set NVIC Group Priority to 4 + - Low Level Initialization: global MSP (MCU Support Package) initialization + */ + HAL_Init(); + + /* Configure the system clock to 180 MHz */ + SystemClock_Config(); + + /* Configure LED1 and LED3 */ + BSP_LED_Init(LED1); + BSP_LED_Init(LED3); + + /*##-1- Configure the SRAM device ##########################################*/ + /* SRAM device configuration */ + + hsram.Instance = FMC_NORSRAM_DEVICE; + hsram.Extended = FMC_NORSRAM_EXTENDED_DEVICE; + + /* SRAM device configuration */ + SRAM_Timing.AddressSetupTime = 2; + SRAM_Timing.AddressHoldTime = 1; + SRAM_Timing.DataSetupTime = 2; + SRAM_Timing.BusTurnAroundDuration = 1; + SRAM_Timing.CLKDivision = 2; + SRAM_Timing.DataLatency = 2; + SRAM_Timing.AccessMode = FMC_ACCESS_MODE_A; + + hsram.Init.NSBank = FMC_NORSRAM_BANK2; + hsram.Init.DataAddressMux = FMC_DATA_ADDRESS_MUX_DISABLE; + hsram.Init.MemoryType = FMC_MEMORY_TYPE_SRAM; + hsram.Init.MemoryDataWidth = SRAM_MEMORY_WIDTH; + hsram.Init.BurstAccessMode = FMC_BURST_ACCESS_MODE_DISABLE; + hsram.Init.WaitSignalPolarity = FMC_WAIT_SIGNAL_POLARITY_LOW; + hsram.Init.WrapMode = FMC_WRAP_MODE_DISABLE; + hsram.Init.WaitSignalActive = FMC_WAIT_TIMING_BEFORE_WS; + hsram.Init.WriteOperation = FMC_WRITE_OPERATION_ENABLE; + hsram.Init.WaitSignal = FMC_WAIT_SIGNAL_DISABLE; + hsram.Init.ExtendedMode = FMC_EXTENDED_MODE_DISABLE; + hsram.Init.AsynchronousWait = FMC_ASYNCHRONOUS_WAIT_DISABLE; + hsram.Init.WriteBurst = FMC_WRITE_BURST_DISABLE; + + HAL_SRAM_DeInit(&hsram); + /* Initialize the SRAM controller */ + if(HAL_SRAM_Init(&hsram, &SRAM_Timing, &SRAM_Timing) != HAL_OK) + { + /* Initialization Error */ + Error_Handler(); + } + + /*##-2- SRAM memory read/write access ######################################*/ + /* Fill the buffer to write */ + Fill_Buffer(aTxBuffer, BUFFER_SIZE, 0xC20FC210); + + /* Write data to the SRAM memory */ + for(uwIndex = 0; uwIndex < BUFFER_SIZE; uwIndex++) + { + *(__IO uint32_t *)(SRAM_BANK_ADDR + WRITE_READ_ADDR + 4 * uwIndex) = aTxBuffer[uwIndex]; + } + + /* Read back data from the SRAM memory */ + for(uwIndex = 0; uwIndex < BUFFER_SIZE; uwIndex++) + { + aRxBuffer[uwIndex] = *(__IO uint32_t *)(SRAM_BANK_ADDR + WRITE_READ_ADDR + 4 * uwIndex); + } + + /*##-3- Checking data integrity ############################################*/ + uwWriteReadStatus = Buffercmp(aTxBuffer, aRxBuffer, BUFFER_SIZE); + + if(uwWriteReadStatus != PASSED) + { + /* KO */ + /* Turn on LED3 */ + BSP_LED_On(LED3); + } + else + { + /* OK */ + /* Turn on LED1 */ + BSP_LED_On(LED1); + } + + /* Infinite loop */ + while (1) + { + } +} + +/** + * @brief System Clock Configuration + * 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) = 25000000 + * PLL_M = 25 + * PLL_N = 360 + * PLL_P = 2 + * PLL_Q = 7 + * PLL_R = 6 + * 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; + HAL_StatusTypeDef ret = HAL_OK; + + /* 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 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 = 360; + RCC_OscInitStruct.PLL.PLLP = RCC_PLLP_DIV2; + RCC_OscInitStruct.PLL.PLLQ = 7; + RCC_OscInitStruct.PLL.PLLR = 6; + + ret = HAL_RCC_OscConfig(&RCC_OscInitStruct); + if(ret != HAL_OK) + { + while(1) { ; } + } + + /* Activate the OverDrive to reach the 180 MHz Frequency */ + ret = HAL_PWREx_EnableOverDrive(); + if(ret != HAL_OK) + { + while(1) { ; } + } + + /* 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; + + ret = HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_5); + if(ret != HAL_OK) + { + while(1) { ; } + } +} + +/** + * @brief This function is executed in case of error occurrence. + * @param None + * @retval None + */ +static void Error_Handler(void) +{ + /* Turn LED3 on */ + BSP_LED_On(LED3); + while (1) + { + } +} + +/** + * @brief Fills buffer with user predefined data. + * @param pBuffer: pointer on the buffer to fill + * @param uwBufferLength: 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 uwBufferLength, uint32_t uwOffset) +{ + uint32_t tmpIndex = 0; + + /* Put in global buffer different values */ + for (tmpIndex = 0; tmpIndex < uwBufferLength; tmpIndex++) + { + pBuffer[tmpIndex] = tmpIndex + uwOffset; + } +} + +/** + * @brief Compares two buffers. + * @param pBuffer1, pBuffer2: buffers to be compared. + * @param BufferLength: buffer's length + * @retval PASSED: pBuffer identical to pBuffer1 + * FAILED: pBuffer differs from pBuffer1 + */ +static TestStatus Buffercmp(uint32_t *pBuffer1, uint32_t *pBuffer2, uint16_t BufferLength) +{ + while (BufferLength--) + { + if (*pBuffer1 != *pBuffer2) + { + return FAILED; + } + + pBuffer1++; + pBuffer2++; + } + + return PASSED; +} + +#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/shard004/C/0100817_ip_vs_sed.c b/pool/shard004/C/0100817_ip_vs_sed.c new file mode 100644 index 0000000000000000000000000000000000000000..6ac6a887d7c3f690475fe7156acd487ae3c7e502 --- /dev/null +++ b/pool/shard004/C/0100817_ip_vs_sed.c @@ -0,0 +1,104 @@ + + + +#define KMSG_COMPONENT "IPVS" +#define pr_fmt(fmt) KMSG_COMPONENT ": " fmt + +#include +#include + +#include + + +static inline unsigned int +ip_vs_sed_dest_overhead(struct ip_vs_dest *dest) +{ + /* + * We only use the active connection number in the cost + * calculation here. + */ + return atomic_read(&dest->activeconns) + 1; +} + + +static struct ip_vs_dest * +ip_vs_sed_schedule(struct ip_vs_service *svc, const struct sk_buff *skb) +{ + struct ip_vs_dest *dest, *least; + unsigned int loh, doh; + + IP_VS_DBG(6, "%s(): Scheduling...\n", __func__); + + /* + * We calculate the load of each dest server as follows: + * (server expected overhead) / dest->weight + * + * Remember -- no floats in kernel mode!!! + * The comparison of h1*w2 > h2*w1 is equivalent to that of + * h1/w1 > h2/w2 + * if every weight is larger than zero. + * + * The server with weight=0 is quiesced and will not receive any + * new connections. + */ + + list_for_each_entry(dest, &svc->destinations, n_list) { + if (!(dest->flags & IP_VS_DEST_F_OVERLOAD) && + atomic_read(&dest->weight) > 0) { + least = dest; + loh = ip_vs_sed_dest_overhead(least); + goto nextstage; + } + } + IP_VS_ERR_RL("SED: no destination available\n"); + return NULL; + + /* + * Find the destination with the least load. + */ + nextstage: + list_for_each_entry_continue(dest, &svc->destinations, n_list) { + if (dest->flags & IP_VS_DEST_F_OVERLOAD) + continue; + doh = ip_vs_sed_dest_overhead(dest); + if (loh * atomic_read(&dest->weight) > + doh * atomic_read(&least->weight)) { + least = dest; + loh = doh; + } + } + + IP_VS_DBG_BUF(6, "SED: server %s:%u " + "activeconns %d refcnt %d weight %d overhead %d\n", + IP_VS_DBG_ADDR(svc->af, &least->addr), ntohs(least->port), + atomic_read(&least->activeconns), + atomic_read(&least->refcnt), + atomic_read(&least->weight), loh); + + return least; +} + + +static struct ip_vs_scheduler ip_vs_sed_scheduler = +{ + .name = "sed", + .refcnt = ATOMIC_INIT(0), + .module = THIS_MODULE, + .n_list = LIST_HEAD_INIT(ip_vs_sed_scheduler.n_list), + .schedule = ip_vs_sed_schedule, +}; + + +static int __init ip_vs_sed_init(void) +{ + return register_ip_vs_scheduler(&ip_vs_sed_scheduler); +} + +static void __exit ip_vs_sed_cleanup(void) +{ + unregister_ip_vs_scheduler(&ip_vs_sed_scheduler); +} + +module_init(ip_vs_sed_init); +module_exit(ip_vs_sed_cleanup); +MODULE_LICENSE("GPL"); diff --git a/pool/shard004/C/0100828_win_attach.c b/pool/shard004/C/0100828_win_attach.c new file mode 100644 index 0000000000000000000000000000000000000000..b6a27cad47c87d7fb4b2b794474b56a95a5ab015 --- /dev/null +++ b/pool/shard004/C/0100828_win_attach.c @@ -0,0 +1,61 @@ +/* + * Copyright (c) 2004-2007 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-2008 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) 2006 Cisco Systems, Inc. All rights reserved. + * Copyright (c) 2015 Research Organization for Information Science + * and Technology (RIST). All rights reserved. + * $COPYRIGHT$ + * + * Additional copyrights may follow + * + * $HEADER$ + */ +#include "ompi_config.h" + +#include + +#include "ompi/mpi/c/bindings.h" +#include "ompi/runtime/params.h" +#include "ompi/communicator/communicator.h" +#include "ompi/errhandler/errhandler.h" +#include "ompi/info/info.h" +#include "ompi/win/win.h" +#include "ompi/memchecker.h" + +#if OMPI_BUILD_MPI_PROFILING +#if OPAL_HAVE_WEAK_SYMBOLS +#pragma weak MPI_Win_attach = PMPI_Win_attach +#endif +#define MPI_Win_attach PMPI_Win_attach +#endif + +static const char FUNC_NAME[] = "MPI_Win_attach"; + +int MPI_Win_attach(MPI_Win win, void *base, MPI_Aint size) +{ + int ret = MPI_SUCCESS; + + /* argument checking */ + if (MPI_PARAM_CHECK) { + OMPI_ERR_INIT_FINALIZE(FUNC_NAME); + + if (ompi_win_invalid(win)) { + return OMPI_ERRHANDLER_INVOKE(MPI_COMM_WORLD, MPI_ERR_WIN, FUNC_NAME); + } else if (NULL == base) { + ret = MPI_ERR_ARG; + } + OMPI_ERRHANDLER_CHECK(ret, win, ret, FUNC_NAME); + } + + /* create window and return */ + ret = win->w_osc_module->osc_win_attach(win, base, size); + OMPI_ERRHANDLER_RETURN(ret, win, ret, FUNC_NAME); +} diff --git a/pool/shard004/C/0100830_extract.c b/pool/shard004/C/0100830_extract.c new file mode 100644 index 0000000000000000000000000000000000000000..e2d284ca65e2c72b52f61c607c3088cf64884a8f --- /dev/null +++ b/pool/shard004/C/0100830_extract.c @@ -0,0 +1,147 @@ +/* + * Copyright 2017-2021 Matt "MateoConLechuga" Waltz + * + * 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 "extract.h" +#include "input.h" +#include "ti8x.h" +#include "log.h" + +#include + +/* + * Write 24-bit value into array. + */ +void extract_write_word(unsigned char *addr, unsigned int value) +{ + addr[0] = (value >> 0) & 0xff; + addr[1] = (value >> 8) & 0xff; + addr[2] = (value >> 16) & 0xff; +} + +/* from extractor.asm */ +/* run the asm makefile to print */ +#define EXTRACTOR_ENTRY_OFFSET 1 +#define EXTRACTOR_PRGM_SIZE_OFFSET 9 +#define EXTRACTOR_EXTRACT_SIZE_OFFSET 19 +#define EXTRACTOR_APPVARS_OFFSET 183 + +/* + * Create and 8xp that extracts from 8xv. + */ +int extract_8xp_to_8xv(unsigned char **arr, + size_t *size, + char appvar_names[10][10], + unsigned int num_appvars) +{ + extern unsigned char extractor[]; + extern unsigned int extractor_len; + unsigned char *newarr = malloc(TI8X_MAXDATA_SIZE); + unsigned char *inarr = *arr; + unsigned int extractorsize; + unsigned int entryaddr; + unsigned int offset; + unsigned int i; + int ret = 0; + + newarr[0] = TI8X_TOKEN_EXT; + newarr[1] = TI8X_TOKEN_ASM84CECMP; + + offset = TI8X_ASMCOMP_LEN; + + /* handle icon and/or description by copying it if it exists */ + if (inarr[TI8X_MAGIC_JUMP_OFFSET_0] == TI8X_MAGIC_JUMP) + { + offset = TI8X_MAGIC_JUMP_OFFSET_0 + 4; + } + else if (inarr[TI8X_MAGIC_JUMP_OFFSET_1] == TI8X_MAGIC_JUMP) + { + offset = TI8X_MAGIC_JUMP_OFFSET_1 + 4; + } + + if (inarr[offset] == TI8X_ICON_MAGIC) + { + unsigned char width = (*arr)[offset + 1]; + unsigned char height = (*arr)[offset + 2]; + + offset += 2 + width * height; + goto move_to_end_of_description; + } + else if (inarr[offset] == TI8X_DESCRIPTION_MAGIC) + { +move_to_end_of_description: + offset += 1; + while (inarr[offset]) + { + offset++; + if (offset >= *size) + { + LL_ERROR("oddly formated 8x file."); + return 1; + } + } + + offset++; + if (offset >= *size) + { + LL_ERROR("oddly formated 8x file."); + return 1; + } + + memcpy(newarr + TI8X_ASMCOMP_LEN, *arr + TI8X_ASMCOMP_LEN, offset); + } + + extract_write_word(extractor + EXTRACTOR_EXTRACT_SIZE_OFFSET, *size + 0x10); + + entryaddr = offset + TI8X_USERMEM_ADDRESS + 16; + extract_write_word(extractor + EXTRACTOR_ENTRY_OFFSET, entryaddr); + + extractorsize = EXTRACTOR_APPVARS_OFFSET - 15 + num_appvars * TI8X_VARLOOKUP_LEN; + extract_write_word(extractor + EXTRACTOR_PRGM_SIZE_OFFSET, extractorsize); + + memcpy(newarr + offset, extractor, extractor_len); + offset += extractor_len; + + for (i = 0; i < num_appvars; ++i) + { + memcpy(newarr + offset, appvar_names[i], TI8X_VARLOOKUP_LEN); + offset += TI8X_VARLOOKUP_LEN; + } + + newarr[offset] = 0; + offset++; + + free(*arr); + *arr = NULL; + + *arr = newarr; + *size = offset; + + return ret; +} diff --git a/pool/shard004/C/0100838_dskn02_c.c b/pool/shard004/C/0100838_dskn02_c.c new file mode 100644 index 0000000000000000000000000000000000000000..c07997840522fe9d52f0c6e7e260eb419e4933d2 --- /dev/null +++ b/pool/shard004/C/0100838_dskn02_c.c @@ -0,0 +1,386 @@ +/* + +-Procedure dskn02_c ( DSK, type 2, compute normal vector for plate ) + +-Abstract + + Compute the unit normal vector for a specified plate from a type + 2 DSK segment. + +-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 + + DAS + DSK + +-Keywords + + DAS + DSK + FILES + +*/ + + #include "SpiceUsr.h" + #include "SpiceZfc.h" + #undef dskn02_c + + + void dskn02_c ( SpiceInt handle, + ConstSpiceDLADescr * dladsc, + SpiceInt plid, + SpiceDouble normal[3] ) +/* + +-Brief_I/O + + Variable I/O Description + -------- --- -------------------------------------------------- + handle I DSK file handle. + dladsc I DLA descriptor. + plid I Plate ID. + normal O Plate's unit normal vector. + +-Detailed_Input + + handle is the handle of a DSK file containing a type 2 + segment from which data are to be fetched. + + dladsc is the DLA descriptor associated with the segment + from which data are to be fetched. + + plid is the plate ID. Plate IDs range from 1 to NP + (the number of plates in the segment identified + by `dladsc'). + +-Detailed_Output + + normal is the normal vector associated with the plate + designated by `plid'. The direction of `normal' is + determined by the order of the plate's vertices; + the vertices are presumed to be ordered in the + right-handed (counterclockwise) sense about the + normal direction. If the plate's vertices are + v1, v2, v3, then `normal' points in the direction + + (v2 - v1) x ( v3 - v2 ) + + where "x" represents the cross product operator. + + The vector `normal' is expressed in the body-fixed + reference frame of the segment designated by + `dladsc'. The center of this frame is the origin of + the cartesian coordinate system in which the vertices + are expressed. Note that the frame center need not + coincide with the central body of the segment. Units + are km. + + The vector has magnitude 1. + + If an error occurs on the call, `normal' is + undefined. + +-Parameters + + See the header file + + SpiceDLA.h + +-Exceptions + + 1) If the input handle is invalid, the error will be diagnosed by + routines in the call tree of this routine. + + 2) If a file read error occurs, the error will be diagnosed by + routines in the call tree of this routine. + + 3) If the input DLA descriptor is invalid, the effect of this + routine is undefined. The error *may* be diagnosed by routines + in the call tree of this routine, but there are no guarantees. + + 4) If `plid' is less than 1 or greater than the number of plates + in the segment, the error SPICE(INDEXOUTOFRANGE) is signaled. + + 5) This routine does not check for linear independence of the + plate's edges. The plate model is assumed to be geometrically + valid. + +-Files + + See input argument `handle'. + +-Particulars + + None. + +-Examples + + 1) Look up all the vertices associated with each plate + of the model contained in a specified type 2 segment. For each + plate, display the plate's vertices and normal vector. + + For this example, we'll show the context of this look-up: + opening the DSK file for read access, traversing a trivial, + one-segment list to obtain the segment of interest. + + Example code begins here. + + #include + #include "SpiceUsr.h" + #include "SpiceDLA.h" + #include "dsk_proto.h" + + int main() + { + /. + Constants + ./ + #define PBUFSIZ 10000 + #define FILSIZ 256 + + /. + Local variables + ./ + SpiceBoolean found; + + SpiceChar dsk [ FILSIZ ]; + + SpiceDLADescr dladsc; + + SpiceDouble normal [3]; + SpiceDouble verts [3][3]; + + SpiceInt handle; + SpiceInt i; + SpiceInt j; + SpiceInt n; + SpiceInt np; + SpiceInt nread; + SpiceInt nv; + SpiceInt nvtx; + SpiceInt plates[PBUFSIZ][3]; + SpiceInt plix; + SpiceInt remain; + SpiceInt start; + + /. + Prompt for name of DSK and open file for reading. + ./ + prompt_c ( "Enter DSK name > ", FILSIZ, dsk ); + + dasopr_c ( dsk, &handle ); + + dlabfs_c ( handle, &dladsc, &found ); + + if ( !found ) + { + setmsg_c ( "No segment found in file #." ); + errch_c ( "#", dsk ); + sigerr_c ( "SPICE(NOSEGMENT)" ); + } + + /. + Get segment vertex and plate counts. + ./ + dskz02_c ( handle, &dladsc, &nv, &np ); + + printf ( "\n" + "Number of vertices: %d\n" + "Number of plates: %d\n", + (int)nv, + (int)np ); + + /. + Display the vertices of each plate. + ./ + remain = np; + start = 1; + + while ( remain > 0 ) + { + /. + `nread' is the number of plates we"ll read on this + loop pass. + ./ + nread = mini_c ( 2, PBUFSIZ, remain ); + + dskp02_c ( handle, &dladsc, start, nread, &n, plates ); + + for ( i = 0; i < nread; i++ ) + { + plix = start + i; + + /. + Read the vertices of the current plate. + ./ + for ( j = 0; j < 3; j++ ) + { + dskv02_c ( handle, &dladsc, plates[i][j], + 1, &nvtx, + ( SpiceDouble(*)[3] )(verts[j]) ); + } + + /. + Display the vertices of the current plate: + ./ + printf ( "\n" + " Plate number: %d\n" + " Vertex 1: ( %16.8e %16.8e %16.8e )\n" + " Vertex 2: ( %16.8e %16.8e %16.8e )\n" + " Vertex 3: ( %16.8e %16.8e %16.8e )\n", + (int)plix, + verts[0][0], verts[0][1], verts[0][2], + verts[1][0], verts[1][1], verts[1][2], + verts[2][0], verts[2][1], verts[2][2] ); + + /. + Display the normal vector of the current plate: + ./ + dskn02_c ( handle, &dladsc, plix, normal ); + + printf( " Normal: ( %16.8e %16.8e %16.8e )\n", + normal[0], normal[1], normal[2] ); + } + + start = start + nread; + remain = remain - nread; + } + + /. + Close the kernel. This isn't necessary in a stand- + alone program, but it's good practice in subroutines + because it frees program and system resources. + ./ + dascls_c ( handle ); + + return ( 0 ); + } + + + When this program was executed on a PC/Linux/gcc/32bit + platform, using a DSK file representing a regular icosahedron, + the output was: + + + Number of vertices: 12 + Number of plates: 20 + + Plate number: 1 + Vertex 1: ( 0.00000000e+00 0.00000000e+00 1.17557000e+00 ) + Vertex 2: ( 1.05146000e+00 0.00000000e+00 5.25731000e-01 ) + Vertex 3: ( 3.24920000e-01 1.00000000e+00 5.25731000e-01 ) + Normal: ( 4.91124160e-01 3.56821347e-01 7.94654382e-01 ) + + Plate number: 2 + Vertex 1: ( 0.00000000e+00 0.00000000e+00 1.17557000e+00 ) + Vertex 2: ( 3.24920000e-01 1.00000000e+00 5.25731000e-01 ) + Vertex 3: ( -8.50651000e-01 6.18034000e-01 5.25731000e-01 ) + Normal: ( -1.87592328e-01 5.77350079e-01 7.94654645e-01 ) + + ... + + Plate number: 20 + Vertex 1: ( 8.50651000e-01 -6.18034000e-01 -5.25731000e-01 ) + Vertex 2: ( 0.00000000e+00 0.00000000e+00 -1.17557000e+00 ) + Vertex 3: ( 8.50651000e-01 6.18034000e-01 -5.25731000e-01 ) + Normal: ( 6.07061680e-01 0.00000000e+00 -7.94654715e-01 ) + + +-Restrictions + + See Exceptions. + +-Literature_References + + None. + +-Author_and_Institution + + N.J. Bachman (JPL) + +-Version + + -CSPICE Version 1.0.1, 27-JAN-2016 (NJB) + + Edit to example program to use "%d" with explicit casts + to int for printing SpiceInts with printf. + + Updated header Detailed_Output and Index_Entries + sections. + + -CSPICE Version 1.0.0, 03-JUN-2010 (NJB) + +-Index_Entries + + compute normal vector for a type 2 dsk plate + compute normal vector from dsk type 2 plate id + +-& +*/ + +{ /* Begin dskn02_c */ + + + /* + Local variables + */ + integer fDLADescr [ SPICE_DLA_DSCSIZ ]; + + /* + Participate in error tracing. + */ + if ( return_c() ) + { + return; + } + chkin_c ( "dskn02_c" ); + + /* + Populate the Fortran DLA descriptor array fDLADescr with the contents + of the input descriptor. + */ + fDLADescr[SPICE_DLA_BWDIDX] = dladsc->bwdptr; + fDLADescr[SPICE_DLA_FWDIDX] = dladsc->fwdptr; + fDLADescr[SPICE_DLA_IBSIDX] = dladsc->ibase; + fDLADescr[SPICE_DLA_ISZIDX] = dladsc->isize; + fDLADescr[SPICE_DLA_DBSIDX] = dladsc->dbase; + fDLADescr[SPICE_DLA_DSZIDX] = dladsc->dsize; + fDLADescr[SPICE_DLA_CBSIDX] = dladsc->cbase; + fDLADescr[SPICE_DLA_CSZIDX] = dladsc->csize; + + /* + Call the f2c'd routine. + */ + dskn02_ ( ( integer * ) &handle, + ( integer * ) fDLADescr, + ( integer * ) &plid, + ( doublereal * ) normal ); + + + chkout_c ( "dskn02_c" ); + +} /* End dskn02_c */ diff --git a/pool/shard004/C/0100857_s_scalbn.c b/pool/shard004/C/0100857_s_scalbn.c new file mode 100644 index 0000000000000000000000000000000000000000..e7efaabbf55941d102f3c7c9ad7f5cd4a54f0197 --- /dev/null +++ b/pool/shard004/C/0100857_s_scalbn.c @@ -0,0 +1,66 @@ +/* @(#)s_scalbn.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. + * ==================================================== + */ + +#ifndef lint +static char rcsid[] = "$FreeBSD$"; +#endif + +/* + * scalbn (double x, int n) + * scalbn(x,n) returns x* 2**n computed by exponent + * manipulation rather than by actually performing an + * exponentiation or a multiplication. + */ + +#include +#include + +#include "math.h" +#include "math_private.h" + +static const double +two54 = 1.80143985094819840000e+16, /* 0x43500000, 0x00000000 */ +twom54 = 5.55111512312578270212e-17, /* 0x3C900000, 0x00000000 */ +huge = 1.0e+300, +tiny = 1.0e-300; + +double +scalbn (double x, int n) +{ + int32_t k,hx,lx; + EXTRACT_WORDS(hx,lx,x); + k = (hx&0x7ff00000)>>20; /* extract exponent */ + if (k==0) { /* 0 or subnormal x */ + if ((lx|(hx&0x7fffffff))==0) return x; /* +-0 */ + x *= two54; + GET_HIGH_WORD(hx,x); + k = ((hx&0x7ff00000)>>20) - 54; + if (n< -50000) return tiny*x; /*underflow*/ + } + if (k==0x7ff) return x+x; /* NaN or Inf */ + k = k+n; + if (k > 0x7fe) return huge*copysign(huge,x); /* overflow */ + if (k > 0) /* normal result */ + {SET_HIGH_WORD(x,(hx&0x800fffff)|(k<<20)); return x;} + if (k <= -54) + if (n > 50000) /* in case integer overflow in n+k */ + return huge*copysign(huge,x); /*overflow*/ + else return tiny*copysign(tiny,x); /*underflow*/ + k += 54; /* subnormal result */ + SET_HIGH_WORD(x,(hx&0x800fffff)|(k<<20)); + return x*twom54; +} + +#if (LDBL_MANT_DIG == 53) +__weak_reference(scalbn, ldexpl); +__weak_reference(scalbn, scalbnl); +#endif diff --git a/pool/shard004/C/0100864_sntp.c b/pool/shard004/C/0100864_sntp.c new file mode 100644 index 0000000000000000000000000000000000000000..677574d20002b206cf51034527be6ff7f57d8c3c --- /dev/null +++ b/pool/shard004/C/0100864_sntp.c @@ -0,0 +1,134 @@ +// Copyright 2015-2019 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 +#include +#include "esp_log.h" +#include "sntp.h" +#include "lwip/apps/sntp.h" + +static const char *TAG = "sntp"; + +static volatile sntp_sync_mode_t sntp_sync_mode = SNTP_SYNC_MODE_IMMED; +static volatile sntp_sync_status_t sntp_sync_status = SNTP_SYNC_STATUS_RESET; +static sntp_sync_time_cb_t time_sync_notification_cb = NULL; +static uint32_t s_sync_interval = CONFIG_LWIP_SNTP_UPDATE_DELAY; + +inline void sntp_set_sync_status(sntp_sync_status_t sync_status) +{ + sntp_sync_status = sync_status; +} + +void __attribute__((weak)) sntp_sync_time(struct timeval *tv) +{ + if (sntp_sync_mode == SNTP_SYNC_MODE_IMMED) { + settimeofday(tv, NULL); + sntp_set_sync_status(SNTP_SYNC_STATUS_COMPLETED); + } else if (sntp_sync_mode == SNTP_SYNC_MODE_SMOOTH) { + struct timeval tv_now; + gettimeofday(&tv_now, NULL); + int64_t cpu_time = (int64_t)tv_now.tv_sec * 1000000L + (int64_t)tv_now.tv_usec; + int64_t sntp_time = (int64_t)tv->tv_sec * 1000000L + (int64_t)tv->tv_usec; + int64_t delta = sntp_time - cpu_time; + struct timeval tv_delta = { .tv_sec = delta / 1000000L, .tv_usec = delta % 1000000L }; + if (adjtime(&tv_delta, NULL) == -1) { + ESP_LOGD(TAG, "Function adjtime don't update time because the error is very big"); + settimeofday(tv, NULL); + ESP_LOGD(TAG, "Time was synchronized through settimeofday"); + sntp_set_sync_status(SNTP_SYNC_STATUS_COMPLETED); + } else { + sntp_set_sync_status(SNTP_SYNC_STATUS_IN_PROGRESS); + } + } + if (time_sync_notification_cb) { + time_sync_notification_cb(tv); + } +} + +void sntp_set_sync_mode(sntp_sync_mode_t sync_mode) +{ + sntp_sync_mode = sync_mode; +} + +sntp_sync_mode_t sntp_get_sync_mode(void) +{ + return sntp_sync_mode; +} + +// set a callback function for time synchronization notification +void sntp_set_time_sync_notification_cb(sntp_sync_time_cb_t callback) +{ + time_sync_notification_cb = callback; +} + +sntp_sync_status_t sntp_get_sync_status(void) +{ + sntp_sync_status_t ret_sync_status = SNTP_SYNC_STATUS_RESET; + sntp_sync_status_t sync_status = sntp_sync_status; + if (sync_status == SNTP_SYNC_STATUS_COMPLETED) { + sntp_set_sync_status(SNTP_SYNC_STATUS_RESET); + ret_sync_status = SNTP_SYNC_STATUS_COMPLETED; + } else if (sync_status == SNTP_SYNC_STATUS_IN_PROGRESS) { + struct timeval outdelta; + adjtime(NULL, &outdelta); + if (outdelta.tv_sec == 0 && outdelta.tv_usec == 0) { + sntp_set_sync_status(SNTP_SYNC_STATUS_RESET); + ret_sync_status = SNTP_SYNC_STATUS_COMPLETED; + } else { + ret_sync_status = SNTP_SYNC_STATUS_IN_PROGRESS; + } + } + return ret_sync_status; +} + +void sntp_set_sync_interval(uint32_t interval_ms) +{ + if (interval_ms < 15000) { + // SNTPv4 RFC 4330 enforces a minimum update time of 15 seconds + interval_ms = 15000; + } + s_sync_interval = interval_ms; +} + +uint32_t sntp_get_sync_interval(void) +{ + return s_sync_interval; +} + +bool sntp_restart(void) +{ + if (sntp_enabled()) { + sntp_stop(); + sntp_init(); + return true; + } + return false; +} + +void sntp_set_system_time(uint32_t sec, uint32_t us) +{ + struct timeval tv = { .tv_sec = sec, .tv_usec = us }; + sntp_sync_time(&tv); +} + +void sntp_get_system_time(uint32_t *sec, uint32_t *us) +{ + struct timeval tv = { .tv_sec = 0, .tv_usec = 0 }; + gettimeofday(&tv, NULL); + *(sec) = tv.tv_sec; + *(us) = tv.tv_usec; + sntp_set_sync_status(SNTP_SYNC_STATUS_RESET); +} diff --git a/pool/shard004/C/0100870_arm-wince-tdep.c b/pool/shard004/C/0100870_arm-wince-tdep.c new file mode 100644 index 0000000000000000000000000000000000000000..206ff4f72bf762860f814fce13cc87855577193b --- /dev/null +++ b/pool/shard004/C/0100870_arm-wince-tdep.c @@ -0,0 +1,167 @@ +/* Target-dependent code for Windows CE running on ARM processors, + for GDB. + + Copyright (C) 2007-2015 Free Software Foundation, Inc. + + This file is part of GDB. + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . */ + +#include "defs.h" +#include "osabi.h" +#include "gdbcore.h" +#include "target.h" +#include "frame.h" + +#include "arm-tdep.h" +#include "windows-tdep.h" + +static const gdb_byte arm_wince_le_breakpoint[] = { 0x10, 0x00, 0x00, 0xe6 }; +static const gdb_byte arm_wince_thumb_le_breakpoint[] = { 0xfe, 0xdf }; + +/* Description of the longjmp buffer. */ +#define ARM_WINCE_JB_ELEMENT_SIZE INT_REGISTER_SIZE +#define ARM_WINCE_JB_PC 10 + +static CORE_ADDR +arm_pe_skip_trampoline_code (struct frame_info *frame, CORE_ADDR pc) +{ + struct gdbarch *gdbarch = get_frame_arch (frame); + enum bfd_endian byte_order = gdbarch_byte_order (gdbarch); + ULONGEST indirect; + struct bound_minimal_symbol indsym; + const char *symname; + CORE_ADDR next_pc; + + /* The format of an ARM DLL trampoline is: + + ldr ip, [pc] + ldr pc, [ip] + .dw __imp_ + + */ + + if (pc == 0 + || read_memory_unsigned_integer (pc + 0, 4, byte_order) != 0xe59fc000 + || read_memory_unsigned_integer (pc + 4, 4, byte_order) != 0xe59cf000) + return 0; + + indirect = read_memory_unsigned_integer (pc + 8, 4, byte_order); + if (indirect == 0) + return 0; + + indsym = lookup_minimal_symbol_by_pc (indirect); + if (indsym.minsym == NULL) + return 0; + + symname = MSYMBOL_LINKAGE_NAME (indsym.minsym); + if (symname == NULL || strncmp (symname, "__imp_", 6) != 0) + return 0; + + next_pc = read_memory_unsigned_integer (indirect, 4, byte_order); + if (next_pc != 0) + return next_pc; + + /* Check with the default arm gdbarch_skip_trampoline. */ + return arm_skip_stub (frame, pc); +} + +/* GCC emits a call to __gccmain in the prologue of main. + + The function below examines the code pointed at by PC and checks to + see if it corresponds to a call to __gccmain. If so, it returns + the address of the instruction following that call. Otherwise, it + simply returns PC. */ + +static CORE_ADDR +arm_wince_skip_main_prologue (struct gdbarch *gdbarch, CORE_ADDR pc) +{ + enum bfd_endian byte_order = gdbarch_byte_order (gdbarch); + ULONGEST this_instr; + + this_instr = read_memory_unsigned_integer (pc, 4, byte_order); + + /* bl offset <__gccmain> */ + if ((this_instr & 0xfff00000) == 0xeb000000) + { +#define sign_extend(V, N) \ + (((long) (V) ^ (1L << ((N) - 1))) - (1L << ((N) - 1))) + + long offset = sign_extend (this_instr & 0x000fffff, 23) << 2; + CORE_ADDR call_dest = (pc + 8 + offset) & 0xffffffffU; + struct bound_minimal_symbol s = lookup_minimal_symbol_by_pc (call_dest); + + if (s.minsym != NULL + && MSYMBOL_LINKAGE_NAME (s.minsym) != NULL + && strcmp (MSYMBOL_LINKAGE_NAME (s.minsym), "__gccmain") == 0) + pc += 4; + } + + return pc; +} + +static void +arm_wince_init_abi (struct gdbarch_info info, struct gdbarch *gdbarch) +{ + struct gdbarch_tdep *tdep = gdbarch_tdep (gdbarch); + + windows_init_abi (info, gdbarch); + + tdep->arm_breakpoint = arm_wince_le_breakpoint; + tdep->arm_breakpoint_size = sizeof (arm_wince_le_breakpoint); + tdep->thumb_breakpoint = arm_wince_thumb_le_breakpoint; + tdep->thumb_breakpoint_size = sizeof (arm_wince_thumb_le_breakpoint); + tdep->struct_return = pcc_struct_return; + + tdep->fp_model = ARM_FLOAT_SOFT_VFP; + + tdep->jb_pc = ARM_WINCE_JB_PC; + tdep->jb_elt_size = ARM_WINCE_JB_ELEMENT_SIZE; + + /* On ARM WinCE char defaults to signed. */ + set_gdbarch_char_signed (gdbarch, 1); + + /* Shared library handling. */ + set_gdbarch_skip_trampoline_code (gdbarch, arm_pe_skip_trampoline_code); + + /* Single stepping. */ + set_gdbarch_software_single_step (gdbarch, arm_software_single_step); + + /* Skip call to __gccmain that gcc places in main. */ + set_gdbarch_skip_main_prologue (gdbarch, arm_wince_skip_main_prologue); +} + +static enum gdb_osabi +arm_wince_osabi_sniffer (bfd *abfd) +{ + const char *target_name = bfd_get_target (abfd); + + if (strcmp (target_name, "pei-arm-wince-little") == 0) + return GDB_OSABI_WINCE; + + return GDB_OSABI_UNKNOWN; +} + +/* Provide a prototype to silence -Wmissing-prototypes. */ +void _initialize_arm_wince_tdep (void); + +void +_initialize_arm_wince_tdep (void) +{ + gdbarch_register_osabi_sniffer (bfd_arch_arm, bfd_target_coff_flavour, + arm_wince_osabi_sniffer); + + gdbarch_register_osabi (bfd_arch_arm, 0, GDB_OSABI_WINCE, + arm_wince_init_abi); +} diff --git a/pool/shard004/C/0100872_simple_encoder.c b/pool/shard004/C/0100872_simple_encoder.c new file mode 100644 index 0000000000000000000000000000000000000000..ce88ed0a9aef7e77d21f3d7a65902e7adbb4d65c --- /dev/null +++ b/pool/shard004/C/0100872_simple_encoder.c @@ -0,0 +1,218 @@ +/* + * Copyright (c) 2010 The WebM project authors. All Rights Reserved. + * + * Use of this source code is governed by a BSD-style license + * that can be found in the LICENSE file in the root of the source + * tree. An additional intellectual property rights grant can be found + * in the file PATENTS. All contributing project authors may + * be found in the AUTHORS file in the root of the source tree. + */ + + +/* + * This is an example of a simple encoder loop. It takes an input file in + * YV12 format, passes it through the encoder, and writes the compressed + * frames to disk in IVF format. Other decoder examples build upon this + * one. + * + * The details of the IVF format have been elided from this example for + * simplicity of presentation, as IVF files will not generally be used by + * your application. In general, an IVF file consists of a file header, + * followed by a variable number of frames. Each frame consists of a frame + * header followed by a variable length payload. The length of the payload + * is specified in the first four bytes of the frame header. The payload is + * the raw compressed data. + */ +#include +#include +#include +#include +#define VPX_CODEC_DISABLE_COMPAT 1 +#include "vpx/vpx_encoder.h" +#include "vpx/vp8cx.h" +#define interface (vpx_codec_vp8_cx()) +#define fourcc 0x30385056 + +#define IVF_FILE_HDR_SZ (32) +#define IVF_FRAME_HDR_SZ (12) + +static void mem_put_le16(char *mem, unsigned int val) { + mem[0] = val; + mem[1] = val>>8; +} + +static void mem_put_le32(char *mem, unsigned int val) { + mem[0] = val; + mem[1] = val>>8; + mem[2] = val>>16; + mem[3] = val>>24; +} + +static void die(const char *fmt, ...) { + va_list ap; + + va_start(ap, fmt); + vprintf(fmt, ap); + if(fmt[strlen(fmt)-1] != '\n') + printf("\n"); + exit(EXIT_FAILURE); +} + +static void die_codec(vpx_codec_ctx_t *ctx, const char *s) { // + const char *detail = vpx_codec_error_detail(ctx); // + // + printf("%s: %s\n", s, vpx_codec_error(ctx)); // + if(detail) // + printf(" %s\n",detail); // + exit(EXIT_FAILURE); // +} // + +static int read_frame(FILE *f, vpx_image_t *img) { + size_t nbytes, to_read; + int res = 1; + + to_read = img->w*img->h*3/2; + nbytes = fread(img->planes[0], 1, to_read, f); + if(nbytes != to_read) { + res = 0; + if(nbytes > 0) + printf("Warning: Read partial frame. Check your width & height!\n"); + } + return res; +} + +static void write_ivf_file_header(FILE *outfile, + const vpx_codec_enc_cfg_t *cfg, + int frame_cnt) { + char header[32]; + + if(cfg->g_pass != VPX_RC_ONE_PASS && cfg->g_pass != VPX_RC_LAST_PASS) + return; + header[0] = 'D'; + header[1] = 'K'; + header[2] = 'I'; + header[3] = 'F'; + mem_put_le16(header+4, 0); /* version */ + mem_put_le16(header+6, 32); /* headersize */ + mem_put_le32(header+8, fourcc); /* headersize */ + mem_put_le16(header+12, cfg->g_w); /* width */ + mem_put_le16(header+14, cfg->g_h); /* height */ + mem_put_le32(header+16, cfg->g_timebase.den); /* rate */ + mem_put_le32(header+20, cfg->g_timebase.num); /* scale */ + mem_put_le32(header+24, frame_cnt); /* length */ + mem_put_le32(header+28, 0); /* unused */ + + (void) fwrite(header, 1, 32, outfile); +} + + +static void write_ivf_frame_header(FILE *outfile, + const vpx_codec_cx_pkt_t *pkt) +{ + char header[12]; + vpx_codec_pts_t pts; + + if(pkt->kind != VPX_CODEC_CX_FRAME_PKT) + return; + + pts = pkt->data.frame.pts; + mem_put_le32(header, pkt->data.frame.sz); + mem_put_le32(header+4, pts&0xFFFFFFFF); + mem_put_le32(header+8, pts >> 32); + + (void) fwrite(header, 1, 12, outfile); +} + +int main(int argc, char **argv) { + FILE *infile, *outfile; + vpx_codec_ctx_t codec; + vpx_codec_enc_cfg_t cfg; + int frame_cnt = 0; + vpx_image_t raw; + vpx_codec_err_t res; + long width; + long height; + int frame_avail; + int got_data; + int flags = 0; + + /* Open files */ + if(argc!=5) + die("Usage: %s \n", argv[0]); + width = strtol(argv[1], NULL, 0); + height = strtol(argv[2], NULL, 0); + if(width < 16 || width%2 || height <16 || height%2) + die("Invalid resolution: %ldx%ld", width, height); + if(!vpx_img_alloc(&raw, VPX_IMG_FMT_I420, width, height, 1)) + die("Faile to allocate image", width, height); + if(!(outfile = fopen(argv[4], "wb"))) + die("Failed to open %s for writing", argv[4]); + + printf("Using %s\n",vpx_codec_iface_name(interface)); + + /* Populate encoder configuration */ // + res = vpx_codec_enc_config_default(interface, &cfg, 0); // + if(res) { // + printf("Failed to get config: %s\n", vpx_codec_err_to_string(res)); // + return EXIT_FAILURE; // + } // + + /* Update the default configuration with our settings */ // + cfg.rc_target_bitrate = width * height * cfg.rc_target_bitrate // + / cfg.g_w / cfg.g_h; // + cfg.g_w = width; // + cfg.g_h = height; // + + write_ivf_file_header(outfile, &cfg, 0); + + + /* Open input file for this encoding pass */ + if(!(infile = fopen(argv[3], "rb"))) + die("Failed to open %s for reading", argv[3]); + + /* Initialize codec */ // + if(vpx_codec_enc_init(&codec, interface, &cfg, 0)) // + die_codec(&codec, "Failed to initialize encoder"); // + + frame_avail = 1; + got_data = 0; + while(frame_avail || got_data) { + vpx_codec_iter_t iter = NULL; + const vpx_codec_cx_pkt_t *pkt; + + frame_avail = read_frame(infile, &raw); // + if(vpx_codec_encode(&codec, frame_avail? &raw : NULL, frame_cnt, // + 1, flags, VPX_DL_REALTIME)) // + die_codec(&codec, "Failed to encode frame"); // + got_data = 0; + while( (pkt = vpx_codec_get_cx_data(&codec, &iter)) ) { + got_data = 1; + switch(pkt->kind) { + case VPX_CODEC_CX_FRAME_PKT: // + write_ivf_frame_header(outfile, pkt); // + (void) fwrite(pkt->data.frame.buf, 1, pkt->data.frame.sz, // + outfile); // + break; // + default: + break; + } + printf(pkt->kind == VPX_CODEC_CX_FRAME_PKT + && (pkt->data.frame.flags & VPX_FRAME_IS_KEY)? "K":"."); + fflush(stdout); + } + frame_cnt++; + } + printf("\n"); + fclose(infile); + + printf("Processed %d frames.\n",frame_cnt-1); + vpx_img_free(&raw); // + if(vpx_codec_destroy(&codec)) // + die_codec(&codec, "Failed to destroy codec"); // + + /* Try to rewrite the file header with the actual frame count */ + if(!fseek(outfile, 0, SEEK_SET)) + write_ivf_file_header(outfile, &cfg, frame_cnt-1); + fclose(outfile); + return EXIT_SUCCESS; +} diff --git a/pool/shard004/C/0100879_xilfatfs_alloc.c b/pool/shard004/C/0100879_xilfatfs_alloc.c new file mode 100644 index 0000000000000000000000000000000000000000..f06dece53f75833a73d9f3816acf0beb35aebcd0 --- /dev/null +++ b/pool/shard004/C/0100879_xilfatfs_alloc.c @@ -0,0 +1,83 @@ +///////////////////////////////////////////////////////////////////////// +// +// Copyright (c) 2004 Xilinx, Inc. All rights reserved. +// +// Xilinx, Inc. +// +// XILINX IS PROVIDING THIS DESIGN, CODE, OR INFORMATION "AS IS" AS A +// COURTESY TO YOU. BY PROVIDING THIS DESIGN, CODE, OR INFORMATION AS +// ONE POSSIBLE IMPLEMENTATION OF THIS FEATURE, APPLICATION OR +// STANDARD, XILINX IS MAKING NO REPRESENTATION THAT THIS IMPLEMENTATION +// IS FREE FROM ANY CLAIMS OF INFRINGEMENT, AND YOU ARE RESPONSIBLE +// FOR OBTAINING ANY RIGHTS YOU MAY REQUIRE FOR YOUR IMPLEMENTATION. +// XILINX EXPRESSLY DISCLAIMS ANY WARRANTY WHATSOEVER WITH RESPECT TO +// THE ADEQUACY OF THE IMPLEMENTATION, INCLUDING BUT NOT LIMITED TO +// ANY WARRANTIES OR REPRESENTATIONS THAT THIS IMPLEMENTATION IS FREE +// FROM CLAIMS OF INFRINGEMENT, IMPLIED WARRANTIES OF MERCHANTABILITY +// AND FITNESS FOR A PARTICULAR PURPOSE. +// +//////////////////////////////////////////////////////////////////////////////// + +#include +#include "alloc.h" +#include "fat.h" + +/* Create and release WDs */ +static WorkingDirectory wd_buf[MAXWD]; +static int wd_init_flag = 1; + +WorkingDirectory * +malloc_wd(const char *name) +{ + int i; + + /* Do initialization because MBlaze seems not to initialize statics per K&R */ + if(wd_init_flag) { + wd_init_flag = 0; + for(i=0; iname[0] = 0; +} + +static FileStatus fs_buf[MAXFILES]; +static int fs_init_flag = 1; + +FileStatus * +malloc_fs(void) +{ + int i; + + if(fs_init_flag) { + fs_init_flag = 0; + for(i=0; ireserved = 0; +} diff --git a/pool/shard004/C/0100887_health_check.c b/pool/shard004/C/0100887_health_check.c new file mode 100644 index 0000000000000000000000000000000000000000..5f0d85fec0814283861a34a8804fc7e895ec1318 --- /dev/null +++ b/pool/shard004/C/0100887_health_check.c @@ -0,0 +1,109 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +static void +usage (void) { + fprintf(stderr, + "Usage: health_check" + " -d debug" + " -I interface" + "\n"); + exit(2); +} + +int +main (int argc, char **argv) +{ + int sd, ch; + uint8_t *opt, *pkt; + struct ifreq ifr; + char *interface = NULL; + bool debug = false; + + while ((ch = getopt(argc, argv, "h?" "I:" "d")) != EOF) { + switch(ch) { + case 'I': + interface = optarg; + break; + case 'd': + debug = true; + break; + default: + usage(); + break; + } + } + + argc -= optind; + argv += optind; + + if (!interface) + usage(); + + /* Request a socket descriptor sd. */ + if ((sd = socket (AF_INET6, SOCK_RAW, IPPROTO_IPIP)) < 0) { + perror ("Failed to get socket descriptor "); + exit (EXIT_FAILURE); + } + + memset(&ifr, 0, sizeof(ifr)); + snprintf(ifr.ifr_name, sizeof(ifr.ifr_name), "%s", interface); + + /* Bind socket to interface of this node. */ + if (setsockopt (sd, SOL_SOCKET, SO_BINDTODEVICE, (void *) &ifr, sizeof (ifr)) < 0) { + perror ("SO_BINDTODEVICE failed"); + exit (EXIT_FAILURE); + } + if (debug) printf("Binding to interface %s\n", interface); + + while (1) { + struct sockaddr_in6 src_addr; + socklen_t addrlen = sizeof(src_addr); + char source[INET6_ADDRSTRLEN+1]; + int len; + uint8_t inpack[IP_MAXPACKET]; + + if ((len = recvfrom(sd, inpack, sizeof(inpack), 0, (struct sockaddr *)&src_addr, &addrlen)) < 0) { + perror("recvfrom failed "); + } + if (inet_ntop(AF_INET6, &src_addr.sin6_addr, source, INET6_ADDRSTRLEN) == NULL) { + perror("inet_ntop() failed."); + exit(EXIT_FAILURE); + } + + /* Reply */ + struct iphdr *ip = (struct iphdr *)inpack; + uint32_t saddr; + struct icmphdr *icmp; + + saddr = ip->saddr; + ip->saddr = ip->daddr; + ip->daddr = saddr; + + switch (ip->protocol) { + case 1: + if (debug) printf ("ICMP Echo request from %s\n", source); + icmp = (struct icmphdr *)&ip[1]; + icmp->type = ICMP_ECHOREPLY; + break; + default: + fprintf(stderr, "Unsupported protocol %d", ip->protocol); + } + if (len = sendto(sd, inpack, len, 0, (struct sockaddr *)&src_addr, addrlen) < 0) { + perror("sendto failed "); + } + } + + close (sd); + + return (EXIT_SUCCESS); +} diff --git a/pool/shard004/C/0100888_plugin-conversation.c b/pool/shard004/C/0100888_plugin-conversation.c new file mode 100644 index 0000000000000000000000000000000000000000..b77f72187f316b15d0c46503b7331ef588ff5723 --- /dev/null +++ b/pool/shard004/C/0100888_plugin-conversation.c @@ -0,0 +1,56 @@ +/* + * Off-the-Record Messaging plugin for pidgin + * Copyright (C) 2004-2018 Ian Goldberg, Rob Smits, + * Chris Alexander, Willy Lew, + * Nikita Borisov + * + * The pidgin-otrng contributors + * + * 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-1301 USA + */ + +#include +#include + +#include + +#include "plugin-conversation.h" + +otrng_plugin_conversation *otrng_plugin_conversation_new(const otrng_s *from) { + otrng_plugin_conversation *ret = malloc(sizeof(otrng_plugin_conversation)); + if (!ret) { + return ret; + } + + ret->account = g_strdup(from->client->client_id.account); + ret->protocol = g_strdup(from->client->client_id.protocol); + ret->peer = g_strdup(from->peer); + ret->their_instance_tag = 0; + ret->our_instance_tag = 0; + ret->conv = from; + + return ret; +} + +void otrng_plugin_conversation_free(otrng_plugin_conversation *conv) { + if (!conv) { + return; + } + + g_free(conv->account); + g_free(conv->protocol); + g_free(conv->peer); + + free(conv); +} diff --git a/pool/shard004/C/0100896_gconv.c b/pool/shard004/C/0100896_gconv.c new file mode 100644 index 0000000000000000000000000000000000000000..b413e26c5ae682ef9082169dfb1ac302132baee0 --- /dev/null +++ b/pool/shard004/C/0100896_gconv.c @@ -0,0 +1,73 @@ +/* Convert characters in input buffer using conversion descriptor to + output buffer. + Copyright (C) 1997, 1998, 1999, 2000, 2001 Free Software Foundation, Inc. + This file is part of the GNU C Library. + Contributed by Ulrich Drepper , 1997. + + 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 +#include + +int +internal_function +__gconv (__gconv_t cd, const unsigned char **inbuf, + const unsigned char *inbufend, unsigned char **outbuf, + unsigned char *outbufend, size_t *irreversible) +{ + size_t last_step; + int result; + + if (cd == (__gconv_t) -1L) + return __GCONV_ILLEGAL_DESCRIPTOR; + + last_step = cd->__nsteps - 1; + + assert (irreversible != NULL); + *irreversible = 0; + + cd->__data[last_step].__outbuf = outbuf != NULL ? *outbuf : NULL; + cd->__data[last_step].__outbufend = outbufend; + + if (inbuf == NULL || *inbuf == NULL) + /* We just flush. */ + result = cd->__steps->__fct (cd->__steps, cd->__data, NULL, NULL, NULL, + irreversible, + cd->__data[last_step].__outbuf == NULL ? 2 : 1, 0); + else + { + const unsigned char *last_start; + + assert (outbuf != NULL && *outbuf != NULL); + + do + { + last_start = *inbuf; + result = cd->__steps->__fct (cd->__steps, cd->__data, inbuf, inbufend, + NULL, irreversible, 0, 0); + } + while (result == __GCONV_EMPTY_INPUT && last_start != *inbuf + && *inbuf + cd->__steps->__min_needed_from <= inbufend); + } + + if (outbuf != NULL && *outbuf != NULL) + *outbuf = cd->__data[last_step].__outbuf; + + return result; +} diff --git a/pool/shard004/C/0100898_global_var_main.c b/pool/shard004/C/0100898_global_var_main.c new file mode 100644 index 0000000000000000000000000000000000000000..f64f456565124472ec3aa348c44581e5a5026ed7 --- /dev/null +++ b/pool/shard004/C/0100898_global_var_main.c @@ -0,0 +1,30 @@ +void setspeed(int v); +int getspeed(); +void setdistance(int v); +int getdistance(); + +int value = 42; + +int compare_value (int v) +{ + asm(""); + return v - value; +} + +int calculate_value () +{ + asm(""); + return getdistance () / getspeed (); +} + +int main (int argc, char **argv) +{ + int value; + + setspeed (6); + setdistance (60); + + value = calculate_value (); + + return compare_value (value) == 0 ? -1 : 0; +} diff --git a/pool/shard004/C/0100900_anim.c b/pool/shard004/C/0100900_anim.c new file mode 100644 index 0000000000000000000000000000000000000000..dfdaa87917a9d0ef2515ac4b9b2cf7a98b037dfb --- /dev/null +++ b/pool/shard004/C/0100900_anim.c @@ -0,0 +1,204 @@ +#include +#include "anim.h" +#include "KwestKingdom.h" + + +extern int timer; + + +void init_anim(ANIM *anim, FLAG loop, int speed) +{ + int i; + + for (i = 0; i < MAX_FRAMES; i++) { + anim->frames[i] = NULL; + } + + anim->len = 0; + anim->pos = 0; + anim->loop = loop; + anim->done = OFF; + anim->speed = speed; + anim->fudge = 0; + anim->offset_x = 0; + anim->offset_y = 0; + anim->h_flip = OFF; + anim->v_flip = OFF; + anim->rotate = OFF; +} + + +void copy_anim(ANIM *anim, ANIM *orig) +{ + int i; + + init_anim(anim, orig->loop, orig->speed); + + for (i = 0; i < orig->len; i++) { + add_frame(anim, orig->frames[i]); + } + + anim->offset_x = orig->offset_x; + anim->offset_y = orig->offset_y; + anim->h_flip = orig->h_flip; + anim->v_flip = orig->v_flip; + anim->rotate = orig->rotate; + + reset_anim(anim); +} + + +void reset_anim(ANIM *anim) +{ + anim->pos = 0; + anim->done = OFF; + anim->fudge = 0; +} + + +IMAGE *get_frame(ANIM *anim) +{ + if (anim->len == 0) { + return NULL; + } + return anim->frames[anim->pos]; +} + + +void add_frame(ANIM *anim, IMAGE *frame) +{ + if (frame) { + anim->frames[anim->len] = frame; + anim->len++; + } +} + + +static IMAGE *canvas_standard_size = NULL; +static IMAGE *canvas_triple_size = NULL; + + +/** + * This silly little function provides a fix for transparency + * when using the rotate sprite and flip sprite functions. + */ +IMAGE *get_canvas(int width, int height) +{ + int tile_size = 20; + + if (width == tile_size && height == tile_size) { + if (canvas_standard_size == NULL) { + canvas_standard_size = create_bitmap(tile_size, tile_size); + } + return canvas_standard_size; + } + + if (width == tile_size * 3 && height == tile_size * 3) { + if (canvas_triple_size == NULL) { + canvas_triple_size = create_bitmap(tile_size * 3, tile_size * 3); + } + return canvas_triple_size; + } + + fprintf(stderr, "Failed to find a canvas size %dx%d. \n", width, height); + + return NULL; +} + + +#include + + +void draw_anim(ANIM *anim, IMAGE *canvas, int x, int y) +{ + IMAGE *tmp_canvas; + + if (get_frame(anim) == NULL) { + return; + } + + // Write to a temporary canvas to get transparency + // to work correctly. + // Only necessary when rotating and flipping sprites. + if (anim->rotate || anim->h_flip || anim->v_flip) { + tmp_canvas = get_canvas(get_frame(anim)->w, get_frame(anim)->h); + if (tmp_canvas) { + blit(get_frame(anim), tmp_canvas, 0, 0, 0, 0, tmp_canvas->w, tmp_canvas->h); + } + } else { + tmp_canvas = get_frame(anim); + } + + if (tmp_canvas == NULL) { + return; + } + + if (anim->rotate && anim->h_flip && anim->v_flip) { + rotate_sprite(canvas, tmp_canvas, x + anim->offset_x, y + anim->offset_y, itofix(192)); + } else if (anim->rotate && anim->h_flip) { + rotate_sprite_v_flip(canvas, tmp_canvas, x + anim->offset_x, y + anim->offset_y, itofix(192)); + } else if (anim->rotate && anim->v_flip) { + rotate_sprite_v_flip(canvas, tmp_canvas, x + anim->offset_x, y + anim->offset_y, itofix(64)); + } else if (anim->rotate) { + rotate_sprite(canvas, tmp_canvas, x + anim->offset_x, y + anim->offset_y, itofix(64)); + } else if (anim->h_flip && anim->v_flip) { + rotate_sprite(canvas, tmp_canvas, x + anim->offset_x, y + anim->offset_y, itofix(128)); + } else if (anim->h_flip) { + draw_sprite_h_flip(canvas, tmp_canvas, x + anim->offset_x, y + anim->offset_y); + } else if (anim->v_flip) { + draw_sprite_v_flip(canvas, tmp_canvas, x + anim->offset_x, y + anim->offset_y); + } else { + draw_sprite(canvas, tmp_canvas, x + anim->offset_x, y + anim->offset_y); + } +} + + +// Animate the animation. +void animate(ANIM *anim) { + + if (anim->len > 1 && anim->speed != 0) { + + anim->fudge += anim->speed; + + while (anim->fudge >= GAME_TICKER) { + + anim->pos++; + + if (anim->pos == anim->len) { + if (anim->loop) { + anim->pos = 0; + } else { + anim->pos--; + anim->done = ON; + } + } + + anim->fudge -= GAME_TICKER; + + } + + } else { + + anim->done = ON; + + } +} + + +int get_anim_w(ANIM *anim) +{ + if (get_frame(anim)) { + return get_frame(anim)->w; + } + return 0; +} + + +int get_anim_h(ANIM *anim) +{ + if (get_frame(anim)) { + return get_frame(anim)->h; + } + return 0; +} + diff --git a/pool/shard004/C/0100908_rtc.c b/pool/shard004/C/0100908_rtc.c new file mode 100644 index 0000000000000000000000000000000000000000..a821c1bc858f9d1e2678dadc2a7f842d676730f7 --- /dev/null +++ b/pool/shard004/C/0100908_rtc.c @@ -0,0 +1,133 @@ +/* + * Copyright (c) 2019, MediaTek Inc. All rights reserved. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +#include +#include +#include + +static void RTC_Config_Interface(uint32_t addr, uint16_t data, + uint16_t MASK, uint16_t SHIFT) +{ + uint16_t pmic_reg = 0; + + pmic_reg = RTC_Read(addr); + + pmic_reg &= ~(MASK << SHIFT); + pmic_reg |= (data << SHIFT); + + RTC_Write(addr, pmic_reg); +} + +static void rtc_disable_2sec_reboot(void) +{ + uint16_t reboot; + + reboot = (RTC_Read(RTC_AL_SEC) & ~RTC_BBPU_2SEC_EN) & + ~RTC_BBPU_AUTO_PDN_SEL; + RTC_Write(RTC_AL_SEC, reboot); + RTC_Write_Trigger(); +} + +static void rtc_xosc_write(uint16_t val, bool reload) +{ + uint16_t bbpu; + + RTC_Write(RTC_OSC32CON, RTC_OSC32CON_UNLOCK1); + rtc_busy_wait(); + RTC_Write(RTC_OSC32CON, RTC_OSC32CON_UNLOCK2); + rtc_busy_wait(); + + RTC_Write(RTC_OSC32CON, val); + rtc_busy_wait(); + + if (reload) { + bbpu = RTC_Read(RTC_BBPU) | RTC_BBPU_KEY | RTC_BBPU_RELOAD; + RTC_Write(RTC_BBPU, bbpu); + RTC_Write_Trigger(); + } +} + +static void rtc_enable_k_eosc(void) +{ + uint16_t osc32; + uint16_t rtc_eosc_cali_td = 8; /* eosc cali period time */ + + /* Truning on eosc cali mode clock */ + RTC_Config_Interface(PMIC_RG_TOP_CON, 1, + PMIC_RG_SRCLKEN_IN0_HW_MODE_MASK, + PMIC_RG_SRCLKEN_IN0_HW_MODE_SHIFT); + RTC_Config_Interface(PMIC_RG_TOP_CON, 1, + PMIC_RG_SRCLKEN_IN1_HW_MODE_MASK, + PMIC_RG_SRCLKEN_IN1_HW_MODE_SHIFT); + RTC_Config_Interface(PMIC_RG_SCK_TOP_CKPDN_CON0, 0, + PMIC_RG_RTC_EOSC32_CK_PDN_MASK, + PMIC_RG_RTC_EOSC32_CK_PDN_SHIFT); + + switch (rtc_eosc_cali_td) { + case 1: + RTC_Config_Interface(PMIC_RG_EOSC_CALI_CON0, 0x3, + PMIC_RG_EOSC_CALI_TD_MASK, PMIC_RG_EOSC_CALI_TD_SHIFT); + break; + case 2: + RTC_Config_Interface(PMIC_RG_EOSC_CALI_CON0, 0x4, + PMIC_RG_EOSC_CALI_TD_MASK, PMIC_RG_EOSC_CALI_TD_SHIFT); + break; + case 4: + RTC_Config_Interface(PMIC_RG_EOSC_CALI_CON0, 0x5, + PMIC_RG_EOSC_CALI_TD_MASK, PMIC_RG_EOSC_CALI_TD_SHIFT); + break; + case 16: + RTC_Config_Interface(PMIC_RG_EOSC_CALI_CON0, 0x7, + PMIC_RG_EOSC_CALI_TD_MASK, PMIC_RG_EOSC_CALI_TD_SHIFT); + break; + default: + RTC_Config_Interface(PMIC_RG_EOSC_CALI_CON0, 0x6, + PMIC_RG_EOSC_CALI_TD_MASK, PMIC_RG_EOSC_CALI_TD_SHIFT); + break; + } + /* Switch the DCXO from 32k-less mode to RTC mode, + * otherwise, EOSC cali will fail + */ + /* RTC mode will have only OFF mode and FPM */ + RTC_Config_Interface(PMIC_RG_DCXO_CW02, 0, PMIC_RG_XO_EN32K_MAN_MASK, + PMIC_RG_XO_EN32K_MAN_SHIFT); + RTC_Write(RTC_BBPU, + RTC_Read(RTC_BBPU) | RTC_BBPU_KEY | RTC_BBPU_RELOAD); + RTC_Write_Trigger(); + /* Enable K EOSC mode for normal power off and then plug out battery */ + RTC_Write(RTC_AL_YEA, ((RTC_Read(RTC_AL_YEA) | RTC_K_EOSC_RSV_0) + & (~RTC_K_EOSC_RSV_1)) | RTC_K_EOSC_RSV_2); + RTC_Write_Trigger(); + + osc32 = RTC_Read(RTC_OSC32CON); + rtc_xosc_write(osc32 | RTC_EMBCK_SRC_SEL, true); + INFO("[RTC] RTC_enable_k_eosc\n"); +} + +void rtc_power_off_sequence(void) +{ + uint16_t bbpu; + + rtc_disable_2sec_reboot(); + rtc_enable_k_eosc(); + + /* clear alarm */ + bbpu = RTC_BBPU_KEY | RTC_BBPU_CLR | RTC_BBPU_PWREN; + if (Writeif_unlock()) { + RTC_Write(RTC_BBPU, bbpu); + + RTC_Write(RTC_AL_MASK, RTC_AL_MASK_DOW); + RTC_Write_Trigger(); + mdelay(1); + + bbpu = RTC_Read(RTC_BBPU) | RTC_BBPU_KEY | RTC_BBPU_RELOAD; + RTC_Write(RTC_BBPU, bbpu); + RTC_Write_Trigger(); + INFO("[RTC] BBPU=0x%x, IRQ_EN=0x%x, AL_MSK=0x%x, AL_SEC=0x%x\n", + RTC_Read(RTC_BBPU), RTC_Read(RTC_IRQ_EN), + RTC_Read(RTC_AL_MASK), RTC_Read(RTC_AL_SEC)); + } +} diff --git a/pool/shard004/C/0100913_i_ta.c b/pool/shard004/C/0100913_i_ta.c new file mode 100644 index 0000000000000000000000000000000000000000..5adf4d03108b864a8bfb7efab3366805c555bfd6 --- /dev/null +++ b/pool/shard004/C/0100913_i_ta.c @@ -0,0 +1,141 @@ +/* + * ===================================================================================== + * + * Filename: i_ta.c + * + * Description: Implementation of the TA instruction + * + * Version: 1.0 + * Created: 16/04/08 18:09:22 + * Revision: none + * Compiler: gcc + * + * Author: Aitor Viana Sanchez (avs), aitor.viana.sanchez@esa.int + * Company: European Space Agency (ESA-ESTEC) + * + * ===================================================================================== + */ + +/* Format (2) + +31-30 29 28-25 24-19 18-14 13 12-5 4-0 ++----+----+--------+------------------------------------------+ +| op | na | cond | 111010 | rs1 |i=0| reserved | rs2 | ++----+----+--------+------------------------------------------+ + +31-30 29 28-25 24-19 18-14 13 12-7 6-0 ++----+----+--------+------------------------------------------+ +| op | na | cond | 111010 | rs1 |i=1| reserved | imm7 | ++----+----+--------+------------------------------------------+ + +op = 00 +cond = 1000 + ++----+----+--------+------------------------------------------+ +| op | na | 1000 | 111010 | rs1 |i=1| reserved | imm7 | ++----+----+--------+------------------------------------------+ + +*/ +#include "../common/bits.h" +#include "../common/sparc.h" +#include "../common/traps.h" +#include "../common/iu.h" +#include "../common/debug.h" +#include "i_utils.h" + +#include + +static int execute(void *); +static int disassemble(uint32 instr, void *state); +static int cond, imm7, fixed, op, rs2, rs1; + +#define TA_CYCLES 1 +#define TA_CODE_MASK 0x91d00000 +#define PRIVILEDGE 0 + +#define OP_OFF_first 30 +#define OP_OFF_last 31 +#define OP 0x2 + +#define NA_OFF 29 + +#define COND_OFF_last 28 +#define COND_OFF_first 25 +#define COND 0x8 + +#define FIXED_OFF_last 24 +#define FIXED_OFF_first 19 +#define FIXED 0x3a + +#define RS1_OFF_last 18 +#define RS1_OFF_first 14 + +#define I_OFF 13 + +#define RS2_OFF_last 4 +#define RS2_OFF_first 0 + +#define IMM7_OFF_last 6 +#define IMM7_OFF_first 0 + +sparc_instruction_t i_ta = { + execute, + disassemble, + TA_CODE_MASK, + PRIVILEDGE, + OP, +}; + +static int execute(void *state) +{ + int tt; + + /* The tt field is writen with 128 + the leas significant seven bits of + * r[rs1] + r[rs2] if 'i' field is zero, or 128 + least significant bits of + * r[rs1] + sign_ext(imm7) if the 'i' field is one */ + if( imm7 < 0 ) + tt = 128 + bits(REG(rs1), 6, 0) + bits(REG(rs2), 6, 0); + else if(rs2 < 0) + tt = 128 + bits(REG(rs1), 6, 0) + imm7; + + traps->signal(tt); + + DBG("ta %d\n", tt - 128); + + // Everyting takes some time + return(TA_CYCLES); + +} + +static int disassemble(uint32 instr, void *state) +{ + + int op; + + op = bits(instr, OP_OFF_last, OP_OFF_first); + cond = bits(instr, COND_OFF_last, COND_OFF_first); + fixed = bits(instr, FIXED_OFF_last, FIXED_OFF_first); + + if( (instr & TA_CODE_MASK) && (op == OP) && (fixed == FIXED) ) + { + rs1 = bits(instr, RS1_OFF_last, RS1_OFF_first); + + int i = bit(instr, I_OFF); + + if( i ) + { + imm7 = bits(instr, IMM7_OFF_last, IMM7_OFF_first); + rs2 = -1; + } + else + { + rs2 = bits(instr, RS2_OFF_last, RS2_OFF_first); + imm7 = -1; + } + + return 1; + } + + return 0; +} + diff --git a/pool/shard004/C/0100920_serial.c b/pool/shard004/C/0100920_serial.c new file mode 100644 index 0000000000000000000000000000000000000000..9f07fc064da83cf74689ad08fc7218529d3b57bf --- /dev/null +++ b/pool/shard004/C/0100920_serial.c @@ -0,0 +1,30 @@ +#include +#include +#include +#include + +static int uart_putchar(char c, FILE *stream); + +static FILE mystdout = FDEV_SETUP_STREAM(uart_putchar, NULL, _FDEV_SETUP_WRITE); + +static int uart_putchar(char c, FILE *stream) +{ + loop_until_bit_is_set(USARTC0.STATUS,USART_DREIF_bp); + USARTC0.DATA = c; + return 0; +} + +void startserial(void) +{ + PORTC.DIRSET = PIN3_bm; + PORTC.DIRCLR = PIN2_bm; + + USARTC0.CTRLC = (uint8_t) USART_CHSIZE_8BIT_gc | USART_PMODE_DISABLED_gc | false; + USARTC0.BAUDCTRLA = 12; + + USARTC0.CTRLB |= USART_RXEN_bm; + USARTC0.CTRLB |= USART_TXEN_bm; + + stdout = &mystdout; +} + diff --git a/pool/shard004/C/0100921_vesagtf.c b/pool/shard004/C/0100921_vesagtf.c new file mode 100644 index 0000000000000000000000000000000000000000..d60de2c0e589aee3b706e22b3de021c08d207dcb --- /dev/null +++ b/pool/shard004/C/0100921_vesagtf.c @@ -0,0 +1,699 @@ +/* $NetBSD: vesagtf.c,v 1.1 2006/05/11 01:49:53 gdamore Exp $ */ + +/*- + * Copyright (c) 2006 Itronix Inc. + * All rights reserved. + * + * Written by Garrett D'Amore for Itronix 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 Itronix Inc. may not be used to endorse + * or promote products derived from this software without specific + * prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY ITRONIX 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 ITRONIX 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. + */ + +/* + * This was derived from a userland GTF program supplied by NVIDIA. + * NVIDIA's original boilerplate follows. + * + * Note that I have heavily modified the program for use in the EDID + * kernel code for NetBSD, including removing the use of floating + * point operations and making significant adjustments to minimize + * error propogation while operating with integer only math. + * + * This has required the use of 64-bit integers in a few places, but + * the upshot is that for a calculation of 1920x1200x85 (as an + * example), the error deviates by only ~.004% relative to the + * floating point version. This error is *well* within VESA + * tolerances. + */ + +/* + * Copyright (c) 2001, Andy Ritger aritger@nvidia.com + * 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 NVIDIA 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 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. + * + * + * + * This program is based on the Generalized Timing Formula(GTF TM) + * Standard Version: 1.0, Revision: 1.0 + * + * The GTF Document contains the following Copyright information: + * + * Copyright (c) 1994, 1995, 1996 - Video Electronics Standards + * Association. Duplication of this document within VESA member + * companies for review purposes is permitted. All other rights + * reserved. + * + * While every precaution has been taken in the preparation + * of this standard, the Video Electronics Standards Association and + * its contributors assume no responsibility for errors or omissions, + * and make no warranties, expressed or implied, of functionality + * of suitability for any purpose. The sample code contained within + * this standard may be used without restriction. + * + * + * + * The GTF EXCEL(TM) SPREADSHEET, a sample (and the definitive) + * implementation of the GTF Timing Standard, is available at: + * + * ftp://ftp.vesa.org/pub/GTF/GTF_V1R1.xls + * + * + * + * This program takes a desired resolution and vertical refresh rate, + * and computes mode timings according to the GTF Timing Standard. + * These mode timings can then be formatted as an XFree86 modeline + * or a mode description for use by fbset(8). + * + * + * + * NOTES: + * + * The GTF allows for computation of "margins" (the visible border + * surrounding the addressable video); on most non-overscan type + * systems, the margin period is zero. I've implemented the margin + * computations but not enabled it because 1) I don't really have + * any experience with this, and 2) neither XFree86 modelines nor + * fbset fb.modes provide an obvious way for margin timings to be + * included in their mode descriptions (needs more investigation). + * + * The GTF provides for computation of interlaced mode timings; + * I've implemented the computations but not enabled them, yet. + * I should probably enable and test this at some point. + * + * + * + * TODO: + * + * o Add support for interlaced modes. + * + * o Implement the other portions of the GTF: compute mode timings + * given either the desired pixel clock or the desired horizontal + * frequency. + * + * o It would be nice if this were more general purpose to do things + * outside the scope of the GTF: like generate double scan mode + * timings, for example. + * + * o Printing digits to the right of the decimal point when the + * digits are 0 annoys me. + * + * o Error checking. + * + */ + + +#ifdef _KERNEL +#include +#include +#include +#include +#include +#else +#include +#include +#include +#include "videomode.h" +#include "vesagtf.h" + +void print_xf86_mode(struct videomode *m); +#endif + +#define CELL_GRAN 8 /* assumed character cell granularity */ + +/* C' and M' are part of the Blanking Duty Cycle computation */ +/* + * #define C_PRIME (((C - J) * K/256.0) + J) + * #define M_PRIME (K/256.0 * M) + */ + +/* + * C' and M' multiplied by 256 to give integer math. Make sure to + * scale results using these back down, appropriately. + */ +#define C_PRIME256(p) (((p->C - p->J) * p->K) + (p->J * 256)) +#define M_PRIME256(p) (p->K * p->M) + +#define DIVIDE(x,y) (((x) + ((y) / 2)) / (y)) + +/* + * print_value() - print the result of the named computation; this is + * useful when comparing against the GTF EXCEL spreadsheet. + */ + +#ifdef GTFDEBUG + +void +print_value(int n, const char *name, unsigned val) +{ + printf("%2d: %-27s: %u\n", n, name, val); +} +#else +#define print_value(n, name, val) +#endif + + +/* + * vert_refresh() - as defined by the GTF Timing Standard, compute the + * Stage 1 Parameters using the vertical refresh frequency. In other + * words: input a desired resolution and desired refresh rate, and + * output the GTF mode timings. + * + * XXX All the code is in place to compute interlaced modes, but I don't + * feel like testing it right now. + * + * XXX margin computations are implemented but not tested (nor used by + * XFree86 of fbset mode descriptions, from what I can tell). + */ + +void +vesagtf_mode_params(unsigned h_pixels, unsigned v_lines, unsigned freq, + struct vesagtf_params *params, int flags, struct videomode *vmp) +{ + unsigned v_field_rqd; + unsigned top_margin; + unsigned bottom_margin; + unsigned interlace; + uint64_t h_period_est; + unsigned vsync_plus_bp; + unsigned v_back_porch; + unsigned total_v_lines; + uint64_t v_field_est; + uint64_t h_period; + unsigned v_field_rate; + unsigned v_frame_rate; + unsigned left_margin; + unsigned right_margin; + unsigned total_active_pixels; + uint64_t ideal_duty_cycle; + unsigned h_blank; + unsigned total_pixels; + unsigned pixel_freq; + + unsigned h_sync; + unsigned h_front_porch; + unsigned v_odd_front_porch_lines; + +#ifdef GTFDEBUG + unsigned h_freq; +#endif + + /* 1. In order to give correct results, the number of horizontal + * pixels requested is first processed to ensure that it is divisible + * by the character size, by rounding it to the nearest character + * cell boundary: + * + * [H PIXELS RND] = ((ROUND([H PIXELS]/[CELL GRAN RND],0))*[CELLGRAN RND]) + */ + + h_pixels = DIVIDE(h_pixels, CELL_GRAN) * CELL_GRAN; + + print_value(1, "[H PIXELS RND]", h_pixels); + + + /* 2. If interlace is requested, the number of vertical lines assumed + * by the calculation must be halved, as the computation calculates + * the number of vertical lines per field. In either case, the + * number of lines is rounded to the nearest integer. + * + * [V LINES RND] = IF([INT RQD?]="y", ROUND([V LINES]/2,0), + * ROUND([V LINES],0)) + */ + + v_lines = (flags & VESAGTF_FLAG_ILACE) ? DIVIDE(v_lines, 2) : v_lines; + + print_value(2, "[V LINES RND]", v_lines); + + + /* 3. Find the frame rate required: + * + * [V FIELD RATE RQD] = IF([INT RQD?]="y", [I/P FREQ RQD]*2, + * [I/P FREQ RQD]) + */ + + v_field_rqd = (flags & VESAGTF_FLAG_ILACE) ? (freq * 2) : (freq); + + print_value(3, "[V FIELD RATE RQD]", v_field_rqd); + + + /* 4. Find number of lines in Top margin: + * 5. Find number of lines in Bottom margin: + * + * [TOP MARGIN (LINES)] = IF([MARGINS RQD?]="Y", + * ROUND(([MARGIN%]/100*[V LINES RND]),0), + * 0) + * + * Ditto for bottom margin. Note that instead of %, we use PPT, which + * is parts per thousand. This helps us with integer math. + */ + + top_margin = bottom_margin = (flags & VESAGTF_FLAG_MARGINS) ? + DIVIDE(v_lines * params->margin_ppt, 1000) : 0; + + print_value(4, "[TOP MARGIN (LINES)]", top_margin); + print_value(5, "[BOT MARGIN (LINES)]", bottom_margin); + + + /* 6. If interlace is required, then set variable [INTERLACE]=0.5: + * + * [INTERLACE]=(IF([INT RQD?]="y",0.5,0)) + * + * To make this integer friendly, we use some special hacks in step + * 7 below. Please read those comments to understand why I am using + * a whole number of 1.0 instead of 0.5 here. + */ + interlace = (flags & VESAGTF_FLAG_ILACE) ? 1 : 0; + + print_value(6, "[2*INTERLACE]", interlace); + + + /* 7. Estimate the Horizontal period + * + * [H PERIOD EST] = ((1/[V FIELD RATE RQD]) - [MIN VSYNC+BP]/1000000) / + * ([V LINES RND] + (2*[TOP MARGIN (LINES)]) + + * [MIN PORCH RND]+[INTERLACE]) * 1000000 + * + * To make it integer friendly, we pre-multiply the 1000000 to get to + * usec. This gives us: + * + * [H PERIOD EST] = ((1000000/[V FIELD RATE RQD]) - [MIN VSYNC+BP]) / + * ([V LINES RND] + (2 * [TOP MARGIN (LINES)]) + + * [MIN PORCH RND]+[INTERLACE]) + * + * The other problem is that the interlace value is wrong. To get + * the interlace to a whole number, we multiply both the numerator and + * divisor by 2, so we can use a value of either 1 or 0 for the interlace + * factor. + * + * This gives us: + * + * [H PERIOD EST] = ((2*((1000000/[V FIELD RATE RQD]) - [MIN VSYNC+BP])) / + * (2*([V LINES RND] + (2*[TOP MARGIN (LINES)]) + + * [MIN PORCH RND]) + [2*INTERLACE])) + * + * Finally we multiply by another 1000, to get value in picosec. + * Why picosec? To minimize rounding errors. Gotta love integer + * math and error propogation. + */ + + h_period_est = DIVIDE(((DIVIDE(2000000000000ULL, v_field_rqd)) - + (2000000 * params->min_vsbp)), + ((2 * (v_lines + (2 * top_margin) + params->min_porch)) + interlace)); + + print_value(7, "[H PERIOD EST (ps)]", h_period_est); + + + /* 8. Find the number of lines in V sync + back porch: + * + * [V SYNC+BP] = ROUND(([MIN VSYNC+BP]/[H PERIOD EST]),0) + * + * But recall that h_period_est is in psec. So multiply by 1000000. + */ + + vsync_plus_bp = DIVIDE(params->min_vsbp * 1000000, h_period_est); + + print_value(8, "[V SYNC+BP]", vsync_plus_bp); + + + /* 9. Find the number of lines in V back porch alone: + * + * [V BACK PORCH] = [V SYNC+BP] - [V SYNC RND] + * + * XXX is "[V SYNC RND]" a typo? should be [V SYNC RQD]? + */ + + v_back_porch = vsync_plus_bp - params->vsync_rqd; + + print_value(9, "[V BACK PORCH]", v_back_porch); + + + /* 10. Find the total number of lines in Vertical field period: + * + * [TOTAL V LINES] = [V LINES RND] + [TOP MARGIN (LINES)] + + * [BOT MARGIN (LINES)] + [V SYNC+BP] + [INTERLACE] + + * [MIN PORCH RND] + */ + + total_v_lines = v_lines + top_margin + bottom_margin + vsync_plus_bp + + interlace + params->min_porch; + + print_value(10, "[TOTAL V LINES]", total_v_lines); + + + /* 11. Estimate the Vertical field frequency: + * + * [V FIELD RATE EST] = 1 / [H PERIOD EST] / [TOTAL V LINES] * 1000000 + * + * Again, we want to pre multiply by 10^9 to convert for nsec, thereby + * making it usable in integer math. + * + * So we get: + * + * [V FIELD RATE EST] = 1000000000 / [H PERIOD EST] / [TOTAL V LINES] + * + * This is all scaled to get the result in uHz. Again, we're trying to + * minimize error propogation. + */ + v_field_est = DIVIDE(DIVIDE(1000000000000000ULL, h_period_est), + total_v_lines); + + print_value(11, "[V FIELD RATE EST(uHz)]", v_field_est); + + + /* 12. Find the actual horizontal period: + * + * [H PERIOD] = [H PERIOD EST] / ([V FIELD RATE RQD] / [V FIELD RATE EST]) + */ + + h_period = DIVIDE(h_period_est * v_field_est, v_field_rqd * 1000); + + print_value(12, "[H PERIOD(ps)]", h_period); + + + /* 13. Find the actual Vertical field frequency: + * + * [V FIELD RATE] = 1 / [H PERIOD] / [TOTAL V LINES] * 1000000 + * + * And again, we convert to nsec ahead of time, giving us: + * + * [V FIELD RATE] = 1000000 / [H PERIOD] / [TOTAL V LINES] + * + * And another rescaling back to mHz. Gotta love it. + */ + + v_field_rate = DIVIDE(1000000000000ULL, h_period * total_v_lines); + + print_value(13, "[V FIELD RATE]", v_field_rate); + + + /* 14. Find the Vertical frame frequency: + * + * [V FRAME RATE] = (IF([INT RQD?]="y", [V FIELD RATE]/2, [V FIELD RATE])) + * + * N.B. that the result here is in mHz. + */ + + v_frame_rate = (flags & VESAGTF_FLAG_ILACE) ? + v_field_rate / 2 : v_field_rate; + + print_value(14, "[V FRAME RATE]", v_frame_rate); + + + /* 15. Find number of pixels in left margin: + * 16. Find number of pixels in right margin: + * + * [LEFT MARGIN (PIXELS)] = (IF( [MARGINS RQD?]="Y", + * (ROUND( ([H PIXELS RND] * [MARGIN%] / 100 / + * [CELL GRAN RND]),0)) * [CELL GRAN RND], + * 0)) + * + * Again, we deal with margin percentages as PPT (parts per thousand). + * And the calculations for left and right are the same. + */ + + left_margin = right_margin = (flags & VESAGTF_FLAG_MARGINS) ? + DIVIDE(DIVIDE(h_pixels * params->margin_ppt, 1000), + CELL_GRAN) * CELL_GRAN : 0; + + print_value(15, "[LEFT MARGIN (PIXELS)]", left_margin); + print_value(16, "[RIGHT MARGIN (PIXELS)]", right_margin); + + + /* 17. Find total number of active pixels in image and left and right + * margins: + * + * [TOTAL ACTIVE PIXELS] = [H PIXELS RND] + [LEFT MARGIN (PIXELS)] + + * [RIGHT MARGIN (PIXELS)] + */ + + total_active_pixels = h_pixels + left_margin + right_margin; + + print_value(17, "[TOTAL ACTIVE PIXELS]", total_active_pixels); + + + /* 18. Find the ideal blanking duty cycle from the blanking duty cycle + * equation: + * + * [IDEAL DUTY CYCLE] = [C'] - ([M']*[H PERIOD]/1000) + * + * However, we have modified values for [C'] as [256*C'] and + * [M'] as [256*M']. Again the idea here is to get good scaling. + * We use 256 as the factor to make the math fast. + * + * Note that this means that we have to scale it appropriately in + * later calculations. + * + * The ending result is that our ideal_duty_cycle is 256000x larger + * than the duty cycle used by VESA. But again, this reduces error + * propogation. + */ + + ideal_duty_cycle = + ((C_PRIME256(params) * 1000) - + (M_PRIME256(params) * h_period / 1000000)); + + print_value(18, "[IDEAL DUTY CYCLE]", ideal_duty_cycle); + + + /* 19. Find the number of pixels in the blanking time to the nearest + * double character cell: + * + * [H BLANK (PIXELS)] = (ROUND(([TOTAL ACTIVE PIXELS] * + * [IDEAL DUTY CYCLE] / + * (100-[IDEAL DUTY CYCLE]) / + * (2*[CELL GRAN RND])), 0)) + * * (2*[CELL GRAN RND]) + * + * Of course, we adjust to make this rounding work in integer math. + */ + + h_blank = DIVIDE(DIVIDE(total_active_pixels * ideal_duty_cycle, + (256000 * 100ULL) - ideal_duty_cycle), + 2 * CELL_GRAN) * (2 * CELL_GRAN); + + print_value(19, "[H BLANK (PIXELS)]", h_blank); + + + /* 20. Find total number of pixels: + * + * [TOTAL PIXELS] = [TOTAL ACTIVE PIXELS] + [H BLANK (PIXELS)] + */ + + total_pixels = total_active_pixels + h_blank; + + print_value(20, "[TOTAL PIXELS]", total_pixels); + + + /* 21. Find pixel clock frequency: + * + * [PIXEL FREQ] = [TOTAL PIXELS] / [H PERIOD] + * + * We calculate this in Hz rather than MHz, to get a value that + * is usable with integer math. Recall that the [H PERIOD] is in + * nsec. + */ + + pixel_freq = DIVIDE(total_pixels * 1000000, DIVIDE(h_period, 1000)); + + print_value(21, "[PIXEL FREQ]", pixel_freq); + + + /* 22. Find horizontal frequency: + * + * [H FREQ] = 1000 / [H PERIOD] + * + * I've ifdef'd this out, because we don't need it for any of + * our calculations. + * We calculate this in Hz rather than kHz, to avoid rounding + * errors. Recall that the [H PERIOD] is in usec. + */ + +#ifdef GTFDEBUG + h_freq = 1000000000 / h_period; + + print_value(22, "[H FREQ]", h_freq); +#endif + + + + /* Stage 1 computations are now complete; I should really pass + the results to another function and do the Stage 2 + computations, but I only need a few more values so I'll just + append the computations here for now */ + + + + /* 17. Find the number of pixels in the horizontal sync period: + * + * [H SYNC (PIXELS)] =(ROUND(([H SYNC%] / 100 * [TOTAL PIXELS] / + * [CELL GRAN RND]),0))*[CELL GRAN RND] + * + * Rewriting for integer math: + * + * [H SYNC (PIXELS)]=(ROUND((H SYNC%] * [TOTAL PIXELS] / 100 / + * [CELL GRAN RND),0))*[CELL GRAN RND] + */ + + h_sync = DIVIDE(((params->hsync_pct * total_pixels) / 100), CELL_GRAN) * + CELL_GRAN; + + print_value(17, "[H SYNC (PIXELS)]", h_sync); + + + /* 18. Find the number of pixels in the horizontal front porch period: + * + * [H FRONT PORCH (PIXELS)] = ([H BLANK (PIXELS)]/2)-[H SYNC (PIXELS)] + * + * Note that h_blank is always an even number of characters (i.e. + * h_blank % (CELL_GRAN * 2) == 0) + */ + + h_front_porch = (h_blank / 2) - h_sync; + + print_value(18, "[H FRONT PORCH (PIXELS)]", h_front_porch); + + + /* 36. Find the number of lines in the odd front porch period: + * + * [V ODD FRONT PORCH(LINES)]=([MIN PORCH RND]+[INTERLACE]) + * + * Adjusting for the fact that the interlace is scaled: + * + * [V ODD FRONT PORCH(LINES)]=(([MIN PORCH RND] * 2) + [2*INTERLACE]) / 2 + */ + + v_odd_front_porch_lines = ((2 * params->min_porch) + interlace) / 2; + + print_value(36, "[V ODD FRONT PORCH(LINES)]", v_odd_front_porch_lines); + + + /* finally, pack the results in the mode struct */ + + vmp->hsync_start = h_pixels + h_front_porch; + vmp->hsync_end = vmp->hsync_start + h_sync; + vmp->htotal = total_pixels; + vmp->hdisplay = h_pixels; + + vmp->vsync_start = v_lines + v_odd_front_porch_lines; + vmp->vsync_end = vmp->vsync_start + params->vsync_rqd; + vmp->vtotal = total_v_lines; + vmp->vdisplay = v_lines; + + vmp->dot_clock = pixel_freq; + +} + +void +vesagtf_mode(unsigned x, unsigned y, unsigned refresh, struct videomode *vmp) +{ + struct vesagtf_params params; + + params.margin_ppt = VESAGTF_MARGIN_PPT; + params.min_porch = VESAGTF_MIN_PORCH; + params.vsync_rqd = VESAGTF_VSYNC_RQD; + params.hsync_pct = VESAGTF_HSYNC_PCT; + params.min_vsbp = VESAGTF_MIN_VSBP; + params.M = VESAGTF_M; + params.C = VESAGTF_C; + params.K = VESAGTF_K; + params.J = VESAGTF_J; + + vesagtf_mode_params(x, y, refresh, ¶ms, 0, vmp); +} + +/* + * The tidbit here is so that you can compile this file as a + * standalone user program to generate X11 modelines using VESA GTF. + * This also allows for testing of the code itself, without + * necessitating a full kernel recompile. + */ + +/* print_xf86_mode() - print the XFree86 modeline, given mode timings. */ + +#ifndef _KERNEL +void +print_xf86_mode (struct videomode *vmp) +{ + float vf, hf; + + hf = 1000.0 * vmp->dot_clock / vmp->htotal; + vf = 1.0 * hf / vmp->vtotal; + + printf("\n"); + printf(" # %dx%d @ %.2f Hz (GTF) hsync: %.2f kHz; pclk: %.2f MHz\n", + vmp->hdisplay, vmp->vdisplay, vf, hf, vmp->dot_clock / 1000.0); + + printf(" Modeline \"%dx%d_%.2f\" %.2f" + " %d %d %d %d" + " %d %d %d %d" + " -HSync +Vsync\n\n", + vmp->hdisplay, vmp->vdisplay, vf, (vmp->dot_clock / 1000.0), + vmp->hdisplay, vmp->hsync_start, vmp->hsync_end, vmp->htotal, + vmp->vdisplay, vmp->vsync_start, vmp->vsync_end, vmp->vtotal); +} + +int +main (int argc, char *argv[]) +{ + struct videomode m; + + if (argc != 4) { + printf("usage: %s x y refresh\n", argv[0]); + exit(1); + } + + vesagtf_mode(atoi(argv[1]), atoi(argv[2]), atoi(argv[3]), &m); + + print_xf86_mode(&m); + + return 0; + +} +#endif diff --git a/pool/shard004/C/0100923_fs_test.c b/pool/shard004/C/0100923_fs_test.c new file mode 100644 index 0000000000000000000000000000000000000000..60e0d17f8f4c5adc0b352fc06d088ab1292792e2 --- /dev/null +++ b/pool/shard004/C/0100923_fs_test.c @@ -0,0 +1,40 @@ +#include "ftk_globals.h" +#include "ftk_file_system.h" +#include "ftk_allocator_default.h" + +int main(int argc, char* argv[]) +{ + char text[100] = {0}; + char cwd[FTK_MAX_PATH+1]; + char cwd1[FTK_MAX_PATH+1]; + FtkFsHandle handle = NULL; + const char* mime_type = NULL; + + ftk_set_allocator(ftk_allocator_default_create()); + + assert((mime_type = ftk_file_get_mime_type("test.jpg")) != NULL && strcmp(mime_type, "image/jpeg") == 0); + assert((mime_type = ftk_file_get_mime_type("test.txt")) != NULL && strcmp(mime_type, "text/plain") == 0); + assert(ftk_fs_get_cwd(cwd) == RET_OK); + assert(ftk_fs_create_dir("./testdir/a/b/c") == RET_OK); + assert(ftk_fs_change_dir("./testdir/a/b/c") == RET_OK); + handle = ftk_file_open("fstest.txt", "wb+"); + assert(handle != NULL); + assert(ftk_file_write(handle, "test", 4) == 4); + ftk_file_close(handle); + + assert(ftk_fs_change_dir(cwd) == RET_OK); + assert(ftk_fs_move("./testdir/a", "./testdir/d") == RET_OK); + handle = ftk_file_open("./testdir/d/b/c/fstest.txt", "r"); + assert(handle != NULL); + assert(ftk_file_read(handle, text, 4) == 4); + assert(strncmp(text, "test", 4) == 0); + ftk_file_close(handle); + assert(ftk_fs_get_cwd(cwd1) == RET_OK); + assert(strcmp(cwd, cwd1) == 0); + assert(ftk_fs_delete("./testdir/d/b/c") == RET_OK); + assert(ftk_fs_get_cwd(cwd1) == RET_OK); + assert(strcmp(cwd, cwd1) == 0); + assert(ftk_fs_delete("./testdir/d") == RET_OK); + + return 0; +} diff --git a/pool/shard004/C/0100931_spbtf2.c b/pool/shard004/C/0100931_spbtf2.c new file mode 100644 index 0000000000000000000000000000000000000000..9ec4bb53b8da4c47740a069b5dc02bd2a8408c7a --- /dev/null +++ b/pool/shard004/C/0100931_spbtf2.c @@ -0,0 +1,215 @@ +/* spbtf2.f -- translated by f2c (version 20061008). + You must link the resulting object file with libf2c: + on Microsoft Windows system, link with libf2c.lib; + on Linux or Unix systems, link with .../path/to/libf2c.a -lm + or, if you install libf2c.a in a standard place, with -lf2c -lm + -- in that order, at the end of the command line, as in + cc *.o -lf2c -lm + Source for libf2c is in /netlib/f2c/libf2c.zip, e.g., + + http://www.netlib.org/f2c/libf2c.zip +*/ + +#include "f2c.h" +#include "blaswrap.h" + +/* Table of constant values */ + +static real c_b8 = -1.f; +static integer c__1 = 1; + +/* Subroutine */ int spbtf2_(char *uplo, integer *n, integer *kd, real *ab, + integer *ldab, integer *info) +{ + /* System generated locals */ + integer ab_dim1, ab_offset, i__1, i__2, i__3; + real r__1; + + /* Local variables */ + integer j, kn; + real ajj; + integer kld; + logical upper; + +/* -- LAPACK routine (version 3.2) -- */ +/* November 2006 */ + +/* Purpose */ +/* ======= */ + +/* SPBTF2 computes the Cholesky factorization of a real symmetric */ +/* positive definite band matrix A. */ + +/* The factorization has the form */ +/* A = U' * U , if UPLO = 'U', or */ +/* A = L * L', if UPLO = 'L', */ +/* where U is an upper triangular matrix, U' is the transpose of U, and */ +/* L is lower triangular. */ + +/* This is the unblocked version of the algorithm, calling Level 2 BLAS. */ + +/* Arguments */ +/* ========= */ + +/* UPLO (input) CHARACTER*1 */ +/* Specifies whether the upper or lower triangular part of the */ +/* symmetric matrix A is stored: */ +/* = 'U': Upper triangular */ +/* = 'L': Lower triangular */ + +/* N (input) INTEGER */ +/* The order of the matrix A. N >= 0. */ + +/* KD (input) INTEGER */ +/* The number of super-diagonals of the matrix A if UPLO = 'U', */ +/* or the number of sub-diagonals if UPLO = 'L'. KD >= 0. */ + +/* AB (input/output) REAL array, dimension (LDAB,N) */ +/* On entry, the upper or lower triangle of the symmetric band */ +/* matrix A, stored in the first KD+1 rows of the array. The */ +/* j-th column of A is stored in the j-th column of the array AB */ +/* as follows: */ +/* if UPLO = 'U', AB(kd+1+i-j,j) = A(i,j) for max(1,j-kd)<=i<=j; */ +/* if UPLO = 'L', AB(1+i-j,j) = A(i,j) for j<=i<=min(n,j+kd). */ + +/* On exit, if INFO = 0, the triangular factor U or L from the */ +/* Cholesky factorization A = U'*U or A = L*L' of the band */ +/* matrix A, in the same storage format as A. */ + +/* LDAB (input) INTEGER */ +/* The leading dimension of the array AB. LDAB >= KD+1. */ + +/* INFO (output) INTEGER */ +/* = 0: successful exit */ +/* < 0: if INFO = -k, the k-th argument had an illegal value */ +/* > 0: if INFO = k, the leading minor of order k is not */ +/* positive definite, and the factorization could not be */ +/* completed. */ + +/* Further Details */ +/* =============== */ + +/* The band storage scheme is illustrated by the following example, when */ +/* N = 6, KD = 2, and UPLO = 'U': */ + +/* On entry: On exit: */ + +/* * * a13 a24 a35 a46 * * u13 u24 u35 u46 */ +/* * a12 a23 a34 a45 a56 * u12 u23 u34 u45 u56 */ +/* a11 a22 a33 a44 a55 a66 u11 u22 u33 u44 u55 u66 */ + +/* Similarly, if UPLO = 'L' the format of A is as follows: */ + +/* On entry: On exit: */ + +/* a11 a22 a33 a44 a55 a66 l11 l22 l33 l44 l55 l66 */ +/* a21 a32 a43 a54 a65 * l21 l32 l43 l54 l65 * */ +/* a31 a42 a53 a64 * * l31 l42 l53 l64 * * */ + +/* Array elements marked * are not used by the routine. */ + +/* ===================================================================== */ + +/* Test the input parameters. */ + + /* Parameter adjustments */ + ab_dim1 = *ldab; + ab_offset = 1 + ab_dim1; + ab -= ab_offset; + + /* Function Body */ + *info = 0; + upper = lsame_(uplo, "U"); + if (! upper && ! lsame_(uplo, "L")) { + *info = -1; + } else if (*n < 0) { + *info = -2; + } else if (*kd < 0) { + *info = -3; + } else if (*ldab < *kd + 1) { + *info = -5; + } + if (*info != 0) { + i__1 = -(*info); + xerbla_("SPBTF2", &i__1); + return 0; + } + +/* Quick return if possible */ + + if (*n == 0) { + return 0; + } + +/* Computing MAX */ + i__1 = 1, i__2 = *ldab - 1; + kld = max(i__1,i__2); + + if (upper) { + +/* Compute the Cholesky factorization A = U'*U. */ + + i__1 = *n; + for (j = 1; j <= i__1; ++j) { + +/* Compute U(J,J) and test for non-positive-definiteness. */ + + ajj = ab[*kd + 1 + j * ab_dim1]; + if (ajj <= 0.f) { + goto L30; + } + ajj = sqrt(ajj); + ab[*kd + 1 + j * ab_dim1] = ajj; + +/* Compute elements J+1:J+KN of row J and update the */ +/* trailing submatrix within the band. */ + +/* Computing MIN */ + i__2 = *kd, i__3 = *n - j; + kn = min(i__2,i__3); + if (kn > 0) { + r__1 = 1.f / ajj; + sscal_(&kn, &r__1, &ab[*kd + (j + 1) * ab_dim1], &kld); + ssyr_("Upper", &kn, &c_b8, &ab[*kd + (j + 1) * ab_dim1], &kld, + &ab[*kd + 1 + (j + 1) * ab_dim1], &kld); + } + } + } else { + +/* Compute the Cholesky factorization A = L*L'. */ + + i__1 = *n; + for (j = 1; j <= i__1; ++j) { + +/* Compute L(J,J) and test for non-positive-definiteness. */ + + ajj = ab[j * ab_dim1 + 1]; + if (ajj <= 0.f) { + goto L30; + } + ajj = sqrt(ajj); + ab[j * ab_dim1 + 1] = ajj; + +/* Compute elements J+1:J+KN of column J and update the */ +/* trailing submatrix within the band. */ + +/* Computing MIN */ + i__2 = *kd, i__3 = *n - j; + kn = min(i__2,i__3); + if (kn > 0) { + r__1 = 1.f / ajj; + sscal_(&kn, &r__1, &ab[j * ab_dim1 + 2], &c__1); + ssyr_("Lower", &kn, &c_b8, &ab[j * ab_dim1 + 2], &c__1, &ab[( + j + 1) * ab_dim1 + 1], &kld); + } + } + } + return 0; + +L30: + *info = j; + return 0; + +/* End of SPBTF2 */ + +} /* spbtf2_ */ diff --git a/pool/shard004/C/0100932_diag_uart.c b/pool/shard004/C/0100932_diag_uart.c new file mode 100644 index 0000000000000000000000000000000000000000..fff776f14c1137a904b43db74b9f485181144b6e --- /dev/null +++ b/pool/shard004/C/0100932_diag_uart.c @@ -0,0 +1,79 @@ +#include + +#include "diag.h" + +#define FIRST_UART_UNDER_TEST 1 +#define NO_OF_UARTS_UNDER_TEST 1 +#define UART_BUFFER_SIZE 16 + +int baudrate_test[] = {9600, 19200, 115200}; +unsigned char pattern[UART_BUFFER_SIZE] = {0x00, 0xff, 0xaa, 0x55, + 0x0f, 0xa5, 0x5a, 0xf0, + 0x00, 0xff, 0xaa, 0x55, + 0x0f, 0xa5, 0x5a, 0xf0}; +int max_baudrates = sizeof(baudrate_test)/sizeof(int); + +int uart_lpbk_test(int internal); + +int uart_int_lpbk_test(void) +{ + return uart_lpbk_test(1); +} + +int uart_ext_lpbk_test(void) +{ + return uart_lpbk_test(0); +} + +/* The test assumes that UART interrupts are disabled */ +int uart_lpbk_test(int internal) +{ + char test[2][9] = {"external", "internal"}; + unsigned char c; + int i = FIRST_UART_UNDER_TEST; + int j, k; + + for(; i <= NO_OF_UARTS_UNDER_TEST; i++) + { + for(j = 0; j < max_baudrates; j++) + { + printf("\tUART %d %s loopback test on baudrate %6d ", i, test[internal], baudrate_test[j]); + + /* Initialize serial port under test with X baudrate */ + diag_serial_init(i, baudrate_test[j]); + + /* Set internal loopback bit */ + if(internal) + diag_int_lpbk(i, 1); + + /* Write to UART buffer */ + for(k = 0; k < UART_BUFFER_SIZE; k++) + diag_uart_putc(i, pattern[k]); + + /* Read from UART buffer */ + for(k = 0; k < UART_BUFFER_SIZE; k++) + { + if(diag_uart_getc(i, &c)) + { + printf("TIMEOUT\n"); + return 1; + } + + if(pattern[k] != c) + break; + } + + if(k != UART_BUFFER_SIZE) + { + printf("FAILED\n\t\tExpected data 0x%02X - %d\n", pattern[k], k); + printf("\t\tActual data 0x%02X\n\n", c); + return 1; + } + printf("PASSED\n"); + } + /* Reset internal loopback bit */ + if(internal) + diag_int_lpbk(i, 0); + } + return 0; +} diff --git a/pool/shard004/C/0100948_fault.c b/pool/shard004/C/0100948_fault.c new file mode 100644 index 0000000000000000000000000000000000000000..67d2559a302ada1ecfa2e5e790eff4cf882eff3d --- /dev/null +++ b/pool/shard004/C/0100948_fault.c @@ -0,0 +1,111 @@ +/* UNIX V7 source code: see /COPYRIGHT or www.tuhs.org for details. */ + +# +/* + * UNIX shell + * + * S. R. Bourne + * Bell Telephone Laboratories + * + */ + +#include +#include "defs.h" + + +STRING trapcom[MAXTRAP]; +BOOL trapflg[MAXTRAP]; + +/* ======== fault handling routines ======== */ + + +void fault(register int sig) +{ + register int flag; + + signal(sig, fault); + if (sig == MEMF) { + if (setbrk(brkincr) == (void *)-1) + error(nospace); + } else if (sig == ALARM) { + if (flags & waiting) + done(); + } else { + flag = (trapcom[sig] ? TRAPSET : SIGSET); + trapnote |= flag; + trapflg[sig] |= flag; + } +} + +void stdsigs(void) +{ + ignsig(QUIT); + getsig(INTR); + getsig(MEMF); + getsig(ALARM); +} + +sighandler_t ignsig(int n) +{ + register int i; + sighandler_t s; + /* FIXME */ + /* Was a test of the low bit.. not clear this is the correct translation of V7 internals */ + if ((s = signal(i = n, SIG_IGN)) != SIG_IGN) + trapflg[i] |= SIGMOD; + return s; +} + +void getsig(int n) +{ + register int i; + + /* Again was a zero test for ignsig, unclear if correct translation FIXME */ + if (trapflg[i = n] & SIGMOD || ignsig(i) == SIG_DFL) + signal(i, fault); +} + +void oldsigs(void) +{ + register int i; + register char *t; + + i = MAXTRAP; + while (i--) { + t = trapcom[i]; + if (t == 0 || *t) + clrsig(i); + trapflg[i] = 0; + } + trapnote = 0; +} + +void clrsig(int i) +{ + sh_free(trapcom[i]); + trapcom[i] = 0; + if (trapflg[i] & SIGMOD) { + signal(i, fault); + trapflg[i] &= ~SIGMOD; + } +} + +void chktrap(void) +{ + /* check for traps */ + register int i = MAXTRAP; + register STRING t; + + trapnote &= ~TRAPSET; + while (--i) { + if (trapflg[i] & TRAPSET) { + trapflg[i] &= ~TRAPSET; + if (t = trapcom[i]) { + int savxit = exitval; + execexp(t, 0); + exitval = savxit; + exitset(); + } + } + } +} diff --git a/pool/shard004/C/0100950_test.c b/pool/shard004/C/0100950_test.c new file mode 100644 index 0000000000000000000000000000000000000000..9ef31419e2d24039405a4d887059d97f02c8daad --- /dev/null +++ b/pool/shard004/C/0100950_test.c @@ -0,0 +1,35 @@ +#include +#include + +#define assert(cond, msg) if (!(cond)) { \ + printf("assert fail: %s\n", msg); \ + exit(-1); \ +} + +struct TreeNode { + int val; + struct TreeNode *left; + struct TreeNode *right; +}; + +int* postorderTraversal(struct TreeNode* root, int* returnSize); + +int main(int argc, char* argv[]) { + struct TreeNode root, left, right; + root.val = 0; + left.val = 1; + right.val = 2; + + root.left = &left; + root.right = &right; + left.left = left.right = right.left = right.right = 0; + + int returnSize; + int* data = postorderTraversal(&root, &returnSize); + assert(returnSize == 3, "return size should be 3"); + assert(data[0] == 1, "data[0] == 1"); + assert(data[1] == 2, "data[1] == 2"); + assert(data[2] == 0, "data[2] == 0"); + printf("everything is fine!\n"); + return 0; +} \ No newline at end of file diff --git a/pool/shard004/C/0100951_ffxopen.c b/pool/shard004/C/0100951_ffxopen.c new file mode 100644 index 0000000000000000000000000000000000000000..0e4f390440246927c87b4e8632ccc7626f2e1323 --- /dev/null +++ b/pool/shard004/C/0100951_ffxopen.c @@ -0,0 +1,77 @@ +/* + This file is part of SUPPL - the supplemental library for DOS + Copyright (C) 1996-2000 Steffen Kaiser + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Library General Public + License as published by the Free Software Foundation; either + version 2 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Library General Public License for more details. + + You should have received a copy of the GNU Library General Public + License along with this library; if not, write to the Free + Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. +*/ +/* $RCSfile: ffxopen.c,v $ + $Locker: $ $Name: $ $State: Exp $ + + FILE *Fxopen(char *fnam, char *mode) + + Open a file as Fopen(); create extended attributes and chain them + into the list of extended attributes. + + If the returned FILE* pointer is closed by fclose() rather than + Fxclose(), the extended attributes remain in memory an could + return invalid information, if used, if the compiler re-uses + FILE* pointers, e.g. Borland C. + +ob(ject): Fxopen +su(bsystem): supplio +ty(pe): +sh(ort description): Open a file and keep extended attributes +lo(ng description): Opens a file like \tok{Fopen()}, but creates + an extended attribute structure associated to the stream. The + attributes are preset with: + \enum \tok{fp}: opened stream / \tok{(FILE*)} pointer + \enum \tok{fnam}: fully-qualified filename + \enum \tok{istmp}: \tok{0} -- not a temorary file + \endlist +pr(erequistes): fnam != NULL && mode != NULL +va(lue): NULL: on failure\item else: stream / \tok{(FILE*)} pointer +re(lated to): Fxclose Fopen +se(condary subsystems): +in(itialized by): +wa(rning): +bu(gs): +co(mpilers): + +*/ + +#include "initsupl.loc" + +#include +#ifndef _MICROC_ +#include +#endif +#include "supplio.loc" +#include "dfn.h" + +#include "suppldbg.h" + +#ifdef RCS_Version +static char const rcsid[] = + "$Id: ffxopen.c,v 1.1 2006/06/17 03:25:05 blairdude Exp $"; +#endif + +FILE *Fxopen(const char * const fnam, const char * const mode) +{ Suppl_ExtAttr *p; + + assert(fnam); + assert(mode); + + return (p = F_xopen(fnam, mode)) == 0? 0: p->sea_fp; +} diff --git a/pool/shard004/C/0100953_sse-addps-1.c b/pool/shard004/C/0100953_sse-addps-1.c new file mode 100644 index 0000000000000000000000000000000000000000..2aa1cfa411add776e74e8917afdcbd976fe944b7 --- /dev/null +++ b/pool/shard004/C/0100953_sse-addps-1.c @@ -0,0 +1,39 @@ +/* { dg-do run } */ +/* { dg-options "-O2 -msse" } */ + +#ifndef CHECK_H +#define CHECK_H "sse-check.h" +#endif + +#ifndef TEST +#define TEST sse_test +#endif + +#include CHECK_H + +#include + +static __m128 +__attribute__((noinline, unused)) +test (__m128 s1, __m128 s2) +{ + return _mm_add_ps (s1, s2); +} + +static void +TEST (void) +{ + union128 u, s1, s2; + float e[4]; + int i; + + s1.x = _mm_set_ps (24.43, 68.346, 43.35, 546.46); + s2.x = _mm_set_ps (1.17, 2.16, 3.15, 4.14); + u.x = test (s1.x, s2.x); + + for (i = 0; i < 4; i++) + e[i] = s1.a[i] + s2.a[i]; + + if (check_union128 (u, e)) + abort (); +} diff --git a/pool/shard004/C/0100960_wakeup.c b/pool/shard004/C/0100960_wakeup.c new file mode 100644 index 0000000000000000000000000000000000000000..d25901d424bfd4c22e3a03d292dcd1cc091d68c2 --- /dev/null +++ b/pool/shard004/C/0100960_wakeup.c @@ -0,0 +1,107 @@ +/* + * (C) Copyright 2010 + * jung hyun kim, Nexell Co, + * + * 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 + +/* nexell soc headers */ +#include +#include + +/*----------------------------------------------------------------------------*/ +#if defined(CONFIG_PM_WAKEUP) && !defined(CONFIG_PM_WAKEUP_ASM) + +#define SLEEP_PHY_BASE CFG_SLEEP_DATA_BASE +#define REG_PWRGATEREG (0xC0019000) +#define REG_SCRATCHREADREG (0xC0019070) + +static void goto_wakeup(void) +{ + volatile U32 *pData, *pBase; + U32 size, sum, val=0, xor=0; + int i=0; + + pBase = (volatile U32*)(SLEEP_PHY_BASE); + pData = (volatile U32*)(SLEEP_PHY_BASE + 0x8); + + size = *(U32*)(SLEEP_PHY_BASE + 0x4); + sum = *(U32*)pBase; + + /* + * Set alive power gating, NX_ALIVE_SetWriteEnable(CTRUE) + */ + WriteIODW((volatile U32*)REG_PWRGATEREG, (REG_PWRGATEREG | (0x1))); + + /* + * Check scratch register, NX_ALIVE_GetScratchReg() + */ + if (CFG_PWR_SLEEP_SIGNATURE == *(volatile U32*)(REG_SCRATCHREADREG)) + { + printf("%s: wakup mode\n", __func__); + /* Check size value */ + if (size <= 0 || size >= 0x100) { + *pBase = 0x12345678; + printf("%s check size error(%d)\n", __func__, size); + return; + } + printf("%s: size(%d)\n", __func__, size); + + /* Verify checksum value */ + for (i = 0; i +#include +#include +#include + +/* SH7366 registers */ +#define FRQCR 0xa4150000 +#define VCLKCR 0xa4150004 +#define SCLKACR 0xa4150008 +#define SCLKBCR 0xa415000c +#define PLLCR 0xa4150024 +#define MSTPCR0 0xa4150030 +#define MSTPCR1 0xa4150034 +#define MSTPCR2 0xa4150038 +#define DLLFRQ 0xa4150050 + +/* Fixed 32 KHz root clock for RTC and Power Management purposes */ +static struct clk r_clk = { + .name = "rclk", + .id = -1, + .rate = 32768, +}; + +/* + * Default rate for the root input clock, reset this with clk_set_rate() + * from the platform code. + */ +struct clk extal_clk = { + .name = "extal", + .id = -1, + .rate = 33333333, +}; + +/* The dll block multiplies the 32khz r_clk, may be used instead of extal */ +static unsigned long dll_recalc(struct clk *clk) +{ + unsigned long mult; + + if (__raw_readl(PLLCR) & 0x1000) + mult = __raw_readl(DLLFRQ); + else + mult = 0; + + return clk->parent->rate * mult; +} + +static struct clk_ops dll_clk_ops = { + .recalc = dll_recalc, +}; + +static struct clk dll_clk = { + .name = "dll_clk", + .id = -1, + .ops = &dll_clk_ops, + .parent = &r_clk, + .flags = CLK_ENABLE_ON_INIT, +}; + +static unsigned long pll_recalc(struct clk *clk) +{ + unsigned long mult = 1; + unsigned long div = 1; + + if (__raw_readl(PLLCR) & 0x4000) + mult = (((__raw_readl(FRQCR) >> 24) & 0x1f) + 1); + else + div = 2; + + return (clk->parent->rate * mult) / div; +} + +static struct clk_ops pll_clk_ops = { + .recalc = pll_recalc, +}; + +static struct clk pll_clk = { + .name = "pll_clk", + .id = -1, + .ops = &pll_clk_ops, + .flags = CLK_ENABLE_ON_INIT, +}; + +struct clk *main_clks[] = { + &r_clk, + &extal_clk, + &dll_clk, + &pll_clk, +}; + +static int multipliers[] = { 1, 2, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1 }; +static int divisors[] = { 1, 3, 2, 5, 3, 4, 5, 6, 8, 10, 12, 16, 20 }; + +static struct clk_div_mult_table div4_div_mult_table = { + .divisors = divisors, + .nr_divisors = ARRAY_SIZE(divisors), + .multipliers = multipliers, + .nr_multipliers = ARRAY_SIZE(multipliers), +}; + +static struct clk_div4_table div4_table = { + .div_mult_table = &div4_div_mult_table, +}; + +enum { DIV4_I, DIV4_U, DIV4_SH, DIV4_B, DIV4_B3, DIV4_P, + DIV4_SIUA, DIV4_SIUB, DIV4_NR }; + +#define DIV4(_str, _reg, _bit, _mask, _flags) \ + SH_CLK_DIV4(_str, &pll_clk, _reg, _bit, _mask, _flags) + +struct clk div4_clks[DIV4_NR] = { + [DIV4_I] = DIV4("cpu_clk", FRQCR, 20, 0x1fef, CLK_ENABLE_ON_INIT), + [DIV4_U] = DIV4("umem_clk", FRQCR, 16, 0x1fff, CLK_ENABLE_ON_INIT), + [DIV4_SH] = DIV4("shyway_clk", FRQCR, 12, 0x1fff, CLK_ENABLE_ON_INIT), + [DIV4_B] = DIV4("bus_clk", FRQCR, 8, 0x1fff, CLK_ENABLE_ON_INIT), + [DIV4_B3] = DIV4("b3_clk", FRQCR, 4, 0x1fff, CLK_ENABLE_ON_INIT), + [DIV4_P] = DIV4("peripheral_clk", FRQCR, 0, 0x1fff, 0), + [DIV4_SIUA] = DIV4("siua_clk", SCLKACR, 0, 0x1fff, 0), + [DIV4_SIUB] = DIV4("siub_clk", SCLKBCR, 0, 0x1fff, 0), +}; + +struct clk div6_clks[] = { + SH_CLK_DIV6("video_clk", &pll_clk, VCLKCR, 0), +}; + +#define MSTP(_str, _parent, _reg, _bit, _flags) \ + SH_CLK_MSTP32(_str, -1, _parent, _reg, _bit, _flags) + +static struct clk mstp_clks[] = { + /* See page 52 of Datasheet V0.40: Overview -> Block Diagram */ + MSTP("tlb0", &div4_clks[DIV4_I], MSTPCR0, 31, CLK_ENABLE_ON_INIT), + MSTP("ic0", &div4_clks[DIV4_I], MSTPCR0, 30, CLK_ENABLE_ON_INIT), + MSTP("oc0", &div4_clks[DIV4_I], MSTPCR0, 29, CLK_ENABLE_ON_INIT), + MSTP("rsmem0", &div4_clks[DIV4_SH], MSTPCR0, 28, CLK_ENABLE_ON_INIT), + MSTP("xymem0", &div4_clks[DIV4_B], MSTPCR0, 26, CLK_ENABLE_ON_INIT), + MSTP("intc3", &div4_clks[DIV4_P], MSTPCR0, 23, 0), + MSTP("intc0", &div4_clks[DIV4_P], MSTPCR0, 22, 0), + MSTP("dmac0", &div4_clks[DIV4_P], MSTPCR0, 21, 0), + MSTP("sh0", &div4_clks[DIV4_P], MSTPCR0, 20, 0), + MSTP("hudi0", &div4_clks[DIV4_P], MSTPCR0, 19, 0), + MSTP("ubc0", &div4_clks[DIV4_P], MSTPCR0, 17, 0), + MSTP("tmu0", &div4_clks[DIV4_P], MSTPCR0, 15, 0), + MSTP("cmt0", &r_clk, MSTPCR0, 14, 0), + MSTP("rwdt0", &r_clk, MSTPCR0, 13, 0), + MSTP("mfi0", &div4_clks[DIV4_P], MSTPCR0, 11, 0), + MSTP("flctl0", &div4_clks[DIV4_P], MSTPCR0, 10, 0), + MSTP("scif0", &div4_clks[DIV4_P], MSTPCR0, 7, 0), + MSTP("scif1", &div4_clks[DIV4_P], MSTPCR0, 6, 0), + MSTP("scif2", &div4_clks[DIV4_P], MSTPCR0, 5, 0), + MSTP("msiof0", &div4_clks[DIV4_P], MSTPCR0, 2, 0), + MSTP("sbr0", &div4_clks[DIV4_P], MSTPCR0, 1, 0), + + MSTP("i2c0", &div4_clks[DIV4_P], MSTPCR1, 9, 0), + + MSTP("icb0", &div4_clks[DIV4_P], MSTPCR2, 27, 0), + MSTP("meram0", &div4_clks[DIV4_P], MSTPCR2, 26, 0), + MSTP("dacy1", &div4_clks[DIV4_P], MSTPCR2, 24, 0), + MSTP("dacy0", &div4_clks[DIV4_P], MSTPCR2, 23, 0), + MSTP("tsif0", &div4_clks[DIV4_P], MSTPCR2, 22, 0), + MSTP("sdhi0", &div4_clks[DIV4_P], MSTPCR2, 18, 0), + MSTP("mmcif0", &div4_clks[DIV4_P], MSTPCR2, 17, 0), + MSTP("usbf0", &div4_clks[DIV4_P], MSTPCR2, 11, 0), + MSTP("siu0", &div4_clks[DIV4_B], MSTPCR2, 9, 0), + MSTP("veu1", &div4_clks[DIV4_B], MSTPCR2, 7, CLK_ENABLE_ON_INIT), + MSTP("vou0", &div4_clks[DIV4_B], MSTPCR2, 5, 0), + MSTP("beu0", &div4_clks[DIV4_B], MSTPCR2, 4, 0), + MSTP("ceu0", &div4_clks[DIV4_B], MSTPCR2, 3, 0), + MSTP("veu0", &div4_clks[DIV4_B], MSTPCR2, 2, CLK_ENABLE_ON_INIT), + MSTP("vpu0", &div4_clks[DIV4_B], MSTPCR2, 1, CLK_ENABLE_ON_INIT), + MSTP("lcdc0", &div4_clks[DIV4_B], MSTPCR2, 0, 0), +}; + +int __init arch_clk_init(void) +{ + int k, ret = 0; + + /* autodetect extal or dll configuration */ + if (__raw_readl(PLLCR) & 0x1000) + pll_clk.parent = &dll_clk; + else + pll_clk.parent = &extal_clk; + + for (k = 0; !ret && (k < ARRAY_SIZE(main_clks)); k++) + ret = clk_register(main_clks[k]); + + if (!ret) + ret = sh_clk_div4_register(div4_clks, DIV4_NR, &div4_table); + + if (!ret) + ret = sh_clk_div6_register(div6_clks, ARRAY_SIZE(div6_clks)); + + if (!ret) + ret = sh_clk_mstp32_register(mstp_clks, ARRAY_SIZE(mstp_clks)); + + return ret; +} diff --git a/pool/shard004/C/0100964_vboot_api_firmware_tests.c b/pool/shard004/C/0100964_vboot_api_firmware_tests.c new file mode 100644 index 0000000000000000000000000000000000000000..9e7c441d8a0c9597d1c21e5413cf9f924500a24f --- /dev/null +++ b/pool/shard004/C/0100964_vboot_api_firmware_tests.c @@ -0,0 +1,249 @@ +/* Copyright (c) 2011 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. + * + * Tests for vboot_api_firmware + */ + +#include +#include +#include + +#include "host_common.h" +#include "rollback_index.h" +#include "test_common.h" +#include "vboot_common.h" +#include "vboot_nvstorage.h" +#include "vboot_struct.h" + +/* Flags for mock_*_got_flags variables */ +#define MOCK_DEV_FLAG 0x01 /* Developer parameter non-zero */ +#define MOCK_REC_FLAG 0x02 /* Recovery parameter non-zero */ + +/* Mock data */ +static VbCommonParams cparams; +static VbSelectFirmwareParams fparams; +static VbNvContext vnc; +static uint8_t shared_data[VB_SHARED_DATA_MIN_SIZE]; +static VbSharedDataHeader* shared = (VbSharedDataHeader*)shared_data; +static uint64_t mock_timer; +static int nv_write_called; +/* Mock TPM versions */ +static uint32_t mock_tpm_version; +static uint32_t mock_lf_tpm_version; /* TPM version set by LoadFirmware() */ +/* Variables for tracking params passed to mock functions */ +static uint32_t mock_stbms_got_flags; +static uint64_t mock_stbms_got_fw_flags; +static int mock_rfl_called; +/* Mock return values, so we can simulate errors */ +static VbError_t mock_rfw_retval; +static VbError_t mock_rfl_retval; +static VbError_t mock_lf_retval; +static VbError_t mock_stbms_retval; + +/* Reset mock data (for use before each test) */ +static void ResetMocks(void) { + Memset(&cparams, 0, sizeof(cparams)); + cparams.shared_data_size = sizeof(shared_data); + cparams.shared_data_blob = shared_data; + + Memset(&fparams, 0, sizeof(fparams)); + + Memset(&vnc, 0, sizeof(vnc)); + VbNvSetup(&vnc); + VbNvTeardown(&vnc); /* So CRC gets generated */ + + Memset(&shared_data, 0, sizeof(shared_data)); + VbSharedDataInit(shared, sizeof(shared_data)); + shared->fw_keyblock_flags = 0xABCDE0; + + mock_timer = 10; + nv_write_called = mock_rfl_called = 0; + + mock_stbms_got_flags = 0; + mock_stbms_got_fw_flags = 0; + + mock_tpm_version = mock_lf_tpm_version = 0x20004; + shared->fw_version_tpm_start = mock_tpm_version; + mock_rfw_retval = mock_rfl_retval = 0; + mock_lf_retval = mock_stbms_retval = 0; +} + +/****************************************************************************/ +/* Mocked verification functions */ + +VbError_t VbExNvStorageRead(uint8_t* buf) { + Memcpy(buf, vnc.raw, sizeof(vnc.raw)); + return VBERROR_SUCCESS; +} + +VbError_t VbExNvStorageWrite(const uint8_t* buf) { + nv_write_called = 1; + Memcpy(vnc.raw, buf, sizeof(vnc.raw)); + return VBERROR_SUCCESS; +} + +uint64_t VbExGetTimer(void) { + /* Exponential-ish rather than linear time, so that subtracting any + * two mock values will yield a unique result. */ + uint64_t new_timer = mock_timer * 2 + 1; + VbAssert(new_timer > mock_timer); /* Make sure we don't overflow */ + mock_timer = new_timer; + return mock_timer; +} + +uint32_t RollbackFirmwareWrite(uint32_t version) { + mock_tpm_version = version; + return mock_rfw_retval; +} + +uint32_t RollbackFirmwareLock(void) { + mock_rfl_called = 1; + return mock_rfl_retval; +} + +uint32_t SetTPMBootModeState(int developer_mode, int recovery_mode, + uint64_t fw_keyblock_flags) { + if (recovery_mode) + mock_stbms_got_flags |= MOCK_REC_FLAG; + if (developer_mode) + mock_stbms_got_flags |= MOCK_DEV_FLAG; + + mock_stbms_got_fw_flags = fw_keyblock_flags; + + return mock_stbms_retval; +} + +int LoadFirmware(VbCommonParams* cparams, VbSelectFirmwareParams* fparams, + VbNvContext* vnc) { + shared->fw_version_tpm = mock_lf_tpm_version; + return mock_lf_retval; +} + + +/****************************************************************************/ +/* Test VbSelectFirmware() and check expected return value and + * recovery reason */ +static void TestVbSf(VbError_t expected_retval, + uint8_t expected_recovery, const char* desc) { + uint32_t rr = 256; + + TEST_EQ(VbSelectFirmware(&cparams, &fparams), expected_retval, desc); + VbNvGet(&vnc, VBNV_RECOVERY_REQUEST, &rr); + TEST_EQ(rr, expected_recovery, " recovery request"); +} + +/****************************************************************************/ + +static void VbSelectFirmwareTest(void) { + /* Normal call */ + ResetMocks(); + TestVbSf(0, 0, "Normal call"); + TEST_EQ(shared->timer_vb_select_firmware_enter, 21, " time enter"); + TEST_EQ(shared->timer_vb_select_firmware_exit, 43, " time exit"); + TEST_EQ(nv_write_called, 0, " NV write not called since nothing changed"); + TEST_EQ(mock_stbms_got_flags, 0, " SetTPMBootModeState() flags"); + TEST_EQ(mock_stbms_got_fw_flags, 0xABCDE0, " fw keyblock flags"); + TEST_EQ(mock_rfl_called, 1, " RollbackFirmwareLock() called"); + + /* Developer mode call */ + ResetMocks(); + shared->flags |= VBSD_BOOT_DEV_SWITCH_ON; + TestVbSf(0, 0, "Developer mode"); + TEST_EQ(mock_stbms_got_flags, MOCK_DEV_FLAG, " SetTPMBootModeState() flags"); + TEST_EQ(mock_rfl_called, 1, " RollbackFirmwareLock() called"); + + /* Recovery mode doesn't call LoadFirmware(), + * RollbackFirmwareWrite(), or RollbackFirmwareLock(). */ + ResetMocks(); + shared->recovery_reason = VBNV_RECOVERY_US_TEST; + mock_lf_retval = VBERROR_UNKNOWN; + mock_rfw_retval = mock_rfl_retval = TPM_E_IOERROR; + TestVbSf(0, 0, "Recovery mode"); + TEST_EQ(fparams.selected_firmware, VB_SELECT_FIRMWARE_RECOVERY, + " select recovery"); + TEST_EQ(mock_stbms_got_flags, MOCK_REC_FLAG, " SetTPMBootModeState() flags"); + TEST_EQ(mock_rfl_called, 0, " RollbackFirmwareLock() not called"); + + /* Dev + recovery */ + ResetMocks(); + shared->recovery_reason = VBNV_RECOVERY_US_TEST; + shared->flags |= VBSD_BOOT_DEV_SWITCH_ON; + TestVbSf(0, 0, "Recovery+developer mode"); + TEST_EQ(fparams.selected_firmware, VB_SELECT_FIRMWARE_RECOVERY, + " select recovery"); + TEST_EQ(mock_stbms_got_flags, MOCK_DEV_FLAG|MOCK_REC_FLAG, + " SetTPMBootModeState() flags"); + TEST_EQ(mock_rfl_called, 0, " RollbackFirmwareLock() not called"); + + /* LoadFirmware() error code passed through */ + ResetMocks(); + mock_lf_retval = 0x12345; + TestVbSf(0x12345, 0, "LoadFirmware() error"); + + /* Select different firmware paths based on LoadFirmware() result */ + ResetMocks(); + shared->flags |= VBSD_LF_USE_RO_NORMAL; + TestVbSf(0, 0, "LoadFirmware() RO-normal"); + TEST_EQ(fparams.selected_firmware, VB_SELECT_FIRMWARE_READONLY, + " select RO normal"); + ResetMocks(); + shared->firmware_index = 0; + TestVbSf(0, 0, "LoadFirmware() A"); + TEST_EQ(fparams.selected_firmware, VB_SELECT_FIRMWARE_A, " select A"); + ResetMocks(); + shared->firmware_index = 1; + TestVbSf(0, 0, "LoadFirmware() B"); + TEST_EQ(fparams.selected_firmware, VB_SELECT_FIRMWARE_B, " select B"); + + /* Handle TPM version updates */ + ResetMocks(); + mock_lf_tpm_version = 0x30005; + TestVbSf(0, 0, "TPM version update"); + TEST_EQ(shared->fw_version_tpm_start, 0x20004, " TPM version start"); + TEST_EQ(shared->fw_version_tpm, 0x30005, " TPM version"); + TEST_EQ(mock_tpm_version, 0x30005, " TPM version written back"); + + /* Check error writing TPM version */ + ResetMocks(); + mock_lf_tpm_version = 0x30005; + mock_rfw_retval = TPM_E_IOERROR; + TestVbSf(VBERROR_TPM_WRITE_FIRMWARE, VBNV_RECOVERY_RO_TPM_W_ERROR, + "TPM version update failure"); + + /* If no change to TPM version, RollbackFirmwareWrite() not called */ + ResetMocks(); + mock_rfw_retval = TPM_E_IOERROR; + TestVbSf(0, 0, "LoadFirmware() TPM version not updated"); + TEST_EQ(shared->fw_version_tpm_start, 0x20004, " TPM version start"); + TEST_EQ(shared->fw_version_tpm, 0x20004, " TPM version"); + TEST_EQ(mock_tpm_version, 0x20004, " TPM version (not) written back"); + + /* Check errors from SetTPMBootModeState() */ + ResetMocks(); + mock_stbms_retval = TPM_E_IOERROR; + TestVbSf(VBERROR_TPM_SET_BOOT_MODE_STATE, VBNV_RECOVERY_RO_TPM_U_ERROR, + "TPM set boot mode state failure"); + ResetMocks(); + mock_stbms_retval = TPM_E_IOERROR; + shared->recovery_reason = VBNV_RECOVERY_US_TEST; + TestVbSf(0, 0, "TPM set boot mode state failure ignored in recovery"); + + /* Handle RollbackFirmwareLock() errors */ + ResetMocks(); + mock_rfl_retval = TPM_E_IOERROR; + TestVbSf(VBERROR_TPM_LOCK_FIRMWARE, VBNV_RECOVERY_RO_TPM_L_ERROR, + "TPM lock firmware failure"); +} + + +int main(int argc, char* argv[]) { + int error_code = 0; + + VbSelectFirmwareTest(); + + if (!gTestSuccess) + error_code = 255; + + return error_code; +} diff --git a/pool/shard004/C/0100965_lyra2re.c b/pool/shard004/C/0100965_lyra2re.c new file mode 100644 index 0000000000000000000000000000000000000000..3ad1360803b3c1e0816963d079bd303423583640 --- /dev/null +++ b/pool/shard004/C/0100965_lyra2re.c @@ -0,0 +1,164 @@ +/*- + * Copyright 2014 James Lovejoy + * Copyright 2014 phm + * 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 "config.h" +#include "miner.h" + +#include +#include +#include + +#include "sph/sph_blake.h" +#include "sph/sph_groestl.h" +#include "sph/sph_skein.h" +#include "sph/sph_keccak.h" +#include "lyra2.h" + +/* + * Encode a length len/4 vector of (uint32_t) into a length len vector of + * (unsigned char) in big-endian form. Assumes len is a multiple of 4. + */ +static inline void +be32enc_vect(uint32_t *dst, const uint32_t *src, uint32_t len) +{ + uint32_t i; + + for (i = 0; i < len; i++) + dst[i] = htobe32(src[i]); +} + + +void lyra2rehash(void *state, const void *input) +{ + sph_blake256_context ctx_blake; + sph_groestl256_context ctx_groestl; + sph_keccak256_context ctx_keccak; + sph_skein256_context ctx_skein; + + uint32_t hashA[8], hashB[8]; + + sph_blake256_init(&ctx_blake); + sph_blake256 (&ctx_blake, input, 80); + sph_blake256_close (&ctx_blake, hashA); + + sph_keccak256_init(&ctx_keccak); + sph_keccak256 (&ctx_keccak,hashA, 32); + sph_keccak256_close(&ctx_keccak, hashB); + + LYRA2(hashA, 32, hashB, 32, hashB, 32, 1, 8, 8); + + + sph_skein256_init(&ctx_skein); + sph_skein256 (&ctx_skein, hashA, 32); + sph_skein256_close(&ctx_skein, hashB); + + + sph_groestl256_init(&ctx_groestl); + sph_groestl256 (&ctx_groestl, hashB, 32); + sph_groestl256_close(&ctx_groestl, hashA); + + memcpy(state, hashA, 32); +} + +static const uint32_t diff1targ = 0x0000ffff; + + +/* Used externally as confirmation of correct OCL code */ +int lyra2re_test(unsigned char *pdata, const unsigned char *ptarget, uint32_t nonce) +{ + uint32_t tmp_hash7, Htarg = le32toh(((const uint32_t *)ptarget)[7]); + uint32_t data[20], ohash[8]; + + be32enc_vect(data, (const uint32_t *)pdata, 19); + data[19] = htobe32(nonce); + lyra2rehash(ohash, data); + tmp_hash7 = be32toh(ohash[7]); + + applog(LOG_DEBUG, "htarget %08lx diff1 %08lx hash %08lx", + (long unsigned int)Htarg, + (long unsigned int)diff1targ, + (long unsigned int)tmp_hash7); + if (tmp_hash7 > diff1targ) + return -1; + if (tmp_hash7 > Htarg) + return 0; + return 1; +} + +void lyra2re_regenhash(struct work *work) +{ + uint32_t data[20]; + uint32_t *nonce = (uint32_t *)(work->data + 76); + uint32_t *ohash = (uint32_t *)(work->hash); + + be32enc_vect(data, (const uint32_t *)work->data, 19); + data[19] = htobe32(*nonce); + lyra2rehash(ohash, data); +} + +bool scanhash_lyra2re(struct thr_info *thr, const unsigned char __maybe_unused *pmidstate, + unsigned char *pdata, unsigned char __maybe_unused *phash1, + unsigned char __maybe_unused *phash, const unsigned char *ptarget, + uint32_t max_nonce, uint32_t *last_nonce, uint32_t n) +{ + uint32_t *nonce = (uint32_t *)(pdata + 76); + uint32_t data[20]; + uint32_t tmp_hash7; + uint32_t Htarg = le32toh(((const uint32_t *)ptarget)[7]); + bool ret = false; + + be32enc_vect(data, (const uint32_t *)pdata, 19); + + while(1) { + uint32_t ostate[8]; + + *nonce = ++n; + data[19] = (n); + lyra2rehash(ostate, data); + tmp_hash7 = (ostate[7]); + + applog(LOG_INFO, "data7 %08lx", + (long unsigned int)data[7]); + + if (unlikely(tmp_hash7 <= Htarg)) { + ((uint32_t *)pdata)[19] = htobe32(n); + *last_nonce = n; + ret = true; + break; + } + + if (unlikely((n >= max_nonce) || thr->work_restart)) { + *last_nonce = n; + break; + } + } + + return ret; +} + + + diff --git a/pool/shard004/C/0100968_proc.c b/pool/shard004/C/0100968_proc.c new file mode 100644 index 0000000000000000000000000000000000000000..686a9ee0c5dee8b43fbcf72e407dc386e52e7086 --- /dev/null +++ b/pool/shard004/C/0100968_proc.c @@ -0,0 +1,263 @@ +/* proc.c: proc files for key database enumeration + * + * Copyright (C) 2004 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. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include "internal.h" + +#ifdef CONFIG_KEYS_DEBUG_PROC_KEYS +static int proc_keys_open(struct inode *inode, struct file *file); +static void *proc_keys_start(struct seq_file *p, loff_t *_pos); +static void *proc_keys_next(struct seq_file *p, void *v, loff_t *_pos); +static void proc_keys_stop(struct seq_file *p, void *v); +static int proc_keys_show(struct seq_file *m, void *v); + +static struct seq_operations proc_keys_ops = { + .start = proc_keys_start, + .next = proc_keys_next, + .stop = proc_keys_stop, + .show = proc_keys_show, +}; + +static struct file_operations proc_keys_fops = { + .open = proc_keys_open, + .read = seq_read, + .llseek = seq_lseek, + .release = seq_release, +}; +#endif + +static int proc_key_users_open(struct inode *inode, struct file *file); +static void *proc_key_users_start(struct seq_file *p, loff_t *_pos); +static void *proc_key_users_next(struct seq_file *p, void *v, loff_t *_pos); +static void proc_key_users_stop(struct seq_file *p, void *v); +static int proc_key_users_show(struct seq_file *m, void *v); + +static struct seq_operations proc_key_users_ops = { + .start = proc_key_users_start, + .next = proc_key_users_next, + .stop = proc_key_users_stop, + .show = proc_key_users_show, +}; + +static struct file_operations proc_key_users_fops = { + .open = proc_key_users_open, + .read = seq_read, + .llseek = seq_lseek, + .release = seq_release, +}; + +/*****************************************************************************/ +/* + * declare the /proc files + */ +static int __init key_proc_init(void) +{ + struct proc_dir_entry *p; + +#ifdef CONFIG_KEYS_DEBUG_PROC_KEYS + p = create_proc_entry("keys", 0, NULL); + if (!p) + panic("Cannot create /proc/keys\n"); + + p->proc_fops = &proc_keys_fops; +#endif + + p = create_proc_entry("key-users", 0, NULL); + if (!p) + panic("Cannot create /proc/key-users\n"); + + p->proc_fops = &proc_key_users_fops; + + return 0; + +} /* end key_proc_init() */ + +__initcall(key_proc_init); + +/*****************************************************************************/ +/* + * implement "/proc/keys" to provides a list of the keys on the system + */ +#ifdef CONFIG_KEYS_DEBUG_PROC_KEYS + +static int proc_keys_open(struct inode *inode, struct file *file) +{ + return seq_open(file, &proc_keys_ops); + +} + +static void *proc_keys_start(struct seq_file *p, loff_t *_pos) +{ + struct rb_node *_p; + loff_t pos = *_pos; + + spin_lock(&key_serial_lock); + + _p = rb_first(&key_serial_tree); + while (pos > 0 && _p) { + pos--; + _p = rb_next(_p); + } + + return _p; + +} + +static void *proc_keys_next(struct seq_file *p, void *v, loff_t *_pos) +{ + (*_pos)++; + return rb_next((struct rb_node *) v); + +} + +static void proc_keys_stop(struct seq_file *p, void *v) +{ + spin_unlock(&key_serial_lock); +} + +static int proc_keys_show(struct seq_file *m, void *v) +{ + struct rb_node *_p = v; + struct key *key = rb_entry(_p, struct key, serial_node); + struct timespec now; + unsigned long timo; + char xbuf[12]; + int rc; + + /* check whether the current task is allowed to view the key (assuming + * non-possession) */ + rc = key_task_permission(make_key_ref(key, 0), current, KEY_VIEW); + if (rc < 0) + return 0; + + now = current_kernel_time(); + + rcu_read_lock(); + + /* come up with a suitable timeout value */ + if (key->expiry == 0) { + memcpy(xbuf, "perm", 5); + } + else if (now.tv_sec >= key->expiry) { + memcpy(xbuf, "expd", 5); + } + else { + timo = key->expiry - now.tv_sec; + + if (timo < 60) + sprintf(xbuf, "%lus", timo); + else if (timo < 60*60) + sprintf(xbuf, "%lum", timo / 60); + else if (timo < 60*60*24) + sprintf(xbuf, "%luh", timo / (60*60)); + else if (timo < 60*60*24*7) + sprintf(xbuf, "%lud", timo / (60*60*24)); + else + sprintf(xbuf, "%luw", timo / (60*60*24*7)); + } + +#define showflag(KEY, LETTER, FLAG) \ + (test_bit(FLAG, &(KEY)->flags) ? LETTER : '-') + + seq_printf(m, "%08x %c%c%c%c%c%c %5d %4s %08x %5d %5d %-9.9s ", + key->serial, + showflag(key, 'I', KEY_FLAG_INSTANTIATED), + showflag(key, 'R', KEY_FLAG_REVOKED), + showflag(key, 'D', KEY_FLAG_DEAD), + showflag(key, 'Q', KEY_FLAG_IN_QUOTA), + showflag(key, 'U', KEY_FLAG_USER_CONSTRUCT), + showflag(key, 'N', KEY_FLAG_NEGATIVE), + atomic_read(&key->usage), + xbuf, + key->perm, + key->uid, + key->gid, + key->type->name); + +#undef showflag + + if (key->type->describe) + key->type->describe(key, m); + seq_putc(m, '\n'); + + rcu_read_unlock(); + + return 0; + +} + +#endif /* CONFIG_KEYS_DEBUG_PROC_KEYS */ + +/*****************************************************************************/ +/* + * implement "/proc/key-users" to provides a list of the key users + */ +static int proc_key_users_open(struct inode *inode, struct file *file) +{ + return seq_open(file, &proc_key_users_ops); + +} + +static void *proc_key_users_start(struct seq_file *p, loff_t *_pos) +{ + struct rb_node *_p; + loff_t pos = *_pos; + + spin_lock(&key_user_lock); + + _p = rb_first(&key_user_tree); + while (pos > 0 && _p) { + pos--; + _p = rb_next(_p); + } + + return _p; + +} + +static void *proc_key_users_next(struct seq_file *p, void *v, loff_t *_pos) +{ + (*_pos)++; + return rb_next((struct rb_node *) v); + +} + +static void proc_key_users_stop(struct seq_file *p, void *v) +{ + spin_unlock(&key_user_lock); +} + +static int proc_key_users_show(struct seq_file *m, void *v) +{ + struct rb_node *_p = v; + struct key_user *user = rb_entry(_p, struct key_user, node); + + seq_printf(m, "%5u: %5d %d/%d %d/%d %d/%d\n", + user->uid, + atomic_read(&user->usage), + atomic_read(&user->nkeys), + atomic_read(&user->nikeys), + user->qnkeys, + KEYQUOTA_MAX_KEYS, + user->qnbytes, + KEYQUOTA_MAX_BYTES + ); + + return 0; + +} diff --git a/pool/shard004/C/0100976_uid_cputime.c b/pool/shard004/C/0100976_uid_cputime.c new file mode 100644 index 0000000000000000000000000000000000000000..89bfba6c5b6aa91bb4ed63560f65fce3f4134bfc --- /dev/null +++ b/pool/shard004/C/0100976_uid_cputime.c @@ -0,0 +1,245 @@ +/* drivers/misc/uid_cputime.c + * + * Copyright (C) 2014 - 2015 Google, Inc. + * + * This software is licensed under the terms of the GNU General Public + * License version 2, as published by the Free Software Foundation, and + * may be copied, distributed, and modified under those terms. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#define UID_HASH_BITS 10 +DECLARE_HASHTABLE(hash_table, UID_HASH_BITS); + +static DEFINE_MUTEX(uid_lock); +static struct proc_dir_entry *parent; + +struct uid_entry { + uid_t uid; + cputime_t utime; + cputime_t stime; + cputime_t active_utime; + cputime_t active_stime; + unsigned long long active_power; + unsigned long long power; + struct hlist_node hash; +}; + +static struct uid_entry *find_uid_entry(uid_t uid) +{ + struct uid_entry *uid_entry; + hash_for_each_possible(hash_table, uid_entry, hash, uid) { + if (uid_entry->uid == uid) + return uid_entry; + } + return NULL; +} + +static struct uid_entry *find_or_register_uid(uid_t uid) +{ + struct uid_entry *uid_entry; + + uid_entry = find_uid_entry(uid); + if (uid_entry) + return uid_entry; + + uid_entry = kzalloc(sizeof(struct uid_entry), GFP_ATOMIC); + if (!uid_entry) + return NULL; + + uid_entry->uid = uid; + + hash_add(hash_table, &uid_entry->hash, uid); + + return uid_entry; +} + +static int uid_stat_show(struct seq_file *m, void *v) +{ + struct uid_entry *uid_entry; + struct task_struct *task; + cputime_t utime; + cputime_t stime; + unsigned long bkt; + + mutex_lock(&uid_lock); + + hash_for_each(hash_table, bkt, uid_entry, hash) { + uid_entry->active_stime = 0; + uid_entry->active_utime = 0; + uid_entry->active_power = 0; + } + + read_lock(&tasklist_lock); + for_each_process(task) { + uid_entry = find_or_register_uid(from_kuid_munged( + current_user_ns(), task_uid(task))); + if (!uid_entry) { + read_unlock(&tasklist_lock); + mutex_unlock(&uid_lock); + pr_err("%s: failed to find the uid_entry for uid %d\n", + __func__, from_kuid_munged(current_user_ns(), + task_uid(task))); + return -ENOMEM; + } + task_cputime_adjusted(task, &utime, &stime); + uid_entry->active_utime += utime; + uid_entry->active_stime += stime; + uid_entry->active_power += task->cpu_power; + } + read_unlock(&tasklist_lock); + + hash_for_each(hash_table, bkt, uid_entry, hash) { + cputime_t total_utime = uid_entry->utime + + uid_entry->active_utime; + cputime_t total_stime = uid_entry->stime + + uid_entry->active_stime; + unsigned long long total_power = uid_entry->power + + uid_entry->active_power; + seq_printf(m, "%d: %u %u %llu\n", uid_entry->uid, + cputime_to_usecs(total_utime), + cputime_to_usecs(total_stime), + total_power); + } + + mutex_unlock(&uid_lock); + return 0; +} + +static int uid_stat_open(struct inode *inode, struct file *file) +{ + return single_open(file, uid_stat_show, PDE_DATA(inode)); +} + +static const struct file_operations uid_stat_fops = { + .open = uid_stat_open, + .read = seq_read, + .llseek = seq_lseek, + .release = single_release, +}; + +static int uid_remove_open(struct inode *inode, struct file *file) +{ + return single_open(file, NULL, NULL); +} + +static ssize_t uid_remove_write(struct file *file, + const char __user *buffer, size_t count, loff_t *ppos) +{ + struct uid_entry *uid_entry; + struct hlist_node *tmp; + char uids[128]; + char *start_uid, *end_uid = NULL; + long int uid_start = 0, uid_end = 0; + + if (count >= sizeof(uids)) + count = sizeof(uids) - 1; + + if (copy_from_user(uids, buffer, count)) + return -EFAULT; + + uids[count] = '\0'; + end_uid = uids; + start_uid = strsep(&end_uid, "-"); + + if (!start_uid || !end_uid) + return -EINVAL; + + if (kstrtol(start_uid, 10, &uid_start) != 0 || + kstrtol(end_uid, 10, &uid_end) != 0) { + return -EINVAL; + } + + mutex_lock(&uid_lock); + + for (; uid_start <= uid_end; uid_start++) { + hash_for_each_possible_safe(hash_table, uid_entry, tmp, + hash, uid_start) { + hash_del(&uid_entry->hash); + kfree(uid_entry); + } + } + + mutex_unlock(&uid_lock); + return count; +} + +static const struct file_operations uid_remove_fops = { + .open = uid_remove_open, + .release = single_release, + .write = uid_remove_write, +}; + +static int process_notifier(struct notifier_block *self, + unsigned long cmd, void *v) +{ + struct task_struct *task = v; + struct uid_entry *uid_entry; + cputime_t utime, stime; + uid_t uid; + + if (!task) + return NOTIFY_OK; + + mutex_lock(&uid_lock); + uid = from_kuid_munged(current_user_ns(), task_uid(task)); + uid_entry = find_or_register_uid(uid); + if (!uid_entry) { + pr_err("%s: failed to find uid %d\n", __func__, uid); + goto exit; + } + + task_cputime_adjusted(task, &utime, &stime); + uid_entry->utime += utime; + uid_entry->stime += stime; + uid_entry->power += task->cpu_power; + +exit: + mutex_unlock(&uid_lock); + return NOTIFY_OK; +} + +static struct notifier_block process_notifier_block = { + .notifier_call = process_notifier, +}; + +static int __init proc_uid_cputime_init(void) +{ + hash_init(hash_table); + + parent = proc_mkdir("uid_cputime", NULL); + if (!parent) { + pr_err("%s: failed to create proc entry\n", __func__); + return -ENOMEM; + } + + proc_create_data("remove_uid_range", S_IWUGO, parent, &uid_remove_fops, + NULL); + + proc_create_data("show_uid_stat", S_IRUGO, parent, &uid_stat_fops, + NULL); + + profile_event_register(PROFILE_TASK_EXIT, &process_notifier_block); + + return 0; +} + +early_initcall(proc_uid_cputime_init); diff --git a/pool/shard004/C/0100979_setup.c b/pool/shard004/C/0100979_setup.c new file mode 100644 index 0000000000000000000000000000000000000000..80f4ecd42b0dc3ca21a57bf2e52745d0c389b769 --- /dev/null +++ b/pool/shard004/C/0100979_setup.c @@ -0,0 +1,242 @@ +/* + * Atheros AR71XX/AR724X/AR913X specific setup + * + * Copyright (C) 2010-2011 Jaiganesh Narayanan + * Copyright (C) 2008-2011 Gabor Juhos + * Copyright (C) 2008 Imre Kaloz + * + * Parts of this file are based on Atheros' 2.6.15/2.6.31 BSP + * + * 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 /* for mips_hpt_frequency */ +#include /* for _machine_{restart,halt} */ +#include + +#include +#include +#include "common.h" +#include "dev-common.h" +#include "machtypes.h" + +#define ATH79_SYS_TYPE_LEN 64 + +#define AR71XX_BASE_FREQ 40000000 +#define AR724X_BASE_FREQ 5000000 +#define AR913X_BASE_FREQ 5000000 + +static char ath79_sys_type[ATH79_SYS_TYPE_LEN]; + +static void ath79_restart(char *command) +{ + ath79_device_reset_set(AR71XX_RESET_FULL_CHIP); + for (;;) + if (cpu_wait) + cpu_wait(); +} + +static void ath79_halt(void) +{ + while (1) + cpu_wait(); +} + +static void __init ath79_detect_sys_type(void) +{ + char *chip = "????"; + u32 id; + u32 major; + u32 minor; + u32 rev = 0; + + id = ath79_reset_rr(AR71XX_RESET_REG_REV_ID); + major = id & REV_ID_MAJOR_MASK; + + switch (major) { + case REV_ID_MAJOR_AR71XX: + minor = id & AR71XX_REV_ID_MINOR_MASK; + rev = id >> AR71XX_REV_ID_REVISION_SHIFT; + rev &= AR71XX_REV_ID_REVISION_MASK; + switch (minor) { + case AR71XX_REV_ID_MINOR_AR7130: + ath79_soc = ATH79_SOC_AR7130; + chip = "7130"; + break; + + case AR71XX_REV_ID_MINOR_AR7141: + ath79_soc = ATH79_SOC_AR7141; + chip = "7141"; + break; + + case AR71XX_REV_ID_MINOR_AR7161: + ath79_soc = ATH79_SOC_AR7161; + chip = "7161"; + break; + } + break; + + case REV_ID_MAJOR_AR7240: + ath79_soc = ATH79_SOC_AR7240; + chip = "7240"; + rev = id & AR724X_REV_ID_REVISION_MASK; + break; + + case REV_ID_MAJOR_AR7241: + ath79_soc = ATH79_SOC_AR7241; + chip = "7241"; + rev = id & AR724X_REV_ID_REVISION_MASK; + break; + + case REV_ID_MAJOR_AR7242: + ath79_soc = ATH79_SOC_AR7242; + chip = "7242"; + rev = id & AR724X_REV_ID_REVISION_MASK; + break; + + case REV_ID_MAJOR_AR913X: + minor = id & AR913X_REV_ID_MINOR_MASK; + rev = id >> AR913X_REV_ID_REVISION_SHIFT; + rev &= AR913X_REV_ID_REVISION_MASK; + switch (minor) { + case AR913X_REV_ID_MINOR_AR9130: + ath79_soc = ATH79_SOC_AR9130; + chip = "9130"; + break; + + case AR913X_REV_ID_MINOR_AR9132: + ath79_soc = ATH79_SOC_AR9132; + chip = "9132"; + break; + } + break; + + case REV_ID_MAJOR_AR9330: + ath79_soc = ATH79_SOC_AR9330; + chip = "9330"; + rev = id & AR933X_REV_ID_REVISION_MASK; + break; + + case REV_ID_MAJOR_AR9331: + ath79_soc = ATH79_SOC_AR9331; + chip = "9331"; + rev = id & AR933X_REV_ID_REVISION_MASK; + break; + + case REV_ID_MAJOR_AR9341: + ath79_soc = ATH79_SOC_AR9341; + chip = "9341"; + rev = id & AR934X_REV_ID_REVISION_MASK; + break; + + case REV_ID_MAJOR_AR9342: + ath79_soc = ATH79_SOC_AR9342; + chip = "9342"; + rev = id & AR934X_REV_ID_REVISION_MASK; + break; + + case REV_ID_MAJOR_AR9344: + ath79_soc = ATH79_SOC_AR9344; + chip = "9344"; + rev = id & AR934X_REV_ID_REVISION_MASK; + break; + + case REV_ID_MAJOR_QCA9556: + ath79_soc = ATH79_SOC_QCA9556; + chip = "9556"; + rev = id & QCA955X_REV_ID_REVISION_MASK; + break; + + case REV_ID_MAJOR_QCA9558: + ath79_soc = ATH79_SOC_QCA9558; + chip = "9558"; + rev = id & QCA955X_REV_ID_REVISION_MASK; + break; + + default: + panic("ath79: unknown SoC, id:0x%08x", id); + } + + ath79_soc_rev = rev; + + if (soc_is_qca955x()) + sprintf(ath79_sys_type, "Qualcomm Atheros QCA%s rev %u", + chip, rev); + else + sprintf(ath79_sys_type, "Atheros AR%s rev %u", chip, rev); + pr_info("SoC: %s\n", ath79_sys_type); +} + +const char *get_system_type(void) +{ + return ath79_sys_type; +} + +unsigned int get_c0_compare_int(void) +{ + return CP0_LEGACY_COMPARE_IRQ; +} + +void __init plat_mem_setup(void) +{ + set_io_port_base(KSEG1); + + ath79_reset_base = ioremap_nocache(AR71XX_RESET_BASE, + AR71XX_RESET_SIZE); + ath79_pll_base = ioremap_nocache(AR71XX_PLL_BASE, + AR71XX_PLL_SIZE); + ath79_ddr_base = ioremap_nocache(AR71XX_DDR_CTRL_BASE, + AR71XX_DDR_CTRL_SIZE); + + ath79_detect_sys_type(); + detect_memory_region(0, ATH79_MEM_SIZE_MIN, ATH79_MEM_SIZE_MAX); + ath79_clocks_init(); + + _machine_restart = ath79_restart; + _machine_halt = ath79_halt; + pm_power_off = ath79_halt; +} + +void __init plat_time_init(void) +{ + struct clk *clk; + + clk = clk_get(NULL, "cpu"); + if (IS_ERR(clk)) + panic("unable to get CPU clock, err=%ld", PTR_ERR(clk)); + + mips_hpt_frequency = clk_get_rate(clk) / 2; +} + +static int __init ath79_setup(void) +{ + ath79_gpio_init(); + ath79_register_uart(); + ath79_register_wdt(); + + mips_machine_setup(); + + return 0; +} + +arch_initcall(ath79_setup); + +static void __init ath79_generic_init(void) +{ + /* Nothing to do */ +} + +MIPS_MACHINE(ATH79_MACH_GENERIC, + "Generic", + "Generic AR71XX/AR724X/AR913X based board", + ath79_generic_init); diff --git a/pool/shard004/C/0100987_dev-dwmci.c b/pool/shard004/C/0100987_dev-dwmci.c new file mode 100644 index 0000000000000000000000000000000000000000..e78a83f0a467a2e9d337342b632ad226caaaa6a5 --- /dev/null +++ b/pool/shard004/C/0100987_dev-dwmci.c @@ -0,0 +1,184 @@ +/* + * linux/arch/arm/mach-exynos/dev-dwmci.c + * + * Copyright (c) 2011 Samsung Electronics Co., Ltd. + * http://www.samsung.com + * + * Platform device for Synopsys DesignWare Mobile Storage IP + * + * 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 + +#define DWMCI_CLKSEL 0x09c + +static int exynos_dwmci_get_bus_wd(u32 slot_id) +{ + return 4; +} + +static int exynos_dwmci_init(u32 slot_id, irq_handler_t handler, void *data) +{ + struct dw_mci *host = (struct dw_mci *)data; + + /* Set Phase Shift Register */ + if (soc_is_exynos4210()) { + host->pdata->sdr_timing = 0x00010001; + host->pdata->ddr_timing = 0x00020002; + } else if (soc_is_exynos4212() || soc_is_exynos4412()) { + host->pdata->sdr_timing = 0x00010001; + host->pdata->ddr_timing = 0x00010002; + } +#ifdef CONFIG_SLP + host->pdata->sdr_timing = 0x00020001; + host->pdata->ddr_timing = 0x00020002; +#endif + + return 0; +} + +static void exynos_dwmci_set_io_timing(void *data, unsigned char timing) +{ + struct dw_mci *host = (struct dw_mci *)data; + + if (timing == MMC_TIMING_UHS_DDR50) + __raw_writel(host->pdata->ddr_timing, + host->regs + DWMCI_CLKSEL); + else + __raw_writel(host->pdata->sdr_timing, + host->regs + DWMCI_CLKSEL); +} + +static struct resource exynos_dwmci_resource[] = { + [0] = { + .start = EXYNOS_PA_DWMCI, + .end = EXYNOS_PA_DWMCI + SZ_4K - 1, + .flags = IORESOURCE_MEM, + }, + [1] = { + .start = IRQ_DWMCI, + .end = IRQ_DWMCI, + .flags = IORESOURCE_IRQ, + } +}; + +static struct dw_mci_board exynos_dwmci_def_platdata = { + .num_slots = 1, + .quirks = DW_MCI_QUIRK_BROKEN_CARD_DETECTION, + .bus_hz = 80 * 1000 * 1000, + .detect_delay_ms = 200, + .init = exynos_dwmci_init, + .get_bus_wd = exynos_dwmci_get_bus_wd, + .set_io_timing = exynos_dwmci_set_io_timing, +}; + +static u64 exynos_dwmci_dmamask = DMA_BIT_MASK(32); + +struct platform_device exynos_device_dwmci = { + .name = "dw_mmc", + .id = -1, + .num_resources = ARRAY_SIZE(exynos_dwmci_resource), + .resource = exynos_dwmci_resource, + .dev = { + .dma_mask = &exynos_dwmci_dmamask, + .coherent_dma_mask = DMA_BIT_MASK(32), + .platform_data = &exynos_dwmci_def_platdata, + }, +}; + +#define EXYNOS5_DWMCI_RESOURCE(_channel) \ +static struct resource exynos5_dwmci##_channel##_resource[] = { \ + [0] = { \ + .start = S3C_PA_HSMMC##_channel, \ + .end = S3C_PA_HSMMC##_channel + SZ_4K - 1, \ + .flags = IORESOURCE_MEM, \ + }, \ + [1] = { \ + .start = IRQ_HSMMC##_channel, \ + .end = IRQ_HSMMC##_channel, \ + .flags = IORESOURCE_IRQ, \ + } \ +}; + +EXYNOS5_DWMCI_RESOURCE(0) +EXYNOS5_DWMCI_RESOURCE(1) +EXYNOS5_DWMCI_RESOURCE(2) +EXYNOS5_DWMCI_RESOURCE(3) + +#define EXYNOS_DWMCI_DEF_PLATDATA(_channel) \ +struct dw_mci_board exynos_dwmci##_channel##_def_platdata = { \ + .num_slots = 1, \ + .quirks = \ + DW_MCI_QUIRK_BROKEN_CARD_DETECTION, \ + .bus_hz = 200 * 1000 * 1000, \ + .detect_delay_ms = 200, \ + .init = exynos_dwmci_init, \ + .get_bus_wd = exynos_dwmci_get_bus_wd, \ + .set_io_timing = exynos_dwmci_set_io_timing, \ + .cd_type = DW_MCI_CD_INTERNAL \ +}; + +EXYNOS_DWMCI_DEF_PLATDATA(0) +EXYNOS_DWMCI_DEF_PLATDATA(1) +EXYNOS_DWMCI_DEF_PLATDATA(2) +EXYNOS_DWMCI_DEF_PLATDATA(3) + +#define EXYNOS_DWMCI_PLATFORM_DEVICE(_channel) \ +struct platform_device exynos_device_dwmci##_channel = \ +{ \ + .name = "dw_mmc", \ + .id = _channel, \ + .num_resources = \ + ARRAY_SIZE(exynos5_dwmci##_channel##_resource), \ + .resource = exynos5_dwmci##_channel##_resource, \ + .dev = { \ + .dma_mask = &exynos_dwmci_dmamask,\ + .coherent_dma_mask = DMA_BIT_MASK(32), \ + .platform_data = \ + &exynos_dwmci##_channel##_def_platdata, \ + }, \ +}; + +EXYNOS_DWMCI_PLATFORM_DEVICE(0) +EXYNOS_DWMCI_PLATFORM_DEVICE(1) +EXYNOS_DWMCI_PLATFORM_DEVICE(2) +EXYNOS_DWMCI_PLATFORM_DEVICE(3) + +void __init exynos_dwmci_set_platdata(struct dw_mci_board *pd) +{ + struct dw_mci_board *npd = NULL; + + if ((soc_is_exynos4210()) || + soc_is_exynos4212() || soc_is_exynos4412()) { + npd = s3c_set_platdata(pd, sizeof(struct dw_mci_board), &exynos_device_dwmci); + } else { + printk("dwmci platform data support only exynos4/5!\n"); +#ifdef CONFIG_SLP + npd = s3c_set_platdata(pd, sizeof(struct dw_mci_board), + &exynos_device_dwmci); +#endif + } + + if (npd) { + if (!npd->init) + npd->init = exynos_dwmci_init; + if (!npd->get_bus_wd) + npd->get_bus_wd = exynos_dwmci_get_bus_wd; + if (!npd->set_io_timing) + npd->set_io_timing = exynos_dwmci_set_io_timing; + } +} diff --git a/pool/shard004/C/0101000_result.c b/pool/shard004/C/0101000_result.c new file mode 100644 index 0000000000000000000000000000000000000000..66fa9704ea27756a8989389e362481fb71829d2a --- /dev/null +++ b/pool/shard004/C/0101000_result.c @@ -0,0 +1,210 @@ +/* + * Copyright (C) 2004 Internet Systems Consortium, Inc. ("ISC") + * Copyright (C) 1998-2001, 2003 Internet Software Consortium. + * + * 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 ISC DISCLAIMS ALL WARRANTIES WITH + * REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY + * AND FITNESS. IN NO EVENT SHALL ISC 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. + */ + +/* $ISC-Id:result.c,v 1.56.2.2.8.7 2004/06/11 00:31:01 marka Exp $ */ +/* $Id: result.c,v 1.1 2005/08/04 21:10:54 mcr Exp $ */ + +#include + +#include + +#include +#include +#include +#include +#include +#include + +typedef struct resulttable { + unsigned int base; + unsigned int last; + const char ** text; + isc_msgcat_t * msgcat; + int set; + ISC_LINK(struct resulttable) link; +} resulttable; + +static const char *text[ISC_R_NRESULTS] = { + "success", /* 0 */ + "out of memory", /* 1 */ + "timed out", /* 2 */ + "no available threads", /* 3 */ + "address not available", /* 4 */ + "address in use", /* 5 */ + "permission denied", /* 6 */ + "no pending connections", /* 7 */ + "network unreachable", /* 8 */ + "host unreachable", /* 9 */ + "network down", /* 10 */ + "host down", /* 11 */ + "connection refused", /* 12 */ + "not enough free resources", /* 13 */ + "end of file", /* 14 */ + "socket already bound", /* 15 */ + "reload", /* 16 */ + "lock busy", /* 17 */ + "already exists", /* 18 */ + "ran out of space", /* 19 */ + "operation canceled", /* 20 */ + "socket is not bound", /* 21 */ + "shutting down", /* 22 */ + "not found", /* 23 */ + "unexpected end of input", /* 24 */ + "failure", /* 25 */ + "I/O error", /* 26 */ + "not implemented", /* 27 */ + "unbalanced parentheses", /* 28 */ + "no more", /* 29 */ + "invalid file", /* 30 */ + "bad base64 encoding", /* 31 */ + "unexpected token", /* 32 */ + "quota reached", /* 33 */ + "unexpected error", /* 34 */ + "already running", /* 35 */ + "ignore", /* 36 */ + "address mask not contiguous", /* 37 */ + "file not found", /* 38 */ + "file already exists", /* 39 */ + "socket is not connected", /* 40 */ + "out of range", /* 41 */ + "out of entropy", /* 42 */ + "invalid use of multicast address", /* 43 */ + "not a file", /* 44 */ + "not a directory", /* 45 */ + "queue is full", /* 46 */ + "address family mismatch", /* 47 */ + "address family not supported", /* 48 */ + "bad hex encoding", /* 49 */ + "too many open files", /* 50 */ + "not blocking", /* 51 */ + "unbalanced quotes", /* 52 */ + "operation in progress", /* 53 */ + "connection reset", /* 54 */ + "soft quota reached", /* 55 */ + "not a valid number", /* 56 */ + "disabled", /* 57 */ + "max size", /* 58 */ + "invalid address format" /* 59 */ +}; + +#define ISC_RESULT_RESULTSET 2 +#define ISC_RESULT_UNAVAILABLESET 3 + +static isc_once_t once = ISC_ONCE_INIT; +static ISC_LIST(resulttable) tables; +static isc_mutex_t lock; + +static isc_result_t +register_table(unsigned int base, unsigned int nresults, const char **mytext, + isc_msgcat_t *msgcat, int set) +{ + resulttable *table; + + REQUIRE(base % ISC_RESULTCLASS_SIZE == 0); + REQUIRE(nresults <= ISC_RESULTCLASS_SIZE); + REQUIRE(mytext != NULL); + + /* + * We use malloc() here because we we want to be able to use + * isc_result_totext() even if there is no memory context. + */ + table = malloc(sizeof(*table)); + if (table == NULL) + return (ISC_R_NOMEMORY); + table->base = base; + table->last = base + nresults - 1; + table->text = mytext; + table->msgcat = msgcat; + table->set = set; + ISC_LINK_INIT(table, link); + + LOCK(&lock); + + ISC_LIST_APPEND(tables, table, link); + + UNLOCK(&lock); + + return (ISC_R_SUCCESS); +} + +static void +initialize_action(void) { + isc_result_t result; + + RUNTIME_CHECK(isc_mutex_init(&lock) == ISC_R_SUCCESS); + ISC_LIST_INIT(tables); + + result = register_table(ISC_RESULTCLASS_ISC, ISC_R_NRESULTS, text, + isc_msgcat, ISC_RESULT_RESULTSET); + if (result != ISC_R_SUCCESS) + UNEXPECTED_ERROR(__FILE__, __LINE__, + "register_table() %s: %u", + isc_msgcat_get(isc_msgcat, ISC_MSGSET_GENERAL, + ISC_MSG_FAILED, "failed"), + result); +} + +static void +initialize(void) { + isc_lib_initmsgcat(); + RUNTIME_CHECK(isc_once_do(&once, initialize_action) == ISC_R_SUCCESS); +} + +const char * +isc_result_totext(isc_result_t result) { + resulttable *table; + const char *mytext, *default_text; + int index; + + initialize(); + + LOCK(&lock); + + mytext = NULL; + for (table = ISC_LIST_HEAD(tables); + table != NULL; + table = ISC_LIST_NEXT(table, link)) { + if (result >= table->base && result <= table->last) { + index = (int)(result - table->base); + default_text = table->text[index]; + /* + * Note: we use 'index + 1' as the message number + * instead of index because isc_msgcat_get() requires + * the message number to be > 0. + */ + mytext = isc_msgcat_get(table->msgcat, table->set, + index + 1, default_text); + break; + } + } + if (mytext == NULL) + mytext = isc_msgcat_get(isc_msgcat, ISC_RESULT_UNAVAILABLESET, + 1, "(result code text not available)"); + + UNLOCK(&lock); + + return (mytext); +} + +isc_result_t +isc_result_register(unsigned int base, unsigned int nresults, + const char **mytext, isc_msgcat_t *msgcat, int set) +{ + initialize(); + + return (register_table(base, nresults, mytext, msgcat, set)); +} diff --git a/pool/shard004/C/0101033_ndr_policyagent.c b/pool/shard004/C/0101033_ndr_policyagent.c new file mode 100644 index 0000000000000000000000000000000000000000..0bedcb3f84dd856762f6c6776f6e59cdbd904525 --- /dev/null +++ b/pool/shard004/C/0101033_ndr_policyagent.c @@ -0,0 +1,92 @@ +/* parser auto-generated by pidl */ + +#include "includes.h" +#include "librpc/gen_ndr/ndr_policyagent.h" + +static enum ndr_err_code ndr_push_policyagent_Dummy(struct ndr_push *ndr, int flags, const struct policyagent_Dummy *r) +{ + if (flags & NDR_IN) { + } + if (flags & NDR_OUT) { + NDR_CHECK(ndr_push_WERROR(ndr, NDR_SCALARS, r->out.result)); + } + return NDR_ERR_SUCCESS; +} + +static enum ndr_err_code ndr_pull_policyagent_Dummy(struct ndr_pull *ndr, int flags, struct policyagent_Dummy *r) +{ + if (flags & NDR_IN) { + } + if (flags & NDR_OUT) { + NDR_CHECK(ndr_pull_WERROR(ndr, NDR_SCALARS, &r->out.result)); + } + return NDR_ERR_SUCCESS; +} + +_PUBLIC_ void ndr_print_policyagent_Dummy(struct ndr_print *ndr, const char *name, int flags, const struct policyagent_Dummy *r) +{ + ndr_print_struct(ndr, name, "policyagent_Dummy"); + if (r == NULL) { ndr_print_null(ndr); return; } + ndr->depth++; + if (flags & NDR_SET_VALUES) { + ndr->flags |= LIBNDR_PRINT_SET_VALUES; + } + if (flags & NDR_IN) { + ndr_print_struct(ndr, "in", "policyagent_Dummy"); + ndr->depth++; + ndr->depth--; + } + if (flags & NDR_OUT) { + ndr_print_struct(ndr, "out", "policyagent_Dummy"); + ndr->depth++; + ndr_print_WERROR(ndr, "result", r->out.result); + ndr->depth--; + } + ndr->depth--; +} + +static const struct ndr_interface_call policyagent_calls[] = { + { + "policyagent_Dummy", + sizeof(struct policyagent_Dummy), + (ndr_push_flags_fn_t) ndr_push_policyagent_Dummy, + (ndr_pull_flags_fn_t) ndr_pull_policyagent_Dummy, + (ndr_print_function_t) ndr_print_disabled, + { 0, NULL }, + { 0, NULL }, + }, + { NULL, 0, NULL, NULL, NULL } +}; + +static const char * const policyagent_endpoint_strings[] = { + "ncacn_np:[\\pipe\\policyagent]", +}; + +static const struct ndr_interface_string_array policyagent_endpoints = { + .count = 1, + .names = policyagent_endpoint_strings +}; + +static const char * const policyagent_authservice_strings[] = { + "host", +}; + +static const struct ndr_interface_string_array policyagent_authservices = { + .count = 1, + .names = policyagent_authservice_strings +}; + + +const struct ndr_interface_table ndr_table_policyagent = { + .name = "policyagent", + .syntax_id = { + {0xd335b8f6,0xcb31,0x11d0,{0xb0,0xf9},{0x00,0x60,0x97,0xba,0x4e,0x54}}, + NDR_POLICYAGENT_VERSION + }, + .helpstring = NDR_POLICYAGENT_HELPSTRING, + .num_calls = 1, + .calls = policyagent_calls, + .endpoints = &policyagent_endpoints, + .authservices = &policyagent_authservices +}; + diff --git a/pool/shard004/C/0101045_hamurabi.c b/pool/shard004/C/0101045_hamurabi.c new file mode 100644 index 0000000000000000000000000000000000000000..20128ba49f2bd6ecbc91ae24447523c056da106f --- /dev/null +++ b/pool/shard004/C/0101045_hamurabi.c @@ -0,0 +1,167 @@ +/* Hamurabi ver 2007-Oct-25 + * by Joseph Larson (c) 2008 + * based on a BASIC program written by David Ahl + * as found in 'BASIC Computer Games' edited by David H Ahl (c) 1978 + * inspired by a Focal program from an unknown author + */ + +#include +#include +#include + +#define SHORT_LAND_MSG printf ("Hamurabi, think again."\ + " You own only %d acres. Now then,\n", acres) +#define SHORT_GRAIN_MSG printf ("Hamurabi, think again."\ + " You have only %d bushels of grain. Now then,\n", grain) + +int pop, acres, grain, starved, born, yield, rats, food, year; + +void resign (void) { + printf ("Hamurabi, I can not do what you wish." + " Get yourself another steward!\n"); + exit (0); +} + +void endgame (int rank) { + switch (rank) { + case 0: + printf ("Due to this extreme mismanagement you have not only been" + " impeached\nand thrown out of office but you have been also declared" + " a national fink!\n"); + break; + case 1: + printf ("You heavy handed performance smacks of Nero and Ivan IV." + " The people\n(remaining) find you an unpleasant ruler and frankly" + " hate your guts!!\n"); + break; + case 2: + printf ("Your performance could have been somewhat better but really" + " wasn't\ntoo bad at all. %d people dearly would like to see you" + " assassinated\nbut we all have our trivial problems.\n" + , pop * (rand () % 80) / 100); + break; + default: + printf ("A fantastic performance!!! Charlemagne, Disraeli, and Jefferson\n" + "combined could not have done better!!\n"); + } +} + +void report (void) { + printf ("\n\nHamurabi, I beg to report to you;\n\n" + "In year %d, %d people starved, %d came to the city.\n" + , year, starved, born); + if (rand() < (RAND_MAX / 100 * 15) && year > 1) { + printf ("A horrible plague struck! Half the people died.\n"); + pop /= 2; + } + printf ("Population is now %d.\n" + "The city now owns %d acres.\n" + "You harvested %d bushels per acre.\n" + "Rats ate %d bushels.\n" + "You now have %d bushels in store.\n\n", + pop, acres, yield, rats, grain); +} + +void buysell (void) { + int input, price; + + price = rand() % 10 + 17; + printf ("Land is trading at %d bushels per acre.\n", price); + printf ("How many acres do you wish to buy? "); + scanf ("%d", &input); + while (price * input > grain) { + SHORT_GRAIN_MSG; + printf ("how many do you wish to buy? "); + scanf ("%d", &input); + } + if (input < 0) resign(); + if (input) { + acres += input; + grain -= price * input; + } else { + printf ("How man acres do you wish to sell? "); + scanf ("%d", &input); + while (input > acres) { + SHORT_LAND_MSG; + printf ("how many do you wish to buy? "); + scanf ("%d", &input); + } + if (input < 0) resign (); + acres -= input; + grain += input * price; + } +} + +void feed (void) { + do { + printf ("How many bushels do you wish to feed your people? "); + scanf ("%d", &food); + if (food < 0) resign (); + if (food > grain) SHORT_GRAIN_MSG; + } while (food > grain); +} + +void farm (void) { + int input, v; + + do { + v = 1; + printf ("How many acres do you wish to plant with seed? "); + scanf ("%d", &input); + if (input < 0) resign (); + else if (input > acres) {SHORT_LAND_MSG; v = 0;} + else if (input / 2 > grain) {SHORT_GRAIN_MSG; v = 0;} + else if (input > 10 * pop) { + printf ("But you only have %d people to tend the fields! Now then,\n" + , pop); + v = 0; + } + } while (!v); + grain -= input / 2; + yield = rand () % 5 + 1; + rats = rand () % 5 + 1; + rats = (rats % 2) ? grain / rats : 0; + grain += input * yield - rats; +} + +int main (void) { + int cstarved = 0; + int cps = 0; + + srand (time (NULL)); + printf ("Hamurabi\n\n" + "Try your hand at governing ancient summeria for a ten-year term of office."); + pop = 100; + grain = 2800; + yield = 3; + rats = 200; + acres = 1000; + born = 5; + for (year = 1; year <= 10 && starved < pop * 45 / 100; year ++){ + report (); + buysell (); + feed (); + farm (); + born = ((rand () % 5 + 1) * (20 * acres + grain) / pop / 100) + 1; + starved = (pop < food / 20) ? 0 : pop - food / 20; + pop += born - starved; + cstarved += starved; + cps += starved * 100 / pop; + } + if (starved >= pop * 45 / 100) { + printf ("\nYou starved %d people in one year!!!\n", starved); + endgame (0); + } else { + year--; + report (); + cps /= 10; + printf ("In your 10-year term of office %d%% of the people died per year\n" + "on the average, IE a total of %d people died!\n", cps, cstarved); + acres /= pop; + printf ("You started with 10 acres per person and ended with %d acres per\n" + "person.\n\n", acres); + endgame ((cps<34 && acres>6)+(cps<11 && acres>8)+(cps<4 && acres>9)); + } + exit (0); +} + diff --git a/pool/shard004/C/0101047_gstomx_h264enc.c b/pool/shard004/C/0101047_gstomx_h264enc.c new file mode 100644 index 0000000000000000000000000000000000000000..42cad1e7db5419ace983b3b6c78c2ecb445c3b74 --- /dev/null +++ b/pool/shard004/C/0101047_gstomx_h264enc.c @@ -0,0 +1,163 @@ +/* + * Copyright (C) 2007-2009 Nokia Corporation. + * + * Author: Felipe Contreras + * + * 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 "gstomx_h264enc.h" +#include "gstomx.h" + +#include /* For calloc, free */ + +#define OMX_COMPONENT_NAME "OMX.st.video_encoder.avc" + +static GstOmxBaseFilterClass *parent_class = NULL; + +static GstCaps * +generate_src_template (void) +{ + GstCaps *caps; + + caps = gst_caps_new_simple ("video/x-h264", + "width", GST_TYPE_INT_RANGE, 16, 4096, + "height", GST_TYPE_INT_RANGE, 16, 4096, + "framerate", GST_TYPE_FRACTION_RANGE, 0, 1, 30, 1, NULL); + + return caps; +} + +static void +type_base_init (gpointer g_class) +{ + GstElementClass *element_class; + GstOmxBaseFilterClass *omx_base_class; + + omx_base_class = GST_OMX_BASE_FILTER_CLASS (g_class); + element_class = GST_ELEMENT_CLASS (g_class); + + { + GstElementDetails details; + + details.longname = "OpenMAX IL H.264/AVC video encoder"; + details.klass = "Codec/Encoder/Video"; + details.description = "Encodes video in H.264/AVC format with OpenMAX IL"; + details.author = "Felipe Contreras"; + + gst_element_class_set_details (element_class, &details); + } + + { + GstPadTemplate *template; + + template = gst_pad_template_new ("src", GST_PAD_SRC, + GST_PAD_ALWAYS, generate_src_template ()); + + gst_element_class_add_pad_template (element_class, template); + } +} + +static void +type_class_init (gpointer g_class, gpointer class_data) +{ + parent_class = g_type_class_ref (GST_OMX_BASE_FILTER_TYPE); +} + +static void +settings_changed_cb (GOmxCore * core) +{ + GstOmxBaseFilter *omx_base; + guint width; + guint height; + guint framerate; + + omx_base = core->client_data; + + GST_DEBUG_OBJECT (omx_base, "settings changed"); + + { + OMX_PARAM_PORTDEFINITIONTYPE *param; + + param = calloc (1, sizeof (OMX_PARAM_PORTDEFINITIONTYPE)); + + param->nSize = sizeof (OMX_PARAM_PORTDEFINITIONTYPE); + param->nVersion.s.nVersionMajor = 1; + param->nVersion.s.nVersionMinor = 1; + + param->nPortIndex = 1; + OMX_GetParameter (omx_base->gomx->omx_handle, OMX_IndexParamPortDefinition, + param); + + width = param->format.video.nFrameWidth; + height = param->format.video.nFrameHeight; + framerate = param->format.video.xFramerate; + + free (param); + } + + { + GstCaps *new_caps; + + new_caps = gst_caps_new_simple ("video/x-h264", + "width", G_TYPE_INT, width, + "height", G_TYPE_INT, height, + "framerate", GST_TYPE_FRACTION, framerate, 1, NULL); + + GST_INFO_OBJECT (omx_base, "caps are: %" GST_PTR_FORMAT, new_caps); + gst_pad_set_caps (omx_base->srcpad, new_caps); + } +} + +static void +type_instance_init (GTypeInstance * instance, gpointer g_class) +{ + GstOmxBaseFilter *omx_base_filter; + GstOmxBaseVideoEnc *omx_base; + + omx_base_filter = GST_OMX_BASE_FILTER (instance); + omx_base = GST_OMX_BASE_VIDEOENC (instance); + + omx_base_filter->omx_component = g_strdup (OMX_COMPONENT_NAME); + omx_base->compression_format = OMX_VIDEO_CodingAVC; + + omx_base_filter->gomx->settings_changed_cb = settings_changed_cb; +} + +GType +gst_omx_h264enc_get_type (void) +{ + static GType type = 0; + + if (G_UNLIKELY (type == 0)) { + GTypeInfo *type_info; + + type_info = g_new0 (GTypeInfo, 1); + type_info->class_size = sizeof (GstOmxH264EncClass); + type_info->base_init = type_base_init; + type_info->class_init = type_class_init; + type_info->instance_size = sizeof (GstOmxH264Enc); + type_info->instance_init = type_instance_init; + + type = + g_type_register_static (GST_OMX_BASE_VIDEOENC_TYPE, "GstOmxH264Enc", + type_info, 0); + + g_free (type_info); + } + + return type; +} diff --git a/pool/shard004/C/0101049_kill_client.c b/pool/shard004/C/0101049_kill_client.c new file mode 100644 index 0000000000000000000000000000000000000000..5b97805321ec99c653252e8aeb832b699e53fc5f --- /dev/null +++ b/pool/shard004/C/0101049_kill_client.c @@ -0,0 +1,28 @@ +#include +#include +#include + +#include "log.h" +#include "zwm.h" + +extern Wm wm; + +void kill_client(__attribute__((unused))const Arg *arg) +{ + Workspace *cur = &wm.workspaces[wm.cwrksp]; + t_list *clients = &cur->windows; + Client *focus = cur->focus; + + if (focus != NULL) + { + if (focus->self.next != NULL) + cur->focus = focus->self.next->data; + else if (clients->size > 0) + cur->focus = clients->head->data; + unmap_window(&wm, focus); + XKillClient(wm.dpy, focus->win); + remove_window(&wm, focus); + XSync(wm.dpy, False); + draw(&wm); + } +} diff --git a/pool/shard004/C/0101068_mu_load_input.c b/pool/shard004/C/0101068_mu_load_input.c new file mode 100644 index 0000000000000000000000000000000000000000..f5662bb086a9492febaeec7fdcb4b262fe84946e --- /dev/null +++ b/pool/shard004/C/0101068_mu_load_input.c @@ -0,0 +1,184 @@ +/**************************************************************** + * * + * Copyright 2001 Sanchez Computer Associates, Inc. * + * * + * This source code contains the intellectual property * + * of its copyright holder(s), and is made available * + * under a license. If you do not know the terms of * + * the license, please stop and do not read further. * + * * + ****************************************************************/ + +#include "mdef.h" + +#include "gtm_fcntl.h" +#include "gtm_string.h" +#include +#include + +#include "gtm_stdio.h" +#include "io.h" +#include "iormdef.h" +#include "iosp.h" +#include "copy.h" +#include "error.h" +#include "gtmio.h" +#include "io_params.h" +#include "gtm_stat.h" +#include "op.h" +#include "mu_load_input.h" + +#define BUFF_SIZE 65536 + +static char *buff1_ptr; +static char *buff1_end; +static char buff1[BUFF_SIZE]; +static int load_fn_len; +static char *load_fn_ptr; +GBLREF io_pair io_curr_device; +GBLREF int (*op_open_ptr)(mval *v, mval *p, int t, mval *mspace); + + +void mu_load_init(char *fn, short fn_len) +{ + mval val; + mval pars; + static readonly unsigned char open_params_list[3] = + { + (unsigned char)iop_readonly, + (unsigned char)iop_rewind, + (unsigned char)iop_eol + }; + + error_def(ERR_LOADFILERR); + + ESTABLISH(mupip_load_ch); + pars.mvtype = MV_STR; + pars.str.len = sizeof(open_params_list); + pars.str.addr = (char *)open_params_list; + val.mvtype = MV_STR; + val.str.len = fn_len; + val.str.addr = (char *)fn; + (*op_open_ptr)(&val, &pars, 0, 0); + op_use(&val, &pars); + load_fn_ptr = fn; + load_fn_len = fn_len; + buff1_ptr = buff1; + buff1_end = buff1; + REVERT; + return; +} + +void mu_load_close(void) +{ + mval val; + mval pars; + unsigned char no_param = (unsigned char)iop_eol; + + val.mvtype = pars.mvtype = MV_STR; + val.str.addr = (char *)load_fn_ptr; + val.str.len = load_fn_len; + pars.str.len = sizeof(iop_eol); + pars.str.addr = (char *)&no_param; + op_close(&val, &pars); +} + +short mu_bin_get(char **in_ptr) +{ + short s1s; + int s1; + int rd_len, ret_len; + char *ptr; + + error_def(ERR_PREMATEOF); + error_def(ERR_LOADFILERR); + + ESTABLISH_RET(mupip_load_ch, 0); + if (buff1_end - buff1_ptr < sizeof(short)) + { + if ((rd_len = mu_bin_read()) <= 0) + { + if (buff1_end != buff1_ptr) + rts_error(VARLSTCNT(1) ERR_PREMATEOF); + else if (-1 == rd_len) + rts_error(VARLSTCNT(4) ERR_LOADFILERR, 2, load_fn_len, load_fn_ptr); + else + { + REVERT; + return 0; + } + } + buff1_end += rd_len; + } + GET_SHORT(s1s, buff1_ptr); + buff1_ptr += sizeof(short); + s1 = s1s; + if (buff1_end - buff1_ptr < s1) + { + /* not enough data in buffer, read additional bytes */ + rd_len = mu_bin_read(); + if (rd_len + (buff1_end - buff1_ptr) < s1) + { + if (-1 == rd_len) + rts_error(VARLSTCNT(4) ERR_LOADFILERR, 2, load_fn_len, load_fn_ptr); + rts_error(VARLSTCNT(1) ERR_PREMATEOF); + } + buff1_end += rd_len; + } + *in_ptr = buff1_ptr; + buff1_ptr += s1; + REVERT; + return s1; +} + +int mu_bin_read(void) +{ + int s1, rdlen; + io_desc *iod; + d_rm_struct *d_rm; + + s1 = buff1_end - buff1_ptr; + memmove(buff1, buff1_ptr, s1); + buff1_end = buff1 + s1; + buff1_ptr = buff1; + iod = io_curr_device.in; + d_rm = (d_rm_struct *)iod->dev_sp; + assert(NULL != d_rm); + DOREADRL(d_rm->fildes, buff1_end, BUFF_SIZE - s1, rdlen); + return rdlen; +} + +short mu_load_get(char **in_ptr) +{ + int s1; + int rd_len, ret_len; + char *ptr; + + mval val; + + error_def(ERR_PREMATEOF); + error_def(ERR_LOADFILERR); + + ESTABLISH_RET(mupip_load_ch, 0); + buff1_ptr = buff1_end = buff1; + for (;;) + { + op_read(&val, 0); + if (!val.str.len && io_curr_device.in->dollar.zeof) + { + REVERT; + if (io_curr_device.in->dollar.x) + rts_error(VARLSTCNT(1) ERR_PREMATEOF); + return -1; + } + memcpy(buff1_end, val.str.addr, val.str.len); + buff1_end = buff1_end + val.str.len; + if ( !(io_curr_device.in->dollar.x) ) + { + *in_ptr = buff1_ptr; + ret_len = buff1_end - buff1_ptr; + REVERT; + return ret_len; + } + } +} diff --git a/pool/shard004/C/0101069_ntgroups.c b/pool/shard004/C/0101069_ntgroups.c new file mode 100644 index 0000000000000000000000000000000000000000..447dc8254f6a0a5854475c139868acb0406f568f --- /dev/null +++ b/pool/shard004/C/0101069_ntgroups.c @@ -0,0 +1,175 @@ +/* + * Copyright (C) 2001, 2004, 2006, 2007, 2009, 2013, 2016 Internet Systems Consortium, Inc. ("ISC") + * + * 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/. + */ + +/* $Id: ntgroups.c,v 1.12 2009/09/29 23:48:04 tbox Exp $ */ + +/* + * The NT Groups have two groups that are not well documented and are + * not normally seen: None and Everyone. A user account belongs to + * any number of groups, but if it is not a member of any group then + * it is a member of the None Group. The None group is not listed + * anywhere. You cannot remove an account from the none group except + * by making it a member of some other group, The second group is the + * Everyone group. All accounts, no matter how many groups that they + * belong to, also belong to the Everyone group. You cannot remove an + * account from the Everyone group. + */ + +#ifndef UNICODE +#define UNICODE +#endif /* UNICODE */ + +/* + * Silence warnings. + */ +#define _CRT_SECURE_NO_DEPRECATE 1 + +#include +#include +#include + +#include +#include + +#define MAX_NAME_LENGTH 256 + +isc_result_t +isc_ntsecurity_getaccountgroups(char *username, char **GroupList, + unsigned int maxgroups, + unsigned int *totalGroups) { + LPGROUP_USERS_INFO_0 pTmpBuf; + LPLOCALGROUP_USERS_INFO_0 pTmpLBuf; + DWORD i; + LPLOCALGROUP_USERS_INFO_0 pBuf = NULL; + LPGROUP_USERS_INFO_0 pgrpBuf = NULL; + DWORD dwLevel = 0; + DWORD dwFlags = LG_INCLUDE_INDIRECT; + DWORD dwPrefMaxLen = MAX_PREFERRED_LENGTH; + DWORD dwEntriesRead = 0; + DWORD dwTotalEntries = 0; + NET_API_STATUS nStatus; + size_t retlen; + wchar_t user[MAX_NAME_LENGTH]; + + retlen = mbstowcs(user, username, MAX_NAME_LENGTH); + + *totalGroups = 0; + /* + * Call the NetUserGetLocalGroups function + * specifying information level 0. + * + * The LG_INCLUDE_INDIRECT flag specifies that the + * function should also return the names of the local + * groups in which the user is indirectly a member. + */ + nStatus = NetUserGetLocalGroups(NULL, + user, + dwLevel, + dwFlags, + (LPBYTE *) &pBuf, + dwPrefMaxLen, + &dwEntriesRead, + &dwTotalEntries); + /* + * See if the call succeeds, + */ + if (nStatus != NERR_Success) { + if (nStatus == ERROR_ACCESS_DENIED) + return (ISC_R_NOPERM); + if (nStatus == ERROR_MORE_DATA) + return (ISC_R_NOSPACE); + if (nStatus == NERR_UserNotFound) + dwEntriesRead = 0; + } + + if (pBuf != NULL) { + pTmpLBuf = pBuf; + /* + * Loop through the entries + */ + for (i = 0; + (i < dwEntriesRead && *totalGroups < maxgroups); i++) { + assert(pTmpLBuf != NULL); + if (pTmpLBuf == NULL) + break; + retlen = wcslen(pTmpLBuf->lgrui0_name); + GroupList[*totalGroups] = (char *) malloc(retlen +1); + if (GroupList[*totalGroups] == NULL) + return (ISC_R_NOMEMORY); + + retlen = wcstombs(GroupList[*totalGroups], + pTmpLBuf->lgrui0_name, retlen); + GroupList[*totalGroups][retlen] = '\0'; + if (strcmp(GroupList[*totalGroups], "None") == 0) + free(GroupList[*totalGroups]); + else + (*totalGroups)++; + pTmpLBuf++; + } + } + /* Free the allocated memory. */ + if (pBuf != NULL) + NetApiBufferFree(pBuf); + + + /* + * Call the NetUserGetGroups function, specifying level 0. + */ + nStatus = NetUserGetGroups(NULL, + user, + dwLevel, + (LPBYTE*)&pgrpBuf, + dwPrefMaxLen, + &dwEntriesRead, + &dwTotalEntries); + /* + * See if the call succeeds, + */ + if (nStatus != NERR_Success) { + if (nStatus == ERROR_ACCESS_DENIED) + return (ISC_R_NOPERM); + if (nStatus == ERROR_MORE_DATA) + return (ISC_R_NOSPACE); + if (nStatus == NERR_UserNotFound) + dwEntriesRead = 0; + } + + if (pgrpBuf != NULL) { + pTmpBuf = pgrpBuf; + /* + * Loop through the entries + */ + for (i = 0; + (i < dwEntriesRead && *totalGroups < maxgroups); i++) { + assert(pTmpBuf != NULL); + + if (pTmpBuf == NULL) + break; + retlen = wcslen(pTmpBuf->grui0_name); + GroupList[*totalGroups] = (char *) malloc(retlen +1); + if (GroupList[*totalGroups] == NULL) + return (ISC_R_NOMEMORY); + + retlen = wcstombs(GroupList[*totalGroups], + pTmpBuf->grui0_name, retlen); + GroupList[*totalGroups][retlen] = '\0'; + if (strcmp(GroupList[*totalGroups], "None") == 0) + free(GroupList[*totalGroups]); + else + (*totalGroups)++; + pTmpBuf++; + } + } + /* + * Free the allocated memory. + */ + if (pgrpBuf != NULL) + NetApiBufferFree(pgrpBuf); + + return (ISC_R_SUCCESS); +} diff --git a/pool/shard004/C/0101075_power.c b/pool/shard004/C/0101075_power.c new file mode 100644 index 0000000000000000000000000000000000000000..ecfa3c2ac93ae0a9a44d5b6d212713e4f7a777e7 --- /dev/null +++ b/pool/shard004/C/0101075_power.c @@ -0,0 +1,333 @@ +/* + * BRIEF MODULE DESCRIPTION + * Au1000 Power Management routines. + * + * Copyright 2001 MontaVista Software Inc. + * Author: MontaVista Software, Inc. + * ppopov@mvista.com or source@mvista.com + * + * Some of the routines are right out of init/main.c, whose + * copyrights apply here. + * + * 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 + +#define DEBUG 1 +#ifdef DEBUG +# define DPRINTK(fmt, args...) printk("%s: " fmt, __FUNCTION__ , ## args) +#else +# define DPRINTK(fmt, args...) +#endif + +extern void au1k_wait(void); +static void calibrate_delay(void); + +extern void set_au1000_speed(unsigned int new_freq); +extern unsigned int get_au1000_speed(void); +extern unsigned long get_au1000_uart_baud_base(void); +extern void set_au1000_uart_baud_base(unsigned long new_baud_base); +extern unsigned long save_local_and_disable(int controller); +extern void restore_local_and_enable(int controller, unsigned long mask); +extern void local_enable_irq(unsigned int irq_nr); + +/* Quick acpi hack. This will have to change! */ +#define CTL_ACPI 9999 +#define ACPI_S1_SLP_TYP 19 +#define ACPI_SLEEP 21 + +#ifdef CONFIG_PM + +static spinlock_t pm_lock = SPIN_LOCK_UNLOCKED; + +unsigned long suspend_mode; + +void wakeup_from_suspend(void) +{ + suspend_mode = 0; +} + +int au_sleep(void) +{ + unsigned long wakeup, flags; + spin_lock_irqsave(&pm_lock,flags); + + flush_cache_all(); + /* pin 6 is gpio */ + au_writel(au_readl(SYS_PINSTATERD) & ~(1 << 11), SYS_PINSTATERD); + + /* gpio 6 can cause a wake up event */ + wakeup = au_readl(SYS_WAKEMSK); + wakeup &= ~(1 << 8); /* turn off match20 wakeup */ + wakeup |= 1 << 6; /* turn on gpio 6 wakeup */ + au_writel(wakeup, SYS_WAKEMSK); + + au_writel(1, SYS_WAKESRC); /* clear cause */ + au_writel(1, SYS_SLPPWR); /* prepare to sleep */ + + __asm__("la $4, 1f\n\t" + "lui $5, 0xb190\n\t" + "ori $5, 0x18\n\t" + "sw $4, 0($5)\n\t" + "li $4, 1\n\t" + "lui $5, 0xb190\n\t" + "ori $5, 0x7c\n\t" + "sw $4, 0($5)\n\t" "sync\n\t" "1:\t\n\t" "nop\n\t"); + + /* after a wakeup, the cpu vectors back to 0x1fc00000 so + * it's up to the boot code to get us back here. + */ + spin_unlock_irqrestore(&pm_lock, flags); + return 0; +} + +static int pm_do_sleep(ctl_table * ctl, int write, struct file *file, + void *buffer, size_t * len) +{ + int retval = 0; + + if (!write) { + *len = 0; + } else { + retval = pm_send_all(PM_SUSPEND, (void *) 2); + if (retval) + return retval; + + au_sleep(); + retval = pm_send_all(PM_RESUME, (void *) 0); + } + return retval; +} + +static int pm_do_suspend(ctl_table * ctl, int write, struct file *file, + void *buffer, size_t * len) +{ + int retval = 0; + + if (!write) { + *len = 0; + } else { + retval = pm_send_all(PM_SUSPEND, (void *) 2); + if (retval) + return retval; + suspend_mode = 1; + au1k_wait(); + retval = pm_send_all(PM_RESUME, (void *) 0); + } + return retval; +} + + +static int pm_do_freq(ctl_table * ctl, int write, struct file *file, + void *buffer, size_t * len) +{ + int retval = 0, i; + unsigned long val, pll; +#define TMPBUFLEN 64 +#define MAX_CPU_FREQ 396 + char buf[8], *p; + unsigned long flags, intc0_mask, intc1_mask; + unsigned long old_baud_base, old_cpu_freq, baud_rate, old_clk, + old_refresh; + unsigned long new_baud_base, new_cpu_freq, new_clk, new_refresh; + + spin_lock_irqsave(&pm_lock, flags); + if (!write) { + *len = 0; + } else { + /* Parse the new frequency */ + if (*len > TMPBUFLEN - 1) { + spin_unlock_irqrestore(&pm_lock, flags); + return -EFAULT; + } + if (copy_from_user(buf, buffer, *len)) { + spin_unlock_irqrestore(&pm_lock, flags); + return -EFAULT; + } + buf[*len] = 0; + p = buf; + val = simple_strtoul(p, &p, 0); + if (val > MAX_CPU_FREQ) { + spin_unlock_irqrestore(&pm_lock, flags); + return -EFAULT; + } + + pll = val / 12; + if ((pll > 33) || (pll < 7)) { /* 396 MHz max, 84 MHz min */ + /* revisit this for higher speed cpus */ + spin_unlock_irqrestore(&pm_lock, flags); + return -EFAULT; + } + + old_baud_base = get_au1000_uart_baud_base(); + old_cpu_freq = get_au1000_speed(); + + new_cpu_freq = pll * 12 * 1000000; + new_baud_base = (new_cpu_freq / 4) / 16; + set_au1000_speed(new_cpu_freq); + set_au1000_uart_baud_base(new_baud_base); + + old_refresh = au_readl(MEM_SDREFCFG) & 0x1ffffff; + new_refresh = + ((old_refresh * new_cpu_freq) / + old_cpu_freq) | (au_readl(MEM_SDREFCFG) & ~0x1ffffff); + + au_writel(pll, SYS_CPUPLL); + au_sync_delay(1); + au_writel(new_refresh, MEM_SDREFCFG); + au_sync_delay(1); + + for (i = 0; i < 4; i++) { + if (au_readl + (UART_BASE + UART_MOD_CNTRL + + i * 0x00100000) == 3) { + old_clk = + au_readl(UART_BASE + UART_CLK + + i * 0x00100000); + // baud_rate = baud_base/clk + baud_rate = old_baud_base / old_clk; + /* we won't get an exact baud rate and the error + * could be significant enough that our new + * calculation will result in a clock that will + * give us a baud rate that's too far off from + * what we really want. + */ + if (baud_rate > 100000) + baud_rate = 115200; + else if (baud_rate > 50000) + baud_rate = 57600; + else if (baud_rate > 30000) + baud_rate = 38400; + else if (baud_rate > 17000) + baud_rate = 19200; + else + (baud_rate = 9600); + // new_clk = new_baud_base/baud_rate + new_clk = new_baud_base / baud_rate; + au_writel(new_clk, + UART_BASE + UART_CLK + + i * 0x00100000); + au_sync_delay(10); + } + } + } + + + /* We don't want _any_ interrupts other than + * match20. Otherwise our calibrate_delay() + * calculation will be off, potentially a lot. + */ + intc0_mask = save_local_and_disable(0); + intc1_mask = save_local_and_disable(1); + local_enable_irq(AU1000_TOY_MATCH2_INT); + spin_unlock_irqrestore(&pm_lock, flags); + calibrate_delay(); + restore_local_and_enable(0, intc0_mask); + restore_local_and_enable(1, intc1_mask); + return retval; +} + + +static struct ctl_table pm_table[] = { + {ACPI_S1_SLP_TYP, "suspend", NULL, 0, 0600, NULL, &pm_do_suspend}, + {ACPI_SLEEP, "sleep", NULL, 0, 0600, NULL, &pm_do_sleep}, + {CTL_ACPI, "freq", NULL, 0, 0600, NULL, &pm_do_freq}, + {0} +}; + +static struct ctl_table pm_dir_table[] = { + {CTL_ACPI, "pm", NULL, 0, 0555, pm_table}, + {0} +}; + +/* + * Initialize power interface + */ +static int __init pm_init(void) +{ + register_sysctl_table(pm_dir_table, 1); + return 0; +} + +__initcall(pm_init); + + +/* + * This is right out of init/main.c + */ + +/* This is the number of bits of precision for the loops_per_jiffy. Each + bit takes on average 1.5/HZ seconds. This (like the original) is a little + better than 1% */ +#define LPS_PREC 8 + +static void calibrate_delay(void) +{ + unsigned long ticks, loopbit; + int lps_precision = LPS_PREC; + + loops_per_jiffy = (1 << 12); + + while (loops_per_jiffy <<= 1) { + /* wait for "start of" clock tick */ + ticks = jiffies; + while (ticks == jiffies) + /* nothing */ ; + /* Go .. */ + ticks = jiffies; + __delay(loops_per_jiffy); + ticks = jiffies - ticks; + if (ticks) + break; + } + +/* Do a binary approximation to get loops_per_jiffy set to equal one clock + (up to lps_precision bits) */ + loops_per_jiffy >>= 1; + loopbit = loops_per_jiffy; + while (lps_precision-- && (loopbit >>= 1)) { + loops_per_jiffy |= loopbit; + ticks = jiffies; + while (ticks == jiffies); + ticks = jiffies; + __delay(loops_per_jiffy); + if (jiffies != ticks) /* longer than 1 tick */ + loops_per_jiffy &= ~loopbit; + } +} + +void au1k_wait(void) +{ + __asm__("nop\n\t" "nop\n\t"); +} + +#endif /* CONFIG_PM */ diff --git a/pool/shard004/C/0101086_util-common.c b/pool/shard004/C/0101086_util-common.c new file mode 100644 index 0000000000000000000000000000000000000000..542dcfdea72ac06c59944a3544c9e5a66d494556 --- /dev/null +++ b/pool/shard004/C/0101086_util-common.c @@ -0,0 +1,205 @@ +/* + * util-common.c + * + * Copyright (c) 2006-2015 Pacman Development 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 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 "util-common.h" + + +/** Parse the basename of a program from a path. +* @param path path to parse basename from +* +* @return everything following the final '/' +*/ +const char *mbasename(const char *path) +{ + const char *last = strrchr(path, '/'); + if(last) { + return last + 1; + } + return path; +} + +/** Parse the dirname of a program from a path. +* The path returned should be freed. +* @param path path to parse dirname from +* +* @return everything preceding the final '/' +*/ +char *mdirname(const char *path) +{ + char *ret, *last; + + /* null or empty path */ + if(path == NULL || *path == '\0') { + return strdup("."); + } + + if((ret = strdup(path)) == NULL) { + return NULL; + } + + last = strrchr(ret, '/'); + + if(last != NULL) { + /* we found a '/', so terminate our string */ + if(last == ret) { + /* return "/" for root */ + last++; + } + *last = '\0'; + return ret; + } + + /* no slash found */ + free(ret); + return strdup("."); +} + +/** lstat wrapper that treats /path/dirsymlink/ the same as /path/dirsymlink. + * Linux lstat follows POSIX semantics and still performs a dereference on + * the first, and for uses of lstat in libalpm this is not what we want. + * @param path path to file to lstat + * @param buf structure to fill with stat information + * @return the return code from lstat + */ +int llstat(char *path, struct stat *buf) +{ + int ret; + char *c = NULL; + size_t len = strlen(path); + + while(len > 1 && path[len - 1] == '/') { + --len; + c = path + len; + } + + if(c) { + *c = '\0'; + ret = lstat(path, buf); + *c = '/'; + } else { + ret = lstat(path, buf); + } + + return ret; +} + +/** Wrapper around fgets() which properly handles EINTR + * @param s string to read into + * @param size maximum length to read + * @param stream stream to read from + * @return value returned by fgets() + */ +char *safe_fgets(char *s, int size, FILE *stream) +{ + char *ret; + int errno_save = errno, ferror_save = ferror(stream); + while((ret = fgets(s, size, stream)) == NULL && !feof(stream)) { + if(errno == EINTR) { + /* clear any errors we set and try again */ + errno = errno_save; + if(!ferror_save) { + clearerr(stream); + } + } else { + break; + } + } + return ret; +} + +/* Trim whitespace and newlines from a string + */ +size_t strtrim(char *str) +{ + char *end, *pch = str; + + if(str == NULL || *str == '\0') { + /* string is empty, so we're done. */ + return 0; + } + + while(isspace((unsigned char)*pch)) { + pch++; + } + if(pch != str) { + size_t len = strlen(pch); + if(len) { + memmove(str, pch, len + 1); + pch = str; + } else { + *str = '\0'; + } + } + + /* check if there wasn't anything but whitespace in the string. */ + if(*str == '\0') { + return 0; + } + + end = (str + strlen(str) - 1); + while(isspace((unsigned char)*end)) { + end--; + } + *++end = '\0'; + + return end - pch; +} + +#ifndef HAVE_STRNLEN +/* A quick and dirty implementation derived from glibc */ +/** Determines the length of a fixed-size string. + * @param s string to be measured + * @param max maximum number of characters to search for the string end + * @return length of s or max, whichever is smaller + */ +static size_t strnlen(const char *s, size_t max) +{ + register const char *p; + for(p = s; *p && max--; ++p); + return (p - s); +} +#endif + +#ifndef HAVE_STRNDUP +/** Copies a string. + * Returned string needs to be freed + * @param s string to be copied + * @param n maximum number of characters to copy + * @return pointer to the new string on success, NULL on error + */ +char *strndup(const char *s, size_t n) +{ + size_t len = strnlen(s, n); + char *new = (char *) malloc(len + 1); + + if(new == NULL) { + return NULL; + } + + new[len] = '\0'; + return (char *)memcpy(new, s, len); +} +#endif + +/* vim: set noet: */ diff --git a/pool/shard004/C/0101087_uart.c b/pool/shard004/C/0101087_uart.c new file mode 100644 index 0000000000000000000000000000000000000000..8d958a54e45e4f3583a74861c48ecec2d2cffc70 --- /dev/null +++ b/pool/shard004/C/0101087_uart.c @@ -0,0 +1,135 @@ +/* + * Copyright (C) 2014-2015 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 cpu_sam3 + * @{ + * + * @file + * @brief Low-level UART driver implementation + * + * @author Hauke Petersen + * + * @} + */ + +#include "cpu.h" +#include "board.h" +#include "sched.h" +#include "thread.h" +#include "periph/uart.h" + +#define ENABLE_DEBUG (0) +#include "debug.h" + +/** + * @brief Allocate memory to store the callback functions. + */ +static uart_isr_ctx_t ctx[UART_NUMOF]; + +int uart_init(uart_t uart, uint32_t baudrate, uart_rx_cb_t rx_cb, void *arg) +{ + Uart *dev; + + /* make sure given device is valid */ + if (uart >= UART_NUMOF) { + return -1; + } + + /* get base register */ + dev = uart_config[uart].dev; + + /* register callback */ + ctx[uart].rx_cb = rx_cb; + ctx[uart].arg = arg; + + /* enable clock */ + uart_poweron(uart); + + /* configure pins + TODO: optimize once GPIO refactoring is merged */ + uart_config[uart].rx_port->PIO_PDR = (1 << uart_config[uart].rx_pin); + uart_config[uart].rx_port->PIO_ABSR &= ~(1 << uart_config[uart].rx_pin); + uart_config[uart].tx_port->PIO_ABSR |= (uart_config[uart].mux << + uart_config[uart].rx_pin); + uart_config[uart].tx_port->PIO_PDR = (1 << uart_config[uart].tx_pin); + uart_config[uart].tx_port->PIO_ABSR &= ~(1 << uart_config[uart].tx_pin); + uart_config[uart].tx_port->PIO_ABSR |= (uart_config[uart].mux << + uart_config[uart].tx_pin); + + /* configure baud rate and set mode to 8N1 */ + dev->UART_BRGR = (CLOCK_CORECLOCK / (16 * baudrate)); + dev->UART_MR = UART_MR_PAR_NO | US_MR_CHRL_8_BIT; + dev->UART_CR = UART_CR_RXEN | UART_CR_TXEN | UART_CR_RSTSTA; + + /* enable RX interrupt */ + NVIC_EnableIRQ(uart_config[uart].irqn); + dev->UART_IER = UART_IER_RXRDY; + + return 0; +} + +void uart_write(uart_t uart, const uint8_t *data, size_t len) +{ + Uart *dev = uart_config[uart].dev; + + for (size_t i = 0; i < len; i++) { + while (!(dev->UART_SR & UART_SR_TXRDY)); + dev->UART_THR = data[i]; + } +} + +void uart_poweron(uart_t uart) +{ + PMC->PMC_PCER0 |= (1 << uart_config[uart].pmc_id); +} + +void uart_poweroff(uart_t uart) +{ + PMC->PMC_PCER0 &= ~(1 << uart_config[uart].pmc_id); +} + +static inline void isr_handler(int num) +{ + Uart *dev = uart_config[num].dev; + + if (dev->UART_SR & UART_SR_RXRDY) { + ctx[num].rx_cb(ctx[num].arg, (char)dev->UART_RHR); + } + if (sched_context_switch_request) { + thread_yield(); + } +} + +#ifdef UART_0_ISR +void UART_0_ISR(void) +{ + isr_handler(0); +} +#endif + +#ifdef UART_1_ISR +void UART_1_ISR(void) +{ + isr_handler(1); +} +#endif + +#ifdef UART_2_ISR +void UART_2_ISR(void) +{ + isr_handler(2); +} +#endif + +#ifdef UART_3_ISR +void UART_3_ISR(void) +{ + isr_handler(3); +} +#endif diff --git a/pool/shard004/C/0101090_main.c b/pool/shard004/C/0101090_main.c new file mode 100644 index 0000000000000000000000000000000000000000..cab03b262a0ab26ee99251fe3cc61cfcfebc6ed4 --- /dev/null +++ b/pool/shard004/C/0101090_main.c @@ -0,0 +1,51 @@ +#include "gorilla/ga.h" +#include "gorilla/gau.h" + +#include + +static void setFlagAndDestroyOnFinish(ga_Handle* in_handle, void* in_context) +{ + gc_int32* flag = (gc_int32*)(in_context); + *flag = 1; + ga_handle_destroy(in_handle); +} +int main(int argc, char** argv) +{ + gau_Manager* mgr; + ga_Mixer* mixer; + ga_Sound* sound; + ga_Handle* handle; + gau_SampleSourceLoop* loopSrc = 0; + gau_SampleSourceLoop** pLoopSrc = &loopSrc; + gc_int32 loop = 0; + gc_int32 quit = 0; + + /* Initialize library + manager */ + gc_initialize(0); + mgr = gau_manager_create(); + mixer = gau_manager_mixer(mgr); + + /* Create and play shared sound */ + if(!loop) + pLoopSrc = 0; + sound = gau_load_sound_file("test.wav", "wav"); + handle = gau_create_handle_sound(mixer, sound, &setFlagAndDestroyOnFinish, &quit, pLoopSrc); + ga_handle_play(handle); + + /* Bounded mix/queue/dispatch loop */ + while(!quit) + { + gau_manager_update(mgr); + printf("%d / %d\n", ga_handle_tell(handle, GA_TELL_PARAM_CURRENT), ga_handle_tell(handle, GA_TELL_PARAM_TOTAL)); + gc_thread_sleep(1); + } + + /* Clean up sound */ + ga_sound_release(sound); + + /* Clean up library + manager */ + gau_manager_destroy(mgr); + gc_shutdown(); + + return 0; +} diff --git a/pool/shard004/C/0101095_quick_sort.c b/pool/shard004/C/0101095_quick_sort.c new file mode 100644 index 0000000000000000000000000000000000000000..9cd6047cdd9f007c23bc49ba751721e6edb7b6d5 --- /dev/null +++ b/pool/shard004/C/0101095_quick_sort.c @@ -0,0 +1,43 @@ +#include "quick_sort.h" + +static void swap(int* i, int* j) { + int temp = *i; + *i = *j; + *j = temp; +} + +static size_t partition(int array[], size_t low, size_t high) { + size_t middle = low + (high - low) / 2; + int pivot = array[middle]; + size_t i = low - 1; + size_t j = high + 1; + while (1) { + do { + ++i; + } while (array[i] < pivot); + do { + --j; + } while (array[j] > pivot); + if (i >= j) { + return j; + } + swap(array + i, array + j); + } +} + +static void quick_sort_internal(int array[], size_t low, size_t high) { + if (low >= high) { + return; + } + size_t index = partition(array, low, high); + quick_sort_internal(array, low, index); + quick_sort_internal(array, index + 1, high); +} + +void quick_sort(int array[], size_t length) { + if (length == 0) { + return; + } + + quick_sort_internal(array, 0, length - 1); +} diff --git a/pool/shard004/C/0101097_emac-sgmii-qdf2400.c b/pool/shard004/C/0101097_emac-sgmii-qdf2400.c new file mode 100644 index 0000000000000000000000000000000000000000..f62c215be779853ad76cf71f02b09dc4f7d62a1a --- /dev/null +++ b/pool/shard004/C/0101097_emac-sgmii-qdf2400.c @@ -0,0 +1,217 @@ +/* Copyright (c) 2015-2016, 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. + */ + +/* Qualcomm Technologies, Inc. QDF2400 EMAC SGMII Controller driver. + */ + +#include +#include "emac.h" + +/* EMAC_SGMII register offsets */ +#define EMAC_SGMII_PHY_TX_PWR_CTRL 0x000C +#define EMAC_SGMII_PHY_LANE_CTRL1 0x0018 +#define EMAC_SGMII_PHY_CDR_CTRL0 0x0058 +#define EMAC_SGMII_PHY_POW_DWN_CTRL0 0x0080 +#define EMAC_SGMII_PHY_RESET_CTRL 0x00a8 +#define EMAC_SGMII_PHY_INTERRUPT_MASK 0x00b4 + +/* SGMII digital lane registers */ +#define EMAC_SGMII_LN_DRVR_CTRL0 0x000C +#define EMAC_SGMII_LN_DRVR_TAP_EN 0x0018 +#define EMAC_SGMII_LN_TX_MARGINING 0x001C +#define EMAC_SGMII_LN_TX_PRE 0x0020 +#define EMAC_SGMII_LN_TX_POST 0x0024 +#define EMAC_SGMII_LN_TX_BAND_MODE 0x0060 +#define EMAC_SGMII_LN_LANE_MODE 0x0064 +#define EMAC_SGMII_LN_PARALLEL_RATE 0x007C +#define EMAC_SGMII_LN_CML_CTRL_MODE0 0x00C0 +#define EMAC_SGMII_LN_MIXER_CTRL_MODE0 0x00D8 +#define EMAC_SGMII_LN_VGA_INITVAL 0x013C +#define EMAC_SGMII_LN_UCDR_FO_GAIN_MODE0 0x0184 +#define EMAC_SGMII_LN_UCDR_SO_GAIN_MODE0 0x0190 +#define EMAC_SGMII_LN_UCDR_SO_CONFIG 0x019C +#define EMAC_SGMII_LN_RX_BAND 0x01A4 +#define EMAC_SGMII_LN_RX_RCVR_PATH1_MODE0 0x01C0 +#define EMAC_SGMII_LN_RSM_CONFIG 0x01F8 +#define EMAC_SGMII_LN_SIGDET_ENABLES 0x0230 +#define EMAC_SGMII_LN_SIGDET_CNTRL 0x0234 +#define EMAC_SGMII_LN_SIGDET_DEGLITCH_CNTRL 0x0238 +#define EMAC_SGMII_LN_RX_EN_SIGNAL 0x02AC +#define EMAC_SGMII_LN_RX_MISC_CNTRL0 0x02B8 +#define EMAC_SGMII_LN_DRVR_LOGIC_CLKDIV 0x02C8 + +/* SGMII digital lane register values */ +#define UCDR_STEP_BY_TWO_MODE0 BIT(7) +#define UCDR_xO_GAIN_MODE(x) ((x) & 0x7f) +#define UCDR_ENABLE BIT(6) +#define UCDR_SO_SATURATION(x) ((x) & 0x3f) + +#define SIGDET_LP_BYP_PS4 BIT(7) +#define SIGDET_EN_PS0_TO_PS2 BIT(6) + +#define TXVAL_VALID_INIT BIT(4) +#define KR_PCIGEN3_MODE BIT(0) + +#define MAIN_EN BIT(0) + +#define TX_MARGINING_MUX BIT(6) +#define TX_MARGINING(x) ((x) & 0x3f) + +#define TX_PRE_MUX BIT(6) + +#define TX_POST_MUX BIT(6) + +#define CML_GEAR_MODE(x) (((x) & 7) << 3) +#define CML2CMOS_IBOOST_MODE(x) ((x) & 7) + +#define MIXER_LOADB_MODE(x) (((x) & 0xf) << 2) +#define MIXER_DATARATE_MODE(x) ((x) & 3) + +#define VGA_THRESH_DFE(x) ((x) & 0x3f) + +#define SIGDET_LP_BYP_PS0_TO_PS2 BIT(5) +#define SIGDET_FLT_BYP BIT(0) + +#define SIGDET_LVL(x) (((x) & 0xf) << 4) + +#define SIGDET_DEGLITCH_CTRL(x) (((x) & 0xf) << 1) + +#define INVERT_PCS_RX_CLK BIT(7) + +#define DRVR_LOGIC_CLK_EN BIT(4) +#define DRVR_LOGIC_CLK_DIV(x) ((x) & 0xf) + +#define PARALLEL_RATE_MODE0(x) ((x) & 0x3) + +#define BAND_MODE0(x) ((x) & 0x3) + +#define LANE_MODE(x) ((x) & 0x1f) + +#define CDR_PD_SEL_MODE0(x) (((x) & 0x3) << 5) +#define EN_DLL_MODE0 BIT(4) +#define EN_IQ_DCC_MODE0 BIT(3) +#define EN_IQCAL_MODE0 BIT(2) + +#define BYPASS_RSM_SAMP_CAL BIT(1) +#define BYPASS_RSM_DLL_CAL BIT(0) + +#define L0_RX_EQUALIZE_ENABLE BIT(6) + +#define PWRDN_B BIT(0) + +#define CDR_MAX_CNT(x) ((x) & 0xff) + +#define SERDES_START_WAIT_TIMES 100 + +struct emac_reg_write { + unsigned int offset; + u32 val; +}; + +static void emac_reg_write_all(void __iomem *base, + const struct emac_reg_write *itr, size_t size) +{ + size_t i; + + for (i = 0; i < size; ++itr, ++i) + writel(itr->val, base + itr->offset); +} + +static const struct emac_reg_write sgmii_laned[] = { + /* CDR Settings */ + {EMAC_SGMII_LN_UCDR_FO_GAIN_MODE0, + UCDR_STEP_BY_TWO_MODE0 | UCDR_xO_GAIN_MODE(10)}, + {EMAC_SGMII_LN_UCDR_SO_GAIN_MODE0, UCDR_xO_GAIN_MODE(0)}, + {EMAC_SGMII_LN_UCDR_SO_CONFIG, UCDR_ENABLE | UCDR_SO_SATURATION(12)}, + + /* TX/RX Settings */ + {EMAC_SGMII_LN_RX_EN_SIGNAL, SIGDET_LP_BYP_PS4 | SIGDET_EN_PS0_TO_PS2}, + + {EMAC_SGMII_LN_DRVR_CTRL0, TXVAL_VALID_INIT | KR_PCIGEN3_MODE}, + {EMAC_SGMII_LN_DRVR_TAP_EN, MAIN_EN}, + {EMAC_SGMII_LN_TX_MARGINING, TX_MARGINING_MUX | TX_MARGINING(25)}, + {EMAC_SGMII_LN_TX_PRE, TX_PRE_MUX}, + {EMAC_SGMII_LN_TX_POST, TX_POST_MUX}, + + {EMAC_SGMII_LN_CML_CTRL_MODE0, + CML_GEAR_MODE(1) | CML2CMOS_IBOOST_MODE(1)}, + {EMAC_SGMII_LN_MIXER_CTRL_MODE0, + MIXER_LOADB_MODE(12) | MIXER_DATARATE_MODE(1)}, + {EMAC_SGMII_LN_VGA_INITVAL, VGA_THRESH_DFE(31)}, + {EMAC_SGMII_LN_SIGDET_ENABLES, + SIGDET_LP_BYP_PS0_TO_PS2 | SIGDET_FLT_BYP}, + {EMAC_SGMII_LN_SIGDET_CNTRL, SIGDET_LVL(8)}, + + {EMAC_SGMII_LN_SIGDET_DEGLITCH_CNTRL, SIGDET_DEGLITCH_CTRL(4)}, + {EMAC_SGMII_LN_RX_MISC_CNTRL0, INVERT_PCS_RX_CLK}, + {EMAC_SGMII_LN_DRVR_LOGIC_CLKDIV, + DRVR_LOGIC_CLK_EN | DRVR_LOGIC_CLK_DIV(4)}, + + {EMAC_SGMII_LN_PARALLEL_RATE, PARALLEL_RATE_MODE0(1)}, + {EMAC_SGMII_LN_TX_BAND_MODE, BAND_MODE0(1)}, + {EMAC_SGMII_LN_RX_BAND, BAND_MODE0(2)}, + {EMAC_SGMII_LN_LANE_MODE, LANE_MODE(26)}, + {EMAC_SGMII_LN_RX_RCVR_PATH1_MODE0, CDR_PD_SEL_MODE0(2) | + EN_DLL_MODE0 | EN_IQ_DCC_MODE0 | EN_IQCAL_MODE0}, + {EMAC_SGMII_LN_RSM_CONFIG, BYPASS_RSM_SAMP_CAL | BYPASS_RSM_DLL_CAL}, +}; + +static const struct emac_reg_write physical_coding_sublayer_programming[] = { + {EMAC_SGMII_PHY_POW_DWN_CTRL0, PWRDN_B}, + {EMAC_SGMII_PHY_CDR_CTRL0, CDR_MAX_CNT(15)}, + {EMAC_SGMII_PHY_TX_PWR_CTRL, 0}, + {EMAC_SGMII_PHY_LANE_CTRL1, L0_RX_EQUALIZE_ENABLE}, +}; + +int emac_sgmii_init_qdf2400(struct emac_adapter *adpt) +{ + struct emac_sgmii *phy = &adpt->phy; + void __iomem *phy_regs = phy->base; + void __iomem *laned = phy->digital; + unsigned int i; + u32 lnstatus; + + /* PCS lane-x init */ + emac_reg_write_all(phy->base, physical_coding_sublayer_programming, + ARRAY_SIZE(physical_coding_sublayer_programming)); + + /* SGMII lane-x init */ + emac_reg_write_all(phy->digital, sgmii_laned, ARRAY_SIZE(sgmii_laned)); + + /* Power up PCS and start reset lane state machine */ + + writel(0, phy_regs + EMAC_SGMII_PHY_RESET_CTRL); + writel(1, laned + SGMII_LN_RSM_START); + + /* Wait for c_ready assertion */ + for (i = 0; i < SERDES_START_WAIT_TIMES; i++) { + lnstatus = readl(phy_regs + SGMII_PHY_LN_LANE_STATUS); + if (lnstatus & BIT(1)) + break; + usleep_range(100, 200); + } + + if (i == SERDES_START_WAIT_TIMES) { + netdev_err(adpt->netdev, "SGMII failed to start\n"); + return -EIO; + } + + /* Disable digital and SERDES loopback */ + writel(0, phy_regs + SGMII_PHY_LN_BIST_GEN0); + writel(0, phy_regs + SGMII_PHY_LN_BIST_GEN2); + writel(0, phy_regs + SGMII_PHY_LN_CDR_CTRL1); + + /* Mask out all the SGMII Interrupt */ + writel(0, phy_regs + EMAC_SGMII_PHY_INTERRUPT_MASK); + + return 0; +} diff --git a/pool/shard004/C/0101098_HAPKBRDF.c b/pool/shard004/C/0101098_HAPKBRDF.c new file mode 100644 index 0000000000000000000000000000000000000000..fc5488cd7a66de4e4a6f6641b6c79b029e311f84 --- /dev/null +++ b/pool/shard004/C/0101098_HAPKBRDF.c @@ -0,0 +1,116 @@ +/* HAPKBRDF.f -- translated by f2c (version 19970805). + You must link the resulting object file with the libraries: + -lf2c -lm (in that order) +*/ + +#ifdef __cplusplus +extern "C" { +#endif +/* OTB patches: replace "f2c.h" by "otb_6S.h" */ +/*#include "f2c.h"*/ +#include "otb_6S.h" + +/* Table of constant values */ + +static doublereal c_b4 = 1.5; + +/*< >*/ +/* Subroutine */ int hapkbrdf_(doublereal *om, doublereal *af, doublereal *s0, + doublereal *h__, integer *mu, integer *np, doublereal *rm, + doublereal *rp, doublereal *brdfint) +{ + /* System generated locals */ + integer rm_offset, brdfint_dim1, brdfint_offset, i__1, i__2; + doublereal d__1; + + /* Builtin functions */ + double sqrt(doublereal), cos(doublereal), pow_dd(doublereal *, doublereal + *), acos(doublereal), tan(doublereal); + + /* Local variables */ + doublereal f, g; + integer j, k; + doublereal h1, h2, p0, bg, cg, fi, pg, mu1, mu2, h1h2; + +/*< integer mu,np,k,j >*/ +/*< real rm(-mu:mu),rp(np),brdfint(-mu:mu,np) >*/ +/*< real f,h1 >*/ +/*< real h2,h1h2,pg,p0,g,bg >*/ +/*< real mu1,mu2,fi,cg >*/ +/*< real om,af,s0,h >*/ +/* here the notation are taken according to j.g.r.,vol 95,no d8,pp 11767, +*/ +/* geometrical conditions: mu1 cosine of sun zenith angle */ +/* mu2 cosine of view zenith angle */ +/* fi: fi1-fi2 [radians] */ +/* cg: cos(g) */ +/* canopy parameters : om (albedo) */ +/* : af assymetry parameter for the phase function */ +/* : s0 amplitude of hot spot */ +/* : h width of the hot spot */ +/*< mu1=rm(0) >*/ + /* Parameter adjustments */ + rm_offset = -(*mu); + rm -= rm_offset; + brdfint_dim1 = *mu - (-(*mu)) + 1; + brdfint_offset = -(*mu) + brdfint_dim1; + brdfint -= brdfint_offset; + --rp; + + /* Function Body */ + mu1 = rm[0]; +/*< do 1 k=1,np >*/ + i__1 = *np; + for (k = 1; k <= i__1; ++k) { +/*< do 2 j=1,mu >*/ + i__2 = *mu; + for (j = 1; j <= i__2; ++j) { +/*< mu2=rm(j) >*/ + mu2 = rm[j]; +/*< if (j.eq.mu) then >*/ + if (j == *mu) { +/*< fi=rm(-mu) >*/ + fi = rm[-(*mu)]; +/*< else >*/ + } else { +/*< fi=rp(k)+rm(-mu) >*/ + fi = rp[k] + rm[-(*mu)]; +/*< endif >*/ + } +/*< cg=mu1*mu2+sqrt(1.-mu1*mu1)*sqrt(1.-mu2*mu2)*cos(fi) >*/ + cg = mu1 * mu2 + sqrt(1. - mu1 * mu1) * sqrt(1. - mu2 * mu2) * + cos(fi); +/*< f=om/4./(mu2+mu1) >*/ + f = *om / 4. / (mu2 + mu1); +/*< h1=(1.+2*mu1)/(1.+2.*sqrt(1.-om)*mu1) >*/ + h1 = (mu1 * 2 + 1.) / (sqrt(1. - *om) * 2. * mu1 + 1.); +/*< h2=(1.+2*mu2)/(1.+2.*sqrt(1.-om)*mu2) >*/ + h2 = (mu2 * 2 + 1.) / (sqrt(1. - *om) * 2. * mu2 + 1.); +/*< h1h2=h1*h2 >*/ + h1h2 = h1 * h2; +/*< pg=(1-af*af)/((1+af*af+2*af*cg)**1.5) >*/ + d__1 = *af * *af + 1 + *af * 2 * cg; + pg = (1 - *af * *af) / pow_dd(&d__1, &c_b4); +/*< p0=(1-af*af)/((1+af*af+2*af)**1.5) >*/ + d__1 = *af * *af + 1 + *af * 2; + p0 = (1 - *af * *af) / pow_dd(&d__1, &c_b4); +/*< g=acos(cg) >*/ + g = acos(cg); +/*< bg=(s0/(om*p0))/(1+tan(g/2.)/h) >*/ + bg = *s0 / (*om * p0) / (tan(g / 2.) / *h__ + 1); +/*< brdfint(j,k)=f*((1.+bg)*pg+h1h2-1.) >*/ + brdfint[j + k * brdfint_dim1] = f * ((bg + 1.) * pg + h1h2 - 1.); +/*< 2 continue >*/ +/* L2: */ + } +/*< 1 continue >*/ +/* L1: */ + } +/*< return >*/ + return 0; +/*< end >*/ +} /* hapkbrdf_ */ + +#ifdef __cplusplus + } +#endif diff --git a/pool/shard004/C/0101099_reset-meson-audio-arb.c b/pool/shard004/C/0101099_reset-meson-audio-arb.c new file mode 100644 index 0000000000000000000000000000000000000000..c53a2185a0393c689c631d7df7f1b760cb2b72e0 --- /dev/null +++ b/pool/shard004/C/0101099_reset-meson-audio-arb.c @@ -0,0 +1,169 @@ +// SPDX-License-Identifier: (GPL-2.0 OR MIT) +// Copyright (c) 2018 BayLibre, SAS. +// Author: Jerome Brunet + +#include +#include +#include +#include +#include +#include + +#include + +struct meson_audio_arb_data { + struct reset_controller_dev rstc; + void __iomem *regs; + struct clk *clk; + const unsigned int *reset_bits; + spinlock_t lock; +}; + +#define ARB_GENERAL_BIT 31 + +static const unsigned int axg_audio_arb_reset_bits[] = { + [AXG_ARB_TODDR_A] = 0, + [AXG_ARB_TODDR_B] = 1, + [AXG_ARB_TODDR_C] = 2, + [AXG_ARB_FRDDR_A] = 4, + [AXG_ARB_FRDDR_B] = 5, + [AXG_ARB_FRDDR_C] = 6, +}; + +static int meson_audio_arb_update(struct reset_controller_dev *rcdev, + unsigned long id, bool assert) +{ + u32 val; + struct meson_audio_arb_data *arb = + container_of(rcdev, struct meson_audio_arb_data, rstc); + + spin_lock(&arb->lock); + val = readl(arb->regs); + + if (assert) + val &= ~BIT(arb->reset_bits[id]); + else + val |= BIT(arb->reset_bits[id]); + + writel(val, arb->regs); + spin_unlock(&arb->lock); + + return 0; +} + +static int meson_audio_arb_status(struct reset_controller_dev *rcdev, + unsigned long id) +{ + u32 val; + struct meson_audio_arb_data *arb = + container_of(rcdev, struct meson_audio_arb_data, rstc); + + val = readl(arb->regs); + + return !(val & BIT(arb->reset_bits[id])); +} + +static int meson_audio_arb_assert(struct reset_controller_dev *rcdev, + unsigned long id) +{ + return meson_audio_arb_update(rcdev, id, true); +} + +static int meson_audio_arb_deassert(struct reset_controller_dev *rcdev, + unsigned long id) +{ + return meson_audio_arb_update(rcdev, id, false); +} + +static const struct reset_control_ops meson_audio_arb_rstc_ops = { + .assert = meson_audio_arb_assert, + .deassert = meson_audio_arb_deassert, + .status = meson_audio_arb_status, +}; + +static const struct of_device_id meson_audio_arb_of_match[] = { + { .compatible = "amlogic,meson-axg-audio-arb", }, + {} +}; +MODULE_DEVICE_TABLE(of, meson_audio_arb_of_match); + +static int meson_audio_arb_remove(struct platform_device *pdev) +{ + struct meson_audio_arb_data *arb = platform_get_drvdata(pdev); + + /* Disable all access */ + spin_lock(&arb->lock); + writel(0, arb->regs); + spin_unlock(&arb->lock); + + clk_disable_unprepare(arb->clk); + + return 0; +} + +static int meson_audio_arb_probe(struct platform_device *pdev) +{ + struct device *dev = &pdev->dev; + struct meson_audio_arb_data *arb; + struct resource *res; + int ret; + + arb = devm_kzalloc(dev, sizeof(*arb), GFP_KERNEL); + if (!arb) + return -ENOMEM; + platform_set_drvdata(pdev, arb); + + arb->clk = devm_clk_get(dev, NULL); + if (IS_ERR(arb->clk)) { + if (PTR_ERR(arb->clk) != -EPROBE_DEFER) + dev_err(dev, "failed to get clock\n"); + return PTR_ERR(arb->clk); + } + + res = platform_get_resource(pdev, IORESOURCE_MEM, 0); + arb->regs = devm_ioremap_resource(dev, res); + if (IS_ERR(arb->regs)) + return PTR_ERR(arb->regs); + + spin_lock_init(&arb->lock); + arb->reset_bits = axg_audio_arb_reset_bits; + arb->rstc.nr_resets = ARRAY_SIZE(axg_audio_arb_reset_bits); + arb->rstc.ops = &meson_audio_arb_rstc_ops; + arb->rstc.of_node = dev->of_node; + arb->rstc.owner = THIS_MODULE; + + /* + * Enable general : + * In the initial state, all memory interfaces are disabled + * and the general bit is on + */ + ret = clk_prepare_enable(arb->clk); + if (ret) { + dev_err(dev, "failed to enable arb clock\n"); + return ret; + } + writel(BIT(ARB_GENERAL_BIT), arb->regs); + + /* Register reset controller */ + ret = devm_reset_controller_register(dev, &arb->rstc); + if (ret) { + dev_err(dev, "failed to register arb reset controller\n"); + meson_audio_arb_remove(pdev); + } + + return ret; +} + +static struct platform_driver meson_audio_arb_pdrv = { + .probe = meson_audio_arb_probe, + .remove = meson_audio_arb_remove, + .driver = { + .name = "meson-audio-arb-reset", + .of_match_table = meson_audio_arb_of_match, + }, +}; +module_platform_driver(meson_audio_arb_pdrv); + +MODULE_DESCRIPTION("Amlogic A113 Audio Memory Arbiter"); +MODULE_AUTHOR("Jerome Brunet "); +MODULE_LICENSE("GPL v2"); diff --git a/pool/shard004/C/0101104_papi_l3_ldm.c b/pool/shard004/C/0101104_papi_l3_ldm.c new file mode 100644 index 0000000000000000000000000000000000000000..f57ea3b593b0545c716642fe6b7b1cac9a4d8864 --- /dev/null +++ b/pool/shard004/C/0101104_papi_l3_ldm.c @@ -0,0 +1,53 @@ +/* This code runs some sanity checks on the PAPI_L3_LDM */ +/* (L3 Load Misses) event. */ + +/* 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_L3_LDM 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_L3_LDM); + if (retval != PAPI_OK) { + if (!quiet) printf("PAPI_L3_LDM not available\n"); + test_skip(test_string); + } + + events[0]=PAPI_L3_LDM; + + 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/shard004/C/0101108_CWE127_Buffer_Underread__malloc_wchar_t_loop_65a.c b/pool/shard004/C/0101108_CWE127_Buffer_Underread__malloc_wchar_t_loop_65a.c new file mode 100644 index 0000000000000000000000000000000000000000..d46e8044c2536202374e449c3870b354cd3005e8 --- /dev/null +++ b/pool/shard004/C/0101108_CWE127_Buffer_Underread__malloc_wchar_t_loop_65a.c @@ -0,0 +1,99 @@ +/* TEMPLATE GENERATED TESTCASE FILE +Filename: CWE127_Buffer_Underread__malloc_wchar_t_loop_65a.c +Label Definition File: CWE127_Buffer_Underread__malloc.label.xml +Template File: sources-sink-65a.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 + * Sinks: loop + * BadSink : Copy data to string using a loop + * Flow Variant: 65 Data/control flow: data passed as an argument from one function to a function in a different source file called via a function pointer + * + * */ + +#include "std_testcase.h" + +#include + +#ifndef OMITBAD + +/* bad function declaration */ +void CWE127_Buffer_Underread__malloc_wchar_t_loop_65b_badSink(wchar_t * data); + +void CWE127_Buffer_Underread__malloc_wchar_t_loop_65_bad() +{ + wchar_t * data; + /* define a function pointer */ + void (*funcPtr) (wchar_t *) = CWE127_Buffer_Underread__malloc_wchar_t_loop_65b_badSink; + data = NULL; + { + wchar_t * dataBuffer = (wchar_t *)malloc(100*sizeof(wchar_t)); + if (dataBuffer == NULL) {exit(-1);} + wmemset(dataBuffer, L'A', 100-1); + dataBuffer[100-1] = L'\0'; + /* FLAW: Set data pointer to before the allocated memory buffer */ + data = dataBuffer - 8; + } + /* use the function pointer */ + funcPtr(data); +} + +#endif /* OMITBAD */ + +#ifndef OMITGOOD + +/* goodG2B uses the GoodSource with the BadSink */ +void CWE127_Buffer_Underread__malloc_wchar_t_loop_65b_goodG2BSink(wchar_t * data); + +static void goodG2B() +{ + wchar_t * data; + void (*funcPtr) (wchar_t *) = CWE127_Buffer_Underread__malloc_wchar_t_loop_65b_goodG2BSink; + data = NULL; + { + wchar_t * dataBuffer = (wchar_t *)malloc(100*sizeof(wchar_t)); + if (dataBuffer == NULL) {exit(-1);} + wmemset(dataBuffer, L'A', 100-1); + dataBuffer[100-1] = L'\0'; + /* FIX: Set data pointer to the allocated memory buffer */ + data = dataBuffer; + } + funcPtr(data); +} + +void CWE127_Buffer_Underread__malloc_wchar_t_loop_65_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()..."); + CWE127_Buffer_Underread__malloc_wchar_t_loop_65_good(); + printLine("Finished good()"); +#endif /* OMITGOOD */ +#ifndef OMITBAD + printLine("Calling bad()..."); + CWE127_Buffer_Underread__malloc_wchar_t_loop_65_bad(); + printLine("Finished bad()"); +#endif /* OMITBAD */ + return 0; +} + +#endif diff --git a/pool/shard004/C/0101110_ttyscreenshot.c b/pool/shard004/C/0101110_ttyscreenshot.c new file mode 100644 index 0000000000000000000000000000000000000000..1558b47f44bf714d8c8cd4589a334b628b193ac4 --- /dev/null +++ b/pool/shard004/C/0101110_ttyscreenshot.c @@ -0,0 +1,224 @@ +/* + Grab tty as image (PNM) + + License: public domain + + compile: + gcc -O2 ttyscreenshot.c -o ttyscreenshot + + + Author: Wojciech Muła + e-mail: wojciech_mula@poczta.onet.pl + www: http://0x80.pl + + Changelog: + + 2013-10-13: some cleanups + 2008-06-21: initial relase +*/ + +#include +#include +#include +#include +#include + +#include + +#include + +extern int errno; +typedef void (*save_fun)(uint8_t char_code, uint8_t font_row, uint8_t fore, uint8_t back); + +/* aux functions */ +uint8_t swapbits(uint8_t b); +void save_8bit_width(uint8_t char_code, uint8_t font_row, uint8_t fore, uint8_t back); +void save_9bit_width(uint8_t char_code, uint8_t font_row, uint8_t fore, uint8_t back); +void die(char*); +void ordie(char*); + + +#define CHAR_COUNT 256 +#define CHAR_HEIGHT 32 + +/* font data */ +uint8_t font[CHAR_COUNT][CHAR_HEIGHT]; + +/* palette data */ +uint8_t palette[16][3] = { + { 0, 0, 0}, + {170, 0, 0}, + { 0, 170, 0}, + {170, 85, 0}, + { 0, 0, 170}, + {170, 0, 170}, + { 0, 170, 170}, + {170, 170, 170}, + { 85, 85, 85}, + {255, 85, 85}, + { 85, 255, 85}, + {255, 255, 85}, + { 85, 85, 255}, + {255, 85, 255}, + { 85, 255, 255}, + {255, 255, 255} +}; + + +void usage() { + fputs( + "Program save contents of console in PNM file\n" + "(PNM is printed on standard output\n" + "\n" + "usage:\n" + "\tttyscreenshot [8|9] console-num\n" + "\n" + "First argument is a character width in pixels;\n" + "9 pixels is a default width use by EGA/VGA cards,\n" + "8 pixels isn't.\n" + "\n" + "You need permissions to read /dev/vcsa[console-num] device.\n", + + stderr + ); + exit(EXIT_FAILURE); +} + + +int main(int argv, char* argc[]) { + + int fd; + struct consolefontdesc dsc; + char path[PATH_MAX]; + save_fun save; + + int char_width, console_num; /* program arguments */ + uint8_t lines, columns; /* dimensions of console */ + + /* aux vars: */ + uint8_t c, attr, fore, back; + int col, line, y; + uint8_t* char_row; + + + /* 1. Parse program arguments */ + if (argv < 3) + usage(); + + char_width = atoi(argc[1]); + if (char_width != 8 && char_width != 9) + die("First argument (character width) must be either 8 or 9."); + + console_num = atoi(argc[2]); + if (console_num < 0 || console_num > 63) + die("Second argument (console number) must lie in range 0..63"); + + + /* 2. Load fonts */ + snprintf(path, PATH_MAX, "/dev/tty%d", console_num); + fd = open(path, O_RDWR); ordie("open(tty)"); + + dsc.charcount = CHAR_COUNT; + dsc.charheight = CHAR_HEIGHT; + dsc.chardata = (void*)font; + ioctl(fd, GIO_FONTX, &dsc); ordie("ioctl(GIO_FONTX)"); + + /* 3. Load palette */ + ioctl(fd, GIO_CMAP, &palette); + if (errno) { + fprintf(stderr, "Can't load palette, using defaults. Reason [errno=%d]: %s\n", errno, strerror(errno)); + errno = 0; + } + + close(fd); ordie("close(tty)"); + + /* 4. Get dimensions of console */ + snprintf(path, PATH_MAX, "/dev/vcsa%d", console_num); + fd = open(path, O_RDWR); ordie("open(vcsa)"); + + read(fd, &lines, 1); ordie("read(lines)"); + read(fd, &columns, 1); ordie("read(columns)"); + + /* 5. Allocate cache memory for a chars row */ + char_row = (uint8_t*)malloc(columns*2); + if (char_row == NULL) + die("malloc failed"); + + lseek(fd, 4, SEEK_SET); + + /* 6. Save image */ + if (char_width == 8) + save = save_8bit_width; + else + save = save_9bit_width; + + + printf("P6\n%d %d\n255\n", columns*char_width, lines*16); + for (line=0; line < lines; line++) { + /* load whole character row */ + read(fd, char_row, columns*2); + + /* process each line of font data */ + for (y=0; y < 16; y++) { + for (col=0; col < columns*2; col+=2) { + c = char_row[col]; /* get charcode */ + attr = swapbits(char_row[col+1]); /* get attribute - order of bits have to be fixed */ + + fore = attr & 0x0f; /* from attribute extract foreground color */ + back = attr >> 4; /* and background color */ + save(c, font[c][y], fore, back); + } + } + } + + free(char_row); + close(fd); + + return 0; +} + + +uint8_t swapbits(uint8_t b) { + /* input: 8-bit number (bits order in a nibble: 3,2,1,0) */ + /* output: 8-bit number (bits order in a nibble: 3,0,1,2) */ + return (b & 0xaa) | ((b & 0x44) >> 2) | ((b & 0x11) << 2); +} + + +void save_8bit_width(uint8_t char_code, uint8_t font_row, uint8_t fore, uint8_t back) { + uint8_t mask; + for (mask = 0x80; mask != 0; mask >>= 1) { + if (font_row & mask) + fwrite(&palette[fore][0], 3, 1, stdout); + else + fwrite(&palette[back][0], 3, 1, stdout); + } +} + + +void save_9bit_width(uint8_t char_code, uint8_t font_row, uint8_t fore, uint8_t back) { + save_8bit_width(char_code, font_row, fore, back); + + /* repeat last column of some characters */ + if (char_code >= 0xbf && char_code <= 0xdf && (font_row & 0x01)) + fwrite(&palette[fore][0], 3, 1, stdout); + else + fwrite(&palette[back][0], 3, 1, stdout); +} + + +void ordie(char* info) { + if (errno != 0) { + fprintf(stderr, "%s [errno=%d]: %s\n", info, errno, strerror(errno)); + exit(EXIT_FAILURE); + } +} + +void die(char* info) { + fprintf(stderr, "%s\n", info); + exit(EXIT_FAILURE); +} + +/* +vim: ts=4 sw=4 nowrap noexpandtab +*/ diff --git a/pool/shard004/C/0101111_snprintf.c b/pool/shard004/C/0101111_snprintf.c new file mode 100644 index 0000000000000000000000000000000000000000..06fab9471542f57fa8337fb103b8af23e088497b --- /dev/null +++ b/pool/shard004/C/0101111_snprintf.c @@ -0,0 +1,47 @@ +/* + * Copyright (C) 2013-2020 Cisco Systems, Inc. and/or its affiliates. All rights reserved. + * Copyright (C) 2009-2013 Sourcefire, Inc. + * + * Authors: aCaB + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License version 2 as + * published by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, + * MA 02110-1301, USA. + */ + +#if HAVE_CONFIG_H +#include "clamav-config.h" +#endif + +#include +#include +#include +#include "snprintf.h" + +#ifndef HAVE_SNPRINTF + +int snprintf(char *str, size_t size, const char *format, ...) +{ + va_list va; + int len; + + va_start(va, format); + errno = 0; + len = vsnprintf(str, size, format, va); + if (len == -1 && errno == ERANGE) + len = size; + va_end(va); + return len; +} + +#endif diff --git a/pool/shard004/C/0101119_mali_ukk_core.c b/pool/shard004/C/0101119_mali_ukk_core.c new file mode 100644 index 0000000000000000000000000000000000000000..af521a57b3d43cc6c5fb38de17bd48c618b5a8ce --- /dev/null +++ b/pool/shard004/C/0101119_mali_ukk_core.c @@ -0,0 +1,146 @@ +/* + * This confidential and proprietary software may be used only as + * authorised by a licensing agreement from ARM Limited + * (C) COPYRIGHT 2008-2015 ARM Limited + * ALL RIGHTS RESERVED + * The entire notice above must be reproduced on all authorised + * copies and copies may only be made to the extent permitted + * by a licensing agreement from ARM Limited. + */ +#include /* file system operations */ +#include /* memort allocation functions */ +#include /* user space access */ + +#include "mali_ukk.h" +#include "mali_osk.h" +#include "mali_kernel_common.h" +#include "mali_session.h" +#include "mali_ukk_wrappers.h" + +int get_api_version_wrapper(struct mali_session_data *session_data, _mali_uk_get_api_version_s __user *uargs) +{ + _mali_uk_get_api_version_s kargs; + _mali_osk_errcode_t err; + + MALI_CHECK_NON_NULL(uargs, -EINVAL); + + if (0 != get_user(kargs.version, &uargs->version)) return -EFAULT; + + kargs.ctx = (uintptr_t)session_data; + err = _mali_ukk_get_api_version(&kargs); + if (_MALI_OSK_ERR_OK != err) return map_errcode(err); + + if (0 != put_user(kargs.version, &uargs->version)) return -EFAULT; + if (0 != put_user(kargs.compatible, &uargs->compatible)) return -EFAULT; + + return 0; +} + +int get_api_version_v2_wrapper(struct mali_session_data *session_data, _mali_uk_get_api_version_v2_s __user *uargs) +{ + _mali_uk_get_api_version_v2_s kargs; + _mali_osk_errcode_t err; + + MALI_CHECK_NON_NULL(uargs, -EINVAL); + + if (0 != get_user(kargs.version, &uargs->version)) return -EFAULT; + + kargs.ctx = (uintptr_t)session_data; + err = _mali_ukk_get_api_version_v2(&kargs); + if (_MALI_OSK_ERR_OK != err) return map_errcode(err); + + if (0 != put_user(kargs.version, &uargs->version)) return -EFAULT; + if (0 != put_user(kargs.compatible, &uargs->compatible)) return -EFAULT; + + return 0; +} + +int wait_for_notification_wrapper(struct mali_session_data *session_data, _mali_uk_wait_for_notification_s __user *uargs) +{ + _mali_uk_wait_for_notification_s kargs; + _mali_osk_errcode_t err; + + MALI_CHECK_NON_NULL(uargs, -EINVAL); + + kargs.ctx = (uintptr_t)session_data; + err = _mali_ukk_wait_for_notification(&kargs); + if (_MALI_OSK_ERR_OK != err) return map_errcode(err); + + if (_MALI_NOTIFICATION_CORE_SHUTDOWN_IN_PROGRESS != kargs.type) { + kargs.ctx = (uintptr_t)NULL; /* prevent kernel address to be returned to user space */ + if (0 != copy_to_user(uargs, &kargs, sizeof(_mali_uk_wait_for_notification_s))) return -EFAULT; + } else { + if (0 != put_user(kargs.type, &uargs->type)) return -EFAULT; + } + + return 0; +} + +int post_notification_wrapper(struct mali_session_data *session_data, _mali_uk_post_notification_s __user *uargs) +{ + _mali_uk_post_notification_s kargs; + _mali_osk_errcode_t err; + + MALI_CHECK_NON_NULL(uargs, -EINVAL); + + kargs.ctx = (uintptr_t)session_data; + + if (0 != get_user(kargs.type, &uargs->type)) { + return -EFAULT; + } + + err = _mali_ukk_post_notification(&kargs); + if (_MALI_OSK_ERR_OK != err) { + return map_errcode(err); + } + + return 0; +} + +int get_user_settings_wrapper(struct mali_session_data *session_data, _mali_uk_get_user_settings_s __user *uargs) +{ + _mali_uk_get_user_settings_s kargs; + _mali_osk_errcode_t err; + + MALI_CHECK_NON_NULL(uargs, -EINVAL); + + kargs.ctx = (uintptr_t)session_data; + err = _mali_ukk_get_user_settings(&kargs); + if (_MALI_OSK_ERR_OK != err) { + return map_errcode(err); + } + + kargs.ctx = 0; /* prevent kernel address to be returned to user space */ + if (0 != copy_to_user(uargs, &kargs, sizeof(_mali_uk_get_user_settings_s))) return -EFAULT; + + return 0; +} + +int request_high_priority_wrapper(struct mali_session_data *session_data, _mali_uk_request_high_priority_s __user *uargs) +{ + _mali_uk_request_high_priority_s kargs; + _mali_osk_errcode_t err; + + MALI_CHECK_NON_NULL(uargs, -EINVAL); + + kargs.ctx = (uintptr_t)session_data; + err = _mali_ukk_request_high_priority(&kargs); + + kargs.ctx = 0; + + return map_errcode(err); +} + +int pending_submit_wrapper(struct mali_session_data *session_data, _mali_uk_pending_submit_s __user *uargs) +{ + _mali_uk_pending_submit_s kargs; + _mali_osk_errcode_t err; + + MALI_CHECK_NON_NULL(uargs, -EINVAL); + + kargs.ctx = (uintptr_t)session_data; + err = _mali_ukk_pending_submit(&kargs); + if (_MALI_OSK_ERR_OK != err) return map_errcode(err); + + return 0; +} diff --git a/pool/shard004/C/0101122_h2200_pm.c b/pool/shard004/C/0101122_h2200_pm.c new file mode 100644 index 0000000000000000000000000000000000000000..e5562152cd9707b6cbd7e2d69b22b0259ed697e5 --- /dev/null +++ b/pool/shard004/C/0101122_h2200_pm.c @@ -0,0 +1,220 @@ +/* + * h2200 power management support for the HTC bootloader + * + * 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 + + +/* On resume, the PXA begins executing the code at 0x00000000, which is in + HAMCOP's SRAM. But there is a conflict: the samcop_sdi driver uses HAMCOP's + SRAM for DMA, which results in the bootloader being overwritten. So we + must save the bootloader before it gets overwritten, and restore it at + suspend. + + The problem with using the HTC bootloader is that it does its + initialization and then jumps to 0xa0040000, which on Linux + is somewhere in kernel code. There are a couple of solutions to this + problem: + + 1. Save/restore enough bytes at 0xa0040000 to insert code to jump to the + resume function. This is still a little risky depending on what's + at 0xa0040000. + + 2. Store a position-independent code fragment into SRAM that jumps to the + resume function. This is safer since we don't have to worry about + stomping on the kernel; and we have to copy the bootloader into place + anyway. + + Both methods have been tested to work. Method #2 seems safer so that is + what we're using. + + We can jump into the resume function a couple of ways: + + a. load the resume address from PSPR into pc + + ldr r0, [pc, #0] + ldr pc, [r0] + .word 0x40f00008; // PSPR + + b. load the resume address directly into pc + + ldr pc, [pc, #-4] + .word resume_addr +*/ + +static u8 *bootloader; +static int bootloader_valid = 0; + +#define BOOTLOADER_LOAD_DELAY (HZ * 30) +#if defined(CONFIG_FW_LOADER_MODULE) +static struct work_struct fw_work; +#else +static struct delayed_work fw_work; +#endif + +extern struct pm_ops pxa_pm_ops; + +static int (*pxa_pm_enter_orig)(suspend_state_t state); + + +static int h2200_pxa_pm_enter(suspend_state_t state) +{ + int ret; + + if (!bootloader_valid) { + printk(KERN_ERR "h2200_pm: no valid bootloader; suspend cancelled\n"); + return 1; + } + + ret = pxa_pm_enter_orig(state); + + MSC0 = 0x246c7ffc; + (void)MSC0; + MSC1 = 0x7ff07ff0; + (void)MSC1; + MSC2 = 0x7ff07ff0; + (void)MSC2; + + return ret; +} + +/* Return a pointer to the bootloader. */ +u8 * +get_hamcop_bootloader(void) +{ + return bootloader; +} +EXPORT_SYMBOL(get_hamcop_bootloader); + +/* Patch the bootloader so it resumes to the address in PSPR + * instead of 0xa0040000. */ +static void h2200_patch_fw(void) +{ + int i; + u32 *code = (u32 *)bootloader; + + i = 0x75c / sizeof(u32); + code[i++] = 0xe59f0000; /* ldr r0, [pc, #0] */ + code[i++] = 0xe590f000; /* ldr pc, [r0] */ + code[i++] = 0x40f00008; /* PSPR */ +} + +#if defined(CONFIG_FW_LOADER) || defined(CONFIG_FW_LOADER_MODULE) +static void h2200_load_bootloader(struct work_struct *notused) +{ + const struct firmware *fw; + + if (request_firmware(&fw, "h2200_bootloader.bin", &h2200_hamcop.dev)) { + printk(KERN_ERR "h2200_pm: request_firmware failed\n"); +#if defined(CONFIG_FW_LOADER_MODULE) + schedule_work(&fw_work); +#else + schedule_delayed_work(&fw_work, BOOTLOADER_LOAD_DELAY); +#endif + return; + } + + printk("h2200_pm: bootloader loaded\n"); + memcpy(bootloader, fw->data, fw->size < HAMCOP_SRAM_Size ? + fw->size : HAMCOP_SRAM_Size); + release_firmware(fw); + h2200_patch_fw(); + bootloader_valid = 1; +} +#endif + +static int __init h2200_pm_init(void) { + + u8 *sram; + + if (machine_is_h2200()) { + + printk("Initialising wince bootloader suspend workaround\n"); + + pxa_pm_enter_orig = pxa_pm_ops.enter; + pxa_pm_ops.enter = h2200_pxa_pm_enter; + + bootloader_valid = 0; + bootloader = kmalloc(HAMCOP_SRAM_Size, GFP_KERNEL); + if (!bootloader) { + printk(KERN_ERR "h2200_pm: unable to kmalloc bootloader\n"); + return -ENOMEM; + } + + /* Copy what's already in SRAM for now, as it's good in + * many cases (e.g. where LAB hasn't already written + * over it.) */ + sram = ioremap(H2200_HAMCOP_BASE, HAMCOP_MAP_SIZE); + memcpy(bootloader, sram, HAMCOP_SRAM_Size); + iounmap(sram); + + /* If the bootloader is good, there's no need to load + * another. Check for the HTC bootloader by looking for + * 'b 0x80' at +0x0, and for 'ECEC' at +0x40. */ + if (((u32 *)bootloader)[0] == 0xea00001e && + ((u32 *)bootloader)[0x10] == 0x43454345) { + + h2200_patch_fw(); + bootloader_valid = 1; + } else + printk(KERN_ERR "h2200_pm: bootloader may be invalid; " + "resume may not work\n"); + +#if defined(CONFIG_FW_LOADER) || defined(CONFIG_FW_LOADER_MODULE) + if (!bootloader_valid) { + + /* There doesn't seem to be a valid bootloader in + * SRAM, so try to load one from userland. Note that + * we schedule the work for a little later when compiled + * into the kernel (rather than as a module), to give + * other modules a chance to initialize; without this + * delay, we were getting an error, + * "Badness in kref_get". */ + printk("h2200_pm: requesting bootloader\n"); + +#if defined(CONFIG_FW_LOADER_MODULE) + INIT_WORK(&fw_work, h2200_load_bootloader); + schedule_work(&fw_work); +#else + INIT_DELAYED_WORK(&fw_work, h2200_load_bootloader); + schedule_delayed_work(&fw_work, BOOTLOADER_LOAD_DELAY); +#endif + } +#else + bootloader_valid = 1; +#endif + } + + return 0; +} + +static void __exit h2200_pm_exit(void) +{ + pxa_pm_ops.enter = pxa_pm_enter_orig; +} + +module_init(h2200_pm_init); +module_exit(h2200_pm_exit); + +MODULE_AUTHOR("Matt Reimer "); +MODULE_DESCRIPTION("HP iPAQ h2200 power management support for HTC bootloader"); +MODULE_LICENSE("Dual BSD/GPL"); diff --git a/pool/shard004/C/0101128_joystick.c b/pool/shard004/C/0101128_joystick.c new file mode 100644 index 0000000000000000000000000000000000000000..b93fb9a3d61f9f746d8464fb43581e5779e82170 --- /dev/null +++ b/pool/shard004/C/0101128_joystick.c @@ -0,0 +1,187 @@ +/* + * See Licensing and Copyright notice in naev.h + */ + +/** + * @file joystick.c + * + * @brief Handles joystick initialization. + */ + + +#include "joystick.h" + +#include "naev.h" + +#include "nstring.h" + +#include "SDL.h" +#include "SDL_joystick.h" +#include "SDL_haptic.h" + +#include "log.h" + + +static SDL_Joystick *joystick = NULL; /**< Current joystick in use. */ +static int has_haptic = 0; /**< Does the player have haptic? */ +SDL_Haptic *haptic = NULL; /**< Current haptic in use, externed in spfx.c. */ +unsigned int haptic_query = 0; /**< Properties of the haptic device. */ + + +/* + * Prototypes. + */ +static void joystick_initHaptic (void); + + +/** + * @brief Gets the joystick index by name. + * + * @param namjoystick Looks for this string in the joystick name. + * @return The index if found, defaults to 0 if it isn't found. + */ +int joystick_get( const char* namjoystick ) +{ + const char *jname; + int i; + for (i=0; i < SDL_NumJoysticks(); i++) { + jname = SDL_JoystickNameForIndex(i); + if (strstr( jname, namjoystick )) + return i; + } + + WARN(_("Joystick '%s' not found, using default joystick '%s'"), + namjoystick, SDL_JoystickName(0)); + return 0; +} + + +/** + * @brief Makes the game use a joystick by index. + * + * @param indjoystick Index of the joystick to use. + * @return 0 on success. + */ +int joystick_use( int indjoystick ) +{ + const char *jname; + + /* Check to see if it exists. */ + if ((indjoystick < 0) || (indjoystick >= SDL_NumJoysticks())) { + WARN(_("Joystick of index number %d does not existing, switching to default 0"), + indjoystick); + indjoystick = 0; + } + + /* Close if already open. */ + if (joystick != NULL) { + SDL_JoystickClose(joystick); + joystick = NULL; + } + + /* Start using joystick. */ + joystick = SDL_JoystickOpen(indjoystick); + jname = SDL_JoystickNameForIndex(indjoystick); + if (joystick == NULL) { + WARN(_("Error opening joystick %d [%s]"), indjoystick, jname); + return -1; + } + LOG(_("Using joystick %d - %s"), indjoystick, jname); + DEBUG(_(" with %d axes, %d buttons, %d balls and %d hats"), + SDL_JoystickNumAxes(joystick), SDL_JoystickNumButtons(joystick), + SDL_JoystickNumBalls(joystick), SDL_JoystickNumHats(joystick)); + + /* Initialize the haptic if possible. */ + joystick_initHaptic(); + + /* For style purposes. */ + DEBUG(""); + + return 0; +} + + +/** + * @brief Initializes force feedback for the loaded device. + */ +static void joystick_initHaptic (void) +{ + if (has_haptic && SDL_JoystickIsHaptic(joystick)) { + + /* Close haptic if already open. */ + if (haptic != NULL) { + SDL_HapticClose(haptic); + haptic = NULL; + } + + /* Try to create haptic device. */ + haptic = SDL_HapticOpenFromJoystick(joystick); + if (haptic == NULL) { + WARN(_("Unable to initialize force feedback: %s"), SDL_GetError()); + return; + } + + /* Check to see what it supports. */ + haptic_query = SDL_HapticQuery(haptic); + if (!(haptic_query & SDL_HAPTIC_SINE)) { + SDL_HapticClose(haptic); + haptic = NULL; + return; + } + + DEBUG(_(" force feedback enabled")); + } +} + + +/** + * @brief Initializes the joystick subsystem. + * + * @return 0 on success. + */ +int joystick_init (void) +{ + int numjoysticks, i; + + /* initialize the sdl subsystem */ + if (SDL_InitSubSystem(SDL_INIT_JOYSTICK)) { + WARN(_("Unable to initialize the joystick subsystem")); + return -1; + } + + if (SDL_InitSubSystem(SDL_INIT_HAPTIC) == 0) + has_haptic = 1; + + /* figure out how many joysticks there are */ + numjoysticks = SDL_NumJoysticks(); + DEBUG( ngettext("%d joystick detected", "%d joysticks detected", numjoysticks), numjoysticks ); + for (i=0; i < numjoysticks; i++) { + const char *jname; + jname = SDL_JoystickNameForIndex(i); + DEBUG(" %d. %s", i, jname); + } + + /* enables joystick events */ + SDL_JoystickEventState(SDL_ENABLE); + + return 0; +} + + +/** + * @brief Exits the joystick subsystem. + */ +void joystick_exit (void) +{ + if (haptic != NULL) { + SDL_HapticClose(haptic); + haptic = NULL; + } + + if (joystick != NULL) { + SDL_JoystickClose(joystick); + joystick = NULL; + } +} + + diff --git a/pool/shard004/C/0101131_flash_sgm3780.c b/pool/shard004/C/0101131_flash_sgm3780.c new file mode 100644 index 0000000000000000000000000000000000000000..42353545aad52a91b4ed6e4749e33d4909ca0640 --- /dev/null +++ b/pool/shard004/C/0101131_flash_sgm3780.c @@ -0,0 +1,207 @@ + +/* wmt.camera.flash ::: + * wmt.camera.flash sgm3780:3:2:12 + */ + +#include +#include +#include +#include +#include "../cmos-subdev.h" +#include "../../wmt-vid.h" +#include "flash.h" + +enum key_status { + Idle,Pending,Pressure +}; + +struct key_struct{ + int gpio; + enum key_status sts; + bool need_on; + struct work_struct work; +}; + +struct sgm3780_struct { + int gpio_en; + int gpio_flen; + struct key_struct torch_key; +}; + +static struct sgm3780_struct *eup; + +/* + * TODO register flash as a subdev + */ +static int flash_dev_set_mode(int mode) +{ + if (!eup) + return -EINVAL; + + switch (mode) { + case FLASH_MODE_OFF: + gpio_direction_output(eup->gpio_en, 0); + gpio_direction_output(eup->gpio_flen, 0); + break; + case FLASH_MODE_ON: + gpio_direction_output(eup->gpio_en, 1); + gpio_direction_output(eup->gpio_flen, 1); + break; + case FLASH_MODE_STROBE: + gpio_direction_output(eup->gpio_en, 0); + gpio_direction_output(eup->gpio_flen, 0); + break; + case FLASH_MODE_TORCH: + gpio_direction_output(eup->gpio_en, 1); + gpio_direction_output(eup->gpio_flen, 0); + msleep(1); + break; + default: + return -EINVAL; + } + return 0; +} + +static void flash_key_scan_work(struct work_struct *work) +{ + struct sgm3780_struct *peup = container_of(work, struct sgm3780_struct,torch_key.work); + + if(peup->torch_key.sts !=Idle){ + pr_err("torch key is busy!!!\n"); + goto work_done; + } + peup->torch_key.sts = Pending; + msleep(50); + if(peup->torch_key.sts == Pending){ + if(!gpio_get_value(peup->torch_key.gpio)){ + peup->torch_key.sts = Pressure; + } + } + + if(peup->torch_key.sts == Pressure){ + if(peup->torch_key.need_on == true){ + flash_dev_set_mode(FLASH_MODE_TORCH); + peup->torch_key.need_on = false; + }else{ + flash_dev_set_mode(FLASH_MODE_OFF); + peup->torch_key.need_on = true; + } + } + +work_done: + peup->torch_key.sts = Idle; + wmt_gpio_unmask_irq(peup->torch_key.gpio); +} + +static irqreturn_t flash_key_ext_irq (int irq, void *dev_id) +{ + struct sgm3780_struct *peup = dev_id; + + if(!is_gpio_irqenable(peup->torch_key.gpio) || !gpio_irqstatus(peup->torch_key.gpio)) + return IRQ_NONE; + + wmt_gpio_ack_irq(peup->torch_key.gpio); + wmt_gpio_mask_irq(peup->torch_key.gpio); + schedule_work(&peup->torch_key.work); + + return IRQ_HANDLED; +} + +static void key_setup_extirq(struct sgm3780_struct *peup) +{ + int ret; + + wmt_gpio_setpull(peup->torch_key.gpio,WMT_GPIO_PULL_UP); + wmt_gpio_set_irq_type(peup->torch_key.gpio,IRQ_TYPE_EDGE_FALLING); + wmt_gpio_mask_irq(peup->torch_key.gpio); + wmt_gpio_ack_irq(peup->torch_key.gpio); + ret = request_irq(IRQ_GPIO, flash_key_ext_irq, IRQF_SHARED,"sgm3780_key_irq", peup); + if (ret) { + printk("request irq type IRQ_TYPE_EDGE_FALLING fail!\n"); + return; + } + wmt_gpio_ack_irq(peup->torch_key.gpio); + wmt_gpio_unmask_irq(peup->torch_key.gpio); +} + +static int parse_charger_param(void) +{ + char *dev_name = "sgm3780"; + char *env = "wmt.camera.flash"; + char s[64]; + size_t l = sizeof(s); + int gpio_en, gpio_flen,gpio_key; + int rc; + + if (wmt_getsyspara(env, s, &l)) { + // pr_err("read %s fail!\n", env); + return -EINVAL; + } + + if (strncmp(s, dev_name, strlen(dev_name))) { + return -EINVAL; + } + + rc = sscanf(s, "sgm3780:%d:%d:%d", &gpio_en, &gpio_flen,&gpio_key); + if (rc < 2) { + pr_err("bad uboot env: %s\n", env); + return -EINVAL; + } + + rc = gpio_request(gpio_en, "flash sgm3780 en"); + if (rc) { + pr_err("flash en gpio(%d) request failed\n", gpio_en); + return rc; + } + + rc = gpio_request(gpio_flen, "flash sgm3780 flen"); + if (rc) { + pr_err("flash flen gpio(%d) request failed\n", gpio_flen); + gpio_free(gpio_en); + return rc; + } + + eup = kzalloc(sizeof(*eup), GFP_KERNEL); + if (!eup) + return -ENOMEM; + + eup->gpio_en = gpio_en; + eup->gpio_flen = gpio_flen; + eup->torch_key.gpio = gpio_key; + eup->torch_key.need_on = true; + INIT_WORK(&eup->torch_key.work,flash_key_scan_work); + key_setup_extirq(eup); + + printk("flash sgm3780 register ok: en %d, flen %d, key %d\n", + eup->gpio_en, eup->gpio_flen,eup->torch_key.gpio); + + return 0; +} + +static int flash_dev_init(void) +{ + if (eup) + return -EINVAL; + + return parse_charger_param(); +} + +static void flash_dev_exit(void) +{ + if (eup) { + gpio_free(eup->gpio_en); + gpio_free(eup->gpio_flen); + cancel_work_sync(&eup->torch_key.work); + free_irq(IRQ_GPIO,eup); + kfree(eup); + eup = NULL; + } +} + +struct flash_dev flash_dev_sgm3780 = { + .name = "sgm3780", + .init = flash_dev_init, + .set_mode = flash_dev_set_mode, + .exit = flash_dev_exit, +}; + diff --git a/pool/shard004/C/0101132_globals.c b/pool/shard004/C/0101132_globals.c new file mode 100644 index 0000000000000000000000000000000000000000..043b1da660236383257fe78cf35e89769931fb5d --- /dev/null +++ b/pool/shard004/C/0101132_globals.c @@ -0,0 +1,179 @@ +/* + Unix SMB/Netbios implementation. + smbd globals + Copyright (C) Stefan Metzmacher 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 "includes.h" +#include "smbd/smbd.h" +#include "smbd/globals.h" +#include "lib/smbd_shim.h" +#include "memcache.h" +#include "messages.h" +#include "tdb_compat.h" + +#if defined(WITH_AIO) +struct aio_extra *aio_list_head = NULL; +struct tevent_signal *aio_signal_event = NULL; +int aio_pending_size = 0; +int outstanding_aio_calls = 0; +#endif + +#ifdef USE_DMAPI +struct smbd_dmapi_context *dmapi_ctx = NULL; +#endif + + +bool dfree_broken = false; + +/* how many write cache buffers have been allocated */ +unsigned int allocated_write_caches = 0; + +const struct mangle_fns *mangle_fns = NULL; + +unsigned char *chartest = NULL; +TDB_CONTEXT *tdb_mangled_cache = NULL; + +/* + this determines how many characters are used from the original filename + in the 8.3 mangled name. A larger value leads to a weaker hash and more collisions. + The largest possible value is 6. +*/ +unsigned mangle_prefix = 0; + +struct msg_state *smbd_msg_state = NULL; + +bool logged_ioctl_message = false; + +time_t last_smb_conf_reload_time = 0; +time_t last_printer_reload_time = 0; +pid_t background_lpq_updater_pid = -1; + +/**************************************************************************** + structure to hold a linked list of queued messages. + for processing. +****************************************************************************/ +uint32_t common_flags2 = FLAGS2_LONG_PATH_COMPONENTS|FLAGS2_32_BIT_ERROR_CODES|FLAGS2_EXTENDED_ATTRIBUTES; + +struct smb_trans_enc_state *partial_srv_trans_enc_ctx = NULL; +struct smb_trans_enc_state *srv_trans_enc_ctx = NULL; + +/* A stack of security contexts. We include the current context as being + the first one, so there is room for another MAX_SEC_CTX_DEPTH more. */ +struct sec_ctx sec_ctx_stack[MAX_SEC_CTX_DEPTH + 1]; +int sec_ctx_stack_ndx = 0; +bool become_uid_done = false; +bool become_gid_done = false; + +connection_struct *last_conn = NULL; +uint16_t last_flags = 0; + +uint32_t global_client_caps = 0; + +uint16_t fnf_handle = 257; + +/* A stack of current_user connection contexts. */ +struct conn_ctx conn_ctx_stack[MAX_SEC_CTX_DEPTH]; +int conn_ctx_stack_ndx = 0; + +struct vfs_init_function_entry *backends = NULL; +char *sparse_buf = NULL; +char *LastDir = NULL; + +/* Current number of oplocks we have outstanding. */ +int32_t exclusive_oplocks_open = 0; +int32_t level_II_oplocks_open = 0; +struct kernel_oplocks *koplocks = NULL; + +int am_parent = 1; +struct memcache *smbd_memcache_ctx = NULL; +bool exit_firsttime = true; +struct child_pid *children = 0; +int num_children = 0; + +struct smbd_server_connection *smbd_server_conn = NULL; + +struct smbd_server_connection *msg_ctx_to_sconn(struct messaging_context *msg_ctx) +{ + struct server_id my_id, msg_id; + + my_id = messaging_server_id(smbd_server_conn->msg_ctx); + msg_id = messaging_server_id(msg_ctx); + + if (!procid_equal(&my_id, &msg_id)) { + return NULL; + } + return smbd_server_conn; +} + +struct messaging_context *smbd_messaging_context(void) +{ + struct messaging_context *msg_ctx = server_messaging_context(); + if (likely(msg_ctx != NULL)) { + return msg_ctx; + } + smb_panic("Could not init smbd's messaging context.\n"); + return NULL; +} + +struct memcache *smbd_memcache(void) +{ + if (!smbd_memcache_ctx) { + /* + * Note we MUST use the NULL context here, not the + * autofree context, to avoid side effects in forked + * children exiting. + */ + smbd_memcache_ctx = memcache_init(NULL, + lp_max_stat_cache_size()*1024); + } + if (!smbd_memcache_ctx) { + smb_panic("Could not init smbd memcache"); + } + + return smbd_memcache_ctx; +} + +static const struct smbd_shim smbd_shim_fns = +{ + .cancel_pending_lock_requests_by_fid = smbd_cancel_pending_lock_requests_by_fid, + .send_stat_cache_delete_message = smbd_send_stat_cache_delete_message, + .can_delete_directory = smbd_can_delete_directory, + .change_to_root_user = smbd_change_to_root_user, + + .contend_level2_oplocks_begin = smbd_contend_level2_oplocks_begin, + .contend_level2_oplocks_end = smbd_contend_level2_oplocks_end, + + .become_root = smbd_become_root, + .unbecome_root = smbd_unbecome_root +}; + +void smbd_init_globals(void) +{ + set_smbd_shim(&smbd_shim_fns); + + ZERO_STRUCT(conn_ctx_stack); + + ZERO_STRUCT(sec_ctx_stack); + + smbd_server_conn = talloc_zero(server_event_context(), struct smbd_server_connection); + if (!smbd_server_conn) { + exit_server("failed to create smbd_server_connection"); + } + + smbd_server_conn->smb1.echo_handler.trusted_fd = -1; + smbd_server_conn->smb1.echo_handler.socket_lock_fd = -1; +} diff --git a/pool/shard004/C/0101136_xt_ipcomp.c b/pool/shard004/C/0101136_xt_ipcomp.c new file mode 100644 index 0000000000000000000000000000000000000000..9976694c440c2a290ddaa797ce8fec1b6051eb9b --- /dev/null +++ b/pool/shard004/C/0101136_xt_ipcomp.c @@ -0,0 +1,120 @@ +/* Kernel module to match IPComp parameters for IPv4 and IPv6 + * + * Copyright (C) 2013 WindRiver + * + * Author: + * Fan Du + * + * Based on: + * net/netfilter/xt_esp.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. + */ + +#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt +#include +#include +#include +#include + +#include +#include + +MODULE_LICENSE("GPL"); +MODULE_AUTHOR("Fan Du "); +MODULE_DESCRIPTION("Xtables: IPv4/6 IPsec-IPComp SPI match"); +MODULE_ALIAS("ipt_ipcomp"); +MODULE_ALIAS("ip6t_ipcomp"); + +/* Returns 1 if the spi is matched by the range, 0 otherwise */ +static inline bool +spi_match(u_int32_t min, u_int32_t max, u_int32_t spi, bool invert) +{ + bool r; + pr_debug("spi_match:%c 0x%x <= 0x%x <= 0x%x\n", + invert ? '!' : ' ', min, spi, max); + r = (spi >= min && spi <= max) ^ invert; + pr_debug(" result %s\n", r ? "PASS" : "FAILED"); + return r; +} + +static bool comp_mt(const struct sk_buff *skb, struct xt_action_param *par) +{ + struct ip_comp_hdr _comphdr; + const struct ip_comp_hdr *chdr; + const struct xt_ipcomp *compinfo = par->matchinfo; + + /* Must not be a fragment. */ + if (par->fragoff != 0) + { + return false; + } + + chdr = skb_header_pointer(skb, par->thoff, sizeof(_comphdr), &_comphdr); + + if (chdr == NULL) + { + /* We've been asked to examine this packet, and we + * can't. Hence, no choice but to drop. + */ + pr_debug("Dropping evil IPComp tinygram.\n"); + par->hotdrop = true; + return 0; + } + + return spi_match(compinfo->spis[0], compinfo->spis[1], + ntohs(chdr->cpi), + !!(compinfo->invflags & XT_IPCOMP_INV_SPI)); +} + +static int comp_mt_check(const struct xt_mtchk_param *par) +{ + const struct xt_ipcomp *compinfo = par->matchinfo; + + /* Must specify no unknown invflags */ + if (compinfo->invflags & ~XT_IPCOMP_INV_MASK) + { + pr_err("unknown flags %X\n", compinfo->invflags); + return -EINVAL; + } + + return 0; +} + +static struct xt_match comp_mt_reg[] __read_mostly = +{ + { + .name = "ipcomp", + .family = NFPROTO_IPV4, + .match = comp_mt, + .matchsize = sizeof(struct xt_ipcomp), + .proto = IPPROTO_COMP, + .checkentry = comp_mt_check, + .me = THIS_MODULE, + }, + { + .name = "ipcomp", + .family = NFPROTO_IPV6, + .match = comp_mt, + .matchsize = sizeof(struct xt_ipcomp), + .proto = IPPROTO_COMP, + .checkentry = comp_mt_check, + .me = THIS_MODULE, + }, +}; + +static int __init comp_mt_init(void) +{ + return xt_register_matches(comp_mt_reg, ARRAY_SIZE(comp_mt_reg)); +} + +static void __exit comp_mt_exit(void) +{ + xt_unregister_matches(comp_mt_reg, ARRAY_SIZE(comp_mt_reg)); +} + +module_init(comp_mt_init); +module_exit(comp_mt_exit); diff --git a/pool/shard004/C/0101137_devlist.c b/pool/shard004/C/0101137_devlist.c new file mode 100644 index 0000000000000000000000000000000000000000..e37377ad05fb269fd1be839a6b9dc9490ffa8f98 --- /dev/null +++ b/pool/shard004/C/0101137_devlist.c @@ -0,0 +1,59 @@ +#include +#include +#include "device.h" +/* + * linked list routines + * + * 1/28/98 g haerr + * Copyright (c) 1999 Greg Haerr + */ + +void * +GdItemAlloc(unsigned int size) +{ + return (void *)calloc(size, 1); +} + +/* insert at tail of list*/ +void +GdListAdd(PMWLISTHEAD pHead,PMWLIST pItem) +{ + if( pHead->tail) { + pItem->prev = pHead->tail; + pHead->tail->next = pItem; + } else + pItem->prev = NULL; + pItem->next = NULL; + pHead->tail = pItem; + if( !pHead->head) + pHead->head = pItem; +} + +/* insert at head of list*/ +void +GdListInsert(PMWLISTHEAD pHead,PMWLIST pItem) +{ + if( pHead->head) { + pItem->next = pHead->head; + pHead->head->prev = pItem; + } else + pItem->next = NULL; + pItem->prev = NULL; + pHead->head = pItem; + if( !pHead->head) + pHead->head = pItem; +} + +void +GdListRemove(PMWLISTHEAD pHead,PMWLIST pItem) +{ + if( pItem->next) + pItem->next->prev = pItem->prev; + if( pItem->prev) + pItem->prev->next = pItem->next; + if( pHead->head == pItem) + pHead->head = pItem->next; + if( pHead->tail == pItem) + pHead->tail = pItem->prev; + pItem->next = pItem->prev = NULL; +} diff --git a/pool/shard004/C/0101154_print-pflog.c b/pool/shard004/C/0101154_print-pflog.c new file mode 100644 index 0000000000000000000000000000000000000000..265efd3c866b9595f5ee8f01225db77ae2c3a793 --- /dev/null +++ b/pool/shard004/C/0101154_print-pflog.c @@ -0,0 +1,185 @@ +/* + * Copyright (c) 1990, 1991, 1993, 1994, 1995, 1996 + * 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: (1) source code distributions + * retain the above copyright notice and this paragraph in its entirety, (2) + * distributions including binary code include the above copyright notice and + * this paragraph in its entirety in the documentation or other materials + * provided with the distribution, and (3) all advertising materials mentioning + * features or use of this software display the following acknowledgement: + * ``This product includes software developed by the University of California, + * Lawrence Berkeley Laboratory and its contributors.'' 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 ``AS IS'' AND WITHOUT ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. + */ + +/* \summary: OpenBSD packet filter log file printer */ + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +#ifndef HAVE_NET_PFVAR_H +#error "No pf headers available" +#endif +#include +#include +#include +#include +#include + +#include + +#include "netdissect.h" +#include "extract.h" + +static const char tstr[] = "[|pflog]"; + +static const struct tok pf_reasons[] = { + { 0, "0(match)" }, + { 1, "1(bad-offset)" }, + { 2, "2(fragment)" }, + { 3, "3(short)" }, + { 4, "4(normalize)" }, + { 5, "5(memory)" }, + { 6, "6(bad-timestamp)" }, + { 7, "7(congestion)" }, + { 8, "8(ip-option)" }, + { 9, "9(proto-cksum)" }, + { 10, "10(state-mismatch)" }, + { 11, "11(state-insert)" }, + { 12, "12(state-limit)" }, + { 13, "13(src-limit)" }, + { 14, "14(synproxy)" }, + { 0, NULL } +}; + +static const struct tok pf_actions[] = { + { PF_PASS, "pass" }, + { PF_DROP, "block" }, + { PF_SCRUB, "scrub" }, + { PF_NAT, "nat" }, + { PF_NONAT, "nat" }, + { PF_BINAT, "binat" }, + { PF_NOBINAT, "binat" }, + { PF_RDR, "rdr" }, + { PF_NORDR, "rdr" }, + { PF_SYNPROXY_DROP, "synproxy-drop" }, + { 0, NULL } +}; + +static const struct tok pf_directions[] = { + { PF_INOUT, "in/out" }, + { PF_IN, "in" }, + { PF_OUT, "out" }, + { 0, NULL } +}; + +/* For reading capture files on other systems */ +#define OPENBSD_AF_INET 2 +#define OPENBSD_AF_INET6 24 + +static void +pflog_print(netdissect_options *ndo, const struct pfloghdr *hdr) +{ + uint32_t rulenr, subrulenr; + + rulenr = EXTRACT_32BITS(&hdr->rulenr); + subrulenr = EXTRACT_32BITS(&hdr->subrulenr); + if (subrulenr == (uint32_t)-1) + ND_PRINT((ndo, "rule %u/", rulenr)); + else + ND_PRINT((ndo, "rule %u.%s.%u/", rulenr, hdr->ruleset, subrulenr)); + + ND_PRINT((ndo, "%s: %s %s on %s: ", + tok2str(pf_reasons, "unkn(%u)", hdr->reason), + tok2str(pf_actions, "unkn(%u)", hdr->action), + tok2str(pf_directions, "unkn(%u)", hdr->dir), + hdr->ifname)); +} + +u_int +pflog_if_print(netdissect_options *ndo, const struct pcap_pkthdr *h, + register const u_char *p) +{ + u_int length = h->len; + u_int hdrlen; + u_int caplen = h->caplen; + const struct pfloghdr *hdr; + uint8_t af; + + /* check length */ + if (caplen < sizeof(uint8_t)) { + ND_PRINT((ndo, "%s", tstr)); + return (caplen); + } + +#define MIN_PFLOG_HDRLEN 45 + hdr = (const struct pfloghdr *)p; + if (hdr->length < MIN_PFLOG_HDRLEN) { + ND_PRINT((ndo, "[pflog: invalid header length!]")); + return (hdr->length); /* XXX: not really */ + } + hdrlen = BPF_WORDALIGN(hdr->length); + + if (caplen < hdrlen) { + ND_PRINT((ndo, "%s", tstr)); + return (hdrlen); /* XXX: true? */ + } + + /* print what we know */ + ND_TCHECK(*hdr); + if (ndo->ndo_eflag) + pflog_print(ndo, hdr); + + /* skip to the real packet */ + af = hdr->af; + length -= hdrlen; + caplen -= hdrlen; + p += hdrlen; + switch (af) { + + case AF_INET: +#if OPENBSD_AF_INET != AF_INET + case OPENBSD_AF_INET: /* XXX: read pcap files */ +#endif + ip_print(ndo, p, length); + break; + +#if defined(AF_INET6) || defined(OPENBSD_AF_INET6) +#ifdef AF_INET6 + case AF_INET6: +#endif /* AF_INET6 */ +#if !defined(AF_INET6) || OPENBSD_AF_INET6 != AF_INET6 + case OPENBSD_AF_INET6: /* XXX: read pcap files */ +#endif /* !defined(AF_INET6) || OPENBSD_AF_INET6 != AF_INET6 */ + ip6_print(ndo, p, length); + break; +#endif /* defined(AF_INET6) || defined(OPENBSD_AF_INET6) */ + + default: + /* address family not handled, print raw packet */ + if (!ndo->ndo_eflag) + pflog_print(ndo, hdr); + if (!ndo->ndo_suppress_default_print) + ND_DEFAULTPRINT(p, caplen); + } + + return (hdrlen); +trunc: + ND_PRINT((ndo, "%s", tstr)); + return (hdrlen); +} + +/* + * Local Variables: + * c-style: whitesmith + * c-basic-offset: 8 + * End: + */ diff --git a/pool/shard004/C/0101164_sprint.c b/pool/shard004/C/0101164_sprint.c new file mode 100644 index 0000000000000000000000000000000000000000..6f9bdf94ffe53e11a8a4ac9759c5db22e8e58c05 --- /dev/null +++ b/pool/shard004/C/0101164_sprint.c @@ -0,0 +1,81 @@ +/* Copyright (c) 2008-2011 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: + * * 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 Freescale Semiconductor nor the + * names of its 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") as published by the Free Software + * Foundation, either version 2 of that License or (at your option) any + * later version. + * + * THIS SOFTWARE IS PROVIDED BY Freescale Semiconductor ``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 Freescale Semiconductor 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: sprint.c */ +/* */ +/* Description: */ +/* Debug routines (externals) */ +/*------------------------------------------------------*/ +#include "string_ext.h" +#include "stdlib_ext.h" +#include "ctype_ext.h" +#include "stdarg_ext.h" +#include "sprint_ext.h" +#include "std_ext.h" +#include "xx_ext.h" + + +int Sprint(char * buf, const char *fmt, ...) +{ + va_list args; + int i; + + va_start(args, fmt); + i=vsprintf(buf,fmt,args); + va_end(args); + return i; +} + +int Snprint(char * buf, uint32_t size, const char *fmt, ...) +{ + va_list args; + int i; + + va_start(args, fmt); + i=vsnprintf(buf,size,fmt,args); + va_end(args); + return i; +} + +#ifndef NCSW_VXWORKS +int Sscan(const char * buf, const char * fmt, ...) +{ + va_list args; + int i; + + va_start(args,fmt); + i = vsscanf(buf,fmt,args); + va_end(args); + return i; +} +#endif /* NCSW_VXWORKS */ diff --git a/pool/shard004/C/0101166_buf_mmap.c b/pool/shard004/C/0101166_buf_mmap.c new file mode 100644 index 0000000000000000000000000000000000000000..75599109b9fd74ddcbad9449ffce63786209b5d8 --- /dev/null +++ b/pool/shard004/C/0101166_buf_mmap.c @@ -0,0 +1,68 @@ +#include + +struct buf_mmap_user { + const char *filename; + int perm; +}; + +// "subclass"" of buf_bytes_priv +struct buf_mmap_priv { + // NOTE: this needs to be first, so that bytes operations will work without changes + struct buf_bytes_priv bytes_priv; + RMmap *mmap; +}; + +static inline struct buf_mmap_priv *get_priv_mmap(RBuffer *b) { + struct buf_mmap_priv *priv = (struct buf_mmap_priv *)b->priv; + r_warn_if_fail (priv); + return priv; +} + +static bool buf_mmap_init(RBuffer *b, const void *user) { + const struct buf_mmap_user *u = (const struct buf_mmap_user *)user; + struct buf_mmap_priv *priv = R_NEW0 (struct buf_mmap_priv); + if (!priv) { + return false; + } + + priv->mmap = r_file_mmap (u->filename, u->perm & R_PERM_W, 0); + if (!priv->mmap) { + free (priv); + return false; + } + priv->bytes_priv.buf = priv->mmap->buf; + priv->bytes_priv.length = priv->mmap->len; + priv->bytes_priv.offset = 0; + b->priv = priv; + return true; +} + +static bool buf_mmap_fini(RBuffer *b) { + struct buf_mmap_priv *priv = get_priv_mmap (b); + r_file_mmap_free (priv->mmap); + R_FREE (b->priv); + return true; +} + +static bool buf_mmap_resize(RBuffer *b, ut64 newsize) { + struct buf_mmap_priv *priv = get_priv_mmap (b); + if (newsize > priv->mmap->len) { + ut8 *t = r_mem_mmap_resize (priv->mmap, newsize); + if (!t) { + return false; + } + priv->bytes_priv.buf = t; + } + priv->bytes_priv.length = newsize; + return true; +} + +static const RBufferMethods buffer_mmap_methods = { + .init = buf_mmap_init, + .fini = buf_mmap_fini, + .read = buf_bytes_read, + .write = buf_bytes_write, + .get_size = buf_bytes_get_size, + .resize = buf_mmap_resize, + .seek = buf_bytes_seek, +}; diff --git a/pool/shard004/C/0101176_ioctl.c b/pool/shard004/C/0101176_ioctl.c new file mode 100644 index 0000000000000000000000000000000000000000..fe74dfecd8e6f2e6d425a6c1793ba4dfef69a681 --- /dev/null +++ b/pool/shard004/C/0101176_ioctl.c @@ -0,0 +1,151 @@ +/* + Unix SMB/CIFS implementation. + + SMB2 client ioctl 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" +#include "librpc/gen_ndr/ioctl.h" + +/* + send a ioctl request +*/ +struct smb2_request *smb2_ioctl_send(struct smb2_tree *tree, struct smb2_ioctl *io) +{ + NTSTATUS status; + struct smb2_request *req; + uint64_t max_payload_in; + uint64_t max_payload_out; + size_t max_payload; + + req = smb2_request_init_tree(tree, SMB2_OP_IOCTL, 0x38, true, + io->in.in.length+io->in.out.length); + if (req == NULL) return NULL; + + SSVAL(req->out.body, 0x02, 0); /* pad */ + SIVAL(req->out.body, 0x04, io->in.function); + smb2_push_handle(req->out.body+0x08, &io->in.file.handle); + + status = smb2_push_o32s32_blob(&req->out, 0x18, io->in.out); + if (!NT_STATUS_IS_OK(status)) { + talloc_free(req); + return NULL; + } + + SIVAL(req->out.body, 0x20, io->in.max_input_response); + + status = smb2_push_o32s32_blob(&req->out, 0x24, io->in.in); + if (!NT_STATUS_IS_OK(status)) { + talloc_free(req); + return NULL; + } + + SIVAL(req->out.body, 0x2C, io->in.max_output_response); + SBVAL(req->out.body, 0x30, io->in.flags); + + max_payload_in = io->in.out.length + io->in.in.length; + max_payload_in = MIN(max_payload_in, UINT32_MAX); + max_payload_out = io->in.max_input_response + io->in.max_output_response; + max_payload_out = MIN(max_payload_out, UINT32_MAX); + + max_payload = MAX(max_payload_in, max_payload_out); + req->credit_charge = (MAX(max_payload, 1) - 1)/ 65536 + 1; + + smb2_transport_send(req); + + return req; +} + +/* + * 3.3.4.4 Sending an Error Response + */ +static bool smb2_ioctl_is_failure(uint32_t ctl_code, NTSTATUS status, + size_t data_size) +{ + if (NT_STATUS_IS_OK(status)) { + return false; + } + + if (NT_STATUS_EQUAL(status, STATUS_BUFFER_OVERFLOW) + && ((ctl_code == FSCTL_PIPE_TRANSCEIVE) + || (ctl_code == FSCTL_PIPE_PEEK) + || (ctl_code == FSCTL_DFS_GET_REFERRALS))) { + return false; + } + + if (((ctl_code == FSCTL_SRV_COPYCHUNK) + || (ctl_code == FSCTL_SRV_COPYCHUNK_WRITE)) + && (data_size == sizeof(struct srv_copychunk_rsp))) { + /* + * copychunk responses may come with copychunk data or error + * response data, independent of status. + */ + return false; + } + + return true; +} + +/* + recv a ioctl reply +*/ +NTSTATUS smb2_ioctl_recv(struct smb2_request *req, + TALLOC_CTX *mem_ctx, struct smb2_ioctl *io) +{ + NTSTATUS status; + + if (!smb2_request_receive(req) || + smb2_ioctl_is_failure(io->in.function, req->status, + req->in.bufinfo.data_size)) { + return smb2_request_destroy(req); + } + + SMB2_CHECK_PACKET_RECV(req, 0x30, true); + + io->out.reserved = SVAL(req->in.body, 0x02); + io->out.function = IVAL(req->in.body, 0x04); + smb2_pull_handle(req->in.body+0x08, &io->out.file.handle); + + status = smb2_pull_o32s32_blob(&req->in, mem_ctx, req->in.body+0x18, &io->out.in); + if (!NT_STATUS_IS_OK(status)) { + smb2_request_destroy(req); + return status; + } + + status = smb2_pull_o32s32_blob(&req->in, mem_ctx, req->in.body+0x20, &io->out.out); + if (!NT_STATUS_IS_OK(status)) { + smb2_request_destroy(req); + return status; + } + + io->out.flags = IVAL(req->in.body, 0x28); + io->out.reserved2 = IVAL(req->in.body, 0x2C); + + return smb2_request_destroy(req); +} + +/* + sync ioctl request +*/ +NTSTATUS smb2_ioctl(struct smb2_tree *tree, TALLOC_CTX *mem_ctx, struct smb2_ioctl *io) +{ + struct smb2_request *req = smb2_ioctl_send(tree, io); + return smb2_ioctl_recv(req, mem_ctx, io); +} diff --git a/pool/shard004/C/0101180_sord_cas.c b/pool/shard004/C/0101180_sord_cas.c new file mode 100644 index 0000000000000000000000000000000000000000..f842f90c9dbcb7e64a35b6416f08b0b9b582a48b --- /dev/null +++ b/pool/shard004/C/0101180_sord_cas.c @@ -0,0 +1,138 @@ +/************************************************************************** + + sord_cas.c + + Format code for Sord M5 cassette files + +**************************************************************************/ + +#include +#include "sord_cas.h" + +#define SORDM5_WAVESAMPLES_HEADER 1 +#define SORDM5_WAVESAMPLES_TRAILER 1 +#define SORDM5_WAVESAMPLES_BLOCK 1 + +static const UINT8 SORDM5_CAS_HEADER[6] = { 'S', 'O', 'R', 'D', 'M', '5'}; + +static const struct CassetteModulation sordm5_cas_modulation = +{ + CASSETTE_MODULATION_SINEWAVE, + 1575.0 - 300, 1575.0, 1575.0 + 300, + 3150.0 - 600, 3150.0, 3150.0 + 600 +}; + +static UINT8 cassette_image_read_uint8( cassette_image *cassette, UINT64 offset) +{ + UINT8 data; + cassette_image_read( cassette, &data, offset, 1); + return data; +} + +static casserr_t sordm5_tap_identify( cassette_image *cassette, struct CassetteOptions *opts) +{ + return cassette_modulation_identify( cassette, &sordm5_cas_modulation, opts); +} + +static casserr_t sordm5_tap_load( cassette_image *cassette) +{ + casserr_t err; + UINT64 image_size; + double time_index = 0.0; + double time_displacement; + UINT8 header[16]; + UINT64 image_pos; + UINT8 block_type, byte, bit; + UINT32 block_size, i, j; + size_t filler_length; + // init + image_size = cassette_image_size(cassette); + image_pos = 0; + // read/check header + if (image_size < 16) return CASSETTE_ERROR_INVALIDIMAGE; + cassette_image_read( cassette, &header, image_pos, 16); + image_pos += 16; + if (memcmp( header, SORDM5_CAS_HEADER, sizeof(SORDM5_CAS_HEADER)) != 0) return CASSETTE_ERROR_INVALIDIMAGE; + // add silence (header) + err = cassette_put_sample( cassette, 0, time_index, SORDM5_WAVESAMPLES_HEADER, 0); + if (err) return err; + time_index += SORDM5_WAVESAMPLES_HEADER; + // process blocks + while (image_pos < image_size) + { + // read block type + block_type = cassette_image_read_uint8( cassette, image_pos + 0); + if ((block_type != 'H') && (block_type != 'D')) return CASSETTE_ERROR_INVALIDIMAGE; + // read block size + block_size = cassette_image_read_uint8( cassette, image_pos + 1); + if (block_size == 0) block_size = 0x100; + block_size += 3; + // add silence (header block) + if (block_type == 'H') + { + err = cassette_put_sample( cassette, 0, time_index, SORDM5_WAVESAMPLES_BLOCK, 0); + if (err) return err; + time_index += SORDM5_WAVESAMPLES_BLOCK; + } + // add sync + if (block_type == 'H') filler_length = 2.4 * (3150 / 8); else filler_length = 0.15 * (3150 / 8); + err = cassette_put_modulated_filler(cassette, 0, time_index, 0xFF, filler_length, &sordm5_cas_modulation, &time_displacement); + if (err) return err; + time_index += time_displacement; + // process block + for (i=0;i 2) crc += byte; + #endif + // process byte + for (j=0;j<10;j++) + { + // get bit + if (j < 2) + { + bit = ((j==0)?1:0); + } + else + { + bit = (byte >> (j-2)) & 1; + } + // add bit + err = cassette_put_modulated_data_bit( cassette, 0, time_index, bit, &sordm5_cas_modulation, &time_displacement); + if (err) return err; + time_index += time_displacement; + } + } + // mark end of block + err = cassette_put_modulated_data_bit( cassette, 0, time_index, 1, &sordm5_cas_modulation, &time_displacement); + if (err) return err; + time_index += time_displacement; + // next block + image_pos += block_size; + } + // add silence (trailer) + err = cassette_put_sample( cassette, 0, time_index, SORDM5_WAVESAMPLES_TRAILER, 0); + if (err) return err; + time_index += SORDM5_WAVESAMPLES_TRAILER; + // + return CASSETTE_ERROR_SUCCESS; +} + +static const struct CassetteFormat sordm5_cas_format = +{ + "cas", + sordm5_tap_identify, + sordm5_tap_load, + NULL +}; + +CASSETTE_FORMATLIST_START(sordm5_cassette_formats) + CASSETTE_FORMAT(sordm5_cas_format) +CASSETTE_FORMATLIST_END diff --git a/pool/shard004/C/0101182_gcspy_test_server.c b/pool/shard004/C/0101182_gcspy_test_server.c new file mode 100644 index 0000000000000000000000000000000000000000..c5ba5d93666d993d7d4100c093fd2ef48a3bc71b --- /dev/null +++ b/pool/shard004/C/0101182_gcspy_test_server.c @@ -0,0 +1,97 @@ +/** + ** Copyright (c) 2002 Sun Microsystems, Inc. + ** + ** See the file "license.terms" for information on usage and redistribution + ** of this file, and for a DISCLAIMER OF ALL WARRANTIES. + **/ + +/** + ** gcspy_test_server.c + ** + ** A test server to test the framework + **/ + +#include +#include + +#include "gcspy_comm.h" +#include "gcspy_timer.h" + +#define MAX_SIZE ( 32 * 1024 ) + +int +main (int argc, char *argv[]) { + gcspy_comm_server_t server; + gcspy_comm_client_t client; + int port; + int i, size; + char *buffer; + + if (argc != 2) { + gcspy_raise_error("Wrong number of arguments"); + } + + port = atoi(argv[1]); + + printf("-- Starting server on port %d\n", port); + gcspy_serverInit(&server, port, 5); + + printf("-- Waiting for a new client\n"); + gcspy_serverWaitForNewClient(&server, &client, MAX_SIZE); + + printf("-- Connection established\n"); + printf("\n"); + + printf("-- Receiving data\n"); + gcspy_clientReceive(&client); + while ( 1 ) { + if (gcspy_client_has_terminated(&client)) { + printf("-- Client closed\n"); + goto the_end; + } + + size = gcspy_client_get_len(&client); + buffer = gcspy_client_get_buffer_in(&client); + printf("-- Received %d bytes\n", size); + printf("-- Data:"); + for (i = 0; i < size; ++i) + printf(" %d", buffer[i]); + printf("\n"); + + if (buffer[0] == 66) + break; + + printf("\n"); + printf("-- Receiving data\n"); + gcspy_clientReceive(&client); + } + + printf("-- Receive finished\n"); + printf("\n"); + + buffer = gcspy_client_get_buffer_out(&client); + + for (i = 0; i < 3; ++i) { + printf("-- Sending data\n"); + buffer[0] = 1; + buffer[1] = 2; + buffer[2] = 3; + gcspy_clientSend(&client, 3); + + gcspy_wait(2000); + } + + printf("-- Sending last value\n"); + buffer[0] = 66; + gcspy_clientSend(&client, 1); + + gcspy_wait(1000); + +the_end: + printf("\n"); + printf("-- Closing client\n"); + gcspy_clientClose(&client); + + printf("-- Closing server\n"); + gcspy_serverClose(&server); +} diff --git a/pool/shard004/C/0101188_httpdemo.c b/pool/shard004/C/0101188_httpdemo.c new file mode 100644 index 0000000000000000000000000000000000000000..ec49a0f939445a2dff12f2dad0b0b97afb1d3b90 --- /dev/null +++ b/pool/shard004/C/0101188_httpdemo.c @@ -0,0 +1,183 @@ +/* $Id$ */ +/* + * Copyright (C) 2008-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 + */ + +/** + * \page page_httpdemo_c Samples: HTTP Client demo + * + * This file is pjsip-apps/src/samples/httpdemo.c + * + * \includelineno httpdemo.c + */ + +#include +#include +#include +#include +#include +#include +#include + +static pj_timer_heap_t *timer_heap; +static pj_ioqueue_t *ioqueue; +static pj_pool_t *pool; +static pj_http_req *http_req; +static pj_pool_factory *mem; +static FILE *f = NULL; + +//#define VERBOSE +#define THIS_FILE "http_demo" + +static void on_response(pj_http_req *req, const pj_http_resp *resp) +{ + unsigned i; + + PJ_UNUSED_ARG(req); + PJ_LOG(3,(THIS_FILE, "%.*s %d %.*s", (int)resp->version.slen, resp->version.ptr, + resp->status_code, + (int)resp->reason.slen, resp->reason.ptr)); + + for (i=0; iheaders.count; ++i) { + const pj_http_header_elmt *h = &resp->headers.header[i]; + + if (!pj_stricmp2(&h->name, "Content-Length") || + !pj_stricmp2(&h->name, "Content-Type")) + { + PJ_LOG(3,(THIS_FILE, "%.*s: %.*s", + (int)h->name.slen, h->name.ptr, + (int)h->value.slen, h->value.ptr)); + } + } +} + +static void on_send_data(pj_http_req *req, void **data, pj_size_t *size) +{ + PJ_UNUSED_ARG(req); + PJ_UNUSED_ARG(size); + PJ_UNUSED_ARG(data); +} + +static void on_data_read(pj_http_req *hreq, void *data, pj_size_t size) +{ + PJ_UNUSED_ARG(hreq); + + if (size > 0) { + fwrite(data, 1, size, f); + fflush(f); +#ifdef VERBOSE + PJ_LOG(3, (THIS_FILE, "Data received: %d bytes", size)); + printf("%.*s\n", (int)size, (char *)data); +#endif + } +} + +static void on_complete(pj_http_req *hreq, pj_status_t status, + const pj_http_resp *resp) +{ + PJ_UNUSED_ARG(hreq); + + if (status != PJ_SUCCESS) { + PJ_PERROR(1, (THIS_FILE, status, "HTTP request completed with error")); + return; + } + PJ_LOG(3, (THIS_FILE, "Data completed: %d bytes", resp->size)); + if (resp->size > 0 && resp->data) { +#ifdef VERBOSE + printf("%.*s\n", (int)resp->size, (char *)resp->data); +#endif + } +} + +pj_status_t getURL(const char *curl) +{ + pj_str_t url; + pj_http_req_callback hcb; + pj_status_t status; + + pj_bzero(&hcb, sizeof(hcb)); + hcb.on_complete = &on_complete; + hcb.on_data_read = &on_data_read; + hcb.on_send_data = &on_send_data; + hcb.on_response = &on_response; + + /* Create pool, timer, and ioqueue */ + pool = pj_pool_create(mem, NULL, 8192, 4096, NULL); + if (pj_timer_heap_create(pool, 16, &timer_heap)) + return -31; + if (pj_ioqueue_create(pool, 16, &ioqueue)) + return -32; + + pj_strdup2(pool, &url, curl); + + if ((status = pj_http_req_create(pool, &url, timer_heap, ioqueue, + NULL, &hcb, &http_req)) != PJ_SUCCESS) + return status; + + if ((status = pj_http_req_start(http_req)) != PJ_SUCCESS) + return status; + + while (pj_http_req_is_running(http_req)) { + pj_time_val delay = {0, 50}; + pj_ioqueue_poll(ioqueue, &delay); + pj_timer_heap_poll(timer_heap, NULL); + } + + pj_http_req_destroy(http_req); + pj_ioqueue_destroy(ioqueue); + pj_timer_heap_destroy(timer_heap); + pj_pool_release(pool); + + return PJ_SUCCESS; +} +/* + * main() + */ +int main(int argc, char *argv[]) +{ + pj_caching_pool cp; + pj_status_t status; + + if (argc < 2 || argc > 3) { + puts("Usage: httpdemo URL [output-filename]"); + return 1; + } + + pj_log_set_level(5); + + pj_init(); + pj_caching_pool_init(&cp, NULL, 0); + mem = &cp.factory; + pjlib_util_init(); + + if (argc > 2) + f = fopen(argv[2], "wb"); + else + f = stdout; + + status = getURL(argv[1]); + if (status != PJ_SUCCESS) { + PJ_PERROR(1, (THIS_FILE, status, "Error")); + } + + if (f != stdout) + fclose(f); + + pj_caching_pool_destroy(&cp); + pj_shutdown(); + return 0; +} diff --git a/pool/shard004/C/0101189_Formatter03.c b/pool/shard004/C/0101189_Formatter03.c new file mode 100644 index 0000000000000000000000000000000000000000..b557b8e636a834b437ab266b93e5270afc171066 --- /dev/null +++ b/pool/shard004/C/0101189_Formatter03.c @@ -0,0 +1,126 @@ +/*************************************************************************************************** + + Zyan Disassembler Library (Zydis) + + Original Author : Florian Bernd + + * 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. + +***************************************************************************************************/ + +/** + * @file + * @brief Demonstrates the tokenizing feature of the `ZydisFormatter` class. + */ + +#include +#include +#include +#include + +/* ============================================================================================== */ +/* Static data */ +/* ============================================================================================== */ + +static const char* const TOKEN_TYPES[] = +{ + "INVALID ", + "WHITESPACE ", + "DELIMITER ", + "PARENTHESIS_OPEN ", + "PARENTHESIS_CLOSE", + "PREFIX ", + "MNEMONIC ", + "REGISTER ", + "ADDRESS_ABS ", + "ADDRESS_REL ", + "DISPLACEMENT ", + "IMMEDIATE ", + "TYPECAST ", + "DECORATOR ", + "SYMBOL " +}; + +/* ============================================================================================== */ +/* Helper functions */ +/* ============================================================================================== */ + +static void DisassembleBuffer(ZydisDecoder* decoder, ZyanU8* data, ZyanUSize length) +{ + ZydisFormatter formatter; + ZydisFormatterInit(&formatter, ZYDIS_FORMATTER_STYLE_INTEL); + ZydisFormatterSetProperty(&formatter, ZYDIS_FORMATTER_PROP_FORCE_SEGMENT, ZYAN_TRUE); + ZydisFormatterSetProperty(&formatter, ZYDIS_FORMATTER_PROP_FORCE_SIZE, ZYAN_TRUE); + + ZyanU64 runtime_address = 0x007FFFFFFF400000; + + ZydisDecodedInstruction instruction; + char buffer[256]; + while (ZYAN_SUCCESS(ZydisDecoderDecodeBuffer(decoder, data, length, &instruction))) + { + const ZydisFormatterToken* token; + if (ZYAN_SUCCESS(ZydisFormatterTokenizeInstruction(&formatter, &instruction, &buffer[0], + sizeof(buffer), runtime_address, &token))) + { + ZydisTokenType token_type; + ZyanConstCharPointer token_value = ZYAN_NULL; + while (token) + { + ZydisFormatterTokenGetValue(token, &token_type, &token_value); + printf("ZYDIS_TOKEN_%17s (%02X): \"%s\"\n", TOKEN_TYPES[token_type], token_type, + token_value); + if (!ZYAN_SUCCESS(ZydisFormatterTokenNext(&token))) + { + token = ZYAN_NULL; + } + } + } + data += instruction.length; + length -= instruction.length; + runtime_address += instruction.length; + } +} + +/* ============================================================================================== */ +/* Entry point */ +/* ============================================================================================== */ + +int main(void) +{ + if (ZydisGetVersion() != ZYDIS_VERSION) + { + fputs("Invalid zydis version\n", ZYAN_STDERR); + return EXIT_FAILURE; + } + + ZyanU8 data[] = + { + // vcmpps k2 {k7}, zmm2, dword ptr ds:[rax + rbx*4 + 0x100] {1to16}, 0x0F + 0x62, 0xF1, 0x6C, 0x5F, 0xC2, 0x54, 0x98, 0x40, 0x0F + }; + + ZydisDecoder decoder; + ZydisDecoderInit(&decoder, ZYDIS_MACHINE_MODE_LONG_64, ZYDIS_ADDRESS_WIDTH_64); + + DisassembleBuffer(&decoder, &data[0], sizeof(data)); + + return 0; +} + +/* ============================================================================================== */ diff --git a/pool/shard004/C/0101194_msm_zen_decision.c b/pool/shard004/C/0101194_msm_zen_decision.c new file mode 100644 index 0000000000000000000000000000000000000000..3025092a593e3d4ede7674147b79c6f1622106d5 --- /dev/null +++ b/pool/shard004/C/0101194_msm_zen_decision.c @@ -0,0 +1,349 @@ +/* linux/arch/arm/mach-msm/msm_zen_decision.c + * + * In-kernel solution to replace CPU hotplug work that breaks from + * disabling certain MSM userspace applications. + * + * Copyright (c) 2015 Brandon Berhent + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License version 2 and + * only version 2 as published by the Free Software Foundation. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#define ZEN_DECISION "zen_decision" + +/* Enable/Disable driver */ +unsigned int enabled = 0; + +/* + * How long to wait to enable cores on wake (in ms) + */ +#define WAKE_WAIT_TIME_MAX 60000 // 1 minute maximum +unsigned int wake_wait_time = 1000; + +/* + * Battery level threshold to ignore UP operations. + * Only do CPU_UP work when battery level is above this value. + * + * Setting to 0 will do CPU_UP work regardless of battery level. + */ +unsigned int bat_threshold_ignore = 15; + +/* FB Notifier */ +static struct notifier_block fb_notifier; + +/* Worker Stuff */ +static struct workqueue_struct *zen_wake_wq; +static struct delayed_work wake_work; + +/* Sysfs stuff */ +struct kobject *zendecision_kobj; + +/* Power supply information */ +static struct power_supply *psy; +union power_supply_propval current_charge; + +/* + * Some devices may have a different name power_supply device representing the battery. + * + * If we can't find the "battery" device, then we ignore all battery work, which means + * we do the CPU_UP work regardless of the battery level. + */ +char ps_name[] = "battery"; + +static int get_power_supply_level(void) +{ + int ret; + if (!psy) { + ret = -ENXIO; + return ret; + } + + /* + * On at least some MSM devices POWER_SUPPLY_PROP_CAPACITY represents current + * battery level as an integer between 0 and 100. + * + * Unknown if other devices use this property or a different one. + */ + ret = psy->get_property(psy, POWER_SUPPLY_PROP_CAPACITY, ¤t_charge); + if (ret) + return ret; + + return current_charge.intval; +} + +/* + * msm_zd_online_cpus + * + * Core wake work function. + * Brings all CPUs online. Called from worker thread. + */ +static void __ref msm_zd_online_all_cpus(struct work_struct *work) +{ + int cpu; + + for_each_cpu_not(cpu, cpu_online_mask) { + cpu_up(cpu); + } +} + +/* + * msm_zd_queue_online_work + * + * Call msm_zd_online_all_cpus as a delayed worker thread on wake_wq. + * Delayed by wake_wait_time. + */ +static void msm_zd_queue_online_work(void) +{ + queue_delayed_work(zen_wake_wq, &wake_work, + msecs_to_jiffies(wake_wait_time)); +} + +/** Use FB notifiers to detect screen off/on and do the work **/ +static int fb_notifier_callback(struct notifier_block *nb, + unsigned long event, void *data) +{ + int *blank; + struct fb_event *evdata = data; + + /* If driver is disabled just leave here */ + if (!enabled) + return 0; + + /* Clear wake workqueue of any pending threads */ + flush_workqueue(zen_wake_wq); + cancel_delayed_work_sync(&wake_work); + + if (evdata && evdata->data && event == FB_EVENT_BLANK) { + blank = evdata->data; + if (*blank == FB_BLANK_UNBLANK) { + /* Always queue work if PS device doesn't exist or bat_threshold_ignore == 0 */ + if (psy && bat_threshold_ignore) { + /* If current level > ignore threshold, then queue UP work */ + if (get_power_supply_level() > bat_threshold_ignore) + msm_zd_queue_online_work(); + } else + msm_zd_queue_online_work(); + } + } + + return 0; +} + +/* Sysfs Start */ +static ssize_t enable_show(struct kobject *kobj, + struct kobj_attribute *attr, char *buf) +{ + return sprintf(buf, "%u\n", enabled); +} + +static ssize_t enable_store(struct kobject *kobj, + struct kobj_attribute *attr, const char *buf, size_t size) +{ + int ret; + unsigned long new_val; + + ret = kstrtoul(buf, 0, &new_val); + if (ret < 0) + return ret; + + if (new_val > 0) + enabled = 1; + else + enabled = 0; + + return size; +} + +static ssize_t wake_delay_show(struct kobject *kobj, + struct kobj_attribute *attr, char *buf) +{ + return sprintf(buf, "%u\n", wake_wait_time); +} + +static ssize_t wake_delay_store(struct kobject *kobj, + struct kobj_attribute *attr, const char *buf, size_t size) +{ + int ret; + unsigned long new_val; + ret = kstrtoul(buf, 0, &new_val); + if (ret < 0) + return ret; + + /* Restrict value between 0 and WAKE_WAIT_TIME_MAX */ + wake_wait_time = new_val > WAKE_WAIT_TIME_MAX ? WAKE_WAIT_TIME_MAX : new_val; + + return size; +} + +static ssize_t bat_threshold_ignore_show(struct kobject *kobj, + struct kobj_attribute *attr, char *buf) +{ + return sprintf(buf, "%u\n", bat_threshold_ignore); +} + +static ssize_t bat_threshold_ignore_store(struct kobject *kobj, + struct kobj_attribute *attr, const char *buf, size_t size) +{ + int ret; + unsigned long new_val; + ret = kstrtoul(buf, 0, &new_val); + if (ret < 0) + return ret; + + /* Restrict between 0 and 100 */ + if (new_val > 100) + bat_threshold_ignore = 100; + else + bat_threshold_ignore = new_val; + + return size; +} + +static struct kobj_attribute kobj_enabled = + __ATTR(enabled, 0644, enable_show, + enable_store); + +static struct kobj_attribute kobj_wake_wait = + __ATTR(wake_wait_time, 0644, wake_delay_show, + wake_delay_store); + +static struct kobj_attribute kobj_bat_threshold_ignore = + __ATTR(bat_threshold_ignore, 0644, bat_threshold_ignore_show, + bat_threshold_ignore_store); + +static struct attribute *zd_attrs[] = { + &kobj_enabled.attr, + &kobj_wake_wait.attr, + &kobj_bat_threshold_ignore.attr, + NULL, +}; + +static struct attribute_group zd_option_group = { + .attrs = zd_attrs, +}; + +/* Sysfs End */ + +static int zd_probe(struct platform_device *pdev) +{ + int ret; + + /* Setup sysfs */ + zendecision_kobj = kobject_create_and_add("zen_decision", kernel_kobj); + if (zendecision_kobj == NULL) { + pr_err("[%s]: subsystem register failed. \n", ZEN_DECISION); + return -ENOMEM; + } + + ret = sysfs_create_group(zendecision_kobj, &zd_option_group); + if (ret) { + pr_info("[%s]: sysfs interface failed to initialize\n", ZEN_DECISION); + return -EINVAL; + } + + /* Setup Workqueues */ + zen_wake_wq = alloc_workqueue("zen_wake_wq", WQ_FREEZABLE | WQ_UNBOUND, 1); + if (!zen_wake_wq) { + pr_err("[%s]: Failed to allocate suspend workqueue\n", ZEN_DECISION); + return -ENOMEM; + } + INIT_DELAYED_WORK(&wake_work, msm_zd_online_all_cpus); + + /* Setup FB Notifier */ + fb_notifier.notifier_call = fb_notifier_callback; + if (fb_register_client(&fb_notifier)) { + pr_err("[%s]: failed to register FB notifier\n", ZEN_DECISION); + return -ENOMEM; + } + + /* Setup power supply */ + psy = power_supply_get_by_name(ps_name); + // We can continue without finding PS info, print debug info + if (!psy) + pr_warn("[%s]: power supply '%s' not found, continuing without \n", ZEN_DECISION, ps_name); + else + pr_info("[%s]: power supply '%s' found\n", ZEN_DECISION, ps_name); + + /* Everything went well, lets say we loaded successfully */ + pr_info("[%s]: driver initialized successfully \n", ZEN_DECISION); + + return ret; +} + +static int zd_remove(struct platform_device *pdev) +{ + kobject_put(zendecision_kobj); + + flush_workqueue(zen_wake_wq); + cancel_delayed_work_sync(&wake_work); + destroy_workqueue(zen_wake_wq); + + fb_unregister_client(&fb_notifier); + fb_notifier.notifier_call = NULL; + + return 0; +} + +static struct platform_driver zd_driver = { + .probe = zd_probe, + .remove = zd_remove, + .driver = { + .name = ZEN_DECISION, + .owner = THIS_MODULE, + } +}; + +static struct platform_device zd_device = { + .name = ZEN_DECISION, + .id = -1 +}; + +static int __init zd_init(void) +{ + int ret = platform_driver_register(&zd_driver); + if (ret) + pr_err("[%s]: platform_driver_register failed: %d\n", ZEN_DECISION, ret); + else + pr_info("[%s]: platform_driver_register succeeded\n", ZEN_DECISION); + + + ret = platform_device_register(&zd_device); + if (ret) + pr_err("[%s]: platform_device_register failed: %d\n", ZEN_DECISION, ret); + else + pr_info("[%s]: platform_device_register succeeded\n", ZEN_DECISION); + + return ret; +} + +static void __exit zd_exit(void) +{ + platform_driver_unregister(&zd_driver); + platform_device_unregister(&zd_device); +} + +late_initcall(zd_init); +module_exit(zd_exit); + +MODULE_VERSION("2.0"); +MODULE_DESCRIPTION("Zen Decision - Kernel MSM Userspace Handler"); +MODULE_LICENSE("GPL v2"); +MODULE_AUTHOR("Brandon Berhent "); + diff --git a/pool/shard004/C/0101198_linux_systemroot.c b/pool/shard004/C/0101198_linux_systemroot.c new file mode 100644 index 0000000000000000000000000000000000000000..afeb5097423d8a620618f04a55929e65cf9f6208 --- /dev/null +++ b/pool/shard004/C/0101198_linux_systemroot.c @@ -0,0 +1,189 @@ +/* + * linux_systemroot.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 "common/talpa.h" +#include "platforms/linux/glue.h" +#include "platforms/linux/vfs_mount.h" +#include "platforms/linux/alloc.h" +#include "linux_systemroot.h" + + + +/* + * Forward declare implementation methods. + */ +static void* directoryEntry(const void* self); +static void* mountPoint(const void* self); +static void deleteLinuxSystemRoot(struct tag_LinuxSystemRoot* object); + + +/* + * Template Object. + */ +static LinuxSystemRoot template_LinuxSystemRoot = + { + { + directoryEntry, + mountPoint, + NULL, + (void (*)(void*))deleteLinuxSystemRoot + }, + deleteLinuxSystemRoot, + NULL, + NULL +}; +#define this ((LinuxSystemRoot*)self) + +/* + * Object creation/destruction. + */ +LinuxSystemRoot* newLinuxSystemRoot(void) +{ + LinuxSystemRoot* object; + unsigned m_seq = 0; + + + object = talpa_alloc(sizeof(template_LinuxSystemRoot)); + if ( object ) + { + struct task_struct* inittask; + + + memcpy(object, &template_LinuxSystemRoot, sizeof(template_LinuxSystemRoot)); + object->i_ISystemRoot.object = object; + + talpa_tasklist_lock(); + inittask = talpa_find_task_by_pid(1); + talpa_tasklist_unlock(); + + if ( inittask ) + { + struct fs_struct *init_fs; + struct vfsmount *rootmnt; + + task_lock(inittask); + init_fs = inittask->fs; + if ( init_fs ) + { +#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,30) + #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,36) + spin_lock(&init_fs->lock); + #else + write_lock(&init_fs->lock); + #endif + init_fs->users++; + #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,36) + spin_unlock(&init_fs->lock); + #else + write_unlock(&init_fs->lock); + #endif +#else + atomic_inc(&init_fs->count); +#endif + } + task_unlock(inittask); + + if ( init_fs ) + { +#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,36) + spin_lock(&init_fs->lock); +#else + write_lock(&init_fs->lock); +#endif + + +restart_mnt: + talpa_vfsmount_lock(&m_seq); // locks dcache_lock on 2.4 + for (rootmnt = talpa_fs_mnt(init_fs); rootmnt != getParent(rootmnt); rootmnt = getParent(rootmnt)); + object->mMnt = mntget(rootmnt); + object->mDentry = dget(rootmnt->mnt_root); + if (talpa_vfsmount_unlock(&m_seq)) // unlocks dcache_lock on 2.4 + { + goto restart_mnt; + } + #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,30) + init_fs->users--; + #else + atomic_dec(&init_fs->count); + #endif +#if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,36) + spin_unlock(&init_fs->lock); +#else + write_unlock(&init_fs->lock); +#endif + } + } + + if ( !object->mMnt || !object->mDentry ) + { + if ( object->mMnt ) + { + mntput(object->mMnt); + } + + if ( object->mDentry ) + { + dput(object->mDentry); + } + + talpa_free(object); + + return NULL; + } + } + + return object; +} + +static void deleteLinuxSystemRoot(struct tag_LinuxSystemRoot* object) +{ + dput(object->mDentry); + mntput(object->mMnt); + + talpa_free(object); + return; +} + +/* + * ISystemRoot. + */ +static void* directoryEntry(const void* self) +{ + return this->mDentry; +} + +static void* mountPoint(const void* self) +{ + return this->mMnt; +} + +/* + * End of linux_systemroot.c + */ + diff --git a/pool/shard004/C/0101199_test_lpm6_perf.c b/pool/shard004/C/0101199_test_lpm6_perf.c new file mode 100644 index 0000000000000000000000000000000000000000..be47d4a18de70f0b2c3405fe04183a3b63393451 --- /dev/null +++ b/pool/shard004/C/0101199_test_lpm6_perf.c @@ -0,0 +1,187 @@ +/*- + * BSD LICENSE + * + * Copyright(c) 2010-2014 Intel Corporation. All rights reserved. + * 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 "test.h" +#include "test_lpm6_routes.h" + +#define TEST_LPM_ASSERT(cond) do { \ + if (!(cond)) { \ + printf("Error at line %d: \n", __LINE__); \ + return -1; \ + } \ +} while(0) + +#define ITERATIONS (1 << 10) +#define BATCH_SIZE 100000 +#define NUMBER_TBL8S (1 << 16) + +static void +print_route_distribution(const struct rules_tbl_entry *table, uint32_t n) +{ + unsigned i, j; + + printf("Route distribution per prefix width: \n"); + printf("DEPTH QUANTITY (PERCENT)\n"); + printf("--------------------------- \n"); + + /* Count depths. */ + for(i = 1; i <= 128; i++) { + unsigned depth_counter = 0; + double percent_hits; + + for (j = 0; j < n; j++) + if (table[j].depth == (uint8_t) i) + depth_counter++; + + percent_hits = ((double)depth_counter)/((double)n) * 100; + printf("%.2u%15u (%.2f)\n", i, depth_counter, percent_hits); + } + printf("\n"); +} + +static int +test_lpm6_perf(void) +{ + struct rte_lpm6 *lpm = NULL; + struct rte_lpm6_config config; + uint64_t begin, total_time; + unsigned i, j; + uint8_t next_hop_add = 0xAA, next_hop_return = 0; + int status = 0; + int64_t count = 0; + + config.max_rules = 1000000; + config.number_tbl8s = NUMBER_TBL8S; + config.flags = 0; + + rte_srand(rte_rdtsc()); + + printf("No. routes = %u\n", (unsigned) NUM_ROUTE_ENTRIES); + + print_route_distribution(large_route_table, (uint32_t) NUM_ROUTE_ENTRIES); + + lpm = rte_lpm6_create(__func__, SOCKET_ID_ANY, &config); + TEST_LPM_ASSERT(lpm != NULL); + + /* Measure add. */ + begin = rte_rdtsc(); + + for (i = 0; i < NUM_ROUTE_ENTRIES; i++) { + if (rte_lpm6_add(lpm, large_route_table[i].ip, + large_route_table[i].depth, next_hop_add) == 0) + status++; + } + /* End Timer. */ + total_time = rte_rdtsc() - begin; + + printf("Unique added entries = %d\n", status); + printf("Average LPM Add: %g cycles\n", + (double)total_time / NUM_ROUTE_ENTRIES); + + /* Measure single Lookup */ + total_time = 0; + count = 0; + + for (i = 0; i < ITERATIONS; i ++) { + begin = rte_rdtsc(); + + for (j = 0; j < NUM_IPS_ENTRIES; j ++) { + if (rte_lpm6_lookup(lpm, large_ips_table[j].ip, + &next_hop_return) != 0) + count++; + } + + total_time += rte_rdtsc() - begin; + + } + printf("Average LPM Lookup: %.1f cycles (fails = %.1f%%)\n", + (double)total_time / ((double)ITERATIONS * BATCH_SIZE), + (count * 100.0) / (double)(ITERATIONS * BATCH_SIZE)); + + /* Measure bulk Lookup */ + total_time = 0; + count = 0; + + uint8_t ip_batch[NUM_IPS_ENTRIES][16]; + int16_t next_hops[NUM_IPS_ENTRIES]; + + for (i = 0; i < NUM_IPS_ENTRIES; i++) + memcpy(ip_batch[i], large_ips_table[i].ip, 16); + + for (i = 0; i < ITERATIONS; i ++) { + + /* Lookup per batch */ + begin = rte_rdtsc(); + rte_lpm6_lookup_bulk_func(lpm, ip_batch, next_hops, NUM_IPS_ENTRIES); + total_time += rte_rdtsc() - begin; + + for (j = 0; j < NUM_IPS_ENTRIES; j++) + if (next_hops[j] < 0) + count++; + } + printf("BULK LPM Lookup: %.1f cycles (fails = %.1f%%)\n", + (double)total_time / ((double)ITERATIONS * BATCH_SIZE), + (count * 100.0) / (double)(ITERATIONS * BATCH_SIZE)); + + /* Delete */ + status = 0; + begin = rte_rdtsc(); + + for (i = 0; i < NUM_ROUTE_ENTRIES; i++) { + /* rte_lpm_delete(lpm, ip, depth) */ + status += rte_lpm6_delete(lpm, large_route_table[i].ip, + large_route_table[i].depth); + } + + total_time += rte_rdtsc() - begin; + + printf("Average LPM Delete: %g cycles\n", + (double)total_time / NUM_ROUTE_ENTRIES); + + rte_lpm6_delete_all(lpm); + rte_lpm6_free(lpm); + + return 0; +} + +REGISTER_TEST_COMMAND(lpm6_perf_autotest, test_lpm6_perf); diff --git a/pool/shard004/C/0101208_input.c b/pool/shard004/C/0101208_input.c new file mode 100644 index 0000000000000000000000000000000000000000..6caf6202fde910254c1353fc77b71de406856140 --- /dev/null +++ b/pool/shard004/C/0101208_input.c @@ -0,0 +1,162 @@ +/* + * Copyright (C) 2012-2013 Evgeny Panov + * This file is part of libvrender. + * + * libvrender is free software: you can 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. + * + * libvrender is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with libvrender. If not, see . + */ + +#include "input.h" + +// массив состояний клавиш клавиатуры +static int input_kb_keys_state[MAX_KB_KEYS]; + +// массив состояний кнопок мыши +static int input_mouse_btns_state[MAX_MOUSE_BUTTONS]; + +static int current_mouse_x = 0, current_mouse_y = 0; +static float current_wheel_rot = 0.0f; + +static unsigned wheel_limit_from = 0, wheel_limit_to = 0; + +static int init = 0; + +void input_init(void) +{ + int i = 0; + + IF_FAILED(!init); + + TRACE_MSG("init input system\n"); + + for(i = 0; i < MAX_KB_KEYS; i++) { + input_kb_keys_state[i] = 0; + } + + for(i = 0; i < MAX_MOUSE_BUTTONS; i++) { + input_mouse_btns_state[i] = 0; + } + + init = 1; +} + +int input_get_kbkey_state(unsigned int key) +{ + if(key > KB_NULL && key < MAX_KB_KEYS) { + return input_kb_keys_state[key]; + } + + // неверный код клавиши + return -1; +} + +int input_get_mousebtn_state(unsigned int key) +{ + if(key > MOUSE_NULL && key < MAX_MOUSE_BUTTONS) { + return input_mouse_btns_state[key]; + } + + // неверный код кнопки + return -1; +} + +void input_get_mouse_position(int *mouse_x, int *mouse_y) +{ + if(mouse_x) + *mouse_x = current_mouse_x; + if(mouse_y) + *mouse_y = current_mouse_y; +} + +float input_get_wheel_rot(void) +{ + return current_wheel_rot; +} + +void input_set_wheel_limits(unsigned from, unsigned to) +{ + wheel_limit_from = from; + wheel_limit_to = to; + + current_wheel_rot = (from+to) / 2.0f; +} + +void input_event_on_keypress(unsigned key) +{ + IF_FAILED(init); + + // код клавиши должен быть валидный + if(key > KB_NULL && key < MAX_KB_KEYS) { + input_kb_keys_state[key] = 1; + } +} + +void input_event_on_keyreleased(unsigned key) +{ + IF_FAILED(init); + + if(key > KB_NULL && key < MAX_KB_KEYS) { + input_kb_keys_state[key] = 0; + + // если мы отпустили букву в верхнем регистре (или нижнем), + // то мы также отпустили и в нижнем (верхнем) регистре + if(key >= KB_A && key <= KB_Z) + input_kb_keys_state[(key - KB_A)+KB_a] = 0; + else if(key >= KB_a && key <= KB_z) + input_kb_keys_state[(key - KB_a)+KB_A] = 0; + } +} + +void input_event_on_btnpress(unsigned key, int mouse_x, int mouse_y) +{ + IF_FAILED(init); + + if(key > MOUSE_NULL && key < MAX_MOUSE_BUTTONS) { + input_mouse_btns_state[key] = 1; + + current_mouse_x = mouse_x; + current_mouse_y = mouse_y; + } +} + +void input_event_on_btnreleased(unsigned key, int mouse_x, int mouse_y) +{ + IF_FAILED(init); + + if(key > MOUSE_NULL && key < MAX_MOUSE_BUTTONS) { + input_mouse_btns_state[key] = 0; + + current_mouse_x = mouse_x; + current_mouse_y = mouse_y; + } +} + +void input_event_on_mouse_motion(int mouse_x, int mouse_y) +{ + IF_FAILED(init); + + current_mouse_x = mouse_x; + current_mouse_y = mouse_y; +} + +void input_event_on_mouse_wheel(float steps) +{ + IF_FAILED(init); + + current_wheel_rot += steps; + + if(current_wheel_rot > wheel_limit_to) + current_wheel_rot = wheel_limit_to; + else if(current_wheel_rot < wheel_limit_from) + current_wheel_rot = wheel_limit_from; +} diff --git a/pool/shard004/C/0101210_up_boot.c b/pool/shard004/C/0101210_up_boot.c new file mode 100644 index 0000000000000000000000000000000000000000..93f6e966c9e3368a716f6c2dd8340484efce9ed5 --- /dev/null +++ b/pool/shard004/C/0101210_up_boot.c @@ -0,0 +1,214 @@ +/**************************************************************************** + * + * Copyright 2017 Samsung Electronics All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, + * either express or implied. See the License for the specific + * language governing permissions and limitations under the License. + * + ****************************************************************************/ +/************************************************************************************ + * configs/lm3s6965-ek/src/up_boot.c + * arch/arm/src/board/up_boot.c + * + * Copyright (C) 2010 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 + +#ifdef CONFIG_MTD +#include +#include +#endif + +#include "up_arch.h" +#include "up_internal.h" +#include "lm3s6965ek_internal.h" + +/************************************************************************************ + * Definitions + ************************************************************************************/ + +/************************************************************************************ + * Private Functions + ************************************************************************************/ + +/************************************************************************************ + * Public Functions + ************************************************************************************/ + +/************************************************************************************ + * Name: tiva_boardinitialize + * + * Description: + * All Stellaris architectures must provide the following entry point. This entry + * point is called early in the intitialization -- after all memory has been + * configured and mapped but before any devices have been initialized. + * + ************************************************************************************/ + +void tiva_boardinitialize(void) +{ + /* Configure SPI chip selects if 1) SSI is not disabled, and 2) the weak function + * lm_ssiinitialize() has been brought into the link. + */ + + /* The LM3S6965 Eval Kit microSD CS and OLED are on SSI0 (Duh! There is no SSI1) */ + +#if defined(CONFIG_TIVA_SSI0) /* || defined(CONFIG_TIVA_SSI1) */ + if (lm_ssiinitialize) { + lm_ssiinitialize(); + } +#endif + + /* Configure on-board LEDs if LED support has been selected. */ + +#ifdef CONFIG_ARCH_LEDS + board_led_initialize(); +#endif +} + + +#ifdef CONFIG_BOARD_INITIALIZE + +#if defined(CONFIG_QEMU_SRAM) || defined (CONFIG_QEMU_SDRAM) + +#define QEMU_SMARTFS_PARTITION_START (0) +#define QEMU_SMARTFS_PARTITION_SIZE (1024 * 1024) /* 1MB */ +#define QEMU_SMARTFS_PARTITION_PARTNO (0) +#define QEMU_SMARTFS_PARTITION_MINORNO (0) +#define QEMU_SMARTFS_MOUNT_POINT "/mnt" + +/************************************************************************************ + * Name: board_initialize + * + * Description: + * Board specific intialization after os app start + * + ************************************************************************************/ + +int board_initialize(void) +{ + int ret; + char partref[4]; + char devname[16]; +#ifdef CONFIG_MTD + FAR struct mtd_dev_s *mtd; + FAR struct mtd_geometry_s geo; + FAR struct mtd_dev_s *mtd_part; +#endif + int partno = QEMU_SMARTFS_PARTITION_PARTNO; + int minorno = QEMU_SMARTFS_PARTITION_MINORNO; + int partoffset = QEMU_SMARTFS_PARTITION_START; + int partsize = QEMU_SMARTFS_PARTITION_SIZE; + +#ifdef CONFIG_MTD + mtd = up_flashinitialize(); + + if (!mtd) { + lldbg("ERROR : up_flashinitializ failed\n"); + return ERROR; + } + + if (mtd->ioctl(mtd, MTDIOC_GEOMETRY, (unsigned long)&geo) < 0) { + lldbg("ERROR: mtd->ioctl failed\n"); + return ERROR; + } + +#ifdef CONFIG_MTD_PARTITION + mtd_part = mtd_partition(mtd, partoffset, partsize / geo.blocksize, partno); + if (!mtd_part) { + lldbg("ERROR: failed to create partition.\n"); + return ERROR; + } +#endif /* CONFIG_MTD_PARTITION */ + + ret = snprintf(partref, sizeof(partref), "p%d", partno); + if (ret < 0) { + lldbg("ERROR: snprintf failed while constructing partref, ret = %d\n", ret); + return ERROR; + } + + if (ret >= sizeof(partref)) { + lldbg("WARNING: snprintf output might have truncated, ret = %d\n", ret); + } + + ret = snprintf(devname, sizeof(devname), "/dev/smart%d%s", minorno, partref); + if (ret < 0) { + lldbg("ERROR: snprintf failed while constructing devname, ret = %d\n", ret); + return ERROR; + } + + if (ret >= sizeof(devname)) { + lldbg("WARNING: snprintf output might have truncated, ret = %d\n", ret); + } + + +#if defined(CONFIG_MTD_SMART) && defined(CONFIG_FS_SMARTFS) + smart_initialize(minorno, mtd_part, partref); +#endif /* defined(CONFIG_MTD_SMART) && defined(CONFIG_FS_SMARTFS) */ + +#endif /* CONFIG_MTD */ + + ret = mksmartfs(devname, false); + + if (ret != OK) { + lldbg("ERROR: mksmartfs on %s failed, ret = %d\n", devname, ret); + } else { + ret = mount(devname, QEMU_SMARTFS_MOUNT_POINT, "smartfs", 0, NULL); + if (ret != OK) { + lldbg("ERROR: mounting '%s' failed, ret = %d\n", devname, ret); + } else { + lldbg("%s is mounted successfully at %s \n", devname, QEMU_SMARTFS_MOUNT_POINT); + } + } + + return OK; +} +#endif /* defined(CONFIG_QEMU_SRAM) || defined (CONFIG_QEMU_SDRAM) */ +#endif /* CONFIG_BOARD_INITIALIZE */ diff --git a/pool/shard004/C/0101216_creat05.c b/pool/shard004/C/0101216_creat05.c new file mode 100644 index 0000000000000000000000000000000000000000..ae29bffa5caec0f085df0626598095392f505400 --- /dev/null +++ b/pool/shard004/C/0101216_creat05.c @@ -0,0 +1,197 @@ +/* + * + * 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 + */ + +/* + * NAME + * creat05.c + * + * DESCRIPTION + * Testcase to check that creat(2) system call returns EMFILE. + * + * ALGORITHM + * A process creates a temporary test directory, then it should + * get the system configured NOFILE parameter (ie. the maximum no. of + * open files of a process). This can be done using the getdtablesize() + * system call. Once this is determined, the process should attempt + * to creat(2) the this no. of files (can be done using a "for" loop). + * Then, the process should attempt to creat() another file, which should + * fail with EMFILE. + * + * USAGE + * creat05 + * + * HISTORY + * 07/2001 Ported by Wayne Boyer + * + * RESTRICTIONS + * None + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "test.h" +#include "usctest.h" + +char *TCID = "creat05"; +int TST_TOTAL = 1; + +#define MODE 0666 + +void remove_files(int); +void setup(void); +void cleanup(void); + +int exp_enos[] = { EMFILE, 0 }; + +int fd, ifile, mypid, first; +int *buf; +char fname[40]; + +int main(int ac, char **av) +{ + int lc; + char *msg; + + if ((msg = parse_opts(ac, av, NULL, NULL)) != NULL) { + tst_brkm(TBROK, NULL, "OPTION PARSING ERROR - %s", msg); + } + + setup(); + + TEST_EXP_ENOS(exp_enos); + + for (lc = 0; TEST_LOOPING(lc); lc++) { + + /* reset Tst_count in case we are looping */ + Tst_count = 0; + + TEST(creat(fname, MODE)); + + if (TEST_RETURN != -1) { + tst_resm(TFAIL, "call succeeded unexpectedly"); + continue; + } + + TEST_ERROR_LOG(TEST_ERRNO); + + if (TEST_ERRNO == EMFILE) { + tst_resm(TPASS, "call failed with expected error - " + "EMFILE"); + } else { + tst_resm(TFAIL|TTERRNO, "Expected EMFILE"); + } + + remove_files(ifile); + } + cleanup(); + + tst_exit(); +} + +/* + * setup() - performs all ONE TIME setup for this test. + */ +void setup() +{ + int max_open; + + tst_sig(NOFORK, DEF_HANDLER, cleanup); + + TEST_PAUSE; + + /* make a temporary directory and cd to it */ + tst_tmpdir(); + + umask(0); + mypid = getpid(); + sprintf(fname, "creat05.%d", mypid); + unlink(fname); + + /* create a file to get the first file descriptor available */ + if ((first = fd = creat(fname, MODE)) == -1) { + tst_brkm(TFAIL, cleanup, "Cannot open first file"); + } + + close(fd); + unlink(fname); + tst_resm(TINFO, "first file is #%d", fd); + + /* get the maximum number of files that we can open */ + max_open = getdtablesize(); + /* Allocate memory for stat and ustat structure variables */ + if ((buf = (int *)malloc(sizeof(int) * max_open - first)) == NULL) { + tst_brkm(TBROK, NULL, "Failed to allocate Memory"); + } + + /* now open as many files as we can up to max_open */ + for (ifile = first; ifile <= max_open; ifile++) { + sprintf(fname, "creat05.%d.%d", ifile, mypid); + if ((fd = creat(fname, 0666)) == -1) { + tst_resm(TINFO, "could not creat file " + "#%d", ifile + 1); + if (errno != EMFILE) { + remove_files(ifile); + tst_brkm(TBROK|TERRNO, cleanup, + "Failed unexpectedly (expected EMFILE)"); + } + break; + } + buf[ifile - first] = fd; + } +} + +/* + * remove_files - remove the temporary files that were created + */ +void remove_files(int nfiles) +{ + int i; + + for (i = first; i < nfiles; i++) { + sprintf(fname, "creat05.%d.%d", i, mypid); + close(buf[i - first]); + unlink(fname); + } +} + +/* + * cleanup() - performs all ONE TIME cleanup for this test at + * completion or premature exit. + */ +void cleanup() +{ + /* + * print timing stats if that option was specified. + * print errno log if that option was specified. + */ + close(first); + + TEST_CLEANUP; + + /* delete the test directory created in setup() */ + tst_rmdir(); + +} diff --git a/pool/shard004/C/0101217_c_slsetr.c b/pool/shard004/C/0101217_c_slsetr.c new file mode 100644 index 0000000000000000000000000000000000000000..38a8109149a891c8579667398c113f3d36584dea --- /dev/null +++ b/pool/shard004/C/0101217_c_slsetr.c @@ -0,0 +1,43 @@ +/* + * $Id: c_slsetr.c,v 1.5 2008-07-23 16:17:03 haley Exp $ + */ +/************************************************************************ +* * +* Copyright (C) 2000 * +* University Corporation for Atmospheric Research * +* All Rights Reserved * +* * +* The use of this Software is governed by a License Agreement. * +* * +************************************************************************/ + +#include + +extern void NGCALLF(slsetr,SLSETR)(NGstring,float*,int); + +void c_slsetr +#ifdef NeedFuncProto +( + char *pa, + float rval +) +#else +(pa,rval) + char *pa; + float rval; +#endif +{ + NGstring pa2; + int len; +/* + * Make sure parameter name is not NULL + */ + if( !pa ) { + fprintf( stderr, "c_slsetr: illegal parameter name (NULL)\n" ); + return; + } + + len = NGSTRLEN(pa); + pa2 = NGCstrToFstr(pa,len); + NGCALLF(slsetr,SLSETR)(pa2,&rval,len); +} diff --git a/pool/shard004/C/0101227_m_away.c b/pool/shard004/C/0101227_m_away.c new file mode 100644 index 0000000000000000000000000000000000000000..d6c06325b352c016d54a2b1375adfea94ec2ad0a --- /dev/null +++ b/pool/shard004/C/0101227_m_away.c @@ -0,0 +1,259 @@ +/* + * ircd-hybrid: an advanced Internet Relay Chat Daemon(ircd). + * m_away.c: Sets/removes away status on a user. + * + * Copyright (C) 2002 by the past and present ircd coders, and others. + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 + * USA + * + * $Id: m_away.c 147 2005-12-26 02:52:10Z jon $ + */ + +#include "stdinc.h" +#include "handlers.h" +#include "client.h" +#include "irc_string.h" +#include "ircd.h" +#include "numeric.h" +#include "send.h" +#include "msg.h" +#include "parse.h" +#include "modules.h" +#include "s_conf.h" +#include "s_serv.h" +#include "packet.h" +#include "s_user.h" + +static void m_away(struct Client *, struct Client *, int, char *[]); +static void mo_away(struct Client *, struct Client *, int, char *[]); +static void ms_away(struct Client *, struct Client *, int, char *[]); + +struct Message away_msgtab = { + "AWAY", 0, 0, 0, 0, MFLG_SLOW, 0, + {m_unregistered, m_away, ms_away, m_ignore, mo_away, m_ignore} +}; + +#ifndef STATIC_MODULES +void +_modinit(void) +{ + mod_add_cmd(&away_msgtab); + add_isupport("AWAYLEN", NULL, AWAYLEN); +} + +void +_moddeinit(void) +{ + mod_del_cmd(&away_msgtab); + delete_isupport("AWAYLEN"); +} + +const char *_version = "$Revision: 147 $"; +#endif + +/*********************************************************************** + * m_away() - Added 14 Dec 1988 by jto. + * Not currently really working, I don't like this + * call at all... + * + * ...trying to make it work. I don't like it either, + * but perhaps it's worth the load it causes to net. + * This requires flooding of the whole net like NICK, + * USER, MODE, etc messages... --msa + ***********************************************************************/ + +/* + * m_away + * parv[0] = sender prefix + * parv[1] = away message + */ +static void +m_away(struct Client *client_p, struct Client *source_p, int parc, char *parv[]) +{ + char *cur_away_msg = source_p->away; + char *new_away_msg = NULL; + size_t nbytes = 0; + + if(!IsFloodDone(source_p)) + flood_endgrace(source_p); + + if(parc < 2 || EmptyString(parv[1])) + { + /* Marking as not away */ + if(cur_away_msg) + { + /* we now send this only if they were away before --is */ + sendto_server(client_p, source_p, NULL, CAP_TS6, NOCAPS, + NOFLAGS, ":%s AWAY", ID(source_p)); + sendto_server(client_p, source_p, NULL, NOCAPS, CAP_TS6, + NOFLAGS, ":%s AWAY", source_p->name); + + MyFree(cur_away_msg); + source_p->away = NULL; + } + + sendto_one(source_p, form_str(RPL_UNAWAY), me.name, source_p->name); + return; + } + + /* Marking as away */ + if((CurrentTime - source_p->localClient->last_away) < ConfigFileEntry.pace_wait) + { + sendto_one(source_p, form_str(RPL_LOAD2HI), me.name, source_p->name); + return; + } + + source_p->localClient->last_away = CurrentTime; + new_away_msg = parv[1]; + + nbytes = strlen(new_away_msg); + if(nbytes > (size_t) AWAYLEN) + { + new_away_msg[AWAYLEN] = '\0'; + nbytes = AWAYLEN; + } + + /* we now send this only if they + * weren't away already --is */ + if(!cur_away_msg) + { + sendto_server(client_p, source_p, NULL, CAP_TS6, NOCAPS, + NOFLAGS, ":%s AWAY :%s", ID(source_p), new_away_msg); + sendto_server(client_p, source_p, NULL, NOCAPS, CAP_TS6, + NOFLAGS, ":%s AWAY :%s", source_p->name, new_away_msg); + } + else + MyFree(cur_away_msg); + + cur_away_msg = MyMalloc(nbytes + 1); + strcpy(cur_away_msg, new_away_msg); + source_p->away = cur_away_msg; + + sendto_one(source_p, form_str(RPL_NOWAWAY), me.name, source_p->name); +} + +static void +mo_away(struct Client *client_p, struct Client *source_p, int parc, char *parv[]) +{ + char *cur_away_msg = source_p->away; + char *new_away_msg = NULL; + size_t nbytes = 0; + + if(!IsFloodDone(source_p)) + flood_endgrace(source_p); + + if(parc < 2 || EmptyString(parv[1])) + { + /* Marking as not away */ + if(cur_away_msg) + { + /* we now send this only if they were away before --is */ + sendto_server(client_p, source_p, NULL, CAP_TS6, NOCAPS, + NOFLAGS, ":%s AWAY", ID(source_p)); + sendto_server(client_p, source_p, NULL, NOCAPS, CAP_TS6, + NOFLAGS, ":%s AWAY", source_p->name); + + MyFree(cur_away_msg); + source_p->away = NULL; + } + + sendto_one(source_p, form_str(RPL_UNAWAY), me.name, source_p->name); + return; + } + + new_away_msg = parv[1]; + + nbytes = strlen(new_away_msg); + if(nbytes > (size_t) AWAYLEN) + { + new_away_msg[AWAYLEN] = '\0'; + nbytes = AWAYLEN; + } + + /* we now send this only if they + * weren't away already --is */ + if(!cur_away_msg) + { + sendto_server(client_p, source_p, NULL, CAP_TS6, NOCAPS, + NOFLAGS, ":%s AWAY :%s", ID(source_p), new_away_msg); + sendto_server(client_p, source_p, NULL, NOCAPS, CAP_TS6, + NOFLAGS, ":%s AWAY :%s", source_p->name, new_away_msg); + } + else + MyFree(cur_away_msg); + + cur_away_msg = MyMalloc(nbytes + 1); + strcpy(cur_away_msg, new_away_msg); + source_p->away = cur_away_msg; + + sendto_one(source_p, form_str(RPL_NOWAWAY), me.name, source_p->name); +} + +static void +ms_away(struct Client *client_p, struct Client *source_p, int parc, char *parv[]) +{ + char *cur_away_msg = NULL; + char *new_away_msg = NULL; + size_t nbytes = 0; + + if(!IsClient(source_p)) + return; + + cur_away_msg = source_p->away; + + if(parc < 2 || EmptyString(parv[1])) + { + /* Marking as not away */ + if(cur_away_msg) + { + /* we now send this only if they were away before --is */ + sendto_server(client_p, source_p, NULL, CAP_TS6, NOCAPS, + NOFLAGS, ":%s AWAY", ID(source_p)); + sendto_server(client_p, source_p, NULL, NOCAPS, CAP_TS6, + NOFLAGS, ":%s AWAY", source_p->name); + + MyFree(cur_away_msg); + source_p->away = NULL; + } + + return; + } + + new_away_msg = parv[1]; + + nbytes = strlen(new_away_msg); + if(nbytes > (size_t) AWAYLEN) + { + new_away_msg[AWAYLEN] = '\0'; + nbytes = AWAYLEN; + } + + /* we now send this only if they + * weren't away already --is */ + if(!cur_away_msg) + { + sendto_server(client_p, source_p, NULL, CAP_TS6, NOCAPS, + NOFLAGS, ":%s AWAY :%s", ID(source_p), new_away_msg); + sendto_server(client_p, source_p, NULL, NOCAPS, CAP_TS6, + NOFLAGS, ":%s AWAY :%s", source_p->name, new_away_msg); + } + else + MyFree(cur_away_msg); + + cur_away_msg = MyMalloc(nbytes + 1); + strcpy(cur_away_msg, new_away_msg); + source_p->away = cur_away_msg; +} diff --git a/pool/shard004/C/0101230_divexact_byfobm1.c b/pool/shard004/C/0101230_divexact_byfobm1.c new file mode 100644 index 0000000000000000000000000000000000000000..86f2688ee6b56014d09caf3271e8396fc343837d --- /dev/null +++ b/pool/shard004/C/0101230_divexact_byfobm1.c @@ -0,0 +1,58 @@ +/* mpn_divexact_by exact division by (B-1)/f + + Copyright 2009 Jason Moxham + + This file is part of the MPIR Library. + + The MPIR 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 MPIR 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 MPIR 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 "mpir.h" +#include "gmp-impl.h" +#include "longlong.h" + +/* + (xp, n) = (qp, n)*f - ret*B^n and 0 <= ret < f + + Note the divexact_by3 code is just a special case of this +*/ +mp_limb_t mpn_divexact_byfobm1(mp_ptr qp, mp_srcptr xp, mp_size_t n, + mp_limb_t f, mp_limb_t Bm1of) +{ + mp_size_t j; + mp_limb_t c, acc, ax, dx; + + ASSERT(n > 0); + ASSERT_MPN(xp, n); + ASSERT(MPN_SAME_OR_SEPARATE_P(qp, xp, n)); + ASSERT(Bm1of*f + 1 == 0); + + acc = 0*Bm1of; /* carry in is 0 */ + + for (j = 0; j <= n - 1; j++) + { + umul_ppmm(dx, ax, xp[j], Bm1of); + + SUBC_LIMB(c, acc, acc, ax); + + qp[j] = acc; + acc -= dx + c; + } + + /* return next quotient*(-f) */ + + return acc*(-f); +} diff --git a/pool/shard004/C/0101237_1051.c b/pool/shard004/C/0101237_1051.c new file mode 100644 index 0000000000000000000000000000000000000000..768fa05f2a9679bac37cfe41f5a5a4dedaa923ea --- /dev/null +++ b/pool/shard004/C/0101237_1051.c @@ -0,0 +1,47 @@ +/* 11051 复数乘法 (15 分) +解析: +1. 复数乘法。 +2. 当A或者B小于0但是大于-0.005(比如-0.00001)时候,如果按照A>=0的判断,会输出“-0.00”这样的结果,事实上应该输出“0.00”。 +*/ + +#include +#include +#include +#define EPSILON 0.01 + +typedef struct +{ + double real; + double imaginary; +} Complex; + +int main(int argc, char *argv[]) +{ + // 处理输入 + Complex a, b; + if (scanf("%lf %lf %lf %lf", &a.real, &a.imaginary, &b.real, &b.imaginary) != 4) + return EXIT_FAILURE; + // 计算乘积 + Complex product; + product.real = a.real * b.real * cos(a.imaginary + b.imaginary); + product.imaginary = a.real * b.real * sin(a.imaginary + b.imaginary); + if (fabs(product.real) < EPSILON) + { + product.real = 0; + } + if (fabs(product.imaginary) < EPSILON) + { + product.imaginary = 0; + } + // 处理输出 + if (product.imaginary >= 0) + { + printf("%.2f+%.2fi", product.real, product.imaginary); + } + else + { + printf("%.2f-%.2fi", product.real, -product.imaginary); + } + + return EXIT_SUCCESS; +} diff --git a/pool/shard004/C/0101244_CWE134_Uncontrolled_Format_String__wchar_t_console_fprintf_66b.c b/pool/shard004/C/0101244_CWE134_Uncontrolled_Format_String__wchar_t_console_fprintf_66b.c new file mode 100644 index 0000000000000000000000000000000000000000..ad49f34cae7afd272e1da2d82c03fb95d677464f --- /dev/null +++ b/pool/shard004/C/0101244_CWE134_Uncontrolled_Format_String__wchar_t_console_fprintf_66b.c @@ -0,0 +1,54 @@ +/* TEMPLATE GENERATED TESTCASE FILE +Filename: CWE134_Uncontrolled_Format_String__wchar_t_console_fprintf_66b.c +Label Definition File: CWE134_Uncontrolled_Format_String.label.xml +Template File: sources-sinks-66b.tmpl.c +*/ +/* + * @description + * CWE: 134 Uncontrolled Format String + * BadSource: console Read input from the console + * GoodSource: Copy a fixed string into data + * Sinks: fprintf + * GoodSink: fwprintf with "%s" as the second argument and data as the third + * BadSink : fwprintf with data as the second argument + * Flow Variant: 66 Data flow: data passed in an array from one function to another in different source files + * + * */ + +#include "std_testcase.h" + +#ifndef _WIN32 +#include +#endif + +#ifndef OMITBAD + +void CWE134_Uncontrolled_Format_String__wchar_t_console_fprintf_66b_badSink(wchar_t * dataArray[]) +{ + /* copy data out of dataArray */ + wchar_t * data = dataArray[2]; + /* POTENTIAL FLAW: Do not specify the format allowing a possible format string vulnerability */ + fwprintf(stdout, data); +} + +#endif /* OMITBAD */ + +#ifndef OMITGOOD + +/* goodG2B uses the GoodSource with the BadSink */ +void CWE134_Uncontrolled_Format_String__wchar_t_console_fprintf_66b_goodG2BSink(wchar_t * dataArray[]) +{ + wchar_t * data = dataArray[2]; + /* POTENTIAL FLAW: Do not specify the format allowing a possible format string vulnerability */ + fwprintf(stdout, data); +} + +/* goodB2G uses the BadSource with the GoodSink */ +void CWE134_Uncontrolled_Format_String__wchar_t_console_fprintf_66b_goodB2GSink(wchar_t * dataArray[]) +{ + wchar_t * data = dataArray[2]; + /* FIX: Specify the format disallowing a format string vulnerability */ + fwprintf(stdout, L"%s\n", data); +} + +#endif /* OMITGOOD */ diff --git a/pool/shard004/C/0101246_usnic_debugfs.c b/pool/shard004/C/0101246_usnic_debugfs.c new file mode 100644 index 0000000000000000000000000000000000000000..5e55b8bc6fe402af423118c1454b5bc67d21d8ba --- /dev/null +++ b/pool/shard004/C/0101246_usnic_debugfs.c @@ -0,0 +1,169 @@ +/* + * Copyright (c) 2013, Cisco Systems, Inc. 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 + * 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 "usnic.h" +#include "usnic_log.h" +#include "usnic_debugfs.h" +#include "usnic_ib_qp_grp.h" +#include "usnic_transport.h" + +static struct dentry *debugfs_root; +static struct dentry *flows_dentry; + +static ssize_t usnic_debugfs_buildinfo_read(struct file *f, char __user *data, + size_t count, loff_t *ppos) +{ + char buf[500]; + int res; + + if (*ppos > 0) + return 0; + + res = scnprintf(buf, sizeof(buf), + "version: %s\n" + "build date: %s\n", + DRV_VERSION, DRV_RELDATE); + + return simple_read_from_buffer(data, count, ppos, buf, res); +} + +static const struct file_operations usnic_debugfs_buildinfo_ops = { + .owner = THIS_MODULE, + .open = simple_open, + .read = usnic_debugfs_buildinfo_read +}; + +static ssize_t flowinfo_read(struct file *f, char __user *data, + size_t count, loff_t *ppos) +{ + struct usnic_ib_qp_grp_flow *qp_flow; + int n; + int left; + char *ptr; + char buf[512]; + + qp_flow = f->private_data; + ptr = buf; + left = count; + + if (*ppos > 0) + return 0; + + spin_lock(&qp_flow->qp_grp->lock); + n = scnprintf(ptr, left, + "QP Grp ID: %d Transport: %s ", + qp_flow->qp_grp->grp_id, + usnic_transport_to_str(qp_flow->trans_type)); + UPDATE_PTR_LEFT(n, ptr, left); + if (qp_flow->trans_type == USNIC_TRANSPORT_ROCE_CUSTOM) { + n = scnprintf(ptr, left, "Port_Num:%hu\n", + qp_flow->usnic_roce.port_num); + UPDATE_PTR_LEFT(n, ptr, left); + } else if (qp_flow->trans_type == USNIC_TRANSPORT_IPV4_UDP) { + n = usnic_transport_sock_to_str(ptr, left, + qp_flow->udp.sock); + UPDATE_PTR_LEFT(n, ptr, left); + n = scnprintf(ptr, left, "\n"); + UPDATE_PTR_LEFT(n, ptr, left); + } + spin_unlock(&qp_flow->qp_grp->lock); + + return simple_read_from_buffer(data, count, ppos, buf, ptr - buf); +} + +static const struct file_operations flowinfo_ops = { + .owner = THIS_MODULE, + .open = simple_open, + .read = flowinfo_read, +}; + +void usnic_debugfs_init(void) +{ + debugfs_root = debugfs_create_dir(DRV_NAME, NULL); + if (IS_ERR(debugfs_root)) { + usnic_err("Failed to create debugfs root dir, check if debugfs is enabled in kernel configuration\n"); + goto out_clear_root; + } + + flows_dentry = debugfs_create_dir("flows", debugfs_root); + if (IS_ERR_OR_NULL(flows_dentry)) { + usnic_err("Failed to create debugfs flow dir with err %ld\n", + PTR_ERR(flows_dentry)); + goto out_free_root; + } + + debugfs_create_file("build-info", S_IRUGO, debugfs_root, + NULL, &usnic_debugfs_buildinfo_ops); + return; + +out_free_root: + debugfs_remove_recursive(debugfs_root); +out_clear_root: + debugfs_root = NULL; +} + +void usnic_debugfs_exit(void) +{ + if (!debugfs_root) + return; + + debugfs_remove_recursive(debugfs_root); + debugfs_root = NULL; +} + +void usnic_debugfs_flow_add(struct usnic_ib_qp_grp_flow *qp_flow) +{ + if (IS_ERR_OR_NULL(flows_dentry)) + return; + + scnprintf(qp_flow->dentry_name, sizeof(qp_flow->dentry_name), + "%u", qp_flow->flow->flow_id); + qp_flow->dbgfs_dentry = debugfs_create_file(qp_flow->dentry_name, + S_IRUGO, + flows_dentry, + qp_flow, + &flowinfo_ops); + if (IS_ERR_OR_NULL(qp_flow->dbgfs_dentry)) { + usnic_err("Failed to create dbg fs entry for flow %u\n", + qp_flow->flow->flow_id); + } +} + +void usnic_debugfs_flow_remove(struct usnic_ib_qp_grp_flow *qp_flow) +{ + if (!IS_ERR_OR_NULL(qp_flow->dbgfs_dentry)) + debugfs_remove(qp_flow->dbgfs_dentry); +} diff --git a/pool/shard004/C/0101251_redo_log.c b/pool/shard004/C/0101251_redo_log.c new file mode 100644 index 0000000000000000000000000000000000000000..cb90b0521e94d4e61b6823601bc0c19217406a0a --- /dev/null +++ b/pool/shard004/C/0101251_redo_log.c @@ -0,0 +1,164 @@ +/** + @file redo_log.c Provides redolog functions. + */ + +/* + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Library General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor Boston, MA 02110-1301, USA + */ + +#include "redo_log.h" + +/** + * @author @author Krunoslav Bilić updated by Dražen Bandić, second update by Tomislav Turek + * @brief Function adds new element to redolog + * @return EXIT_FAILURE if not allocated memory for ispis, otherwise EXIT_SUCCESS + */ +int AK_add_to_redolog(int command, struct list_node *row_root){ + AK_PRO; + + if (redo_log == NULL) + return EXIT_FAILURE; + int n = redo_log->number; + printf("AK_add_to_redolog: Recovery checkpoint %d\n", n); + + if(n == MAX_REDO_LOG_ENTRIES){ + AK_archive_log(-10); + n = 0; + } + + struct list_node * el = (struct list_node *) Ak_First_L2(row_root); + + char* record; + if((record = (char*) AK_calloc(MAX_VARCHAR_LENGTH, sizeof(char))) == NULL){ + AK_EPI; + return EXIT_FAILURE; + } + + char table[MAX_ATT_NAME]; + memset(table, '\0', MAX_ATT_NAME); + memcpy(&table, el->table, strlen(el->table)); + + int max = AK_num_attr(table); + int numAttr = 1; + + char** attrs = AK_calloc(MAX_ATTRIBUTES, sizeof(char*)); + int i = 0; + while (el != NULL) { + switch (el->type) { + + case FREE_CHAR: + strncat(record, "null", 4); + attrs[i] = "null"; + break; + case TYPE_INT: + attrs[i] = (char*) AK_malloc(MAX_VARCHAR_LENGTH * sizeof(char)); + sprintf (attrs[i], "%i", *((int *) el->data)); + strncat(record, attrs[i], strlen(attrs[i])); + break; + case TYPE_FLOAT: + attrs[i] = (char*) AK_malloc(MAX_VARCHAR_LENGTH * sizeof(char)); + sprintf (attrs[i], "%.3f", *((float *) el->data)); + strncat(record, attrs[i], strlen(attrs[i])); + break; + case TYPE_VARCHAR: + default: + attrs[i] = AK_check_attributes(el->data); + strncat(record, attrs[i], strlen(el->data)); + break; + } + if(numAttr < max){ + strncat(record, "|", 1); + } + numAttr++; + i++; + el = el->next; + } + + printf("AK_add_to_redolog: redolog new entry -- %s, %s\n", table, record); + memcpy(redo_log->command_recovery[n].table_name, table, strlen(table)); + for(i=0; icommand_recovery[n].arguments[i], attrs[i]); + redo_log->command_recovery[n].operation = command; + redo_log->command_recovery[n].finished = 0; + redo_log->number = n+1; + AK_free(record); + for(i=0; i < numAttr-1; i++) + AK_free(attrs[i]); + AK_free(attrs); + printf("AK_add_to_redolog: Recovery checkpoint saved\n"); + AK_EPI; + return EXIT_SUCCESS; +} + +void AK_redolog_commit() { + int i; + for(i = 0; i < redo_log->number; i++) { + redo_log->command_recovery[i].finished = 1; + } +} + + +/** + * @author Krunoslav Bilić updated by Dražen Bandić, second update by Tomislav Turek + * @brief Function prints out the content of redolog memory + * @return No return value. + */ +void AK_printout_redolog(){ + AK_PRO; + int x = redo_log->number; + int i = 0; + for (i = 0; i < x; i++){ + printf("%d. %s %s %s\n", i, redo_log->command_recovery[i].table_name, + redo_log->command_recovery[i].operation, redo_log->command_recovery[i].arguments); + } + AK_EPI; +} + +/** + * @author Dražen Bandić + * @brief Checks if the attribute contains '|', and if it does it replaces it with "\|" + * @return new attribute + */ +char* AK_check_attributes(char *attributes){ + AK_PRO; + int n = strlen(attributes); + + if( attributes[n-1] == '\\' ){ + if( n == MAX_VARCHAR_LENGTH ) + attributes[n-1] = ' '; + else + attributes[n] = ' '; + } + + char* result = AK_malloc(MAX_VARCHAR_LENGTH * sizeof(char)); + int index = 0; + int att_index = 0; + + do{ + if ( attributes[att_index] == '|' ){ + if ( index + 2 <= MAX_VARCHAR_LENGTH ){ + result[index++] = '\\'; + result[index++] = '|'; + } else { + break; + } + } else { + result[index++] = attributes[att_index]; + } + att_index++; + } while ( att_index < n || index < MAX_VARCHAR_LENGTH); + AK_EPI; + return result; +} diff --git a/pool/shard004/C/0101252_huff.c b/pool/shard004/C/0101252_huff.c new file mode 100644 index 0000000000000000000000000000000000000000..7011765ac3fe9a08566dc3a39c2ee35aa983744d --- /dev/null +++ b/pool/shard004/C/0101252_huff.c @@ -0,0 +1,171 @@ +#include "huff.h" + +void storeSymbolCount(unsigned char *in, huffchar *s, unsigned int size) { + int i, ch; + /* Initialize all Characters/Symbols in the array huffchar *s */ + for(i = 0; i < CHARS; i++) { + s[i].symbol = i; + s[i].count = s[i].path = s[i].bits = 0; + } + /* Calculating and storing the frequency of each symbol */ + for(i = 0; i < size; i++) { + ch = *in; + s[ch].count++; + in++; + } +} + +void GenerateHuffTree(huffchar *s, bitstream *strm) { + huffnode node[MAXNODES]; + int k, num = 0; + + /* Initialize all Symbol Nodes with at least one Count */ + for(k = 0; k < CHARS; k++) { + if(s[k].count > 0) { + node[num].symbol = s[k].symbol; + node[num].count = s[k].count; + node[num].C1 = node[num].C2 = (huffnode*) 0; + num++; + } + } + + huffnode *n1, *n2, *root; + root = (huffnode*) 0; + int total = num; + + /* Creating a dummy node for comparisions */ + huffnode *n; + n = (huffnode*) malloc (sizeof(huffnode)); + n->count = INT_MAX; + + /* Look for the TWO Lowest Count Nodes */ + while(total > 1) { + n1 = n2 = (huffnode*) 0; + + for(k = 0; k < num; k++) { + if(node[k].count > 0) { + if (!n1 || node[k].count <= n1->count) { + n2 = n1; + n1 = &node[k]; + } + else if (!n2 || node[k].count <= n2->count) + n2 = &node[k]; + } + } + + /* Join the nodes */ + total--; + root = &node[num]; + root->C1 = n1; + root->C2 = n2; + root->symbol = -1; + root->count = n1->count + n2->count; + n1->count = n2->count = 0; + num++; + } + if(root) + StoreHuffTree(root, s, strm, 0, 0); + else + StoreHuffTree(&node[0], s, strm, 0, 0); + return; +} + +void StoreHuffTree(huffnode *node, huffchar *s, bitstream *strm, int path, int bits) { + int k; + + /* If Leaf Node && Symbol exists*/ + if(node->symbol >= 0) { + /* Write 1 followed by character in the bitstream */ + writeBits(strm, 1, 1); + writeBits(strm, node->symbol, 8); + + /* Store Path in the Symbol array huffchar *s for encoding*/ + for(k = 0; k < CHARS; k++) + if(node->symbol == s[k].symbol) + break; + s[k].path = path; + s[k].bits = bits; + return; + } + else + writeBits(strm, 0, 1); + + /* Recursive Storage */ + StoreHuffTree(node->C1, s, strm, (path<<1) + 0, bits + 1); + StoreHuffTree(node->C2, s, strm, (path<<1) + 1, bits + 1); +} + +huffnode* ReadHuffTree(huffnode *node, bitstream *strm, int *num) { + huffnode *currnode = &node[*num]; + (*num)++; + currnode->symbol = -1; + currnode->C1 = (huffnode*) 0; + currnode->C2 = (huffnode*) 0; + /* 1 indicates leaf node and that a symbol follows whereas 0 moves to next child */ + if(readBit(strm)) { + currnode->symbol = readByte(strm); + return currnode; + } + + /* Recursive Reading */ + currnode->C1 = ReadHuffTree(node, strm, num); + currnode->C2 = ReadHuffTree(node, strm, num); + + return currnode; +} + +void HuffUncompress(unsigned char *in, unsigned char *out, unsigned int insize) { + /* Is there anything to Decompress */ + if(insize < 1) return; + + huffnode node[MAXNODES], *root, *n; + bitstream strm; + initBitStream(&strm, in); + int num = 0, k; + + root = ReadHuffTree(node, &strm, &num); + + unsigned char *buf; + buf = out; + + for(k = 0; k < insize; k++) { + n = root; + + while(n->symbol < 0) { + if(readBit(&strm)) + n = n->C2; + else + n = n->C1; + } + *buf ++ = (unsigned char) n->symbol; + } +} + +unsigned int HuffCompress(unsigned char *in, unsigned char *out, int insize) { + bitstream strm; + int k = 0, symbol; + huffchar sym[CHARS]; + + initBitStream(&strm, out); + storeSymbolCount(in, sym, insize); + GenerateHuffTree(sym, &strm); + + /* Encode all characters of the in stream and write path and bits to the out stream */ + for(k = 0; k <= insize; k++) { + symbol = in[k]; + writeBits(&strm, sym[symbol].path, sym[symbol].bits); + } + + long outsize = (int) (strm.currbyte - out); + outsize++; + return outsize; +} + +void printhuffchar(huffchar *s) { + int i; + for(i = 0; i < CHARS; i++) { + if(s[i].count > 0) + printf("%c %d %d %d\n", s[i].symbol, s[i].count, s[i].path, s[i].bits); + } +} + diff --git a/pool/shard004/C/0101258_hid-penmount.c b/pool/shard004/C/0101258_hid-penmount.c new file mode 100644 index 0000000000000000000000000000000000000000..bac2e7e9b344ceae0b2deb237a6518901d4e0518 --- /dev/null +++ b/pool/shard004/C/0101258_hid-penmount.c @@ -0,0 +1,59 @@ +/* + * HID driver for PenMount touchscreens + * + * Copyright (c) 2014 Christian Gmeiner gmail.com> + * + * based on hid-penmount copyrighted by + * PenMount Touch Solutions seed.net.tw> + */ + +/* + * 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 "hid-ids.h" + +static int penmount_input_mapping(struct hid_device *hdev, + struct hid_input *hi, struct hid_field *field, + struct hid_usage *usage, unsigned long **bit, int *max) +{ + if ((usage->hid & HID_USAGE_PAGE) == HID_UP_BUTTON) + { + if (((usage->hid - 1) & HID_USAGE) == 0) + { + hid_map_usage(hi, usage, bit, max, EV_KEY, BTN_TOUCH); + return 1; + } + else + { + return -1; + } + } + + return 0; +} + +static const struct hid_device_id penmount_devices[] = +{ + { HID_USB_DEVICE(USB_VENDOR_ID_PENMOUNT, USB_DEVICE_ID_PENMOUNT_6000) }, + { } +}; +MODULE_DEVICE_TABLE(hid, penmount_devices); + +static struct hid_driver penmount_driver = +{ + .name = "hid-penmount", + .id_table = penmount_devices, + .input_mapping = penmount_input_mapping, +}; + +module_hid_driver(penmount_driver); + +MODULE_AUTHOR("Christian Gmeiner "); +MODULE_DESCRIPTION("PenMount HID TouchScreen driver"); +MODULE_LICENSE("GPL"); diff --git a/pool/shard004/C/0101259_vmx_tsc_adjust_test.c b/pool/shard004/C/0101259_vmx_tsc_adjust_test.c new file mode 100644 index 0000000000000000000000000000000000000000..69e482a95c47f5f9c8be165f8bc08eb69f0b429f --- /dev/null +++ b/pool/shard004/C/0101259_vmx_tsc_adjust_test.c @@ -0,0 +1,168 @@ +// SPDX-License-Identifier: GPL-2.0-only +/* + * vmx_tsc_adjust_test + * + * Copyright (C) 2018, Google LLC. + * + * IA32_TSC_ADJUST test + * + * According to the SDM, "if an execution of WRMSR to the + * IA32_TIME_STAMP_COUNTER MSR adds (or subtracts) value X from the TSC, + * the logical processor also adds (or subtracts) value X from the + * IA32_TSC_ADJUST MSR. + * + * Note that when L1 doesn't intercept writes to IA32_TSC, a + * WRMSR(IA32_TSC) from L2 sets L1's TSC value, not L2's perceived TSC + * value. + * + * This test verifies that this unusual case is handled correctly. + */ + +#include "test_util.h" +#include "kvm_util.h" +#include "processor.h" +#include "vmx.h" + +#include +#include + +#include "kselftest.h" + +#ifndef MSR_IA32_TSC_ADJUST +#define MSR_IA32_TSC_ADJUST 0x3b +#endif + +#define PAGE_SIZE 4096 +#define VCPU_ID 5 + +#define TSC_ADJUST_VALUE (1ll << 32) +#define TSC_OFFSET_VALUE -(1ll << 48) + +enum { + PORT_ABORT = 0x1000, + PORT_REPORT, + PORT_DONE, +}; + +enum { + VMXON_PAGE = 0, + VMCS_PAGE, + MSR_BITMAP_PAGE, + + NUM_VMX_PAGES, +}; + +struct kvm_single_msr { + struct kvm_msrs header; + struct kvm_msr_entry entry; +} __attribute__((packed)); + +/* The virtual machine object. */ +static struct kvm_vm *vm; + +static void check_ia32_tsc_adjust(int64_t max) +{ + int64_t adjust; + + adjust = rdmsr(MSR_IA32_TSC_ADJUST); + GUEST_SYNC(adjust); + GUEST_ASSERT(adjust <= max); +} + +static void l2_guest_code(void) +{ + uint64_t l1_tsc = rdtsc() - TSC_OFFSET_VALUE; + + wrmsr(MSR_IA32_TSC, l1_tsc - TSC_ADJUST_VALUE); + check_ia32_tsc_adjust(-2 * TSC_ADJUST_VALUE); + + /* Exit to L1 */ + __asm__ __volatile__("vmcall"); +} + +static void l1_guest_code(struct vmx_pages *vmx_pages) +{ +#define L2_GUEST_STACK_SIZE 64 + unsigned long l2_guest_stack[L2_GUEST_STACK_SIZE]; + uint32_t control; + uintptr_t save_cr3; + + GUEST_ASSERT(rdtsc() < TSC_ADJUST_VALUE); + wrmsr(MSR_IA32_TSC, rdtsc() - TSC_ADJUST_VALUE); + check_ia32_tsc_adjust(-1 * TSC_ADJUST_VALUE); + + GUEST_ASSERT(prepare_for_vmx_operation(vmx_pages)); + GUEST_ASSERT(load_vmcs(vmx_pages)); + + /* Prepare the VMCS for L2 execution. */ + prepare_vmcs(vmx_pages, l2_guest_code, + &l2_guest_stack[L2_GUEST_STACK_SIZE]); + control = vmreadz(CPU_BASED_VM_EXEC_CONTROL); + control |= CPU_BASED_USE_MSR_BITMAPS | CPU_BASED_USE_TSC_OFFSETTING; + vmwrite(CPU_BASED_VM_EXEC_CONTROL, control); + vmwrite(TSC_OFFSET, TSC_OFFSET_VALUE); + + /* Jump into L2. First, test failure to load guest CR3. */ + save_cr3 = vmreadz(GUEST_CR3); + vmwrite(GUEST_CR3, -1ull); + GUEST_ASSERT(!vmlaunch()); + GUEST_ASSERT(vmreadz(VM_EXIT_REASON) == + (EXIT_REASON_FAILED_VMENTRY | EXIT_REASON_INVALID_STATE)); + check_ia32_tsc_adjust(-1 * TSC_ADJUST_VALUE); + vmwrite(GUEST_CR3, save_cr3); + + GUEST_ASSERT(!vmlaunch()); + GUEST_ASSERT(vmreadz(VM_EXIT_REASON) == EXIT_REASON_VMCALL); + + check_ia32_tsc_adjust(-2 * TSC_ADJUST_VALUE); + + GUEST_DONE(); +} + +static void report(int64_t val) +{ + printf("IA32_TSC_ADJUST is %ld (%lld * TSC_ADJUST_VALUE + %lld).\n", + val, val / TSC_ADJUST_VALUE, val % TSC_ADJUST_VALUE); +} + +int main(int argc, char *argv[]) +{ + vm_vaddr_t vmx_pages_gva; + + nested_vmx_check_supported(); + + vm = vm_create_default(VCPU_ID, 0, (void *) l1_guest_code); + vcpu_set_cpuid(vm, VCPU_ID, kvm_get_supported_cpuid()); + + /* Allocate VMX pages and shared descriptors (vmx_pages). */ + vcpu_alloc_vmx(vm, &vmx_pages_gva); + vcpu_args_set(vm, VCPU_ID, 1, vmx_pages_gva); + + for (;;) { + volatile struct kvm_run *run = vcpu_state(vm, VCPU_ID); + struct ucall uc; + + vcpu_run(vm, VCPU_ID); + TEST_ASSERT(run->exit_reason == KVM_EXIT_IO, + "Got exit_reason other than KVM_EXIT_IO: %u (%s)\n", + run->exit_reason, + exit_reason_str(run->exit_reason)); + + switch (get_ucall(vm, VCPU_ID, &uc)) { + case UCALL_ABORT: + TEST_ASSERT(false, "%s", (const char *)uc.args[0]); + /* NOT REACHED */ + case UCALL_SYNC: + report(uc.args[1]); + break; + case UCALL_DONE: + goto done; + default: + TEST_ASSERT(false, "Unknown ucall 0x%x.", uc.cmd); + } + } + + kvm_vm_free(vm); +done: + return 0; +} diff --git a/pool/shard004/C/0101271_speakup_decext.c b/pool/shard004/C/0101271_speakup_decext.c new file mode 100644 index 0000000000000000000000000000000000000000..fa2b4e11a798355e06f4fa626d09998cadcacf83 --- /dev/null +++ b/pool/shard004/C/0101271_speakup_decext.c @@ -0,0 +1,242 @@ +/* + * originally written by: Kirk Reiser +* this version considerably modified by David Borowski, david575@rogers.com + * + * Copyright (C) 1998-99 Kirk Reiser. + * Copyright (C) 2003 David Borowski. + * + * 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. + * + * specificly written as a driver for the speakup screenreview + * s not a general device driver. + */ +#include +#include +#include +#include + +#include "spk_priv.h" +#include "serialio.h" +#include "speakup.h" + +#define DRV_VERSION "2.14" +#define SYNTH_CLEAR 0x03 +#define PROCSPEECH 0x0b +static unsigned char last_char; + +static inline u_char get_last_char(void) +{ + u_char avail = inb_p(speakup_info.port_tts + UART_LSR) & UART_LSR_DR; + + if (avail) + last_char = inb_p(speakup_info.port_tts + UART_RX); + return last_char; +} + +static inline bool synth_full(void) +{ + return get_last_char() == 0x13; +} + +static void do_catch_up(struct spk_synth *synth); +static void synth_flush(struct spk_synth *synth); + +static int in_escape; + +static struct var_t vars[] = { + { CAPS_START, .u.s = {"[:dv ap 222]" } }, + { CAPS_STOP, .u.s = {"[:dv ap 100]" } }, + { RATE, .u.n = {"[:ra %d]", 7, 0, 9, 150, 25, NULL } }, + { PITCH, .u.n = {"[:dv ap %d]", 100, 0, 100, 0, 0, NULL } }, + { VOL, .u.n = {"[:dv gv %d]", 13, 0, 16, 0, 5, NULL } }, + { PUNCT, .u.n = {"[:pu %c]", 0, 0, 2, 0, 0, "nsa" } }, + { VOICE, .u.n = {"[:n%c]", 0, 0, 9, 0, 0, "phfdburwkv" } }, + { DIRECT, .u.n = {NULL, 0, 0, 1, 0, 0, NULL } }, + V_LAST_VAR +}; + +/* + * These attributes will appear in /sys/accessibility/speakup/decext. + */ +static struct kobj_attribute caps_start_attribute = + __ATTR(caps_start, S_IWUSR | S_IRUGO, spk_var_show, spk_var_store); +static struct kobj_attribute caps_stop_attribute = + __ATTR(caps_stop, S_IWUSR | S_IRUGO, spk_var_show, spk_var_store); +static struct kobj_attribute pitch_attribute = + __ATTR(pitch, S_IWUSR | S_IRUGO, spk_var_show, spk_var_store); +static struct kobj_attribute punct_attribute = + __ATTR(punct, S_IWUSR | S_IRUGO, spk_var_show, spk_var_store); +static struct kobj_attribute rate_attribute = + __ATTR(rate, S_IWUSR | S_IRUGO, spk_var_show, spk_var_store); +static struct kobj_attribute voice_attribute = + __ATTR(voice, S_IWUSR | S_IRUGO, spk_var_show, spk_var_store); +static struct kobj_attribute vol_attribute = + __ATTR(vol, S_IWUSR | S_IRUGO, spk_var_show, spk_var_store); + +static struct kobj_attribute delay_time_attribute = + __ATTR(delay_time, S_IWUSR | S_IRUGO, spk_var_show, spk_var_store); +static struct kobj_attribute direct_attribute = + __ATTR(direct, S_IWUSR | S_IRUGO, spk_var_show, spk_var_store); +static struct kobj_attribute full_time_attribute = + __ATTR(full_time, S_IWUSR | S_IRUGO, spk_var_show, spk_var_store); +static struct kobj_attribute jiffy_delta_attribute = + __ATTR(jiffy_delta, S_IWUSR | S_IRUGO, spk_var_show, spk_var_store); +static struct kobj_attribute trigger_time_attribute = + __ATTR(trigger_time, S_IWUSR | S_IRUGO, spk_var_show, spk_var_store); + +/* + * Create a group of attributes so that we can create and destroy them all + * at once. + */ +static struct attribute *synth_attrs[] = { + &caps_start_attribute.attr, + &caps_stop_attribute.attr, + &pitch_attribute.attr, + &punct_attribute.attr, + &rate_attribute.attr, + &voice_attribute.attr, + &vol_attribute.attr, + &delay_time_attribute.attr, + &direct_attribute.attr, + &full_time_attribute.attr, + &jiffy_delta_attribute.attr, + &trigger_time_attribute.attr, + NULL, /* need to NULL terminate the list of attributes */ +}; + +static struct spk_synth synth_decext = { + .name = "decext", + .version = DRV_VERSION, + .long_name = "Dectalk External", + .init = "[:pe -380]", + .procspeech = PROCSPEECH, + .clear = SYNTH_CLEAR, + .delay = 500, + .trigger = 50, + .jiffies = 50, + .full = 40000, + .flags = SF_DEC, + .startup = SYNTH_START, + .checkval = SYNTH_CHECK, + .vars = vars, + .probe = spk_serial_synth_probe, + .release = spk_serial_release, + .synth_immediate = spk_synth_immediate, + .catch_up = do_catch_up, + .flush = synth_flush, + .is_alive = spk_synth_is_alive_restart, + .synth_adjust = NULL, + .read_buff_add = NULL, + .get_index = NULL, + .indexing = { + .command = NULL, + .lowindex = 0, + .highindex = 0, + .currindex = 0, + }, + .attributes = { + .attrs = synth_attrs, + .name = "decext", + }, +}; + +static void do_catch_up(struct spk_synth *synth) +{ + u_char ch; + static u_char last = '\0'; + unsigned long flags; + unsigned long jiff_max; + struct var_t *jiffy_delta; + struct var_t *delay_time; + int jiffy_delta_val = 0; + int delay_time_val = 0; + + jiffy_delta = spk_get_var(JIFFY); + delay_time = spk_get_var(DELAY); + + spin_lock_irqsave(&speakup_info.spinlock, flags); + jiffy_delta_val = jiffy_delta->u.n.value; + spin_unlock_irqrestore(&speakup_info.spinlock, flags); + jiff_max = jiffies + jiffy_delta_val; + + while (!kthread_should_stop()) { + spin_lock_irqsave(&speakup_info.spinlock, flags); + if (speakup_info.flushing) { + speakup_info.flushing = 0; + spin_unlock_irqrestore(&speakup_info.spinlock, flags); + synth->flush(synth); + continue; + } + if (synth_buffer_empty()) { + spin_unlock_irqrestore(&speakup_info.spinlock, flags); + break; + } + ch = synth_buffer_peek(); + set_current_state(TASK_INTERRUPTIBLE); + delay_time_val = delay_time->u.n.value; + spin_unlock_irqrestore(&speakup_info.spinlock, flags); + if (ch == '\n') + ch = 0x0D; + if (synth_full() || !spk_serial_out(ch)) { + schedule_msec_hrtimeout((delay_time_val)); + continue; + } + set_current_state(TASK_RUNNING); + spin_lock_irqsave(&speakup_info.spinlock, flags); + synth_buffer_getc(); + spin_unlock_irqrestore(&speakup_info.spinlock, flags); + if (ch == '[') + in_escape = 1; + else if (ch == ']') + in_escape = 0; + else if (ch <= SPACE) { + if (!in_escape && strchr(",.!?;:", last)) + spk_serial_out(PROCSPEECH); + if (time_after_eq(jiffies, jiff_max)) { + if (!in_escape) + spk_serial_out(PROCSPEECH); + spin_lock_irqsave(&speakup_info.spinlock, + flags); + jiffy_delta_val = jiffy_delta->u.n.value; + delay_time_val = delay_time->u.n.value; + spin_unlock_irqrestore(&speakup_info.spinlock, + flags); + schedule_timeout(msecs_to_jiffies + (delay_time_val)); + jiff_max = jiffies + jiffy_delta_val; + } + } + last = ch; + } + if (!in_escape) + spk_serial_out(PROCSPEECH); +} + +static void synth_flush(struct spk_synth *synth) +{ + in_escape = 0; + spk_synth_immediate(synth, "\033P;10z\033\\"); +} + +module_param_named(ser, synth_decext.ser, int, S_IRUGO); +module_param_named(start, synth_decext.startup, short, S_IRUGO); + +MODULE_PARM_DESC(ser, "Set the serial port for the synthesizer (0-based)."); +MODULE_PARM_DESC(start, "Start the synthesizer once it is loaded."); + +module_spk_synth(synth_decext); + +MODULE_AUTHOR("Kirk Reiser "); +MODULE_AUTHOR("David Borowski"); +MODULE_DESCRIPTION("Speakup support for DECtalk External synthesizers"); +MODULE_LICENSE("GPL"); +MODULE_VERSION(DRV_VERSION); + diff --git a/pool/shard004/C/0101272_memcpy_kprobe_kern.c b/pool/shard004/C/0101272_memcpy_kprobe_kern.c new file mode 100644 index 0000000000000000000000000000000000000000..2e6bd3522b40eb62b375abcb786d91ae9b512080 --- /dev/null +++ b/pool/shard004/C/0101272_memcpy_kprobe_kern.c @@ -0,0 +1,22 @@ +#include +#include +#include +#include +#include "bpf_helpers.h" + +SEC("kprobe/memcpy") + +int bpf_prog1(struct pt_regs *ctx) +{ + unsigned long long size; + char fmt[] = "memcpy size %d\n"; + + bpf_probe_read(&size, sizeof(size), (void *)&PT_REGS_PARM3(ctx)); + + bpf_trace_printk(fmt, sizeof(fmt), size); + + return 0; +} + +char _license[] SEC("license") = "GPL"; +u32 _version SEC("version") = LINUX_VERSION_CODE; diff --git a/pool/shard004/C/0101277_test-gskstreamexternal.c b/pool/shard004/C/0101277_test-gskstreamexternal.c new file mode 100644 index 0000000000000000000000000000000000000000..4b47b12e95f78555c1c51726d4bc3740632d83a4 --- /dev/null +++ b/pool/shard004/C/0101277_test-gskstreamexternal.c @@ -0,0 +1,49 @@ +#include "../gskinit.h" +#include "../gskstreamexternal.h" +#include "../gskbufferstream.h" +#include + +int +main (int argc, char **argv) +{ + GskBufferStream *input_buffer; + GskBufferStream *output_buffer; + GskStream *external; + const char *args[10]; + const char *desired_output; + char tmp[1024]; + + gsk_init_without_threads (&argc, &argv); + + /* filter some text through 'grep cat' */ + input_buffer = gsk_buffer_stream_new(); + output_buffer = gsk_buffer_stream_new(); + gsk_buffer_append_string (gsk_buffer_stream_peek_read_buffer (input_buffer), + "cat\n" + "dog\n" + "kitty-cat\n" + "elephant\n"); + gsk_buffer_stream_read_buffer_changed (input_buffer); + gsk_buffer_stream_read_shutdown (input_buffer); + args[0] = "grep"; + args[1] = "cat"; + args[2] = NULL; + external = gsk_stream_external_new (GSK_STREAM_EXTERNAL_SEARCH_PATH, + NULL, NULL, /* in/out redirect */ + NULL, NULL, NULL, /* termination */ + "grep", args, /* args */ + NULL, /* environment */ + NULL /* error */ + ); + gsk_stream_attach (GSK_STREAM (input_buffer), external, NULL); + gsk_stream_attach (external, GSK_STREAM (output_buffer), NULL); + desired_output = "cat\nkitty-cat\n"; + while (gsk_buffer_stream_peek_write_buffer (output_buffer)->size < strlen (desired_output)) + gsk_main_loop_run (gsk_main_loop_default (), -1, NULL); + g_assert (gsk_buffer_stream_peek_write_buffer (output_buffer)->size == strlen (desired_output)); + gsk_buffer_read (gsk_buffer_stream_peek_write_buffer (output_buffer), tmp, sizeof (tmp)); + g_assert (memcmp (tmp, desired_output, strlen (desired_output)) == 0); + gsk_buffer_stream_write_buffer_changed (output_buffer); + + return 0; +} diff --git a/pool/shard004/C/0101280_analog_monitor.c b/pool/shard004/C/0101280_analog_monitor.c new file mode 100644 index 0000000000000000000000000000000000000000..e2bcca799953ed25369c8fac0cc9149ab7751a5f --- /dev/null +++ b/pool/shard004/C/0101280_analog_monitor.c @@ -0,0 +1,203 @@ +/******************************************************************************* + * Copyright (c) 2009-2016, MAV'RIC 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 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 analog_monitor.c + * + * \author MAV'RIC Team + * \author Felix Schill + * \author Gregoire Heitz + * + * \brief The driver for the analog monitor module + * + ******************************************************************************/ + + +#include "hal/analog_monitor.h" +#include "hal/avr32/adc_int.h" + + +//------------------------------------------------------------------------------ +// PRIVATE FUNCTIONS DECLARATION +//------------------------------------------------------------------------------ + +/** + * \brief Trigger the analog monitor + * Start sampling + */ +void trigger_analog_monitor(void); + +/** + * \brief Compute the average of the analog channels + * + * \param analog_monitor The pointer to the analog monitor structure + * \param rail The rail structure + * + * \return Return the average of an analog channel + */ +float analog_compute_avg(analog_monitor_t* analog_monitor, analog_rails_t rail); + +//------------------------------------------------------------------------------ +// PRIVATE FUNCTIONS IMPLEMENTATION +//------------------------------------------------------------------------------ + +void trigger_analog_monitor(void) +{ + // adc_int_start_sampling(MONITOR_SAMPLES, 100,16, 4, false); +} + +float analog_compute_avg(analog_monitor_t* analog_monitor, analog_rails_t rail) +{ + float out = 0.0f; + + for (int32_t i = 0; i < MONITOR_SAMPLES; i++) + { + out += (float)analog_monitor->buffer[rail][i]; + } + out = out / MONITOR_SAMPLES; + return out; +} + + +//------------------------------------------------------------------------------ +// PUBLIC FUNCTIONS IMPLEMENTATION +//------------------------------------------------------------------------------ + +void analog_monitor_init(analog_monitor_t* analog_monitor, const analog_monitor_conf_t* config) +{ + // Init buffer and avg outputs + for (int32_t i = 0; i < MONITOR_CHANNELS; ++i) + { + // Init buffer + for (int32_t j = 0; j < MONITOR_SAMPLES; ++j) + { + analog_monitor->buffer[i][j] = 0; + } + // Init avg outputs + analog_monitor->avg[i] = 0; + + // Init conv_factor + analog_monitor->conv_factor[i] = config->conv_factor[i]; + + // Init enable flags + analog_monitor->enable[i] = config->enable[i]; + } + + // Init desired ADC pin + // adc_int_init(100000, ADCIFA_REF06VDD); + + // if (analog_monitor->enable[ANALOG_RAIL_2]) + // { + // adc_int_sequencer_add( analog_monitor->buffer[ANALOG_RAIL_2], + // AVR32_ADCIFA_INP_ADCIN2, + // AVR32_ADCIFA_INN_GNDANA, + // ADCIFA_SHG_1); + // } + // if (analog_monitor->enable[ANALOG_RAIL_3]) + // { + // adc_int_sequencer_add( analog_monitor->buffer[ANALOG_RAIL_3], + // AVR32_ADCIFA_INP_ADCIN3, + // AVR32_ADCIFA_INN_GNDANA, + // ADCIFA_SHG_1); + // } + // if (analog_monitor->enable[ANALOG_RAIL_4]) + // { + // adc_int_sequencer_add( analog_monitor->buffer[ANALOG_RAIL_4], + // AVR32_ADCIFA_INP_ADCIN4, + // AVR32_ADCIFA_INN_GNDANA, + // ADCIFA_SHG_1); + // } + // if (analog_monitor->enable[ANALOG_RAIL_5]) + // { + // adc_int_sequencer_add( analog_monitor->buffer[ANALOG_RAIL_5], + // AVR32_ADCIFA_INP_ADCIN5, + // AVR32_ADCIFA_INN_GNDANA, + // ADCIFA_SHG_1); + // } + // if (analog_monitor->enable[ANALOG_RAIL_6]) + // { + // adc_int_sequencer_add( analog_monitor->buffer[ANALOG_RAIL_6], + // AVR32_ADCIFA_INP_ADCIN6, + // AVR32_ADCIFA_INN_GNDANA, + // ADCIFA_SHG_1); + // } + // if (analog_monitor->enable[ANALOG_RAIL_7]) + // { + // adc_int_sequencer_add( analog_monitor->buffer[ANALOG_RAIL_7], + // AVR32_ADCIFA_INP_ADCIN7, + // AVR32_ADCIFA_INN_GNDANA, + // ADCIFA_SHG_1); ///< 5V_ANALOG + // } + // if (analog_monitor->enable[ANALOG_RAIL_10]) + // { + // adc_int_sequencer_add( analog_monitor->buffer[ANALOG_RAIL_10], + // AVR32_ADCIFA_INP_GNDANA, + // AVR32_ADCIFA_INN_ADCIN10, + // ADCIFA_SHG_1); ///< BAT_FILTERED + // } + // if (analog_monitor->enable[ANALOG_RAIL_11]) + // { + // adc_int_sequencer_add( analog_monitor->buffer[ANALOG_RAIL_11], + // AVR32_ADCIFA_INP_GNDANA, + // AVR32_ADCIFA_INN_ADCIN11, + // ADCIFA_SHG_1); ///< BATTERY + // } + // if (analog_monitor->enable[ANALOG_RAIL_12]) + // { + // adc_int_sequencer_add( analog_monitor->buffer[ANALOG_RAIL_12], + // AVR32_ADCIFA_INP_GNDANA, + // AVR32_ADCIFA_INN_ADCIN12, + // ADCIFA_SHG_1); ///< Analog pin 12 + // } + // if (analog_monitor->enable[ANALOG_RAIL_13]) + // { + // adc_int_sequencer_add( analog_monitor->buffer[ANALOG_RAIL_13], + // AVR32_ADCIFA_INP_GNDANA, + // AVR32_ADCIFA_INN_ADCIN13, + // ADCIFA_SHG_1); ///< Analog pin 13 + // } +} + +bool analog_monitor_update(analog_monitor_t* analog_monitor) +{ + + for (int32_t i = 0; i < MONITOR_CHANNELS; ++i) + { + if (analog_monitor->enable[i]) + { + analog_monitor->avg[i] = analog_compute_avg(analog_monitor, i) * analog_monitor->conv_factor[i]; + } + } + + trigger_analog_monitor(); + + return true; +} \ No newline at end of file diff --git a/pool/shard004/C/0101285_wdt_qmsi.c b/pool/shard004/C/0101285_wdt_qmsi.c new file mode 100644 index 0000000000000000000000000000000000000000..381014ebd5b36435a75bc977c5c02e2d4f3e3268 --- /dev/null +++ b/pool/shard004/C/0101285_wdt_qmsi.c @@ -0,0 +1,191 @@ +/* + * Copyright (c) 2015 Intel Corporation. + * + * SPDX-License-Identifier: Apache-2.0 + */ + +#include +#include +#include +#include +#include +#include +#include + +#include "clk.h" +#include "qm_isr.h" +#include "qm_wdt.h" + +struct wdt_data { +#ifdef CONFIG_WDT_QMSI_API_REENTRANCY + struct k_sem sem; +#endif +#ifdef CONFIG_DEVICE_POWER_MANAGEMENT + uint32_t device_power_state; +#endif +}; + +#define WDT_HAS_CONTEXT_DATA \ + (CONFIG_WDT_QMSI_API_REENTRANCY || CONFIG_DEVICE_POWER_MANAGEMENT) + +#if WDT_HAS_CONTEXT_DATA +static struct wdt_data wdt_context; +#define WDT_CONTEXT (&wdt_context) +#else +#define WDT_CONTEXT (NULL) +#endif /* WDT_HAS_CONTEXT_DATA */ + +#ifdef CONFIG_WDT_QMSI_API_REENTRANCY +#define RP_GET(dev) (&((struct wdt_data *)(dev->driver_data))->sem) +#else +#define RP_GET(dev) (NULL) +#endif + +static void (*user_cb)(struct device *dev); + +static void get_config(struct device *dev, struct wdt_config *cfg) +{ + cfg->timeout = QM_WDT[QM_WDT_0]->wdt_torr; + cfg->mode = ((QM_WDT[QM_WDT_0]->wdt_cr & QM_WDT_CR_RMOD) >> + QM_WDT_CR_RMOD_OFFSET); + cfg->interrupt_fn = user_cb; +} + +static int set_config(struct device *dev, struct wdt_config *cfg) +{ + int ret_val = 0; + qm_wdt_config_t qm_cfg; + + user_cb = cfg->interrupt_fn; + qm_cfg.timeout = cfg->timeout; + qm_cfg.mode = (cfg->mode == WDT_MODE_RESET) ? + QM_WDT_MODE_RESET : QM_WDT_MODE_INTERRUPT_RESET; + qm_cfg.callback = (void *)user_cb; + qm_cfg.callback_data = dev; + + if (IS_ENABLED(CONFIG_WDT_QMSI_API_REENTRANCY)) { + k_sem_take(RP_GET(dev), K_FOREVER); + } + + if (qm_wdt_set_config(QM_WDT_0, &qm_cfg)) { + ret_val = -EIO; + goto wdt_config_return; + } + + if (qm_wdt_start(QM_WDT_0)) { + ret_val = -EIO; + } + +wdt_config_return: + if (IS_ENABLED(CONFIG_WDT_QMSI_API_REENTRANCY)) { + k_sem_give(RP_GET(dev)); + } + + return ret_val; +} + +static void reload(struct device *dev) +{ + qm_wdt_reload(QM_WDT_0); +} + +static void enable(struct device *dev) +{ + clk_periph_enable(CLK_PERIPH_WDT_REGISTER | CLK_PERIPH_CLK); +} + +static void disable(struct device *dev) +{ + clk_periph_disable(CLK_PERIPH_WDT_REGISTER); +} + +static const struct wdt_driver_api api = { + .enable = enable, + .disable = disable, + .get_config = get_config, + .set_config = set_config, + .reload = reload, +}; + +#ifdef CONFIG_DEVICE_POWER_MANAGEMENT +static qm_wdt_context_t wdt_ctx; + +static void wdt_qmsi_set_power_state(struct device *dev, uint32_t power_state) +{ + struct wdt_data *context = dev->driver_data; + + context->device_power_state = power_state; +} + +static uint32_t wdt_qmsi_get_power_state(struct device *dev) +{ + struct wdt_data *context = dev->driver_data; + + return context->device_power_state; +} + +static int wdt_suspend_device(struct device *dev) +{ + qm_wdt_save_context(QM_WDT_0, &wdt_ctx); + + wdt_qmsi_set_power_state(dev, DEVICE_PM_SUSPEND_STATE); + + return 0; +} + +static int wdt_resume_device_from_suspend(struct device *dev) +{ + qm_wdt_restore_context(QM_WDT_0, &wdt_ctx); + + wdt_qmsi_set_power_state(dev, DEVICE_PM_ACTIVE_STATE); + + return 0; +} + +/* +* Implements the driver control management functionality +* the *context may include IN data or/and OUT data +*/ +static int wdt_qmsi_device_ctrl(struct device *dev, uint32_t ctrl_command, + void *context) +{ + if (ctrl_command == DEVICE_PM_SET_POWER_STATE) { + if (*((uint32_t *)context) == DEVICE_PM_SUSPEND_STATE) { + return wdt_suspend_device(dev); + } else if (*((uint32_t *)context) == DEVICE_PM_ACTIVE_STATE) { + return wdt_resume_device_from_suspend(dev); + } + } else if (ctrl_command == DEVICE_PM_GET_POWER_STATE) { + *((uint32_t *)context) = wdt_qmsi_get_power_state(dev); + return 0; + } + + return 0; +} +#else +#define wdt_qmsi_set_power_state(...) +#endif + +static int init(struct device *dev) +{ + if (IS_ENABLED(CONFIG_WDT_QMSI_API_REENTRANCY)) { + k_sem_init(RP_GET(dev), 0, UINT_MAX); + k_sem_give(RP_GET(dev)); + } + + IRQ_CONNECT(IRQ_GET_NUMBER(QM_IRQ_WDT_0_INT), CONFIG_WDT_0_IRQ_PRI, + qm_wdt_0_isr, 0, IOAPIC_EDGE | IOAPIC_HIGH); + + /* Unmask watchdog interrupt */ + irq_enable(IRQ_GET_NUMBER(QM_IRQ_WDT_0_INT)); + + /* Route watchdog interrupt to the current core */ + QM_IR_UNMASK_INTERRUPTS(QM_INTERRUPT_ROUTER->wdt_0_int_mask); + + wdt_qmsi_set_power_state(dev, DEVICE_PM_ACTIVE_STATE); + + return 0; +} + +DEVICE_DEFINE(wdt, CONFIG_WDT_0_NAME, init, wdt_qmsi_device_ctrl, WDT_CONTEXT, + 0, PRE_KERNEL_1, CONFIG_KERNEL_INIT_PRIORITY_DEVICE, &api); diff --git a/pool/shard004/C/0101288_test1.c b/pool/shard004/C/0101288_test1.c new file mode 100644 index 0000000000000000000000000000000000000000..af3e09bb7ab510f2053028d1b0273e703ff58c54 --- /dev/null +++ b/pool/shard004/C/0101288_test1.c @@ -0,0 +1,72 @@ +/* $Id $ */ + +#include +#include + +#include +#include +#include + +#include "../../common/Test.h" + +#ifndef Prim_BottomShadowGC +#define Prim_BottomShadowGC(w) \ + (((XmPrimitiveWidget)(w))->primitive.bottom_shadow_GC) +#endif + +#ifndef Prim_TopShadowGC +#define Prim_TopShadowGC(w) \ + (((XmPrimitiveWidget)(w))->primitive.top_shadow_GC) +#endif + +#ifndef MGR_BackgroundGC +#define MGR_BackgroundGC(w) \ + (((XmManagerWidget)(w))->manager.background_GC) +#endif + +void +onExpose(Widget w, XtPointer udata, XtPointer cdata) +{ + Widget mgr = (Widget) udata; + + /* draw into window */ + XmeDrawArrow(XtDisplay(w), + XtWindow(w), + Prim_BottomShadowGC(w), /* bottom gc */ + Prim_TopShadowGC(w), /* top gc */ + MGR_BackgroundGC(mgr), /* fill gc */ + 5, 5, 22, 22, 2, XmARROW_DOWN); +} + +int +main(int argc, char **argv) +{ + Widget toplevel, widget, bb, list; + XtAppContext app; + XmString item; + Arg args[10]; + int n = 0; + + XtSetLanguageProc(NULL, NULL, NULL); + + toplevel = XtVaAppInitialize(&app, "ComBox", NULL, 0, &argc, argv, NULL, NULL); + + bb = XmCreateBulletinBoard(toplevel, "bb", NULL, 0); + XtManageChild(bb); + + XtSetArg(args[n], XmNwidth, 100); n++; + XtSetArg(args[n], XmNheight, 100); n++; + widget = XmCreateDrawnButton(bb, "drawnButton", args, n); + + XtAddCallback(widget, XmNexposeCallback, (XtCallbackProc) onExpose, + (XtPointer)bb); + + XtManageChild(widget); + + XtRealizeWidget(toplevel); + + LessTifTestMainLoop(toplevel); + + exit(0); +} + diff --git a/pool/shard004/C/0101293_sin_cos_series_basecase.c b/pool/shard004/C/0101293_sin_cos_series_basecase.c new file mode 100644 index 0000000000000000000000000000000000000000..5c998d279b88a0b71baea60954c79d719bc5fae7 --- /dev/null +++ b/pool/shard004/C/0101293_sin_cos_series_basecase.c @@ -0,0 +1,95 @@ +/* + 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_sin_cos_series_basecase(arb_ptr s, arb_ptr c, arb_srcptr h, slong hlen, + slong n, slong prec, int times_pi) +{ + slong j, k, alen = FLINT_MIN(n, hlen); + arb_ptr a; + arb_t t, u; + + if (times_pi) + arb_sin_cos_pi(s, c, h, prec); + else + arb_sin_cos(s, c, h, prec); + + if (hlen == 1) + { + _arb_vec_zero(s + 1, n - 1); + _arb_vec_zero(c + 1, n - 1); + return; + } + + arb_init(t); + arb_init(u); + a = _arb_vec_init(alen); + + for (k = 1; k < alen; k++) + arb_mul_ui(a + k, h + k, k, prec); + + if (times_pi) + { + arb_const_pi(t, prec); + _arb_vec_scalar_mul(a + 1, a + 1, alen - 1, t, prec); + } + + for (k = 1; k < n; k++) + { + arb_zero(t); + arb_zero(u); + + for (j = 1; j < FLINT_MIN(k + 1, hlen); j++) + { + arb_submul(t, a + j, s + k - j, prec); + arb_addmul(u, a + j, c + k - j, prec); + } + + arb_div_ui(c + k, t, k, prec); + arb_div_ui(s + k, u, k, prec); + } + + arb_clear(t); + arb_clear(u); + _arb_vec_clear(a, alen); +} + +void +arb_poly_sin_cos_series_basecase(arb_poly_t s, arb_poly_t c, + const arb_poly_t h, slong n, slong prec, int times_pi) +{ + slong hlen = h->length; + + if (n == 0) + { + arb_poly_zero(s); + arb_poly_zero(c); + return; + } + + if (hlen == 0) + { + arb_poly_zero(s); + arb_poly_one(c); + return; + } + + arb_poly_fit_length(s, n); + arb_poly_fit_length(c, n); + _arb_poly_sin_cos_series_basecase(s->coeffs, c->coeffs, h->coeffs, hlen, n, prec, times_pi); + _arb_poly_set_length(s, n); + _arb_poly_normalise(s); + _arb_poly_set_length(c, n); + _arb_poly_normalise(c); +} + diff --git a/pool/shard004/C/0101295_metric_US.c b/pool/shard004/C/0101295_metric_US.c new file mode 100644 index 0000000000000000000000000000000000000000..16f0841f90e7560fb0a203721d1559d2aadd5a4d --- /dev/null +++ b/pool/shard004/C/0101295_metric_US.c @@ -0,0 +1,124 @@ +#include "common.h" +#include "metric_US.h" + +void metric_US(char * input_file) +{ + int i; + char parameters[METRIC_PARAMS][2][64]={{"M","Module (Metric)"},{"P","Diametral Pitch (US)"}}; + char unknown_choice='\0'; + char toss_char; + double dia_pitch=0; + double met_module=0; + + if (strcmp(input_file,"Does Not Exist")==0) + interactive_parse(parameters,&unknown_choice,&dia_pitch,&met_module); + else + file_parse(input_file,&unknown_choice,&dia_pitch,&met_module); + + switch (unknown_choice){ + case 'M' : + met_module=25.4/dia_pitch; + assert(dia_pitch>0); + printf("Module is %f\n",met_module); + break; + case 'P' : + dia_pitch=25.4/met_module; + assert(met_module>0); + printf("Diametral pitch is %f\n",dia_pitch); + break; + } + +} + +static void interactive_parse(char parameters[METRIC_PARAMS][2][64], char * ptr_unknown_choice, double * dia_pitch, double * met_module) +{ + int i; + bool valid_param=false; + + printf("Index | Parameter Name\n"); + for (i=0;i0); + break; + case 'P' : + printf("Module: "); + scanf("%lf",met_module); + assert(met_module>0); + break; + } + +} + + +static void file_parse(char * input_file, char * unknown_choice, double * dia_pitch, double * met_module) +{ + FILE * fp; + char file_str[INPUT_FILE_LINE]; + char * var_parse; + char * val_parse; + int i, j; + + fp = fopen(input_file, "r"); //open file in read only + *dia_pitch=0; + *met_module=0; + while(fgets(file_str,INPUT_FILE_LINE,fp)) + { + var_parse = (char *)calloc(strlen(file_str)+1,sizeof(char)); + val_parse = (char *)calloc(strlen(file_str)+1,sizeof(char)); + i=0; + while(file_str[i]!=' ' && file_str[i]!='\0') + var_parse[i]=file_str[i++]; + var_parse[i]='\0'; + i++; + if (file_str[i]=='?') + { + if (strcmp(var_parse,"dia_pitch")==0) + *unknown_choice='P'; + if (strcmp(var_parse,"met_module")==0) + *unknown_choice='M'; + } + else + { + j=0; + while(file_str[i]!='\0') + val_parse[j++]=file_str[i++]; + val_parse[j]='\0'; + if (strcmp(var_parse,"dia_pitch")==0) + { + printf("Dia_pitch set to %f\n",atof(val_parse)); + assert(atof(val_parse)>0); + *dia_pitch=atof(val_parse); + } + if (strcmp(var_parse,"met_module")==0) + { + printf("Met_module set to %f\n",atof(val_parse)); + assert(atof(val_parse)>0); + *met_module=atof(val_parse); + } + } + free(var_parse); + free(val_parse); + } + fclose(fp); + assert((*dia_pitch==0)^(*met_module==0)); //XOR check on value assignments to exactly 1 unknown + assert(*unknown_choice!='\0'); //Ensure unknown variable was specified +} diff --git a/pool/shard004/C/0101307_programTest13.c b/pool/shard004/C/0101307_programTest13.c new file mode 100644 index 0000000000000000000000000000000000000000..e1a34eaba5883793fd03863b8446d86702ffd264 --- /dev/null +++ b/pool/shard004/C/0101307_programTest13.c @@ -0,0 +1,19 @@ +int *func(int a, int *b) { + static int result = 0; + int i; + for (i = 0; i < a; i++) { + // NOTE: unary semantics differ between + // GCC and Clang + // One unary per line hides these differences. + int temp = (*b)--; + result += temp; + } + return &result; +} + +int main() { + int asdf = 3; + int *ptr1 = func(4, &asdf); + int *ptr2 = func(asdf, ptr1); + return *func(5, ptr2) % 128; +} diff --git a/pool/shard004/C/0101309_binary_tree.c b/pool/shard004/C/0101309_binary_tree.c new file mode 100644 index 0000000000000000000000000000000000000000..11be1327d33f8e655185335b8ceff8bcda0629e4 --- /dev/null +++ b/pool/shard004/C/0101309_binary_tree.c @@ -0,0 +1,154 @@ +/** + @file binary_tree.c + + @author Evgeny Zhurko + @copyright Copyright (c) 2016, Evgeny Zhurko. + @license This file is released under the MIT Licesne. +*/ + +#include "binary_tree.h" + +/** + @brief Print binary tree + + This function print binary tree. + Root node will be printed first. + Then will be printed left subtree with all elements. + And after left subtree will be printed right subtree + with all elements. + + @param[in] node Root of the binary tree + @return Execution status +*/ +int tree_print(node_t *node) +{ + if (node == NULL) { + return 1; + } + + if (!node->is_leaf) { + printf("%d - %d\n", node->is_leaf, node->element->frequency); + } + else { + printf("%d - %c - %d\n", node->is_leaf, node->element->c, + node->element->frequency); + } + + tree_print(node->left); + tree_print(node->right); + return 0; +} + +/** + @brief Delete binary tree + + This function delete binary tree with all elements. + + @param[in] node Root of the binary tree + @return Execution status +*/ +int tree_delete(node_t *node) +{ + if (node == NULL) { + return 1; + } + + tree_delete(node->left); + tree_delete(node->right); + FREE_PTR(node->element); + FREE_PTR(node); + return 0; +} + +/** + @brief Create new node with given parameters + + This function connew node for tree with given parameters. + + @param[in] c Define character for this node + @param[in] frequency Define frequency for character + @param[in] is_leaf Define is leaf or intermediate node + @return New node +*/ +node_t *create_node(unsigned char c, unsigned int frequency, unsigned int is_leaf) +{ + pair_t *pair_new; + node_t *node_new; + + pair_new = malloc(sizeof(*pair_new)); + node_new = malloc(sizeof(*node_new)); + + IS_NULL(pair_new); + IS_NULL(node_new); + + pair_new->c = c; + pair_new->frequency = frequency; + node_new->element = pair_new; + node_new->is_leaf = is_leaf; + node_new->parent = NULL; + node_new->left = NULL; + node_new->right = NULL; + + return node_new; +} + +/** + @brief Merge two tree into one tree + + Create new tree from two tree. + One of the tree will be left subtree, the other will be right subtree. + + @param[in] left Left tree + @param[in] right Right tree + @return New tree +*/ +node_t *merge_tree(node_t *left, node_t *right) +{ + node_t *node_new = NULL; + + node_new = create_node(0, 0, 0); + + left->parent = node_new; + right->parent = node_new; + node_new->left = left; + node_new->right = right; + node_new->element->frequency = left->element->frequency +\ + right->element->frequency; + return node_new; +} + +/** + @brief Find node by character + + This function find charater in tree. + If character isn't find function return NULL. + + @param[in] node Root node + @param[in] c Character to find in tree + @return node Lead that contain this character or NULL(if not find) +*/ +node_t *find_node(node_t *node, unsigned char c) +{ + if (node == NULL) { + return NULL; + } + + if (node->is_leaf) { + if (node->element->c == c) { + return node; + } + return NULL; + } + else { + node_t *left = find_node(node->left, c); + node_t *right = find_node(node->right, c); + + if (left != NULL) { + return left; + } + else if (right != NULL) { + return right; + } + return NULL; + } +} \ No newline at end of file diff --git a/pool/shard004/C/0101310_capture.c b/pool/shard004/C/0101310_capture.c new file mode 100644 index 0000000000000000000000000000000000000000..82c807d046dd245e4ffd09f5428c2b9df14f12a1 --- /dev/null +++ b/pool/shard004/C/0101310_capture.c @@ -0,0 +1,101 @@ +#include +#include +#include +#include +#include +#include +#include + +#include + +#include +#include +#include +#include + +#include "capture.h" +#include "main.h" + +#define NUM_BUFS 3 + +Void *captureThrFxn(Void *arg) { + CaptureEnv *envp = (CaptureEnv *) arg; + Void *status = THREAD_SUCCESS; + + Capture_Handle hCapture = NULL; + Capture_Attrs cAttrs; + ColorSpace_Type colorSpace = ColorSpace_UYVY; + + BufferGfx_Attrs gfxAttrs = BufferGfx_Attrs_DEFAULT; + Int bufSize = 0; + BufTab_Handle hCapTab = NULL; + Buffer_Handle cBuf, dBuf; + + /* ▼▼▼▼▼ Initialization ▼▼▼▼▼ */ + /* BufTab creating */ + BufferGfx_calcDimensions(VideoStd_D1_PAL, colorSpace, &gfxAttrs.dim); + gfxAttrs.dim.lineLength = Dmai_roundUp(BufferGfx_calcLineLength(gfxAttrs.dim.width, colorSpace), 32); + gfxAttrs.colorSpace = colorSpace; + bufSize = gfxAttrs.dim.lineLength * gfxAttrs.dim.height; + hCapTab = BufTab_create(NUM_BUFS, bufSize, BufferGfx_getBufferAttrs(&gfxAttrs)); + if (hCapTab == NULL) { + ERR("Failed to create capture buftab\n"); + cleanup(THREAD_FAILURE); + } + + /* Create the capture display driver instance */ + cAttrs = Capture_Attrs_DM365_DEFAULT; + cAttrs.numBufs = NUM_BUFS; + cAttrs.colorSpace = colorSpace; + cAttrs.videoInput = Capture_Input_COMPOSITE; + cAttrs.videoStd = VideoStd_D1_PAL; + cAttrs.onTheFly = FALSE; + hCapture = Capture_create(hCapTab, &cAttrs); + if (hCapture == NULL) { + ERR("Failed to create capture device\n"); + cleanup(THREAD_FAILURE); + } + + Rendezvous_meet(envp->hRendezvousInit); + /* ▲▲▲▲▲ Initialization ▲▲▲▲▲ */ + + while (1) { + /* Capture a frame */ + if (Capture_get(hCapture, &cBuf) < 0) { + ERR("Failed to get capture buffer\n"); + cleanup(THREAD_FAILURE); + } + + /* Send buffer to dei thread for de-interlacing */ + if (Fifo_put(envp->hCaptureOutFifo, cBuf) < 0) { + ERR("Failed to send buffer to dei thread\n"); + cleanup(THREAD_FAILURE); + } + + /* Recieve buffer from dei thread for capturing */ + if (Fifo_get(envp->hCaptureInFifo, &dBuf) < 0) { + ERR("Failed to get buffer from dei thread\n"); + cleanup(THREAD_FAILURE); + } + + /* Release buffer to the display device driver */ + if (Capture_put(hCapture, dBuf) < 0) { + ERR("Failed to put display buffer\n"); + cleanup(THREAD_FAILURE); + } + } + +cleanup: + Rendezvous_force(envp->hRendezvousInit); + Rendezvous_meet(envp->hRendezvousCleanup); + + if (hCapture) { + Capture_delete(hCapture); + } + + if (hCapTab) { + BufTab_delete(hCapTab); + } + + return status; +} \ No newline at end of file diff --git a/pool/shard004/C/0101314_demod_display.c b/pool/shard004/C/0101314_demod_display.c new file mode 100644 index 0000000000000000000000000000000000000000..2f6858e2c381a4b8be3567651d8db7714e883a33 --- /dev/null +++ b/pool/shard004/C/0101314_demod_display.c @@ -0,0 +1,90 @@ +/* + * demod_display.c -- signal display + * + * Copyright (C) 1996 + * Thomas Sailer (sailer@ife.ee.ethz.ch, hb9jnx@hb9w.che.eu) + * + * 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. + */ + +#ifndef NO_X11 +/* ---------------------------------------------------------------------- */ + +#include "multimon.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include + +/* ---------------------------------------------------------------------- */ + +#define SAMPLING_RATE 22050 + +/* ---------------------------------------------------------------------- */ + +static void scope_init(struct demod_state *s) +{ + memset(&s->l1.scope, 0, sizeof(s->l1.scope)); + s->l1.scope.dispnum = xdisp_start(); + if (s->l1.scope.dispnum == -1) + return; +} + +/* ---------------------------------------------------------------------- */ + +#define MEMSIZE sizeof(s->l1.scope.data)/sizeof(s->l1.scope.data[0]) + +static void scope_demod(struct demod_state *s, buffer_t buffer, int length) +{ + const float *src; + float *dst; + int i; + + if (s->l1.scope.dispnum == -1) + return; + if ( (unsigned int) length >= MEMSIZE) { + src = buffer.fbuffer+length-MEMSIZE; + dst = s->l1.scope.data; + i = MEMSIZE; + } else { + i = MEMSIZE-length; + memmove(s->l1.scope.data, s->l1.scope.data+i, + i*sizeof(s->l1.scope.data[0])); + src = buffer.fbuffer; + dst = s->l1.scope.data+i; + i = length; + } + s->l1.scope.datalen += i; + memcpy(dst, src, i*sizeof(s->l1.scope.data[0])); + if ( (unsigned int) s->l1.scope.datalen < MEMSIZE) + return; + if (xdisp_update(s->l1.scope.dispnum, s->l1.scope.data)) + s->l1.scope.datalen = 0; +} + +/* ---------------------------------------------------------------------- */ + +const struct demod_param demod_scope = { + "SCOPE", true, SAMPLING_RATE, 0, scope_init, scope_demod, NULL +}; + + +/* ---------------------------------------------------------------------- */ +#endif //NO_X11 diff --git a/pool/shard004/C/0101323_chal_dmux.c b/pool/shard004/C/0101323_chal_dmux.c new file mode 100644 index 0000000000000000000000000000000000000000..446e32b180c41eab460f4d6b5aaaed5d836b6105 --- /dev/null +++ b/pool/shard004/C/0101323_chal_dmux.c @@ -0,0 +1,272 @@ +/***************************************************************************** +* Copyright 2001 - 2008 Broadcom Corporation. All rights reserved. +* +* Unless you and Broadcom execute a separate written software license +* agreement governing use of this software, this software is licensed to you +* under the terms of the GNU General Public License version 2, available at +* http://www.gnu.org/licenses/old-license/gpl-2.0.html (the "GPL"). +* +* Notwithstanding the above, under no circumstances may you combine this +* software in any way with any other Broadcom software provided under a +* license other than the GPL, without Broadcom's express prior written +* consent. +* +*****************************************************************************/ + +#include +#include +#include +#include + + +/* + * **************************************************************************** + * local macro declarations + * **************************************************************************** + */ + +#define CHAL_DMUX_CHAN_INVALID 0x0F +#define CHAL_DMUX_PERI_INVALID 0x7F + +#undef chal_dprintf +#define chal_dprintf(a) /* printf a*/ + + +typedef struct chal_dmux_s { + uint32_t baseAddr; +} chal_dmux_t, *p_chal_dmux_t; + +static chal_dmux_t dmux_dev; + + +/* + * **************************************************************************** + * + * Function Name: chal_dmux_init + * + * Description: Initialize CHAL DMUX for the passed DMUX instance + * + * **************************************************************************** + */ +CHAL_HANDLE chal_dmux_init(uint32_t baseAddr) +{ + chal_dmux_t *dev = NULL; + + chal_dprintf(( "chal_dmux_init\n" )); + + /* Don't re-init a block*/ + if (dmux_dev.baseAddr == baseAddr) + { + chal_dprintf(("ERROR: chal_dmux_init: already initialized\n")); + return (CHAL_HANDLE)dev; + } + + dmux_dev.baseAddr = baseAddr; + dev = &dmux_dev; + return (CHAL_HANDLE)dev; +} + + +/* + * **************************************************************************** + * + * Function Name: chal_dmux_deinit + * + * Description: De-Initialize CHAL DMUX for the passed DMUX instance + * + * **************************************************************************** + */ +CHAL_DMUX_STATUS_t chal_dmux_deinit(CHAL_HANDLE handle) +{ + chal_dmux_t *dev = (chal_dmux_t *) handle; + + chal_dprintf(( "chal_dmux_deinit\n")); + + if (dev == NULL) + { + chal_dprintf(("ERROR: chal_dmux_deinit: NULL handle\n")); + return CHAL_DMUX_STATUS_FAILURE; + } + + dev->baseAddr = 0; + + return CHAL_DMUX_STATUS_SUCCESS; +} + + +/* + * **************************************************************************** + * + * Function Name: chal_dmux_alloc_channel + * + * Description: Allocate channel + * + * **************************************************************************** + */ +CHAL_DMUX_STATUS_t chal_dmux_alloc_channel(CHAL_HANDLE handle, uint32_t *chan) +{ + chal_dmux_t *pDmuxDev = (chal_dmux_t *) handle; + uint32_t channel; + + channel = CHAL_REG_READ32 ( pDmuxDev->baseAddr + DMUX_CHAN_ALLOC_DEALLOC_OFFSET ) & DMUX_CHAN_ALLOC_DEALLOC_CHANNEL_AD_MASK; + + if( channel != CHAL_DMUX_CHAN_INVALID ) + { + *chan = channel; + return CHAL_DMUX_STATUS_SUCCESS; + } + else + { + return CHAL_DMUX_STATUS_FAILURE; + } +} + +/* + * **************************************************************************** + * + * Function Name: chal_dmux_dealloc_channel + * + * Description: De-allocate channel + * + * **************************************************************************** + */ +CHAL_DMUX_STATUS_t chal_dmux_dealloc_channel( CHAL_HANDLE handle, uint32_t channel ) +{ + chal_dmux_t *pDmuxDev = (chal_dmux_t *) handle; + + CHAL_REG_WRITE32 ( pDmuxDev->baseAddr + DMUX_CHAN_ALLOC_DEALLOC_OFFSET, channel ); + + return CHAL_DMUX_STATUS_SUCCESS; +} + +/* + * **************************************************************************** + * + * Function Name: chal_dmux_alloc_peripheral + * + * Description: Allocate peripherals associated with a certain channel + * + * **************************************************************************** + */ +CHAL_DMUX_STATUS_t chal_dmux_alloc_peripheral( + CHAL_HANDLE handle, + uint32_t channel, + CHAL_DMUX_END_POINT_t peri_a, + CHAL_DMUX_END_POINT_t peri_b, + uint8_t *src_id, + uint8_t *dst_id + ) +{ + chal_dmux_t *pDmuxDev = (chal_dmux_t *) handle; + uint32_t val1, val2; + uint32_t time_out = 256; + + if ( ( peri_a != CHAL_DMUX_EPT_INVALID ) && ( peri_b != CHAL_DMUX_EPT_INVALID ) ) + { + val1 = peri_a | ( peri_b << DMUX_PER_0_PER_B_0_SHIFT ); + } + else if(peri_a != CHAL_DMUX_EPT_INVALID) + { + val1 = peri_a | ( CHAL_DMUX_PERI_INVALID << DMUX_PER_0_PER_B_0_SHIFT ); + } + else + { + val1 = peri_b | ( CHAL_DMUX_PERI_INVALID << DMUX_PER_0_PER_B_0_SHIFT ); + } + + CHAL_REG_WRITE32(pDmuxDev->baseAddr + DMUX_PER_0_OFFSET + channel * 4, val1); + + do + { + val2 = CHAL_REG_READ32( pDmuxDev->baseAddr + DMUX_PER_0_OFFSET + channel * 4 ); + + if( ( val2 & ~DMUX_PER_0_RESERVED_MASK ) == val1 ) + { + if ( dst_id ) + { + *dst_id = 2 * channel; + if ( src_id ) + { + *src_id = 2 * channel + 1; + } + } + else + { + *src_id = 2 * channel; + } + return CHAL_DMUX_STATUS_SUCCESS; + } + } while( time_out-- ); + + return CHAL_DMUX_STATUS_FAILURE; +} + +/* + * **************************************************************************** + * + * Function Name: chal_dmux_dealloc_peripheral + * + * Description: De-allocate peripheral + * + * **************************************************************************** + */ +CHAL_DMUX_STATUS_t chal_dmux_dealloc_peripheral( CHAL_HANDLE handle, uint32_t channel ) +{ + chal_dmux_t *pDmuxDev = (chal_dmux_t *) handle; + + channel &= DMUX_PER_DEALLOC_CHANNEL_P_MASK; + CHAL_REG_WRITE32 ( pDmuxDev->baseAddr + DMUX_PER_DEALLOC_OFFSET, channel ); + + return CHAL_DMUX_STATUS_SUCCESS; +} + + + +/* + * **************************************************************************** + * + * Function Name: chal_dmux_protect + * + * Description: Protect + * + * **************************************************************************** + */ +CHAL_DMUX_STATUS_t chal_dmux_protect( CHAL_HANDLE handle ) +{ + chal_dmux_t *pDmuxDev = (chal_dmux_t *) handle; + + if( CHAL_REG_READ32 ( pDmuxDev->baseAddr + DMUX_SEMAPHORE_OFFSET ) == 0 ) + { + return CHAL_DMUX_STATUS_SUCCESS; + } + else + { + return CHAL_DMUX_STATUS_FAILURE; + } +} + + +/* + * **************************************************************************** + * + * Function Name: chal_dmux_unprotect + * + * Description: Unprotect + * + * **************************************************************************** + */ +CHAL_DMUX_STATUS_t chal_dmux_unprotect( CHAL_HANDLE handle ) +{ + chal_dmux_t *pDmuxDev = (chal_dmux_t *) handle; + + CHAL_REG_WRITE32 ( pDmuxDev->baseAddr + DMUX_SEMAPHORE_OFFSET, 0 ); + + return CHAL_DMUX_STATUS_SUCCESS; +} + + + + + + + diff --git a/pool/shard004/C/0101328_main.c b/pool/shard004/C/0101328_main.c new file mode 100644 index 0000000000000000000000000000000000000000..e615777c2df69329eefe169acfc77a9f473ec390 --- /dev/null +++ b/pool/shard004/C/0101328_main.c @@ -0,0 +1,26 @@ +/* + file name: ch0404_scope01/main.c + author: Jung,JaeJoon(rgbi3307@nate.com, http://www.kernel.bz/) + comments: ¿ÜºÎ º¯¼ö +*/ + +#include + +//¿ÜºÎ º¯¼ö +int gA = 50; +int gB = 60; + +int fn_a (); +int fn_b (int a, int b); +int fn_c (int a, int b); + +int main () +{ + printf("fn_a(): %d\n", fn_a ()); + printf("fn_b(): %d\n", fn_b (30, 40)); + printf("fn_c(): %d\n", fn_c (gA, gB)); + + printf("\nPress any key to end..."); + getchar(); + return 0; +} diff --git a/pool/shard004/C/0101334_rand.c b/pool/shard004/C/0101334_rand.c new file mode 100644 index 0000000000000000000000000000000000000000..d3fb421866358046e6f5cb0d1a846c18f49770c8 --- /dev/null +++ b/pool/shard004/C/0101334_rand.c @@ -0,0 +1,160 @@ +/* Implementations of several methods for generating random floating-point. + + Copyright 2016 Allen B. Downey + License: MIT License https://opensource.org/licenses/MIT +*/ + +#include + +// generate a random float using the algorithm described +// at http://allendowney.com/research/rand +float my_random_float() +{ + int x, exp, mant; + float f; + + // this union is for assembling the float. + union { + float f; + int i; + } b; + + // generate 31 random bits (assuming that RAND_MAX is 2^31 - 1 + x = random(); + + // use bit-scan-forward to find the first set bit and + // compute the exponent + asm ("bsfl %1, %0" + :"=r"(exp) + :"r"(x) + ); + exp = 126 - exp; + + // use the other 23 bits for the mantissa (for small numbers + // this means we are re-using some bits) + mant = x >> 8; + b.i = (exp << 23) | mant; + + return b.f; +} + +// alternative implementation of my algorithm that doesn't use +// embedded assembly +float my_random_float2() +{ + int x; + int mant; + int exp = 126; + int mask = 1; + + union { + float f; + int i; + } b; + + // generate random bits until we see the first set bit + while (1) { + x = random(); + if (x == 0) { + exp -= 31; + } else { + break; + } + } + + // find the location of the first set bit and compute the exponent + while (x & mask) { + mask <<= 1; + exp--; + } + + // use the remaining bit as the mantissa + mant = x >> 8; + b.i = (exp << 23) | mant; + + return b.f; +} + +// compute a random double using my algorithm +double my_random_double() +{ + long int x; + int mant; + long int exp = 1022; + int mask = 1; + + union { + double d; + long int i; + } b; + + // generate random bits until we see the first set bit + while (1) { + x = random(); + if (x == 0) { + exp -= 63; + } else { + break; + } + } + x <<= 12; + x |= random(); + + // find the location of the first set bit and compute the exponent + while (x & mask) { + mask <<= 1; + exp--; + } + + // use the remaining bit as the mantissa + mant = x >> 11; + b.i = (exp << 52) | mant; + + return b.d; +} + +// return a constant (this is a dummy function for time trials) +float dummy() +{ + float f = 0.5; + return f; +} + +// generate a random integer and convert to float (dummy function) +float dummy2() +{ + int x; + float f; + + x = random(); + f = (float) x; + + return f; +} + +// generate a random float using the standard algorithm +float random_float() +{ + int x; + float f; + + x = random(); + f = (float) x / (float) RAND_MAX; + + return f; +} + + +// generate a random double using the standard algorithm +float random_double() +{ + int x; + double f; + + x = random(); + f = (double) x / (double) RAND_MAX; + + return f; +} + + diff --git a/pool/shard004/C/0101336_icalperiod.c b/pool/shard004/C/0101336_icalperiod.c new file mode 100644 index 0000000000000000000000000000000000000000..d7aaa90efc306adcb6b04cbad443ab9de43ebd20 --- /dev/null +++ b/pool/shard004/C/0101336_icalperiod.c @@ -0,0 +1,172 @@ +/* -*- Mode: C -*- + ====================================================================== + FILE: icalperiod.c + CREATOR: eric 02 June 2000 + + $Id$ + $Locker$ + + (C) COPYRIGHT 2000, Eric Busboom, http://www.softwarestudio.org + + This program is free software; you can redistribute it and/or modify + it under the terms of either: + + The LGPL as published by the Free Software Foundation, version + 2.1, available at: http://www.fsf.org/copyleft/lesser.html + + Or: + + The Mozilla Public License Version 1.0. You may obtain a copy of + the License at http://www.mozilla.org/MPL/ + + The Original Code is eric. The Initial Developer of the Original + Code is Eric Busboom + + + ======================================================================*/ + +#ifdef HAVE_CONFIG_H +#include +#endif + +#include "icalperiod.h" + +#include +#include +#include +#include + +#ifdef ICAL_NO_LIBICAL +#define icalerror_set_errno(x) +#define icalerror_check_arg_rv(x,y) +#define icalerror_check_arg_re(x,y,z) +#else +#include "icalerror.h" +#include "icalmemory.h" +#endif + + + + +struct icalperiodtype icalperiodtype_from_string (const char* str) +{ + + struct icalperiodtype p, null_p; + char *s = icalmemory_strdup(str); + char *start, *end = s; + icalerrorstate es; + + /* Errors are normally generated in the following code, so save + the error state for resoration later */ + + icalerrorenum e = icalerrno; + + p.start = p.end = icaltime_null_time(); + p.duration = icaldurationtype_from_int(0); + + null_p = p; + + if(s == 0) goto error; + + start = s; + end = strchr(s, '/'); + + if(end == 0) goto error; + + *end = 0; + end++; + + p.start = icaltime_from_string(start); + + if (icaltime_is_null_time(p.start)) goto error; + + es = icalerror_get_error_state(ICAL_MALFORMEDDATA_ERROR); + icalerror_set_error_state(ICAL_MALFORMEDDATA_ERROR,ICAL_ERROR_NONFATAL); + + p.end = icaltime_from_string(end); + + icalerror_set_error_state(ICAL_MALFORMEDDATA_ERROR,es); + + + if (icaltime_is_null_time(p.end)){ + + p.duration = icaldurationtype_from_string(end); + + if(icaldurationtype_as_int(p.duration) == 0) goto error; + } + + icalerrno = e; + icalmemory_free_buffer(s); + return p; + + error: + icalmemory_free_buffer(s); + icalerror_set_errno(ICAL_MALFORMEDDATA_ERROR); + return null_p; +} + + +const char* icalperiodtype_as_ical_string(struct icalperiodtype p) +{ + + const char* start; + const char* end; + + char *buf; + size_t buf_size = 40; + char* buf_ptr = 0; + + buf = (char*)icalmemory_new_buffer(buf_size); + buf_ptr = buf; + + + start = icaltime_as_ical_string(p.start); + + icalmemory_append_string(&buf, &buf_ptr, &buf_size, start); + + if(!icaltime_is_null_time(p.end)){ + end = icaltime_as_ical_string(p.end); + } else { + end = icaldurationtype_as_ical_string(p.duration); + } + + icalmemory_append_char(&buf, &buf_ptr, &buf_size, '/'); + + icalmemory_append_string(&buf, &buf_ptr, &buf_size, end); + + icalmemory_add_tmp_buffer(buf); + + return buf; +} + + + +struct icalperiodtype icalperiodtype_null_period() { + struct icalperiodtype p; + p.start = icaltime_null_time(); + p.end = icaltime_null_time(); + p.duration = icaldurationtype_null_duration(); + + return p; +} +int icalperiodtype_is_null_period(struct icalperiodtype p){ + + if(icaltime_is_null_time(p.start) && + icaltime_is_null_time(p.end) && + icaldurationtype_is_null_duration(p.duration)){ + return 1; + } else { + return 0; + } +} + +int icalperiodtype_is_valid_period(struct icalperiodtype p){ + if(icaltime_is_valid_time(p.start) && + (icaltime_is_valid_time(p.end) || icaltime_is_null_time(p.end)) ) + { + return 1; + } + + return 0; +} + diff --git a/pool/shard004/C/0101340_cip.c b/pool/shard004/C/0101340_cip.c new file mode 100644 index 0000000000000000000000000000000000000000..3a3b587d19189b71d0f22614f228c5a6dfdd1be7 --- /dev/null +++ b/pool/shard004/C/0101340_cip.c @@ -0,0 +1,269 @@ +/* +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +% % +% % +% CCCC IIIII PPPP % +% C I P P % +% C I PPPP % +% C I P % +% CCCC IIIII P % +% % +% % +% Read/Write Cisco IP Phone Image Format % +% % +% Software Design % +% Cristy % +% April 2004 % +% % +% % +% Copyright 1999-2014 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. % +% % +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +% +% +*/ + +/* + Include declarations. +*/ +#include "magick/studio.h" +#include "magick/blob.h" +#include "magick/blob-private.h" +#include "magick/cache.h" +#include "magick/color-private.h" +#include "magick/colorspace.h" +#include "magick/colorspace-private.h" +#include "magick/constitute.h" +#include "magick/exception.h" +#include "magick/exception-private.h" +#include "magick/image.h" +#include "magick/image-private.h" +#include "magick/list.h" +#include "magick/magick.h" +#include "magick/memory_.h" +#include "magick/monitor.h" +#include "magick/monitor-private.h" +#include "magick/pixel-accessor.h" +#include "magick/property.h" +#include "magick/quantize.h" +#include "magick/quantum-private.h" +#include "magick/static.h" +#include "magick/string_.h" +#include "magick/module.h" +#include "magick/utility.h" + +/* + Forward declarations. +*/ +static MagickBooleanType + WriteCIPImage(const ImageInfo *,Image *); + +/* +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +% % +% % +% % +% R e g i s t e r C I P I m a g e % +% % +% % +% % +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +% +% RegisterCIPImage() adds properties for the CIP IP phone image format to +% the list of supported formats. The properties include the image format +% tag, a method to read and/or write the format, whether the format +% supports the saving of more than one frame to the same file or blob, +% whether the format supports native in-memory I/O, and a brief +% description of the format. +% +% The format of the RegisterCIPImage method is: +% +% size_t RegisterCIPImage(void) +% +*/ +ModuleExport size_t RegisterCIPImage(void) +{ + MagickInfo + *entry; + + entry=SetMagickInfo("CIP"); + entry->encoder=(EncodeImageHandler *) WriteCIPImage; + entry->adjoin=MagickFalse; + entry->description=ConstantString("Cisco IP phone image format"); + entry->module=ConstantString("CIP"); + (void) RegisterMagickInfo(entry); + return(MagickImageCoderSignature); +} + +/* +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +% % +% % +% % +% U n r e g i s t e r C I P I m a g e % +% % +% % +% % +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +% +% UnregisterCIPImage() removes format registrations made by the +% CIP module from the list of supported formats. +% +% The format of the UnregisterCIPImage method is: +% +% UnregisterCIPImage(void) +% +*/ +ModuleExport void UnregisterCIPImage(void) +{ + (void) UnregisterMagickInfo("CIP"); +} + +/* +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +% % +% % +% % +% W r i t e C I P I m a g e % +% % +% % +% % +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +% +% Procedure WriteCIPImage() writes an image to a file in the Cisco IP phone +% image format. +% +% The format of the WriteCIPImage method is: +% +% MagickBooleanType WriteCIPImage(const ImageInfo *image_info,Image *image) +% +% A description of each parameter follows. +% +% o image_info: the image info. +% +% o image: The image. +% +*/ + +static inline ssize_t MagickMin(const ssize_t x,const ssize_t y) +{ + if (x < y) + return(x); + return(y); +} + +static MagickBooleanType WriteCIPImage(const ImageInfo *image_info,Image *image) +{ + char + buffer[MaxTextExtent]; + + const char + *value; + + MagickBooleanType + status; + + register const PixelPacket + *p; + + register ssize_t + i, + x; + + ssize_t + y; + + unsigned char + byte; + + /* + Open output image file. + */ + assert(image_info != (const ImageInfo *) NULL); + assert(image_info->signature == MagickSignature); + assert(image != (Image *) NULL); + assert(image->signature == MagickSignature); + if (image->debug != MagickFalse) + (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); + status=OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception); + if (status == MagickFalse) + return(status); + (void) WriteBlobString(image,"\n"); + value=GetImageProperty(image,"label"); + if (value != (const char *) NULL) + (void) FormatLocaleString(buffer,MaxTextExtent,"%s\n",value); + else + { + char + basename[MaxTextExtent]; + + GetPathComponent(image->filename,BasePath,basename); + (void) FormatLocaleString(buffer,MaxTextExtent,"%s\n", + basename); + } + (void) WriteBlobString(image,buffer); + (void) FormatLocaleString(buffer,MaxTextExtent, + "%.20g\n",(double) image->page.x); + (void) WriteBlobString(image,buffer); + (void) FormatLocaleString(buffer,MaxTextExtent, + "%.20g\n",(double) image->page.y); + (void) WriteBlobString(image,buffer); + (void) FormatLocaleString(buffer,MaxTextExtent,"%.20g\n", + (double) (image->columns+(image->columns % 2))); + (void) WriteBlobString(image,buffer); + (void) FormatLocaleString(buffer,MaxTextExtent,"%.20g\n", + (double) image->rows); + (void) WriteBlobString(image,buffer); + (void) FormatLocaleString(buffer,MaxTextExtent,"2\n"); + (void) WriteBlobString(image,buffer); + (void) WriteBlobString(image,""); + (void) TransformImageColorspace(image,sRGBColorspace); + for (y=0; y < (ssize_t) image->rows; y++) + { + p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception); + if (p == (const PixelPacket *) NULL) + break; + for (x=0; x < ((ssize_t) image->columns-3); x+=4) + { + byte=(unsigned char) + ((((size_t) (3*ClampToQuantum(GetPixelLuma(image,p+3))/QuantumRange) & 0x03) << 6) | + (((size_t) (3*ClampToQuantum(GetPixelLuma(image,p+2))/QuantumRange) & 0x03) << 4) | + (((size_t) (3*ClampToQuantum(GetPixelLuma(image,p+1))/QuantumRange) & 0x03) << 2) | + (((size_t) (3*ClampToQuantum(GetPixelLuma(image,p+0))/QuantumRange) & 0x03) << 0)); + (void) FormatLocaleString(buffer,MaxTextExtent,"%02x",byte); + (void) WriteBlobString(image,buffer); + p+=4; + } + if ((image->columns % 4) != 0) + { + i=(ssize_t) image->columns % 4; + byte=(unsigned char) + ((((size_t) (3*ClampToQuantum(GetPixelLuma(image,p+MagickMin(i,3)))/QuantumRange) & 0x03) << 6) | + (((size_t) (3*ClampToQuantum(GetPixelLuma(image,p+MagickMin(i,2)))/QuantumRange) & 0x03) << 4) | + (((size_t) (3*ClampToQuantum(GetPixelLuma(image,p+MagickMin(i,1)))/QuantumRange) & 0x03) << 2) | + (((size_t) (3*ClampToQuantum(GetPixelLuma(image,p+MagickMin(i,0)))/QuantumRange) & 0x03) << 0)); + (void) FormatLocaleString(buffer,MaxTextExtent,"%02x",~byte); + (void) WriteBlobString(image,buffer); + } + status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, + image->rows); + if (status == MagickFalse) + break; + } + (void) WriteBlobString(image,"\n"); + (void) WriteBlobString(image,"\n"); + (void) CloseBlob(image); + return(MagickTrue); +} diff --git a/pool/shard004/C/0101342_test-delta.c b/pool/shard004/C/0101342_test-delta.c new file mode 100644 index 0000000000000000000000000000000000000000..59937dc1be1c4f0b3d80e3ef3a86e09bff3703b6 --- /dev/null +++ b/pool/shard004/C/0101342_test-delta.c @@ -0,0 +1,78 @@ +/* + * test-delta.c: test code to exercise diff-delta.c and patch-delta.c + * + * (C) 2005 Nicolas Pitre + * + * 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 "git-compat-util.h" +#include "delta.h" +#include "cache.h" + +static const char usage_str[] = + "test-delta (-d|-p) "; + +int cmd_main(int argc, const char **argv) +{ + int fd; + struct stat st; + void *from_buf, *data_buf, *out_buf; + unsigned long from_size, data_size, out_size; + + if (argc != 5 || (strcmp(argv[1], "-d") && strcmp(argv[1], "-p"))) { + fprintf(stderr, "usage: %s\n", usage_str); + return 1; + } + + fd = open(argv[2], O_RDONLY); + if (fd < 0 || fstat(fd, &st)) { + perror(argv[2]); + return 1; + } + from_size = st.st_size; + from_buf = mmap(NULL, from_size, PROT_READ, MAP_PRIVATE, fd, 0); + if (from_buf == MAP_FAILED) { + perror(argv[2]); + close(fd); + return 1; + } + close(fd); + + fd = open(argv[3], O_RDONLY); + if (fd < 0 || fstat(fd, &st)) { + perror(argv[3]); + return 1; + } + data_size = st.st_size; + data_buf = mmap(NULL, data_size, PROT_READ, MAP_PRIVATE, fd, 0); + if (data_buf == MAP_FAILED) { + perror(argv[3]); + close(fd); + return 1; + } + close(fd); + + if (argv[1][1] == 'd') + out_buf = diff_delta(from_buf, from_size, + data_buf, data_size, + &out_size, 0); + else + out_buf = patch_delta(from_buf, from_size, + data_buf, data_size, + &out_size); + if (!out_buf) { + fprintf(stderr, "delta operation failed (returned NULL)\n"); + return 1; + } + + fd = open (argv[4], O_WRONLY|O_CREAT|O_TRUNC, 0666); + if (fd < 0 || write_in_full(fd, out_buf, out_size) != out_size) { + perror(argv[4]); + return 1; + } + + return 0; +} diff --git a/pool/shard004/C/0101343_truncate.c b/pool/shard004/C/0101343_truncate.c new file mode 100644 index 0000000000000000000000000000000000000000..89661e683d6b94fcbac82ed70e574ec95fb08c6f --- /dev/null +++ b/pool/shard004/C/0101343_truncate.c @@ -0,0 +1,43 @@ +/* Copyright (C) 1991-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 + +/* Truncate FILE_NAME to LENGTH bytes. */ +int +__truncate (file_name, length) + const char *file_name; + off_t length; +{ + error_t err; + file_t file = __file_name_lookup (file_name, O_WRITE, 0); + + if (file == MACH_PORT_NULL) + return -1; + + err = __file_set_size (file, length); + __mach_port_deallocate (__mach_task_self (), file); + + if (err) + return __hurd_fail (err); + return 0; +} +weak_alias (__truncate, truncate) diff --git a/pool/shard004/C/0101346_gvfsjobopeniconforread.c b/pool/shard004/C/0101346_gvfsjobopeniconforread.c new file mode 100644 index 0000000000000000000000000000000000000000..bcb5361d3191b23ff2c57f598cbb9f150128afbc --- /dev/null +++ b/pool/shard004/C/0101346_gvfsjobopeniconforread.c @@ -0,0 +1,126 @@ +/* GIO - GLib Input, Output and Streaming Library + * + * Copyright (C) 2006-2007 Red Hat, Inc. + * + * 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. + * + * Author: Alexander Larsson + */ + +#include + +#include +#include +#include +#include + +#include +#include +#include +#include "gvfsreadchannel.h" +#include "gvfsjobopeniconforread.h" + +G_DEFINE_TYPE (GVfsJobOpenIconForRead, g_vfs_job_open_icon_for_read, G_VFS_TYPE_JOB_OPEN_FOR_READ) + +static void run (GVfsJob *job); +static gboolean try (GVfsJob *job); + +static void +g_vfs_job_open_icon_for_read_finalize (GObject *object) +{ + if (G_OBJECT_CLASS (g_vfs_job_open_icon_for_read_parent_class)->finalize) + (*G_OBJECT_CLASS (g_vfs_job_open_icon_for_read_parent_class)->finalize) (object); +} + +static void +g_vfs_job_open_icon_for_read_class_init (GVfsJobOpenIconForReadClass *klass) +{ + GObjectClass *gobject_class = G_OBJECT_CLASS (klass); + GVfsJobClass *job_class = G_VFS_JOB_CLASS (klass); + + gobject_class->finalize = g_vfs_job_open_icon_for_read_finalize; + job_class->run = run; + job_class->try = try; +} + +static void +g_vfs_job_open_icon_for_read_init (GVfsJobOpenIconForRead *job) +{ +} + +gboolean +g_vfs_job_open_icon_for_read_new_handle (GVfsDBusMount *object, + GDBusMethodInvocation *invocation, + GUnixFDList *fd_list, + const gchar *arg_path_data, + GVfsBackend *backend) +{ + GVfsJobOpenIconForRead *job; + GVfsJobOpenForRead *job_open_for_read; + + if (g_vfs_backend_invocation_first_handler (object, invocation, backend)) + return TRUE; + + job = g_object_new (G_VFS_TYPE_JOB_OPEN_ICON_FOR_READ, + "object", object, + "invocation", invocation, + NULL); + + job_open_for_read = G_VFS_JOB_OPEN_FOR_READ (job); + + job->icon_id = g_strdup (arg_path_data); + job_open_for_read->backend = backend; + job_open_for_read->read_icon = TRUE; + + g_vfs_job_source_new_job (G_VFS_JOB_SOURCE (backend), G_VFS_JOB (job)); + g_object_unref (job); + + return TRUE; +} + +static void +run (GVfsJob *job) +{ + GVfsJobOpenIconForRead *op_job = G_VFS_JOB_OPEN_ICON_FOR_READ (job); + GVfsJobOpenForRead *op_job_open_for_read = G_VFS_JOB_OPEN_FOR_READ (job); + GVfsBackendClass *class = G_VFS_BACKEND_GET_CLASS (op_job_open_for_read->backend); + + if (class->open_icon_for_read == NULL) + { + g_vfs_job_failed (job, G_IO_ERROR, G_IO_ERROR_NOT_SUPPORTED, + _("Operation not supported by backend")); + return; + } + + class->open_icon_for_read (op_job_open_for_read->backend, + op_job, + op_job->icon_id); +} + +static gboolean +try (GVfsJob *job) +{ + GVfsJobOpenIconForRead *op_job = G_VFS_JOB_OPEN_ICON_FOR_READ (job); + GVfsJobOpenForRead *op_job_open_for_read = G_VFS_JOB_OPEN_FOR_READ (job); + GVfsBackendClass *class = G_VFS_BACKEND_GET_CLASS (op_job_open_for_read->backend); + + if (class->try_open_icon_for_read == NULL) + return FALSE; + + return class->try_open_icon_for_read (op_job_open_for_read->backend, + op_job, + op_job->icon_id); +} diff --git a/pool/shard004/C/0101348_suffixarray.c b/pool/shard004/C/0101348_suffixarray.c new file mode 100644 index 0000000000000000000000000000000000000000..d01bb2efadd474c5c5e6177275e6b9180617a2d2 --- /dev/null +++ b/pool/shard004/C/0101348_suffixarray.c @@ -0,0 +1,149 @@ +/*############################################################################## +# +# Copyright 2010-2012 Carlos Ramisch, Vitor De Araujo +# +# suffixarray.c is part of mwetoolkit +# +# mwetoolkit is free software: you can 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. +# +# mwetoolkit is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with mwetoolkit. If not, see . +# +##############################################################################*/ +#include +#include "base.h" +#include "symboltable.h" +#include "suffixarray.h" + +suffixarray_t *current_suffix_array; + +suffixarray_t* make_suffixarray() { + suffixarray_t *new = alloc(1, suffixarray_t); + new->corpus = NULL; + new->suffix = NULL; + new->symboltable = make_symboltable(); + new->allocated = 0; + new->used = 0; + return new; +} + +void free_suffixarray(suffixarray_t *suf) { + free(suf->corpus); + free(suf->suffix); + free_symboltable(suf->symboltable); + free(suf); +} + +void suffixarray_append_word(suffixarray_t *suf, symbolname_t word) { + if (suf->used >= suf->allocated) { + resize_alloc(suf->corpus, + suf->allocated + SUFFIX_ARRAY_ALLOC_CHUNK, + symbolnumber_t); + resize_alloc(suf->suffix, + suf->allocated + SUFFIX_ARRAY_ALLOC_CHUNK, + position_t); + suf->allocated += SUFFIX_ARRAY_ALLOC_CHUNK; + } + + symbolnumber_t symnum = intern_symbol(suf->symboltable, word); + suf->corpus[suf->used] = symnum; + // suf->suffix[suf->used] = suf->used; + suf->used++; +} + +int suffixarray_compare(suffixarray_t *suf, position_t pos1, position_t pos2) { + position_t limit = suf->used; + symbolnumber_t *corpus = suf->corpus; + int first = 1; + + while (pos1=limit) + return -1; + else if (pos2>=limit) + return 1; + else + return 0; +} + +int suffixarray_compare_global(const void *ptr1, const void *ptr2) { + return suffixarray_compare(current_suffix_array, *(size_t *)ptr1, *(size_t *)ptr2); +} + +void suffixarray_sort(suffixarray_t *suf) { + position_t i; + current_suffix_array = suf; + for (i=0; i < suf->used; i++) + suf->suffix[i] = i; + qsort(suf->suffix, suf->used, sizeof(symbolnumber_t), suffixarray_compare_global); +} + +void read_suffix_array(suffixarray_t *suf, FILE *corpusfile, FILE *suffixfile) { + position_t nread1;//nread2; + while (1) { + suf->allocated += SUFFIX_ARRAY_ALLOC_CHUNK; + resize_alloc(suf->corpus, suf->allocated, symbolnumber_t); + resize_alloc(suf->suffix, suf->allocated, position_t); + nread1 = fread(corpusfile, sizeof(symbolnumber_t), SUFFIX_ARRAY_ALLOC_CHUNK, corpusfile); + fread(suffixfile, sizeof(position_t), SUFFIX_ARRAY_ALLOC_CHUNK, suffixfile); + suf->used += nread1; + if (nread1 < SUFFIX_ARRAY_ALLOC_CHUNK) + break; + } +} + +void write_suffix_array(suffixarray_t *suf, FILE *corpusfile, FILE *suffixfile) { + fwrite(suf->corpus, sizeof(symbolnumber_t), suf->used, corpusfile); + fwrite(suf->suffix, sizeof(position_t), suf->used, suffixfile); +} + +void load_suffix_array(suffixarray_t *suf, char *basepath) { + char corpuspath[strlen(basepath) + 7 + 1]; + char suffixpath[strlen(basepath) + 7 + 1]; + + strcpy(corpuspath, basepath); + strcat(corpuspath, ".corpus"); + strcpy(suffixpath, basepath); + strcat(suffixpath, ".suffix"); + + FILE *corpusfile = fopen(corpuspath, "r"); + FILE *suffixfile = fopen(suffixpath, "r"); + if (!corpusfile || !suffixfile) + error("-- Error opening corpus/suffix file for reading!\n"); + read_suffix_array(suf, corpusfile, suffixfile); + fclose(corpusfile); + fclose(suffixfile); +} + +void save_suffix_array(suffixarray_t *suf, char *basepath) { + char corpuspath[strlen(basepath) + 7 + 1]; + char suffixpath[strlen(basepath) + 7 + 1]; + + strcpy(corpuspath, basepath); + strcat(corpuspath, ".corpus"); + strcpy(suffixpath, basepath); + strcat(suffixpath, ".suffix"); + + FILE *corpusfile = fopen(corpuspath, "w"); + FILE *suffixfile = fopen(suffixpath, "w"); + if (!corpusfile || !suffixfile) + error("-- Error opening corpus/suffix file for reading!\n"); + write_suffix_array(suf, corpusfile, suffixfile); + fclose(corpusfile); + fclose(suffixfile); +} + diff --git a/pool/shard004/C/0101350_TeleOp.c b/pool/shard004/C/0101350_TeleOp.c new file mode 100644 index 0000000000000000000000000000000000000000..0f95f757290c2c9dcc744bad349280bbe78cc996 --- /dev/null +++ b/pool/shard004/C/0101350_TeleOp.c @@ -0,0 +1,289 @@ +#pragma config(Hubs, S1, HTMotor, HTMotor, HTServo, none) +#pragma config(Sensor, S1, , sensorI2CMuxController) +#pragma config(Motor, motorA, , tmotorNXT, PIDControl) +#pragma config(Motor, motorC, , tmotorNXT, PIDControl) +#pragma config(Motor, mtr_S1_C1_1, motorR, tmotorTetrix, openLoop) +#pragma config(Motor, mtr_S1_C1_2, motorL, tmotorTetrix, openLoop, reversed) +#pragma config(Motor, mtr_S1_C2_1, FlagMotor, tmotorTetrix, openLoop) +#pragma config(Motor, mtr_S1_C2_2, motorWinch, tmotorTetrix, openLoop) +#pragma config(Servo, srvo_S1_C3_1, servoFlip, tServoStandard) +#pragma config(Servo, srvo_S1_C3_2, hangServo, tServoStandard) +#pragma config(Servo, srvo_S1_C3_3, servo3, tServoNone) +#pragma config(Servo, srvo_S1_C3_4, servo4, tServoNone) +#pragma config(Servo, srvo_S1_C3_5, servo5, tServoNone) +#pragma config(Servo, srvo_S1_C3_6, servo6, tServoNone) +//*!!Code automatically generated by 'ROBOTC' configuration wizard !!*// + +///////////////////////////////////////////////////////////////////////////////////////////////////// +// +// Tele-Operation Mode Code Template +// +// This file contains a template for simplified creation of an tele-op program for an FTC +// competition. +// +// You need to customize two functions with code unique to your specific robot. +// +///////////////////////////////////////////////////////////////////////////////////////////////////// + +#include "JoystickDriver.c" //Include file to "handle" the Bluetooth messages. +#define JOYSTICK_MIN 10 + +const int rotateSpeed = 30; //speed for flag motor +int servoMoveRange = 140; +float hangArmPos=255.0;//starting position for lifting arm +///////////////////////////////////////////////////////////////////////////////////////////////////// +// +// initializeRobot +// +// Prior to the start of tele-op mode, you may want to perform some initialization on your robot +// and the variables within your program. +// +// In most cases, you may not have to add any code to this function and it will remain "empty". +// +///////////////////////////////////////////////////////////////////////////////////////////////////// +#define MOTOR_NUM 5 +#define MOTOR_MAX_VALUE 127 +#define MOTOR_MIN_VALUE (-127) +#define MOTOR_DEFAULT_SLEW_RATE 7 // Default will cause 375mS from full fwd to rev +#define MOTOR_FAST_SLEW_RATE 256 // essentially off +#define MOTOR_TASK_DELAY 15 // task 1/frequency in mS (about 66Hz) +#define MOTOR_DEADBAND 10 + +// Array to hold requested speed for the motors +int motorReq[ MOTOR_NUM ]; + +// Array to hold "slew rate" for the motors, the maximum change every time the task +// runs checking current mootor speed. +int motorSlew[ MOTOR_NUM ]; +task MotorSlewRateTask() +{ + int motorIndex; + int motorTmp; + + // Initialize stuff + for(motorIndex=0;motorIndex motorTmp ) + { + motorTmp += motorSlew[motorIndex]; + // limit + if( motorTmp > motorReq[motorIndex] ) + motorTmp = motorReq[motorIndex]; + } + + // decreasing motor value + if( motorReq[motorIndex] < motorTmp ) + { + motorTmp -= motorSlew[motorIndex]; + // limit + if( motorTmp < motorReq[motorIndex] ) + motorTmp = motorReq[motorIndex]; + } + + // finally set motor + motor[motorIndex] = motorTmp; + } + } + + // Wait approx the speed of motor update over the spi bus? + wait1Msec( MOTOR_TASK_DELAY ); + } +} + +void moveLiftArm() +{ + if (joy1Btn(6)&&hangArmPos>0) + { + hangArmPos -=0.1; + } + else if (joy1Btn(8)&&hangArmPos<255) + { + hangArmPos += 0.1; + } + servo[hangServo] = (int) hangArmPos; + //wait10Msec(servo[hangServo]); + + //move autonomous arm out of the way + + if (hangArmPos<245) + { + servo[servoFlip]=127; + } + else if (hangArmPos>245) + { + servo[servoFlip]=0; + } +} + +void operateWinch() +{ + + if (joy1Btn(2)) + { + motor[motorWinch]=100; + } + + if (joy1Btn(3)) + { + motor[motorWinch]= -100; + } + if (joy1Btn(2)==0 && joy1Btn(3)==0) + { + motor[motorWinch]=0; + } +} + +void initializeRobot() +{ +// Move servo1 to position to starting position +servo[hangServo]=hangArmPos; +} + +// Operate the two drive motors +void driveMotors() +{ + int joyLeft = joystick.joy1_y1; + int joyRight = -joystick.joy1_y2; + + // If the left or right joysticks are engaged beyond a minimum threshold, operate the drive + // motors; else stop them. The threshold is needed because a joystick that's not being touched + // can still show small non-zero values. + // Uses exponential increase in speed to help smooth the control at slow speeds. + if ((abs(joyLeft) > JOYSTICK_MIN) || (abs(joyRight) > JOYSTICK_MIN)) + { + if (abs(joyLeft) < 80) + { + if (joyLeft > 0) + joyLeft = -1*pow(1+.056,joyLeft); + else + joyLeft = 1*pow(1+.056,abs(joyLeft)); + } + + if (abs(joyRight) < 80) + { + if (joyRight > 0) + joyRight = -1*pow(1+.056,joyRight); + else + joyRight = 1*pow(1+.056,abs(joyRight)); + } + + motorReq[motorL] = (joyLeft)*100/127; + motorReq[motorR] = (joyRight)*-100/127; + //motor[motorL] = (joyLeft)*100/127; + //motor[motorR] = (joyRight)*-100/127; + } + else + { + motorReq[motorL] = 0; + motorReq[motorR] = 0; + //motor[motorL] = 0; + //motor[motorR] = 0; + } +} + +void driveMotors (int lspeed, int rspeed) +{ +//motorReq[motorL] = lspeed; +//motorReq[motorR] = rspeed; +motor[motorL] = lspeed; +motor[motorR] = rspeed; +} + +//Raise Flag +void flagControl(int direction) +{ + if (direction == 0) { + motor[FlagMotor] = 0 ; // turn motor off + } + else { + motor[FlagMotor] = rotateSpeed*direction ; // turn flag + } +} + +int getFlagButtons() +{ + int button; + if (joy1Btn(7))//Button for control of the motor to turn flag + button = -1; + else if (joy1Btn(5)) + button = 1; + else + button = 0; + return button; +} + +///////////////////////////////////////////////////////////////////////////////////////////////////// +// +// Main Task +// +// The following is the main code for the tele-op robot operation. Customize as appropriate for +// your specific robot. +// +// Game controller / joystick information is sent periodically (about every 50 milliseconds) from +// the FMS (Field Management System) to the robot. Most tele-op programs will follow the following +// logic: +// 1. Loop forever repeating the following actions: +// 2. Get the latest game controller / joystick settings that have been received from the PC. +// 3. Perform appropriate actions based on the joystick + buttons settings. This is usually a +// simple action: +// * Joystick values are usually directly translated into power levels for a motor or +// position of a servo. +// * Buttons are usually used to start/stop a motor or cause a servo to move to a specific +// position. +// 4. Repeat the loop. +// +// Your program needs to continuously loop because you need to continuously respond to changes in +// the game controller settings. +// +// At the end of the tele-op period, the FMS will autonmatically abort (stop) execution of the program. +// +///////////////////////////////////////////////////////////////////////////////////////////////////// + +task main() +{ + initializeRobot(); + //waitForStart(); // wait for start of tele-op phase + //StartTask(MotorSlewRateTask); + while (true) + { + /////////////////////////////////////////////////////////// + /////////////////////////////////////////////////////////// + //// //// + //// Add your robot specific tele-op code here. //// + //// //// + /////////////////////////////////////////////////////////// + /////////////////////////////////////////////////////////// + + getJoystickSettings(joystick); // Obtain current game controller settings + + // Display the settings on the NXT Brick + nxtDisplayString(0, "joy1_x1: %d", joystick.joy1_x1); + nxtDisplayString(1, "joy1_y1: %d", joystick.joy1_y1); + nxtDisplayString(2, "joy1_x2: %d", joystick.joy1_x2); + nxtDisplayString(3, "joy1_y2: %d", joystick.joy1_y2); + nxtDisplayString(4, "Buttons: %d", joystick.joy1_Buttons); + nxtDisplayString(5, "TopHat: %d", joystick.joy1_TopHat); + // Drive Motors + flagControl(getFlagButtons()); + moveLiftArm(); + operateWinch(); + driveMotors(); + } +} diff --git a/pool/shard004/C/0101357_main.c b/pool/shard004/C/0101357_main.c new file mode 100644 index 0000000000000000000000000000000000000000..c088b947f2547b8de9d06d8b42045c6d2b98ffac --- /dev/null +++ b/pool/shard004/C/0101357_main.c @@ -0,0 +1,185 @@ +/* + * 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 "sysinit/sysinit.h" +#include "os/os.h" +#include "console/console.h" +#include "host/ble_hs.h" +#include "host/util/util.h" +#include "log/log.h" + +static uint8_t g_own_addr_type; + +static void +ble_app_set_addr(void) +{ + ble_addr_t addr; + int rc; + + /* generate new non-resolvable private address */ + rc = ble_hs_id_gen_rnd(0, &addr); + assert(rc == 0); + + /* set generated address */ + rc = ble_hs_id_set_rnd(addr.val); + assert(rc == 0); +} + +/* scan_event() calls scan(), so forward declaration is required */ +static void scan(void); + +/* connection has separate event handler from scan */ +static int +conn_event(struct ble_gap_event *event, void *arg) +{ + switch (event->type) { + case BLE_GAP_EVENT_CONNECT: + if (event->connect.status == 0) { + MODLOG_DFLT(INFO,"Connection was established\n"); + ble_gap_terminate(event->connect.conn_handle, 0x13); + } else { + MODLOG_DFLT(INFO,"Connection failed, error code: %i\n", + event->connect.status); + } + break; + case BLE_GAP_EVENT_DISCONNECT: + MODLOG_DFLT(INFO,"Disconnected, reason code: %i\n", + event->disconnect.reason); + scan(); + break; + case BLE_GAP_EVENT_CONN_UPDATE_REQ: + MODLOG_DFLT(INFO,"Connection update request received\n"); + break; + case BLE_GAP_EVENT_CONN_UPDATE: + if (event->conn_update.status == 0) { + MODLOG_DFLT(INFO,"Connection update successful\n"); + } else { + MODLOG_DFLT(INFO,"Connection update failed; reson: %d\n", + event->conn_update.status); + } + break; + default: + MODLOG_DFLT(INFO,"Connection event type not supported, %d\n", + event->type); + break; + } + return 0; +} + +static int +scan_event(struct ble_gap_event *event, void *arg) +{ + /* predef_uuid stores information about UUID of device, + that we connect to */ + const ble_uuid128_t predef_uuid = + BLE_UUID128_INIT(0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, + 0x88, 0x99, 0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff); + struct ble_hs_adv_fields parsed_fields; + int uuid_cmp_result; + + memset(&parsed_fields, 0, sizeof(parsed_fields)); + + switch (event->type) { + /* advertising report has been received during discovery procedure */ + case BLE_GAP_EVENT_DISC: + MODLOG_DFLT(INFO, "Advertising report received! Checking UUID...\n"); + ble_hs_adv_parse_fields(&parsed_fields, event->disc.data, + event->disc.length_data); + /* Predefined UUID is compared to recieved one; + if doesn't fit - end procedure and go back to scanning, + else - connect. */ + uuid_cmp_result = ble_uuid_cmp(&predef_uuid.u, &parsed_fields.uuids128->u); + if (uuid_cmp_result) { + MODLOG_DFLT(INFO, "UUID doesn't fit\n"); + } else { + MODLOG_DFLT(INFO, "UUID fits, connecting...\n"); + ble_gap_disc_cancel(); + ble_gap_connect(g_own_addr_type, &(event->disc.addr), 10000, + NULL, conn_event, NULL); + } + break; + case BLE_GAP_EVENT_DISC_COMPLETE: + MODLOG_DFLT(INFO,"Discovery completed, reason: %d\n", + event->disc_complete.reason); + scan(); + break; + default: + MODLOG_DFLT(ERROR, "Discovery event not handled\n"); + break; + } + return 0; +} + +static void +scan(void) +{ + int rc; + + /* set scan parameters: + - scan interval in 0.625ms units + - scan window in 0.625ms units + - filter policy - 0 if whitelisting not used + - limited - should limited discovery be used + - passive - should passive scan be used + - filter duplicates - 1 enables filtering duplicated advertisements */ + const struct ble_gap_disc_params scan_params = {10000, 200, 0, 0, 0, 1}; + + /* performs discovery procedure */ + rc = ble_gap_disc(g_own_addr_type, 10000, &scan_params,scan_event, NULL); + assert(rc == 0); +} + +static void +on_sync(void) +{ + int rc; + /* Generate a non-resolvable private address. */ + ble_app_set_addr(); + + /* g_own_addr_type will store type of addres our BSP uses */ + + rc = ble_hs_util_ensure_addr(0); + rc = ble_hs_id_infer_auto(0, &g_own_addr_type); + assert(rc == 0); + /* begin scanning */ + scan(); +} + +static void +on_reset(int reason) +{ + console_printf("Resetting state; reason=%d\n", reason); +} + +int +main(int argc, char **argv) +{ + /* Initialize all packages. */ + sysinit(); + + ble_hs_cfg.sync_cb = on_sync; + ble_hs_cfg.reset_cb = on_reset; + + /* As the last thing, process events from default event queue. */ + while (1) { + os_eventq_run(os_eventq_dflt_get()); + } + + return 0; +} diff --git a/pool/shard004/C/0101366_max6675.c b/pool/shard004/C/0101366_max6675.c new file mode 100644 index 0000000000000000000000000000000000000000..ae9754e99bc109039efabe814ebbb7a90a3e7bc8 --- /dev/null +++ b/pool/shard004/C/0101366_max6675.c @@ -0,0 +1,53 @@ + +#include "max6675.h" + +static void printInt16(uint16_t d) { + int i; + for (i = 15; i >= 0; i--) { + int v = (d >> i) & 1; + printf("%d", v); + } + puts(""); +} + +int max6675_init(int sclk, int cs, int miso) { + pinModeOut(cs); + pinModeOut(sclk); + pinModeIn(miso); + pinPUD(miso, PUD_DOWN); + pinHigh(cs); + return 1; +} + +int max6675_read(float *result, int sclk, int cs, int miso) { + uint16_t v=0; + pinLow(cs); + delayUsBusy(1000); + { + int i; + for (i = 15; i >= 0; i--) { + pinLow(sclk); + DELAY_US_BUSY(1000); + if (pinRead(miso)) { + v |= (1 << i); + } + pinHigh(sclk); + DELAY_US_BUSY(1000); + } + } + pinHigh(cs); +#ifdef MODE_DEBUG + printInt16(v); +#endif + if (v & 0x4) { +#ifdef MODE_DEBUG + fprintf(stderr,"%s(): thermocouple input is open\n", __func__); +#endif + return 0; + } + v >>= 3; + *result = v * 0.25; + return 1; +} + + diff --git a/pool/shard004/C/0101382_CWE78_OS_Command_Injection__char_listen_socket_w32spawnl_14.c b/pool/shard004/C/0101382_CWE78_OS_Command_Injection__char_listen_socket_w32spawnl_14.c new file mode 100644 index 0000000000000000000000000000000000000000..2decde7640787f0d4070ac53ad00906f7afabc39 --- /dev/null +++ b/pool/shard004/C/0101382_CWE78_OS_Command_Injection__char_listen_socket_w32spawnl_14.c @@ -0,0 +1,226 @@ +/* TEMPLATE GENERATED TESTCASE FILE +Filename: CWE78_OS_Command_Injection__char_listen_socket_w32spawnl_14.c +Label Definition File: CWE78_OS_Command_Injection.strings.label.xml +Template File: sources-sink-14.tmpl.c +*/ +/* + * @description + * CWE: 78 OS Command Injection + * BadSource: listen_socket Read data using a listen socket (server side) + * GoodSource: Fixed string + * Sink: w32spawnl + * BadSink : execute command with spawnl + * Flow Variant: 14 Control flow: if(globalFive==5) and if(globalFive!=5) + * + * */ + +#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 "-c" +#define COMMAND_ARG2 "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 + +#include + +#ifndef OMITBAD + +void CWE78_OS_Command_Injection__char_listen_socket_w32spawnl_14_bad() +{ + char * data; + char dataBuffer[100] = COMMAND_ARG2; + data = dataBuffer; + if(globalFive==5) + { + { +#ifdef _WIN32 + WSADATA wsaData; + int wsaDataInit = 0; +#endif + int recvResult; + struct sockaddr_in service; + char *replace; + SOCKET listenSocket = INVALID_SOCKET; + SOCKET acceptSocket = 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 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(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 (listenSocket != INVALID_SOCKET) + { + CLOSE_SOCKET(listenSocket); + } + if (acceptSocket != INVALID_SOCKET) + { + CLOSE_SOCKET(acceptSocket); + } +#ifdef _WIN32 + if (wsaDataInit) + { + WSACleanup(); + } +#endif + } + } + /* spawnl - specify the path where the command is located */ + /* POTENTIAL FLAW: Execute command without validating input possibly leading to command injection */ + _spawnl(_P_WAIT, COMMAND_INT_PATH, COMMAND_INT_PATH, COMMAND_ARG1, COMMAND_ARG3, NULL); +} + +#endif /* OMITBAD */ + +#ifndef OMITGOOD + +/* goodG2B1() - use goodsource and badsink by changing the globalFive==5 to globalFive!=5 */ +static void goodG2B1() +{ + char * data; + char dataBuffer[100] = COMMAND_ARG2; + data = dataBuffer; + if(globalFive!=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) */ + strcat(data, "*.*"); + } + /* spawnl - specify the path where the command is located */ + /* POTENTIAL FLAW: Execute command without validating input possibly leading to command injection */ + _spawnl(_P_WAIT, 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() +{ + char * data; + char dataBuffer[100] = COMMAND_ARG2; + data = dataBuffer; + if(globalFive==5) + { + /* FIX: Append a fixed string to data (not user / external input) */ + strcat(data, "*.*"); + } + /* spawnl - specify the path where the command is located */ + /* POTENTIAL FLAW: Execute command without validating input possibly leading to command injection */ + _spawnl(_P_WAIT, COMMAND_INT_PATH, COMMAND_INT_PATH, COMMAND_ARG1, COMMAND_ARG3, NULL); +} + +void CWE78_OS_Command_Injection__char_listen_socket_w32spawnl_14_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_listen_socket_w32spawnl_14_good(); + printLine("Finished good()"); +#endif /* OMITGOOD */ +#ifndef OMITBAD + printLine("Calling bad()..."); + CWE78_OS_Command_Injection__char_listen_socket_w32spawnl_14_bad(); + printLine("Finished bad()"); +#endif /* OMITBAD */ + return 0; +} + +#endif diff --git a/pool/shard004/C/0101385_ipcp-1.c b/pool/shard004/C/0101385_ipcp-1.c new file mode 100644 index 0000000000000000000000000000000000000000..baa9c97ffb0bb64cc7f1ff040eeb7745cb4ffa8a --- /dev/null +++ b/pool/shard004/C/0101385_ipcp-1.c @@ -0,0 +1,51 @@ +/* Test that IPA-CP is able to figure out that both parameters a are constant 7 + even though f and h recursively call each other and specialize them + accordingly. */ + +/* { dg-do compile } */ +/* { dg-options "-O3 -fipa-cp -fipa-cp-clone -fdump-ipa-cp -fno-early-inlining" } */ +/* { dg-add-options bind_pic_locally } */ + +extern void use_stuff (int); + +static +int g (int b, int c) +{ + int i; + + for (i = 0; i < b; i++) + use_stuff (c); +} + +static void f (int a, int x, int z); + +static void h (int z, int a) +{ + use_stuff (z); + f (a, 9, 10); + +} + +static void +f (int a, int x, int z) +{ + if (z > 1) + g (a, x); + else + h (5, a); +} + +int +main (int argc, char *argv[]) +{ + int i; + for (i = 0; i < 100; i++) + f (7, 8, argc); + return 0; +} + + +/* { dg-final { scan-ipa-dump "Creating a specialized node of f" "cp" } } */ +/* { dg-final { scan-ipa-dump "replacing param .0 a with const 7" "cp" } } */ + + diff --git a/pool/shard004/C/0101412_main.c b/pool/shard004/C/0101412_main.c new file mode 100644 index 0000000000000000000000000000000000000000..26fdf4eb3604f0b0942edbc7d391a9e18b586cd0 --- /dev/null +++ b/pool/shard004/C/0101412_main.c @@ -0,0 +1,196 @@ +//**************************************************************************** +// EXEMPLO USO DA EEPROM INTERNA +//**************************************************************************** +//Compilador CCS PCWH Ver 4.104 + +#include <16F877.h> //include do 16F628 +#include +#include <16f8x_registradores.h> //MAPEAMENTO DE MEÓRIA DOS REGISTRADORES + +//**************************************************************************** +// CONFIGURAÇÕES DO COMPILADOR +//**************************************************************************** + +#use fast_io(a) //modo de entrada e saida de dados que +#use fast_io(b) //o compilador nao configura o tris + +#use delay(clock=20000000) //clock usual +#fuses HS,NOWDT,NOLVP,PUT,NOPROTECT + +#rom 0x2100={'P','I','C',' '} //programa os primeiros endereços da eeprom + +//**************************************************************************** +// BIOS +//**************************************************************************** +//**************************** ENTRADAS ************************************ + + +//***************************** SAÍDAS ************************************* + +// As definições a seguir são utilizadas para acesso aos pinos do display +// caso o pino RW não seja utilizado, comente a definição lcd_rw +#ifndef lcd_enable + #define lcd_enable pin_b5 // pino enable do LCD + #define lcd_rs pin_b4 // pino rs do LCD + //#define lcd_rw pin_b2 // pino rw do LCD + #define lcd_d4 pin_b0 // pino de dados d4 do LCD + #define lcd_d5 pin_b1 // pino de dados d5 do LCD + #define lcd_d6 pin_b2 // pino de dados d6 do LCD + #define lcd_d7 pin_b3 // pino de dados d7 do LCD +#endif + +//**************************************************************************** +// CONSTANTES E VARIÁVEIS +//**************************************************************************** + +int w_temp; +int status_temp; +int count; +char texto[16]; + +//*************************************************************************** +// DRIVES +//*************************************************************************** +#include "c:\dados\projeto\includes\lcd.h" + +//**************************************************************************** +// Rotinas da interrupcao +//**************************************************************************** +//#inline //descomentar se for usar o in_line + +//**************************************************************************** +// INTERRUPÇÕES +//**************************************************************************** +#int_global +void interrupcao(){ +restart_wdt(); +disable_interrupts(global); +#asm +movwf w_temp +swapf status,w +movwf status_temp +#endasm + + +//*************************************************************************** +// FIM DA INTERRUPCAO +//*************************************************************************** +enable_interrupts(global); +#asm +swapf status_temp,w +movwf status +swapf w_temp,f +swapf w_temp,w +#endasm +} + +//**************************************************************************** +// Sub-rotinas +//**************************************************************************** + + +//**************************************************************************** +// Rotina Principal +//**************************************************************************** + +void main(){ +//********************** CONFIGURAÇÕES INICIAIS ***************************** + setup_timer_0(rtcc_internal); //clock interno + setup_wdt(wdt_288ms); + disable_interrupts(global); + port_b_pullups(false); //sem pull-up + +// Configuração do tris +// Bit porta: 76543210 + tris_a = 0b00000000; + tris_b = 0b00000000; + tris_c = 0b00000000; + tris_d = 0b00000000; + tris_e = 0b00000000; + +// Inicialização do LCD + lcd_ini(); + delay_ms(100); + lcd_escreve('\f'); //Limpa o lcd + lcd_escreve('\b'); +//******************** INICIALIZAÇÃO DE VARIÁVEIS *************************** + count = 0; + texto = "16F877A"; + +//**************************************************************************** +// INICIO DO LOOP +//**************************************************************************** + while(1){ + restart_wdt(); + + while(count + * + * 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 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. + * + * Abstract director API + * + * The abstract director API does not know how we talk to the backend or + * if there even is one in the usual meaning of the word. + * + */ + +#include "config.h" + +#include "cache.h" + +#include "cache_director.h" + +/* Resolve director --------------------------------------------------*/ + +static const struct director * +vdi_resolve(struct worker *wrk, struct busyobj *bo) +{ + const struct director *d; + const struct director *d2; + + CHECK_OBJ_NOTNULL(wrk, WORKER_MAGIC); + CHECK_OBJ_NOTNULL(bo, BUSYOBJ_MAGIC); + + for (d = bo->director_req; d != NULL && d->resolve != NULL; d = d2) { + CHECK_OBJ_NOTNULL(d, DIRECTOR_MAGIC); + d2 = d->resolve(d, wrk, bo); + if (d2 == NULL) + VSLb(bo->vsl, SLT_FetchError, + "Director %s returned no backend", d->vcl_name); + } + CHECK_OBJ_ORNULL(d, DIRECTOR_MAGIC); + if (d == NULL) + VSLb(bo->vsl, SLT_FetchError, "No backend"); + bo->director_resp = d; + return (d); +} + +/* Get a set of response headers -------------------------------------*/ + +int +VDI_GetHdr(struct worker *wrk, struct busyobj *bo) +{ + const struct director *d; + int i = -1; + + CHECK_OBJ_NOTNULL(wrk, WORKER_MAGIC); + CHECK_OBJ_NOTNULL(bo, BUSYOBJ_MAGIC); + + d = vdi_resolve(wrk, bo); + if (d != NULL) { + AN(d->gethdrs); + bo->director_state = DIR_S_HDRS; + i = d->gethdrs(d, wrk, bo); + } + if (i) + bo->director_state = DIR_S_NULL; + return (i); +} + +/* Setup body fetch --------------------------------------------------*/ + +int +VDI_GetBody(struct worker *wrk, struct busyobj *bo) +{ + const struct director *d; + + CHECK_OBJ_NOTNULL(wrk, WORKER_MAGIC); + CHECK_OBJ_NOTNULL(bo, BUSYOBJ_MAGIC); + + d = bo->director_resp; + CHECK_OBJ_NOTNULL(d, DIRECTOR_MAGIC); + AZ(d->resolve); + AN(d->getbody); + + assert(bo->director_state == DIR_S_HDRS); + bo->director_state = DIR_S_BODY; + return (d->getbody(d, wrk, bo)); +} + +/* Get IP number (if any ) -------------------------------------------*/ + +const struct suckaddr * +VDI_GetIP(struct worker *wrk, struct busyobj *bo) +{ + const struct director *d; + + CHECK_OBJ_NOTNULL(wrk, WORKER_MAGIC); + CHECK_OBJ_NOTNULL(bo, BUSYOBJ_MAGIC); + + d = bo->director_resp; + CHECK_OBJ_NOTNULL(d, DIRECTOR_MAGIC); + assert(bo->director_state == DIR_S_HDRS || + bo->director_state == DIR_S_BODY); + AZ(d->resolve); + if (d->getip == NULL) + return (NULL); + return (d->getip(d, wrk, bo)); +} + +/* Finish fetch ------------------------------------------------------*/ + +void +VDI_Finish(struct worker *wrk, struct busyobj *bo) +{ + const struct director *d; + + CHECK_OBJ_NOTNULL(wrk, WORKER_MAGIC); + CHECK_OBJ_NOTNULL(bo, BUSYOBJ_MAGIC); + + d = bo->director_resp; + CHECK_OBJ_NOTNULL(d, DIRECTOR_MAGIC); + + AZ(d->resolve); + AN(d->finish); + + assert(bo->director_state != DIR_S_NULL); + d->finish(d, wrk, bo); + bo->director_state = DIR_S_NULL; +} + +/* Get a connection --------------------------------------------------*/ + +int +VDI_Http1Pipe(struct req *req, struct busyobj *bo) +{ + const struct director *d; + + CHECK_OBJ_NOTNULL(req, REQ_MAGIC); + CHECK_OBJ_NOTNULL(bo, BUSYOBJ_MAGIC); + + d = vdi_resolve(req->wrk, bo); + if (d == NULL || d->http1pipe == NULL) + return (-1); + d->http1pipe(d, req, bo); + return (0); +} + +/* Check health -------------------------------------------------------- + * + * If director has no healthy method, we just assume it is healthy. + */ + +int +VDI_Healthy(const struct director *d, const struct busyobj *bo) +{ + + CHECK_OBJ_NOTNULL(d, DIRECTOR_MAGIC); + if (d->healthy == NULL) + return (1); + return (d->healthy(d, bo, NULL)); +} + +/* Dump panic info ----------------------------------------------------- + */ + +void +VDI_Panic(const struct director *d, struct vsb *vsb, const char *nm) +{ + if (d == NULL) + return; + VSB_printf(vsb, " %s = %p {\n", nm, d); + VSB_printf(vsb, " vcl_name = %s\n", d->vcl_name); + VSB_printf(vsb, " name = %s\n", d->name); + if (d->panic != NULL) + d->panic(d, vsb); + VSB_printf(vsb, " }\n"); +} diff --git a/pool/shard004/C/0101431_pidwait.c b/pool/shard004/C/0101431_pidwait.c new file mode 100644 index 0000000000000000000000000000000000000000..7510883c7e4eb48cf5496819c6376c8be8280856 --- /dev/null +++ b/pool/shard004/C/0101431_pidwait.c @@ -0,0 +1,56 @@ +/* pidwait.c - wait for child to exit */ +#ifndef lint +static char ident[] = "@(#)$Id: pidwait.c,v 1.10 1992/12/15 00:20:22 jromine Exp $"; +#endif /* lint */ + +#include "../h/mh.h" +#include +#include +#if defined (BSD42) || defined (SVR4) +#include +#endif + + +int pidwait (id, sigsok) +register int id, + sigsok; +{ + register int pid; + TYPESIG (*hstat) (), (*istat) (), (*qstat) (), (*tstat) (); +#if defined(BSD42) && !defined(WAITINT) + union wait status; +#else + int status; +#endif + + if (sigsok == NOTOK) { +#ifdef notdef /* I don't see why to trap these... */ + hstat = signal (SIGHUP, SIG_IGN); + tstat = signal (SIGTERM, SIG_IGN); +#endif + istat = signal (SIGINT, SIG_IGN); + qstat = signal (SIGQUIT, SIG_IGN); + } + +#ifdef SVR4 + pid = waitpid (id, &status, WUNTRACED); +#else + while ((pid = wait (&status)) != NOTOK && pid != id) + continue; +#endif + + if (sigsok == NOTOK) { +#ifdef notdef + (void) signal (SIGHUP, hstat); + (void) signal (SIGTERM, tstat); +#endif + (void) signal (SIGINT, istat); + (void) signal (SIGQUIT, qstat); + } + +#if defined(BSD42) && !defined(WAITINT) + return (pid == NOTOK ? NOTOK : status.w_status); +#else + return (pid == NOTOK ? NOTOK : status); +#endif +} diff --git a/pool/shard004/C/0101441_gen_crc32table.c b/pool/shard004/C/0101441_gen_crc32table.c new file mode 100644 index 0000000000000000000000000000000000000000..8d940175c5956e50f9f50cb60dd1378edcf11944 --- /dev/null +++ b/pool/shard004/C/0101441_gen_crc32table.c @@ -0,0 +1,82 @@ +#include +#include "crc32defs.h" +#include + +#define ENTRIES_PER_LINE 4 + +#define LE_TABLE_SIZE (1 << CRC_LE_BITS) +#define BE_TABLE_SIZE (1 << CRC_BE_BITS) + +static u_int32_t crc32table_le[LE_TABLE_SIZE]; +static u_int32_t crc32table_be[BE_TABLE_SIZE]; + +/** + * crc32init_le() - allocate and initialize LE table data + * + * crc is the crc of the byte i; other entries are filled in based on the + * fact that crctable[i^j] = crctable[i] ^ crctable[j]. + * + */ +static void crc32init_le(void) +{ + unsigned i, j; + u_int32_t crc = 1; + + crc32table_le[0] = 0; + + for (i = 1 << (CRC_LE_BITS - 1); i; i >>= 1) { + crc = (crc >> 1) ^ ((crc & 1) ? CRCPOLY_LE : 0); + for (j = 0; j < LE_TABLE_SIZE; j += 2 * i) + crc32table_le[i + j] = crc ^ crc32table_le[j]; + } +} + +/** + * crc32init_be() - allocate and initialize BE table data + */ +static void crc32init_be(void) +{ + unsigned i, j; + u_int32_t crc = 0x80000000; + + crc32table_be[0] = 0; + + for (i = 1; i < BE_TABLE_SIZE; i <<= 1) { + crc = (crc << 1) ^ ((crc & 0x80000000) ? CRCPOLY_BE : 0); + for (j = 0; j < i; j++) + crc32table_be[i + j] = crc ^ crc32table_be[j]; + } +} + +static void output_table(u_int32_t table[], int len, char *trans) +{ + int i; + + for (i = 0; i < len - 1; i++) { + if (i % ENTRIES_PER_LINE == 0) + printf("\n"); + printf("%s(0x%8.8xL), ", trans, table[i]); + } + printf("%s(0x%8.8xL)\n", trans, table[len - 1]); +} + +int main(int argc, char** argv) +{ + printf("/* this file is generated - do not edit */\n\n"); + + if (CRC_LE_BITS > 1) { + crc32init_le(); + printf("static const u32 crc32table_le[] = {"); + output_table(crc32table_le, LE_TABLE_SIZE, "tole"); + printf("};\n"); + } + + if (CRC_BE_BITS > 1) { + crc32init_be(); + printf("static const u32 crc32table_be[] = {"); + output_table(crc32table_be, BE_TABLE_SIZE, "tobe"); + printf("};\n"); + } + + return 0; +} diff --git a/pool/shard004/C/0101442_ion_cma_secure_heap.c b/pool/shard004/C/0101442_ion_cma_secure_heap.c new file mode 100644 index 0000000000000000000000000000000000000000..bdf48b3b1720447e06c1c2a1ec6b4fe0ccc63eec --- /dev/null +++ b/pool/shard004/C/0101442_ion_cma_secure_heap.c @@ -0,0 +1,297 @@ +/* + * drivers/gpu/ion/ion_secure_cma_heap.c + * + * Copyright (C) Linaro 2012 + * Author: for ST-Ericsson. + * Copyright (c) 2013, The Linux Foundation. All rights reserved. + * + * 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 + +/* for ion_heap_ops structure */ +#include "ion_priv.h" +#include "msm/ion_cp_common.h" + +#define ION_CMA_ALLOCATE_FAILED NULL + +struct ion_secure_cma_buffer_info { + /* + * This needs to come first for compatibility with the secure buffer API + */ + struct ion_cp_buffer secure; + void *cpu_addr; + dma_addr_t handle; + struct sg_table *table; + bool is_cached; +}; + +/* + * Create scatter-list for the already allocated DMA buffer. + * This function could be replace by dma_common_get_sgtable + * as soon as it will avalaible. + */ +int ion_secure_cma_get_sgtable(struct device *dev, struct sg_table *sgt, + void *cpu_addr, dma_addr_t handle, size_t size) +{ + struct page *page = phys_to_page(handle); + int ret; + + ret = sg_alloc_table(sgt, 1, GFP_KERNEL); + if (unlikely(ret)) + return ret; + + sg_set_page(sgt->sgl, page, PAGE_ALIGN(size), 0); + sg_dma_address(sgt->sgl) = handle; + return 0; +} + +/* ION CMA heap operations functions */ +static struct ion_secure_cma_buffer_info *__ion_secure_cma_allocate( + struct ion_heap *heap, struct ion_buffer *buffer, + unsigned long len, unsigned long align, + unsigned long flags) +{ + struct device *dev = heap->priv; + struct ion_secure_cma_buffer_info *info; + DEFINE_DMA_ATTRS(attrs); + dma_set_attr(DMA_ATTR_NO_KERNEL_MAPPING, &attrs); + + dev_dbg(dev, "Request buffer allocation len %ld\n", len); + + info = kzalloc(sizeof(struct ion_secure_cma_buffer_info), GFP_KERNEL); + if (!info) { + dev_err(dev, "Can't allocate buffer info\n"); + return ION_CMA_ALLOCATE_FAILED; + } + + info->cpu_addr = dma_alloc_attrs(dev, len, &(info->handle), GFP_KERNEL, + &attrs); + + if (!info->cpu_addr) { + dev_err(dev, "Fail to allocate buffer\n"); + goto err; + } + + info->table = kmalloc(sizeof(struct sg_table), GFP_KERNEL); + if (!info->table) { + dev_err(dev, "Fail to allocate sg table\n"); + goto err; + } + + ion_secure_cma_get_sgtable(dev, + info->table, info->cpu_addr, info->handle, len); + + info->secure.buffer = info->handle; + + /* keep this for memory release */ + buffer->priv_virt = info; + dev_dbg(dev, "Allocate buffer %p\n", buffer); + return info; + +err: + kfree(info); + return ION_CMA_ALLOCATE_FAILED; +} + +static int ion_secure_cma_allocate(struct ion_heap *heap, + struct ion_buffer *buffer, + unsigned long len, unsigned long align, + unsigned long flags) +{ + unsigned long secure_allocation = flags & ION_FLAG_SECURE; + struct ion_secure_cma_buffer_info *buf = NULL; + + if (!secure_allocation) { + pr_err("%s: non-secure allocation disallowed from heap %s %lx\n", + __func__, heap->name, flags); + return -ENOMEM; + } + + if (ION_IS_CACHED(flags)) { + pr_err("%s: cannot allocate cached memory from secure heap %s\n", + __func__, heap->name); + return -ENOMEM; + } + + + buf = __ion_secure_cma_allocate(heap, buffer, len, align, flags); + + if (buf) { + int ret; + + buf->secure.want_delayed_unsecure = 0; + atomic_set(&buf->secure.secure_cnt, 0); + mutex_init(&buf->secure.lock); + buf->secure.is_secure = 1; + buf->secure.ignore_check = true; + + /* + * make sure the size is set before trying to secure + */ + buffer->size = len; + ret = ion_cp_secure_buffer(buffer, ION_CP_V2, 0, 0); + if (ret) { + /* + * Don't treat the secure buffer failing here as an + * error for backwards compatibility reasons. If + * the secure fails, the map will also fail so there + * is no security risk. + */ + pr_debug("%s: failed to secure buffer\n", __func__); + } + return 0; + } else { + return -ENOMEM; + } +} + + +static void ion_secure_cma_free(struct ion_buffer *buffer) +{ + struct device *dev = buffer->heap->priv; + struct ion_secure_cma_buffer_info *info = buffer->priv_virt; + + dev_dbg(dev, "Release buffer %p\n", buffer); + + ion_cp_unsecure_buffer(buffer, 1); + /* release memory */ + dma_free_coherent(dev, buffer->size, info->cpu_addr, info->handle); + sg_free_table(info->table); + /* release sg table */ + kfree(info->table); + kfree(info); +} + +static int ion_secure_cma_phys(struct ion_heap *heap, struct ion_buffer *buffer, + ion_phys_addr_t *addr, size_t *len) +{ + struct device *dev = heap->priv; + struct ion_secure_cma_buffer_info *info = buffer->priv_virt; + + dev_dbg(dev, "Return buffer %p physical address 0x%pa\n", buffer, + &info->handle); + + *addr = info->handle; + *len = buffer->size; + + return 0; +} + +struct sg_table *ion_secure_cma_heap_map_dma(struct ion_heap *heap, + struct ion_buffer *buffer) +{ + struct ion_secure_cma_buffer_info *info = buffer->priv_virt; + + return info->table; +} + +void ion_secure_cma_heap_unmap_dma(struct ion_heap *heap, + struct ion_buffer *buffer) +{ + return; +} + +static int ion_secure_cma_mmap(struct ion_heap *mapper, + struct ion_buffer *buffer, + struct vm_area_struct *vma) +{ + pr_info("%s: mmaping from secure heap %s disallowed\n", + __func__, mapper->name); + return -EINVAL; +} + +static void *ion_secure_cma_map_kernel(struct ion_heap *heap, + struct ion_buffer *buffer) +{ + pr_info("%s: kernel mapping from secure heap %s disallowed\n", + __func__, heap->name); + return NULL; +} + +static void ion_secure_cma_unmap_kernel(struct ion_heap *heap, + struct ion_buffer *buffer) +{ + return; +} + +static int ion_secure_cma_print_debug(struct ion_heap *heap, struct seq_file *s, + const struct list_head *mem_map) +{ + if (mem_map) { + struct mem_map_data *data; + + seq_printf(s, "\nMemory Map\n"); + seq_printf(s, "%16.s %14.s %14.s %14.s\n", + "client", "start address", "end address", + "size (hex)"); + + list_for_each_entry(data, mem_map, node) { + const char *client_name = "(null)"; + + + if (data->client_name) + client_name = data->client_name; + + seq_printf(s, "%16.s %14pa %14pa %14lu (%lx)\n", + client_name, &data->addr, + &data->addr_end, + data->size, data->size); + } + } + return 0; +} + +static struct ion_heap_ops ion_secure_cma_ops = { + .allocate = ion_secure_cma_allocate, + .free = ion_secure_cma_free, + .map_dma = ion_secure_cma_heap_map_dma, + .unmap_dma = ion_secure_cma_heap_unmap_dma, + .phys = ion_secure_cma_phys, + .map_user = ion_secure_cma_mmap, + .map_kernel = ion_secure_cma_map_kernel, + .unmap_kernel = ion_secure_cma_unmap_kernel, + .print_debug = ion_secure_cma_print_debug, + .secure_buffer = ion_cp_secure_buffer, + .unsecure_buffer = ion_cp_unsecure_buffer, +}; + +struct ion_heap *ion_secure_cma_heap_create(struct ion_platform_heap *data) +{ + struct ion_heap *heap; + + heap = kzalloc(sizeof(struct ion_heap), GFP_KERNEL); + + if (!heap) + return ERR_PTR(-ENOMEM); + + heap->ops = &ion_secure_cma_ops; + /* set device as private heaps data, later it will be + * used to make the link with reserved CMA memory */ + heap->priv = data->priv; + heap->type = ION_HEAP_TYPE_SECURE_DMA; + return heap; +} + +void ion_secure_cma_heap_destroy(struct ion_heap *heap) +{ + kfree(heap); +} diff --git a/pool/shard004/C/0101462_rl_fprintf.c b/pool/shard004/C/0101462_rl_fprintf.c new file mode 100644 index 0000000000000000000000000000000000000000..65f1af67fad8bc82bf85f90108bdb7d84c3577d0 --- /dev/null +++ b/pool/shard004/C/0101462_rl_fprintf.c @@ -0,0 +1,51 @@ +#include +#include +#include + +#include + +/* + Jean-Bernard Pellerin Nov. 7th, 2011 + http://stackoverflow.com/questions/8032418 +*/ + +void rl_fprintf(FILE *f, char *fmt, ...) +{ + int need_hack = (rl_readline_state & RL_STATE_READCMD) > 0; + char *saved_line = NULL; + int saved_point = 0; + va_list args; + + if (need_hack) + { + rl_save_prompt(); + + if (rl_end > 0) + { + saved_point = rl_point; + saved_line = rl_copy_text(0, rl_end); + rl_replace_line("", 0); + } + + rl_redisplay(); + } + + va_start(args, fmt); + vfprintf(f, fmt, args); + va_end(args); + fprintf(f, "\n"); + + if (need_hack) + { + rl_restore_prompt(); + + if (saved_line != NULL) + { + rl_replace_line(saved_line, 0); + rl_point = saved_point; + free(saved_line); + } + + rl_redisplay(); + } +} diff --git a/pool/shard004/C/0101463_module-camd33.c b/pool/shard004/C/0101463_module-camd33.c new file mode 100644 index 0000000000000000000000000000000000000000..c490a70261df88b89ba60a065fcb2783053a8042 --- /dev/null +++ b/pool/shard004/C/0101463_module-camd33.c @@ -0,0 +1,175 @@ +#include "globals.h" +#ifdef MODULE_CAMD33 + +#define REQ_SIZE 4 + +static int32_t camd33_send(uchar *buf, int32_t ml) +{ + int32_t l; + if (!cur_client()->pfd) return(-1); + l=boundary(4, ml); + memset(buf+ml, 0, l-ml); + cs_ddump_mask(D_CLIENT, buf, l, "send %d bytes to client", l); + if (cur_client()->crypted) + aes_encrypt(buf, l); + return(send(cur_client()->pfd, buf, l, 0)); +} + +static int32_t camd33_recv(struct s_client * client, uchar *buf, int32_t l) +{ + int32_t n; + if (!client->pfd) return(-1); + if ((n=recv(client->pfd, buf, l, 0))>0) + { + client->last=time((time_t *) 0); + if (client->crypted) + aes_decrypt(client, buf, n); + } + cs_ddump_mask(D_CLIENT, buf, n, "received %d bytes from client", n); + return(n); +} + +static void camd33_request_emm() +{ + uchar mbuf[20]; + struct s_reader *aureader = NULL, *rdr = NULL; + + //TODO: just take the first reader in list + LL_ITER itr = ll_iter_create(cur_client()->aureader_list); + while ((rdr = ll_iter_next(&itr))) { + aureader=rdr; + break; + } + + if (!aureader) return; + + if (aureader->hexserial[0]) + { + log_emm_request(aureader); + mbuf[0]=0; + mbuf[1]=aureader->caid>>8; + mbuf[2]=aureader->caid&0xff; + memcpy(mbuf+3, aureader->hexserial, 4); + memcpy(mbuf+7, &aureader->prid[0][1], 3); + memcpy(mbuf+10, &aureader->prid[2][1], 3); + camd33_send(mbuf, 13); + } +} + +static void camd33_auth_client(uchar *camdbug) +{ + int32_t i, rc; + uchar *usr=NULL, *pwd=NULL; + struct s_auth *account; + uchar mbuf[1024]; + + cur_client()->crypted=cfg.c33_crypted; + + if (cur_client()->crypted) + cur_client()->crypted = check_ip(cfg.c33_plain, cur_client()->ip) ? 0 : 1; + + if (cur_client()->crypted) + aes_set_key((char *) cfg.c33_key); + + mbuf[0]=0; + camd33_send(mbuf, 1); // send login-request + + for (rc=0, camdbug[0]=0, mbuf[0]=1; (rc<2) && (mbuf[0]); rc++) + { + i=process_input(mbuf, sizeof(mbuf), 1); + if ((i>0) && (!mbuf[0])) + { + usr=mbuf+1; + pwd=usr+strlen((char *)usr)+2; + } + else + memcpy(camdbug+1, mbuf, camdbug[0]=i); + } + for (rc=-1, account=cfg.account; (usr) && (account) && (rc<0); account=account->next) + if ((!strcmp((char *)usr, account->usr)) && (!strcmp((char *)pwd, account->pwd))) + rc=cs_auth_client(cur_client(), account, NULL); + if (!rc) + camd33_request_emm(); + else + { + if (rc<0) cs_auth_client(cur_client(), 0, usr ? "invalid account" : "no user given"); + cs_disconnect_client(cur_client()); + } +} + +static void camd33_send_dcw(struct s_client *UNUSED(client), ECM_REQUEST *er) +{ + uchar mbuf[1024]; + mbuf[0]=2; + memcpy(mbuf+1, &er->msgid, 4); // get pin + memcpy(mbuf+5, er->cw, 16); + camd33_send(mbuf, 21); + if (!cfg.c33_passive) + camd33_request_emm(); +} + +static void camd33_process_ecm(uchar *buf, int32_t l) +{ + ECM_REQUEST *er; + if (!(er=get_ecmtask())) + return; + memcpy(&er->msgid, buf+3, 4); // save pin + er->l=l-7; + er->caid=b2i(2, buf+1); + memcpy(er->ecm , buf+7, er->l); + get_cw(cur_client(), er); +} + +static void camd33_process_emm(uchar *buf, int32_t l) +{ + EMM_PACKET epg; + memset(&epg, 0, sizeof(epg)); + epg.l=l-7; + memcpy(epg.caid , buf+1, 2); + memcpy(epg.hexserial, buf+3, 4); + memcpy(epg.emm , buf+7, epg.l); + do_emm(cur_client(), &epg); +} + +static void * camd33_server(struct s_client *UNUSED(client), uchar *mbuf, int32_t n) +{ + switch(mbuf[0]) { + case 2: + camd33_process_ecm(mbuf, n); + break; + case 3: + camd33_process_emm(mbuf, n); + break; + default: + cs_debug_mask(D_CLIENT, "unknown command !"); + } + + return NULL; +} + +static void camd33_server_init(struct s_client *UNUSED(client)) { + uchar camdbug[256]; + + camd33_auth_client(camdbug); +} + +void module_camd33(struct s_module *ph) +{ + static PTAB ptab; //since there is always only 1 camd33 server running, this is threadsafe + ptab.ports[0].s_port = cfg.c33_port; + ph->ptab = &ptab; + ph->ptab->nports = 1; + + cs_strncpy(ph->desc, "camd33", sizeof(ph->desc)); + ph->type=MOD_CONN_TCP; + ph->listenertype = LIS_CAMD33TCP; + ph->logtxt=cfg.c33_crypted ? ", crypted" : ", UNCRYPTED!"; + ph->multi=1; + ph->s_ip=cfg.c33_srvip; + ph->s_handler=camd33_server; + ph->s_init=camd33_server_init; + ph->recv=camd33_recv; + ph->send_dcw=camd33_send_dcw; + ph->num=R_CAMD33; +} +#endif diff --git a/pool/shard004/C/0101465_fifo_create.c b/pool/shard004/C/0101465_fifo_create.c new file mode 100644 index 0000000000000000000000000000000000000000..d7f8620bf015f2853106ef12914f16bb403816e8 --- /dev/null +++ b/pool/shard004/C/0101465_fifo_create.c @@ -0,0 +1,285 @@ +/*- + * Copyright (c) 2005-2008 Robert N. M. Watson + * 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. + * + * $FreeBSD: soc2013/dpl/head/tools/regression/fifo/fifo_create/fifo_create.c 179977 2008-06-22 21:03:26Z rwatson $ + */ + +#include + +#include +#include +#include +#include +#include +#include +#include + +/* + * Simple regression test for the creation and destruction of POSIX fifos in + * the file system name space. Using a specially created directory, create + * a fifo in it and check that the following properties are present, as + * specified in IEEE Std 1003.1, 2004 Edition: + * + * - When mkfifo() or mknod(S_IFIFO) is called, on success, a fifo is + * created. + * + * - On an error, no fifo is created. (XXX: Not tested) + * + * - The mode bits on the fifo are a product of combining the umask and + * requested mode. + * + * - The fifo's owner will be the processes effective user ID. (XXX: Not + * tested) + * + * - The fifo's group will be the parent directory's group or the effective + * group ID of the process. For historical reasons, BSD prefers the group + * ID of the process, so we will generate an error if it's not that. (XXX: + * Not tested) + * + * - The st_atime, st_ctime, st_mtime of the fifo will be set appropriately, + * and st_ctime and st_mtime on the directory will be updated. (XXX: We + * test they are updated, not correct) + * + * - EEXIST is returned if the named file already exists. + * + * In addition, we check that we can unlink the fifo, and that if we do, it + * disappears. + * + * This test must run as root in order to usefully frob the process + * credential to test permission parts. + */ + +/* + * All activity occurs within a temporary directory created early in the + * test. + */ +char temp_dir[PATH_MAX]; + +static void __unused +atexit_temp_dir(void) +{ + + rmdir(temp_dir); +} + +/* + * Basic creation tests: verify that mkfifo(2) (or mknod(2)) creates a fifo, + * that the time stamps on the directory are updated, that if we try twice we + * get EEXIST, and that we can unlink it. + */ +static void +fifo_create_test(int use_mkfifo) +{ + struct stat old_dirsb, dirsb, fifosb; + const char *testname; + char path[PATH_MAX]; + int error; + + if (use_mkfifo) + testname = "mkfifo"; + else + testname = "mknod"; + + /* + * Sleep to make sure that the time stamp on the directory will be + * updated. + */ + if (stat(temp_dir, &old_dirsb) < 0) + err(-1, "basic_create_test: %s: stat: %s", testname, + temp_dir); + + sleep(2); + + snprintf(path, PATH_MAX, "%s/testfifo", temp_dir); + + if (use_mkfifo) { + if (mkfifo(path, 0600) < 0) + err(-1, "basic_create_test: %s: %s", testname, path); + } else { + if (mknod(path, S_IFIFO | 0600, 0) < 0) + err(-1, "basic_create_test: %s: %s", testname, path); + } + + if (stat(path, &fifosb) < 0) { + error = errno; + (void)unlink(path); + errno = error; + err(-1, "basic_create_test: %s: stat: %s", testname, path); + } + + if (!(S_ISFIFO(fifosb.st_mode))) { + (void)unlink(path); + errx(-1, "basic_create_test: %s produced non-fifo", + testname); + } + + if (use_mkfifo) { + if (mkfifo(path, 0600) == 0) + errx(-1, "basic_create_test: dup %s succeeded", + testname); + } else { + if (mknod(path, S_IFIFO | 0600, 0) == 0) + errx(-1, "basic_create_test: dup %s succeeded", + testname); + } + + if (errno != EEXIST) + err(-1, "basic_create_test: dup %s unexpected error", + testname); + + if (stat(temp_dir, &dirsb) < 0) { + error = errno; + (void)unlink(path); + errno = error; + err(-1, "basic_create_test: %s: stat: %s", testname, + temp_dir); + } + + if (old_dirsb.st_ctime == dirsb.st_ctime) { + (void)unlink(path); + errx(-1, "basic_create_test: %s: old_dirsb.st_ctime == " + "dirsb.st_ctime", testname); + } + + if (old_dirsb.st_mtime == dirsb.st_mtime) { + (void)unlink(path); + errx(-1, "basic_create_test: %s: old_dirsb.st_mtime == " + "dirsb.st_mtime", testname); + } + + if (unlink(path) < 0) + err(-1, "basic_create_test: %s: unlink: %s", testname, path); + + if (stat(path, &fifosb) == 0) + errx(-1, "basic_create_test: %s: unlink failed to unlink", + testname); + if (errno != ENOENT) + err(-1, "basic_create_test: %s: unlink unexpected error", + testname); +} + +/* + * Having determined that basic create/remove/etc functionality is present + * for fifos, now make sure that the umask, requested permissions, and + * resulting mode are handled properly. + */ +static const struct permission_test { + mode_t pt_umask; + mode_t pt_reqmode; + mode_t pt_mode; +} permission_test[] = { + {0000, 0, S_IFIFO}, + {0000, S_IRWXU, S_IFIFO | S_IRWXU}, + {0000, S_IRWXU | S_IRWXG | S_IRWXO, S_IFIFO | S_IRWXU | S_IRWXG | + S_IRWXO }, + {0077, S_IRWXU, S_IFIFO | S_IRWXU}, + {0077, S_IRWXU | S_IRWXG | S_IRWXO, S_IFIFO | S_IRWXU}, +}; +static const int permission_test_count = sizeof(permission_test) / + sizeof(struct permission_test); + +static void +fifo_permission_test(int use_mkfifo) +{ + const struct permission_test *ptp; + mode_t __unused old_umask; + char path[PATH_MAX]; + const char *testname; + struct stat sb; + int error, i; + + if (use_mkfifo) + testname = "mkfifo"; + else + testname = "mknod"; + + snprintf(path, PATH_MAX, "%s/testfifo", temp_dir); + old_umask = umask(0022); + for (i = 0; i < permission_test_count; i++) { + ptp = &permission_test[i]; + + umask(ptp->pt_umask); + if (use_mkfifo) { + if (mkfifo(path, ptp->pt_reqmode) < 0) + err(-1, "fifo_permission_test: %s: %08o " + "%08o %08o\n", testname, ptp->pt_umask, + ptp->pt_reqmode, ptp->pt_mode); + } else { + if (mknod(path, S_IFIFO | ptp->pt_reqmode, 0) < 0) + err(-1, "fifo_permission_test: %s: %08o " + "%08o %08o\n", testname, ptp->pt_umask, + ptp->pt_reqmode, ptp->pt_mode); + } + + if (stat(path, &sb) < 0) { + error = errno; + (void)unlink(path); + errno = error; + err(-1, "fifo_permission_test: %s: %s", testname, + path); + } + + if (sb.st_mode != ptp->pt_mode) { + (void)unlink(path); + errx(-1, "fifo_permission_test: %s: %08o %08o %08o " + "got %08o", testname, ptp->pt_umask, + ptp->pt_reqmode, ptp->pt_mode, sb.st_mode); + } + + if (unlink(path) < 0) + err(-1, "fifo_permission_test: %s: unlink: %s", + testname, path); + } + umask(old_umask); +} + +int +main(int argc, char *argv[]) +{ + int i; + + if (geteuid() != 0) + errx(-1, "must be run as root"); + + strcpy(temp_dir, "/tmp/fifo_create.XXXXXXXXXXX"); + if (mkdtemp(temp_dir) == NULL) + err(-1, "mkdtemp"); + atexit(atexit_temp_dir); + + if (chdir(temp_dir) < 0) + err(-1, "chdir"); + + /* + * Run each test twice, once with mknod(2) and a second time with + * mkfifo(2). Historically, BSD has not allowed mknod(2) to be used + * to create fifos, but the Single UNIX Specification requires it. + */ + for (i = 0; i < 2; i++) { + fifo_create_test(i); + fifo_permission_test(i); + } + + return (0); +} diff --git a/pool/shard004/C/0101466_fix_vfr_pts.c b/pool/shard004/C/0101466_fix_vfr_pts.c new file mode 100644 index 0000000000000000000000000000000000000000..03092511bd652e5da27e9427ab5314a7dd17d4a9 --- /dev/null +++ b/pool/shard004/C/0101466_fix_vfr_pts.c @@ -0,0 +1,136 @@ +/***************************************************************************** + * fix_vfr_pts.c: vfr pts fixing video filter + ***************************************************************************** + * Copyright (C) 2010-2022 x264 project + * + * Authors: 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 "video.h" +#include "internal.h" + +/* This filter calculates and store the frame's duration to the frame data + * (if it is not already calculated when the frame arrives to this point) + * so it can be used by filters that will need to reconstruct pts due to + * out-of-order frame requests */ + +typedef struct +{ + hnd_t prev_hnd; + cli_vid_filter_t prev_filter; + + /* we need 1 buffer picture and 1 place holder */ + cli_pic_t buffer; + cli_pic_t holder; + int buffer_allocated; + int holder_frame; + int holder_ret; + int64_t pts; + int64_t last_duration; +} fix_vfr_pts_hnd_t; + +cli_vid_filter_t fix_vfr_pts_filter; + +static int init( hnd_t *handle, cli_vid_filter_t *filter, video_info_t *info, x264_param_t *param, char *opt_string ) +{ + /* if the input is not vfr, we don't do anything */ + if( !info->vfr ) + return 0; + fix_vfr_pts_hnd_t *h = calloc( 1, sizeof(fix_vfr_pts_hnd_t) ); + if( !h ) + return -1; + + h->holder_frame = -1; + h->prev_hnd = *handle; + h->prev_filter = *filter; + *handle = h; + *filter = fix_vfr_pts_filter; + + return 0; +} + +static int get_frame( hnd_t handle, cli_pic_t *output, int frame ) +{ + fix_vfr_pts_hnd_t *h = handle; + /* if we want the holder picture and it errored, return the error. */ + if( frame == h->holder_frame ) + { + if( h->holder_ret ) + return h->holder_ret; + } + else + { + /* if we have a holder frame and we don't want it, release the frame */ + if( h->holder_frame > 0 && h->holder_frame < frame && h->prev_filter.release_frame( h->prev_hnd, &h->holder, h->holder_frame ) ) + return -1; + h->holder_frame = -1; + if( h->prev_filter.get_frame( h->prev_hnd, &h->holder, frame ) ) + return -1; + } + + /* if the frame's duration is not set already, read the next frame to set it. */ + if( !h->holder.duration ) + { + /* allocate a buffer picture if we didn't already */ + if( !h->buffer_allocated ) + { + if( x264_cli_pic_alloc( &h->buffer, h->holder.img.csp, h->holder.img.width, h->holder.img.height ) ) + return -1; + h->buffer_allocated = 1; + } + h->holder_frame = frame+1; + /* copy the current frame to the buffer, release it, and then read in the next frame to the placeholder */ + if( x264_cli_pic_copy( &h->buffer, &h->holder ) || h->prev_filter.release_frame( h->prev_hnd, &h->holder, frame ) ) + return -1; + h->holder_ret = h->prev_filter.get_frame( h->prev_hnd, &h->holder, h->holder_frame ); + /* suppress non-monotonic pts warnings by setting the duration to be at least 1 */ + if( !h->holder_ret ) + h->last_duration = X264_MAX( h->holder.pts - h->buffer.pts, 1 ); + h->buffer.duration = h->last_duration; + *output = h->buffer; + } + else + *output = h->holder; + + output->pts = h->pts; + h->pts += output->duration; + + return 0; +} + +static int release_frame( hnd_t handle, cli_pic_t *pic, int frame ) +{ + fix_vfr_pts_hnd_t *h = handle; + /* if the frame is the buffered one, it's already been released */ + if( frame == (h->holder_frame - 1) ) + return 0; + return h->prev_filter.release_frame( h->prev_hnd, pic, frame ); +} + +static void free_filter( hnd_t handle ) +{ + fix_vfr_pts_hnd_t *h = handle; + h->prev_filter.free( h->prev_hnd ); + if( h->buffer_allocated ) + x264_cli_pic_clean( &h->buffer ); + free( h ); +} + +cli_vid_filter_t fix_vfr_pts_filter = { "fix_vfr_pts", NULL, init, get_frame, release_frame, free_filter, NULL }; diff --git a/pool/shard004/C/0101469_hvc_irq.c b/pool/shard004/C/0101469_hvc_irq.c new file mode 100644 index 0000000000000000000000000000000000000000..7ddbe30728404754f34d97da1965c126591eb10d --- /dev/null +++ b/pool/shard004/C/0101469_hvc_irq.c @@ -0,0 +1,46 @@ +/* + * Copyright IBM Corp. 2001,2008 + * + * This file contains the IRQ specific code for hvc_console + * + */ + +#include + +#include "hvc_console.h" + +static irqreturn_t hvc_handle_interrupt(int irq, void *dev_instance) +{ + + if (hvc_poll(dev_instance)) + hvc_kick(); + return IRQ_HANDLED; +} + +int notifier_add_irq(struct hvc_struct *hp, int irq) +{ + int rc; + + if (!irq) { + hp->irq_requested = 0; + return 0; + } + rc = request_irq(irq, hvc_handle_interrupt, 0, + "hvc_console", hp); + if (!rc) + hp->irq_requested = 1; + return rc; +} + +void notifier_del_irq(struct hvc_struct *hp, int irq) +{ + if (!hp->irq_requested) + return; + free_irq(irq, hp); + hp->irq_requested = 0; +} + +void notifier_hangup_irq(struct hvc_struct *hp, int irq) +{ + notifier_del_irq(hp, irq); +} diff --git a/pool/shard004/C/0101474_select-game.c b/pool/shard004/C/0101474_select-game.c new file mode 100644 index 0000000000000000000000000000000000000000..9abc698c414f4c32b9051ef2c247566f2da7cdf2 --- /dev/null +++ b/pool/shard004/C/0101474_select-game.c @@ -0,0 +1,197 @@ +/* A custom widget for selecting a game from a list of games. + * + * The code is based on the TICTACTOE example + * www.gtk.oorg/tutorial/app-codeexamples.html#SEC-TICTACTOE + * + * Adaptation for Pioneers: 2004 Roland Clobus + * + */ + +#include "config.h" +#include "game.h" +#include +#include +#include "guimap.h" +#include "gtkbugs.h" + +#include "select-game.h" + +/* The signals */ +enum { + ACTIVATE, + LAST_SIGNAL +}; + +static void select_game_class_init(SelectGameClass * klass); +static void select_game_init(SelectGame * sg); +static void select_game_item_changed(GtkWidget * widget, SelectGame * sg); + +/* All signals */ +static guint select_game_signals[LAST_SIGNAL] = { 0 }; + +/* Register the class */ +GType select_game_get_type(void) +{ + static GType sg_type = 0; + + if (!sg_type) { + static const GTypeInfo sg_info = { + sizeof(SelectGameClass), + NULL, /* base_init */ + NULL, /* base_finalize */ + (GClassInitFunc) select_game_class_init, + NULL, /* class_finalize */ + NULL, /* class_data */ + sizeof(SelectGame), + 0, + (GInstanceInitFunc) select_game_init, + NULL + }; + sg_type = + g_type_register_static(GTK_TYPE_TABLE, "SelectGame", + &sg_info, 0); + } + return sg_type; +} + +/* Register the signals. + * SelectGame will emit one signal: 'activate' with the text of the + * active game in user_data + */ +static void select_game_class_init(SelectGameClass * klass) +{ + select_game_signals[ACTIVATE] = g_signal_new("activate", + G_TYPE_FROM_CLASS + (klass), + G_SIGNAL_RUN_FIRST | + G_SIGNAL_ACTION, + G_STRUCT_OFFSET + (SelectGameClass, + activate), NULL, + NULL, + g_cclosure_marshal_VOID__VOID, + G_TYPE_NONE, 0); +} + +/* Build the composite widget */ +static void select_game_init(SelectGame * sg) +{ + GtkCellRenderer *cell; + + /* Create model */ + sg->data = gtk_list_store_new(2, G_TYPE_STRING, GDK_TYPE_PIXBUF); + sg->combo_box = + gtk_combo_box_new_with_model(GTK_TREE_MODEL(sg->data)); + + cell = gtk_cell_renderer_text_new(); + gtk_cell_layout_pack_start(GTK_CELL_LAYOUT(sg->combo_box), + cell, TRUE); + gtk_cell_layout_set_attributes(GTK_CELL_LAYOUT(sg->combo_box), + cell, "text", 0, NULL); + + cell = gtk_cell_renderer_pixbuf_new(); + gtk_cell_layout_pack_start(GTK_CELL_LAYOUT(sg->combo_box), + cell, FALSE); + gtk_cell_layout_set_attributes(GTK_CELL_LAYOUT(sg->combo_box), + cell, "pixbuf", 1, NULL); + + sg->game_names = g_ptr_array_new(); + + gtk_widget_show(sg->combo_box); + gtk_widget_set_tooltip_text(sg->combo_box, + /* Tooltip for the list of games */ + _("Select a game")); + gtk_table_resize(GTK_TABLE(sg), 1, 1); + gtk_table_attach_defaults(GTK_TABLE(sg), sg->combo_box, + 0, 1, 0, 1); + sg->default_game = g_strdup("Default"); + g_signal_connect(G_OBJECT(sg->combo_box), "changed", + G_CALLBACK(select_game_item_changed), sg); +} + +/* Create a new instance of the widget */ +GtkWidget *select_game_new(void) +{ + return GTK_WIDGET(g_object_new(select_game_get_type(), NULL)); +} + +/* Set the default game */ +void select_game_set_default(SelectGame * sg, const gchar * game_title) +{ + if (sg->default_game) + g_free(sg->default_game); + sg->default_game = g_strdup(game_title); +} + +/* Add a game title to the list. + * The default game will be the active item. + */ +void select_game_add(SelectGame * sg, const gchar * game_title) +{ + GtkTreeIter iter; + gchar *title = g_strdup(game_title); + + g_ptr_array_add(sg->game_names, title); + gtk_list_store_insert_with_values(sg->data, &iter, 999, + 0, game_title, -1); + + if (!strcmp(game_title, sg->default_game)) + gtk_combo_box_set_active(GTK_COMBO_BOX(sg->combo_box), + sg->game_names->len - 1); +} + +/* Add a game title to the list, and add the map. + * The default game will be the active item. + */ +void select_game_add_with_map(SelectGame * sg, const gchar * game_title, + Map * map) +{ + GtkTreeIter iter; + gchar *title = g_strdup(game_title); + + int width, height; + GdkPixbuf *pixbuf; + + GuiMap *gmap; + + width = 64; + height = 48; + + gmap = guimap_new(); + gmap->pixmap = + gdk_pixmap_new(sg->combo_box->window, width, height, + gdk_visual_get_system()->depth); + gmap->width = width; + gmap->height = height; + gmap->area = sg->combo_box; + g_object_ref(gmap->area); + gmap->map = map; + guimap_scale_to_size(gmap, width, height); + guimap_display(gmap); + + pixbuf = + gdk_pixbuf_get_from_drawable(NULL, gmap->pixmap, NULL, 0, 0, 0, + 0, -1, -1); + guimap_delete(gmap); + + g_ptr_array_add(sg->game_names, title); + gtk_list_store_insert_with_values(sg->data, &iter, 999, + 0, game_title, 1, pixbuf, -1); + g_object_unref(pixbuf); + + if (!strcmp(game_title, sg->default_game)) + gtk_combo_box_set_active(GTK_COMBO_BOX(sg->combo_box), + sg->game_names->len - 1); +} + +static void select_game_item_changed(G_GNUC_UNUSED GtkWidget * widget, + SelectGame * sg) +{ + g_signal_emit(G_OBJECT(sg), select_game_signals[ACTIVATE], 0); +} + +const gchar *select_game_get_active(SelectGame * sg) +{ + gint idx = gtk_combo_box_get_active(GTK_COMBO_BOX(sg->combo_box)); + return g_ptr_array_index(sg->game_names, idx); +} diff --git a/pool/shard004/C/0101479_convertable_info.c b/pool/shard004/C/0101479_convertable_info.c new file mode 100644 index 0000000000000000000000000000000000000000..642a789ace9df3775655d9d8ee4eff01d9034129 --- /dev/null +++ b/pool/shard004/C/0101479_convertable_info.c @@ -0,0 +1,66 @@ +/*! + * log metatype info. + */ + +#include + +#include "types.h" + +#include "object.h" + +/*! + * \ingroup mptCore + * \brief metatype info + * + * Fill property with convertable instance description. + * + * \param val metatype instance + * \param pr property data + */ +int mpt_convertable_info(MPT_INTERFACE(convertable) *val, MPT_STRUCT(property) *pr) +{ + MPT_INTERFACE(object) *obj = 0; + const MPT_STRUCT(named_traits) *traits; + const char *desc; + int code; + + code = val->_vptr->convert(val, 0, 0); + + if ((code < 0) || !pr) { + return code; + } + /* object specific name */ + if (val->_vptr->convert(val, MPT_ENUM(TypeObjectPtr), &obj) >= 0 + && obj) { + pr->name = ""; + pr->desc = 0; + if ((obj->_vptr->property(obj, pr) >= 0)) { + pr->desc = pr->name; + pr->name = "object"; + return code; + } + } + /* interface instance */ + desc = pr->desc; + if ((traits = mpt_interface_traits(code))) { + pr->name = "interface"; + pr->desc = traits->name; + } + /* metatype instance */ + else if ((traits = mpt_metatype_traits(code))) { + pr->name = "metatype"; + pr->desc = traits->name; + } + /* generic convertable */ + else { + pr->name = "convertable"; + pr->desc = 0; + } + /* generic value data */ + pr->val.domain = 0; + pr->val.type = 0; + if (val->_vptr->convert(val, MPT_ENUM(TypeValue), &pr->val) < 0) { + MPT_value_set_data(&pr->val, 's', &desc); + } + return code; +} diff --git a/pool/shard004/C/0101486_ipu-dmfc.c b/pool/shard004/C/0101486_ipu-dmfc.c new file mode 100644 index 0000000000000000000000000000000000000000..42705bb5aaa36b6e42d495032df6758ef9a0ddcd --- /dev/null +++ b/pool/shard004/C/0101486_ipu-dmfc.c @@ -0,0 +1,239 @@ +/* + * Copyright (c) 2010 Sascha Hauer + * Copyright (C) 2005-2009 Freescale Semiconductor, 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